middleware_test.go 48 KB

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