Skip to content

Conversation

supalarry
Copy link
Contributor

Linear CAL-6118

@supalarry supalarry requested review from a team as code owners July 17, 2025 15:22
Copy link

linear bot commented Jul 17, 2025

Copy link
Contributor

coderabbitai bot commented Jul 17, 2025

Walkthrough

This change refactors organization admin and owner permissions for managed users across several modules. It introduces new service and repository methods to check for organization admin/owner roles, enables organization admins to bypass team membership checks when accessing or updating team event types, and modifies endpoints and authorization logic to allow organization admins to view all organization teams and manage team event types. Helper functions and test cases are added to support and verify these behaviors. The changes are focused on backend service, repository, controller, and API handler layers, with some adjustments in example platform code.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Assessment against linked issues

Objective Addressed Explanation
1. Create organization team event type: update create.handler.ts to allow org admin/owner to create team event types without requiring team membership (CAL-6118)
2. Read all organization teams: update organizations-teams.controller.ts so org admins see all org teams, not just those they belong to (CAL-6118)
3. Read team event type: update getEventTypeById.ts and repository/eventType.ts to allow org admins/org owners to read any team event type in their org (CAL-6118)
4. Update team event: update event-types-atom.service.ts to allow org admins/owners to update team event types for teams in their org (CAL-6118)

Assessment against linked issues: Out-of-scope changes

