middleware_test.go 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463
  1. package api
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto"
  6. "encoding/base64"
  7. "encoding/json"
  8. "fmt"
  9. "io"
  10. "io/ioutil"
  11. "net/http"
  12. "net/http/httptest"
  13. "net/url"
  14. "strings"
  15. "testing"
  16. "github.com/pkg/errors"
  17. "github.com/smallstep/assert"
  18. "github.com/smallstep/certificates/acme"
  19. "github.com/smallstep/nosql/database"
  20. "go.step.sm/crypto/jose"
  21. )
  22. var testBody = []byte("foo")
  23. func testNext(w http.ResponseWriter, r *http.Request) {
  24. w.Write(testBody)
  25. }
  26. func Test_baseURLFromRequest(t *testing.T) {
  27. tests := []struct {
  28. name string
  29. targetURL string
  30. expectedResult *url.URL
  31. requestPreparer func(*http.Request)
  32. }{
  33. {
  34. "HTTPS host pass-through failed.",
  35. "https://my.dummy.host",
  36. &url.URL{Scheme: "https", Host: "my.dummy.host"},
  37. nil,
  38. },
  39. {
  40. "Port pass-through failed",
  41. "https://host.with.port:8080",
  42. &url.URL{Scheme: "https", Host: "host.with.port:8080"},
  43. nil,
  44. },
  45. {
  46. "Explicit host from Request.Host was not used.",
  47. "https://some.target.host:8080",
  48. &url.URL{Scheme: "https", Host: "proxied.host"},
  49. func(r *http.Request) {
  50. r.Host = "proxied.host"
  51. },
  52. },
  53. {
  54. "Missing Request.Host value did not result in empty string result.",
  55. "https://some.host",
  56. nil,
  57. func(r *http.Request) {
  58. r.Host = ""
  59. },
  60. },
  61. }
  62. for _, tc := range tests {
  63. t.Run(tc.name, func(t *testing.T) {
  64. request := httptest.NewRequest("GET", tc.targetURL, nil)
  65. if tc.requestPreparer != nil {
  66. tc.requestPreparer(request)
  67. }
  68. result := baseURLFromRequest(request)
  69. if result == nil || tc.expectedResult == nil {
  70. assert.Equals(t, result, tc.expectedResult)
  71. } else if result.String() != tc.expectedResult.String() {
  72. t.Errorf("Expected %q, but got %q", tc.expectedResult.String(), result.String())
  73. }
  74. })
  75. }
  76. }
  77. func TestHandlerBaseURLFromRequest(t *testing.T) {
  78. h := &Handler{}
  79. req := httptest.NewRequest("GET", "/foo", nil)
  80. req.Host = "test.ca.smallstep.com:8080"
  81. w := httptest.NewRecorder()
  82. next := func(w http.ResponseWriter, r *http.Request) {
  83. bu := baseURLFromContext(r.Context())
  84. if assert.NotNil(t, bu) {
  85. assert.Equals(t, bu.Host, "test.ca.smallstep.com:8080")
  86. assert.Equals(t, bu.Scheme, "https")
  87. }
  88. }
  89. h.baseURLFromRequest(next)(w, req)
  90. req = httptest.NewRequest("GET", "/foo", nil)
  91. req.Host = ""
  92. next = func(w http.ResponseWriter, r *http.Request) {
  93. assert.Equals(t, baseURLFromContext(r.Context()), nil)
  94. }
  95. h.baseURLFromRequest(next)(w, req)
  96. }
  97. func TestHandler_AddNonce(t *testing.T) {
  98. url := "https://ca.smallstep.com/acme/new-nonce"
  99. type test struct {
  100. db acme.DB
  101. err *acme.Error
  102. statusCode int
  103. }
  104. var tests = map[string]func(t *testing.T) test{
  105. "fail/AddNonce-error": func(t *testing.T) test {
  106. return test{
  107. db: &acme.MockDB{
  108. MockCreateNonce: func(ctx context.Context) (acme.Nonce, error) {
  109. return acme.Nonce(""), acme.NewErrorISE("force")
  110. },
  111. },
  112. statusCode: 500,
  113. err: acme.NewErrorISE("force"),
  114. }
  115. },
  116. "ok": func(t *testing.T) test {
  117. return test{
  118. db: &acme.MockDB{
  119. MockCreateNonce: func(ctx context.Context) (acme.Nonce, error) {
  120. return "bar", nil
  121. },
  122. },
  123. statusCode: 200,
  124. }
  125. },
  126. }
  127. for name, run := range tests {
  128. tc := run(t)
  129. t.Run(name, func(t *testing.T) {
  130. h := &Handler{db: tc.db}
  131. req := httptest.NewRequest("GET", url, nil)
  132. w := httptest.NewRecorder()
  133. h.addNonce(testNext)(w, req)
  134. res := w.Result()
  135. assert.Equals(t, res.StatusCode, tc.statusCode)
  136. body, err := ioutil.ReadAll(res.Body)
  137. res.Body.Close()
  138. assert.FatalError(t, err)
  139. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  140. var ae acme.Error
  141. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  142. assert.Equals(t, ae.Type, tc.err.Type)
  143. assert.Equals(t, ae.Detail, tc.err.Detail)
  144. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  145. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  146. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  147. } else {
  148. assert.Equals(t, res.Header["Replay-Nonce"], []string{"bar"})
  149. assert.Equals(t, res.Header["Cache-Control"], []string{"no-store"})
  150. assert.Equals(t, bytes.TrimSpace(body), testBody)
  151. }
  152. })
  153. }
  154. }
  155. func TestHandler_addDirLink(t *testing.T) {
  156. prov := newProv()
  157. provName := url.PathEscape(prov.GetName())
  158. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  159. type test struct {
  160. link string
  161. linker Linker
  162. statusCode int
  163. ctx context.Context
  164. err *acme.Error
  165. }
  166. var tests = map[string]func(t *testing.T) test{
  167. "ok": func(t *testing.T) test {
  168. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  169. ctx = context.WithValue(ctx, baseURLContextKey, baseURL)
  170. return test{
  171. linker: NewLinker("dns", "acme"),
  172. ctx: ctx,
  173. link: fmt.Sprintf("%s/acme/%s/directory", baseURL.String(), provName),
  174. statusCode: 200,
  175. }
  176. },
  177. }
  178. for name, run := range tests {
  179. tc := run(t)
  180. t.Run(name, func(t *testing.T) {
  181. h := &Handler{linker: tc.linker}
  182. req := httptest.NewRequest("GET", "/foo", nil)
  183. req = req.WithContext(tc.ctx)
  184. w := httptest.NewRecorder()
  185. h.addDirLink(testNext)(w, req)
  186. res := w.Result()
  187. assert.Equals(t, res.StatusCode, tc.statusCode)
  188. body, err := ioutil.ReadAll(res.Body)
  189. res.Body.Close()
  190. assert.FatalError(t, err)
  191. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  192. var ae acme.Error
  193. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  194. assert.Equals(t, ae.Type, tc.err.Type)
  195. assert.Equals(t, ae.Detail, tc.err.Detail)
  196. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  197. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  198. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  199. } else {
  200. assert.Equals(t, res.Header["Link"], []string{fmt.Sprintf("<%s>;rel=\"index\"", tc.link)})
  201. assert.Equals(t, bytes.TrimSpace(body), testBody)
  202. }
  203. })
  204. }
  205. }
  206. func TestHandler_VerifyContentType(t *testing.T) {
  207. prov := newProv()
  208. provName := prov.GetName()
  209. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  210. url := fmt.Sprintf("%s/acme/%s/certificate/abc123", baseURL.String(), provName)
  211. type test struct {
  212. h Handler
  213. ctx context.Context
  214. contentType string
  215. err *acme.Error
  216. statusCode int
  217. url string
  218. }
  219. var tests = map[string]func(t *testing.T) test{
  220. "fail/general-bad-content-type": func(t *testing.T) test {
  221. return test{
  222. h: Handler{
  223. linker: NewLinker("dns", "acme"),
  224. },
  225. url: fmt.Sprintf("%s/acme/%s/new-account", baseURL.String(), provName),
  226. ctx: context.WithValue(context.Background(), provisionerContextKey, prov),
  227. contentType: "foo",
  228. statusCode: 400,
  229. err: acme.NewError(acme.ErrorMalformedType, "expected content-type to be in [application/jose+json], but got foo"),
  230. }
  231. },
  232. "fail/certificate-bad-content-type": func(t *testing.T) test {
  233. return test{
  234. h: Handler{
  235. linker: NewLinker("dns", "acme"),
  236. },
  237. ctx: context.WithValue(context.Background(), provisionerContextKey, prov),
  238. contentType: "foo",
  239. statusCode: 400,
  240. err: acme.NewError(acme.ErrorMalformedType, "expected content-type to be in [application/jose+json application/pkix-cert application/pkcs7-mime], but got foo"),
  241. }
  242. },
  243. "ok": func(t *testing.T) test {
  244. return test{
  245. h: Handler{
  246. linker: NewLinker("dns", "acme"),
  247. },
  248. ctx: context.WithValue(context.Background(), provisionerContextKey, prov),
  249. contentType: "application/jose+json",
  250. statusCode: 200,
  251. }
  252. },
  253. "ok/certificate/pkix-cert": func(t *testing.T) test {
  254. return test{
  255. h: Handler{
  256. linker: NewLinker("dns", "acme"),
  257. },
  258. ctx: context.WithValue(context.Background(), provisionerContextKey, prov),
  259. contentType: "application/pkix-cert",
  260. statusCode: 200,
  261. }
  262. },
  263. "ok/certificate/jose+json": func(t *testing.T) test {
  264. return test{
  265. h: Handler{
  266. linker: NewLinker("dns", "acme"),
  267. },
  268. ctx: context.WithValue(context.Background(), provisionerContextKey, prov),
  269. contentType: "application/jose+json",
  270. statusCode: 200,
  271. }
  272. },
  273. "ok/certificate/pkcs7-mime": func(t *testing.T) test {
  274. return test{
  275. h: Handler{
  276. linker: NewLinker("dns", "acme"),
  277. },
  278. ctx: context.WithValue(context.Background(), provisionerContextKey, prov),
  279. contentType: "application/pkcs7-mime",
  280. statusCode: 200,
  281. }
  282. },
  283. }
  284. for name, run := range tests {
  285. tc := run(t)
  286. t.Run(name, func(t *testing.T) {
  287. _url := url
  288. if tc.url != "" {
  289. _url = tc.url
  290. }
  291. req := httptest.NewRequest("GET", _url, nil)
  292. req = req.WithContext(tc.ctx)
  293. req.Header.Add("Content-Type", tc.contentType)
  294. w := httptest.NewRecorder()
  295. tc.h.verifyContentType(testNext)(w, req)
  296. res := w.Result()
  297. assert.Equals(t, res.StatusCode, tc.statusCode)
  298. body, err := ioutil.ReadAll(res.Body)
  299. res.Body.Close()
  300. assert.FatalError(t, err)
  301. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  302. var ae acme.Error
  303. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  304. assert.Equals(t, ae.Type, tc.err.Type)
  305. assert.Equals(t, ae.Detail, tc.err.Detail)
  306. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  307. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  308. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  309. } else {
  310. assert.Equals(t, bytes.TrimSpace(body), testBody)
  311. }
  312. })
  313. }
  314. }
  315. func TestHandlerIsPostAsGet(t *testing.T) {
  316. url := "https://ca.smallstep.com/acme/new-account"
  317. type test struct {
  318. ctx context.Context
  319. err *acme.Error
  320. statusCode int
  321. }
  322. var tests = map[string]func(t *testing.T) test{
  323. "fail/no-payload": func(t *testing.T) test {
  324. return test{
  325. ctx: context.Background(),
  326. statusCode: 500,
  327. err: acme.NewErrorISE("payload expected in request context"),
  328. }
  329. },
  330. "fail/nil-payload": func(t *testing.T) test {
  331. return test{
  332. ctx: context.WithValue(context.Background(), payloadContextKey, nil),
  333. statusCode: 500,
  334. err: acme.NewErrorISE("payload expected in request context"),
  335. }
  336. },
  337. "fail/not-post-as-get": func(t *testing.T) test {
  338. return test{
  339. ctx: context.WithValue(context.Background(), payloadContextKey, &payloadInfo{}),
  340. statusCode: 400,
  341. err: acme.NewError(acme.ErrorMalformedType, "expected POST-as-GET"),
  342. }
  343. },
  344. "ok": func(t *testing.T) test {
  345. return test{
  346. ctx: context.WithValue(context.Background(), payloadContextKey, &payloadInfo{isPostAsGet: true}),
  347. statusCode: 200,
  348. }
  349. },
  350. }
  351. for name, run := range tests {
  352. tc := run(t)
  353. t.Run(name, func(t *testing.T) {
  354. h := &Handler{}
  355. req := httptest.NewRequest("GET", url, nil)
  356. req = req.WithContext(tc.ctx)
  357. w := httptest.NewRecorder()
  358. h.isPostAsGet(testNext)(w, req)
  359. res := w.Result()
  360. assert.Equals(t, res.StatusCode, tc.statusCode)
  361. body, err := ioutil.ReadAll(res.Body)
  362. res.Body.Close()
  363. assert.FatalError(t, err)
  364. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  365. var ae acme.Error
  366. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  367. assert.Equals(t, ae.Type, tc.err.Type)
  368. assert.Equals(t, ae.Detail, tc.err.Detail)
  369. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  370. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  371. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  372. } else {
  373. assert.Equals(t, bytes.TrimSpace(body), testBody)
  374. }
  375. })
  376. }
  377. }
  378. type errReader int
  379. func (errReader) Read(p []byte) (n int, err error) {
  380. return 0, errors.New("force")
  381. }
  382. func (errReader) Close() error {
  383. return nil
  384. }
  385. func TestHandlerParseJWS(t *testing.T) {
  386. url := "https://ca.smallstep.com/acme/new-account"
  387. type test struct {
  388. next nextHTTP
  389. body io.Reader
  390. err *acme.Error
  391. statusCode int
  392. }
  393. var tests = map[string]func(t *testing.T) test{
  394. "fail/read-body-error": func(t *testing.T) test {
  395. return test{
  396. body: errReader(0),
  397. statusCode: 500,
  398. err: acme.NewErrorISE("failed to read request body: force"),
  399. }
  400. },
  401. "fail/parse-jws-error": func(t *testing.T) test {
  402. return test{
  403. body: strings.NewReader("foo"),
  404. statusCode: 400,
  405. err: acme.NewError(acme.ErrorMalformedType, "failed to parse JWS from request body: square/go-jose: compact JWS format must have three parts"),
  406. }
  407. },
  408. "ok": func(t *testing.T) test {
  409. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  410. assert.FatalError(t, err)
  411. signer, err := jose.NewSigner(jose.SigningKey{
  412. Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
  413. Key: jwk.Key,
  414. }, new(jose.SignerOptions))
  415. assert.FatalError(t, err)
  416. signed, err := signer.Sign([]byte("baz"))
  417. assert.FatalError(t, err)
  418. expRaw, err := signed.CompactSerialize()
  419. assert.FatalError(t, err)
  420. return test{
  421. body: strings.NewReader(expRaw),
  422. next: func(w http.ResponseWriter, r *http.Request) {
  423. jws, err := jwsFromContext(r.Context())
  424. assert.FatalError(t, err)
  425. gotRaw, err := jws.CompactSerialize()
  426. assert.FatalError(t, err)
  427. assert.Equals(t, gotRaw, expRaw)
  428. w.Write(testBody)
  429. },
  430. statusCode: 200,
  431. }
  432. },
  433. }
  434. for name, run := range tests {
  435. tc := run(t)
  436. t.Run(name, func(t *testing.T) {
  437. h := &Handler{}
  438. req := httptest.NewRequest("GET", url, tc.body)
  439. w := httptest.NewRecorder()
  440. h.parseJWS(tc.next)(w, req)
  441. res := w.Result()
  442. assert.Equals(t, res.StatusCode, tc.statusCode)
  443. body, err := ioutil.ReadAll(res.Body)
  444. res.Body.Close()
  445. assert.FatalError(t, err)
  446. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  447. var ae acme.Error
  448. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  449. assert.Equals(t, ae.Type, tc.err.Type)
  450. assert.Equals(t, ae.Detail, tc.err.Detail)
  451. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  452. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  453. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  454. } else {
  455. assert.Equals(t, bytes.TrimSpace(body), testBody)
  456. }
  457. })
  458. }
  459. }
  460. func TestHandlerVerifyAndExtractJWSPayload(t *testing.T) {
  461. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  462. assert.FatalError(t, err)
  463. _pub := jwk.Public()
  464. pub := &_pub
  465. so := new(jose.SignerOptions)
  466. so.WithHeader("alg", jose.SignatureAlgorithm(jwk.Algorithm))
  467. signer, err := jose.NewSigner(jose.SigningKey{
  468. Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
  469. Key: jwk.Key,
  470. }, so)
  471. assert.FatalError(t, err)
  472. jws, err := signer.Sign([]byte("baz"))
  473. assert.FatalError(t, err)
  474. raw, err := jws.CompactSerialize()
  475. assert.FatalError(t, err)
  476. parsedJWS, err := jose.ParseJWS(raw)
  477. assert.FatalError(t, err)
  478. url := "https://ca.smallstep.com/acme/account/1234"
  479. type test struct {
  480. ctx context.Context
  481. next func(http.ResponseWriter, *http.Request)
  482. err *acme.Error
  483. statusCode int
  484. }
  485. var tests = map[string]func(t *testing.T) test{
  486. "fail/no-jws": func(t *testing.T) test {
  487. return test{
  488. ctx: context.Background(),
  489. statusCode: 500,
  490. err: acme.NewErrorISE("jws expected in request context"),
  491. }
  492. },
  493. "fail/nil-jws": func(t *testing.T) test {
  494. return test{
  495. ctx: context.WithValue(context.Background(), jwsContextKey, nil),
  496. statusCode: 500,
  497. err: acme.NewErrorISE("jws expected in request context"),
  498. }
  499. },
  500. "fail/no-jwk": func(t *testing.T) test {
  501. return test{
  502. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  503. statusCode: 500,
  504. err: acme.NewErrorISE("jwk expected in request context"),
  505. }
  506. },
  507. "fail/nil-jwk": func(t *testing.T) test {
  508. ctx := context.WithValue(context.Background(), jwsContextKey, parsedJWS)
  509. return test{
  510. ctx: context.WithValue(ctx, jwsContextKey, nil),
  511. statusCode: 500,
  512. err: acme.NewErrorISE("jwk expected in request context"),
  513. }
  514. },
  515. "fail/verify-jws-failure": func(t *testing.T) test {
  516. _jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  517. assert.FatalError(t, err)
  518. _pub := _jwk.Public()
  519. ctx := context.WithValue(context.Background(), jwsContextKey, parsedJWS)
  520. ctx = context.WithValue(ctx, jwsContextKey, &_pub)
  521. return test{
  522. ctx: ctx,
  523. statusCode: 400,
  524. err: acme.NewError(acme.ErrorMalformedType, "error verifying jws: square/go-jose: error in cryptographic primitive"),
  525. }
  526. },
  527. "fail/algorithm-mismatch": func(t *testing.T) test {
  528. _pub := *pub
  529. clone := &_pub
  530. clone.Algorithm = jose.HS256
  531. ctx := context.WithValue(context.Background(), jwsContextKey, parsedJWS)
  532. ctx = context.WithValue(ctx, jwsContextKey, clone)
  533. return test{
  534. ctx: ctx,
  535. statusCode: 400,
  536. err: acme.NewError(acme.ErrorMalformedType, "verifier and signature algorithm do not match"),
  537. }
  538. },
  539. "ok": func(t *testing.T) test {
  540. ctx := context.WithValue(context.Background(), jwsContextKey, parsedJWS)
  541. ctx = context.WithValue(ctx, jwsContextKey, pub)
  542. return test{
  543. ctx: ctx,
  544. statusCode: 200,
  545. next: func(w http.ResponseWriter, r *http.Request) {
  546. p, err := payloadFromContext(r.Context())
  547. assert.FatalError(t, err)
  548. if assert.NotNil(t, p) {
  549. assert.Equals(t, p.value, []byte("baz"))
  550. assert.False(t, p.isPostAsGet)
  551. assert.False(t, p.isEmptyJSON)
  552. }
  553. w.Write(testBody)
  554. },
  555. }
  556. },
  557. "ok/empty-algorithm-in-jwk": func(t *testing.T) test {
  558. _pub := *pub
  559. clone := &_pub
  560. clone.Algorithm = ""
  561. ctx := context.WithValue(context.Background(), jwsContextKey, parsedJWS)
  562. ctx = context.WithValue(ctx, jwsContextKey, pub)
  563. return test{
  564. ctx: ctx,
  565. statusCode: 200,
  566. next: func(w http.ResponseWriter, r *http.Request) {
  567. p, err := payloadFromContext(r.Context())
  568. assert.FatalError(t, err)
  569. if assert.NotNil(t, p) {
  570. assert.Equals(t, p.value, []byte("baz"))
  571. assert.False(t, p.isPostAsGet)
  572. assert.False(t, p.isEmptyJSON)
  573. }
  574. w.Write(testBody)
  575. },
  576. }
  577. },
  578. "ok/post-as-get": func(t *testing.T) test {
  579. _jws, err := signer.Sign([]byte(""))
  580. assert.FatalError(t, err)
  581. _raw, err := _jws.CompactSerialize()
  582. assert.FatalError(t, err)
  583. _parsed, err := jose.ParseJWS(_raw)
  584. assert.FatalError(t, err)
  585. ctx := context.WithValue(context.Background(), jwsContextKey, _parsed)
  586. ctx = context.WithValue(ctx, jwsContextKey, pub)
  587. return test{
  588. ctx: ctx,
  589. statusCode: 200,
  590. next: func(w http.ResponseWriter, r *http.Request) {
  591. p, err := payloadFromContext(r.Context())
  592. assert.FatalError(t, err)
  593. if assert.NotNil(t, p) {
  594. assert.Equals(t, p.value, []byte{})
  595. assert.True(t, p.isPostAsGet)
  596. assert.False(t, p.isEmptyJSON)
  597. }
  598. w.Write(testBody)
  599. },
  600. }
  601. },
  602. "ok/empty-json": func(t *testing.T) test {
  603. _jws, err := signer.Sign([]byte("{}"))
  604. assert.FatalError(t, err)
  605. _raw, err := _jws.CompactSerialize()
  606. assert.FatalError(t, err)
  607. _parsed, err := jose.ParseJWS(_raw)
  608. assert.FatalError(t, err)
  609. ctx := context.WithValue(context.Background(), jwsContextKey, _parsed)
  610. ctx = context.WithValue(ctx, jwsContextKey, pub)
  611. return test{
  612. ctx: ctx,
  613. statusCode: 200,
  614. next: func(w http.ResponseWriter, r *http.Request) {
  615. p, err := payloadFromContext(r.Context())
  616. assert.FatalError(t, err)
  617. if assert.NotNil(t, p) {
  618. assert.Equals(t, p.value, []byte("{}"))
  619. assert.False(t, p.isPostAsGet)
  620. assert.True(t, p.isEmptyJSON)
  621. }
  622. w.Write(testBody)
  623. },
  624. }
  625. },
  626. }
  627. for name, run := range tests {
  628. tc := run(t)
  629. t.Run(name, func(t *testing.T) {
  630. h := &Handler{}
  631. req := httptest.NewRequest("GET", url, nil)
  632. req = req.WithContext(tc.ctx)
  633. w := httptest.NewRecorder()
  634. h.verifyAndExtractJWSPayload(tc.next)(w, req)
  635. res := w.Result()
  636. assert.Equals(t, res.StatusCode, tc.statusCode)
  637. body, err := ioutil.ReadAll(res.Body)
  638. res.Body.Close()
  639. assert.FatalError(t, err)
  640. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  641. var ae acme.Error
  642. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  643. assert.Equals(t, ae.Type, tc.err.Type)
  644. assert.Equals(t, ae.Detail, tc.err.Detail)
  645. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  646. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  647. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  648. } else {
  649. assert.Equals(t, bytes.TrimSpace(body), testBody)
  650. }
  651. })
  652. }
  653. }
  654. func TestHandlerLookupJWK(t *testing.T) {
  655. prov := newProv()
  656. provName := url.PathEscape(prov.GetName())
  657. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  658. url := fmt.Sprintf("%s/acme/%s/account/1234",
  659. baseURL, provName)
  660. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  661. assert.FatalError(t, err)
  662. accID := "account-id"
  663. prefix := fmt.Sprintf("%s/acme/%s/account/",
  664. baseURL, provName)
  665. so := new(jose.SignerOptions)
  666. so.WithHeader("kid", fmt.Sprintf("%s%s", prefix, accID))
  667. signer, err := jose.NewSigner(jose.SigningKey{
  668. Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
  669. Key: jwk.Key,
  670. }, so)
  671. assert.FatalError(t, err)
  672. jws, err := signer.Sign([]byte("baz"))
  673. assert.FatalError(t, err)
  674. raw, err := jws.CompactSerialize()
  675. assert.FatalError(t, err)
  676. parsedJWS, err := jose.ParseJWS(raw)
  677. assert.FatalError(t, err)
  678. type test struct {
  679. linker Linker
  680. db acme.DB
  681. ctx context.Context
  682. next func(http.ResponseWriter, *http.Request)
  683. err *acme.Error
  684. statusCode int
  685. }
  686. var tests = map[string]func(t *testing.T) test{
  687. "fail/no-jws": func(t *testing.T) test {
  688. return test{
  689. ctx: context.WithValue(context.Background(), provisionerContextKey, prov),
  690. statusCode: 500,
  691. err: acme.NewErrorISE("jws expected in request context"),
  692. }
  693. },
  694. "fail/nil-jws": func(t *testing.T) test {
  695. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  696. ctx = context.WithValue(ctx, jwsContextKey, nil)
  697. return test{
  698. ctx: ctx,
  699. statusCode: 500,
  700. err: acme.NewErrorISE("jws expected in request context"),
  701. }
  702. },
  703. "fail/no-kid": func(t *testing.T) test {
  704. _signer, err := jose.NewSigner(jose.SigningKey{
  705. Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
  706. Key: jwk.Key,
  707. }, new(jose.SignerOptions))
  708. assert.FatalError(t, err)
  709. _jws, err := _signer.Sign([]byte("baz"))
  710. assert.FatalError(t, err)
  711. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  712. ctx = context.WithValue(ctx, jwsContextKey, _jws)
  713. ctx = context.WithValue(ctx, baseURLContextKey, baseURL)
  714. return test{
  715. linker: NewLinker("dns", "acme"),
  716. ctx: ctx,
  717. statusCode: 400,
  718. err: acme.NewError(acme.ErrorMalformedType, "kid does not have required prefix; expected %s, but got ", prefix),
  719. }
  720. },
  721. "fail/bad-kid-prefix": func(t *testing.T) test {
  722. _so := new(jose.SignerOptions)
  723. _so.WithHeader("kid", "foo")
  724. _signer, err := jose.NewSigner(jose.SigningKey{
  725. Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
  726. Key: jwk.Key,
  727. }, _so)
  728. assert.FatalError(t, err)
  729. _jws, err := _signer.Sign([]byte("baz"))
  730. assert.FatalError(t, err)
  731. _raw, err := _jws.CompactSerialize()
  732. assert.FatalError(t, err)
  733. _parsed, err := jose.ParseJWS(_raw)
  734. assert.FatalError(t, err)
  735. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  736. ctx = context.WithValue(ctx, jwsContextKey, _parsed)
  737. ctx = context.WithValue(ctx, baseURLContextKey, baseURL)
  738. return test{
  739. linker: NewLinker("dns", "acme"),
  740. ctx: ctx,
  741. statusCode: 400,
  742. err: acme.NewError(acme.ErrorMalformedType, "kid does not have required prefix; expected %s, but got foo", prefix),
  743. }
  744. },
  745. "fail/account-not-found": func(t *testing.T) test {
  746. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  747. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  748. ctx = context.WithValue(ctx, baseURLContextKey, baseURL)
  749. return test{
  750. linker: NewLinker("dns", "acme"),
  751. db: &acme.MockDB{
  752. MockGetAccount: func(ctx context.Context, accID string) (*acme.Account, error) {
  753. assert.Equals(t, accID, accID)
  754. return nil, database.ErrNotFound
  755. },
  756. },
  757. ctx: ctx,
  758. statusCode: 400,
  759. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  760. }
  761. },
  762. "fail/GetAccount-error": func(t *testing.T) test {
  763. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  764. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  765. ctx = context.WithValue(ctx, baseURLContextKey, baseURL)
  766. return test{
  767. linker: NewLinker("dns", "acme"),
  768. db: &acme.MockDB{
  769. MockGetAccount: func(ctx context.Context, id string) (*acme.Account, error) {
  770. assert.Equals(t, id, accID)
  771. return nil, acme.NewErrorISE("force")
  772. },
  773. },
  774. ctx: ctx,
  775. statusCode: 500,
  776. err: acme.NewErrorISE("force"),
  777. }
  778. },
  779. "fail/account-not-valid": func(t *testing.T) test {
  780. acc := &acme.Account{Status: "deactivated"}
  781. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  782. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  783. ctx = context.WithValue(ctx, baseURLContextKey, baseURL)
  784. return test{
  785. linker: NewLinker("dns", "acme"),
  786. db: &acme.MockDB{
  787. MockGetAccount: func(ctx context.Context, id string) (*acme.Account, error) {
  788. assert.Equals(t, id, accID)
  789. return acc, nil
  790. },
  791. },
  792. ctx: ctx,
  793. statusCode: 401,
  794. err: acme.NewError(acme.ErrorUnauthorizedType, "account is not active"),
  795. }
  796. },
  797. "ok": func(t *testing.T) test {
  798. acc := &acme.Account{Status: "valid", Key: jwk}
  799. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  800. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  801. ctx = context.WithValue(ctx, baseURLContextKey, baseURL)
  802. return test{
  803. linker: NewLinker("dns", "acme"),
  804. db: &acme.MockDB{
  805. MockGetAccount: func(ctx context.Context, id string) (*acme.Account, error) {
  806. assert.Equals(t, id, accID)
  807. return acc, nil
  808. },
  809. },
  810. ctx: ctx,
  811. next: func(w http.ResponseWriter, r *http.Request) {
  812. _acc, err := accountFromContext(r.Context())
  813. assert.FatalError(t, err)
  814. assert.Equals(t, _acc, acc)
  815. _jwk, err := jwkFromContext(r.Context())
  816. assert.FatalError(t, err)
  817. assert.Equals(t, _jwk, jwk)
  818. w.Write(testBody)
  819. },
  820. statusCode: 200,
  821. }
  822. },
  823. }
  824. for name, run := range tests {
  825. tc := run(t)
  826. t.Run(name, func(t *testing.T) {
  827. h := &Handler{db: tc.db, linker: tc.linker}
  828. req := httptest.NewRequest("GET", url, nil)
  829. req = req.WithContext(tc.ctx)
  830. w := httptest.NewRecorder()
  831. h.lookupJWK(tc.next)(w, req)
  832. res := w.Result()
  833. assert.Equals(t, res.StatusCode, tc.statusCode)
  834. body, err := ioutil.ReadAll(res.Body)
  835. res.Body.Close()
  836. assert.FatalError(t, err)
  837. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  838. var ae acme.Error
  839. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  840. assert.Equals(t, ae.Type, tc.err.Type)
  841. assert.Equals(t, ae.Detail, tc.err.Detail)
  842. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  843. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  844. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  845. } else {
  846. assert.Equals(t, bytes.TrimSpace(body), testBody)
  847. }
  848. })
  849. }
  850. }
  851. func TestHandlerExtractJWK(t *testing.T) {
  852. prov := newProv()
  853. provName := url.PathEscape(prov.GetName())
  854. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  855. assert.FatalError(t, err)
  856. kid, err := jwk.Thumbprint(crypto.SHA256)
  857. assert.FatalError(t, err)
  858. pub := jwk.Public()
  859. pub.KeyID = base64.RawURLEncoding.EncodeToString(kid)
  860. so := new(jose.SignerOptions)
  861. so.WithHeader("jwk", pub)
  862. signer, err := jose.NewSigner(jose.SigningKey{
  863. Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
  864. Key: jwk.Key,
  865. }, so)
  866. assert.FatalError(t, err)
  867. jws, err := signer.Sign([]byte("baz"))
  868. assert.FatalError(t, err)
  869. raw, err := jws.CompactSerialize()
  870. assert.FatalError(t, err)
  871. parsedJWS, err := jose.ParseJWS(raw)
  872. assert.FatalError(t, err)
  873. url := fmt.Sprintf("https://ca.smallstep.com/acme/%s/account/1234",
  874. provName)
  875. type test struct {
  876. db acme.DB
  877. ctx context.Context
  878. next func(http.ResponseWriter, *http.Request)
  879. err *acme.Error
  880. statusCode int
  881. }
  882. var tests = map[string]func(t *testing.T) test{
  883. "fail/no-jws": func(t *testing.T) test {
  884. return test{
  885. ctx: context.WithValue(context.Background(), provisionerContextKey, prov),
  886. statusCode: 500,
  887. err: acme.NewErrorISE("jws expected in request context"),
  888. }
  889. },
  890. "fail/nil-jws": func(t *testing.T) test {
  891. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  892. ctx = context.WithValue(ctx, jwsContextKey, nil)
  893. return test{
  894. ctx: ctx,
  895. statusCode: 500,
  896. err: acme.NewErrorISE("jws expected in request context"),
  897. }
  898. },
  899. "fail/nil-jwk": func(t *testing.T) test {
  900. _jws := &jose.JSONWebSignature{
  901. Signatures: []jose.Signature{
  902. {
  903. Protected: jose.Header{
  904. JSONWebKey: nil,
  905. },
  906. },
  907. },
  908. }
  909. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  910. ctx = context.WithValue(ctx, jwsContextKey, _jws)
  911. return test{
  912. ctx: ctx,
  913. statusCode: 400,
  914. err: acme.NewError(acme.ErrorMalformedType, "jwk expected in protected header"),
  915. }
  916. },
  917. "fail/invalid-jwk": func(t *testing.T) test {
  918. _jws := &jose.JSONWebSignature{
  919. Signatures: []jose.Signature{
  920. {
  921. Protected: jose.Header{
  922. JSONWebKey: &jose.JSONWebKey{Key: "foo"},
  923. },
  924. },
  925. },
  926. }
  927. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  928. ctx = context.WithValue(ctx, jwsContextKey, _jws)
  929. return test{
  930. ctx: ctx,
  931. statusCode: 400,
  932. err: acme.NewError(acme.ErrorMalformedType, "invalid jwk in protected header"),
  933. }
  934. },
  935. "fail/GetAccountByKey-error": func(t *testing.T) test {
  936. ctx := context.WithValue(context.Background(), provisionerContextKey, 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 nil, acme.NewErrorISE("force")
  944. },
  945. },
  946. statusCode: 500,
  947. err: acme.NewErrorISE("force"),
  948. }
  949. },
  950. "fail/account-not-valid": func(t *testing.T) test {
  951. acc := &acme.Account{Status: "deactivated"}
  952. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  953. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  954. return test{
  955. ctx: ctx,
  956. db: &acme.MockDB{
  957. MockGetAccountByKeyID: func(ctx context.Context, kid string) (*acme.Account, error) {
  958. assert.Equals(t, kid, pub.KeyID)
  959. return acc, nil
  960. },
  961. },
  962. statusCode: 401,
  963. err: acme.NewError(acme.ErrorUnauthorizedType, "account is not active"),
  964. }
  965. },
  966. "ok": func(t *testing.T) test {
  967. acc := &acme.Account{Status: "valid"}
  968. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  969. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  970. return test{
  971. ctx: ctx,
  972. db: &acme.MockDB{
  973. MockGetAccountByKeyID: func(ctx context.Context, kid string) (*acme.Account, error) {
  974. assert.Equals(t, kid, pub.KeyID)
  975. return acc, nil
  976. },
  977. },
  978. next: func(w http.ResponseWriter, r *http.Request) {
  979. _acc, err := accountFromContext(r.Context())
  980. assert.FatalError(t, err)
  981. assert.Equals(t, _acc, acc)
  982. _jwk, err := jwkFromContext(r.Context())
  983. assert.FatalError(t, err)
  984. assert.Equals(t, _jwk.KeyID, pub.KeyID)
  985. w.Write(testBody)
  986. },
  987. statusCode: 200,
  988. }
  989. },
  990. "ok/no-account": func(t *testing.T) test {
  991. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  992. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  993. return test{
  994. ctx: ctx,
  995. db: &acme.MockDB{
  996. MockGetAccountByKeyID: func(ctx context.Context, kid string) (*acme.Account, error) {
  997. assert.Equals(t, kid, pub.KeyID)
  998. return nil, database.ErrNotFound
  999. },
  1000. },
  1001. next: func(w http.ResponseWriter, r *http.Request) {
  1002. _acc, err := accountFromContext(r.Context())
  1003. assert.NotNil(t, err)
  1004. assert.Nil(t, _acc)
  1005. _jwk, err := jwkFromContext(r.Context())
  1006. assert.FatalError(t, err)
  1007. assert.Equals(t, _jwk.KeyID, pub.KeyID)
  1008. w.Write(testBody)
  1009. },
  1010. statusCode: 200,
  1011. }
  1012. },
  1013. }
  1014. for name, run := range tests {
  1015. tc := run(t)
  1016. t.Run(name, func(t *testing.T) {
  1017. h := &Handler{db: tc.db}
  1018. req := httptest.NewRequest("GET", url, nil)
  1019. req = req.WithContext(tc.ctx)
  1020. w := httptest.NewRecorder()
  1021. h.extractJWK(tc.next)(w, req)
  1022. res := w.Result()
  1023. assert.Equals(t, res.StatusCode, tc.statusCode)
  1024. body, err := ioutil.ReadAll(res.Body)
  1025. res.Body.Close()
  1026. assert.FatalError(t, err)
  1027. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  1028. var ae acme.Error
  1029. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  1030. assert.Equals(t, ae.Type, tc.err.Type)
  1031. assert.Equals(t, ae.Detail, tc.err.Detail)
  1032. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  1033. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  1034. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  1035. } else {
  1036. assert.Equals(t, bytes.TrimSpace(body), testBody)
  1037. }
  1038. })
  1039. }
  1040. }
  1041. func TestHandlerValidateJWS(t *testing.T) {
  1042. url := "https://ca.smallstep.com/acme/account/1234"
  1043. type test struct {
  1044. db acme.DB
  1045. ctx context.Context
  1046. next func(http.ResponseWriter, *http.Request)
  1047. err *acme.Error
  1048. statusCode int
  1049. }
  1050. var tests = map[string]func(t *testing.T) test{
  1051. "fail/no-jws": func(t *testing.T) test {
  1052. return test{
  1053. ctx: context.Background(),
  1054. statusCode: 500,
  1055. err: acme.NewErrorISE("jws expected in request context"),
  1056. }
  1057. },
  1058. "fail/nil-jws": func(t *testing.T) test {
  1059. return test{
  1060. ctx: context.WithValue(context.Background(), jwsContextKey, nil),
  1061. statusCode: 500,
  1062. err: acme.NewErrorISE("jws expected in request context"),
  1063. }
  1064. },
  1065. "fail/no-signature": func(t *testing.T) test {
  1066. return test{
  1067. ctx: context.WithValue(context.Background(), jwsContextKey, &jose.JSONWebSignature{}),
  1068. statusCode: 400,
  1069. err: acme.NewError(acme.ErrorMalformedType, "request body does not contain a signature"),
  1070. }
  1071. },
  1072. "fail/more-than-one-signature": func(t *testing.T) test {
  1073. jws := &jose.JSONWebSignature{
  1074. Signatures: []jose.Signature{
  1075. {},
  1076. {},
  1077. },
  1078. }
  1079. return test{
  1080. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1081. statusCode: 400,
  1082. err: acme.NewError(acme.ErrorMalformedType, "request body contains more than one signature"),
  1083. }
  1084. },
  1085. "fail/unprotected-header-not-empty": func(t *testing.T) test {
  1086. jws := &jose.JSONWebSignature{
  1087. Signatures: []jose.Signature{
  1088. {Unprotected: jose.Header{Nonce: "abc"}},
  1089. },
  1090. }
  1091. return test{
  1092. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1093. statusCode: 400,
  1094. err: acme.NewError(acme.ErrorMalformedType, "unprotected header must not be used"),
  1095. }
  1096. },
  1097. "fail/unsuitable-algorithm-none": func(t *testing.T) test {
  1098. jws := &jose.JSONWebSignature{
  1099. Signatures: []jose.Signature{
  1100. {Protected: jose.Header{Algorithm: "none"}},
  1101. },
  1102. }
  1103. return test{
  1104. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1105. statusCode: 400,
  1106. err: acme.NewError(acme.ErrorMalformedType, "unsuitable algorithm: none"),
  1107. }
  1108. },
  1109. "fail/unsuitable-algorithm-mac": func(t *testing.T) test {
  1110. jws := &jose.JSONWebSignature{
  1111. Signatures: []jose.Signature{
  1112. {Protected: jose.Header{Algorithm: jose.HS256}},
  1113. },
  1114. }
  1115. return test{
  1116. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1117. statusCode: 400,
  1118. err: acme.NewError(acme.ErrorMalformedType, "unsuitable algorithm: %s", jose.HS256),
  1119. }
  1120. },
  1121. "fail/rsa-key-&-alg-mismatch": func(t *testing.T) test {
  1122. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  1123. assert.FatalError(t, err)
  1124. pub := jwk.Public()
  1125. jws := &jose.JSONWebSignature{
  1126. Signatures: []jose.Signature{
  1127. {
  1128. Protected: jose.Header{
  1129. Algorithm: jose.RS256,
  1130. JSONWebKey: &pub,
  1131. ExtraHeaders: map[jose.HeaderKey]interface{}{
  1132. "url": url,
  1133. },
  1134. },
  1135. },
  1136. },
  1137. }
  1138. return test{
  1139. db: &acme.MockDB{
  1140. MockDeleteNonce: func(ctx context.Context, n acme.Nonce) error {
  1141. return nil
  1142. },
  1143. },
  1144. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1145. statusCode: 400,
  1146. err: acme.NewError(acme.ErrorMalformedType, "jws key type and algorithm do not match"),
  1147. }
  1148. },
  1149. "fail/rsa-key-too-small": func(t *testing.T) test {
  1150. jwk, err := jose.GenerateJWK("RSA", "", "", "sig", "", 1024)
  1151. assert.FatalError(t, err)
  1152. pub := jwk.Public()
  1153. jws := &jose.JSONWebSignature{
  1154. Signatures: []jose.Signature{
  1155. {
  1156. Protected: jose.Header{
  1157. Algorithm: jose.RS256,
  1158. JSONWebKey: &pub,
  1159. ExtraHeaders: map[jose.HeaderKey]interface{}{
  1160. "url": url,
  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, "rsa keys must be at least 2048 bits (256 bytes) in size"),
  1175. }
  1176. },
  1177. "fail/UseNonce-error": func(t *testing.T) test {
  1178. jws := &jose.JSONWebSignature{
  1179. Signatures: []jose.Signature{
  1180. {Protected: jose.Header{Algorithm: jose.ES256}},
  1181. },
  1182. }
  1183. return test{
  1184. db: &acme.MockDB{
  1185. MockDeleteNonce: func(ctx context.Context, n acme.Nonce) error {
  1186. return acme.NewErrorISE("force")
  1187. },
  1188. },
  1189. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1190. statusCode: 500,
  1191. err: acme.NewErrorISE("force"),
  1192. }
  1193. },
  1194. "fail/no-url-header": func(t *testing.T) test {
  1195. jws := &jose.JSONWebSignature{
  1196. Signatures: []jose.Signature{
  1197. {Protected: jose.Header{Algorithm: jose.ES256}},
  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, "jws missing url protected header"),
  1209. }
  1210. },
  1211. "fail/url-mismatch": func(t *testing.T) test {
  1212. jws := &jose.JSONWebSignature{
  1213. Signatures: []jose.Signature{
  1214. {
  1215. Protected: jose.Header{
  1216. Algorithm: jose.ES256,
  1217. ExtraHeaders: map[jose.HeaderKey]interface{}{
  1218. "url": "foo",
  1219. },
  1220. },
  1221. },
  1222. },
  1223. }
  1224. return test{
  1225. db: &acme.MockDB{
  1226. MockDeleteNonce: func(ctx context.Context, n acme.Nonce) error {
  1227. return nil
  1228. },
  1229. },
  1230. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1231. statusCode: 400,
  1232. err: acme.NewError(acme.ErrorMalformedType, "url header in JWS (foo) does not match request url (%s)", url),
  1233. }
  1234. },
  1235. "fail/both-jwk-kid": func(t *testing.T) test {
  1236. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  1237. assert.FatalError(t, err)
  1238. pub := jwk.Public()
  1239. jws := &jose.JSONWebSignature{
  1240. Signatures: []jose.Signature{
  1241. {
  1242. Protected: jose.Header{
  1243. Algorithm: jose.ES256,
  1244. KeyID: "bar",
  1245. JSONWebKey: &pub,
  1246. ExtraHeaders: map[jose.HeaderKey]interface{}{
  1247. "url": url,
  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, "jwk and kid are mutually exclusive"),
  1262. }
  1263. },
  1264. "fail/no-jwk-kid": func(t *testing.T) test {
  1265. jws := &jose.JSONWebSignature{
  1266. Signatures: []jose.Signature{
  1267. {
  1268. Protected: jose.Header{
  1269. Algorithm: jose.ES256,
  1270. ExtraHeaders: map[jose.HeaderKey]interface{}{
  1271. "url": url,
  1272. },
  1273. },
  1274. },
  1275. },
  1276. }
  1277. return test{
  1278. db: &acme.MockDB{
  1279. MockDeleteNonce: func(ctx context.Context, n acme.Nonce) error {
  1280. return nil
  1281. },
  1282. },
  1283. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1284. statusCode: 400,
  1285. err: acme.NewError(acme.ErrorMalformedType, "either jwk or kid must be defined in jws protected header"),
  1286. }
  1287. },
  1288. "ok/kid": func(t *testing.T) test {
  1289. jws := &jose.JSONWebSignature{
  1290. Signatures: []jose.Signature{
  1291. {
  1292. Protected: jose.Header{
  1293. Algorithm: jose.ES256,
  1294. KeyID: "bar",
  1295. ExtraHeaders: map[jose.HeaderKey]interface{}{
  1296. "url": url,
  1297. },
  1298. },
  1299. },
  1300. },
  1301. }
  1302. return test{
  1303. db: &acme.MockDB{
  1304. MockDeleteNonce: func(ctx context.Context, n acme.Nonce) error {
  1305. return nil
  1306. },
  1307. },
  1308. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1309. next: func(w http.ResponseWriter, r *http.Request) {
  1310. w.Write(testBody)
  1311. },
  1312. statusCode: 200,
  1313. }
  1314. },
  1315. "ok/jwk/ecdsa": func(t *testing.T) test {
  1316. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  1317. assert.FatalError(t, err)
  1318. pub := jwk.Public()
  1319. jws := &jose.JSONWebSignature{
  1320. Signatures: []jose.Signature{
  1321. {
  1322. Protected: jose.Header{
  1323. Algorithm: jose.ES256,
  1324. JSONWebKey: &pub,
  1325. ExtraHeaders: map[jose.HeaderKey]interface{}{
  1326. "url": url,
  1327. },
  1328. },
  1329. },
  1330. },
  1331. }
  1332. return test{
  1333. db: &acme.MockDB{
  1334. MockDeleteNonce: func(ctx context.Context, n acme.Nonce) error {
  1335. return nil
  1336. },
  1337. },
  1338. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1339. next: func(w http.ResponseWriter, r *http.Request) {
  1340. w.Write(testBody)
  1341. },
  1342. statusCode: 200,
  1343. }
  1344. },
  1345. "ok/jwk/rsa": func(t *testing.T) test {
  1346. jwk, err := jose.GenerateJWK("RSA", "", "", "sig", "", 2048)
  1347. assert.FatalError(t, err)
  1348. pub := jwk.Public()
  1349. jws := &jose.JSONWebSignature{
  1350. Signatures: []jose.Signature{
  1351. {
  1352. Protected: jose.Header{
  1353. Algorithm: jose.RS256,
  1354. JSONWebKey: &pub,
  1355. ExtraHeaders: map[jose.HeaderKey]interface{}{
  1356. "url": url,
  1357. },
  1358. },
  1359. },
  1360. },
  1361. }
  1362. return test{
  1363. db: &acme.MockDB{
  1364. MockDeleteNonce: func(ctx context.Context, n acme.Nonce) error {
  1365. return nil
  1366. },
  1367. },
  1368. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1369. next: func(w http.ResponseWriter, r *http.Request) {
  1370. w.Write(testBody)
  1371. },
  1372. statusCode: 200,
  1373. }
  1374. },
  1375. }
  1376. for name, run := range tests {
  1377. tc := run(t)
  1378. t.Run(name, func(t *testing.T) {
  1379. h := &Handler{db: tc.db}
  1380. req := httptest.NewRequest("GET", url, nil)
  1381. req = req.WithContext(tc.ctx)
  1382. w := httptest.NewRecorder()
  1383. h.validateJWS(tc.next)(w, req)
  1384. res := w.Result()
  1385. assert.Equals(t, res.StatusCode, tc.statusCode)
  1386. body, err := ioutil.ReadAll(res.Body)
  1387. res.Body.Close()
  1388. assert.FatalError(t, err)
  1389. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  1390. var ae acme.Error
  1391. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  1392. assert.Equals(t, ae.Type, tc.err.Type)
  1393. assert.Equals(t, ae.Detail, tc.err.Detail)
  1394. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  1395. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  1396. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  1397. } else {
  1398. assert.Equals(t, bytes.TrimSpace(body), testBody)
  1399. }
  1400. })
  1401. }
  1402. }