admin_test.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919
  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. "github.com/smallstep/assert"
  16. "github.com/smallstep/certificates/authority/admin"
  17. "github.com/smallstep/certificates/authority/provisioner"
  18. "go.step.sm/linkedca"
  19. "google.golang.org/protobuf/types/known/timestamppb"
  20. )
  21. type mockAdminAuthority struct {
  22. MockLoadProvisionerByName func(name string) (provisioner.Interface, error)
  23. MockGetProvisioners func(nextCursor string, limit int) (provisioner.List, string, error)
  24. MockRet1, MockRet2 interface{} // TODO: refactor the ret1/ret2 into those two
  25. MockErr error
  26. MockIsAdminAPIEnabled func() bool
  27. MockLoadAdminByID func(id string) (*linkedca.Admin, bool)
  28. MockGetAdmins func(cursor string, limit int) ([]*linkedca.Admin, string, error)
  29. MockStoreAdmin func(ctx context.Context, adm *linkedca.Admin, prov provisioner.Interface) error
  30. MockUpdateAdmin func(ctx context.Context, id string, nu *linkedca.Admin) (*linkedca.Admin, error)
  31. MockRemoveAdmin func(ctx context.Context, id string) error
  32. MockAuthorizeAdminToken func(r *http.Request, token string) (*linkedca.Admin, error)
  33. MockStoreProvisioner func(ctx context.Context, prov *linkedca.Provisioner) error
  34. MockLoadProvisionerByID func(id string) (provisioner.Interface, error)
  35. MockUpdateProvisioner func(ctx context.Context, nu *linkedca.Provisioner) error
  36. MockRemoveProvisioner func(ctx context.Context, id string) error
  37. }
  38. func (m *mockAdminAuthority) IsAdminAPIEnabled() bool {
  39. if m.MockIsAdminAPIEnabled != nil {
  40. return m.MockIsAdminAPIEnabled()
  41. }
  42. return m.MockRet1.(bool)
  43. }
  44. func (m *mockAdminAuthority) LoadProvisionerByName(name string) (provisioner.Interface, error) {
  45. if m.MockLoadProvisionerByName != nil {
  46. return m.MockLoadProvisionerByName(name)
  47. }
  48. return m.MockRet1.(provisioner.Interface), m.MockErr
  49. }
  50. func (m *mockAdminAuthority) GetProvisioners(nextCursor string, limit int) (provisioner.List, string, error) {
  51. if m.MockGetProvisioners != nil {
  52. return m.MockGetProvisioners(nextCursor, limit)
  53. }
  54. return m.MockRet1.(provisioner.List), m.MockRet2.(string), m.MockErr
  55. }
  56. func (m *mockAdminAuthority) LoadAdminByID(id string) (*linkedca.Admin, bool) {
  57. if m.MockLoadAdminByID != nil {
  58. return m.MockLoadAdminByID(id)
  59. }
  60. return m.MockRet1.(*linkedca.Admin), m.MockRet2.(bool)
  61. }
  62. func (m *mockAdminAuthority) GetAdmins(cursor string, limit int) ([]*linkedca.Admin, string, error) {
  63. if m.MockGetAdmins != nil {
  64. return m.MockGetAdmins(cursor, limit)
  65. }
  66. return m.MockRet1.([]*linkedca.Admin), m.MockRet2.(string), m.MockErr
  67. }
  68. func (m *mockAdminAuthority) StoreAdmin(ctx context.Context, adm *linkedca.Admin, prov provisioner.Interface) error {
  69. if m.MockStoreAdmin != nil {
  70. return m.MockStoreAdmin(ctx, adm, prov)
  71. }
  72. return m.MockErr
  73. }
  74. func (m *mockAdminAuthority) UpdateAdmin(ctx context.Context, id string, nu *linkedca.Admin) (*linkedca.Admin, error) {
  75. if m.MockUpdateAdmin != nil {
  76. return m.MockUpdateAdmin(ctx, id, nu)
  77. }
  78. return m.MockRet1.(*linkedca.Admin), m.MockErr
  79. }
  80. func (m *mockAdminAuthority) RemoveAdmin(ctx context.Context, id string) error {
  81. if m.MockRemoveAdmin != nil {
  82. return m.MockRemoveAdmin(ctx, id)
  83. }
  84. return m.MockErr
  85. }
  86. func (m *mockAdminAuthority) AuthorizeAdminToken(r *http.Request, token string) (*linkedca.Admin, error) {
  87. if m.MockAuthorizeAdminToken != nil {
  88. return m.MockAuthorizeAdminToken(r, token)
  89. }
  90. return m.MockRet1.(*linkedca.Admin), m.MockErr
  91. }
  92. func (m *mockAdminAuthority) StoreProvisioner(ctx context.Context, prov *linkedca.Provisioner) error {
  93. if m.MockStoreProvisioner != nil {
  94. return m.MockStoreProvisioner(ctx, prov)
  95. }
  96. return m.MockErr
  97. }
  98. func (m *mockAdminAuthority) LoadProvisionerByID(id string) (provisioner.Interface, error) {
  99. if m.MockLoadProvisionerByID != nil {
  100. return m.MockLoadProvisionerByID(id)
  101. }
  102. return m.MockRet1.(provisioner.Interface), m.MockErr
  103. }
  104. func (m *mockAdminAuthority) UpdateProvisioner(ctx context.Context, nu *linkedca.Provisioner) error {
  105. if m.MockUpdateProvisioner != nil {
  106. return m.MockUpdateProvisioner(ctx, nu)
  107. }
  108. return m.MockErr
  109. }
  110. func (m *mockAdminAuthority) RemoveProvisioner(ctx context.Context, id string) error {
  111. if m.MockRemoveProvisioner != nil {
  112. return m.MockRemoveProvisioner(ctx, id)
  113. }
  114. return m.MockErr
  115. }
  116. func TestCreateAdminRequest_Validate(t *testing.T) {
  117. type fields struct {
  118. Subject string
  119. Provisioner string
  120. Type linkedca.Admin_Type
  121. }
  122. tests := []struct {
  123. name string
  124. fields fields
  125. err *admin.Error
  126. }{
  127. {
  128. name: "fail/subject-empty",
  129. fields: fields{
  130. Subject: "",
  131. Provisioner: "",
  132. Type: 0,
  133. },
  134. err: admin.NewError(admin.ErrorBadRequestType, "subject cannot be empty"),
  135. },
  136. {
  137. name: "fail/provisioner-empty",
  138. fields: fields{
  139. Subject: "admin",
  140. Provisioner: "",
  141. Type: 0,
  142. },
  143. err: admin.NewError(admin.ErrorBadRequestType, "provisioner cannot be empty"),
  144. },
  145. {
  146. name: "fail/invalid-type",
  147. fields: fields{
  148. Subject: "admin",
  149. Provisioner: "prov",
  150. Type: -1,
  151. },
  152. err: admin.NewError(admin.ErrorBadRequestType, "invalid value for admin type"),
  153. },
  154. {
  155. name: "ok",
  156. fields: fields{
  157. Subject: "admin",
  158. Provisioner: "prov",
  159. Type: linkedca.Admin_SUPER_ADMIN,
  160. },
  161. err: nil,
  162. },
  163. }
  164. for _, tt := range tests {
  165. t.Run(tt.name, func(t *testing.T) {
  166. car := &CreateAdminRequest{
  167. Subject: tt.fields.Subject,
  168. Provisioner: tt.fields.Provisioner,
  169. Type: tt.fields.Type,
  170. }
  171. err := car.Validate()
  172. if (err != nil) != (tt.err != nil) {
  173. t.Errorf("CreateAdminRequest.Validate() error = %v, wantErr %v", err, (tt.err != nil))
  174. return
  175. }
  176. if err != nil {
  177. assert.Type(t, &admin.Error{}, err)
  178. adminErr, _ := err.(*admin.Error)
  179. assert.Equals(t, tt.err.Type, adminErr.Type)
  180. assert.Equals(t, tt.err.Detail, adminErr.Detail)
  181. assert.Equals(t, tt.err.Status, adminErr.Status)
  182. assert.Equals(t, tt.err.Message, adminErr.Message)
  183. }
  184. })
  185. }
  186. }
  187. func TestUpdateAdminRequest_Validate(t *testing.T) {
  188. type fields struct {
  189. Type linkedca.Admin_Type
  190. }
  191. tests := []struct {
  192. name string
  193. fields fields
  194. err *admin.Error
  195. }{
  196. {
  197. name: "fail/invalid-type",
  198. fields: fields{
  199. Type: -1,
  200. },
  201. err: admin.NewError(admin.ErrorBadRequestType, "invalid value for admin type"),
  202. },
  203. {
  204. name: "ok",
  205. fields: fields{
  206. Type: linkedca.Admin_SUPER_ADMIN,
  207. },
  208. err: nil,
  209. },
  210. }
  211. for _, tt := range tests {
  212. t.Run(tt.name, func(t *testing.T) {
  213. uar := &UpdateAdminRequest{
  214. Type: tt.fields.Type,
  215. }
  216. err := uar.Validate()
  217. if (err != nil) != (tt.err != nil) {
  218. t.Errorf("CreateAdminRequest.Validate() error = %v, wantErr %v", err, (tt.err != nil))
  219. return
  220. }
  221. if err != nil {
  222. assert.Type(t, &admin.Error{}, err)
  223. adminErr, _ := err.(*admin.Error)
  224. assert.Equals(t, tt.err.Type, adminErr.Type)
  225. assert.Equals(t, tt.err.Detail, adminErr.Detail)
  226. assert.Equals(t, tt.err.Status, adminErr.Status)
  227. assert.Equals(t, tt.err.Message, adminErr.Message)
  228. }
  229. })
  230. }
  231. }
  232. func TestHandler_GetAdmin(t *testing.T) {
  233. type test struct {
  234. ctx context.Context
  235. auth adminAuthority
  236. statusCode int
  237. err *admin.Error
  238. adm *linkedca.Admin
  239. }
  240. var tests = map[string]func(t *testing.T) test{
  241. "fail/auth.LoadAdminByID-not-found": func(t *testing.T) test {
  242. chiCtx := chi.NewRouteContext()
  243. chiCtx.URLParams.Add("id", "adminID")
  244. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  245. auth := &mockAdminAuthority{
  246. MockLoadAdminByID: func(id string) (*linkedca.Admin, bool) {
  247. assert.Equals(t, "adminID", id)
  248. return nil, false
  249. },
  250. }
  251. return test{
  252. ctx: ctx,
  253. auth: auth,
  254. statusCode: 404,
  255. err: &admin.Error{
  256. Type: admin.ErrorNotFoundType.String(),
  257. Status: 404,
  258. Detail: "resource not found",
  259. Message: "admin adminID not found",
  260. },
  261. }
  262. },
  263. "ok": func(t *testing.T) test {
  264. chiCtx := chi.NewRouteContext()
  265. chiCtx.URLParams.Add("id", "adminID")
  266. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  267. createdAt := time.Now()
  268. var deletedAt time.Time
  269. adm := &linkedca.Admin{
  270. Id: "adminID",
  271. AuthorityId: "authorityID",
  272. Subject: "admin",
  273. ProvisionerId: "provID",
  274. Type: linkedca.Admin_SUPER_ADMIN,
  275. CreatedAt: timestamppb.New(createdAt),
  276. DeletedAt: timestamppb.New(deletedAt),
  277. }
  278. auth := &mockAdminAuthority{
  279. MockLoadAdminByID: func(id string) (*linkedca.Admin, bool) {
  280. assert.Equals(t, "adminID", id)
  281. return adm, true
  282. },
  283. }
  284. return test{
  285. ctx: ctx,
  286. auth: auth,
  287. statusCode: 200,
  288. err: nil,
  289. adm: adm,
  290. }
  291. },
  292. }
  293. for name, prep := range tests {
  294. tc := prep(t)
  295. t.Run(name, func(t *testing.T) {
  296. h := &Handler{
  297. auth: tc.auth,
  298. }
  299. req := httptest.NewRequest("GET", "/foo", nil) // chi routing is prepared in test setup
  300. req = req.WithContext(tc.ctx)
  301. w := httptest.NewRecorder()
  302. h.GetAdmin(w, req)
  303. res := w.Result()
  304. assert.Equals(t, tc.statusCode, res.StatusCode)
  305. if res.StatusCode >= 400 {
  306. body, err := io.ReadAll(res.Body)
  307. res.Body.Close()
  308. assert.FatalError(t, err)
  309. adminErr := admin.Error{}
  310. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &adminErr))
  311. assert.Equals(t, tc.err.Type, adminErr.Type)
  312. assert.Equals(t, tc.err.Message, adminErr.Message)
  313. assert.Equals(t, tc.err.Detail, adminErr.Detail)
  314. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  315. return
  316. }
  317. adm := &linkedca.Admin{}
  318. err := readProtoJSON(res.Body, adm)
  319. assert.FatalError(t, err)
  320. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  321. opts := []cmp.Option{cmpopts.IgnoreUnexported(linkedca.Admin{}, timestamppb.Timestamp{})}
  322. if !cmp.Equal(tc.adm, adm, opts...) {
  323. t.Errorf("linkedca.Admin diff =\n%s", cmp.Diff(tc.adm, adm, opts...))
  324. }
  325. })
  326. }
  327. }
  328. func TestHandler_GetAdmins(t *testing.T) {
  329. type test struct {
  330. ctx context.Context
  331. auth adminAuthority
  332. req *http.Request
  333. statusCode int
  334. err *admin.Error
  335. resp GetAdminsResponse
  336. }
  337. var tests = map[string]func(t *testing.T) test{
  338. "fail/parse-cursor": func(t *testing.T) test {
  339. req := httptest.NewRequest("GET", "/foo?limit=A", nil)
  340. return test{
  341. ctx: context.Background(),
  342. req: req,
  343. statusCode: 400,
  344. err: &admin.Error{
  345. Status: 400,
  346. Type: admin.ErrorBadRequestType.String(),
  347. Detail: "bad request",
  348. Message: "error parsing cursor and limit from query params: limit 'A' is not an integer: strconv.Atoi: parsing \"A\": invalid syntax",
  349. },
  350. }
  351. },
  352. "fail/auth.GetAdmins": func(t *testing.T) test {
  353. req := httptest.NewRequest("GET", "/foo", nil)
  354. auth := &mockAdminAuthority{
  355. MockGetAdmins: func(cursor string, limit int) ([]*linkedca.Admin, string, error) {
  356. assert.Equals(t, "", cursor)
  357. assert.Equals(t, 0, limit)
  358. return nil, "", errors.New("force")
  359. },
  360. }
  361. return test{
  362. ctx: context.Background(),
  363. req: req,
  364. auth: auth,
  365. statusCode: 500,
  366. err: &admin.Error{
  367. Status: 500,
  368. Type: admin.ErrorServerInternalType.String(),
  369. Detail: "the server experienced an internal error",
  370. Message: "error retrieving paginated admins: force",
  371. },
  372. }
  373. },
  374. "ok": func(t *testing.T) test {
  375. req := httptest.NewRequest("GET", "/foo", nil)
  376. createdAt := time.Now()
  377. var deletedAt time.Time
  378. adm1 := &linkedca.Admin{
  379. Id: "adminID1",
  380. AuthorityId: "authorityID1",
  381. Subject: "admin1",
  382. ProvisionerId: "provID",
  383. Type: linkedca.Admin_SUPER_ADMIN,
  384. CreatedAt: timestamppb.New(createdAt),
  385. DeletedAt: timestamppb.New(deletedAt),
  386. }
  387. adm2 := &linkedca.Admin{
  388. Id: "adminID2",
  389. AuthorityId: "authorityID",
  390. Subject: "admin2",
  391. ProvisionerId: "provID",
  392. Type: linkedca.Admin_ADMIN,
  393. CreatedAt: timestamppb.New(createdAt),
  394. DeletedAt: timestamppb.New(deletedAt),
  395. }
  396. auth := &mockAdminAuthority{
  397. MockGetAdmins: func(cursor string, limit int) ([]*linkedca.Admin, string, error) {
  398. assert.Equals(t, "", cursor)
  399. assert.Equals(t, 0, limit)
  400. return []*linkedca.Admin{
  401. adm1,
  402. adm2,
  403. }, "nextCursorValue", nil
  404. },
  405. }
  406. return test{
  407. ctx: context.Background(),
  408. req: req,
  409. auth: auth,
  410. statusCode: 200,
  411. err: nil,
  412. resp: GetAdminsResponse{
  413. Admins: []*linkedca.Admin{
  414. adm1,
  415. adm2,
  416. },
  417. NextCursor: "nextCursorValue",
  418. },
  419. }
  420. },
  421. }
  422. for name, prep := range tests {
  423. tc := prep(t)
  424. t.Run(name, func(t *testing.T) {
  425. h := &Handler{
  426. auth: tc.auth,
  427. }
  428. req := tc.req.WithContext(tc.ctx)
  429. w := httptest.NewRecorder()
  430. h.GetAdmins(w, req)
  431. res := w.Result()
  432. assert.Equals(t, tc.statusCode, res.StatusCode)
  433. body, err := io.ReadAll(res.Body)
  434. res.Body.Close()
  435. assert.FatalError(t, err)
  436. if res.StatusCode >= 400 {
  437. adminErr := admin.Error{}
  438. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &adminErr))
  439. assert.Equals(t, tc.err.Type, adminErr.Type)
  440. assert.Equals(t, tc.err.Message, adminErr.Message)
  441. assert.Equals(t, tc.err.Detail, adminErr.Detail)
  442. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  443. return
  444. }
  445. response := GetAdminsResponse{}
  446. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &response))
  447. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  448. opts := []cmp.Option{cmpopts.IgnoreUnexported(linkedca.Admin{}, timestamppb.Timestamp{})}
  449. if !cmp.Equal(tc.resp, response, opts...) {
  450. t.Errorf("GetAdmins diff =\n%s", cmp.Diff(tc.resp, response, opts...))
  451. }
  452. })
  453. }
  454. }
  455. func TestHandler_CreateAdmin(t *testing.T) {
  456. type test struct {
  457. ctx context.Context
  458. auth adminAuthority
  459. body []byte
  460. statusCode int
  461. err *admin.Error
  462. adm *linkedca.Admin
  463. }
  464. var tests = map[string]func(t *testing.T) test{
  465. "fail/ReadJSON": func(t *testing.T) test {
  466. body := []byte("{!?}")
  467. return test{
  468. ctx: context.Background(),
  469. body: body,
  470. statusCode: 400,
  471. err: &admin.Error{
  472. Type: admin.ErrorBadRequestType.String(),
  473. Status: 400,
  474. Detail: "bad request",
  475. Message: "error reading request body: error decoding json: invalid character '!' looking for beginning of object key string",
  476. },
  477. }
  478. },
  479. "fail/validate": func(t *testing.T) test {
  480. req := CreateAdminRequest{
  481. Subject: "",
  482. Provisioner: "",
  483. Type: -1,
  484. }
  485. body, err := json.Marshal(req)
  486. assert.FatalError(t, err)
  487. return test{
  488. ctx: context.Background(),
  489. body: body,
  490. statusCode: 400,
  491. err: &admin.Error{
  492. Type: admin.ErrorBadRequestType.String(),
  493. Status: 400,
  494. Detail: "bad request",
  495. Message: "subject cannot be empty",
  496. },
  497. }
  498. },
  499. "fail/auth.LoadProvisionerByName": func(t *testing.T) test {
  500. req := CreateAdminRequest{
  501. Subject: "admin",
  502. Provisioner: "prov",
  503. Type: linkedca.Admin_SUPER_ADMIN,
  504. }
  505. body, err := json.Marshal(req)
  506. assert.FatalError(t, err)
  507. auth := &mockAdminAuthority{
  508. MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
  509. assert.Equals(t, "prov", name)
  510. return nil, errors.New("force")
  511. },
  512. }
  513. return test{
  514. ctx: context.Background(),
  515. body: body,
  516. auth: auth,
  517. statusCode: 500,
  518. err: &admin.Error{
  519. Type: admin.ErrorServerInternalType.String(),
  520. Status: 500,
  521. Detail: "the server experienced an internal error",
  522. Message: "error loading provisioner prov: force",
  523. },
  524. }
  525. },
  526. "fail/auth.StoreAdmin": func(t *testing.T) test {
  527. req := CreateAdminRequest{
  528. Subject: "admin",
  529. Provisioner: "prov",
  530. Type: linkedca.Admin_SUPER_ADMIN,
  531. }
  532. body, err := json.Marshal(req)
  533. assert.FatalError(t, err)
  534. auth := &mockAdminAuthority{
  535. MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
  536. assert.Equals(t, "prov", name)
  537. return &provisioner.ACME{
  538. ID: "provID",
  539. Name: "prov",
  540. }, nil
  541. },
  542. MockStoreAdmin: func(ctx context.Context, adm *linkedca.Admin, prov provisioner.Interface) error {
  543. assert.Equals(t, "admin", adm.Subject)
  544. assert.Equals(t, "provID", prov.GetID())
  545. return errors.New("force")
  546. },
  547. }
  548. return test{
  549. ctx: context.Background(),
  550. body: body,
  551. auth: auth,
  552. statusCode: 500,
  553. err: &admin.Error{
  554. Type: admin.ErrorServerInternalType.String(),
  555. Status: 500,
  556. Detail: "the server experienced an internal error",
  557. Message: "error storing admin: force",
  558. },
  559. }
  560. },
  561. "ok": func(t *testing.T) test {
  562. req := CreateAdminRequest{
  563. Subject: "admin",
  564. Provisioner: "prov",
  565. Type: linkedca.Admin_SUPER_ADMIN,
  566. }
  567. body, err := json.Marshal(req)
  568. assert.FatalError(t, err)
  569. auth := &mockAdminAuthority{
  570. MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
  571. assert.Equals(t, "prov", name)
  572. return &provisioner.ACME{
  573. ID: "provID",
  574. Name: "prov",
  575. }, nil
  576. },
  577. MockStoreAdmin: func(ctx context.Context, adm *linkedca.Admin, prov provisioner.Interface) error {
  578. assert.Equals(t, "admin", adm.Subject)
  579. assert.Equals(t, "provID", prov.GetID())
  580. return nil
  581. },
  582. }
  583. return test{
  584. ctx: context.Background(),
  585. body: body,
  586. auth: auth,
  587. statusCode: 201,
  588. err: nil,
  589. adm: &linkedca.Admin{
  590. ProvisionerId: "provID",
  591. Subject: "admin",
  592. Type: linkedca.Admin_SUPER_ADMIN,
  593. },
  594. }
  595. },
  596. }
  597. for name, prep := range tests {
  598. tc := prep(t)
  599. t.Run(name, func(t *testing.T) {
  600. h := &Handler{
  601. auth: tc.auth,
  602. }
  603. req := httptest.NewRequest("GET", "/foo", io.NopCloser(bytes.NewBuffer(tc.body)))
  604. req = req.WithContext(tc.ctx)
  605. w := httptest.NewRecorder()
  606. h.CreateAdmin(w, req)
  607. res := w.Result()
  608. assert.Equals(t, tc.statusCode, res.StatusCode)
  609. if res.StatusCode >= 400 {
  610. body, err := io.ReadAll(res.Body)
  611. res.Body.Close()
  612. assert.FatalError(t, err)
  613. adminErr := admin.Error{}
  614. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &adminErr))
  615. assert.Equals(t, tc.err.Type, adminErr.Type)
  616. assert.Equals(t, tc.err.Message, adminErr.Message)
  617. assert.Equals(t, tc.err.Detail, adminErr.Detail)
  618. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  619. return
  620. }
  621. adm := &linkedca.Admin{}
  622. err := readProtoJSON(res.Body, adm)
  623. assert.FatalError(t, err)
  624. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  625. opts := []cmp.Option{cmpopts.IgnoreUnexported(linkedca.Admin{}, timestamppb.Timestamp{})}
  626. if !cmp.Equal(tc.adm, adm, opts...) {
  627. t.Errorf("h.CreateAdmin diff =\n%s", cmp.Diff(tc.adm, adm, opts...))
  628. }
  629. })
  630. }
  631. }
  632. func TestHandler_DeleteAdmin(t *testing.T) {
  633. type test struct {
  634. ctx context.Context
  635. auth adminAuthority
  636. statusCode int
  637. err *admin.Error
  638. }
  639. var tests = map[string]func(t *testing.T) test{
  640. "fail/auth.RemoveAdmin": func(t *testing.T) test {
  641. chiCtx := chi.NewRouteContext()
  642. chiCtx.URLParams.Add("id", "adminID")
  643. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  644. auth := &mockAdminAuthority{
  645. MockRemoveAdmin: func(ctx context.Context, id string) error {
  646. assert.Equals(t, "adminID", id)
  647. return errors.New("force")
  648. },
  649. }
  650. return test{
  651. ctx: ctx,
  652. auth: auth,
  653. statusCode: 500,
  654. err: &admin.Error{
  655. Type: admin.ErrorServerInternalType.String(),
  656. Status: 500,
  657. Detail: "the server experienced an internal error",
  658. Message: "error deleting admin adminID: force",
  659. },
  660. }
  661. },
  662. "ok": func(t *testing.T) test {
  663. chiCtx := chi.NewRouteContext()
  664. chiCtx.URLParams.Add("id", "adminID")
  665. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  666. auth := &mockAdminAuthority{
  667. MockRemoveAdmin: func(ctx context.Context, id string) error {
  668. assert.Equals(t, "adminID", id)
  669. return nil
  670. },
  671. }
  672. return test{
  673. ctx: ctx,
  674. auth: auth,
  675. statusCode: 200,
  676. err: nil,
  677. }
  678. },
  679. }
  680. for name, prep := range tests {
  681. tc := prep(t)
  682. t.Run(name, func(t *testing.T) {
  683. h := &Handler{
  684. auth: tc.auth,
  685. }
  686. req := httptest.NewRequest("DELETE", "/foo", nil) // chi routing is prepared in test setup
  687. req = req.WithContext(tc.ctx)
  688. w := httptest.NewRecorder()
  689. h.DeleteAdmin(w, req)
  690. res := w.Result()
  691. assert.Equals(t, tc.statusCode, res.StatusCode)
  692. if res.StatusCode >= 400 {
  693. body, err := io.ReadAll(res.Body)
  694. res.Body.Close()
  695. assert.FatalError(t, err)
  696. adminErr := admin.Error{}
  697. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &adminErr))
  698. assert.Equals(t, tc.err.Type, adminErr.Type)
  699. assert.Equals(t, tc.err.Message, adminErr.Message)
  700. assert.Equals(t, tc.err.StatusCode(), res.StatusCode)
  701. assert.Equals(t, tc.err.Detail, adminErr.Detail)
  702. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  703. return
  704. }
  705. body, err := io.ReadAll(res.Body)
  706. res.Body.Close()
  707. assert.FatalError(t, err)
  708. response := DeleteResponse{}
  709. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &response))
  710. assert.Equals(t, "ok", response.Status)
  711. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  712. })
  713. }
  714. }
  715. func TestHandler_UpdateAdmin(t *testing.T) {
  716. type test struct {
  717. ctx context.Context
  718. auth adminAuthority
  719. body []byte
  720. statusCode int
  721. err *admin.Error
  722. adm *linkedca.Admin
  723. }
  724. var tests = map[string]func(t *testing.T) test{
  725. "fail/ReadJSON": func(t *testing.T) test {
  726. body := []byte("{!?}")
  727. return test{
  728. ctx: context.Background(),
  729. body: body,
  730. statusCode: 400,
  731. err: &admin.Error{
  732. Type: admin.ErrorBadRequestType.String(),
  733. Status: 400,
  734. Detail: "bad request",
  735. Message: "error reading request body: error decoding json: invalid character '!' looking for beginning of object key string",
  736. },
  737. }
  738. },
  739. "fail/validate": func(t *testing.T) test {
  740. req := UpdateAdminRequest{
  741. Type: -1,
  742. }
  743. body, err := json.Marshal(req)
  744. assert.FatalError(t, err)
  745. return test{
  746. ctx: context.Background(),
  747. body: body,
  748. statusCode: 400,
  749. err: &admin.Error{
  750. Type: admin.ErrorBadRequestType.String(),
  751. Status: 400,
  752. Detail: "bad request",
  753. Message: "invalid value for admin type",
  754. },
  755. }
  756. },
  757. "fail/auth.UpdateAdmin": func(t *testing.T) test {
  758. req := UpdateAdminRequest{
  759. Type: linkedca.Admin_ADMIN,
  760. }
  761. body, err := json.Marshal(req)
  762. assert.FatalError(t, err)
  763. chiCtx := chi.NewRouteContext()
  764. chiCtx.URLParams.Add("id", "adminID")
  765. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  766. auth := &mockAdminAuthority{
  767. MockUpdateAdmin: func(ctx context.Context, id string, nu *linkedca.Admin) (*linkedca.Admin, error) {
  768. assert.Equals(t, "adminID", id)
  769. assert.Equals(t, linkedca.Admin_ADMIN, nu.Type)
  770. return nil, errors.New("force")
  771. },
  772. }
  773. return test{
  774. ctx: ctx,
  775. body: body,
  776. auth: auth,
  777. statusCode: 500,
  778. err: &admin.Error{
  779. Type: admin.ErrorServerInternalType.String(),
  780. Status: 500,
  781. Detail: "the server experienced an internal error",
  782. Message: "error updating admin adminID: force",
  783. },
  784. }
  785. },
  786. "ok": func(t *testing.T) test {
  787. req := UpdateAdminRequest{
  788. Type: linkedca.Admin_ADMIN,
  789. }
  790. body, err := json.Marshal(req)
  791. assert.FatalError(t, err)
  792. chiCtx := chi.NewRouteContext()
  793. chiCtx.URLParams.Add("id", "adminID")
  794. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  795. adm := &linkedca.Admin{
  796. Id: "adminID",
  797. ProvisionerId: "provID",
  798. Subject: "admin",
  799. Type: linkedca.Admin_SUPER_ADMIN,
  800. }
  801. auth := &mockAdminAuthority{
  802. MockUpdateAdmin: func(ctx context.Context, id string, nu *linkedca.Admin) (*linkedca.Admin, error) {
  803. assert.Equals(t, "adminID", id)
  804. assert.Equals(t, linkedca.Admin_ADMIN, nu.Type)
  805. return adm, nil
  806. },
  807. }
  808. return test{
  809. ctx: ctx,
  810. body: body,
  811. auth: auth,
  812. statusCode: 200,
  813. err: nil,
  814. adm: adm,
  815. }
  816. },
  817. }
  818. for name, prep := range tests {
  819. tc := prep(t)
  820. t.Run(name, func(t *testing.T) {
  821. h := &Handler{
  822. auth: tc.auth,
  823. }
  824. req := httptest.NewRequest("GET", "/foo", io.NopCloser(bytes.NewBuffer(tc.body)))
  825. req = req.WithContext(tc.ctx)
  826. w := httptest.NewRecorder()
  827. h.UpdateAdmin(w, req)
  828. res := w.Result()
  829. assert.Equals(t, tc.statusCode, res.StatusCode)
  830. if res.StatusCode >= 400 {
  831. body, err := io.ReadAll(res.Body)
  832. res.Body.Close()
  833. assert.FatalError(t, err)
  834. adminErr := admin.Error{}
  835. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &adminErr))
  836. assert.Equals(t, tc.err.Type, adminErr.Type)
  837. assert.Equals(t, tc.err.Message, adminErr.Message)
  838. assert.Equals(t, tc.err.Detail, adminErr.Detail)
  839. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  840. return
  841. }
  842. adm := &linkedca.Admin{}
  843. err := readProtoJSON(res.Body, adm)
  844. assert.FatalError(t, err)
  845. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  846. opts := []cmp.Option{cmpopts.IgnoreUnexported(linkedca.Admin{}, timestamppb.Timestamp{})}
  847. if !cmp.Equal(tc.adm, adm, opts...) {
  848. t.Errorf("h.UpdateAdmin diff =\n%s", cmp.Diff(tc.adm, adm, opts...))
  849. }
  850. })
  851. }
  852. }