Code Change Explanation
Refactoring and modularization in packages/platform/examples/base/src/pages/api/managed-user.ts These changes improve code structure and add helper functions for managed user/test data setup, but are not directly related to admin permission logic for team event types as described in CAL-6118.
Changes to generateRandomEmail and related logic in packages/platform/examples/base/src/pages/_app.tsx Updates to email generation for test/demo users are unrelated to the admin permission objectives.

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 78971b7 and e482622.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (1)
  • apps/api/v2/package.json (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • apps/api/v2/package.json
⏰ 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: Socket Security: Pull Request Alerts
✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch lauris/cal-6118-refactor-platform-managed-user-admin-permissions

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@graphite-app graphite-app bot requested a review from a team July 17, 2025 15:22
@keithwillcode keithwillcode added core area: core, team members only platform Anything related to our platform plan labels Jul 17, 2025
Copy link

graphite-app bot commented Jul 17, 2025

Graphite Automations

"Add consumer team as reviewer" took an action on this PR • (07/17/25)

1 reviewer was added to this PR based on Keith Williams's automation.

Copy link

delve-auditor bot commented Jul 17, 2025

No security or compliance issues detected. Reviewed everything up to 276b033.

Security Overview
  • 🔎 Scanned files: 14 changed file(s)
Detected Code Changes
Change Type Relevant files
Enhancement ► atoms.module.ts
    Add Organizations Teams Repository
► event-types-atom.service.ts
    Update team event type permissions
► organizations-teams.controller.ts
    Add organization admin team access
► organizations-teams.repository.ts
    Add organization teams pagination with members
► managed-user.ts
    Refactor user creation and add round robin event type
► _app.tsx
    Update email generation with names
Configuration changes ► package.json
    Update platform libraries version

Reply to this PR with @delve-auditor followed by a description of what change you want and we'll auto-submit a change to this PR to implement it.

Copy link
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: 2

🧹 Nitpick comments (3)
packages/platform/examples/base/src/pages/_app.tsx (1)

16-27: Consider making the names configurable for better maintainability.

The implementation correctly generates predictable emails with name prefixes. However, the hardcoded names could be made more flexible.

Consider extracting the names to a constant or configuration:

+const DEMO_NAMES = ["keith", "somay", "rajiv", "morgan", "lauris"];
+
function generateRandomEmail(name: string) {
  const localPartLength = 5;
  const domain = ["example.com", "example.net", "example.org"];
  // ... rest of implementation
}

This would make it easier to modify the demo users without changing the function calls.

apps/api/v2/src/modules/atoms/services/event-types-atom.service.ts (1)

78-99: Verify security implications of context switching for organization admins.

This change allows organization admins to operate in the context of the event type's owner rather than their own context. While this aligns with the PR's goal of enhancing org admin access, it's important to ensure:

  1. This doesn't bypass any critical security checks
  2. Audit logs properly reflect who made changes (the admin, not the effective user)
  3. The behavior is clearly documented for API consumers

The logic is sound, but the security implications should be carefully considered.

Consider adding audit logging to track when an org admin operates on behalf of another user. This would help with compliance and debugging.

packages/platform/examples/base/src/pages/api/managed-user.ts (1)

68-75: Use optional chaining for cleaner code.

The static analysis correctly identifies an opportunity to use optional chaining.

-  if (existingUser && existingUser.calcomUserId) {
+  if (existingUser?.calcomUserId) {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 292073e and 3c3fe83.

📒 Files selected for processing (8)
  • apps/api/v2/src/modules/atoms/services/event-types-atom.service.ts (3 hunks)
  • apps/api/v2/src/modules/organizations/memberships/services/organizations-membership.service.ts (1 hunks)
  • apps/api/v2/src/modules/organizations/teams/index/organizations-teams.controller.ts (3 hunks)
  • apps/api/v2/src/modules/organizations/teams/index/organizations-teams.repository.ts (1 hunks)
  • apps/api/v2/src/modules/organizations/teams/index/services/organizations-teams.service.ts (1 hunks)
  • packages/platform/examples/base/src/pages/_app.tsx (3 hunks)
  • packages/platform/examples/base/src/pages/api/managed-user.ts (4 hunks)
  • packages/trpc/server/routers/viewer/eventTypes/create.handler.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
apps/api/v2/src/modules/organizations/teams/index/organizations-teams.controller.ts (1)
apps/api/v2/src/modules/organizations/memberships/services/organizations-membership.service.ts (1)
  • isOrgAdminOrOwner (30-41)
apps/api/v2/src/modules/atoms/services/event-types-atom.service.ts (2)
apps/api/v2/src/modules/memberships/memberships.repository.ts (1)
  • isUserOrganizationAdmin (50-61)
packages/lib/event-types/getEventTypeById.ts (1)
  • getEventTypeById (36-260)
packages/platform/examples/base/src/pages/api/managed-user.ts (1)
packages/platform/constants/api.ts (2)
  • X_CAL_SECRET_KEY (49-49)
  • X_CAL_CLIENT_ID (50-50)
🪛 Biome (1.9.4)
packages/platform/examples/base/src/pages/api/managed-user.ts

[error] 68-68: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

⏰ 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: Check for E2E label
  • GitHub Check: Security Check
🔇 Additional comments (7)
apps/api/v2/src/modules/organizations/memberships/services/organizations-membership.service.ts (1)

30-41: LGTM! Well-implemented role checking method.

The isOrgAdminOrOwner method correctly implements role-based access control by:

  • Reusing existing repository method for consistency
  • Providing clear error handling with descriptive messages
  • Following the established service pattern
  • Using proper return type for boolean checks

This method will enable proper authorization checks across the organization modules.

packages/platform/examples/base/src/pages/_app.tsx (1)

53-57: Email generation calls are consistent with the refactored function.

The updated calls to generateRandomEmail with specific names align well with the function signature change and support the demo user creation workflow.

apps/api/v2/src/modules/organizations/teams/index/services/organizations-teams.service.ts (1)

27-34: LGTM! Method follows established service patterns.

The getPaginatedOrgTeamsWithMembers method correctly:

  • Maintains consistency with existing service methods
  • Uses proper pagination parameters with sensible defaults
  • Delegates to the repository layer appropriately
  • Supports the role-based access control requirements

This method enables organization admins/owners to retrieve all teams with member information.

packages/trpc/server/routers/viewer/eventTypes/create.handler.ts (1)

92-93: LGTM! Authorization logic correctly exempts organization admins.

The updated condition properly implements the organization admin privilege by:

  • Adding !isOrgAdmin check to bypass membership role requirements
  • Maintaining existing system admin and membership role validations
  • Following logical precedence: system admin → org admin → membership role

This change aligns with the PR objective of refactoring platform managed user org admin access.

apps/api/v2/src/modules/organizations/teams/index/organizations-teams.repository.ts (1)

111-122: LGTM! Repository method efficiently retrieves teams with member data.

The findOrgTeamsPaginatedWithMembers method is well-implemented:

  • Correctly filters teams by organization ID
  • Uses selective field inclusion for members (accepted, userId, role) to optimize performance
  • Applies pagination properly with skip/take parameters
  • Follows established repository patterns
  • Supports the role-based access control requirements

The selective member field inclusion is particularly good for performance while providing necessary data for authorization checks.

apps/api/v2/src/modules/organizations/teams/index/organizations-teams.controller.ts (1)

60-63: LGTM! Proper dependency injection.

The OrganizationsMembershipService is correctly injected following NestJS conventions.

packages/platform/examples/base/src/pages/api/managed-user.ts (1)

15-56: Excellent refactoring to reduce code duplication!

The helper function properly consolidates the user creation logic and makes the code more maintainable.

Copy link

vercel bot commented Jul 18, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

2 Skipped Deployments
Name Status Preview Comments Updated (UTC)
cal ⬜️ Ignored (Inspect) Jul 28, 2025 10:08am
cal-eu ⬜️ Ignored (Inspect) Jul 28, 2025 10:08am

Copy link
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: 0

🧹 Nitpick comments (2)
packages/lib/server/repository/eventTypeRepository.ts (2)

751-764: Optimize the organization users query for better performance

The nested query with profiles.some could impact performance. Consider adding database indexes and potentially restructuring the query.

  1. Add indexes to improve query performance:

    • Index on Profile.organizationId
    • Index on Team.parentId
    • Composite index on EventType.userId and EventType.teamId
  2. Consider denormalizing the organization relationship on the EventType table for faster queries if this becomes a performance bottleneck.

Would you like me to generate the Prisma schema changes for these indexes?


749-777: Extract organization admin conditions into a separate method

Consider extracting the organization admin condition building logic into a separate private method for better readability and testability.

+  private buildOrganizationAdminConditions(currentOrganizationId: number) {
+    const organizationUsersEventTypesQuery = {
+      AND: [
+        { userId: { not: null } },
+        {
+          owner: {
+            profiles: {
+              some: {
+                organizationId: currentOrganizationId,
+              },
+            },
+          },
+        },
+      ],
+    };
+    
+    const organizationTeamsEventTypesQuery = {
+      AND: [
+        { teamId: { not: null } },
+        {
+          team: {
+            parentId: currentOrganizationId,
+          },
+        },
+      ],
+    };
+    
+    return [organizationUsersEventTypesQuery, organizationTeamsEventTypesQuery];
+  }

   const orgAdminConditions = [];
   if (isUserOrganizationAdmin && currentOrganizationId) {
-    const organizationUsersEventTypesQuery = {
-      AND: [
-        { userId: { not: null } },
-        {
-          owner: {
-            profiles: {
-              some: {
-                organizationId: currentOrganizationId,
-              },
-            },
-          },
-        },
-      ],
-    };
-    const organizationTeamsEventTypesQuery = {
-      AND: [
-        { teamId: { not: null } },
-        {
-          team: {
-            parentId: currentOrganizationId,
-          },
-        },
-      ],
-    };
-    orgAdminConditions.push(organizationUsersEventTypesQuery);
-    orgAdminConditions.push(organizationTeamsEventTypesQuery);
+    orgAdminConditions.push(...this.buildOrganizationAdminConditions(currentOrganizationId));
   }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 276b033 and e084c76.

📒 Files selected for processing (3)
  • packages/lib/event-types/getEventTypeById.ts (1 hunks)
  • packages/lib/server/repository/eventTypeRepository.ts (2 hunks)
  • packages/trpc/server/routers/viewer/eventTypes/create.handler.ts (1 hunks)
📓 Path-based instructions (1)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/review.mdc)

Flag excessive Day.js use in performance-critical code. Functions like .add, .diff, .isBefore, and .isAfter are slow, especially in timezone mode. Prefer .utc() for better performance. Where possible, replace with native Date and direct .valueOf() comparisons for faster execution. Recommend using native methods or Day.js .utc() consistently in hot paths like loops.

Files:

  • packages/lib/server/repository/eventTypeRepository.ts
🧬 Code Graph Analysis (1)
packages/lib/server/repository/eventTypeRepository.ts (1)
apps/api/v2/src/modules/memberships/memberships.repository.ts (1)
  • isUserOrganizationAdmin (50-61)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/lib/event-types/getEventTypeById.ts
  • packages/trpc/server/routers/viewer/eventTypes/create.handler.ts
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/review.mdc)

Flag excessive Day.js use in performance-critical code. Functions like .add, .diff, .isBefore, and .isAfter are slow, especially in timezone mode. Prefer .utc() for better performance. Where possible, replace with native Date and direct .valueOf() comparisons for faster execution. Recommend using native methods or Day.js .utc() consistently in hot paths like loops.

Files:

  • packages/lib/server/repository/eventTypeRepository.ts
🧬 Code Graph Analysis (1)
packages/lib/server/repository/eventTypeRepository.ts (1)
apps/api/v2/src/modules/memberships/memberships.repository.ts (1)
  • isUserOrganizationAdmin (50-61)
⏰ 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: Socket Security: Pull Request Alerts
🔇 Additional comments (1)
packages/lib/server/repository/eventTypeRepository.ts (1)

471-481: Ignore admin‐status verification in the repository
The findById method is a data-access layer API that intentionally trusts the isUserOrganizationAdmin flag provided by its caller. Authorization (including any necessary MembershipRepository.isUserOrganizationAdmin checks) is performed in the service or controller layer before invoking this repository method. You can safely ignore the previous suggestion to re-verify admin status inside findById.

Likely an incorrect or invalid review comment.

Copy link
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: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a61d043 and b1549ce.

📒 Files selected for processing (2)
  • packages/lib/event-types/getEventTypeById.test.ts (1 hunks)
  • packages/lib/event-types/getEventTypeById.ts (2 hunks)
📓 Path-based instructions (1)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/review.mdc)

