| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306 |
- package api
- import (
- "bytes"
- "context"
- "encoding/json"
- "errors"
- "io"
- "net/http"
- "net/http/httptest"
- "strings"
- "testing"
- "time"
- "github.com/go-chi/chi"
- "github.com/google/go-cmp/cmp"
- "github.com/google/go-cmp/cmp/cmpopts"
- "google.golang.org/protobuf/encoding/protojson"
- "google.golang.org/protobuf/types/known/timestamppb"
- "github.com/smallstep/assert"
- "go.step.sm/linkedca"
- "github.com/smallstep/certificates/authority/admin"
- "github.com/smallstep/certificates/authority/provisioner"
- )
- func TestHandler_GetProvisioner(t *testing.T) {
- type test struct {
- ctx context.Context
- auth adminAuthority
- adminDB admin.DB
- req *http.Request
- statusCode int
- err *admin.Error
- prov *linkedca.Provisioner
- }
- var tests = map[string]func(t *testing.T) test{
- "fail/auth.LoadProvisionerByID": func(t *testing.T) test {
- req := httptest.NewRequest("GET", "/foo?id=provID", nil)
- chiCtx := chi.NewRouteContext()
- ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
- auth := &mockAdminAuthority{
- MockLoadProvisionerByID: func(id string) (provisioner.Interface, error) {
- assert.Equals(t, "provID", id)
- return nil, errors.New("force")
- },
- }
- return test{
- ctx: ctx,
- req: req,
- auth: auth,
- adminDB: &admin.MockDB{},
- statusCode: 500,
- err: &admin.Error{
- Type: admin.ErrorServerInternalType.String(),
- Status: 500,
- Detail: "the server experienced an internal error",
- Message: "error loading provisioner provID: force",
- },
- }
- },
- "fail/auth.LoadProvisionerByName": func(t *testing.T) test {
- req := httptest.NewRequest("GET", "/foo", nil)
- chiCtx := chi.NewRouteContext()
- chiCtx.URLParams.Add("name", "provName")
- ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
- auth := &mockAdminAuthority{
- MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
- assert.Equals(t, "provName", name)
- return nil, errors.New("force")
- },
- }
- return test{
- ctx: ctx,
- req: req,
- auth: auth,
- adminDB: &admin.MockDB{},
- statusCode: 500,
- err: &admin.Error{
- Type: admin.ErrorServerInternalType.String(),
- Status: 500,
- Detail: "the server experienced an internal error",
- Message: "error loading provisioner provName: force",
- },
- }
- },
- "fail/db.GetProvisioner": func(t *testing.T) test {
- req := httptest.NewRequest("GET", "/foo", nil)
- chiCtx := chi.NewRouteContext()
- chiCtx.URLParams.Add("name", "provName")
- ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
- auth := &mockAdminAuthority{
- MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
- assert.Equals(t, "provName", name)
- return &provisioner.ACME{
- ID: "acmeID",
- Name: "provName",
- }, nil
- },
- }
- db := &admin.MockDB{
- MockGetProvisioner: func(ctx context.Context, id string) (*linkedca.Provisioner, error) {
- assert.Equals(t, "acmeID", id)
- return nil, admin.NewErrorISE("error loading provisioner provName: force")
- },
- }
- return test{
- ctx: ctx,
- req: req,
- auth: auth,
- adminDB: db,
- statusCode: 500,
- err: &admin.Error{
- Type: admin.ErrorServerInternalType.String(),
- Status: 500,
- Detail: "the server experienced an internal error",
- Message: "error loading provisioner provName: force",
- },
- }
- },
- "ok": func(t *testing.T) test {
- req := httptest.NewRequest("GET", "/foo", nil)
- chiCtx := chi.NewRouteContext()
- chiCtx.URLParams.Add("name", "provName")
- ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
- auth := &mockAdminAuthority{
- MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
- assert.Equals(t, "provName", name)
- return &provisioner.ACME{
- ID: "acmeID",
- Name: "provName",
- }, nil
- },
- }
- prov := &linkedca.Provisioner{
- Id: "acmeID",
- Type: linkedca.Provisioner_ACME,
- Name: "provName", // TODO(hs): other fields too?
- }
- db := &admin.MockDB{
- MockGetProvisioner: func(ctx context.Context, id string) (*linkedca.Provisioner, error) {
- assert.Equals(t, "acmeID", id)
- return prov, nil
- },
- }
- return test{
- ctx: ctx,
- req: req,
- auth: auth,
- adminDB: db,
- statusCode: 200,
- err: nil,
- prov: prov,
- }
- },
- }
- for name, prep := range tests {
- tc := prep(t)
- t.Run(name, func(t *testing.T) {
- mockMustAuthority(t, tc.auth)
- ctx := admin.NewContext(tc.ctx, tc.adminDB)
- req := tc.req.WithContext(ctx)
- w := httptest.NewRecorder()
- GetProvisioner(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
- }
- prov := &linkedca.Provisioner{}
- err := readProtoJSON(res.Body, prov)
- assert.FatalError(t, err)
- assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
- opts := []cmp.Option{cmpopts.IgnoreUnexported(linkedca.Provisioner{}, timestamppb.Timestamp{})}
- if !cmp.Equal(tc.prov, prov, opts...) {
- t.Errorf("h.GetProvisioner diff =\n%s", cmp.Diff(tc.prov, prov, opts...))
- }
- })
- }
- }
- func TestHandler_GetProvisioners(t *testing.T) {
- type test struct {
- ctx context.Context
- auth adminAuthority
- req *http.Request
- statusCode int
- err *admin.Error
- resp GetProvisionersResponse
- }
- var tests = map[string]func(t *testing.T) test{
- "fail/parse-cursor": func(t *testing.T) test {
- req := httptest.NewRequest("GET", "/foo?limit=X", nil)
- return test{
- ctx: context.Background(),
- statusCode: 400,
- req: req,
- err: &admin.Error{
- Status: 400,
- Type: admin.ErrorBadRequestType.String(),
- Detail: "bad request",
- Message: "error parsing cursor and limit from query params: limit 'X' is not an integer: strconv.Atoi: parsing \"X\": invalid syntax",
- },
- }
- },
- "fail/auth.GetProvisioners": func(t *testing.T) test {
- req := httptest.NewRequest("GET", "/foo", nil)
- auth := &mockAdminAuthority{
- MockGetProvisioners: func(cursor string, limit int) (provisioner.List, 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{
- Type: "",
- Status: 500,
- Detail: "",
- Message: "The certificate authority encountered an Internal Server Error. Please see the certificate authority logs for more info.",
- },
- }
- },
- "ok": func(t *testing.T) test {
- req := httptest.NewRequest("GET", "/foo", nil)
- provisioners := provisioner.List{
- &provisioner.OIDC{
- Type: "OIDC",
- Name: "oidcProv",
- },
- &provisioner.ACME{
- Type: "ACME",
- Name: "provName",
- ForceCN: false,
- RequireEAB: false,
- },
- }
- auth := &mockAdminAuthority{
- MockGetProvisioners: func(cursor string, limit int) (provisioner.List, string, error) {
- assert.Equals(t, "", cursor)
- assert.Equals(t, 0, limit)
- return provisioners, "nextCursorValue", nil
- },
- }
- return test{
- ctx: context.Background(),
- req: req,
- auth: auth,
- statusCode: 200,
- err: nil,
- resp: GetProvisionersResponse{
- Provisioners: provisioners,
- 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()
- GetProvisioners(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
- }
- body, err := io.ReadAll(res.Body)
- res.Body.Close()
- assert.FatalError(t, err)
- response := GetProvisionersResponse{}
- assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &response))
- assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
- opts := []cmp.Option{cmpopts.IgnoreUnexported(provisioner.ACME{}, provisioner.OIDC{})}
- if !cmp.Equal(tc.resp, response, opts...) {
- t.Errorf("h.GetProvisioners diff =\n%s", cmp.Diff(tc.resp, response, opts...))
- }
- })
- }
- }
- func TestHandler_CreateProvisioner(t *testing.T) {
- type test struct {
- ctx context.Context
- auth adminAuthority
- body []byte
- statusCode int
- err *admin.Error
- prov *linkedca.Provisioner
- }
- var tests = map[string]func(t *testing.T) test{
- "fail/readProtoJSON": func(t *testing.T) test {
- body := []byte("{!?}")
- return test{
- ctx: context.Background(),
- body: body,
- statusCode: 400,
- err: &admin.Error{
- Type: "badRequest",
- Status: 400,
- Detail: "bad request",
- Message: "proto: syntax error (line 1:2): invalid value !",
- },
- }
- },
- // TODO(hs): ValidateClaims can't be mocked atm
- // "fail/authority.ValidateClaims": func(t *testing.T) test {
- // return test{}
- // },
- "fail/validateTemplates": func(t *testing.T) test {
- prov := &linkedca.Provisioner{
- Id: "provID",
- Type: linkedca.Provisioner_OIDC,
- Name: "provName",
- X509Template: &linkedca.Template{
- Template: []byte(`{ {{missingFunction "foo"}} }`),
- },
- }
- body, err := protojson.Marshal(prov)
- assert.FatalError(t, err)
- return test{
- ctx: context.Background(),
- body: body,
- statusCode: 400,
- err: &admin.Error{
- Type: "badRequest",
- Status: 400,
- Detail: "bad request",
- Message: "invalid template: invalid X.509 template: error parsing template: template: template:1: function \"missingFunction\" not defined",
- },
- }
- },
- "fail/auth.StoreProvisioner": func(t *testing.T) test {
- prov := &linkedca.Provisioner{
- Id: "provID",
- Type: linkedca.Provisioner_OIDC,
- Name: "provName",
- }
- body, err := protojson.Marshal(prov)
- assert.FatalError(t, err)
- auth := &mockAdminAuthority{
- MockStoreProvisioner: func(ctx context.Context, prov *linkedca.Provisioner) error {
- assert.Equals(t, "provID", prov.Id)
- 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 provisioner provName: force",
- },
- }
- },
- "ok": func(t *testing.T) test {
- prov := &linkedca.Provisioner{
- Id: "provID",
- Type: linkedca.Provisioner_OIDC,
- Name: "provName",
- }
- body, err := protojson.Marshal(prov)
- assert.FatalError(t, err)
- auth := &mockAdminAuthority{
- MockStoreProvisioner: func(ctx context.Context, prov *linkedca.Provisioner) error {
- assert.Equals(t, "provID", prov.Id)
- return nil
- },
- }
- return test{
- ctx: context.Background(),
- body: body,
- auth: auth,
- statusCode: 201,
- err: nil,
- prov: prov,
- }
- },
- }
- for name, prep := range tests {
- tc := prep(t)
- t.Run(name, func(t *testing.T) {
- mockMustAuthority(t, tc.auth)
- req := httptest.NewRequest("POST", "/foo", io.NopCloser(bytes.NewBuffer(tc.body)))
- req = req.WithContext(tc.ctx)
- w := httptest.NewRecorder()
- CreateProvisioner(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.Detail, adminErr.Detail)
- assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
- if strings.HasPrefix(tc.err.Message, "proto:") {
- assert.True(t, strings.Contains(adminErr.Message, "syntax error"))
- } else {
- assert.Equals(t, tc.err.Message, adminErr.Message)
- }
- return
- }
- prov := &linkedca.Provisioner{}
- err := readProtoJSON(res.Body, prov)
- assert.FatalError(t, err)
- assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
- opts := []cmp.Option{cmpopts.IgnoreUnexported(linkedca.Provisioner{}, timestamppb.Timestamp{})}
- if !cmp.Equal(tc.prov, prov, opts...) {
- t.Errorf("linkedca.Admin diff =\n%s", cmp.Diff(tc.prov, prov, opts...))
- }
- })
- }
- }
- func TestHandler_DeleteProvisioner(t *testing.T) {
- type test struct {
- ctx context.Context
- auth adminAuthority
- req *http.Request
- statusCode int
- err *admin.Error
- }
- var tests = map[string]func(t *testing.T) test{
- "fail/auth.LoadProvisionerByID": func(t *testing.T) test {
- req := httptest.NewRequest("DELETE", "/foo?id=provID", nil)
- chiCtx := chi.NewRouteContext()
- ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
- auth := &mockAdminAuthority{
- MockLoadProvisionerByID: func(id string) (provisioner.Interface, error) {
- assert.Equals(t, "provID", id)
- return nil, errors.New("force")
- },
- }
- return test{
- ctx: ctx,
- req: req,
- auth: auth,
- statusCode: 500,
- err: &admin.Error{
- Type: admin.ErrorServerInternalType.String(),
- Status: 500,
- Detail: "the server experienced an internal error",
- Message: "error loading provisioner provID: force",
- },
- }
- },
- "fail/auth.LoadProvisionerByName": func(t *testing.T) test {
- req := httptest.NewRequest("DELETE", "/foo", nil)
- chiCtx := chi.NewRouteContext()
- chiCtx.URLParams.Add("name", "provName")
- ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
- auth := &mockAdminAuthority{
- MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
- assert.Equals(t, "provName", name)
- return nil, errors.New("force")
- },
- }
- return test{
- ctx: ctx,
- req: req,
- auth: auth,
- statusCode: 500,
- err: &admin.Error{
- Type: admin.ErrorServerInternalType.String(),
- Status: 500,
- Detail: "the server experienced an internal error",
- Message: "error loading provisioner provName: force",
- },
- }
- },
- "fail/auth.RemoveProvisioner": func(t *testing.T) test {
- req := httptest.NewRequest("DELETE", "/foo", nil)
- chiCtx := chi.NewRouteContext()
- chiCtx.URLParams.Add("name", "provName")
- ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
- auth := &mockAdminAuthority{
- MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
- assert.Equals(t, "provName", name)
- return &provisioner.OIDC{
- ID: "provID",
- Name: "provName",
- Type: "OIDC",
- }, nil
- },
- MockRemoveProvisioner: func(ctx context.Context, id string) error {
- assert.Equals(t, "provID", id)
- return errors.New("force")
- },
- }
- return test{
- ctx: ctx,
- req: req,
- auth: auth,
- statusCode: 500,
- err: &admin.Error{
- Type: admin.ErrorServerInternalType.String(),
- Status: 500,
- Detail: "the server experienced an internal error",
- Message: "error removing provisioner provName: force",
- },
- }
- },
- "ok": func(t *testing.T) test {
- req := httptest.NewRequest("DELETE", "/foo", nil)
- chiCtx := chi.NewRouteContext()
- chiCtx.URLParams.Add("name", "provName")
- ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
- auth := &mockAdminAuthority{
- MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
- assert.Equals(t, "provName", name)
- return &provisioner.OIDC{
- ID: "provID",
- Name: "provName",
- Type: "OIDC",
- }, nil
- },
- MockRemoveProvisioner: func(ctx context.Context, id string) error {
- assert.Equals(t, "provID", id)
- return nil
- },
- }
- return test{
- ctx: ctx,
- req: req,
- 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 := tc.req.WithContext(tc.ctx)
- w := httptest.NewRecorder()
- DeleteProvisioner(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
- }
- 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_UpdateProvisioner(t *testing.T) {
- type test struct {
- ctx context.Context
- auth adminAuthority
- body []byte
- adminDB admin.DB
- statusCode int
- err *admin.Error
- prov *linkedca.Provisioner
- }
- var tests = map[string]func(t *testing.T) test{
- "fail/readProtoJSON": func(t *testing.T) test {
- body := []byte("{!?}")
- return test{
- ctx: context.Background(),
- body: body,
- adminDB: &admin.MockDB{},
- statusCode: 400,
- err: &admin.Error{
- Type: "badRequest",
- Status: 400,
- Detail: "bad request",
- Message: "proto: syntax error (line 1:2): invalid value !",
- },
- }
- },
- "fail/auth.LoadProvisionerByName": func(t *testing.T) test {
- chiCtx := chi.NewRouteContext()
- chiCtx.URLParams.Add("name", "provName")
- ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
- prov := &linkedca.Provisioner{
- Id: "provID",
- Type: linkedca.Provisioner_OIDC,
- Name: "provName",
- }
- body, err := protojson.Marshal(prov)
- assert.FatalError(t, err)
- auth := &mockAdminAuthority{
- MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
- assert.Equals(t, "provName", name)
- return nil, errors.New("force")
- },
- }
- return test{
- ctx: ctx,
- body: body,
- adminDB: &admin.MockDB{},
- auth: auth,
- statusCode: 500,
- err: &admin.Error{
- Type: admin.ErrorServerInternalType.String(),
- Status: 500,
- Detail: "the server experienced an internal error",
- Message: "error loading provisioner from cached configuration 'provName': force",
- },
- }
- },
- "fail/db.GetProvisioner": func(t *testing.T) test {
- chiCtx := chi.NewRouteContext()
- chiCtx.URLParams.Add("name", "provName")
- ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
- prov := &linkedca.Provisioner{
- Id: "provID",
- Type: linkedca.Provisioner_OIDC,
- Name: "provName",
- }
- body, err := protojson.Marshal(prov)
- assert.FatalError(t, err)
- auth := &mockAdminAuthority{
- MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
- assert.Equals(t, "provName", name)
- return &provisioner.OIDC{
- ID: "provID",
- Name: "provName",
- }, nil
- },
- }
- db := &admin.MockDB{
- MockGetProvisioner: func(ctx context.Context, id string) (*linkedca.Provisioner, error) {
- assert.Equals(t, "provID", id)
- return nil, errors.New("force")
- },
- }
- return test{
- ctx: ctx,
- body: body,
- auth: auth,
- adminDB: db,
- statusCode: 500,
- err: &admin.Error{
- Type: admin.ErrorServerInternalType.String(),
- Status: 500,
- Detail: "the server experienced an internal error",
- Message: "error loading provisioner from db 'provID': force",
- },
- }
- },
- "fail/change-id-error": func(t *testing.T) test {
- chiCtx := chi.NewRouteContext()
- chiCtx.URLParams.Add("name", "provName")
- ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
- prov := &linkedca.Provisioner{
- Id: "differentProvID",
- Type: linkedca.Provisioner_OIDC,
- Name: "provName",
- }
- body, err := protojson.Marshal(prov)
- assert.FatalError(t, err)
- auth := &mockAdminAuthority{
- MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
- assert.Equals(t, "provName", name)
- return &provisioner.OIDC{
- ID: "provID",
- Name: "provName",
- }, nil
- },
- }
- db := &admin.MockDB{
- MockGetProvisioner: func(ctx context.Context, id string) (*linkedca.Provisioner, error) {
- assert.Equals(t, "provID", id)
- return &linkedca.Provisioner{
- Id: "provID",
- Name: "provName",
- }, nil
- },
- }
- return test{
- ctx: ctx,
- body: body,
- auth: auth,
- adminDB: db,
- statusCode: 500,
- err: &admin.Error{
- Type: admin.ErrorServerInternalType.String(),
- Status: 500,
- Detail: "the server experienced an internal error",
- Message: "cannot change provisioner ID",
- },
- }
- },
- "fail/change-type-error": func(t *testing.T) test {
- chiCtx := chi.NewRouteContext()
- chiCtx.URLParams.Add("name", "provName")
- ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
- prov := &linkedca.Provisioner{
- Id: "provID",
- Type: linkedca.Provisioner_JWK,
- Name: "provName",
- }
- body, err := protojson.Marshal(prov)
- assert.FatalError(t, err)
- auth := &mockAdminAuthority{
- MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
- assert.Equals(t, "provName", name)
- return &provisioner.OIDC{
- ID: "provID",
- Name: "provName",
- }, nil
- },
- }
- db := &admin.MockDB{
- MockGetProvisioner: func(ctx context.Context, id string) (*linkedca.Provisioner, error) {
- assert.Equals(t, "provID", id)
- return &linkedca.Provisioner{
- Id: "provID",
- Name: "provName",
- Type: linkedca.Provisioner_OIDC,
- }, nil
- },
- }
- return test{
- ctx: ctx,
- body: body,
- auth: auth,
- adminDB: db,
- statusCode: 500,
- err: &admin.Error{
- Type: admin.ErrorServerInternalType.String(),
- Status: 500,
- Detail: "the server experienced an internal error",
- Message: "cannot change provisioner type",
- },
- }
- },
- "fail/change-authority-id-error": func(t *testing.T) test {
- chiCtx := chi.NewRouteContext()
- chiCtx.URLParams.Add("name", "provName")
- ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
- prov := &linkedca.Provisioner{
- Id: "provID",
- Type: linkedca.Provisioner_OIDC,
- Name: "provName",
- AuthorityId: "differentAuthorityID",
- }
- body, err := protojson.Marshal(prov)
- assert.FatalError(t, err)
- auth := &mockAdminAuthority{
- MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
- assert.Equals(t, "provName", name)
- return &provisioner.OIDC{
- ID: "provID",
- Name: "provName",
- }, nil
- },
- }
- db := &admin.MockDB{
- MockGetProvisioner: func(ctx context.Context, id string) (*linkedca.Provisioner, error) {
- assert.Equals(t, "provID", id)
- return &linkedca.Provisioner{
- Id: "provID",
- Name: "provName",
- Type: linkedca.Provisioner_OIDC,
- AuthorityId: "authorityID",
- }, nil
- },
- }
- return test{
- ctx: ctx,
- body: body,
- auth: auth,
- adminDB: db,
- statusCode: 500,
- err: &admin.Error{
- Type: admin.ErrorServerInternalType.String(),
- Status: 500,
- Detail: "the server experienced an internal error",
- Message: "cannot change provisioner authorityID",
- },
- }
- },
- "fail/change-createdAt-error": func(t *testing.T) test {
- chiCtx := chi.NewRouteContext()
- chiCtx.URLParams.Add("name", "provName")
- ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
- createdAt := time.Now()
- prov := &linkedca.Provisioner{
- Id: "provID",
- Type: linkedca.Provisioner_OIDC,
- Name: "provName",
- AuthorityId: "authorityID",
- CreatedAt: timestamppb.New(time.Now().Add(-1 * time.Hour)),
- }
- body, err := protojson.Marshal(prov)
- assert.FatalError(t, err)
- auth := &mockAdminAuthority{
- MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
- assert.Equals(t, "provName", name)
- return &provisioner.OIDC{
- ID: "provID",
- Name: "provName",
- }, nil
- },
- }
- db := &admin.MockDB{
- MockGetProvisioner: func(ctx context.Context, id string) (*linkedca.Provisioner, error) {
- assert.Equals(t, "provID", id)
- return &linkedca.Provisioner{
- Id: "provID",
- Name: "provName",
- Type: linkedca.Provisioner_OIDC,
- AuthorityId: "authorityID",
- CreatedAt: timestamppb.New(createdAt),
- }, nil
- },
- }
- return test{
- ctx: ctx,
- body: body,
- auth: auth,
- adminDB: db,
- statusCode: 500,
- err: &admin.Error{
- Type: admin.ErrorServerInternalType.String(),
- Status: 500,
- Detail: "the server experienced an internal error",
- Message: "cannot change provisioner createdAt",
- },
- }
- },
- "fail/change-deletedAt-error": func(t *testing.T) test {
- chiCtx := chi.NewRouteContext()
- chiCtx.URLParams.Add("name", "provName")
- ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
- createdAt := time.Now()
- var deletedAt time.Time
- prov := &linkedca.Provisioner{
- Id: "provID",
- Type: linkedca.Provisioner_OIDC,
- Name: "provName",
- AuthorityId: "authorityID",
- CreatedAt: timestamppb.New(createdAt),
- DeletedAt: timestamppb.New(time.Now()),
- }
- body, err := protojson.Marshal(prov)
- assert.FatalError(t, err)
- auth := &mockAdminAuthority{
- MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
- assert.Equals(t, "provName", name)
- return &provisioner.OIDC{
- ID: "provID",
- Name: "provName",
- }, nil
- },
- }
- db := &admin.MockDB{
- MockGetProvisioner: func(ctx context.Context, id string) (*linkedca.Provisioner, error) {
- assert.Equals(t, "provID", id)
- return &linkedca.Provisioner{
- Id: "provID",
- Name: "provName",
- Type: linkedca.Provisioner_OIDC,
- AuthorityId: "authorityID",
- CreatedAt: timestamppb.New(createdAt),
- DeletedAt: timestamppb.New(deletedAt),
- }, nil
- },
- }
- return test{
- ctx: ctx,
- body: body,
- auth: auth,
- adminDB: db,
- statusCode: 500,
- err: &admin.Error{
- Type: admin.ErrorServerInternalType.String(),
- Status: 500,
- Detail: "the server experienced an internal error",
- Message: "cannot change provisioner deletedAt",
- },
- }
- },
- // TODO(hs): ValidateClaims can't be mocked atm
- //"fail/ValidateClaims": func(t *testing.T) test { return test{} },
- "fail/validateTemplates": func(t *testing.T) test {
- chiCtx := chi.NewRouteContext()
- chiCtx.URLParams.Add("name", "provName")
- ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
- createdAt := time.Now()
- var deletedAt time.Time
- prov := &linkedca.Provisioner{
- Id: "provID",
- Type: linkedca.Provisioner_OIDC,
- Name: "provName",
- AuthorityId: "authorityID",
- CreatedAt: timestamppb.New(createdAt),
- DeletedAt: timestamppb.New(deletedAt),
- X509Template: &linkedca.Template{
- <<<<<<< HEAD
- Template: []byte("{ {{ missingFunction }} }"),
- =======
- Template: []byte("{!?}"),
- >>>>>>> 440ac4b2 (Add provisioner template validation)
- },
- }
- body, err := protojson.Marshal(prov)
- assert.FatalError(t, err)
- auth := &mockAdminAuthority{
- MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
- assert.Equals(t, "provName", name)
- return &provisioner.OIDC{
- ID: "provID",
- Name: "provName",
- }, nil
- },
- }
- db := &admin.MockDB{
- MockGetProvisioner: func(ctx context.Context, id string) (*linkedca.Provisioner, error) {
- assert.Equals(t, "provID", id)
- return &linkedca.Provisioner{
- Id: "provID",
- Name: "provName",
- Type: linkedca.Provisioner_OIDC,
- AuthorityId: "authorityID",
- CreatedAt: timestamppb.New(createdAt),
- DeletedAt: timestamppb.New(deletedAt),
- }, nil
- },
- }
- return test{
- ctx: ctx,
- body: body,
- auth: auth,
- adminDB: db,
- statusCode: 400,
- err: &admin.Error{
- Type: "badRequest",
- Status: 400,
- Detail: "bad request",
- <<<<<<< HEAD
- Message: "invalid template: invalid X.509 template: error parsing template: template: template:1: function \"missingFunction\" not defined",
- =======
- Message: "invalid template: invalid X.509 template: invalid JSON: invalid character '!' looking for beginning of object key string",
- >>>>>>> 440ac4b2 (Add provisioner template validation)
- },
- }
- },
- "fail/auth.UpdateProvisioner": func(t *testing.T) test {
- chiCtx := chi.NewRouteContext()
- chiCtx.URLParams.Add("name", "provName")
- ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
- createdAt := time.Now()
- var deletedAt time.Time
- prov := &linkedca.Provisioner{
- Id: "provID",
- Type: linkedca.Provisioner_OIDC,
- Name: "provName",
- AuthorityId: "authorityID",
- CreatedAt: timestamppb.New(createdAt),
- DeletedAt: timestamppb.New(deletedAt),
- }
- body, err := protojson.Marshal(prov)
- assert.FatalError(t, err)
- auth := &mockAdminAuthority{
- MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
- assert.Equals(t, "provName", name)
- return &provisioner.OIDC{
- ID: "provID",
- Name: "provName",
- }, nil
- },
- MockUpdateProvisioner: func(ctx context.Context, nu *linkedca.Provisioner) error {
- assert.Equals(t, "provID", nu.Id)
- assert.Equals(t, "provName", nu.Name)
- return errors.New("force")
- },
- }
- db := &admin.MockDB{
- MockGetProvisioner: func(ctx context.Context, id string) (*linkedca.Provisioner, error) {
- assert.Equals(t, "provID", id)
- return &linkedca.Provisioner{
- Id: "provID",
- Name: "provName",
- Type: linkedca.Provisioner_OIDC,
- AuthorityId: "authorityID",
- CreatedAt: timestamppb.New(createdAt),
- DeletedAt: timestamppb.New(deletedAt),
- }, nil
- },
- }
- return test{
- ctx: ctx,
- body: body,
- auth: auth,
- adminDB: db,
- statusCode: 500,
- err: &admin.Error{
- Type: "", // TODO(hs): this error can be improved
- Status: 500,
- Detail: "",
- Message: "",
- },
- }
- },
- "ok": func(t *testing.T) test {
- chiCtx := chi.NewRouteContext()
- chiCtx.URLParams.Add("name", "provName")
- ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
- createdAt := time.Now()
- var deletedAt time.Time
- prov := &linkedca.Provisioner{
- Id: "provID",
- Type: linkedca.Provisioner_OIDC,
- Name: "provName",
- AuthorityId: "authorityID",
- CreatedAt: timestamppb.New(createdAt),
- DeletedAt: timestamppb.New(deletedAt),
- Details: &linkedca.ProvisionerDetails{
- Data: &linkedca.ProvisionerDetails_OIDC{
- OIDC: &linkedca.OIDCProvisioner{
- ClientId: "new-client-id",
- ClientSecret: "new-client-secret",
- },
- },
- },
- }
- body, err := protojson.Marshal(prov)
- assert.FatalError(t, err)
- auth := &mockAdminAuthority{
- MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
- assert.Equals(t, "provName", name)
- return &provisioner.OIDC{
- ID: "provID",
- Name: "provName",
- }, nil
- },
- MockUpdateProvisioner: func(ctx context.Context, nu *linkedca.Provisioner) error {
- assert.Equals(t, "provID", nu.Id)
- assert.Equals(t, "provName", nu.Name)
- return nil
- },
- }
- db := &admin.MockDB{
- MockGetProvisioner: func(ctx context.Context, id string) (*linkedca.Provisioner, error) {
- assert.Equals(t, "provID", id)
- return &linkedca.Provisioner{
- Id: "provID",
- Name: "provName",
- Type: linkedca.Provisioner_OIDC,
- AuthorityId: "authorityID",
- CreatedAt: timestamppb.New(createdAt),
- DeletedAt: timestamppb.New(deletedAt),
- }, nil
- },
- }
- return test{
- ctx: ctx,
- body: body,
- auth: auth,
- adminDB: db,
- statusCode: 200,
- prov: prov,
- }
- },
- }
- for name, prep := range tests {
- tc := prep(t)
- t.Run(name, func(t *testing.T) {
- mockMustAuthority(t, tc.auth)
- ctx := admin.NewContext(tc.ctx, tc.adminDB)
- req := httptest.NewRequest("POST", "/foo", io.NopCloser(bytes.NewBuffer(tc.body)))
- req = req.WithContext(ctx)
- w := httptest.NewRecorder()
- UpdateProvisioner(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.Detail, adminErr.Detail)
- assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
- if strings.HasPrefix(tc.err.Message, "proto:") {
- assert.True(t, strings.Contains(adminErr.Message, "syntax error"))
- } else {
- assert.Equals(t, tc.err.Message, adminErr.Message)
- }
- return
- }
- prov := &linkedca.Provisioner{}
- err := readProtoJSON(res.Body, prov)
- assert.FatalError(t, err)
- assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
- opts := []cmp.Option{
- cmpopts.IgnoreUnexported(
- linkedca.Provisioner{}, linkedca.ProvisionerDetails{}, linkedca.ProvisionerDetails_OIDC{},
- linkedca.OIDCProvisioner{}, timestamppb.Timestamp{},
- ),
- }
- if !cmp.Equal(tc.prov, prov, opts...) {
- t.Errorf("linkedca.Admin diff =\n%s", cmp.Diff(tc.prov, prov, opts...))
- }
- })
- }
- }
- func Test_validateTemplates(t *testing.T) {
- type args struct {
- x509 *linkedca.Template
- ssh *linkedca.Template
- }
- tests := []struct {
- name string
- args args
- err error
- }{
- {
- name: "ok",
- args: args{},
- err: nil,
- },
- {
- name: "ok/x509",
- args: args{
- x509: &linkedca.Template{
- Template: []byte(`{"x": 1}`),
- },
- },
- err: nil,
- },
- {
- name: "ok/ssh",
- args: args{
- ssh: &linkedca.Template{
- Template: []byte(`{"x": 1}`),
- },
- },
- err: nil,
- },
- {
- <<<<<<< HEAD
- name: "fail/x509-template-missing-quote",
- args: args{
- x509: &linkedca.Template{
- Template: []byte(`{ {{printf "%q" "quoted}} }`),
- },
- },
- err: errors.New("invalid X.509 template: error parsing template: template: template:1: unterminated quoted string"),
- =======
- name: "fail/x509-template-trailing-comma",
- args: args{
- x509: &linkedca.Template{
- Template: []byte(`{"x": 1,}`),
- },
- },
- err: errors.New("invalid X.509 template: invalid JSON: invalid character '}' looking for beginning of object key string"),
- >>>>>>> 440ac4b2 (Add provisioner template validation)
- },
- {
- name: "fail/x509-template-data",
- args: args{
- x509: &linkedca.Template{
- Data: []byte(`{!?}`),
- },
- },
- <<<<<<< HEAD
- err: errors.New("invalid X.509 template data: error validating json template data"),
- },
- {
- name: "fail/ssh-template-unknown-function",
- args: args{
- ssh: &linkedca.Template{
- Template: []byte(`{ {{unknownFunction "foo"}} }`),
- },
- },
- err: errors.New("invalid SSH template: error parsing template: template: template:1: function \"unknownFunction\" not defined"),
- =======
- err: errors.New("invalid X.509 template data: invalid JSON: invalid character '!' looking for beginning of object key string"),
- },
- {
- name: "fail/ssh-template-trailing-comma",
- args: args{
- ssh: &linkedca.Template{
- Template: []byte(`{"x": 1,}`),
- },
- },
- err: errors.New("invalid SSH template: invalid JSON: invalid character '}' looking for beginning of object key string"),
- >>>>>>> 440ac4b2 (Add provisioner template validation)
- },
- {
- name: "fail/ssh-template-data",
- args: args{
- ssh: &linkedca.Template{
- Data: []byte(`{!?}`),
- },
- },
- <<<<<<< HEAD
- err: errors.New("invalid SSH template data: error validating json template data"),
- =======
- err: errors.New("invalid SSH template data: invalid JSON: invalid character '!' looking for beginning of object key string"),
- >>>>>>> 440ac4b2 (Add provisioner template validation)
- },
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- err := validateTemplates(tt.args.x509, tt.args.ssh)
- if tt.err != nil {
- assert.Error(t, err)
- assert.Equals(t, tt.err.Error(), err.Error())
- return
- }
- assert.Nil(t, err)
- })
- }
- }
|