middleware_test.go 51 KB

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