Add handler and API support for alias creation with target (#4508)

* Add handler and API support for alias creation with target
This commit is contained in:
Todd authored and GitHub committed 2024-03-12 13:57:47 -07:00
1 parent 8d5ec21d73
commit 868228847d
15 files changed
+1116 -484

No files matched your search

@@ -403,6 +403,13 @@ func (s Service) CreateTarget(ctx context.Context, req *pbs.CreateTargetRequest)
if authResults.Error != nil {
return nil, authResults.Error
}
for _, a := range req.GetItem().WithAliases {
authResults := s.aliasCreateAuthResult(ctx, a.GetScopeId())
if authResults.Error != nil {
return nil, authResults.Error
}
}
t, ts, cl, err := s.createInRepo(ctx, req.GetItem())
if err != nil {
return nil, err
@@ -1305,7 +1312,21 @@ func (s Service) createInRepo(ctx context.Context, item *pb.Target) (target.Targ
if err != nil {
return nil, nil, nil, err
}
out, err := repo.CreateTarget(ctx, u)
createOptions := []target.Option{}
if len(item.GetWithAliases()) > 0 {
writeAliases := make([]*talias.Alias, 0, len(item.GetWithAliases()))
for _, a := range item.GetWithAliases() {
na, err := talias.NewAlias(ctx, a.GetScopeId(), a.GetValue(), talias.WithHostId(a.GetAttributes().GetAuthorizeSessionArguments().GetHostId()))
if err != nil {
return nil, nil, nil, errors.Wrap(ctx, err, op, errors.WithMsg("converting from proto to storage alias"))
}
writeAliases = append(writeAliases, na)
}
createOptions = append(createOptions, target.WithAliases(writeAliases))
}
out, err := repo.CreateTarget(ctx, u, createOptions...)
if err != nil {
return nil, nil, nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to create target"))
}
@@ -1579,6 +1600,30 @@ func (s Service) removeCredentialSourcesInRepo(ctx context.Context, targetId str
return out, hs, credSources, nil
}
// aliasCreateAuthResult verifies authorization for creating an alias
func (s Service) aliasCreateAuthResult(ctx context.Context, parentId string) auth.VerifyResults {
res := auth.VerifyResults{}
a := action.Create
opts := []auth.Option{auth.WithType(resource.Alias), auth.WithAction(a)}
iamRepo, err := s.iamRepoFn()
if err != nil {
res.Error = err
return res
}
scp, err := iamRepo.LookupScope(ctx, parentId)
if err != nil {
res.Error = err
return res
}
if scp == nil {
res.Error = handlers.NotFoundError()
return res
}
opts = append(opts, auth.WithScopeId(parentId))
ret := auth.Verify(ctx, opts...)
return ret
}
func (s Service) authResult(ctx context.Context, id string, a action.Type, lookupOpt ...target.Option) auth.VerifyResults {
res := auth.VerifyResults{}
@@ -1704,6 +1749,9 @@ func toProto(ctx context.Context, in target.Target, opt ...handlers.Option) (*pb
}
if outputFields.Has(globals.AliasesField) {
for _, a := range aliases {
// Even though pb.Alias has more than just these 2 fields, we only
// want to return these 2 fields to the client. Any more information
// may be sharing more than the client should know.
out.Aliases = append(out.Aliases, &pb.Alias{
Id: a.PublicId,
Value: a.Value,
@@ -1777,6 +1825,15 @@ func validateCreateRequest(req *pbs.CreateTargetRequest) error {
if item.GetName() == nil || item.GetName().GetValue() == "" {
badFields[globals.NameField] = "This field is required."
}
for _, a := range item.GetWithAliases() {
pa := proto.Clone(a).(*pb.Alias)
pa.Value = ""
pa.ScopeId = ""
pa.Attributes = nil
if !proto.Equal(pa, &pb.Alias{}) {
badFields[globals.WithAliasesField] = "Included aliases can only specify a value, a scope id, and attributes."
}
}
if item.GetSessionConnectionLimit() != nil {
val := item.GetSessionConnectionLimit().GetValue()
switch {
@@ -1860,6 +1917,9 @@ func validateUpdateRequest(req *pbs.UpdateTargetRequest) error {
if item.GetSessionMaxSeconds() != nil && item.GetSessionMaxSeconds().GetValue() == 0 {
badFields[globals.SessionMaxSecondsField] = "This must be greater than zero."
}
if len(item.GetWithAliases()) > 0 {
badFields[globals.WithAliasesField] = "This field can only be set at target creation time."
}
// worker_filter is mutually exclusive from ingress and egress filter
workerFilterFound := false
if workerFilter := item.GetWorkerFilter(); workerFilter != nil {
@@ -156,7 +156,7 @@ func TestGet(t *testing.T) {
tarAddr := tcp.TestTarget(ctx, t, conn, proj.GetPublicId(), "test address", target.WithAddress("8.8.8.8"))
al := talias.TestAlias(t, rw, "test.alias", talias.WithDestinationId(tar.GetPublicId()))
al := talias.TestAlias(t, rw, "test.alias", talias.WithDestinationId(tar.GetPublicId()), talias.WithHostId("hsht_1234567890"))
pAlias := &pb.Alias{
Id: al.GetPublicId(),
@@ -983,9 +983,10 @@ func TestCreate(t *testing.T) {
org, proj := iam.TestScopes(t, iamRepo)
at := authtoken.TestAuthToken(t, conn, kms, org.GetPublicId())
r := iam.TestRole(t, conn, proj.GetPublicId())
r := iam.TestRole(t, conn, "global")
_ = iam.TestUserRole(t, conn, r.GetPublicId(), at.GetIamUserId())
_ = iam.TestRoleGrant(t, conn, r.GetPublicId(), "ids=*;type=*;actions=*")
_ = iam.TestRoleGrantScope(t, conn, r.GetPublicId(), globals.GrantScopeDescendants)
// Ensure we are using the OSS worker filter function
workerFilterFn := targets.AuthorizeSessionWorkerFilterFn
@@ -1035,6 +1036,140 @@ func TestCreate(t *testing.T) {
},
},
},
{
name: "Create a valid target with two aliases",
req: &pbs.CreateTargetRequest{Item: &pb.Target{
ScopeId: proj.GetPublicId(),
Name: wrapperspb.String("target_with_aliases"),
Type: tcp.Subtype.String(),
Attrs: &pb.Target_TcpTargetAttributes{
TcpTargetAttributes: &pb.TcpTargetAttributes{
DefaultPort: wrapperspb.UInt32(2),
},
},
WithAliases: []*pb.Alias{
{
Value: "create-two-aliasses1",
ScopeId: "global",
},
{
Value: "create-two-aliasses2",
ScopeId: "global",
},
},
}},
res: &pbs.CreateTargetResponse{
Uri: fmt.Sprintf("targets/%s_", globals.TcpTargetPrefix),
Item: &pb.Target{
ScopeId: proj.GetPublicId(),
Scope: &scopes.ScopeInfo{Id: proj.GetPublicId(), Type: scope.Project.String(), ParentScopeId: org.GetPublicId()},
Name: wrapperspb.String("target_with_aliases"),
Type: tcp.Subtype.String(),
Attrs: &pb.Target_TcpTargetAttributes{
TcpTargetAttributes: &pb.TcpTargetAttributes{
DefaultPort: wrapperspb.UInt32(2),
},
},
Aliases: []*pb.Alias{
{
Value: "create-two-aliasses1",
},
{
Value: "create-two-aliasses2",
},
},
SessionMaxSeconds: wrapperspb.UInt32(28800),
SessionConnectionLimit: wrapperspb.Int32(-1),
AuthorizedActions: testAuthorizedActions,
Address: &wrapperspb.StringValue{},
},
},
},
{
name: "Create a target with alias specifying the id",
req: &pbs.CreateTargetRequest{Item: &pb.Target{
ScopeId: proj.GetPublicId(),
Name: wrapperspb.String("target_with_invalid_alias"),
Type: tcp.Subtype.String(),
Attrs: &pb.Target_TcpTargetAttributes{
TcpTargetAttributes: &pb.TcpTargetAttributes{
DefaultPort: wrapperspb.UInt32(2),
},
},
WithAliases: []*pb.Alias{
{
Id: "alt_1234567890",
Value: "id-specified",
ScopeId: "global",
},
},
}},
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
},
{
name: "Create a target with invalid alias",
req: &pbs.CreateTargetRequest{Item: &pb.Target{
ScopeId: proj.GetPublicId(),
Name: wrapperspb.String("target_with_invalid_alias"),
Type: tcp.Subtype.String(),
Attrs: &pb.Target_TcpTargetAttributes{
TcpTargetAttributes: &pb.TcpTargetAttributes{
DefaultPort: wrapperspb.UInt32(2),
},
},
WithAliases: []*pb.Alias{
{
Value: "invalid alias",
ScopeId: "global",
},
},
}},
errStr: "unable to create target alias",
},
{
name: "Create a target with invalid scope",
req: &pbs.CreateTargetRequest{Item: &pb.Target{
ScopeId: proj.GetPublicId(),
Name: wrapperspb.String("target_with_invalid_alias"),
Type: tcp.Subtype.String(),
Attrs: &pb.Target_TcpTargetAttributes{
TcpTargetAttributes: &pb.TcpTargetAttributes{
DefaultPort: wrapperspb.UInt32(2),
},
},
WithAliases: []*pb.Alias{
{
Value: "alias.invalid.scope",
ScopeId: proj.GetPublicId(),
},
},
}},
errStr: "unable to create target alias",
},
{
name: "Create a target with duplicate aliasses",
req: &pbs.CreateTargetRequest{Item: &pb.Target{
ScopeId: proj.GetPublicId(),
Name: wrapperspb.String("target_with_invalid_alias"),
Type: tcp.Subtype.String(),
Attrs: &pb.Target_TcpTargetAttributes{
TcpTargetAttributes: &pb.TcpTargetAttributes{
DefaultPort: wrapperspb.UInt32(2),
},
},
WithAliases: []*pb.Alias{
{
Value: "duplicate-alias",
ScopeId: "global",
},
{
Value: "duplicate-alias",
ScopeId: "global",
},
},
}},
errStr: "duplicate key value violates unique constraint",
},
{
name: "Create a target with no port",
req: &pbs.CreateTargetRequest{Item: &pb.Target{
@@ -1168,11 +1303,13 @@ func TestCreate(t *testing.T) {
ctx := auth.NewVerifierContext(requestContext, iamRepoFn, tokenRepoFn, serversRepoFn, kms, &requestInfo)
got, gErr := s.CreateTarget(ctx, tc.req)
if tc.err != nil {
if tc.err != nil || tc.errStr != "" {
require.Error(gErr)
assert.True(errors.Is(gErr, tc.err), "CreateTarget(%+v) got error %v, wanted %v", tc.req, gErr, tc.err)
if tc.err != nil {
assert.True(errors.Is(gErr, tc.err), "CreateTarget(%+v) got error %v, wanted %v", tc.req, gErr, tc.err)
}
if tc.errStr != "" {
require.ErrorContains(gErr, tc.errStr)
assert.ErrorContains(gErr, tc.errStr)
}
} else {
assert.Nil(gErr, "Unexpected err: %v", gErr)
@@ -1194,6 +1331,9 @@ func TestCreate(t *testing.T) {
got,
tc.res,
protocmp.Transform(),
// These are generated, so we don't know what they are when
// specifying the expected case.
protocmp.IgnoreFields(&pb.Alias{}, "id"),
cmpopts.SortSlices(func(a, b string) bool {
return a < b
}),
@@ -1204,6 +1344,93 @@ func TestCreate(t *testing.T) {
targets.AuthorizeSessionWorkerFilterFn = workerFilterFn
}
func TestCreate_AliasAuthCheck(t *testing.T) {
t.Parallel()
ctx := context.Background()
conn, _ := db.TestSetup(t, "postgres")
wrapper := db.TestWrapper(t)
kms := kms.TestKms(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(ctx, rw, rw, kms)
}
serversRepoFn := func() (*server.Repository, error) {
return server.NewRepository(ctx, rw, rw, kms)
}
org, proj := iam.TestScopes(t, iamRepo)
at := authtoken.TestAuthToken(t, conn, kms, org.GetPublicId())
// Both users can create targets
allProjectR := iam.TestRole(t, conn, proj.GetPublicId())
_ = iam.TestUserRole(t, conn, allProjectR.GetPublicId(), at.GetIamUserId())
_ = iam.TestRoleGrant(t, conn, allProjectR.GetPublicId(), "ids=*;type=*;actions=*")
req := &pb.Target{
ScopeId: proj.GetPublicId(),
Name: wrapperspb.String("name"),
Type: tcp.Subtype.String(),
Attrs: &pb.Target_TcpTargetAttributes{
TcpTargetAttributes: &pb.TcpTargetAttributes{
DefaultPort: wrapperspb.UInt32(2),
},
},
WithAliases: []*pb.Alias{
{
Value: "alias-allowed",
ScopeId: "global",
},
},
}
// Ensure we are using the OSS worker filter function
workerFilterFn := targets.AuthorizeSessionWorkerFilterFn
targets.AuthorizeSessionWorkerFilterFn = targets.AuthorizeSessionWithWorkerFilter
t.Cleanup(func() {
targets.AuthorizeSessionWorkerFilterFn = workerFilterFn
})
s, err := testService(t, context.Background(), conn, kms, wrapper)
require.NoError(t, err, "Failed to create a new host set service.")
t.Run("disallowed user creating target", func(t *testing.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)
resp, err := s.CreateTarget(ctx, &pbs.CreateTargetRequest{Item: req})
require.Error(t, err)
require.Nil(t, resp)
assert.ErrorContains(t, err, "PermissionDenied")
})
t.Run("allowed user creating a target", func(t *testing.T) {
// only aliasAllowedAt can create aliases
aliasR := iam.TestRole(t, conn, "global")
_ = iam.TestUserRole(t, conn, aliasR.GetPublicId(), at.GetIamUserId())
_ = iam.TestRoleGrant(t, conn, aliasR.GetPublicId(), "ids=*;type=alias;actions=*")
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)
resp, err := s.CreateTarget(ctx, &pbs.CreateTargetRequest{Item: req})
require.NoError(t, err)
require.NotNil(t, resp)
})
}
func TestUpdate(t *testing.T) {
t.Parallel()
ctx := context.Background()
@@ -1529,6 +1756,19 @@ func TestUpdate(t *testing.T) {
},
},
},
{
name: "Update WithAlias",
req: &pbs.UpdateTargetRequest{
UpdateMask: &field_mask.FieldMask{
Paths: []string{"with_alias"},
},
Item: &pb.Target{
Name: wrapperspb.String("ignored"),
WithAliases: []*pb.Alias{{Value: "new-alias", ScopeId: "global"}},
},
},
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
},
{
name: "Update a Non Existing Target",
req: &pbs.UpdateTargetRequest{