Flag excessive Day.js use in performance-critical code. Functions like .add, .diff, .isBefore, and .isAfter are slow, especially in timezone mode. Prefer .utc() for better performance. Where possible, replace with native Date and direct .valueOf() comparisons for faster execution. Recommend using native methods or Day.js .utc() consistently in hot paths like loops.

Files:

  • packages/lib/event-types/getEventTypeById.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/lib/event-types/getEventTypeById.ts
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/review.mdc)

Flag excessive Day.js use in performance-critical code. Functions like .add, .diff, .isBefore, and .isAfter are slow, especially in timezone mode. Prefer .utc() for better performance. Where possible, replace with native Date and direct .valueOf() comparisons for faster execution. Recommend using native methods or Day.js .utc() consistently in hot paths like loops.

Files:

  • packages/lib/event-types/getEventTypeById.test.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: Socket Security: Pull Request Alerts
🔇 Additional comments (6)
packages/lib/event-types/getEventTypeById.test.ts (6)

1-16: LGTM! Well-structured test setup.

The imports and test setup are properly configured with appropriate mocking for database operations and translations.


19-54: LGTM! Comprehensive test for basic user access.

The test properly sets up user ownership and verifies that users can access their own event types with appropriate assertions.


113-165: LGTM! Good test coverage for organization admin team access.

