4
0

middleware_test.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  1. package api
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "io"
  8. "net/http"
  9. "net/http/httptest"
  10. "testing"
  11. "time"
  12. "github.com/go-chi/chi"
  13. "github.com/google/go-cmp/cmp"
  14. "github.com/google/go-cmp/cmp/cmpopts"
  15. "google.golang.org/protobuf/types/known/timestamppb"
  16. "go.step.sm/linkedca"
  17. "github.com/smallstep/assert"
  18. "github.com/smallstep/certificates/acme"
  19. "github.com/smallstep/certificates/authority/admin"
  20. "github.com/smallstep/certificates/authority/admin/db/nosql"
  21. "github.com/smallstep/certificates/authority/provisioner"
  22. )
  23. func TestHandler_requireAPIEnabled(t *testing.T) {
  24. type test struct {
  25. ctx context.Context
  26. auth adminAuthority
  27. next http.HandlerFunc
  28. err *admin.Error
  29. statusCode int
  30. }
  31. var tests = map[string]func(t *testing.T) test{
  32. "fail/auth.IsAdminAPIEnabled": func(t *testing.T) test {
  33. return test{
  34. ctx: context.Background(),
  35. auth: &mockAdminAuthority{
  36. MockIsAdminAPIEnabled: func() bool {
  37. return false
  38. },
  39. },
  40. err: &admin.Error{
  41. Type: admin.ErrorNotImplementedType.String(),
  42. Status: 501,
  43. Detail: "not implemented",
  44. Message: "administration API not enabled",
  45. },
  46. statusCode: 501,
  47. }
  48. },
  49. "ok": func(t *testing.T) test {
  50. auth := &mockAdminAuthority{
  51. MockIsAdminAPIEnabled: func() bool {
  52. return true
  53. },
  54. }
  55. next := func(w http.ResponseWriter, r *http.Request) {
  56. w.Write(nil) // mock response with status 200
  57. }
  58. return test{
  59. ctx: context.Background(),
  60. auth: auth,
  61. next: next,
  62. statusCode: 200,
  63. }
  64. },
  65. }
  66. for name, prep := range tests {
  67. tc := prep(t)
  68. t.Run(name, func(t *testing.T) {
  69. h := &Handler{
  70. auth: tc.auth,
  71. }
  72. req := httptest.NewRequest("GET", "/foo", nil) // chi routing is prepared in test setup
  73. req = req.WithContext(tc.ctx)
  74. w := httptest.NewRecorder()
  75. h.requireAPIEnabled(tc.next)(w, req)
  76. res := w.Result()
  77. assert.Equals(t, tc.statusCode, res.StatusCode)
  78. body, err := io.ReadAll(res.Body)
  79. res.Body.Close()
  80. assert.FatalError(t, err)
  81. if res.StatusCode >= 400 {
  82. err := admin.Error{}
  83. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &err))
  84. assert.Equals(t, tc.err.Type, err.Type)
  85. assert.Equals(t, tc.err.Message, err.Message)
  86. assert.Equals(t, tc.err.StatusCode(), res.StatusCode)
  87. assert.Equals(t, tc.err.Detail, err.Detail)
  88. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  89. return
  90. }
  91. // nothing to test when the requireAPIEnabled middleware succeeds, currently
  92. })
  93. }
  94. }
  95. func TestHandler_extractAuthorizeTokenAdmin(t *testing.T) {
  96. type test struct {
  97. ctx context.Context
  98. auth adminAuthority
  99. req *http.Request
  100. next http.HandlerFunc
  101. err *admin.Error
  102. statusCode int
  103. }
  104. var tests = map[string]func(t *testing.T) test{
  105. "fail/missing-authorization-token": func(t *testing.T) test {
  106. req := httptest.NewRequest("GET", "/foo", nil)
  107. req.Header["Authorization"] = []string{""}
  108. return test{
  109. ctx: context.Background(),
  110. req: req,
  111. statusCode: 401,
  112. err: &admin.Error{
  113. Type: admin.ErrorUnauthorizedType.String(),
  114. Status: 401,
  115. Detail: "unauthorized",
  116. Message: "missing authorization header token",
  117. },
  118. }
  119. },
  120. "fail/auth.AuthorizeAdminToken": func(t *testing.T) test {
  121. req := httptest.NewRequest("GET", "/foo", nil)
  122. req.Header["Authorization"] = []string{"token"}
  123. auth := &mockAdminAuthority{
  124. MockAuthorizeAdminToken: func(r *http.Request, token string) (*linkedca.Admin, error) {
  125. assert.Equals(t, "token", token)
  126. return nil, admin.NewError(
  127. admin.ErrorUnauthorizedType,
  128. "not authorized",
  129. )
  130. },
  131. }
  132. return test{
  133. ctx: context.Background(),
  134. auth: auth,
  135. req: req,
  136. statusCode: 401,
  137. err: &admin.Error{
  138. Type: admin.ErrorUnauthorizedType.String(),
  139. Status: 401,
  140. Detail: "unauthorized",
  141. Message: "not authorized",
  142. },
  143. }
  144. },
  145. "ok": func(t *testing.T) test {
  146. req := httptest.NewRequest("GET", "/foo", nil)
  147. req.Header["Authorization"] = []string{"token"}
  148. createdAt := time.Now()
  149. var deletedAt time.Time
  150. adm := &linkedca.Admin{
  151. Id: "adminID",
  152. AuthorityId: "authorityID",
  153. Subject: "admin",
  154. ProvisionerId: "provID",
  155. Type: linkedca.Admin_SUPER_ADMIN,
  156. CreatedAt: timestamppb.New(createdAt),
  157. DeletedAt: timestamppb.New(deletedAt),
  158. }
  159. auth := &mockAdminAuthority{
  160. MockAuthorizeAdminToken: func(r *http.Request, token string) (*linkedca.Admin, error) {
  161. assert.Equals(t, "token", token)
  162. return adm, nil
  163. },
  164. }
  165. next := func(w http.ResponseWriter, r *http.Request) {
  166. ctx := r.Context()
  167. adm := linkedca.MustAdminFromContext(ctx) // verifying that the context now has a linkedca.Admin
  168. opts := []cmp.Option{cmpopts.IgnoreUnexported(linkedca.Admin{}, timestamppb.Timestamp{})}
  169. if !cmp.Equal(adm, adm, opts...) {
  170. t.Errorf("linkedca.Admin diff =\n%s", cmp.Diff(adm, adm, opts...))
  171. }
  172. w.Write(nil) // mock response with status 200
  173. }
  174. return test{
  175. ctx: context.Background(),
  176. auth: auth,
  177. req: req,
  178. next: next,
  179. statusCode: 200,
  180. err: nil,
  181. }
  182. },
  183. }
  184. for name, prep := range tests {
  185. tc := prep(t)
  186. t.Run(name, func(t *testing.T) {
  187. h := &Handler{
  188. auth: tc.auth,
  189. }
  190. req := tc.req.WithContext(tc.ctx)
  191. w := httptest.NewRecorder()
  192. h.extractAuthorizeTokenAdmin(tc.next)(w, req)
  193. res := w.Result()
  194. assert.Equals(t, tc.statusCode, res.StatusCode)
  195. body, err := io.ReadAll(res.Body)
  196. res.Body.Close()
  197. assert.FatalError(t, err)
  198. if res.StatusCode >= 400 {
  199. err := admin.Error{}
  200. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &err))
  201. assert.Equals(t, tc.err.Type, err.Type)
  202. assert.Equals(t, tc.err.Message, err.Message)
  203. assert.Equals(t, tc.err.StatusCode(), res.StatusCode)
  204. assert.Equals(t, tc.err.Detail, err.Detail)
  205. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  206. return
  207. }
  208. })
  209. }
  210. }
  211. func TestHandler_loadProvisionerByName(t *testing.T) {
  212. type test struct {
  213. adminDB admin.DB
  214. auth adminAuthority
  215. ctx context.Context
  216. next http.HandlerFunc
  217. err *admin.Error
  218. statusCode int
  219. }
  220. var tests = map[string]func(t *testing.T) test{
  221. "fail/auth.LoadProvisionerByName": func(t *testing.T) test {
  222. chiCtx := chi.NewRouteContext()
  223. chiCtx.URLParams.Add("provisionerName", "provName")
  224. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  225. auth := &mockAdminAuthority{
  226. MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
  227. assert.Equals(t, "provName", name)
  228. return nil, errors.New("force")
  229. },
  230. }
  231. err := admin.WrapErrorISE(errors.New("force"), "error loading provisioner provName")
  232. err.Message = "error loading provisioner provName: force"
  233. return test{
  234. ctx: ctx,
  235. auth: auth,
  236. statusCode: 500,
  237. err: err,
  238. }
  239. },
  240. "fail/db.GetProvisioner": func(t *testing.T) test {
  241. chiCtx := chi.NewRouteContext()
  242. chiCtx.URLParams.Add("provisionerName", "provName")
  243. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  244. auth := &mockAdminAuthority{
  245. MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
  246. assert.Equals(t, "provName", name)
  247. return &provisioner.MockProvisioner{
  248. MgetID: func() string {
  249. return "provID"
  250. },
  251. }, nil
  252. },
  253. }
  254. db := &admin.MockDB{
  255. MockGetProvisioner: func(ctx context.Context, id string) (*linkedca.Provisioner, error) {
  256. assert.Equals(t, "provID", id)
  257. return nil, errors.New("force")
  258. },
  259. }
  260. err := admin.WrapErrorISE(errors.New("force"), "error retrieving provisioner provName")
  261. err.Message = "error retrieving provisioner provName: force"
  262. return test{
  263. ctx: ctx,
  264. auth: auth,
  265. adminDB: db,
  266. statusCode: 500,
  267. err: err,
  268. }
  269. },
  270. "ok": func(t *testing.T) test {
  271. chiCtx := chi.NewRouteContext()
  272. chiCtx.URLParams.Add("provisionerName", "provName")
  273. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  274. auth := &mockAdminAuthority{
  275. MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
  276. assert.Equals(t, "provName", name)
  277. return &provisioner.MockProvisioner{
  278. MgetID: func() string {
  279. return "provID"
  280. },
  281. }, nil
  282. },
  283. }
  284. db := &admin.MockDB{
  285. MockGetProvisioner: func(ctx context.Context, id string) (*linkedca.Provisioner, error) {
  286. assert.Equals(t, "provID", id)
  287. return &linkedca.Provisioner{
  288. Id: "provID",
  289. Name: "provName",
  290. }, nil
  291. },
  292. }
  293. return test{
  294. ctx: ctx,
  295. auth: auth,
  296. adminDB: db,
  297. statusCode: 200,
  298. next: func(w http.ResponseWriter, r *http.Request) {
  299. prov := linkedca.MustProvisionerFromContext(r.Context())
  300. assert.NotNil(t, prov)
  301. assert.Equals(t, "provID", prov.GetId())
  302. assert.Equals(t, "provName", prov.GetName())
  303. w.Write(nil) // mock response with status 200
  304. },
  305. }
  306. },
  307. }
  308. for name, prep := range tests {
  309. tc := prep(t)
  310. t.Run(name, func(t *testing.T) {
  311. h := &Handler{
  312. auth: tc.auth,
  313. adminDB: tc.adminDB,
  314. }
  315. req := httptest.NewRequest("GET", "/foo", nil) // chi routing is prepared in test setup
  316. req = req.WithContext(tc.ctx)
  317. w := httptest.NewRecorder()
  318. h.loadProvisionerByName(tc.next)(w, req)
  319. res := w.Result()
  320. assert.Equals(t, tc.statusCode, res.StatusCode)
  321. body, err := io.ReadAll(res.Body)
  322. res.Body.Close()
  323. assert.FatalError(t, err)
  324. if res.StatusCode >= 400 {
  325. err := admin.Error{}
  326. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &err))
  327. assert.Equals(t, tc.err.Type, err.Type)
  328. assert.Equals(t, tc.err.Message, err.Message)
  329. assert.Equals(t, tc.err.StatusCode(), res.StatusCode)
  330. assert.Equals(t, tc.err.Detail, err.Detail)
  331. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  332. return
  333. }
  334. })
  335. }
  336. }
  337. func TestHandler_checkAction(t *testing.T) {
  338. type test struct {
  339. adminDB admin.DB
  340. next http.HandlerFunc
  341. supportedInStandalone bool
  342. err *admin.Error
  343. statusCode int
  344. }
  345. var tests = map[string]func(t *testing.T) test{
  346. "standalone-nosql-supported": func(t *testing.T) test {
  347. return test{
  348. supportedInStandalone: true,
  349. adminDB: &nosql.DB{},
  350. next: func(w http.ResponseWriter, r *http.Request) {
  351. w.Write(nil) // mock response with status 200
  352. },
  353. statusCode: 200,
  354. }
  355. },
  356. "standalone-nosql-not-supported": func(t *testing.T) test {
  357. err := admin.NewError(admin.ErrorNotImplementedType, "operation not supported in standalone mode")
  358. err.Message = "operation not supported in standalone mode"
  359. return test{
  360. supportedInStandalone: false,
  361. adminDB: &nosql.DB{},
  362. statusCode: 501,
  363. err: err,
  364. }
  365. },
  366. "standalone-no-nosql-not-supported": func(t *testing.T) test {
  367. err := admin.NewError(admin.ErrorNotImplementedType, "operation not supported")
  368. err.Message = "operation not supported"
  369. return test{
  370. supportedInStandalone: false,
  371. adminDB: &admin.MockDB{},
  372. next: func(w http.ResponseWriter, r *http.Request) {
  373. w.Write(nil) // mock response with status 200
  374. },
  375. statusCode: 200,
  376. err: err,
  377. }
  378. },
  379. }
  380. for name, prep := range tests {
  381. tc := prep(t)
  382. t.Run(name, func(t *testing.T) {
  383. h := &Handler{
  384. adminDB: tc.adminDB,
  385. }
  386. req := httptest.NewRequest("GET", "/foo", nil)
  387. w := httptest.NewRecorder()
  388. h.checkAction(tc.next, tc.supportedInStandalone)(w, req)
  389. res := w.Result()
  390. assert.Equals(t, tc.statusCode, res.StatusCode)
  391. body, err := io.ReadAll(res.Body)
  392. res.Body.Close()
  393. assert.FatalError(t, err)
  394. if res.StatusCode >= 400 {
  395. err := admin.Error{}
  396. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &err))
  397. assert.Equals(t, tc.err.Type, err.Type)
  398. assert.Equals(t, tc.err.Message, err.Message)
  399. assert.Equals(t, tc.err.StatusCode(), res.StatusCode)
  400. assert.Equals(t, tc.err.Detail, err.Detail)
  401. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  402. return
  403. }
  404. })
  405. }
  406. }
  407. func TestHandler_loadExternalAccountKey(t *testing.T) {
  408. type test struct {
  409. ctx context.Context
  410. acmeDB acme.DB
  411. next http.HandlerFunc
  412. err *admin.Error
  413. statusCode int
  414. }
  415. var tests = map[string]func(t *testing.T) test{
  416. "fail/keyID-not-found-error": func(t *testing.T) test {
  417. prov := &linkedca.Provisioner{
  418. Id: "provID",
  419. }
  420. chiCtx := chi.NewRouteContext()
  421. chiCtx.URLParams.Add("keyID", "key")
  422. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  423. ctx = linkedca.NewContextWithProvisioner(ctx, prov)
  424. err := admin.NewError(admin.ErrorNotFoundType, "ACME External Account Key not found")
  425. err.Message = "ACME External Account Key not found"
  426. return test{
  427. ctx: ctx,
  428. acmeDB: &acme.MockDB{
  429. MockGetExternalAccountKey: func(ctx context.Context, provisionerID, keyID string) (*acme.ExternalAccountKey, error) {
  430. assert.Equals(t, "provID", provisionerID)
  431. assert.Equals(t, "key", keyID)
  432. return nil, acme.ErrNotFound
  433. },
  434. },
  435. err: err,
  436. statusCode: 404,
  437. }
  438. },
  439. "fail/keyID-error": func(t *testing.T) test {
  440. prov := &linkedca.Provisioner{
  441. Id: "provID",
  442. }
  443. chiCtx := chi.NewRouteContext()
  444. chiCtx.URLParams.Add("keyID", "key")
  445. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  446. ctx = linkedca.NewContextWithProvisioner(ctx, prov)
  447. err := admin.WrapErrorISE(errors.New("force"), "error retrieving ACME External Account Key")
  448. err.Message = "error retrieving ACME External Account Key: force"
  449. return test{
  450. ctx: ctx,
  451. acmeDB: &acme.MockDB{
  452. MockGetExternalAccountKey: func(ctx context.Context, provisionerID, keyID string) (*acme.ExternalAccountKey, error) {
  453. assert.Equals(t, "provID", provisionerID)
  454. assert.Equals(t, "key", keyID)
  455. return nil, errors.New("force")
  456. },
  457. },
  458. err: err,
  459. statusCode: 500,
  460. }
  461. },
  462. "fail/reference-not-found-error": func(t *testing.T) test {
  463. prov := &linkedca.Provisioner{
  464. Id: "provID",
  465. }
  466. chiCtx := chi.NewRouteContext()
  467. chiCtx.URLParams.Add("reference", "ref")
  468. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  469. ctx = linkedca.NewContextWithProvisioner(ctx, prov)
  470. err := admin.NewError(admin.ErrorNotFoundType, "ACME External Account Key not found")
  471. err.Message = "ACME External Account Key not found"
  472. return test{
  473. ctx: ctx,
  474. acmeDB: &acme.MockDB{
  475. MockGetExternalAccountKeyByReference: func(ctx context.Context, provisionerID, reference string) (*acme.ExternalAccountKey, error) {
  476. assert.Equals(t, "provID", provisionerID)
  477. assert.Equals(t, "ref", reference)
  478. return nil, acme.ErrNotFound
  479. },
  480. },
  481. err: err,
  482. statusCode: 404,
  483. }
  484. },
  485. "fail/reference-error": func(t *testing.T) test {
  486. prov := &linkedca.Provisioner{
  487. Id: "provID",
  488. }
  489. chiCtx := chi.NewRouteContext()
  490. chiCtx.URLParams.Add("reference", "ref")
  491. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  492. ctx = linkedca.NewContextWithProvisioner(ctx, prov)
  493. err := admin.WrapErrorISE(errors.New("force"), "error retrieving ACME External Account Key")
  494. err.Message = "error retrieving ACME External Account Key: force"
  495. return test{
  496. ctx: ctx,
  497. acmeDB: &acme.MockDB{
  498. MockGetExternalAccountKeyByReference: func(ctx context.Context, provisionerID, reference string) (*acme.ExternalAccountKey, error) {
  499. assert.Equals(t, "provID", provisionerID)
  500. assert.Equals(t, "ref", reference)
  501. return nil, errors.New("force")
  502. },
  503. },
  504. err: err,
  505. statusCode: 500,
  506. }
  507. },
  508. "fail/no-key": func(t *testing.T) test {
  509. prov := &linkedca.Provisioner{
  510. Id: "provID",
  511. }
  512. chiCtx := chi.NewRouteContext()
  513. chiCtx.URLParams.Add("reference", "ref")
  514. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  515. ctx = linkedca.NewContextWithProvisioner(ctx, prov)
  516. err := admin.NewError(admin.ErrorNotFoundType, "ACME External Account Key not found")
  517. err.Message = "ACME External Account Key not found"
  518. return test{
  519. ctx: ctx,
  520. acmeDB: &acme.MockDB{
  521. MockGetExternalAccountKeyByReference: func(ctx context.Context, provisionerID, reference string) (*acme.ExternalAccountKey, error) {
  522. assert.Equals(t, "provID", provisionerID)
  523. assert.Equals(t, "ref", reference)
  524. return nil, nil
  525. },
  526. },
  527. err: err,
  528. statusCode: 404,
  529. }
  530. },
  531. "ok/keyID": func(t *testing.T) test {
  532. prov := &linkedca.Provisioner{
  533. Id: "provID",
  534. }
  535. chiCtx := chi.NewRouteContext()
  536. chiCtx.URLParams.Add("keyID", "eakID")
  537. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  538. ctx = linkedca.NewContextWithProvisioner(ctx, prov)
  539. err := admin.NewError(admin.ErrorNotFoundType, "ACME External Account Key not found")
  540. err.Message = "ACME External Account Key not found"
  541. createdAt := time.Now().Add(-1 * time.Hour)
  542. var boundAt time.Time
  543. eak := &acme.ExternalAccountKey{
  544. ID: "eakID",
  545. ProvisionerID: "provID",
  546. CreatedAt: createdAt,
  547. BoundAt: boundAt,
  548. }
  549. return test{
  550. ctx: ctx,
  551. acmeDB: &acme.MockDB{
  552. MockGetExternalAccountKey: func(ctx context.Context, provisionerID, keyID string) (*acme.ExternalAccountKey, error) {
  553. assert.Equals(t, "provID", provisionerID)
  554. assert.Equals(t, "eakID", keyID)
  555. return eak, nil
  556. },
  557. },
  558. next: func(w http.ResponseWriter, r *http.Request) {
  559. contextEAK := linkedca.MustExternalAccountKeyFromContext(r.Context())
  560. assert.NotNil(t, eak)
  561. exp := &linkedca.EABKey{
  562. Id: "eakID",
  563. Provisioner: "provID",
  564. CreatedAt: timestamppb.New(createdAt),
  565. BoundAt: timestamppb.New(boundAt),
  566. }
  567. assert.Equals(t, exp, contextEAK)
  568. w.Write(nil) // mock response with status 200
  569. },
  570. err: nil,
  571. statusCode: 200,
  572. }
  573. },
  574. "ok/reference": func(t *testing.T) test {
  575. prov := &linkedca.Provisioner{
  576. Id: "provID",
  577. }
  578. chiCtx := chi.NewRouteContext()
  579. chiCtx.URLParams.Add("reference", "ref")
  580. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  581. ctx = linkedca.NewContextWithProvisioner(ctx, prov)
  582. err := admin.NewError(admin.ErrorNotFoundType, "ACME External Account Key not found")
  583. err.Message = "ACME External Account Key not found"
  584. createdAt := time.Now().Add(-1 * time.Hour)
  585. var boundAt time.Time
  586. eak := &acme.ExternalAccountKey{
  587. ID: "eakID",
  588. ProvisionerID: "provID",
  589. Reference: "ref",
  590. CreatedAt: createdAt,
  591. BoundAt: boundAt,
  592. }
  593. return test{
  594. ctx: ctx,
  595. acmeDB: &acme.MockDB{
  596. MockGetExternalAccountKeyByReference: func(ctx context.Context, provisionerID, reference string) (*acme.ExternalAccountKey, error) {
  597. assert.Equals(t, "provID", provisionerID)
  598. assert.Equals(t, "ref", reference)
  599. return eak, nil
  600. },
  601. },
  602. next: func(w http.ResponseWriter, r *http.Request) {
  603. contextEAK := linkedca.MustExternalAccountKeyFromContext(r.Context())
  604. assert.NotNil(t, eak)
  605. exp := &linkedca.EABKey{
  606. Id: "eakID",
  607. Provisioner: "provID",
  608. Reference: "ref",
  609. CreatedAt: timestamppb.New(createdAt),
  610. BoundAt: timestamppb.New(boundAt),
  611. }
  612. assert.Equals(t, exp, contextEAK)
  613. w.Write(nil) // mock response with status 200
  614. },
  615. err: nil,
  616. statusCode: 200,
  617. }
  618. },
  619. }
  620. for name, prep := range tests {
  621. tc := prep(t)
  622. t.Run(name, func(t *testing.T) {
  623. h := &Handler{
  624. acmeDB: tc.acmeDB,
  625. }
  626. req := httptest.NewRequest("GET", "/foo", nil)
  627. req = req.WithContext(tc.ctx)
  628. w := httptest.NewRecorder()
  629. h.loadExternalAccountKey(tc.next)(w, req)
  630. res := w.Result()
  631. assert.Equals(t, tc.statusCode, res.StatusCode)
  632. body, err := io.ReadAll(res.Body)
  633. res.Body.Close()
  634. assert.FatalError(t, err)
  635. if res.StatusCode >= 400 {
  636. err := admin.Error{}
  637. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &err))
  638. assert.Equals(t, tc.err.Type, err.Type)
  639. assert.Equals(t, tc.err.Message, err.Message)
  640. assert.Equals(t, tc.err.StatusCode(), res.StatusCode)
  641. assert.Equals(t, tc.err.Detail, err.Detail)
  642. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  643. return
  644. }
  645. })
  646. }
  647. }