4
0

middleware.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. package api
  2. import (
  3. "context"
  4. "crypto/rsa"
  5. "errors"
  6. "io"
  7. "net/http"
  8. "net/url"
  9. "path"
  10. "strings"
  11. "go.step.sm/crypto/jose"
  12. "go.step.sm/crypto/keyutil"
  13. "github.com/smallstep/certificates/acme"
  14. "github.com/smallstep/certificates/api/render"
  15. "github.com/smallstep/certificates/authority/provisioner"
  16. "github.com/smallstep/certificates/logging"
  17. )
  18. type nextHTTP = func(http.ResponseWriter, *http.Request)
  19. func logNonce(w http.ResponseWriter, nonce string) {
  20. if rl, ok := w.(logging.ResponseLogger); ok {
  21. m := map[string]interface{}{
  22. "nonce": nonce,
  23. }
  24. rl.WithFields(m)
  25. }
  26. }
  27. // addNonce is a middleware that adds a nonce to the response header.
  28. func addNonce(next nextHTTP) nextHTTP {
  29. return func(w http.ResponseWriter, r *http.Request) {
  30. db := acme.MustDatabaseFromContext(r.Context())
  31. nonce, err := db.CreateNonce(r.Context())
  32. if err != nil {
  33. render.Error(w, r, err)
  34. return
  35. }
  36. w.Header().Set("Replay-Nonce", string(nonce))
  37. w.Header().Set("Cache-Control", "no-store")
  38. logNonce(w, string(nonce))
  39. next(w, r)
  40. }
  41. }
  42. // addDirLink is a middleware that adds a 'Link' response reader with the
  43. // directory index url.
  44. func addDirLink(next nextHTTP) nextHTTP {
  45. return func(w http.ResponseWriter, r *http.Request) {
  46. ctx := r.Context()
  47. linker := acme.MustLinkerFromContext(ctx)
  48. w.Header().Add("Link", link(linker.GetLink(ctx, acme.DirectoryLinkType), "index"))
  49. next(w, r)
  50. }
  51. }
  52. // verifyContentType is a middleware that verifies that content type is
  53. // application/jose+json.
  54. func verifyContentType(next nextHTTP) nextHTTP {
  55. return func(w http.ResponseWriter, r *http.Request) {
  56. p, err := provisionerFromContext(r.Context())
  57. if err != nil {
  58. render.Error(w, r, err)
  59. return
  60. }
  61. u := &url.URL{
  62. Path: acme.GetUnescapedPathSuffix(acme.CertificateLinkType, p.GetName(), ""),
  63. }
  64. var expected []string
  65. if strings.Contains(r.URL.String(), u.EscapedPath()) {
  66. // GET /certificate requests allow a greater range of content types.
  67. expected = []string{"application/jose+json", "application/pkix-cert", "application/pkcs7-mime"}
  68. } else {
  69. // By default every request should have content-type applictaion/jose+json.
  70. expected = []string{"application/jose+json"}
  71. }
  72. ct := r.Header.Get("Content-Type")
  73. for _, e := range expected {
  74. if ct == e {
  75. next(w, r)
  76. return
  77. }
  78. }
  79. render.Error(w, r, acme.NewError(acme.ErrorMalformedType,
  80. "expected content-type to be in %s, but got %s", expected, ct))
  81. }
  82. }
  83. // parseJWS is a middleware that parses a request body into a JSONWebSignature struct.
  84. func parseJWS(next nextHTTP) nextHTTP {
  85. return func(w http.ResponseWriter, r *http.Request) {
  86. body, err := io.ReadAll(r.Body)
  87. if err != nil {
  88. render.Error(w, r, acme.WrapErrorISE(err, "failed to read request body"))
  89. return
  90. }
  91. jws, err := jose.ParseJWS(string(body))
  92. if err != nil {
  93. render.Error(w, r, acme.WrapError(acme.ErrorMalformedType, err, "failed to parse JWS from request body"))
  94. return
  95. }
  96. ctx := context.WithValue(r.Context(), jwsContextKey, jws)
  97. next(w, r.WithContext(ctx))
  98. }
  99. }
  100. // validateJWS checks the request body for to verify that it meets ACME
  101. // requirements for a JWS.
  102. //
  103. // The JWS MUST NOT have multiple signatures
  104. // The JWS Unencoded Payload Option [RFC7797] MUST NOT be used
  105. // The JWS Unprotected Header [RFC7515] MUST NOT be used
  106. // The JWS Payload MUST NOT be detached
  107. // The JWS Protected Header MUST include the following fields:
  108. // - “alg” (Algorithm).
  109. // This field MUST NOT contain “none” or a Message Authentication Code
  110. // (MAC) algorithm (e.g. one in which the algorithm registry description
  111. // mentions MAC/HMAC).
  112. // - “nonce” (defined in Section 6.5)
  113. // - “url” (defined in Section 6.4)
  114. // - Either “jwk” (JSON Web Key) or “kid” (Key ID) as specified below<Paste>
  115. func validateJWS(next nextHTTP) nextHTTP {
  116. return func(w http.ResponseWriter, r *http.Request) {
  117. ctx := r.Context()
  118. db := acme.MustDatabaseFromContext(ctx)
  119. jws, err := jwsFromContext(ctx)
  120. if err != nil {
  121. render.Error(w, r, err)
  122. return
  123. }
  124. if len(jws.Signatures) == 0 {
  125. render.Error(w, r, acme.NewError(acme.ErrorMalformedType, "request body does not contain a signature"))
  126. return
  127. }
  128. if len(jws.Signatures) > 1 {
  129. render.Error(w, r, acme.NewError(acme.ErrorMalformedType, "request body contains more than one signature"))
  130. return
  131. }
  132. sig := jws.Signatures[0]
  133. uh := sig.Unprotected
  134. if uh.KeyID != "" ||
  135. uh.JSONWebKey != nil ||
  136. uh.Algorithm != "" ||
  137. uh.Nonce != "" ||
  138. len(uh.ExtraHeaders) > 0 {
  139. render.Error(w, r, acme.NewError(acme.ErrorMalformedType, "unprotected header must not be used"))
  140. return
  141. }
  142. hdr := sig.Protected
  143. switch hdr.Algorithm {
  144. case jose.RS256, jose.RS384, jose.RS512, jose.PS256, jose.PS384, jose.PS512:
  145. if hdr.JSONWebKey != nil {
  146. switch k := hdr.JSONWebKey.Key.(type) {
  147. case *rsa.PublicKey:
  148. if k.Size() < keyutil.MinRSAKeyBytes {
  149. render.Error(w, r, acme.NewError(acme.ErrorMalformedType,
  150. "rsa keys must be at least %d bits (%d bytes) in size",
  151. 8*keyutil.MinRSAKeyBytes, keyutil.MinRSAKeyBytes))
  152. return
  153. }
  154. default:
  155. render.Error(w, r, acme.NewError(acme.ErrorMalformedType,
  156. "jws key type and algorithm do not match"))
  157. return
  158. }
  159. }
  160. case jose.ES256, jose.ES384, jose.ES512, jose.EdDSA:
  161. // we good
  162. default:
  163. render.Error(w, r, acme.NewError(acme.ErrorBadSignatureAlgorithmType, "unsuitable algorithm: %s", hdr.Algorithm))
  164. return
  165. }
  166. // Check the validity/freshness of the Nonce.
  167. if err := db.DeleteNonce(ctx, acme.Nonce(hdr.Nonce)); err != nil {
  168. render.Error(w, r, err)
  169. return
  170. }
  171. // Check that the JWS url matches the requested url.
  172. jwsURL, ok := hdr.ExtraHeaders["url"].(string)
  173. if !ok {
  174. render.Error(w, r, acme.NewError(acme.ErrorMalformedType, "jws missing url protected header"))
  175. return
  176. }
  177. reqURL := &url.URL{Scheme: "https", Host: r.Host, Path: r.URL.Path}
  178. if jwsURL != reqURL.String() {
  179. render.Error(w, r, acme.NewError(acme.ErrorMalformedType,
  180. "url header in JWS (%s) does not match request url (%s)", jwsURL, reqURL))
  181. return
  182. }
  183. if hdr.JSONWebKey != nil && hdr.KeyID != "" {
  184. render.Error(w, r, acme.NewError(acme.ErrorMalformedType, "jwk and kid are mutually exclusive"))
  185. return
  186. }
  187. if hdr.JSONWebKey == nil && hdr.KeyID == "" {
  188. render.Error(w, r, acme.NewError(acme.ErrorMalformedType, "either jwk or kid must be defined in jws protected header"))
  189. return
  190. }
  191. next(w, r)
  192. }
  193. }
  194. // extractJWK is a middleware that extracts the JWK from the JWS and saves it
  195. // in the context. Make sure to parse and validate the JWS before running this
  196. // middleware.
  197. func extractJWK(next nextHTTP) nextHTTP {
  198. return func(w http.ResponseWriter, r *http.Request) {
  199. ctx := r.Context()
  200. db := acme.MustDatabaseFromContext(ctx)
  201. jws, err := jwsFromContext(ctx)
  202. if err != nil {
  203. render.Error(w, r, err)
  204. return
  205. }
  206. jwk := jws.Signatures[0].Protected.JSONWebKey
  207. if jwk == nil {
  208. render.Error(w, r, acme.NewError(acme.ErrorMalformedType, "jwk expected in protected header"))
  209. return
  210. }
  211. if !jwk.Valid() {
  212. render.Error(w, r, acme.NewError(acme.ErrorMalformedType, "invalid jwk in protected header"))
  213. return
  214. }
  215. // Overwrite KeyID with the JWK thumbprint.
  216. jwk.KeyID, err = acme.KeyToID(jwk)
  217. if err != nil {
  218. render.Error(w, r, acme.WrapErrorISE(err, "error getting KeyID from JWK"))
  219. return
  220. }
  221. // Store the JWK in the context.
  222. ctx = context.WithValue(ctx, jwkContextKey, jwk)
  223. // Get Account OR continue to generate a new one OR continue Revoke with certificate private key
  224. acc, err := db.GetAccountByKeyID(ctx, jwk.KeyID)
  225. switch {
  226. case acme.IsErrNotFound(err):
  227. // For NewAccount and Revoke requests ...
  228. break
  229. case err != nil:
  230. render.Error(w, r, err)
  231. return
  232. default:
  233. if !acc.IsValid() {
  234. render.Error(w, r, acme.NewError(acme.ErrorUnauthorizedType, "account is not active"))
  235. return
  236. }
  237. ctx = context.WithValue(ctx, accContextKey, acc)
  238. }
  239. next(w, r.WithContext(ctx))
  240. }
  241. }
  242. // checkPrerequisites checks if all prerequisites for serving ACME
  243. // are met by the CA configuration.
  244. func checkPrerequisites(next nextHTTP) nextHTTP {
  245. return func(w http.ResponseWriter, r *http.Request) {
  246. ctx := r.Context()
  247. // If the function is not set assume that all prerequisites are met.
  248. checkFunc, ok := acme.PrerequisitesCheckerFromContext(ctx)
  249. if ok {
  250. ok, err := checkFunc(ctx)
  251. if err != nil {
  252. render.Error(w, r, acme.WrapErrorISE(err, "error checking acme provisioner prerequisites"))
  253. return
  254. }
  255. if !ok {
  256. render.Error(w, r, acme.NewError(acme.ErrorNotImplementedType, "acme provisioner configuration lacks prerequisites"))
  257. return
  258. }
  259. }
  260. next(w, r)
  261. }
  262. }
  263. // lookupJWK loads the JWK associated with the acme account referenced by the
  264. // kid parameter of the signed payload.
  265. // Make sure to parse and validate the JWS before running this middleware.
  266. func lookupJWK(next nextHTTP) nextHTTP {
  267. return func(w http.ResponseWriter, r *http.Request) {
  268. ctx := r.Context()
  269. db := acme.MustDatabaseFromContext(ctx)
  270. jws, err := jwsFromContext(ctx)
  271. if err != nil {
  272. render.Error(w, r, err)
  273. return
  274. }
  275. kid := jws.Signatures[0].Protected.KeyID
  276. if kid == "" {
  277. render.Error(w, r, acme.NewError(acme.ErrorMalformedType, "signature missing 'kid'"))
  278. return
  279. }
  280. accID := path.Base(kid)
  281. acc, err := db.GetAccount(ctx, accID)
  282. switch {
  283. case acme.IsErrNotFound(err):
  284. render.Error(w, r, acme.NewError(acme.ErrorAccountDoesNotExistType, "account with ID '%s' not found", accID))
  285. return
  286. case err != nil:
  287. render.Error(w, r, err)
  288. return
  289. default:
  290. if !acc.IsValid() {
  291. render.Error(w, r, acme.NewError(acme.ErrorUnauthorizedType, "account is not active"))
  292. return
  293. }
  294. if storedLocation := acc.GetLocation(); storedLocation != "" {
  295. if kid != storedLocation {
  296. // ACME accounts should have a stored location equivalent to the
  297. // kid in the ACME request.
  298. render.Error(w, r, acme.NewError(acme.ErrorUnauthorizedType,
  299. "kid does not match stored account location; expected %s, but got %s",
  300. storedLocation, kid))
  301. return
  302. }
  303. // Verify that the provisioner with which the account was created
  304. // matches the provisioner in the request URL.
  305. reqProv := acme.MustProvisionerFromContext(ctx)
  306. switch {
  307. case acc.ProvisionerID == "" && acc.ProvisionerName != reqProv.GetName():
  308. render.Error(w, r, acme.NewError(acme.ErrorUnauthorizedType,
  309. "account provisioner does not match requested provisioner; account provisioner = %s, requested provisioner = %s",
  310. acc.ProvisionerName, reqProv.GetName()))
  311. return
  312. case acc.ProvisionerID != "" && acc.ProvisionerID != reqProv.GetID():
  313. render.Error(w, r, acme.NewError(acme.ErrorUnauthorizedType,
  314. "account provisioner does not match requested provisioner; account provisioner = %s, requested provisioner = %s",
  315. acc.ProvisionerID, reqProv.GetID()))
  316. return
  317. }
  318. } else {
  319. // This code will only execute for old ACME accounts that do
  320. // not have a cached location. The following validation was
  321. // the original implementation of the `kid` check which has
  322. // since been deprecated. However, the code will remain to
  323. // ensure consistent behavior for old ACME accounts.
  324. linker := acme.MustLinkerFromContext(ctx)
  325. kidPrefix := linker.GetLink(ctx, acme.AccountLinkType, "")
  326. if !strings.HasPrefix(kid, kidPrefix) {
  327. render.Error(w, r, acme.NewError(acme.ErrorMalformedType,
  328. "kid does not have required prefix; expected %s, but got %s",
  329. kidPrefix, kid))
  330. return
  331. }
  332. }
  333. ctx = context.WithValue(ctx, accContextKey, acc)
  334. ctx = context.WithValue(ctx, jwkContextKey, acc.Key)
  335. next(w, r.WithContext(ctx))
  336. return
  337. }
  338. }
  339. }
  340. // extractOrLookupJWK forwards handling to either extractJWK or
  341. // lookupJWK based on the presence of a JWK or a KID, respectively.
  342. func extractOrLookupJWK(next nextHTTP) nextHTTP {
  343. return func(w http.ResponseWriter, r *http.Request) {
  344. ctx := r.Context()
  345. jws, err := jwsFromContext(ctx)
  346. if err != nil {
  347. render.Error(w, r, err)
  348. return
  349. }
  350. // at this point the JWS has already been verified (if correctly configured in middleware),
  351. // and it can be used to check if a JWK exists. This flow is used when the ACME client
  352. // signed the payload with a certificate private key.
  353. if canExtractJWKFrom(jws) {
  354. extractJWK(next)(w, r)
  355. return
  356. }
  357. // default to looking up the JWK based on KeyID. This flow is used when the ACME client
  358. // signed the payload with an account private key.
  359. lookupJWK(next)(w, r)
  360. }
  361. }
  362. // canExtractJWKFrom checks if the JWS has a JWK that can be extracted
  363. func canExtractJWKFrom(jws *jose.JSONWebSignature) bool {
  364. if jws == nil {
  365. return false
  366. }
  367. if len(jws.Signatures) == 0 {
  368. return false
  369. }
  370. return jws.Signatures[0].Protected.JSONWebKey != nil
  371. }
  372. // verifyAndExtractJWSPayload extracts the JWK from the JWS and saves it in the context.
  373. // Make sure to parse and validate the JWS before running this middleware.
  374. func verifyAndExtractJWSPayload(next nextHTTP) nextHTTP {
  375. return func(w http.ResponseWriter, r *http.Request) {
  376. ctx := r.Context()
  377. jws, err := jwsFromContext(ctx)
  378. if err != nil {
  379. render.Error(w, r, err)
  380. return
  381. }
  382. jwk, err := jwkFromContext(ctx)
  383. if err != nil {
  384. render.Error(w, r, err)
  385. return
  386. }
  387. if jwk.Algorithm != "" && jwk.Algorithm != jws.Signatures[0].Protected.Algorithm {
  388. render.Error(w, r, acme.NewError(acme.ErrorMalformedType, "verifier and signature algorithm do not match"))
  389. return
  390. }
  391. payload, err := jws.Verify(jwk)
  392. switch {
  393. case errors.Is(err, jose.ErrCryptoFailure):
  394. payload, err = retryVerificationWithPatchedSignatures(jws, jwk)
  395. if err != nil {
  396. render.Error(w, r, acme.WrapError(acme.ErrorMalformedType, err, "error verifying jws with patched signature(s)"))
  397. return
  398. }
  399. case err != nil:
  400. render.Error(w, r, acme.WrapError(acme.ErrorMalformedType, err, "error verifying jws"))
  401. return
  402. }
  403. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{
  404. value: payload,
  405. isPostAsGet: len(payload) == 0,
  406. isEmptyJSON: string(payload) == "{}",
  407. })
  408. next(w, r.WithContext(ctx))
  409. }
  410. }
  411. // retryVerificationWithPatchedSignatures retries verification of the JWS using
  412. // the JWK by patching the JWS signatures if they're determined to be too short.
  413. //
  414. // Generally this shouldn't happen, but we've observed this to be the case with
  415. // the macOS ACME client, which seems to omit (at least one) leading null
  416. // byte(s). The error returned is `go-jose/go-jose: error in cryptographic
  417. // primitive`, which is a sentinel error that hides the details of the actual
  418. // underlying error, which is as follows: `go-jose/go-jose: invalid signature
  419. // size, have 63 bytes, wanted 64`, for ES256.
  420. func retryVerificationWithPatchedSignatures(jws *jose.JSONWebSignature, jwk *jose.JSONWebKey) (data []byte, err error) {
  421. originalSignatureValues := make([][]byte, len(jws.Signatures))
  422. patched := false
  423. defer func() {
  424. if patched && err != nil {
  425. for i, sig := range jws.Signatures {
  426. sig.Signature = originalSignatureValues[i]
  427. jws.Signatures[i] = sig
  428. }
  429. }
  430. }()
  431. for i, sig := range jws.Signatures {
  432. var expectedSize int
  433. alg := strings.ToUpper(sig.Header.Algorithm)
  434. switch alg {
  435. case jose.ES256:
  436. expectedSize = 64
  437. case jose.ES384:
  438. expectedSize = 96
  439. case jose.ES512:
  440. expectedSize = 132
  441. default:
  442. // other cases are (currently) ignored
  443. continue
  444. }
  445. switch diff := expectedSize - len(sig.Signature); diff {
  446. case 0:
  447. // expected length; nothing to do; will result in just doing the
  448. // same verification (as done before calling this function) again,
  449. // and thus an error will be returned.
  450. continue
  451. case 1:
  452. patched = true
  453. original := make([]byte, expectedSize-diff)
  454. copy(original, sig.Signature)
  455. originalSignatureValues[i] = original
  456. patchedR := make([]byte, expectedSize)
  457. copy(patchedR[1:], original) // [0x00, R.0:31, S.0:32], for expectedSize 64
  458. sig.Signature = patchedR
  459. jws.Signatures[i] = sig
  460. // verify it with a patched R; return early if successful; continue
  461. // with patching S if not.
  462. data, err = jws.Verify(jwk)
  463. if err == nil {
  464. return
  465. }
  466. patchedS := make([]byte, expectedSize)
  467. halfSize := expectedSize / 2
  468. copy(patchedS, original[:halfSize]) // [R.0:32], for expectedSize 64
  469. copy(patchedS[halfSize+1:], original[halfSize:]) // [R.0:32, 0x00, S.0:31]
  470. sig.Signature = patchedS
  471. jws.Signatures[i] = sig
  472. case 2:
  473. // assumption is currently the Apple case, in which only the
  474. // first null byte of R and/or S are removed, and thus not a case in
  475. // which two first bytes of either R or S are removed.
  476. patched = true
  477. original := make([]byte, expectedSize-diff)
  478. copy(original, sig.Signature)
  479. originalSignatureValues[i] = original
  480. patchedRS := make([]byte, expectedSize)
  481. halfSize := expectedSize / 2
  482. copy(patchedRS[1:], original[:halfSize-1]) // [0x00, R.0:31], for expectedSize 64
  483. copy(patchedRS[halfSize+1:], original[halfSize-1:]) // [0x00, R.0:31, 0x00, S.0:31]
  484. sig.Signature = patchedRS
  485. jws.Signatures[i] = sig
  486. default:
  487. // Technically, there can be multiple null bytes in either R or S,
  488. // so when the difference is larger than 2, there is more than one
  489. // option to pick. Apple's ACME client seems to only cut off the
  490. // first null byte of either R or S, so we don't do anything in this
  491. // case. Will result in just doing the same verification (as done
  492. // before calling this function) again, and thus an error will be
  493. // returned.
  494. // TODO(hs): log this specific case? It might mean some other ACME
  495. // client is doing weird things.
  496. continue
  497. }
  498. }
  499. data, err = jws.Verify(jwk)
  500. return
  501. }
  502. // isPostAsGet asserts that the request is a PostAsGet (empty JWS payload).
  503. func isPostAsGet(next nextHTTP) nextHTTP {
  504. return func(w http.ResponseWriter, r *http.Request) {
  505. payload, err := payloadFromContext(r.Context())
  506. if err != nil {
  507. render.Error(w, r, err)
  508. return
  509. }
  510. if !payload.isPostAsGet {
  511. render.Error(w, r, acme.NewError(acme.ErrorMalformedType, "expected POST-as-GET"))
  512. return
  513. }
  514. next(w, r)
  515. }
  516. }
  517. // ContextKey is the key type for storing and searching for ACME request
  518. // essentials in the context of a request.
  519. type ContextKey string
  520. const (
  521. // accContextKey account key
  522. accContextKey = ContextKey("acc")
  523. // jwsContextKey jws key
  524. jwsContextKey = ContextKey("jws")
  525. // jwkContextKey jwk key
  526. jwkContextKey = ContextKey("jwk")
  527. // payloadContextKey payload key
  528. payloadContextKey = ContextKey("payload")
  529. )
  530. // accountFromContext searches the context for an ACME account. Returns the
  531. // account or an error.
  532. func accountFromContext(ctx context.Context) (*acme.Account, error) {
  533. val, ok := ctx.Value(accContextKey).(*acme.Account)
  534. if !ok || val == nil {
  535. return nil, acme.NewError(acme.ErrorAccountDoesNotExistType, "account not in context")
  536. }
  537. return val, nil
  538. }
  539. // jwkFromContext searches the context for a JWK. Returns the JWK or an error.
  540. func jwkFromContext(ctx context.Context) (*jose.JSONWebKey, error) {
  541. val, ok := ctx.Value(jwkContextKey).(*jose.JSONWebKey)
  542. if !ok || val == nil {
  543. return nil, acme.NewErrorISE("jwk expected in request context")
  544. }
  545. return val, nil
  546. }
  547. // jwsFromContext searches the context for a JWS. Returns the JWS or an error.
  548. func jwsFromContext(ctx context.Context) (*jose.JSONWebSignature, error) {
  549. val, ok := ctx.Value(jwsContextKey).(*jose.JSONWebSignature)
  550. if !ok || val == nil {
  551. return nil, acme.NewErrorISE("jws expected in request context")
  552. }
  553. return val, nil
  554. }
  555. // provisionerFromContext searches the context for a provisioner. Returns the
  556. // provisioner or an error.
  557. func provisionerFromContext(ctx context.Context) (acme.Provisioner, error) {
  558. p, ok := acme.ProvisionerFromContext(ctx)
  559. if !ok || p == nil {
  560. return nil, acme.NewErrorISE("provisioner expected in request context")
  561. }
  562. return p, nil
  563. }
  564. // acmeProvisionerFromContext searches the context for an ACME provisioner. Returns
  565. // pointer to an ACME provisioner or an error.
  566. func acmeProvisionerFromContext(ctx context.Context) (*provisioner.ACME, error) {
  567. p, err := provisionerFromContext(ctx)
  568. if err != nil {
  569. return nil, err
  570. }
  571. ap, ok := p.(*provisioner.ACME)
  572. if !ok {
  573. return nil, acme.NewErrorISE("provisioner in context is not an ACME provisioner")
  574. }
  575. return ap, nil
  576. }
  577. // payloadFromContext searches the context for a payload. Returns the payload
  578. // or an error.
  579. func payloadFromContext(ctx context.Context) (*payloadInfo, error) {
  580. val, ok := ctx.Value(payloadContextKey).(*payloadInfo)
  581. if !ok || val == nil {
  582. return nil, acme.NewErrorISE("payload expected in request context")
  583. }
  584. return val, nil
  585. }