The test properly demonstrates the new permission model where organization admins can access team event types within their organization hierarchy.


167-228: LGTM! Comprehensive test for organization admin access to user event types.

The test properly verifies that organization admins can access event types owned by users within their organization, with appropriate user profile setup.


230-288: LGTM! Critical security test for cross-organization access control.

This test properly verifies that organization admins cannot access event types from different organizations, which is essential for multi-tenant security.


290-325: LGTM! Good edge case handling for fallback behavior.

The test properly verifies graceful degradation to regular user permissions when organization context is inconsistent, ensuring robust error handling.

Comment on lines +56 to +109
test.skip("should return null when user doesn't have access to event type", async () => {
// note(Lauris): test skipped because somehow when creating event type eventType.users includes otherUser
const owner = await prismock.user.create({
data: {
username: "owner",
email: "owner1@example.com",
},
});

const otherUser = await prismock.user.create({
data: {
username: "otheruser",
email: "otheruser@example.com",
},
});

const eventType = await prismock.eventType.create({
data: {
title: "Owner's Event Type",
slug: "owner-event",
length: 30,
userId: owner.id,
users: {
connect: [{ id: owner.id }],
},
},
select: {
id: true,
userId: true,
users: true,
},
});

await prismock.user.update({
where: {
id: otherUser.id,
},
data: {
eventTypes: {
disconnect: [{ id: eventType.id }],
},
},
});

const result = await getRawEventType({
userId: otherUser.id,
eventTypeId: eventType.id,
isUserOrganizationAdmin: false,
currentOrganizationId: null,
prisma: prismock as any,
});

expect(result).toBeNull();
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Address the skipped security test.

This test covers an important security scenario (access denial for non-owners) but is disabled due to prismock limitations. Consider using a different approach to enable this test.

Possible solutions:

  1. Use a real test database with proper cleanup
  2. Try a different mocking approach that handles user-eventType associations correctly
  3. Mock the repository layer directly instead of the database

This test gap could miss authorization vulnerabilities in production.

🤖 Prompt for AI Agents
In packages/lib/event-types/getEventTypeById.test.ts between lines 56 and 109,
the test verifying access denial for non-owners is skipped due to prismock not
correctly handling user-eventType associations. To fix this, replace prismock
with a real test database setup that supports proper user-eventType relations
and includes cleanup after tests, or alternatively mock the repository layer
directly to simulate these associations accurately. This will enable the test to
run and properly verify the security scenario.

SomayChauhan
SomayChauhan previously approved these changes Jul 24, 2025
Copy link
Member

@SomayChauhan SomayChauhan left a comment

Choose a reason for hiding this comment

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

🚀 🚀 🚀

Copy link

Review the following changes in direct dependencies. Learn more about Socket for GitHub.

Diff Package Supply Chain
Security
Vulnerability Quality Maintenance License

View full report

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
core area: core, team members only platform Anything related to our platform plan ready-for-e2e
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants