Skip to content

Comments

fix: add authentication guard to /apps/installed routes#23092

Merged
emrysal merged 2 commits intomainfrom
devin/fix-installed-apps-auth-1755179842
Aug 14, 2025
Merged

fix: add authentication guard to /apps/installed routes#23092
emrysal merged 2 commits intomainfrom
devin/fix-installed-apps-auth-1755179842

Conversation

@emrysal
Copy link
Contributor

@emrysal emrysal commented Aug 14, 2025

fix: add authentication guard to /apps/installed routes

Summary

This PR fixes a 500 error that occurs when unauthenticated users access /apps/installed/calendar (and other installed app categories). The issue was caused by the server component making tRPC calls without first validating that a user session exists.

Changes made:

  • Added session validation using getServerSession before making tRPC calls in the /apps/installed/[category] server component
  • Redirects unauthenticated users to /auth/login instead of allowing the server to throw 500 errors
  • Follows the same authentication pattern used consistently throughout the Cal.com codebase

Root cause: The server component was calling createRouterCaller for tRPC operations without ensuring a valid session existed first. When getTRPCContext is called without a session, subsequent database queries fail, resulting in 500 errors.

Review & Testing Checklist for Human

  • Verify authentication logic matches existing patterns - Compare the session check implementation with other server components like /availability/page.tsx and /event-types/page.tsx to ensure consistency
  • Test unauthenticated redirect flow - Navigate to /apps/installed/calendar without being logged in and verify it redirects to /auth/login instead of showing a 500 error
  • Test authenticated user flow - Ensure logged-in users can still access /apps/installed/calendar and other categories normally without any regressions
  • Test multiple app categories - Verify the fix works for all installed app categories (conferencing, payment, etc.), not just calendar
  • Check middleware interaction - Ensure the server-level auth check doesn't conflict with existing middleware logic that handles return-to cookies for /apps/installed routes

Diagram

%%{ init : { "theme" : "default" }}%%
graph TB
    User[["User Access<br/>/apps/installed/calendar"]] --> Middleware[["middleware.ts<br/>(return-to cookie logic)"]]:::context
    Middleware --> PageComponent[["apps/installed/[category]/page.tsx<br/><br/>NEW: Session Check Added"]]:::major-edit
    
    PageComponent --> SessionCheck{{"getServerSession()<br/>validation"}}
    SessionCheck -->|"No Session"| LoginRedirect[["redirect('/auth/login')"]]:::major-edit
    SessionCheck -->|"Valid Session"| TRPCCalls[["createRouterCaller()<br/>calendarsRouter & appsRouter"]]:::context
    
    TRPCCalls --> GetServerSession[["@calcom/features/auth/lib/<br/>getServerSession"]]:::context
    TRPCCalls --> BuildLegacyRequest[["@lib/buildLegacyCtx"]]:::context
    
    subgraph Legend
        L1[Major Edit]:::major-edit
        L2[Minor Edit]:::minor-edit  
        L3[Context/No Edit]:::context
    end

    classDef major-edit fill:#90EE90
    classDef minor-edit fill:#87CEEB  
    classDef context fill:#FFFFFF
Loading

Notes

Testing performed:

  • ✅ Type checking passed (yarn type-check:ci --force)
  • ✅ Local testing confirmed unauthenticated users redirect to /auth/login
  • ✅ Tested multiple categories (/calendar, /conferencing) - both redirect correctly
  • ⚠️ Lint failed in unrelated @calcom/lib package (not related to this change)

Session details:

Screenshots of successful redirect:
Authentication redirect working
Conferencing category redirect

- Add session validation before making tRPC calls in server component
- Redirect unauthenticated users to /auth/login instead of throwing 500 errors
- Follows existing authentication patterns used throughout the codebase
- Fixes 500 error when accessing /apps/installed/calendar and other categories

Co-Authored-By: alex@cal.com <me@alexvanandel.com>
@devin-ai-integration
Copy link
Contributor

🤖 Devin AI Engineer

I'll be helping with this pull request! Here's what you should know:

✅ I will automatically:

  • Address comments on this PR that start with 'DevinAI'.
  • Look at CI failures and help fix them

Note: I can only respond to comments from users who have write access to this repository.

⚙️ Control Options:

  • Disable automatic comment and CI monitoring

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 14, 2025

Walkthrough

Adds a server-side authentication guard to apps/web/app/(use-page-wrapper)/apps/installed/[category]/page.tsx. Imports cookies, headers (next/headers), buildLegacyRequest, and getServerSession. Constructs a server request from current headers and cookies, retrieves the session, and redirects to /auth/login if no session or missing user.id. This check executes before TRPC calls (calendarsRouter, appsRouter) and after query param validation. Existing logic for parsing params and redirecting to the default calendar remains unchanged. No exported/public signatures are modified.

