Diffinery

homeflare/celldpublic

227 lines · 10.0 KBRaw History
1// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2
3//! HTTP predicates, reified sans-IO.
4//!
5//! A Worker reads `request.url`, and celld builds that URL from a request
6//! header. The header is client-controlled whenever no proxy sits in front, so
7//! the shape of the authority is a SECURITY fence, exactly as
8//! `cell::valid_cell_scope`'s is. celld interpolates the authority into
9//! `<scheme>://<authority><path_and_query>`, so a character that is structural
10//! in a URL moves the boundary between the parts.
11//!
12//! The gate checks the structure as well as the charset. celld carries the URL
13//! to the Worker as a string and never parses it, so an authority a URL parser
14//! refuses reaches the application intact. `new URL(request.url)` is how a
15//! Worker reads its own path and query, and that call then throws: a `Host` of
16//! `a]b` gives `TypeError: Invalid URL`. A client therefore turns every request
17//! into an application error, so a shape like `a]b` or `999.1.1.1` has to fail
18//! here rather than inside the isolate.
19
20use std::net::Ipv6Addr;
21
22/// The longest authority celld accepts. A hostname is at most 253 bytes and can
23/// carry the root dot, and a port adds at most 6 more — a `:` and five digits —
24/// so this admits every legal value and bounds what one request can make the
25/// URL parser allocate.
26pub const MAX_AUTHORITY: usize = 260;
27
28/// The largest port a URL parser accepts.
29const MAX_PORT: u32 = 65535;
30
31/// The complete sans-IO decision for an authority in `request.url`.
32#[derive(Clone, Copy, Debug, Eq, PartialEq)]
33#[must_use]
34pub enum AuthorityDecision<'a> {
35 /// The authority cannot be installed in `request.url`.
36 Reject,
37 /// The authority is safe to install without another check.
38 Use(&'a str),
39 /// The authority has valid syntax, but a URL parser must validate its IDN.
40 NeedsUrlParser(&'a str),
41}
42
43/// Classify an authority before celld installs it in `request.url`.
44///
45/// The result carries the authority with the decision, so a caller cannot use
46/// a partial syntax result as a validated value.
47pub fn authority_decision(authority: &str) -> AuthorityDecision<'_> {
48 if !valid_authority(authority) {
49 AuthorityDecision::Reject
50 } else if has_idn_label(authority) {
51 AuthorityDecision::NeedsUrlParser(authority)
52 } else {
53 AuthorityDecision::Use(authority)
54 }
55}
56
57/// Does a URL authority have valid syntax? An optional port after either a
58/// bracketed IPv6 address or a registered name, and at most `MAX_AUTHORITY`
59/// bytes.
60///
61/// The charset of the name is the first fence, and it excludes every character
62/// that is structural in a URL. `/` starts a path, `?` starts a query, `#`
63/// starts a fragment, and `@` ends userinfo — so each one lets a client move
64/// the rest of the URL into a different component. A `Host: evil.example#`
65/// header on a request for `/admin` makes `request.url` read
66/// `http://evil.example#/admin`, where the real path becomes a fragment. celld
67/// dispatches on the request target, so the Worker then reads a path celld did
68/// not route, inside one process.
69///
70/// Whitespace and control bytes are excluded because they make the URL
71/// unparseable rather than merely wrong. Non-ASCII is excluded because a
72/// hostname reaches celld in its A-label form.
73///
74/// The structure is the second fence, because a charset alone admits shapes a
75/// URL parser refuses: `a]b`, `::1` and `999.1.1.1` carry no character that
76/// reshapes a URL, and each one makes `new URL(request.url)` throw in the
77/// Worker. So `[` and `]` are admitted only as a matched pair that wraps a whole
78/// IPv6 address, `:` only once outside that pair, where it separates a port that
79/// must be a number in range, and a name that ends in a number must be an IPv4
80/// address. `_` is admitted in a name because it occurs in practice in internal
81/// hostnames.
82///
83/// This predicate does not check that the authority is a hostname celld serves.
84/// `authority_decision` combines this syntax result with the IDN decision, so
85/// callers cannot install the partial result by itself.
86fn valid_authority(authority: &str) -> bool {
87 if authority.is_empty() || authority.len() > MAX_AUTHORITY {
88 return false;
89 }
90 // An IPv6 address is the one shape where a `:` is not the port separator,
91 // so the brackets are matched first and a port can only follow the closing
92 // one.
93 let after_host = if let Some(tail) = authority.strip_prefix('[') {
94 let Some((literal, after_host)) = tail.split_once(']') else {
95 return false;
96 };
97 if literal.parse::<Ipv6Addr>().is_err() {
98 return false;
99 }
100 after_host
101 } else {
102 let (name, after_host) = authority.split_at(authority.find(':').unwrap_or(authority.len()));
103 if !valid_reg_name(name) {
104 return false;
105 }
106 after_host
107 };
108 match after_host.strip_prefix(':') {
109 Some(port) => valid_port(port),
110 None => after_host.is_empty(),
111 }
112}
113
114/// A registered name: non-empty ASCII alphanumerics plus `_ - .`, and an IPv4
115/// address whenever it reads as one.
116///
117/// A URL parser stops treating a name as a name as soon as the last label is a
118/// number, and reads the whole name as an IPv4 address instead. So a name that
119/// merely looks numeric at the end is not a name that parses: `999.1.1.1`,
120/// `1.2.3.4.5` and `foo.1` each fail the address parse, and the URL therefore
121/// fails with them. Every such name is refused here.
122///
123/// The check on an address is stricter than the parser is, and deliberately so.
124/// A parser reads `010.1.1.1` as octal and `0x7f.1` as hex, so both name a
125/// different host than the text does, and `1234567890` names a fourth host
126/// again. celld refuses all three rather than hand a Worker a URL whose host is
127/// not the host the string shows. An address must therefore be four decimal
128/// labels, each at most 255 and none carrying a leading zero.
129fn valid_reg_name(name: &str) -> bool {
130 if name.is_empty()
131 || !name
132 .bytes()
133 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.'))
134 {
135 return false;
136 }
137 // A single root dot ends a fully-qualified name, and the parser reads the
138 // label before it as the last one.
139 let labels = name.strip_suffix('.').unwrap_or(name);
140 match labels.rsplit('.').next() {
141 Some(last) if reads_as_number(last) => {
142 let mut octets = labels.split('.');
143 let address = [octets.next(), octets.next(), octets.next(), octets.next()];
144 octets.next().is_none() && address.iter().all(|octet| octet.is_some_and(valid_octet))
145 }
146 _ => true,
147 }
148}
149
150/// Does this label make a URL parser read the whole name as an IPv4 address? It
151/// does when the label is decimal, and when it is hexadecimal with the `0x`
152/// prefix the parser accepts.
153fn reads_as_number(label: &str) -> bool {
154 let hex = label
155 .strip_prefix("0x")
156 .or_else(|| label.strip_prefix("0X"));
157 match hex {
158 Some(digits) => digits.bytes().all(|b| b.is_ascii_hexdigit()),
159 None => !label.is_empty() && label.bytes().all(|b| b.is_ascii_digit()),
160 }
161}
162
163/// One decimal octet of an IPv4 address: at most 255, and no leading zero,
164/// which a parser would read as octal.
165fn valid_octet(octet: &str) -> bool {
166 !octet.is_empty()
167 && octet.bytes().all(|b| b.is_ascii_digit())
168 && (octet == "0" || !octet.starts_with('0'))
169 && octet.parse::<u32>().is_ok_and(|octet| octet <= 255)
170}
171
172/// A port: decimal digits, and a number at most `MAX_PORT`. Leading zeros pass
173/// because a parser reads the number and not the text, and both name the same
174/// port. An empty port is refused, though a parser reads `host:` as `host`,
175/// because a header that carries a bare `:` is malformed at the source.
176fn valid_port(port: &str) -> bool {
177 !port.is_empty()
178 && port.bytes().all(|b| b.is_ascii_digit())
179 && port.parse::<u32>().is_ok_and(|port| port <= MAX_PORT)
180}
181
182/// Does this authority carry a label a URL parser decodes as Punycode?
183///
184/// A parser reads every label that starts with `xn--` as an internationalized
185/// name, and it fails the whole parse when the decode fails. `xn--a` passes
186/// `valid_authority` — it carries no character that reshapes a URL and no label
187/// that reads as a number — and `new URL(request.url)` still throws on it. A
188/// charset cannot see this, because Punycode is an encoding and not a charset,
189/// and the rules that decide a decoded label are the whole of IDNA. So the
190/// decision is reified here and the check itself belongs with a parser.
191///
192/// The predicate exists to keep that parser off the request path. A hostname
193/// carries no such label in almost every deployment, so celld scans for the
194/// prefix and parses only when it is present. Refusing every `xn--` label
195/// instead would cost every internationalized deployment its hostname, and
196/// admitting every one of them hands a client an error it can aim at any
197/// request.
198fn has_idn_label(authority: &str) -> bool {
199 authority.split('.').any(|label| {
200 label
201 .as_bytes()
202 .get(..4)
203 .is_some_and(|prefix| prefix.eq_ignore_ascii_case(b"xn--"))
204 })
205}
206
207/// The scheme celld serves for this value, or `None` for a value it cannot
208/// serve. Only `http` and `https`.
209///
210/// The scheme is interpolated into `request.url`, and a Worker builds a
211/// redirect or a link from it. An arbitrary scheme therefore becomes an
212/// arbitrary URL in an application's output: `X-Forwarded-Proto: javascript:`
213/// makes `new URL(request.url).protocol` read `javascript:`. celld speaks only
214/// HTTP, so no other scheme can be correct.
215///
216/// The header casing is not fixed, so the match ignores case. The return is the
217/// canonical spelling rather than the text that arrived, because celld puts the
218/// result in a URL it logs and hands on, and a scheme is lowercase there.
219pub fn canonical_scheme(scheme: &str) -> Option<&'static str> {
220 if scheme.eq_ignore_ascii_case("http") {
221 Some("http")
222 } else if scheme.eq_ignore_ascii_case("https") {
223 Some("https")
224 } else {
225 None
226 }
227}