Repository navigation
fix: Host header is not a Uri. Introduce an RFC3986 compliant HostHeader class - #142
Conversation
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the 📝 WalkthroughWalkthroughSwitches 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
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Assessment against linked issues
Assessment against linked issues: Out-of-scope changes
Possibly related PRs
✨ Finishing Touches🧪 Generate unit tests
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. Comment |
|
@CodeRabbit review |
✅ Actions performedReview triggered.
|
Codecov Report❌ Patch coverage is
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. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (13)
test/headers/header_test.dart (1)
2-2: Prefer public barrel import over internal path.Import
HostHeaderfrom the typed headers barrel to avoid depending onsrc/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
portnullable; 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:80equalsexample.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.
📒 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
uriHeaderCodectoHostHeader.codec.
80-81: LGTM: single-value codec enforces one Host header.Using
HeaderCodec.singlesatisfies 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.hostcodec.
219-220: Dup block updated correctly.Both read-only getters mirror the new type.
344ccdf to
0754cc6
Compare
SandPod
left a comment
There was a problem hiding this comment.
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
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:
///), ensuring consistency with existing project documentation.Breaking Changes
hostextension onHeadersis now of typeHostHeader. Used to beUri.Summary by CodeRabbit