Skip to content

Api logic building - #23

Merged
azeemstack merged 2 commits into
mainfrom
API-LogicBuilding
Apr 16, 2026
Merged

azeemstack merged 2 commits into
mainfrom
API-LogicBuilding

Conversation

@azeemstack

Copy link
Copy Markdown
Owner

No description provided.

Copilot AI review requested due to automatic review settings April 16, 2026 00:34
@coderabbitai

coderabbitai Bot commented Apr 16, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@benazeem has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 0 minutes and 13 seconds before requesting another review.

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 0 minutes and 13 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 61304c71-25ae-49da-ad58-6b30cc533ce9

📥 Commits

Reviewing files that changed from the base of the PR and between 982f0cc and a3bd69f.

📒 Files selected for processing (1)
  • src/middleware/security/requireCsrf.ts
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch API-LogicBuilding

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@azeemstack
azeemstack merged commit 247fdc3 into main Apr 16, 2026
4 checks passed

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Updates the Express CSRF middleware to add token normalization, safer parsing of Origin/Referer, and additional logging to diagnose mismatches for API requests guarded by csrfMiddleware.

Changes:

  • Refactors unsafe-method detection into a shared constant and introduces token normalization before comparison.
  • Replaces the prior CSRF token comparison helper with a local timingSafeEqual-based compare.
  • Adds origin parsing/validation handling and warning logs on CSRF validation failures.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +31 to +42
const rawOrigin = req.headers.origin || req.headers.referer;

if (rawOrigin) {
try {
const originUrl = new URL(rawOrigin as string).origin;

if (!ALLOWED_ORIGINS.includes(originUrl)) {
return next(new UnauthorizedError('Invalid origin'));
}
} catch {
return next(new UnauthorizedError('Invalid origin format'));
}

Copilot AI Apr 16, 2026

Copy link

Choose a reason for hiding this comment

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

The middleware no longer rejects unsafe requests when both Origin and Referer headers are missing (it simply skips origin validation if rawOrigin is falsy). This is a security regression compared to the previous behavior and weakens CSRF defenses for user-agents/clients that omit these headers. Consider restoring a hard-fail for unsafe methods when neither header is present (or making the exception explicit and gated by trusted internal clients).

Suggested change
const rawOrigin = req.headers.origin || req.headers.referer;
if (rawOrigin) {
try {
const originUrl = new URL(rawOrigin as string).origin;
if (!ALLOWED_ORIGINS.includes(originUrl)) {
return next(new UnauthorizedError('Invalid origin'));
}
} catch {
return next(new UnauthorizedError('Invalid origin format'));
}
const originHeader = Array.isArray(req.headers.origin) ? req.headers.origin[0] : req.headers.origin;
const refererHeader = Array.isArray(req.headers.referer) ? req.headers.referer[0] : req.headers.referer;
const rawOrigin = originHeader || refererHeader;
if (!rawOrigin) {
return next(new UnauthorizedError('Origin or Referer header required'));
}
try {
const originUrl = new URL(rawOrigin).origin;
if (!ALLOWED_ORIGINS.includes(originUrl)) {
return next(new UnauthorizedError('Invalid origin'));
}
} catch {
return next(new UnauthorizedError('Invalid origin format'));

Copilot uses AI. Check for mistakes.
Comment on lines +59 to +67
if (!isValid) {
logger.warn(`'CSRF DEBUG',
header: ${csrfHeader},
cookie: ${csrfCookieRaw},
normalizedHeader: ${csrfToken},
normalizedCookie: ${csrfCookie},
headerLength: ${csrfToken.length},
cookieLength: ${csrfCookie.length},
`);

Copilot AI Apr 16, 2026

Copy link

Choose a reason for hiding this comment

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

logger.warn logs raw and normalized CSRF token values from both the header and cookie. CSRF tokens are secrets and can be replayed; writing them to logs is a sensitive data exposure risk (and warn level is likely to be retained in production). Remove token values from logs (at most log non-sensitive metadata like lengths or a one-way hash) and ensure any debug logging is gated behind a non-production flag and uses an appropriate log level.

Copilot uses AI. Check for mistakes.
Comment on lines +17 to +24
const safeCompare = (a: string, b: string): boolean => {
const aBuf = Buffer.from(a);
const bBuf = Buffer.from(b);

if (aBuf.length !== bBuf.length) return false;

return crypto.timingSafeEqual(aBuf, bBuf);
};

Copilot AI Apr 16, 2026

Copy link

Choose a reason for hiding this comment

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

safeCompare duplicates the existing compareHashTokens helper in @utils/tokens.js (both do a length check and crypto.timingSafeEqual). Duplicating this logic increases maintenance cost and leaves the exported util unused after this change. Prefer reusing the shared helper (or moving/renaming so there is a single canonical implementation).

Copilot uses AI. Check for mistakes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants