Skip to content

fix: Host header is not a Uri. Introduce an RFC3986 compliant HostHeader class - #142

Merged
nielsenko merged 5 commits into
serverpod:mainfrom
nielsenko:fix-host
Sep 10, 2025
Merged

nielsenko merged 5 commits into
serverpod:mainfrom
nielsenko:fix-host

Conversation

@nielsenko

@nielsenko nielsenko commented Sep 2, 2025 •

Copy link
Copy Markdown
Collaborator

Description

Don't treat 'Host' header as a Uri. Fx, it cannot contain a scheme (http(s)). Format is defined in RFC3986.

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.

host extension on Headers is now of type HostHeader. Used to be Uri.

Summary by CodeRabbit

  • New Features
    • Introduces a typed HostHeader for the HTTP Host header with host and optional port, including value-based equality and parsing/encoding.
    • Updates headers.host getter/setter to use HostHeader instead of Uri.
    • Expands typed header exports to include HostHeader and X-Forwarded-For.
  • Tests
    • Updated tests to validate HostHeader behavior (whitespace handling, ports, basic IPv6), replacing Uri-based expectations and messages where applicable.

@coderabbitai

coderabbitai Bot commented Sep 2, 2025 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough

Walkthrough

Switches Host header handling from Uri to a new typed HostHeader. Introduces HostHeader class with parsing/encoding and value equality, wires it via HeaderAccessor using HostHeader.codec, updates extensions and tests accordingly, and re-exports the new header types in the typed headers barrel.

Changes

Cohort / File(s) Summary
Host header codec wiring
lib/src/headers/headers.dart
Replace uriHeaderCodec with HostHeader.codec in Headers.host accessor.
Extensions API update
lib/src/headers/standard_headers_extensions.dart
Change host getter/setter types from Uri? to HostHeader? in two extension blocks; import HostHeader.
Typed header implementation
lib/src/headers/typed/headers/host_header.dart
Add HostHeader class with host, port, parsing (incl. IPv6 brackets), encoding, equality, and static codec.
Barrel exports
lib/src/headers/typed/typed_headers.dart
Export new host_header.dart and x_forwarded_for_header.dart.
Tests update: Host header
test/headers/basic/host_header_test.dart, test/headers/header_test.dart
Update tests to expect/set HostHeader instead of Uri; adjust invalid/whitespace/port expectations and imports.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Client
  participant Server
  participant Headers
  participant HostHeaderCodec as HostHeader.codec

  Client->>Server: HTTP request with "Host" header
  Server->>Headers: parse("Host")
  activate Headers
  Headers->>HostHeaderCodec: decode(raw "Host" value)
  activate HostHeaderCodec
  HostHeaderCodec-->>Headers: HostHeader(host, port?)
  deactivate HostHeaderCodec
  Headers-->>Server: Headers.host -> HostHeader?
  deactivate Headers

  Note over Server: Server reads host and optional port from HostHeader
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Assessment against linked issues

