Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: implement comprehensive email update with cascade for all user references (#18427)
Danny Xufafc73c6139c
diff --git a/backend/api/v1/user_service.go b/backend/api/v1/user_service.goindex be5f85497f..7cb01cdd8e 100644--- a/backend/api/v1/user_service.go+++ b/backend/api/v1/user_service.go@@ -731,7 +731,7 @@ func (s *UserService) UpdateEmail(ctx context.Context, request *connect.Request[}// Update the email- user, err = s.store.UpdateUser(ctx, user, &store.UpdateUserMessage{Email: &request.Msg.Email})+ user, err = s.store.UpdateUserEmail(ctx, user, request.Msg.Email)if err != nil {return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to update user email, error: %v", err))}diff --git a/backend/migrator/migration/3.13/0023##cascade_update_user_email.sql b/backend/migrator/migration/3.13/0023##cascade_update_user_email.sqlnew file mode 100644index 0000000000..47c47cd552--- /dev/null+++ b/backend/migrator/migration/3.13/0023##cascade_update_user_email.sql@@ -0,0 +1,45 @@+-- Add ON UPDATE CASCADE to user email foreign keys++-- 1. sheet+ALTER TABLE sheet DROP CONSTRAINT IF EXISTS sheet_creator_fkey;+ALTER TABLE sheet ADD CONSTRAINT sheet_creator_fkey FOREIGN KEY (creator) REFERENCES principal(email) ON UPDATE CASCADE;++-- 2. pipeline+ALTER TABLE pipeline DROP CONSTRAINT IF EXISTS pipeline_creator_fkey;+ALTER TABLE pipeline ADD CONSTRAINT pipeline_creator_fkey FOREIGN KEY (creator) REFERENCES principal(email) ON UPDATE CASCADE;++-- 3. task_run+ALTER TABLE task_run DROP CONSTRAINT IF EXISTS task_run_creator_fkey;+ALTER TABLE task_run ADD CONSTRAINT task_run_creator_fkey FOREIGN KEY (creator) REFERENCES principal(email) ON UPDATE CASCADE;++-- 4. plan+ALTER TABLE plan DROP CONSTRAINT IF EXISTS plan_creator_fkey;+ALTER TABLE plan ADD CONSTRAINT plan_creator_fkey FOREIGN KEY (creator) REFERENCES principal(email) ON UPDATE CASCADE;++-- 5. issue+ALTER TABLE issue DROP CONSTRAINT IF EXISTS issue_creator_fkey;+ALTER TABLE issue ADD CONSTRAINT issue_creator_fkey FOREIGN KEY (creator) REFERENCES principal(email) ON UPDATE CASCADE;++-- 6. issue_comment+ALTER TABLE issue_comment DROP CONSTRAINT IF EXISTS issue_comment_creator_fkey;+ALTER TABLE issue_comment ADD CONSTRAINT issue_comment_creator_fkey FOREIGN KEY (creator) REFERENCES principal(email) ON UPDATE CASCADE;++-- 7. query_history+ALTER TABLE query_history DROP CONSTRAINT IF EXISTS query_history_creator_fkey;+ALTER TABLE query_history ADD CONSTRAINT query_history_creator_fkey FOREIGN KEY (creator) REFERENCES principal(email) ON UPDATE CASCADE;++-- 8. worksheet+ALTER TABLE worksheet DROP CONSTRAINT IF EXISTS worksheet_creator_fkey;+ALTER TABLE worksheet ADD CONSTRAINT worksheet_creator_fkey FOREIGN KEY (creator) REFERENCES principal(email) ON UPDATE CASCADE;++-- 9. worksheet_organizer+ALTER TABLE worksheet_organizer DROP CONSTRAINT IF EXISTS worksheet_organizer_principal_fkey;+ALTER TABLE worksheet_organizer ADD CONSTRAINT worksheet_organizer_principal_fkey FOREIGN KEY (principal) REFERENCES principal(email) ON UPDATE CASCADE;++-- 10. revision+ALTER TABLE revision DROP CONSTRAINT IF EXISTS revision_deleter_fkey;+ALTER TABLE revision ADD CONSTRAINT revision_deleter_fkey FOREIGN KEY (deleter) REFERENCES principal(email) ON UPDATE CASCADE;++-- 11. release+ALTER TABLE release DROP CONSTRAINT IF EXISTS release_creator_fkey;+ALTER TABLE release ADD CONSTRAINT release_creator_fkey FOREIGN KEY (creator) REFERENCES principal(email) ON UPDATE CASCADE;diff --git a/backend/migrator/migration/LATEST.sql b/backend/migrator/migration/LATEST.sqlindex 5ff920d936..73c765711a 100644--- a/backend/migrator/migration/LATEST.sql+++ b/backend/migrator/migration/LATEST.sql@@ -176,7 +176,7 @@ CREATE TABLE sheet_blob (-- sheet table stores general statements.CREATE TABLE sheet (id serial PRIMARY KEY,- creator text NOT NULL REFERENCES principal(email),+ creator text NOT NULL REFERENCES principal(email) ON UPDATE CASCADE,created_at timestamptz NOT NULL DEFAULT now(),project text NOT NULL REFERENCES project(resource_id),name text NOT NULL,@@ -194,7 +194,7 @@ ALTER SEQUENCE sheet_id_seq RESTART WITH 101;-- pipeline tableCREATE TABLE pipeline (id serial PRIMARY KEY,- creator text NOT NULL REFERENCES principal(email),+ creator text NOT NULL REFERENCES principal(email) ON UPDATE CASCADE,created_at timestamptz NOT NULL DEFAULT now(),project text NOT NULL REFERENCES project(resource_id));@@ -220,7 +220,7 @@ ALTER SEQUENCE task_id_seq RESTART WITH 101;-- task run table stores the task runCREATE TABLE task_run (id serial PRIMARY KEY,- creator text NOT NULL REFERENCES principal(email),+ creator text NOT NULL REFERENCES principal(email) ON UPDATE CASCADE,created_at timestamptz NOT NULL DEFAULT now(),updated_at timestamptz NOT NULL DEFAULT now(),task_id integer NOT NULL REFERENCES task(id),@@ -264,7 +264,7 @@ ALTER SEQUENCE task_run_log_id_seq RESTART WITH 101;CREATE TABLE plan (id bigserial PRIMARY KEY,deleted boolean NOT NULL DEFAULT FALSE,- creator text NOT NULL REFERENCES principal(email),+ creator text NOT NULL REFERENCES principal(email) ON UPDATE CASCADE,created_at timestamptz NOT NULL DEFAULT now(),updated_at timestamptz NOT NULL DEFAULT now(),project text NOT NULL REFERENCES project(resource_id),@@ -306,7 +306,7 @@ ALTER SEQUENCE plan_check_run_id_seq RESTART WITH 101;-- issueCREATE TABLE issue (id serial PRIMARY KEY,- creator text NOT NULL REFERENCES principal(email),+ creator text NOT NULL REFERENCES principal(email) ON UPDATE CASCADE,created_at timestamptz NOT NULL DEFAULT now(),updated_at timestamptz NOT NULL DEFAULT now(),project text NOT NULL REFERENCES project(resource_id),@@ -363,7 +363,7 @@ ALTER SEQUENCE audit_log_id_seq RESTART WITH 101;CREATE TABLE issue_comment (id bigserial PRIMARY KEY,- creator text NOT NULL REFERENCES principal(email),+ creator text NOT NULL REFERENCES principal(email) ON UPDATE CASCADE,created_at timestamptz NOT NULL DEFAULT now(),updated_at timestamptz NOT NULL DEFAULT now(),issue_id integer NOT NULL REFERENCES issue(id),@@ -377,7 +377,7 @@ ALTER SEQUENCE issue_comment_id_seq RESTART WITH 101;CREATE TABLE query_history (id bigserial PRIMARY KEY,- creator text NOT NULL REFERENCES principal(email),+ creator text NOT NULL REFERENCES principal(email) ON UPDATE CASCADE,created_at timestamptz NOT NULL DEFAULT now(),project_id text NOT NULL, -- the project resource iddatabase text NOT NULL, -- the database resource name, for example, instances/{instance}/databases/{database}@@ -396,7 +396,7 @@ ALTER SEQUENCE query_history_id_seq RESTART WITH 101;-- worksheet table stores worksheets in SQL Editor.CREATE TABLE worksheet (id serial PRIMARY KEY,- creator text NOT NULL REFERENCES principal(email),+ creator text NOT NULL REFERENCES principal(email) ON UPDATE CASCADE,created_at timestamptz NOT NULL DEFAULT now(),updated_at timestamptz NOT NULL DEFAULT now(),project text NOT NULL REFERENCES project(resource_id),@@ -418,7 +418,7 @@ ALTER SEQUENCE worksheet_id_seq RESTART WITH 101;CREATE TABLE worksheet_organizer (id serial PRIMARY KEY,worksheet_id integer NOT NULL REFERENCES worksheet(id) ON DELETE CASCADE,- principal text NOT NULL REFERENCES principal(email),+ principal text NOT NULL REFERENCES principal(email) ON UPDATE CASCADE,payload jsonb NOT NULL DEFAULT '{}');@@ -476,7 +476,7 @@ CREATE TABLE revision (instance text NOT NULL,db_name text NOT NULL,created_at timestamptz NOT NULL DEFAULT now(),- deleter text REFERENCES principal(email),+ deleter text REFERENCES principal(email) ON UPDATE CASCADE,deleted_at timestamptz,version text NOT NULL,-- Stored as RevisionPayload (proto/store/store/revision.proto)@@ -526,7 +526,7 @@ CREATE TABLE release (id bigserial PRIMARY KEY,deleted boolean NOT NULL DEFAULT FALSE,project text NOT NULL REFERENCES project(resource_id),- creator text NOT NULL REFERENCES principal (email),+ creator text NOT NULL REFERENCES principal(email) ON UPDATE CASCADE,created_at timestamptz NOT NULL DEFAULT now(),digest text NOT NULL DEFAULT '',-- Stored as ReleasePayload (proto/store/store/release.proto)diff --git a/backend/migrator/migrator_test.go b/backend/migrator/migrator_test.goindex 285db2579d..ffb1b58c8d 100644--- a/backend/migrator/migrator_test.go+++ b/backend/migrator/migrator_test.go@@ -12,7 +12,7 @@ import (func TestLatestVersion(t *testing.T) {files, err := getSortedVersionedFiles()require.NoError(t, err)- require.Equal(t, semver.MustParse("3.13.22"), *files[len(files)-1].version)+ require.Equal(t, semver.MustParse("3.13.23"), *files[len(files)-1].version)}func TestVersionUnique(t *testing.T) {diff --git a/backend/store/principal.go b/backend/store/principal.goindex 6d80131afc..6584970177 100644--- a/backend/store/principal.go+++ b/backend/store/principal.go@@ -489,3 +489,340 @@ func (s *Store) UpdateUser(ctx context.Context, currentUser *UserMessage, patchs.userEmailCache.Add(user.Email, user)return user, nil}++// UpdateUserEmail updates a user's email and all related references.+func (s *Store) UpdateUserEmail(ctx context.Context, user *UserMessage, newEmail string) (*UserMessage, error) {+ newEmail = strings.ToLower(newEmail)++ // Fetch affected issues for cache invalidation later.+ // We need to fetch both issue ID and pipeline ID (via plan).+ // We do this before the transaction/update because finding by old creator is straightforward.+ issueQuery := qb.Q().Space(`+ SELECT+ issue.id,+ plan.pipeline_id+ FROM issue+ LEFT JOIN plan ON issue.plan_id = plan.id+ WHERE issue.creator = ?+ `, user.Email)+ issueSQL, issueArgs, err := issueQuery.ToSQL()+ if err != nil {+ return nil, errors.Wrapf(err, "failed to build select issue sql")+ }++ rows, err := s.GetDB().QueryContext(ctx, issueSQL, issueArgs...)+ if err != nil {+ return nil, errors.Wrapf(err, "failed to query affected issues")+ }+ defer rows.Close()++ type issueInvalidation struct {+ id int+ pipelineUID *int+ }+ var issuesToInvalidate []issueInvalidation+ for rows.Next() {+ var info issueInvalidation+ if err := rows.Scan(&info.id, &info.pipelineUID); err != nil {+ return nil, errors.Wrapf(err, "failed to scan issue info")+ }+ issuesToInvalidate = append(issuesToInvalidate, info)+ }+ if err := rows.Err(); err != nil {+ return nil, errors.Wrapf(err, "failed to scan issue rows")+ }+ rows.Close()++ tx, err := s.GetDB().BeginTx(ctx, nil)+ if err != nil {+ return nil, err+ }+ defer tx.Rollback()++ // 1. Update Principal table+ // Because we have ON UPDATE CASCADE on foreign keys (issue.creator, etc.),+ // this will automatically update the creator field in:+ // - issue+ // - issue_comment+ // - simple table references (plan, pipeline, task_run, etc.)+ query := qb.Q().Space("UPDATE principal SET email = ? WHERE id = ?", newEmail, user.ID)+ sqlStr, args, err := query.ToSQL()+ if err != nil {+ return nil, errors.Wrapf(err, "failed to build update principal sql")+ }+ if _, err := tx.ExecContext(ctx, sqlStr, args...); err != nil {+ return nil, errors.Wrapf(err, "failed to update principal email")+ }++ // 2. Update GrantRequest in Issue payload+ // The user in GrantRequest is stored as "users/{email}" within the JSON payload.+ // We use text replacement for the specific path.+ oldUserRef := common.FormatUserEmail(user.Email)+ newUserRef := common.FormatUserEmail(newEmail)++ // 'grantRequest' is the json key for grant_request field in Issue proto+ query = qb.Q().Space(`+ UPDATE issue+ SET payload = jsonb_set(payload, '{grantRequest,user}', to_jsonb(?::text))+ WHERE payload->'grantRequest'->>'user' = ?`,+ newUserRef, oldUserRef)+ sqlStr, args, err = query.ToSQL()+ if err != nil {+ return nil, errors.Wrapf(err, "failed to build update grant request sql")+ }+ if _, err := tx.ExecContext(ctx, sqlStr, args...); err != nil {+ return nil, errors.Wrapf(err, "failed to update issue grant request")+ }++ // 3. Update Policies+ // Update IAM policies: bindings->members array contains user references+ // Update MASKING_EXCEPTION policies: maskingExceptions->member field contains user references+ var invalidatedPolicies []struct {+ ResourceType storepb.Policy_Resource+ Resource string+ Type storepb.Policy_Type+ }++ // 3a. Update IAM policy bindings+ iamPolicySQL := `+ UPDATE policy+ SET payload = (+ SELECT jsonb_set(+ policy.payload,+ '{bindings}',+ COALESCE(+ (+ SELECT jsonb_agg(+ jsonb_set(+ binding,+ '{members}',+ COALESCE(+ (+ SELECT jsonb_agg(+ CASE WHEN member = $1 THEN $2::text ELSE member END+ )+ FROM jsonb_array_elements_text(binding->'members') AS member+ ),+ '[]'::jsonb+ )+ )+ )+ FROM jsonb_array_elements(policy.payload->'bindings') AS binding+ ),+ '[]'::jsonb+ )+ )+ )+ WHERE type = $3+ AND payload ? 'bindings'+ AND EXISTS (+ SELECT 1+ FROM jsonb_array_elements(payload->'bindings') AS binding,+ jsonb_array_elements_text(binding->'members') AS member+ WHERE member = $1+ )+ RETURNING resource_type, resource, type`++ rows, err = tx.QueryContext(ctx, iamPolicySQL, oldUserRef, newUserRef, storepb.Policy_IAM.String())+ if err != nil {+ return nil, errors.Wrapf(err, "failed to update IAM policies")+ }+ defer rows.Close()++ for rows.Next() {+ var resourceTypeStr, resource, typeStr string+ if err := rows.Scan(&resourceTypeStr, &resource, &typeStr); err != nil {+ return nil, errors.Wrapf(err, "failed to scan updated IAM policy")+ }++ var invalidation struct {+ ResourceType storepb.Policy_Resource+ Resource string+ Type storepb.Policy_Type+ }+ invalidation.Resource = resource++ if val, ok := storepb.Policy_Resource_value[resourceTypeStr]; ok {+ invalidation.ResourceType = storepb.Policy_Resource(val)+ }+ if val, ok := storepb.Policy_Type_value[typeStr]; ok {+ invalidation.Type = storepb.Policy_Type(val)+ }+ invalidatedPolicies = append(invalidatedPolicies, invalidation)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ rows.Close()++ // 3b. Update MASKING_EXCEPTION policy maskingExceptions+ maskingPolicySQL := `+ UPDATE policy+ SET payload = (+ SELECT jsonb_set(+ policy.payload,+ '{maskingExceptions}',+ COALESCE(+ (+ SELECT jsonb_agg(+ CASE+ WHEN exception->>'member' = $1 THEN+ jsonb_set(exception, '{member}', to_jsonb($2::text))+ ELSE exception+ END+ )+ FROM jsonb_array_elements(policy.payload->'maskingExceptions') AS exception+ ),+ '[]'::jsonb+ )+ )+ )+ WHERE type = $3+ AND payload ? 'maskingExceptions'+ AND EXISTS (+ SELECT 1+ FROM jsonb_array_elements(payload->'maskingExceptions') AS exception+ WHERE exception->>'member' = $1+ )+ RETURNING resource_type, resource, type`++ rows, err = tx.QueryContext(ctx, maskingPolicySQL, oldUserRef, newUserRef, storepb.Policy_MASKING_EXCEPTION.String())+ if err != nil {+ return nil, errors.Wrapf(err, "failed to update MASKING_EXCEPTION policies")+ }+ defer rows.Close()++ for rows.Next() {+ var resourceTypeStr, resource, typeStr string+ if err := rows.Scan(&resourceTypeStr, &resource, &typeStr); err != nil {+ return nil, errors.Wrapf(err, "failed to scan updated MASKING_EXCEPTION policy")+ }++ var invalidation struct {+ ResourceType storepb.Policy_Resource+ Resource string+ Type storepb.Policy_Type+ }+ invalidation.Resource = resource++ if val, ok := storepb.Policy_Resource_value[resourceTypeStr]; ok {+ invalidation.ResourceType = storepb.Policy_Resource(val)+ }+ if val, ok := storepb.Policy_Type_value[typeStr]; ok {+ invalidation.Type = storepb.Policy_Type(val)+ }+ invalidatedPolicies = append(invalidatedPolicies, invalidation)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ rows.Close()++ // 4. Update User Groups+ // Update user_group.payload to replace old user reference with new one in members array.+ // Members are stored as GroupMember objects with member field in "users/{email}" format.+ userGroupSQL := `+ UPDATE user_group+ SET payload = (+ SELECT jsonb_set(+ user_group.payload,+ '{members}',+ COALESCE(+ (+ SELECT jsonb_agg(+ CASE+ WHEN member->>'member' = $1 THEN+ jsonb_set(member, '{member}', to_jsonb($2::text))+ ELSE member+ END+ )+ FROM jsonb_array_elements(user_group.payload->'members') AS member+ ),+ '[]'::jsonb+ )+ )+ )+ WHERE payload ? 'members'+ AND EXISTS (+ SELECT 1+ FROM jsonb_array_elements(payload->'members') AS member+ WHERE member->>'member' = $1+ )+ RETURNING email`++ rows, err = tx.QueryContext(ctx, userGroupSQL, oldUserRef, newUserRef)+ if err != nil {+ return nil, errors.Wrapf(err, "failed to update user_group memberships")+ }+ defer rows.Close()++ var invalidatedGroupEmails []string+ for rows.Next() {+ var email sql.NullString+ if err := rows.Scan(&email); err != nil {+ return nil, errors.Wrapf(err, "failed to scan updated group")+ }+ if email.Valid {+ invalidatedGroupEmails = append(invalidatedGroupEmails, email.String)+ }+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ rows.Close()++ // 5. Update Audit Logs+ // Update audit_log.payload to replace old user reference with new one.+ // User is stored in the 'user' field in "users/{email}" format.+ query = qb.Q().Space(`+ UPDATE audit_log+ SET payload = jsonb_set(payload, '{user}', to_jsonb(?::text))+ WHERE payload->>'user' = ?`,+ newUserRef, oldUserRef)++ sqlStr, args, err = query.ToSQL()+ if err != nil {+ return nil, errors.Wrapf(err, "failed to build update audit_log sql")+ }++ if _, err := tx.ExecContext(ctx, sqlStr, args...); err != nil {+ return nil, errors.Wrapf(err, "failed to update audit_log user references")+ }++ if err := tx.Commit(); err != nil {+ return nil, err+ }++ // 6. Update caches+ s.userIDCache.Remove(user.ID)+ s.userEmailCache.Remove(user.Email)++ // Invalidate issue caches+ for _, issue := range issuesToInvalidate {+ s.issueCache.Remove(issue.id)+ if issue.pipelineUID != nil {+ s.issueByPipelineCache.Remove(*issue.pipelineUID)+ }+ }++ // Invalidate policy cache for updated policies+ for _, p := range invalidatedPolicies {+ s.policyCache.Remove(getPolicyCacheKey(p.ResourceType, p.Resource, p.Type))+ }++ // Invalidate group cache for updated groups+ for _, email := range invalidatedGroupEmails {+ s.groupCache.Remove(email)+ }++ // Fetch updated user+ updatedUser, err := s.GetUserByID(ctx, user.ID)+ if err != nil {+ return nil, err+ }+ // Re-populate user cache+ s.userIDCache.Add(updatedUser.ID, updatedUser)+ s.userEmailCache.Add(updatedUser.Email, updatedUser)++ return updatedUser, nil+}diff --git a/backend/tests/tests.go b/backend/tests/tests.goindex c6a41d9102..15c83ab871 100644--- a/backend/tests/tests.go+++ b/backend/tests/tests.go@@ -112,6 +112,8 @@ type controller struct {workspaceServiceClient v1connect.WorkspaceServiceClientreleaseServiceClient v1connect.ReleaseServiceClientrevisionServiceClient v1connect.RevisionServiceClient+ groupServiceClient v1connect.GroupServiceClient+ auditLogServiceClient v1connect.AuditLogServiceClientproject *v1pb.Project@@ -296,6 +298,8 @@ func (ctl *controller) start(ctx context.Context, port int) (context.Context, erctl.workspaceServiceClient = v1connect.NewWorkspaceServiceClient(ctl.client, baseURL, interceptors)ctl.releaseServiceClient = v1connect.NewReleaseServiceClient(ctl.client, baseURL, interceptors)ctl.revisionServiceClient = v1connect.NewRevisionServiceClient(ctl.client, baseURL, interceptors)+ ctl.groupServiceClient = v1connect.NewGroupServiceClient(ctl.client, baseURL, interceptors)+ ctl.auditLogServiceClient = v1connect.NewAuditLogServiceClient(ctl.client, baseURL, interceptors)if err := ctl.waitForHealthz(ctx); err != nil {return nil, errors.Wrap(err, "failed to wait for healthz")diff --git a/backend/tests/user_test.go b/backend/tests/user_test.goindex b57f08a537..dc60b1a70e 100644--- a/backend/tests/user_test.go+++ b/backend/tests/user_test.go@@ -7,6 +7,8 @@ import ("connectrpc.com/connect""github.com/stretchr/testify/require"+ "google.golang.org/genproto/googleapis/type/expr"+ "google.golang.org/protobuf/types/known/fieldmaskpb""github.com/bytebase/bytebase/backend/common"@@ -141,3 +143,230 @@ func TestDeleteUser(t *testing.T) {}))a.NoError(err)}++func TestUpdateUserEmail(t *testing.T) {+ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)++ // 1. Create a user+ originalEmail := "[email protected]"+ newEmail := "[email protected]"+ userResp, err := ctl.userServiceClient.CreateUser(ctx, connect.NewRequest(&v1pb.CreateUserRequest{+ User: &v1pb.User{+ Title: "temp-user",+ UserType: v1pb.UserType_USER,+ Email: originalEmail,+ Password: "1024bytebase",+ },+ }))+ a.NoError(err)+ user := userResp.Msg++ // 1.5 Grant user permission to create issues in the project+ projectID := "test-project"+ // Login as admin (StartServer returns admin token but let's be explicit or reuse ctl state if it hasn't changed)+ // Actually StartServer sets ctl.authInterceptor.token to admin token.+ // So we are currently admin.++ policyResp, err := ctl.projectServiceClient.GetIamPolicy(ctx, connect.NewRequest(&v1pb.GetIamPolicyRequest{+ Resource: "projects/" + projectID,+ }))+ a.NoError(err)+ policy := policyResp.Msg++ policy.Bindings = append(policy.Bindings, &v1pb.Binding{+ Role: "roles/projectDeveloper",+ Members: []string{fmt.Sprintf("user:%s", originalEmail)},+ })++ _, err = ctl.projectServiceClient.SetIamPolicy(ctx, connect.NewRequest(&v1pb.SetIamPolicyRequest{+ Resource: "projects/" + projectID,+ Policy: policy,+ }))+ a.NoError(err)++ // 1.6 Create a group and add the user to it+ groupEmail := "[email protected]"+ groupResp, err := ctl.groupServiceClient.CreateGroup(ctx, connect.NewRequest(&v1pb.CreateGroupRequest{+ Group: &v1pb.Group{+ Title: "Test Group",+ },+ GroupEmail: groupEmail,+ }))+ a.NoError(err)+ group := groupResp.Msg++ // Add user to the group+ updatedGroupResp, err := ctl.groupServiceClient.UpdateGroup(ctx, connect.NewRequest(&v1pb.UpdateGroupRequest{+ Group: &v1pb.Group{+ Name: group.Name,+ Title: group.Title,+ Email: group.Email,+ Members: []*v1pb.GroupMember{{Member: common.FormatUserEmail(originalEmail), Role: v1pb.GroupMember_MEMBER}},+ },+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"members"}},+ }))+ a.NoError(err)+ a.Len(updatedGroupResp.Msg.Members, 1)+ a.Equal(common.FormatUserEmail(originalEmail), updatedGroupResp.Msg.Members[0].Member)++ // 1.7 Create a masking exception policy with the user+ maskingPolicy, err := ctl.orgPolicyServiceClient.CreatePolicy(ctx, connect.NewRequest(&v1pb.CreatePolicyRequest{+ Parent: "projects/" + projectID,+ Policy: &v1pb.Policy{+ Type: v1pb.PolicyType_MASKING_EXCEPTION,+ Policy: &v1pb.Policy_MaskingExceptionPolicy{+ MaskingExceptionPolicy: &v1pb.MaskingExceptionPolicy{+ MaskingExceptions: []*v1pb.MaskingExceptionPolicy_MaskingException{+ {+ Action: v1pb.MaskingExceptionPolicy_MaskingException_QUERY,+ Member: fmt.Sprintf("user:%s", originalEmail),+ Condition: &expr.Expr{}, // Empty condition means access all databases without expiration+ },+ },+ },+ },+ },+ }))+ a.NoError(err)++ // 2. Login as user and create resources+ loginResp, err := ctl.authServiceClient.Login(ctx, connect.NewRequest(&v1pb.LoginRequest{+ Email: originalEmail,+ Password: "1024bytebase",+ }))+ a.NoError(err)+ userCtx := ctx+ ctl.authInterceptor.token = loginResp.Msg.Token++ // Create Issue+ // Use GRANT_REQUEST to avoid plan requirement and also test payload update.+ grantUser := common.FormatUserEmail(originalEmail)+ issueResp, err := ctl.issueServiceClient.CreateIssue(userCtx, connect.NewRequest(&v1pb.CreateIssueRequest{+ Parent: "projects/" + projectID,+ Issue: &v1pb.Issue{+ Title: "Test Grant Request",+ Type: v1pb.Issue_GRANT_REQUEST,+ GrantRequest: &v1pb.GrantRequest{+ Role: "roles/projectDeveloper",+ User: grantUser,+ },+ Description: "desc",+ },+ }))+ a.NoError(err)+ issue := issueResp.Msg++ // Create Issue Comment+ commentResp, err := ctl.issueServiceClient.CreateIssueComment(userCtx, connect.NewRequest(&v1pb.CreateIssueCommentRequest{+ IssueComment: &v1pb.IssueComment{+ Comment: "Test Comment",+ },+ Parent: issue.Name,+ }))+ a.NoError(err)+ comment := commentResp.Msg++ // 3. Update Email (as Admin)+ // Login as admin+ adminLoginResp, err := ctl.authServiceClient.Login(ctx, connect.NewRequest(&v1pb.LoginRequest{+ Email: "[email protected]",+ Password: "1024bytebase",+ }))+ a.NoError(err)+ ctl.authInterceptor.token = adminLoginResp.Msg.Token++ // Function under test+ updateResp, err := ctl.userServiceClient.UpdateEmail(ctx, connect.NewRequest(&v1pb.UpdateEmailRequest{+ Name: user.Name,+ Email: newEmail,+ }))+ a.NoError(err)+ a.Equal(newEmail, updateResp.Msg.Email)++ // 4. Verify Cascade++ // Verify Issue Creator+ updatedIssueResp, err := ctl.issueServiceClient.GetIssue(ctx, connect.NewRequest(&v1pb.GetIssueRequest{+ Name: issue.Name,+ }))+ a.NoError(err)+ // Creator is a string "users/{email}"+ a.Equal(common.FormatUserEmail(newEmail), updatedIssueResp.Msg.Creator, "Issue creator should be updated")+ // Verify GrantRequest User in Payload+ a.Equal(common.FormatUserEmail(newEmail), updatedIssueResp.Msg.GrantRequest.User, "GrantRequest user should be updated")++ // Verify Issue Comment Creator+ commentsResp, err := ctl.issueServiceClient.ListIssueComments(ctx, connect.NewRequest(&v1pb.ListIssueCommentsRequest{+ Parent: issue.Name,+ }))+ a.NoError(err)+ foundComment := false+ for _, c := range commentsResp.Msg.IssueComments {+ if c.Name == comment.Name {+ a.Equal(common.FormatUserEmail(newEmail), c.Creator)+ foundComment = true+ }+ }+ a.True(foundComment)++ // Verify Project Policy+ newPolicyResp, err := ctl.projectServiceClient.GetIamPolicy(ctx, connect.NewRequest(&v1pb.GetIamPolicyRequest{+ Resource: "projects/" + projectID,+ }))+ a.NoError(err)+ foundMember := false+ for _, b := range newPolicyResp.Msg.Bindings {+ for _, m := range b.Members {+ if m == fmt.Sprintf("user:%s", newEmail) {+ foundMember = true+ }+ a.NotEqual(fmt.Sprintf("user:%s", originalEmail), m, "Old email should not present")+ }+ }+ a.True(foundMember, "New email should be in policy")++ // Verify Group Membership+ updatedGroup, err := ctl.groupServiceClient.GetGroup(ctx, connect.NewRequest(&v1pb.GetGroupRequest{+ Name: group.Name,+ }))+ a.NoError(err)+ a.Len(updatedGroup.Msg.Members, 1)+ a.Equal(common.FormatUserEmail(newEmail), updatedGroup.Msg.Members[0].Member, "Group member should be updated to new email")+ for _, m := range updatedGroup.Msg.Members {+ a.NotEqual(common.FormatUserEmail(originalEmail), m.Member, "Old email should not present in group")+ }++ // Verify Masking Exception Policy+ updatedMaskingPolicy, err := ctl.orgPolicyServiceClient.GetPolicy(ctx, connect.NewRequest(&v1pb.GetPolicyRequest{+ Name: maskingPolicy.Msg.Name,+ }))+ a.NoError(err)+ maskingExceptions := updatedMaskingPolicy.Msg.GetMaskingExceptionPolicy().GetMaskingExceptions()+ a.Len(maskingExceptions, 1)+ a.Equal(fmt.Sprintf("user:%s", newEmail), maskingExceptions[0].Member, "Masking exception member should be updated to new email")+ for _, exception := range maskingExceptions {+ a.NotEqual(fmt.Sprintf("user:%s", originalEmail), exception.Member, "Old email should not present in masking exception")+ }++ // Verify Audit Logs+ // Search for audit logs related to the project (audit logs were created when user created issue/comment)+ auditLogs, err := ctl.auditLogServiceClient.SearchAuditLogs(ctx, connect.NewRequest(&v1pb.SearchAuditLogsRequest{+ Parent: "projects/" + projectID,+ Filter: fmt.Sprintf(`user == "%s"`, common.FormatUserEmail(newEmail)),+ }))+ a.NoError(err)+ // We should have at least some audit logs from the issue/comment creation+ a.NotEmpty(auditLogs.Msg.AuditLogs, "Should have audit logs with new email")+ // Verify no audit logs have the old email+ oldEmailAuditLogs, err := ctl.auditLogServiceClient.SearchAuditLogs(ctx, connect.NewRequest(&v1pb.SearchAuditLogsRequest{+ Parent: "projects/" + projectID,+ Filter: fmt.Sprintf(`user == "%s"`, common.FormatUserEmail(originalEmail)),+ }))+ a.NoError(err)+ a.Empty(oldEmailAuditLogs.Msg.AuditLogs, "Should not have audit logs with old email")+}