Skip to content

chore: CSRF protect forgot-password functionality #22361

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

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

emrysal
Copy link
Contributor

@emrysal emrysal commented Jul 9, 2025

What does this PR do?


Summary by cubic

Added CSRF protection to the forgot password flow to prevent cross-site request forgery attacks.

  • Security
    • Added a new CSRF token API and set token as a cookie.
    • Updated the reset password API and form to require and validate the CSRF token.

@keithwillcode keithwillcode added core area: core, team members only foundation labels Jul 9, 2025
Copy link

vercel bot commented Jul 9, 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 22, 2025 0:19am
cal-eu ⬜️ Ignored (Inspect) Jul 22, 2025 0:19am

Copy link

delve-auditor bot commented Jul 9, 2025

No security or compliance issues detected. Reviewed everything up to 7f9ee3b.

Security Overview
  • 🔎 Scanned files: 4 changed file(s)
Detected Code Changes
Change Type Relevant files
Enhancement ► route.ts
    Add CSRF token validation to reset password
► csrf/route.ts
    Add CSRF token generation endpoint
► forgot-password-single-view.tsx
    Update password reset form to handle CSRF tokens
► getServerSideProps.tsx
    Remove CSRF token from server props

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.

@emrysal emrysal marked this pull request as ready for review July 22, 2025 12:19
Copy link
Contributor

coderabbitai bot commented Jul 22, 2025

Walkthrough

The changes introduce CSRF protection to the password reset functionality. A new API route is added to generate and return a CSRF token, which is also set as a cookie. The password reset API handler is updated to validate the submitted CSRF token against the value stored in the cookie, returning a 403 error if validation fails. The password reset frontend is refactored to modularize UI components and now fetches and submits a CSRF token as part of the form submission, with logic to refresh the token on failure. Server-side logic is updated to remove unused CSRF-related imports.

Estimated code review effort

3 (~45 minutes)

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

apps/web/app/api/auth/reset-password/route.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-playwright".

