middleware_test.go 48 KB

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