Skip to content

Overhaul typed header parsers #113

Closed
0 of 1 issue completed
Closed

Description

@nielsenko

While the idea of typed headers is great, we are not particular compliant to the various RFCs when it comes to parsing headers.

We should use a composable parser library such petitparser and implement the various header parsers by composing the parsers in strict accordance with the RFCs.

Go over all the (many) typed header parses and ensure they are compliant with their respective RFCs.

Sub-issues

Sub-issues

0 of 1 Issues completed
Loading 1 sub-issues

Activity

  1. moved this from Inbox 📫 to Backlog 🗂️ in Serverpod Frameworkson Aug 14, 2025
  2. nielsenko commented on May 19, 2026

    @nielsenko
    CollaboratorAuthor

    Did a pass over all 45 typed headers under packages/relic_core/lib/src/headers/typed/headers/ against their RFCs / defacto specs. Findings below as a concrete checklist to drive the overhaul.

    Out of scope (tracked separately, not repeated below):

    Line references are from main at the time of audit and may drift. Use them as starting points, not anchors.

    Critical: encoder produces invalid wire output

    • content_range_header.dart (RFC 9110 14.4): encoder emits literal "bytes null-499/1234" when start==null && end!=null via Dart string interpolation. Unsatisfied range with size==null emits bytes */*; spec requires */complete-length.
    • access_control_allow_origin_header.dart (Fetch 3.2.2): stores origin as Uri, so Uri.parse("https://example.com/") round-trips with the trailing slash. Same shape bug as bug: SetCookieHeader emits invalid Domain (and Path) attributes via Uri.toString() #355. Also null sentinel not modeled (lands as a degenerate Uri with scheme="" path="null"; happens to encode "null" by accident).
    • host_header.dart (RFC 9110 7.2): HostHeader.fromUri uses uri.port, which returns the default port (80/443) when no port was specified. Result: Host: example.com:80. Fix: uri.hasPort ? uri.port : null.
    • authorization_header.dart Digest encoder (RFC 7616 3.4): always quotes every parameter; algorithm, qop, nc, stale MUST be unquoted tokens. Strict servers (Apache mod_auth_digest) reject.
    • permission_policy_header.dart (W3C Permissions Policy): emits origins as bare sf-tokens, e.g. geolocation=(self https://example.com). Spec is RFC 8941 structured field; origins must be sh-strings (quoted). Browsers drop the directive.
    • accept_header.dart, accept_encoding_header.dart, accept_language_header.dart, te_header.dart (RFC 9110 12.4.2 weight): q-value parser splits on the literal ";q=". Spec allows OWS around ;, so gzip; q=0.8 misparses (q ignored, falls back to 1.0). In accept_header.dart the q= literal also collides with media-range params that begin with q. Encoder emits double.toString() which can produce more than 3 digits; spec caps at 3.
    • upgrade_header.dart (RFC 9110 7.8): protocol-version is a token but stored as double. HTTP/2 round-trips to HTTP/2.0, a different protocol token. Affects h2/websocket negotiation.

    High: parser rejects spec-valid input, drops data, or accepts illegal input silently

    • cookie_header.dart (RFC 6265 4.2): splits on = rejecting values that contain = (e.g. base64 padding ==). Lowercases cookie names for dedup; spec says names are case-sensitive. validateCookieValue calls Uri.decodeComponent, mutating opaque octets and throwing on stray %.
    • set_cookie_header.dart (RFC 6265 4.1): throws on unknown attributes (Partitioned, Priority); spec says ignore. Attribute matching via contains() mis-routes pathological inputs (a name/value pair like name=secure is detected as Secure first because contains('=') is checked last).
    • cache_control_header.dart (RFC 9111 5.2): drops the field-list argument from no-cache="X-Foo" / private="set-cookie". Validates directives via startsWith() with no delimiter, so max-age-extended=5 is accepted. Falsely rejects co-occurring max-age and stale-while-revalidate (no spec basis). Accepts negative delta-seconds.
    • if_range_header.dart (RFC 9110 13.1.5): accepts weak ETags. Spec: "client MUST NOT generate an If-Range header containing an entity-tag that is marked as weak."
    • accept_ranges_header.dart (RFC 9110 14.3): models as single rangeUnit string. Spec is 1#range-unit (list). Accept-Ranges: bytes, custom-unit stored as the literal string "bytes, custom-unit".
    • content_encoding_header.dart (RFC 9110 8.4): hardcoded enum throws on any unknown content-coding. The IANA registry is open and recipients SHOULD pass through unknowns. Case-sensitive (GZIP rejected).
    • connection_header.dart (RFC 9110 7.6.1): whitelists 4 directives; spec allows any token referring to hop-by-hop field names. Connection: TE (RFC-required companion to TE header) fails to parse. Has a bogus downgrade directive that doesn't exist in any spec. Case-sensitive.
    • authentication_header.dart (WWW-Authenticate / Proxy-Authenticate, RFC 9110 11.6.1): only supports one challenge; spec is #challenge. Multi-scheme responses common in the wild (Newauth realm="apps", Basic realm="simple"). Scheme equality case-sensitive (spec: case-insensitive).
    • authorization_header.dart (RFC 9110 11.6.2 / RFC 7617 / RFC 6750): case-sensitive scheme dispatch (bearer abc rejected). Basic rejects empty password; RFC 7617 grammar permits password = *TEXT and the empty-password pattern is common (apikey: style). Digest parser only accepts quoted params, dropping unquoted tokens (algorithm=MD5, qop=auth, nc=00000001, stale=false).
    • transfer_encoding_header.dart (RFC 9112 6.1): case-sensitive token matching (Chunked rejected). _reorderEncodings silently moves chunked to last position; this changes wire semantics (chunked is the framing applied last), so reordering hides caller bugs.
    • content_disposition_header.dart (RFC 6266, RFC 5987) -- beyond what Improve HTTP header parsing to handle quoted strings with delimiters #102 covers:
      • Extended-form encoder emits filename*=''en'foo.txt (empty charset) when encoding is null; RFC 5987 3.2.1 requires charset.
      • Uri.encodeComponent does not equal RFC 5987 attr-char: ', *, (, ) are not encoded. O'Brien.pdf produces an invalid filename*.
      • disposition-type not validated as token; case-sensitive equality where RFC 6266 4.1.2 says insensitive.
    • content_language_header.dart (RFC 5646 / RFC 9110 8.5): regex ^[a-zA-Z]{2,8}(-[a-zA-Z]{2,8})?$ rejects most BCP 47 tags: es-419 (digits), zh-Hant-TW (3+ subtags), de-DE-1996 (variant), de-DE-u-co-phonebk (extension), x-foo (private-use), i-klingon (grandfathered).
    • expect_header.dart (RFC 9110 10.1.1): rejects anything other than literal 100-continue and is case-sensitive. Spec calls for 417 response on unknown expectations, so the parser should preserve them.
    • access_control_allow_methods_header.dart (Fetch): Method enum is closed and lowercases input. Cannot represent MKCOL, REPORT, PROPFIND, custom REST verbs.
    • cross_origin_embedder_policy_header.dart: no report-to parameter handling. Production headers require-corp; report-to="coep" raise FormatException.
    • cross_origin_opener_policy_header.dart: missing noopener-allow-popups (newer HTML spec value). No report-to parameter.
    • referrer_policy_header.dart: spec REQUIRES parsing a comma-separated list and picking the last valid token; pattern no-referrer, strict-origin-when-cross-origin exists specifically to give older UAs a fallback. Current parser throws on the whole list. Also case-sensitive.
    • strict_transport_security_header.dart (RFC 6797 6.1): case-sensitive directive matching (Max-Age=..., IncludeSubDomains rejected). Does not accept quoted max-age (spec explicitly allows max-age="0"). Accepts negative max-age.
    • clear_site_data_header.dart: missing clientHints value. Parser accepts unquoted bare tokens; spec requires sh-strings (quoted).
    • sec_fetch_mode_header.dart: defines a nested-navigate value that does not exist in the Fetch spec enum. Should be removed.
    • from_header.dart (RFC 9110 10.1.2): models a list but From = mailbox is a singleton; encoder can emit a@x, b@y. Email regex is far too strict and rejects name-addr forms like Webmaster <[email protected]>.

    Medium: case-sensitivity / equality bugs

    Field-name / token equality issues where the wire format is fine but Dart == / hash give wrong results. These collapse into the "strict value types" theme below (a Token type whose equality is ASCII case-insensitive fixes most of these in one move).

    Affected: vary_header.dart, access_control_allow_headers_header.dart, access_control_expose_headers_header.dart, content_security_policy_header.dart (directive names), accept_language_header.dart (BCP 47 canonical casing not preserved on parse), upgrade_header.dart (protocol-name).

    Low / Possibly

    • etag_header.dart: replaceAll('"', '') strips all quotes including any interior; no etagc charset validation; allows whitespace between W/ and ".
    • range_header.dart: no start <= end validation; regex permits OWS around = (mostly harmless on receive).
    • retry_after_header.dart: int.tryParse accepts leading +.
    • cache_control_header.dart: publicCache/privateCache typed as bool? but constructor/parser leave them non-null asymmetrically (round-trip on direct construction is lossy).

    No findings (or helper-only)

    x_forwarded_for_header.dart, wildcard_list_header.dart (generic helper), cross_origin_resource_policy_header.dart, sec_fetch_dest_header.dart, sec_fetch_site_header.dart.

    Themes

    Most "Critical", "High", and "Medium" findings collapse into three root causes:

    1. Missing strict value types for spec primitives

    The specs use a small recurring vocabulary (token, quoted-string, uri-host, origin, language-tag, mailbox, delta-seconds, entity-tag). Today these are typed as String, Uri, double, or ad-hoc Dart enums, none of which match the spec's shape. This is the root cause of #355 (Domain/Path as Uri), of the Allow-Origin / Host / Upgrade encoder bugs, and of nearly every case-sensitivity / equality issue in the Medium bucket.

    Proposed primitives to introduce, sharable across headers:

    • Token (RFC 9110 5.6.2): case-insensitive equality, restricted ASCII tchar. Used for method names, header names, scheme names, transfer-codings, content-codings, cache directive names, CSP directive names, sf-tokens.
    • Host (RFC 3986 uri-host, optional port): SetCookie Domain, Host, Forwarded host=/for= host-part.
    • Origin (Fetch / RFC 6454) with explicit null sentinel: Allow-Origin.
    • LanguageTag (BCP 47): Content-Language, Accept-Language.
    • MailboxAddress (RFC 5322): From.
    • DeltaSeconds (non-negative int): Max-Age, max-age, Retry-After seconds form.
    • ETagValue (opaque + weak flag): tighten existing.
    • ParameterValue (token / quoted-string choice): auth params, Content-Disposition params, Cache-Control field-list arguments.

    Implementation note: Token should be an abstract interface class (not a Dart enum). This lets closed-by-spec enum headers continue to be Dart enums that implement Token, while genuinely open headers use a non-enum Token-implementor. The same parser/encoder primitives (tchar validation, case-insensitive equality, sf-token serialization) then apply uniformly to both. If a future Dart relaxes the rule that enums implicitly extend Enum, switching from implements to extends is a one-line change. Sketch:

    abstract interface class Token {
      String get value;
    }
    
    // Closed by spec: stays an enum.
    enum CoopValue implements Token {
      unsafeNone('unsafe-none'),
      requireCorp('require-corp'),
      // ...
      ;
      const CoopValue(this.value);
      @override final String value;
    }
    
    // Open by spec: a non-enum Token implementor.
    final class ContentCoding implements Token { /* ... */ }

    Precedent already in the codebase: SameSite and Method are this shape, just inconsistent. Standardising fixes the Uri-mistyping cluster and the equality cluster in one move, and benefits the currently-spec-compliant headers too (consistency, future-proofing, validation at construction).

    2. Wrong leniency on parse vs construct, plus a few genuinely-open value sets miscoded as closed enums

    Two sub-points:

    (a) Parse should be lenient, construct/encode should be strict. Several closed-enum headers (COOP, COEP, Referrer-Policy) have specs that say "ignore unknown values, fall back to default" when parsing. Today's parsers throw FormatException, which fails the whole header. Fix: on parse, return the default for unknown values; on construct, validate strictly so callers can't emit garbage.

    (b) A few headers are genuinely open per spec and should not be enums at all. These need a Token-typed open value, not a bigger Dart enum:

    • Content-Encoding (RFC 9110 8.4.1): IANA registry is extensible; the RFC explicitly allows extension content-codings; private codings inside internal services are legitimate.
    • Connection (RFC 9110 7.6.1): connection-option = token naming hop-by-hop field names, including custom ones (Connection: TE, Connection: Trailer).
    • CORS Allow-Methods / Method: HTTP methods are an IANA registry; WebDAV (PROPFIND, MKCOL), CalDAV (REPORT, MKCALENDAR), and custom REST verbs are all legal.

    All other closed-enum headers (COOP, COEP, Referrer-Policy, SameSite, Sec-Fetch-*, CORP) stay enums; the fix for those is just (a) plus adding any missing spec values.

    3. String-split parsing with literal separators

    The pure quoted-string subset is #102. The OWS subset (especially ;q=) is independent of #102 and is what makes Accept*/TE mis-parse weighted preferences. A composable parser library (petitparser as suggested in the issue body) addresses both subsets cleanly.

  3. moved this from Backlog 🗂️ to Done 🚀 in Serverpod Frameworkson Jun 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions