handler.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. package api
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "github.com/go-chi/chi"
  7. "github.com/pkg/errors"
  8. "github.com/smallstep/certificates/acme"
  9. "github.com/smallstep/certificates/api"
  10. )
  11. func link(url, typ string) string {
  12. return fmt.Sprintf("<%s>;rel=\"%s\"", url, typ)
  13. }
  14. type payloadInfo struct {
  15. value []byte
  16. isPostAsGet bool
  17. isEmptyJSON bool
  18. }
  19. // payloadFromContext searches the context for a payload. Returns the payload
  20. // or an error.
  21. func payloadFromContext(ctx context.Context) (*payloadInfo, error) {
  22. val, ok := ctx.Value(acme.PayloadContextKey).(*payloadInfo)
  23. if !ok || val == nil {
  24. return nil, acme.ServerInternalErr(errors.Errorf("payload expected in request context"))
  25. }
  26. return val, nil
  27. }
  28. // New returns a new ACME API router.
  29. func New(acmeAuth acme.Interface) api.RouterHandler {
  30. return &Handler{acmeAuth}
  31. }
  32. // Handler is the ACME request handler.
  33. type Handler struct {
  34. Auth acme.Interface
  35. }
  36. // Route traffic and implement the Router interface.
  37. func (h *Handler) Route(r api.Router) {
  38. getLink := h.Auth.GetLinkExplicit
  39. // Standard ACME API
  40. r.MethodFunc("GET", getLink(acme.NewNonceLink, "{provisionerID}", false, nil), h.baseURLFromRequest(h.lookupProvisioner(h.addNonce(h.GetNonce))))
  41. r.MethodFunc("HEAD", getLink(acme.NewNonceLink, "{provisionerID}", false, nil), h.baseURLFromRequest(h.lookupProvisioner(h.addNonce(h.GetNonce))))
  42. r.MethodFunc("GET", getLink(acme.DirectoryLink, "{provisionerID}", false, nil), h.baseURLFromRequest(h.lookupProvisioner(h.addNonce(h.GetDirectory))))
  43. r.MethodFunc("HEAD", getLink(acme.DirectoryLink, "{provisionerID}", false, nil), h.baseURLFromRequest(h.lookupProvisioner(h.addNonce(h.GetDirectory))))
  44. extractPayloadByJWK := func(next nextHTTP) nextHTTP {
  45. return h.baseURLFromRequest(h.lookupProvisioner(h.addNonce(h.addDirLink(h.verifyContentType(h.parseJWS(h.validateJWS(h.extractJWK(h.verifyAndExtractJWSPayload(next)))))))))
  46. }
  47. extractPayloadByKid := func(next nextHTTP) nextHTTP {
  48. return h.baseURLFromRequest(h.lookupProvisioner(h.addNonce(h.addDirLink(h.verifyContentType(h.parseJWS(h.validateJWS(h.lookupJWK(h.verifyAndExtractJWSPayload(next)))))))))
  49. }
  50. r.MethodFunc("POST", getLink(acme.NewAccountLink, "{provisionerID}", false, nil), extractPayloadByJWK(h.NewAccount))
  51. r.MethodFunc("POST", getLink(acme.AccountLink, "{provisionerID}", false, nil, "{accID}"), extractPayloadByKid(h.GetUpdateAccount))
  52. r.MethodFunc("POST", getLink(acme.NewOrderLink, "{provisionerID}", false, nil), extractPayloadByKid(h.NewOrder))
  53. r.MethodFunc("POST", getLink(acme.OrderLink, "{provisionerID}", false, nil, "{ordID}"), extractPayloadByKid(h.isPostAsGet(h.GetOrder)))
  54. r.MethodFunc("POST", getLink(acme.OrdersByAccountLink, "{provisionerID}", false, nil, "{accID}"), extractPayloadByKid(h.isPostAsGet(h.GetOrdersByAccount)))
  55. r.MethodFunc("POST", getLink(acme.FinalizeLink, "{provisionerID}", false, nil, "{ordID}"), extractPayloadByKid(h.FinalizeOrder))
  56. r.MethodFunc("POST", getLink(acme.AuthzLink, "{provisionerID}", false, nil, "{authzID}"), extractPayloadByKid(h.isPostAsGet(h.GetAuthz)))
  57. r.MethodFunc("POST", getLink(acme.ChallengeLink, "{provisionerID}", false, nil, "{chID}"), extractPayloadByKid(h.GetChallenge))
  58. r.MethodFunc("POST", getLink(acme.CertificateLink, "{provisionerID}", false, nil, "{certID}"), extractPayloadByKid(h.isPostAsGet(h.GetCertificate)))
  59. }
  60. // GetNonce just sets the right header since a Nonce is added to each response
  61. // by middleware by default.
  62. func (h *Handler) GetNonce(w http.ResponseWriter, r *http.Request) {
  63. if r.Method == "HEAD" {
  64. w.WriteHeader(http.StatusOK)
  65. } else {
  66. w.WriteHeader(http.StatusNoContent)
  67. }
  68. }
  69. // GetDirectory is the ACME resource for returning a directory configuration
  70. // for client configuration.
  71. func (h *Handler) GetDirectory(w http.ResponseWriter, r *http.Request) {
  72. dir, err := h.Auth.GetDirectory(r.Context())
  73. if err != nil {
  74. api.WriteError(w, err)
  75. return
  76. }
  77. api.JSON(w, dir)
  78. }
  79. // GetAuthz ACME api for retrieving an Authz.
  80. func (h *Handler) GetAuthz(w http.ResponseWriter, r *http.Request) {
  81. acc, err := acme.AccountFromContext(r.Context())
  82. if err != nil {
  83. api.WriteError(w, err)
  84. return
  85. }
  86. authz, err := h.Auth.GetAuthz(r.Context(), acc.GetID(), chi.URLParam(r, "authzID"))
  87. if err != nil {
  88. api.WriteError(w, err)
  89. return
  90. }
  91. w.Header().Set("Location", h.Auth.GetLink(r.Context(), acme.AuthzLink, true, authz.GetID()))
  92. api.JSON(w, authz)
  93. }
  94. // GetChallenge ACME api for retrieving a Challenge.
  95. func (h *Handler) GetChallenge(w http.ResponseWriter, r *http.Request) {
  96. acc, err := acme.AccountFromContext(r.Context())
  97. if err != nil {
  98. api.WriteError(w, err)
  99. return
  100. }
  101. // Just verify that the payload was set, since we're not strictly adhering
  102. // to ACME V2 spec for reasons specified below.
  103. _, err = payloadFromContext(r.Context())
  104. if err != nil {
  105. api.WriteError(w, err)
  106. return
  107. }
  108. // NOTE: We should be checking that the request is either a POST-as-GET, or
  109. // that the payload is an empty JSON block ({}). However, older ACME clients
  110. // still send a vestigial body (rather than an empty JSON block) and
  111. // strict enforcement would render these clients broken. For the time being
  112. // we'll just ignore the body.
  113. var (
  114. ch *acme.Challenge
  115. chID = chi.URLParam(r, "chID")
  116. )
  117. ch, err = h.Auth.ValidateChallenge(r.Context(), acc.GetID(), chID, acc.GetKey())
  118. if err != nil {
  119. api.WriteError(w, err)
  120. return
  121. }
  122. w.Header().Add("Link", link(h.Auth.GetLink(r.Context(), acme.AuthzLink, true, ch.GetAuthzID()), "up"))
  123. w.Header().Set("Location", h.Auth.GetLink(r.Context(), acme.ChallengeLink, true, ch.GetID()))
  124. api.JSON(w, ch)
  125. }
  126. // GetCertificate ACME api for retrieving a Certificate.
  127. func (h *Handler) GetCertificate(w http.ResponseWriter, r *http.Request) {
  128. acc, err := acme.AccountFromContext(r.Context())
  129. if err != nil {
  130. api.WriteError(w, err)
  131. return
  132. }
  133. certID := chi.URLParam(r, "certID")
  134. certBytes, err := h.Auth.GetCertificate(acc.GetID(), certID)
  135. if err != nil {
  136. api.WriteError(w, err)
  137. return
  138. }
  139. w.Header().Set("Content-Type", "application/pem-certificate-chain; charset=utf-8")
  140. w.Write(certBytes)
  141. }