middleware.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package api
  2. import (
  3. "context"
  4. "net/http"
  5. "github.com/smallstep/certificates/api/render"
  6. "github.com/smallstep/certificates/authority/admin"
  7. )
  8. type nextHTTP = func(http.ResponseWriter, *http.Request)
  9. // requireAPIEnabled is a middleware that ensures the Administration API
  10. // is enabled before servicing requests.
  11. func requireAPIEnabled(next nextHTTP) nextHTTP {
  12. return func(w http.ResponseWriter, r *http.Request) {
  13. if !mustAuthority(r.Context()).IsAdminAPIEnabled() {
  14. render.Error(w, admin.NewError(admin.ErrorNotImplementedType, "administration API not enabled"))
  15. return
  16. }
  17. next(w, r)
  18. }
  19. }
  20. // extractAuthorizeTokenAdmin is a middleware that extracts and caches the bearer token.
  21. func extractAuthorizeTokenAdmin(next nextHTTP) nextHTTP {
  22. return func(w http.ResponseWriter, r *http.Request) {
  23. tok := r.Header.Get("Authorization")
  24. if tok == "" {
  25. render.Error(w, admin.NewError(admin.ErrorUnauthorizedType,
  26. "missing authorization header token"))
  27. return
  28. }
  29. ctx := r.Context()
  30. adm, err := mustAuthority(ctx).AuthorizeAdminToken(r, tok)
  31. if err != nil {
  32. render.Error(w, err)
  33. return
  34. }
  35. ctx = context.WithValue(ctx, adminContextKey, adm)
  36. next(w, r.WithContext(ctx))
  37. }
  38. }
  39. // ContextKey is the key type for storing and searching for ACME request
  40. // essentials in the context of a request.
  41. type ContextKey string
  42. const (
  43. // adminContextKey account key
  44. adminContextKey = ContextKey("admin")
  45. )