handler.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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 is the ACME api for retrieving a Challenge resource.
  95. //
  96. // Potential Challenges are requested by the client when creating an order.
  97. // Once the client knows the appropriate validation resources are provisioned,
  98. // it makes a POST-as-GET request to this endpoint in order to initiate the
  99. // validation flow.
  100. //
  101. // The validation state machine describes the flow for a challenge.
  102. //
  103. // https://tools.ietf.org/html/rfc8555#section-7.1.6
  104. //
  105. // Once a validation attempt has completed without error, the challenge's
  106. // status is updated depending on the result (valid|invalid) of the server's
  107. // validation attempt. Once this is the case, a challenge cannot be reset.
  108. //
  109. // If a challenge cannot be completed because no suitable data can be
  110. // acquired the server (whilst communicating retry information) and the
  111. // client (whilst respecting the information from the server) may request
  112. // retries of the validation.
  113. //
  114. // https://tools.ietf.org/html/rfc8555#section-8.2
  115. //
  116. // Retry status is communicated using the error field and by sending a
  117. // Retry-After header back to the client.
  118. //
  119. // The request body is challenge-specific. The current challenges (http-01,
  120. // dns-01, tls-alpn-01) simply expect an empty object ("{}") in the payload
  121. // of the JWT sent by the client. We don't gain anything by stricly enforcing
  122. // nonexistence of unknown attributes, or, in these three cases, enforcing
  123. // an empty payload. And the spec also says to just ignore it:
  124. //
  125. // > The server MUST ignore any fields in the response object
  126. // > that are not specified as response fields for this type of challenge.
  127. //
  128. // https://tools.ietf.org/html/rfc8555#section-7.5.1
  129. //
  130. func (h *Handler) GetChallenge(w http.ResponseWriter, r *http.Request) {
  131. acc, err := acme.AccountFromContext(r.Context())
  132. if err != nil {
  133. api.WriteError(w, err)
  134. return
  135. }
  136. // Just verify that the payload was set since the client is required
  137. // to send _something_.
  138. _, err = payloadFromContext(r.Context())
  139. if err != nil {
  140. api.WriteError(w, err)
  141. return
  142. }
  143. var (
  144. ch *acme.Challenge
  145. chID = chi.URLParam(r, "chID")
  146. )
  147. ch, err = h.Auth.ValidateChallenge(r.Context(), acc.GetID(), chID, acc.GetKey())
  148. if err != nil {
  149. api.WriteError(w, err)
  150. return
  151. }
  152. w.Header().Add("Link", link(h.Auth.GetLink(r.Context(), acme.AuthzLink, true, ch.GetAuthzID()), "up"))
  153. w.Header().Set("Location", h.Auth.GetLink(r.Context(), acme.ChallengeLink, true, ch.GetID()))
  154. if ch.Status == acme.StatusProcessing {
  155. w.Header().Add("Retry-After", ch.RetryAfter)
  156. // 200s are cachable. Don't cache this because it will likely change.
  157. w.Header().Add("Cache-Control", "no-cache")
  158. }
  159. api.JSON(w, ch)
  160. }
  161. // GetCertificate ACME api for retrieving a Certificate.
  162. func (h *Handler) GetCertificate(w http.ResponseWriter, r *http.Request) {
  163. acc, err := acme.AccountFromContext(r.Context())
  164. if err != nil {
  165. api.WriteError(w, err)
  166. return
  167. }
  168. certID := chi.URLParam(r, "certID")
  169. certBytes, err := h.Auth.GetCertificate(acc.GetID(), certID)
  170. if err != nil {
  171. api.WriteError(w, err)
  172. return
  173. }
  174. w.Header().Set("Content-Type", "application/pem-certificate-chain; charset=utf-8")
  175. w.Write(certBytes)
  176. }