acme_test.go 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200
  1. package api
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "io"
  8. "net/http"
  9. "net/http/httptest"
  10. "strings"
  11. "testing"
  12. "time"
  13. "github.com/go-chi/chi"
  14. "github.com/google/go-cmp/cmp"
  15. "github.com/google/go-cmp/cmp/cmpopts"
  16. "github.com/smallstep/assert"
  17. "github.com/smallstep/certificates/acme"
  18. "github.com/smallstep/certificates/authority/admin"
  19. "github.com/smallstep/certificates/authority/provisioner"
  20. "go.step.sm/linkedca"
  21. "google.golang.org/protobuf/encoding/protojson"
  22. "google.golang.org/protobuf/proto"
  23. "google.golang.org/protobuf/types/known/timestamppb"
  24. )
  25. func readProtoJSON(r io.ReadCloser, m proto.Message) error {
  26. defer r.Close()
  27. data, err := io.ReadAll(r)
  28. if err != nil {
  29. return err
  30. }
  31. return protojson.Unmarshal(data, m)
  32. }
  33. func TestHandler_requireEABEnabled(t *testing.T) {
  34. type test struct {
  35. ctx context.Context
  36. db admin.DB
  37. auth adminAuthority
  38. next nextHTTP
  39. err *admin.Error
  40. statusCode int
  41. }
  42. var tests = map[string]func(t *testing.T) test{
  43. "fail/h.provisionerHasEABEnabled": func(t *testing.T) test {
  44. chiCtx := chi.NewRouteContext()
  45. chiCtx.URLParams.Add("prov", "provName")
  46. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  47. auth := &mockAdminAuthority{
  48. MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
  49. assert.Equals(t, "provName", name)
  50. return nil, errors.New("force")
  51. },
  52. }
  53. err := admin.NewErrorISE("error loading provisioner provName: force")
  54. err.Message = "error loading provisioner provName: force"
  55. return test{
  56. ctx: ctx,
  57. auth: auth,
  58. err: err,
  59. statusCode: 500,
  60. }
  61. },
  62. "ok/eab-disabled": func(t *testing.T) test {
  63. chiCtx := chi.NewRouteContext()
  64. chiCtx.URLParams.Add("prov", "provName")
  65. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  66. auth := &mockAdminAuthority{
  67. MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
  68. assert.Equals(t, "provName", name)
  69. return &provisioner.MockProvisioner{
  70. MgetID: func() string {
  71. return "provID"
  72. },
  73. }, nil
  74. },
  75. }
  76. db := &admin.MockDB{
  77. MockGetProvisioner: func(ctx context.Context, id string) (*linkedca.Provisioner, error) {
  78. assert.Equals(t, "provID", id)
  79. return &linkedca.Provisioner{
  80. Id: "provID",
  81. Name: "provName",
  82. Details: &linkedca.ProvisionerDetails{
  83. Data: &linkedca.ProvisionerDetails_ACME{
  84. ACME: &linkedca.ACMEProvisioner{
  85. RequireEab: false,
  86. },
  87. },
  88. },
  89. }, nil
  90. },
  91. }
  92. err := admin.NewError(admin.ErrorBadRequestType, "ACME EAB not enabled for provisioner provName")
  93. err.Message = "ACME EAB not enabled for provisioner provName"
  94. return test{
  95. ctx: ctx,
  96. auth: auth,
  97. db: db,
  98. err: err,
  99. statusCode: 400,
  100. }
  101. },
  102. "ok/eab-enabled": func(t *testing.T) test {
  103. chiCtx := chi.NewRouteContext()
  104. chiCtx.URLParams.Add("prov", "provName")
  105. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  106. auth := &mockAdminAuthority{
  107. MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
  108. assert.Equals(t, "provName", name)
  109. return &provisioner.MockProvisioner{
  110. MgetID: func() string {
  111. return "provID"
  112. },
  113. }, nil
  114. },
  115. }
  116. db := &admin.MockDB{
  117. MockGetProvisioner: func(ctx context.Context, id string) (*linkedca.Provisioner, error) {
  118. assert.Equals(t, "provID", id)
  119. return &linkedca.Provisioner{
  120. Id: "provID",
  121. Name: "provName",
  122. Details: &linkedca.ProvisionerDetails{
  123. Data: &linkedca.ProvisionerDetails_ACME{
  124. ACME: &linkedca.ACMEProvisioner{
  125. RequireEab: true,
  126. },
  127. },
  128. },
  129. }, nil
  130. },
  131. }
  132. return test{
  133. ctx: ctx,
  134. auth: auth,
  135. db: db,
  136. next: func(w http.ResponseWriter, r *http.Request) {
  137. w.Write(nil) // mock response with status 200
  138. },
  139. statusCode: 200,
  140. }
  141. },
  142. }
  143. for name, prep := range tests {
  144. tc := prep(t)
  145. t.Run(name, func(t *testing.T) {
  146. h := &Handler{
  147. db: tc.db,
  148. auth: tc.auth,
  149. acmeDB: nil,
  150. }
  151. req := httptest.NewRequest("GET", "/foo", nil) // chi routing is prepared in test setup
  152. req = req.WithContext(tc.ctx)
  153. w := httptest.NewRecorder()
  154. h.requireEABEnabled(tc.next)(w, req)
  155. res := w.Result()
  156. assert.Equals(t, tc.statusCode, res.StatusCode)
  157. body, err := io.ReadAll(res.Body)
  158. res.Body.Close()
  159. assert.FatalError(t, err)
  160. if res.StatusCode >= 400 {
  161. err := admin.Error{}
  162. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &err))
  163. assert.Equals(t, tc.err.Type, err.Type)
  164. assert.Equals(t, tc.err.Message, err.Message)
  165. assert.Equals(t, tc.err.StatusCode(), res.StatusCode)
  166. assert.Equals(t, tc.err.Detail, err.Detail)
  167. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  168. return
  169. }
  170. })
  171. }
  172. }
  173. func TestHandler_provisionerHasEABEnabled(t *testing.T) {
  174. type test struct {
  175. db admin.DB
  176. auth adminAuthority
  177. provisionerName string
  178. want bool
  179. err *admin.Error
  180. }
  181. var tests = map[string]func(t *testing.T) test{
  182. "fail/auth.LoadProvisionerByName": func(t *testing.T) test {
  183. auth := &mockAdminAuthority{
  184. MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
  185. assert.Equals(t, "provName", name)
  186. return nil, errors.New("force")
  187. },
  188. }
  189. return test{
  190. auth: auth,
  191. provisionerName: "provName",
  192. want: false,
  193. err: admin.WrapErrorISE(errors.New("force"), "error loading provisioner provName"),
  194. }
  195. },
  196. "fail/db.GetProvisioner": func(t *testing.T) test {
  197. auth := &mockAdminAuthority{
  198. MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
  199. assert.Equals(t, "provName", name)
  200. return &provisioner.MockProvisioner{
  201. MgetID: func() string {
  202. return "provID"
  203. },
  204. }, nil
  205. },
  206. }
  207. db := &admin.MockDB{
  208. MockGetProvisioner: func(ctx context.Context, id string) (*linkedca.Provisioner, error) {
  209. assert.Equals(t, "provID", id)
  210. return nil, errors.New("force")
  211. },
  212. }
  213. return test{
  214. auth: auth,
  215. db: db,
  216. provisionerName: "provName",
  217. want: false,
  218. err: admin.WrapErrorISE(errors.New("force"), "error loading provisioner provName"),
  219. }
  220. },
  221. "fail/prov.GetDetails": func(t *testing.T) test {
  222. auth := &mockAdminAuthority{
  223. MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
  224. assert.Equals(t, "provName", name)
  225. return &provisioner.MockProvisioner{
  226. MgetID: func() string {
  227. return "provID"
  228. },
  229. }, nil
  230. },
  231. }
  232. db := &admin.MockDB{
  233. MockGetProvisioner: func(ctx context.Context, id string) (*linkedca.Provisioner, error) {
  234. assert.Equals(t, "provID", id)
  235. return &linkedca.Provisioner{
  236. Id: "provID",
  237. Name: "provName",
  238. Details: nil,
  239. }, nil
  240. },
  241. }
  242. return test{
  243. auth: auth,
  244. db: db,
  245. provisionerName: "provName",
  246. want: false,
  247. err: admin.WrapErrorISE(errors.New("force"), "error loading provisioner provName"),
  248. }
  249. },
  250. "fail/details.GetACME": func(t *testing.T) test {
  251. auth := &mockAdminAuthority{
  252. MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
  253. assert.Equals(t, "provName", name)
  254. return &provisioner.MockProvisioner{
  255. MgetID: func() string {
  256. return "provID"
  257. },
  258. }, nil
  259. },
  260. }
  261. db := &admin.MockDB{
  262. MockGetProvisioner: func(ctx context.Context, id string) (*linkedca.Provisioner, error) {
  263. assert.Equals(t, "provID", id)
  264. return &linkedca.Provisioner{
  265. Id: "provID",
  266. Name: "provName",
  267. Details: &linkedca.ProvisionerDetails{
  268. Data: &linkedca.ProvisionerDetails_ACME{
  269. ACME: nil,
  270. },
  271. },
  272. }, nil
  273. },
  274. }
  275. return test{
  276. auth: auth,
  277. db: db,
  278. provisionerName: "provName",
  279. want: false,
  280. err: admin.WrapErrorISE(errors.New("force"), "error loading provisioner provName"),
  281. }
  282. },
  283. "ok/eab-disabled": func(t *testing.T) test {
  284. auth := &mockAdminAuthority{
  285. MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
  286. assert.Equals(t, "eab-disabled", name)
  287. return &provisioner.MockProvisioner{
  288. MgetID: func() string {
  289. return "provID"
  290. },
  291. }, nil
  292. },
  293. }
  294. db := &admin.MockDB{
  295. MockGetProvisioner: func(ctx context.Context, id string) (*linkedca.Provisioner, error) {
  296. assert.Equals(t, "provID", id)
  297. return &linkedca.Provisioner{
  298. Id: "provID",
  299. Name: "eab-disabled",
  300. Details: &linkedca.ProvisionerDetails{
  301. Data: &linkedca.ProvisionerDetails_ACME{
  302. ACME: &linkedca.ACMEProvisioner{
  303. RequireEab: false,
  304. },
  305. },
  306. },
  307. }, nil
  308. },
  309. }
  310. return test{
  311. db: db,
  312. auth: auth,
  313. provisionerName: "eab-disabled",
  314. want: false,
  315. }
  316. },
  317. "ok/eab-enabled": func(t *testing.T) test {
  318. auth := &mockAdminAuthority{
  319. MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
  320. assert.Equals(t, "eab-enabled", name)
  321. return &provisioner.MockProvisioner{
  322. MgetID: func() string {
  323. return "provID"
  324. },
  325. }, nil
  326. },
  327. }
  328. db := &admin.MockDB{
  329. MockGetProvisioner: func(ctx context.Context, id string) (*linkedca.Provisioner, error) {
  330. assert.Equals(t, "provID", id)
  331. return &linkedca.Provisioner{
  332. Id: "provID",
  333. Name: "eab-enabled",
  334. Details: &linkedca.ProvisionerDetails{
  335. Data: &linkedca.ProvisionerDetails_ACME{
  336. ACME: &linkedca.ACMEProvisioner{
  337. RequireEab: true,
  338. },
  339. },
  340. },
  341. }, nil
  342. },
  343. }
  344. return test{
  345. db: db,
  346. auth: auth,
  347. provisionerName: "eab-enabled",
  348. want: true,
  349. }
  350. },
  351. }
  352. for name, prep := range tests {
  353. tc := prep(t)
  354. t.Run(name, func(t *testing.T) {
  355. h := &Handler{
  356. db: tc.db,
  357. auth: tc.auth,
  358. acmeDB: nil,
  359. }
  360. got, prov, err := h.provisionerHasEABEnabled(context.TODO(), tc.provisionerName)
  361. if (err != nil) != (tc.err != nil) {
  362. t.Errorf("Handler.provisionerHasEABEnabled() error = %v, want err %v", err, tc.err)
  363. return
  364. }
  365. if tc.err != nil {
  366. assert.Type(t, &linkedca.Provisioner{}, prov)
  367. assert.Type(t, &admin.Error{}, err)
  368. adminError, _ := err.(*admin.Error)
  369. assert.Equals(t, tc.err.Type, adminError.Type)
  370. assert.Equals(t, tc.err.Status, adminError.Status)
  371. assert.Equals(t, tc.err.StatusCode(), adminError.StatusCode())
  372. assert.Equals(t, tc.err.Message, adminError.Message)
  373. assert.Equals(t, tc.err.Detail, adminError.Detail)
  374. return
  375. }
  376. if got != tc.want {
  377. t.Errorf("Handler.provisionerHasEABEnabled() = %v, want %v", got, tc.want)
  378. }
  379. })
  380. }
  381. }
  382. func Test_provisionerFromContext(t *testing.T) {
  383. prov := &linkedca.Provisioner{
  384. Id: "provID",
  385. Name: "acmeProv",
  386. }
  387. tests := []struct {
  388. name string
  389. ctx context.Context
  390. want *linkedca.Provisioner
  391. wantErr bool
  392. }{
  393. {
  394. name: "fail/no-provisioner",
  395. ctx: context.Background(),
  396. want: nil,
  397. wantErr: true,
  398. },
  399. {
  400. name: "fail/wrong-type",
  401. ctx: context.WithValue(context.Background(), provisionerContextKey, "prov"),
  402. want: nil,
  403. wantErr: true,
  404. },
  405. {
  406. name: "ok",
  407. ctx: context.WithValue(context.Background(), provisionerContextKey, prov),
  408. want: &linkedca.Provisioner{
  409. Id: "provID",
  410. Name: "acmeProv",
  411. },
  412. wantErr: false,
  413. },
  414. }
  415. for _, tt := range tests {
  416. t.Run(tt.name, func(t *testing.T) {
  417. got, err := provisionerFromContext(tt.ctx)
  418. if (err != nil) != tt.wantErr {
  419. t.Errorf("provisionerFromContext() error = %v, wantErr %v", err, tt.wantErr)
  420. return
  421. }
  422. opts := []cmp.Option{cmpopts.IgnoreUnexported(linkedca.Provisioner{})}
  423. if !cmp.Equal(tt.want, got, opts...) {
  424. t.Errorf("provisionerFromContext() diff =\n %s", cmp.Diff(tt.want, got, opts...))
  425. }
  426. })
  427. }
  428. }
  429. func TestCreateExternalAccountKeyRequest_Validate(t *testing.T) {
  430. type fields struct {
  431. Reference string
  432. }
  433. tests := []struct {
  434. name string
  435. fields fields
  436. wantErr bool
  437. }{
  438. {
  439. name: "fail/reference-too-long",
  440. fields: fields{
  441. Reference: strings.Repeat("A", 257),
  442. },
  443. wantErr: true,
  444. },
  445. {
  446. name: "ok/empty-reference",
  447. fields: fields{
  448. Reference: "",
  449. },
  450. wantErr: false,
  451. },
  452. {
  453. name: "ok",
  454. fields: fields{
  455. Reference: "my-eab-reference",
  456. },
  457. wantErr: false,
  458. },
  459. }
  460. for _, tt := range tests {
  461. t.Run(tt.name, func(t *testing.T) {
  462. r := &CreateExternalAccountKeyRequest{
  463. Reference: tt.fields.Reference,
  464. }
  465. if err := r.Validate(); (err != nil) != tt.wantErr {
  466. t.Errorf("CreateExternalAccountKeyRequest.Validate() error = %v, wantErr %v", err, tt.wantErr)
  467. }
  468. })
  469. }
  470. }
  471. func TestHandler_CreateExternalAccountKey(t *testing.T) {
  472. prov := &linkedca.Provisioner{
  473. Id: "provID",
  474. Name: "provName",
  475. }
  476. type test struct {
  477. ctx context.Context
  478. db acme.DB
  479. body []byte
  480. statusCode int
  481. eak *linkedca.EABKey
  482. err *admin.Error
  483. }
  484. var tests = map[string]func(t *testing.T) test{
  485. "fail/ReadJSON": func(t *testing.T) test {
  486. chiCtx := chi.NewRouteContext()
  487. chiCtx.URLParams.Add("prov", "provName")
  488. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  489. body := []byte("{!?}")
  490. return test{
  491. ctx: ctx,
  492. body: body,
  493. statusCode: 400,
  494. eak: nil,
  495. err: &admin.Error{
  496. Type: admin.ErrorBadRequestType.String(),
  497. Status: 400,
  498. Detail: "bad request",
  499. Message: "error reading request body: error decoding json: invalid character '!' looking for beginning of object key string",
  500. },
  501. }
  502. },
  503. "fail/validate": func(t *testing.T) test {
  504. chiCtx := chi.NewRouteContext()
  505. chiCtx.URLParams.Add("prov", "provName")
  506. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  507. req := CreateExternalAccountKeyRequest{
  508. Reference: strings.Repeat("A", 257),
  509. }
  510. body, err := json.Marshal(req)
  511. assert.FatalError(t, err)
  512. return test{
  513. ctx: ctx,
  514. body: body,
  515. statusCode: 400,
  516. eak: nil,
  517. err: &admin.Error{
  518. Type: admin.ErrorBadRequestType.String(),
  519. Status: 400,
  520. Detail: "bad request",
  521. Message: "error validating request body: reference length 257 exceeds the maximum (256)",
  522. },
  523. }
  524. },
  525. "fail/no-provisioner-in-context": func(t *testing.T) test {
  526. chiCtx := chi.NewRouteContext()
  527. chiCtx.URLParams.Add("prov", "provName")
  528. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  529. req := CreateExternalAccountKeyRequest{
  530. Reference: "aRef",
  531. }
  532. body, err := json.Marshal(req)
  533. assert.FatalError(t, err)
  534. return test{
  535. ctx: ctx,
  536. body: body,
  537. statusCode: 500,
  538. eak: nil,
  539. err: &admin.Error{
  540. Type: admin.ErrorServerInternalType.String(),
  541. Status: 500,
  542. Detail: "the server experienced an internal error",
  543. Message: "error getting provisioner from context: provisioner expected in request context",
  544. },
  545. }
  546. },
  547. "fail/acmeDB.GetExternalAccountKeyByReference": func(t *testing.T) test {
  548. chiCtx := chi.NewRouteContext()
  549. chiCtx.URLParams.Add("prov", "provName")
  550. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  551. ctx = context.WithValue(ctx, provisionerContextKey, prov)
  552. req := CreateExternalAccountKeyRequest{
  553. Reference: "an-external-key-reference",
  554. }
  555. body, err := json.Marshal(req)
  556. assert.FatalError(t, err)
  557. db := &acme.MockDB{
  558. MockGetExternalAccountKeyByReference: func(ctx context.Context, provisionerID, reference string) (*acme.ExternalAccountKey, error) {
  559. assert.Equals(t, "provID", provisionerID)
  560. assert.Equals(t, "an-external-key-reference", reference)
  561. return nil, errors.New("force")
  562. },
  563. }
  564. return test{
  565. ctx: ctx,
  566. db: db,
  567. body: body,
  568. statusCode: 500,
  569. eak: nil,
  570. err: &admin.Error{
  571. Type: admin.ErrorServerInternalType.String(),
  572. Status: 500,
  573. Detail: "the server experienced an internal error",
  574. Message: "could not lookup external account key by reference: force",
  575. },
  576. }
  577. },
  578. "fail/reference-conflict-409": func(t *testing.T) test {
  579. chiCtx := chi.NewRouteContext()
  580. chiCtx.URLParams.Add("prov", "provName")
  581. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  582. ctx = context.WithValue(ctx, provisionerContextKey, prov)
  583. req := CreateExternalAccountKeyRequest{
  584. Reference: "an-external-key-reference",
  585. }
  586. body, err := json.Marshal(req)
  587. assert.FatalError(t, err)
  588. db := &acme.MockDB{
  589. MockGetExternalAccountKeyByReference: func(ctx context.Context, provisionerID, reference string) (*acme.ExternalAccountKey, error) {
  590. assert.Equals(t, "provID", provisionerID)
  591. assert.Equals(t, "an-external-key-reference", reference)
  592. past := time.Now().Add(-24 * time.Hour)
  593. return &acme.ExternalAccountKey{
  594. ID: "eakID",
  595. ProvisionerID: "provID",
  596. Reference: "an-external-key-reference",
  597. KeyBytes: []byte{1, 3, 3, 7},
  598. CreatedAt: past,
  599. }, nil
  600. },
  601. }
  602. return test{
  603. ctx: ctx,
  604. db: db,
  605. body: body,
  606. statusCode: 409,
  607. eak: nil,
  608. err: &admin.Error{
  609. Type: admin.ErrorBadRequestType.String(),
  610. Status: 409,
  611. Detail: "bad request",
  612. Message: "an ACME EAB key for provisioner 'provName' with reference 'an-external-key-reference' already exists",
  613. },
  614. }
  615. },
  616. "fail/acmeDB.CreateExternalAccountKey-no-reference": func(t *testing.T) test {
  617. chiCtx := chi.NewRouteContext()
  618. chiCtx.URLParams.Add("prov", "provName")
  619. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  620. ctx = context.WithValue(ctx, provisionerContextKey, prov)
  621. req := CreateExternalAccountKeyRequest{
  622. Reference: "",
  623. }
  624. body, err := json.Marshal(req)
  625. assert.FatalError(t, err)
  626. db := &acme.MockDB{
  627. MockCreateExternalAccountKey: func(ctx context.Context, provisionerID, reference string) (*acme.ExternalAccountKey, error) {
  628. assert.Equals(t, "provID", provisionerID)
  629. assert.Equals(t, "", reference)
  630. return nil, errors.New("force")
  631. },
  632. }
  633. return test{
  634. ctx: ctx,
  635. db: db,
  636. body: body,
  637. statusCode: 500,
  638. err: &admin.Error{
  639. Type: admin.ErrorServerInternalType.String(),
  640. Status: 500,
  641. Detail: "the server experienced an internal error",
  642. Message: "error creating ACME EAB key for provisioner 'provName': force",
  643. },
  644. }
  645. },
  646. "fail/acmeDB.CreateExternalAccountKey-with-reference": func(t *testing.T) test {
  647. chiCtx := chi.NewRouteContext()
  648. chiCtx.URLParams.Add("prov", "provName")
  649. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  650. ctx = context.WithValue(ctx, provisionerContextKey, prov)
  651. req := CreateExternalAccountKeyRequest{
  652. Reference: "an-external-key-reference",
  653. }
  654. body, err := json.Marshal(req)
  655. assert.FatalError(t, err)
  656. db := &acme.MockDB{
  657. MockGetExternalAccountKeyByReference: func(ctx context.Context, provisionerID, reference string) (*acme.ExternalAccountKey, error) {
  658. assert.Equals(t, "provID", provisionerID)
  659. assert.Equals(t, "an-external-key-reference", reference)
  660. return nil, acme.ErrNotFound // simulating not found; skipping 409 conflict
  661. },
  662. MockCreateExternalAccountKey: func(ctx context.Context, provisionerID, reference string) (*acme.ExternalAccountKey, error) {
  663. assert.Equals(t, "provID", provisionerID)
  664. assert.Equals(t, "an-external-key-reference", reference)
  665. return nil, errors.New("force")
  666. },
  667. }
  668. return test{
  669. ctx: ctx,
  670. db: db,
  671. body: body,
  672. statusCode: 500,
  673. err: &admin.Error{
  674. Type: admin.ErrorServerInternalType.String(),
  675. Status: 500,
  676. Detail: "the server experienced an internal error",
  677. Message: "error creating ACME EAB key for provisioner 'provName' and reference 'an-external-key-reference': force",
  678. },
  679. }
  680. },
  681. "ok/no-reference": func(t *testing.T) test {
  682. chiCtx := chi.NewRouteContext()
  683. chiCtx.URLParams.Add("prov", "provName")
  684. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  685. ctx = context.WithValue(ctx, provisionerContextKey, prov)
  686. req := CreateExternalAccountKeyRequest{
  687. Reference: "",
  688. }
  689. body, err := json.Marshal(req)
  690. assert.FatalError(t, err)
  691. now := time.Now()
  692. db := &acme.MockDB{
  693. MockCreateExternalAccountKey: func(ctx context.Context, provisionerID, reference string) (*acme.ExternalAccountKey, error) {
  694. assert.Equals(t, "provID", provisionerID)
  695. assert.Equals(t, "", reference)
  696. return &acme.ExternalAccountKey{
  697. ID: "eakID",
  698. ProvisionerID: "provID",
  699. Reference: "",
  700. KeyBytes: []byte{1, 3, 3, 7},
  701. CreatedAt: now,
  702. }, nil
  703. },
  704. }
  705. return test{
  706. ctx: ctx,
  707. db: db,
  708. body: body,
  709. statusCode: 201,
  710. eak: &linkedca.EABKey{
  711. Id: "eakID",
  712. Provisioner: "provName",
  713. Reference: "",
  714. HmacKey: []byte{1, 3, 3, 7},
  715. },
  716. }
  717. },
  718. "ok/with-reference": func(t *testing.T) test {
  719. chiCtx := chi.NewRouteContext()
  720. chiCtx.URLParams.Add("prov", "provName")
  721. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  722. ctx = context.WithValue(ctx, provisionerContextKey, prov)
  723. req := CreateExternalAccountKeyRequest{
  724. Reference: "an-external-key-reference",
  725. }
  726. body, err := json.Marshal(req)
  727. assert.FatalError(t, err)
  728. now := time.Now()
  729. db := &acme.MockDB{
  730. MockGetExternalAccountKeyByReference: func(ctx context.Context, provisionerID, reference string) (*acme.ExternalAccountKey, error) {
  731. assert.Equals(t, "provID", provisionerID)
  732. assert.Equals(t, "an-external-key-reference", reference)
  733. return nil, acme.ErrNotFound // simulating not found; skipping 409 conflict
  734. },
  735. MockCreateExternalAccountKey: func(ctx context.Context, provisionerID, reference string) (*acme.ExternalAccountKey, error) {
  736. assert.Equals(t, "provID", provisionerID)
  737. assert.Equals(t, "an-external-key-reference", reference)
  738. return &acme.ExternalAccountKey{
  739. ID: "eakID",
  740. ProvisionerID: "provID",
  741. Reference: "an-external-key-reference",
  742. KeyBytes: []byte{1, 3, 3, 7},
  743. CreatedAt: now,
  744. }, nil
  745. },
  746. }
  747. return test{
  748. ctx: ctx,
  749. db: db,
  750. body: body,
  751. statusCode: 201,
  752. eak: &linkedca.EABKey{
  753. Id: "eakID",
  754. Provisioner: "provName",
  755. Reference: "an-external-key-reference",
  756. HmacKey: []byte{1, 3, 3, 7},
  757. },
  758. }
  759. },
  760. }
  761. for name, prep := range tests {
  762. tc := prep(t)
  763. t.Run(name, func(t *testing.T) {
  764. h := &Handler{
  765. acmeDB: tc.db,
  766. }
  767. req := httptest.NewRequest("POST", "/foo", io.NopCloser(bytes.NewBuffer(tc.body))) // chi routing is prepared in test setup
  768. req = req.WithContext(tc.ctx)
  769. w := httptest.NewRecorder()
  770. h.CreateExternalAccountKey(w, req)
  771. res := w.Result()
  772. assert.Equals(t, tc.statusCode, res.StatusCode)
  773. if res.StatusCode >= 400 {
  774. body, err := io.ReadAll(res.Body)
  775. res.Body.Close()
  776. assert.FatalError(t, err)
  777. adminErr := admin.Error{}
  778. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &adminErr))
  779. assert.Equals(t, tc.err.Type, adminErr.Type)
  780. assert.Equals(t, tc.err.Message, adminErr.Message)
  781. assert.Equals(t, tc.err.StatusCode(), res.StatusCode)
  782. assert.Equals(t, tc.err.Detail, adminErr.Detail)
  783. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  784. return
  785. }
  786. eabKey := &linkedca.EABKey{}
  787. err := readProtoJSON(res.Body, eabKey)
  788. assert.FatalError(t, err)
  789. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  790. opts := []cmp.Option{cmpopts.IgnoreUnexported(linkedca.EABKey{})}
  791. if !cmp.Equal(tc.eak, eabKey, opts...) {
  792. t.Errorf("h.CreateExternalAccountKey diff =\n%s", cmp.Diff(tc.eak, eabKey, opts...))
  793. }
  794. })
  795. }
  796. }
  797. func TestHandler_DeleteExternalAccountKey(t *testing.T) {
  798. prov := &linkedca.Provisioner{
  799. Id: "provID",
  800. Name: "provName",
  801. }
  802. type test struct {
  803. ctx context.Context
  804. db acme.DB
  805. statusCode int
  806. err *admin.Error
  807. }
  808. var tests = map[string]func(t *testing.T) test{
  809. "fail/no-provisioner-in-context": func(t *testing.T) test {
  810. chiCtx := chi.NewRouteContext()
  811. chiCtx.URLParams.Add("prov", "provName")
  812. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  813. return test{
  814. ctx: ctx,
  815. statusCode: 500,
  816. err: &admin.Error{
  817. Type: admin.ErrorServerInternalType.String(),
  818. Status: 500,
  819. Detail: "the server experienced an internal error",
  820. Message: "error getting provisioner from context: provisioner expected in request context",
  821. },
  822. }
  823. },
  824. "fail/acmeDB.DeleteExternalAccountKey": func(t *testing.T) test {
  825. chiCtx := chi.NewRouteContext()
  826. chiCtx.URLParams.Add("prov", "provName")
  827. chiCtx.URLParams.Add("id", "keyID")
  828. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  829. ctx = context.WithValue(ctx, provisionerContextKey, prov)
  830. db := &acme.MockDB{
  831. MockDeleteExternalAccountKey: func(ctx context.Context, provisionerID, keyID string) error {
  832. assert.Equals(t, "provID", provisionerID)
  833. assert.Equals(t, "keyID", keyID)
  834. return errors.New("force")
  835. },
  836. }
  837. return test{
  838. ctx: ctx,
  839. db: db,
  840. statusCode: 500,
  841. err: &admin.Error{
  842. Type: admin.ErrorServerInternalType.String(),
  843. Status: 500,
  844. Detail: "the server experienced an internal error",
  845. Message: "error deleting ACME EAB Key 'keyID': force",
  846. },
  847. }
  848. },
  849. "ok": func(t *testing.T) test {
  850. chiCtx := chi.NewRouteContext()
  851. chiCtx.URLParams.Add("prov", "provName")
  852. chiCtx.URLParams.Add("id", "keyID")
  853. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  854. ctx = context.WithValue(ctx, provisionerContextKey, prov)
  855. db := &acme.MockDB{
  856. MockDeleteExternalAccountKey: func(ctx context.Context, provisionerID, keyID string) error {
  857. assert.Equals(t, "provID", provisionerID)
  858. assert.Equals(t, "keyID", keyID)
  859. return nil
  860. },
  861. }
  862. return test{
  863. ctx: ctx,
  864. db: db,
  865. statusCode: 200,
  866. err: nil,
  867. }
  868. },
  869. }
  870. for name, prep := range tests {
  871. tc := prep(t)
  872. t.Run(name, func(t *testing.T) {
  873. h := &Handler{
  874. acmeDB: tc.db,
  875. }
  876. req := httptest.NewRequest("DELETE", "/foo", nil) // chi routing is prepared in test setup
  877. req = req.WithContext(tc.ctx)
  878. w := httptest.NewRecorder()
  879. h.DeleteExternalAccountKey(w, req)
  880. res := w.Result()
  881. assert.Equals(t, tc.statusCode, res.StatusCode)
  882. if res.StatusCode >= 400 {
  883. body, err := io.ReadAll(res.Body)
  884. res.Body.Close()
  885. assert.FatalError(t, err)
  886. adminErr := admin.Error{}
  887. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &adminErr))
  888. assert.Equals(t, tc.err.Type, adminErr.Type)
  889. assert.Equals(t, tc.err.Message, adminErr.Message)
  890. assert.Equals(t, tc.err.StatusCode(), res.StatusCode)
  891. assert.Equals(t, tc.err.Detail, adminErr.Detail)
  892. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  893. return
  894. }
  895. body, err := io.ReadAll(res.Body)
  896. res.Body.Close()
  897. assert.FatalError(t, err)
  898. response := DeleteResponse{}
  899. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &response))
  900. assert.Equals(t, "ok", response.Status)
  901. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  902. })
  903. }
  904. }
  905. func TestHandler_GetExternalAccountKeys(t *testing.T) {
  906. prov := &linkedca.Provisioner{
  907. Id: "provID",
  908. Name: "provName",
  909. }
  910. type test struct {
  911. ctx context.Context
  912. db acme.DB
  913. statusCode int
  914. req *http.Request
  915. resp GetExternalAccountKeysResponse
  916. err *admin.Error
  917. }
  918. var tests = map[string]func(t *testing.T) test{
  919. "fail/no-provisioner-in-context": func(t *testing.T) test {
  920. chiCtx := chi.NewRouteContext()
  921. chiCtx.URLParams.Add("prov", "provName")
  922. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  923. req := httptest.NewRequest("GET", "/foo", nil)
  924. return test{
  925. ctx: ctx,
  926. statusCode: 500,
  927. req: req,
  928. err: &admin.Error{
  929. Type: admin.ErrorServerInternalType.String(),
  930. Status: 500,
  931. Detail: "the server experienced an internal error",
  932. Message: "error getting provisioner from context: provisioner expected in request context",
  933. },
  934. }
  935. },
  936. "fail/acmeDB.GetExternalAccountKeyByReference": func(t *testing.T) test {
  937. chiCtx := chi.NewRouteContext()
  938. chiCtx.URLParams.Add("prov", "provName")
  939. chiCtx.URLParams.Add("ref", "an-external-key-reference")
  940. req := httptest.NewRequest("GET", "/foo", nil)
  941. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  942. ctx = context.WithValue(ctx, provisionerContextKey, prov)
  943. db := &acme.MockDB{
  944. MockGetExternalAccountKeyByReference: func(ctx context.Context, provisionerID, reference string) (*acme.ExternalAccountKey, error) {
  945. assert.Equals(t, "provID", provisionerID)
  946. assert.Equals(t, "an-external-key-reference", reference)
  947. return nil, errors.New("force")
  948. },
  949. }
  950. return test{
  951. ctx: ctx,
  952. statusCode: 500,
  953. req: req,
  954. db: db,
  955. err: &admin.Error{
  956. Status: 500,
  957. Type: admin.ErrorServerInternalType.String(),
  958. Detail: "the server experienced an internal error",
  959. Message: "error retrieving external account key with reference 'an-external-key-reference': force",
  960. },
  961. }
  962. },
  963. "fail/acmeDB.GetExternalAccountKeys": func(t *testing.T) test {
  964. chiCtx := chi.NewRouteContext()
  965. chiCtx.URLParams.Add("prov", "provName")
  966. req := httptest.NewRequest("GET", "/foo", nil)
  967. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  968. ctx = context.WithValue(ctx, provisionerContextKey, prov)
  969. db := &acme.MockDB{
  970. MockGetExternalAccountKeys: func(ctx context.Context, provisionerID string) ([]*acme.ExternalAccountKey, error) {
  971. assert.Equals(t, "provID", provisionerID)
  972. return nil, errors.New("force")
  973. },
  974. }
  975. return test{
  976. ctx: ctx,
  977. statusCode: 500,
  978. req: req,
  979. db: db,
  980. err: &admin.Error{
  981. Status: 500,
  982. Type: admin.ErrorServerInternalType.String(),
  983. Detail: "the server experienced an internal error",
  984. Message: "error retrieving external account keys: force",
  985. },
  986. }
  987. },
  988. "ok/reference-not-found": func(t *testing.T) test {
  989. chiCtx := chi.NewRouteContext()
  990. chiCtx.URLParams.Add("prov", "provName")
  991. chiCtx.URLParams.Add("ref", "an-external-key-reference")
  992. req := httptest.NewRequest("GET", "/foo", nil)
  993. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  994. ctx = context.WithValue(ctx, provisionerContextKey, prov)
  995. db := &acme.MockDB{
  996. MockGetExternalAccountKeyByReference: func(ctx context.Context, provisionerID, reference string) (*acme.ExternalAccountKey, error) {
  997. assert.Equals(t, "provID", provisionerID)
  998. assert.Equals(t, "an-external-key-reference", reference)
  999. return nil, nil // returning nil; no key found
  1000. },
  1001. }
  1002. return test{
  1003. ctx: ctx,
  1004. statusCode: 200,
  1005. req: req,
  1006. resp: GetExternalAccountKeysResponse{
  1007. EAKs: []*linkedca.EABKey{},
  1008. },
  1009. db: db,
  1010. err: nil,
  1011. }
  1012. },
  1013. "ok/reference-found": func(t *testing.T) test {
  1014. chiCtx := chi.NewRouteContext()
  1015. chiCtx.URLParams.Add("prov", "provName")
  1016. chiCtx.URLParams.Add("ref", "an-external-key-reference")
  1017. req := httptest.NewRequest("GET", "/foo", nil)
  1018. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  1019. ctx = context.WithValue(ctx, provisionerContextKey, prov)
  1020. createdAt := time.Now().Add(-24 * time.Hour)
  1021. var boundAt time.Time
  1022. db := &acme.MockDB{
  1023. MockGetExternalAccountKeyByReference: func(ctx context.Context, provisionerID, reference string) (*acme.ExternalAccountKey, error) {
  1024. assert.Equals(t, "provID", provisionerID)
  1025. assert.Equals(t, "an-external-key-reference", reference)
  1026. return &acme.ExternalAccountKey{
  1027. ID: "eakID",
  1028. ProvisionerID: "provID",
  1029. Reference: "an-external-key-reference",
  1030. CreatedAt: createdAt,
  1031. }, nil
  1032. },
  1033. }
  1034. return test{
  1035. ctx: ctx,
  1036. statusCode: 200,
  1037. req: req,
  1038. resp: GetExternalAccountKeysResponse{
  1039. EAKs: []*linkedca.EABKey{
  1040. {
  1041. Id: "eakID",
  1042. Provisioner: "provName",
  1043. Reference: "an-external-key-reference",
  1044. CreatedAt: timestamppb.New(createdAt),
  1045. BoundAt: timestamppb.New(boundAt),
  1046. },
  1047. },
  1048. },
  1049. db: db,
  1050. err: nil,
  1051. }
  1052. },
  1053. "ok/multiple-keys": func(t *testing.T) test {
  1054. chiCtx := chi.NewRouteContext()
  1055. chiCtx.URLParams.Add("prov", "provName")
  1056. req := httptest.NewRequest("GET", "/foo", nil)
  1057. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  1058. ctx = context.WithValue(ctx, provisionerContextKey, prov)
  1059. createdAt := time.Now().Add(-24 * time.Hour)
  1060. var boundAt time.Time
  1061. boundAtSet := time.Now().Add(-12 * time.Hour)
  1062. db := &acme.MockDB{
  1063. MockGetExternalAccountKeys: func(ctx context.Context, provisionerID string) ([]*acme.ExternalAccountKey, error) {
  1064. assert.Equals(t, "provID", provisionerID)
  1065. return []*acme.ExternalAccountKey{
  1066. {
  1067. ID: "eakID1",
  1068. ProvisionerID: "provID",
  1069. Reference: "some-external-key-reference",
  1070. KeyBytes: []byte{1, 3, 3, 7},
  1071. CreatedAt: createdAt,
  1072. },
  1073. {
  1074. ID: "eakID2",
  1075. ProvisionerID: "provID",
  1076. Reference: "some-other-external-key-reference",
  1077. KeyBytes: []byte{1, 3, 3, 7},
  1078. CreatedAt: createdAt.Add(1 * time.Hour),
  1079. },
  1080. {
  1081. ID: "eakID3",
  1082. ProvisionerID: "provID",
  1083. Reference: "another-external-key-reference",
  1084. KeyBytes: []byte{1, 3, 3, 7},
  1085. CreatedAt: createdAt,
  1086. BoundAt: boundAtSet,
  1087. AccountID: "accountID",
  1088. },
  1089. }, nil
  1090. },
  1091. }
  1092. return test{
  1093. ctx: ctx,
  1094. statusCode: 200,
  1095. req: req,
  1096. resp: GetExternalAccountKeysResponse{
  1097. EAKs: []*linkedca.EABKey{
  1098. {
  1099. Id: "eakID1",
  1100. Provisioner: "provName",
  1101. Reference: "some-external-key-reference",
  1102. CreatedAt: timestamppb.New(createdAt),
  1103. BoundAt: timestamppb.New(boundAt),
  1104. },
  1105. {
  1106. Id: "eakID2",
  1107. Provisioner: "provName",
  1108. Reference: "some-other-external-key-reference",
  1109. CreatedAt: timestamppb.New(createdAt.Add(1 * time.Hour)),
  1110. BoundAt: timestamppb.New(boundAt),
  1111. },
  1112. {
  1113. Id: "eakID3",
  1114. Provisioner: "provName",
  1115. Reference: "another-external-key-reference",
  1116. CreatedAt: timestamppb.New(createdAt),
  1117. BoundAt: timestamppb.New(boundAtSet),
  1118. Account: "accountID",
  1119. },
  1120. },
  1121. },
  1122. db: db,
  1123. err: nil,
  1124. }
  1125. },
  1126. }
  1127. for name, prep := range tests {
  1128. tc := prep(t)
  1129. t.Run(name, func(t *testing.T) {
  1130. h := &Handler{
  1131. acmeDB: tc.db,
  1132. }
  1133. req := tc.req.WithContext(tc.ctx)
  1134. w := httptest.NewRecorder()
  1135. h.GetExternalAccountKeys(w, req)
  1136. res := w.Result()
  1137. assert.Equals(t, tc.statusCode, res.StatusCode)
  1138. if res.StatusCode >= 400 {
  1139. body, err := io.ReadAll(res.Body)
  1140. res.Body.Close()
  1141. assert.FatalError(t, err)
  1142. adminErr := admin.Error{}
  1143. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &adminErr))
  1144. assert.Equals(t, tc.err.Type, adminErr.Type)
  1145. assert.Equals(t, tc.err.Message, adminErr.Message)
  1146. assert.Equals(t, tc.err.StatusCode(), res.StatusCode)
  1147. assert.Equals(t, tc.err.Detail, adminErr.Detail)
  1148. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  1149. return
  1150. }
  1151. body, err := io.ReadAll(res.Body)
  1152. res.Body.Close()
  1153. assert.FatalError(t, err)
  1154. response := GetExternalAccountKeysResponse{}
  1155. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &response))
  1156. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  1157. opts := []cmp.Option{cmpopts.IgnoreUnexported(linkedca.EABKey{}, timestamppb.Timestamp{})}
  1158. if !cmp.Equal(tc.resp, response, opts...) {
  1159. t.Errorf("h.GetExternalAccountKeys diff =\n%s", cmp.Diff(tc.resp, response, opts...))
  1160. }
  1161. })
  1162. }
  1163. }