Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix: not count deleted principal (#20492)
ecmadaocbfc66995606
diff --git a/backend/api/v1/user_service.go b/backend/api/v1/user_service.goindex 7d1a41d6af..f67d4c5b63 100644--- a/backend/api/v1/user_service.go+++ b/backend/api/v1/user_service.go@@ -861,7 +861,9 @@ func generateRecoveryCodes(n int) ([]string, error) {// countUsersInIamPolicy counts distinct user members in an IAM policy,// expanding group memberships. When allUsers is present and not in SaaS mode,-// returns the total active principal count instead.+// returns the total active principal count instead. Soft-deleted principals do+// not occupy a seat, so emails whose principal is deleted are excluded; emails+// without a principal yet (e.g. pending SaaS invites) are still counted.func countUsersInIamPolicy(ctx context.Context, s *store.Store, workspaceID string, policy *storepb.IamPolicy, saas bool) (int, error) {emails := make(map[string]struct{})var groupRefs []string@@ -874,7 +876,9 @@ func countUsersInIamPolicy(ctx context.Context, s *store.Store, workspaceID stricontinue}if strings.HasPrefix(member, "users/") {- emails[strings.TrimPrefix(member, "users/")] = struct{}{}+ // Principal emails are stored lower-cased, but IAM members may keep+ // mixed casing; normalize so dedup and the deleted lookup below match.+ emails[strings.ToLower(strings.TrimPrefix(member, "users/"))] = struct{}{}} else if strings.HasPrefix(member, "groups/") {groupRefs = append(groupRefs, strings.TrimPrefix(member, "groups/"))}@@ -884,11 +888,32 @@ func countUsersInIamPolicy(ctx context.Context, s *store.Store, workspaceID strimembers, _ := s.GetGroupMembersSnapshot(ctx, workspaceID, "groups/"+ref)for member := range members {if strings.HasPrefix(member, "users/") {- emails[strings.TrimPrefix(member, "users/")] = struct{}{}+ emails[strings.ToLower(strings.TrimPrefix(member, "users/"))] = struct{}{}}}}- return len(emails), nil+ if len(emails) == 0 {+ return 0, nil+ }+ emailList := make([]string, 0, len(emails))+ for email := range emails {+ emailList = append(emailList, email)+ }+ // Pass an empty workspace to look up principals by email only: the seat set is+ // already derived from policy, we just need each principal's deleted state.+ users, err := s.BatchGetUsersByEmails(ctx, "", emailList)+ if err != nil {+ return 0, errors.Wrapf(err, "failed to batch get users by emails")+ }+ deleted := 0+ for _, user := range users {+ if user.MemberDeleted {+ if _, ok := emails[user.Email]; ok {+ deleted+++ }+ }+ }+ return len(emails) - deleted, nil}// userCountGuard checks seat limits before adding a new IAM member (e.g. SSO login).diff --git a/backend/api/v1/workspace_service.go b/backend/api/v1/workspace_service.goindex 88681bce88..2ad9a8ff64 100644--- a/backend/api/v1/workspace_service.go+++ b/backend/api/v1/workspace_service.go@@ -401,8 +401,11 @@ func (s *WorkspaceService) SetIamPolicy(ctx context.Context, req *connect.Requesreturn nil, connect.NewError(connect.CodeInvalidArgument, errors.New("workspace must have at least one admin"))}- // Guard: count members in the new policy BEFORE saving.- // Allow over-limit workspaces to reduce seats incrementally (e.g. after license downgrade).+ // Guard: count user seats in the new policy BEFORE saving. Only reject when this+ // change increases the user seat count beyond the limit. Over-limit workspaces (e.g.+ // after a license downgrade) may still hold steady or reduce seats, and seat-neutral+ // edits such as adding a service account or workload identity are always allowed+ // because those members do not occupy a seat.userLimit := s.licenseService.GetUserLimit(ctx, workspaceID)newCount, err := countUsersInIamPolicy(ctx, s.store, workspaceID, iamPolicy, s.profile.SaaS)if err != nil {@@ -413,7 +416,7 @@ func (s *WorkspaceService) SetIamPolicy(ctx context.Context, req *connect.Requesif err != nil {return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to count users in current IAM policy"))}- if newCount >= oldCount {+ if newCount > oldCount {return nil, connect.NewError(connect.CodeResourceExhausted, errors.Errorf("workspace has %d users, exceeding the limit of %d", newCount, userLimit))}}diff --git a/backend/tests/user_test.go b/backend/tests/user_test.goindex 5a9c83298a..78085f5a7c 100644--- a/backend/tests/user_test.go+++ b/backend/tests/user_test.go@@ -125,6 +125,149 @@ func TestDeleteUser(t *testing.T) {a.NoError(err)}+// TestSeatCountExcludesDeletedPrincipal verifies a soft-deleted principal stops+// occupying a seat even though its IAM binding lingers, while a pending member+// (in IAM, no principal) still counts.+func TestSeatCountExcludesDeletedPrincipal(t *testing.T) {+ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)++ workspaceInfo := func() int32 {+ actuator, err := ctl.actuatorServiceClient.GetActuatorInfo(ctx, connect.NewRequest(&v1pb.GetActuatorInfoRequest{}))+ a.NoError(err)+ return actuator.Msg.UserCountInIam+ }++ base := workspaceInfo()++ memberResp, err := ctl.userServiceClient.CreateUser(ctx, connect.NewRequest(&v1pb.CreateUserRequest{+ User: &v1pb.User{+ Title: "member",+ Email: "[email protected]",+ Password: "1024bytebase",+ },+ }))+ a.NoError(err)+ member := memberResp.Msg++ // Creating a principal alone does not occupy a seat until added to IAM.+ a.Equal(base, workspaceInfo())++ _, err = ctl.addMemberToWorkspaceIAM(ctx, member.Workspace, fmt.Sprintf("user:%v", member.Email), "roles/workspaceAdmin")+ a.NoError(err)+ a.Equal(base+1, workspaceInfo())++ // Soft-deleting the member releases the seat even though the IAM binding remains.+ _, err = ctl.userServiceClient.DeleteUser(ctx, connect.NewRequest(&v1pb.DeleteUserRequest{+ Name: member.Name,+ }))+ a.NoError(err)+ a.Equal(base, workspaceInfo())++ // Undeleting re-occupies the seat.+ _, err = ctl.userServiceClient.UndeleteUser(ctx, connect.NewRequest(&v1pb.UndeleteUserRequest{+ Name: member.Name,+ }))+ a.NoError(err)+ a.Equal(base+1, workspaceInfo())+}++// TestSeatLimitAllowsServiceAccountWhenOverLimit verifies that an over-limit+// workspace can still add a seat-neutral member (service account / workload+// identity) to its IAM, while adding another end user remains blocked.+func TestSeatLimitAllowsServiceAccountWhenOverLimit(t *testing.T) {+ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)++ const freeSeatLimit = 20++ // Seed users beyond the FREE seat limit using an unlimited license, then drop the+ // license so the workspace becomes over-limit on the FREE plan.+ a.NoError(ctl.setLicense(ctx))++ actuator, err := ctl.actuatorServiceClient.GetActuatorInfo(ctx, connect.NewRequest(&v1pb.GetActuatorInfoRequest{}))+ a.NoError(err)+ workspace := actuator.Msg.Workspace++ memberEmails := make([]string, 0, freeSeatLimit+1)+ for i := 0; i <= freeSeatLimit; i++ {+ resp, err := ctl.userServiceClient.CreateUser(ctx, connect.NewRequest(&v1pb.CreateUserRequest{+ User: &v1pb.User{+ Title: fmt.Sprintf("member-%d", i),+ Email: fmt.Sprintf("member-%[email protected]", i),+ Password: "1024bytebase",+ },+ }))+ a.NoError(err)+ memberEmails = append(memberEmails, resp.Msg.Email)+ }++ // Create the service account and overflow user while licensed; only the IAM+ // mutations below are exercised against the FREE limit.+ saResp, err := ctl.serviceAccountServiceClient.CreateServiceAccount(ctx, connect.NewRequest(&v1pb.CreateServiceAccountRequest{+ Parent: workspace,+ ServiceAccountId: "bot",+ ServiceAccount: &v1pb.ServiceAccount{Title: "bot"},+ }))+ a.NoError(err)+ overflowResp, err := ctl.userServiceClient.CreateUser(ctx, connect.NewRequest(&v1pb.CreateUserRequest{+ User: &v1pb.User{+ Title: "overflow",+ Email: "[email protected]",+ Password: "1024bytebase",+ },+ }))+ a.NoError(err)++ // Add all seed users to the workspace IAM (allowed: license is unlimited).+ policyResp, err := ctl.workspaceServiceClient.GetIamPolicy(ctx, connect.NewRequest(&v1pb.GetIamPolicyRequest{Resource: workspace}))+ a.NoError(err)+ policy := policyResp.Msg+ var memberBinding *v1pb.Binding+ for _, binding := range policy.Bindings {+ if binding.Role == "roles/workspaceMember" {+ memberBinding = binding+ break+ }+ }+ if memberBinding == nil {+ memberBinding = &v1pb.Binding{Role: "roles/workspaceMember"}+ policy.Bindings = append(policy.Bindings, memberBinding)+ }+ for _, email := range memberEmails {+ memberBinding.Members = append(memberBinding.Members, fmt.Sprintf("user:%s", email))+ }+ _, err = ctl.workspaceServiceClient.SetIamPolicy(ctx, connect.NewRequest(&v1pb.SetIamPolicyRequest{+ Etag: policy.Etag,+ Policy: policy,+ Resource: workspace,+ }))+ a.NoError(err)++ // Drop the license: the FREE limit now applies and the workspace is over limit.+ a.NoError(ctl.removeLicense(ctx))+ overLimit, err := ctl.actuatorServiceClient.GetActuatorInfo(ctx, connect.NewRequest(&v1pb.GetActuatorInfoRequest{}))+ a.NoError(err)+ a.Greater(overLimit.Msg.UserCountInIam, int32(freeSeatLimit))++ // A seat-neutral member (service account) can still be added while over limit.+ _, err = ctl.addMemberToWorkspaceIAM(ctx, workspace, fmt.Sprintf("serviceAccount:%s", saResp.Msg.Email), "roles/workspaceMember")+ a.NoError(err)++ // Adding another end user must still be rejected.+ _, err = ctl.addMemberToWorkspaceIAM(ctx, workspace, fmt.Sprintf("user:%s", overflowResp.Msg.Email), "roles/workspaceMember")+ a.Error(err)+ a.ErrorContains(err, "exceeding the limit")+}+func TestUpdateUserEmail(t *testing.T) {a := require.New(t)ctx := context.Background()