admin_test.go 22 KB

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