middleware_test.go 21 KB

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