handler.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. package api
  2. import (
  3. "fmt"
  4. "github.com/go-chi/chi"
  5. "github.com/pkg/errors"
  6. "github.com/smallstep/certificates/acme"
  7. "github.com/smallstep/certificates/api"
  8. "github.com/smallstep/certificates/authority/provisioner"
  9. "github.com/smallstep/cli/jose"
  10. "net/http"
  11. )
  12. func link(url, typ string) string {
  13. return fmt.Sprintf("<%s>;rel=\"%s\"", url, typ)
  14. }
  15. type contextKey string
  16. const (
  17. accContextKey = contextKey("acc")
  18. jwsContextKey = contextKey("jws")
  19. jwkContextKey = contextKey("jwk")
  20. payloadContextKey = contextKey("payload")
  21. provisionerContextKey = contextKey("provisioner")
  22. )
  23. type payloadInfo struct {
  24. value []byte
  25. isPostAsGet bool
  26. isEmptyJSON bool
  27. }
  28. func accountFromContext(r *http.Request) (*acme.Account, error) {
  29. val, ok := r.Context().Value(accContextKey).(*acme.Account)
  30. if !ok || val == nil {
  31. return nil, acme.AccountDoesNotExistErr(nil)
  32. }
  33. return val, nil
  34. }
  35. func jwkFromContext(r *http.Request) (*jose.JSONWebKey, error) {
  36. val, ok := r.Context().Value(jwkContextKey).(*jose.JSONWebKey)
  37. if !ok || val == nil {
  38. return nil, acme.ServerInternalErr(errors.Errorf("jwk expected in request context"))
  39. }
  40. return val, nil
  41. }
  42. func jwsFromContext(r *http.Request) (*jose.JSONWebSignature, error) {
  43. val, ok := r.Context().Value(jwsContextKey).(*jose.JSONWebSignature)
  44. if !ok || val == nil {
  45. return nil, acme.ServerInternalErr(errors.Errorf("jws expected in request context"))
  46. }
  47. return val, nil
  48. }
  49. func payloadFromContext(r *http.Request) (*payloadInfo, error) {
  50. val, ok := r.Context().Value(payloadContextKey).(*payloadInfo)
  51. if !ok || val == nil {
  52. return nil, acme.ServerInternalErr(errors.Errorf("payload expected in request context"))
  53. }
  54. return val, nil
  55. }
  56. func provisionerFromContext(r *http.Request) (provisioner.Interface, error) {
  57. val, ok := r.Context().Value(provisionerContextKey).(provisioner.Interface)
  58. if !ok || val == nil {
  59. return nil, acme.ServerInternalErr(errors.Errorf("provisioner expected in request context"))
  60. }
  61. return val, nil
  62. }
  63. // New returns a new ACME API router.
  64. func New(acmeAuth acme.Interface) api.RouterHandler {
  65. return &Handler{acmeAuth}
  66. }
  67. // Handler is the ACME request handler.
  68. type Handler struct {
  69. Auth acme.Interface
  70. }
  71. // Route traffic and implement the Router interface.
  72. func (h *Handler) Route(r api.Router) {
  73. getLink := h.Auth.GetLink
  74. // Standard ACME API
  75. r.MethodFunc("GET", getLink(acme.NewNonceLink, "{provisionerID}", false), h.lookupProvisioner(h.addNonce(h.GetNonce)))
  76. r.MethodFunc("HEAD", getLink(acme.NewNonceLink, "{provisionerID}", false), h.lookupProvisioner(h.addNonce(h.GetNonce)))
  77. r.MethodFunc("GET", getLink(acme.DirectoryLink, "{provisionerID}", false), h.lookupProvisioner(h.addNonce(h.GetDirectory)))
  78. r.MethodFunc("HEAD", getLink(acme.DirectoryLink, "{provisionerID}", false), h.lookupProvisioner(h.addNonce(h.GetDirectory)))
  79. extractPayloadByJWK := func(next nextHTTP) nextHTTP {
  80. return h.lookupProvisioner(h.addNonce(h.addDirLink(h.verifyContentType(h.parseJWS(h.validateJWS(h.extractJWK(h.verifyAndExtractJWSPayload(next))))))))
  81. }
  82. extractPayloadByKid := func(next nextHTTP) nextHTTP {
  83. return h.lookupProvisioner(h.addNonce(h.addDirLink(h.verifyContentType(h.parseJWS(h.validateJWS(h.lookupJWK(h.verifyAndExtractJWSPayload(next))))))))
  84. }
  85. r.MethodFunc("POST", getLink(acme.NewAccountLink, "{provisionerID}", false), extractPayloadByJWK(h.NewAccount))
  86. r.MethodFunc("POST", getLink(acme.AccountLink, "{provisionerID}", false, "{accID}"), extractPayloadByKid(h.GetUpdateAccount))
  87. r.MethodFunc("POST", getLink(acme.NewOrderLink, "{provisionerID}", false), extractPayloadByKid(h.NewOrder))
  88. r.MethodFunc("POST", getLink(acme.OrderLink, "{provisionerID}", false, "{ordID}"), extractPayloadByKid(h.isPostAsGet(h.GetOrder)))
  89. r.MethodFunc("POST", getLink(acme.OrdersByAccountLink, "{provisionerID}", false, "{accID}"), extractPayloadByKid(h.isPostAsGet(h.GetOrdersByAccount)))
  90. r.MethodFunc("POST", getLink(acme.FinalizeLink, "{provisionerID}", false, "{ordID}"), extractPayloadByKid(h.FinalizeOrder))
  91. r.MethodFunc("POST", getLink(acme.AuthzLink, "{provisionerID}", false, "{authzID}"), extractPayloadByKid(h.isPostAsGet(h.GetAuthz)))
  92. r.MethodFunc("POST", getLink(acme.ChallengeLink, "{provisionerID}", false, "{chID}"), extractPayloadByKid(h.GetChallenge))
  93. r.MethodFunc("POST", getLink(acme.CertificateLink, "{provisionerID}", false, "{certID}"), extractPayloadByKid(h.isPostAsGet(h.GetCertificate)))
  94. }
  95. // GetNonce just sets the right header since a Nonce is added to each response
  96. // by middleware by default.
  97. func (h *Handler) GetNonce(w http.ResponseWriter, r *http.Request) {
  98. if r.Method == "HEAD" {
  99. w.WriteHeader(http.StatusOK)
  100. } else {
  101. w.WriteHeader(http.StatusNoContent)
  102. }
  103. }
  104. // GetDirectory is the ACME resource for returning a directory configuration
  105. // for client configuration.
  106. func (h *Handler) GetDirectory(w http.ResponseWriter, r *http.Request) {
  107. prov, err := provisionerFromContext(r)
  108. if err != nil {
  109. api.WriteError(w, err)
  110. return
  111. }
  112. dir := h.Auth.GetDirectory(prov)
  113. api.JSON(w, dir)
  114. }
  115. // GetAuthz ACME api for retrieving an Authz.
  116. func (h *Handler) GetAuthz(w http.ResponseWriter, r *http.Request) {
  117. prov, err := provisionerFromContext(r)
  118. if err != nil {
  119. api.WriteError(w, err)
  120. return
  121. }
  122. acc, err := accountFromContext(r)
  123. if err != nil {
  124. api.WriteError(w, err)
  125. return
  126. }
  127. authz, err := h.Auth.GetAuthz(prov, acc.GetID(), chi.URLParam(r, "authzID"))
  128. if err != nil {
  129. api.WriteError(w, err)
  130. return
  131. }
  132. w.Header().Set("Location", h.Auth.GetLink(acme.AuthzLink, acme.URLSafeProvisionerName(prov), true, authz.GetID()))
  133. api.JSON(w, authz)
  134. }
  135. // ACME api for retrieving the Challenge resource.
  136. //
  137. // Potential Challenges are requested by the client when creating an order.
  138. // Once the client knows the appropriate validation resources are provisioned,
  139. // it makes a POST-as-GET request to this endpoint in order to initiate the
  140. // validation flow.
  141. //
  142. // The validation state machine describes the flow for a challenge.
  143. //
  144. // https://tools.ietf.org/html/rfc8555#section-7.1.6
  145. //
  146. // Once a validation attempt has completed without error, the challenge's
  147. // status is updated depending on the result (valid|invalid) of the server's
  148. // validation attempt. Once this is the case, a challenge cannot be reset.
  149. //
  150. // If a challenge cannot be completed because no suitable data can be
  151. // acquired the server (whilst communicating retry information) and the
  152. // client (whilst respecting the information from the server) may request
  153. // retries of the validation.
  154. //
  155. // https://tools.ietf.org/html/rfc8555#section-8.2
  156. //
  157. // Retry status is communicated using the error field and by sending a
  158. // Retry-After header back to the client.
  159. //
  160. // The request body is challenge-specific. The current challenges (http-01,
  161. // dns-01, tls-alpn-01) simply expect an empty object ("{}") in the payload
  162. // of the JWT sent by the client. We don't gain anything by stricly enforcing
  163. // nonexistence of unknown attributes, or, in these three cases, enforcing
  164. // an empty payload. And the spec also says to just ignore it:
  165. //
  166. // > The server MUST ignore any fields in the response object
  167. // > that are not specified as response fields for this type of challenge.
  168. //
  169. // https://tools.ietf.org/html/rfc8555#section-7.5.1
  170. //
  171. func (h *Handler) GetChallenge(w http.ResponseWriter, r *http.Request) {
  172. prov, err := provisionerFromContext(r)
  173. if err != nil {
  174. api.WriteError(w, err)
  175. return
  176. }
  177. acc, err := accountFromContext(r)
  178. if err != nil {
  179. api.WriteError(w, err)
  180. return
  181. }
  182. // Just verify that the payload was set since the client is required
  183. // to send _something_.
  184. _, err = payloadFromContext(r)
  185. if err != nil {
  186. api.WriteError(w, err)
  187. return
  188. }
  189. var (
  190. ch *acme.Challenge
  191. chID = chi.URLParam(r, "chID")
  192. )
  193. ch, err = h.Auth.ValidateChallenge(prov, acc.GetID(), chID, acc.GetKey())
  194. if err != nil {
  195. api.WriteError(w, err)
  196. }
  197. switch ch.Status {
  198. case acme.StatusPending:
  199. panic("validation attempt did not move challenge to the processing state")
  200. // When a transient error occurs, the challenge will not be progressed to the `invalid` state.
  201. // Add a Retry-After header to indicate that the client should check again in the future.
  202. case acme.StatusProcessing:
  203. w.Header().Add("Retry-After", ch.RetryAfter)
  204. w.Header().Add("Cache-Control", "no-cache")
  205. api.JSON(w, ch)
  206. case acme.StatusInvalid:
  207. api.JSON(w, ch)
  208. case acme.StatusValid:
  209. getLink := h.Auth.GetLink
  210. w.Header().Add("Link", link(getLink(acme.AuthzLink, acme.URLSafeProvisionerName(prov), true, ch.GetAuthzID()), "up"))
  211. w.Header().Set("Location", getLink(acme.ChallengeLink, acme.URLSafeProvisionerName(prov), true, ch.GetID()))
  212. api.JSON(w, ch)
  213. default:
  214. panic("unexpected challenge state" + ch.Status)
  215. }
  216. }
  217. // GetCertificate ACME api for retrieving a Certificate.
  218. func (h *Handler) GetCertificate(w http.ResponseWriter, r *http.Request) {
  219. acc, err := accountFromContext(r)
  220. if err != nil {
  221. api.WriteError(w, err)
  222. return
  223. }
  224. certID := chi.URLParam(r, "certID")
  225. certBytes, err := h.Auth.GetCertificate(acc.GetID(), certID)
  226. if err != nil {
  227. api.WriteError(w, err)
  228. return
  229. }
  230. w.Header().Set("Content-Type", "application/pem-certificate-chain; charset=utf-8")
  231. w.Write(certBytes)
  232. }