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

[WIP] fix: Fix the auth proxy trust by ensuring the proxy is in the trust #499

Open
wants to merge 5 commits into
base: master
Choose a base branch
from

Conversation

twk3
Copy link
Contributor

@twk3 twk3 commented Nov 9, 2024

TODO: update docs

Fixes: #371
Fixes: #392

- Validate that the closest peer to the express server is trusted proxy
- Add a new trustedAuthProxies config to eventually be used for this
- Add a allowedLoginMethod config to enable fully disabling header auth
@actual-github-bot actual-github-bot bot changed the title fix: Fix the auth proxy trust by ensuring the proxy is in the trust [WIP] fix: Fix the auth proxy trust by ensuring the proxy is in the trust Nov 9, 2024
@twk3
Copy link
Contributor Author

twk3 commented Nov 9, 2024

@tuetenk0pp let me know if this solves the issue you were running into. By default your local proxy should be trusted, but you can refine it. We are only checking the closest peer, so if your auth proxy is further out than that, it's up to you to configure your closest peer proxy to only accept the header from a proxy you trust.

This matches the behaviour of the project I had initially suggested as a reference during the original feature which is https://github.com/BeryJu/hass-auth-header

@tuetenk0pp
Copy link

@twk3 I am very busy at the moment and not able to test the PR. I will test it once I find some time to spend.

Copy link
Contributor

👋 Hi! It looks like this PR has not had any changes for a week now. Would you like someone to review this PR? If so - please remove the "[WIP]" prefix from the PR title. That will let the community know that this PR is open for a review.

@github-actions github-actions bot added the stale label Nov 23, 2024
@twk3 twk3 removed the stale label Nov 23, 2024
@kmcgonigle
Copy link

@twk3 for what it's worth, I ran across this issue because I noticed the error in #392 while setting up my local installation using Docker and reverse proxy. I'm currently running off of this branch, and it solves the error for me.

@MarianoRD
Copy link

Can confirm this PR works and solves the issue of the Trusted Proxies.

Copy link
Contributor

github-actions bot commented Dec 8, 2024

👋 Hi! It looks like this PR has not had any changes for a week now. Would you like someone to review this PR? If so - please remove the "[WIP]" prefix from the PR title. That will let the community know that this PR is open for a review.

@github-actions github-actions bot added the stale label Dec 8, 2024
@twk3 twk3 changed the title [WIP] fix: Fix the auth proxy trust by ensuring the proxy is in the trust fix: Fix the auth proxy trust by ensuring the proxy is in the trust Dec 9, 2024
@twk3 twk3 removed the stale label Dec 9, 2024
Copy link
Contributor

coderabbitai bot commented Dec 9, 2024

Walkthrough

The pull request introduces several changes across multiple files to enhance the login functionality and configuration management. In src/app-account.js, a new import statement for config is added, which is utilized to validate the loginMethod against allowed methods specified in the configuration. This results in an early return for unsupported login methods in the /login endpoint. In src/app.js, the Express application is configured to trust specific proxies by setting the 'trust proxy' property. The src/config-types.ts file sees the introduction of a new type alias LoginMethod and updates to the Config interface, adding properties for allowedLoginMethods and trustedAuthProxies. The src/load-config.js file is modified to load these new configuration options from environment variables. Finally, in src/util/validate-user.js, the logic for validating the authentication header is updated to accommodate the new proxy handling and improve IP address determination.

Assessment against linked issues

