Managed Groups service (#1262)
This commit is contained in:
1 parent
6c9b9e948e
commit
179a49657e
27 files changed
+4734
-120
No files matched your search
@@ -21,6 +21,7 @@ import (
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers/accounts"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers/authmethods"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers/host_sets"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers/managed_groups"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers/sessions"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers/targets"
|
||||
"github.com/hashicorp/boundary/sdk/strutil"
|
||||
@@ -166,6 +167,13 @@ func handleGrpcGateway(c *Controller, props HandlerProperties) (http.Handler, er
|
||||
if err := services.RegisterSessionServiceHandlerServer(ctx, mux, ss); err != nil {
|
||||
return nil, fmt.Errorf("failed to register session service handler: %w", err)
|
||||
}
|
||||
mgs, err := managed_groups.NewService(c.OidcRepoFn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create managed groups handler service: %w", err)
|
||||
}
|
||||
if err := services.RegisterManagedGroupServiceHandlerServer(ctx, mux, mgs); err != nil {
|
||||
return nil, fmt.Errorf("failed to register managed groups service handler: %w", err)
|
||||
}
|
||||
|
||||
return mux, nil
|
||||
}
|
||||
|
||||
@@ -95,7 +95,7 @@ type Service struct {
|
||||
oidcRepoFn common.OidcAuthRepoFactory
|
||||
}
|
||||
|
||||
// NewService returns a user service which handles user related requests to boundary.
|
||||
// NewService returns a account service which handles account related requests to boundary.
|
||||
func NewService(pwRepo common.PasswordAuthRepoFactory, oidcRepo common.OidcAuthRepoFactory) (Service, error) {
|
||||
const op = "accounts.NewService"
|
||||
if pwRepo == nil {
|
||||
@@ -180,7 +180,7 @@ func (s Service) GetAccount(ctx context.Context, req *pbs.GetAccountRequest) (*p
|
||||
if authResults.Error != nil {
|
||||
return nil, authResults.Error
|
||||
}
|
||||
acct, err := s.getFromRepo(ctx, req.GetId())
|
||||
acct, mgIds, err := s.getFromRepo(ctx, req.GetId())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -198,6 +198,9 @@ func (s Service) GetAccount(ctx context.Context, req *pbs.GetAccountRequest) (*p
|
||||
if outputFields.Has(globals.AuthorizedActionsField) {
|
||||
outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, acct.GetPublicId(), IdActions[auth.SubtypeFromId(acct.GetPublicId())]).Strings()))
|
||||
}
|
||||
if outputFields.Has(globals.ManagedGroupIdsField) {
|
||||
outputOpts = append(outputOpts, handlers.WithManagedGroupIds(mgIds))
|
||||
}
|
||||
|
||||
item, err := toProto(ctx, acct, outputOpts...)
|
||||
if err != nil {
|
||||
@@ -379,39 +382,49 @@ func (s Service) SetPassword(ctx context.Context, req *pbs.SetPasswordRequest) (
|
||||
return &pbs.SetPasswordResponse{Item: item}, nil
|
||||
}
|
||||
|
||||
func (s Service) getFromRepo(ctx context.Context, id string) (auth.Account, error) {
|
||||
// getFromRepo returns the account and, if available, managed groups the account
|
||||
// belongs to within the auth method
|
||||
func (s Service) getFromRepo(ctx context.Context, id string) (auth.Account, []string, error) {
|
||||
var acct auth.Account
|
||||
var mgIds []string
|
||||
switch auth.SubtypeFromId(id) {
|
||||
case auth.PasswordSubtype:
|
||||
repo, err := s.pwRepoFn()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
a, err := repo.LookupAccount(ctx, id)
|
||||
if err != nil {
|
||||
if errors.IsNotFoundError(err) {
|
||||
return nil, handlers.NotFoundErrorf("Account %q doesn't exist.", id)
|
||||
return nil, nil, handlers.NotFoundErrorf("Account %q doesn't exist.", id)
|
||||
}
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
acct = a
|
||||
case auth.OidcSubtype:
|
||||
repo, err := s.oidcRepoFn()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
a, err := repo.LookupAccount(ctx, id)
|
||||
if err != nil {
|
||||
if errors.IsNotFoundError(err) {
|
||||
return nil, handlers.NotFoundErrorf("Account %q doesn't exist.", id)
|
||||
return nil, nil, handlers.NotFoundErrorf("Account %q doesn't exist.", id)
|
||||
}
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
mgs, err := repo.ListManagedGroupMembershipsByMember(ctx, a.GetPublicId())
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
for _, mg := range mgs {
|
||||
mgIds = append(mgIds, mg.GetManagedGroupId())
|
||||
}
|
||||
acct = a
|
||||
default:
|
||||
return nil, handlers.NotFoundErrorf("Unrecognized id.")
|
||||
return nil, nil, handlers.NotFoundErrorf("Unrecognized id.")
|
||||
}
|
||||
return acct, nil
|
||||
return acct, mgIds, nil
|
||||
}
|
||||
|
||||
func (s Service) createPwInRepo(ctx context.Context, am auth.AuthMethod, item *pb.Account) (*password.Account, error) {
|
||||
@@ -433,7 +446,7 @@ func (s Service) createPwInRepo(ctx context.Context, am auth.AuthMethod, item *p
|
||||
}
|
||||
a, err := password.NewAccount(am.GetPublicId(), opts...)
|
||||
if err != nil {
|
||||
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to build user for creation: %v.", err)
|
||||
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to build account for creation: %v.", err)
|
||||
}
|
||||
repo, err := s.pwRepoFn()
|
||||
if err != nil {
|
||||
@@ -449,7 +462,7 @@ func (s Service) createPwInRepo(ctx context.Context, am auth.AuthMethod, item *p
|
||||
return nil, errors.Wrap(err, op)
|
||||
}
|
||||
if out == nil {
|
||||
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create user but no error returned from repository.")
|
||||
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create account but no error returned from repository.")
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -480,7 +493,7 @@ func (s Service) createOidcInRepo(ctx context.Context, am auth.AuthMethod, item
|
||||
}
|
||||
a, err := oidc.NewAccount(am.GetPublicId(), attrs.GetSubject(), opts...)
|
||||
if err != nil {
|
||||
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to build user for creation: %v.", err)
|
||||
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to build account for creation: %v.", err)
|
||||
}
|
||||
repo, err := s.oidcRepoFn()
|
||||
if err != nil {
|
||||
@@ -489,10 +502,10 @@ func (s Service) createOidcInRepo(ctx context.Context, am auth.AuthMethod, item
|
||||
|
||||
out, err := repo.CreateAccount(ctx, am.GetScopeId(), a)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op, errors.WithMsg("unable to create user"))
|
||||
return nil, errors.Wrap(err, op, errors.WithMsg("unable to create account"))
|
||||
}
|
||||
if out == nil {
|
||||
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create user but no error returned from repository.")
|
||||
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create account but no error returned from repository.")
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -510,7 +523,7 @@ func (s Service) createInRepo(ctx context.Context, am auth.AuthMethod, item *pb.
|
||||
return nil, errors.Wrap(err, op)
|
||||
}
|
||||
if am == nil {
|
||||
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create auth method but no error returned from repository.")
|
||||
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create account but no error returned from repository.")
|
||||
}
|
||||
out = am
|
||||
case auth.OidcSubtype:
|
||||
@@ -519,7 +532,7 @@ func (s Service) createInRepo(ctx context.Context, am auth.AuthMethod, item *pb.
|
||||
return nil, errors.Wrap(err, op)
|
||||
}
|
||||
if am == nil {
|
||||
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create auth method but no error returned from repository.")
|
||||
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create account but no error returned from repository.")
|
||||
}
|
||||
out = am
|
||||
}
|
||||
@@ -836,6 +849,9 @@ func toProto(ctx context.Context, in auth.Account, opt ...handlers.Option) (*pb.
|
||||
if outputFields.Has(globals.AuthorizedActionsField) {
|
||||
out.AuthorizedActions = opts.WithAuthorizedActions
|
||||
}
|
||||
if outputFields.Has(globals.ManagedGroupIdsField) {
|
||||
out.ManagedGroupIds = opts.WithManagedGroupIds
|
||||
}
|
||||
switch i := in.(type) {
|
||||
case *password.Account:
|
||||
if outputFields.Has(globals.TypeField) {
|
||||
|
||||
@@ -148,6 +148,9 @@ func TestGet(t *testing.T) {
|
||||
oidc.WithApiUrl(oidc.TestConvertToUrls(t, "https://www.alice.com/callback")[0]),
|
||||
)
|
||||
oidcA := oidc.TestAccount(t, conn, oidcAm, "test-subject")
|
||||
// Create a managed group that will always match, so we can test that it is
|
||||
// returned in results
|
||||
mg := oidc.TestManagedGroup(t, conn, oidcAm, `"/token/sub" matches ".*"`)
|
||||
oidcWireAccount := pb.Account{
|
||||
Id: oidcA.GetPublicId(),
|
||||
AuthMethodId: oidcA.GetAuthMethodId(),
|
||||
@@ -161,6 +164,7 @@ func TestGet(t *testing.T) {
|
||||
"subject": structpb.NewStringValue("test-subject"),
|
||||
}},
|
||||
AuthorizedActions: oidcAuthorizedActions,
|
||||
ManagedGroupIds: []string{mg.GetPublicId()},
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
@@ -207,6 +211,18 @@ func TestGet(t *testing.T) {
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
|
||||
if auth.SubtypeFromId(tc.req.Id) == auth.OidcSubtype {
|
||||
// Set up managed groups before getting. First get the current
|
||||
// managed group to make sure we have the right version.
|
||||
oidcRepo, err := oidcRepoFn()
|
||||
require.NoError(err)
|
||||
currMg, err := oidcRepo.LookupManagedGroup(ctx, mg.GetPublicId())
|
||||
require.NoError(err)
|
||||
_, _, err = oidcRepo.SetManagedGroupMemberships(ctx, oidcAm, oidcA, []*oidc.ManagedGroup{currMg})
|
||||
require.NoError(err)
|
||||
}
|
||||
|
||||
got, gErr := s.GetAccount(auth.DisabledAuthTestContext(iamRepoFn, org.GetPublicId()), tc.req)
|
||||
if tc.err != nil {
|
||||
require.Error(gErr)
|
||||
@@ -622,7 +638,7 @@ func TestDelete_twice(t *testing.T) {
|
||||
assert.NoError(gErr, "First attempt")
|
||||
_, gErr = s.DeleteAccount(auth.DisabledAuthTestContext(iamRepoFn, o.GetPublicId()), req)
|
||||
assert.Error(gErr, "Second attempt")
|
||||
assert.True(errors.Is(gErr, handlers.ApiErrorWithCode(codes.NotFound)), "Expected permission denied for the second delete.")
|
||||
assert.True(errors.Is(gErr, handlers.ApiErrorWithCode(codes.NotFound)), "Expected not found for the second delete.")
|
||||
}
|
||||
|
||||
func TestCreatePassword(t *testing.T) {
|
||||
@@ -1057,7 +1073,7 @@ func TestUpdatePassword(t *testing.T) {
|
||||
o, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrap))
|
||||
am := password.TestAuthMethods(t, conn, o.GetPublicId(), 1)[0]
|
||||
tested, err := accounts.NewService(pwRepoFn, oidcRepoFn)
|
||||
require.NoError(t, err, "Error when getting new auth_method service.")
|
||||
require.NoError(t, err, "Error when getting new accounts service.")
|
||||
|
||||
defaultScopeInfo := &scopepb.ScopeInfo{Id: o.GetPublicId(), Type: o.GetType(), ParentScopeId: scope.Global.String()}
|
||||
defaultAttributes := &structpb.Struct{Fields: map[string]*structpb.Value{
|
||||
|
||||
@@ -21,6 +21,7 @@ func fieldError(field, details string) string {
|
||||
}
|
||||
|
||||
func TestValidateCreateRequest(t *testing.T) {
|
||||
t.Parallel()
|
||||
cases := []struct {
|
||||
name string
|
||||
item *pb.Account
|
||||
@@ -132,6 +133,7 @@ func TestValidateCreateRequest(t *testing.T) {
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
req := &pbs.CreateAccountRequest{Item: tc.item}
|
||||
err := validateCreateRequest(req)
|
||||
if tc.errContains == "" {
|
||||
@@ -145,6 +147,7 @@ func TestValidateCreateRequest(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestValidateUpdateRequest(t *testing.T) {
|
||||
t.Parallel()
|
||||
cases := []struct {
|
||||
name string
|
||||
req *pbs.UpdateAccountRequest
|
||||
@@ -207,6 +210,7 @@ func TestValidateUpdateRequest(t *testing.T) {
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
err := validateUpdateRequest(tc.req)
|
||||
if tc.errContains == "" {
|
||||
require.NoError(t, err)
|
||||
@@ -218,6 +222,7 @@ func TestValidateUpdateRequest(t *testing.T) {
|
||||
}
|
||||
|
||||
t.Run("oidc read only fields", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
readOnlyFields := []string{
|
||||
emailClaimField,
|
||||
nameClaimField,
|
||||
@@ -235,6 +240,7 @@ func TestValidateUpdateRequest(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("oidc write only at create fields", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
readOnlyFields := []string{
|
||||
issuerField,
|
||||
subjectField,
|
||||
|
||||
@@ -0,0 +1,652 @@
|
||||
package managed_groups
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/hashicorp/boundary/globals"
|
||||
"github.com/hashicorp/boundary/internal/auth"
|
||||
"github.com/hashicorp/boundary/internal/auth/oidc"
|
||||
oidcstore "github.com/hashicorp/boundary/internal/auth/oidc/store"
|
||||
"github.com/hashicorp/boundary/internal/errors"
|
||||
pb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/managedgroups"
|
||||
pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services"
|
||||
"github.com/hashicorp/boundary/internal/perms"
|
||||
"github.com/hashicorp/boundary/internal/requests"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/common"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers"
|
||||
"github.com/hashicorp/boundary/internal/types/action"
|
||||
"github.com/hashicorp/boundary/internal/types/resource"
|
||||
"github.com/hashicorp/go-bexpr"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/protobuf/types/known/wrapperspb"
|
||||
)
|
||||
|
||||
const (
|
||||
// oidc field names
|
||||
attrFilterField = "attributes.filter"
|
||||
)
|
||||
|
||||
var (
|
||||
oidcMaskManager handlers.MaskManager
|
||||
|
||||
// IdActions contains the set of actions that can be performed on
|
||||
// individual resources
|
||||
IdActions = map[auth.Subtype]action.ActionSet{
|
||||
auth.OidcSubtype: {
|
||||
action.NoOp,
|
||||
action.Read,
|
||||
action.Update,
|
||||
action.Delete,
|
||||
},
|
||||
}
|
||||
|
||||
// CollectionActions contains the set of actions that can be performed on
|
||||
// this collection
|
||||
CollectionActions = action.ActionSet{
|
||||
action.Create,
|
||||
action.List,
|
||||
}
|
||||
)
|
||||
|
||||
func init() {
|
||||
var err error
|
||||
if oidcMaskManager, err = handlers.NewMaskManager(&oidcstore.ManagedGroup{}, &pb.ManagedGroup{}, &pb.OidcManagedGroupAttributes{}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Service handles request as described by the pbs.ManagedGroupServiceServer interface.
|
||||
type Service struct {
|
||||
pbs.UnimplementedManagedGroupServiceServer
|
||||
|
||||
oidcRepoFn common.OidcAuthRepoFactory
|
||||
}
|
||||
|
||||
// NewService returns a managed group service which handles managed group related requests to boundary.
|
||||
func NewService(oidcRepo common.OidcAuthRepoFactory) (Service, error) {
|
||||
const op = "managed_groups.NewService"
|
||||
if oidcRepo == nil {
|
||||
return Service{}, errors.New(errors.InvalidParameter, op, "missing oidc repository provided")
|
||||
}
|
||||
return Service{oidcRepoFn: oidcRepo}, nil
|
||||
}
|
||||
|
||||
var _ pbs.ManagedGroupServiceServer = Service{}
|
||||
|
||||
// ListManagedGroups implements the interface pbs.ManagedGroupsServiceServer.
|
||||
func (s Service) ListManagedGroups(ctx context.Context, req *pbs.ListManagedGroupsRequest) (*pbs.ListManagedGroupsResponse, error) {
|
||||
if err := validateListRequest(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, authResults := s.parentAndAuthResult(ctx, req.GetAuthMethodId(), action.List)
|
||||
if authResults.Error != nil {
|
||||
return nil, authResults.Error
|
||||
}
|
||||
ul, err := s.listFromRepo(ctx, req.GetAuthMethodId())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(ul) == 0 {
|
||||
return &pbs.ListManagedGroupsResponse{}, nil
|
||||
}
|
||||
|
||||
filter, err := handlers.NewFilter(req.GetFilter())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
finalItems := make([]*pb.ManagedGroup, 0, len(ul))
|
||||
|
||||
res := perms.Resource{
|
||||
ScopeId: authResults.Scope.Id,
|
||||
Type: resource.ManagedGroup,
|
||||
Pin: req.GetAuthMethodId(),
|
||||
}
|
||||
for _, mg := range ul {
|
||||
res.Id = mg.GetPublicId()
|
||||
authorizedActions := authResults.FetchActionSetForId(ctx, mg.GetPublicId(), IdActions[auth.SubtypeFromId(mg.GetPublicId())], auth.WithResource(&res)).Strings()
|
||||
if len(authorizedActions) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
outputFields := authResults.FetchOutputFields(res, action.List).SelfOrDefaults(authResults.UserId)
|
||||
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(authorizedActions))
|
||||
}
|
||||
|
||||
item, err := toProto(ctx, mg, outputOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// This comes last so that we can use item fields in the filter after
|
||||
// the allowed fields are populated above
|
||||
if filter.Match(item) {
|
||||
finalItems = append(finalItems, item)
|
||||
}
|
||||
}
|
||||
return &pbs.ListManagedGroupsResponse{Items: finalItems}, nil
|
||||
}
|
||||
|
||||
// GetManagedGroup implements the interface pbs.ManagedGroupServiceServer.
|
||||
func (s Service) GetManagedGroup(ctx context.Context, req *pbs.GetManagedGroupRequest) (*pbs.GetManagedGroupResponse, error) {
|
||||
const op = "managed_groups.(Service).GetManagedGroup"
|
||||
|
||||
if err := validateGetRequest(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
_, authResults := s.parentAndAuthResult(ctx, req.GetId(), action.Read)
|
||||
if authResults.Error != nil {
|
||||
return nil, authResults.Error
|
||||
}
|
||||
mg, err := s.getFromRepo(ctx, req.GetId())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
outputFields, ok := requests.OutputFields(ctx)
|
||||
if !ok {
|
||||
return nil, errors.New(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, mg.GetPublicId(), IdActions[auth.SubtypeFromId(mg.GetPublicId())]).Strings()))
|
||||
}
|
||||
|
||||
item, err := toProto(ctx, mg, outputOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &pbs.GetManagedGroupResponse{Item: item}, nil
|
||||
}
|
||||
|
||||
// CreateManagedGroup implements the interface pbs.ManagedGroupServiceServer.
|
||||
func (s Service) CreateManagedGroup(ctx context.Context, req *pbs.CreateManagedGroupRequest) (*pbs.CreateManagedGroupResponse, error) {
|
||||
const op = "managed_groups.(Service).CreateManagedGroup"
|
||||
|
||||
if err := validateCreateRequest(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
authMeth, authResults := s.parentAndAuthResult(ctx, req.GetItem().GetAuthMethodId(), action.Create)
|
||||
if authResults.Error != nil {
|
||||
return nil, authResults.Error
|
||||
}
|
||||
mg, err := s.createInRepo(ctx, authMeth, req.GetItem())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
outputFields, ok := requests.OutputFields(ctx)
|
||||
if !ok {
|
||||
return nil, errors.New(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, mg.GetPublicId(), IdActions[auth.SubtypeFromId(mg.GetPublicId())]).Strings()))
|
||||
}
|
||||
|
||||
item, err := toProto(ctx, mg, outputOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &pbs.CreateManagedGroupResponse{Item: item, Uri: fmt.Sprintf("managed-groups/%s", item.GetId())}, nil
|
||||
}
|
||||
|
||||
// UpdateManagedGroup implements the interface pbs.ManagedGroupServiceServer.
|
||||
func (s Service) UpdateManagedGroup(ctx context.Context, req *pbs.UpdateManagedGroupRequest) (*pbs.UpdateManagedGroupResponse, error) {
|
||||
const op = "managed_groups.(Service).UpdateManagedGroup"
|
||||
|
||||
if err := validateUpdateRequest(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
authMeth, authResults := s.parentAndAuthResult(ctx, req.GetId(), action.Update)
|
||||
if authResults.Error != nil {
|
||||
return nil, authResults.Error
|
||||
}
|
||||
mg, err := s.updateInRepo(ctx, authResults.Scope.GetId(), authMeth.GetPublicId(), req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
outputFields, ok := requests.OutputFields(ctx)
|
||||
if !ok {
|
||||
return nil, errors.New(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, mg.GetPublicId(), IdActions[auth.SubtypeFromId(mg.GetPublicId())]).Strings()))
|
||||
}
|
||||
|
||||
item, err := toProto(ctx, mg, outputOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &pbs.UpdateManagedGroupResponse{Item: item}, nil
|
||||
}
|
||||
|
||||
// DeleteManagedGroup implements the interface pbs.ManagedGroupServiceServer.
|
||||
func (s Service) DeleteManagedGroup(ctx context.Context, req *pbs.DeleteManagedGroupRequest) (*pbs.DeleteManagedGroupResponse, error) {
|
||||
if err := validateDeleteRequest(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, authResults := s.parentAndAuthResult(ctx, req.GetId(), action.Delete)
|
||||
if authResults.Error != nil {
|
||||
return nil, authResults.Error
|
||||
}
|
||||
_, err := s.deleteFromRepo(ctx, authResults.Scope.GetId(), req.GetId())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s Service) getFromRepo(ctx context.Context, id string) (auth.ManagedGroup, error) {
|
||||
var out auth.ManagedGroup
|
||||
switch auth.SubtypeFromId(id) {
|
||||
case auth.OidcSubtype:
|
||||
repo, err := s.oidcRepoFn()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mg, err := repo.LookupManagedGroup(ctx, id)
|
||||
if err != nil {
|
||||
if errors.IsNotFoundError(err) {
|
||||
return nil, handlers.NotFoundErrorf("ManagedGroup %q doesn't exist.", id)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
out = mg
|
||||
default:
|
||||
return nil, handlers.NotFoundErrorf("Unrecognized id.")
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s Service) createOidcInRepo(ctx context.Context, am auth.AuthMethod, item *pb.ManagedGroup) (*oidc.ManagedGroup, error) {
|
||||
const op = "managed_groups.(Service).createOidcInRepo"
|
||||
if item == nil {
|
||||
return nil, errors.New(errors.InvalidParameter, op, "missing item")
|
||||
}
|
||||
var opts []oidc.Option
|
||||
if item.GetName() != nil {
|
||||
opts = append(opts, oidc.WithName(item.GetName().GetValue()))
|
||||
}
|
||||
if item.GetDescription() != nil {
|
||||
opts = append(opts, oidc.WithDescription(item.GetDescription().GetValue()))
|
||||
}
|
||||
attrs := &pb.OidcManagedGroupAttributes{}
|
||||
if err := handlers.StructToProto(item.GetAttributes(), attrs); err != nil {
|
||||
return nil, handlers.InvalidArgumentErrorf("Error in provided request.",
|
||||
map[string]string{"attributes": "Attribute fields do not match the expected format."})
|
||||
}
|
||||
mg, err := oidc.NewManagedGroup(am.GetPublicId(), attrs.GetFilter(), opts...)
|
||||
if err != nil {
|
||||
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to build user for creation: %v.", err)
|
||||
}
|
||||
repo, err := s.oidcRepoFn()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
out, err := repo.CreateManagedGroup(ctx, am.GetScopeId(), mg)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op, errors.WithMsg("unable to create managed group"))
|
||||
}
|
||||
if out == nil {
|
||||
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create managed group but no error returned from repository.")
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s Service) createInRepo(ctx context.Context, am auth.AuthMethod, item *pb.ManagedGroup) (auth.ManagedGroup, error) {
|
||||
const op = "managed_groups.(Service).createInRepo"
|
||||
if item == nil {
|
||||
return nil, errors.New(errors.InvalidParameter, op, "missing item")
|
||||
}
|
||||
var out auth.ManagedGroup
|
||||
switch auth.SubtypeFromId(am.GetPublicId()) {
|
||||
case auth.OidcSubtype:
|
||||
am, err := s.createOidcInRepo(ctx, am, item)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op)
|
||||
}
|
||||
if am == nil {
|
||||
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create managed group but no error returned from repository.")
|
||||
}
|
||||
out = am
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s Service) updateOidcInRepo(ctx context.Context, scopeId, amId, id string, mask []string, item *pb.ManagedGroup) (*oidc.ManagedGroup, error) {
|
||||
const op = "managed_groups.(Service).updateOidcInRepo"
|
||||
if item == nil {
|
||||
return nil, errors.New(errors.InvalidParameter, op, "nil managed group.")
|
||||
}
|
||||
mg := oidc.AllocManagedGroup()
|
||||
mg.PublicId = id
|
||||
if item.GetName() != nil {
|
||||
mg.Name = item.GetName().GetValue()
|
||||
}
|
||||
if item.GetDescription() != nil {
|
||||
mg.Description = item.GetDescription().GetValue()
|
||||
}
|
||||
if apiAttr := item.GetAttributes(); apiAttr != nil {
|
||||
attrs := &pb.OidcManagedGroupAttributes{}
|
||||
if err := handlers.StructToProto(apiAttr, attrs); err != nil {
|
||||
return nil, handlers.InvalidArgumentErrorf("Error in provided request.",
|
||||
map[string]string{globals.AttributesField: "Attribute fields do not match the expected format."})
|
||||
}
|
||||
// Set this regardless; it'll only take effect if the masks contain the value
|
||||
mg.Filter = attrs.Filter
|
||||
}
|
||||
|
||||
version := item.GetVersion()
|
||||
|
||||
dbMask := oidcMaskManager.Translate(mask)
|
||||
if len(dbMask) == 0 {
|
||||
return nil, handlers.InvalidArgumentErrorf("No valid fields included in the update mask.", map[string]string{"update_mask": "No valid fields provided in the update mask."})
|
||||
}
|
||||
repo, err := s.oidcRepoFn()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op)
|
||||
}
|
||||
out, rowsUpdated, err := repo.UpdateManagedGroup(ctx, scopeId, mg, version, dbMask)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op, errors.WithMsg("unable to update managed group"))
|
||||
}
|
||||
if rowsUpdated == 0 {
|
||||
return nil, handlers.NotFoundErrorf("Managed Group %q doesn't exist or incorrect version provided.", id)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s Service) updateInRepo(ctx context.Context, scopeId, authMethodId string, req *pbs.UpdateManagedGroupRequest) (auth.ManagedGroup, error) {
|
||||
const op = "managed_groups.(Service).updateInRepo"
|
||||
var out auth.ManagedGroup
|
||||
switch auth.SubtypeFromId(req.GetId()) {
|
||||
case auth.OidcSubtype:
|
||||
mg, err := s.updateOidcInRepo(ctx, scopeId, authMethodId, req.GetId(), req.GetUpdateMask().GetPaths(), req.GetItem())
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op)
|
||||
}
|
||||
if mg == nil {
|
||||
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to update managed group but no error returned from repository.")
|
||||
}
|
||||
out = mg
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s Service) deleteFromRepo(ctx context.Context, scopeId, id string) (bool, error) {
|
||||
const op = "managed_groups.(Service).deleteFromRepo"
|
||||
var rows int
|
||||
var err error
|
||||
switch auth.SubtypeFromId(id) {
|
||||
case auth.OidcSubtype:
|
||||
repo, iErr := s.oidcRepoFn()
|
||||
if iErr != nil {
|
||||
return false, iErr
|
||||
}
|
||||
rows, err = repo.DeleteManagedGroup(ctx, scopeId, id)
|
||||
}
|
||||
if err != nil {
|
||||
if errors.IsNotFoundError(err) {
|
||||
return false, nil
|
||||
}
|
||||
return false, errors.Wrap(err, op)
|
||||
}
|
||||
return rows > 0, nil
|
||||
}
|
||||
|
||||
func (s Service) listFromRepo(ctx context.Context, authMethodId string) ([]auth.ManagedGroup, error) {
|
||||
const op = "managed_groups.(Service).listFromRepo"
|
||||
|
||||
var outUl []auth.ManagedGroup
|
||||
switch auth.SubtypeFromId(authMethodId) {
|
||||
case auth.OidcSubtype:
|
||||
oidcRepo, err := s.oidcRepoFn()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op)
|
||||
}
|
||||
oidcl, err := oidcRepo.ListManagedGroups(ctx, authMethodId)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op)
|
||||
}
|
||||
for _, a := range oidcl {
|
||||
outUl = append(outUl, a)
|
||||
}
|
||||
}
|
||||
return outUl, nil
|
||||
}
|
||||
|
||||
func (s Service) parentAndAuthResult(ctx context.Context, id string, a action.Type) (auth.AuthMethod, auth.VerifyResults) {
|
||||
res := auth.VerifyResults{}
|
||||
oidcRepo, err := s.oidcRepoFn()
|
||||
if err != nil {
|
||||
res.Error = err
|
||||
return nil, res
|
||||
}
|
||||
|
||||
var parentId string
|
||||
opts := []auth.Option{auth.WithType(resource.ManagedGroup), auth.WithAction(a)}
|
||||
switch a {
|
||||
case action.List, action.Create:
|
||||
parentId = id
|
||||
default:
|
||||
switch auth.SubtypeFromId(id) {
|
||||
case auth.OidcSubtype:
|
||||
acct, err := oidcRepo.LookupManagedGroup(ctx, id)
|
||||
if err != nil {
|
||||
res.Error = err
|
||||
return nil, res
|
||||
}
|
||||
if acct == nil {
|
||||
res.Error = handlers.NotFoundError()
|
||||
return nil, res
|
||||
}
|
||||
parentId = acct.GetAuthMethodId()
|
||||
}
|
||||
opts = append(opts, auth.WithId(id))
|
||||
}
|
||||
|
||||
var authMeth auth.AuthMethod
|
||||
switch auth.SubtypeFromId(parentId) {
|
||||
case auth.OidcSubtype:
|
||||
am, err := oidcRepo.LookupAuthMethod(ctx, parentId)
|
||||
if err != nil {
|
||||
res.Error = err
|
||||
return nil, res
|
||||
}
|
||||
if am == nil {
|
||||
res.Error = handlers.NotFoundError()
|
||||
return nil, res
|
||||
}
|
||||
authMeth = am
|
||||
}
|
||||
opts = append(opts, auth.WithScopeId(authMeth.GetScopeId()), auth.WithPin(parentId))
|
||||
return authMeth, auth.Verify(ctx, opts...)
|
||||
}
|
||||
|
||||
func toProto(ctx context.Context, in auth.ManagedGroup, opt ...handlers.Option) (*pb.ManagedGroup, error) {
|
||||
opts := handlers.GetOpts(opt...)
|
||||
if opts.WithOutputFields == nil {
|
||||
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "output fields not found when building managed group proto")
|
||||
}
|
||||
outputFields := *opts.WithOutputFields
|
||||
|
||||
out := pb.ManagedGroup{}
|
||||
if outputFields.Has(globals.IdField) {
|
||||
out.Id = in.GetPublicId()
|
||||
}
|
||||
if outputFields.Has(globals.AuthMethodIdField) {
|
||||
out.AuthMethodId = in.GetAuthMethodId()
|
||||
}
|
||||
if outputFields.Has(globals.DescriptionField) && in.GetDescription() != "" {
|
||||
out.Description = &wrapperspb.StringValue{Value: in.GetDescription()}
|
||||
}
|
||||
if outputFields.Has(globals.NameField) && in.GetName() != "" {
|
||||
out.Name = &wrapperspb.StringValue{Value: in.GetName()}
|
||||
}
|
||||
if outputFields.Has(globals.CreatedTimeField) {
|
||||
out.CreatedTime = in.GetCreateTime().GetTimestamp()
|
||||
}
|
||||
if outputFields.Has(globals.UpdatedTimeField) {
|
||||
out.UpdatedTime = in.GetUpdateTime().GetTimestamp()
|
||||
}
|
||||
if outputFields.Has(globals.VersionField) {
|
||||
out.Version = in.GetVersion()
|
||||
}
|
||||
if outputFields.Has(globals.ScopeField) {
|
||||
out.Scope = opts.WithScope
|
||||
}
|
||||
if outputFields.Has(globals.AuthorizedActionsField) {
|
||||
out.AuthorizedActions = opts.WithAuthorizedActions
|
||||
}
|
||||
switch i := in.(type) {
|
||||
case *oidc.ManagedGroup:
|
||||
if outputFields.Has(globals.TypeField) {
|
||||
out.Type = auth.OidcSubtype.String()
|
||||
}
|
||||
if !outputFields.Has(globals.AttributesField) {
|
||||
break
|
||||
}
|
||||
attrs := &pb.OidcManagedGroupAttributes{
|
||||
Filter: i.GetFilter(),
|
||||
}
|
||||
st, err := handlers.ProtoToStruct(attrs)
|
||||
if err != nil {
|
||||
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "failed building oidc attribute struct: %v", err)
|
||||
}
|
||||
out.Attributes = st
|
||||
}
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
// A validateX method should exist for each method above. These methods do not make calls to any backing service but enforce
|
||||
// requirements on the structure of the request. They verify that:
|
||||
// * The path passed in is correctly formatted
|
||||
// * All required parameters are set
|
||||
// * There are no conflicting parameters provided
|
||||
func validateGetRequest(req *pbs.GetManagedGroupRequest) error {
|
||||
const op = "managed_groups.validateGetRequest"
|
||||
if req == nil {
|
||||
return errors.New(errors.InvalidParameter, op, "nil request")
|
||||
}
|
||||
return handlers.ValidateGetRequest(handlers.NoopValidatorFn, req, oidc.ManagedGroupPrefix)
|
||||
}
|
||||
|
||||
func validateCreateRequest(req *pbs.CreateManagedGroupRequest) error {
|
||||
const op = "managed_groups.validateCreateRequest"
|
||||
if req == nil {
|
||||
return errors.New(errors.InvalidParameter, op, "nil request")
|
||||
}
|
||||
return handlers.ValidateCreateRequest(req.GetItem(), func() map[string]string {
|
||||
badFields := map[string]string{}
|
||||
if req.GetItem().GetAuthMethodId() == "" {
|
||||
badFields[globals.AuthMethodIdField] = "This field is required."
|
||||
}
|
||||
switch auth.SubtypeFromId(req.GetItem().GetAuthMethodId()) {
|
||||
case auth.OidcSubtype:
|
||||
if req.GetItem().GetType() != "" && req.GetItem().GetType() != auth.OidcSubtype.String() {
|
||||
badFields[globals.TypeField] = "Doesn't match the parent resource's type."
|
||||
}
|
||||
attrs := &pb.OidcManagedGroupAttributes{}
|
||||
if err := handlers.StructToProto(req.GetItem().GetAttributes(), attrs); err != nil {
|
||||
badFields[globals.AttributesField] = "Attribute fields do not match the expected format."
|
||||
}
|
||||
if attrs.Filter == "" {
|
||||
badFields[attrFilterField] = "This field is required."
|
||||
} else {
|
||||
if _, err := bexpr.CreateEvaluator(attrs.Filter); err != nil {
|
||||
badFields[attrFilterField] = fmt.Sprintf("Error evaluating submitted filter expression: %v.", err)
|
||||
}
|
||||
}
|
||||
default:
|
||||
badFields[globals.AuthMethodIdField] = "Unknown auth method type from ID."
|
||||
}
|
||||
return badFields
|
||||
})
|
||||
}
|
||||
|
||||
func validateUpdateRequest(req *pbs.UpdateManagedGroupRequest) error {
|
||||
const op = "managed_groups.validateUpdateRequest"
|
||||
if req == nil {
|
||||
return errors.New(errors.InvalidParameter, op, "nil request")
|
||||
}
|
||||
return handlers.ValidateUpdateRequest(req, req.GetItem(), func() map[string]string {
|
||||
badFields := map[string]string{}
|
||||
switch auth.SubtypeFromId(req.GetId()) {
|
||||
case auth.OidcSubtype:
|
||||
if req.GetItem().GetType() != "" && req.GetItem().GetType() != auth.OidcSubtype.String() {
|
||||
badFields[globals.TypeField] = "Cannot modify the resource type."
|
||||
}
|
||||
attrs := &pb.OidcManagedGroupAttributes{}
|
||||
if err := handlers.StructToProto(req.GetItem().GetAttributes(), attrs); err != nil {
|
||||
badFields[globals.AttributesField] = "Attribute fields do not match the expected format."
|
||||
}
|
||||
if handlers.MaskContains(req.GetUpdateMask().GetPaths(), attrFilterField) {
|
||||
if attrs.Filter == "" {
|
||||
badFields[attrFilterField] = "Field cannot be empty."
|
||||
} else {
|
||||
if _, err := bexpr.CreateEvaluator(attrs.Filter); err != nil {
|
||||
badFields[attrFilterField] = fmt.Sprintf("Error evaluating submitted filter expression: %v.", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return badFields
|
||||
}, oidc.ManagedGroupPrefix)
|
||||
}
|
||||
|
||||
func validateDeleteRequest(req *pbs.DeleteManagedGroupRequest) error {
|
||||
const op = "managed_groups.validateDeleteRequest"
|
||||
if req == nil {
|
||||
return errors.New(errors.InvalidParameter, op, "nil request")
|
||||
}
|
||||
return handlers.ValidateDeleteRequest(handlers.NoopValidatorFn, req, oidc.ManagedGroupPrefix)
|
||||
}
|
||||
|
||||
func validateListRequest(req *pbs.ListManagedGroupsRequest) error {
|
||||
const op = "managed_groups.validateListRequest"
|
||||
if req == nil {
|
||||
return errors.New(errors.InvalidParameter, op, "nil request")
|
||||
}
|
||||
badFields := map[string]string{}
|
||||
if !handlers.ValidId(handlers.Id(req.GetAuthMethodId()), oidc.AuthMethodPrefix) {
|
||||
badFields[globals.AuthMethodIdField] = "Invalid formatted identifier."
|
||||
}
|
||||
if _, err := handlers.NewFilter(req.GetFilter()); err != nil {
|
||||
badFields[globals.FilterField] = fmt.Sprintf("This field could not be parsed. %v", err)
|
||||
}
|
||||
if len(badFields) > 0 {
|
||||
return handlers.InvalidArgumentErrorf("Error in provided request.", badFields)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,987 @@
|
||||
package managed_groups_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/boundary/globals"
|
||||
"github.com/hashicorp/boundary/internal/auth"
|
||||
"github.com/hashicorp/boundary/internal/auth/oidc"
|
||||
"github.com/hashicorp/boundary/internal/authtoken"
|
||||
"github.com/hashicorp/boundary/internal/db"
|
||||
pb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/managedgroups"
|
||||
scopepb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/scopes"
|
||||
pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services"
|
||||
"github.com/hashicorp/boundary/internal/iam"
|
||||
"github.com/hashicorp/boundary/internal/kms"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/common"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers/managed_groups"
|
||||
"github.com/hashicorp/boundary/internal/types/action"
|
||||
"github.com/hashicorp/boundary/internal/types/scope"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/genproto/protobuf/field_mask"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/protobuf/testing/protocmp"
|
||||
"google.golang.org/protobuf/types/known/structpb"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
"google.golang.org/protobuf/types/known/wrapperspb"
|
||||
)
|
||||
|
||||
var oidcAuthorizedActions = []string{
|
||||
action.NoOp.String(),
|
||||
action.Read.String(),
|
||||
action.Update.String(),
|
||||
action.Delete.String(),
|
||||
}
|
||||
|
||||
const testFakeManagedGroupFilter = `"/foo" == "bar"`
|
||||
|
||||
func TestNewService(t *testing.T) {
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
rw := db.New(conn)
|
||||
wrap := db.TestWrapper(t)
|
||||
kmsCache := kms.TestKms(t, conn, wrap)
|
||||
oidcRepoFn := func() (*oidc.Repository, error) {
|
||||
return oidc.NewRepository(rw, rw, kmsCache)
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
oidcRepo common.OidcAuthRepoFactory
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "nil-oidc-repo",
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "success",
|
||||
oidcRepo: oidcRepoFn,
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
_, err := managed_groups.NewService(tc.oidcRepo)
|
||||
if tc.wantErr {
|
||||
assert.Error(t, err)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGet(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
rw := db.New(conn)
|
||||
wrap := db.TestWrapper(t)
|
||||
kmsCache := kms.TestKms(t, conn, wrap)
|
||||
oidcRepoFn := func() (*oidc.Repository, error) {
|
||||
return oidc.NewRepository(rw, rw, kmsCache)
|
||||
}
|
||||
iamRepoFn := func() (*iam.Repository, error) {
|
||||
return iam.NewRepository(rw, rw, kmsCache)
|
||||
}
|
||||
|
||||
s, err := managed_groups.NewService(oidcRepoFn)
|
||||
require.NoError(t, err, "Couldn't create new managed groups service.")
|
||||
|
||||
org, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrap))
|
||||
|
||||
databaseWrapper, err := kmsCache.GetWrapper(ctx, org.PublicId, kms.KeyPurposeDatabase)
|
||||
require.NoError(t, err)
|
||||
oidcAm := oidc.TestAuthMethod(
|
||||
t, conn, databaseWrapper, org.PublicId, oidc.ActivePrivateState,
|
||||
"alice-rp", "fido",
|
||||
oidc.WithIssuer(oidc.TestConvertToUrls(t, "https://www.alice.com")[0]),
|
||||
oidc.WithSigningAlgs(oidc.RS256),
|
||||
oidc.WithApiUrl(oidc.TestConvertToUrls(t, "https://www.alice.com/callback")[0]),
|
||||
)
|
||||
omg := oidc.TestManagedGroup(t, conn, oidcAm, testFakeManagedGroupFilter)
|
||||
|
||||
oidcWireManagedGroup := pb.ManagedGroup{
|
||||
Id: omg.GetPublicId(),
|
||||
AuthMethodId: omg.GetAuthMethodId(),
|
||||
CreatedTime: omg.GetCreateTime().GetTimestamp(),
|
||||
UpdatedTime: omg.GetUpdateTime().GetTimestamp(),
|
||||
Scope: &scopepb.ScopeInfo{Id: org.GetPublicId(), Type: scope.Org.String(), ParentScopeId: scope.Global.String()},
|
||||
Version: 1,
|
||||
Type: "oidc",
|
||||
Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{"filter": structpb.NewStringValue(omg.GetFilter())}},
|
||||
AuthorizedActions: oidcAuthorizedActions,
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
req *pbs.GetManagedGroupRequest
|
||||
res *pbs.GetManagedGroupResponse
|
||||
err error
|
||||
}{
|
||||
{
|
||||
name: "Get an oidc managed group",
|
||||
req: &pbs.GetManagedGroupRequest{Id: oidcWireManagedGroup.GetId()},
|
||||
res: &pbs.GetManagedGroupResponse{Item: &oidcWireManagedGroup},
|
||||
},
|
||||
{
|
||||
name: "Get a non existing oidc managed group",
|
||||
req: &pbs.GetManagedGroupRequest{Id: oidc.ManagedGroupPrefix + "_DoesntExis"},
|
||||
res: nil,
|
||||
err: handlers.ApiErrorWithCode(codes.NotFound),
|
||||
},
|
||||
{
|
||||
name: "Wrong id prefix",
|
||||
req: &pbs.GetManagedGroupRequest{Id: "j_1234567890"},
|
||||
res: nil,
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "space in id",
|
||||
req: &pbs.GetManagedGroupRequest{Id: authtoken.AuthTokenPrefix + "_1 23456789"},
|
||||
res: nil,
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
got, gErr := s.GetManagedGroup(auth.DisabledAuthTestContext(iamRepoFn, org.GetPublicId()), tc.req)
|
||||
if tc.err != nil {
|
||||
require.Error(gErr)
|
||||
assert.True(errors.Is(gErr, tc.err), "GetManagedGroup(%+v) got error %v, wanted %v", tc.req, gErr, tc.err)
|
||||
return
|
||||
}
|
||||
require.NoError(gErr)
|
||||
assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform()), "GetManagedGroup(%q) got response %q, wanted %q", tc.req, got, tc.res)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestListOidc(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
rw := db.New(conn)
|
||||
wrap := db.TestWrapper(t)
|
||||
kmsCache := kms.TestKms(t, conn, wrap)
|
||||
oidcRepoFn := func() (*oidc.Repository, error) {
|
||||
return oidc.NewRepository(rw, rw, kmsCache)
|
||||
}
|
||||
iamRepoFn := func() (*iam.Repository, error) {
|
||||
return iam.NewRepository(rw, rw, kmsCache)
|
||||
}
|
||||
|
||||
o, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrap))
|
||||
databaseWrapper, err := kmsCache.GetWrapper(ctx, o.PublicId, kms.KeyPurposeDatabase)
|
||||
require.NoError(t, err)
|
||||
amNoManagedGroups := oidc.TestAuthMethod(t, conn, databaseWrapper, o.PublicId, oidc.ActivePrivateState, "noManagedGroups", "fido",
|
||||
oidc.WithIssuer(oidc.TestConvertToUrls(t, "https://www.nomanagedgroups.com")[0]), oidc.WithSigningAlgs(oidc.RS256), oidc.WithApiUrl(oidc.TestConvertToUrls(t, "https://www.alice.com/callback")[0]))
|
||||
amSomeManagedGroups := oidc.TestAuthMethod(t, conn, databaseWrapper, o.PublicId, oidc.ActivePrivateState, "someManagedGroups", "fido",
|
||||
oidc.WithIssuer(oidc.TestConvertToUrls(t, "https://www.somemanagedgroups.com")[0]), oidc.WithSigningAlgs(oidc.RS256), oidc.WithApiUrl(oidc.TestConvertToUrls(t, "https://www.alice.com/callback")[0]))
|
||||
amOtherManagedGroups := oidc.TestAuthMethod(t, conn, databaseWrapper, o.PublicId, oidc.ActivePrivateState, "otherManagedGroups", "fido",
|
||||
oidc.WithIssuer(oidc.TestConvertToUrls(t, "https://www.othermanagedgroups.com")[0]), oidc.WithSigningAlgs(oidc.RS256), oidc.WithApiUrl(oidc.TestConvertToUrls(t, "https://www.alice.com/callback")[0]))
|
||||
|
||||
var wantSomeManagedGroups []*pb.ManagedGroup
|
||||
for i := 0; i < 3; i++ {
|
||||
mg := oidc.TestManagedGroup(t, conn, amSomeManagedGroups, testFakeManagedGroupFilter, oidc.WithName(strconv.Itoa(i)))
|
||||
wantSomeManagedGroups = append(wantSomeManagedGroups, &pb.ManagedGroup{
|
||||
Id: mg.GetPublicId(),
|
||||
AuthMethodId: mg.GetAuthMethodId(),
|
||||
Name: wrapperspb.String(strconv.Itoa(i)),
|
||||
CreatedTime: mg.GetCreateTime().GetTimestamp(),
|
||||
UpdatedTime: mg.GetUpdateTime().GetTimestamp(),
|
||||
Scope: &scopepb.ScopeInfo{Id: o.GetPublicId(), Type: scope.Org.String(), ParentScopeId: scope.Global.String()},
|
||||
Version: 1,
|
||||
Type: auth.OidcSubtype.String(),
|
||||
Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{
|
||||
"filter": structpb.NewStringValue(testFakeManagedGroupFilter),
|
||||
}},
|
||||
AuthorizedActions: oidcAuthorizedActions,
|
||||
})
|
||||
}
|
||||
|
||||
var wantOtherManagedGroups []*pb.ManagedGroup
|
||||
for i := 0; i < 3; i++ {
|
||||
mg := oidc.TestManagedGroup(t, conn, amOtherManagedGroups, testFakeManagedGroupFilter, oidc.WithName(strconv.Itoa(i)))
|
||||
wantOtherManagedGroups = append(wantOtherManagedGroups, &pb.ManagedGroup{
|
||||
Id: mg.GetPublicId(),
|
||||
AuthMethodId: mg.GetAuthMethodId(),
|
||||
Name: wrapperspb.String(strconv.Itoa(i)),
|
||||
CreatedTime: mg.GetCreateTime().GetTimestamp(),
|
||||
UpdatedTime: mg.GetUpdateTime().GetTimestamp(),
|
||||
Scope: &scopepb.ScopeInfo{Id: o.GetPublicId(), Type: scope.Org.String(), ParentScopeId: scope.Global.String()},
|
||||
Version: 1,
|
||||
Type: auth.OidcSubtype.String(),
|
||||
Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{
|
||||
"filter": structpb.NewStringValue(testFakeManagedGroupFilter),
|
||||
}},
|
||||
AuthorizedActions: oidcAuthorizedActions,
|
||||
})
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
req *pbs.ListManagedGroupsRequest
|
||||
res *pbs.ListManagedGroupsResponse
|
||||
err error
|
||||
skipAnon bool
|
||||
}{
|
||||
{
|
||||
name: "List Some ManagedGroups",
|
||||
req: &pbs.ListManagedGroupsRequest{AuthMethodId: amSomeManagedGroups.GetPublicId()},
|
||||
res: &pbs.ListManagedGroupsResponse{Items: wantSomeManagedGroups},
|
||||
},
|
||||
{
|
||||
name: "List Other ManagedGroups",
|
||||
req: &pbs.ListManagedGroupsRequest{AuthMethodId: amOtherManagedGroups.GetPublicId()},
|
||||
res: &pbs.ListManagedGroupsResponse{Items: wantOtherManagedGroups},
|
||||
},
|
||||
{
|
||||
name: "List No ManagedGroups",
|
||||
req: &pbs.ListManagedGroupsRequest{AuthMethodId: amNoManagedGroups.GetPublicId()},
|
||||
res: &pbs.ListManagedGroupsResponse{},
|
||||
},
|
||||
{
|
||||
name: "Unfound Auth Method",
|
||||
req: &pbs.ListManagedGroupsRequest{AuthMethodId: oidc.AuthMethodPrefix + "_DoesntExis"},
|
||||
err: handlers.ApiErrorWithCode(codes.NotFound),
|
||||
},
|
||||
{
|
||||
name: "Filter Some ManagedGroups",
|
||||
req: &pbs.ListManagedGroupsRequest{
|
||||
AuthMethodId: amSomeManagedGroups.GetPublicId(),
|
||||
Filter: fmt.Sprintf(`"/item/name"==%q`, wantSomeManagedGroups[1].Name.GetValue()),
|
||||
},
|
||||
res: &pbs.ListManagedGroupsResponse{Items: wantSomeManagedGroups[1:2]},
|
||||
skipAnon: true,
|
||||
},
|
||||
{
|
||||
name: "Filter All ManagedGroups",
|
||||
req: &pbs.ListManagedGroupsRequest{
|
||||
AuthMethodId: amSomeManagedGroups.GetPublicId(),
|
||||
Filter: `"/item/id"=="noManagedGroupmatchesthis"`,
|
||||
},
|
||||
res: &pbs.ListManagedGroupsResponse{},
|
||||
},
|
||||
{
|
||||
name: "Filter Bad Format",
|
||||
req: &pbs.ListManagedGroupsRequest{AuthMethodId: amSomeManagedGroups.GetPublicId(), Filter: `"//id/"=="bad"`},
|
||||
err: handlers.InvalidArgumentErrorf("bad format", nil),
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
s, err := managed_groups.NewService(oidcRepoFn)
|
||||
require.NoError(err, "Couldn't create new managed group service.")
|
||||
|
||||
got, gErr := s.ListManagedGroups(auth.DisabledAuthTestContext(iamRepoFn, o.GetPublicId()), tc.req)
|
||||
if tc.err != nil {
|
||||
require.Error(gErr)
|
||||
assert.True(errors.Is(gErr, tc.err), "ListManagedGroups() with auth method %q got error %v, wanted %v", tc.req, gErr, tc.err)
|
||||
return
|
||||
} else {
|
||||
require.NoError(gErr)
|
||||
}
|
||||
sort.Slice(got.Items, func(i, j int) bool {
|
||||
return strings.Compare(got.Items[i].GetName().GetValue(),
|
||||
got.Items[j].GetName().GetValue()) < 0
|
||||
})
|
||||
assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform()), "ListManagedGroups() with scope %q got response %q, wanted %q", tc.req, got, tc.res)
|
||||
|
||||
// Now test with anon
|
||||
if tc.skipAnon {
|
||||
return
|
||||
}
|
||||
got, gErr = s.ListManagedGroups(auth.DisabledAuthTestContext(iamRepoFn, o.GetPublicId(), auth.WithUserId(auth.AnonymousUserId)), tc.req)
|
||||
require.NoError(gErr)
|
||||
assert.Len(got.Items, len(tc.res.Items))
|
||||
for _, g := range got.GetItems() {
|
||||
assert.Nil(g.Attributes)
|
||||
assert.Nil(g.CreatedTime)
|
||||
assert.Nil(g.UpdatedTime)
|
||||
assert.Empty(g.Version)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDelete(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
rw := db.New(conn)
|
||||
wrap := db.TestWrapper(t)
|
||||
kmsCache := kms.TestKms(t, conn, wrap)
|
||||
oidcRepoFn := func() (*oidc.Repository, error) {
|
||||
return oidc.NewRepository(rw, rw, kmsCache)
|
||||
}
|
||||
iamRepoFn := func() (*iam.Repository, error) {
|
||||
return iam.NewRepository(rw, rw, kmsCache)
|
||||
}
|
||||
|
||||
o, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrap))
|
||||
|
||||
databaseWrapper, err := kmsCache.GetWrapper(ctx, o.PublicId, kms.KeyPurposeDatabase)
|
||||
require.NoError(t, err)
|
||||
oidcAm := oidc.TestAuthMethod(
|
||||
t, conn, databaseWrapper, o.PublicId, oidc.ActivePrivateState,
|
||||
"alice-rp", "fido",
|
||||
oidc.WithIssuer(oidc.TestConvertToUrls(t, "https://www.alice.com")[0]),
|
||||
oidc.WithSigningAlgs(oidc.RS256),
|
||||
oidc.WithApiUrl(oidc.TestConvertToUrls(t, "https://www.alice.com/callback")[0]),
|
||||
)
|
||||
oidcMg := oidc.TestManagedGroup(t, conn, oidcAm, testFakeManagedGroupFilter)
|
||||
|
||||
s, err := managed_groups.NewService(oidcRepoFn)
|
||||
require.NoError(t, err, "Error when getting new user service.")
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
scope string
|
||||
req *pbs.DeleteManagedGroupRequest
|
||||
res *pbs.DeleteManagedGroupResponse
|
||||
err error
|
||||
}{
|
||||
{
|
||||
name: "Delete an existing oidc managed group",
|
||||
req: &pbs.DeleteManagedGroupRequest{
|
||||
Id: oidcMg.GetPublicId(),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Delete bad oidc managed group id",
|
||||
req: &pbs.DeleteManagedGroupRequest{
|
||||
Id: oidc.ManagedGroupPrefix + "_doesntexis",
|
||||
},
|
||||
err: handlers.ApiErrorWithCode(codes.NotFound),
|
||||
},
|
||||
{
|
||||
name: "Bad managed group id formatting",
|
||||
req: &pbs.DeleteManagedGroupRequest{
|
||||
Id: "bad_format",
|
||||
},
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
got, gErr := s.DeleteManagedGroup(auth.DisabledAuthTestContext(iamRepoFn, o.GetPublicId()), tc.req)
|
||||
if tc.err != nil {
|
||||
require.Error(gErr)
|
||||
assert.True(errors.Is(gErr, tc.err), "DeleteManagedGroup(%+v) got error %v, wanted %v", tc.req, gErr, tc.err)
|
||||
}
|
||||
assert.EqualValuesf(tc.res, got, "DeleteManagedGroup(%q) got response %q, wanted %q", tc.req, got, tc.res)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDelete_twice(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
wrap := db.TestWrapper(t)
|
||||
rw := db.New(conn)
|
||||
kmsCache := kms.TestKms(t, conn, wrap)
|
||||
|
||||
oidcRepoFn := func() (*oidc.Repository, error) {
|
||||
return oidc.NewRepository(rw, rw, kmsCache)
|
||||
}
|
||||
iamRepoFn := func() (*iam.Repository, error) {
|
||||
return iam.NewRepository(rw, rw, kmsCache)
|
||||
}
|
||||
|
||||
o, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrap))
|
||||
|
||||
databaseWrapper, err := kmsCache.GetWrapper(context.Background(), o.PublicId, kms.KeyPurposeDatabase)
|
||||
|
||||
oidcAm := oidc.TestAuthMethod(
|
||||
t, conn, databaseWrapper, o.PublicId, oidc.ActivePrivateState,
|
||||
"alice-rp", "fido",
|
||||
oidc.WithIssuer(oidc.TestConvertToUrls(t, "https://www.alice.com")[0]),
|
||||
oidc.WithSigningAlgs(oidc.RS256),
|
||||
oidc.WithApiUrl(oidc.TestConvertToUrls(t, "https://www.alice.com/callback")[0]),
|
||||
)
|
||||
oidcMg := oidc.TestManagedGroup(t, conn, oidcAm, testFakeManagedGroupFilter)
|
||||
|
||||
s, err := managed_groups.NewService(oidcRepoFn)
|
||||
require.NoError(err, "Error when getting new user service")
|
||||
req := &pbs.DeleteManagedGroupRequest{
|
||||
Id: oidcMg.GetPublicId(),
|
||||
}
|
||||
_, gErr := s.DeleteManagedGroup(auth.DisabledAuthTestContext(iamRepoFn, o.GetPublicId()), req)
|
||||
assert.NoError(gErr, "First attempt")
|
||||
_, gErr = s.DeleteManagedGroup(auth.DisabledAuthTestContext(iamRepoFn, o.GetPublicId()), req)
|
||||
assert.Error(gErr, "Second attempt")
|
||||
assert.True(errors.Is(gErr, handlers.ApiErrorWithCode(codes.NotFound)), "Expected not found for the second delete.")
|
||||
}
|
||||
|
||||
func TestCreateOidc(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
rw := db.New(conn)
|
||||
wrap := db.TestWrapper(t)
|
||||
kmsCache := kms.TestKms(t, conn, wrap)
|
||||
oidcRepoFn := func() (*oidc.Repository, error) {
|
||||
return oidc.NewRepository(rw, rw, kmsCache)
|
||||
}
|
||||
iamRepoFn := func() (*iam.Repository, error) {
|
||||
return iam.NewRepository(rw, rw, kmsCache)
|
||||
}
|
||||
|
||||
s, err := managed_groups.NewService(oidcRepoFn)
|
||||
require.NoError(t, err, "Error when getting new managed group service.")
|
||||
|
||||
o, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrap))
|
||||
databaseWrapper, err := kmsCache.GetWrapper(ctx, o.PublicId, kms.KeyPurposeDatabase)
|
||||
require.NoError(t, err)
|
||||
am := oidc.TestAuthMethod(
|
||||
t, conn, databaseWrapper, o.PublicId, oidc.ActivePrivateState,
|
||||
"alice-rp", "fido",
|
||||
oidc.WithIssuer(oidc.TestConvertToUrls(t, "https://www.alice.com")[0]),
|
||||
oidc.WithSigningAlgs(oidc.RS256),
|
||||
oidc.WithApiUrl(oidc.TestConvertToUrls(t, "https://www.alice.com/callback")[0]),
|
||||
)
|
||||
|
||||
createAttr := func() *structpb.Struct {
|
||||
attr := &pb.OidcManagedGroupAttributes{Filter: testFakeManagedGroupFilter}
|
||||
ret, err := handlers.ProtoToStruct(attr)
|
||||
require.NoError(t, err, "Error converting proto to struct.")
|
||||
return ret
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
req *pbs.CreateManagedGroupRequest
|
||||
res *pbs.CreateManagedGroupResponse
|
||||
err error
|
||||
}{
|
||||
{
|
||||
name: "Create a valid ManagedGroup",
|
||||
req: &pbs.CreateManagedGroupRequest{
|
||||
Item: &pb.ManagedGroup{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
Name: &wrapperspb.StringValue{Value: "name"},
|
||||
Description: &wrapperspb.StringValue{Value: "desc"},
|
||||
Type: auth.OidcSubtype.String(),
|
||||
Attributes: createAttr(),
|
||||
},
|
||||
},
|
||||
res: &pbs.CreateManagedGroupResponse{
|
||||
Uri: fmt.Sprintf("managed-groups/%s_", oidc.ManagedGroupPrefix),
|
||||
Item: &pb.ManagedGroup{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
Name: &wrapperspb.StringValue{Value: "name"},
|
||||
Description: &wrapperspb.StringValue{Value: "desc"},
|
||||
Scope: &scopepb.ScopeInfo{Id: o.GetPublicId(), Type: scope.Org.String(), ParentScopeId: scope.Global.String()},
|
||||
Version: 1,
|
||||
Type: auth.OidcSubtype.String(),
|
||||
Attributes: func() *structpb.Struct {
|
||||
a := createAttr()
|
||||
a.Fields["filter"] = structpb.NewStringValue(testFakeManagedGroupFilter)
|
||||
return a
|
||||
}(),
|
||||
AuthorizedActions: oidcAuthorizedActions,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Create a valid ManagedGroup without type defined",
|
||||
req: &pbs.CreateManagedGroupRequest{
|
||||
Item: &pb.ManagedGroup{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
Attributes: createAttr(),
|
||||
},
|
||||
},
|
||||
res: &pbs.CreateManagedGroupResponse{
|
||||
Uri: fmt.Sprintf("managed-groups/%s_", oidc.ManagedGroupPrefix),
|
||||
Item: &pb.ManagedGroup{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
Scope: &scopepb.ScopeInfo{Id: o.GetPublicId(), Type: scope.Org.String(), ParentScopeId: scope.Global.String()},
|
||||
Version: 1,
|
||||
Type: auth.OidcSubtype.String(),
|
||||
Attributes: func() *structpb.Struct {
|
||||
a := createAttr()
|
||||
a.Fields["filter"] = structpb.NewStringValue(testFakeManagedGroupFilter)
|
||||
return a
|
||||
}(),
|
||||
AuthorizedActions: oidcAuthorizedActions,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Cant specify mismatching type",
|
||||
req: &pbs.CreateManagedGroupRequest{
|
||||
Item: &pb.ManagedGroup{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
Type: auth.PasswordSubtype.String(),
|
||||
Attributes: createAttr(),
|
||||
},
|
||||
},
|
||||
res: nil,
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Can't specify Id",
|
||||
req: &pbs.CreateManagedGroupRequest{
|
||||
Item: &pb.ManagedGroup{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
Id: oidc.ManagedGroupPrefix + "_notallowed",
|
||||
Type: auth.OidcSubtype.String(),
|
||||
Attributes: createAttr(),
|
||||
},
|
||||
},
|
||||
res: nil,
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Can't specify Created Time",
|
||||
req: &pbs.CreateManagedGroupRequest{
|
||||
Item: &pb.ManagedGroup{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
CreatedTime: timestamppb.Now(),
|
||||
Type: auth.OidcSubtype.String(),
|
||||
Attributes: createAttr(),
|
||||
},
|
||||
},
|
||||
res: nil,
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Can't specify Update Time",
|
||||
req: &pbs.CreateManagedGroupRequest{
|
||||
Item: &pb.ManagedGroup{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
UpdatedTime: timestamppb.Now(),
|
||||
Type: auth.OidcSubtype.String(),
|
||||
Attributes: createAttr(),
|
||||
},
|
||||
},
|
||||
res: nil,
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Can't specify bad filter",
|
||||
req: &pbs.CreateManagedGroupRequest{
|
||||
Item: &pb.ManagedGroup{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
UpdatedTime: timestamppb.Now(),
|
||||
Type: auth.OidcSubtype.String(),
|
||||
Attributes: func() *structpb.Struct {
|
||||
a := createAttr()
|
||||
a.Fields["filter"] = structpb.NewStringValue("foobar")
|
||||
return a
|
||||
}(),
|
||||
},
|
||||
},
|
||||
res: nil,
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
got, gErr := s.CreateManagedGroup(auth.DisabledAuthTestContext(iamRepoFn, o.GetPublicId()), tc.req)
|
||||
if tc.err != nil {
|
||||
require.Error(gErr)
|
||||
assert.True(errors.Is(gErr, tc.err), "CreateManagedGroup(%+v) got error %v, wanted %v", tc.req, gErr, tc.err)
|
||||
return
|
||||
}
|
||||
require.NoError(gErr)
|
||||
if got != nil {
|
||||
assert.Contains(got.GetUri(), tc.res.Uri)
|
||||
assert.True(strings.HasPrefix(got.GetItem().GetId(), oidc.ManagedGroupPrefix+"_"))
|
||||
// Clear all values which are hard to compare against.
|
||||
got.Uri, tc.res.Uri = "", ""
|
||||
got.Item.Id, tc.res.Item.Id = "", ""
|
||||
got.Item.CreatedTime, got.Item.UpdatedTime, tc.res.Item.CreatedTime, tc.res.Item.UpdatedTime = nil, nil, nil, nil
|
||||
}
|
||||
assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform()), "CreateManagedGroup(%q) got response %q, wanted %q", tc.req, got, tc.res)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateOidc(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
rw := db.New(conn)
|
||||
wrap := db.TestWrapper(t)
|
||||
kmsCache := kms.TestKms(t, conn, wrap)
|
||||
oidcRepoFn := func() (*oidc.Repository, error) {
|
||||
return oidc.NewRepository(rw, rw, kmsCache)
|
||||
}
|
||||
iamRepoFn := func() (*iam.Repository, error) {
|
||||
return iam.NewRepository(rw, rw, kmsCache)
|
||||
}
|
||||
|
||||
o, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrap))
|
||||
|
||||
databaseWrapper, err := kmsCache.GetWrapper(ctx, o.PublicId, kms.KeyPurposeDatabase)
|
||||
require.NoError(t, err)
|
||||
am := oidc.TestAuthMethod(
|
||||
t, conn, databaseWrapper, o.PublicId, oidc.ActivePrivateState,
|
||||
"alice-rp", "fido",
|
||||
oidc.WithIssuer(oidc.TestConvertToUrls(t, "https://www.alice.com")[0]),
|
||||
oidc.WithSigningAlgs(oidc.RS256),
|
||||
oidc.WithApiUrl(oidc.TestConvertToUrls(t, "https://www.alice.com/callback")[0]))
|
||||
|
||||
tested, err := managed_groups.NewService(oidcRepoFn)
|
||||
require.NoError(t, err, "Error when getting new managed_groups service.")
|
||||
|
||||
defaultScopeInfo := &scopepb.ScopeInfo{Id: o.GetPublicId(), Type: o.GetType(), ParentScopeId: scope.Global.String()}
|
||||
defaultAttributes := &structpb.Struct{Fields: map[string]*structpb.Value{
|
||||
"filter": structpb.NewStringValue(testFakeManagedGroupFilter),
|
||||
}}
|
||||
|
||||
modifiedFilter := `"/token/zip" == "zap"`
|
||||
modifiedAttributes := &structpb.Struct{Fields: map[string]*structpb.Value{
|
||||
"filter": structpb.NewStringValue(modifiedFilter),
|
||||
}}
|
||||
|
||||
badFilter := `"foobar"`
|
||||
badAttributes := &structpb.Struct{Fields: map[string]*structpb.Value{
|
||||
"filter": structpb.NewStringValue(badFilter),
|
||||
}}
|
||||
|
||||
freshManagedGroup := func(t *testing.T) (*oidc.ManagedGroup, func()) {
|
||||
t.Helper()
|
||||
mg := oidc.TestManagedGroup(t, conn, am, testFakeManagedGroupFilter, oidc.WithName("default"), oidc.WithDescription("default"))
|
||||
|
||||
clean := func() {
|
||||
_, err := tested.DeleteManagedGroup(auth.DisabledAuthTestContext(iamRepoFn, o.GetPublicId()),
|
||||
&pbs.DeleteManagedGroupRequest{Id: mg.GetPublicId()})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
return mg, clean
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
req *pbs.UpdateManagedGroupRequest
|
||||
res *pbs.UpdateManagedGroupResponse
|
||||
err error
|
||||
}{
|
||||
{
|
||||
name: "Update an Existing AuthMethod",
|
||||
req: &pbs.UpdateManagedGroupRequest{
|
||||
UpdateMask: &field_mask.FieldMask{
|
||||
Paths: []string{globals.NameField, globals.DescriptionField},
|
||||
},
|
||||
Item: &pb.ManagedGroup{
|
||||
Name: &wrapperspb.StringValue{Value: "new"},
|
||||
Description: &wrapperspb.StringValue{Value: "desc"},
|
||||
Type: auth.OidcSubtype.String(),
|
||||
},
|
||||
},
|
||||
res: &pbs.UpdateManagedGroupResponse{
|
||||
Item: &pb.ManagedGroup{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
Name: &wrapperspb.StringValue{Value: "new"},
|
||||
Description: &wrapperspb.StringValue{Value: "desc"},
|
||||
Type: auth.OidcSubtype.String(),
|
||||
Attributes: defaultAttributes,
|
||||
Scope: defaultScopeInfo,
|
||||
AuthorizedActions: oidcAuthorizedActions,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Multiple Paths in single string",
|
||||
req: &pbs.UpdateManagedGroupRequest{
|
||||
UpdateMask: &field_mask.FieldMask{
|
||||
Paths: []string{"name,description"},
|
||||
},
|
||||
Item: &pb.ManagedGroup{
|
||||
Name: &wrapperspb.StringValue{Value: "new"},
|
||||
Description: &wrapperspb.StringValue{Value: "desc"},
|
||||
Type: auth.OidcSubtype.String(),
|
||||
},
|
||||
},
|
||||
res: &pbs.UpdateManagedGroupResponse{
|
||||
Item: &pb.ManagedGroup{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
Name: &wrapperspb.StringValue{Value: "new"},
|
||||
Description: &wrapperspb.StringValue{Value: "desc"},
|
||||
Type: auth.OidcSubtype.String(),
|
||||
Attributes: defaultAttributes,
|
||||
Scope: defaultScopeInfo,
|
||||
AuthorizedActions: oidcAuthorizedActions,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "No Update Mask",
|
||||
req: &pbs.UpdateManagedGroupRequest{
|
||||
Item: &pb.ManagedGroup{
|
||||
Name: &wrapperspb.StringValue{Value: "updated name"},
|
||||
Description: &wrapperspb.StringValue{Value: "updated desc"},
|
||||
Attributes: modifiedAttributes,
|
||||
},
|
||||
},
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Cant change type",
|
||||
req: &pbs.UpdateManagedGroupRequest{
|
||||
UpdateMask: &field_mask.FieldMask{
|
||||
Paths: []string{globals.NameField},
|
||||
},
|
||||
Item: &pb.ManagedGroup{
|
||||
Name: &wrapperspb.StringValue{Value: ""},
|
||||
Type: "oidc",
|
||||
},
|
||||
},
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "No Paths in Mask",
|
||||
req: &pbs.UpdateManagedGroupRequest{
|
||||
UpdateMask: &field_mask.FieldMask{Paths: []string{}},
|
||||
Item: &pb.ManagedGroup{
|
||||
Name: &wrapperspb.StringValue{Value: "updated name"},
|
||||
Description: &wrapperspb.StringValue{Value: "updated desc"},
|
||||
Attributes: modifiedAttributes,
|
||||
},
|
||||
},
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Only non-existant paths in Mask",
|
||||
req: &pbs.UpdateManagedGroupRequest{
|
||||
UpdateMask: &field_mask.FieldMask{Paths: []string{"nonexistant_field"}},
|
||||
Item: &pb.ManagedGroup{
|
||||
Name: &wrapperspb.StringValue{Value: "updated name"},
|
||||
Description: &wrapperspb.StringValue{Value: "updated desc"},
|
||||
Attributes: modifiedAttributes,
|
||||
},
|
||||
},
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Unset Name",
|
||||
req: &pbs.UpdateManagedGroupRequest{
|
||||
UpdateMask: &field_mask.FieldMask{
|
||||
Paths: []string{globals.NameField},
|
||||
},
|
||||
Item: &pb.ManagedGroup{
|
||||
Description: &wrapperspb.StringValue{Value: "ignored"},
|
||||
Attributes: modifiedAttributes,
|
||||
},
|
||||
},
|
||||
res: &pbs.UpdateManagedGroupResponse{
|
||||
Item: &pb.ManagedGroup{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
Description: &wrapperspb.StringValue{Value: "default"},
|
||||
Type: auth.OidcSubtype.String(),
|
||||
Attributes: defaultAttributes,
|
||||
Scope: defaultScopeInfo,
|
||||
AuthorizedActions: oidcAuthorizedActions,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Update Only Name",
|
||||
req: &pbs.UpdateManagedGroupRequest{
|
||||
UpdateMask: &field_mask.FieldMask{
|
||||
Paths: []string{globals.NameField},
|
||||
},
|
||||
Item: &pb.ManagedGroup{
|
||||
Name: &wrapperspb.StringValue{Value: "updated"},
|
||||
Description: &wrapperspb.StringValue{Value: "ignored"},
|
||||
Attributes: modifiedAttributes,
|
||||
},
|
||||
},
|
||||
res: &pbs.UpdateManagedGroupResponse{
|
||||
Item: &pb.ManagedGroup{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
Name: &wrapperspb.StringValue{Value: "updated"},
|
||||
Description: &wrapperspb.StringValue{Value: "default"},
|
||||
Type: auth.OidcSubtype.String(),
|
||||
Attributes: defaultAttributes,
|
||||
Scope: defaultScopeInfo,
|
||||
AuthorizedActions: oidcAuthorizedActions,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Update Only Description",
|
||||
req: &pbs.UpdateManagedGroupRequest{
|
||||
UpdateMask: &field_mask.FieldMask{
|
||||
Paths: []string{globals.DescriptionField},
|
||||
},
|
||||
Item: &pb.ManagedGroup{
|
||||
Name: &wrapperspb.StringValue{Value: "ignored"},
|
||||
Description: &wrapperspb.StringValue{Value: "notignored"},
|
||||
Attributes: modifiedAttributes,
|
||||
},
|
||||
},
|
||||
res: &pbs.UpdateManagedGroupResponse{
|
||||
Item: &pb.ManagedGroup{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
Name: &wrapperspb.StringValue{Value: "default"},
|
||||
Description: &wrapperspb.StringValue{Value: "notignored"},
|
||||
Type: auth.OidcSubtype.String(),
|
||||
Attributes: defaultAttributes,
|
||||
Scope: defaultScopeInfo,
|
||||
AuthorizedActions: oidcAuthorizedActions,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Update a Non Existing ManagedGroup",
|
||||
req: &pbs.UpdateManagedGroupRequest{
|
||||
Id: oidc.ManagedGroupPrefix + "_DoesntExis",
|
||||
UpdateMask: &field_mask.FieldMask{
|
||||
Paths: []string{globals.DescriptionField},
|
||||
},
|
||||
Item: &pb.ManagedGroup{
|
||||
Name: &wrapperspb.StringValue{Value: "new"},
|
||||
Description: &wrapperspb.StringValue{Value: "desc"},
|
||||
},
|
||||
},
|
||||
err: handlers.ApiErrorWithCode(codes.NotFound),
|
||||
},
|
||||
{
|
||||
name: "Cant change Id",
|
||||
req: &pbs.UpdateManagedGroupRequest{
|
||||
UpdateMask: &field_mask.FieldMask{
|
||||
Paths: []string{"id"},
|
||||
},
|
||||
Item: &pb.ManagedGroup{
|
||||
Id: oidc.ManagedGroupPrefix + "_somethinge",
|
||||
Name: &wrapperspb.StringValue{Value: "new"},
|
||||
Description: &wrapperspb.StringValue{Value: "new desc"},
|
||||
},
|
||||
},
|
||||
res: nil,
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Cant specify Created Time",
|
||||
req: &pbs.UpdateManagedGroupRequest{
|
||||
UpdateMask: &field_mask.FieldMask{
|
||||
Paths: []string{"created_time"},
|
||||
},
|
||||
Item: &pb.ManagedGroup{
|
||||
CreatedTime: timestamppb.Now(),
|
||||
},
|
||||
},
|
||||
res: nil,
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Cant specify Updated Time",
|
||||
req: &pbs.UpdateManagedGroupRequest{
|
||||
UpdateMask: &field_mask.FieldMask{
|
||||
Paths: []string{"updated_time"},
|
||||
},
|
||||
Item: &pb.ManagedGroup{
|
||||
UpdatedTime: timestamppb.Now(),
|
||||
},
|
||||
},
|
||||
res: nil,
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Cant specify Type",
|
||||
req: &pbs.UpdateManagedGroupRequest{
|
||||
UpdateMask: &field_mask.FieldMask{
|
||||
Paths: []string{"type"},
|
||||
},
|
||||
Item: &pb.ManagedGroup{
|
||||
Type: "oidc",
|
||||
},
|
||||
},
|
||||
res: nil,
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Update Filter with Bad Value",
|
||||
req: &pbs.UpdateManagedGroupRequest{
|
||||
UpdateMask: &field_mask.FieldMask{
|
||||
Paths: []string{"attributes.filter"},
|
||||
},
|
||||
Item: &pb.ManagedGroup{
|
||||
Attributes: badAttributes,
|
||||
},
|
||||
},
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Update Filter With Good Value",
|
||||
req: &pbs.UpdateManagedGroupRequest{
|
||||
UpdateMask: &field_mask.FieldMask{
|
||||
Paths: []string{"attributes.filter"},
|
||||
},
|
||||
Item: &pb.ManagedGroup{
|
||||
Attributes: modifiedAttributes,
|
||||
},
|
||||
},
|
||||
res: &pbs.UpdateManagedGroupResponse{
|
||||
Item: &pb.ManagedGroup{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
Name: &wrapperspb.StringValue{Value: "default"},
|
||||
Description: &wrapperspb.StringValue{Value: "default"},
|
||||
Type: auth.OidcSubtype.String(),
|
||||
Attributes: modifiedAttributes,
|
||||
Scope: defaultScopeInfo,
|
||||
AuthorizedActions: oidcAuthorizedActions,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
mg, cleanup := freshManagedGroup(t)
|
||||
defer cleanup()
|
||||
|
||||
tc.req.Item.Version = 1
|
||||
|
||||
if tc.req.GetId() == "" {
|
||||
tc.req.Id = mg.GetPublicId()
|
||||
}
|
||||
|
||||
if tc.res != nil && tc.res.Item != nil {
|
||||
tc.res.Item.Id = mg.GetPublicId()
|
||||
tc.res.Item.CreatedTime = mg.GetCreateTime().GetTimestamp()
|
||||
}
|
||||
|
||||
got, gErr := tested.UpdateManagedGroup(auth.DisabledAuthTestContext(iamRepoFn, o.GetPublicId()), tc.req)
|
||||
if tc.err != nil {
|
||||
require.Error(gErr)
|
||||
assert.True(errors.Is(gErr, tc.err), "UpdateManagedGroup(%+v) got error %v, wanted %v", tc.req, gErr, tc.err)
|
||||
}
|
||||
|
||||
if tc.res == nil {
|
||||
require.Nil(got)
|
||||
}
|
||||
|
||||
if got != nil {
|
||||
assert.NotNilf(tc.res, "Expected UpdateManagedGroup response to be nil, but was %v", got)
|
||||
gotUpdateTime := got.GetItem().GetUpdatedTime()
|
||||
require.NoError(err, "Error converting proto to timestamp")
|
||||
|
||||
created := mg.GetCreateTime().GetTimestamp()
|
||||
require.NoError(err, "Error converting proto to timestamp")
|
||||
|
||||
// Verify it is a auth_method updated after it was created
|
||||
assert.True(gotUpdateTime.AsTime().After(created.AsTime()), "Updated account should have been updated after it's creation. Was updated %v, which is after %v", gotUpdateTime, created)
|
||||
|
||||
// Clear all values which are hard to compare against.
|
||||
got.Item.UpdatedTime, tc.res.Item.UpdatedTime = nil, nil
|
||||
|
||||
assert.EqualValues(2, got.Item.Version)
|
||||
tc.res.Item.Version = 2
|
||||
}
|
||||
assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform()), "UpdateManagedGroup(%q) got response %q, wanted %q", tc.req, got, tc.res)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package managed_groups
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/hashicorp/boundary/globals"
|
||||
"github.com/hashicorp/boundary/internal/auth"
|
||||
"github.com/hashicorp/boundary/internal/auth/oidc"
|
||||
pb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/managedgroups"
|
||||
pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/protobuf/types/known/fieldmaskpb"
|
||||
"google.golang.org/protobuf/types/known/structpb"
|
||||
)
|
||||
|
||||
func fieldError(field, details string) string {
|
||||
return fmt.Sprintf(`{name: %q, desc: %q}`, field, details)
|
||||
}
|
||||
|
||||
func TestValidateCreateRequest(t *testing.T) {
|
||||
t.Parallel()
|
||||
cases := []struct {
|
||||
name string
|
||||
item *pb.ManagedGroup
|
||||
errContains string
|
||||
}{
|
||||
{
|
||||
name: "unrecognized authmethod prefix",
|
||||
item: &pb.ManagedGroup{
|
||||
AuthMethodId: "anything_1234567890",
|
||||
},
|
||||
errContains: fieldError(globals.AuthMethodIdField, "Unknown auth method type from ID."),
|
||||
},
|
||||
{
|
||||
name: "mismatched oidc authmethod pw type",
|
||||
item: &pb.ManagedGroup{
|
||||
Type: "ldap",
|
||||
AuthMethodId: oidc.AuthMethodPrefix + "_1234567890",
|
||||
},
|
||||
errContains: fieldError(globals.TypeField, "Doesn't match the parent resource's type."),
|
||||
},
|
||||
{
|
||||
name: "missing oidc attributes",
|
||||
item: &pb.ManagedGroup{
|
||||
Type: auth.OidcSubtype.String(),
|
||||
AuthMethodId: oidc.AuthMethodPrefix + "_1234567890",
|
||||
Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{}},
|
||||
},
|
||||
errContains: fieldError(attrFilterField, "This field is required."),
|
||||
},
|
||||
{
|
||||
name: "bad oidc attributes",
|
||||
item: &pb.ManagedGroup{
|
||||
Type: auth.OidcSubtype.String(),
|
||||
AuthMethodId: oidc.AuthMethodPrefix + "_1234567890",
|
||||
Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{
|
||||
"filter": structpb.NewStringValue("foobar"),
|
||||
}},
|
||||
},
|
||||
errContains: "Error evaluating submitted filter",
|
||||
},
|
||||
{
|
||||
name: "no oidc errors",
|
||||
item: &pb.ManagedGroup{
|
||||
Type: auth.OidcSubtype.String(),
|
||||
AuthMethodId: oidc.AuthMethodPrefix + "_1234567890",
|
||||
Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{
|
||||
"filter": structpb.NewStringValue(`"/foo/bar" == "zipzap"`),
|
||||
}},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
req := &pbs.CreateManagedGroupRequest{Item: tc.item}
|
||||
err := validateCreateRequest(req)
|
||||
if tc.errContains == "" {
|
||||
require.NoError(t, err)
|
||||
return
|
||||
}
|
||||
assert.True(t, strings.Contains(err.Error(), tc.errContains),
|
||||
"%q wasn't contained in %q", tc.errContains, err.Error())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateUpdateRequest(t *testing.T) {
|
||||
t.Parallel()
|
||||
cases := []struct {
|
||||
name string
|
||||
req *pbs.UpdateManagedGroupRequest
|
||||
errContains string
|
||||
}{
|
||||
{
|
||||
name: "oidc to password change type",
|
||||
req: &pbs.UpdateManagedGroupRequest{
|
||||
Id: oidc.ManagedGroupPrefix + "_1234567890",
|
||||
Item: &pb.ManagedGroup{
|
||||
Type: auth.PasswordSubtype.String(),
|
||||
},
|
||||
},
|
||||
errContains: fieldError(globals.TypeField, "Cannot modify the resource type."),
|
||||
},
|
||||
{
|
||||
name: "oidc bad attributes",
|
||||
req: &pbs.UpdateManagedGroupRequest{
|
||||
Id: oidc.ManagedGroupPrefix + "_1234567890",
|
||||
Item: &pb.ManagedGroup{
|
||||
Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{
|
||||
"test": structpb.NewStringValue("something"),
|
||||
}},
|
||||
},
|
||||
},
|
||||
errContains: fieldError(globals.AttributesField, "Attribute fields do not match the expected format."),
|
||||
},
|
||||
{
|
||||
name: "no error",
|
||||
req: &pbs.UpdateManagedGroupRequest{
|
||||
Id: oidc.ManagedGroupPrefix + "_1234567890",
|
||||
UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{}},
|
||||
Item: &pb.ManagedGroup{
|
||||
Version: 1,
|
||||
Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{
|
||||
"filter": structpb.NewStringValue(`"/foo/bar" == "zipzap"`),
|
||||
}},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
err := validateUpdateRequest(tc.req)
|
||||
if tc.errContains == "" {
|
||||
require.NoError(t, err)
|
||||
return
|
||||
}
|
||||
assert.True(t, strings.Contains(err.Error(), tc.errContains),
|
||||
"%q wasn't contained in %q", tc.errContains, err.Error())
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -60,4 +60,16 @@ func Test_GetOpts(t *testing.T) {
|
||||
require.NotNil(opts.WithOutputFields)
|
||||
assert.Nil(*opts.WithOutputFields)
|
||||
})
|
||||
t.Run("WithManagedGroupIds", func(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
require := require.New(t)
|
||||
|
||||
opts := GetOpts()
|
||||
assert.Nil(opts.WithManagedGroupIds)
|
||||
|
||||
out := []string{"foobar"}
|
||||
|
||||
opts = GetOpts(WithManagedGroupIds(out))
|
||||
require.Equal(out, opts.WithManagedGroupIds)
|
||||
})
|
||||
}
|
||||
@@ -30,6 +30,7 @@ type options struct {
|
||||
WithScope *scopes.ScopeInfo
|
||||
WithAuthorizedActions []string
|
||||
WithAuthorizedCollectionActions map[string]*structpb.ListValue
|
||||
WithManagedGroupIds []string
|
||||
}
|
||||
|
||||
func getDefaultOptions() options {
|
||||
@@ -91,3 +92,11 @@ func WithAuthorizedCollectionActions(colActs map[string]*structpb.ListValue) Opt
|
||||
o.WithAuthorizedCollectionActions = colActs
|
||||
}
|
||||
}
|
||||
|
||||
// WithManagedGroupIds provides an option when creating responses to include the given
|
||||
// managed group IDs if allowed
|
||||
func WithManagedGroupIds(ids []string) Option {
|
||||
return func(o *options) {
|
||||
o.WithManagedGroupIds = ids
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user