diff --git a/internal/cmd/base/initial_resources.go b/internal/cmd/base/initial_resources.go index 6282e67c7..aa09fc44c 100644 --- a/internal/cmd/base/initial_resources.go +++ b/internal/cmd/base/initial_resources.go @@ -461,7 +461,7 @@ func (b *Server) CreateInitialTargetWithAddress(ctx context.Context) (target.Tar if err != nil { return nil, fmt.Errorf("failed to create target object: %w", err) } - tt, _, _, err := targetRepo.CreateTarget(ctx, t, opts...) + tt, err := targetRepo.CreateTarget(ctx, t, opts...) if err != nil { return nil, fmt.Errorf("failed to save target to the db: %w", err) } @@ -525,11 +525,11 @@ func (b *Server) CreateInitialTargetWithHostSources(ctx context.Context) (target if err != nil { return nil, fmt.Errorf("failed to create target object: %w", err) } - tt, _, _, err := targetRepo.CreateTarget(ctx, t, opts...) + tt, err := targetRepo.CreateTarget(ctx, t, opts...) if err != nil { return nil, fmt.Errorf("failed to save target to the db: %w", err) } - tt, _, _, err = targetRepo.AddTargetHostSources(ctx, tt.GetPublicId(), tt.GetVersion(), []string{b.DevHostSetId}) + tt, err = targetRepo.AddTargetHostSources(ctx, tt.GetPublicId(), tt.GetVersion(), []string{b.DevHostSetId}) if err != nil { return nil, fmt.Errorf("failed to add host source %q to target: %w", b.DevHostSetId, err) } diff --git a/internal/daemon/controller/handlers/targets/target_service.go b/internal/daemon/controller/handlers/targets/target_service.go index 35e681338..e4f56ec02 100644 --- a/internal/daemon/controller/handlers/targets/target_service.go +++ b/internal/daemon/controller/handlers/targets/target_service.go @@ -245,7 +245,7 @@ func (s Service) ListTargets(ctx context.Context, req *pbs.ListTargetsRequest) ( outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authorizedActions)) } - item, err := toProto(ctx, item, nil, nil, outputOpts...) + item, err := toProto(ctx, item, outputOpts...) if err != nil { return nil, err } @@ -291,8 +291,10 @@ func (s Service) GetTarget(ctx context.Context, req *pbs.GetTargetRequest) (*pbs if outputFields.Has(globals.AuthorizedActionsField) { outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, t.GetPublicId(), IdActions).Strings())) } + t.SetHostSources(ts) + t.SetCredentialSources(cl) - item, err := toProto(ctx, t, ts, cl, outputOpts...) + item, err := toProto(ctx, t, outputOpts...) if err != nil { return nil, err } @@ -329,8 +331,10 @@ func (s Service) CreateTarget(ctx context.Context, req *pbs.CreateTargetRequest) if outputFields.Has(globals.AuthorizedActionsField) { outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, t.GetPublicId(), IdActions).Strings())) } + t.SetHostSources(ts) + t.SetCredentialSources(cl) - item, err := toProto(ctx, t, ts, cl, outputOpts...) + item, err := toProto(ctx, t, outputOpts...) if err != nil { return nil, err } @@ -367,8 +371,10 @@ func (s Service) UpdateTarget(ctx context.Context, req *pbs.UpdateTargetRequest) if outputFields.Has(globals.AuthorizedActionsField) { outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, t.GetPublicId(), IdActions).Strings())) } + t.SetHostSources(ts) + t.SetCredentialSources(cl) - item, err := toProto(ctx, t, ts, cl, outputOpts...) + item, err := toProto(ctx, t, outputOpts...) if err != nil { return nil, err } @@ -403,10 +409,12 @@ func (s Service) AddTargetHostSources(ctx context.Context, req *pbs.AddTargetHos if authResults.Error != nil { return nil, authResults.Error } - t, ts, cl, err := s.addHostSourcesInRepo(ctx, req.GetId(), req.GetHostSourceIds(), req.GetVersion()) + t, err := s.addHostSourcesInRepo(ctx, req.GetId(), req.GetHostSourceIds(), req.GetVersion()) if err != nil { return nil, err } + ts := t.GetHostSources() + cl := t.GetCredentialSources() outputFields, ok := requests.OutputFields(ctx) if !ok { @@ -421,8 +429,10 @@ func (s Service) AddTargetHostSources(ctx context.Context, req *pbs.AddTargetHos if outputFields.Has(globals.AuthorizedActionsField) { outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, t.GetPublicId(), IdActions).Strings())) } + t.SetHostSources(ts) + t.SetCredentialSources(cl) - item, err := toProto(ctx, t, ts, cl, outputOpts...) + item, err := toProto(ctx, t, outputOpts...) if err != nil { return nil, err } @@ -459,8 +469,10 @@ func (s Service) SetTargetHostSources(ctx context.Context, req *pbs.SetTargetHos if outputFields.Has(globals.AuthorizedActionsField) { outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, t.GetPublicId(), IdActions).Strings())) } + t.SetHostSources(ts) + t.SetCredentialSources(cl) - item, err := toProto(ctx, t, ts, cl, outputOpts...) + item, err := toProto(ctx, t, outputOpts...) if err != nil { return nil, err } @@ -497,8 +509,10 @@ func (s Service) RemoveTargetHostSources(ctx context.Context, req *pbs.RemoveTar if outputFields.Has(globals.AuthorizedActionsField) { outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, t.GetPublicId(), IdActions).Strings())) } + t.SetHostSources(ts) + t.SetCredentialSources(cl) - item, err := toProto(ctx, t, ts, cl, outputOpts...) + item, err := toProto(ctx, t, outputOpts...) if err != nil { return nil, err } @@ -537,8 +551,10 @@ func (s Service) AddTargetCredentialSources(ctx context.Context, req *pbs.AddTar if outputFields.Has(globals.AuthorizedActionsField) { outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, t.GetPublicId(), IdActions).Strings())) } + t.SetHostSources(ts) + t.SetCredentialSources(cl) - item, err := toProto(ctx, t, ts, cl, outputOpts...) + item, err := toProto(ctx, t, outputOpts...) if err != nil { return nil, err } @@ -577,8 +593,10 @@ func (s Service) SetTargetCredentialSources(ctx context.Context, req *pbs.SetTar if outputFields.Has(globals.AuthorizedActionsField) { outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, t.GetPublicId(), IdActions).Strings())) } + t.SetHostSources(ts) + t.SetCredentialSources(cl) - item, err := toProto(ctx, t, ts, cl, outputOpts...) + item, err := toProto(ctx, t, outputOpts...) if err != nil { return nil, err } @@ -617,8 +635,10 @@ func (s Service) RemoveTargetCredentialSources(ctx context.Context, req *pbs.Rem if outputFields.Has(globals.AuthorizedActionsField) { outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, t.GetPublicId(), IdActions).Strings())) } + t.SetHostSources(ts) + t.SetCredentialSources(cl) - item, err := toProto(ctx, t, ts, cl, outputOpts...) + item, err := toProto(ctx, t, outputOpts...) if err != nil { return nil, err } @@ -711,7 +731,10 @@ func (s Service) AuthorizeSession(ctx context.Context, req *pbs.AuthorizeSession if err != nil { return nil, err } - t, hostSources, credSources, err := repo.LookupTarget(ctx, t.GetPublicId()) + t, err = repo.LookupTarget(ctx, t.GetPublicId()) + hostSources := t.GetHostSources() + credSources := t.GetCredentialSources() + if err != nil { if errors.IsNotFoundError(err) { return nil, handlers.NotFoundErrorf("Target %q not found.", t.GetPublicId()) @@ -1037,13 +1060,16 @@ func (s Service) getFromRepo(ctx context.Context, id string) (target.Target, []t if err != nil { return nil, nil, nil, err } - u, hs, cl, err := repo.LookupTarget(ctx, id) + u, err := repo.LookupTarget(ctx, id) if err != nil { if errors.IsNotFoundError(err) { return nil, nil, nil, handlers.NotFoundErrorf("Target %q doesn't exist.", id) } return nil, nil, nil, err } + hs := u.GetHostSources() + cl := u.GetCredentialSources() + if u == nil { return nil, nil, nil, handlers.NotFoundErrorf("Target %q doesn't exist.", id) } @@ -1086,10 +1112,13 @@ func (s Service) createInRepo(ctx context.Context, item *pb.Target) (target.Targ if err != nil { return nil, nil, nil, err } - out, hs, cl, err := repo.CreateTarget(ctx, u) + out, err := repo.CreateTarget(ctx, u) if err != nil { return nil, nil, nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to create target")) } + hs := out.GetHostSources() + cl := out.GetCredentialSources() + if out == nil { return nil, nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create target but no error returned from repository.") } @@ -1157,10 +1186,13 @@ func (s Service) updateInRepo(ctx context.Context, scopeId, id string, mask []st if err != nil { return nil, nil, nil, err } - out, hs, cl, rowsUpdated, err := repo.UpdateTarget(ctx, u, version, dbMask, opts...) + out, rowsUpdated, err := repo.UpdateTarget(ctx, u, version, dbMask, opts...) if err != nil { return nil, nil, nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to update target")) } + hs := out.GetHostSources() + cl := out.GetCredentialSources() + if rowsUpdated == 0 { return nil, nil, nil, handlers.NotFoundErrorf("Target %q not found or incorrect version provided.", id) } @@ -1195,26 +1227,26 @@ func (s Service) listFromRepo(ctx context.Context, perms []perms.Permission) ([] return ul, nil } -func (s Service) addHostSourcesInRepo(ctx context.Context, targetId string, hostSourceIds []string, version uint32) (target.Target, []target.HostSource, []target.CredentialSource, error) { +func (s Service) addHostSourcesInRepo(ctx context.Context, targetId string, hostSourceIds []string, version uint32) (target.Target, error) { repo, err := s.repoFn() if err != nil { - return nil, nil, nil, err + return nil, err } - out, hs, cl, err := repo.AddTargetHostSources(ctx, targetId, version, strutil.RemoveDuplicates(hostSourceIds, false)) + out, err := repo.AddTargetHostSources(ctx, targetId, version, strutil.RemoveDuplicates(hostSourceIds, false)) if err != nil { var internalErr *errors.Err if stderrors.As(err, &internalErr) && internalErr.Code == errors.Conflict { // The conflict error is surfaced directly as it's correctly // converted all the way down to the HTTP status. - return nil, nil, nil, err + return nil, err } // TODO: Figure out a way to surface more helpful error info beyond the Internal error. - return nil, nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Failed to add target host sources") + return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Failed to add target host sources") } if out == nil { - return nil, nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to lookup target after adding host sources to it.") + return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to lookup target after adding host sources to it.") } - return out, hs, cl, nil + return out, nil } func (s Service) setHostSourcesInRepo(ctx context.Context, targetId string, hostSourceIds []string, version uint32) (target.Target, []target.HostSource, []target.CredentialSource, error) { @@ -1235,10 +1267,13 @@ func (s Service) setHostSourcesInRepo(ctx context.Context, targetId string, host return nil, nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Failed to set target host sources") } - out, hs, cl, err := repo.LookupTarget(ctx, targetId) + out, err := repo.LookupTarget(ctx, targetId) if err != nil { return nil, nil, nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to look up target after setting host sources")) } + hs := out.GetHostSources() + cl := out.GetCredentialSources() + if out == nil { return nil, nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to lookup target after setting host sources for it.") } @@ -1256,10 +1291,13 @@ func (s Service) removeHostSourcesInRepo(ctx context.Context, targetId string, h // TODO: Figure out a way to surface more helpful error info beyond the Internal error. return nil, nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to remove host sources from target: %v.", err) } - out, hs, cl, err := repo.LookupTarget(ctx, targetId) + out, err := repo.LookupTarget(ctx, targetId) if err != nil { return nil, nil, nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to look up target after removing host sources")) } + hs := out.GetHostSources() + cl := out.GetCredentialSources() + if out == nil { return nil, nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to lookup target after removing host sources from it.") } @@ -1280,11 +1318,14 @@ func (s Service) addCredentialSourcesInRepo(ctx context.Context, targetId string creds.InjectedApplicationCredentialIds = strutil.RemoveDuplicates(injectedAppIds, false) } - out, hs, credSources, err := repo.AddTargetCredentialSources(ctx, targetId, version, creds) + out, err := repo.AddTargetCredentialSources(ctx, targetId, version, creds) if err != nil { // TODO: Figure out a way to surface more helpful error info beyond the Internal error. return nil, nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to add credential sources to target: %v.", err) } + hs := out.GetHostSources() + credSources := out.GetCredentialSources() + if out == nil { return nil, nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to lookup target after adding credential sources to it.") } @@ -1312,10 +1353,13 @@ func (s Service) setCredentialSourcesInRepo(ctx context.Context, targetId string return nil, nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to set credential sources in target: %v.", err) } - out, hs, credSources, err := repo.LookupTarget(ctx, targetId) + out, err := repo.LookupTarget(ctx, targetId) if err != nil { return nil, nil, nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to look up target after setting credential sources")) } + hs := out.GetHostSources() + credSources := out.GetCredentialSources() + if out == nil { return nil, nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to lookup target after setting credential sources for it.") } @@ -1341,10 +1385,13 @@ func (s Service) removeCredentialSourcesInRepo(ctx context.Context, targetId str // TODO: Figure out a way to surface more helpful error info beyond the Internal error. return nil, nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to remove credential sources from target: %v.", err) } - out, hs, credSources, err := repo.LookupTarget(ctx, targetId) + out, err := repo.LookupTarget(ctx, targetId) if err != nil { return nil, nil, nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to look up target after removing credential sources")) } + hs := out.GetHostSources() + credSources := out.GetCredentialSources() + if out == nil { return nil, nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to lookup target after removing credential sources from it.") } @@ -1380,7 +1427,7 @@ func (s Service) authResult(ctx context.Context, id string, a action.Type, looku res.Error = err return res } - t, _, _, err = repo.LookupTarget(ctx, id, lookupOpt...) + t, err = repo.LookupTarget(ctx, id, lookupOpt...) if err != nil { // TODO: Fix this with new/better error handling if strings.Contains(err.Error(), "more than one row returned by a subquery") { @@ -1404,13 +1451,15 @@ func (s Service) authResult(ctx context.Context, id string, a action.Type, looku return ret } -func toProto(ctx context.Context, in target.Target, hostSources []target.HostSource, credSources []target.CredentialSource, opt ...handlers.Option) (*pb.Target, error) { +func toProto(ctx context.Context, in target.Target, opt ...handlers.Option) (*pb.Target, error) { const op = "target_service.toProto" opts := handlers.GetOpts(opt...) if opts.WithOutputFields == nil { return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "output fields not found when building target proto") } outputFields := *opts.WithOutputFields + hostSources := in.GetHostSources() + credSources := in.GetCredentialSources() out := pb.Target{} if outputFields.Has(globals.IdField) { diff --git a/internal/daemon/controller/handlers/targets/tcp/target_service_test.go b/internal/daemon/controller/handlers/targets/tcp/target_service_test.go index c4664cecf..17de25259 100644 --- a/internal/daemon/controller/handlers/targets/tcp/target_service_test.go +++ b/internal/daemon/controller/handlers/targets/tcp/target_service_test.go @@ -819,16 +819,16 @@ func TestUpdate(t *testing.T) { target.WithSessionConnectionLimit(1), target.WithDefaultPort(2)) require.NoError(t, err) - tar, _, _, err := repo.CreateTarget(context.Background(), ttar) + tar, err := repo.CreateTarget(context.Background(), ttar) require.NoError(t, err) - tar, _, _, err = repo.AddTargetHostSources(context.Background(), tar.GetPublicId(), tar.GetVersion(), []string{hs[0].GetPublicId(), hs[1].GetPublicId()}) + tar, err = repo.AddTargetHostSources(context.Background(), tar.GetPublicId(), tar.GetVersion(), []string{hs[0].GetPublicId(), hs[1].GetPublicId()}) require.NoError(t, err) resetTarget := func() { - itar, _, _, err := repo.LookupTarget(context.Background(), tar.GetPublicId()) + itar, err := repo.LookupTarget(context.Background(), tar.GetPublicId()) require.NoError(t, err) - tar, _, _, _, err = repo.UpdateTarget(context.Background(), tar, itar.GetVersion(), + tar, _, err = repo.UpdateTarget(context.Background(), tar, itar.GetVersion(), []string{"Name", "Description", "SessionMaxSeconds", "SessionConnectionLimit", "DefaultPort"}) require.NoError(t, err, "Failed to reset target.") } @@ -1297,7 +1297,7 @@ func TestUpdate_BadVersion(t *testing.T) { tar := ttar.(*tcp.Target) tar.DefaultPort = 2 require.NoError(t, err) - gtar, _, _, err := repo.CreateTarget(context.Background(), tar) + gtar, err := repo.CreateTarget(context.Background(), tar) require.NoError(t, err) tested, err := testService(t, context.Background(), conn, kms, wrapper) diff --git a/internal/session/repository_session_test.go b/internal/session/repository_session_test.go index 98eada54b..5fdb84c9b 100644 --- a/internal/session/repository_session_test.go +++ b/internal/session/repository_session_test.go @@ -999,7 +999,7 @@ func TestRepository_CancelSession(t *testing.T) { targetRepo, err := target.NewRepository(ctx, rw, rw, testKms) require.NoError(t, err) - _, _, _, err = targetRepo.AddTargetHostSources(ctx, tcpTarget.GetPublicId(), tcpTarget.GetVersion(), []string{sets[0].PublicId}) + _, err = targetRepo.AddTargetHostSources(ctx, tcpTarget.GetPublicId(), tcpTarget.GetVersion(), []string{sets[0].PublicId}) require.NoError(t, err) authMethod := password.TestAuthMethods(t, conn, org.PublicId, 1)[0] @@ -1527,7 +1527,7 @@ func testSessionCredentialParams(t *testing.T, conn *db.DB, wrapper wrapping.Wra kms := kms.TestKms(t, conn, wrapper) targetRepo, err := target.NewRepository(ctx, rw, rw, kms) require.NoError(err) - tar, _, _, err := targetRepo.LookupTarget(ctx, params.TargetId) + tar, err := targetRepo.LookupTarget(ctx, params.TargetId) require.NoError(err) require.NotNil(tar) @@ -1540,7 +1540,7 @@ func testSessionCredentialParams(t *testing.T, conn *db.DB, wrapper wrapping.Wra ids := target.CredentialSources{ BrokeredCredentialIds: []string{libIds[0].GetPublicId(), libIds[1].GetPublicId(), upCreds[0].GetPublicId(), upCreds[1].GetPublicId()}, } - _, _, _, err = targetRepo.AddTargetCredentialSources(ctx, tar.GetPublicId(), tar.GetVersion(), ids) + _, err = targetRepo.AddTargetCredentialSources(ctx, tar.GetPublicId(), tar.GetVersion(), ids) require.NoError(err) dynamicCreds := []*DynamicCredential{ NewDynamicCredential(libIds[0].GetPublicId(), cred.BrokeredPurpose), diff --git a/internal/session/service_authorize_connection_test.go b/internal/session/service_authorize_connection_test.go index 6d09a607a..ee5698e30 100644 --- a/internal/session/service_authorize_connection_test.go +++ b/internal/session/service_authorize_connection_test.go @@ -95,7 +95,7 @@ func TestService_AuthorizeConnection(t *testing.T) { targetRepo, err := target.NewRepository(ctx, rw, rw, testKms) require.NoError(t, err) - _, _, _, err = targetRepo.AddTargetHostSources(ctx, tcpTarget.GetPublicId(), tcpTarget.GetVersion(), []string{sets[0].PublicId}) + _, err = targetRepo.AddTargetHostSources(ctx, tcpTarget.GetPublicId(), tcpTarget.GetVersion(), []string{sets[0].PublicId}) require.NoError(t, err) authMethod := password.TestAuthMethods(t, conn, org.PublicId, 1)[0] diff --git a/internal/session/service_close_connections_test.go b/internal/session/service_close_connections_test.go index 1a7c2cc1f..59bcb2338 100644 --- a/internal/session/service_close_connections_test.go +++ b/internal/session/service_close_connections_test.go @@ -56,7 +56,7 @@ func TestServiceCloseConnections(t *testing.T) { targetRepo, err := target.NewRepository(ctx, rw, rw, testKms) require.NoError(t, err) - _, _, _, err = targetRepo.AddTargetHostSources(ctx, tcpTarget.GetPublicId(), tcpTarget.GetVersion(), []string{sets[0].PublicId}) + _, err = targetRepo.AddTargetHostSources(ctx, tcpTarget.GetPublicId(), tcpTarget.GetVersion(), []string{sets[0].PublicId}) require.NoError(t, err) authMethod := password.TestAuthMethods(t, conn, org.PublicId, 1)[0] diff --git a/internal/session/testing.go b/internal/session/testing.go index 6ad94b1f7..a969a0b76 100644 --- a/internal/session/testing.go +++ b/internal/session/testing.go @@ -222,7 +222,7 @@ func TestSessionParams(t testing.TB, conn *db.DB, wrapper wrapping.Wrapper, iamR kms := kms.TestKms(t, conn, wrapper) targetRepo, err := target.NewRepository(ctx, rw, rw, kms) require.NoError(err) - _, _, _, err = targetRepo.AddTargetHostSources(ctx, tcpTarget.GetPublicId(), tcpTarget.GetVersion(), []string{sets[0].PublicId}) + _, err = targetRepo.AddTargetHostSources(ctx, tcpTarget.GetPublicId(), tcpTarget.GetVersion(), []string{sets[0].PublicId}) require.NoError(err) authMethod := password.TestAuthMethods(t, conn, org.PublicId, 1)[0] diff --git a/internal/target/repository.go b/internal/target/repository.go index d14d65815..10cd47263 100644 --- a/internal/target/repository.go +++ b/internal/target/repository.go @@ -87,12 +87,12 @@ func NewRepository(ctx context.Context, r db.Reader, w db.Writer, kms *kms.Kms, // LookupTarget will look up a target in the repository and return the target // with its host source ids and credential source ids. If the target is not // found, it will return nil, nil, nil, nil. No options are currently supported. -func (r *Repository) LookupTarget(ctx context.Context, publicIdOrName string, opt ...Option) (Target, []HostSource, []CredentialSource, error) { +func (r *Repository) LookupTarget(ctx context.Context, publicIdOrName string, opt ...Option) (Target, error) { const op = "target.(Repository).LookupTarget" opts := GetOpts(opt...) if publicIdOrName == "" { - return nil, nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing public id") + return nil, errors.New(ctx, errors.InvalidParameter, op, "missing public id") } var where []string @@ -102,27 +102,27 @@ func (r *Repository) LookupTarget(ctx context.Context, publicIdOrName string, op projectNameEmpty := opts.WithProjectName == "" if !nameEmpty { if opts.WithName != publicIdOrName { - return nil, nil, nil, errors.New(ctx, errors.InvalidParameter, op, "name passed in but does not match publicId") + return nil, errors.New(ctx, errors.InvalidParameter, op, "name passed in but does not match publicId") } where, whereArgs = append(where, "lower(name) = lower(?)"), append(whereArgs, opts.WithName) switch { case projectIdEmpty && projectNameEmpty: - return nil, nil, nil, errors.New(ctx, errors.InvalidParameter, op, "using name but both project ID and project name are empty") + return nil, errors.New(ctx, errors.InvalidParameter, op, "using name but both project ID and project name are empty") case !projectIdEmpty && !projectNameEmpty: - return nil, nil, nil, errors.New(ctx, errors.InvalidParameter, op, "using name but both project ID and project name are set") + return nil, errors.New(ctx, errors.InvalidParameter, op, "using name but both project ID and project name are set") case !projectIdEmpty: where, whereArgs = append(where, "project_id = ?"), append(whereArgs, opts.WithProjectId) case !projectNameEmpty: where, whereArgs = append(where, "project_id = (select public_id from iam_scope where lower(name) = lower(?))"), append(whereArgs, opts.WithProjectName) default: - return nil, nil, nil, errors.New(ctx, errors.InvalidParameter, op, "unknown combination of parameters") + return nil, errors.New(ctx, errors.InvalidParameter, op, "unknown combination of parameters") } } else { switch { case !projectIdEmpty: - return nil, nil, nil, errors.New(ctx, errors.InvalidParameter, op, "passed in project ID when using target ID for lookup") + return nil, errors.New(ctx, errors.InvalidParameter, op, "passed in project ID when using target ID for lookup") case !projectNameEmpty: - return nil, nil, nil, errors.New(ctx, errors.InvalidParameter, op, "passed in project name when using target ID for lookup") + return nil, errors.New(ctx, errors.InvalidParameter, op, "passed in project name when using target ID for lookup") } } @@ -166,15 +166,18 @@ func (r *Repository) LookupTarget(ctx context.Context, publicIdOrName string, op ) if err != nil { if errors.IsNotFoundError(err) { - return nil, nil, nil, nil + return nil, nil } - return nil, nil, nil, errors.Wrap(ctx, err, op) + return nil, errors.Wrap(ctx, err, op) } subtype, err := target.targetSubtype(ctx, address) if err != nil { - return nil, nil, nil, errors.Wrap(ctx, err, op) + return nil, errors.Wrap(ctx, err, op) } - return subtype, hostSources, credSources, nil + subtype.SetHostSources(hostSources) + subtype.SetCredentialSources(credSources) + + return subtype, nil } // FetchAuthzProtectedEntitiesByScope implements boundary.AuthzProtectedEntityProvider @@ -375,44 +378,44 @@ func (r *Repository) DeleteTarget(ctx context.Context, publicId string, _ ...Opt // CreateTarget inserts into the repository and returns the new Target with // its list of host sets and credential libraries. // WithPublicId is the only supported option. -func (r *Repository) CreateTarget(ctx context.Context, target Target, opt ...Option) (Target, []HostSource, []CredentialSource, error) { +func (r *Repository) CreateTarget(ctx context.Context, target Target, opt ...Option) (Target, error) { const op = "target.(Repository).CreateTarget" opts := GetOpts(opt...) if target == nil { - return nil, nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing target") + return nil, errors.New(ctx, errors.InvalidParameter, op, "missing target") } vet, ok := subtypeRegistry.vetFunc(target.GetType()) if !ok { - return nil, nil, nil, errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("unsupported target type %s", target.GetType())) + return nil, errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("unsupported target type %s", target.GetType())) } if err := vet(ctx, target); err != nil { - return nil, nil, nil, err + return nil, err } if target.GetProjectId() == "" { - return nil, nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing project id") + return nil, errors.New(ctx, errors.InvalidParameter, op, "missing project id") } if target.GetName() == "" { - return nil, nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing name") + return nil, errors.New(ctx, errors.InvalidParameter, op, "missing name") } if target.GetPublicId() != "" { - return nil, nil, nil, errors.New(ctx, errors.InvalidParameter, op, "public id not empty") + return nil, errors.New(ctx, errors.InvalidParameter, op, "public id not empty") } t := target.Clone() if opts.WithPublicId != "" { if err := t.SetPublicId(ctx, opts.WithPublicId); err != nil { - return nil, nil, nil, err + return nil, err } } else { prefix, ok := subtypeRegistry.idPrefix(target.GetType()) if !ok { - return nil, nil, nil, errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("unsupported target type %s", target.GetType())) + return nil, errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("unsupported target type %s", target.GetType())) } id, err := db.NewPublicId(prefix) if err != nil { - return nil, nil, nil, errors.Wrap(ctx, err, op) + return nil, errors.Wrap(ctx, err, op) } t.SetPublicId(ctx, id) } @@ -423,19 +426,17 @@ func (r *Repository) CreateTarget(ctx context.Context, target Target, opt ...Opt t.SetAddress(strings.TrimSpace(t.GetAddress())) address, err = NewAddress(t.GetPublicId(), t.GetAddress()) if err != nil { - return nil, nil, nil, errors.Wrap(ctx, err, op) + return nil, errors.Wrap(ctx, err, op) } } oplogWrapper, err := r.kms.GetWrapper(ctx, target.GetProjectId(), kms.KeyPurposeOplog) if err != nil { - return nil, nil, nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to get oplog wrapper")) + return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to get oplog wrapper")) } metadata := t.Oplog(oplog.OpType_OP_TYPE_CREATE) var returnedTarget any - var returnedHostSources []HostSource - var returnedCredSources []CredentialSource _, err = r.writer.DoTx( ctx, db.StdRetryCnt, @@ -469,9 +470,9 @@ func (r *Repository) CreateTarget(ctx context.Context, target Target, opt ...Opt }, ) if err != nil { - return nil, nil, nil, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("failed for %s target id", t.GetPublicId()))) + return nil, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("failed for %s target id", t.GetPublicId()))) } - return returnedTarget.(Target), returnedHostSources, returnedCredSources, nil + return returnedTarget.(Target), nil } // UpdateTarget will update a target in the repository and return the written @@ -480,26 +481,26 @@ func (r *Repository) CreateTarget(ctx context.Context, target Target, opt ...Opt // included in fieldMask. Name, Description, and WorkerFilter are the only // updatable fields. If no updatable fields are included in the fieldMaskPaths, // then an error is returned. -func (r *Repository) UpdateTarget(ctx context.Context, target Target, version uint32, fieldMaskPaths []string, _ ...Option) (Target, []HostSource, []CredentialSource, int, error) { +func (r *Repository) UpdateTarget(ctx context.Context, target Target, version uint32, fieldMaskPaths []string, _ ...Option) (Target, int, error) { const op = "target.(Repository).UpdateTarget" if target == nil { - return nil, nil, nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing target") + return nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing target") } if target.GetPublicId() == "" { - return nil, nil, nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing target public id") + return nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing target public id") } if target.GetProjectId() == "" { - return nil, nil, nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing project id") + return nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing project id") } if version == 0 { - return nil, nil, nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing version") + return nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing version") } vet, ok := subtypeRegistry.vetForUpdateFunc(target.GetType()) if !ok { - return nil, nil, nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("unsupported target type %s", target.GetType())) + return nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("unsupported target type %s", target.GetType())) } if err := vet(ctx, target, fieldMaskPaths); err != nil { - return nil, nil, nil, db.NoRowsAffected, err + return nil, db.NoRowsAffected, err } var addressEndpoint string @@ -517,7 +518,7 @@ func (r *Repository) UpdateTarget(ctx context.Context, target Target, version ui target.SetAddress(strings.TrimSpace(target.GetAddress())) addressEndpoint = target.GetAddress() default: - return nil, nil, nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidFieldMask, op, fmt.Sprintf("invalid field mask: %s", f)) + return nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidFieldMask, op, fmt.Sprintf("invalid field mask: %s", f)) } } @@ -538,7 +539,7 @@ func (r *Repository) UpdateTarget(ctx context.Context, target Target, version ui []string{"SessionMaxSeconds", "SessionConnectionLimit"}, ) if len(dbMask) == 0 && len(nullFields) == 0 { - return nil, nil, nil, db.NoRowsAffected, errors.New(ctx, errors.EmptyFieldMask, op, "empty field mask") + return nil, db.NoRowsAffected, errors.New(ctx, errors.EmptyFieldMask, op, "empty field mask") } // The Address field is not apart of the target schema in the database. @@ -573,7 +574,7 @@ func (r *Repository) UpdateTarget(ctx context.Context, target Target, version ui oplogWrapper, err := r.kms.GetWrapper(ctx, target.GetProjectId(), kms.KeyPurposeOplog) if err != nil { - return nil, nil, nil, db.NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg("unable to get oplog wrapper")) + return nil, db.NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg("unable to get oplog wrapper")) } var rowsUpdated int @@ -653,9 +654,13 @@ func (r *Repository) UpdateTarget(ctx context.Context, target Target, version ui ) if err != nil { if errors.IsUniqueError(err) { - return nil, nil, nil, db.NoRowsAffected, errors.New(ctx, errors.NotUnique, op, fmt.Sprintf("target %s already exists in project %s", target.GetName(), target.GetProjectId())) + return nil, db.NoRowsAffected, errors.New(ctx, errors.NotUnique, op, fmt.Sprintf("target %s already exists in project %s", target.GetName(), target.GetProjectId())) } - return nil, nil, nil, db.NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("failed for %s", target.GetPublicId()))) + return nil, db.NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("failed for %s", target.GetPublicId()))) } - return returnedTarget, hostSources, credSources, rowsUpdated, nil + + returnedTarget.SetHostSources(hostSources) + returnedTarget.SetCredentialSources(credSources) + + return returnedTarget, rowsUpdated, nil } diff --git a/internal/target/repository_credential_source.go b/internal/target/repository_credential_source.go index c9b3e7a03..56ab09279 100644 --- a/internal/target/repository_credential_source.go +++ b/internal/target/repository_credential_source.go @@ -22,35 +22,35 @@ import ( // The target and the list of credential sources attached to the target, after ids are added, // will be returned on success. // The targetVersion must match the current version of the targetId in the repository. -func (r *Repository) AddTargetCredentialSources(ctx context.Context, targetId string, targetVersion uint32, idsByPurpose CredentialSources, _ ...Option) (Target, []HostSource, []CredentialSource, error) { +func (r *Repository) AddTargetCredentialSources(ctx context.Context, targetId string, targetVersion uint32, idsByPurpose CredentialSources, _ ...Option) (Target, error) { const op = "target.(Repository).AddTargetCredentialSources" if targetId == "" { - return nil, nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing target id") + return nil, errors.New(ctx, errors.InvalidParameter, op, "missing target id") } if targetVersion == 0 { - return nil, nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing version") + return nil, errors.New(ctx, errors.InvalidParameter, op, "missing version") } t := allocTargetView() t.PublicId = targetId if err := r.reader.LookupByPublicId(ctx, &t); err != nil { - return nil, nil, nil, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("failed for %s", targetId))) + return nil, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("failed for %s", targetId))) } var metadata oplog.Metadata alloc, ok := subtypeRegistry.allocFunc(t.Subtype()) if !ok { - return nil, nil, nil, errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("%s is an unsupported target type %s", t.PublicId, t.Type)) + return nil, errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("%s is an unsupported target type %s", t.PublicId, t.Type)) } addCredLibs, addStaticCreds, err := r.createSources(ctx, targetId, t.Subtype(), idsByPurpose) if err != nil { - return nil, nil, nil, errors.Wrap(ctx, err, op) + return nil, errors.Wrap(ctx, err, op) } target := alloc() if err := target.SetPublicId(ctx, t.PublicId); err != nil { - return nil, nil, nil, errors.Wrap(ctx, err, op) + return nil, errors.Wrap(ctx, err, op) } target.SetVersion(targetVersion + 1) metadata = target.Oplog(oplog.OpType_OP_TYPE_UPDATE) @@ -58,11 +58,9 @@ func (r *Repository) AddTargetCredentialSources(ctx context.Context, targetId st oplogWrapper, err := r.kms.GetWrapper(ctx, t.GetProjectId(), kms.KeyPurposeOplog) if err != nil { - return nil, nil, nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to get oplog wrapper")) + return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to get oplog wrapper")) } - var hostSources []HostSource - var credSources []CredentialSource var updatedTarget Target _, err = r.writer.DoTx( ctx, @@ -116,14 +114,18 @@ func (r *Repository) AddTargetCredentialSources(ctx context.Context, targetId st if err := w.WriteOplogEntryWith(ctx, oplogWrapper, targetTicket, metadata, msgs); err != nil { return errors.Wrap(ctx, err, op, errors.WithMsg("unable to write oplog")) } - hostSources, err = fetchHostSources(ctx, reader, targetId) + hostSources, err := fetchHostSources(ctx, reader, targetId) if err != nil { return errors.Wrap(ctx, err, op, errors.WithMsg("unable to retrieve host sources after adding")) } - credSources, err = fetchCredentialSources(ctx, reader, targetId) + updatedTarget.SetHostSources(hostSources) + + credSources, err := fetchCredentialSources(ctx, reader, targetId) if err != nil { return errors.Wrap(ctx, err, op, errors.WithMsg("unable to retrieve credential sources after adding")) } + updatedTarget.SetCredentialSources(credSources) + address, err := fetchAddress(ctx, reader, targetId) if err != nil && !errors.IsNotFoundError(err) { return errors.Wrap(ctx, err, op, errors.WithMsg("unable to retrieve target address after adding")) @@ -135,9 +137,9 @@ func (r *Repository) AddTargetCredentialSources(ctx context.Context, targetId st }, ) if err != nil { - return nil, nil, nil, errors.Wrap(ctx, err, op) + return nil, errors.Wrap(ctx, err, op) } - return updatedTarget.(Target), hostSources, credSources, nil + return updatedTarget, nil } // DeleteTargetCredentialSources deletes credential sources from a target in the repository. @@ -334,8 +336,6 @@ func (r *Repository) SetTargetCredentialSources(ctx context.Context, targetId st } var rowsAffected int - var hostSources []HostSource - var credSources []CredentialSource _, err = r.writer.DoTx( ctx, db.StdRetryCnt, @@ -432,21 +432,25 @@ func (r *Repository) SetTargetCredentialSources(ctx context.Context, targetId st return errors.Wrap(ctx, err, op, errors.WithMsg("unable to write oplog")) } - hostSources, err = fetchHostSources(ctx, reader, targetId) + hostSources, err := fetchHostSources(ctx, reader, targetId) if err != nil { return errors.Wrap(ctx, err, op, errors.WithMsg("unable to retrieve current target host sets after add/delete")) } - credSources, err = fetchCredentialSources(ctx, reader, targetId) + updatedTarget.SetHostSources(hostSources) + + credSources, err := fetchCredentialSources(ctx, reader, targetId) if err != nil { return errors.Wrap(ctx, err, op, errors.WithMsg("unable to retrieve current target credential sources after add/delete")) } + updatedTarget.SetCredentialSources(credSources) + return nil }, ) if err != nil { return nil, nil, db.NoRowsAffected, errors.Wrap(ctx, err, op) } - return hostSources, credSources, rowsAffected, nil + return t.HostSource, t.CredentialSources, rowsAffected, nil } type changeQueryResult struct { diff --git a/internal/target/repository_credential_source_test.go b/internal/target/repository_credential_source_test.go index 442c6d4dd..b5246d769 100644 --- a/internal/target/repository_credential_source_test.go +++ b/internal/target/repository_credential_source_test.go @@ -79,10 +79,13 @@ func TestRepository_SetTargetCredentialSources(t *testing.T) { ids.BrokeredCredentialIds = append(ids.BrokeredCredentialIds, cred.GetPublicId()) } - _, _, created, err := repo.AddTargetCredentialSources(context.Background(), tar.GetPublicId(), 1, ids) + target, err := repo.AddTargetCredentialSources(context.Background(), tar.GetPublicId(), 1, ids) require.NoError(t, err) - require.Equal(t, 10, len(created)) - return created, ids + + credentialSources := target.GetCredentialSources() + + require.Equal(t, 10, len(credentialSources)) + return credentialSources, ids } type args struct { targetVersion uint32 @@ -267,9 +270,10 @@ func TestRepository_SetTargetCredentialSources(t *testing.T) { } } - origTarget, _, lookupCredSources, err := repo.LookupTarget(ctx, tar.GetPublicId()) + origTarget, err := repo.LookupTarget(ctx, tar.GetPublicId()) require.NoError(err) - assert.Equal(origCredSources, lookupCredSources) + + assert.Equal(origCredSources, origTarget.GetCredentialSources()) _, gotSources, affectedRows, err := repo.SetTargetCredentialSources(ctx, tar.GetPublicId(), tt.args.targetVersion, tt.args.ids) if tt.wantErr { @@ -289,7 +293,7 @@ func TestRepository_SetTargetCredentialSources(t *testing.T) { assert.Equal(w.CredentialPurpose(), cs.CredentialPurpose()) } - foundTarget, _, _, err := repo.LookupTarget(ctx, tar.GetPublicId()) + foundTarget, err := repo.LookupTarget(ctx, tar.GetPublicId()) require.NoError(err) if tt.name != "no-change" { assert.Equalf(tt.args.targetVersion+1, foundTarget.GetVersion(), "%s unexpected version: %d/%d", tt.name, tt.args.targetVersion+1, foundTarget.GetVersion()) diff --git a/internal/target/repository_host_source.go b/internal/target/repository_host_source.go index 9ac89d3ea..557956af6 100644 --- a/internal/target/repository_host_source.go +++ b/internal/target/repository_host_source.go @@ -18,35 +18,35 @@ import ( // targetVersion or an error will be returned. The target and a list of current // host source ids will be returned on success. Zero is not a valid value for the // WithVersion option and will return an error. -func (r *Repository) AddTargetHostSources(ctx context.Context, targetId string, targetVersion uint32, hostSourceIds []string, _ ...Option) (Target, []HostSource, []CredentialSource, error) { +func (r *Repository) AddTargetHostSources(ctx context.Context, targetId string, targetVersion uint32, hostSourceIds []string, _ ...Option) (Target, error) { const op = "target.(Repository).AddTargetHostSources" if targetId == "" { - return nil, nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing target id") + return nil, errors.New(ctx, errors.InvalidParameter, op, "missing target id") } if targetVersion == 0 { - return nil, nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing version") + return nil, errors.New(ctx, errors.InvalidParameter, op, "missing version") } if len(hostSourceIds) == 0 { - return nil, nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing host source ids") + return nil, errors.New(ctx, errors.InvalidParameter, op, "missing host source ids") } newHostSources := make([]any, 0, len(hostSourceIds)) for _, id := range hostSourceIds { ths, err := NewTargetHostSet(targetId, id) if err != nil { - return nil, nil, nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to create in memory target host set")) + return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to create in memory target host set")) } newHostSources = append(newHostSources, ths) } t := allocTargetView() t.PublicId = targetId if err := r.reader.LookupByPublicId(ctx, &t); err != nil { - return nil, nil, nil, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("failed for %s", targetId))) + return nil, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("failed for %s", targetId))) } var metadata oplog.Metadata alloc, ok := subtypeRegistry.allocFunc(t.Subtype()) if !ok { - return nil, nil, nil, errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("%s is an unsupported target type %s", t.PublicId, t.Type)) + return nil, errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("%s is an unsupported target type %s", t.PublicId, t.Type)) } target := alloc() @@ -57,7 +57,7 @@ func (r *Repository) AddTargetHostSources(ctx context.Context, targetId string, oplogWrapper, err := r.kms.GetWrapper(ctx, t.GetProjectId(), kms.KeyPurposeOplog) if err != nil { - return nil, nil, nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to get oplog wrapper")) + return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to get oplog wrapper")) } var currentHostSources []HostSource var currentCredSources []CredentialSource @@ -113,10 +113,13 @@ func (r *Repository) AddTargetHostSources(ctx context.Context, targetId string, }, ) if err != nil { - return nil, nil, nil, errors.Wrap(ctx, err, op, errors.WithMsg("error creating sets")) + return nil, errors.Wrap(ctx, err, op, errors.WithMsg("error creating sets")) } - return updatedTarget, currentHostSources, currentCredSources, nil + updatedTarget.SetHostSources(currentHostSources) + updatedTarget.SetCredentialSources(currentCredSources) + + return updatedTarget, nil } // DeleteTargeHostSources deletes host sources from a target (targetId). The @@ -290,8 +293,6 @@ func (r *Repository) SetTargetHostSources(ctx context.Context, targetId string, } var totalRowsAffected int - var currentHostSources []HostSource - var currentCredSources []CredentialSource _, err = r.writer.DoTx( ctx, db.StdRetryCnt, @@ -350,14 +351,17 @@ func (r *Repository) SetTargetHostSources(ctx context.Context, targetId string, return errors.Wrap(ctx, err, op, errors.WithMsg("unable to write oplog")) } - currentHostSources, err = fetchHostSources(ctx, reader, targetId) + currentHostSources, err := fetchHostSources(ctx, reader, targetId) if err != nil { return errors.Wrap(ctx, err, op, errors.WithMsg("unable to retrieve current target host sources after set")) } - currentCredSources, err = fetchCredentialSources(ctx, reader, targetId) + t.SetHostSources(currentHostSources) + + currentCredSources, err := fetchCredentialSources(ctx, reader, targetId) if err != nil { return errors.Wrap(ctx, err, op, errors.WithMsg("unable to retrieve current target credential sources after set")) } + t.SetCredentialSources(currentCredSources) return nil }, @@ -365,7 +369,7 @@ func (r *Repository) SetTargetHostSources(ctx context.Context, targetId string, if err != nil { return nil, nil, db.NoRowsAffected, errors.Wrap(ctx, err, op) } - return currentHostSources, currentCredSources, totalRowsAffected, nil + return t.HostSource, t.CredentialSources, totalRowsAffected, nil } func fetchHostSources(ctx context.Context, r db.Reader, targetId string) ([]HostSource, error) { diff --git a/internal/target/target.go b/internal/target/target.go index 94342906a..30c1e7921 100644 --- a/internal/target/target.go +++ b/internal/target/target.go @@ -33,6 +33,8 @@ type Target interface { GetEgressWorkerFilter() string GetIngressWorkerFilter() string GetAddress() string + GetHostSources() []HostSource + GetCredentialSources() []CredentialSource Clone() Target SetPublicId(context.Context, string) error SetProjectId(string) @@ -48,6 +50,8 @@ type Target interface { SetEgressWorkerFilter(string) SetIngressWorkerFilter(string) SetAddress(string) + SetHostSources([]HostSource) + SetCredentialSources([]CredentialSource) Oplog(op oplog.OpType) oplog.Metadata } @@ -66,8 +70,10 @@ var ( type targetView struct { *store.TargetView // Network address assigned to the Target. - Address string `json:"address,omitempty" gorm:"-"` - tableName string `gorm:"-"` + Address string `json:"address,omitempty" gorm:"-"` + tableName string `gorm:"-"` + HostSource []HostSource `gorm:"-"` + CredentialSources []CredentialSource `gorm:"-"` } // allocTargetView will allocate a target view @@ -96,6 +102,14 @@ func (t *targetView) SetTableName(n string) { } } +func (t *targetView) SetHostSources(hs []HostSource) { + t.HostSource = hs +} + +func (t *targetView) SetCredentialSources(cs []CredentialSource) { + t.CredentialSources = cs +} + // GetPublicId satisfies boundary.AuthzProtectedEntity func (t targetView) GetPublicId() string { return t.PublicId @@ -106,6 +120,14 @@ func (t targetView) GetProjectId() string { return t.ProjectId } +func (t *targetView) GetHostSources() []HostSource { + return t.HostSource +} + +func (t *targetView) GetCredentialSources() []CredentialSource { + return t.CredentialSources +} + // GetUserId satisfies boundary.AuthzProtectedEntity; targets are not associated // with a user ID so this always returns an empty string func (t targetView) GetUserId() string { @@ -147,5 +169,7 @@ func (t *targetView) targetSubtype(ctx context.Context, address string) (Target, tt.SetEgressWorkerFilter(t.EgressWorkerFilter) tt.SetIngressWorkerFilter(t.IngressWorkerFilter) tt.SetAddress(address) + tt.SetHostSources(t.HostSource) + tt.SetCredentialSources(t.CredentialSources) return tt, nil } diff --git a/internal/target/targettest/target.go b/internal/target/targettest/target.go index 2cf5a8bcb..1257ef057 100644 --- a/internal/target/targettest/target.go +++ b/internal/target/targettest/target.go @@ -30,8 +30,10 @@ const ( // Target is a target.Target used for tests. type Target struct { *store.Target - Address string `gorm:"-"` - tableName string `gorm:"-"` + Address string `gorm:"-"` + tableName string `gorm:"-"` + HostSource []target.HostSource `gorm:"-"` + CredentialSources []target.CredentialSource `gorm:"-"` } var ( @@ -133,11 +135,21 @@ func (t *Target) GetAddress() string { return t.Address } +func (t *Target) GetHostSources() []target.HostSource { + return t.HostSource +} + +func (t *Target) GetCredentialSources() []target.CredentialSource { + return t.CredentialSources +} + func (t *Target) Clone() target.Target { cp := proto.Clone(t.Target) return &Target{ - Address: t.Address, - Target: cp.(*store.Target), + Address: t.Address, + Target: cp.(*store.Target), + HostSource: t.HostSource, + CredentialSources: t.CredentialSources, } } @@ -198,6 +210,14 @@ func (t *Target) SetAddress(a string) { t.Address = a } +func (t *Target) SetHostSources(sources []target.HostSource) { + t.HostSource = sources +} + +func (t *Target) SetCredentialSources(sources []target.CredentialSource) { + t.CredentialSources = sources +} + func (t *Target) Oplog(op oplog.OpType) oplog.Metadata { return oplog.Metadata{ "resource-public-id": []string{t.PublicId}, diff --git a/internal/target/tcp/immutable_fields_test.go b/internal/target/tcp/immutable_fields_test.go index 0c6f6b04d..c4dff542d 100644 --- a/internal/target/tcp/immutable_fields_test.go +++ b/internal/target/tcp/immutable_fields_test.go @@ -178,7 +178,8 @@ func TestTargetHostSet_ImmutableFields(t *testing.T) { updateTarget := tcp.TestTarget(ctx, t, conn, proj.PublicId, tcp.TestId(t)) updateHset := hsets[1] - _, gotHostSources, _, err := repo.AddTargetHostSources(ctx, projTarget.GetPublicId(), 1, []string{hsets[0].PublicId}) + gotTarget, err := repo.AddTargetHostSources(ctx, projTarget.GetPublicId(), 1, []string{hsets[0].PublicId}) + gotHostSources := gotTarget.GetHostSources() require.NoError(t, err) require.Equal(t, 1, len(gotHostSources)) new, err := target.NewTargetHostSet(projTarget.GetPublicId(), gotHostSources[0].Id()) diff --git a/internal/target/tcp/repository_credential_source_test.go b/internal/target/tcp/repository_credential_source_test.go index 58f34cd73..a8547043b 100644 --- a/internal/target/tcp/repository_credential_source_test.go +++ b/internal/target/tcp/repository_credential_source_test.go @@ -246,13 +246,15 @@ func TestRepository_AddTargetCredentialSources(t *testing.T) { ctx := context.Background() projTarget := tcp.TestTarget(ctx, t, conn, staticProj.PublicId, tt.name) - gotTarget, _, gotCredSources, err := repo.AddTargetCredentialSources(context.Background(), projTarget.GetPublicId(), tt.args.targetVersion, tt.args.ids) + gotTarget, err := repo.AddTargetCredentialSources(context.Background(), projTarget.GetPublicId(), tt.args.targetVersion, tt.args.ids) if tt.wantErr { require.Error(err) assert.Truef(errors.Match(errors.T(tt.wantErrCode), err), "unexpected error %s", err.Error()) return } require.NoError(err) + + gotCredSources := gotTarget.GetCredentialSources() assert.Len(gotCredSources, len(tt.wantCredSources)) for _, cs := range gotCredSources { @@ -266,8 +268,10 @@ func TestRepository_AddTargetCredentialSources(t *testing.T) { err = db.TestVerifyOplog(t, rw, projTarget.GetPublicId(), db.WithOperation(oplog.OpType_OP_TYPE_UPDATE), db.WithCreateNotBefore(10*time.Second)) assert.NoError(err) - tar, _, lookupCredSources, err := repo.LookupTarget(context.Background(), projTarget.GetPublicId()) + tar, err := repo.LookupTarget(context.Background(), projTarget.GetPublicId()) require.NoError(err) + lookupCredSources := tar.GetCredentialSources() + assert.Equal(tt.args.targetVersion+1, tar.GetVersion()) assert.Equal(projTarget.GetVersion(), tar.GetVersion()-1) assert.True(proto.Equal(gotTarget.(*tcp.Target), tar.(*tcp.Target))) @@ -291,7 +295,8 @@ func TestRepository_AddTargetCredentialSources(t *testing.T) { ids := target.CredentialSources{ BrokeredCredentialIds: []string{lib1.PublicId}, } - _, _, gotCredSources, err := repo.AddTargetCredentialSources(ctx, projTarget.GetPublicId(), 1, ids) + gotTarget, err := repo.AddTargetCredentialSources(ctx, projTarget.GetPublicId(), 1, ids) + gotCredSources := gotTarget.GetCredentialSources() require.NoError(err) assert.Len(gotCredSources, 1) assert.Equal(lib1.PublicId, gotCredSources[0].Id()) @@ -300,7 +305,7 @@ func TestRepository_AddTargetCredentialSources(t *testing.T) { ids = target.CredentialSources{ BrokeredCredentialIds: []string{lib1.PublicId}, } - _, _, _, err = repo.AddTargetCredentialSources(ctx, projTarget.GetPublicId(), 2, ids) + _, err = repo.AddTargetCredentialSources(ctx, projTarget.GetPublicId(), 2, ids) require.Error(err) assert.True(errors.Match(errors.T(errors.NotUnique), err)) @@ -308,13 +313,14 @@ func TestRepository_AddTargetCredentialSources(t *testing.T) { ids = target.CredentialSources{ BrokeredCredentialIds: []string{lib3.PublicId, lib2.PublicId, lib1.PublicId}, } - _, _, _, err = repo.AddTargetCredentialSources(ctx, projTarget.GetPublicId(), 2, ids) + _, err = repo.AddTargetCredentialSources(ctx, projTarget.GetPublicId(), 2, ids) require.Error(err) assert.True(errors.Match(errors.T(errors.NotUnique), err)) // Previous transactions should have been rolled back and only lib1 should be associated - _, _, lookupCredSources, err := repo.LookupTarget(ctx, projTarget.GetPublicId()) + lookupTarget, err := repo.LookupTarget(ctx, projTarget.GetPublicId()) require.NoError(err) + lookupCredSources := lookupTarget.GetCredentialSources() assert.Len(lookupCredSources, 1) assert.Equal(lib1.PublicId, lookupCredSources[0].Id()) }) @@ -324,7 +330,7 @@ func TestRepository_AddTargetCredentialSources(t *testing.T) { ids := target.CredentialSources{ BrokeredCredentialIds: []string{lib1.PublicId}, } - _, _, _, err := repo.AddTargetCredentialSources(context.Background(), "fake-target-id", 1, ids) + _, err := repo.AddTargetCredentialSources(context.Background(), "fake-target-id", 1, ids) require.Error(err) assert.Truef(errors.Match(errors.T(errors.RecordNotFound), err), "unexpected error %s", err.Error()) @@ -473,9 +479,9 @@ func TestRepository_DeleteTargetCredentialSources(t *testing.T) { ids.BrokeredCredentialIds = append(ids.BrokeredCredentialIds, c.GetPublicId()) } - _, _, addedCredSources, err := repo.AddTargetCredentialSources(ctx, tar.GetPublicId(), 1, ids) + addedTarget, err := repo.AddTargetCredentialSources(ctx, tar.GetPublicId(), 1, ids) require.NoError(err) - assert.Equal(tt.args.createLibCnt+tt.args.createStaticCnt, len(addedCredSources)) + assert.Equal(tt.args.createLibCnt+tt.args.createStaticCnt, len(addedTarget.GetCredentialSources())) var deleteIds target.CredentialSources for i := 0; i < tt.args.deleteLibCnt; i++ { @@ -531,8 +537,9 @@ func TestRepository_DeleteTargetCredentialSources(t *testing.T) { ids := target.CredentialSources{ BrokeredCredentialIds: []string{lib1.GetPublicId(), lib2.GetPublicId()}, } - _, _, gotCredSources, err := repo.AddTargetCredentialSources(ctx, projTarget.GetPublicId(), 1, ids) + gotTarget, err := repo.AddTargetCredentialSources(ctx, projTarget.GetPublicId(), 1, ids) require.NoError(err) + gotCredSources := gotTarget.GetCredentialSources() assert.Len(gotCredSources, 2) // Deleting an unassociated source should return an error @@ -554,8 +561,9 @@ func TestRepository_DeleteTargetCredentialSources(t *testing.T) { assert.Equal(0, delCount) // Previous transactions should have been rolled back and only lib1 should be associated - _, _, lookupCredSources, err := repo.LookupTarget(ctx, projTarget.GetPublicId()) + lookupTarget, err := repo.LookupTarget(ctx, projTarget.GetPublicId()) require.NoError(err) + lookupCredSources := lookupTarget.GetCredentialSources() assert.Len(lookupCredSources, 2) }) } @@ -593,8 +601,9 @@ func TestRepository_SetTargetCredentialSources(t *testing.T) { ids.BrokeredCredentialIds = append(ids.BrokeredCredentialIds, cred.GetPublicId()) } - _, _, created, err := repo.AddTargetCredentialSources(context.Background(), tar.GetPublicId(), 1, ids) + addedTarget, err := repo.AddTargetCredentialSources(context.Background(), tar.GetPublicId(), 1, ids) require.NoError(t, err) + created := addedTarget.GetCredentialSources() require.Equal(t, 10, len(created)) return created, ids } @@ -769,8 +778,9 @@ func TestRepository_SetTargetCredentialSources(t *testing.T) { } } - origTarget, _, lookupCredSources, err := repo.LookupTarget(ctx, tar.GetPublicId()) + origTarget, err := repo.LookupTarget(ctx, tar.GetPublicId()) require.NoError(err) + lookupCredSources := origTarget.GetCredentialSources() assert.Equal(origCredSources, lookupCredSources) _, gotSources, affectedRows, err := repo.SetTargetCredentialSources(ctx, tar.GetPublicId(), tt.args.targetVersion, tt.args.ids) @@ -791,7 +801,7 @@ func TestRepository_SetTargetCredentialSources(t *testing.T) { assert.Equal(w.CredentialPurpose(), cs.CredentialPurpose()) } - foundTarget, _, _, err := repo.LookupTarget(ctx, tar.GetPublicId()) + foundTarget, err := repo.LookupTarget(ctx, tar.GetPublicId()) require.NoError(err) if tt.name != "no-change" { assert.Equalf(tt.args.targetVersion+1, foundTarget.GetVersion(), "%s unexpected version: %d/%d", tt.name, tt.args.targetVersion+1, foundTarget.GetVersion()) diff --git a/internal/target/tcp/repository_host_source_test.go b/internal/target/tcp/repository_host_source_test.go index 5bff43ef5..85050fb75 100644 --- a/internal/target/tcp/repository_host_source_test.go +++ b/internal/target/tcp/repository_host_source_test.go @@ -120,9 +120,9 @@ func TestRepository_AddTargetHostSets(t *testing.T) { } var hostSourceIds []string - origTarget, origHostSet, _, err := repo.LookupTarget(ctx, projTarget.GetPublicId()) + origTarget, err := repo.LookupTarget(ctx, projTarget.GetPublicId()) require.NoError(err) - require.Equal(0, len(origHostSet)) + require.Equal(0, len(origTarget.GetHostSources())) if address != nil { require.Equal(address.GetAddress(), origTarget.GetAddress()) @@ -132,7 +132,7 @@ func TestRepository_AddTargetHostSets(t *testing.T) { hostSourceIds = createHostSetsFn([]string{staticProj.PublicId}) } - gotTarget, gotHostSources, _, err := repo.AddTargetHostSources(ctx, projTarget.GetPublicId(), tt.args.targetVersion, hostSourceIds, tt.args.opt...) + gotTarget, err := repo.AddTargetHostSources(ctx, projTarget.GetPublicId(), tt.args.targetVersion, hostSourceIds, tt.args.opt...) if tt.wantErr { require.Error(err) if tt.wantErrIs != nil { @@ -156,6 +156,8 @@ func TestRepository_AddTargetHostSets(t *testing.T) { return } require.NoError(err) + + gotHostSources := gotTarget.GetHostSources() gotHostSet := map[string]target.HostSource{} for _, s := range gotHostSources { gotHostSet[s.Id()] = s @@ -173,8 +175,9 @@ func TestRepository_AddTargetHostSets(t *testing.T) { err = db.TestVerifyOplog(t, rw, projTarget.GetPublicId(), db.WithOperation(oplog.OpType_OP_TYPE_UPDATE), db.WithCreateNotBefore(10*time.Second)) assert.NoError(err) - tar, ths, _, err := repo.LookupTarget(ctx, projTarget.GetPublicId()) + tar, err := repo.LookupTarget(ctx, projTarget.GetPublicId()) require.NoError(err) + ths := tar.GetHostSources() assert.Equal(tt.args.targetVersion+1, tar.GetVersion()) assert.Equal(origTarget.GetVersion(), tar.GetVersion()-1) assert.Equal(gotHostSources, ths) @@ -195,24 +198,26 @@ func TestRepository_AddTargetHostSets(t *testing.T) { ctx := context.Background() projTarget := tcp.TestTarget(ctx, t, conn, staticProj.PublicId, "add-existing") - _, gotHostSources, _, err := repo.AddTargetHostSources(ctx, projTarget.GetPublicId(), 1, []string{hs1.PublicId}) + gotTarget, err := repo.AddTargetHostSources(ctx, projTarget.GetPublicId(), 1, []string{hs1.PublicId}) require.NoError(err) + gotHostSources := gotTarget.GetHostSources() assert.Len(gotHostSources, 1) assert.Equal(hs1.PublicId, gotHostSources[0].Id()) // Adding hs1 again should error - _, _, _, err = repo.AddTargetHostSources(ctx, projTarget.GetPublicId(), 2, []string{hs1.PublicId}) + _, err = repo.AddTargetHostSources(ctx, projTarget.GetPublicId(), 2, []string{hs1.PublicId}) require.Error(err) assert.True(errors.Match(errors.T(errors.NotUnique), err)) // Adding multiple with hs1 in set should error - _, _, _, err = repo.AddTargetHostSources(ctx, projTarget.GetPublicId(), 2, []string{hs3.PublicId, hs2.PublicId, hs1.PublicId}) + _, err = repo.AddTargetHostSources(ctx, projTarget.GetPublicId(), 2, []string{hs3.PublicId, hs2.PublicId, hs1.PublicId}) require.Error(err) assert.True(errors.Match(errors.T(errors.NotUnique), err)) // Previous transactions should have been rolled back and only hs1 should be associated - _, gotHostSources, _, err = repo.LookupTarget(ctx, projTarget.GetPublicId()) + gotTarget, err = repo.LookupTarget(ctx, projTarget.GetPublicId()) require.NoError(err) + gotHostSources = gotTarget.GetHostSources() assert.Len(gotHostSources, 1) assert.Equal(hs1.PublicId, gotHostSources[0].Id()) }) @@ -334,9 +339,9 @@ func TestRepository_DeleteTargetHosts(t *testing.T) { hsIds = append(hsIds, hsets[0].PublicId) } } - _, addedHostSources, _, err := repo.AddTargetHostSources(context.Background(), tt.args.target.GetPublicId(), 1, hsIds, tt.args.opt...) + addedTarget, err := repo.AddTargetHostSources(context.Background(), tt.args.target.GetPublicId(), 1, hsIds, tt.args.opt...) require.NoError(err) - assert.Equal(tt.args.createCnt, len(addedHostSources)) + assert.Equal(tt.args.createCnt, len(addedTarget.GetHostSources())) deleteHostSources := make([]string, 0, tt.args.deleteCnt) for i := 0; i < tt.args.deleteCnt; i++ { @@ -401,8 +406,9 @@ func TestRepository_DeleteTargetHosts(t *testing.T) { ctx := context.Background() projTarget := tcp.TestTarget(ctx, t, conn, proj.PublicId, "delete-unassociated") - _, gotHostSources, _, err := repo.AddTargetHostSources(ctx, projTarget.GetPublicId(), 1, []string{hs1.PublicId, hs2.PublicId}) + gotTarget, err := repo.AddTargetHostSources(ctx, projTarget.GetPublicId(), 1, []string{hs1.PublicId, hs2.PublicId}) require.NoError(err) + gotHostSources := gotTarget.GetHostSources() assert.Len(gotHostSources, 2) assert.Equal(hs1.PublicId, gotHostSources[0].Id()) @@ -419,8 +425,9 @@ func TestRepository_DeleteTargetHosts(t *testing.T) { assert.Equal(0, delCount) // Previous transactions should have been rolled back - _, gotHostSources, _, err = repo.LookupTarget(ctx, projTarget.GetPublicId()) + gotTarget, err = repo.LookupTarget(ctx, projTarget.GetPublicId()) require.NoError(err) + gotHostSources = gotTarget.GetHostSources() assert.Len(gotHostSources, 2) }) } @@ -458,8 +465,9 @@ func TestRepository_SetTargetHostSets(t *testing.T) { setupFn := func(target target.Target) []target.HostSource { hs := createHostSetsFn() - _, created, _, err := repo.AddTargetHostSources(context.Background(), target.GetPublicId(), 1, hs) + addedTarget, err := repo.AddTargetHostSources(context.Background(), target.GetPublicId(), 1, hs) require.NoError(t, err) + created := addedTarget.GetHostSources() require.Equal(t, 10, len(created)) return created } @@ -562,9 +570,9 @@ func TestRepository_SetTargetHostSets(t *testing.T) { } tt.args.hostSourceIds = append(tt.args.hostSourceIds, origIds...) } - origTarget, lookedUpHs, _, err := repo.LookupTarget(context.Background(), tt.args.target.GetPublicId()) + origTarget, err := repo.LookupTarget(context.Background(), tt.args.target.GetPublicId()) require.NoError(err) - assert.Equal(len(origHostSources), len(lookedUpHs)) + assert.Equal(len(origHostSources), len(origTarget.GetHostSources())) got, _, affectedRows, err := repo.SetTargetHostSources(context.Background(), tt.args.target.GetPublicId(), tt.args.targetVersion, tt.args.hostSourceIds, tt.args.opt...) if tt.wantErr { @@ -591,7 +599,7 @@ func TestRepository_SetTargetHostSets(t *testing.T) { sort.Strings(gotIds) assert.Equal(wantIds, gotIds) - foundTarget, _, _, err := repo.LookupTarget(context.Background(), tt.args.target.GetPublicId()) + foundTarget, err := repo.LookupTarget(context.Background(), tt.args.target.GetPublicId()) require.NoError(err) if tt.name != "no-change" { assert.Equalf(tt.args.targetVersion+1, foundTarget.GetVersion(), "%s unexpected version: %d/%d", tt.name, tt.args.targetVersion+1, foundTarget.GetVersion()) diff --git a/internal/target/tcp/repository_tcp_target_test.go b/internal/target/tcp/repository_tcp_target_test.go index ec64580fa..0deb8c53a 100644 --- a/internal/target/tcp/repository_tcp_target_test.go +++ b/internal/target/tcp/repository_tcp_target_test.go @@ -211,7 +211,7 @@ func TestRepository_CreateTarget(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert, require := assert.New(t), require.New(t) - tar, hostSources, credSources, err := repo.CreateTarget(context.Background(), tt.args.target, tt.args.opt...) + tar, err := repo.CreateTarget(context.Background(), tt.args.target, tt.args.opt...) if tt.wantErr { assert.Error(err) assert.Nil(tar) @@ -221,7 +221,13 @@ func TestRepository_CreateTarget(t *testing.T) { require.NoError(err) assert.NotNil(tar.GetPublicId()) - foundTarget, foundHostSources, foundCredLibs, err := repo.LookupTarget(context.Background(), tar.GetPublicId()) + hostSources := tar.GetHostSources() + credSources := tar.GetCredentialSources() + + foundTarget, err := repo.LookupTarget(context.Background(), tar.GetPublicId()) + foundHostSources := foundTarget.GetHostSources() + foundCredLibs := foundTarget.GetCredentialSources() + assert.NoError(err) if len(tt.wantAddress) != 0 { assert.Equal(tt.wantAddress, tar.GetAddress()) @@ -577,7 +583,7 @@ func TestRepository_UpdateTcpTarget(t *testing.T) { ut.PublicId = *tt.args.PublicId } - targetAfterUpdate, hostSources, credSources, updatedRows, err := repo.UpdateTarget(ctx, updateTarget, tar.GetVersion(), tt.args.fieldMaskPaths, tt.args.opt...) + targetAfterUpdate, updatedRows, err := repo.UpdateTarget(ctx, updateTarget, tar.GetVersion(), tt.args.fieldMaskPaths, tt.args.opt...) if tt.wantErr { assert.Error(err) assert.True(errors.Match(errors.T(tt.wantIsError), err)) @@ -593,6 +599,9 @@ func TestRepository_UpdateTcpTarget(t *testing.T) { require.NoError(err) require.NotNil(targetAfterUpdate) assert.Equal(tt.wantRowsUpdate, updatedRows) + + hostSources := targetAfterUpdate.GetHostSources() + credSources := targetAfterUpdate.GetCredentialSources() afterUpdateIds := make([]string, 0, len(hostSources)) for _, hs := range hostSources { afterUpdateIds = append(afterUpdateIds, hs.Id()) @@ -616,7 +625,7 @@ func TestRepository_UpdateTcpTarget(t *testing.T) { default: assert.NotEqual(tar.GetUpdateTime(), targetAfterUpdate.GetUpdateTime()) } - foundTarget, _, _, err := repo.LookupTarget(context.Background(), tar.GetPublicId()) + foundTarget, err := repo.LookupTarget(context.Background(), tar.GetPublicId()) assert.NoError(err) assert.True(proto.Equal(targetAfterUpdate.((*tcp.Target)), foundTarget.((*tcp.Target)))) assert.Equal(targetAfterUpdate.GetAddress(), foundTarget.GetAddress()) diff --git a/internal/target/tcp/repository_test.go b/internal/target/tcp/repository_test.go index cd2557382..aa21ce157 100644 --- a/internal/target/tcp/repository_test.go +++ b/internal/target/tcp/repository_test.go @@ -130,7 +130,7 @@ func TestRepository_LookupTarget(t *testing.T) { if tt.projectName != "" { opts = append(opts, target.WithProjectName(tt.projectName)) } - got, _, _, err := repo.LookupTarget(ctx, id, opts...) + got, err := repo.LookupTarget(ctx, id, opts...) if tt.wantErr { require.Error(err) return @@ -262,7 +262,7 @@ func TestRepository_DeleteTarget(t *testing.T) { } assert.NoError(err) assert.Equal(tt.wantRowsDeleted, deletedRows) - foundGroup, _, _, err := repo.LookupTarget(ctx, tt.args.target.GetPublicId()) + foundGroup, err := repo.LookupTarget(ctx, tt.args.target.GetPublicId()) assert.NoError(err) assert.Nil(foundGroup) diff --git a/internal/target/tcp/target.go b/internal/target/tcp/target.go index 6b62d762a..032eae2f2 100644 --- a/internal/target/tcp/target.go +++ b/internal/target/tcp/target.go @@ -31,8 +31,10 @@ const ( type Target struct { *store.Target // Network address assigned to the Target. - Address string `json:"address,omitempty" gorm:"-"` - tableName string `gorm:"-"` + Address string `json:"address,omitempty" gorm:"-"` + tableName string `gorm:"-"` + HostSource []target.HostSource `gorm:"-"` + CredentialSources []target.CredentialSource `gorm:"-"` } // Ensure Target implements interfaces @@ -78,8 +80,10 @@ func (h targetHooks) AllocTarget() target.Target { func (t *Target) Clone() target.Target { cp := proto.Clone(t.Target) return &Target{ - Target: cp.(*store.Target), - Address: t.Address, + Target: cp.(*store.Target), + Address: t.Address, + HostSource: t.HostSource, + CredentialSources: t.CredentialSources, } } @@ -135,6 +139,14 @@ func (t *Target) GetAddress() string { return t.Address } +func (t *Target) GetHostSources() []target.HostSource { + return t.HostSource +} + +func (t *Target) GetCredentialSources() []target.CredentialSource { + return t.CredentialSources +} + func (t *Target) SetPublicId(ctx context.Context, publicId string) error { const op = "tcp.(Target).SetPublicId" if !strings.HasPrefix(publicId, TargetPrefix+"_") { @@ -196,3 +208,11 @@ func (t *Target) SetIngressWorkerFilter(filter string) { func (t *Target) SetAddress(address string) { t.Address = address } + +func (t *Target) SetHostSources(sources []target.HostSource) { + t.HostSource = sources +} + +func (t *Target) SetCredentialSources(sources []target.CredentialSource) { + t.CredentialSources = sources +} diff --git a/internal/target/tcp/testing_test.go b/internal/target/tcp/testing_test.go index 0c4b89451..fb8a93fa7 100644 --- a/internal/target/tcp/testing_test.go +++ b/internal/target/tcp/testing_test.go @@ -43,7 +43,9 @@ func Test_TestTcpTarget(t *testing.T) { require.NotEmpty(tar.GetPublicId()) require.Equal(name, tar.GetName()) - _, foundSources, _, err := repo.LookupTarget(context.Background(), tar.GetPublicId()) + foundTarget, err := repo.LookupTarget(context.Background(), tar.GetPublicId()) + foundSources := foundTarget.GetHostSources() + require.NoError(err) foundIds := make([]string, 0, len(foundSources)) for _, s := range foundSources { @@ -79,7 +81,9 @@ func Test_TestCredentialLibrary(t *testing.T) { assert.Len(libs, 2) - _, _, foundSources, err := repo.LookupTarget(context.Background(), tar.GetPublicId()) + foundTarget, err := repo.LookupTarget(context.Background(), tar.GetPublicId()) + foundSources := foundTarget.GetCredentialSources() + require.NoError(err) foundIds := make([]string, 0, len(foundSources)) for _, s := range foundSources {