middleware.go 2.3 KB

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