Objective Addressed Explanation
Represent Host header with a non-URI type [#95] ✅
Accept valid formats: hostname, hostname:port, IPv4, [IPv6], [IPv6]:port [#95] ❓ IPv6 brackets handled; full IPv4/hostname validation not evident; edge cases unverified.
Enforce rules: no scheme/path/query/fragment; single Host header; required in HTTP/1.1 [#95] ❓ Parser appears to reject schemes implicitly; single-header/required constraints not implemented here.
Port handling: numeric 1–65535; defaults (80/443) if omitted [#95] ❌ Range and default port logic not present.
Case-insensitive domain handling [#95] ❓ No normalization/comparison behavior shown.

Assessment against linked issues: Out-of-scope changes

Code Change Explanation
Add export for x_forwarded_for_header.dart (lib/src/headers/typed/typed_headers.dart) Not related to Host header parsing or representation in #95; expands public API beyond stated objective.

Possibly related PRs

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@nielsenko

Copy link
Copy Markdown
Collaborator Author

@CodeRabbit review

@coderabbitai

coderabbitai Bot commented Sep 2, 2025

Copy link
Copy Markdown
Contributor
✅ 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.

@codecov

codecov Bot commented Sep 2, 2025 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.91837% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 92.46%. Comparing base (5ac8e4e) to head (de4e253).
⚠️ Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
lib/src/headers/typed/headers/host_header.dart 94.73% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #142      +/-   ##
==========================================
+ Coverage   92.43%   92.46%   +0.02%     
==========================================
  Files          83       84       +1     
  Lines        3119     3157      +38     
  Branches     1592     1610      +18     
==========================================
+ Hits         2883     2919      +36     
- Misses        236      238       +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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (13)
test/headers/header_test.dart (1)

2-2: Prefer public barrel import over internal path.

Import HostHeader from the typed headers barrel to avoid depending on src/ internals.

-import 'package:relic/src/headers/typed/headers/host_header.dart';
+import 'package:relic/src/headers/typed/typed_headers.dart';
lib/src/headers/typed/headers/host_header.dart (4)

3-3: Tighten the doc comment to cite specs.

Replace “Wanna-be” phrasing and reference RFC 3986 and RFC 9110/9112.

-/// Wanna-be RFC3986 compliant 'Host' header.
+/// HTTP Host header value per RFC 3986 (uri-host) and RFC 9110/9112:
+/// host = uri-host [ ":" port ] with IPv6 literals bracketed.

9-14: Clarify TODO: default ports are contextual, not part of Host parsing.

Keep port nullable; resolve defaults at request/connection level (e.g., scheme/TLS). Update comment to avoid implying parsing should inject defaults.

-  // TODO: This should default 80 for http, or 443 for https, but we don't have
-  // access to the scheme in HostHeader.parse. Will require some refactoring,
-  // perhaps allowing Header instances to know what Request instance they belong
-  // to. For now allow port to be null, at leave it to the client to handle.
+  // Note: Default ports (80/443) are contextual (scheme/TLS) and should be
+  // applied by higher layers, not during Host header parsing. Keep null when
+  // the port is not explicitly present.

5-7: Optional: predeclare the invalid-char regex once.

Minor allocation reduction during parsing.

   static const codec = HeaderCodec.single(HostHeader.parse, __encode);
   static List<String> __encode(final HostHeader value) => [value._encode()];
+  static final RegExp _invalidChars = RegExp(r'[/?#@]');

1-52: Add targeted tests for edge cases (scheme/path/userinfo/IPv6).

Covers regressions for bracketless IPv6, “:null”, and port range.

I can add cases to test/headers/basic/host_header_test.dart:

  • Accept: example.com, example.com:8080, localhost:3000, 192.168.1.1, 192.168.1.1:8080, [2001:db8::1], [2001:db8::1]:8080, [::1]:3000, EXAMPLE.com:80 equals example.com:80.
  • Reject: https://example.com, example.com/, example.com?x, example.com#x, [email protected], example.com:0, example.com:65536, 2001:db8::1 (no brackets), 2001:db8::1:80 (no brackets).
    Do you want me to push those?
test/headers/basic/host_header_test.dart (8)

45-49: Stabilize the error assertion; avoid coupling to "Invalid radix-10 number".

That message comes from int parsing and is brittle. Assert the error type (and optionally a stable, high-level message) instead.

Apply this diff:

-            throwsA(
-              isA<BadRequestException>().having(
-                (final e) => e.message,
-                'message',
-                contains('Invalid radix-10 number'),
-              ),
-            ),
+            throwsA(isA<BadRequestException>()),

Also applies to: 60-61


68-79: Add numeric port bounds tests (0 and >65535).

Covers RFC-compliant range enforcement.

       test(
         'when a Host header with an invalid port number is passed '
         'then the server responds with a bad request including a message that '
         'states the format is invalid',
         () async {
           expect(
             getServerRequestHeaders(
               server: server,
-              headers: {'host': 'example.com:test'},
+              headers: {'host': 'example.com:test'},
               touchHeaders: (final h) => h.host,
             ),
             throwsA(isA<BadRequestException>()),
           );
         },
       );
+
+      test(
+        'when a Host header with an out-of-range port (0) is passed then it is rejected',
+        () async {
+          expect(
+            getServerRequestHeaders(
+              server: server,
+              headers: {'host': 'example.com:0'},
+              touchHeaders: (final h) => h.host,
+            ),
+            throwsA(isA<BadRequestException>()),
+          );
+        },
+      );
+
+      test(
+        'when a Host header with an out-of-range port (65536) is passed then it is rejected',
+        () async {
+          expect(
+            getServerRequestHeaders(
+              server: server,
+              headers: {'host': 'example.com:65536'},
+              touchHeaders: (final h) => h.host,
+            ),
+            throwsA(isA<BadRequestException>()),
+          );
+        },
+      );

84-92: Nit: fix test description grammar.

“headers is not actually used” → “header is not actually used”.

-        'when a Host header with an invalid value is passed '
-        'then the server does not respond with a bad request if the headers '
-        'is not actually used',
+        'when a Host header with an invalid value is passed '
+        'then the server does not respond with a bad request if the header '
+        'is not actually used',

91-92: Add a companion test to ensure a schemed Host is rejected when accessed.

Validates “must not include a scheme” enforcement in strict mode.

       final headers = await getServerRequestHeaders(
         server: server,
         touchHeaders: (final _) {},
         headers: {'host': 'http://example.com'}, // scheme not allowed!
       );
 
       expect(headers, isNotNull);
     },
   );
+
+  test(
+    'when a Host header includes a scheme and is accessed then it should be rejected',
+    () async {
+      expect(
+        getServerRequestHeaders(
+          server: server,
+          headers: {'host': 'http://example.com'},
+          touchHeaders: (final h) => h.host,
+        ),
+        throwsA(isA<BadRequestException>()),
+      );
+    },
+  );

99-108: Consider adding a case-insensitivity test for domain names.

If HostHeader normalizes or compares case-insensitively, add a test asserting EXAMPLE.COM parses as example.com.

Would you like me to add the test assuming HostHeader lowercases the reg-name, or should equality be case-insensitive without normalization?


117-122: Also assert full equality for host+port.

Tightens the positive path by verifying both host and port.

   expect(headers.host?.port, equals(8080));
+  expect(headers.host, equals(HostHeader('example.com', 8080)));

126-135: Add coverage for IPv4/IPv6 and disallowing path/query/fragment.

These are in the PR objectives and RFC constraints.

   expect(headers.host, equals(HostHeader('example.com', null)));
 },
);
 
+test(
+  'when an IPv4 Host header is passed then it should parse correctly',
+  () async {
+    final headers = await getServerRequestHeaders(
+      server: server,
+      headers: {'host': '192.168.1.1'},
+      touchHeaders: (final h) => h.host,
+    );
+    expect(headers.host, equals(HostHeader('192.168.1.1', null)));
+  },
+);
+
+test(
+  'when an IPv4 Host header with a port is passed then it should parse the port correctly',
+  () async {
+    final headers = await getServerRequestHeaders(
+      server: server,
+      headers: {'host': '192.168.1.1:3000'},
+      touchHeaders: (final h) => h.host,
+    );
+    expect(headers.host?.port, equals(3000));
+  },
+);
+
+test(
+  'when an IPv6 Host header with a port is passed then it should parse the port correctly',
+  () async {
+    final headers = await getServerRequestHeaders(
+      server: server,
+      headers: {'host': '[::1]:3000'},
+      touchHeaders: (final h) => h.host,
+    );
+    expect(headers.host?.port, equals(3000));
+  },
+);
+
+test(
+  'when a Host header contains a path then it should be rejected',
+  () async {
+    expect(
+      getServerRequestHeaders(
+        server: server,
+        headers: {'host': 'example.com/path'},
+        touchHeaders: (final h) => h.host,
+      ),
+      throwsA(isA<BadRequestException>()),
+    );
+  },
+);
+
+test(
+  'when a Host header contains a query then it should be rejected',
+  () async {
+    expect(
+      getServerRequestHeaders(
+        server: server,
+        headers: {'host': 'example.com?x=1'},
+        touchHeaders: (final h) => h.host,
+      ),
+      throwsA(isA<BadRequestException>()),
+    );
+  },
+);
+
+test(
+  'when a Host header contains a fragment then it should be rejected',
+  () async {
+    expect(
+      getServerRequestHeaders(
+        server: server,
+        headers: {'host': 'example.com#frag'},
+        touchHeaders: (final h) => h.host,
+      ),
+      throwsA(isA<BadRequestException>()),
+    );
+  },
+);

138-149: Confirm intended behavior for missing Host in strict mode.

HTTP/1.1 requires Host; this test expects defaulting to machine address even with strictHeaders: true. Verify this aligns with product requirements; otherwise consider failing requests missing Host under strict mode.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between f4ed7bf and a377f47.

📒 Files selected for processing (6)
  • lib/src/headers/headers.dart (2 hunks)
  • lib/src/headers/standard_headers_extensions.dart (4 hunks)
  • lib/src/headers/typed/headers/host_header.dart (1 hunks)
  • lib/src/headers/typed/typed_headers.dart (2 hunks)
  • test/headers/basic/host_header_test.dart (6 hunks)
  • test/headers/header_test.dart (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • 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, downgrade)
  • GitHub Check: Run Unit Tests (macos-latest, 3.5.0, downgrade)
  • GitHub Check: Run Unit Tests (macos-latest, stable, upgrade)
  • GitHub Check: Run Unit Tests (macos-latest, 3.5.0, upgrade)
🔇 Additional comments (9)
test/headers/header_test.dart (1)

522-523: Good: setter uses the new HostHeader type.

This validates the breaking change is exercised by tests.

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

7-8: LGTM: wire Host to the new HostHeader codec.

Correctly switches from uriHeaderCodec to HostHeader.codec.


80-81: LGTM: single-value codec enforces one Host header.

Using HeaderCodec.single satisfies the “single Host header” constraint.

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

28-29: LGTM: export HostHeader publicly.

Makes the new type available without src/ imports.


43-44: LGTM: export XForwardedForHeader too.

Consistent with other typed headers.

lib/src/headers/standard_headers_extensions.dart (4)

3-4: LGTM: import HostHeader in extensions.

Matches the accessor type change.


17-18: LGTM: host getter now returns HostHeader?.

Aligned with new typed accessor.


108-109: LGTM: host setter accepts HostHeader?.

Consistent with Headers.host codec.


219-220: Dup block updated correctly.

Both read-only getters mirror the new type.

@nielsenko
nielsenko force-pushed the fix-host branch 5 times, most recently from 344ccdf to 0754cc6 Compare September 8, 2025 11:09
@nielsenko nielsenko self-assigned this Sep 8, 2025
@nielsenko
nielsenko marked this pull request as ready for review September 9, 2025 11:57
@nielsenko
nielsenko requested a review from a team September 9, 2025 11:57
@SandPod SandPod self-assigned this Sep 10, 2025

@SandPod SandPod left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Some minor test fix suggestions.

Please solve these and then I'm OK with a merge without a second review.

test: Address some PR feedback regarding tests

refactor: Include raw value in InvalidHeaderException
@nielsenko
nielsenko merged commit f7cc753 into serverpod:main Sep 10, 2025
@nielsenko
nielsenko deleted the fix-host branch September 10, 2025 13:22
@nielsenko nielsenko mentioned this pull request Jun 12, 2026
7 of 9 tasks
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.

bug: Host header incorrectly parsed as Uri

2 participants