Skip to content

Conversation

@gaby
Copy link
Member

@gaby gaby commented Aug 20, 2025

Summary

  • ensure CSRF trusted-origin parsing mirrors CORS logic
  • harden CSRF subdomain matching and cover edge cases
  • test malformed subdomain rejection

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 20, 2025

Walkthrough

Refactors CSRF trusted-origin parsing to trim and normalize entries, adds explicit wildcard base-origin handling, and hardens subdomain matching logic. Updates CSRF and helper tests to align with new suffix semantics and to cover malformed subdomain cases. Public API unchanged.

Changes

Cohort / File(s) Summary of Changes
Trusted origins parsing
middleware/csrf/csrf.go
Trim origins before processing; detect wildcard entries post-trim; derive and validate base origin without wildcard via normalizeOrigin; reconstruct subdomain with actual scheme; maintain panic on invalid formats.
Subdomain match hardening
middleware/csrf/helpers.go
Replace simple prefix/suffix check with dot-aware validation: require separator dots, ensure non-empty middle label(s), guard against malformed labels and edge cases; early-return control flow.
CSRF tests
middleware/csrf/csrf_test.go
Add test ensuring malformed subdomain origin is rejected (expects 403); positioned among existing trusted-origin tests.
Helper tests/benchmarks
middleware/csrf/helpers_test.go
Switch suffix expectations from ".example.com" to "example.com"; add edge-case tests (malformed/empty labels); update benchmark suffix accordingly.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Client
  participant CSRF as CSRF Middleware
  participant Parser as TrustedOrigins Parser
  participant Matcher as subdomain.match

  rect rgba(230,245,255,0.6)
    note over Parser: Init (on startup/config)
    Parser->>Parser: Trim cfg.TrustedOrigins
    Parser->>Parser: If wildcard, strip "*" and normalize base
    Parser->>Parser: Store exact or wildcard-base entry
  end

  Client->>CSRF: HTTP Request (Origin/Referer, Cookie/Token)
  CSRF->>CSRF: Validate CSRF token
  alt Origin present
    CSRF->>Matcher: Is request origin in trusted origins?
    opt Wildcard entry
      CSRF->>Matcher: prefix/suffix dot-aware check
      Matcher-->>CSRF: true/false
    end
    alt Match
      CSRF-->>Client: Proceed
    else No match
      CSRF-->>Client: 403 Forbidden
    end
  else No Origin
    CSRF-->>Client: Proceed (per existing rules)
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • efectn
  • sixcolors
  • ReneWerner87

Poem

A rabbit trims the tails of schemes,
Wildcards tamed, no sloppy seams.
Dots aligned in careful rows,
Empty labels—out it throws.
With steady paws and guarded gate,
Bad subdomains meet their fate.
Hop secure, validate!

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 2025-08-20-04-30-35

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.

@gaby gaby added this to v3 Aug 20, 2025
@gaby gaby added this to the v3 milestone Aug 20, 2025
@gaby gaby moved this to In Progress in v3 Aug 20, 2025
@gaby gaby changed the title refactor(csrf): align subdomain matching with cors 🐛 bug: Fix CSRF subdomain wildcard boundary Aug 20, 2025
@codecov
Copy link

codecov bot commented Aug 20, 2025

Codecov Report

❌ Patch coverage is 88.00000% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 91.80%. Comparing base (ac909e8) to head (98a494d).
⚠️ Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
middleware/csrf/helpers.go 84.21% 2 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3694      +/-   ##
==========================================
- Coverage   91.81%   91.80%   -0.02%     
==========================================
  Files         114      114              
  Lines       11498    11517      +19     
==========================================
+ Hits        10557    10573      +16     
- Misses        681      683       +2     
- Partials      260      261       +1     
Flag Coverage Δ
unittests 91.80% <88.00%> (-0.02%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

⚠️ Performance Alert ⚠️

Possible performance regression was detected for benchmark.
Benchmark result of this commit is worse than the previous benchmark result exceeding threshold 1.50.

Benchmark suite Current: 57a9f29 Previous: 9ed35c9 Ratio
Benchmark_Compress_Levels_Parallel/Brotli_LevelBestCompression - B/op 1 B/op 0 B/op +∞

This comment was automatically generated by workflow using github-action-benchmark.

@gaby gaby marked this pull request as ready for review August 20, 2025 06:30
Copilot AI review requested due to automatic review settings August 20, 2025 06:30
@gaby gaby requested a review from a team as a code owner August 20, 2025 06:30
@gaby
Copy link
Member Author

gaby commented Aug 20, 2025

/gemini review

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR fixes CSRF subdomain wildcard boundary validation by hardening the subdomain matching logic to prevent bypass attacks and ensuring proper parsing of trusted origins. The changes align CSRF subdomain validation with CORS logic for consistency.

Key changes:

  • Enhanced subdomain matching with proper boundary validation and malformed input rejection
  • Fixed trusted origin parsing to correctly handle wildcard patterns
  • Added comprehensive test coverage for edge cases and malformed inputs

Reviewed Changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.

File Description
middleware/csrf/helpers.go Replaces simple string matching with robust boundary validation logic
middleware/csrf/csrf.go Fixes trusted origin parsing to properly extract scheme and host components
middleware/csrf/helpers_test.go Updates test cases to reflect new suffix format and adds edge case coverage
middleware/csrf/csrf_test.go Adds test for malformed subdomain attack vector

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request effectively addresses a security vulnerability in the CSRF subdomain wildcard matching by hardening the logic and expanding test coverage for edge cases. The refactoring of the trusted origin parsing in middleware/csrf/csrf.go improves clarity and robustness. The new subdomain.match logic in middleware/csrf/helpers.go correctly handles various malformed origin formats, and the new tests are a valuable addition. I have a couple of suggestions to further refine the code.

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 (4)
middleware/csrf/csrf_test.go (1)

853-866: Good addition: malformed subdomain origin is correctly rejected

The case "http://evil.comdomain-1.com" while host is "domain-1.com" should indeed be denied. This test guards against suffix substring tricks and aligns with the hardened Subdomain.match.

Consider adding:

  • The same malformed subdomain with https scheme.
  • A referer-based counterpart to ensure parity when Origin is absent on HTTPS.

If you want, I can draft those tests.

middleware/csrf/helpers.go (1)

55-84: Subdomain matching hardened and precise; logic LGTM

The guarded checks are clear and correct:

  • Length guard prevents trivial underflows.
  • Combined HasPrefix/HasSuffix assures scheme and base host alignment.
  • Dot-before-suffix constraint + non-empty label validation block suffix-substring attacks (e.g., evil.comexample.com) and empty labels (., ..).

No functional gaps spotted for wildcard host semantics; ports are naturally handled since they’re part of the suffix.

Optional: micro-clarify expectations in a short doc comment above match, e.g., that prefix normally ends at "://", and suffix is the base host (possibly with port).

middleware/csrf/csrf.go (1)

63-79: Wildcard parsing mirrors CORS and feeds the stronger matcher; one tiny trim nit

The approach of stripping "://*." to derive a base origin, normalizing, then building subdomain{prefix: scheme://, suffix: host[:port]} is sound and avoids false positives.

Minor nit: utils.Trim(origin, ' ') only trims spaces, not other whitespace. Using TrimSpace is more robust without changing semantics here.

Apply within this hunk:

-        trimmedOrigin := utils.Trim(origin, ' ')
+        trimmedOrigin := strings.TrimSpace(origin)
middleware/csrf/helpers_test.go (1)

66-67: Tests aligned with new suffix semantics; edge cases covered

  • Updating suffixes from ".example.com" to "example.com" matches the new matcher contract.
  • New negatives for malformed subdomain and empty/malformed labels are valuable and map directly to the new guards.
  • Benchmark updated accordingly.

One small naming nit: there are two cases labeled "match with different scheme" (Line 65 and Line 71). Renaming for uniqueness improves failure reporting (e.g., "no match with different scheme (prefix anchored)" vs "no match with different scheme (scheme mismatch)").

Would you like me to propose exact renames?

Also applies to: 72-73, 78-79, 84-85, 91-92, 97-98, 103-104, 107-112, 115-116, 119-130, 145-146

📜 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 sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between ac909e8 and 98a494d.

📒 Files selected for processing (4)
  • middleware/csrf/csrf.go (1 hunks)
  • middleware/csrf/csrf_test.go (1 hunks)
  • middleware/csrf/helpers.go (1 hunks)
  • middleware/csrf/helpers_test.go (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
middleware/csrf/csrf_test.go (2)
constants.go (2)
  • MethodPost (7-7)
  • HeaderOrigin (206-206)
middleware/csrf/config.go (2)
  • HeaderName (120-120)
  • ConfigDefault (123-130)
⏰ 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). (7)
  • GitHub Check: unit (1.25.x, macos-13)
  • GitHub Check: repeated
  • GitHub Check: unit (1.25.x, windows-latest)
  • GitHub Check: unit (1.25.x, macos-latest)
  • GitHub Check: Analyse
  • GitHub Check: Compare
  • GitHub Check: lint

@ReneWerner87 ReneWerner87 merged commit f121fd3 into main Aug 21, 2025
14 of 15 checks passed
@ReneWerner87 ReneWerner87 deleted the 2025-08-20-04-30-35 branch August 21, 2025 06:36
@github-project-automation github-project-automation bot moved this from In Progress to Done in v3 Aug 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants