Remove deprecated methods/fields on targets (#2393)

This commit is contained in:
Jeff Mitchell authored and GitHub committed 2022-09-15 09:20:08 -04:00
1 parent 54cdaaada8
commit 53b5e532d5
32 files changed
+1125 -3546

No files matched your search

@@ -160,9 +160,6 @@ func TestHandleImplementedPaths(t *testing.T) {
"v1/roles/someid:remove-principals",
"v1/sessions/someid:cancel",
"v1/targets/someid:authorize-session",
"v1/targets/someid:add-host-sets",
"v1/targets/someid:set-host-sets",
"v1/targets/someid:remove-host-sets",
"v1/targets/someid:add-host-sources",
"v1/targets/someid:set-host-sources",
"v1/targets/someid:remove-host-sources",
@@ -1053,10 +1053,17 @@ func validateAddRoleGrantsRequest(req *pbs.AddRoleGrantsRequest) error {
badFields["grant_strings"] = "Grant strings must not be empty."
break
}
if _, err := perms.Parse("p_anything", v); err != nil {
grant, err := perms.Parse("p_anything", v)
if err != nil {
badFields["grant_strings"] = fmt.Sprintf("Improperly formatted grant %q.", v)
break
}
_, actStrs := grant.Actions()
for _, actStr := range actStrs {
if depAct := action.DeprecatedMap[actStr]; depAct != action.Unknown {
badFields["grant_strings"] = fmt.Sprintf("Action %q has been deprecated and is not allowed to be set in grants. Use %q instead.", actStr, depAct.String())
}
}
}
if len(badFields) > 0 {
return handlers.InvalidArgumentErrorf("Errors in provided fields.", badFields)
@@ -1077,10 +1084,17 @@ func validateSetRoleGrantsRequest(req *pbs.SetRoleGrantsRequest) error {
badFields["grant_strings"] = "Grant strings must not be empty."
break
}
if _, err := perms.Parse("p_anything", v); err != nil {
grant, err := perms.Parse("p_anything", v)
if err != nil {
badFields["grant_strings"] = fmt.Sprintf("Improperly formatted grant %q.", v)
break
}
_, actStrs := grant.Actions()
for _, actStr := range actStrs {
if depAct := action.DeprecatedMap[actStr]; depAct != action.Unknown {
badFields["grant_strings"] = fmt.Sprintf("Action %q has been deprecated and is not allowed to be set in grants. Use %q instead.", actStr, depAct.String())
}
}
}
if len(badFields) > 0 {
return handlers.InvalidArgumentErrorf("Errors in provided fields.", badFields)
@@ -1108,6 +1122,7 @@ func validateRemoveRoleGrantsRequest(req *pbs.RemoveRoleGrantsRequest) error {
badFields["grant_strings"] = fmt.Sprintf("Improperly formatted grant %q.", v)
break
}
// NOTE: we don't do a deprecation check here because it's fine to allow people to remove deprecated grants.
}
if len(badFields) > 0 {
return handlers.InvalidArgumentErrorf("Errors in provided fields.", badFields)
@@ -1653,11 +1653,12 @@ func TestAddGrants(t *testing.T) {
require.NoError(t, err, "Error when getting new role service.")
addCases := []struct {
name string
existing []string
add []string
result []string
wantErr bool
name string
existing []string
add []string
result []string
wantErr bool
wantErrContains string
}{
{
name: "Add grant on empty role",
@@ -1682,6 +1683,13 @@ func TestAddGrants(t *testing.T) {
add: []string{"id=*;type=*;actions=delete"},
wantErr: true,
},
{
name: "Check deprecation",
existing: []string{"id=1;actions=read", "id=*;type=*;actions=delete"},
add: []string{"id=*;type=target;actions=add-host-sets"},
wantErr: true,
wantErrContains: "Use \\\"add-host-sources\\\" instead",
},
}
for _, tc := range addCases {
@@ -1705,6 +1713,9 @@ func TestAddGrants(t *testing.T) {
got, err := s.AddRoleGrants(auth.DisabledAuthTestContext(repoFn, scopeId), req)
if tc.wantErr {
assert.Error(err)
if tc.wantErrContains != "" {
assert.Contains(err.Error(), tc.wantErrContains)
}
return
}
require.NoError(err)
@@ -1781,11 +1792,12 @@ func TestSetGrants(t *testing.T) {
require.NoError(t, err, "Error when getting new role service.")
setCases := []struct {
name string
existing []string
set []string
result []string
wantErr bool
name string
existing []string
set []string
result []string
wantErr bool
wantErrContains string
}{
{
name: "Set grant on empty role",
@@ -1816,6 +1828,13 @@ func TestSetGrants(t *testing.T) {
set: nil,
result: nil,
},
{
name: "Check deprecation",
existing: []string{"id=1;actions=read", "id=*;type=*;actions=delete"},
set: []string{"id=*;type=target;actions=add-host-sets"},
wantErr: true,
wantErrContains: "Use \\\"add-host-sources\\\" instead",
},
}
for _, tc := range setCases {
@@ -1839,6 +1858,9 @@ func TestSetGrants(t *testing.T) {
got, err := s.SetRoleGrants(auth.DisabledAuthTestContext(repoFn, scopeId), req)
if tc.wantErr {
assert.Error(err)
if tc.wantErrContains != "" {
assert.Contains(err.Error(), tc.wantErrContains)
}
return
}
require.NoError(err, "Got error %v", err)
@@ -74,9 +74,6 @@ var (
action.Read,
action.Update,
action.Delete,
action.AddHostSets,
action.SetHostSets,
action.RemoveHostSets,
action.AddHostSources,
action.SetHostSources,
action.RemoveHostSources,
@@ -376,120 +373,6 @@ func (s Service) DeleteTarget(ctx context.Context, req *pbs.DeleteTargetRequest)
return nil, nil
}
// AddTargetHostSets implements the interface pbs.TargetServiceServer.
func (s Service) AddTargetHostSets(ctx context.Context, req *pbs.AddTargetHostSetsRequest) (*pbs.AddTargetHostSetsResponse, error) {
const op = "targets.(Service).AddTargetHostSets"
if err := validateAddSetsRequest(req); err != nil {
return nil, err
}
authResults := s.authResult(ctx, req.GetId(), action.AddHostSets)
if authResults.Error != nil {
return nil, authResults.Error
}
t, ts, cl, err := s.addHostSourcesInRepo(ctx, req.GetId(), req.GetHostSetIds(), req.GetVersion())
if err != nil {
return nil, err
}
outputFields, ok := requests.OutputFields(ctx)
if !ok {
return nil, errors.New(ctx, errors.Internal, op, "no request context found")
}
outputOpts := make([]handlers.Option, 0, 3)
outputOpts = append(outputOpts, handlers.WithOutputFields(&outputFields))
if outputFields.Has(globals.ScopeField) {
outputOpts = append(outputOpts, handlers.WithScope(authResults.Scope))
}
if outputFields.Has(globals.AuthorizedActionsField) {
outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, t.GetPublicId(), IdActions).Strings()))
}
item, err := toProto(ctx, t, ts, cl, outputOpts...)
if err != nil {
return nil, err
}
return &pbs.AddTargetHostSetsResponse{Item: item}, nil
}
// SetTargetHostSets implements the interface pbs.TargetServiceServer.
func (s Service) SetTargetHostSets(ctx context.Context, req *pbs.SetTargetHostSetsRequest) (*pbs.SetTargetHostSetsResponse, error) {
const op = "targets.(Service).SetTargetHostSets"
if err := validateSetSetsRequest(req); err != nil {
return nil, err
}
authResults := s.authResult(ctx, req.GetId(), action.SetHostSets)
if authResults.Error != nil {
return nil, authResults.Error
}
t, ts, cl, err := s.setHostSourcesInRepo(ctx, req.GetId(), req.GetHostSetIds(), req.GetVersion())
if err != nil {
return nil, err
}
outputFields, ok := requests.OutputFields(ctx)
if !ok {
return nil, errors.New(ctx, errors.Internal, op, "no request context found")
}
outputOpts := make([]handlers.Option, 0, 3)
outputOpts = append(outputOpts, handlers.WithOutputFields(&outputFields))
if outputFields.Has(globals.ScopeField) {
outputOpts = append(outputOpts, handlers.WithScope(authResults.Scope))
}
if outputFields.Has(globals.AuthorizedActionsField) {
outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, t.GetPublicId(), IdActions).Strings()))
}
item, err := toProto(ctx, t, ts, cl, outputOpts...)
if err != nil {
return nil, err
}
return &pbs.SetTargetHostSetsResponse{Item: item}, nil
}
// RemoveTargetHostSets implements the interface pbs.TargetServiceServer.
func (s Service) RemoveTargetHostSets(ctx context.Context, req *pbs.RemoveTargetHostSetsRequest) (*pbs.RemoveTargetHostSetsResponse, error) {
const op = "targets.(Service).RemoveTargetHostSets"
if err := validateRemoveSetsRequest(req); err != nil {
return nil, err
}
authResults := s.authResult(ctx, req.GetId(), action.RemoveHostSets)
if authResults.Error != nil {
return nil, authResults.Error
}
t, ts, cl, err := s.removeHostSourcesInRepo(ctx, req.GetId(), req.GetHostSetIds(), req.GetVersion())
if err != nil {
return nil, err
}
outputFields, ok := requests.OutputFields(ctx)
if !ok {
return nil, errors.New(ctx, errors.Internal, op, "no request context found")
}
outputOpts := make([]handlers.Option, 0, 3)
outputOpts = append(outputOpts, handlers.WithOutputFields(&outputFields))
if outputFields.Has(globals.ScopeField) {
outputOpts = append(outputOpts, handlers.WithScope(authResults.Scope))
}
if outputFields.Has(globals.AuthorizedActionsField) {
outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, t.GetPublicId(), IdActions).Strings()))
}
item, err := toProto(ctx, t, ts, cl, outputOpts...)
if err != nil {
return nil, err
}
return &pbs.RemoveTargetHostSetsResponse{Item: item}, nil
}
// AddTargetHostSources implements the interface pbs.TargetServiceServer.
func (s Service) AddTargetHostSources(ctx context.Context, req *pbs.AddTargetHostSourcesRequest) (*pbs.AddTargetHostSourcesResponse, error) {
const op = "targets.(Service).AddTargetHostSources"
@@ -613,12 +496,7 @@ func (s Service) AddTargetCredentialSources(ctx context.Context, req *pbs.AddTar
}
authResults := s.authResult(ctx, req.GetId(), action.AddCredentialSources)
if authResults.Error != nil {
// TODO AddCredentialLibraries was deprecated but grant actions were never migrated
// remove this check once actions have been migrated
authResults = s.authResult(ctx, req.GetId(), action.AddCredentialLibraries)
if authResults.Error != nil {
return nil, authResults.Error
}
return nil, authResults.Error
}
brokeredCredentialSources := strutil.MergeSlices(req.GetApplicationCredentialSourceIds(), req.GetBrokeredCredentialSourceIds())
@@ -658,12 +536,7 @@ func (s Service) SetTargetCredentialSources(ctx context.Context, req *pbs.SetTar
}
authResults := s.authResult(ctx, req.GetId(), action.SetCredentialSources)
if authResults.Error != nil {
// TODO SetCredentialLibraries was deprecated but grant actions were never migrated
// remove this check once actions have been migrated
authResults = s.authResult(ctx, req.GetId(), action.SetCredentialLibraries)
if authResults.Error != nil {
return nil, authResults.Error
}
return nil, authResults.Error
}
brokeredCredentialSources := strutil.MergeSlices(req.GetApplicationCredentialSourceIds(), req.GetBrokeredCredentialSourceIds())
@@ -703,12 +576,7 @@ func (s Service) RemoveTargetCredentialSources(ctx context.Context, req *pbs.Rem
}
authResults := s.authResult(ctx, req.GetId(), action.RemoveCredentialSources)
if authResults.Error != nil {
// TODO RemoveCredentialLibraries was deprecated but grant actions were never migrated
// remove this check once actions have been migrated
authResults = s.authResult(ctx, req.GetId(), action.RemoveCredentialLibraries)
if authResults.Error != nil {
return nil, authResults.Error
}
return nil, authResults.Error
}
brokeredCredentialSources := strutil.MergeSlices(req.GetApplicationCredentialSourceIds(), req.GetBrokeredCredentialSourceIds())
@@ -1483,24 +1351,11 @@ func toProto(ctx context.Context, in target.Target, hostSources []target.HostSou
if outputFields.Has(globals.AuthorizedActionsField) {
out.AuthorizedActions = opts.WithAuthorizedActions
}
if outputFields.Has(globals.HostSetIdsField) {
for _, hs := range hostSources {
out.HostSetIds = append(out.HostSetIds, hs.Id())
}
}
if outputFields.Has(globals.HostSourceIdsField) {
for _, hs := range hostSources {
out.HostSourceIds = append(out.HostSourceIds, hs.Id())
}
}
if outputFields.Has(globals.HostSetsField) {
for _, hs := range hostSources {
out.HostSets = append(out.HostSets, &pb.HostSet{
Id: hs.Id(),
HostCatalogId: hs.HostCatalogId(),
})
}
}
if outputFields.Has(globals.HostSourcesField) {
for _, hs := range hostSources {
out.HostSources = append(out.HostSources, &pb.HostSource{
@@ -1685,72 +1540,6 @@ func validateListRequest(req *pbs.ListTargetsRequest) error {
return nil
}
func validateAddSetsRequest(req *pbs.AddTargetHostSetsRequest) error {
badFields := map[string]string{}
if !handlers.ValidId(handlers.Id(req.GetId()), target.Prefixes()...) {
badFields[globals.IdField] = "Incorrectly formatted identifier."
}
if req.GetVersion() == 0 {
badFields[globals.VersionField] = "Required field."
}
if len(req.GetHostSetIds()) == 0 {
badFields[globals.HostSetIdsField] = "Must be non-empty."
}
for _, id := range req.GetHostSetIds() {
if !handlers.ValidId(handlers.Id(id), static.HostSetPrefix, plugin.HostSetPrefix, plugin.PreviousHostSetPrefix) {
badFields[globals.HostSetIdsField] = fmt.Sprintf("Incorrectly formatted host set identifier %q.", id)
break
}
}
if len(badFields) > 0 {
return handlers.InvalidArgumentErrorf("Errors in provided fields.", badFields)
}
return nil
}
func validateSetSetsRequest(req *pbs.SetTargetHostSetsRequest) error {
badFields := map[string]string{}
if !handlers.ValidId(handlers.Id(req.GetId()), target.Prefixes()...) {
badFields[globals.IdField] = "Incorrectly formatted identifier."
}
if req.GetVersion() == 0 {
badFields[globals.VersionField] = "Required field."
}
for _, id := range req.GetHostSetIds() {
if !handlers.ValidId(handlers.Id(id), static.HostSetPrefix, plugin.HostSetPrefix, plugin.PreviousHostSetPrefix) {
badFields[globals.HostSetIdsField] = fmt.Sprintf("Incorrectly formatted host set identifier %q.", id)
break
}
}
if len(badFields) > 0 {
return handlers.InvalidArgumentErrorf("Errors in provided fields.", badFields)
}
return nil
}
func validateRemoveSetsRequest(req *pbs.RemoveTargetHostSetsRequest) error {
badFields := map[string]string{}
if !handlers.ValidId(handlers.Id(req.GetId()), target.Prefixes()...) {
badFields[globals.IdField] = "Incorrectly formatted identifier."
}
if req.GetVersion() == 0 {
badFields[globals.VersionField] = "Required field."
}
if len(req.GetHostSetIds()) == 0 {
badFields[globals.HostSetIdsField] = "Must be non-empty."
}
for _, id := range req.GetHostSetIds() {
if !handlers.ValidId(handlers.Id(id), static.HostSetPrefix, plugin.HostSetPrefix, plugin.PreviousHostSetPrefix) {
badFields[globals.HostSetIdsField] = fmt.Sprintf("Incorrectly formatted host set identifier %q.", id)
break
}
}
if len(badFields) > 0 {
return handlers.InvalidArgumentErrorf("Errors in provided fields.", badFields)
}
return nil
}
func validateAddHostSourcesRequest(req *pbs.AddTargetHostSourcesRequest) error {
badFields := map[string]string{}
if !handlers.ValidId(handlers.Id(req.GetId()), target.Prefixes()...) {
@@ -61,9 +61,6 @@ var testAuthorizedActions = []string{
"read",
"update",
"delete",
"add-host-sets",
"set-host-sets",
"remove-host-sets",
"add-host-sources",
"set-host-sources",
"remove-host-sources",
@@ -142,7 +139,6 @@ func TestGet(t *testing.T) {
UpdatedTime: tar.GetUpdateTime().GetTimestamp(),
Scope: &scopes.ScopeInfo{Id: proj.GetPublicId(), Type: scope.Project.String(), ParentScopeId: o.GetPublicId()},
Type: tcp.Subtype.String(),
HostSetIds: []string{hs[0].GetPublicId(), hs[1].GetPublicId()},
HostSourceIds: []string{hs[0].GetPublicId(), hs[1].GetPublicId()},
Attrs: &pb.Target_TcpTargetAttributes{},
SessionMaxSeconds: wrapperspb.UInt32(28800),
@@ -150,7 +146,6 @@ func TestGet(t *testing.T) {
AuthorizedActions: testAuthorizedActions,
}
for _, ihs := range hs {
pTar.HostSets = append(pTar.HostSets, &pb.HostSet{Id: ihs.GetPublicId(), HostCatalogId: ihs.GetCatalogId()})
pTar.HostSources = append(pTar.HostSources, &pb.HostSource{Id: ihs.GetPublicId(), HostCatalogId: ihs.GetCatalogId()})
}
@@ -719,11 +714,6 @@ func TestUpdate(t *testing.T) {
hc := static.TestCatalogs(t, conn, proj.GetPublicId(), 1)[0]
hs := static.TestSets(t, conn, hc.GetPublicId(), 2)
hsIds := []string{hs[0].GetPublicId(), hs[1].GetPublicId()}
hostSets := []*pb.HostSet{
{Id: hs[0].GetPublicId(), HostCatalogId: hs[0].GetCatalogId()},
{Id: hs[1].GetPublicId(), HostCatalogId: hs[1].GetCatalogId()},
}
hostSourceIds := []string{hs[0].GetPublicId(), hs[1].GetPublicId()}
hostSources := []*pb.HostSource{
{Id: hs[0].GetPublicId(), HostCatalogId: hs[0].GetCatalogId()},
@@ -793,8 +783,6 @@ func TestUpdate(t *testing.T) {
},
},
CreatedTime: tar.GetCreateTime().GetTimestamp(),
HostSetIds: hsIds,
HostSets: hostSets,
HostSourceIds: hostSourceIds,
HostSources: hostSources,
SessionMaxSeconds: wrapperspb.UInt32(3600),
@@ -829,8 +817,6 @@ func TestUpdate(t *testing.T) {
DefaultPort: wrapperspb.UInt32(2),
},
},
HostSetIds: hsIds,
HostSets: hostSets,
HostSourceIds: hostSourceIds,
HostSources: hostSources,
SessionMaxSeconds: wrapperspb.UInt32(tar.GetSessionMaxSeconds()),
@@ -928,8 +914,6 @@ func TestUpdate(t *testing.T) {
DefaultPort: wrapperspb.UInt32(2),
},
},
HostSetIds: hsIds,
HostSets: hostSets,
HostSourceIds: hostSourceIds,
HostSources: hostSources,
SessionMaxSeconds: wrapperspb.UInt32(tar.GetSessionMaxSeconds()),
@@ -963,8 +947,6 @@ func TestUpdate(t *testing.T) {
DefaultPort: wrapperspb.UInt32(2),
},
},
HostSetIds: hsIds,
HostSets: hostSets,
HostSourceIds: hostSourceIds,
HostSources: hostSources,
SessionMaxSeconds: wrapperspb.UInt32(tar.GetSessionMaxSeconds()),
@@ -998,8 +980,6 @@ func TestUpdate(t *testing.T) {
},
},
Type: tcp.Subtype.String(),
HostSetIds: hsIds,
HostSets: hostSets,
HostSourceIds: hostSourceIds,
HostSources: hostSources,
SessionMaxSeconds: wrapperspb.UInt32(tar.GetSessionMaxSeconds()),
@@ -1171,492 +1151,6 @@ func TestUpdate_BadVersion(t *testing.T) {
assert.True(t, errors.Is(err, handlers.NotFoundError()), "Got %v, wanted not found error.", err)
}
func TestAddTargetHostSets(t *testing.T) {
conn, _ := db.TestSetup(t, "postgres")
wrapper := db.TestWrapper(t)
kms := kms.TestKms(t, conn, wrapper)
sche := scheduler.TestScheduler(t, conn, wrapper)
rw := db.New(conn)
iamRepo := iam.TestRepo(t, conn, wrapper)
iamRepoFn := func() (*iam.Repository, error) {
return iamRepo, nil
}
tokenRepoFn := func() (*authtoken.Repository, error) {
return authtoken.NewRepository(rw, rw, kms)
}
serversRepoFn := func() (*server.Repository, error) {
return server.NewRepository(rw, rw, kms)
}
org, proj := iam.TestScopes(t, iamRepo)
at := authtoken.TestAuthToken(t, conn, kms, org.GetPublicId())
r := iam.TestRole(t, conn, proj.GetPublicId())
_ = iam.TestUserRole(t, conn, r.GetPublicId(), at.GetIamUserId())
_ = iam.TestRoleGrant(t, conn, r.GetPublicId(), "id=*;type=*;actions=*")
s, err := testService(t, context.Background(), conn, kms, wrapper)
require.NoError(t, err, "Error when getting new target service.")
hc := static.TestCatalogs(t, conn, proj.GetPublicId(), 1)[0]
hs := static.TestSets(t, conn, hc.GetPublicId(), 2)
plg := host.TestPlugin(t, conn, "test")
pluginHc := plugin.TestCatalog(t, conn, proj.GetPublicId(), plg.GetPublicId())
pluginHs := plugin.TestSet(t, conn, kms, sche, pluginHc, map[string]plgpb.HostPluginServiceClient{
plg.GetPublicId(): plugin.NewWrappingPluginClient(&plugin.TestPluginServer{}),
})
ctx := context.Background()
addCases := []struct {
name string
tar target.Target
addHostSets []string
resultHostSets []string
}{
{
name: "Add set on empty target",
tar: tcp.TestTarget(ctx, t, conn, proj.GetPublicId(), "empty"),
addHostSets: []string{hs[1].GetPublicId()},
resultHostSets: []string{hs[1].GetPublicId()},
},
{
name: "Add set on populated target",
tar: tcp.TestTarget(ctx, t, conn, proj.GetPublicId(), "populated", target.WithHostSources([]string{hs[0].GetPublicId()})),
addHostSets: []string{hs[1].GetPublicId()},
resultHostSets: []string{hs[0].GetPublicId(), hs[1].GetPublicId()},
},
{
name: "Add duplicated sets on populated target",
tar: tcp.TestTarget(ctx, t, conn, proj.GetPublicId(), "duplicated", target.WithHostSources([]string{hs[0].GetPublicId()})),
addHostSets: []string{hs[1].GetPublicId(), hs[1].GetPublicId()},
resultHostSets: []string{hs[0].GetPublicId(), hs[1].GetPublicId()},
},
{
name: "Add plugin set on empty target",
tar: tcp.TestTarget(ctx, t, conn, proj.GetPublicId(), "plugin empty"),
addHostSets: []string{pluginHs.GetPublicId()},
resultHostSets: []string{pluginHs.GetPublicId()},
},
{
name: "Add plugin set on populated target",
tar: tcp.TestTarget(ctx, t, conn, proj.GetPublicId(), "plugin populated", target.WithHostSources([]string{hs[0].GetPublicId()})),
addHostSets: []string{pluginHs.GetPublicId()},
resultHostSets: []string{hs[0].GetPublicId(), pluginHs.GetPublicId()},
},
}
for _, tc := range addCases {
t.Run(tc.name, func(t *testing.T) {
req := &pbs.AddTargetHostSetsRequest{
Id: tc.tar.GetPublicId(),
Version: tc.tar.GetVersion(),
HostSetIds: tc.addHostSets,
}
requestInfo := authpb.RequestInfo{
TokenFormat: uint32(auth.AuthTokenTypeBearer),
PublicId: at.GetPublicId(),
Token: at.GetToken(),
}
requestContext := context.WithValue(context.Background(), requests.ContextRequestInformationKey, &requests.RequestContext{})
ctx := auth.NewVerifierContext(requestContext, iamRepoFn, tokenRepoFn, serversRepoFn, kms, &requestInfo)
got, err := s.AddTargetHostSets(ctx, req)
s, ok := status.FromError(err)
require.True(t, ok)
require.NoError(t, err, "Got error: %v", s)
assert.ElementsMatch(t, tc.resultHostSets, got.GetItem().GetHostSetIds())
})
}
tar := tcp.TestTarget(ctx, t, conn, proj.GetPublicId(), "test")
failCases := []struct {
name string
req *pbs.AddTargetHostSetsRequest
err error
}{
{
name: "Bad Set Id",
req: &pbs.AddTargetHostSetsRequest{
Id: "bad id",
Version: tar.GetVersion(),
HostSetIds: []string{hs[0].GetPublicId()},
},
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
},
{
name: "Bad version",
req: &pbs.AddTargetHostSetsRequest{
Id: tar.GetPublicId(),
Version: tar.GetVersion() + 2,
HostSetIds: []string{hs[0].GetPublicId()},
},
err: handlers.ApiErrorWithCode(codes.Internal),
},
{
name: "Empty host set list",
req: &pbs.AddTargetHostSetsRequest{
Id: tar.GetPublicId(),
Version: tar.GetVersion(),
},
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
},
{
name: "Incorrect host set ids",
req: &pbs.AddTargetHostSetsRequest{
Id: tar.GetPublicId(),
Version: tar.GetVersion(),
HostSetIds: []string{"incorrect"},
},
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
},
}
for _, tc := range failCases {
t.Run(tc.name, func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
requestInfo := authpb.RequestInfo{
TokenFormat: uint32(auth.AuthTokenTypeBearer),
PublicId: at.GetPublicId(),
Token: at.GetToken(),
}
requestContext := context.WithValue(context.Background(), requests.ContextRequestInformationKey, &requests.RequestContext{})
ctx := auth.NewVerifierContext(requestContext, iamRepoFn, tokenRepoFn, serversRepoFn, kms, &requestInfo)
_, gErr := s.AddTargetHostSets(ctx, tc.req)
if tc.err != nil {
require.Error(gErr)
assert.True(errors.Is(gErr, tc.err), "AddTargetHostSets(%+v) got error %v, wanted %v", tc.req, gErr, tc.err)
}
})
}
}
func TestSetTargetHostSets(t *testing.T) {
conn, _ := db.TestSetup(t, "postgres")
wrapper := db.TestWrapper(t)
kms := kms.TestKms(t, conn, wrapper)
sche := scheduler.TestScheduler(t, conn, wrapper)
rw := db.New(conn)
iamRepo := iam.TestRepo(t, conn, wrapper)
iamRepoFn := func() (*iam.Repository, error) {
return iamRepo, nil
}
tokenRepoFn := func() (*authtoken.Repository, error) {
return authtoken.NewRepository(rw, rw, kms)
}
serversRepoFn := func() (*server.Repository, error) {
return server.NewRepository(rw, rw, kms)
}
org, proj := iam.TestScopes(t, iamRepo)
at := authtoken.TestAuthToken(t, conn, kms, org.GetPublicId())
r := iam.TestRole(t, conn, proj.GetPublicId())
_ = iam.TestUserRole(t, conn, r.GetPublicId(), at.GetIamUserId())
_ = iam.TestRoleGrant(t, conn, r.GetPublicId(), "id=*;type=*;actions=*")
s, err := testService(t, context.Background(), conn, kms, wrapper)
require.NoError(t, err, "Error when getting new host set service.")
hc := static.TestCatalogs(t, conn, proj.GetPublicId(), 1)[0]
hs := static.TestSets(t, conn, hc.GetPublicId(), 2)
plg := host.TestPlugin(t, conn, "test")
pluginHc := plugin.TestCatalog(t, conn, proj.GetPublicId(), plg.GetPublicId())
pluginHs := plugin.TestSet(t, conn, kms, sche, pluginHc, map[string]plgpb.HostPluginServiceClient{
plg.GetPublicId(): plugin.NewWrappingPluginClient(&plugin.TestPluginServer{}),
})
ctx := context.Background()
setCases := []struct {
name string
tar target.Target
setHostSets []string
resultHostSets []string
}{
{
name: "Set on empty target",
tar: tcp.TestTarget(ctx, t, conn, proj.GetPublicId(), "empty"),
setHostSets: []string{hs[1].GetPublicId()},
resultHostSets: []string{hs[1].GetPublicId()},
},
{
name: "Set on populated target",
tar: tcp.TestTarget(ctx, t, conn, proj.GetPublicId(), "populated", target.WithHostSources([]string{hs[0].GetPublicId()})),
setHostSets: []string{hs[1].GetPublicId()},
resultHostSets: []string{hs[1].GetPublicId()},
},
{
name: "Set duplicate host set on populated target",
tar: tcp.TestTarget(ctx, t, conn, proj.GetPublicId(), "duplicate", target.WithHostSources([]string{hs[0].GetPublicId()})),
setHostSets: []string{hs[1].GetPublicId(), hs[1].GetPublicId()},
resultHostSets: []string{hs[1].GetPublicId()},
},
{
name: "Set empty on populated target",
tar: tcp.TestTarget(ctx, t, conn, proj.GetPublicId(), "another populated", target.WithHostSources([]string{hs[0].GetPublicId()})),
setHostSets: []string{},
resultHostSets: nil,
},
{
name: "Set plugin set on empty target",
tar: tcp.TestTarget(ctx, t, conn, proj.GetPublicId(), "plugin empty"),
setHostSets: []string{pluginHs.GetPublicId()},
resultHostSets: []string{pluginHs.GetPublicId()},
},
{
name: "Set plugin set on populated target",
tar: tcp.TestTarget(ctx, t, conn, proj.GetPublicId(), "plugin populated", target.WithHostSources([]string{hs[0].GetPublicId()})),
setHostSets: []string{pluginHs.GetPublicId()},
resultHostSets: []string{pluginHs.GetPublicId()},
},
}
for _, tc := range setCases {
t.Run(tc.name, func(t *testing.T) {
req := &pbs.SetTargetHostSetsRequest{
Id: tc.tar.GetPublicId(),
Version: tc.tar.GetVersion(),
HostSetIds: tc.setHostSets,
}
requestInfo := authpb.RequestInfo{
TokenFormat: uint32(auth.AuthTokenTypeBearer),
PublicId: at.GetPublicId(),
Token: at.GetToken(),
}
requestContext := context.WithValue(context.Background(), requests.ContextRequestInformationKey, &requests.RequestContext{})
ctx := auth.NewVerifierContext(requestContext, iamRepoFn, tokenRepoFn, serversRepoFn, kms, &requestInfo)
got, err := s.SetTargetHostSets(ctx, req)
require.NoError(t, err, "Got error: %v", s)
assert.ElementsMatch(t, tc.resultHostSets, got.GetItem().GetHostSetIds())
})
}
tar := tcp.TestTarget(ctx, t, conn, proj.GetPublicId(), "test name")
failCases := []struct {
name string
req *pbs.SetTargetHostSetsRequest
err error
}{
{
name: "Bad target Id",
req: &pbs.SetTargetHostSetsRequest{
Id: "bad id",
Version: tar.GetVersion(),
HostSetIds: []string{hs[0].GetPublicId()},
},
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
},
{
name: "Bad version",
req: &pbs.SetTargetHostSetsRequest{
Id: tar.GetPublicId(),
Version: tar.GetVersion() + 3,
HostSetIds: []string{hs[0].GetPublicId()},
},
err: handlers.ApiErrorWithCode(codes.Internal),
},
{
name: "Bad host set id",
req: &pbs.SetTargetHostSetsRequest{
Id: tar.GetPublicId(),
Version: tar.GetVersion(),
HostSetIds: []string{"invalid"},
},
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
},
}
for _, tc := range failCases {
t.Run(tc.name, func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
requestInfo := authpb.RequestInfo{
TokenFormat: uint32(auth.AuthTokenTypeBearer),
PublicId: at.GetPublicId(),
Token: at.GetToken(),
}
requestContext := context.WithValue(context.Background(), requests.ContextRequestInformationKey, &requests.RequestContext{})
ctx := auth.NewVerifierContext(requestContext, iamRepoFn, tokenRepoFn, serversRepoFn, kms, &requestInfo)
_, gErr := s.SetTargetHostSets(ctx, tc.req)
if tc.err != nil {
require.Error(gErr)
assert.True(errors.Is(gErr, tc.err), "SetTargetHostSets(%+v) got error %v, wanted %v", tc.req, gErr, tc.err)
}
})
}
}
func TestRemoveTargetHostSets(t *testing.T) {
conn, _ := db.TestSetup(t, "postgres")
wrapper := db.TestWrapper(t)
kms := kms.TestKms(t, conn, wrapper)
sche := scheduler.TestScheduler(t, conn, wrapper)
rw := db.New(conn)
iamRepo := iam.TestRepo(t, conn, wrapper)
iamRepoFn := func() (*iam.Repository, error) {
return iamRepo, nil
}
tokenRepoFn := func() (*authtoken.Repository, error) {
return authtoken.NewRepository(rw, rw, kms)
}
serversRepoFn := func() (*server.Repository, error) {
return server.NewRepository(rw, rw, kms)
}
org, proj := iam.TestScopes(t, iamRepo)
at := authtoken.TestAuthToken(t, conn, kms, org.GetPublicId())
r := iam.TestRole(t, conn, proj.GetPublicId())
_ = iam.TestUserRole(t, conn, r.GetPublicId(), at.GetIamUserId())
_ = iam.TestRoleGrant(t, conn, r.GetPublicId(), "id=*;type=*;actions=*")
s, err := testService(t, context.Background(), conn, kms, wrapper)
require.NoError(t, err, "Error when getting new host set service.")
hc := static.TestCatalogs(t, conn, proj.GetPublicId(), 1)[0]
hs := static.TestSets(t, conn, hc.GetPublicId(), 2)
plg := host.TestPlugin(t, conn, "test")
pluginHc := plugin.TestCatalog(t, conn, proj.GetPublicId(), plg.GetPublicId())
pluginHs := plugin.TestSet(t, conn, kms, sche, pluginHc, map[string]plgpb.HostPluginServiceClient{
plg.GetPublicId(): plugin.NewWrappingPluginClient(&plugin.TestPluginServer{}),
})
ctx := context.Background()
removeCases := []struct {
name string
tar target.Target
removeHosts []string
resultHosts []string
wantErr bool
}{
{
name: "Remove from empty",
tar: tcp.TestTarget(ctx, t, conn, proj.GetPublicId(), "empty"),
removeHosts: []string{hs[1].GetPublicId()},
wantErr: true,
},
{
name: "Remove 1 of 2 sets",
tar: tcp.TestTarget(ctx, t, conn, proj.GetPublicId(), "remove partial", target.WithHostSources([]string{hs[0].GetPublicId(), hs[1].GetPublicId()})),
removeHosts: []string{hs[1].GetPublicId()},
resultHosts: []string{hs[0].GetPublicId()},
},
{
name: "Remove 1 duplicate set of 2 sets",
tar: tcp.TestTarget(ctx, t, conn, proj.GetPublicId(), "remove duplicate", target.WithHostSources([]string{hs[0].GetPublicId(), hs[1].GetPublicId()})),
removeHosts: []string{hs[1].GetPublicId(), hs[1].GetPublicId()},
resultHosts: []string{hs[0].GetPublicId()},
},
{
name: "Remove all hosts from set",
tar: tcp.TestTarget(ctx, t, conn, proj.GetPublicId(), "remove all", target.WithHostSources([]string{hs[0].GetPublicId(), hs[1].GetPublicId()})),
removeHosts: []string{hs[0].GetPublicId(), hs[1].GetPublicId()},
resultHosts: []string{},
},
{
name: "Remove 1 plugin of 2 sets",
tar: tcp.TestTarget(ctx, t, conn, proj.GetPublicId(), "remove plugin partial", target.WithHostSources([]string{hs[0].GetPublicId(), pluginHs.GetPublicId()})),
removeHosts: []string{pluginHs.GetPublicId()},
resultHosts: []string{hs[0].GetPublicId()},
},
}
for _, tc := range removeCases {
t.Run(tc.name, func(t *testing.T) {
req := &pbs.RemoveTargetHostSetsRequest{
Id: tc.tar.GetPublicId(),
Version: tc.tar.GetVersion(),
HostSetIds: tc.removeHosts,
}
requestInfo := authpb.RequestInfo{
TokenFormat: uint32(auth.AuthTokenTypeBearer),
PublicId: at.GetPublicId(),
Token: at.GetToken(),
}
requestContext := context.WithValue(context.Background(), requests.ContextRequestInformationKey, &requests.RequestContext{})
ctx := auth.NewVerifierContext(requestContext, iamRepoFn, tokenRepoFn, serversRepoFn, kms, &requestInfo)
got, err := s.RemoveTargetHostSets(ctx, req)
if tc.wantErr {
assert.Error(t, err)
return
}
s, ok := status.FromError(err)
require.True(t, ok)
require.NoError(t, err, "Got error: %v", s)
assert.ElementsMatch(t, tc.resultHosts, got.GetItem().GetHostSetIds())
})
}
tar := tcp.TestTarget(ctx, t, conn, proj.GetPublicId(), "testing")
failCases := []struct {
name string
req *pbs.RemoveTargetHostSetsRequest
err error
}{
{
name: "Bad version",
req: &pbs.RemoveTargetHostSetsRequest{
Id: tar.GetPublicId(),
Version: tar.GetVersion() + 3,
HostSetIds: []string{hs[0].GetPublicId()},
},
err: handlers.ApiErrorWithCode(codes.Internal),
},
{
name: "Bad target Id",
req: &pbs.RemoveTargetHostSetsRequest{
Id: "bad id",
Version: tar.GetVersion(),
HostSetIds: []string{hs[0].GetPublicId()},
},
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
},
{
name: "empty sets",
req: &pbs.RemoveTargetHostSetsRequest{
Id: tar.GetPublicId(),
Version: tar.GetVersion(),
HostSetIds: []string{},
},
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
},
{
name: "Invalid set ids",
req: &pbs.RemoveTargetHostSetsRequest{
Id: tar.GetPublicId(),
Version: tar.GetVersion(),
HostSetIds: []string{"invalid"},
},
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
},
}
for _, tc := range failCases {
t.Run(tc.name, func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
requestInfo := authpb.RequestInfo{
TokenFormat: uint32(auth.AuthTokenTypeBearer),
PublicId: at.GetPublicId(),
Token: at.GetToken(),
}
requestContext := context.WithValue(context.Background(), requests.ContextRequestInformationKey, &requests.RequestContext{})
ctx := auth.NewVerifierContext(requestContext, iamRepoFn, tokenRepoFn, serversRepoFn, kms, &requestInfo)
_, gErr := s.RemoveTargetHostSets(ctx, tc.req)
if tc.err != nil {
require.Error(gErr)
assert.True(errors.Is(gErr, tc.err), "RemoveTargetHostSets(%+v) got error %v, wanted %v", tc.req, gErr, tc.err)
}
})
}
}
func TestAddTargetHostSources(t *testing.T) {
conn, _ := db.TestSetup(t, "postgres")
wrapper := db.TestWrapper(t)
@@ -3832,264 +3326,3 @@ func decodeJsonSecret(t *testing.T, in string) map[string]interface{} {
require.NoError(t, dec.Decode(&ret))
return ret
}
// Test that deprecated action add-credential-libraries still works
// TODO: this test can be removed when grants are migrated
func TestAddTargetCredentialLibraryPerms(t *testing.T) {
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrapper := db.TestWrapper(t)
kms := kms.TestKms(t, conn, wrapper)
atRepoFn := func() (*authtoken.Repository, error) {
return authtoken.NewRepository(rw, rw, kms)
}
iamRepoFn := func() (*iam.Repository, error) {
return iam.TestRepo(t, conn, wrapper), nil
}
serversRepoFn := func() (*server.Repository, error) {
return server.NewRepository(rw, rw, kms)
}
iamRepo := iam.TestRepo(t, conn, wrapper)
_, proj := iam.TestScopes(t, iamRepo)
org, proj := iam.TestScopes(t, iamRepo)
storeStatic := credstatic.TestCredentialStore(t, conn, wrapper, proj.GetPublicId())
cred := credstatic.TestUsernamePasswordCredential(t, conn, wrapper, "user", "pass", storeStatic.GetPublicId(), proj.GetPublicId())
cases := []struct {
name string
grant string
wantErr bool
}{
{
name: "valid-deprecated",
grant: "id=*;type=*;actions=add-credential-libraries",
},
{
name: "invalid",
grant: "id=*;type=*;actions=authorize-session",
wantErr: true,
},
{
name: "valid-sources",
grant: "id=*;type=*;actions=add-credential-sources",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
at := authtoken.TestAuthToken(t, conn, kms, org.GetPublicId())
ctx := auth.NewVerifierContext(requests.NewRequestContext(context.Background()),
iamRepoFn,
atRepoFn,
serversRepoFn,
kms,
&authpb.RequestInfo{
Token: at.GetToken(),
TokenFormat: uint32(auth.AuthTokenTypeBearer),
PublicId: at.GetPublicId(),
})
r := iam.TestRole(t, conn, proj.GetPublicId())
_ = iam.TestUserRole(t, conn, r.GetPublicId(), at.GetIamUserId())
_ = iam.TestRoleGrant(t, conn, r.GetPublicId(), tc.grant)
s, err := testService(t, context.Background(), conn, kms, wrapper)
require.NoError(t, err)
tar := tcp.TestTarget(ctx, t, conn, proj.GetPublicId(), tc.name)
req := &pbs.AddTargetCredentialSourcesRequest{
Id: tar.GetPublicId(),
Version: tar.GetVersion(),
BrokeredCredentialSourceIds: []string{cred.GetPublicId()},
}
got, err := s.AddTargetCredentialSources(ctx, req)
if tc.wantErr {
require.Error(t, err)
require.Nil(t, got)
return
}
status, ok := status.FromError(err)
require.True(t, ok)
require.NoError(t, err, "Got error: %v", status)
require.NotNil(t, got)
})
}
}
// Test that deprecated action add-credential-libraries still works
// TODO: this test can be removed when grants are migrated
func TestSetTargetCredentialLibraryPerms(t *testing.T) {
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrapper := db.TestWrapper(t)
kms := kms.TestKms(t, conn, wrapper)
atRepoFn := func() (*authtoken.Repository, error) {
return authtoken.NewRepository(rw, rw, kms)
}
iamRepoFn := func() (*iam.Repository, error) {
return iam.TestRepo(t, conn, wrapper), nil
}
serversRepoFn := func() (*server.Repository, error) {
return server.NewRepository(rw, rw, kms)
}
iamRepo := iam.TestRepo(t, conn, wrapper)
_, proj := iam.TestScopes(t, iamRepo)
org, proj := iam.TestScopes(t, iamRepo)
storeStatic := credstatic.TestCredentialStore(t, conn, wrapper, proj.GetPublicId())
cred := credstatic.TestUsernamePasswordCredential(t, conn, wrapper, "user", "pass", storeStatic.GetPublicId(), proj.GetPublicId())
cases := []struct {
name string
grant string
wantErr bool
}{
{
name: "valid-deprecated",
grant: "id=*;type=*;actions=set-credential-libraries",
},
{
name: "invalid",
grant: "id=*;type=*;actions=authorize-session",
wantErr: true,
},
{
name: "valid-sources",
grant: "id=*;type=*;actions=set-credential-sources",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
at := authtoken.TestAuthToken(t, conn, kms, org.GetPublicId())
ctx := auth.NewVerifierContext(requests.NewRequestContext(context.Background()),
iamRepoFn,
atRepoFn,
serversRepoFn,
kms,
&authpb.RequestInfo{
Token: at.GetToken(),
TokenFormat: uint32(auth.AuthTokenTypeBearer),
PublicId: at.GetPublicId(),
})
r := iam.TestRole(t, conn, proj.GetPublicId())
_ = iam.TestUserRole(t, conn, r.GetPublicId(), at.GetIamUserId())
_ = iam.TestRoleGrant(t, conn, r.GetPublicId(), tc.grant)
s, err := testService(t, context.Background(), conn, kms, wrapper)
require.NoError(t, err)
tar := tcp.TestTarget(ctx, t, conn, proj.GetPublicId(), tc.name)
req := &pbs.SetTargetCredentialSourcesRequest{
Id: tar.GetPublicId(),
Version: tar.GetVersion(),
BrokeredCredentialSourceIds: []string{cred.GetPublicId()},
}
got, err := s.SetTargetCredentialSources(ctx, req)
if tc.wantErr {
require.Error(t, err)
require.Nil(t, got)
return
}
status, ok := status.FromError(err)
require.True(t, ok)
require.NoError(t, err, "Got error: %v", status)
require.NotNil(t, got)
})
}
}
// Test that deprecated action remove-credential-libraries still works
// TODO: this test can be removed when grants are migrated
func TestRemoveTargetCredentialLibraryPerms(t *testing.T) {
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrapper := db.TestWrapper(t)
kms := kms.TestKms(t, conn, wrapper)
atRepoFn := func() (*authtoken.Repository, error) {
return authtoken.NewRepository(rw, rw, kms)
}
iamRepoFn := func() (*iam.Repository, error) {
return iam.TestRepo(t, conn, wrapper), nil
}
serversRepoFn := func() (*server.Repository, error) {
return server.NewRepository(rw, rw, kms)
}
iamRepo := iam.TestRepo(t, conn, wrapper)
_, proj := iam.TestScopes(t, iamRepo)
org, proj := iam.TestScopes(t, iamRepo)
storeStatic := credstatic.TestCredentialStore(t, conn, wrapper, proj.GetPublicId())
cred := credstatic.TestUsernamePasswordCredential(t, conn, wrapper, "user", "pass", storeStatic.GetPublicId(), proj.GetPublicId())
cases := []struct {
name string
grant string
wantErr bool
}{
{
name: "valid-deprecated",
grant: "id=*;type=*;actions=remove-credential-libraries",
},
{
name: "invalid",
grant: "id=*;type=*;actions=authorize-session",
wantErr: true,
},
{
name: "valid-sources",
grant: "id=*;type=*;actions=remove-credential-sources",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
at := authtoken.TestAuthToken(t, conn, kms, org.GetPublicId())
ctx := auth.NewVerifierContext(requests.NewRequestContext(context.Background()),
iamRepoFn,
atRepoFn,
serversRepoFn,
kms,
&authpb.RequestInfo{
Token: at.GetToken(),
TokenFormat: uint32(auth.AuthTokenTypeBearer),
PublicId: at.GetPublicId(),
})
r := iam.TestRole(t, conn, proj.GetPublicId())
_ = iam.TestUserRole(t, conn, r.GetPublicId(), at.GetIamUserId())
_ = iam.TestRoleGrant(t, conn, r.GetPublicId(), tc.grant)
s, err := testService(t, context.Background(), conn, kms, wrapper)
require.NoError(t, err)
tar := tcp.TestTarget(ctx, t, conn, proj.GetPublicId(), tc.name, target.WithStaticCredentials([]*target.StaticCredential{
target.TestNewStaticCredential("", cred.GetPublicId(), credential.BrokeredPurpose),
}))
req := &pbs.RemoveTargetCredentialSourcesRequest{
Id: tar.GetPublicId(),
Version: tar.GetVersion(),
BrokeredCredentialSourceIds: []string{cred.GetPublicId()},
}
got, err := s.RemoveTargetCredentialSources(ctx, req)
if tc.wantErr {
require.Error(t, err)
require.Nil(t, got)
return
}
status, ok := status.FromError(err)
require.True(t, ok)
require.NoError(t, err, "Got error: %v", status)
require.NotNil(t, got)
})
}
}