handler.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. package api
  2. import (
  3. "fmt"
  4. "net/http"
  5. "github.com/go-chi/chi"
  6. "github.com/pkg/errors"
  7. "github.com/smallstep/certificates/acme"
  8. "github.com/smallstep/certificates/api"
  9. "github.com/smallstep/certificates/authority/provisioner"
  10. "github.com/smallstep/cli/jose"
  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. return
  104. }
  105. // GetDirectory is the ACME resource for returning a directory configuration
  106. // for client configuration.
  107. func (h *Handler) GetDirectory(w http.ResponseWriter, r *http.Request) {
  108. prov, err := provisionerFromContext(r)
  109. if err != nil {
  110. api.WriteError(w, err)
  111. return
  112. }
  113. dir := h.Auth.GetDirectory(prov)
  114. api.JSON(w, dir)
  115. return
  116. }
  117. // GetAuthz ACME api for retrieving an Authz.
  118. func (h *Handler) GetAuthz(w http.ResponseWriter, r *http.Request) {
  119. prov, err := provisionerFromContext(r)
  120. if err != nil {
  121. api.WriteError(w, err)
  122. return
  123. }
  124. acc, err := accountFromContext(r)
  125. if err != nil {
  126. api.WriteError(w, err)
  127. return
  128. }
  129. authz, err := h.Auth.GetAuthz(prov, acc.GetID(), chi.URLParam(r, "authzID"))
  130. if err != nil {
  131. api.WriteError(w, err)
  132. return
  133. }
  134. w.Header().Set("Location", h.Auth.GetLink(acme.AuthzLink, acme.URLSafeProvisionerName(prov), true, authz.GetID()))
  135. api.JSON(w, authz)
  136. return
  137. }
  138. // GetChallenge ACME api for retrieving a Challenge.
  139. func (h *Handler) GetChallenge(w http.ResponseWriter, r *http.Request) {
  140. prov, err := provisionerFromContext(r)
  141. if err != nil {
  142. api.WriteError(w, err)
  143. return
  144. }
  145. acc, err := accountFromContext(r)
  146. if err != nil {
  147. api.WriteError(w, err)
  148. return
  149. }
  150. // Just verify that the payload was set, since we're not strictly adhering
  151. // to ACME V2 spec for reasons specified below.
  152. _, err = payloadFromContext(r)
  153. if err != nil {
  154. api.WriteError(w, err)
  155. return
  156. }
  157. // NOTE: We should be checking that the request is either a POST-as-GET, or
  158. // that the payload is an empty JSON block ({}). However, older ACME clients
  159. // still send a vestigial body (rather than an empty JSON block) and
  160. // strict enforcement would render these clients broken. For the time being
  161. // we'll just ignore the body.
  162. var (
  163. ch *acme.Challenge
  164. chID = chi.URLParam(r, "chID")
  165. )
  166. ch, err = h.Auth.ValidateChallenge(prov, acc.GetID(), chID, acc.GetKey())
  167. if err != nil {
  168. api.WriteError(w, err)
  169. return
  170. }
  171. getLink := h.Auth.GetLink
  172. w.Header().Add("Link", link(getLink(acme.AuthzLink, acme.URLSafeProvisionerName(prov), true, ch.GetAuthzID()), "up"))
  173. w.Header().Set("Location", getLink(acme.ChallengeLink, acme.URLSafeProvisionerName(prov), true, ch.GetID()))
  174. api.JSON(w, ch)
  175. return
  176. }
  177. // GetCertificate ACME api for retrieving a Certificate.
  178. func (h *Handler) GetCertificate(w http.ResponseWriter, r *http.Request) {
  179. acc, err := accountFromContext(r)
  180. if err != nil {
  181. api.WriteError(w, err)
  182. return
  183. }
  184. certID := chi.URLParam(r, "certID")
  185. certBytes, err := h.Auth.GetCertificate(acc.GetID(), certID)
  186. if err != nil {
  187. api.WriteError(w, err)
  188. return
  189. }
  190. w.Header().Set("Content-Type", "application/pem-certificate-chain; charset=utf-8")
  191. w.Write(certBytes)
  192. return
  193. }