Possibly related PRs

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 Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch devin/fix-installed-apps-auth-1755179842

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
🪧 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@keithwillcode keithwillcode added core area: core, team members only foundation labels Aug 14, 2025
@emrysal emrysal requested a review from hbjORbj August 14, 2025 14:13
@vercel
Copy link

vercel bot commented Aug 14, 2025

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

2 Skipped Deployments
Project Deployment Preview Comments Updated (UTC)
cal ⬜️ Ignored Aug 14, 2025 2:14pm
cal-eu ⬜️ Ignored Aug 14, 2025 2:14pm

@emrysal emrysal marked this pull request as ready for review August 14, 2025 14:14
@emrysal emrysal enabled auto-merge (squash) August 14, 2025 14:15
@graphite-app graphite-app bot requested a review from a team August 14, 2025 14:15
@graphite-app
Copy link

graphite-app bot commented Aug 14, 2025

Graphite Automations

"Add foundation team as reviewer" took an action on this PR • (08/14/25)

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

@dosubot dosubot bot added app-store area: app store, apps, calendar integrations, google calendar, outlook, lark, apple calendar authentication area: authentication, auth, google sign in, password, SAML, password reset, can't log in labels Aug 14, 2025
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 (1)
apps/web/app/(use-page-wrapper)/apps/installed/[category]/page.tsx (1)

38-41: Nit: remove unnecessary awaits and call redirect directly; confirm callback behavior.

  • headers() and cookies() are sync; awaiting them is unnecessary and adds noise.
  • redirect() throws; returning it is unnecessary. Elsewhere in the file you call redirect() without return—make this consistent.

Apply this diff:

-  const session = await getServerSession({ req: buildLegacyRequest(await headers(), await cookies()) });
+  const session = await getServerSession({ req: buildLegacyRequest(headers(), cookies()) });
   if (!session?.user?.id) {
-    return redirect("/auth/login");
+    redirect("/auth/login");
   }

Additionally, if your middleware doesn’t reliably set a return-to cookie, consider appending a callbackUrl to preserve the intended destination after login (or confirm that middleware handles this path).

📜 Review details

Configuration used: CodeRabbit UI
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 settings in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between e4ef283 and 36040f1.

📒 Files selected for processing (1)
  • apps/web/app/(use-page-wrapper)/apps/installed/[category]/page.tsx (2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.tsx

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

Always use t() for text localization in frontend code; direct text embedding should trigger a warning

Files:

  • apps/web/app/(use-page-wrapper)/apps/installed/[category]/page.tsx
**/*.{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/web/app/(use-page-wrapper)/apps/installed/[category]/page.tsx
🧬 Code Graph Analysis (1)
apps/web/app/(use-page-wrapper)/apps/installed/[category]/page.tsx (2)
packages/features/auth/lib/getServerSession.ts (1)
  • getServerSession (32-136)
apps/web/lib/buildLegacyCtx.tsx (1)
  • buildLegacyRequest (47-49)
🔇 Additional comments (3)
apps/web/app/(use-page-wrapper)/apps/installed/[category]/page.tsx (3)

4-4: Good use of next/headers primitives for server-only auth.

Importing cookies() and headers() is appropriate here for building the server-side request.


8-8: Using getServerSession to guard tRPC calls is correct.

This aligns with patterns elsewhere and prevents 500s due to missing session in the tRPC context.


13-14: Correct bridge to NextApiRequest via buildLegacyRequest.

This matches the expected signature (ReadonlyHeaders, ReadonlyRequestCookies) and keeps getServerSession usage consistent across the app.

@emrysal emrysal merged commit 994a36d into main Aug 14, 2025
80 of 84 checks passed
@emrysal emrysal deleted the devin/fix-installed-apps-auth-1755179842 branch August 14, 2025 14:50
@github-actions
Copy link
Contributor

E2E results are ready!

emrysal added a commit that referenced this pull request Aug 14, 2025
* fix: add authentication guard to /apps/installed routes

- Add session validation before making tRPC calls in server component
- Redirect unauthenticated users to /auth/login instead of throwing 500 errors
- Follows existing authentication patterns used throughout the codebase
- Fixes 500 error when accessing /apps/installed/calendar and other categories

Co-Authored-By: alex@cal.com <me@alexvanandel.com>

* fix: Missing return; was that so hard, DevinAI?

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app-store area: app store, apps, calendar integrations, google calendar, outlook, lark, apple calendar authentication area: authentication, auth, google sign in, password, SAML, password reset, can't log in core area: core, team members only foundation ready-for-e2e

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants