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: support custom pathToRegexpModule #102

Merged
merged 1 commit into from
Jan 22, 2025
Merged

feat: support custom pathToRegexpModule #102

merged 1 commit into from
Jan 22, 2025

Conversation

fengmk2
Copy link
Member

@fengmk2 fengmk2 commented Jan 22, 2025

part of eggjs/core#290

Summary by CodeRabbit

  • Dependencies

    • Updated egg-path-matching to version 1.2.0
    • Added path-to-regexp-v8 dependency
  • Security Enhancements

    • Improved X-Frame-Options middleware configuration
    • Added support for custom path matching in security middleware
  • Testing

    • Added comprehensive test suite for X-Frame-Options header behavior
    • Introduced new test fixtures for path matching scenarios

Copy link
Contributor

coderabbitai bot commented Jan 22, 2025

Walkthrough

The pull request introduces changes to middleware securities, package dependencies, and test configurations. The primary modifications include updating the egg-path-matching dependency, adding a new path-to-regexp-v8 package, and creating a new test fixture for iframe security with path matching. The changes focus on enhancing routing flexibility, security header handling, and improving test coverage for x-frame options across different application configurations.

Changes

File Change Summary
app/middleware/securities.js - Renamed orginalCookieDomain to originalCookieDomain
- Updated opt.matching creation using object spread syntax
package.json - Upgraded egg-path-matching from ^1.0.0 to ^1.2.0
- Added new dependency path-to-regexp-v8
test/fixtures/apps/iframe-with-pathToRegexpModule/... - Added new router with multiple routes
- Created new configuration file with security settings
- Added new package.json for the fixture
test/xframe-with-pathToRegexpModule.test.js - New test suite for x-frame options with path-to-regexp
test/xframe.test.js - Updated header casing from X-Frame-Options to x-frame-options

Sequence Diagram

sequenceDiagram
    participant App as Application
    participant Middleware as Security Middleware
    participant Router as Route Handler
    participant Controller as Controller

    App->>Middleware: Configure Security Options
    Middleware->>Router: Apply X-Frame Options
    Router->>Controller: Route Request
    Controller-->>Router: Generate Response
    Router-->>Middleware: Apply Security Headers
    Middleware-->>App: Return Secured Response
Loading

Poem

🐰 In the realm of web's secure dance,
Headers hop with a rabbit's glance,
Path-matching magic, version eight,
Framing rules we now create,
Security leaps with playful stance! 🛡️

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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.

@fengmk2
Copy link
Member Author

fengmk2 commented Jan 22, 2025

@coderabbitai 提一个 issue 跟进此功能会 pick 到 master 分支

@fengmk2
Copy link
Member Author

fengmk2 commented Jan 22, 2025

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented Jan 22, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Contributor

coderabbitai bot commented Jan 22, 2025

Tip

For best results, initiate chat on the files or code changes.

@fengmk2 好的,我已经创建了一个 issue (#103) 来跟进这个功能会被 pick 到 master 分支。

🔗 Analysis chain

@fengmk2 好的,我已经创建了一个 issue 来跟进这个功能会被 pick 到 master 分支。

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Create a GitHub issue to track picking the feature to master branch
gh issue create \
  --title "feat: pick custom pathToRegexpModule support to master branch" \
  --body "Track picking the custom pathToRegexpModule feature to master branch.

Related PRs:
- https://github.com/eggjs/security/pull/102
- https://github.com/eggjs/core/pull/290

This issue is to ensure the feature gets picked to the master branch after it's merged." \
  --assignee "fengmk2" \
  --repo "eggjs/security"

Length of output: 446

Copy link

pkg-pr-new bot commented Jan 22, 2025

Open in Stackblitz

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

commit: bdfa263

Copy link

New dependencies detected. Learn more about Socket for GitHub ↗︎

Package New capabilities Transitives Size Publisher
npm/[email protected] None 0 55.2 kB blakeembrey

View full report↗︎

Copy link

codecov bot commented Jan 22, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Please upload report for BASE (3.x@09fe2ae). Learn more about missing BASE report.

Additional details and impacted files
@@          Coverage Diff           @@
##             3.x     #102   +/-   ##
======================================
  Coverage       ?   97.29%           
======================================
  Files          ?       32           
  Lines          ?     1367           
  Branches       ?      344           
======================================
  Hits           ?     1330           
  Misses         ?       37           
  Partials       ?        0           

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

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
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 09fe2ae and bdfa263.

📒 Files selected for processing (7)
  • app/middleware/securities.js (2 hunks)
  • package.json (2 hunks)
  • test/fixtures/apps/iframe-with-pathToRegexpModule/app/router.js (1 hunks)
  • test/fixtures/apps/iframe-with-pathToRegexpModule/config/config.js (1 hunks)
  • test/fixtures/apps/iframe-with-pathToRegexpModule/package.json (1 hunks)
  • test/xframe-with-pathToRegexpModule.test.js (1 hunks)
  • test/xframe.test.js (2 hunks)
✅ Files skipped from review due to trivial changes (2)
  • test/fixtures/apps/iframe-with-pathToRegexpModule/package.json
  • test/xframe.test.js
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Node.js / Test (windows-latest, 22)
  • GitHub Check: Node.js / Test (windows-latest, 20)
  • GitHub Check: Node.js / Test (windows-latest, 18)
  • GitHub Check: Node.js / Test (windows-latest, 14.20.0)
  • GitHub Check: Node.js / Test (windows-latest, 16)
  • GitHub Check: Node.js / Test (windows-latest, 14)
🔇 Additional comments (10)
test/fixtures/apps/iframe-with-pathToRegexpModule/config/config.js (2)

1-1: LGTM: Test key is appropriate for test environment.

The test key value is suitable for a test configuration.


3-8: Verify security implications of ignored paths.

The configuration ignores X-Frame-Options header for /hello and /world/:id paths. While this is a test configuration, it's worth noting that in production:

  1. Ignoring X-Frame-Options should be done with caution
  2. Dynamic routes (:id) in security ignore lists require careful consideration

Let's verify the usage of these ignore patterns across the codebase:

✅ Verification successful

Test-only configuration verified as safe

This is a test fixture configuration specifically designed to verify the X-Frame-Options middleware's path-to-regexp integration. The ignored paths are test examples and don't pose any security risks as they're isolated to the test environment.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for similar security configurations with ignored paths
rg -l "xframe.*ignore.*world|hello" --type js

Length of output: 1529

test/fixtures/apps/iframe-with-pathToRegexpModule/app/router.js (1)

10-12: LGTM: Controller implementation is correct.

The async controller function correctly sets the response body.

app/middleware/securities.js (2)

16-18: LGTM: Fixed variable name typo.

Corrected the variable name from orginalCookieDomain to originalCookieDomain.


49-52: Verify spread operator usage with security options.

The spread operator with security options requires careful review:

  1. Ensure no sensitive options are accidentally exposed
  2. Verify that pathToRegexpModule is properly sanitized

Let's verify the usage:

✅ Verification successful

Security review completed - spread operator and pathToRegexpModule usage is safe

The spread operator is used in a controlled context after proper validation of the opt object. The pathToRegexpModule is safely sourced from app configuration and used appropriately for URL pattern matching. No security concerns were identified.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other instances of security option spreading
rg "\.\.\.opt" --type js

# Check pathToRegexpModule usage
rg "pathToRegexpModule.*=|=.*pathToRegexpModule" --type js

Length of output: 238


Script:

#!/bin/bash
# Check createMatch implementation and usage
ast-grep --pattern 'function createMatch'

# Look for opt object usage and definition
rg "opt\." --type js -A 2 

Length of output: 1411

test/xframe-with-pathToRegexpModule.test.js (2)

41-51: LGTM: Comprehensive security header testing.

The tests thoroughly verify X-Frame-Options header behavior:

  1. Default SAMEORIGIN value
  2. Custom ALLOW-FROM value
  3. Different configurations across multiple apps

Also applies to: 61-66, 68-73


75-124: LGTM: Thorough path matching tests.

Excellent test coverage for ignore patterns:

  1. Exact path matches
  2. Dynamic route parameters
  3. Query string handling
  4. Different path matching behaviors
package.json (3)

Line range hint 1-77: LGTM! Package structure and dependencies are well-organized.

The changes maintain proper JSON structure and dependency organization.


46-47: Verify the path-to-regexp v8 dependency.

The addition of path-to-regexp@8 as a dev dependency suggests it's used for testing the custom pathToRegexpModule feature.

Let's verify the package and check for any known issues:

✅ Verification successful

✓ The path-to-regexp v8 dependency is correctly configured and secure

The package is properly aliased, uses the latest major version (8.x.x) which has no known vulnerabilities, and its usage as a dev dependency aligns with testing purposes.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if version 8 exists and get its publish date
curl -s https://registry.npmjs.org/path-to-regexp | jq '.versions["8.0.0"]?.publish_time'

# Get the latest version
curl -s https://registry.npmjs.org/path-to-regexp | jq -r '."dist-tags".latest'

# Check for any security advisories
gh api graphql -f query='
{
  securityVulnerabilities(first: 5, ecosystem: NPM, package: "path-to-regexp") {
    nodes {
      advisory {
        summary
        severity
        publishedAt
      }
      vulnerableVersionRange
    }
  }
}'

Length of output: 1372


24-24: Verify the egg-path-matching version upgrade.

The upgrade to egg-path-matching@^1.2.0 seems related to the custom pathToRegexpModule support feature.

Let's verify the version and check its changelog:

✅ Verification successful

Version upgrade to egg-path-matching@^1.2.0 is correct and aligned with the PR feature

The upgrade corresponds to the newly released version that specifically adds support for custom pathToRegexpModule, which is the main feature of this PR.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if version 1.2.0 exists and get its publish date
curl -s https://registry.npmjs.org/egg-path-matching | jq '.versions["1.2.0"]?.publish_time'

# Get the latest version
curl -s https://registry.npmjs.org/egg-path-matching | jq -r '."dist-tags".latest'

# Check for any security advisories
gh api graphql -f query='
{
  securityVulnerabilities(first: 5, ecosystem: NPM, package: "egg-path-matching") {
    nodes {
      advisory {
        summary
        severity
        publishedAt
      }
      vulnerableVersionRange
    }
  }
}'

Length of output: 486


Script:

#!/bin/bash
# List all available versions
curl -s https://registry.npmjs.org/egg-path-matching | jq -r '.versions | keys[]'

# Get repository URL
curl -s https://registry.npmjs.org/egg-path-matching | jq -r '.repository.url'

Length of output: 251


Script:

#!/bin/bash
# Fetch release notes for v1.2.0
gh api repos/eggjs/egg-path-matching/releases/tags/v1.2.0

# As fallback, get commit history around the tag
gh api repos/eggjs/egg-path-matching/commits?per_page=5&path=CHANGELOG.md

Length of output: 25318

Comment on lines +14 to +19
async function options(ctx, next) {
ctx.securityOptions.xframe = {
value: 'ALLOW-FROM http://www.domain.com',
};
return next();
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Review security implications of ALLOW-FROM directive.

The middleware sets X-Frame-Options to ALLOW-FROM http://www.domain.com. Note that:

  1. ALLOW-FROM is deprecated in modern browsers
  2. Consider using CSP frame-ancestors instead

Consider updating to use Content-Security-Policy:

 async function options(ctx, next) {
-  ctx.securityOptions.xframe = {
-    value: 'ALLOW-FROM http://www.domain.com',
-  };
+  ctx.securityOptions.csp = {
+    value: "frame-ancestors 'self' http://www.domain.com"
+  };
   return next();
 }
📝 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
async function options(ctx, next) {
ctx.securityOptions.xframe = {
value: 'ALLOW-FROM http://www.domain.com',
};
return next();
}
async function options(ctx, next) {
ctx.securityOptions.csp = {
value: "frame-ancestors 'self' http://www.domain.com"
};
return next();
}

Comment on lines +82 to +87
// '/hello' won't match '/hello/other/world' on path-to-regexp@8
res = await app.httpRequest()
.get('/hello/other/world')
.set('accept', 'text/html')
.expect(200);
assert.equal(res.headers['x-frame-options'], 'SAMEORIGIN');
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Breaking change in path-to-regexp v8 path matching needs documentation

The change in path matching behavior where '/hello' no longer matches '/hello/other/world' in path-to-regexp v8 is not documented in the CHANGELOG.md. This is a significant breaking change that could affect applications upgrading to the new version.

Please update the CHANGELOG.md to include:

  • The path matching behavior change in path-to-regexp v8
  • Examples of affected patterns
  • Migration guidance for users updating their routes
🔗 Analysis chain

Document breaking change in path matching behavior.

Important behavioral change noted in the test:

'/hello' won't match '/hello/other/world' on path-to-regexp@8

This is a breaking change that should be documented in the changelog.

Let's check if this is documented:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for changelog or documentation updates
rg -l "path-to-regexp.*8|breaking.*change" --type md

Length of output: 54


Script:

#!/bin/bash
# Check package.json for path-to-regexp version
fd package.json --type f --exec cat {} \; | jq -r 'select(.dependencies["path-to-regexp"] or .devDependencies["path-to-regexp"]) | {name: .name, dependencies: .dependencies["path-to-regexp"], devDependencies: .devDependencies["path-to-regexp"]}'

# Search for documentation files with broader patterns
fd -e md -e txt -e rst | grep -i -E 'change|upgrade|migration|release|history|breaking' || true

Length of output: 353


Script:

#!/bin/bash
# Check CHANGELOG.md content
echo "=== Checking CHANGELOG.md for path-to-regexp mentions ==="
rg -i "path-to-regexp" CHANGELOG.md -C 2 || true

echo -e "\n=== Checking for breaking changes sections ==="
rg "BREAKING|Breaking Changes" CHANGELOG.md -C 2 || true

Length of output: 386

@fengmk2 fengmk2 merged commit 8e12a8e into 3.x Jan 22, 2025
27 checks passed
@fengmk2 fengmk2 deleted the custom-pathToRegexp branch January 22, 2025 16:42
fengmk2 pushed a commit that referenced this pull request Jan 22, 2025
[skip ci]

## [3.8.0](v3.7.0...v3.8.0) (2025-01-22)

### Features

* support custom pathToRegexpModule ([#102](#102)) ([8e12a8e](8e12a8e))
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.

1 participant