middleware_test.go 50 KB

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