Skip to content

feat: move SetOrganizationMemberRole to membership package#1541

Open
whoAbhishekSah wants to merge 10 commits intomainfrom
feat/membership-set-org-member-role
Open

feat: move SetOrganizationMemberRole to membership package#1541
whoAbhishekSah wants to merge 10 commits intomainfrom
feat/membership-set-org-member-role

Conversation

@whoAbhishekSah
Copy link
Copy Markdown
Member

Summary

Moves the existing SetOrganizationMemberRole RPC implementation from core/organization into core/membership. Also fixes the known leak where demoting an org owner to viewer left the org#owner direct relation in place.

What changes

New in core/membership/

  • SetOrganizationMemberRole(ctx, orgID, principalID, principalType, roleID) — handles the full role-change flow
  • Private helpers: validateMinOwnerConstraint, replacePolicy, replaceRelation
  • Skips write when role is unchanged (existing optimization carried over)

Removed from core/organization/

  • SetMemberRole
  • validateSetMemberRoleRequest
  • getUserOrgPolicies
  • validateMinOwnerConstraint
  • replaceUserOrgPolicies

Handler

  • SetOrganizationMemberRole RPC handler now calls membershipService.SetOrganizationMemberRole with schema.UserPrincipal
  • Error mapping updated to membership package error types (membership.ErrNotMember, membership.ErrInvalidOrgRole, membership.ErrLastOwnerRole)

Bug fix — relation cleanup

Previously, org.SetMemberRole replaced policies but never touched the explicit org#owner or org#member relations. So demoting an owner to viewer left the owner relation in place, continuing to grant owner permissions via SpiceDB.

Now replaceRelation deletes both owner and member relations for the principal before creating the new one matching the target role. Verified by the should succeed demoting owner to viewer with multiple owners test.

Edge cases handled

  • Principal type must be app/user (serviceusers bound at creation, not changed via this RPC)
  • Org does not exist or is disabled → error
  • User does not exist or is disabled → error
  • Role does not exist → error
  • Role is not org-scoped → error
  • User is not a member → ErrNotMember
  • Role is unchanged → early return (no writes)
  • Min-owner constraint — can't demote the last owner

Test plan

  • 6 new unit tests in core/membership/ covering all edge cases above
  • Handler tests updated to use membership service mock

Related

  • Parent issue: #1478
  • Prior PR (AddOrganizationMember): #1537

🤖 Generated with Claude Code

Moves SetMemberRole logic from organization service into the
membership package as SetOrganizationMemberRole, with relation
cleanup added (fixes the known leak where demoting owner to viewer
left the org#owner relation in place).

- New: membership.SetOrganizationMemberRole with validateMinOwnerConstraint,
  replacePolicy, replaceRelation
- Removed from organization service: SetMemberRole,
  validateSetMemberRoleRequest, getUserOrgPolicies,
  validateMinOwnerConstraint, replaceUserOrgPolicies
- Handler rewired from orgService.SetMemberRole to
  membershipService.SetOrganizationMemberRole
- Added 6 unit tests covering skip-unchanged, last-owner constraint,
  owner->viewer demotion (with relation swap), viewer->owner promotion

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@vercel
Copy link
Copy Markdown

vercel bot commented Apr 15, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
frontier Ready Ready Preview, Comment Apr 16, 2026 5:30am

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Apr 15, 2026

Warning

Rate limit exceeded

@whoAbhishekSah has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 44 minutes and 49 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 44 minutes and 49 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 3f1e93c5-3a44-4d7e-848e-3ac9aad24920

📥 Commits

Reviewing files that changed from the base of the PR and between 899deed and b24631e.

📒 Files selected for processing (2)
  • core/membership/service.go
  • core/membership/service_test.go
📝 Walkthrough

Walkthrough

This PR moves organization member role-update logic from core/organization to core/membership by adding Service.SetOrganizationMemberRole(principalType-aware), removing the old organization method, updating interfaces and mocks, and rewiring the API handler and tests to call the membership service.

Changes

Cohort / File(s) Summary
Core Membership Service
core/membership/service.go, core/membership/service_test.go
Added SetOrganizationMemberRole(ctx, orgID, principalID, principalType, roleID) with validation, owner-minimum checks, atomic policy replacement, relation replacement, and audit recording; comprehensive tests for control-flow paths.
Core Organization Service Removal
core/organization/service.go, core/organization/service_test.go
Removed SetMemberRole and its helper functions and tests, deleting prior org-scoped role-update implementation and related test coverage.
API Interface Updates
internal/api/v1beta1connect/interfaces.go
Removed OrganizationService.SetMemberRole(...); added MembershipService.SetOrganizationMemberRole(...) with principal-type parameter.
API Mock Generation
internal/api/v1beta1connect/mocks/membership_service.go, internal/api/v1beta1connect/mocks/organization_service.go
Added autogenerated MembershipService mock exposing SetOrganizationMemberRole; removed SetMemberRole mock from OrganizationService.
API Handler and Tests
internal/api/v1beta1connect/organization.go, internal/api/v1beta1connect/organization_test.go
Handler switched to membershipService.SetOrganizationMemberRole(...) and updated error mappings; tests updated to use the new membership mock and membership-scoped errors.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

Possibly related PRs

Suggested reviewers

  • rohilsurana
  • AmanGIT07
  • rsbh

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coveralls
Copy link
Copy Markdown

coveralls commented Apr 15, 2026

Coverage Report for CI Build 24493841489

Warning

Build has drifted: This PR's base is out of sync with its target branch, so coverage data may include unrelated changes.
Quick fix: rebase this PR. Learn more →

Coverage decreased (-0.03%) to 41.698%

Details

  • Coverage decreased (-0.03%) from the base build.
  • Patch coverage: 40 uncovered changes across 2 files (119 of 159 lines covered, 74.84%).
  • 46 coverage regressions across 7 files.

Uncovered Changes

File Changed Covered %
core/membership/service.go 153 115 75.16%
internal/api/v1beta1connect/organization.go 6 4 66.67%

Coverage Regressions

46 previously-covered lines in 7 files lost coverage.

File Lines Losing Coverage Coverage
internal/store/postgres/org_pats_repository.go 18 78.33%
internal/api/v1beta1connect/user_pat.go 10 79.94%
internal/store/postgres/userpat_repository.go 7 14.9%
core/aggregates/orgpats/service.go 4 92.0%
core/organization/service.go 4 37.87%
internal/api/v1beta1connect/organization_pats.go 2 90.91%
internal/store/postgres/userpat.go 1 89.47%

Coverage Stats

Coverage Status
Relevant Lines: 36661
Covered Lines: 15287
Line Coverage: 41.7%
Coverage Strength: 11.86 hits per line

💛 - Coveralls

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
core/membership/service_test.go (1)

276-428: Add a regression for relation-replacement failures.

This suite only covers the success path for deleting old relations and creating the new one. A case where RelationService.Delete or Create fails during SetOrganizationMemberRole would lock in the owner-demotion fix and catch the partial-update paths in this new flow.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 7017a580-65f7-4314-aa5d-0fccb1f9afc1

📥 Commits

Reviewing files that changed from the base of the PR and between 08d63db and bc494ac.

📒 Files selected for processing (9)
  • core/membership/service.go
  • core/membership/service_test.go
  • core/organization/service.go
  • core/organization/service_test.go
  • internal/api/v1beta1connect/interfaces.go
  • internal/api/v1beta1connect/mocks/membership_service.go
  • internal/api/v1beta1connect/mocks/organization_service.go
  • internal/api/v1beta1connect/organization.go
  • internal/api/v1beta1connect/organization_test.go
💤 Files with no reviewable changes (3)
  • core/organization/service_test.go
  • core/organization/service.go
  • internal/api/v1beta1connect/mocks/organization_service.go

Comment thread core/membership/service.go
Comment thread core/membership/service.go Outdated
Comment thread core/membership/service.go
Silently ignoring all relation delete errors would mask a failed
owner relation delete during demotion, leaving both owner and member
relations in place. Now only relation.ErrNotExist is ignored.

Added 2 tests: real error fails the operation, not-found is ignored.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

♻️ Duplicate comments (2)
core/membership/service.go (2)

185-188: ⚠️ Potential issue | 🔴 Critical

Retry can silently skip relation repair after a partial failure.

If Line 194 succeeds and Line 199 fails, a retry hits the no-op at Line 186 and returns early, leaving policy/relation inconsistent.

Suggested fix
-	// skip if the user already has exactly this role
-	if len(existing) == 1 && existing[0].RoleID == roleID {
-		return nil
-	}
+	// keep policy no-op optimization, but still repair relation state
+	if len(existing) == 1 && existing[0].RoleID == roleID {
+		relationName := orgRoleToRelation(fetchedRole)
+		return s.replaceRelation(ctx, orgID, schema.OrganizationNamespace, principalID, principalType, relationName)
+	}

Also applies to: 194-200


203-204: ⚠️ Potential issue | 🟠 Major

Audit record write failures are being dropped in the role-change path.

Line 344 ignores AuditRecordRepository.Create errors, so callers get success even when audit persistence fails.

Suggested fix
-	s.auditOrgMemberRoleChanged(ctx, org, usr, roleID)
-	return nil
+	if err := s.auditOrgMemberRoleChanged(ctx, org, usr, roleID); err != nil {
+		return err
+	}
+	return nil
 }
 
