-
Notifications
You must be signed in to change notification settings - Fork 10.4k
fix: Use Memberships with OWNER role for platform owner lookup #22475
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
fix: Use Memberships with OWNER role for platform owner lookup #22475
Conversation
@sahitya-chandra is attempting to deploy a commit to the cal Team on Vercel. A member of the Team first needs to authorize it. |
Graphite Automations"Add consumer team as reviewer" took an action on this PR • (07/14/25)1 reviewer was added to this PR based on Keith Williams's automation. "Add community label" took an action on this PR • (07/14/25)1 label was added to this PR based on Keith Williams's automation. "Add ready-for-e2e label" took an action on this PR • (08/13/25)1 label was added to this PR based on Keith Williams's automation. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
cubic reviewed 2 files and found no issues. Review PR in cubic.dev.
WalkthroughThe PR replaces ProfilesRepository usage in ApiAuthStrategy with MembershipsRepository; ApiAuthStrategy now resolves platform owner by calling findPlatformOwnerUserId(organizationId) and, if absent, findPlatformAdminUserId(organizationId). Two new methods were added to MembershipsRepository to return the userId of an accepted OWNER or ADMIN membership. AuthModule removes the ProfilesModule import. The ApiAuthStrategy error message for a missing owner ID was changed. Several e2e specs and app tests add membership fixtures and include MembershipsModule to ensure an OWNER membership exists in tests. Assessment against linked issues
Tip 🔌 Remote MCP (Model Context Protocol) integration is now available!Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats. ✨ Finishing Touches
🧪 Generate unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
Status, Documentation and Community
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
apps/api/v2/src/modules/auth/strategies/api-auth/api-auth.strategy.ts
(3 hunks)apps/api/v2/src/modules/memberships/memberships.repository.ts
(1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: Install dependencies / Yarn install & cache
- GitHub Check: Security Check
🔇 Additional comments (3)
apps/api/v2/src/modules/memberships/memberships.repository.ts (1)
23-36
: LGTM! The method correctly implements platform owner lookup.The implementation properly queries the membership table with the correct filters (teamId, role, accepted) and handles the null case appropriately. This addresses the issue where the previous approach could incorrectly identify managed users as platform owners.
apps/api/v2/src/modules/auth/strategies/api-auth/api-auth.strategy.ts (2)
7-7
: LGTM! Dependency injection implemented correctly.The MembershipsRepository is properly imported and injected following the established patterns in the codebase.
Also applies to: 62-62
188-188
: LGTM! Method call change correctly implements the fix.The change from
profilesRepository.getPlatformOwnerUserId
tomembershipsRepository.findPlatformOwnerUserId
properly addresses the issue where managed users could be incorrectly identified as platform owners. The new approach correctly validates actual ownership through membership roles.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
hey @sahitya-chandra thanks for the pr, can you please address the unit test failing. Also it will be good to add a loom.
Head branch was pushed to by a user without write access
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
🧹 Nitpick comments (1)
apps/api/v2/src/modules/slots/slots-2024-09-04/services/slots.service.spec.ts (1)
14-18
: Remove redundant jest.mock for AvailableSlotsServiceYou already provide AvailableSlotsService via Nest DI with a useValue mock below. The top-level jest.mock here is redundant and risks diverging behavior if the service’s shape changes. Rely on the DI-provided mock only.
-jest.mock("@/lib/services/available-slots.service", () => ({ - AvailableSlotsService: jest.fn().mockImplementation(() => ({ - getAvailableSlots: jest.fn(), - })), -}));
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
apps/api/v2/src/modules/auth/guards/billing/platform-plan.guard.spec.ts
(1 hunks)apps/api/v2/src/modules/slots/slots-2024-09-04/services/slots.service.spec.ts
(1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.ts
📄 CodeRabbit Inference Engine (.cursor/rules/review.mdc)
**/*.ts
: For Prisma queries, only select data you need; never useinclude
, always useselect
Ensure thecredential.key
field is never returned from tRPC endpoints or APIs
Files:
apps/api/v2/src/modules/auth/guards/billing/platform-plan.guard.spec.ts
apps/api/v2/src/modules/slots/slots-2024-09-04/services/slots.service.spec.ts
**/*.{ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/review.mdc)
Flag excessive Day.js use in performance-critical code; prefer native Date or Day.js
.utc()
in hot paths like loops
Files:
apps/api/v2/src/modules/auth/guards/billing/platform-plan.guard.spec.ts
apps/api/v2/src/modules/slots/slots-2024-09-04/services/slots.service.spec.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: Install dependencies / Yarn install & cache
- GitHub Check: Codacy Static Code Analysis
apps/api/v2/src/modules/auth/guards/billing/platform-plan.guard.spec.ts
Outdated
Show resolved
Hide resolved
apps/api/v2/src/modules/slots/slots-2024-09-04/services/slots.service.spec.ts
Outdated
Show resolved
Hide resolved
@sahitya-chandra We still have a test failing. |
@kart1ka I'm still working on it sir... |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (2)
apps/api/v2/src/modules/auth/strategies/api-auth/api-auth.strategy.e2e-spec.ts (2)
12-12
: ProfilesModule may be redundant now—verify and remove if unused.Profiles are no longer part of the owner lookup in this strategy. If nothing else in this spec requires Nest DI from ProfilesModule (fixtures usually talk directly to Prisma), drop it to reduce bootstrap time and stale dependencies.
Also applies to: 67-67
298-305
: Tighten teardown: delete org2 and client2; await module.close for clean shutdown.Avoids leftover records and unawaited async cleanup in Jest/Nest.
afterAll(async () => { await oAuthClientRepositoryFixture.delete(oAuthClient.id); + await oAuthClientRepositoryFixture.delete(oAuthClientTwo.id); await userRepositoryFixture.delete(validApiKeyUser.id); await userRepositoryFixture.delete(validAccessTokenUser.id); await userRepositoryFixture.delete(validOAuthUser.id); await teamRepositoryFixture.delete(organization.id); - module.close(); + await teamRepositoryFixture.delete(organizationTwo.id); + await module.close(); });
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
apps/api/v2/src/modules/auth/strategies/api-auth/api-auth.strategy.e2e-spec.ts
(2 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/review.mdc)
**/*.ts
: For Prisma queries, only select data you need; never useinclude
, always useselect
Ensure thecredential.key
field is never returned from tRPC endpoints or APIs
Files:
apps/api/v2/src/modules/auth/strategies/api-auth/api-auth.strategy.e2e-spec.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/review.mdc)
Flag excessive Day.js use in performance-critical code; prefer native Date or Day.js
.utc()
in hot paths like loops
Files:
apps/api/v2/src/modules/auth/strategies/api-auth/api-auth.strategy.e2e-spec.ts
**/*.{ts,tsx,js,jsx}
⚙️ CodeRabbit configuration file
Flag default exports and encourage named exports. Named exports provide better tree-shaking, easier refactoring, and clearer imports. Exempt main components like pages, layouts, and components that serve as the primary export of a module.
Files:
apps/api/v2/src/modules/auth/strategies/api-auth/api-auth.strategy.e2e-spec.ts
⏰ Context from checks skipped due to timeout of 180000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Install dependencies / Yarn install & cache
🔇 Additional comments (2)
apps/api/v2/src/modules/auth/strategies/api-auth/api-auth.strategy.e2e-spec.ts (2)
7-7
: Importing MembershipsModule is the right move to align DI with the new owner-resolution path.This ensures the strategy can resolve the owner via MembershipsRepository at runtime in tests.
187-205
: OAuth-client assertions remain valid once OWNER memberships are seeded.No assertion change needed, but without the new memberships the test will 401 with “No owner ID found…”.
apps/api/v2/src/modules/auth/strategies/api-auth/api-auth.strategy.e2e-spec.ts
Show resolved
Hide resolved
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
♻️ Duplicate comments (1)
apps/api/v2/src/modules/auth/strategies/api-auth/api-auth.strategy.e2e-spec.ts (1)
24-24
: Correct fixture import (singular) — aligns with existing test fixturesPath and name now match the actual fixture. This addresses the earlier feedback about the plural form.
🧹 Nitpick comments (1)
apps/api/v2/src/modules/auth/strategies/api-auth/api-auth.strategy.e2e-spec.ts (1)
129-135
: OWNER memberships seeded — required for OAuth-client flow; consider minor cleanupsSeeding accepted OWNER memberships is exactly what the new logic needs. Two small, optional improvements:
- Prefer direct FKs over nested connect for brevity (fixture accepts Prisma.MembershipCreateInput either way).
- Add explicit cleanup for created entities to reduce DB litter and avoid relying on cascades.
Apply this minimal diff to use direct FKs:
- await membershipRepositoryFixture.create({ - user: { connect: { id: validOAuthUser.id } }, - team: { connect: { id: organization.id } }, - role: "OWNER", - accepted: true, - }); + await membershipRepositoryFixture.create({ + userId: validOAuthUser.id, + teamId: organization.id, + role: "OWNER", + accepted: true, + }); - await membershipRepositoryFixture.create({ - user: { connect: { id: validOAuthUser.id } }, - team: { connect: { id: organizationTwo.id } }, - role: "OWNER", - accepted: true, - }); + await membershipRepositoryFixture.create({ + userId: validOAuthUser.id, + teamId: organizationTwo.id, + role: "OWNER", + accepted: true, + });Additionally, consider explicitly deleting org2 in teardown (and/or membership rows) so this spec doesn’t leave residue:
@@ afterAll(async () => { await oAuthClientRepositoryFixture.delete(oAuthClient.id); await userRepositoryFixture.delete(validApiKeyUser.id); await userRepositoryFixture.delete(validAccessTokenUser.id); await userRepositoryFixture.delete(validOAuthUser.id); await teamRepositoryFixture.delete(organization.id); + await teamRepositoryFixture.delete(organizationTwo.id); module.close(); });
Optional coverage follow-up: add a test for the ADMIN fallback (when OWNER is absent) to exercise the new repository method chain (findPlatformOwnerUserId → findPlatformAdminUserId). I can draft that if useful.
Also applies to: 136-142
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
apps/api/v2/src/modules/auth/strategies/api-auth/api-auth.strategy.e2e-spec.ts
(6 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/review.mdc)
**/*.ts
: For Prisma queries, only select data you need; never useinclude
, always useselect
Ensure thecredential.key
field is never returned from tRPC endpoints or APIs
Files:
apps/api/v2/src/modules/auth/strategies/api-auth/api-auth.strategy.e2e-spec.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/review.mdc)
Flag excessive Day.js use in performance-critical code; prefer native Date or Day.js
.utc()
in hot paths like loops
Files:
apps/api/v2/src/modules/auth/strategies/api-auth/api-auth.strategy.e2e-spec.ts
**/*.{ts,tsx,js,jsx}
⚙️ CodeRabbit configuration file
Flag default exports and encourage named exports. Named exports provide better tree-shaking, easier refactoring, and clearer imports. Exempt main components like pages, layouts, and components that serve as the primary export of a module.
Files:
apps/api/v2/src/modules/auth/strategies/api-auth/api-auth.strategy.e2e-spec.ts
🧬 Code graph analysis (1)
apps/api/v2/src/modules/auth/strategies/api-auth/api-auth.strategy.e2e-spec.ts (1)
apps/api/v2/test/fixtures/repository/membership.repository.fixture.ts (1)
MembershipRepositoryFixture
(6-42)
🔇 Additional comments (4)
apps/api/v2/src/modules/auth/strategies/api-auth/api-auth.strategy.e2e-spec.ts (4)
7-7
: Good call: Importing MembershipsModule makes DI consistent with the new lookup pathThis ensures the strategy’s dependencies (via MembershipsRepository) are available in the test module.
50-50
: Fixture handle addedThe dedicated fixture handle keeps setup clear and mirrors other repository fixtures.
71-71
: MembershipsModule registered in the TestingModuleMatches the strategy change to membership-based owner resolution.
98-98
: Fixture wiring looks correctInstantiating MembershipRepositoryFixture from the compiled module follows the same pattern as other fixtures.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Great stuff! Thank you Sahitya for the contribution! : )
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (2)
apps/api/v2/src/app.e2e-spec.ts (1)
113-120
: Ensure role typing via enum to avoid stringly-typed regressions.Using the enum eliminates typos and keeps parity with Prisma types.
Apply within this block:
- role: "OWNER", + role: MembershipRole.OWNER,Add this import near existing Prisma imports:
import { MembershipRole } from "@calcom/prisma/client";Optional: if any provider caches memberships at bootstrap in the future, consider creating the membership before creating the OAuth client to make test intent explicit. No change required now.
apps/api/v2/src/modules/oauth-clients/controllers/oauth-flow/oauth-flow.controller.e2e-spec.ts (1)
111-116
: Creating an accepted OWNER membership is essential; switch to enum and consider minor hardening.
- Type-safe role protects against typos.
- Optional: assert the create() returns an id to fail fast if setup changes.
Apply within this block:
- role: "OWNER", + role: MembershipRole.OWNER,Add this import near existing Prisma imports:
import { MembershipRole } from "@prisma/client";If you want a quick assertion:
const membership = await membershipRepositoryFixture.create({ /* ... */ }); expect(membership?.id).toBeDefined();Also consider adding a separate test where OWNER is absent but ADMIN exists to validate the fallback introduced in ApiAuthStrategy.
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (2)
apps/api/v2/src/app.e2e-spec.ts
(3 hunks)apps/api/v2/src/modules/oauth-clients/controllers/oauth-flow/oauth-flow.controller.e2e-spec.ts
(4 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/review.mdc)
**/*.ts
: For Prisma queries, only select data you need; never useinclude
, always useselect
Ensure thecredential.key
field is never returned from tRPC endpoints or APIs
Files:
apps/api/v2/src/app.e2e-spec.ts
apps/api/v2/src/modules/oauth-clients/controllers/oauth-flow/oauth-flow.controller.e2e-spec.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/review.mdc)
Flag excessive Day.js use in performance-critical code; prefer native Date or Day.js
.utc()
in hot paths like loops
Files:
apps/api/v2/src/app.e2e-spec.ts
apps/api/v2/src/modules/oauth-clients/controllers/oauth-flow/oauth-flow.controller.e2e-spec.ts
**/*.{ts,tsx,js,jsx}
⚙️ CodeRabbit configuration file
Flag default exports and encourage named exports. Named exports provide better tree-shaking, easier refactoring, and clearer imports. Exempt main components like pages, layouts, and components that serve as the primary export of a module.
Files:
apps/api/v2/src/app.e2e-spec.ts
apps/api/v2/src/modules/oauth-clients/controllers/oauth-flow/oauth-flow.controller.e2e-spec.ts
⏰ Context from checks skipped due to timeout of 180000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Install dependencies / Yarn install & cache
🔇 Additional comments (5)
apps/api/v2/src/app.e2e-spec.ts (2)
12-12
: Importing MembershipRepositoryFixture is the right move for OWNER-based resolution.This aligns the e2e with the new Memberships-based owner lookup. No issues spotted.
37-37
: Fixture variable addition is fine.Naming is consistent with the other fixtures and keeps setup readable.
apps/api/v2/src/modules/oauth-clients/controllers/oauth-flow/oauth-flow.controller.e2e-spec.ts (3)
18-18
: Importing MembershipRepositoryFixture is necessary for the new flow.Matches the refactor to OWNER-based platform owner detection.
67-67
: Fixture variable addition looks good.Keeps test setup aligned with repository fixtures.
94-95
: No caching detected—post-init membership fixture is safe.I searched the ApiAuthStrategy, application modules, the memberships repository, and the MembershipRepositoryFixture for any caching configuration or keywords (e.g. CacheModule, CacheInterceptor, “cache”) and found none. There’s no bootstrap-time or request-scope caching that would interfere with resolving the owner per request, so initializing the membership fixture after
app.init()
poses no risk.
@supalarry sir, thanks a lot for previously approving the PR, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Great stuff!
What does this PR do?
Replaced the logic for identifying the platform owner from the Profiles table (ordered by createdAt) with a direct lookup in the Memberships table using the 'OWNER' role. This prevents managed users from being mistakenly treated as platform owners if the original owner is deleted.
Visual Demo (For contributors especially)
A visual demonstration is strongly recommended, for both the original and new change (video / image - any one).
Video Demo (if applicable):
Image Demo (if applicable):
Mandatory Tasks (DO NOT REMOVE)
How should this be tested?
Checklist
Summary by cubic
Changed platform owner lookup to use the Memberships table with the OWNER role instead of Profiles, ensuring only valid owners are identified.