(The package "eslint-plugin-playwright" was not found when loaded as a Node module from the directory "".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-playwright@latest --save-dev

The plugin "eslint-plugin-playwright" was referenced from the config file in ".eslintrc.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

apps/web/app/api/csrf/route.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-playwright".

(The package "eslint-plugin-playwright" was not found when loaded as a Node module from the directory "".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-playwright@latest --save-dev

The plugin "eslint-plugin-playwright" was referenced from the config file in ".eslintrc.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

apps/web/modules/auth/forgot-password/[id]/forgot-password-single-view.tsx

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-playwright".

(The package "eslint-plugin-playwright" was not found when loaded as a Node module from the directory "".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-playwright@latest --save-dev

The plugin "eslint-plugin-playwright" was referenced from the config file in ".eslintrc.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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 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 22, 2025 12:19
Copy link

graphite-app bot commented Jul 22, 2025

Graphite Automations

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

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

@dosubot dosubot bot added the security label Jul 22, 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: 3

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 48bd12b and 7f9ee3b.

📒 Files selected for processing (4)
  • apps/web/app/api/auth/reset-password/route.ts (3 hunks)
  • apps/web/app/api/csrf/route.ts (1 hunks)
  • apps/web/modules/auth/forgot-password/[id]/forgot-password-single-view.tsx (2 hunks)
  • apps/web/server/lib/auth/forgot-password/[id]/getServerSideProps.tsx (0 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:

  • apps/web/app/api/auth/reset-password/route.ts
  • apps/web/app/api/csrf/route.ts
  • apps/web/modules/auth/forgot-password/[id]/forgot-password-single-view.tsx
🧠 Learnings (3)
📓 Common learnings
Learnt from: alishaz-polymath
PR: calcom/cal.com#22304
File: packages/prisma/schema.prisma:1068-1071
Timestamp: 2025-07-16T05:10:22.891Z
Learning: In PR #22304 for Cal.com private link expiration features, the `maxUsageCount` field was intentionally set to default to 1 (non-nullable) as a breaking change, making all existing private links single-use after migration. This was a deliberate design decision by alishaz-polymath.
apps/web/app/api/auth/reset-password/route.ts (1)

Learnt from: CR
PR: calcom/cal.com#0
File: .cursor/rules/review.mdc:0-0
Timestamp: 2025-07-21T13:54:11.770Z
Learning: Applies to backend/**/*.{ts,tsx} : Make sure the credential.key field is never returned back from tRPC endpoints or APIs.

apps/web/modules/auth/forgot-password/[id]/forgot-password-single-view.tsx (2)

Learnt from: Anshumancanrock
PR: #22570
File: apps/web/modules/signup-view.tsx:253-253
Timestamp: 2025-07-21T21:33:23.343Z
Learning: In signup-view.tsx, when checking if redirectUrl contains certain strings, using explicit && checks (redirectUrl && redirectUrl.includes()) is preferred over optional chaining (redirectUrl?.includes()) to ensure the result is always a boolean rather than potentially undefined. This approach provides cleaner boolean contracts for downstream conditional logic.

Learnt from: eunjae-lee
PR: #22106
File: packages/features/insights/components/FailedBookingsByField.tsx:65-71
Timestamp: 2025-07-15T12:59:34.389Z
Learning: In the FailedBookingsByField component (packages/features/insights/components/FailedBookingsByField.tsx), although routingFormId is typed as optional in useInsightsParameters, the system automatically enforces a routing form filter, so routingFormId is always present in practice. This means the data always contains only one entry, making the single-entry destructuring approach safe.

💤 Files with no reviewable changes (1)
  • apps/web/server/lib/auth/forgot-password/[id]/getServerSideProps.tsx
🧰 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:

  • apps/web/app/api/auth/reset-password/route.ts
  • apps/web/app/api/csrf/route.ts
  • apps/web/modules/auth/forgot-password/[id]/forgot-password-single-view.tsx
🧠 Learnings (3)
📓 Common learnings
Learnt from: alishaz-polymath
PR: calcom/cal.com#22304
File: packages/prisma/schema.prisma:1068-1071
Timestamp: 2025-07-16T05:10:22.891Z
Learning: In PR #22304 for Cal.com private link expiration features, the `maxUsageCount` field was intentionally set to default to 1 (non-nullable) as a breaking change, making all existing private links single-use after migration. This was a deliberate design decision by alishaz-polymath.
apps/web/app/api/auth/reset-password/route.ts (1)

Learnt from: CR
PR: calcom/cal.com#0
File: .cursor/rules/review.mdc:0-0
Timestamp: 2025-07-21T13:54:11.770Z
Learning: Applies to backend/**/*.{ts,tsx} : Make sure the credential.key field is never returned back from tRPC endpoints or APIs.

apps/web/modules/auth/forgot-password/[id]/forgot-password-single-view.tsx (2)

Learnt from: Anshumancanrock
PR: #22570
File: apps/web/modules/signup-view.tsx:253-253
Timestamp: 2025-07-21T21:33:23.343Z
Learning: In signup-view.tsx, when checking if redirectUrl contains certain strings, using explicit && checks (redirectUrl && redirectUrl.includes()) is preferred over optional chaining (redirectUrl?.includes()) to ensure the result is always a boolean rather than potentially undefined. This approach provides cleaner boolean contracts for downstream conditional logic.

Learnt from: eunjae-lee
PR: #22106
File: packages/features/insights/components/FailedBookingsByField.tsx:65-71
Timestamp: 2025-07-15T12:59:34.389Z
Learning: In the FailedBookingsByField component (packages/features/insights/components/FailedBookingsByField.tsx), although routingFormId is typed as optional in useInsightsParameters, the system automatically enforces a routing form filter, so routingFormId is always present in practice. This means the data always contains only one entry, making the single-entry destructuring approach safe.

⏰ 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). (1)
  • GitHub Check: Security Check
🔇 Additional comments (3)
apps/web/app/api/auth/reset-password/route.ts (1)

28-37: CSRF token validation implementation looks good

The implementation correctly:

  • Retrieves the token from cookies
  • Validates token presence and equality
  • Deletes the token after successful validation to prevent reuse
apps/web/modules/auth/forgot-password/[id]/forgot-password-single-view.tsx (2)

20-163: Excellent modular refactoring

The refactoring into separate components (Success, Expired, and PasswordResetForm) improves code organization and maintainability. The CSRF token integration is well-implemented with automatic refresh on failure.


137-146: Password validation rules are comprehensive

The password validation enforces:

  • Minimum length of 7 characters
  • At least one digit, one uppercase, and one lowercase letter

This provides good baseline security for password strength.

@@ -10,6 +11,7 @@ import prisma from "@calcom/prisma";
import { IdentityProvider } from "@calcom/prisma/enums";

const passwordResetRequestSchema = z.object({
csrfToken: z.string().optional(),
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Make CSRF token required in the schema

The CSRF token is marked as optional in the schema, but the validation logic treats it as required (returning 403 if missing). Update the schema to reflect this requirement.

const passwordResetRequestSchema = z.object({
-  csrfToken: z.string().optional(),
+  csrfToken: z.string(),
  password: z.string().refine(validPassword, () => ({
    message: "Password does not meet the requirements",
  })),
  requestId: z.string(), // format doesn't matter.
});
🤖 Prompt for AI Agents
In apps/web/app/api/auth/reset-password/route.ts at line 14, the csrfToken field
in the schema is currently optional but should be required to match the
validation logic that returns a 403 error if it is missing. Change the schema
definition for csrfToken from optional to required by removing the .optional()
modifier to ensure consistent validation.

Comment on lines +9 to +14
res.cookies.set("calcom.csrf_token", token, {
httpOnly: false,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/",
});
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

Consider adding an expiration time to the CSRF token cookie

The CSRF token cookie is set without an expiration time, making it a session cookie that persists until the browser is closed. For enhanced security, consider adding a reasonable expiration time (e.g., 1 hour) to limit the token's validity window.

  res.cookies.set("calcom.csrf_token", token, {
    httpOnly: false,
    secure: process.env.NODE_ENV === "production",
    sameSite: "lax",
    path: "/",
+   maxAge: 3600, // 1 hour in seconds
  });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
res.cookies.set("calcom.csrf_token", token, {
httpOnly: false,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/",
});
res.cookies.set("calcom.csrf_token", token, {
httpOnly: false,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/",
maxAge: 3600, // 1 hour in seconds
});
🤖 Prompt for AI Agents
In apps/web/app/api/csrf/route.ts around lines 9 to 14, the CSRF token cookie is
set without an expiration time, making it a session cookie. To enhance security,
add an expiration time by including the 'maxAge' property set to 3600 seconds (1
hour) in the cookie options object when calling res.cookies.set.

Comment on lines +81 to +86
useEffect(() => {
fetch("/api/csrf", { cache: "no-store" })
.then((res) => res.json())
.then(({ csrfToken }) => setValue("csrfToken", csrfToken))
.catch(() => setValue("csrfToken", ""));
}, [setValue, refreshToken]);
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

Add error handling for CSRF token fetch failure

The CSRF token fetch catches errors but sets an empty string, which will cause the form submission to fail with a generic error. Consider showing a specific error message to the user or retrying the fetch.

  useEffect(() => {
    fetch("/api/csrf", { cache: "no-store" })
      .then((res) => res.json())
      .then(({ csrfToken }) => setValue("csrfToken", csrfToken))
-     .catch(() => setValue("csrfToken", ""));
+     .catch(() => {
+       setValue("csrfToken", "");
+       setError("newPassword", { 
+         type: "client", 
+         message: t("csrf_token_fetch_failed") 
+       });
+     });
  }, [setValue, refreshToken]);

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In apps/web/modules/auth/forgot-password/[id]/forgot-password-single-view.tsx
around lines 81 to 86, the fetch call for the CSRF token catches errors but only
sets an empty string, which leads to generic form submission errors. Update the
error handling to either display a specific error message to the user indicating
the CSRF token fetch failed or implement a retry mechanism for the fetch. This
will improve user feedback and reduce confusion during form submission failures.

Comment on lines +189 to +190
{!success && <PasswordResetForm form={formMethods} requestId={requestId} />}
{success && <Success />}
Copy link
Contributor

Choose a reason for hiding this comment

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

While it's not true on all cases, I think it would be more readable and shorter using a ternary instead of two expressions:

{success ? <Success /> : <PasswordResetForm form={formMethods} requestId={requestId} />}

@volnei
Copy link
Contributor

volnei commented Aug 7, 2025

Hey @emrysal, can you address the comments on PR? So I'll approve it :)

Copy link
Contributor

@volnei volnei left a comment

Choose a reason for hiding this comment

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

Some small comments

@github-actions github-actions bot marked this pull request as draft August 12, 2025 13:25
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 foundation security
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants