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: add rotateWhenInvalid option for CSRF token #98

Merged
merged 2 commits into from
Jul 3, 2024

Conversation

hongzzz
Copy link
Contributor

@hongzzz hongzzz commented Jul 2, 2024

closes #97

Summary by CodeRabbit

  • New Features

    • Introduced a new security option rotateWhenInvalid to control CSRF token rotation when invalid, enhancing overall security.
  • Documentation

    • Updated README.md and README.zh-CN.md to include the new rotateWhenInvalid configuration option.
  • Tests

    • Added test cases to verify CSRF token rotation behavior when rotateWhenInvalid is enabled.

Copy link
Contributor

coderabbitai bot commented Jul 2, 2024

Walkthrough

The update introduces a new configuration option, rotateWhenInvalid, to the CSRF security settings. This option determines whether the CSRF secret should be rotated when an invalid CSRF token is detected, thereby enhancing security. By default, this option is set to false. Changes have been made across various documentation and code files to accommodate this feature, including updating configurations, context logic, and test cases.

Changes

File Change Summary
README.md Added rotateWhenInvalid to security configuration summary.
README.zh-CN.md Added rotateWhenInvalid to security configuration summary in Chinese.
.../context.js Included logic to rotate CSRF secret if rotateWhenInvalid is true.
.../config.default.js Added rotateWhenInvalid set to false in CSRF configuration.
.../csrf.test.js Added a test case for verifying behavior with rotateWhenInvalid.

Assessment against linked issues

Objective Addressed Explanation
Add an option to rotate CSRF token when it is invalid (#97)

Poem

In the heart of code, a change so neat,
With rotateWhenInvalid, security's sweet.
Tokens now fresh when they're found to be flawed,
A safer web, with just a nod.
The rabbit hops through fields of code,
Ensuring the secure, seamless node.
🌼🛡️🚀

Tip

AI model upgrade

gpt-4o model for reviews and chat is now live

OpenAI claims that this model is better at understanding and generating code than the previous models. Please join our Discord Community to provide any feedback or to report any issues.


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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: 2

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 4711437 and f315dd1.

Files selected for processing (5)
  • README.md (1 hunks)
  • README.zh-CN.md (1 hunks)
  • app/extend/context.js (1 hunks)
  • config/config.default.js (1 hunks)
  • test/csrf.test.js (1 hunks)
Additional comments not posted (3)
app/extend/context.js (1)

203-206: Ensure proper logging for CSRF secret rotation.

Consider adding logging to indicate when the CSRF secret is rotated for better traceability.

    const { rotateWhenInvalid } = this.app.config.security.csrf;
    if (rotateWhenInvalid) {
      this.rotateCsrfSecret();
+     this.logger.info('CSRF secret rotated due to invalid token');
    }
README.zh-CN.md (1)

146-146: Ensure clarity in the documentation for rotateWhenInvalid.

The documentation for rotateWhenInvalid is clear and correctly placed.

README.md (1)

217-217: Ensure clarity in the documentation for rotateWhenInvalid.

The documentation for rotateWhenInvalid is clear and correctly placed.

Comment on lines +286 to +295
it('token should be rotated when enable rotateWhenInvalid', async () => {
mm(app.config.security.csrf, 'rotateWhenInvalid', true);
await app.httpRequest()
.post('/update')
.set('x-csrf-token', '2')
.set('cookie', 'csrfToken=1')
.send({ title: 'invalid token' })
.expect(403)
.expect(res => assert(!!res.header['set-cookie']));
});
Copy link
Contributor

Choose a reason for hiding this comment

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

Add comments for clarity.

The test function is well-structured and correctly tests the new functionality. Adding comments will improve readability and maintainability.

+  // Test to check if the CSRF token is rotated when `rotateWhenInvalid` is enabled
  it('token should be rotated when enable rotateWhenInvalid', async () => {
+    // Mock the `rotateWhenInvalid` configuration to true
    mm(app.config.security.csrf, 'rotateWhenInvalid', true);
+    // Perform an HTTP request with an invalid CSRF token
    await app.httpRequest()
      .post('/update')
      .set('x-csrf-token', '2')
      .set('cookie', 'csrfToken=1')
      .send({ title: 'invalid token' })
      .expect(403)
+      // Assert that the CSRF token is rotated by checking the `set-cookie` header
      .expect(res => assert(!!res.header['set-cookie']));
  });
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
it('token should be rotated when enable rotateWhenInvalid', async () => {
mm(app.config.security.csrf, 'rotateWhenInvalid', true);
await app.httpRequest()
.post('/update')
.set('x-csrf-token', '2')
.set('cookie', 'csrfToken=1')
.send({ title: 'invalid token' })
.expect(403)
.expect(res => assert(!!res.header['set-cookie']));
});
// Test to check if the CSRF token is rotated when `rotateWhenInvalid` is enabled
it('token should be rotated when enable rotateWhenInvalid', async () => {
// Mock the `rotateWhenInvalid` configuration to true
mm(app.config.security.csrf, 'rotateWhenInvalid', true);
// Perform an HTTP request with an invalid CSRF token
await app.httpRequest()
.post('/update')
.set('x-csrf-token', '2')
.set('cookie', 'csrfToken=1')
.send({ title: 'invalid token' })
.expect(403)
// Assert that the CSRF token is rotated by checking the `set-cookie` header
.expect(res => assert(!!res.header['set-cookie']));
});

@@ -42,6 +42,7 @@ module.exports = () => {
headerName: 'x-csrf-token',
bodyName: '_csrf',
queryName: '_csrf',
rotateWhenInvalid: false,
Copy link
Contributor

Choose a reason for hiding this comment

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

Add documentation for the new rotateWhenInvalid option.

Ensure that the new rotateWhenInvalid option is documented within the comments for the csrf configuration.

   * @property {Object} csrf - whether defend csrf attack
   * @property {Object} xframe - whether enable X-Frame-Options response header, default SAMEORIGIN
   * @property {Object} hsts - whether enable Strict-Transport-Security response header, default is one year
   * @property {Object} methodnoallow - whether enable Http Method filter
   * @property {Object} noopen - whether enable IE automaticlly download open
   * @property {Object} nosniff -  whether enable IE8 automaticlly dedect mime
   * @property {Object} xssProtection -  whether enable IE8 XSS Filter, default is open
   * @property {Object} csp - content security policy config
   * @property {Object} referrerPolicy - referrer policy config
   * @property {Object} dta - auto avoid directory traversal attack
   * @property {Array} domainWhiteList - domain white list
   * @property {Array} protocolWhiteList - protocal white list
   * @property {Boolean} rotateWhenInvalid - rotate CSRF secret when token is invalid
   */
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
rotateWhenInvalid: false,
* @property {Object} csrf - whether defend csrf attack
* @property {Object} xframe - whether enable X-Frame-Options response header, default SAMEORIGIN
* @property {Object} hsts - whether enable Strict-Transport-Security response header, default is one year
* @property {Object} methodnoallow - whether enable Http Method filter
* @property {Object} noopen - whether enable IE automaticlly download open
* @property {Object} nosniff - whether enable IE8 automaticlly dedect mime
* @property {Object} xssProtection - whether enable IE8 XSS Filter, default is open
* @property {Object} csp - content security policy config
* @property {Object} referrerPolicy - referrer policy config
* @property {Object} dta - auto avoid directory traversal attack
* @property {Array} domainWhiteList - domain white list
* @property {Array} protocolWhiteList - protocal white list
* @property {Boolean} rotateWhenInvalid - rotate CSRF secret when token is invalid

Copy link

pkg-pr-new bot commented Jul 3, 2024

Review PR in StackBlitz Codeflow Run & review this pull request in StackBlitz Codeflow.

commit: 3fe56e0

egg-security

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


templates

README.zh-CN.md Outdated Show resolved Hide resolved
@fengmk2 fengmk2 self-assigned this Jul 3, 2024
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between f315dd1 and 3fe56e0.

Files selected for processing (2)
  • README.md (1 hunks)
  • README.zh-CN.md (1 hunks)
Files skipped from review as they are similar to previous changes (2)
  • README.md
  • README.zh-CN.md

@fengmk2
Copy link
Member

fengmk2 commented Jul 3, 2024

@hongzzz 很棒的功能!感谢贡献!

@fengmk2 fengmk2 merged commit ae37c8f into eggjs:master Jul 3, 2024
23 checks passed
fengmk2 pushed a commit that referenced this pull request Jul 3, 2024
[skip ci]

## [3.5.0](v3.4.0...v3.5.0) (2024-07-03)

### Features

* add rotateWhenInvalid option for CSRF token ([#98](#98)) ([ae37c8f](ae37c8f))
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.

csrf 中间件 invalid csrf token 时,能否加一个option 来选择是否 rotate 来刷新 token?
2 participants