From bfdfcc4a50485905cff642970c250bd40194feb5 Mon Sep 17 00:00:00 2001 From: Victor Vieira Barros Leal da Silveira Date: Fri, 5 May 2023 11:40:37 -0300 Subject: [PATCH 01/20] feat: Implementing Admin Handlers --- pkg/server/endpoints/management.go | 118 +++++++++++++++++++++++++++++ 1 file changed, 118 insertions(+) diff --git a/pkg/server/endpoints/management.go b/pkg/server/endpoints/management.go index bef77ceb..97ad2d8f 100644 --- a/pkg/server/endpoints/management.go +++ b/pkg/server/endpoints/management.go @@ -4,12 +4,15 @@ import ( "context" "fmt" "net/http" + "time" "github.com/HewlettPackard/galadriel/pkg/common/api" "github.com/HewlettPackard/galadriel/pkg/common/entity" chttp "github.com/HewlettPackard/galadriel/pkg/common/http" "github.com/HewlettPackard/galadriel/pkg/server/api/admin" "github.com/HewlettPackard/galadriel/pkg/server/datastore" + "github.com/google/uuid" + "github.com/spiffe/go-spiffe/v2/spiffeid" "github.com/sirupsen/logrus" @@ -89,6 +92,21 @@ func (h AdminAPIHandlers) PutRelationships(ctx echo.Context) error { // GetRelationshipsRelationshipID retrieve a specific relationship based on its id - (GET /relationships/{relationshipID}) func (h AdminAPIHandlers) GetRelationshipsRelationshipID(ctx echo.Context, relationshipID api.UUID) error { + gctx := ctx.Request().Context() + + r, err := h.Datastore.FindRelationshipByID(gctx, relationshipID) + if err != nil { + err = fmt.Errorf("failed getting relationships: %v", err) + return h.HandleAndLog(err, http.StatusInternalServerError) + } + + response := api.RelationshipFromEntity(r) + err = chttp.WriteResponse(ctx, response) + if err != nil { + err = fmt.Errorf("relationship entity - %v", err.Error()) + return h.HandleAndLog(err, http.StatusInternalServerError) + } + return nil } @@ -138,16 +156,116 @@ func (h AdminAPIHandlers) PutTrustDomain(ctx echo.Context) error { // GetTrustDomainTrustDomainName retrieve a specific trust domain by its name - (GET /trust-domain/{trustDomainName}) func (h AdminAPIHandlers) GetTrustDomainTrustDomainName(ctx echo.Context, trustDomainName api.TrustDomainName) error { + gctx := ctx.Request().Context() + + tdName, err := spiffeid.TrustDomainFromString(trustDomainName) + if err != nil { + err = fmt.Errorf("failed parsing trust domain name: %v", err) + return h.HandleAndLog(err, http.StatusBadRequest) + } + + td, err := h.Datastore.FindTrustDomainByName(gctx, tdName) + if err != nil { + err = fmt.Errorf("failed getting trust domain: %v", err) + return h.HandleAndLog(err, http.StatusInternalServerError) + } + + response := api.TrustDomainFromEntity(td) + err = chttp.WriteResponse(ctx, response) + if err != nil { + err = fmt.Errorf("trust domain entity - %v", err.Error()) + return h.HandleAndLog(err, http.StatusInternalServerError) + } + return nil } // PutTrustDomainTrustDomainName updates the trust domain - (PUT /trust-domain/{trustDomainName}) func (h AdminAPIHandlers) PutTrustDomainTrustDomainName(ctx echo.Context, trustDomainName api.UUID) error { + gctx := ctx.Request().Context() + + reqBody := &admin.PutTrustDomainTrustDomainNameJSONRequestBody{} + err := chttp.FromBody(ctx, reqBody) + if err != nil { + err := fmt.Errorf("failed to read trust domain put body: %v", err) + return h.HandleAndLog(err, http.StatusBadRequest) + } + + etd, err := reqBody.ToEntity() + if err != nil { + err := fmt.Errorf("failed to read trust domain put body: %v", err) + return h.HandleAndLog(err, http.StatusBadRequest) + } + + td, err := h.Datastore.CreateOrUpdateTrustDomain(gctx, etd) + if err != nil { + err = fmt.Errorf("failed creating/updating trust domain: %v", err) + return h.HandleAndLog(err, http.StatusInternalServerError) + } + + h.Logger.Printf("Trust Bundle %v created/updated", td.Name) + + response := api.TrustDomainFromEntity(td) + err = chttp.WriteResponse(ctx, response) + if err != nil { + err = fmt.Errorf("relationships - %v", err.Error()) + return h.HandleAndLog(err, http.StatusInternalServerError) + } + return nil } // PostTrustDomainTrustDomainNameJoinToken generate a join token for the trust domain - (POST /trust-domain/{trustDomainName}/join-token) func (h AdminAPIHandlers) PostTrustDomainTrustDomainNameJoinToken(ctx echo.Context, trustDomainName api.TrustDomainName) error { + gctx := ctx.Request().Context() + + tdName, err := spiffeid.TrustDomainFromString(trustDomainName) + if err != nil { + err = fmt.Errorf("failed parsing trust domain name: %v", err) + return h.HandleAndLog(err, http.StatusBadRequest) + } + + td, err := h.Datastore.FindTrustDomainByName(gctx, tdName) + if err != nil { + err = fmt.Errorf("failed retrieve the trust domain by name %v", err) + return h.HandleAndLog(err, http.StatusInternalServerError) + } + + if td == nil { + err = fmt.Errorf("trust domain does not exists %v", trustDomainName) + return h.HandleAndLog(err, http.StatusBadRequest) + } + + token, err := util.GenerateToken() + if err != nil { + err = fmt.Errorf("failed generating a new join token %v", err) + return h.HandleAndLog(err, http.StatusInternalServerError) + } + + jt := &entity.JoinToken{ + TrustDomainID: td.ID.UUID, + Token: token, + ExpiresAt: time.Now().Add(1 * time.Hour), + } + + jt, err = h.Datastore.CreateJoinToken(gctx, jt) + if err != nil { + err = fmt.Errorf("failed creating the join token: %v", err) + return h.HandleAndLog(err, http.StatusInternalServerError) + } + + h.Logger.Printf("join token successfully created for %v", td.Name) + + response := admin.JoinTokenResult{ + Token: uuid.MustParse(jt.Token), + } + + err = chttp.WriteResponse(ctx, response) + if err != nil { + err = fmt.Errorf("relationships - %v", err.Error()) + return h.HandleAndLog(err, http.StatusInternalServerError) + } + return nil } From cbdaf2620fb4226a5634ea4646a5531e2833c304 Mon Sep 17 00:00:00 2001 From: Victor Vieira Barros Leal da Silveira Date: Mon, 8 May 2023 15:53:25 -0300 Subject: [PATCH 02/20] feat: Adding unit testes helpers and implemenenting get relationships unit tests --- pkg/server/datastore/fakedatabase.go | 22 +++++ pkg/server/endpoints/auth_test.go | 6 +- pkg/server/endpoints/harvester_test.go | 21 +++-- pkg/server/endpoints/management.go | 104 ++++++++++++++++++--- pkg/server/endpoints/management_test.go | 116 +++++++++++++++++++++++- 5 files changed, 244 insertions(+), 25 deletions(-) diff --git a/pkg/server/datastore/fakedatabase.go b/pkg/server/datastore/fakedatabase.go index 84242adf..3f0f71d5 100644 --- a/pkg/server/datastore/fakedatabase.go +++ b/pkg/server/datastore/fakedatabase.go @@ -431,6 +431,28 @@ func (db *FakeDatabase) DeleteRelationship(ctx context.Context, relationshipID u return nil } +// WithRelationships overrides all relationships +func (db *FakeDatabase) WithRelationships(relationships []*entity.Relationship) { + db.mutex.Lock() + defer db.mutex.Unlock() + + db.relationships = make(map[uuid.UUID]*entity.Relationship) + for _, r := range relationships { + db.relationships[r.ID.UUID] = r + } +} + +// WithRelationships overrides all trust domains +func (db *FakeDatabase) WithTrustDomains(trustDomains []*entity.TrustDomain) { + db.mutex.Lock() + defer db.mutex.Unlock() + + db.trustDomains = make(map[uuid.UUID]*entity.TrustDomain) + for _, td := range trustDomains { + db.trustDomains[td.ID.UUID] = td + } +} + func (db *FakeDatabase) SetNextError(err error) { db.mutex.Lock() defer db.mutex.Unlock() diff --git a/pkg/server/endpoints/auth_test.go b/pkg/server/endpoints/auth_test.go index bfa7550f..fac1b2c6 100644 --- a/pkg/server/endpoints/auth_test.go +++ b/pkg/server/endpoints/auth_test.go @@ -46,8 +46,8 @@ func SetupMiddleware() *AuthNTestSetup { } } -func SetupToken(t *testing.T, ds datastore.Datastore, token string, tdID uuid.UUID) *entity.JoinToken { - td, err := spiffeid.TrustDomainFromString(testTrustDomain) +func SetupToken(t *testing.T, ds datastore.Datastore, tdID uuid.UUID, token, tdName string) *entity.JoinToken { + td, err := spiffeid.TrustDomainFromString(tdName) assert.NoError(t, err) jt := &entity.JoinToken{ @@ -67,7 +67,7 @@ func TestAuthenticate(t *testing.T) { t.Run("Authorized tokens must be able to pass authn verification", func(t *testing.T) { authnSetup := SetupMiddleware() token := GenerateSecureToken(10) - SetupToken(t, authnSetup.FakeDatabase, token, uuid.New()) + SetupToken(t, authnSetup.FakeDatabase, uuid.New(), token, testTrustDomain) authorized, err := authnSetup.Middleware.Authenticate(token, authnSetup.EchoCtx) assert.NoError(t, err) diff --git a/pkg/server/endpoints/harvester_test.go b/pkg/server/endpoints/harvester_test.go index 75b3b766..c86e7f15 100644 --- a/pkg/server/endpoints/harvester_test.go +++ b/pkg/server/endpoints/harvester_test.go @@ -3,6 +3,7 @@ package endpoints import ( "context" "encoding/json" + "io" "net/http" "net/http/httptest" "strings" @@ -23,9 +24,16 @@ type HarvesterTestSetup struct { Recorder *httptest.ResponseRecorder } -func NewHarvesterTestSetup(method, url, body string) *HarvesterTestSetup { +func NewHarvesterTestSetup(t *testing.T, method, url string, body interface{}) *HarvesterTestSetup { + var bodyReader io.Reader + if body != nil { + bodyStr, err := json.Marshal(body) + assert.NoError(t, err) + bodyReader = strings.NewReader(string(bodyStr)) + } + e := echo.New() - req := httptest.NewRequest(method, url, strings.NewReader(body)) + req := httptest.NewRequest(method, url, bodyReader) req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) rec := httptest.NewRecorder() fakeDB := datastore.NewFakeDB() @@ -67,7 +75,7 @@ func TestTCPBundleSync(t *testing.T) { } func TestTCPBundlePut(t *testing.T) { - t.Run("Succesfully register bundles for a trust domain", func(t *testing.T) { + t.Run("Successfully register bundles for a trust domain", func(t *testing.T) { bundlePut := harvester.BundlePut{ Signature: "", SigningCertificate: "", @@ -75,10 +83,7 @@ func TestTCPBundlePut(t *testing.T) { TrustDomain: testTrustDomain, } - body, err := json.Marshal(bundlePut) - assert.NoError(t, err) - - harvesterTestSetup := NewHarvesterTestSetup(http.MethodPut, "/trust-domain/:trustDomainName/bundles", string(body)) + harvesterTestSetup := NewHarvesterTestSetup(t, http.MethodPut, "/trust-domain/:trustDomainName/bundles", bundlePut) echoCtx := harvesterTestSetup.EchoCtx // Creating Trust Domain @@ -87,7 +92,7 @@ func TestTCPBundlePut(t *testing.T) { // Creating Auth token to bypass AuthN layer token := GenerateSecureToken(10) - jt := SetupToken(t, harvesterTestSetup.Handler.Datastore, token, td.ID.UUID) + jt := SetupToken(t, harvesterTestSetup.Handler.Datastore, td.ID.UUID, token, td.Name.String()) assert.NoError(t, err) echoCtx.Set(tokenKey, jt) diff --git a/pkg/server/endpoints/management.go b/pkg/server/endpoints/management.go index 97ad2d8f..d8396325 100644 --- a/pkg/server/endpoints/management.go +++ b/pkg/server/endpoints/management.go @@ -38,10 +38,32 @@ func NewAdminAPIHandlers(l logrus.FieldLogger, ds datastore.Datastore) *AdminAPI func (h AdminAPIHandlers) GetRelationships(ctx echo.Context, params admin.GetRelationshipsParams) error { gctx := ctx.Request().Context() - rels, err := h.Datastore.ListRelationships(gctx) + var err error + var rels []*entity.Relationship + + if params.TrustDomainName != nil { + td, err := h.findTrustDomainByName(gctx, *params.TrustDomainName) + if err != nil { + err = fmt.Errorf("failed parsing trust domain name: %v", err) + return h.HandleAndLog(err, http.StatusBadRequest) + } + + rels, err = h.Datastore.FindRelationshipsByTrustDomainID(gctx, td.ID.UUID) + if err != nil { + err = fmt.Errorf("failed listing relationships: %v", err) + return h.HandleAndLog(err, http.StatusInternalServerError) + } + } else { + rels, err = h.Datastore.ListRelationships(gctx) + if err != nil { + err = fmt.Errorf("failed listing relationships: %v", err) + return h.HandleAndLog(err, http.StatusInternalServerError) + } + } + + rels, err = h.filterRelationshipsByStatus(gctx, rels, params.Status) if err != nil { - err = fmt.Errorf("failed listing relationships: %v", err) - return h.HandleAndLog(err, http.StatusInternalServerError) + return err } rels, err = h.populateTrustDomainNames(gctx, rels) @@ -219,16 +241,9 @@ func (h AdminAPIHandlers) PutTrustDomainTrustDomainName(ctx echo.Context, trustD func (h AdminAPIHandlers) PostTrustDomainTrustDomainNameJoinToken(ctx echo.Context, trustDomainName api.TrustDomainName) error { gctx := ctx.Request().Context() - tdName, err := spiffeid.TrustDomainFromString(trustDomainName) + td, err := h.findTrustDomainByName(gctx, trustDomainName) if err != nil { - err = fmt.Errorf("failed parsing trust domain name: %v", err) - return h.HandleAndLog(err, http.StatusBadRequest) - } - - td, err := h.Datastore.FindTrustDomainByName(gctx, tdName) - if err != nil { - err = fmt.Errorf("failed retrieve the trust domain by name %v", err) - return h.HandleAndLog(err, http.StatusInternalServerError) + return err } if td == nil { @@ -269,6 +284,48 @@ func (h AdminAPIHandlers) PostTrustDomainTrustDomainNameJoinToken(ctx echo.Conte return nil } +func (h AdminAPIHandlers) findTrustDomainByName(ctx context.Context, trustDomain string) (*entity.TrustDomain, error) { + tdName, err := spiffeid.TrustDomainFromString(trustDomain) + if err != nil { + err = fmt.Errorf("failed parsing trust domain name: %v", err) + return nil, h.HandleAndLog(err, http.StatusBadRequest) + } + + td, err := h.Datastore.FindTrustDomainByName(ctx, tdName) + if err != nil { + err = fmt.Errorf("failed getting trust domain: %v", err) + return nil, h.HandleAndLog(err, http.StatusInternalServerError) + } + + return td, nil +} + +func (h AdminAPIHandlers) filterRelationshipsByStatus( + ctx context.Context, + relationships []*entity.Relationship, + status *admin.GetRelationshipsParamsStatus, +) ([]*entity.Relationship, error) { + + if status != nil { + switch *status { + case admin.Denied: + return filterBy(relationships, deniedRelationFilter), nil + case admin.Approved: + return filterBy(relationships, approvedRelationFilter), nil + case admin.Pending: + return filterBy(relationships, pendingRelationFilter), nil + } + + err := fmt.Errorf( + "unrecognized status filter %v, accepted values [%v, %v, %v]", + *status, admin.Denied, admin.Approved, admin.Pending, + ) + return nil, h.HandleAndLog(err, http.StatusBadRequest) + } else { + return filterBy(relationships, pendingRelationFilter), nil + } +} + func (h AdminAPIHandlers) populateTrustDomainNames(ctx context.Context, relationships []*entity.Relationship) ([]*entity.Relationship, error) { for _, r := range relationships { tda, err := h.Datastore.FindTrustDomainByID(ctx, r.TrustDomainAID) @@ -302,3 +359,26 @@ func (h AdminAPIHandlers) HandleAndLog(err error, code int) error { h.Logger.Errorf(errMsg) return echo.NewHTTPError(code, err.Error()) } + +func deniedRelationFilter(e *entity.Relationship) bool { + return !e.TrustDomainAConsent || !e.TrustDomainBConsent +} + +func approvedRelationFilter(e *entity.Relationship) bool { + return e.TrustDomainAConsent && e.TrustDomainBConsent +} + +func pendingRelationFilter(e *entity.Relationship) bool { + return !e.TrustDomainAConsent || !e.TrustDomainBConsent +} + +// filterBy will generate a new slice with the elements that matched +func filterBy[E any](s []E, match func(E) bool) []E { + filtered := []E{} + for _, e := range s { + if match(e) { + filtered = append(filtered, e) + } + } + return filtered +} diff --git a/pkg/server/endpoints/management_test.go b/pkg/server/endpoints/management_test.go index 0cc941d2..92f5c480 100644 --- a/pkg/server/endpoints/management_test.go +++ b/pkg/server/endpoints/management_test.go @@ -1,9 +1,108 @@ package endpoints -import "testing" +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/HewlettPackard/galadriel/pkg/common/api" + "github.com/HewlettPackard/galadriel/pkg/common/entity" + "github.com/HewlettPackard/galadriel/pkg/server/api/admin" + "github.com/HewlettPackard/galadriel/pkg/server/datastore" + "github.com/google/uuid" + "github.com/labstack/echo/v4" + "github.com/sirupsen/logrus" + "github.com/spiffe/go-spiffe/v2/spiffeid" + "github.com/stretchr/testify/assert" +) + +type ManagementTestSetup struct { + EchoCtx echo.Context + Handler *AdminAPIHandlers + Recorder *httptest.ResponseRecorder + FakeDatabase *datastore.FakeDatabase +} + +func NewManagementTestSetup(t *testing.T, method, url string, body interface{}) *ManagementTestSetup { + var bodyReader io.Reader + if body != nil { + bodyStr, err := json.Marshal(body) + assert.NoError(t, err) + bodyReader = strings.NewReader(string(bodyStr)) + } + + e := echo.New() + req := httptest.NewRequest(method, url, bodyReader) + req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) + rec := httptest.NewRecorder() + fakeDB := datastore.NewFakeDB() + logger := logrus.New() + + return &ManagementTestSetup{ + EchoCtx: e.NewContext(req, rec), + Recorder: rec, + Handler: NewAdminAPIHandlers(logger, fakeDB), + FakeDatabase: fakeDB, + } +} func TestUDSGetRelationships(t *testing.T) { - t.Skip("Missing tests will be added when the API be implemented") + t.Run("Successfully filter by trust domain", func(t *testing.T) { + + // Setup + managementTestSetup := NewManagementTestSetup(t, http.MethodGet, "/relationships", nil) + echoCtx := managementTestSetup.EchoCtx + + // Creating fake trust bundles and relationships to be filtered + td1Name := NewTrustDomain(t, testTrustDomain) + tdUUID1 := NewNullableID() + tdUUID2 := NewNullableID() + tdUUID3 := NewNullableID() + + fakeTrustDomains := []*entity.TrustDomain{ + {ID: tdUUID1, Name: td1Name}, + {ID: tdUUID2, Name: NewTrustDomain(t, "test2.com")}, + {ID: tdUUID3, Name: NewTrustDomain(t, "test3.com")}, + } + + fakeRelationships := []*entity.Relationship{ + {ID: NewNullableID(), TrustDomainAID: tdUUID1.UUID, TrustDomainBID: tdUUID2.UUID, TrustDomainAConsent: false, TrustDomainBConsent: false}, + {ID: NewNullableID(), TrustDomainBID: tdUUID1.UUID, TrustDomainAID: tdUUID3.UUID, TrustDomainAConsent: false, TrustDomainBConsent: false}, + {ID: NewNullableID(), TrustDomainAID: uuid.New(), TrustDomainBID: uuid.New(), TrustDomainAConsent: false, TrustDomainBConsent: false}, + } + + managementTestSetup.FakeDatabase.WithTrustDomains(fakeTrustDomains) + managementTestSetup.FakeDatabase.WithRelationships(fakeRelationships) + + // managementTestSetup.Handler.Datastore + tdName := td1Name.String() + params := admin.GetRelationshipsParams{ + TrustDomainName: &tdName, + } + + err := managementTestSetup.Handler.GetRelationships(echoCtx, params) + assert.NoError(t, err) + + recorder := managementTestSetup.Recorder + assert.Equal(t, http.StatusOK, recorder.Code) + assert.NotEmpty(t, recorder.Body) + + relationships := []*api.Relationship{} + err = json.Unmarshal(recorder.Body.Bytes(), &relationships) + assert.NoError(t, err) + + assert.Len(t, relationships, 2) + + // apiRelations := mapRelationships([]*entity.Relationship{ + // {TrustDomainAID: tdUUID1.UUID, TrustDomainBID: tdUUID2.UUID, TrustDomainAConsent: false, TrustDomainBConsent: false}, + // {TrustDomainBID: tdUUID1.UUID, TrustDomainAID: tdUUID3.UUID, TrustDomainAConsent: false, TrustDomainBConsent: false}, + // }) + + // assert.ElementsMatchf(t, relationships, apiRelations, "filter does not work properly") + }) } func TestUDSPutRelationships(t *testing.T) { @@ -29,3 +128,16 @@ func TestUDSPutTrustDomainTrustDomainName(t *testing.T) { func TestUDSPostTrustDomainTrustDomainNameJoinToken(t *testing.T) { t.Skip("Missing tests will be added when the API be implemented") } + +func NewNullableID() uuid.NullUUID { + return uuid.NullUUID{ + Valid: true, + UUID: uuid.New(), + } +} + +func NewTrustDomain(t *testing.T, tdName string) spiffeid.TrustDomain { + td, err := spiffeid.TrustDomainFromString(tdName) + assert.NoError(t, err) + return td +} From 664cb5891e8264b12cf43395e99500479d7fb844 Mon Sep 17 00:00:00 2001 From: Victor Vieira Barros Leal da Silveira Date: Tue, 9 May 2023 15:58:55 -0300 Subject: [PATCH 03/20] feat: Creating unit tests for relationshio request creation and improving get relationship uni tests --- pkg/common/http/http.go | 4 +- pkg/common/http/http_test.go | 4 +- pkg/server/datastore/fakedatabase.go | 17 +- pkg/server/endpoints/auth_test.go | 2 +- pkg/server/endpoints/const_test.go | 4 +- pkg/server/endpoints/harvester.go | 2 +- pkg/server/endpoints/harvester_test.go | 6 +- pkg/server/endpoints/management.go | 73 ++++---- pkg/server/endpoints/management_test.go | 218 ++++++++++++++++++++++-- 9 files changed, 265 insertions(+), 65 deletions(-) diff --git a/pkg/common/http/http.go b/pkg/common/http/http.go index 7c4e35f0..1014f2ab 100644 --- a/pkg/common/http/http.go +++ b/pkg/common/http/http.go @@ -21,8 +21,8 @@ func WriteResponse(ctx echo.Context, body interface{}) error { return nil } -// BodylessResponse wraps error echo body-less responses. -func BodylessResponse(ctx echo.Context) error { +// BodilessResponse wraps error echo body-less responses. +func BodilessResponse(ctx echo.Context) error { if err := ctx.NoContent(http.StatusOK); err != nil { return fmt.Errorf("failed to respond without body: %v", err) } diff --git a/pkg/common/http/http_test.go b/pkg/common/http/http_test.go index 75fc59d7..26dea5c6 100644 --- a/pkg/common/http/http_test.go +++ b/pkg/common/http/http_test.go @@ -63,7 +63,7 @@ func TestWriteResponse(t *testing.T) { func TestBodylessResponse(t *testing.T) { t.Run("Ensuring that the body is empty", func(t *testing.T) { setup := Setup() - err := BodylessResponse(setup.EchoContext) + err := BodilessResponse(setup.EchoContext) assert.NoError(t, err) assert.NoError(t, err) @@ -75,7 +75,7 @@ func TestBodylessResponse(t *testing.T) { func TestFromBody(t *testing.T) { t.Run("Ensuring that the body is empty", func(t *testing.T) { setup := Setup() - err := BodylessResponse(setup.EchoContext) + err := BodilessResponse(setup.EchoContext) assert.NoError(t, err) assert.NoError(t, err) diff --git a/pkg/server/datastore/fakedatabase.go b/pkg/server/datastore/fakedatabase.go index 3f0f71d5..eb256570 100644 --- a/pkg/server/datastore/fakedatabase.go +++ b/pkg/server/datastore/fakedatabase.go @@ -354,7 +354,18 @@ func (db *FakeDatabase) CreateOrUpdateRelationship(ctx context.Context, req *ent return nil, err } - return nil, nil + if req.ID.Valid { + + } else { + req.CreatedAt = time.Now() + + } + + req.UpdatedAt = time.Now() + + db.relationships[req.ID.UUID] = req + + return req, nil } func (db *FakeDatabase) FindRelationshipByID(ctx context.Context, relationshipID uuid.UUID) (*entity.Relationship, error) { @@ -432,7 +443,7 @@ func (db *FakeDatabase) DeleteRelationship(ctx context.Context, relationshipID u } // WithRelationships overrides all relationships -func (db *FakeDatabase) WithRelationships(relationships []*entity.Relationship) { +func (db *FakeDatabase) WithRelationships(relationships ...*entity.Relationship) { db.mutex.Lock() defer db.mutex.Unlock() @@ -443,7 +454,7 @@ func (db *FakeDatabase) WithRelationships(relationships []*entity.Relationship) } // WithRelationships overrides all trust domains -func (db *FakeDatabase) WithTrustDomains(trustDomains []*entity.TrustDomain) { +func (db *FakeDatabase) WithTrustDomains(trustDomains ...*entity.TrustDomain) { db.mutex.Lock() defer db.mutex.Unlock() diff --git a/pkg/server/endpoints/auth_test.go b/pkg/server/endpoints/auth_test.go index fac1b2c6..29d65e3b 100644 --- a/pkg/server/endpoints/auth_test.go +++ b/pkg/server/endpoints/auth_test.go @@ -67,7 +67,7 @@ func TestAuthenticate(t *testing.T) { t.Run("Authorized tokens must be able to pass authn verification", func(t *testing.T) { authnSetup := SetupMiddleware() token := GenerateSecureToken(10) - SetupToken(t, authnSetup.FakeDatabase, uuid.New(), token, testTrustDomain) + SetupToken(t, authnSetup.FakeDatabase, uuid.New(), token, td1) authorized, err := authnSetup.Middleware.Authenticate(token, authnSetup.EchoCtx) assert.NoError(t, err) diff --git a/pkg/server/endpoints/const_test.go b/pkg/server/endpoints/const_test.go index 5c9c66a5..730f855a 100644 --- a/pkg/server/endpoints/const_test.go +++ b/pkg/server/endpoints/const_test.go @@ -1,5 +1,7 @@ package endpoints const ( - testTrustDomain = "test.com" + td1 = "test1.com" + td2 = "test2.com" + td3 = "test3.com" ) diff --git a/pkg/server/endpoints/harvester.go b/pkg/server/endpoints/harvester.go index 99ec5a42..1ce83521 100644 --- a/pkg/server/endpoints/harvester.go +++ b/pkg/server/endpoints/harvester.go @@ -116,7 +116,7 @@ func (h HarvesterAPIHandlers) BundlePut(ctx echo.Context, trustDomainName api.Tr return h.handleErrorAndLog(err, http.StatusInternalServerError) } - if err = chttp.BodylessResponse(ctx); err != nil { + if err = chttp.BodilessResponse(ctx); err != nil { return h.handleErrorAndLog(err, http.StatusInternalServerError) } diff --git a/pkg/server/endpoints/harvester_test.go b/pkg/server/endpoints/harvester_test.go index c86e7f15..8c79968d 100644 --- a/pkg/server/endpoints/harvester_test.go +++ b/pkg/server/endpoints/harvester_test.go @@ -47,7 +47,7 @@ func NewHarvesterTestSetup(t *testing.T, method, url string, body interface{}) * } func SetupTrustDomain(t *testing.T, ds datastore.Datastore) (*entity.TrustDomain, error) { - td, err := spiffeid.TrustDomainFromString(testTrustDomain) + td, err := spiffeid.TrustDomainFromString(td1) assert.NoError(t, err) tdEntity := &entity.TrustDomain{ @@ -80,7 +80,7 @@ func TestTCPBundlePut(t *testing.T) { Signature: "", SigningCertificate: "", TrustBundle: "a new bundle", - TrustDomain: testTrustDomain, + TrustDomain: td1, } harvesterTestSetup := NewHarvesterTestSetup(t, http.MethodPut, "/trust-domain/:trustDomainName/bundles", bundlePut) @@ -97,7 +97,7 @@ func TestTCPBundlePut(t *testing.T) { echoCtx.Set(tokenKey, jt) // Test Main Objective - err = harvesterTestSetup.Handler.BundlePut(echoCtx, testTrustDomain) + err = harvesterTestSetup.Handler.BundlePut(echoCtx, td1) assert.NoError(t, err) recorder := harvesterTestSetup.Recorder diff --git a/pkg/server/endpoints/management.go b/pkg/server/endpoints/management.go index d8396325..e1d3910d 100644 --- a/pkg/server/endpoints/management.go +++ b/pkg/server/endpoints/management.go @@ -35,7 +35,7 @@ func NewAdminAPIHandlers(l logrus.FieldLogger, ds datastore.Datastore) *AdminAPI } // GetRelationships list all relationships filtered by the request params - (GET /relationships) -func (h AdminAPIHandlers) GetRelationships(ctx echo.Context, params admin.GetRelationshipsParams) error { +func (h *AdminAPIHandlers) GetRelationships(ctx echo.Context, params admin.GetRelationshipsParams) error { gctx := ctx.Request().Context() var err error @@ -45,19 +45,19 @@ func (h AdminAPIHandlers) GetRelationships(ctx echo.Context, params admin.GetRel td, err := h.findTrustDomainByName(gctx, *params.TrustDomainName) if err != nil { err = fmt.Errorf("failed parsing trust domain name: %v", err) - return h.HandleAndLog(err, http.StatusBadRequest) + return h.handleAndLog(err, http.StatusBadRequest) } rels, err = h.Datastore.FindRelationshipsByTrustDomainID(gctx, td.ID.UUID) if err != nil { err = fmt.Errorf("failed listing relationships: %v", err) - return h.HandleAndLog(err, http.StatusInternalServerError) + return h.handleAndLog(err, http.StatusInternalServerError) } } else { rels, err = h.Datastore.ListRelationships(gctx) if err != nil { err = fmt.Errorf("failed listing relationships: %v", err) - return h.HandleAndLog(err, http.StatusInternalServerError) + return h.handleAndLog(err, http.StatusInternalServerError) } } @@ -69,14 +69,14 @@ func (h AdminAPIHandlers) GetRelationships(ctx echo.Context, params admin.GetRel rels, err = h.populateTrustDomainNames(gctx, rels) if err != nil { err = fmt.Errorf("failed populating relationships entities: %v", err) - return h.HandleAndLog(err, http.StatusInternalServerError) + return h.handleAndLog(err, http.StatusInternalServerError) } cRelationships := mapRelationships(rels) err = chttp.WriteResponse(ctx, cRelationships) if err != nil { err = fmt.Errorf("relationships entities - %v", err.Error()) - return h.HandleAndLog(err, http.StatusInternalServerError) + return h.handleAndLog(err, http.StatusInternalServerError) } return nil @@ -90,14 +90,17 @@ func (h AdminAPIHandlers) PutRelationships(ctx echo.Context) error { err := chttp.FromBody(ctx, reqBody) if err != nil { err := fmt.Errorf("failed to read relationship put body: %v", err) - return h.HandleAndLog(err, http.StatusBadRequest) + return h.handleAndLog(err, http.StatusBadRequest) } + // Possible scenario when a fake trust domain uuid is used will fail to create + // a relationship and a bad request should be raised. + // Should we query the trust domains before trying to create a relation ?? eRelationship := reqBody.ToEntity() rel, err := h.Datastore.CreateOrUpdateRelationship(gctx, eRelationship) if err != nil { err = fmt.Errorf("failed creating relationship: %v", err) - return h.HandleAndLog(err, http.StatusInternalServerError) + return h.handleAndLog(err, http.StatusInternalServerError) } h.Logger.Printf("Created relationship between trust domains %s and %s", rel.TrustDomainAID, rel.TrustDomainBID) @@ -106,7 +109,7 @@ func (h AdminAPIHandlers) PutRelationships(ctx echo.Context) error { err = chttp.WriteResponse(ctx, response) if err != nil { err = fmt.Errorf("relationships - %v", err.Error()) - return h.HandleAndLog(err, http.StatusInternalServerError) + return h.handleAndLog(err, http.StatusInternalServerError) } return nil @@ -119,14 +122,14 @@ func (h AdminAPIHandlers) GetRelationshipsRelationshipID(ctx echo.Context, relat r, err := h.Datastore.FindRelationshipByID(gctx, relationshipID) if err != nil { err = fmt.Errorf("failed getting relationships: %v", err) - return h.HandleAndLog(err, http.StatusInternalServerError) + return h.handleAndLog(err, http.StatusInternalServerError) } response := api.RelationshipFromEntity(r) err = chttp.WriteResponse(ctx, response) if err != nil { err = fmt.Errorf("relationship entity - %v", err.Error()) - return h.HandleAndLog(err, http.StatusInternalServerError) + return h.handleAndLog(err, http.StatusInternalServerError) } return nil @@ -140,28 +143,28 @@ func (h AdminAPIHandlers) PutTrustDomain(ctx echo.Context) error { reqBody := &admin.PutTrustDomainJSONRequestBody{} err := chttp.FromBody(ctx, reqBody) if err != nil { - return h.HandleAndLog(err, http.StatusBadRequest) + return h.handleAndLog(err, http.StatusBadRequest) } dbTD, err := reqBody.ToEntity() if err != nil { - return h.HandleAndLog(err, http.StatusBadRequest) + return h.handleAndLog(err, http.StatusBadRequest) } td, err := h.Datastore.FindTrustDomainByName(gctx, dbTD.Name) if err != nil { err = fmt.Errorf("failed looking up trust domain: %v", err) - return h.HandleAndLog(err, http.StatusInternalServerError) + return h.handleAndLog(err, http.StatusInternalServerError) } if td != nil { err = fmt.Errorf("trust domain already exists: %q", dbTD.Name) - return h.HandleAndLog(err, http.StatusInternalServerError) + return h.handleAndLog(err, http.StatusInternalServerError) } m, err := h.Datastore.CreateOrUpdateTrustDomain(gctx, dbTD) if err != nil { err = fmt.Errorf("failed creating trustDomain: %v", err) - return h.HandleAndLog(err, http.StatusInternalServerError) + return h.handleAndLog(err, http.StatusInternalServerError) } h.Logger.Printf("Created trustDomain for trust domain: %s", dbTD.Name) @@ -170,7 +173,7 @@ func (h AdminAPIHandlers) PutTrustDomain(ctx echo.Context) error { err = chttp.WriteResponse(ctx, response) if err != nil { err = fmt.Errorf("trustDomain entity - %v", err.Error()) - return h.HandleAndLog(err, http.StatusInternalServerError) + return h.handleAndLog(err, http.StatusInternalServerError) } return nil @@ -183,20 +186,20 @@ func (h AdminAPIHandlers) GetTrustDomainTrustDomainName(ctx echo.Context, trustD tdName, err := spiffeid.TrustDomainFromString(trustDomainName) if err != nil { err = fmt.Errorf("failed parsing trust domain name: %v", err) - return h.HandleAndLog(err, http.StatusBadRequest) + return h.handleAndLog(err, http.StatusBadRequest) } td, err := h.Datastore.FindTrustDomainByName(gctx, tdName) if err != nil { err = fmt.Errorf("failed getting trust domain: %v", err) - return h.HandleAndLog(err, http.StatusInternalServerError) + return h.handleAndLog(err, http.StatusInternalServerError) } response := api.TrustDomainFromEntity(td) err = chttp.WriteResponse(ctx, response) if err != nil { err = fmt.Errorf("trust domain entity - %v", err.Error()) - return h.HandleAndLog(err, http.StatusInternalServerError) + return h.handleAndLog(err, http.StatusInternalServerError) } return nil @@ -210,19 +213,19 @@ func (h AdminAPIHandlers) PutTrustDomainTrustDomainName(ctx echo.Context, trustD err := chttp.FromBody(ctx, reqBody) if err != nil { err := fmt.Errorf("failed to read trust domain put body: %v", err) - return h.HandleAndLog(err, http.StatusBadRequest) + return h.handleAndLog(err, http.StatusBadRequest) } etd, err := reqBody.ToEntity() if err != nil { err := fmt.Errorf("failed to read trust domain put body: %v", err) - return h.HandleAndLog(err, http.StatusBadRequest) + return h.handleAndLog(err, http.StatusBadRequest) } td, err := h.Datastore.CreateOrUpdateTrustDomain(gctx, etd) if err != nil { err = fmt.Errorf("failed creating/updating trust domain: %v", err) - return h.HandleAndLog(err, http.StatusInternalServerError) + return h.handleAndLog(err, http.StatusInternalServerError) } h.Logger.Printf("Trust Bundle %v created/updated", td.Name) @@ -231,7 +234,7 @@ func (h AdminAPIHandlers) PutTrustDomainTrustDomainName(ctx echo.Context, trustD err = chttp.WriteResponse(ctx, response) if err != nil { err = fmt.Errorf("relationships - %v", err.Error()) - return h.HandleAndLog(err, http.StatusInternalServerError) + return h.handleAndLog(err, http.StatusInternalServerError) } return nil @@ -248,13 +251,13 @@ func (h AdminAPIHandlers) PostTrustDomainTrustDomainNameJoinToken(ctx echo.Conte if td == nil { err = fmt.Errorf("trust domain does not exists %v", trustDomainName) - return h.HandleAndLog(err, http.StatusBadRequest) + return h.handleAndLog(err, http.StatusBadRequest) } token, err := util.GenerateToken() if err != nil { err = fmt.Errorf("failed generating a new join token %v", err) - return h.HandleAndLog(err, http.StatusInternalServerError) + return h.handleAndLog(err, http.StatusInternalServerError) } jt := &entity.JoinToken{ @@ -266,7 +269,7 @@ func (h AdminAPIHandlers) PostTrustDomainTrustDomainNameJoinToken(ctx echo.Conte jt, err = h.Datastore.CreateJoinToken(gctx, jt) if err != nil { err = fmt.Errorf("failed creating the join token: %v", err) - return h.HandleAndLog(err, http.StatusInternalServerError) + return h.handleAndLog(err, http.StatusInternalServerError) } h.Logger.Printf("join token successfully created for %v", td.Name) @@ -278,29 +281,29 @@ func (h AdminAPIHandlers) PostTrustDomainTrustDomainNameJoinToken(ctx echo.Conte err = chttp.WriteResponse(ctx, response) if err != nil { err = fmt.Errorf("relationships - %v", err.Error()) - return h.HandleAndLog(err, http.StatusInternalServerError) + return h.handleAndLog(err, http.StatusInternalServerError) } return nil } -func (h AdminAPIHandlers) findTrustDomainByName(ctx context.Context, trustDomain string) (*entity.TrustDomain, error) { +func (h *AdminAPIHandlers) findTrustDomainByName(ctx context.Context, trustDomain string) (*entity.TrustDomain, error) { tdName, err := spiffeid.TrustDomainFromString(trustDomain) if err != nil { err = fmt.Errorf("failed parsing trust domain name: %v", err) - return nil, h.HandleAndLog(err, http.StatusBadRequest) + return nil, h.handleAndLog(err, http.StatusBadRequest) } td, err := h.Datastore.FindTrustDomainByName(ctx, tdName) if err != nil { err = fmt.Errorf("failed getting trust domain: %v", err) - return nil, h.HandleAndLog(err, http.StatusInternalServerError) + return nil, h.handleAndLog(err, http.StatusInternalServerError) } return td, nil } -func (h AdminAPIHandlers) filterRelationshipsByStatus( +func (h *AdminAPIHandlers) filterRelationshipsByStatus( ctx context.Context, relationships []*entity.Relationship, status *admin.GetRelationshipsParamsStatus, @@ -320,13 +323,13 @@ func (h AdminAPIHandlers) filterRelationshipsByStatus( "unrecognized status filter %v, accepted values [%v, %v, %v]", *status, admin.Denied, admin.Approved, admin.Pending, ) - return nil, h.HandleAndLog(err, http.StatusBadRequest) + return nil, h.handleAndLog(err, http.StatusBadRequest) } else { return filterBy(relationships, pendingRelationFilter), nil } } -func (h AdminAPIHandlers) populateTrustDomainNames(ctx context.Context, relationships []*entity.Relationship) ([]*entity.Relationship, error) { +func (h *AdminAPIHandlers) populateTrustDomainNames(ctx context.Context, relationships []*entity.Relationship) ([]*entity.Relationship, error) { for _, r := range relationships { tda, err := h.Datastore.FindTrustDomainByID(ctx, r.TrustDomainAID) if err != nil { @@ -354,7 +357,7 @@ func mapRelationships(relationships []*entity.Relationship) []*api.Relationship return cRelationships } -func (h AdminAPIHandlers) HandleAndLog(err error, code int) error { +func (h *AdminAPIHandlers) handleAndLog(err error, code int) error { errMsg := util.LogSanitize(err.Error()) h.Logger.Errorf(errMsg) return echo.NewHTTPError(code, err.Error()) diff --git a/pkg/server/endpoints/management_test.go b/pkg/server/endpoints/management_test.go index 92f5c480..b6eeac38 100644 --- a/pkg/server/endpoints/management_test.go +++ b/pkg/server/endpoints/management_test.go @@ -2,6 +2,7 @@ package endpoints import ( "encoding/json" + "fmt" "io" "net/http" "net/http/httptest" @@ -24,6 +25,12 @@ type ManagementTestSetup struct { Handler *AdminAPIHandlers Recorder *httptest.ResponseRecorder FakeDatabase *datastore.FakeDatabase + + // Helpers + bodyReader io.Reader + + url string + method string } func NewManagementTestSetup(t *testing.T, method, url string, body interface{}) *ManagementTestSetup { @@ -46,39 +53,55 @@ func NewManagementTestSetup(t *testing.T, method, url string, body interface{}) Recorder: rec, Handler: NewAdminAPIHandlers(logger, fakeDB), FakeDatabase: fakeDB, + // Helpers + url: url, + method: method, + bodyReader: bodyReader, } } +func (setup *ManagementTestSetup) Refresh() { + e := echo.New() + req := httptest.NewRequest(setup.method, setup.url, setup.bodyReader) + req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) + rec := httptest.NewRecorder() + + // Refreshing Request context and Recorder + setup.EchoCtx = e.NewContext(req, rec) + setup.Recorder = rec +} + func TestUDSGetRelationships(t *testing.T) { t.Run("Successfully filter by trust domain", func(t *testing.T) { - // Setup managementTestSetup := NewManagementTestSetup(t, http.MethodGet, "/relationships", nil) echoCtx := managementTestSetup.EchoCtx - // Creating fake trust bundles and relationships to be filtered - td1Name := NewTrustDomain(t, testTrustDomain) + td1Name := NewTrustDomain(t, td1) tdUUID1 := NewNullableID() tdUUID2 := NewNullableID() tdUUID3 := NewNullableID() fakeTrustDomains := []*entity.TrustDomain{ {ID: tdUUID1, Name: td1Name}, - {ID: tdUUID2, Name: NewTrustDomain(t, "test2.com")}, - {ID: tdUUID3, Name: NewTrustDomain(t, "test3.com")}, + {ID: tdUUID2, Name: NewTrustDomain(t, td2)}, + {ID: tdUUID3, Name: NewTrustDomain(t, td3)}, } + r1ID := NewNullableID() + r2ID := NewNullableID() fakeRelationships := []*entity.Relationship{ - {ID: NewNullableID(), TrustDomainAID: tdUUID1.UUID, TrustDomainBID: tdUUID2.UUID, TrustDomainAConsent: false, TrustDomainBConsent: false}, - {ID: NewNullableID(), TrustDomainBID: tdUUID1.UUID, TrustDomainAID: tdUUID3.UUID, TrustDomainAConsent: false, TrustDomainBConsent: false}, + {ID: r1ID, TrustDomainAID: tdUUID1.UUID, TrustDomainBID: tdUUID2.UUID, TrustDomainAConsent: false, TrustDomainBConsent: false}, + {ID: r2ID, TrustDomainBID: tdUUID1.UUID, TrustDomainAID: tdUUID3.UUID, TrustDomainAConsent: false, TrustDomainBConsent: false}, + {ID: NewNullableID(), TrustDomainAID: uuid.New(), TrustDomainBID: uuid.New(), TrustDomainAConsent: true, TrustDomainBConsent: true}, + {ID: NewNullableID(), TrustDomainAID: uuid.New(), TrustDomainBID: uuid.New(), TrustDomainAConsent: true, TrustDomainBConsent: false}, {ID: NewNullableID(), TrustDomainAID: uuid.New(), TrustDomainBID: uuid.New(), TrustDomainAConsent: false, TrustDomainBConsent: false}, } - managementTestSetup.FakeDatabase.WithTrustDomains(fakeTrustDomains) - managementTestSetup.FakeDatabase.WithRelationships(fakeRelationships) + managementTestSetup.FakeDatabase.WithTrustDomains(fakeTrustDomains...) + managementTestSetup.FakeDatabase.WithRelationships(fakeRelationships...) - // managementTestSetup.Handler.Datastore - tdName := td1Name.String() + tdName := td1 params := admin.GetRelationshipsParams{ TrustDomainName: &tdName, } @@ -96,17 +119,178 @@ func TestUDSGetRelationships(t *testing.T) { assert.Len(t, relationships, 2) - // apiRelations := mapRelationships([]*entity.Relationship{ - // {TrustDomainAID: tdUUID1.UUID, TrustDomainBID: tdUUID2.UUID, TrustDomainAConsent: false, TrustDomainBConsent: false}, - // {TrustDomainBID: tdUUID1.UUID, TrustDomainAID: tdUUID3.UUID, TrustDomainAConsent: false, TrustDomainBConsent: false}, - // }) + apiRelations := mapRelationships([]*entity.Relationship{ + {ID: r1ID, TrustDomainAID: tdUUID1.UUID, TrustDomainBID: tdUUID2.UUID, TrustDomainAConsent: false, TrustDomainBConsent: false}, + {ID: r2ID, TrustDomainBID: tdUUID1.UUID, TrustDomainAID: tdUUID3.UUID, TrustDomainAConsent: false, TrustDomainBConsent: false}, + }) - // assert.ElementsMatchf(t, relationships, apiRelations, "filter does not work properly") + assert.ElementsMatch(t, relationships, apiRelations, "trust domain name filter does not work properly") + }) + + t.Run("Successfully filter by status", func(t *testing.T) { + // Setup + setup := NewManagementTestSetup(t, http.MethodGet, "/relationships", nil) + + td1Name := NewTrustDomain(t, td1) + tdUUID1 := NewNullableID() + tdUUID2 := NewNullableID() + tdUUID3 := NewNullableID() + + fakeTrustDomains := []*entity.TrustDomain{ + {ID: tdUUID1, Name: td1Name}, + {ID: tdUUID2, Name: NewTrustDomain(t, td2)}, + {ID: tdUUID3, Name: NewTrustDomain(t, td3)}, + } + + r1ID := NewNullableID() + r2ID := NewNullableID() + r3ID := NewNullableID() + fakeRelationships := []*entity.Relationship{ + {ID: r1ID, TrustDomainAID: tdUUID1.UUID, TrustDomainBID: tdUUID3.UUID, TrustDomainAConsent: true, TrustDomainBConsent: true}, + {ID: r2ID, TrustDomainAID: tdUUID1.UUID, TrustDomainBID: tdUUID2.UUID, TrustDomainAConsent: false, TrustDomainBConsent: false}, + {ID: r3ID, TrustDomainAID: tdUUID2.UUID, TrustDomainBID: tdUUID3.UUID, TrustDomainAConsent: false, TrustDomainBConsent: true}, + } + + setup.FakeDatabase.WithTrustDomains(fakeTrustDomains...) + setup.FakeDatabase.WithRelationships(fakeRelationships...) + + // Approved filter + status := admin.Approved + params := admin.GetRelationshipsParams{ + Status: &status, + } + + err := setup.Handler.GetRelationships(setup.EchoCtx, params) + assert.NoError(t, err) + + assert.Equal(t, http.StatusOK, setup.Recorder.Code) + assert.NotEmpty(t, setup.Recorder.Body) + + relationships := []*api.Relationship{} + err = json.Unmarshal(setup.Recorder.Body.Bytes(), &relationships) + assert.NoError(t, err) + + assert.Len(t, relationships, 1) + + apiRelations := mapRelationships([]*entity.Relationship{ + {ID: r1ID, TrustDomainAID: tdUUID1.UUID, TrustDomainBID: tdUUID3.UUID, TrustDomainAConsent: true, TrustDomainBConsent: true}, + }) + + assert.ElementsMatchf(t, relationships, apiRelations, "%v status filter does not work properly", admin.Approved) + + // Denied + setup.Refresh() + + status = admin.Denied + params = admin.GetRelationshipsParams{ + Status: &status, + } + + err = setup.Handler.GetRelationships(setup.EchoCtx, params) + assert.NoError(t, err) + + assert.Equal(t, http.StatusOK, setup.Recorder.Code) + assert.NotEmpty(t, setup.Recorder.Body) + + relationships = []*api.Relationship{} + err = json.Unmarshal(setup.Recorder.Body.Bytes(), &relationships) + assert.NoError(t, err) + + assert.Len(t, relationships, 2) + + apiRelations = mapRelationships([]*entity.Relationship{ + {ID: r2ID, TrustDomainAID: tdUUID1.UUID, TrustDomainBID: tdUUID2.UUID, TrustDomainAConsent: false, TrustDomainBConsent: false}, + {ID: r3ID, TrustDomainAID: tdUUID2.UUID, TrustDomainBID: tdUUID3.UUID, TrustDomainAConsent: false, TrustDomainBConsent: true}, + }) + + assert.ElementsMatchf(t, relationships, apiRelations, "%v status filter does not work properly", admin.Denied) + + // Pending + setup.Refresh() + + status = admin.Pending + params = admin.GetRelationshipsParams{ + Status: &status, + } + + err = setup.Handler.GetRelationships(setup.EchoCtx, params) + assert.NoError(t, err) + + assert.Equal(t, http.StatusOK, setup.Recorder.Code) + assert.NotEmpty(t, setup.Recorder.Body) + + relationships = []*api.Relationship{} + err = json.Unmarshal(setup.Recorder.Body.Bytes(), &relationships) + assert.NoError(t, err) + + assert.Len(t, relationships, 2) + + apiRelations = mapRelationships([]*entity.Relationship{ + {ID: r2ID, TrustDomainAID: tdUUID1.UUID, TrustDomainBID: tdUUID2.UUID, TrustDomainAConsent: false, TrustDomainBConsent: false}, + {ID: r3ID, TrustDomainAID: tdUUID2.UUID, TrustDomainBID: tdUUID3.UUID, TrustDomainAConsent: false, TrustDomainBConsent: true}, + }) + + assert.ElementsMatchf(t, relationships, apiRelations, "%v status filter does not work properly", admin.Pending) + }) + + t.Run("Should raise a bad request when receiving undefined status filter", func(t *testing.T) { + + // Setup + setup := NewManagementTestSetup(t, http.MethodGet, "/relationships", nil) + + // Approved filter + var randomFilter admin.GetRelationshipsParamsStatus = "a random filter" + params := admin.GetRelationshipsParams{ + Status: &randomFilter, + } + + err := setup.Handler.GetRelationships(setup.EchoCtx, params) + assert.Error(t, err) + + httpErr := err.(*echo.HTTPError) + assert.Equal(t, http.StatusBadRequest, httpErr.Code) + assert.Empty(t, setup.Recorder.Body) + + expectedMsg := fmt.Sprintf( + "unrecognized status filter %v, accepted values [%v, %v, %v]", + randomFilter, admin.Denied, admin.Approved, admin.Pending, + ) + + assert.ErrorContains(t, err, expectedMsg) }) } func TestUDSPutRelationships(t *testing.T) { - t.Skip("Missing tests will be added when the API be implemented") + t.Run("Successfully create a new relationship request", func(t *testing.T) { + td1ID := NewNullableID() + td2ID := NewNullableID() + + fakeTrustDomains := []*entity.TrustDomain{ + {ID: td1ID, Name: NewTrustDomain(t, td1)}, + {ID: td2ID, Name: NewTrustDomain(t, td2)}, + } + + reqBody := &admin.PutRelationshipsJSONRequestBody{ + TrustDomainAId: td1ID.UUID, + TrustDomainBId: td2ID.UUID, + } + + // Setup + setup := NewManagementTestSetup(t, http.MethodPut, "/relationships", reqBody) + setup.FakeDatabase.WithTrustDomains(fakeTrustDomains...) + + err := setup.Handler.PutRelationships(setup.EchoCtx) + assert.NoError(t, err) + + assert.Equal(t, http.StatusOK, setup.Recorder.Code) + + apiRelation := api.Relationship{} + json.Unmarshal(setup.Recorder.Body.Bytes(), &apiRelation) + + assert.NotNil(t, apiRelation) + assert.Equal(t, td1ID.UUID, apiRelation.TrustDomainAId) + assert.Equal(t, td2ID.UUID, apiRelation.TrustDomainBId) + }) } func TestUDSGetRelationshipsRelationshipID(t *testing.T) { From a55e8faf5bcc1c403f15c3115a0b229f9b00999c Mon Sep 17 00:00:00 2001 From: Victor Vieira Barros Leal da Silveira Date: Tue, 9 May 2023 16:05:23 -0300 Subject: [PATCH 04/20] fix: Unmashaling assertion --- pkg/server/endpoints/management_test.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pkg/server/endpoints/management_test.go b/pkg/server/endpoints/management_test.go index b6eeac38..40093ebd 100644 --- a/pkg/server/endpoints/management_test.go +++ b/pkg/server/endpoints/management_test.go @@ -285,7 +285,8 @@ func TestUDSPutRelationships(t *testing.T) { assert.Equal(t, http.StatusOK, setup.Recorder.Code) apiRelation := api.Relationship{} - json.Unmarshal(setup.Recorder.Body.Bytes(), &apiRelation) + err = json.Unmarshal(setup.Recorder.Body.Bytes(), &apiRelation) + assert.NoError(t, err) assert.NotNil(t, apiRelation) assert.Equal(t, td1ID.UUID, apiRelation.TrustDomainAId) From a7edd5d20d129441c7c693666a4caead22dd3292 Mon Sep 17 00:00:00 2001 From: Victor Vieira Barros Leal da Silveira Date: Tue, 9 May 2023 16:23:41 -0300 Subject: [PATCH 05/20] fix: Removin code duplication --- pkg/server/endpoints/management_test.go | 86 ++++++++----------------- 1 file changed, 28 insertions(+), 58 deletions(-) diff --git a/pkg/server/endpoints/management_test.go b/pkg/server/endpoints/management_test.go index 40093ebd..78492572 100644 --- a/pkg/server/endpoints/management_test.go +++ b/pkg/server/endpoints/management_test.go @@ -154,83 +154,53 @@ func TestUDSGetRelationships(t *testing.T) { setup.FakeDatabase.WithTrustDomains(fakeTrustDomains...) setup.FakeDatabase.WithRelationships(fakeRelationships...) - // Approved filter - status := admin.Approved - params := admin.GetRelationshipsParams{ - Status: &status, - } - - err := setup.Handler.GetRelationships(setup.EchoCtx, params) - assert.NoError(t, err) - - assert.Equal(t, http.StatusOK, setup.Recorder.Code) - assert.NotEmpty(t, setup.Recorder.Body) + assertFilter := func( + t *testing.T, + setup *ManagementTestSetup, + expectedRelations []*api.Relationship, + status admin.GetRelationshipsParamsStatus, + ) { + setup.Refresh() - relationships := []*api.Relationship{} - err = json.Unmarshal(setup.Recorder.Body.Bytes(), &relationships) - assert.NoError(t, err) + strAddress := status + params := admin.GetRelationshipsParams{ + Status: &strAddress, + } - assert.Len(t, relationships, 1) + err := setup.Handler.GetRelationships(setup.EchoCtx, params) + assert.NoError(t, err) - apiRelations := mapRelationships([]*entity.Relationship{ - {ID: r1ID, TrustDomainAID: tdUUID1.UUID, TrustDomainBID: tdUUID3.UUID, TrustDomainAConsent: true, TrustDomainBConsent: true}, - }) + assert.Equal(t, http.StatusOK, setup.Recorder.Code) + assert.NotEmpty(t, setup.Recorder.Body) - assert.ElementsMatchf(t, relationships, apiRelations, "%v status filter does not work properly", admin.Approved) + relationships := []*api.Relationship{} + err = json.Unmarshal(setup.Recorder.Body.Bytes(), &relationships) + assert.NoError(t, err) - // Denied - setup.Refresh() + assert.Len(t, relationships, len(expectedRelations)) - status = admin.Denied - params = admin.GetRelationshipsParams{ - Status: &status, + assert.ElementsMatchf(t, relationships, expectedRelations, "%v status filter does not work properly", status) } - err = setup.Handler.GetRelationships(setup.EchoCtx, params) - assert.NoError(t, err) - - assert.Equal(t, http.StatusOK, setup.Recorder.Code) - assert.NotEmpty(t, setup.Recorder.Body) - - relationships = []*api.Relationship{} - err = json.Unmarshal(setup.Recorder.Body.Bytes(), &relationships) - assert.NoError(t, err) + expectedRelations := mapRelationships([]*entity.Relationship{ + {ID: r1ID, TrustDomainAID: tdUUID1.UUID, TrustDomainBID: tdUUID3.UUID, TrustDomainAConsent: true, TrustDomainBConsent: true}, + }) - assert.Len(t, relationships, 2) + assertFilter(t, setup, expectedRelations, admin.Approved) - apiRelations = mapRelationships([]*entity.Relationship{ + expectedRelations = mapRelationships([]*entity.Relationship{ {ID: r2ID, TrustDomainAID: tdUUID1.UUID, TrustDomainBID: tdUUID2.UUID, TrustDomainAConsent: false, TrustDomainBConsent: false}, {ID: r3ID, TrustDomainAID: tdUUID2.UUID, TrustDomainBID: tdUUID3.UUID, TrustDomainAConsent: false, TrustDomainBConsent: true}, }) - assert.ElementsMatchf(t, relationships, apiRelations, "%v status filter does not work properly", admin.Denied) - - // Pending - setup.Refresh() - - status = admin.Pending - params = admin.GetRelationshipsParams{ - Status: &status, - } - - err = setup.Handler.GetRelationships(setup.EchoCtx, params) - assert.NoError(t, err) - - assert.Equal(t, http.StatusOK, setup.Recorder.Code) - assert.NotEmpty(t, setup.Recorder.Body) - - relationships = []*api.Relationship{} - err = json.Unmarshal(setup.Recorder.Body.Bytes(), &relationships) - assert.NoError(t, err) - - assert.Len(t, relationships, 2) + assertFilter(t, setup, expectedRelations, admin.Denied) - apiRelations = mapRelationships([]*entity.Relationship{ + expectedRelations = mapRelationships([]*entity.Relationship{ {ID: r2ID, TrustDomainAID: tdUUID1.UUID, TrustDomainBID: tdUUID2.UUID, TrustDomainAConsent: false, TrustDomainBConsent: false}, {ID: r3ID, TrustDomainAID: tdUUID2.UUID, TrustDomainBID: tdUUID3.UUID, TrustDomainAConsent: false, TrustDomainBConsent: true}, }) - assert.ElementsMatchf(t, relationships, apiRelations, "%v status filter does not work properly", admin.Pending) + assertFilter(t, setup, expectedRelations, admin.Pending) }) t.Run("Should raise a bad request when receiving undefined status filter", func(t *testing.T) { From c6218019e94099390d1bb80d739fd358404f977a Mon Sep 17 00:00:00 2001 From: Victor Vieira Barros Leal da Silveira Date: Tue, 9 May 2023 16:25:53 -0300 Subject: [PATCH 06/20] fix: Organization --- pkg/server/endpoints/management_test.go | 57 +++++++++++++------------ 1 file changed, 29 insertions(+), 28 deletions(-) diff --git a/pkg/server/endpoints/management_test.go b/pkg/server/endpoints/management_test.go index 78492572..0edc6103 100644 --- a/pkg/server/endpoints/management_test.go +++ b/pkg/server/endpoints/management_test.go @@ -145,6 +145,7 @@ func TestUDSGetRelationships(t *testing.T) { r1ID := NewNullableID() r2ID := NewNullableID() r3ID := NewNullableID() + fakeRelationships := []*entity.Relationship{ {ID: r1ID, TrustDomainAID: tdUUID1.UUID, TrustDomainBID: tdUUID3.UUID, TrustDomainAConsent: true, TrustDomainBConsent: true}, {ID: r2ID, TrustDomainAID: tdUUID1.UUID, TrustDomainBID: tdUUID2.UUID, TrustDomainAConsent: false, TrustDomainBConsent: false}, @@ -154,34 +155,6 @@ func TestUDSGetRelationships(t *testing.T) { setup.FakeDatabase.WithTrustDomains(fakeTrustDomains...) setup.FakeDatabase.WithRelationships(fakeRelationships...) - assertFilter := func( - t *testing.T, - setup *ManagementTestSetup, - expectedRelations []*api.Relationship, - status admin.GetRelationshipsParamsStatus, - ) { - setup.Refresh() - - strAddress := status - params := admin.GetRelationshipsParams{ - Status: &strAddress, - } - - err := setup.Handler.GetRelationships(setup.EchoCtx, params) - assert.NoError(t, err) - - assert.Equal(t, http.StatusOK, setup.Recorder.Code) - assert.NotEmpty(t, setup.Recorder.Body) - - relationships := []*api.Relationship{} - err = json.Unmarshal(setup.Recorder.Body.Bytes(), &relationships) - assert.NoError(t, err) - - assert.Len(t, relationships, len(expectedRelations)) - - assert.ElementsMatchf(t, relationships, expectedRelations, "%v status filter does not work properly", status) - } - expectedRelations := mapRelationships([]*entity.Relationship{ {ID: r1ID, TrustDomainAID: tdUUID1.UUID, TrustDomainBID: tdUUID3.UUID, TrustDomainAConsent: true, TrustDomainBConsent: true}, }) @@ -230,6 +203,34 @@ func TestUDSGetRelationships(t *testing.T) { }) } +func assertFilter( + t *testing.T, + setup *ManagementTestSetup, + expectedRelations []*api.Relationship, + status admin.GetRelationshipsParamsStatus, +) { + setup.Refresh() + + strAddress := status + params := admin.GetRelationshipsParams{ + Status: &strAddress, + } + + err := setup.Handler.GetRelationships(setup.EchoCtx, params) + assert.NoError(t, err) + + assert.Equal(t, http.StatusOK, setup.Recorder.Code) + assert.NotEmpty(t, setup.Recorder.Body) + + relationships := []*api.Relationship{} + err = json.Unmarshal(setup.Recorder.Body.Bytes(), &relationships) + assert.NoError(t, err) + + assert.Len(t, relationships, len(expectedRelations)) + + assert.ElementsMatchf(t, relationships, expectedRelations, "%v status filter does not work properly", status) +} + func TestUDSPutRelationships(t *testing.T) { t.Run("Successfully create a new relationship request", func(t *testing.T) { td1ID := NewNullableID() From 4b49fccfc58e038b9501325ca47d3d966f2ee2c2 Mon Sep 17 00:00:00 2001 From: Victor Vieira Barros Leal da Silveira Date: Wed, 10 May 2023 15:41:07 -0300 Subject: [PATCH 07/20] feat: Adding more unit tests --- pkg/common/http/http.go | 6 +- pkg/common/http/http_test.go | 13 ++- pkg/server/endpoints/harvester.go | 2 +- pkg/server/endpoints/management.go | 77 +++++++----- pkg/server/endpoints/management_test.go | 149 ++++++++++++++++++++++-- 5 files changed, 204 insertions(+), 43 deletions(-) diff --git a/pkg/common/http/http.go b/pkg/common/http/http.go index 1014f2ab..83e85dd7 100644 --- a/pkg/common/http/http.go +++ b/pkg/common/http/http.go @@ -9,12 +9,12 @@ import ( ) // WriteResponse parses a struct into a json and writes in the response -func WriteResponse(ctx echo.Context, body interface{}) error { +func WriteResponse(ctx echo.Context, code int, body interface{}) error { if body == nil { return errors.New("body is required") } - if err := ctx.JSON(http.StatusOK, body); err != nil { + if err := ctx.JSON(code, body); err != nil { return fmt.Errorf("failed to write response body: %v", err) } @@ -22,7 +22,7 @@ func WriteResponse(ctx echo.Context, body interface{}) error { } // BodilessResponse wraps error echo body-less responses. -func BodilessResponse(ctx echo.Context) error { +func BodilessResponse(ctx echo.Context, code int) error { if err := ctx.NoContent(http.StatusOK); err != nil { return fmt.Errorf("failed to respond without body: %v", err) } diff --git a/pkg/common/http/http_test.go b/pkg/common/http/http_test.go index 26dea5c6..f8b0f924 100644 --- a/pkg/common/http/http_test.go +++ b/pkg/common/http/http_test.go @@ -34,21 +34,22 @@ func Setup() *HTTPSetup { func TestWriteResponse(t *testing.T) { t.Run("Error when nil body is passed", func(t *testing.T) { setup := Setup() - err := WriteResponse(setup.EchoContext, nil) + err := WriteResponse(setup.EchoContext, 0, nil) assert.EqualError(t, err, "body is required") assert.Empty(t, setup.Recorder.Body) }) t.Run("No error when an empty body is passed", func(t *testing.T) { setup := Setup() - err := WriteResponse(setup.EchoContext, TestBody{}) + err := WriteResponse(setup.EchoContext, http.StatusOK, TestBody{}) assert.NoError(t, err) + assert.Equal(t, http.StatusOK, setup.Recorder.Code) }) t.Run("Ensuring that the body is being full filled with the entity", func(t *testing.T) { expectedResponseBody := TestBody{Name: "teste"} setup := Setup() - err := WriteResponse(setup.EchoContext, expectedResponseBody) + err := WriteResponse(setup.EchoContext, http.StatusOK, expectedResponseBody) assert.NoError(t, err) responseBody := TestBody{} @@ -60,10 +61,10 @@ func TestWriteResponse(t *testing.T) { }) } -func TestBodylessResponse(t *testing.T) { +func TestBodilessResponse(t *testing.T) { t.Run("Ensuring that the body is empty", func(t *testing.T) { setup := Setup() - err := BodilessResponse(setup.EchoContext) + err := BodilessResponse(setup.EchoContext, http.StatusOK) assert.NoError(t, err) assert.NoError(t, err) @@ -75,7 +76,7 @@ func TestBodylessResponse(t *testing.T) { func TestFromBody(t *testing.T) { t.Run("Ensuring that the body is empty", func(t *testing.T) { setup := Setup() - err := BodilessResponse(setup.EchoContext) + err := BodilessResponse(setup.EchoContext, http.StatusOK) assert.NoError(t, err) assert.NoError(t, err) diff --git a/pkg/server/endpoints/harvester.go b/pkg/server/endpoints/harvester.go index 1ce83521..c4c11c7c 100644 --- a/pkg/server/endpoints/harvester.go +++ b/pkg/server/endpoints/harvester.go @@ -116,7 +116,7 @@ func (h HarvesterAPIHandlers) BundlePut(ctx echo.Context, trustDomainName api.Tr return h.handleErrorAndLog(err, http.StatusInternalServerError) } - if err = chttp.BodilessResponse(ctx); err != nil { + if err = chttp.BodilessResponse(ctx, http.StatusOK); err != nil { return h.handleErrorAndLog(err, http.StatusInternalServerError) } diff --git a/pkg/server/endpoints/management.go b/pkg/server/endpoints/management.go index e1d3910d..9e2a3388 100644 --- a/pkg/server/endpoints/management.go +++ b/pkg/server/endpoints/management.go @@ -2,6 +2,7 @@ package endpoints import ( "context" + "errors" "fmt" "net/http" "time" @@ -35,45 +36,45 @@ func NewAdminAPIHandlers(l logrus.FieldLogger, ds datastore.Datastore) *AdminAPI } // GetRelationships list all relationships filtered by the request params - (GET /relationships) -func (h *AdminAPIHandlers) GetRelationships(ctx echo.Context, params admin.GetRelationshipsParams) error { - gctx := ctx.Request().Context() +func (h *AdminAPIHandlers) GetRelationships(echoContext echo.Context, params admin.GetRelationshipsParams) error { + ctx := echoContext.Request().Context() var err error var rels []*entity.Relationship if params.TrustDomainName != nil { - td, err := h.findTrustDomainByName(gctx, *params.TrustDomainName) + td, err := h.findTrustDomainByName(ctx, *params.TrustDomainName) if err != nil { err = fmt.Errorf("failed parsing trust domain name: %v", err) return h.handleAndLog(err, http.StatusBadRequest) } - rels, err = h.Datastore.FindRelationshipsByTrustDomainID(gctx, td.ID.UUID) + rels, err = h.Datastore.FindRelationshipsByTrustDomainID(ctx, td.ID.UUID) if err != nil { err = fmt.Errorf("failed listing relationships: %v", err) return h.handleAndLog(err, http.StatusInternalServerError) } } else { - rels, err = h.Datastore.ListRelationships(gctx) + rels, err = h.Datastore.ListRelationships(ctx) if err != nil { err = fmt.Errorf("failed listing relationships: %v", err) return h.handleAndLog(err, http.StatusInternalServerError) } } - rels, err = h.filterRelationshipsByStatus(gctx, rels, params.Status) + rels, err = h.filterRelationshipsByStatus(ctx, rels, params.Status) if err != nil { return err } - rels, err = h.populateTrustDomainNames(gctx, rels) + rels, err = h.populateTrustDomainNames(ctx, rels) if err != nil { err = fmt.Errorf("failed populating relationships entities: %v", err) return h.handleAndLog(err, http.StatusInternalServerError) } cRelationships := mapRelationships(rels) - err = chttp.WriteResponse(ctx, cRelationships) + err = chttp.WriteResponse(echoContext, http.StatusOK, cRelationships) if err != nil { err = fmt.Errorf("relationships entities - %v", err.Error()) return h.handleAndLog(err, http.StatusInternalServerError) @@ -83,21 +84,22 @@ func (h *AdminAPIHandlers) GetRelationships(ctx echo.Context, params admin.GetRe } // PutRelationships create a new relationship request between two trust domains - (PUT /relationships) -func (h AdminAPIHandlers) PutRelationships(ctx echo.Context) error { - gctx := ctx.Request().Context() +func (h AdminAPIHandlers) PutRelationships(echoCtx echo.Context) error { + ctx := echoCtx.Request().Context() reqBody := &admin.PutRelationshipsJSONRequestBody{} - err := chttp.FromBody(ctx, reqBody) + err := chttp.FromBody(echoCtx, reqBody) if err != nil { err := fmt.Errorf("failed to read relationship put body: %v", err) return h.handleAndLog(err, http.StatusBadRequest) } - - // Possible scenario when a fake trust domain uuid is used will fail to create - // a relationship and a bad request should be raised. - // Should we query the trust domains before trying to create a relation ?? eRelationship := reqBody.ToEntity() - rel, err := h.Datastore.CreateOrUpdateRelationship(gctx, eRelationship) + + if err := h.checkTrustDomains(ctx, eRelationship.TrustDomainAID, eRelationship.TrustDomainBID); err != nil { + return err + } + + rel, err := h.Datastore.CreateOrUpdateRelationship(ctx, eRelationship) if err != nil { err = fmt.Errorf("failed creating relationship: %v", err) return h.handleAndLog(err, http.StatusInternalServerError) @@ -106,7 +108,7 @@ func (h AdminAPIHandlers) PutRelationships(ctx echo.Context) error { h.Logger.Printf("Created relationship between trust domains %s and %s", rel.TrustDomainAID, rel.TrustDomainBID) response := api.RelationshipFromEntity(rel) - err = chttp.WriteResponse(ctx, response) + err = chttp.WriteResponse(echoCtx, http.StatusOK, response) if err != nil { err = fmt.Errorf("relationships - %v", err.Error()) return h.handleAndLog(err, http.StatusInternalServerError) @@ -116,17 +118,22 @@ func (h AdminAPIHandlers) PutRelationships(ctx echo.Context) error { } // GetRelationshipsRelationshipID retrieve a specific relationship based on its id - (GET /relationships/{relationshipID}) -func (h AdminAPIHandlers) GetRelationshipsRelationshipID(ctx echo.Context, relationshipID api.UUID) error { - gctx := ctx.Request().Context() +func (h AdminAPIHandlers) GetRelationshipsRelationshipID(echoCtx echo.Context, relationshipID api.UUID) error { + ctx := echoCtx.Request().Context() - r, err := h.Datastore.FindRelationshipByID(gctx, relationshipID) + r, err := h.Datastore.FindRelationshipByID(ctx, relationshipID) if err != nil { err = fmt.Errorf("failed getting relationships: %v", err) return h.handleAndLog(err, http.StatusInternalServerError) } + if r == nil { + err = errors.New("relationship not found") + return h.handleAndLog(err, http.StatusNotFound) + } + response := api.RelationshipFromEntity(r) - err = chttp.WriteResponse(ctx, response) + err = chttp.WriteResponse(echoCtx, http.StatusOK, response) if err != nil { err = fmt.Errorf("relationship entity - %v", err.Error()) return h.handleAndLog(err, http.StatusInternalServerError) @@ -156,9 +163,10 @@ func (h AdminAPIHandlers) PutTrustDomain(ctx echo.Context) error { err = fmt.Errorf("failed looking up trust domain: %v", err) return h.handleAndLog(err, http.StatusInternalServerError) } + if td != nil { err = fmt.Errorf("trust domain already exists: %q", dbTD.Name) - return h.handleAndLog(err, http.StatusInternalServerError) + return h.handleAndLog(err, http.StatusBadRequest) } m, err := h.Datastore.CreateOrUpdateTrustDomain(gctx, dbTD) @@ -170,7 +178,7 @@ func (h AdminAPIHandlers) PutTrustDomain(ctx echo.Context) error { h.Logger.Printf("Created trustDomain for trust domain: %s", dbTD.Name) response := api.TrustDomainFromEntity(m) - err = chttp.WriteResponse(ctx, response) + err = chttp.WriteResponse(ctx, http.StatusCreated, response) if err != nil { err = fmt.Errorf("trustDomain entity - %v", err.Error()) return h.handleAndLog(err, http.StatusInternalServerError) @@ -196,7 +204,7 @@ func (h AdminAPIHandlers) GetTrustDomainTrustDomainName(ctx echo.Context, trustD } response := api.TrustDomainFromEntity(td) - err = chttp.WriteResponse(ctx, response) + err = chttp.WriteResponse(ctx, http.StatusOK, response) if err != nil { err = fmt.Errorf("trust domain entity - %v", err.Error()) return h.handleAndLog(err, http.StatusInternalServerError) @@ -231,7 +239,7 @@ func (h AdminAPIHandlers) PutTrustDomainTrustDomainName(ctx echo.Context, trustD h.Logger.Printf("Trust Bundle %v created/updated", td.Name) response := api.TrustDomainFromEntity(td) - err = chttp.WriteResponse(ctx, response) + err = chttp.WriteResponse(ctx, http.StatusOK, response) if err != nil { err = fmt.Errorf("relationships - %v", err.Error()) return h.handleAndLog(err, http.StatusInternalServerError) @@ -278,7 +286,7 @@ func (h AdminAPIHandlers) PostTrustDomainTrustDomainNameJoinToken(ctx echo.Conte Token: uuid.MustParse(jt.Token), } - err = chttp.WriteResponse(ctx, response) + err = chttp.WriteResponse(ctx, http.StatusOK, response) if err != nil { err = fmt.Errorf("relationships - %v", err.Error()) return h.handleAndLog(err, http.StatusInternalServerError) @@ -346,6 +354,23 @@ func (h *AdminAPIHandlers) populateTrustDomainNames(ctx context.Context, relatio return relationships, nil } +func (h *AdminAPIHandlers) checkTrustDomains(ctx context.Context, ids ...uuid.UUID) error { + for _, id := range ids { + td, err := h.Datastore.FindTrustDomainByID(ctx, id) + if err != nil { + err := fmt.Errorf("not able retrieve information about trust domain %w", err) + return h.handleAndLog(err, http.StatusInternalServerError) + } + + if td == nil { + err := fmt.Errorf("trust domain %v does not exists", id) + return h.handleAndLog(err, http.StatusBadRequest) + } + } + + return nil +} + func mapRelationships(relationships []*entity.Relationship) []*api.Relationship { cRelationships := []*api.Relationship{} diff --git a/pkg/server/endpoints/management_test.go b/pkg/server/endpoints/management_test.go index 0edc6103..8447aeed 100644 --- a/pkg/server/endpoints/management_test.go +++ b/pkg/server/endpoints/management_test.go @@ -34,7 +34,7 @@ type ManagementTestSetup struct { } func NewManagementTestSetup(t *testing.T, method, url string, body interface{}) *ManagementTestSetup { - var bodyReader io.Reader + var bodyReader io.Reader = nil if body != nil { bodyStr, err := json.Marshal(body) assert.NoError(t, err) @@ -72,9 +72,11 @@ func (setup *ManagementTestSetup) Refresh() { } func TestUDSGetRelationships(t *testing.T) { + relationshipsPath := "/relationships" + t.Run("Successfully filter by trust domain", func(t *testing.T) { // Setup - managementTestSetup := NewManagementTestSetup(t, http.MethodGet, "/relationships", nil) + managementTestSetup := NewManagementTestSetup(t, http.MethodGet, relationshipsPath, nil) echoCtx := managementTestSetup.EchoCtx td1Name := NewTrustDomain(t, td1) @@ -129,7 +131,7 @@ func TestUDSGetRelationships(t *testing.T) { t.Run("Successfully filter by status", func(t *testing.T) { // Setup - setup := NewManagementTestSetup(t, http.MethodGet, "/relationships", nil) + setup := NewManagementTestSetup(t, http.MethodGet, relationshipsPath, nil) td1Name := NewTrustDomain(t, td1) tdUUID1 := NewNullableID() @@ -179,7 +181,7 @@ func TestUDSGetRelationships(t *testing.T) { t.Run("Should raise a bad request when receiving undefined status filter", func(t *testing.T) { // Setup - setup := NewManagementTestSetup(t, http.MethodGet, "/relationships", nil) + setup := NewManagementTestSetup(t, http.MethodGet, relationshipsPath, nil) // Approved filter var randomFilter admin.GetRelationshipsParamsStatus = "a random filter" @@ -232,6 +234,8 @@ func assertFilter( } func TestUDSPutRelationships(t *testing.T) { + relationshipsPath := "/relationships" + t.Run("Successfully create a new relationship request", func(t *testing.T) { td1ID := NewNullableID() td2ID := NewNullableID() @@ -247,7 +251,7 @@ func TestUDSPutRelationships(t *testing.T) { } // Setup - setup := NewManagementTestSetup(t, http.MethodPut, "/relationships", reqBody) + setup := NewManagementTestSetup(t, http.MethodPut, relationshipsPath, reqBody) setup.FakeDatabase.WithTrustDomains(fakeTrustDomains...) err := setup.Handler.PutRelationships(setup.EchoCtx) @@ -263,14 +267,145 @@ func TestUDSPutRelationships(t *testing.T) { assert.Equal(t, td1ID.UUID, apiRelation.TrustDomainAId) assert.Equal(t, td2ID.UUID, apiRelation.TrustDomainBId) }) + + t.Run("Should not allow relationships request between inexistent trust domains", func(t *testing.T) { + td1ID := NewNullableID() + + // Creating a fake UUID that does not match with any trust domain ID in the database + td2ID := NewNullableID() + + fakeTrustDomains := []*entity.TrustDomain{ + {ID: td1ID, Name: NewTrustDomain(t, td1)}, + } + + reqBody := &admin.PutRelationshipsJSONRequestBody{ + TrustDomainAId: td1ID.UUID, + TrustDomainBId: td2ID.UUID, + } + + // Setup + setup := NewManagementTestSetup(t, http.MethodPut, relationshipsPath, reqBody) + setup.FakeDatabase.WithTrustDomains(fakeTrustDomains...) + + err := setup.Handler.PutRelationships(setup.EchoCtx) + assert.Error(t, err) + assert.Empty(t, setup.Recorder.Body.Bytes()) + + echoHTTPErr := err.(*echo.HTTPError) + assert.Equal(t, http.StatusBadRequest, echoHTTPErr.Code) + + expectedErrorMsg := fmt.Sprintf("trust domain %v does not exists", td2ID.UUID) + assert.Equal(t, expectedErrorMsg, echoHTTPErr.Message) + }) + + // Should we test sending wrong body formats ? } func TestUDSGetRelationshipsRelationshipID(t *testing.T) { - t.Skip("Missing tests will be added when the API be implemented") + relationshipsPath := "/relationships/%v" + + t.Run("Successfully get relationship information", func(t *testing.T) { + td1ID := NewNullableID() + td2ID := NewNullableID() + + fakeTrustDomains := []*entity.TrustDomain{ + {ID: td1ID, Name: NewTrustDomain(t, td1)}, + {ID: td2ID, Name: NewTrustDomain(t, td2)}, + } + + r1ID := NewNullableID() + fakeRelationship := &entity.Relationship{ + ID: r1ID, + TrustDomainAID: td1ID.UUID, + TrustDomainBID: td2ID.UUID, + } + + completePath := fmt.Sprintf(relationshipsPath, r1ID.UUID) + + // Setup + setup := NewManagementTestSetup(t, http.MethodGet, completePath, nil) + setup.FakeDatabase.WithTrustDomains(fakeTrustDomains...) + setup.FakeDatabase.WithRelationships(fakeRelationship) + + err := setup.Handler.GetRelationshipsRelationshipID(setup.EchoCtx, r1ID.UUID) + assert.NoError(t, err) + + assert.Equal(t, http.StatusOK, setup.Recorder.Code) + + apiRelation := api.Relationship{} + err = json.Unmarshal(setup.Recorder.Body.Bytes(), &apiRelation) + assert.NoError(t, err) + + assert.NotNil(t, apiRelation) + assert.Equal(t, td1ID.UUID, apiRelation.TrustDomainAId) + assert.Equal(t, td2ID.UUID, apiRelation.TrustDomainBId) + }) + + t.Run("Should raise a not found request when try to get information about a relationship that doesn't exists", func(t *testing.T) { + + // A random UUID that can represents a real ID + r1ID := NewNullableID() + completePath := fmt.Sprintf(relationshipsPath, r1ID.UUID) + + // Setup + setup := NewManagementTestSetup(t, http.MethodGet, completePath, nil) + + err := setup.Handler.GetRelationshipsRelationshipID(setup.EchoCtx, r1ID.UUID) + assert.Error(t, err) + assert.Empty(t, setup.Recorder.Body.Bytes()) + + echoHTTPerr := err.(*echo.HTTPError) + assert.Equal(t, http.StatusNotFound, echoHTTPerr.Code) + assert.Equal(t, "relationship not found", echoHTTPerr.Message) + }) } func TestUDSPutTrustDomain(t *testing.T) { - t.Skip("Missing tests will be added when the API be implemented") + trustDomainPath := "/trust-domain" + t.Run("Successfully create a new trust domain", func(t *testing.T) { + description := "A test trust domain" + reqBody := &admin.PutTrustDomainJSONRequestBody{ + Name: td1, + Description: &description, + } + + // Setup + setup := NewManagementTestSetup(t, http.MethodPut, trustDomainPath, reqBody) + + err := setup.Handler.PutTrustDomain(setup.EchoCtx) + assert.NoError(t, err) + + assert.Equal(t, http.StatusCreated, setup.Recorder.Code) + + apiTrustDomain := api.TrustDomain{} + err = json.Unmarshal(setup.Recorder.Body.Bytes(), &apiTrustDomain) + assert.NoError(t, err) + + assert.NotNil(t, apiTrustDomain) + assert.Equal(t, td1, apiTrustDomain.Name) + assert.Equal(t, description, *apiTrustDomain.Description) + + }) + + t.Run("Should not allow creating trust domain with the same name of one already created", func(t *testing.T) { + reqBody := &admin.PutTrustDomainJSONRequestBody{ + Name: td1, + } + + fakeTrustDomains := entity.TrustDomain{ID: NewNullableID(), Name: NewTrustDomain(t, td1)} + + // Setup + setup := NewManagementTestSetup(t, http.MethodPut, trustDomainPath, reqBody) + setup.FakeDatabase.WithTrustDomains(&fakeTrustDomains) + + err := setup.Handler.PutTrustDomain(setup.EchoCtx) + assert.Error(t, err) + + echoHttpErr := err.(*echo.HTTPError) + + assert.Equal(t, http.StatusBadRequest, echoHttpErr.Code) + assert.ErrorContains(t, echoHttpErr, "trust domain already exists") + }) } func TestUDSGetTrustDomainTrustDomainName(t *testing.T) { From 5f3dcbd0a109589a7d11b945c0e9c88511fcfd74 Mon Sep 17 00:00:00 2001 From: Victor Vieira Barros Leal da Silveira Date: Wed, 10 May 2023 15:44:27 -0300 Subject: [PATCH 08/20] feat: Changin return code for relationship request creation --- pkg/server/endpoints/management.go | 2 +- pkg/server/endpoints/management_test.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pkg/server/endpoints/management.go b/pkg/server/endpoints/management.go index 9e2a3388..261c7793 100644 --- a/pkg/server/endpoints/management.go +++ b/pkg/server/endpoints/management.go @@ -108,7 +108,7 @@ func (h AdminAPIHandlers) PutRelationships(echoCtx echo.Context) error { h.Logger.Printf("Created relationship between trust domains %s and %s", rel.TrustDomainAID, rel.TrustDomainBID) response := api.RelationshipFromEntity(rel) - err = chttp.WriteResponse(echoCtx, http.StatusOK, response) + err = chttp.WriteResponse(echoCtx, http.StatusCreated, response) if err != nil { err = fmt.Errorf("relationships - %v", err.Error()) return h.handleAndLog(err, http.StatusInternalServerError) diff --git a/pkg/server/endpoints/management_test.go b/pkg/server/endpoints/management_test.go index 8447aeed..ec640b11 100644 --- a/pkg/server/endpoints/management_test.go +++ b/pkg/server/endpoints/management_test.go @@ -257,7 +257,7 @@ func TestUDSPutRelationships(t *testing.T) { err := setup.Handler.PutRelationships(setup.EchoCtx) assert.NoError(t, err) - assert.Equal(t, http.StatusOK, setup.Recorder.Code) + assert.Equal(t, http.StatusCreated, setup.Recorder.Code) apiRelation := api.Relationship{} err = json.Unmarshal(setup.Recorder.Body.Bytes(), &apiRelation) From 9bc7b3a317f40c46f4335c3946343618b17349f5 Mon Sep 17 00:00:00 2001 From: Victor Vieira Barros Leal da Silveira Date: Thu, 11 May 2023 11:42:04 -0300 Subject: [PATCH 09/20] feat: Finishing unit tests --- pkg/server/datastore/fakedatabase.go | 32 +++--- pkg/server/endpoints/management.go | 59 +++++----- pkg/server/endpoints/management_test.go | 136 +++++++++++++++++++++++- 3 files changed, 184 insertions(+), 43 deletions(-) diff --git a/pkg/server/datastore/fakedatabase.go b/pkg/server/datastore/fakedatabase.go index eb256570..a500c373 100644 --- a/pkg/server/datastore/fakedatabase.go +++ b/pkg/server/datastore/fakedatabase.go @@ -41,14 +41,15 @@ func (db *FakeDatabase) CreateOrUpdateTrustDomain(ctx context.Context, req *enti return nil, err } - req.ID = uuid.NullUUID{ - UUID: uuid.New(), - Valid: true, + if !req.ID.Valid { + req.ID = uuid.NullUUID{ + UUID: uuid.New(), + Valid: true, + } + req.CreatedAt = time.Now() } - req.CreatedAt = time.Now() req.UpdatedAt = time.Now() - db.trustDomains[req.ID.UUID] = req return req, nil @@ -133,14 +134,15 @@ func (db *FakeDatabase) CreateOrUpdateBundle(ctx context.Context, req *entity.Bu return nil, err } - req.ID = uuid.NullUUID{ - UUID: uuid.New(), - Valid: true, + if !req.ID.Valid { + req.ID = uuid.NullUUID{ + UUID: uuid.New(), + Valid: true, + } + req.CreatedAt = time.Now() } - req.CreatedAt = time.Now() req.UpdatedAt = time.Now() - db.bundles[req.ID.UUID] = req return req, nil @@ -354,15 +356,15 @@ func (db *FakeDatabase) CreateOrUpdateRelationship(ctx context.Context, req *ent return nil, err } - if req.ID.Valid { - - } else { + if !req.ID.Valid { + req.ID = uuid.NullUUID{ + Valid: true, + UUID: uuid.New(), + } req.CreatedAt = time.Now() - } req.UpdatedAt = time.Now() - db.relationships[req.ID.UUID] = req return req, nil diff --git a/pkg/server/endpoints/management.go b/pkg/server/endpoints/management.go index 261c7793..65078770 100644 --- a/pkg/server/endpoints/management.go +++ b/pkg/server/endpoints/management.go @@ -95,7 +95,7 @@ func (h AdminAPIHandlers) PutRelationships(echoCtx echo.Context) error { } eRelationship := reqBody.ToEntity() - if err := h.checkTrustDomains(ctx, eRelationship.TrustDomainAID, eRelationship.TrustDomainBID); err != nil { + if err := h.checkTrustDomains(ctx, http.StatusBadRequest, eRelationship.TrustDomainAID, eRelationship.TrustDomainBID); err != nil { return err } @@ -143,12 +143,12 @@ func (h AdminAPIHandlers) GetRelationshipsRelationshipID(echoCtx echo.Context, r } // PutTrustDomain create a new trust domain - (PUT /trust-domain) -func (h AdminAPIHandlers) PutTrustDomain(ctx echo.Context) error { +func (h AdminAPIHandlers) PutTrustDomain(echoCtx echo.Context) error { // Getting golang context - gctx := ctx.Request().Context() + ctx := echoCtx.Request().Context() reqBody := &admin.PutTrustDomainJSONRequestBody{} - err := chttp.FromBody(ctx, reqBody) + err := chttp.FromBody(echoCtx, reqBody) if err != nil { return h.handleAndLog(err, http.StatusBadRequest) } @@ -158,7 +158,7 @@ func (h AdminAPIHandlers) PutTrustDomain(ctx echo.Context) error { return h.handleAndLog(err, http.StatusBadRequest) } - td, err := h.Datastore.FindTrustDomainByName(gctx, dbTD.Name) + td, err := h.Datastore.FindTrustDomainByName(ctx, dbTD.Name) if err != nil { err = fmt.Errorf("failed looking up trust domain: %v", err) return h.handleAndLog(err, http.StatusInternalServerError) @@ -169,7 +169,7 @@ func (h AdminAPIHandlers) PutTrustDomain(ctx echo.Context) error { return h.handleAndLog(err, http.StatusBadRequest) } - m, err := h.Datastore.CreateOrUpdateTrustDomain(gctx, dbTD) + m, err := h.Datastore.CreateOrUpdateTrustDomain(ctx, dbTD) if err != nil { err = fmt.Errorf("failed creating trustDomain: %v", err) return h.handleAndLog(err, http.StatusInternalServerError) @@ -178,7 +178,7 @@ func (h AdminAPIHandlers) PutTrustDomain(ctx echo.Context) error { h.Logger.Printf("Created trustDomain for trust domain: %s", dbTD.Name) response := api.TrustDomainFromEntity(m) - err = chttp.WriteResponse(ctx, http.StatusCreated, response) + err = chttp.WriteResponse(echoCtx, http.StatusCreated, response) if err != nil { err = fmt.Errorf("trustDomain entity - %v", err.Error()) return h.handleAndLog(err, http.StatusInternalServerError) @@ -188,8 +188,8 @@ func (h AdminAPIHandlers) PutTrustDomain(ctx echo.Context) error { } // GetTrustDomainTrustDomainName retrieve a specific trust domain by its name - (GET /trust-domain/{trustDomainName}) -func (h AdminAPIHandlers) GetTrustDomainTrustDomainName(ctx echo.Context, trustDomainName api.TrustDomainName) error { - gctx := ctx.Request().Context() +func (h AdminAPIHandlers) GetTrustDomainTrustDomainName(echoCtx echo.Context, trustDomainName api.TrustDomainName) error { + ctx := echoCtx.Request().Context() tdName, err := spiffeid.TrustDomainFromString(trustDomainName) if err != nil { @@ -197,14 +197,19 @@ func (h AdminAPIHandlers) GetTrustDomainTrustDomainName(ctx echo.Context, trustD return h.handleAndLog(err, http.StatusBadRequest) } - td, err := h.Datastore.FindTrustDomainByName(gctx, tdName) + td, err := h.Datastore.FindTrustDomainByName(ctx, tdName) if err != nil { err = fmt.Errorf("failed getting trust domain: %v", err) return h.handleAndLog(err, http.StatusInternalServerError) } + if td == nil { + err = fmt.Errorf("trust domain does not exists") + return h.handleAndLog(err, http.StatusNotFound) + } + response := api.TrustDomainFromEntity(td) - err = chttp.WriteResponse(ctx, http.StatusOK, response) + err = chttp.WriteResponse(echoCtx, http.StatusOK, response) if err != nil { err = fmt.Errorf("trust domain entity - %v", err.Error()) return h.handleAndLog(err, http.StatusInternalServerError) @@ -214,11 +219,11 @@ func (h AdminAPIHandlers) GetTrustDomainTrustDomainName(ctx echo.Context, trustD } // PutTrustDomainTrustDomainName updates the trust domain - (PUT /trust-domain/{trustDomainName}) -func (h AdminAPIHandlers) PutTrustDomainTrustDomainName(ctx echo.Context, trustDomainName api.UUID) error { - gctx := ctx.Request().Context() +func (h AdminAPIHandlers) PutTrustDomainTrustDomainName(echoCtx echo.Context, trustDomainID api.UUID) error { + ctx := echoCtx.Request().Context() reqBody := &admin.PutTrustDomainTrustDomainNameJSONRequestBody{} - err := chttp.FromBody(ctx, reqBody) + err := chttp.FromBody(echoCtx, reqBody) if err != nil { err := fmt.Errorf("failed to read trust domain put body: %v", err) return h.handleAndLog(err, http.StatusBadRequest) @@ -230,16 +235,20 @@ func (h AdminAPIHandlers) PutTrustDomainTrustDomainName(ctx echo.Context, trustD return h.handleAndLog(err, http.StatusBadRequest) } - td, err := h.Datastore.CreateOrUpdateTrustDomain(gctx, etd) + if err := h.checkTrustDomains(ctx, http.StatusNotFound, trustDomainID); err != nil { + return err + } + + td, err := h.Datastore.CreateOrUpdateTrustDomain(ctx, etd) if err != nil { err = fmt.Errorf("failed creating/updating trust domain: %v", err) return h.handleAndLog(err, http.StatusInternalServerError) } - h.Logger.Printf("Trust Bundle %v created/updated", td.Name) + h.Logger.Printf("Trust Bundle %v updated", td.Name) response := api.TrustDomainFromEntity(td) - err = chttp.WriteResponse(ctx, http.StatusOK, response) + err = chttp.WriteResponse(echoCtx, http.StatusOK, response) if err != nil { err = fmt.Errorf("relationships - %v", err.Error()) return h.handleAndLog(err, http.StatusInternalServerError) @@ -249,16 +258,16 @@ func (h AdminAPIHandlers) PutTrustDomainTrustDomainName(ctx echo.Context, trustD } // PostTrustDomainTrustDomainNameJoinToken generate a join token for the trust domain - (POST /trust-domain/{trustDomainName}/join-token) -func (h AdminAPIHandlers) PostTrustDomainTrustDomainNameJoinToken(ctx echo.Context, trustDomainName api.TrustDomainName) error { - gctx := ctx.Request().Context() +func (h AdminAPIHandlers) PostTrustDomainTrustDomainNameJoinToken(echoCtx echo.Context, trustDomainName api.TrustDomainName) error { + ctx := echoCtx.Request().Context() - td, err := h.findTrustDomainByName(gctx, trustDomainName) + td, err := h.findTrustDomainByName(ctx, trustDomainName) if err != nil { return err } if td == nil { - err = fmt.Errorf("trust domain does not exists %v", trustDomainName) + err = fmt.Errorf("trust domain %v does not exists ", trustDomainName) return h.handleAndLog(err, http.StatusBadRequest) } @@ -274,7 +283,7 @@ func (h AdminAPIHandlers) PostTrustDomainTrustDomainNameJoinToken(ctx echo.Conte ExpiresAt: time.Now().Add(1 * time.Hour), } - jt, err = h.Datastore.CreateJoinToken(gctx, jt) + jt, err = h.Datastore.CreateJoinToken(ctx, jt) if err != nil { err = fmt.Errorf("failed creating the join token: %v", err) return h.handleAndLog(err, http.StatusInternalServerError) @@ -286,7 +295,7 @@ func (h AdminAPIHandlers) PostTrustDomainTrustDomainNameJoinToken(ctx echo.Conte Token: uuid.MustParse(jt.Token), } - err = chttp.WriteResponse(ctx, http.StatusOK, response) + err = chttp.WriteResponse(echoCtx, http.StatusOK, response) if err != nil { err = fmt.Errorf("relationships - %v", err.Error()) return h.handleAndLog(err, http.StatusInternalServerError) @@ -354,7 +363,7 @@ func (h *AdminAPIHandlers) populateTrustDomainNames(ctx context.Context, relatio return relationships, nil } -func (h *AdminAPIHandlers) checkTrustDomains(ctx context.Context, ids ...uuid.UUID) error { +func (h *AdminAPIHandlers) checkTrustDomains(ctx context.Context, errCode int, ids ...uuid.UUID) error { for _, id := range ids { td, err := h.Datastore.FindTrustDomainByID(ctx, id) if err != nil { @@ -364,7 +373,7 @@ func (h *AdminAPIHandlers) checkTrustDomains(ctx context.Context, ids ...uuid.UU if td == nil { err := fmt.Errorf("trust domain %v does not exists", id) - return h.handleAndLog(err, http.StatusBadRequest) + return h.handleAndLog(err, errCode) } } diff --git a/pkg/server/endpoints/management_test.go b/pkg/server/endpoints/management_test.go index ec640b11..c3bb2226 100644 --- a/pkg/server/endpoints/management_test.go +++ b/pkg/server/endpoints/management_test.go @@ -409,15 +409,145 @@ func TestUDSPutTrustDomain(t *testing.T) { } func TestUDSGetTrustDomainTrustDomainName(t *testing.T) { - t.Skip("Missing tests will be added when the API be implemented") + trustDomainPath := "/trust-domain/%v" + + t.Run("Successfully retrieve trust domain information", func(t *testing.T) { + td1ID := NewNullableID() + fakeTrustDomains := entity.TrustDomain{ID: td1ID, Name: NewTrustDomain(t, td1)} + + completePath := fmt.Sprintf(trustDomainPath, td1ID.UUID) + + // Setup + setup := NewManagementTestSetup(t, http.MethodPut, completePath, nil) + setup.FakeDatabase.WithTrustDomains(&fakeTrustDomains) + + err := setup.Handler.GetTrustDomainTrustDomainName(setup.EchoCtx, td1) + assert.NoError(t, err) + assert.Equal(t, http.StatusOK, setup.Recorder.Code) + + apiTrustDomain := api.TrustDomain{} + err = json.Unmarshal(setup.Recorder.Body.Bytes(), &apiTrustDomain) + assert.NoError(t, err) + + assert.Equal(t, td1, apiTrustDomain.Name) + assert.Equal(t, td1ID.UUID, apiTrustDomain.Id) + }) + + t.Run("Raise a not found when trying to retrieve a trust domain that does not exists", func(t *testing.T) { + td1ID := NewNullableID() + completePath := fmt.Sprintf(trustDomainPath, td1ID.UUID) + + // Setup + setup := NewManagementTestSetup(t, http.MethodPut, completePath, nil) + + err := setup.Handler.GetTrustDomainTrustDomainName(setup.EchoCtx, td1) + assert.Error(t, err) + + echoHttpErr := err.(*echo.HTTPError) + assert.Equal(t, http.StatusNotFound, echoHttpErr.Code) + assert.Equal(t, "trust domain does not exists", echoHttpErr.Message) + }) } func TestUDSPutTrustDomainTrustDomainName(t *testing.T) { - t.Skip("Missing tests will be added when the API be implemented") + trustDomainPath := "/trust-domain/%v" + + t.Run("Successfully updated a trust domain", func(t *testing.T) { + td1ID := NewNullableID() + fakeTrustDomains := entity.TrustDomain{ID: td1ID, Name: NewTrustDomain(t, td1)} + + completePath := fmt.Sprintf(trustDomainPath, td1ID.UUID) + + description := "I am being updated" + reqBody := &admin.PutTrustDomainTrustDomainNameJSONRequestBody{ + Id: td1ID.UUID, + Name: td1, + Description: &description, + } + + // Setup + setup := NewManagementTestSetup(t, http.MethodPut, completePath, reqBody) + setup.FakeDatabase.WithTrustDomains(&fakeTrustDomains) + + err := setup.Handler.PutTrustDomainTrustDomainName(setup.EchoCtx, td1ID.UUID) + assert.NoError(t, err) + assert.Equal(t, http.StatusOK, setup.Recorder.Code) + + apiTrustDomain := api.TrustDomain{} + err = json.Unmarshal(setup.Recorder.Body.Bytes(), &apiTrustDomain) + assert.NoError(t, err) + + assert.Equal(t, td1, apiTrustDomain.Name) + assert.Equal(t, td1ID.UUID, apiTrustDomain.Id) + assert.Equal(t, description, *apiTrustDomain.Description) + }) + + t.Run("Raise a not found when trying to updated a trust domain that does not exists", func(t *testing.T) { + // Fake ID + td1ID := NewNullableID() + completePath := fmt.Sprintf(trustDomainPath, td1ID.UUID) + + // Fake Request body + description := "I am being updated" + reqBody := &admin.PutTrustDomainTrustDomainNameJSONRequestBody{ + Id: td1ID.UUID, + Name: td1, + Description: &description, + } + + // Setup + setup := NewManagementTestSetup(t, http.MethodPut, completePath, reqBody) + + err := setup.Handler.PutTrustDomainTrustDomainName(setup.EchoCtx, td1ID.UUID) + assert.Error(t, err) + assert.Empty(t, setup.Recorder.Body.Bytes()) + + echoHTTPErr := err.(*echo.HTTPError) + assert.Equal(t, http.StatusNotFound, echoHTTPErr.Code) + expectedErrorMsg := fmt.Sprintf("trust domain %v does not exists", td1ID.UUID) + assert.Equal(t, expectedErrorMsg, echoHTTPErr.Message) + }) } func TestUDSPostTrustDomainTrustDomainNameJoinToken(t *testing.T) { - t.Skip("Missing tests will be added when the API be implemented") + trustDomainPath := "/trust-domain/%v/join-token" + + t.Run("Successfully generates a join token for the trust domain", func(t *testing.T) { + td1ID := NewNullableID() + fakeTrustDomains := entity.TrustDomain{ID: td1ID, Name: NewTrustDomain(t, td1)} + + completePath := fmt.Sprintf(trustDomainPath, td1) + + // Setup + setup := NewManagementTestSetup(t, http.MethodPut, completePath, nil) + setup.FakeDatabase.WithTrustDomains(&fakeTrustDomains) + + err := setup.Handler.PostTrustDomainTrustDomainNameJoinToken(setup.EchoCtx, td1) + assert.NoError(t, err) + assert.Equal(t, http.StatusOK, setup.Recorder.Code) + + apiJToken := admin.JoinTokenResult{} + err = json.Unmarshal(setup.Recorder.Body.Bytes(), &apiJToken) + assert.NoError(t, err) + + assert.NotEmpty(t, apiJToken) + }) + + t.Run("Raise a bad request when trying to generates a join token for the trust domain that does not exists", func(t *testing.T) { + completePath := fmt.Sprintf(trustDomainPath, td1) + + // Setup + setup := NewManagementTestSetup(t, http.MethodPut, completePath, nil) + + err := setup.Handler.PostTrustDomainTrustDomainNameJoinToken(setup.EchoCtx, td1) + assert.Error(t, err) + + echoHttpErr := err.(*echo.HTTPError) + assert.Equal(t, http.StatusBadRequest, echoHttpErr.Code) + + expectedMsg := fmt.Sprintf("trust domain %v does not exists ", td1) + assert.Equal(t, expectedMsg, echoHttpErr.Message) + }) } func NewNullableID() uuid.NullUUID { From 46ca4124e869434e3664a0997c79c2d8aac5c0f8 Mon Sep 17 00:00:00 2001 From: Victor Vieira Barros Leal da Silveira Date: Thu, 11 May 2023 17:08:52 -0300 Subject: [PATCH 10/20] Update pkg/server/endpoints/management.go Co-authored-by: Max Lambrecht Signed-off-by: Victor Vieira Barros Leal da Silveira --- pkg/server/endpoints/management.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/server/endpoints/management.go b/pkg/server/endpoints/management.go index 65078770..c9ce25ef 100644 --- a/pkg/server/endpoints/management.go +++ b/pkg/server/endpoints/management.go @@ -45,7 +45,7 @@ func (h *AdminAPIHandlers) GetRelationships(echoContext echo.Context, params adm if params.TrustDomainName != nil { td, err := h.findTrustDomainByName(ctx, *params.TrustDomainName) if err != nil { - err = fmt.Errorf("failed parsing trust domain name: %v", err) + err = fmt.Errorf("failed looking up trust domain name: %w", err) return h.handleAndLog(err, http.StatusBadRequest) } From 02de6e69dc7e34fc3961669cb6ae9788f93942a9 Mon Sep 17 00:00:00 2001 From: Victor Vieira Barros Leal da Silveira Date: Thu, 11 May 2023 17:08:58 -0300 Subject: [PATCH 11/20] Update pkg/server/endpoints/management.go Co-authored-by: Max Lambrecht Signed-off-by: Victor Vieira Barros Leal da Silveira --- pkg/server/endpoints/management.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/server/endpoints/management.go b/pkg/server/endpoints/management.go index c9ce25ef..47356b61 100644 --- a/pkg/server/endpoints/management.go +++ b/pkg/server/endpoints/management.go @@ -51,7 +51,7 @@ func (h *AdminAPIHandlers) GetRelationships(echoContext echo.Context, params adm rels, err = h.Datastore.FindRelationshipsByTrustDomainID(ctx, td.ID.UUID) if err != nil { - err = fmt.Errorf("failed listing relationships: %v", err) + err = fmt.Errorf("failed looking up relationships: %v", err) return h.handleAndLog(err, http.StatusInternalServerError) } } else { From 85ce2357df0b83ef882545a6223c1106a2a71c04 Mon Sep 17 00:00:00 2001 From: Victor Vieira Barros Leal da Silveira Date: Mon, 15 May 2023 10:15:17 -0300 Subject: [PATCH 12/20] fix: Function names --- pkg/server/api/admin/admin.gen.go | 282 ++++++++++++------------ pkg/server/api/admin/admin.yaml | 6 + pkg/server/endpoints/management.go | 22 +- pkg/server/endpoints/management_test.go | 34 +-- 4 files changed, 175 insertions(+), 169 deletions(-) diff --git a/pkg/server/api/admin/admin.gen.go b/pkg/server/api/admin/admin.gen.go index cb1edb6f..dc9ef2db 100644 --- a/pkg/server/api/admin/admin.gen.go +++ b/pkg/server/api/admin/admin.gen.go @@ -61,14 +61,14 @@ type GetRelationshipsParams struct { // GetRelationshipsParamsStatus defines parameters for GetRelationships. type GetRelationshipsParamsStatus string -// PutRelationshipsJSONRequestBody defines body for PutRelationships for application/json ContentType. -type PutRelationshipsJSONRequestBody = RelationshipRequest +// PutRelationshipJSONRequestBody defines body for PutRelationship for application/json ContentType. +type PutRelationshipJSONRequestBody = RelationshipRequest // PutTrustDomainJSONRequestBody defines body for PutTrustDomain for application/json ContentType. type PutTrustDomainJSONRequestBody = TrustDomainPut -// PutTrustDomainTrustDomainNameJSONRequestBody defines body for PutTrustDomainTrustDomainName for application/json ContentType. -type PutTrustDomainTrustDomainNameJSONRequestBody = externalRef0.TrustDomain +// PutTrustDomainByNameJSONRequestBody defines body for PutTrustDomainByName for application/json ContentType. +type PutTrustDomainByNameJSONRequestBody = externalRef0.TrustDomain // RequestEditorFn is the function signature for the RequestEditor callback function type RequestEditorFn func(ctx context.Context, req *http.Request) error @@ -146,26 +146,26 @@ type ClientInterface interface { // GetRelationships request GetRelationships(ctx context.Context, params *GetRelationshipsParams, reqEditors ...RequestEditorFn) (*http.Response, error) - // PutRelationships request with any body - PutRelationshipsWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + // PutRelationship request with any body + PutRelationshipWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - PutRelationships(ctx context.Context, body PutRelationshipsJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + PutRelationship(ctx context.Context, body PutRelationshipJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) - // GetRelationshipsRelationshipID request - GetRelationshipsRelationshipID(ctx context.Context, relationshipID externalRef0.UUID, reqEditors ...RequestEditorFn) (*http.Response, error) + // GetRelationshipByID request + GetRelationshipByID(ctx context.Context, relationshipID externalRef0.UUID, reqEditors ...RequestEditorFn) (*http.Response, error) // PutTrustDomain request with any body PutTrustDomainWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) PutTrustDomain(ctx context.Context, body PutTrustDomainJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) - // GetTrustDomainTrustDomainName request - GetTrustDomainTrustDomainName(ctx context.Context, trustDomainName externalRef0.TrustDomainName, reqEditors ...RequestEditorFn) (*http.Response, error) + // GetTrustDomainByName request + GetTrustDomainByName(ctx context.Context, trustDomainName externalRef0.TrustDomainName, reqEditors ...RequestEditorFn) (*http.Response, error) - // PutTrustDomainTrustDomainName request with any body - PutTrustDomainTrustDomainNameWithBody(ctx context.Context, trustDomainName externalRef0.UUID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + // PutTrustDomainByName request with any body + PutTrustDomainByNameWithBody(ctx context.Context, trustDomainName externalRef0.UUID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - PutTrustDomainTrustDomainName(ctx context.Context, trustDomainName externalRef0.UUID, body PutTrustDomainTrustDomainNameJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + PutTrustDomainByName(ctx context.Context, trustDomainName externalRef0.UUID, body PutTrustDomainByNameJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) // GetJoinToken request GetJoinToken(ctx context.Context, trustDomainName externalRef0.TrustDomainName, reqEditors ...RequestEditorFn) (*http.Response, error) @@ -183,8 +183,8 @@ func (c *Client) GetRelationships(ctx context.Context, params *GetRelationshipsP return c.Client.Do(req) } -func (c *Client) PutRelationshipsWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewPutRelationshipsRequestWithBody(c.Server, contentType, body) +func (c *Client) PutRelationshipWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewPutRelationshipRequestWithBody(c.Server, contentType, body) if err != nil { return nil, err } @@ -195,8 +195,8 @@ func (c *Client) PutRelationshipsWithBody(ctx context.Context, contentType strin return c.Client.Do(req) } -func (c *Client) PutRelationships(ctx context.Context, body PutRelationshipsJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewPutRelationshipsRequest(c.Server, body) +func (c *Client) PutRelationship(ctx context.Context, body PutRelationshipJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewPutRelationshipRequest(c.Server, body) if err != nil { return nil, err } @@ -207,8 +207,8 @@ func (c *Client) PutRelationships(ctx context.Context, body PutRelationshipsJSON return c.Client.Do(req) } -func (c *Client) GetRelationshipsRelationshipID(ctx context.Context, relationshipID externalRef0.UUID, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetRelationshipsRelationshipIDRequest(c.Server, relationshipID) +func (c *Client) GetRelationshipByID(ctx context.Context, relationshipID externalRef0.UUID, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetRelationshipByIDRequest(c.Server, relationshipID) if err != nil { return nil, err } @@ -243,8 +243,8 @@ func (c *Client) PutTrustDomain(ctx context.Context, body PutTrustDomainJSONRequ return c.Client.Do(req) } -func (c *Client) GetTrustDomainTrustDomainName(ctx context.Context, trustDomainName externalRef0.TrustDomainName, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetTrustDomainTrustDomainNameRequest(c.Server, trustDomainName) +func (c *Client) GetTrustDomainByName(ctx context.Context, trustDomainName externalRef0.TrustDomainName, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetTrustDomainByNameRequest(c.Server, trustDomainName) if err != nil { return nil, err } @@ -255,8 +255,8 @@ func (c *Client) GetTrustDomainTrustDomainName(ctx context.Context, trustDomainN return c.Client.Do(req) } -func (c *Client) PutTrustDomainTrustDomainNameWithBody(ctx context.Context, trustDomainName externalRef0.UUID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewPutTrustDomainTrustDomainNameRequestWithBody(c.Server, trustDomainName, contentType, body) +func (c *Client) PutTrustDomainByNameWithBody(ctx context.Context, trustDomainName externalRef0.UUID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewPutTrustDomainByNameRequestWithBody(c.Server, trustDomainName, contentType, body) if err != nil { return nil, err } @@ -267,8 +267,8 @@ func (c *Client) PutTrustDomainTrustDomainNameWithBody(ctx context.Context, trus return c.Client.Do(req) } -func (c *Client) PutTrustDomainTrustDomainName(ctx context.Context, trustDomainName externalRef0.UUID, body PutTrustDomainTrustDomainNameJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewPutTrustDomainTrustDomainNameRequest(c.Server, trustDomainName, body) +func (c *Client) PutTrustDomainByName(ctx context.Context, trustDomainName externalRef0.UUID, body PutTrustDomainByNameJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewPutTrustDomainByNameRequest(c.Server, trustDomainName, body) if err != nil { return nil, err } @@ -354,19 +354,19 @@ func NewGetRelationshipsRequest(server string, params *GetRelationshipsParams) ( return req, nil } -// NewPutRelationshipsRequest calls the generic PutRelationships builder with application/json body -func NewPutRelationshipsRequest(server string, body PutRelationshipsJSONRequestBody) (*http.Request, error) { +// NewPutRelationshipRequest calls the generic PutRelationship builder with application/json body +func NewPutRelationshipRequest(server string, body PutRelationshipJSONRequestBody) (*http.Request, error) { var bodyReader io.Reader buf, err := json.Marshal(body) if err != nil { return nil, err } bodyReader = bytes.NewReader(buf) - return NewPutRelationshipsRequestWithBody(server, "application/json", bodyReader) + return NewPutRelationshipRequestWithBody(server, "application/json", bodyReader) } -// NewPutRelationshipsRequestWithBody generates requests for PutRelationships with any type of body -func NewPutRelationshipsRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { +// NewPutRelationshipRequestWithBody generates requests for PutRelationship with any type of body +func NewPutRelationshipRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { var err error serverURL, err := url.Parse(server) @@ -394,8 +394,8 @@ func NewPutRelationshipsRequestWithBody(server string, contentType string, body return req, nil } -// NewGetRelationshipsRelationshipIDRequest generates requests for GetRelationshipsRelationshipID -func NewGetRelationshipsRelationshipIDRequest(server string, relationshipID externalRef0.UUID) (*http.Request, error) { +// NewGetRelationshipByIDRequest generates requests for GetRelationshipByID +func NewGetRelationshipByIDRequest(server string, relationshipID externalRef0.UUID) (*http.Request, error) { var err error var pathParam0 string @@ -468,8 +468,8 @@ func NewPutTrustDomainRequestWithBody(server string, contentType string, body io return req, nil } -// NewGetTrustDomainTrustDomainNameRequest generates requests for GetTrustDomainTrustDomainName -func NewGetTrustDomainTrustDomainNameRequest(server string, trustDomainName externalRef0.TrustDomainName) (*http.Request, error) { +// NewGetTrustDomainByNameRequest generates requests for GetTrustDomainByName +func NewGetTrustDomainByNameRequest(server string, trustDomainName externalRef0.TrustDomainName) (*http.Request, error) { var err error var pathParam0 string @@ -502,19 +502,19 @@ func NewGetTrustDomainTrustDomainNameRequest(server string, trustDomainName exte return req, nil } -// NewPutTrustDomainTrustDomainNameRequest calls the generic PutTrustDomainTrustDomainName builder with application/json body -func NewPutTrustDomainTrustDomainNameRequest(server string, trustDomainName externalRef0.UUID, body PutTrustDomainTrustDomainNameJSONRequestBody) (*http.Request, error) { +// NewPutTrustDomainByNameRequest calls the generic PutTrustDomainByName builder with application/json body +func NewPutTrustDomainByNameRequest(server string, trustDomainName externalRef0.UUID, body PutTrustDomainByNameJSONRequestBody) (*http.Request, error) { var bodyReader io.Reader buf, err := json.Marshal(body) if err != nil { return nil, err } bodyReader = bytes.NewReader(buf) - return NewPutTrustDomainTrustDomainNameRequestWithBody(server, trustDomainName, "application/json", bodyReader) + return NewPutTrustDomainByNameRequestWithBody(server, trustDomainName, "application/json", bodyReader) } -// NewPutTrustDomainTrustDomainNameRequestWithBody generates requests for PutTrustDomainTrustDomainName with any type of body -func NewPutTrustDomainTrustDomainNameRequestWithBody(server string, trustDomainName externalRef0.UUID, contentType string, body io.Reader) (*http.Request, error) { +// NewPutTrustDomainByNameRequestWithBody generates requests for PutTrustDomainByName with any type of body +func NewPutTrustDomainByNameRequestWithBody(server string, trustDomainName externalRef0.UUID, contentType string, body io.Reader) (*http.Request, error) { var err error var pathParam0 string @@ -629,26 +629,26 @@ type ClientWithResponsesInterface interface { // GetRelationships request GetRelationshipsWithResponse(ctx context.Context, params *GetRelationshipsParams, reqEditors ...RequestEditorFn) (*GetRelationshipsResponse, error) - // PutRelationships request with any body - PutRelationshipsWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PutRelationshipsResponse, error) + // PutRelationship request with any body + PutRelationshipWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PutRelationshipResponse, error) - PutRelationshipsWithResponse(ctx context.Context, body PutRelationshipsJSONRequestBody, reqEditors ...RequestEditorFn) (*PutRelationshipsResponse, error) + PutRelationshipWithResponse(ctx context.Context, body PutRelationshipJSONRequestBody, reqEditors ...RequestEditorFn) (*PutRelationshipResponse, error) - // GetRelationshipsRelationshipID request - GetRelationshipsRelationshipIDWithResponse(ctx context.Context, relationshipID externalRef0.UUID, reqEditors ...RequestEditorFn) (*GetRelationshipsRelationshipIDResponse, error) + // GetRelationshipByID request + GetRelationshipByIDWithResponse(ctx context.Context, relationshipID externalRef0.UUID, reqEditors ...RequestEditorFn) (*GetRelationshipByIDResponse, error) // PutTrustDomain request with any body PutTrustDomainWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PutTrustDomainResponse, error) PutTrustDomainWithResponse(ctx context.Context, body PutTrustDomainJSONRequestBody, reqEditors ...RequestEditorFn) (*PutTrustDomainResponse, error) - // GetTrustDomainTrustDomainName request - GetTrustDomainTrustDomainNameWithResponse(ctx context.Context, trustDomainName externalRef0.TrustDomainName, reqEditors ...RequestEditorFn) (*GetTrustDomainTrustDomainNameResponse, error) + // GetTrustDomainByName request + GetTrustDomainByNameWithResponse(ctx context.Context, trustDomainName externalRef0.TrustDomainName, reqEditors ...RequestEditorFn) (*GetTrustDomainByNameResponse, error) - // PutTrustDomainTrustDomainName request with any body - PutTrustDomainTrustDomainNameWithBodyWithResponse(ctx context.Context, trustDomainName externalRef0.UUID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PutTrustDomainTrustDomainNameResponse, error) + // PutTrustDomainByName request with any body + PutTrustDomainByNameWithBodyWithResponse(ctx context.Context, trustDomainName externalRef0.UUID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PutTrustDomainByNameResponse, error) - PutTrustDomainTrustDomainNameWithResponse(ctx context.Context, trustDomainName externalRef0.UUID, body PutTrustDomainTrustDomainNameJSONRequestBody, reqEditors ...RequestEditorFn) (*PutTrustDomainTrustDomainNameResponse, error) + PutTrustDomainByNameWithResponse(ctx context.Context, trustDomainName externalRef0.UUID, body PutTrustDomainByNameJSONRequestBody, reqEditors ...RequestEditorFn) (*PutTrustDomainByNameResponse, error) // GetJoinToken request GetJoinTokenWithResponse(ctx context.Context, trustDomainName externalRef0.TrustDomainName, reqEditors ...RequestEditorFn) (*GetJoinTokenResponse, error) @@ -677,7 +677,7 @@ func (r GetRelationshipsResponse) StatusCode() int { return 0 } -type PutRelationshipsResponse struct { +type PutRelationshipResponse struct { Body []byte HTTPResponse *http.Response JSON200 *externalRef0.Relationship @@ -685,7 +685,7 @@ type PutRelationshipsResponse struct { } // Status returns HTTPResponse.Status -func (r PutRelationshipsResponse) Status() string { +func (r PutRelationshipResponse) Status() string { if r.HTTPResponse != nil { return r.HTTPResponse.Status } @@ -693,14 +693,14 @@ func (r PutRelationshipsResponse) Status() string { } // StatusCode returns HTTPResponse.StatusCode -func (r PutRelationshipsResponse) StatusCode() int { +func (r PutRelationshipResponse) StatusCode() int { if r.HTTPResponse != nil { return r.HTTPResponse.StatusCode } return 0 } -type GetRelationshipsRelationshipIDResponse struct { +type GetRelationshipByIDResponse struct { Body []byte HTTPResponse *http.Response JSON200 *externalRef0.Relationship @@ -708,7 +708,7 @@ type GetRelationshipsRelationshipIDResponse struct { } // Status returns HTTPResponse.Status -func (r GetRelationshipsRelationshipIDResponse) Status() string { +func (r GetRelationshipByIDResponse) Status() string { if r.HTTPResponse != nil { return r.HTTPResponse.Status } @@ -716,7 +716,7 @@ func (r GetRelationshipsRelationshipIDResponse) Status() string { } // StatusCode returns HTTPResponse.StatusCode -func (r GetRelationshipsRelationshipIDResponse) StatusCode() int { +func (r GetRelationshipByIDResponse) StatusCode() int { if r.HTTPResponse != nil { return r.HTTPResponse.StatusCode } @@ -746,7 +746,7 @@ func (r PutTrustDomainResponse) StatusCode() int { return 0 } -type GetTrustDomainTrustDomainNameResponse struct { +type GetTrustDomainByNameResponse struct { Body []byte HTTPResponse *http.Response JSON200 *externalRef0.TrustDomain @@ -754,7 +754,7 @@ type GetTrustDomainTrustDomainNameResponse struct { } // Status returns HTTPResponse.Status -func (r GetTrustDomainTrustDomainNameResponse) Status() string { +func (r GetTrustDomainByNameResponse) Status() string { if r.HTTPResponse != nil { return r.HTTPResponse.Status } @@ -762,14 +762,14 @@ func (r GetTrustDomainTrustDomainNameResponse) Status() string { } // StatusCode returns HTTPResponse.StatusCode -func (r GetTrustDomainTrustDomainNameResponse) StatusCode() int { +func (r GetTrustDomainByNameResponse) StatusCode() int { if r.HTTPResponse != nil { return r.HTTPResponse.StatusCode } return 0 } -type PutTrustDomainTrustDomainNameResponse struct { +type PutTrustDomainByNameResponse struct { Body []byte HTTPResponse *http.Response JSON200 *externalRef0.TrustDomain @@ -777,7 +777,7 @@ type PutTrustDomainTrustDomainNameResponse struct { } // Status returns HTTPResponse.Status -func (r PutTrustDomainTrustDomainNameResponse) Status() string { +func (r PutTrustDomainByNameResponse) Status() string { if r.HTTPResponse != nil { return r.HTTPResponse.Status } @@ -785,7 +785,7 @@ func (r PutTrustDomainTrustDomainNameResponse) Status() string { } // StatusCode returns HTTPResponse.StatusCode -func (r PutTrustDomainTrustDomainNameResponse) StatusCode() int { +func (r PutTrustDomainByNameResponse) StatusCode() int { if r.HTTPResponse != nil { return r.HTTPResponse.StatusCode } @@ -824,30 +824,30 @@ func (c *ClientWithResponses) GetRelationshipsWithResponse(ctx context.Context, return ParseGetRelationshipsResponse(rsp) } -// PutRelationshipsWithBodyWithResponse request with arbitrary body returning *PutRelationshipsResponse -func (c *ClientWithResponses) PutRelationshipsWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PutRelationshipsResponse, error) { - rsp, err := c.PutRelationshipsWithBody(ctx, contentType, body, reqEditors...) +// PutRelationshipWithBodyWithResponse request with arbitrary body returning *PutRelationshipResponse +func (c *ClientWithResponses) PutRelationshipWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PutRelationshipResponse, error) { + rsp, err := c.PutRelationshipWithBody(ctx, contentType, body, reqEditors...) if err != nil { return nil, err } - return ParsePutRelationshipsResponse(rsp) + return ParsePutRelationshipResponse(rsp) } -func (c *ClientWithResponses) PutRelationshipsWithResponse(ctx context.Context, body PutRelationshipsJSONRequestBody, reqEditors ...RequestEditorFn) (*PutRelationshipsResponse, error) { - rsp, err := c.PutRelationships(ctx, body, reqEditors...) +func (c *ClientWithResponses) PutRelationshipWithResponse(ctx context.Context, body PutRelationshipJSONRequestBody, reqEditors ...RequestEditorFn) (*PutRelationshipResponse, error) { + rsp, err := c.PutRelationship(ctx, body, reqEditors...) if err != nil { return nil, err } - return ParsePutRelationshipsResponse(rsp) + return ParsePutRelationshipResponse(rsp) } -// GetRelationshipsRelationshipIDWithResponse request returning *GetRelationshipsRelationshipIDResponse -func (c *ClientWithResponses) GetRelationshipsRelationshipIDWithResponse(ctx context.Context, relationshipID externalRef0.UUID, reqEditors ...RequestEditorFn) (*GetRelationshipsRelationshipIDResponse, error) { - rsp, err := c.GetRelationshipsRelationshipID(ctx, relationshipID, reqEditors...) +// GetRelationshipByIDWithResponse request returning *GetRelationshipByIDResponse +func (c *ClientWithResponses) GetRelationshipByIDWithResponse(ctx context.Context, relationshipID externalRef0.UUID, reqEditors ...RequestEditorFn) (*GetRelationshipByIDResponse, error) { + rsp, err := c.GetRelationshipByID(ctx, relationshipID, reqEditors...) if err != nil { return nil, err } - return ParseGetRelationshipsRelationshipIDResponse(rsp) + return ParseGetRelationshipByIDResponse(rsp) } // PutTrustDomainWithBodyWithResponse request with arbitrary body returning *PutTrustDomainResponse @@ -867,30 +867,30 @@ func (c *ClientWithResponses) PutTrustDomainWithResponse(ctx context.Context, bo return ParsePutTrustDomainResponse(rsp) } -// GetTrustDomainTrustDomainNameWithResponse request returning *GetTrustDomainTrustDomainNameResponse -func (c *ClientWithResponses) GetTrustDomainTrustDomainNameWithResponse(ctx context.Context, trustDomainName externalRef0.TrustDomainName, reqEditors ...RequestEditorFn) (*GetTrustDomainTrustDomainNameResponse, error) { - rsp, err := c.GetTrustDomainTrustDomainName(ctx, trustDomainName, reqEditors...) +// GetTrustDomainByNameWithResponse request returning *GetTrustDomainByNameResponse +func (c *ClientWithResponses) GetTrustDomainByNameWithResponse(ctx context.Context, trustDomainName externalRef0.TrustDomainName, reqEditors ...RequestEditorFn) (*GetTrustDomainByNameResponse, error) { + rsp, err := c.GetTrustDomainByName(ctx, trustDomainName, reqEditors...) if err != nil { return nil, err } - return ParseGetTrustDomainTrustDomainNameResponse(rsp) + return ParseGetTrustDomainByNameResponse(rsp) } -// PutTrustDomainTrustDomainNameWithBodyWithResponse request with arbitrary body returning *PutTrustDomainTrustDomainNameResponse -func (c *ClientWithResponses) PutTrustDomainTrustDomainNameWithBodyWithResponse(ctx context.Context, trustDomainName externalRef0.UUID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PutTrustDomainTrustDomainNameResponse, error) { - rsp, err := c.PutTrustDomainTrustDomainNameWithBody(ctx, trustDomainName, contentType, body, reqEditors...) +// PutTrustDomainByNameWithBodyWithResponse request with arbitrary body returning *PutTrustDomainByNameResponse +func (c *ClientWithResponses) PutTrustDomainByNameWithBodyWithResponse(ctx context.Context, trustDomainName externalRef0.UUID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PutTrustDomainByNameResponse, error) { + rsp, err := c.PutTrustDomainByNameWithBody(ctx, trustDomainName, contentType, body, reqEditors...) if err != nil { return nil, err } - return ParsePutTrustDomainTrustDomainNameResponse(rsp) + return ParsePutTrustDomainByNameResponse(rsp) } -func (c *ClientWithResponses) PutTrustDomainTrustDomainNameWithResponse(ctx context.Context, trustDomainName externalRef0.UUID, body PutTrustDomainTrustDomainNameJSONRequestBody, reqEditors ...RequestEditorFn) (*PutTrustDomainTrustDomainNameResponse, error) { - rsp, err := c.PutTrustDomainTrustDomainName(ctx, trustDomainName, body, reqEditors...) +func (c *ClientWithResponses) PutTrustDomainByNameWithResponse(ctx context.Context, trustDomainName externalRef0.UUID, body PutTrustDomainByNameJSONRequestBody, reqEditors ...RequestEditorFn) (*PutTrustDomainByNameResponse, error) { + rsp, err := c.PutTrustDomainByName(ctx, trustDomainName, body, reqEditors...) if err != nil { return nil, err } - return ParsePutTrustDomainTrustDomainNameResponse(rsp) + return ParsePutTrustDomainByNameResponse(rsp) } // GetJoinTokenWithResponse request returning *GetJoinTokenResponse @@ -935,15 +935,15 @@ func ParseGetRelationshipsResponse(rsp *http.Response) (*GetRelationshipsRespons return response, nil } -// ParsePutRelationshipsResponse parses an HTTP response from a PutRelationshipsWithResponse call -func ParsePutRelationshipsResponse(rsp *http.Response) (*PutRelationshipsResponse, error) { +// ParsePutRelationshipResponse parses an HTTP response from a PutRelationshipWithResponse call +func ParsePutRelationshipResponse(rsp *http.Response) (*PutRelationshipResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &PutRelationshipsResponse{ + response := &PutRelationshipResponse{ Body: bodyBytes, HTTPResponse: rsp, } @@ -968,15 +968,15 @@ func ParsePutRelationshipsResponse(rsp *http.Response) (*PutRelationshipsRespons return response, nil } -// ParseGetRelationshipsRelationshipIDResponse parses an HTTP response from a GetRelationshipsRelationshipIDWithResponse call -func ParseGetRelationshipsRelationshipIDResponse(rsp *http.Response) (*GetRelationshipsRelationshipIDResponse, error) { +// ParseGetRelationshipByIDResponse parses an HTTP response from a GetRelationshipByIDWithResponse call +func ParseGetRelationshipByIDResponse(rsp *http.Response) (*GetRelationshipByIDResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &GetRelationshipsRelationshipIDResponse{ + response := &GetRelationshipByIDResponse{ Body: bodyBytes, HTTPResponse: rsp, } @@ -1034,15 +1034,15 @@ func ParsePutTrustDomainResponse(rsp *http.Response) (*PutTrustDomainResponse, e return response, nil } -// ParseGetTrustDomainTrustDomainNameResponse parses an HTTP response from a GetTrustDomainTrustDomainNameWithResponse call -func ParseGetTrustDomainTrustDomainNameResponse(rsp *http.Response) (*GetTrustDomainTrustDomainNameResponse, error) { +// ParseGetTrustDomainByNameResponse parses an HTTP response from a GetTrustDomainByNameWithResponse call +func ParseGetTrustDomainByNameResponse(rsp *http.Response) (*GetTrustDomainByNameResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &GetTrustDomainTrustDomainNameResponse{ + response := &GetTrustDomainByNameResponse{ Body: bodyBytes, HTTPResponse: rsp, } @@ -1067,15 +1067,15 @@ func ParseGetTrustDomainTrustDomainNameResponse(rsp *http.Response) (*GetTrustDo return response, nil } -// ParsePutTrustDomainTrustDomainNameResponse parses an HTTP response from a PutTrustDomainTrustDomainNameWithResponse call -func ParsePutTrustDomainTrustDomainNameResponse(rsp *http.Response) (*PutTrustDomainTrustDomainNameResponse, error) { +// ParsePutTrustDomainByNameResponse parses an HTTP response from a PutTrustDomainByNameWithResponse call +func ParsePutTrustDomainByNameResponse(rsp *http.Response) (*PutTrustDomainByNameResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &PutTrustDomainTrustDomainNameResponse{ + response := &PutTrustDomainByNameResponse{ Body: bodyBytes, HTTPResponse: rsp, } @@ -1140,19 +1140,19 @@ type ServerInterface interface { GetRelationships(ctx echo.Context, params GetRelationshipsParams) error // Create a relationship request between two Trust Domains // (PUT /relationships) - PutRelationships(ctx echo.Context) error + PutRelationship(ctx echo.Context) error // Get a specific relationship // (GET /relationships/{relationshipID}) - GetRelationshipsRelationshipID(ctx echo.Context, relationshipID externalRef0.UUID) error + GetRelationshipByID(ctx echo.Context, relationshipID externalRef0.UUID) error // Add a specific trust domain // (PUT /trust-domain) PutTrustDomain(ctx echo.Context) error // Get a specific trust domain // (GET /trust-domain/{trustDomainName}) - GetTrustDomainTrustDomainName(ctx echo.Context, trustDomainName externalRef0.TrustDomainName) error + GetTrustDomainByName(ctx echo.Context, trustDomainName externalRef0.TrustDomainName) error // Update a specific trust domain // (PUT /trust-domain/{trustDomainName}) - PutTrustDomainTrustDomainName(ctx echo.Context, trustDomainName externalRef0.UUID) error + PutTrustDomainByName(ctx echo.Context, trustDomainName externalRef0.UUID) error // Get a join token for a specific Trust Domain // (GET /trust-domain/{trustDomainName}/join-token) GetJoinToken(ctx echo.Context, trustDomainName externalRef0.TrustDomainName) error @@ -1188,17 +1188,17 @@ func (w *ServerInterfaceWrapper) GetRelationships(ctx echo.Context) error { return err } -// PutRelationships converts echo context to params. -func (w *ServerInterfaceWrapper) PutRelationships(ctx echo.Context) error { +// PutRelationship converts echo context to params. +func (w *ServerInterfaceWrapper) PutRelationship(ctx echo.Context) error { var err error // Invoke the callback with all the unmarshalled arguments - err = w.Handler.PutRelationships(ctx) + err = w.Handler.PutRelationship(ctx) return err } -// GetRelationshipsRelationshipID converts echo context to params. -func (w *ServerInterfaceWrapper) GetRelationshipsRelationshipID(ctx echo.Context) error { +// GetRelationshipByID converts echo context to params. +func (w *ServerInterfaceWrapper) GetRelationshipByID(ctx echo.Context) error { var err error // ------------- Path parameter "relationshipID" ------------- var relationshipID externalRef0.UUID @@ -1209,7 +1209,7 @@ func (w *ServerInterfaceWrapper) GetRelationshipsRelationshipID(ctx echo.Context } // Invoke the callback with all the unmarshalled arguments - err = w.Handler.GetRelationshipsRelationshipID(ctx, relationshipID) + err = w.Handler.GetRelationshipByID(ctx, relationshipID) return err } @@ -1222,8 +1222,8 @@ func (w *ServerInterfaceWrapper) PutTrustDomain(ctx echo.Context) error { return err } -// GetTrustDomainTrustDomainName converts echo context to params. -func (w *ServerInterfaceWrapper) GetTrustDomainTrustDomainName(ctx echo.Context) error { +// GetTrustDomainByName converts echo context to params. +func (w *ServerInterfaceWrapper) GetTrustDomainByName(ctx echo.Context) error { var err error // ------------- Path parameter "trustDomainName" ------------- var trustDomainName externalRef0.TrustDomainName @@ -1234,12 +1234,12 @@ func (w *ServerInterfaceWrapper) GetTrustDomainTrustDomainName(ctx echo.Context) } // Invoke the callback with all the unmarshalled arguments - err = w.Handler.GetTrustDomainTrustDomainName(ctx, trustDomainName) + err = w.Handler.GetTrustDomainByName(ctx, trustDomainName) return err } -// PutTrustDomainTrustDomainName converts echo context to params. -func (w *ServerInterfaceWrapper) PutTrustDomainTrustDomainName(ctx echo.Context) error { +// PutTrustDomainByName converts echo context to params. +func (w *ServerInterfaceWrapper) PutTrustDomainByName(ctx echo.Context) error { var err error // ------------- Path parameter "trustDomainName" ------------- var trustDomainName externalRef0.UUID @@ -1250,7 +1250,7 @@ func (w *ServerInterfaceWrapper) PutTrustDomainTrustDomainName(ctx echo.Context) } // Invoke the callback with all the unmarshalled arguments - err = w.Handler.PutTrustDomainTrustDomainName(ctx, trustDomainName) + err = w.Handler.PutTrustDomainByName(ctx, trustDomainName) return err } @@ -1299,11 +1299,11 @@ func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL } router.GET(baseURL+"/relationships", wrapper.GetRelationships) - router.PUT(baseURL+"/relationships", wrapper.PutRelationships) - router.GET(baseURL+"/relationships/:relationshipID", wrapper.GetRelationshipsRelationshipID) + router.PUT(baseURL+"/relationships", wrapper.PutRelationship) + router.GET(baseURL+"/relationships/:relationshipID", wrapper.GetRelationshipByID) router.PUT(baseURL+"/trust-domain", wrapper.PutTrustDomain) - router.GET(baseURL+"/trust-domain/:trustDomainName", wrapper.GetTrustDomainTrustDomainName) - router.PUT(baseURL+"/trust-domain/:trustDomainName", wrapper.PutTrustDomainTrustDomainName) + router.GET(baseURL+"/trust-domain/:trustDomainName", wrapper.GetTrustDomainByName) + router.PUT(baseURL+"/trust-domain/:trustDomainName", wrapper.PutTrustDomainByName) router.GET(baseURL+"/trust-domain/:trustDomainName/join-token", wrapper.GetJoinToken) } @@ -1311,31 +1311,31 @@ func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL // Base64 encoded, gzipped, json marshaled Swagger object var swaggerSpec = []string{ - "H4sIAAAAAAAC/9xYbW/bNhD+KwTXD1uhN9uJm+ib26Sdhy4LkhQYGngBLZ1sthKpklTcLNB/H0jJtiQr", - "sdy8rO0ny+LLHe95nuOdbnHAk5QzYEpi/xYLkClnEsyfI4hIFiv9GHCmgJlHkqYxDYiinLmfJGf6nQzm", - "kBD99EJAhH38i7ve1y1GpTtK6bEQXOA8zy0cggwETfU+2MdmAI1Ox2jtgp5VrtVbr5ZrJ8KQ6pUkPhU8", - "BaGodjkisQQLp5VX2vUQ9G/ERUIU9jFlariHLZyQrzTJEuzvHx5aOKGs+NfzPAurmxSKqTADgXMLJyAl", - "mZmd4CtJ0liPj9AUSKZolMUIzAmW06y1PakEZbPC4HtgMzXHfr9ipBzXpxXwJaMCQuxfFn6v7U5W8/n0", - "EwRK+/QHp+yCfwZW92oQkYP9aLhn77/qvbL39od9ezqIArsfHA4H0XBIIjKsOphlNKy7NxhaOCVKgdDY", - "/HPp2YfEjia3B7m9et7r8Nzr5y/wxkErjp+BLBm2A6JqeeT7yLaOTTOwxfK2eJ5BbHgt5zTdlWUCiILw", - "iqg6Fn2v37O9nj3wLrwDf+D5nvexGvuQKLAVTaDBj15L1Gi47dAfPoyP9EwlMqmuQp4Qyq7IVaD1VKg3", - "XGq6PEVpZMp5DIS1rP1Go9MHGJ3uYDRLwyeOe4M9RioVtGsutEWv7XB3InRnFLfR9Qy+ZCB3VtIjYd11", - "YVOJnYLVdvQLPevITPoOhVq72qpGjNuoOBxSc6KQgFSARhipOSBgiqob9Hen66OSoH9FLy9H9keTdv+d", - "oJe/vWxNu3MirkEqEFcypVEEHXA7Px2/fXtcgN6dHowksG1uBcITPT23MGdTTkRI2exqmrEw7rbH62Lq", - "/5YMzGHvzglb6HtShmrtrVGAU5DECXiynQx7By1gV2ycZrsmhudh8IbP38SbBiZmj7agG3L+UIWSPhpl", - "EV9W4CQwOBZRwu+ommdTTTYRYx/PlUql77oz81oTx/0dFjEodUqCz0SE7ozEJBQU4o0chd8th9A5iGsQ", - "6E/CyAwSDasuymUKAY3Kst/BFo5pAExCxZ1RSoI5oL7j1VzyXXexWDjEjDpczNxyqXTfj98cn5wf233H", - "c+YqMW4pqgw0Gw6NwoQy44uN/kqB6aeBsXUNQhan6Dme0+uZTJICIynVGDueM8AGpbmhtisq16Z5MwMT", - "Vs1/MzAOtQOgzmoT9RaCJKBASOxfNjSCq7siqYjKJIoETxBBhWYKyqIUhA6motdgYQ0v9vGXDMTNMpNo", - "+PVqbFXaKmC6NbnUzZfg16BZGAKj5iEFplNmhfPrbNX0snpvthtXDXlZHZu7TVlOrHo72fe8nVpJqiCR", - "28zWSvZ8FQEiBLlp6zPPsyAAKXXDtsK7kMOq120ztzqIu2yKTXOaJQkRNwVbkGjQRZGZJgqu02iSWzjN", - "Wgh3mm0QThRF3Wse3jxaE95WNOb1HKpEBvkDweuO2bNh9MZc0IjUgEJljNEU1AKAIbXgNcHeh2RuNbKJ", - "e1v9Oz7KO6eXs9q6bclmfIR4ZO7bWixLRetUtxa0aO5cB7qrvssCfvLz8UJrl6xuuBo7tmBvcqUdrtqQ", - "u3Rdz7pPoepGsZeXiq4B1XsKa204FUILHwGaURhWoVGV4rMCTVWuLci4t4077V5VVs52sXEV3ivK2jVf", - "NgUtety8YL9NkI9/4T4A8ueRZjf8rS46/L6xrSbbJ00W7ZniR6fNB9N9P0XmcD9xyuzVB+i7ksj64/Mu", - "vDr5yXJG8yv/c+cNjRUyWKGIiyodariv6aAdRgVuE+OsNL1nAVy9y455QOI5l8qRCzKbgXAod0lK3esB", - "1kEtt2ziPULFB7WmByXOtbeb3duoXrpSaUrA1QcYM6ILQ7K08hbCMqi1QvHeYrd0pV7vbPpy1mK1EvAp", - "z1iIFG+0v87aQCXY+ST/LwAA///i709UiRwAAA==", + "H4sIAAAAAAAC/9xYXW/buBL9KwRvH+4t9GU7cRO9OU3a60U3GyQtsGjgDWhpZLOVSJWk4noD/fcFKdmW", + "ZCWW2yTb9smy+DHDOecMZ3SHA56knAFTEvt3WIBMOZNg/pxCRLJY6ceAMwXMPJI0jWlAFOXM/SQ50+9k", + "MIeE6KcXAiLs4/+4m33dYlS6o5SeCcEFzvPcwiHIQNBU74N9bAbQ6GKMNi7oWeVavfV6uXYiDKleSeIL", + "wVMQimqXIxJLsHBaeaVdD0H/RlwkRGEfU6aGB9jCCflKkyzB/uHxsYUTyop/Pc+zsFqmUEyFGQicWzgB", + "KcnM7ARfSZLGenyEpkAyRaMsRmBOsJpmbexJJSibFQbfAZupOfb7FSPluD6tgC8ZFRBi/7rwe2N3sp7P", + "p58gUNqn3zhl7/lnYHWvBhE5OoyGB/bhq94r++Bw2Lengyiw+8HxcBANhyQiw6qDWUbDunuDoYVTohQI", + "jc1f1559TOxocneU2+vngw7PvX7+Am8dtOL4JciSYXsgqlZHfohsm9g0A1ssb4vnJcSG13JO031ZJoAo", + "CG+IqmPR9/o92+vZA++9d+QPPN/zPlZjHxIFtqIJNPjRa4kaDXcd+sOH8ameqUQm1U3IE0LZDbkJtJ4K", + "9YYrTZenKI1MOY+BsJa132h0+h1Gp3sYzdLwiePeYI+RSgXtmgtt0Ws73L0I3RvFXXS9hC8ZyL2V9EhY", + "d13YVGKnYLUd/b2edWom/YBCrV1tVSPGbVQcDqk5UUhAKkAjjNQcEDBF1RL92en6qCTo/6KX1yP7o0m7", + "f0/Qy/+9bE27cyJuQSoQNzKlUQQdcLu6GL95c1aA3p0ejCSwa24FwnM9PbcwZ1NOREjZ7GaasTDutsdJ", + "MfVfSwbmsPfnhB30PS9DtfHWKMApSOIEPNlNhoOjFrArNi6yfRPD8zB4y+dv4k0DE7NHW9ANOX+qQkkf", + "jbKIrypwEhgciyjht1TNs6kmm4ixj+dKpdJ33Zl5rYnj/h8WMSh1QYLPRITujMQkFBTirRyF366G0BWI", + "WxDod8LIDBINqy7KZQoBjcqy38EWjmkATELFnVFKgjmgvuPVXPJdd7FYOMSMOlzM3HKpdN+NX5+dX53Z", + "fcdz5ioxbimqDDRbDo3ChDLji43+SIHpp4GxdQtCFqfoOZ7T65lMkgIjKdUYO54zwAaluaG2KyrXpnkz", + "AxNWzX8zMA61A6AuaxP1FoIkoEBI7F83NIKruyKpiMokigRPEEGFZgrKohSEDqait2BhDS/28ZcMxHKV", + "STT8ejW2Km0VMN2aXOvmS/Bb0CwMgVHzkALTKbPC+U22anpZvTfbjauGvKyOzd22LCdWvZ3se95erSRV", + "kMhdZmsle76OABGCLNv6zKssCEBK3bCt8S7ksO5128ytD+KummLTnGZJQsSyYAsSDbooMtNEwXUaTXIL", + "p1kL4S6yGuFwkdVAqhMeLh+tB2+rGfN6ClUig/w7sesO2bNB9Nrcz4jUcEJljNEU1AKAIbXgNb0+BGRu", + "NZKJe1f9Oz7Nu2aXk+X4dFeCGZ8iHpk7tkETo2Kd3jYirruBm+h21XRZtE9+PTJovZL1rVajxA7ATX60", + "w3XrcZ+W65n2KaTcKPDyUsY1oHpPYa0Np0Jd4SNAMwrDKjSqUnBWoKlqtAUZ965xjz0oxcrZTpblrfeg", + "Fms3eln/t8hw+y79Nh0+/t36HUg/jyK7wW51kd8PCWk1tT5pamjPCz87Wz6Y/vop8oT7iVNmrz8x35cy", + "Np+X9+HV+S+WKprf8Z87XWiskMEKRVxU6VDDfUMH7TAqcJsYZ6XpLgvg6n10zAMSz7lUjlyQ2QyEQ7lL", + "UureDrAOarllE+8RKj6ZNT0oca693e7PRvXqlEpT8K0/sZgRXQaSlZU3EJZBrZWFD9azpSv16mbbl8sW", + "q5WAT3nGQqR4o8F1NgYqwc4n+T8BAAD//9XrDSNrHAAA", } // GetSwagger returns the content of the embedded swagger specification file diff --git a/pkg/server/api/admin/admin.yaml b/pkg/server/api/admin/admin.yaml index 004b3101..a1f51e95 100644 --- a/pkg/server/api/admin/admin.yaml +++ b/pkg/server/api/admin/admin.yaml @@ -23,6 +23,7 @@ tags: paths: /trust-domain/{trustDomainName}: get: + operationId: GetTrustDomainByName tags: - Trust Domain summary: Get a specific trust domain @@ -43,6 +44,7 @@ paths: default: $ref: '#/components/responses/Default' put: + operationId: PutTrustDomainByName tags: - Trust Domain summary: Update a specific trust domain @@ -70,6 +72,7 @@ paths: /trust-domain: put: + operationId: PutTrustDomain tags: - Trust Domain summary: Add a specific trust domain @@ -90,6 +93,7 @@ paths: /relationships: get: + operationId: GetRelationships tags: - Relationships summary: Get relationships @@ -117,6 +121,7 @@ paths: default: $ref: '#/components/responses/Default' put: + operationId: PutRelationship tags: - Relationships summary: Create a relationship request between two Trust Domains @@ -138,6 +143,7 @@ paths: /relationships/{relationshipID}: get: + operationId: GetRelationshipByID tags: - Relationships summary: Get a specific relationship diff --git a/pkg/server/endpoints/management.go b/pkg/server/endpoints/management.go index c3c70840..3b12d78b 100644 --- a/pkg/server/endpoints/management.go +++ b/pkg/server/endpoints/management.go @@ -82,10 +82,10 @@ func (h *AdminAPIHandlers) GetRelationships(echoContext echo.Context, params adm } // PutRelationships create a new relationship request between two trust domains - (PUT /relationships) -func (h AdminAPIHandlers) PutRelationships(echoCtx echo.Context) error { +func (h *AdminAPIHandlers) PutRelationship(echoCtx echo.Context) error { ctx := echoCtx.Request().Context() - reqBody := &admin.PutRelationshipsJSONRequestBody{} + reqBody := &admin.PutRelationshipJSONRequestBody{} err := chttp.FromBody(echoCtx, reqBody) if err != nil { err := fmt.Errorf("failed to read relationship put body: %v", err) @@ -115,8 +115,8 @@ func (h AdminAPIHandlers) PutRelationships(echoCtx echo.Context) error { return nil } -// GetRelationshipsRelationshipID retrieve a specific relationship based on its id - (GET /relationships/{relationshipID}) -func (h AdminAPIHandlers) GetRelationshipsRelationshipID(echoCtx echo.Context, relationshipID api.UUID) error { +// GetRelationshipByID retrieve a specific relationship based on its id - (GET /relationships/{relationshipID}) +func (h *AdminAPIHandlers) GetRelationshipByID(echoCtx echo.Context, relationshipID api.UUID) error { ctx := echoCtx.Request().Context() r, err := h.Datastore.FindRelationshipByID(ctx, relationshipID) @@ -141,7 +141,7 @@ func (h AdminAPIHandlers) GetRelationshipsRelationshipID(echoCtx echo.Context, r } // PutTrustDomain create a new trust domain - (PUT /trust-domain) -func (h AdminAPIHandlers) PutTrustDomain(echoCtx echo.Context) error { +func (h *AdminAPIHandlers) PutTrustDomain(echoCtx echo.Context) error { // Getting golang context ctx := echoCtx.Request().Context() @@ -186,8 +186,8 @@ func (h AdminAPIHandlers) PutTrustDomain(echoCtx echo.Context) error { } // TODO: customize these names. -// GetTrustDomainTrustDomainName retrieve a specific trust domain by its name - (GET /trust-domain/{trustDomainName}) -func (h AdminAPIHandlers) GetTrustDomainTrustDomainName(echoCtx echo.Context, trustDomainName api.TrustDomainName) error { +// GetTrustDomainByName retrieve a specific trust domain by its name - (GET /trust-domain/{trustDomainName}) +func (h *AdminAPIHandlers) GetTrustDomainByName(echoCtx echo.Context, trustDomainName api.TrustDomainName) error { ctx := echoCtx.Request().Context() tdName, err := spiffeid.TrustDomainFromString(trustDomainName) @@ -218,10 +218,10 @@ func (h AdminAPIHandlers) GetTrustDomainTrustDomainName(echoCtx echo.Context, tr } // PutTrustDomainTrustDomainName updates the trust domain - (PUT /trust-domain/{trustDomainName}) -func (h AdminAPIHandlers) PutTrustDomainTrustDomainName(echoCtx echo.Context, trustDomainID api.UUID) error { +func (h *AdminAPIHandlers) PutTrustDomainByName(echoCtx echo.Context, trustDomainID api.UUID) error { ctx := echoCtx.Request().Context() - reqBody := &admin.PutTrustDomainTrustDomainNameJSONRequestBody{} + reqBody := &admin.PutTrustDomainByNameJSONRequestBody{} err := chttp.FromBody(echoCtx, reqBody) if err != nil { err := fmt.Errorf("failed to read trust domain put body: %v", err) @@ -256,8 +256,8 @@ func (h AdminAPIHandlers) PutTrustDomainTrustDomainName(echoCtx echo.Context, tr return nil } -// GetJoinToken generate a join token for the trust domain - (POST /trust-domain/{trustDomainName}/join-token) -func (h AdminAPIHandlers) GetJoinToken(echoCtx echo.Context, trustDomainName api.TrustDomainName) error { +// GetJoinToken generate a join token for the trust domain - (GET /trust-domain/{trustDomainName}/join-token) +func (h *AdminAPIHandlers) GetJoinToken(echoCtx echo.Context, trustDomainName api.TrustDomainName) error { ctx := echoCtx.Request().Context() tdName, err := spiffeid.TrustDomainFromString(trustDomainName) if err != nil { diff --git a/pkg/server/endpoints/management_test.go b/pkg/server/endpoints/management_test.go index 29205201..b8b30f33 100644 --- a/pkg/server/endpoints/management_test.go +++ b/pkg/server/endpoints/management_test.go @@ -245,7 +245,7 @@ func TestUDSPutRelationships(t *testing.T) { {ID: td2ID, Name: NewTrustDomain(t, td2)}, } - reqBody := &admin.PutRelationshipsJSONRequestBody{ + reqBody := &admin.PutRelationshipJSONRequestBody{ TrustDomainAId: td1ID.UUID, TrustDomainBId: td2ID.UUID, } @@ -254,7 +254,7 @@ func TestUDSPutRelationships(t *testing.T) { setup := NewManagementTestSetup(t, http.MethodPut, relationshipsPath, reqBody) setup.FakeDatabase.WithTrustDomains(fakeTrustDomains...) - err := setup.Handler.PutRelationships(setup.EchoCtx) + err := setup.Handler.PutRelationship(setup.EchoCtx) assert.NoError(t, err) assert.Equal(t, http.StatusCreated, setup.Recorder.Code) @@ -278,7 +278,7 @@ func TestUDSPutRelationships(t *testing.T) { {ID: td1ID, Name: NewTrustDomain(t, td1)}, } - reqBody := &admin.PutRelationshipsJSONRequestBody{ + reqBody := &admin.PutRelationshipJSONRequestBody{ TrustDomainAId: td1ID.UUID, TrustDomainBId: td2ID.UUID, } @@ -287,7 +287,7 @@ func TestUDSPutRelationships(t *testing.T) { setup := NewManagementTestSetup(t, http.MethodPut, relationshipsPath, reqBody) setup.FakeDatabase.WithTrustDomains(fakeTrustDomains...) - err := setup.Handler.PutRelationships(setup.EchoCtx) + err := setup.Handler.PutRelationship(setup.EchoCtx) assert.Error(t, err) assert.Empty(t, setup.Recorder.Body.Bytes()) @@ -301,7 +301,7 @@ func TestUDSPutRelationships(t *testing.T) { // Should we test sending wrong body formats ? } -func TestUDSGetRelationshipsRelationshipID(t *testing.T) { +func TestUDSGetRelationshipsByID(t *testing.T) { relationshipsPath := "/relationships/%v" t.Run("Successfully get relationship information", func(t *testing.T) { @@ -327,7 +327,7 @@ func TestUDSGetRelationshipsRelationshipID(t *testing.T) { setup.FakeDatabase.WithTrustDomains(fakeTrustDomains...) setup.FakeDatabase.WithRelationships(fakeRelationship) - err := setup.Handler.GetRelationshipsRelationshipID(setup.EchoCtx, r1ID.UUID) + err := setup.Handler.GetRelationshipByID(setup.EchoCtx, r1ID.UUID) assert.NoError(t, err) assert.Equal(t, http.StatusOK, setup.Recorder.Code) @@ -350,7 +350,7 @@ func TestUDSGetRelationshipsRelationshipID(t *testing.T) { // Setup setup := NewManagementTestSetup(t, http.MethodGet, completePath, nil) - err := setup.Handler.GetRelationshipsRelationshipID(setup.EchoCtx, r1ID.UUID) + err := setup.Handler.GetRelationshipByID(setup.EchoCtx, r1ID.UUID) assert.Error(t, err) assert.Empty(t, setup.Recorder.Body.Bytes()) @@ -364,7 +364,7 @@ func TestUDSPutTrustDomain(t *testing.T) { trustDomainPath := "/trust-domain" t.Run("Successfully create a new trust domain", func(t *testing.T) { description := "A test trust domain" - reqBody := &admin.PutTrustDomainJSONRequestBody{ + reqBody := &admin.TrustDomainPut{ Name: td1, Description: &description, } @@ -388,7 +388,7 @@ func TestUDSPutTrustDomain(t *testing.T) { }) t.Run("Should not allow creating trust domain with the same name of one already created", func(t *testing.T) { - reqBody := &admin.PutTrustDomainJSONRequestBody{ + reqBody := &admin.TrustDomainPut{ Name: td1, } @@ -408,7 +408,7 @@ func TestUDSPutTrustDomain(t *testing.T) { }) } -func TestUDSGetTrustDomainTrustDomainName(t *testing.T) { +func TestUDSGetTrustDomainByName(t *testing.T) { trustDomainPath := "/trust-domain/%v" t.Run("Successfully retrieve trust domain information", func(t *testing.T) { @@ -421,7 +421,7 @@ func TestUDSGetTrustDomainTrustDomainName(t *testing.T) { setup := NewManagementTestSetup(t, http.MethodPut, completePath, nil) setup.FakeDatabase.WithTrustDomains(&fakeTrustDomains) - err := setup.Handler.GetTrustDomainTrustDomainName(setup.EchoCtx, td1) + err := setup.Handler.GetTrustDomainByName(setup.EchoCtx, td1) assert.NoError(t, err) assert.Equal(t, http.StatusOK, setup.Recorder.Code) @@ -440,7 +440,7 @@ func TestUDSGetTrustDomainTrustDomainName(t *testing.T) { // Setup setup := NewManagementTestSetup(t, http.MethodPut, completePath, nil) - err := setup.Handler.GetTrustDomainTrustDomainName(setup.EchoCtx, td1) + err := setup.Handler.GetTrustDomainByName(setup.EchoCtx, td1) assert.Error(t, err) echoHttpErr := err.(*echo.HTTPError) @@ -449,7 +449,7 @@ func TestUDSGetTrustDomainTrustDomainName(t *testing.T) { }) } -func TestUDSPutTrustDomainTrustDomainName(t *testing.T) { +func TestUDSPutTrustDomainByName(t *testing.T) { trustDomainPath := "/trust-domain/%v" t.Run("Successfully updated a trust domain", func(t *testing.T) { @@ -459,7 +459,7 @@ func TestUDSPutTrustDomainTrustDomainName(t *testing.T) { completePath := fmt.Sprintf(trustDomainPath, td1ID.UUID) description := "I am being updated" - reqBody := &admin.PutTrustDomainTrustDomainNameJSONRequestBody{ + reqBody := &admin.PutTrustDomainByNameJSONRequestBody{ Id: td1ID.UUID, Name: td1, Description: &description, @@ -469,7 +469,7 @@ func TestUDSPutTrustDomainTrustDomainName(t *testing.T) { setup := NewManagementTestSetup(t, http.MethodPut, completePath, reqBody) setup.FakeDatabase.WithTrustDomains(&fakeTrustDomains) - err := setup.Handler.PutTrustDomainTrustDomainName(setup.EchoCtx, td1ID.UUID) + err := setup.Handler.PutTrustDomainByName(setup.EchoCtx, td1ID.UUID) assert.NoError(t, err) assert.Equal(t, http.StatusOK, setup.Recorder.Code) @@ -489,7 +489,7 @@ func TestUDSPutTrustDomainTrustDomainName(t *testing.T) { // Fake Request body description := "I am being updated" - reqBody := &admin.PutTrustDomainTrustDomainNameJSONRequestBody{ + reqBody := &admin.PutTrustDomainByNameJSONRequestBody{ Id: td1ID.UUID, Name: td1, Description: &description, @@ -498,7 +498,7 @@ func TestUDSPutTrustDomainTrustDomainName(t *testing.T) { // Setup setup := NewManagementTestSetup(t, http.MethodPut, completePath, reqBody) - err := setup.Handler.PutTrustDomainTrustDomainName(setup.EchoCtx, td1ID.UUID) + err := setup.Handler.PutTrustDomainByName(setup.EchoCtx, td1ID.UUID) assert.Error(t, err) assert.Empty(t, setup.Recorder.Body.Bytes()) From 63306ecd28ce9afc2082232359978defce3b3d74 Mon Sep 17 00:00:00 2001 From: Victor Vieira Barros Leal da Silveira Date: Mon, 15 May 2023 10:30:16 -0300 Subject: [PATCH 13/20] fix: Centralizing common stuff --- pkg/server/endpoints/const_test.go | 12 ++++ pkg/server/endpoints/management_test.go | 86 +++++++++---------------- 2 files changed, 41 insertions(+), 57 deletions(-) diff --git a/pkg/server/endpoints/const_test.go b/pkg/server/endpoints/const_test.go index 730f855a..147037f1 100644 --- a/pkg/server/endpoints/const_test.go +++ b/pkg/server/endpoints/const_test.go @@ -5,3 +5,15 @@ const ( td2 = "test2.com" td3 = "test3.com" ) + +var ( + // Relationships ID's + r1ID = NewNullableID() + r2ID = NewNullableID() + r3ID = NewNullableID() + + // Trust Domains ID's + tdUUID1 = NewNullableID() + tdUUID2 = NewNullableID() + tdUUID3 = NewNullableID() +) diff --git a/pkg/server/endpoints/management_test.go b/pkg/server/endpoints/management_test.go index b8b30f33..133cf968 100644 --- a/pkg/server/endpoints/management_test.go +++ b/pkg/server/endpoints/management_test.go @@ -80,9 +80,6 @@ func TestUDSGetRelationships(t *testing.T) { echoCtx := managementTestSetup.EchoCtx td1Name := NewTrustDomain(t, td1) - tdUUID1 := NewNullableID() - tdUUID2 := NewNullableID() - tdUUID3 := NewNullableID() fakeTrustDomains := []*entity.TrustDomain{ {ID: tdUUID1, Name: td1Name}, @@ -90,8 +87,6 @@ func TestUDSGetRelationships(t *testing.T) { {ID: tdUUID3, Name: NewTrustDomain(t, td3)}, } - r1ID := NewNullableID() - r2ID := NewNullableID() fakeRelationships := []*entity.Relationship{ {ID: r1ID, TrustDomainAID: tdUUID1.UUID, TrustDomainBID: tdUUID2.UUID, TrustDomainAConsent: false, TrustDomainBConsent: false}, {ID: r2ID, TrustDomainBID: tdUUID1.UUID, TrustDomainAID: tdUUID3.UUID, TrustDomainAConsent: false, TrustDomainBConsent: false}, @@ -134,9 +129,6 @@ func TestUDSGetRelationships(t *testing.T) { setup := NewManagementTestSetup(t, http.MethodGet, relationshipsPath, nil) td1Name := NewTrustDomain(t, td1) - tdUUID1 := NewNullableID() - tdUUID2 := NewNullableID() - tdUUID3 := NewNullableID() fakeTrustDomains := []*entity.TrustDomain{ {ID: tdUUID1, Name: td1Name}, @@ -144,10 +136,6 @@ func TestUDSGetRelationships(t *testing.T) { {ID: tdUUID3, Name: NewTrustDomain(t, td3)}, } - r1ID := NewNullableID() - r2ID := NewNullableID() - r3ID := NewNullableID() - fakeRelationships := []*entity.Relationship{ {ID: r1ID, TrustDomainAID: tdUUID1.UUID, TrustDomainBID: tdUUID3.UUID, TrustDomainAConsent: true, TrustDomainBConsent: true}, {ID: r2ID, TrustDomainAID: tdUUID1.UUID, TrustDomainBID: tdUUID2.UUID, TrustDomainAConsent: false, TrustDomainBConsent: false}, @@ -237,17 +225,15 @@ func TestUDSPutRelationships(t *testing.T) { relationshipsPath := "/relationships" t.Run("Successfully create a new relationship request", func(t *testing.T) { - td1ID := NewNullableID() - td2ID := NewNullableID() fakeTrustDomains := []*entity.TrustDomain{ - {ID: td1ID, Name: NewTrustDomain(t, td1)}, - {ID: td2ID, Name: NewTrustDomain(t, td2)}, + {ID: tdUUID1, Name: NewTrustDomain(t, td1)}, + {ID: tdUUID2, Name: NewTrustDomain(t, td2)}, } reqBody := &admin.PutRelationshipJSONRequestBody{ - TrustDomainAId: td1ID.UUID, - TrustDomainBId: td2ID.UUID, + TrustDomainAId: tdUUID1.UUID, + TrustDomainBId: tdUUID2.UUID, } // Setup @@ -264,23 +250,19 @@ func TestUDSPutRelationships(t *testing.T) { assert.NoError(t, err) assert.NotNil(t, apiRelation) - assert.Equal(t, td1ID.UUID, apiRelation.TrustDomainAId) - assert.Equal(t, td2ID.UUID, apiRelation.TrustDomainBId) + assert.Equal(t, tdUUID1.UUID, apiRelation.TrustDomainAId) + assert.Equal(t, tdUUID2.UUID, apiRelation.TrustDomainBId) }) t.Run("Should not allow relationships request between inexistent trust domains", func(t *testing.T) { - td1ID := NewNullableID() - - // Creating a fake UUID that does not match with any trust domain ID in the database - td2ID := NewNullableID() fakeTrustDomains := []*entity.TrustDomain{ - {ID: td1ID, Name: NewTrustDomain(t, td1)}, + {ID: tdUUID1, Name: NewTrustDomain(t, td1)}, } reqBody := &admin.PutRelationshipJSONRequestBody{ - TrustDomainAId: td1ID.UUID, - TrustDomainBId: td2ID.UUID, + TrustDomainAId: tdUUID1.UUID, + TrustDomainBId: tdUUID2.UUID, } // Setup @@ -294,7 +276,7 @@ func TestUDSPutRelationships(t *testing.T) { echoHTTPErr := err.(*echo.HTTPError) assert.Equal(t, http.StatusBadRequest, echoHTTPErr.Code) - expectedErrorMsg := fmt.Sprintf("trust domain %v does not exists", td2ID.UUID) + expectedErrorMsg := fmt.Sprintf("trust domain %v does not exists", tdUUID2.UUID) assert.Equal(t, expectedErrorMsg, echoHTTPErr.Message) }) @@ -305,19 +287,17 @@ func TestUDSGetRelationshipsByID(t *testing.T) { relationshipsPath := "/relationships/%v" t.Run("Successfully get relationship information", func(t *testing.T) { - td1ID := NewNullableID() - td2ID := NewNullableID() fakeTrustDomains := []*entity.TrustDomain{ - {ID: td1ID, Name: NewTrustDomain(t, td1)}, - {ID: td2ID, Name: NewTrustDomain(t, td2)}, + {ID: tdUUID1, Name: NewTrustDomain(t, td1)}, + {ID: tdUUID2, Name: NewTrustDomain(t, td2)}, } r1ID := NewNullableID() fakeRelationship := &entity.Relationship{ ID: r1ID, - TrustDomainAID: td1ID.UUID, - TrustDomainBID: td2ID.UUID, + TrustDomainAID: tdUUID1.UUID, + TrustDomainBID: tdUUID2.UUID, } completePath := fmt.Sprintf(relationshipsPath, r1ID.UUID) @@ -337,14 +317,11 @@ func TestUDSGetRelationshipsByID(t *testing.T) { assert.NoError(t, err) assert.NotNil(t, apiRelation) - assert.Equal(t, td1ID.UUID, apiRelation.TrustDomainAId) - assert.Equal(t, td2ID.UUID, apiRelation.TrustDomainBId) + assert.Equal(t, tdUUID1.UUID, apiRelation.TrustDomainAId) + assert.Equal(t, tdUUID2.UUID, apiRelation.TrustDomainBId) }) t.Run("Should raise a not found request when try to get information about a relationship that doesn't exists", func(t *testing.T) { - - // A random UUID that can represents a real ID - r1ID := NewNullableID() completePath := fmt.Sprintf(relationshipsPath, r1ID.UUID) // Setup @@ -412,10 +389,9 @@ func TestUDSGetTrustDomainByName(t *testing.T) { trustDomainPath := "/trust-domain/%v" t.Run("Successfully retrieve trust domain information", func(t *testing.T) { - td1ID := NewNullableID() - fakeTrustDomains := entity.TrustDomain{ID: td1ID, Name: NewTrustDomain(t, td1)} + fakeTrustDomains := entity.TrustDomain{ID: tdUUID1, Name: NewTrustDomain(t, td1)} - completePath := fmt.Sprintf(trustDomainPath, td1ID.UUID) + completePath := fmt.Sprintf(trustDomainPath, tdUUID1.UUID) // Setup setup := NewManagementTestSetup(t, http.MethodPut, completePath, nil) @@ -430,12 +406,11 @@ func TestUDSGetTrustDomainByName(t *testing.T) { assert.NoError(t, err) assert.Equal(t, td1, apiTrustDomain.Name) - assert.Equal(t, td1ID.UUID, apiTrustDomain.Id) + assert.Equal(t, tdUUID1.UUID, apiTrustDomain.Id) }) t.Run("Raise a not found when trying to retrieve a trust domain that does not exists", func(t *testing.T) { - td1ID := NewNullableID() - completePath := fmt.Sprintf(trustDomainPath, td1ID.UUID) + completePath := fmt.Sprintf(trustDomainPath, tdUUID1.UUID) // Setup setup := NewManagementTestSetup(t, http.MethodPut, completePath, nil) @@ -453,14 +428,13 @@ func TestUDSPutTrustDomainByName(t *testing.T) { trustDomainPath := "/trust-domain/%v" t.Run("Successfully updated a trust domain", func(t *testing.T) { - td1ID := NewNullableID() - fakeTrustDomains := entity.TrustDomain{ID: td1ID, Name: NewTrustDomain(t, td1)} + fakeTrustDomains := entity.TrustDomain{ID: tdUUID1, Name: NewTrustDomain(t, td1)} - completePath := fmt.Sprintf(trustDomainPath, td1ID.UUID) + completePath := fmt.Sprintf(trustDomainPath, tdUUID1.UUID) description := "I am being updated" reqBody := &admin.PutTrustDomainByNameJSONRequestBody{ - Id: td1ID.UUID, + Id: tdUUID1.UUID, Name: td1, Description: &description, } @@ -469,7 +443,7 @@ func TestUDSPutTrustDomainByName(t *testing.T) { setup := NewManagementTestSetup(t, http.MethodPut, completePath, reqBody) setup.FakeDatabase.WithTrustDomains(&fakeTrustDomains) - err := setup.Handler.PutTrustDomainByName(setup.EchoCtx, td1ID.UUID) + err := setup.Handler.PutTrustDomainByName(setup.EchoCtx, tdUUID1.UUID) assert.NoError(t, err) assert.Equal(t, http.StatusOK, setup.Recorder.Code) @@ -478,19 +452,17 @@ func TestUDSPutTrustDomainByName(t *testing.T) { assert.NoError(t, err) assert.Equal(t, td1, apiTrustDomain.Name) - assert.Equal(t, td1ID.UUID, apiTrustDomain.Id) + assert.Equal(t, tdUUID1.UUID, apiTrustDomain.Id) assert.Equal(t, description, *apiTrustDomain.Description) }) t.Run("Raise a not found when trying to updated a trust domain that does not exists", func(t *testing.T) { - // Fake ID - td1ID := NewNullableID() - completePath := fmt.Sprintf(trustDomainPath, td1ID.UUID) + completePath := fmt.Sprintf(trustDomainPath, tdUUID1.UUID) // Fake Request body description := "I am being updated" reqBody := &admin.PutTrustDomainByNameJSONRequestBody{ - Id: td1ID.UUID, + Id: tdUUID1.UUID, Name: td1, Description: &description, } @@ -498,13 +470,13 @@ func TestUDSPutTrustDomainByName(t *testing.T) { // Setup setup := NewManagementTestSetup(t, http.MethodPut, completePath, reqBody) - err := setup.Handler.PutTrustDomainByName(setup.EchoCtx, td1ID.UUID) + err := setup.Handler.PutTrustDomainByName(setup.EchoCtx, tdUUID1.UUID) assert.Error(t, err) assert.Empty(t, setup.Recorder.Body.Bytes()) echoHTTPErr := err.(*echo.HTTPError) assert.Equal(t, http.StatusNotFound, echoHTTPErr.Code) - expectedErrorMsg := fmt.Sprintf("trust domain %v does not exists", td1ID.UUID) + expectedErrorMsg := fmt.Sprintf("trust domain %v does not exists", tdUUID1.UUID) assert.Equal(t, expectedErrorMsg, echoHTTPErr.Message) }) } From 2b5d9588a7dc2b05397a3fda0a005f99788ad206 Mon Sep 17 00:00:00 2001 From: Victor Vieira Barros Leal da Silveira Date: Mon, 15 May 2023 10:40:24 -0300 Subject: [PATCH 14/20] fix: Removing const_test file and unit test changes --- pkg/server/endpoints/auth_test.go | 2 -- pkg/server/endpoints/const_test.go | 19 ------------------- pkg/server/endpoints/harvester_test.go | 21 +++++++++++++++++++-- 3 files changed, 19 insertions(+), 23 deletions(-) delete mode 100644 pkg/server/endpoints/const_test.go diff --git a/pkg/server/endpoints/auth_test.go b/pkg/server/endpoints/auth_test.go index f6909bed..5977e753 100644 --- a/pkg/server/endpoints/auth_test.go +++ b/pkg/server/endpoints/auth_test.go @@ -19,8 +19,6 @@ import ( "github.com/stretchr/testify/require" ) -const testTrustDomain = "test.com" - type AuthNTestSetup struct { EchoCtx echo.Context Middleware *AuthenticationMiddleware diff --git a/pkg/server/endpoints/const_test.go b/pkg/server/endpoints/const_test.go deleted file mode 100644 index 147037f1..00000000 --- a/pkg/server/endpoints/const_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package endpoints - -const ( - td1 = "test1.com" - td2 = "test2.com" - td3 = "test3.com" -) - -var ( - // Relationships ID's - r1ID = NewNullableID() - r2ID = NewNullableID() - r3ID = NewNullableID() - - // Trust Domains ID's - tdUUID1 = NewNullableID() - tdUUID2 = NewNullableID() - tdUUID3 = NewNullableID() -) diff --git a/pkg/server/endpoints/harvester_test.go b/pkg/server/endpoints/harvester_test.go index bfcd59e0..aac1f745 100644 --- a/pkg/server/endpoints/harvester_test.go +++ b/pkg/server/endpoints/harvester_test.go @@ -26,6 +26,23 @@ import ( const ( jwtPath = "/jwt" onboardPath = "/onboard" + + // Trust Domains + td1 = "test1.com" + td2 = "test2.com" + td3 = "test3.com" +) + +var ( + // Relationships ID's + r1ID = NewNullableID() + r2ID = NewNullableID() + r3ID = NewNullableID() + + // Trust Domains ID's + tdUUID1 = NewNullableID() + tdUUID2 = NewNullableID() + tdUUID3 = NewNullableID() ) type HarvesterTestSetup struct { @@ -51,7 +68,7 @@ func NewHarvesterTestSetup(t *testing.T, method, url string, body interface{}) * logger := logrus.New() jwtAudience := []string{"test"} - jwtIssuer := fakejwtissuer.New(t, "test", testTrustDomain, jwtAudience) + jwtIssuer := fakejwtissuer.New(t, "test", td1, jwtAudience) jwtValidator := jwttest.NewJWTValidator(jwtIssuer.Signer, jwtAudience) return &HarvesterTestSetup{ @@ -63,7 +80,7 @@ func NewHarvesterTestSetup(t *testing.T, method, url string, body interface{}) * } func SetupTrustDomain(t *testing.T, ds datastore.Datastore) *entity.TrustDomain { - td, err := spiffeid.TrustDomainFromString(testTrustDomain) + td, err := spiffeid.TrustDomainFromString(td1) assert.NoError(t, err) tdEntity := &entity.TrustDomain{ From 38449f079326ad2280fbef1920f9f0a01aa23f5e Mon Sep 17 00:00:00 2001 From: Victor Vieira Barros Leal da Silveira Date: Mon, 15 May 2023 11:36:20 -0300 Subject: [PATCH 15/20] fix: Misstypes and const places --- pkg/common/http/http.go | 3 +-- pkg/common/http/http_test.go | 2 +- pkg/server/endpoints/harvester_test.go | 18 ------------------ pkg/server/endpoints/management_test.go | 19 +++++++++++++++++++ 4 files changed, 21 insertions(+), 21 deletions(-) diff --git a/pkg/common/http/http.go b/pkg/common/http/http.go index 83e85dd7..50169d3a 100644 --- a/pkg/common/http/http.go +++ b/pkg/common/http/http.go @@ -3,7 +3,6 @@ package http import ( "errors" "fmt" - "net/http" "github.com/labstack/echo/v4" ) @@ -23,7 +22,7 @@ func WriteResponse(ctx echo.Context, code int, body interface{}) error { // BodilessResponse wraps error echo body-less responses. func BodilessResponse(ctx echo.Context, code int) error { - if err := ctx.NoContent(http.StatusOK); err != nil { + if err := ctx.NoContent(code); err != nil { return fmt.Errorf("failed to respond without body: %v", err) } diff --git a/pkg/common/http/http_test.go b/pkg/common/http/http_test.go index f8b0f924..cd7ef396 100644 --- a/pkg/common/http/http_test.go +++ b/pkg/common/http/http_test.go @@ -34,7 +34,7 @@ func Setup() *HTTPSetup { func TestWriteResponse(t *testing.T) { t.Run("Error when nil body is passed", func(t *testing.T) { setup := Setup() - err := WriteResponse(setup.EchoContext, 0, nil) + err := WriteResponse(setup.EchoContext, http.StatusOK, nil) assert.EqualError(t, err, "body is required") assert.Empty(t, setup.Recorder.Body) }) diff --git a/pkg/server/endpoints/harvester_test.go b/pkg/server/endpoints/harvester_test.go index aac1f745..11a5ab4f 100644 --- a/pkg/server/endpoints/harvester_test.go +++ b/pkg/server/endpoints/harvester_test.go @@ -26,23 +26,6 @@ import ( const ( jwtPath = "/jwt" onboardPath = "/onboard" - - // Trust Domains - td1 = "test1.com" - td2 = "test2.com" - td3 = "test3.com" -) - -var ( - // Relationships ID's - r1ID = NewNullableID() - r2ID = NewNullableID() - r3ID = NewNullableID() - - // Trust Domains ID's - tdUUID1 = NewNullableID() - tdUUID2 = NewNullableID() - tdUUID3 = NewNullableID() ) type HarvesterTestSetup struct { @@ -87,7 +70,6 @@ func SetupTrustDomain(t *testing.T, ds datastore.Datastore) *entity.TrustDomain Name: td, Description: "Fake domain", } - trustDomain, err := ds.CreateOrUpdateTrustDomain(context.TODO(), tdEntity) require.NoError(t, err) diff --git a/pkg/server/endpoints/management_test.go b/pkg/server/endpoints/management_test.go index 133cf968..9b3a3d8b 100644 --- a/pkg/server/endpoints/management_test.go +++ b/pkg/server/endpoints/management_test.go @@ -20,6 +20,25 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + // Trust Domains + td1 = "test1.com" + td2 = "test2.com" + td3 = "test3.com" +) + +var ( + // Relationships ID's + r1ID = NewNullableID() + r2ID = NewNullableID() + r3ID = NewNullableID() + + // Trust Domains ID's + tdUUID1 = NewNullableID() + tdUUID2 = NewNullableID() + tdUUID3 = NewNullableID() +) + type ManagementTestSetup struct { EchoCtx echo.Context Handler *AdminAPIHandlers From 21b679b0369824b7d8f74217ad2416a34d72e8bd Mon Sep 17 00:00:00 2001 From: Victor Vieira Barros Leal da Silveira Date: Mon, 15 May 2023 13:31:27 -0300 Subject: [PATCH 16/20] fix: Refactoring trust domain lookup functions --- pkg/server/endpoints/management.go | 45 ++++++++++++------- pkg/server/endpoints/management_test.go | 58 ++++++++++++------------- 2 files changed, 59 insertions(+), 44 deletions(-) diff --git a/pkg/server/endpoints/management.go b/pkg/server/endpoints/management.go index 3b12d78b..edb250e8 100644 --- a/pkg/server/endpoints/management.go +++ b/pkg/server/endpoints/management.go @@ -93,7 +93,13 @@ func (h *AdminAPIHandlers) PutRelationship(echoCtx echo.Context) error { } eRelationship := reqBody.ToEntity() - if err := h.checkTrustDomains(ctx, http.StatusBadRequest, eRelationship.TrustDomainAID, eRelationship.TrustDomainBID); err != nil { + _, err = h.lookupTrustDomain(ctx, eRelationship.TrustDomainAID) + if err != nil { + return err + } + + _, err = h.lookupTrustDomain(ctx, eRelationship.TrustDomainBID) + if err != nil { return err } @@ -234,7 +240,8 @@ func (h *AdminAPIHandlers) PutTrustDomainByName(echoCtx echo.Context, trustDomai return h.handleAndLog(err, http.StatusBadRequest) } - if err := h.checkTrustDomains(ctx, http.StatusNotFound, trustDomainID); err != nil { + _, err = h.lookupTrustDomain(ctx, trustDomainID) + if err != nil { return err } @@ -271,6 +278,11 @@ func (h *AdminAPIHandlers) GetJoinToken(echoCtx echo.Context, trustDomainName ap return h.handleAndLog(err, http.StatusInternalServerError) } + if td == nil { + errMsg := fmt.Errorf("trust domain exists: %q", trustDomainName) + return h.handleAndLog(errMsg, http.StatusBadRequest) + } + token := uuid.New() joinToken := &entity.JoinToken{ @@ -287,7 +299,11 @@ func (h *AdminAPIHandlers) GetJoinToken(echoCtx echo.Context, trustDomainName ap h.Logger.Infof("Created join token for trust domain: %s", tdName) - err = chttp.WriteResponse(echoCtx, http.StatusOK, token) + response := admin.JoinTokenResult{ + Token: token, + } + + err = chttp.WriteResponse(echoCtx, http.StatusOK, response) if err != nil { err = fmt.Errorf("failed to write join token response: %v", err.Error()) return h.handleAndLog(err, http.StatusInternalServerError) @@ -355,21 +371,20 @@ func (h *AdminAPIHandlers) populateTrustDomainNames(ctx context.Context, relatio return relationships, nil } -func (h *AdminAPIHandlers) checkTrustDomains(ctx context.Context, errCode int, ids ...uuid.UUID) error { - for _, id := range ids { - td, err := h.Datastore.FindTrustDomainByID(ctx, id) - if err != nil { - err := fmt.Errorf("not able retrieve information about trust domain %w", err) - return h.handleAndLog(err, http.StatusInternalServerError) - } +func (h *AdminAPIHandlers) lookupTrustDomain(ctx context.Context, trustDomainID uuid.UUID) (*entity.TrustDomain, error) { + td, err := h.Datastore.FindTrustDomainByID(ctx, trustDomainID) + if err != nil { + msg := errors.New("error looking up trust domain") + errMsg := fmt.Errorf("%s: %w", msg, err) + return nil, h.handleAndLog(errMsg, http.StatusInternalServerError) + } - if td == nil { - err := fmt.Errorf("trust domain %v does not exists", id) - return h.handleAndLog(err, errCode) - } + if td == nil { + errMsg := fmt.Errorf("trust domain exists: %q", trustDomainID) + return nil, h.handleAndLog(errMsg, http.StatusBadRequest) } - return nil + return td, nil } func mapRelationships(relationships []*entity.Relationship) []*api.Relationship { diff --git a/pkg/server/endpoints/management_test.go b/pkg/server/endpoints/management_test.go index 9b3a3d8b..49a32d11 100644 --- a/pkg/server/endpoints/management_test.go +++ b/pkg/server/endpoints/management_test.go @@ -500,46 +500,46 @@ func TestUDSPutTrustDomainByName(t *testing.T) { }) } -// func TestUDSPostTrustDomainTrustDomainNameJoinToken(t *testing.T) { -// trustDomainPath := "/trust-domain/%v/join-token" +func TestUDSGetJoinToken(t *testing.T) { + trustDomainPath := "/trust-domain/%v/join-token" -// t.Run("Successfully generates a join token for the trust domain", func(t *testing.T) { -// td1ID := NewNullableID() -// fakeTrustDomains := entity.TrustDomain{ID: td1ID, Name: NewTrustDomain(t, td1)} + t.Run("Successfully generates a join token for the trust domain", func(t *testing.T) { + td1ID := NewNullableID() + fakeTrustDomains := entity.TrustDomain{ID: td1ID, Name: NewTrustDomain(t, td1)} -// completePath := fmt.Sprintf(trustDomainPath, td1) + completePath := fmt.Sprintf(trustDomainPath, td1) -// // Setup -// setup := NewManagementTestSetup(t, http.MethodPut, completePath, nil) -// setup.FakeDatabase.WithTrustDomains(&fakeTrustDomains) + // Setup + setup := NewManagementTestSetup(t, http.MethodGet, completePath, nil) + setup.FakeDatabase.WithTrustDomains(&fakeTrustDomains) -// err := setup.Handler.PostTrustDomainTrustDomainNameJoinToken(setup.EchoCtx, td1) -// assert.NoError(t, err) -// assert.Equal(t, http.StatusOK, setup.Recorder.Code) + err := setup.Handler.GetJoinToken(setup.EchoCtx, td1) + assert.NoError(t, err) + assert.Equal(t, http.StatusOK, setup.Recorder.Code) -// apiJToken := admin.JoinTokenResult{} -// err = json.Unmarshal(setup.Recorder.Body.Bytes(), &apiJToken) -// assert.NoError(t, err) + apiJToken := admin.JoinTokenResult{} + err = json.Unmarshal(setup.Recorder.Body.Bytes(), &apiJToken) + assert.NoError(t, err) -// assert.NotEmpty(t, apiJToken) -// }) + assert.NotEmpty(t, apiJToken) + }) -// t.Run("Raise a bad request when trying to generates a join token for the trust domain that does not exists", func(t *testing.T) { -// completePath := fmt.Sprintf(trustDomainPath, td1) + t.Run("Raise a bad request when trying to generates a join token for the trust domain that does not exists", func(t *testing.T) { + completePath := fmt.Sprintf(trustDomainPath, td1) -// // Setup -// setup := NewManagementTestSetup(t, http.MethodPut, completePath, nil) + // Setup + setup := NewManagementTestSetup(t, http.MethodGet, completePath, nil) -// err := setup.Handler.PostTrustDomainTrustDomainNameJoinToken(setup.EchoCtx, td1) -// assert.Error(t, err) + err := setup.Handler.GetJoinToken(setup.EchoCtx, td1) + assert.Error(t, err) -// echoHttpErr := err.(*echo.HTTPError) -// assert.Equal(t, http.StatusBadRequest, echoHttpErr.Code) + echoHttpErr := err.(*echo.HTTPError) + assert.Equal(t, http.StatusBadRequest, echoHttpErr.Code) -// expectedMsg := fmt.Sprintf("trust domain %v does not exists ", td1) -// assert.Equal(t, expectedMsg, echoHttpErr.Message) -// }) -// } + expectedMsg := fmt.Errorf("trust domain exists: %q", td1) + assert.Equal(t, expectedMsg.Error(), echoHttpErr.Message) + }) +} func NewNullableID() uuid.NullUUID { return uuid.NullUUID{ From 7eafbe5753757bbe73404e4475cdbaa1d8263eda Mon Sep 17 00:00:00 2001 From: Victor Vieira Barros Leal da Silveira Date: Mon, 15 May 2023 13:39:00 -0300 Subject: [PATCH 17/20] fix: Unit tests failing --- pkg/server/endpoints/management.go | 10 +++++----- pkg/server/endpoints/management_test.go | 4 ++-- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/pkg/server/endpoints/management.go b/pkg/server/endpoints/management.go index edb250e8..f8ced053 100644 --- a/pkg/server/endpoints/management.go +++ b/pkg/server/endpoints/management.go @@ -93,12 +93,12 @@ func (h *AdminAPIHandlers) PutRelationship(echoCtx echo.Context) error { } eRelationship := reqBody.ToEntity() - _, err = h.lookupTrustDomain(ctx, eRelationship.TrustDomainAID) + _, err = h.lookupTrustDomain(ctx, eRelationship.TrustDomainAID, http.StatusBadRequest) if err != nil { return err } - _, err = h.lookupTrustDomain(ctx, eRelationship.TrustDomainBID) + _, err = h.lookupTrustDomain(ctx, eRelationship.TrustDomainBID, http.StatusBadRequest) if err != nil { return err } @@ -240,7 +240,7 @@ func (h *AdminAPIHandlers) PutTrustDomainByName(echoCtx echo.Context, trustDomai return h.handleAndLog(err, http.StatusBadRequest) } - _, err = h.lookupTrustDomain(ctx, trustDomainID) + _, err = h.lookupTrustDomain(ctx, trustDomainID, http.StatusNotFound) if err != nil { return err } @@ -371,7 +371,7 @@ func (h *AdminAPIHandlers) populateTrustDomainNames(ctx context.Context, relatio return relationships, nil } -func (h *AdminAPIHandlers) lookupTrustDomain(ctx context.Context, trustDomainID uuid.UUID) (*entity.TrustDomain, error) { +func (h *AdminAPIHandlers) lookupTrustDomain(ctx context.Context, trustDomainID uuid.UUID, code int) (*entity.TrustDomain, error) { td, err := h.Datastore.FindTrustDomainByID(ctx, trustDomainID) if err != nil { msg := errors.New("error looking up trust domain") @@ -381,7 +381,7 @@ func (h *AdminAPIHandlers) lookupTrustDomain(ctx context.Context, trustDomainID if td == nil { errMsg := fmt.Errorf("trust domain exists: %q", trustDomainID) - return nil, h.handleAndLog(errMsg, http.StatusBadRequest) + return nil, h.handleAndLog(errMsg, code) } return td, nil diff --git a/pkg/server/endpoints/management_test.go b/pkg/server/endpoints/management_test.go index 49a32d11..ee44ca64 100644 --- a/pkg/server/endpoints/management_test.go +++ b/pkg/server/endpoints/management_test.go @@ -295,7 +295,7 @@ func TestUDSPutRelationships(t *testing.T) { echoHTTPErr := err.(*echo.HTTPError) assert.Equal(t, http.StatusBadRequest, echoHTTPErr.Code) - expectedErrorMsg := fmt.Sprintf("trust domain %v does not exists", tdUUID2.UUID) + expectedErrorMsg := fmt.Sprintf("trust domain exists: %q", tdUUID2.UUID) assert.Equal(t, expectedErrorMsg, echoHTTPErr.Message) }) @@ -495,7 +495,7 @@ func TestUDSPutTrustDomainByName(t *testing.T) { echoHTTPErr := err.(*echo.HTTPError) assert.Equal(t, http.StatusNotFound, echoHTTPErr.Code) - expectedErrorMsg := fmt.Sprintf("trust domain %v does not exists", tdUUID1.UUID) + expectedErrorMsg := fmt.Sprintf("trust domain exists: %q", tdUUID1.UUID) assert.Equal(t, expectedErrorMsg, echoHTTPErr.Message) }) } From b60cec3a7224a36e36a14fc1d7926b263e690aa4 Mon Sep 17 00:00:00 2001 From: Victor Vieira Barros Leal da Silveira Date: Tue, 16 May 2023 13:29:05 -0300 Subject: [PATCH 18/20] fix: Removing unused values --- pkg/server/endpoints/management_test.go | 1 - 1 file changed, 1 deletion(-) diff --git a/pkg/server/endpoints/management_test.go b/pkg/server/endpoints/management_test.go index 2604c80b..be973155 100644 --- a/pkg/server/endpoints/management_test.go +++ b/pkg/server/endpoints/management_test.go @@ -34,7 +34,6 @@ var ( r3ID = NewNullableID() r4ID = NewNullableID() r5ID = NewNullableID() - r6ID = NewNullableID() // Trust Domains ID's tdUUID1 = NewNullableID() From 4da954f811bfd28942e8e43b90f89040fb5545d5 Mon Sep 17 00:00:00 2001 From: Victor Vieira Barros Leal da Silveira Date: Tue, 16 May 2023 13:35:39 -0300 Subject: [PATCH 19/20] fix: Unit test failing --- pkg/server/endpoints/harvester_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/server/endpoints/harvester_test.go b/pkg/server/endpoints/harvester_test.go index 900fb32c..3c560491 100644 --- a/pkg/server/endpoints/harvester_test.go +++ b/pkg/server/endpoints/harvester_test.go @@ -618,7 +618,7 @@ func testBundlePut(t *testing.T, setupFunc func(*HarvesterTestSetup) *entity.Tru TrustDomain: td1, } - body, err := json.Marshal(bundlePut) + body, err := json.Marshal(&bundlePut) require.NoError(t, err) setup := NewHarvesterTestSetup(t, http.MethodPut, "/trust-domain/:trustDomainName/bundles", string(body)) From b92ffcb366573a10634ff402207b263054809d20 Mon Sep 17 00:00:00 2001 From: Victor Vieira Barros Leal da Silveira Date: Tue, 16 May 2023 13:51:29 -0300 Subject: [PATCH 20/20] fix: Unit test checking --- pkg/server/endpoints/harvester_test.go | 57 ++++++++++---------------- 1 file changed, 21 insertions(+), 36 deletions(-) diff --git a/pkg/server/endpoints/harvester_test.go b/pkg/server/endpoints/harvester_test.go index 3c560491..55c0cef4 100644 --- a/pkg/server/endpoints/harvester_test.go +++ b/pkg/server/endpoints/harvester_test.go @@ -150,7 +150,7 @@ func TestTCPGetRelationships(t *testing.T) { }) t.Run("Fails with invalid consent status", func(t *testing.T) { - setup := NewHarvesterTestSetup(t, http.MethodGet, relationshipsPath, "") + setup := NewHarvesterTestSetup(t, http.MethodGet, relationshipsPath, nil) echoCtx := setup.EchoCtx setup.EchoCtx.Set(authTrustDomainKey, tdA) @@ -168,7 +168,7 @@ func TestTCPGetRelationships(t *testing.T) { }) t.Run("Fails if no authenticated trust domain", func(t *testing.T) { - setup := NewHarvesterTestSetup(t, http.MethodGet, relationshipsPath, "") + setup := NewHarvesterTestSetup(t, http.MethodGet, relationshipsPath, nil) echoCtx := setup.EchoCtx tdName := tdA.Name.String() @@ -183,7 +183,7 @@ func TestTCPGetRelationships(t *testing.T) { }) t.Run("Fails if authenticated trust domain does not match trust domain parameter", func(t *testing.T) { - setup := NewHarvesterTestSetup(t, http.MethodGet, relationshipsPath, "") + setup := NewHarvesterTestSetup(t, http.MethodGet, relationshipsPath, nil) echoCtx := setup.EchoCtx setup.EchoCtx.Set(authTrustDomainKey, tdA) @@ -200,7 +200,7 @@ func TestTCPGetRelationships(t *testing.T) { } func testGetRelationships(t *testing.T, setupFn func(*HarvesterTestSetup, *entity.TrustDomain), status api.ConsentStatus, trustDomain *entity.TrustDomain, expectedRelationshipCount int) { - setup := NewHarvesterTestSetup(t, http.MethodGet, relationshipsPath, "") + setup := NewHarvesterTestSetup(t, http.MethodGet, relationshipsPath, nil) echoCtx := setup.EchoCtx setup.Datastore.WithTrustDomains(tdA, tdB, tdC) @@ -268,10 +268,7 @@ func testPatchRelationship(t *testing.T, f func(setup *HarvesterTestSetup, trust ConsentStatus: status, } - body, err := json.Marshal(requestBody) - require.NoError(t, err) - - setup := NewHarvesterTestSetup(t, http.MethodPatch, relationshipsPath+"/"+relationship.ID.UUID.String(), string(body)) + setup := NewHarvesterTestSetup(t, http.MethodPatch, relationshipsPath+"/"+relationship.ID.UUID.String(), &requestBody) echoCtx := setup.EchoCtx setup.Datastore.WithTrustDomains(tdA, tdB, tdC) @@ -279,7 +276,7 @@ func testPatchRelationship(t *testing.T, f func(setup *HarvesterTestSetup, trust f(setup, trustDomain) - err = setup.Handler.PatchRelationship(echoCtx, relationship.ID.UUID) + err := setup.Handler.PatchRelationship(echoCtx, relationship.ID.UUID) assert.NoError(t, err) recorder := setup.Recorder @@ -304,7 +301,7 @@ func testPatchRelationship(t *testing.T, f func(setup *HarvesterTestSetup, trust func TestTCPOnboard(t *testing.T) { t.Run("Successfully onboard a new agent", func(t *testing.T) { - harvesterTestSetup := NewHarvesterTestSetup(t, http.MethodGet, onboardPath, "") + harvesterTestSetup := NewHarvesterTestSetup(t, http.MethodGet, onboardPath, nil) echoCtx := harvesterTestSetup.EchoCtx td := SetupTrustDomain(t, harvesterTestSetup.Handler.Datastore) @@ -325,7 +322,7 @@ func TestTCPOnboard(t *testing.T) { assert.Equal(t, harvesterTestSetup.JWTIssuer.Token, jwtToken) }) t.Run("Onboard without join token fails", func(t *testing.T) { - harvesterTestSetup := NewHarvesterTestSetup(t, http.MethodGet, onboardPath, "") + harvesterTestSetup := NewHarvesterTestSetup(t, http.MethodGet, onboardPath, nil) echoCtx := harvesterTestSetup.EchoCtx SetupTrustDomain(t, harvesterTestSetup.Handler.Datastore) @@ -341,7 +338,7 @@ func TestTCPOnboard(t *testing.T) { assert.Contains(t, httpErr.Message, "join token is required") }) t.Run("Onboard with join token that does not exist fails", func(t *testing.T) { - harvesterTestSetup := NewHarvesterTestSetup(t, http.MethodGet, onboardPath, "") + harvesterTestSetup := NewHarvesterTestSetup(t, http.MethodGet, onboardPath, nil) echoCtx := harvesterTestSetup.EchoCtx td := SetupTrustDomain(t, harvesterTestSetup.Handler.Datastore) @@ -358,7 +355,7 @@ func TestTCPOnboard(t *testing.T) { assert.Contains(t, httpErr.Message, "token not found") }) t.Run("Onboard with join token that was used", func(t *testing.T) { - harvesterTestSetup := NewHarvesterTestSetup(t, http.MethodGet, onboardPath, "") + harvesterTestSetup := NewHarvesterTestSetup(t, http.MethodGet, onboardPath, nil) echoCtx := harvesterTestSetup.EchoCtx td := SetupTrustDomain(t, harvesterTestSetup.Handler.Datastore) @@ -382,7 +379,7 @@ func TestTCPOnboard(t *testing.T) { func TestTCPGetNewJWTToken(t *testing.T) { t.Run("Successfully get a new JWT token", func(t *testing.T) { - harvesterTestSetup := NewHarvesterTestSetup(t, http.MethodGet, jwtPath, "") + harvesterTestSetup := NewHarvesterTestSetup(t, http.MethodGet, jwtPath, nil) echoCtx := harvesterTestSetup.EchoCtx SetupTrustDomain(t, harvesterTestSetup.Handler.Datastore) @@ -406,7 +403,7 @@ func TestTCPGetNewJWTToken(t *testing.T) { assert.Equal(t, harvesterTestSetup.JWTIssuer.Token, jwtToken) }) t.Run("Fails if no JWT token was sent", func(t *testing.T) { - harvesterTestSetup := NewHarvesterTestSetup(t, http.MethodGet, jwtPath, "") + harvesterTestSetup := NewHarvesterTestSetup(t, http.MethodGet, jwtPath, nil) echoCtx := harvesterTestSetup.EchoCtx err := harvesterTestSetup.Handler.GetNewJWTToken(echoCtx) @@ -525,10 +522,7 @@ func TestTCPBundleSync(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - body, err := json.Marshal(tc.bundleState) - require.NoError(t, err) - - setup := NewHarvesterTestSetup(t, http.MethodPost, "/trust-domain/:trustDomainName/bundles/sync", string(body)) + setup := NewHarvesterTestSetup(t, http.MethodPost, "/trust-domain/:trustDomainName/bundles/sync", &tc.bundleState) echoCtx := setup.EchoCtx setup.EchoCtx.Set(authTrustDomainKey, tdA) @@ -537,7 +531,7 @@ func TestTCPBundleSync(t *testing.T) { setup.Datastore.WithBundles(bundleA, bundleB, bundleC) // test bundle sync - err = setup.Handler.BundleSync(echoCtx, tdA.Name.String()) + err := setup.Handler.BundleSync(echoCtx, tdA.Name.String()) assert.NoError(t, err) recorder := setup.Recorder @@ -581,13 +575,10 @@ func TestBundlePut(t *testing.T) { TrustDomain: td1, } - body, err := json.Marshal(bundlePut) - require.NoError(t, err) - - setup := NewHarvesterTestSetup(t, http.MethodPut, "/trust-domain/:trustDomainName/bundles", string(body)) + setup := NewHarvesterTestSetup(t, http.MethodPut, "/trust-domain/:trustDomainName/bundles", &bundlePut) setup.EchoCtx.Set(authTrustDomainKey, "") - err = setup.Handler.BundlePut(setup.EchoCtx, td1) + err := setup.Handler.BundlePut(setup.EchoCtx, td1) require.Error(t, err) assert.Equal(t, http.StatusUnauthorized, err.(*echo.HTTPError).Code) assert.Contains(t, err.(*echo.HTTPError).Message, "no authenticated trust domain") @@ -606,7 +597,7 @@ func TestBundlePut(t *testing.T) { }) t.Run("Fail post bundle bundle trust domain does not match authenticated trust domain", func(t *testing.T) { - testInvalidBundleRequest(t, "TrustDomain", "other-trust-domain", http.StatusUnauthorized, "trust domain in request bundle \"other-trust-domain\" does not match authenticated trust domain: \"test.com\"") + testInvalidBundleRequest(t, "TrustDomain", "other-trust-domain", http.StatusUnauthorized, "trust domain in request bundle \"other-trust-domain\" does not match authenticated trust domain: \"test1.com\"") }) } @@ -618,15 +609,12 @@ func testBundlePut(t *testing.T, setupFunc func(*HarvesterTestSetup) *entity.Tru TrustDomain: td1, } - body, err := json.Marshal(&bundlePut) - require.NoError(t, err) - - setup := NewHarvesterTestSetup(t, http.MethodPut, "/trust-domain/:trustDomainName/bundles", string(body)) + setup := NewHarvesterTestSetup(t, http.MethodPut, "/trust-domain/:trustDomainName/bundles", &bundlePut) echoCtx := setup.EchoCtx td := setupFunc(setup) - err = setup.Handler.BundlePut(echoCtx, td1) + err := setup.Handler.BundlePut(echoCtx, td1) require.NoError(t, err) recorder := setup.Recorder @@ -650,16 +638,13 @@ func testInvalidBundleRequest(t *testing.T, fieldName string, fieldValue interfa } reflect.ValueOf(&bundlePut).Elem().FieldByName(fieldName).Set(reflect.ValueOf(fieldValue)) - body, err := json.Marshal(bundlePut) - require.NoError(t, err) - - setup := NewHarvesterTestSetup(t, http.MethodPut, "/trust-domain/:trustDomainName/bundles", string(body)) + setup := NewHarvesterTestSetup(t, http.MethodPut, "/trust-domain/:trustDomainName/bundles", &bundlePut) echoCtx := setup.EchoCtx td := SetupTrustDomain(t, setup.Handler.Datastore) echoCtx.Set(authTrustDomainKey, td) - err = setup.Handler.BundlePut(echoCtx, td1) + err := setup.Handler.BundlePut(echoCtx, td1) require.Error(t, err) assert.Equal(t, expectedStatusCode, err.(*echo.HTTPError).Code) assert.Contains(t, err.(*echo.HTTPError).Message, expectedErrorMessage)