4
0

middleware_test.go 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897
  1. package api
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto"
  6. "encoding/base64"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "net/http"
  12. "net/http/httptest"
  13. "net/url"
  14. "strings"
  15. "testing"
  16. "github.com/google/uuid"
  17. "github.com/smallstep/assert"
  18. "github.com/smallstep/certificates/acme"
  19. tassert "github.com/stretchr/testify/assert"
  20. "github.com/stretchr/testify/require"
  21. "go.step.sm/crypto/jose"
  22. "go.step.sm/crypto/keyutil"
  23. )
  24. var testBody = []byte("foo")
  25. func testNext(w http.ResponseWriter, _ *http.Request) {
  26. w.Write(testBody)
  27. }
  28. func newBaseContext(ctx context.Context, args ...interface{}) context.Context {
  29. for _, a := range args {
  30. switch v := a.(type) {
  31. case acme.DB:
  32. ctx = acme.NewDatabaseContext(ctx, v)
  33. case acme.Linker:
  34. ctx = acme.NewLinkerContext(ctx, v)
  35. case acme.PrerequisitesChecker:
  36. ctx = acme.NewPrerequisitesCheckerContext(ctx, v)
  37. }
  38. }
  39. return ctx
  40. }
  41. func TestHandler_addNonce(t *testing.T) {
  42. u := "https://ca.smallstep.com/acme/new-nonce"
  43. type test struct {
  44. db acme.DB
  45. err *acme.Error
  46. statusCode int
  47. }
  48. var tests = map[string]func(t *testing.T) test{
  49. "fail/AddNonce-error": func(t *testing.T) test {
  50. return test{
  51. db: &acme.MockDB{
  52. MockCreateNonce: func(ctx context.Context) (acme.Nonce, error) {
  53. return acme.Nonce(""), acme.NewErrorISE("force")
  54. },
  55. },
  56. statusCode: 500,
  57. err: acme.NewErrorISE("force"),
  58. }
  59. },
  60. "ok": func(t *testing.T) test {
  61. return test{
  62. db: &acme.MockDB{
  63. MockCreateNonce: func(ctx context.Context) (acme.Nonce, error) {
  64. return "bar", nil
  65. },
  66. },
  67. statusCode: 200,
  68. }
  69. },
  70. }
  71. for name, run := range tests {
  72. tc := run(t)
  73. t.Run(name, func(t *testing.T) {
  74. ctx := newBaseContext(context.Background(), tc.db)
  75. req := httptest.NewRequest("GET", u, http.NoBody).WithContext(ctx)
  76. w := httptest.NewRecorder()
  77. addNonce(testNext)(w, req)
  78. res := w.Result()
  79. assert.Equals(t, res.StatusCode, tc.statusCode)
  80. body, err := io.ReadAll(res.Body)
  81. res.Body.Close()
  82. assert.FatalError(t, err)
  83. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  84. var ae acme.Error
  85. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  86. assert.Equals(t, ae.Type, tc.err.Type)
  87. assert.Equals(t, ae.Detail, tc.err.Detail)
  88. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  89. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  90. } else {
  91. assert.Equals(t, res.Header["Replay-Nonce"], []string{"bar"})
  92. assert.Equals(t, res.Header["Cache-Control"], []string{"no-store"})
  93. assert.Equals(t, bytes.TrimSpace(body), testBody)
  94. }
  95. })
  96. }
  97. }
  98. func TestHandler_addDirLink(t *testing.T) {
  99. prov := newProv()
  100. provName := url.PathEscape(prov.GetName())
  101. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  102. type test struct {
  103. link string
  104. statusCode int
  105. ctx context.Context
  106. err *acme.Error
  107. }
  108. var tests = map[string]func(t *testing.T) test{
  109. "ok": func(t *testing.T) test {
  110. ctx := acme.NewProvisionerContext(context.Background(), prov)
  111. ctx = acme.NewLinkerContext(ctx, acme.NewLinker("test.ca.smallstep.com", "acme"))
  112. return test{
  113. ctx: ctx,
  114. link: fmt.Sprintf("%s/acme/%s/directory", baseURL.String(), provName),
  115. statusCode: 200,
  116. }
  117. },
  118. }
  119. for name, run := range tests {
  120. tc := run(t)
  121. t.Run(name, func(t *testing.T) {
  122. req := httptest.NewRequest("GET", "/foo", http.NoBody)
  123. req = req.WithContext(tc.ctx)
  124. w := httptest.NewRecorder()
  125. addDirLink(testNext)(w, req)
  126. res := w.Result()
  127. assert.Equals(t, res.StatusCode, tc.statusCode)
  128. body, err := io.ReadAll(res.Body)
  129. res.Body.Close()
  130. assert.FatalError(t, err)
  131. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  132. var ae acme.Error
  133. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  134. assert.Equals(t, ae.Type, tc.err.Type)
  135. assert.Equals(t, ae.Detail, tc.err.Detail)
  136. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  137. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  138. } else {
  139. assert.Equals(t, res.Header["Link"], []string{fmt.Sprintf("<%s>;rel=\"index\"", tc.link)})
  140. assert.Equals(t, bytes.TrimSpace(body), testBody)
  141. }
  142. })
  143. }
  144. }
  145. func TestHandler_verifyContentType(t *testing.T) {
  146. prov := newProv()
  147. escProvName := url.PathEscape(prov.GetName())
  148. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  149. u := fmt.Sprintf("%s/acme/%s/certificate/abc123", baseURL.String(), escProvName)
  150. type test struct {
  151. ctx context.Context
  152. contentType string
  153. err *acme.Error
  154. statusCode int
  155. url string
  156. }
  157. var tests = map[string]func(t *testing.T) test{
  158. "fail/provisioner-not-set": func(t *testing.T) test {
  159. return test{
  160. url: u,
  161. ctx: context.Background(),
  162. contentType: "foo",
  163. statusCode: 500,
  164. err: acme.NewErrorISE("provisioner expected in request context"),
  165. }
  166. },
  167. "fail/general-bad-content-type": func(t *testing.T) test {
  168. return test{
  169. url: u,
  170. ctx: acme.NewProvisionerContext(context.Background(), prov),
  171. contentType: "foo",
  172. statusCode: 400,
  173. err: acme.NewError(acme.ErrorMalformedType, "expected content-type to be in [application/jose+json], but got foo"),
  174. }
  175. },
  176. "fail/certificate-bad-content-type": func(t *testing.T) test {
  177. return test{
  178. ctx: acme.NewProvisionerContext(context.Background(), prov),
  179. contentType: "foo",
  180. statusCode: 400,
  181. err: acme.NewError(acme.ErrorMalformedType, "expected content-type to be in [application/jose+json application/pkix-cert application/pkcs7-mime], but got foo"),
  182. }
  183. },
  184. "ok": func(t *testing.T) test {
  185. return test{
  186. ctx: acme.NewProvisionerContext(context.Background(), prov),
  187. contentType: "application/jose+json",
  188. statusCode: 200,
  189. }
  190. },
  191. "ok/certificate/pkix-cert": func(t *testing.T) test {
  192. return test{
  193. ctx: acme.NewProvisionerContext(context.Background(), prov),
  194. contentType: "application/pkix-cert",
  195. statusCode: 200,
  196. }
  197. },
  198. "ok/certificate/jose+json": func(t *testing.T) test {
  199. return test{
  200. ctx: acme.NewProvisionerContext(context.Background(), prov),
  201. contentType: "application/jose+json",
  202. statusCode: 200,
  203. }
  204. },
  205. "ok/certificate/pkcs7-mime": func(t *testing.T) test {
  206. return test{
  207. ctx: acme.NewProvisionerContext(context.Background(), prov),
  208. contentType: "application/pkcs7-mime",
  209. statusCode: 200,
  210. }
  211. },
  212. }
  213. for name, run := range tests {
  214. tc := run(t)
  215. t.Run(name, func(t *testing.T) {
  216. _u := u
  217. if tc.url != "" {
  218. _u = tc.url
  219. }
  220. req := httptest.NewRequest("GET", _u, http.NoBody)
  221. req = req.WithContext(tc.ctx)
  222. req.Header.Add("Content-Type", tc.contentType)
  223. w := httptest.NewRecorder()
  224. verifyContentType(testNext)(w, req)
  225. res := w.Result()
  226. assert.Equals(t, res.StatusCode, tc.statusCode)
  227. body, err := io.ReadAll(res.Body)
  228. res.Body.Close()
  229. assert.FatalError(t, err)
  230. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  231. var ae acme.Error
  232. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  233. assert.Equals(t, ae.Type, tc.err.Type)
  234. assert.Equals(t, ae.Detail, tc.err.Detail)
  235. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  236. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  237. } else {
  238. assert.Equals(t, bytes.TrimSpace(body), testBody)
  239. }
  240. })
  241. }
  242. }
  243. func TestHandler_isPostAsGet(t *testing.T) {
  244. u := "https://ca.smallstep.com/acme/new-account"
  245. type test struct {
  246. ctx context.Context
  247. err *acme.Error
  248. statusCode int
  249. }
  250. var tests = map[string]func(t *testing.T) test{
  251. "fail/no-payload": func(t *testing.T) test {
  252. return test{
  253. ctx: context.Background(),
  254. statusCode: 500,
  255. err: acme.NewErrorISE("payload expected in request context"),
  256. }
  257. },
  258. "fail/nil-payload": func(t *testing.T) test {
  259. return test{
  260. ctx: context.WithValue(context.Background(), payloadContextKey, nil),
  261. statusCode: 500,
  262. err: acme.NewErrorISE("payload expected in request context"),
  263. }
  264. },
  265. "fail/not-post-as-get": func(t *testing.T) test {
  266. return test{
  267. ctx: context.WithValue(context.Background(), payloadContextKey, &payloadInfo{}),
  268. statusCode: 400,
  269. err: acme.NewError(acme.ErrorMalformedType, "expected POST-as-GET"),
  270. }
  271. },
  272. "ok": func(t *testing.T) test {
  273. return test{
  274. ctx: context.WithValue(context.Background(), payloadContextKey, &payloadInfo{isPostAsGet: true}),
  275. statusCode: 200,
  276. }
  277. },
  278. }
  279. for name, run := range tests {
  280. tc := run(t)
  281. t.Run(name, func(t *testing.T) {
  282. // h := &Handler{}
  283. req := httptest.NewRequest("GET", u, http.NoBody)
  284. req = req.WithContext(tc.ctx)
  285. w := httptest.NewRecorder()
  286. isPostAsGet(testNext)(w, req)
  287. res := w.Result()
  288. assert.Equals(t, res.StatusCode, tc.statusCode)
  289. body, err := io.ReadAll(res.Body)
  290. res.Body.Close()
  291. assert.FatalError(t, err)
  292. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  293. var ae acme.Error
  294. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  295. assert.Equals(t, ae.Type, tc.err.Type)
  296. assert.Equals(t, ae.Detail, tc.err.Detail)
  297. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  298. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  299. } else {
  300. assert.Equals(t, bytes.TrimSpace(body), testBody)
  301. }
  302. })
  303. }
  304. }
  305. type errReader int
  306. func (errReader) Read([]byte) (int, error) {
  307. return 0, errors.New("force")
  308. }
  309. func (errReader) Close() error {
  310. return nil
  311. }
  312. func TestHandler_parseJWS(t *testing.T) {
  313. u := "https://ca.smallstep.com/acme/new-account"
  314. type test struct {
  315. next nextHTTP
  316. body io.Reader
  317. err *acme.Error
  318. statusCode int
  319. }
  320. var tests = map[string]func(t *testing.T) test{
  321. "fail/read-body-error": func(t *testing.T) test {
  322. return test{
  323. body: errReader(0),
  324. statusCode: 500,
  325. err: acme.NewErrorISE("failed to read request body: force"),
  326. }
  327. },
  328. "fail/parse-jws-error": func(t *testing.T) test {
  329. return test{
  330. body: strings.NewReader("foo"),
  331. statusCode: 400,
  332. err: acme.NewError(acme.ErrorMalformedType, "failed to parse JWS from request body: go-jose/go-jose: compact JWS format must have three parts"),
  333. }
  334. },
  335. "ok": func(t *testing.T) test {
  336. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  337. assert.FatalError(t, err)
  338. signer, err := jose.NewSigner(jose.SigningKey{
  339. Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
  340. Key: jwk.Key,
  341. }, new(jose.SignerOptions))
  342. assert.FatalError(t, err)
  343. signed, err := signer.Sign([]byte("baz"))
  344. assert.FatalError(t, err)
  345. expRaw, err := signed.CompactSerialize()
  346. assert.FatalError(t, err)
  347. return test{
  348. body: strings.NewReader(expRaw),
  349. next: func(w http.ResponseWriter, r *http.Request) {
  350. jws, err := jwsFromContext(r.Context())
  351. assert.FatalError(t, err)
  352. gotRaw, err := jws.CompactSerialize()
  353. assert.FatalError(t, err)
  354. assert.Equals(t, gotRaw, expRaw)
  355. w.Write(testBody)
  356. },
  357. statusCode: 200,
  358. }
  359. },
  360. }
  361. for name, run := range tests {
  362. tc := run(t)
  363. t.Run(name, func(t *testing.T) {
  364. // h := &Handler{}
  365. req := httptest.NewRequest("GET", u, tc.body)
  366. w := httptest.NewRecorder()
  367. parseJWS(tc.next)(w, req)
  368. res := w.Result()
  369. assert.Equals(t, res.StatusCode, tc.statusCode)
  370. body, err := io.ReadAll(res.Body)
  371. res.Body.Close()
  372. assert.FatalError(t, err)
  373. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  374. var ae acme.Error
  375. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  376. assert.Equals(t, ae.Type, tc.err.Type)
  377. assert.Equals(t, ae.Detail, tc.err.Detail)
  378. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  379. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  380. } else {
  381. assert.Equals(t, bytes.TrimSpace(body), testBody)
  382. }
  383. })
  384. }
  385. }
  386. func TestHandler_verifyAndExtractJWSPayload(t *testing.T) {
  387. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  388. assert.FatalError(t, err)
  389. _pub := jwk.Public()
  390. pub := &_pub
  391. so := new(jose.SignerOptions)
  392. so.WithHeader("alg", jose.SignatureAlgorithm(jwk.Algorithm))
  393. signer, err := jose.NewSigner(jose.SigningKey{
  394. Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
  395. Key: jwk.Key,
  396. }, so)
  397. assert.FatalError(t, err)
  398. jws, err := signer.Sign([]byte("baz"))
  399. assert.FatalError(t, err)
  400. raw, err := jws.CompactSerialize()
  401. assert.FatalError(t, err)
  402. parsedJWS, err := jose.ParseJWS(raw)
  403. assert.FatalError(t, err)
  404. u := "https://ca.smallstep.com/acme/account/1234"
  405. type test struct {
  406. ctx context.Context
  407. next func(http.ResponseWriter, *http.Request)
  408. err *acme.Error
  409. statusCode int
  410. }
  411. var tests = map[string]func(t *testing.T) test{
  412. "fail/no-jws": func(t *testing.T) test {
  413. return test{
  414. ctx: context.Background(),
  415. statusCode: 500,
  416. err: acme.NewErrorISE("jws expected in request context"),
  417. }
  418. },
  419. "fail/nil-jws": func(t *testing.T) test {
  420. return test{
  421. ctx: context.WithValue(context.Background(), jwsContextKey, nil),
  422. statusCode: 500,
  423. err: acme.NewErrorISE("jws expected in request context"),
  424. }
  425. },
  426. "fail/no-jwk": func(t *testing.T) test {
  427. return test{
  428. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  429. statusCode: 500,
  430. err: acme.NewErrorISE("jwk expected in request context"),
  431. }
  432. },
  433. "fail/nil-jwk": func(t *testing.T) test {
  434. ctx := context.WithValue(context.Background(), jwsContextKey, parsedJWS)
  435. return test{
  436. ctx: context.WithValue(ctx, jwsContextKey, nil),
  437. statusCode: 500,
  438. err: acme.NewErrorISE("jwk expected in request context"),
  439. }
  440. },
  441. "fail/verify-jws-failure-wrong-jwk": func(t *testing.T) test {
  442. _jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  443. assert.FatalError(t, err)
  444. _pub := _jwk.Public()
  445. ctx := context.WithValue(context.Background(), jwsContextKey, parsedJWS)
  446. ctx = context.WithValue(ctx, jwkContextKey, &_pub)
  447. return test{
  448. ctx: ctx,
  449. statusCode: 400,
  450. err: acme.NewError(acme.ErrorMalformedType, "error verifying jws: go-jose/go-jose: error in cryptographic primitive"),
  451. }
  452. },
  453. "fail/verify-jws-failure-too-many-signatures": func(t *testing.T) test {
  454. newParsedJWS, err := jose.ParseJWS(raw)
  455. assert.FatalError(t, err)
  456. newParsedJWS.Signatures = append(newParsedJWS.Signatures, newParsedJWS.Signatures...)
  457. ctx := context.WithValue(context.Background(), jwsContextKey, newParsedJWS)
  458. ctx = context.WithValue(ctx, jwkContextKey, pub)
  459. return test{
  460. ctx: ctx,
  461. statusCode: 400,
  462. err: acme.NewError(acme.ErrorMalformedType, "error verifying jws: go-jose/go-jose: too many signatures in payload; expecting only one"),
  463. }
  464. },
  465. "fail/apple-acmeclient-omitting-leading-null-byte-in-signature-with-wrong-jwk": func(t *testing.T) test {
  466. _jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  467. assert.FatalError(t, err)
  468. _pub := _jwk.Public()
  469. appleNullByteCaseBody := `{"payload":"dGVzdC0xMTA1","protected":"eyJhbGciOiJFUzI1NiJ9","signature":"rQPYKYflfKnlgBKqDeWsJH2TJ6iHAnou7sFzXlmYD4ArXqLfYuqotWERKrna2wfzh0pu7USWO2gzlOqRK9qq"}`
  470. appleNullByteCaseJWS, err := jose.ParseJWS(appleNullByteCaseBody)
  471. require.NoError(t, err)
  472. ctx := context.WithValue(context.Background(), jwsContextKey, appleNullByteCaseJWS)
  473. ctx = context.WithValue(ctx, jwkContextKey, &_pub)
  474. return test{
  475. ctx: ctx,
  476. statusCode: 400,
  477. err: acme.NewError(acme.ErrorMalformedType, "error verifying jws: go-jose/go-jose: error in cryptographic primitive"),
  478. }
  479. },
  480. "fail/algorithm-mismatch": func(t *testing.T) test {
  481. _pub := *pub
  482. clone := &_pub
  483. clone.Algorithm = jose.HS256
  484. ctx := context.WithValue(context.Background(), jwsContextKey, parsedJWS)
  485. ctx = context.WithValue(ctx, jwkContextKey, clone)
  486. return test{
  487. ctx: ctx,
  488. statusCode: 400,
  489. err: acme.NewError(acme.ErrorMalformedType, "verifier and signature algorithm do not match"),
  490. }
  491. },
  492. "ok": func(t *testing.T) test {
  493. ctx := context.WithValue(context.Background(), jwsContextKey, parsedJWS)
  494. ctx = context.WithValue(ctx, jwkContextKey, pub)
  495. return test{
  496. ctx: ctx,
  497. statusCode: 200,
  498. next: func(w http.ResponseWriter, r *http.Request) {
  499. p, err := payloadFromContext(r.Context())
  500. assert.FatalError(t, err)
  501. if assert.NotNil(t, p) {
  502. assert.Equals(t, p.value, []byte("baz"))
  503. assert.False(t, p.isPostAsGet)
  504. assert.False(t, p.isEmptyJSON)
  505. }
  506. w.Write(testBody)
  507. },
  508. }
  509. },
  510. "ok/empty-algorithm-in-jwk": func(t *testing.T) test {
  511. ctx := context.WithValue(context.Background(), jwsContextKey, parsedJWS)
  512. ctx = context.WithValue(ctx, jwkContextKey, pub)
  513. return test{
  514. ctx: ctx,
  515. statusCode: 200,
  516. next: func(w http.ResponseWriter, r *http.Request) {
  517. p, err := payloadFromContext(r.Context())
  518. assert.FatalError(t, err)
  519. if assert.NotNil(t, p) {
  520. assert.Equals(t, p.value, []byte("baz"))
  521. assert.False(t, p.isPostAsGet)
  522. assert.False(t, p.isEmptyJSON)
  523. }
  524. w.Write(testBody)
  525. },
  526. }
  527. },
  528. "ok/post-as-get": func(t *testing.T) test {
  529. _jws, err := signer.Sign([]byte(""))
  530. assert.FatalError(t, err)
  531. _raw, err := _jws.CompactSerialize()
  532. assert.FatalError(t, err)
  533. _parsed, err := jose.ParseJWS(_raw)
  534. assert.FatalError(t, err)
  535. ctx := context.WithValue(context.Background(), jwsContextKey, _parsed)
  536. ctx = context.WithValue(ctx, jwkContextKey, pub)
  537. return test{
  538. ctx: ctx,
  539. statusCode: 200,
  540. next: func(w http.ResponseWriter, r *http.Request) {
  541. p, err := payloadFromContext(r.Context())
  542. assert.FatalError(t, err)
  543. if assert.NotNil(t, p) {
  544. assert.Equals(t, p.value, []byte{})
  545. assert.True(t, p.isPostAsGet)
  546. assert.False(t, p.isEmptyJSON)
  547. }
  548. w.Write(testBody)
  549. },
  550. }
  551. },
  552. "ok/empty-json": func(t *testing.T) test {
  553. _jws, err := signer.Sign([]byte("{}"))
  554. assert.FatalError(t, err)
  555. _raw, err := _jws.CompactSerialize()
  556. assert.FatalError(t, err)
  557. _parsed, err := jose.ParseJWS(_raw)
  558. assert.FatalError(t, err)
  559. ctx := context.WithValue(context.Background(), jwsContextKey, _parsed)
  560. ctx = context.WithValue(ctx, jwkContextKey, pub)
  561. return test{
  562. ctx: ctx,
  563. statusCode: 200,
  564. next: func(w http.ResponseWriter, r *http.Request) {
  565. p, err := payloadFromContext(r.Context())
  566. assert.FatalError(t, err)
  567. if assert.NotNil(t, p) {
  568. assert.Equals(t, p.value, []byte("{}"))
  569. assert.False(t, p.isPostAsGet)
  570. assert.True(t, p.isEmptyJSON)
  571. }
  572. w.Write(testBody)
  573. },
  574. }
  575. },
  576. "ok/apple-acmeclient-omitting-leading-null-byte-in-signature": func(t *testing.T) test {
  577. appleNullByteCaseKey := []byte(`{
  578. "kid": "uioinbiTlJICL0MYsb6ar1totfRA2tiPqWgntF8xUdo",
  579. "crv": "P-256",
  580. "alg": "ES256",
  581. "kty": "EC",
  582. "x": "wlz-Kv9X0h32fzLq-cogls9HxoZQqV-GuWxdb2MCeUY",
  583. "y": "xzP6zRrg_jynYljZTxfJuql_QWtdQR6lpJ52q_6Vavg"
  584. }`)
  585. appleNullByteCaseJWK := &jose.JSONWebKey{}
  586. err = json.Unmarshal(appleNullByteCaseKey, appleNullByteCaseJWK)
  587. require.NoError(t, err)
  588. appleNullByteCaseBody := `{"payload":"dGVzdC0xMTA1","protected":"eyJhbGciOiJFUzI1NiJ9","signature":"rQPYKYflfKnlgBKqDeWsJH2TJ6iHAnou7sFzXlmYD4ArXqLfYuqotWERKrna2wfzh0pu7USWO2gzlOqRK9qq"}`
  589. appleNullByteCaseJWS, err := jose.ParseJWS(appleNullByteCaseBody)
  590. require.NoError(t, err)
  591. ctx := context.WithValue(context.Background(), jwsContextKey, appleNullByteCaseJWS)
  592. ctx = context.WithValue(ctx, jwkContextKey, appleNullByteCaseJWK)
  593. return test{
  594. ctx: ctx,
  595. statusCode: 200,
  596. next: func(w http.ResponseWriter, r *http.Request) {
  597. p, err := payloadFromContext(r.Context())
  598. tassert.NoError(t, err)
  599. if tassert.NotNil(t, p) {
  600. tassert.Equal(t, []byte(`test-1105`), p.value)
  601. tassert.False(t, p.isPostAsGet)
  602. tassert.False(t, p.isEmptyJSON)
  603. }
  604. w.Write(testBody)
  605. },
  606. }
  607. },
  608. }
  609. for name, run := range tests {
  610. tc := run(t)
  611. t.Run(name, func(t *testing.T) {
  612. // h := &Handler{}
  613. req := httptest.NewRequest("GET", u, http.NoBody)
  614. req = req.WithContext(tc.ctx)
  615. w := httptest.NewRecorder()
  616. verifyAndExtractJWSPayload(tc.next)(w, req)
  617. res := w.Result()
  618. assert.Equals(t, res.StatusCode, tc.statusCode)
  619. body, err := io.ReadAll(res.Body)
  620. res.Body.Close()
  621. assert.FatalError(t, err)
  622. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  623. var ae acme.Error
  624. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  625. assert.Equals(t, ae.Type, tc.err.Type)
  626. assert.Equals(t, ae.Detail, tc.err.Detail)
  627. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  628. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  629. } else {
  630. assert.Equals(t, bytes.TrimSpace(body), testBody)
  631. }
  632. })
  633. }
  634. }
  635. func TestHandler_lookupJWK(t *testing.T) {
  636. prov := newProv()
  637. provName := url.PathEscape(prov.GetName())
  638. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  639. u := fmt.Sprintf("%s/acme/%s/account/1234",
  640. baseURL, provName)
  641. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  642. assert.FatalError(t, err)
  643. accID := "account-id"
  644. prefix := fmt.Sprintf("%s/acme/%s/account/",
  645. baseURL, provName)
  646. so := new(jose.SignerOptions)
  647. so.WithHeader("kid", fmt.Sprintf("%s%s", prefix, accID))
  648. signer, err := jose.NewSigner(jose.SigningKey{
  649. Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
  650. Key: jwk.Key,
  651. }, so)
  652. assert.FatalError(t, err)
  653. jws, err := signer.Sign([]byte("baz"))
  654. assert.FatalError(t, err)
  655. raw, err := jws.CompactSerialize()
  656. assert.FatalError(t, err)
  657. parsedJWS, err := jose.ParseJWS(raw)
  658. assert.FatalError(t, err)
  659. type test struct {
  660. linker acme.Linker
  661. db acme.DB
  662. ctx context.Context
  663. next func(http.ResponseWriter, *http.Request)
  664. err *acme.Error
  665. statusCode int
  666. }
  667. var tests = map[string]func(t *testing.T) test{
  668. "fail/no-jws": func(t *testing.T) test {
  669. return test{
  670. db: &acme.MockDB{},
  671. linker: acme.NewLinker("test.ca.smallstep.com", "acme"),
  672. ctx: acme.NewProvisionerContext(context.Background(), prov),
  673. statusCode: 500,
  674. err: acme.NewErrorISE("jws expected in request context"),
  675. }
  676. },
  677. "fail/nil-jws": func(t *testing.T) test {
  678. ctx := acme.NewProvisionerContext(context.Background(), prov)
  679. ctx = context.WithValue(ctx, jwsContextKey, nil)
  680. return test{
  681. db: &acme.MockDB{},
  682. linker: acme.NewLinker("test.ca.smallstep.com", "acme"),
  683. ctx: ctx,
  684. statusCode: 500,
  685. err: acme.NewErrorISE("jws expected in request context"),
  686. }
  687. },
  688. "fail/no-kid": func(t *testing.T) test {
  689. _signer, err := jose.NewSigner(jose.SigningKey{
  690. Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
  691. Key: jwk.Key,
  692. }, new(jose.SignerOptions))
  693. assert.FatalError(t, err)
  694. _jws, err := _signer.Sign([]byte("baz"))
  695. assert.FatalError(t, err)
  696. ctx := acme.NewProvisionerContext(context.Background(), prov)
  697. ctx = context.WithValue(ctx, jwsContextKey, _jws)
  698. return test{
  699. db: &acme.MockDB{},
  700. linker: acme.NewLinker("test.ca.smallstep.com", "acme"),
  701. ctx: ctx,
  702. statusCode: 400,
  703. err: acme.NewError(acme.ErrorMalformedType, "signature missing 'kid'"),
  704. }
  705. },
  706. "fail/account-not-found": func(t *testing.T) test {
  707. ctx := acme.NewProvisionerContext(context.Background(), prov)
  708. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  709. return test{
  710. linker: acme.NewLinker("test.ca.smallstep.com", "acme"),
  711. db: &acme.MockDB{
  712. MockGetAccount: func(ctx context.Context, accID string) (*acme.Account, error) {
  713. assert.Equals(t, accID, accID)
  714. return nil, acme.ErrNotFound
  715. },
  716. },
  717. ctx: ctx,
  718. statusCode: 400,
  719. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  720. }
  721. },
  722. "fail/GetAccount-error": func(t *testing.T) test {
  723. ctx := acme.NewProvisionerContext(context.Background(), prov)
  724. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  725. return test{
  726. linker: acme.NewLinker("test.ca.smallstep.com", "acme"),
  727. db: &acme.MockDB{
  728. MockGetAccount: func(ctx context.Context, id string) (*acme.Account, error) {
  729. assert.Equals(t, id, accID)
  730. return nil, acme.NewErrorISE("force")
  731. },
  732. },
  733. ctx: ctx,
  734. statusCode: 500,
  735. err: acme.NewErrorISE("force"),
  736. }
  737. },
  738. "fail/account-not-valid": func(t *testing.T) test {
  739. acc := &acme.Account{Status: "deactivated"}
  740. ctx := acme.NewProvisionerContext(context.Background(), prov)
  741. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  742. return test{
  743. linker: acme.NewLinker("test.ca.smallstep.com", "acme"),
  744. db: &acme.MockDB{
  745. MockGetAccount: func(ctx context.Context, id string) (*acme.Account, error) {
  746. assert.Equals(t, id, accID)
  747. return acc, nil
  748. },
  749. },
  750. ctx: ctx,
  751. statusCode: 401,
  752. err: acme.NewError(acme.ErrorUnauthorizedType, "account is not active"),
  753. }
  754. },
  755. "fail/account-with-location-prefix/bad-kid": func(t *testing.T) test {
  756. acc := &acme.Account{LocationPrefix: "foobar", Status: "valid"}
  757. ctx := acme.NewProvisionerContext(context.Background(), prov)
  758. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  759. return test{
  760. linker: acme.NewLinker("test.ca.smallstep.com", "acme"),
  761. db: &acme.MockDB{
  762. MockGetAccount: func(ctx context.Context, id string) (*acme.Account, error) {
  763. assert.Equals(t, id, accID)
  764. return acc, nil
  765. },
  766. },
  767. ctx: ctx,
  768. statusCode: http.StatusUnauthorized,
  769. err: acme.NewError(acme.ErrorUnauthorizedType, "kid does not match stored account location; expected foobar, but %q", prefix+accID),
  770. }
  771. },
  772. "fail/account-with-location-prefix/bad-provisioner": func(t *testing.T) test {
  773. acc := &acme.Account{LocationPrefix: prefix + accID, Status: "valid", Key: jwk, ProvisionerName: "other"}
  774. ctx := acme.NewProvisionerContext(context.Background(), prov)
  775. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  776. return test{
  777. linker: acme.NewLinker("test.ca.smallstep.com", "acme"),
  778. db: &acme.MockDB{
  779. MockGetAccount: func(ctx context.Context, id string) (*acme.Account, error) {
  780. assert.Equals(t, id, accID)
  781. return acc, nil
  782. },
  783. },
  784. ctx: ctx,
  785. next: func(w http.ResponseWriter, r *http.Request) {
  786. _acc, err := accountFromContext(r.Context())
  787. assert.FatalError(t, err)
  788. assert.Equals(t, _acc, acc)
  789. _jwk, err := jwkFromContext(r.Context())
  790. assert.FatalError(t, err)
  791. assert.Equals(t, _jwk, jwk)
  792. w.Write(testBody)
  793. },
  794. statusCode: http.StatusUnauthorized,
  795. err: acme.NewError(acme.ErrorUnauthorizedType,
  796. "account provisioner does not match requested provisioner; account provisioner = %s, requested provisioner = %s",
  797. "other", prov.GetName()),
  798. }
  799. },
  800. "fail/account-with-location-prefix/bad-provisioner-id": func(t *testing.T) test {
  801. p := newProvWithID()
  802. acc := &acme.Account{LocationPrefix: prefix + accID, Status: "valid", Key: jwk, ProvisionerID: uuid.NewString()}
  803. ctx := acme.NewProvisionerContext(context.Background(), p)
  804. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  805. return test{
  806. linker: acme.NewLinker("test.ca.smallstep.com", "acme"),
  807. db: &acme.MockDB{
  808. MockGetAccount: func(ctx context.Context, id string) (*acme.Account, error) {
  809. assert.Equals(t, id, accID)
  810. return acc, nil
  811. },
  812. },
  813. ctx: ctx,
  814. next: func(w http.ResponseWriter, r *http.Request) {
  815. _acc, err := accountFromContext(r.Context())
  816. assert.FatalError(t, err)
  817. assert.Equals(t, _acc, acc)
  818. _jwk, err := jwkFromContext(r.Context())
  819. assert.FatalError(t, err)
  820. assert.Equals(t, _jwk, jwk)
  821. w.Write(testBody)
  822. },
  823. statusCode: http.StatusUnauthorized,
  824. err: acme.NewError(acme.ErrorUnauthorizedType,
  825. "account provisioner does not match requested provisioner; account provisioner = %s, requested provisioner = %s",
  826. acc.ProvisionerID, p.GetID()),
  827. }
  828. },
  829. "ok/account-with-location-prefix": func(t *testing.T) test {
  830. acc := &acme.Account{LocationPrefix: prefix + accID, Status: "valid", Key: jwk, ProvisionerName: prov.GetName()}
  831. ctx := acme.NewProvisionerContext(context.Background(), prov)
  832. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  833. return test{
  834. linker: acme.NewLinker("test.ca.smallstep.com", "acme"),
  835. db: &acme.MockDB{
  836. MockGetAccount: func(ctx context.Context, id string) (*acme.Account, error) {
  837. assert.Equals(t, id, accID)
  838. return acc, nil
  839. },
  840. },
  841. ctx: ctx,
  842. next: func(w http.ResponseWriter, r *http.Request) {
  843. _acc, err := accountFromContext(r.Context())
  844. assert.FatalError(t, err)
  845. assert.Equals(t, _acc, acc)
  846. _jwk, err := jwkFromContext(r.Context())
  847. assert.FatalError(t, err)
  848. assert.Equals(t, _jwk, jwk)
  849. w.Write(testBody)
  850. },
  851. statusCode: http.StatusOK,
  852. }
  853. },
  854. "ok/account-without-location-prefix": func(t *testing.T) test {
  855. acc := &acme.Account{Status: "valid", Key: jwk}
  856. ctx := acme.NewProvisionerContext(context.Background(), prov)
  857. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  858. return test{
  859. linker: acme.NewLinker("test.ca.smallstep.com", "acme"),
  860. db: &acme.MockDB{
  861. MockGetAccount: func(ctx context.Context, id string) (*acme.Account, error) {
  862. assert.Equals(t, id, accID)
  863. return acc, nil
  864. },
  865. },
  866. ctx: ctx,
  867. next: func(w http.ResponseWriter, r *http.Request) {
  868. _acc, err := accountFromContext(r.Context())
  869. assert.FatalError(t, err)
  870. assert.Equals(t, _acc, acc)
  871. _jwk, err := jwkFromContext(r.Context())
  872. assert.FatalError(t, err)
  873. assert.Equals(t, _jwk, jwk)
  874. w.Write(testBody)
  875. },
  876. statusCode: 200,
  877. }
  878. },
  879. "ok/account-with-provisioner-id": func(t *testing.T) test {
  880. p := newProvWithID()
  881. acc := &acme.Account{LocationPrefix: prefix + accID, Status: "valid", Key: jwk, ProvisionerID: p.GetID()}
  882. ctx := acme.NewProvisionerContext(context.Background(), p)
  883. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  884. return test{
  885. linker: acme.NewLinker("test.ca.smallstep.com", "acme"),
  886. db: &acme.MockDB{
  887. MockGetAccount: func(ctx context.Context, id string) (*acme.Account, error) {
  888. assert.Equals(t, id, accID)
  889. return acc, nil
  890. },
  891. },
  892. ctx: ctx,
  893. next: func(w http.ResponseWriter, r *http.Request) {
  894. _acc, err := accountFromContext(r.Context())
  895. assert.FatalError(t, err)
  896. assert.Equals(t, _acc, acc)
  897. _jwk, err := jwkFromContext(r.Context())
  898. assert.FatalError(t, err)
  899. assert.Equals(t, _jwk, jwk)
  900. w.Write(testBody)
  901. },
  902. statusCode: 200,
  903. }
  904. },
  905. }
  906. for name, run := range tests {
  907. tc := run(t)
  908. t.Run(name, func(t *testing.T) {
  909. ctx := newBaseContext(tc.ctx, tc.db, tc.linker)
  910. req := httptest.NewRequest("GET", u, http.NoBody)
  911. req = req.WithContext(ctx)
  912. w := httptest.NewRecorder()
  913. lookupJWK(tc.next)(w, req)
  914. res := w.Result()
  915. assert.Equals(t, res.StatusCode, tc.statusCode)
  916. body, err := io.ReadAll(res.Body)
  917. res.Body.Close()
  918. assert.FatalError(t, err)
  919. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  920. var ae acme.Error
  921. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  922. assert.Equals(t, ae.Type, tc.err.Type)
  923. assert.Equals(t, ae.Detail, tc.err.Detail)
  924. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  925. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  926. } else {
  927. assert.Equals(t, bytes.TrimSpace(body), testBody)
  928. }
  929. })
  930. }
  931. }
  932. func TestHandler_extractJWK(t *testing.T) {
  933. prov := newProv()
  934. provName := url.PathEscape(prov.GetName())
  935. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  936. assert.FatalError(t, err)
  937. kid, err := jwk.Thumbprint(crypto.SHA256)
  938. assert.FatalError(t, err)
  939. pub := jwk.Public()
  940. pub.KeyID = base64.RawURLEncoding.EncodeToString(kid)
  941. so := new(jose.SignerOptions)
  942. so.WithHeader("jwk", pub)
  943. signer, err := jose.NewSigner(jose.SigningKey{
  944. Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
  945. Key: jwk.Key,
  946. }, so)
  947. assert.FatalError(t, err)
  948. jws, err := signer.Sign([]byte("baz"))
  949. assert.FatalError(t, err)
  950. raw, err := jws.CompactSerialize()
  951. assert.FatalError(t, err)
  952. parsedJWS, err := jose.ParseJWS(raw)
  953. assert.FatalError(t, err)
  954. u := fmt.Sprintf("https://ca.smallstep.com/acme/%s/account/1234",
  955. provName)
  956. type test struct {
  957. db acme.DB
  958. ctx context.Context
  959. next func(http.ResponseWriter, *http.Request)
  960. err *acme.Error
  961. statusCode int
  962. }
  963. var tests = map[string]func(t *testing.T) test{
  964. "fail/no-jws": func(t *testing.T) test {
  965. return test{
  966. db: &acme.MockDB{},
  967. ctx: acme.NewProvisionerContext(context.Background(), prov),
  968. statusCode: 500,
  969. err: acme.NewErrorISE("jws expected in request context"),
  970. }
  971. },
  972. "fail/nil-jws": func(t *testing.T) test {
  973. ctx := acme.NewProvisionerContext(context.Background(), prov)
  974. ctx = context.WithValue(ctx, jwsContextKey, nil)
  975. return test{
  976. db: &acme.MockDB{},
  977. ctx: ctx,
  978. statusCode: 500,
  979. err: acme.NewErrorISE("jws expected in request context"),
  980. }
  981. },
  982. "fail/nil-jwk": func(t *testing.T) test {
  983. _jws := &jose.JSONWebSignature{
  984. Signatures: []jose.Signature{
  985. {
  986. Protected: jose.Header{
  987. JSONWebKey: nil,
  988. },
  989. },
  990. },
  991. }
  992. ctx := acme.NewProvisionerContext(context.Background(), prov)
  993. ctx = context.WithValue(ctx, jwsContextKey, _jws)
  994. return test{
  995. db: &acme.MockDB{},
  996. ctx: ctx,
  997. statusCode: 400,
  998. err: acme.NewError(acme.ErrorMalformedType, "jwk expected in protected header"),
  999. }
  1000. },
  1001. "fail/invalid-jwk": func(t *testing.T) test {
  1002. _jws := &jose.JSONWebSignature{
  1003. Signatures: []jose.Signature{
  1004. {
  1005. Protected: jose.Header{
  1006. JSONWebKey: &jose.JSONWebKey{Key: "foo"},
  1007. },
  1008. },
  1009. },
  1010. }
  1011. ctx := acme.NewProvisionerContext(context.Background(), prov)
  1012. ctx = context.WithValue(ctx, jwsContextKey, _jws)
  1013. return test{
  1014. db: &acme.MockDB{},
  1015. ctx: ctx,
  1016. statusCode: 400,
  1017. err: acme.NewError(acme.ErrorMalformedType, "invalid jwk in protected header"),
  1018. }
  1019. },
  1020. "fail/GetAccountByKey-error": func(t *testing.T) test {
  1021. ctx := acme.NewProvisionerContext(context.Background(), prov)
  1022. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  1023. return test{
  1024. ctx: ctx,
  1025. db: &acme.MockDB{
  1026. MockGetAccountByKeyID: func(ctx context.Context, kid string) (*acme.Account, error) {
  1027. assert.Equals(t, kid, pub.KeyID)
  1028. return nil, acme.NewErrorISE("force")
  1029. },
  1030. },
  1031. statusCode: 500,
  1032. err: acme.NewErrorISE("force"),
  1033. }
  1034. },
  1035. "fail/account-not-valid": func(t *testing.T) test {
  1036. acc := &acme.Account{Status: "deactivated"}
  1037. ctx := acme.NewProvisionerContext(context.Background(), prov)
  1038. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  1039. return test{
  1040. ctx: ctx,
  1041. db: &acme.MockDB{
  1042. MockGetAccountByKeyID: func(ctx context.Context, kid string) (*acme.Account, error) {
  1043. assert.Equals(t, kid, pub.KeyID)
  1044. return acc, nil
  1045. },
  1046. },
  1047. statusCode: 401,
  1048. err: acme.NewError(acme.ErrorUnauthorizedType, "account is not active"),
  1049. }
  1050. },
  1051. "ok": func(t *testing.T) test {
  1052. acc := &acme.Account{Status: "valid"}
  1053. ctx := acme.NewProvisionerContext(context.Background(), prov)
  1054. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  1055. return test{
  1056. ctx: ctx,
  1057. db: &acme.MockDB{
  1058. MockGetAccountByKeyID: func(ctx context.Context, kid string) (*acme.Account, error) {
  1059. assert.Equals(t, kid, pub.KeyID)
  1060. return acc, nil
  1061. },
  1062. },
  1063. next: func(w http.ResponseWriter, r *http.Request) {
  1064. _acc, err := accountFromContext(r.Context())
  1065. assert.FatalError(t, err)
  1066. assert.Equals(t, _acc, acc)
  1067. _jwk, err := jwkFromContext(r.Context())
  1068. assert.FatalError(t, err)
  1069. assert.Equals(t, _jwk.KeyID, pub.KeyID)
  1070. w.Write(testBody)
  1071. },
  1072. statusCode: 200,
  1073. }
  1074. },
  1075. "ok/no-account": func(t *testing.T) test {
  1076. ctx := acme.NewProvisionerContext(context.Background(), prov)
  1077. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  1078. return test{
  1079. ctx: ctx,
  1080. db: &acme.MockDB{
  1081. MockGetAccountByKeyID: func(ctx context.Context, kid string) (*acme.Account, error) {
  1082. assert.Equals(t, kid, pub.KeyID)
  1083. return nil, acme.ErrNotFound
  1084. },
  1085. },
  1086. next: func(w http.ResponseWriter, r *http.Request) {
  1087. _acc, err := accountFromContext(r.Context())
  1088. assert.NotNil(t, err)
  1089. assert.Nil(t, _acc)
  1090. _jwk, err := jwkFromContext(r.Context())
  1091. assert.FatalError(t, err)
  1092. assert.Equals(t, _jwk.KeyID, pub.KeyID)
  1093. w.Write(testBody)
  1094. },
  1095. statusCode: 200,
  1096. }
  1097. },
  1098. }
  1099. for name, run := range tests {
  1100. tc := run(t)
  1101. t.Run(name, func(t *testing.T) {
  1102. ctx := newBaseContext(tc.ctx, tc.db)
  1103. req := httptest.NewRequest("GET", u, http.NoBody)
  1104. req = req.WithContext(ctx)
  1105. w := httptest.NewRecorder()
  1106. extractJWK(tc.next)(w, req)
  1107. res := w.Result()
  1108. assert.Equals(t, res.StatusCode, tc.statusCode)
  1109. body, err := io.ReadAll(res.Body)
  1110. res.Body.Close()
  1111. assert.FatalError(t, err)
  1112. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  1113. var ae acme.Error
  1114. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  1115. assert.Equals(t, ae.Type, tc.err.Type)
  1116. assert.Equals(t, ae.Detail, tc.err.Detail)
  1117. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  1118. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  1119. } else {
  1120. assert.Equals(t, bytes.TrimSpace(body), testBody)
  1121. }
  1122. })
  1123. }
  1124. }
  1125. func TestHandler_validateJWS(t *testing.T) {
  1126. u := "https://ca.smallstep.com/acme/account/1234"
  1127. type test struct {
  1128. db acme.DB
  1129. ctx context.Context
  1130. next func(http.ResponseWriter, *http.Request)
  1131. err *acme.Error
  1132. statusCode int
  1133. }
  1134. var tests = map[string]func(t *testing.T) test{
  1135. "fail/no-jws": func(t *testing.T) test {
  1136. return test{
  1137. db: &acme.MockDB{},
  1138. ctx: context.Background(),
  1139. statusCode: 500,
  1140. err: acme.NewErrorISE("jws expected in request context"),
  1141. }
  1142. },
  1143. "fail/nil-jws": func(t *testing.T) test {
  1144. return test{
  1145. db: &acme.MockDB{},
  1146. ctx: context.WithValue(context.Background(), jwsContextKey, nil),
  1147. statusCode: 500,
  1148. err: acme.NewErrorISE("jws expected in request context"),
  1149. }
  1150. },
  1151. "fail/no-signature": func(t *testing.T) test {
  1152. return test{
  1153. db: &acme.MockDB{},
  1154. ctx: context.WithValue(context.Background(), jwsContextKey, &jose.JSONWebSignature{}),
  1155. statusCode: 400,
  1156. err: acme.NewError(acme.ErrorMalformedType, "request body does not contain a signature"),
  1157. }
  1158. },
  1159. "fail/more-than-one-signature": func(t *testing.T) test {
  1160. jws := &jose.JSONWebSignature{
  1161. Signatures: []jose.Signature{
  1162. {},
  1163. {},
  1164. },
  1165. }
  1166. return test{
  1167. db: &acme.MockDB{},
  1168. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1169. statusCode: 400,
  1170. err: acme.NewError(acme.ErrorMalformedType, "request body contains more than one signature"),
  1171. }
  1172. },
  1173. "fail/unprotected-header-not-empty": func(t *testing.T) test {
  1174. jws := &jose.JSONWebSignature{
  1175. Signatures: []jose.Signature{
  1176. {Unprotected: jose.Header{Nonce: "abc"}},
  1177. },
  1178. }
  1179. return test{
  1180. db: &acme.MockDB{},
  1181. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1182. statusCode: 400,
  1183. err: acme.NewError(acme.ErrorMalformedType, "unprotected header must not be used"),
  1184. }
  1185. },
  1186. "fail/unsuitable-algorithm-none": func(t *testing.T) test {
  1187. jws := &jose.JSONWebSignature{
  1188. Signatures: []jose.Signature{
  1189. {Protected: jose.Header{Algorithm: "none"}},
  1190. },
  1191. }
  1192. return test{
  1193. db: &acme.MockDB{},
  1194. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1195. statusCode: 400,
  1196. err: acme.NewError(acme.ErrorBadSignatureAlgorithmType, "unsuitable algorithm: none"),
  1197. }
  1198. },
  1199. "fail/unsuitable-algorithm-mac": func(t *testing.T) test {
  1200. jws := &jose.JSONWebSignature{
  1201. Signatures: []jose.Signature{
  1202. {Protected: jose.Header{Algorithm: jose.HS256}},
  1203. },
  1204. }
  1205. return test{
  1206. db: &acme.MockDB{},
  1207. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1208. statusCode: 400,
  1209. err: acme.NewError(acme.ErrorBadSignatureAlgorithmType, "unsuitable algorithm: %s", jose.HS256),
  1210. }
  1211. },
  1212. "fail/rsa-key-&-alg-mismatch": func(t *testing.T) test {
  1213. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  1214. assert.FatalError(t, err)
  1215. pub := jwk.Public()
  1216. jws := &jose.JSONWebSignature{
  1217. Signatures: []jose.Signature{
  1218. {
  1219. Protected: jose.Header{
  1220. Algorithm: jose.RS256,
  1221. JSONWebKey: &pub,
  1222. ExtraHeaders: map[jose.HeaderKey]interface{}{
  1223. "url": u,
  1224. },
  1225. },
  1226. },
  1227. },
  1228. }
  1229. return test{
  1230. db: &acme.MockDB{
  1231. MockDeleteNonce: func(ctx context.Context, n acme.Nonce) error {
  1232. return nil
  1233. },
  1234. },
  1235. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1236. statusCode: 400,
  1237. err: acme.NewError(acme.ErrorMalformedType, "jws key type and algorithm do not match"),
  1238. }
  1239. },
  1240. "fail/rsa-key-too-small": func(t *testing.T) test {
  1241. revert := keyutil.Insecure()
  1242. defer revert()
  1243. jwk, err := jose.GenerateJWK("RSA", "", "", "sig", "", 1024)
  1244. assert.FatalError(t, err)
  1245. pub := jwk.Public()
  1246. jws := &jose.JSONWebSignature{
  1247. Signatures: []jose.Signature{
  1248. {
  1249. Protected: jose.Header{
  1250. Algorithm: jose.RS256,
  1251. JSONWebKey: &pub,
  1252. ExtraHeaders: map[jose.HeaderKey]interface{}{
  1253. "url": u,
  1254. },
  1255. },
  1256. },
  1257. },
  1258. }
  1259. return test{
  1260. db: &acme.MockDB{
  1261. MockDeleteNonce: func(ctx context.Context, n acme.Nonce) error {
  1262. return nil
  1263. },
  1264. },
  1265. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1266. statusCode: 400,
  1267. err: acme.NewError(acme.ErrorMalformedType, "rsa keys must be at least 2048 bits (256 bytes) in size"),
  1268. }
  1269. },
  1270. "fail/UseNonce-error": func(t *testing.T) test {
  1271. jws := &jose.JSONWebSignature{
  1272. Signatures: []jose.Signature{
  1273. {Protected: jose.Header{Algorithm: jose.ES256}},
  1274. },
  1275. }
  1276. return test{
  1277. db: &acme.MockDB{
  1278. MockDeleteNonce: func(ctx context.Context, n acme.Nonce) error {
  1279. return acme.NewErrorISE("force")
  1280. },
  1281. },
  1282. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1283. statusCode: 500,
  1284. err: acme.NewErrorISE("force"),
  1285. }
  1286. },
  1287. "fail/no-url-header": func(t *testing.T) test {
  1288. jws := &jose.JSONWebSignature{
  1289. Signatures: []jose.Signature{
  1290. {Protected: jose.Header{Algorithm: jose.ES256}},
  1291. },
  1292. }
  1293. return test{
  1294. db: &acme.MockDB{
  1295. MockDeleteNonce: func(ctx context.Context, n acme.Nonce) error {
  1296. return nil
  1297. },
  1298. },
  1299. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1300. statusCode: 400,
  1301. err: acme.NewError(acme.ErrorMalformedType, "jws missing url protected header"),
  1302. }
  1303. },
  1304. "fail/url-mismatch": func(t *testing.T) test {
  1305. jws := &jose.JSONWebSignature{
  1306. Signatures: []jose.Signature{
  1307. {
  1308. Protected: jose.Header{
  1309. Algorithm: jose.ES256,
  1310. ExtraHeaders: map[jose.HeaderKey]interface{}{
  1311. "url": "foo",
  1312. },
  1313. },
  1314. },
  1315. },
  1316. }
  1317. return test{
  1318. db: &acme.MockDB{
  1319. MockDeleteNonce: func(ctx context.Context, n acme.Nonce) error {
  1320. return nil
  1321. },
  1322. },
  1323. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1324. statusCode: 400,
  1325. err: acme.NewError(acme.ErrorMalformedType, "url header in JWS (foo) does not match request url (%s)", u),
  1326. }
  1327. },
  1328. "fail/both-jwk-kid": func(t *testing.T) test {
  1329. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  1330. assert.FatalError(t, err)
  1331. pub := jwk.Public()
  1332. jws := &jose.JSONWebSignature{
  1333. Signatures: []jose.Signature{
  1334. {
  1335. Protected: jose.Header{
  1336. Algorithm: jose.ES256,
  1337. KeyID: "bar",
  1338. JSONWebKey: &pub,
  1339. ExtraHeaders: map[jose.HeaderKey]interface{}{
  1340. "url": u,
  1341. },
  1342. },
  1343. },
  1344. },
  1345. }
  1346. return test{
  1347. db: &acme.MockDB{
  1348. MockDeleteNonce: func(ctx context.Context, n acme.Nonce) error {
  1349. return nil
  1350. },
  1351. },
  1352. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1353. statusCode: 400,
  1354. err: acme.NewError(acme.ErrorMalformedType, "jwk and kid are mutually exclusive"),
  1355. }
  1356. },
  1357. "fail/no-jwk-kid": func(t *testing.T) test {
  1358. jws := &jose.JSONWebSignature{
  1359. Signatures: []jose.Signature{
  1360. {
  1361. Protected: jose.Header{
  1362. Algorithm: jose.ES256,
  1363. ExtraHeaders: map[jose.HeaderKey]interface{}{
  1364. "url": u,
  1365. },
  1366. },
  1367. },
  1368. },
  1369. }
  1370. return test{
  1371. db: &acme.MockDB{
  1372. MockDeleteNonce: func(ctx context.Context, n acme.Nonce) error {
  1373. return nil
  1374. },
  1375. },
  1376. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1377. statusCode: 400,
  1378. err: acme.NewError(acme.ErrorMalformedType, "either jwk or kid must be defined in jws protected header"),
  1379. }
  1380. },
  1381. "ok/kid": func(t *testing.T) test {
  1382. jws := &jose.JSONWebSignature{
  1383. Signatures: []jose.Signature{
  1384. {
  1385. Protected: jose.Header{
  1386. Algorithm: jose.ES256,
  1387. KeyID: "bar",
  1388. ExtraHeaders: map[jose.HeaderKey]interface{}{
  1389. "url": u,
  1390. },
  1391. },
  1392. },
  1393. },
  1394. }
  1395. return test{
  1396. db: &acme.MockDB{
  1397. MockDeleteNonce: func(ctx context.Context, n acme.Nonce) error {
  1398. return nil
  1399. },
  1400. },
  1401. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1402. next: func(w http.ResponseWriter, r *http.Request) {
  1403. w.Write(testBody)
  1404. },
  1405. statusCode: 200,
  1406. }
  1407. },
  1408. "ok/jwk/ecdsa": func(t *testing.T) test {
  1409. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  1410. assert.FatalError(t, err)
  1411. pub := jwk.Public()
  1412. jws := &jose.JSONWebSignature{
  1413. Signatures: []jose.Signature{
  1414. {
  1415. Protected: jose.Header{
  1416. Algorithm: jose.ES256,
  1417. JSONWebKey: &pub,
  1418. ExtraHeaders: map[jose.HeaderKey]interface{}{
  1419. "url": u,
  1420. },
  1421. },
  1422. },
  1423. },
  1424. }
  1425. return test{
  1426. db: &acme.MockDB{
  1427. MockDeleteNonce: func(ctx context.Context, n acme.Nonce) error {
  1428. return nil
  1429. },
  1430. },
  1431. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1432. next: func(w http.ResponseWriter, r *http.Request) {
  1433. w.Write(testBody)
  1434. },
  1435. statusCode: 200,
  1436. }
  1437. },
  1438. "ok/jwk/rsa": func(t *testing.T) test {
  1439. jwk, err := jose.GenerateJWK("RSA", "", "", "sig", "", 2048)
  1440. assert.FatalError(t, err)
  1441. pub := jwk.Public()
  1442. jws := &jose.JSONWebSignature{
  1443. Signatures: []jose.Signature{
  1444. {
  1445. Protected: jose.Header{
  1446. Algorithm: jose.RS256,
  1447. JSONWebKey: &pub,
  1448. ExtraHeaders: map[jose.HeaderKey]interface{}{
  1449. "url": u,
  1450. },
  1451. },
  1452. },
  1453. },
  1454. }
  1455. return test{
  1456. db: &acme.MockDB{
  1457. MockDeleteNonce: func(ctx context.Context, n acme.Nonce) error {
  1458. return nil
  1459. },
  1460. },
  1461. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1462. next: func(w http.ResponseWriter, r *http.Request) {
  1463. w.Write(testBody)
  1464. },
  1465. statusCode: 200,
  1466. }
  1467. },
  1468. }
  1469. for name, run := range tests {
  1470. tc := run(t)
  1471. t.Run(name, func(t *testing.T) {
  1472. ctx := newBaseContext(tc.ctx, tc.db)
  1473. req := httptest.NewRequest("GET", u, http.NoBody)
  1474. req = req.WithContext(ctx)
  1475. w := httptest.NewRecorder()
  1476. validateJWS(tc.next)(w, req)
  1477. res := w.Result()
  1478. assert.Equals(t, res.StatusCode, tc.statusCode)
  1479. body, err := io.ReadAll(res.Body)
  1480. res.Body.Close()
  1481. assert.FatalError(t, err)
  1482. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  1483. var ae acme.Error
  1484. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  1485. assert.Equals(t, ae.Type, tc.err.Type)
  1486. assert.Equals(t, ae.Detail, tc.err.Detail)
  1487. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  1488. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  1489. } else {
  1490. assert.Equals(t, bytes.TrimSpace(body), testBody)
  1491. }
  1492. })
  1493. }
  1494. }
  1495. func Test_canExtractJWKFrom(t *testing.T) {
  1496. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  1497. assert.FatalError(t, err)
  1498. type args struct {
  1499. jws *jose.JSONWebSignature
  1500. }
  1501. tests := []struct {
  1502. name string
  1503. args args
  1504. want bool
  1505. }{
  1506. {
  1507. name: "no-jws",
  1508. args: args{
  1509. jws: nil,
  1510. },
  1511. want: false,
  1512. },
  1513. {
  1514. name: "no-signatures",
  1515. args: args{
  1516. jws: &jose.JSONWebSignature{
  1517. Signatures: []jose.Signature{},
  1518. },
  1519. },
  1520. want: false,
  1521. },
  1522. {
  1523. name: "no-jwk",
  1524. args: args{
  1525. jws: &jose.JSONWebSignature{
  1526. Signatures: []jose.Signature{
  1527. {
  1528. Protected: jose.Header{},
  1529. },
  1530. },
  1531. },
  1532. },
  1533. want: false,
  1534. },
  1535. {
  1536. name: "ok",
  1537. args: args{
  1538. jws: &jose.JSONWebSignature{
  1539. Signatures: []jose.Signature{
  1540. {
  1541. Protected: jose.Header{
  1542. JSONWebKey: jwk,
  1543. },
  1544. },
  1545. },
  1546. },
  1547. },
  1548. want: true,
  1549. },
  1550. }
  1551. for _, tt := range tests {
  1552. t.Run(tt.name, func(t *testing.T) {
  1553. if got := canExtractJWKFrom(tt.args.jws); got != tt.want {
  1554. t.Errorf("canExtractJWKFrom() = %v, want %v", got, tt.want)
  1555. }
  1556. })
  1557. }
  1558. }
  1559. func TestHandler_extractOrLookupJWK(t *testing.T) {
  1560. u := "https://ca.smallstep.com/acme/account"
  1561. type test struct {
  1562. db acme.DB
  1563. linker acme.Linker
  1564. statusCode int
  1565. ctx context.Context
  1566. err *acme.Error
  1567. next func(w http.ResponseWriter, r *http.Request)
  1568. }
  1569. var tests = map[string]func(t *testing.T) test{
  1570. "ok/extract": func(t *testing.T) test {
  1571. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  1572. assert.FatalError(t, err)
  1573. kid, err := jwk.Thumbprint(crypto.SHA256)
  1574. assert.FatalError(t, err)
  1575. pub := jwk.Public()
  1576. pub.KeyID = base64.RawURLEncoding.EncodeToString(kid)
  1577. so := new(jose.SignerOptions)
  1578. so.WithHeader("jwk", pub) // JWK for certificate private key flow
  1579. signer, err := jose.NewSigner(jose.SigningKey{
  1580. Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
  1581. Key: jwk.Key,
  1582. }, so)
  1583. assert.FatalError(t, err)
  1584. signed, err := signer.Sign([]byte("foo"))
  1585. assert.FatalError(t, err)
  1586. raw, err := signed.CompactSerialize()
  1587. assert.FatalError(t, err)
  1588. parsedJWS, err := jose.ParseJWS(raw)
  1589. assert.FatalError(t, err)
  1590. return test{
  1591. linker: acme.NewLinker("dns", "acme"),
  1592. db: &acme.MockDB{
  1593. MockGetAccountByKeyID: func(ctx context.Context, kid string) (*acme.Account, error) {
  1594. assert.Equals(t, kid, pub.KeyID)
  1595. return nil, acme.ErrNotFound
  1596. },
  1597. },
  1598. ctx: context.WithValue(context.Background(), jwsContextKey, parsedJWS),
  1599. statusCode: 200,
  1600. next: func(w http.ResponseWriter, r *http.Request) {
  1601. w.Write(testBody)
  1602. },
  1603. }
  1604. },
  1605. "ok/lookup": func(t *testing.T) test {
  1606. prov := newProv()
  1607. provName := url.PathEscape(prov.GetName())
  1608. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  1609. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  1610. assert.FatalError(t, err)
  1611. accID := "accID"
  1612. prefix := fmt.Sprintf("%s/acme/%s/account/", baseURL, provName)
  1613. so := new(jose.SignerOptions)
  1614. so.WithHeader("kid", fmt.Sprintf("%s%s", prefix, accID)) // KID for account private key flow
  1615. signer, err := jose.NewSigner(jose.SigningKey{
  1616. Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
  1617. Key: jwk.Key,
  1618. }, so)
  1619. assert.FatalError(t, err)
  1620. jws, err := signer.Sign([]byte("baz"))
  1621. assert.FatalError(t, err)
  1622. raw, err := jws.CompactSerialize()
  1623. assert.FatalError(t, err)
  1624. parsedJWS, err := jose.ParseJWS(raw)
  1625. assert.FatalError(t, err)
  1626. acc := &acme.Account{ID: "accID", Key: jwk, Status: "valid"}
  1627. ctx := acme.NewProvisionerContext(context.Background(), prov)
  1628. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  1629. return test{
  1630. linker: acme.NewLinker("test.ca.smallstep.com", "acme"),
  1631. db: &acme.MockDB{
  1632. MockGetAccount: func(ctx context.Context, accID string) (*acme.Account, error) {
  1633. assert.Equals(t, accID, acc.ID)
  1634. return acc, nil
  1635. },
  1636. },
  1637. ctx: ctx,
  1638. statusCode: 200,
  1639. next: func(w http.ResponseWriter, r *http.Request) {
  1640. w.Write(testBody)
  1641. },
  1642. }
  1643. },
  1644. }
  1645. for name, prep := range tests {
  1646. tc := prep(t)
  1647. t.Run(name, func(t *testing.T) {
  1648. ctx := newBaseContext(tc.ctx, tc.db, tc.linker)
  1649. req := httptest.NewRequest("GET", u, http.NoBody)
  1650. req = req.WithContext(ctx)
  1651. w := httptest.NewRecorder()
  1652. extractOrLookupJWK(tc.next)(w, req)
  1653. res := w.Result()
  1654. assert.Equals(t, res.StatusCode, tc.statusCode)
  1655. body, err := io.ReadAll(res.Body)
  1656. res.Body.Close()
  1657. assert.FatalError(t, err)
  1658. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  1659. var ae acme.Error
  1660. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  1661. assert.Equals(t, ae.Type, tc.err.Type)
  1662. assert.Equals(t, ae.Detail, tc.err.Detail)
  1663. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  1664. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  1665. } else {
  1666. assert.Equals(t, bytes.TrimSpace(body), testBody)
  1667. }
  1668. })
  1669. }
  1670. }
  1671. func TestHandler_checkPrerequisites(t *testing.T) {
  1672. prov := newProv()
  1673. provName := url.PathEscape(prov.GetName())
  1674. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  1675. u := fmt.Sprintf("%s/acme/%s/account/1234",
  1676. baseURL, provName)
  1677. type test struct {
  1678. linker acme.Linker
  1679. ctx context.Context
  1680. prerequisitesChecker func(context.Context) (bool, error)
  1681. next func(http.ResponseWriter, *http.Request)
  1682. err *acme.Error
  1683. statusCode int
  1684. }
  1685. var tests = map[string]func(t *testing.T) test{
  1686. "fail/error": func(t *testing.T) test {
  1687. ctx := acme.NewProvisionerContext(context.Background(), prov)
  1688. return test{
  1689. linker: acme.NewLinker("dns", "acme"),
  1690. ctx: ctx,
  1691. prerequisitesChecker: func(context.Context) (bool, error) { return false, errors.New("force") },
  1692. next: func(w http.ResponseWriter, r *http.Request) {
  1693. w.Write(testBody)
  1694. },
  1695. err: acme.WrapErrorISE(errors.New("force"), "error checking acme provisioner prerequisites"),
  1696. statusCode: 500,
  1697. }
  1698. },
  1699. "fail/prerequisites-nok": func(t *testing.T) test {
  1700. ctx := acme.NewProvisionerContext(context.Background(), prov)
  1701. return test{
  1702. linker: acme.NewLinker("dns", "acme"),
  1703. ctx: ctx,
  1704. prerequisitesChecker: func(context.Context) (bool, error) { return false, nil },
  1705. next: func(w http.ResponseWriter, r *http.Request) {
  1706. w.Write(testBody)
  1707. },
  1708. err: acme.NewError(acme.ErrorNotImplementedType, "acme provisioner configuration lacks prerequisites"),
  1709. statusCode: 501,
  1710. }
  1711. },
  1712. "ok": func(t *testing.T) test {
  1713. ctx := acme.NewProvisionerContext(context.Background(), prov)
  1714. return test{
  1715. linker: acme.NewLinker("dns", "acme"),
  1716. ctx: ctx,
  1717. prerequisitesChecker: func(context.Context) (bool, error) { return true, nil },
  1718. next: func(w http.ResponseWriter, r *http.Request) {
  1719. w.Write(testBody)
  1720. },
  1721. statusCode: 200,
  1722. }
  1723. },
  1724. }
  1725. for name, run := range tests {
  1726. tc := run(t)
  1727. t.Run(name, func(t *testing.T) {
  1728. ctx := acme.NewPrerequisitesCheckerContext(tc.ctx, tc.prerequisitesChecker)
  1729. req := httptest.NewRequest("GET", u, http.NoBody)
  1730. req = req.WithContext(ctx)
  1731. w := httptest.NewRecorder()
  1732. checkPrerequisites(tc.next)(w, req)
  1733. res := w.Result()
  1734. assert.Equals(t, res.StatusCode, tc.statusCode)
  1735. body, err := io.ReadAll(res.Body)
  1736. res.Body.Close()
  1737. assert.FatalError(t, err)
  1738. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  1739. var ae acme.Error
  1740. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  1741. assert.Equals(t, ae.Type, tc.err.Type)
  1742. assert.Equals(t, ae.Detail, tc.err.Detail)
  1743. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  1744. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  1745. } else {
  1746. assert.Equals(t, bytes.TrimSpace(body), testBody)
  1747. }
  1748. })
  1749. }
  1750. }
  1751. func Test_retryVerificationWithPatchedSignatures(t *testing.T) {
  1752. patchedRKey := []byte(`{
  1753. "kid": "uioinbiTlJICL0MYsb6ar1totfRA2tiPqWgntF8xUdo",
  1754. "crv": "P-256",
  1755. "alg": "ES256",
  1756. "kty": "EC",
  1757. "x": "wlz-Kv9X0h32fzLq-cogls9HxoZQqV-GuWxdb2MCeUY",
  1758. "y": "xzP6zRrg_jynYljZTxfJuql_QWtdQR6lpJ52q_6Vavg"
  1759. }`)
  1760. patchedRJWK := &jose.JSONWebKey{}
  1761. err := json.Unmarshal(patchedRKey, patchedRJWK)
  1762. require.NoError(t, err)
  1763. patchedRBody := `{"payload":"dGVzdC0xMTA1","protected":"eyJhbGciOiJFUzI1NiJ9","signature":"rQPYKYflfKnlgBKqDeWsJH2TJ6iHAnou7sFzXlmYD4ArXqLfYuqotWERKrna2wfzh0pu7USWO2gzlOqRK9qq"}`
  1764. patchedR, err := jose.ParseJWS(patchedRBody)
  1765. require.NoError(t, err)
  1766. patchedSKey := []byte(`{
  1767. "kid": "PblXsnK59uTiF5k3mmAN2B6HDPPxqBL_4UGhEG8ZO6g",
  1768. "crv": "P-256",
  1769. "alg": "ES256",
  1770. "kty": "EC",
  1771. "x": "T5aM_TOSattXNeUkH1VHZXh8URzdjZTI2zLvVgI0cy0",
  1772. "y": "Lf8h8qZnURXIxm6OnQ69kxGC91YtTZRD2GAroEf1UA8"
  1773. }`)
  1774. patchedSJWK := &jose.JSONWebKey{}
  1775. err = json.Unmarshal(patchedSKey, patchedSJWK)
  1776. require.NoError(t, err)
  1777. patchedSBody := `{"payload":"dGVzdC02Ng","protected":"eyJhbGciOiJFUzI1NiJ9","signature":"krtSKSgVB04oqx6i9QLeal_wZSnjV1_PSIM3AubT0WRIxnhl_yYbVpa3i53p3dUW56TtP6_SUZboH6SvLHMz"}`
  1778. patchedS, err := jose.ParseJWS(patchedSBody)
  1779. require.NoError(t, err)
  1780. patchedRSKey := []byte(`{
  1781. "kid": "U8BmBVbZsNUawvhOomJQPa6uYj1rdxCPQWF_nOLVsc4",
  1782. "crv": "P-256",
  1783. "alg": "ES256",
  1784. "kty": "EC",
  1785. "x": "Ym0l3GMS6aHBLo-xe73Kub4kafnOBu_QAfOsx5y-bV0",
  1786. "y": "wKijX9Cu67HbK94StPcI18WulgRfIMbP2ZU7gQuf3-M"
  1787. }`)
  1788. patchedRSJWK := &jose.JSONWebKey{}
  1789. err = json.Unmarshal(patchedRSKey, patchedRSJWK)
  1790. require.NoError(t, err)
  1791. patchedRSBody := `{"payload":"dGVzdC05MDY3","protected":"eyJhbGciOiJFUzI1NiJ9","signature":"2r_My19oRg7mWf9I5JTkNYp8otfEMz-yXRA8ltZTAKZxyJLurpVEgicmNItu7lfcCrGrTgI3Obye_gSaIyc"}`
  1792. patchedRS, err := jose.ParseJWS(patchedRSBody)
  1793. require.NoError(t, err)
  1794. patchedRWithWrongJWK, err := jose.ParseJWS(patchedRBody)
  1795. require.NoError(t, err)
  1796. tests := []struct {
  1797. name string
  1798. jws *jose.JSONWebSignature
  1799. jwk *jose.JSONWebKey
  1800. expectedData []byte
  1801. expectedSignature string
  1802. expectedError error
  1803. }{
  1804. {"ok/patched-r", patchedR, patchedRJWK, []byte(`test-1105`), `AK0D2CmH5Xyp5YASqg3lrCR9kyeohwJ6Lu7Bc15ZmA-AK16i32LqqLVhESq52tsH84dKbu1EljtoM5TqkSvaqg`, nil},
  1805. {"ok/patched-s", patchedS, patchedSJWK, []byte(`test-66`), `krtSKSgVB04oqx6i9QLeal_wZSnjV1_PSIM3AubT0WQASMZ4Zf8mG1aWt4ud6d3VFuek7T-v0lGW6B-kryxzMw`, nil},
  1806. {"ok/patched-rs", patchedRS, patchedRSJWK, []byte(`test-9067`), `ANq_zMtfaEYO5ln_SOSU5DWKfKLXxDM_sl0QPJbWUwAApnHIku6ulUSCJyY0i27uV9wKsatOAjc5vJ7-BJojJw`, nil},
  1807. {"fail/patched-r-wrong-jwk", patchedRWithWrongJWK, patchedRSJWK, nil, `rQPYKYflfKnlgBKqDeWsJH2TJ6iHAnou7sFzXlmYD4ArXqLfYuqotWERKrna2wfzh0pu7USWO2gzlOqRK9qq`, errors.New("go-jose/go-jose: error in cryptographic primitive")},
  1808. }
  1809. for _, tt := range tests {
  1810. t.Run(tt.name, func(t *testing.T) {
  1811. expectedSignature, decodeErr := base64.RawURLEncoding.DecodeString(tt.expectedSignature)
  1812. require.NoError(t, decodeErr)
  1813. data, err := retryVerificationWithPatchedSignatures(tt.jws, tt.jwk)
  1814. if tt.expectedError != nil {
  1815. tassert.EqualError(t, err, tt.expectedError.Error())
  1816. tassert.Equal(t, expectedSignature, tt.jws.Signatures[0].Signature)
  1817. tassert.Empty(t, data)
  1818. return
  1819. }
  1820. tassert.NoError(t, err)
  1821. tassert.Len(t, tt.jws.Signatures[0].Signature, 64)
  1822. tassert.Equal(t, expectedSignature, tt.jws.Signatures[0].Signature)
  1823. tassert.Equal(t, tt.expectedData, data)
  1824. })
  1825. }
  1826. }