Repository navigation
Update CSRF Checks - #22
Conversation
|
Warning Rate limit exceeded
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 24 minutes and 46 seconds. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the 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 configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Pull request overview
Updates CSRF validation logic to strengthen request-origin checks and perform constant-time CSRF token comparisons.
Changes:
- Enforce
Origin/Refererpresence and validate againstALLOWED_ORIGINSfor unsafe HTTP methods. - Compare CSRF header token vs cookie using a timing-safe comparison helper.
- Apply formatting/quoting consistency updates in token/auth utilities.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 5 comments.
| File | Description |
|---|---|
src/utils/tokens.ts |
Adjusts token utility formatting and changes the constant-time compare helper used by CSRF validation. |
src/middleware/security/requireCsrf.ts |
Tightens CSRF checks: method gating, origin validation, and timing-safe token comparison. |
src/middleware/auth/requireAuth.ts |
Formatting/quoting consistency changes in auth middleware. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| const origin = req.headers.origin || req.headers.referer; | ||
|
|
||
| const origin = req.headers.origin as string | undefined; | ||
| if (!origin) { | ||
| throw new UnauthorizedError('Missing Origin or Referer header'); | ||
| } |
There was a problem hiding this comment.
This change rejects unsafe-method requests that omit both Origin and Referer headers. Since csrfMiddleware is applied to all private API routes (src/routes/api.ts:20), this can break non-browser clients (mobile apps, server-to-server, CLI) that rely on cookie auth but don't send these headers. If those clients are supported, consider allowing missing Origin/Referer for same-site requests, or gating this strictness behind an environment flag/documented contract.
| export function compareHashTokens(hash1: string, hash2: string): boolean { | ||
| const hash1Buffer = Buffer.from(hash1, "hex"); | ||
| const hash2Buffer = Buffer.from(hash2, "hex"); | ||
| if ( | ||
| hash1Buffer.length !== hash2Buffer.length || | ||
| !crypto.timingSafeEqual(hash1Buffer, hash2Buffer) | ||
| ) { | ||
| const hash1Buffer = Buffer.from(hash1, 'utf-8'); | ||
| const hash2Buffer = Buffer.from(hash2, 'utf-8'); | ||
| if (hash1Buffer.length !== hash2Buffer.length) { | ||
| return false; | ||
| } | ||
| return true; | ||
|
|
||
| return crypto.timingSafeEqual(hash1Buffer, hash2Buffer); |
There was a problem hiding this comment.
compareHashTokens now compares UTF-8 bytes of the string values, but the function name and surrounding token utilities imply hex-encoded hashes (and verifyToken uses Buffer.from(..., 'hex')). This mismatch is easy to misuse later (e.g., passing a hex digest expecting byte-level compare). Consider either decoding as 'hex' here as well, or renaming the function to something like constantTimeEqual and documenting that it compares raw strings.
| sessionId: string, | ||
| reduceTime: boolean = false | ||
| ) { | ||
| export function generateRefreshToken(userId: Types.ObjectId, sessionId: string, reduceTime: boolean = false) { |
There was a problem hiding this comment.
reduceTime is declared but unused. If it's no longer needed, remove it to avoid confusion; if it is needed, wire it into the expiresIn selection (or add a comment explaining why it's intentionally unused).
| export function generateRefreshToken(userId: Types.ObjectId, sessionId: string, reduceTime: boolean = false) { | |
| export function generateRefreshToken(userId: Types.ObjectId, sessionId: string, reduceTime: boolean = false) { | |
| // Intentionally kept for API compatibility with callers that may still pass this flag. | |
| // Refresh tokens currently always use the configured default expiration window. | |
| void reduceTime; |
| @@ -1,31 +1,37 @@ | |||
| import crypto from 'crypto'; | |||
There was a problem hiding this comment.
Unused crypto import. This will be flagged by linters/formatters and adds noise; remove it (or use it directly instead of compareHashTokens).
| import crypto from 'crypto'; |
| } | ||
|
|
||
| if (origin && !ALLOWED_ORIGINS.includes(origin)) { | ||
| const originUrl = new URL(origin as string).origin; |
There was a problem hiding this comment.
new URL(origin as string) will throw for non-absolute/invalid values (e.g., Origin: null, malformed Referer). That will turn a bad request into an unhandled exception/500 instead of a clean 401. Wrap URL parsing in a try/catch and convert failures into UnauthorizedError('Invalid origin') (or similar).
| const originUrl = new URL(origin as string).origin; | |
| let originUrl: string; | |
| try { | |
| originUrl = new URL(origin as string).origin; | |
| } catch { | |
| throw new UnauthorizedError('Invalid origin'); | |
| } |
No description provided.