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