-func (s *Service) auditOrgMemberRoleChanged(ctx context.Context, org organization.Organization, usr user.User, roleID string) {
-	s.auditRecordRepository.Create(ctx, auditrecord.AuditRecord{
+func (s *Service) auditOrgMemberRoleChanged(ctx context.Context, org organization.Organization, usr user.User, roleID string) error {
+	if _, err := s.auditRecordRepository.Create(ctx, auditrecord.AuditRecord{
 		Event: pkgAuditRecord.OrganizationMemberRoleChangedEvent,
 		Resource: auditrecord.Resource{
 			ID:   org.ID,
@@
-		OccurredAt: time.Now(),
-	})
+		OccurredAt: time.Now(),
+	}); err != nil {
+		return fmt.Errorf("create audit record: %w", err)
+	}
@@
 	audit.GetAuditor(ctx, org.ID).LogWithAttrs(audit.OrgMemberRoleChangedEvent, audit.Target{
 		ID:   usr.ID,
 		Type: schema.UserPrincipal,
 	}, map[string]string{
 		"role_id": roleID,
 	})
+	return nil
 }

Based on learnings: In core/organization/service.go (SetMemberRole method), returning an audit error after the business operation has already succeeded is an intentional design choice.

Also applies to: 343-363

🧹 Nitpick comments (1)
core/membership/service.go (1)

258-260: Comment text in replaceRelation is outdated.

Line 260 says delete errors are ignored, but the implementation only ignores relation.ErrNotExist and fails on other errors.

Suggested fix
-// on the resource, then creates a new relation with the given name. Delete errors
-// are ignored because the relation may not exist.
+// on the resource, then creates a new relation with the given name. Delete errors
+// are ignored only when they are relation.ErrNotExist.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 2245ba2d-333b-413b-aa99-ccb4bf25fa8a

📥 Commits

Reviewing files that changed from the base of the PR and between bc494ac and 899deed.

📒 Files selected for processing (2)
  • core/membership/service.go
  • core/membership/service_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • core/membership/service_test.go

If replaceRelation fails after replacePolicy succeeds, the policy now
has the new role. A retry would hit the early-return (same role) and
never repair the relation. To prevent this, rollback the policy to
the old role so the next retry sees the old state and redoes both.

If rollback also fails, log at error level with all context (org_id,
principal_id, old/new role, both errors) since the membership state
is now inconsistent and needs manual intervention.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
If replaceRelation fails after replacePolicy succeeds, log at error
level with full context (org_id, principal_id, role_id, expected
relation, error) for manual investigation. Removes the rollback
complexity which was getting unwieldy without solving the full
cross-store consistency problem.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
If replacePolicy deletes the existing policies but fails to create
the new one, the user has a relation with no policy. Log at error
level with full context for manual investigation.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
…eleted

If replaceRelation deletes existing relations but fails to create the
new one, the user has a policy with no relation. Log at error level
with full context for manual investigation.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
…delete

Caller passes which relations to clean up instead of hardcoding
owner/member. Org passes [owner, member], project will skip the
call entirely, group can pass its own set.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants