Skip to content
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

feat: csrf support check origin header with referer type #69

Merged
merged 5 commits into from
Jan 13, 2025

Conversation

anthinkingcoder
Copy link
Contributor

@anthinkingcoder anthinkingcoder commented Jul 10, 2020

csrf 防范可以通过检查 Origin 头来验证来源

Identifying Source Origin (via Origin/Referer header)

Summary by CodeRabbit

  • Security Improvements

    • Enhanced CSRF protection by validating both referer and origin headers.
    • Improved error handling and validation messages for CSRF token checks.
  • Testing

    • Updated test case descriptions to reflect dual validation of referer and origin.
    • Added assertions for scenarios involving the origin header.

@codecov
Copy link

codecov bot commented Jul 10, 2020

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 95.89%. Comparing base (79c38e0) to head (51d0223).
Report is 35 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff           @@
##           master      #69   +/-   ##
=======================================
  Coverage   95.89%   95.89%           
=======================================
  Files          32       32           
  Lines         560      560           
=======================================
  Hits          537      537           
  Misses         23       23           

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

app/extend/context.js Outdated Show resolved Hide resolved
Copy link
Contributor

coderabbitai bot commented Jan 13, 2025

Warning

Rate limit exceeded

@fengmk2 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 19 minutes and 29 seconds before requesting another review.

⌛ 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.

📥 Commits

Reviewing files that changed from the base of the PR and between dbdceaa and e618d53.

📒 Files selected for processing (1)
  • test/csrf.test.js (14 hunks)

Walkthrough

The pull request introduces enhancements to the CSRF (Cross-Site Request Forgery) protection mechanism in the application. The changes focus on expanding the validation process to check both referer and origin headers, improving the security and robustness of the CSRF protection. The modifications are implemented in the context extension file and accompanied by corresponding updates to the test cases to ensure comprehensive coverage of the new validation logic.

Changes

File Change Summary
app/extend/context.js Updated CSRF validation to check both referer and origin headers, with enhanced debug messages and error handling.
test/csrf.test.js Updated test cases to reflect new CSRF validation logic, including tests for origin header scenarios.

Sequence Diagram

sequenceDiagram
    participant Client
    participant Server
    participant CSRFValidator

    Client->>Server: Request with headers
    Server->>CSRFValidator: Validate CSRF token
    CSRFValidator->>CSRFValidator: Check referer header
    CSRFValidator->>CSRFValidator: Check origin header
    alt Valid headers
        CSRFValidator-->>Server: Allow request
    else Invalid headers
        CSRFValidator-->>Server: Reject request (403 Forbidden)
    end
    Server-->>Client: Response
Loading

Poem

🐰 A Rabbit's CSRF Rhyme 🛡️

Referer and origin, now we check with care,
Protecting our web from a sneaky cyber snare.
Headers dancing, validation tight,
Keeping our application's defenses bright!
Security hops, no vulnerability in sight! 🚀


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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.

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)
app/extend/context.js (1)

206-207: Consider prioritizing Origin header when present.

While the current implementation correctly accepts either header, the Origin header is more reliable for CSRF protection. Consider prioritizing it when available:

-    const referer = (this.headers.referer || this.headers.origin || '').toLowerCase();
+    // Origin header is more reliable for CSRF protection
+    const referer = (this.headers.origin || this.headers.referer || '').toLowerCase();
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 79c38e0 and 51d0223.

📒 Files selected for processing (2)
  • app/extend/context.js (1 hunks)
  • test/csrf.test.js (14 hunks)
🔇 Additional comments (4)
app/extend/context.js (2)

206-207: LGTM! Enhanced CSRF protection with Origin header check.

The addition of the Origin header check alongside Referer strengthens CSRF protection. The Origin header is more reliable for CSRF prevention as it:

  1. Cannot be spoofed by attackers
  2. Is automatically stripped of path information
  3. Is mandatorily sent by browsers in cross-origin requests

210-212: LGTM! Clear and informative error messages.

Error messages have been updated to accurately reflect that either Referer or Origin header can be used for CSRF validation.

Also applies to: 218-220

test/csrf.test.js (2)

Line range hint 472-486: LGTM! Comprehensive test coverage for Origin header support.

The test suite has been thoroughly updated to verify CSRF protection with both Referer and Origin headers. The tests cover:

  1. Success cases with valid headers
  2. Failure cases with invalid headers
  3. Edge cases and different domain scenarios

Also applies to: 489-504, 524-535, 549-554, 567-571, 584-588, 602-607, 621-626


619-626: LGTM! Consistent error message testing.

The test assertions properly verify the updated error messages for both Referer and Origin header validation scenarios.

Also applies to: 693-694

@fengmk2 fengmk2 self-assigned this Jan 13, 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: 1

🧹 Nitpick comments (2)
test/csrf.test.js (2)

Line range hint 472-708: Consider reorganizing test cases for better maintainability.

The test file has multiple test cases testing similar scenarios with different variations. Consider grouping related tests using describe blocks to improve organization and readability:

  • Group Referer/Origin validation tests
  • Group token validation tests
  • Group configuration type tests (all, any, referer)

Example structure:

describe('CSRF Protection', () => {
  describe('Header Validation', () => {
    describe('Referer/Origin Checks', () => {
      // Tests for correct, incorrect, evil, illegal headers
    });
  });
  
  describe('Configuration Types', () => {
    describe('type: all', () => {
      // Tests for all type
    });
    describe('type: any', () => {
      // Tests for any type
    });
    // etc.
  });
});

Line range hint 472-708: Consider adding edge case tests for Origin header.

While the current test coverage is good, consider adding tests for the following edge cases:

  1. Origin header with different casing (e.g., HTTPS://nodejs.org)
  2. Origin header with port numbers
  3. Origin header with IP addresses (IPv4 and IPv6)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 51d0223 and dbdceaa.

📒 Files selected for processing (2)
  • app/extend/context.js (1 hunks)
  • test/csrf.test.js (14 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • app/extend/context.js
🧰 Additional context used
🪛 Biome (1.9.4)
test/csrf.test.js

[error] 550-550: yield is only allowed within generator functions.

(parse)

🔇 Additional comments (2)
test/csrf.test.js (2)

Line range hint 472-487: LGTM! Good test coverage for both Referer and Origin headers.

The test case properly validates that requests with either a correct Referer or Origin header from whitelisted domains are accepted.


Line range hint 640-668: LGTM! Comprehensive coverage of CSRF type configurations.

The test cases thoroughly validate the behavior of different CSRF configuration types:

  • all: Requires both token and header validation
  • any: Requires either token or header validation

Comment on lines 550 to 555
yield this.app.httpRequest()
.post('/update')
.set('accept', 'text/html')
.set('origin', 'https://wwwnodejs.org/en/')
.set('host', 'nodejs.org')
.expect(403);
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

Fix syntax error in test case.

The test case contains a syntax error using yield instead of await.

Apply this diff to fix the syntax error:

-    yield this.app.httpRequest()
+    await app.httpRequest()
📝 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
yield this.app.httpRequest()
.post('/update')
.set('accept', 'text/html')
.set('origin', 'https://wwwnodejs.org/en/')
.set('host', 'nodejs.org')
.expect(403);
await this.app.httpRequest()
.post('/update')
.set('accept', 'text/html')
.set('origin', 'https://wwwnodejs.org/en/')
.set('host', 'nodejs.org')
.expect(403);
🧰 Tools
🪛 Biome (1.9.4)

[error] 550-550: yield is only allowed within generator functions.

(parse)

Copy link

pkg-pr-new bot commented Jan 13, 2025

Open in Stackblitz

npm i https://pkg.pr.new/eggjs/egg-security@69

commit: e618d53

@fengmk2 fengmk2 merged commit 2c950d3 into eggjs:master Jan 13, 2025
21 of 24 checks passed
fengmk2 pushed a commit that referenced this pull request Jan 13, 2025
[skip ci]

## [3.7.0](v3.6.0...v3.7.0) (2025-01-13)

### Features

* csrf support check origin header with referer type ([#69](#69)) ([2c950d3](2c950d3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants