middleware.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package api
  2. import (
  3. "net/http"
  4. "go.step.sm/linkedca"
  5. "github.com/smallstep/certificates/api"
  6. "github.com/smallstep/certificates/authority/admin"
  7. "github.com/smallstep/certificates/authority/admin/db/nosql"
  8. )
  9. type nextHTTP = func(http.ResponseWriter, *http.Request)
  10. // requireAPIEnabled is a middleware that ensures the Administration API
  11. // is enabled before servicing requests.
  12. func (h *Handler) requireAPIEnabled(next nextHTTP) nextHTTP {
  13. return func(w http.ResponseWriter, r *http.Request) {
  14. if !h.auth.IsAdminAPIEnabled() {
  15. api.WriteError(w, admin.NewError(admin.ErrorNotImplementedType,
  16. "administration API not enabled"))
  17. return
  18. }
  19. next(w, r)
  20. }
  21. }
  22. // extractAuthorizeTokenAdmin is a middleware that extracts and caches the bearer token.
  23. func (h *Handler) extractAuthorizeTokenAdmin(next nextHTTP) nextHTTP {
  24. return func(w http.ResponseWriter, r *http.Request) {
  25. tok := r.Header.Get("Authorization")
  26. if tok == "" {
  27. api.WriteError(w, admin.NewError(admin.ErrorUnauthorizedType,
  28. "missing authorization header token"))
  29. return
  30. }
  31. adm, err := h.auth.AuthorizeAdminToken(r, tok)
  32. if err != nil {
  33. api.WriteError(w, err)
  34. return
  35. }
  36. ctx := linkedca.WithAdmin(r.Context(), adm)
  37. next(w, r.WithContext(ctx))
  38. }
  39. }
  40. // checkAction checks if an action is supported in standalone or not
  41. func (h *Handler) checkAction(next nextHTTP, supportedInStandalone bool) nextHTTP {
  42. return func(w http.ResponseWriter, r *http.Request) {
  43. // actions allowed in standalone mode are always supported
  44. if supportedInStandalone {
  45. next(w, r)
  46. return
  47. }
  48. // when not in standalone mode and using a nosql.DB backend,
  49. // actions are not supported
  50. if _, ok := h.adminDB.(*nosql.DB); ok {
  51. api.WriteError(w, admin.NewError(admin.ErrorNotImplementedType,
  52. "operation not supported in standalone mode"))
  53. return
  54. }
  55. // continue to next http handler
  56. next(w, r)
  57. }
  58. }