Objective Addressed Explanation
Validate that the 'trust proxy' setting is enabled to handle X-Forwarded-For headers correctly. (#392)
Ensure that the ACTUAL_TRUSTED_PROXIES configuration is respected and functional. (#371)
Implement validation for allowed login methods to prevent unsupported methods. (#371)

Possibly related PRs

Suggested labels

:sparkles: Merged


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 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: 1

🧹 Outside diff range and nitpick comments (4)
src/util/validate-user.js (2)

50-51: Consider using let/const consistently.

The code uses let for some variables but switches to var later. Consider using const here as these values aren't reassigned.

-let peer = req.socket.remoteAddress;
-let peerIp = ipaddr.process(peer);
+const peer = req.socket.remoteAddress;
+const peerIp = ipaddr.process(peer);

52-58: Improve type safety and variable declaration.

The code has a few issues:

  1. Uses var instead of const
  2. Has a TypeScript ignore comment that should be addressed
-const rangeList = {
-  allowed_ips: trustedAuthProxies.map((q) => ipaddr.parseCIDR(q)),
-};
-/* eslint-disable @typescript-eslint/ban-ts-comment */
-// @ts-ignore : there is an error in the ts definition for the function, but this is valid
-var matched = ipaddr.subnetMatch(peerIp, rangeList, 'fail');
-/* eslint-enable @typescript-eslint/ban-ts-comment */
+const rangeList = {
+  allowed_ips: trustedAuthProxies.map((cidr) => ipaddr.parseCIDR(cidr)),
+};
+const matched = ipaddr.subnetMatch(peerIp, rangeList, 'fail');

Consider opening an issue or PR to fix the TypeScript definitions in the ipaddr.js library instead of using @ts-ignore.

src/app-account.js (1)

Line range hint 68-82: Consider improving sensitive data handling in debug logs

While the password obfuscation is good, consider moving the debug statement to use the debugSensitive logger (as seen in load-config.js) to ensure sensitive data is only logged when explicitly enabled.

-      console.debug('HEADER VALUE: ' + obfuscated);
+      const debugSensitive = createDebug('actual-sensitive:auth');
+      debugSensitive('HEADER VALUE: ' + obfuscated);
src/load-config.js (1)

57-68: Good security practice: Explicit separation of proxy trust concerns

The separation between trustedProxies (for Express) and trustedAuthProxies (for header auth) is a good security practice that follows the principle of least privilege. The default trusted networks are appropriately set to common private network ranges.

Consider documenting these security-critical settings in the README to help users understand the implications of modifying them.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 645958b and df7ac96.

⛔ Files ignored due to path filters (1)
  • upcoming-release-notes/499.md is excluded by !**/*.md
📒 Files selected for processing (5)
  • src/app-account.js (2 hunks)
  • src/app.js (1 hunks)
  • src/config-types.ts (1 hunks)
  • src/load-config.js (2 hunks)
  • src/util/validate-user.js (1 hunks)
🔇 Additional comments (7)
src/config-types.ts (2)

3-4: LGTM! Well-structured type definition.

The LoginMethod type alias effectively encapsulates all supported authentication methods, improving type safety and maintainability.


7-10: Verify the relationship between loginMethod and allowedLoginMethods.

The configuration now has both a single loginMethod and an array of allowedLoginMethods. This might lead to confusion or inconsistency.

✅ Verification successful

Based on the search results, I can now provide a final response:

The relationship between loginMethod and allowedLoginMethods is valid and serves different purposes

The codebase shows these properties work together in a clear way:

  • allowedLoginMethods defines the list of permitted authentication methods
  • loginMethod specifies the currently active/default method
  • There's a validation check in app-account.js that ensures the chosen loginMethod exists in allowedLoginMethods
  • The default configuration in load-config.js shows a sensible setup with password as default method and both password/header as allowed methods
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usage of both properties to understand their relationship
rg -A 5 "loginMethod|allowedLoginMethods" --type ts --type js

Length of output: 4023

src/util/validate-user.js (2)

47-48: LGTM! Sensible fallback mechanism.

The fallback to trustedProxies when trustedAuthProxies is not set provides good backward compatibility.


59-64: LGTM! Good security logging.

The code properly logs both successful and failed authentication attempts with the peer IP address.

src/app.js (1)

25-25: Verify the impact on rate limiting and security middleware.

Setting trust proxy affects how Express handles X-Forwarded-* headers, which impacts:

  1. Rate limiting (configured below this line)
  2. IP-based security features
  3. Request IP determination

Ensure that:

  1. Rate limiting works correctly with trusted proxies
  2. Security features properly identify client IPs
✅ Verification successful

Let me gather more information about the trust proxy configuration and its relationship with rate limiting.


Let me search for the configuration file and rate limiter implementation details.


Trust proxy configuration is properly implemented and secure

The configuration is well-implemented with:

  1. Default trusted proxy ranges limited to private networks (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fc00::/7, ::1/128)
  2. Rate limiting properly configured with:
    • 500 requests per minute window
    • Standard rate limit headers enabled
    • Legacy headers disabled

The trust proxy setting is appropriately placed before the rate limiter middleware and the configuration aligns with security best practices for handling X-Forwarded-* headers in a proxied environment.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usage of req.ip and X-Forwarded-* headers
rg -A 5 "req\.ip|X-Forwarded-" --type js

# Search for rate limiting configurations
rg -A 5 "rateLimit|limiter" --type js

Length of output: 1405


Script:

#!/bin/bash
# Search for trust proxy and config related code
ast-grep --pattern 'app.set("trust proxy", $_)'
ast-grep --pattern 'app.set('\''trust proxy'\'', $_)'

# Search for config definition related to trusted proxies
rg -A 3 "trustedProxies.*=" --type js
rg -A 3 "export.*trustedProxies" --type js

# Search for IP-based security features
rg -A 5 "req\.(ip|ips)" --type js

Length of output: 287


Script:

#!/bin/bash
# Find and show configuration files
fd -e js config
fd -e json config

# Show content of potential config files
fd -e js config -x cat {}
fd -e json config -x cat {}

# Look for rate limiter configuration and implementation
ast-grep --pattern 'rateLimit({
  $$$
})'

Length of output: 9887

src/app-account.js (1)

17-17: LGTM: Good security enhancement for login method validation

The early validation of login methods against an allowed list is a good security practice that prevents unauthorized authentication attempts.

Also applies to: 63-66

src/load-config.js (1)

123-137: Verify environment variable parsing for security settings

The parsing logic for trusted proxies looks correct, but let's verify there are no edge cases that could lead to security issues.

✅ Verification successful

Let's gather more information about how these proxy settings are used in the identified files.


Based on the findings, I can now provide a final response:

Proxy trust settings are properly handled with appropriate security measures

The verification shows that:

  • The proxy settings are correctly used in Express's trust proxy mechanism
  • The validation logic in validate-user.js properly processes IP addresses using ipaddr.js library
  • Empty/malformed values are filtered out by the .filter(Boolean) call in the parsing logic
  • There's a secure fallback mechanism where trustedAuthProxies falls back to trustedProxies when not set
  • The IP validation uses CIDR parsing for proper network range checking
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential edge cases in proxy trust parsing

# Test 1: Check if empty/malformed values are properly handled
echo "Test 1: Empty/malformed values"
ACTUAL_TRUSTED_PROXIES=",,  , invalid" \
ACTUAL_TRUSTED_AUTH_PROXIES=",,  , invalid" \
node -e "
const config = require('./src/load-config.js').default;
console.log('Trusted Proxies:', config.trustedProxies);
console.log('Trusted Auth Proxies:', config.trustedAuthProxies);
"

# Test 2: Search for any direct proxy trust validations in the codebase
echo -e "\nTest 2: Proxy trust validation usage"
rg -l "trustedAuthProxies|trustedProxies" --type js

Length of output: 1033


Script:

#!/bin/bash
# Check how proxy settings are used in the identified files
echo "Checking app.js usage:"
rg "trustedAuthProxies|trustedProxies" src/app.js -B 2 -A 2

echo -e "\nChecking validate-user.js usage:"
rg "trustedAuthProxies|trustedProxies" src/util/validate-user.js -B 2 -A 2

# Let's also check the actual config structure
echo -e "\nChecking default config structure:"
ast-grep --pattern 'export const defaultConfig = {
  $$$
}'

Length of output: 1007

src/load-config.js Show resolved Hide resolved
@twk3 twk3 changed the title fix: Fix the auth proxy trust by ensuring the proxy is in the trust [WIP] fix: Fix the auth proxy trust by ensuring the proxy is in the trust Dec 9, 2024
@twk3
Copy link
Contributor Author

twk3 commented Dec 9, 2024

Just one more thing here to get it ready for review. The login method changed a bit with the intro of openid, specifically the allowedLoginMethods config here no longer makes sense. I need to take a look at the new changes around listingLoginMethod.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
4 participants