Skip to content

Conversation

@nielsenko
Copy link
Collaborator

@nielsenko nielsenko commented Jun 18, 2025

Description

feat: Add typed header for X-Forwarded-For

Introduces XForwardedForHeader for typed access to the X-Forwarded-For HTTP header.
Includes:

  • Parsing and encoding logic for comma-separated IP addresses.
  • Integration into Headers class and relevant test suites.
  • Refactoring of string list splitting extensions for clarity.

Related Issues

Pre-Launch Checklist

Please ensure that your PR meets the following requirements before submitting:

  • This update focuses on a single feature or bug fix. (For multiple fixes, please submit separate PRs.)
  • I have read and followed the Dart Style Guide and formatted the code using dart format.
  • I have referenced at least one issue this PR fixes or is related to.
  • I have updated/added relevant documentation (doc comments with ///), ensuring consistency with existing project documentation.
  • I have added new tests to verify the changes.
  • All existing and new tests pass successfully.
  • I have documented any breaking changes below.

Breaking Changes

  • Includes breaking changes.
  • No breaking changes.

Additional Notes

To be used as fallback, when Forwarded header not set in serverpod.

Summary by CodeRabbit

  • New Features
    • Added support for the X-Forwarded-For HTTP header, providing typed access and validation for lists of IP addresses.
  • Refactor
    • Improved string list handling for header values by separating splitting, trimming, and uniqueness filtering into distinct methods.
  • Tests
    • Introduced comprehensive tests for the X-Forwarded-For header, including parsing, immutability, equality, and codec behavior.
    • Updated header tests to accommodate the new X-Forwarded-For header.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 18, 2025

📝 Walkthrough

Walkthrough

The changes introduce a new typed header class for X-Forwarded-For, integrate it into the headers framework, and add comprehensive unit tests. Supporting code is refactored to facilitate splitting and trimming header values. The Headers class and related test exclusions are updated to recognize the new header.

Changes

File(s) Change Summary
lib/src/headers/typed/headers/x_forwarded_for_header.dart Added new XForwardedForHeader class, parsing logic, codec, and equality/immutability enforcement.
lib/src/headers/headers.dart Integrated X-Forwarded-For as a static accessor and constant; updated header sets and documentation.
lib/src/headers/extension/string_list_extensions.dart Refactored string splitting/trimming logic into helper method for reuse by typed header parsing.
test/headers/typed/x_forwarded_for_header_test.dart Added comprehensive unit tests for parsing, immutability, equality, and codec of XForwardedForHeader.
test/headers/header_test.dart Updated to exclude xForwardedFor from certain invalid raw value tests.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Headers
    participant XForwardedForHeader

    Client->>Headers: Set X-Forwarded-For header (raw value)
    Headers->>XForwardedForHeader: Parse raw header value(s)
    XForwardedForHeader->>XForwardedForHeader: Split, trim, validate addresses
    XForwardedForHeader-->>Headers: Return typed header instance
    Headers-->>Client: Provide access to parsed addresses list
Loading

Assessment against linked issues

Objective Addressed Explanation
Create a typed header class for parsing and representing X-Forwarded-For values (#103)
Support IPv4 and IPv6 addresses (#103)
Handle comma-separated lists of addresses (#103)
Integrate with the existing header framework (accessor, extensions) (#103)
Add comprehensive unit tests (#103)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes found.

Possibly related issues


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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

@codecov
Copy link

codecov bot commented Jun 18, 2025

Codecov Report

Attention: Patch coverage is 90.90909% with 2 lines in your changes missing coverage. Please review.

Project coverage is 82.77%. Comparing base (081f34e) to head (c12d397).
Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
.../headers/typed/headers/x_forwarded_for_header.dart 87.50% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #107      +/-   ##
==========================================
+ Coverage   82.73%   82.77%   +0.04%     
==========================================
  Files          82       83       +1     
  Lines        2659     2677      +18     
  Branches     1466     1475       +9     
==========================================
+ Hits         2200     2216      +16     
- Misses        459      461       +2     

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

@nielsenko
Copy link
Collaborator Author

@coderabbitai review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 18, 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.

@nielsenko nielsenko self-assigned this Jun 18, 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: 0

🧹 Nitpick comments (5)
lib/src/headers/extension/string_list_extensions.dart (2)

20-23: Consider documenting the new helper’s contract

splitTrimAndFilterUnique now delegates to splitAndTrim, but the public-facing doc comment still enumerates the old algorithm step-by-step (including uniqueness) while the helper itself is undocumented.
It would be clearer to:

  1. Move the uniqueness bullet-point from splitAndTrim’s description to splitTrimAndFilterUnique.
  2. Add a short doc comment on splitAndTrim explaining that it does not de-duplicate.

No functional change – purely about preventing reader confusion.


24-30: Minor perf nit – avoid a second iteration

LinkedHashSet.from(splitAndTrim(...)) walks the iterable twice (once to create the list for the set and once to copy).
If you want to micro-optimise, build the LinkedHashSet directly while expanding:

-LinkedHashSet<String>.from(
-    splitAndTrim(separator: separator, emptyCheck: emptyCheck));
+final result = LinkedHashSet<String>();
+for (final el in this) {
+  for (final part in el.split(separator)) {
+    final trimmed = part.trim();
+    if (!emptyCheck || trimmed.isNotEmpty) result.add(trimmed);
+  }
+}
+return result;

Completely optional; probably not measurable unless the header list is very large.

test/headers/header_test.dart (1)

154-181: The TODO comment is now stale

Headers.xForwardedFor was added to the “invalid raw value” exclusion list, but the preceding TODO still claims the exclusions are “not all correct”.
If the list has been audited as part of this PR, consider removing or updating the TODO to avoid confusion.

lib/src/headers/typed/headers/x_forwarded_for_header.dart (2)

25-33: Validate IP literals (optional)

At the moment any non-empty token is accepted as an “address”.
While spec-compliant (many servers are permissive), consider an optional check using InternetAddress.tryParse and allowing the literal "unknown". This guards against garbage values early:

final parsedAddresses = values.splitAndTrim();
if (parsedAddresses.isEmpty) {
  throw const FormatException('Value cannot be empty');
}
-return XForwardedForHeader(parsedAddresses);
+if (parsedAddresses.any((a) =>
+    a != 'unknown' && InternetAddress.tryParse(a) == null)) {
+  throw const FormatException('Invalid IP literal');
+}
+return XForwardedForHeader(parsedAddresses);

Up to you whether the stricter behaviour is desirable.


40-42: Encoding – drop the extra space for round-trip fidelity

join(', ') emits a space after every comma, whereas many upstream proxies emit no space (1.2.3.4,5.6.7.8).
Parsing handles either, but round-tripping (decode → encode) changes the byte sequence. Using join(',') retains the original compact form and avoids surprises in signature/macro validations.

-String _encode() => addresses.join(', ');
+String _encode() => addresses.join(',');
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 081f34e and c12d397.

📒 Files selected for processing (5)
  • lib/src/headers/extension/string_list_extensions.dart (1 hunks)
  • lib/src/headers/headers.dart (5 hunks)
  • lib/src/headers/typed/headers/x_forwarded_for_header.dart (1 hunks)
  • test/headers/header_test.dart (1 hunks)
  • test/headers/typed/x_forwarded_for_header_test.dart (1 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
lib/src/headers/typed/headers/x_forwarded_for_header.dart

[warning] 54-54: lib/src/headers/typed/headers/x_forwarded_for_header.dart#L54
Added line #L54 was not covered by tests

⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: Run Unit Tests (macos-latest, stable, downgrade)
  • GitHub Check: Run Unit Tests (macos-latest, 3.5.0, upgrade)
  • GitHub Check: Run Unit Tests (macos-latest, beta, downgrade)
  • GitHub Check: Run Unit Tests (macos-latest, beta, upgrade)
  • GitHub Check: Run Unit Tests (macos-latest, stable, upgrade)
  • GitHub Check: Run Unit Tests (macos-latest, 3.5.0, downgrade)
  • GitHub Check: Run Unit Tests (windows-latest, 3.5.0, downgrade)
🔇 Additional comments (3)
lib/src/headers/headers.dart (1)

248-251: Accessor registered correctly – LGTM

Headers.xForwardedFor is exposed with its codec and placed in the request-only set. Integration looks consistent with existing pattern.

lib/src/headers/typed/headers/x_forwarded_for_header.dart (1)

54-54: Missing test coverage only on toString() – acceptable

Codec, equality and parsing are thoroughly tested. Lack of coverage on toString() is not an issue.

test/headers/typed/x_forwarded_for_header_test.dart (1)

130-140: Great edge-case coverage

Including IPv6, obfuscated identifiers and ports demonstrates thoughtful testing beyond the happy path.

@nielsenko nielsenko requested a review from SandPod June 18, 2025 13:21
@nielsenko nielsenko marked this pull request as ready for review June 18, 2025 13:21
Copy link
Contributor

@SandPod SandPod left a comment

Choose a reason for hiding this comment

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

🚀

@nielsenko nielsenko merged commit 3cae0a8 into serverpod:main Jun 19, 2025
28 checks passed
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.

Add support for X-Forwarded-For header as typed header

2 participants