Skip to main content

feather_reader/
net.rs

1//! Hardened outbound HTTP for **untrusted, user-supplied feed URLs**.
2//!
3//! A feed reader fetches arbitrary URLs on behalf of its users: the add-feed
4//! flow, the background poller, and OPML import all hand a *user-controlled*
5//! host to `reqwest`. Left unguarded that is a textbook **SSRF** primitive — a
6//! subscribed feed can `302` to `http://169.254.169.254/` (cloud metadata) or
7//! `http://127.0.0.1:<port>/` (an internal service), and because the body is
8//! reflected back into the reader UI the exfiltration is *non-blind*.
9//!
10//! This module centralises the defence so every fetch path shares one guard:
11//!
12//! 1. **Scheme allow-list** — only `http` / `https`. No `file:`, `gopher:`, …
13//! 2. **IP allow-list** — the target host is resolved to IP(s) and rejected if
14//!    *any* resolved address is one no public feed can live at: loopback,
15//!    link-local, private, ULA, multicast, unspecified, broadcast, and the
16//!    reserved, shared and documentation ranges — including any of those
17//!    embedded in an IPv6 address. [`is_forbidden_ip`] has the complete list.
18//! 3. **Per-hop re-validation** — auto-redirect is disabled and redirects are
19//!    followed manually, re-running (1) and (2) on **every** hop, so a benign
20//!    first host cannot bounce us onto an internal one.
21//! 4. **Capped streaming body** — the response body is streamed and aborted the
22//!    moment it exceeds [`MAX_BODY_BYTES`], so a gzip decompression bomb cannot
23//!    materialise gigabytes before a post-hoc size check (a Content-Length
24//!    guard is useless once gzip strips the header).
25//!
26//! Resolution happens immediately before each request. The vetted IP is then
27//! **pinned** onto the connection (reqwest `.resolve(host, addr)`), so `connect`
28//! reuses the exact address that passed [`is_forbidden_ip`] rather than doing an
29//! independent second DNS lookup. That closes the DNS-rebinding TOCTOU window: an
30//! attacker-controlled resolver cannot answer "public IP" for the check and
31//! "127.0.0.1" for the connect, because there is no second resolution.
32
33use std::collections::HashMap;
34use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
35use std::sync::atomic::{AtomicUsize, Ordering};
36use std::sync::{LazyLock, Mutex};
37use std::time::{Duration, Instant};
38
39use anyhow::{bail, Context, Result};
40use reqwest::header::{
41    HeaderName, HeaderValue, AUTHORIZATION, CONTENT_TYPE, COOKIE, PROXY_AUTHORIZATION,
42    WWW_AUTHENTICATE,
43};
44use reqwest::{Client, Response};
45use url::{Host, Url};
46
47/// Cap on how many bytes we will read from any body, streamed. 8 MiB is
48/// comfortably above any sane feed; a body that exceeds it is aborted mid-stream
49/// (never fully buffered), which is what defeats a gzip decompression bomb.
50pub const MAX_BODY_BYTES: usize = 8 * 1024 * 1024;
51
52/// Total per-request timeout for a guarded fetch. Matches
53/// [`crate::feed::build_client`]'s `FETCH_TIMEOUT` so the poller's per-hop
54/// pinned client is bounded the same way the feed client is — an unattended
55/// poll can't hang forever on a slow/silent upstream.
56///
57/// `pub(crate)` so a caller that wraps a *multi-request* walk in its own
58/// deadline can size that deadline against this per-request bound rather than
59/// hardcoding a second copy of the number — see [`crate::network::RelayClient`].
60pub(crate) const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
61
62/// Per-read idle timeout: cap the wait for the *next* body chunk, so a server
63/// that trickles bytes forever (slowloris) can't tie up a fetch under the total
64/// timeout. Matches [`crate::feed::build_client`]'s `READ_TIMEOUT`.
65const READ_TIMEOUT: Duration = Duration::from_secs(15);
66
67/// Maximum number of redirect hops we will follow (each re-validated).
68///
69/// `pub(crate)` alongside [`FETCH_TIMEOUT`] because the two together give the
70/// real worst-case cost of ONE guarded request: the redirect loop runs
71/// `0..=MAX_REDIRECTS`, and every hop builds a fresh [`pinned_client`] carrying
72/// its own full [`FETCH_TIMEOUT`]. A caller that wraps a guarded request in an
73/// outer deadline must budget `(MAX_REDIRECTS + 1) * FETCH_TIMEOUT`, not one
74/// `FETCH_TIMEOUT` — getting that wrong silently pre-empts the inner logic.
75pub(crate) const MAX_REDIRECTS: usize = 5;
76
77/// Worst-case wall-clock cost of a single guarded request, redirects included.
78/// The number an outer deadline has to respect; see [`MAX_REDIRECTS`].
79pub(crate) const WORST_CASE_REQUEST: Duration =
80    Duration::from_secs(FETCH_TIMEOUT.as_secs() * (MAX_REDIRECTS as u64 + 1));
81
82/// Whether an already-resolved IP address is one we must never connect to on
83/// behalf of an untrusted URL (SSRF sinks).
84///
85/// This is the complete list; keep it in step with the code.
86///
87/// **IPv4**
88///
89/// * `0.0.0.0/8` — "this network", including the unspecified `0.0.0.0` (RFC 1122 §3.2.1.3)
90/// * `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16` — private (RFC 1918)
91/// * `100.64.0.0/10` — shared address space, carrier-grade NAT and overlay VPNs (RFC 6598)
92/// * `127.0.0.0/8` — loopback (RFC 1122 §3.2.1.3)
93/// * `169.254.0.0/16` — link-local, where cloud metadata lives (RFC 3927)
94/// * `192.0.0.0/24` — IETF protocol assignments (RFC 6890)
95/// * `192.0.2.0/24`, `198.51.100.0/24`, `203.0.113.0/24` — documentation,
96///   TEST-NET-1/2/3 (RFC 5737)
97/// * `198.18.0.0/15` — benchmarking (RFC 2544)
98/// * `224.0.0.0/4` — multicast (RFC 5771)
99/// * `240.0.0.0/4` — reserved (RFC 1112 §4), which includes the limited
100///   broadcast address `255.255.255.255` (RFC 919)
101///
102/// **IPv6**
103///
104/// * `::` unspecified and `::1` loopback (RFC 4291)
105/// * `100::/64` — discard-only (RFC 6666)
106/// * `2001:db8::/32` — documentation (RFC 3849)
107/// * `fc00::/7` — unique local (RFC 4193)
108/// * `fe80::/10` — link-local (RFC 4291)
109/// * `fec0::/10` — site-local, deprecated but still routed internally on some
110///   networks (RFC 3879)
111/// * `ff00::/8` — multicast (RFC 4291)
112/// * Any address that embeds a forbidden IPv4 one: mapped and compatible
113///   (RFC 4291), IPv4-translated (RFC 2765), NAT64 (RFC 6052), 6to4 (RFC 3056),
114///   Teredo (RFC 4380) and ISATAP (RFC 5214). These are decoded and checked
115///   against the same IPv4 list above. The rest of `64:ff9b::/32` outside the
116///   well-known `/96`, including RFC 8215's local-use `64:ff9b:1::/48`, is
117///   refused outright. See `embedded_v4`.
118pub fn is_forbidden_ip(ip: &IpAddr) -> bool {
119    match ip {
120        IpAddr::V4(v4) => is_forbidden_v4(v4),
121        IpAddr::V6(v6) => is_forbidden_v6(v6),
122    }
123}
124
125fn is_forbidden_v4(ip: &Ipv4Addr) -> bool {
126    ip.is_loopback()            // 127.0.0.0/8
127        || ip.is_private()      // 10/8, 172.16/12, 192.168/16
128        || ip.is_link_local()   // 169.254.0.0/16 (cloud metadata)
129        || ip.is_unspecified()  // 0.0.0.0
130        || ip.is_multicast()    // 224.0.0.0/4
131        // 240.0.0.0/4 reserved (RFC 1112 §4). This also covers the broadcast
132        // address 255.255.255.255, so a separate `is_broadcast()` would be dead.
133        || matches!(ip.octets(), [240..=255, ..])
134        // Documentation ranges, TEST-NET-1/2/3 (RFC 5737).
135        || matches!(ip.octets(), [192, 0, 2, _])
136        || matches!(ip.octets(), [198, 51, 100, _])
137        || matches!(ip.octets(), [203, 0, 113, _])
138        // Carrier-grade NAT / "this-host" / benchmarking ranges — not routable
139        // to a legitimate public feed, but reachable internally.
140        || matches!(ip.octets(), [0, ..])
141        || matches!(ip.octets(), [100, b, ..] if (64..=127).contains(&b)) // 100.64/10 CGNAT (also used by overlay VPNs)
142        || matches!(ip.octets(), [192, 0, 0, _])
143        || matches!(ip.octets(), [198, 18..=19, _, _])
144}
145
146fn is_forbidden_v6(ip: &Ipv6Addr) -> bool {
147    if ip.is_loopback() || ip.is_unspecified() || ip.is_multicast() {
148        return true;
149    }
150    // Unwrap IPv4-mapped / -compatible addresses and re-check against the v4
151    // rules, so `::ffff:127.0.0.1` and friends can't slip past.
152    if let Some(v4) = ip.to_ipv4() {
153        return is_forbidden_v4(&v4);
154    }
155    // **And every OTHER way an IPv6 address carries an IPv4 one.** `to_ipv4()`
156    // stops at the mapped and compatible forms; five more families embed an
157    // address this function would refuse on sight, and all five were getting
158    // through. See [`embedded_v4`].
159    //
160    // This arm only ever returns `true`, so an address whose embedded IPv4 is
161    // public still falls through to the link-local and ULA checks below — which
162    // is what keeps `fe80::5efe:8.8.8.8` refused for being link-local.
163    if embedded_v4(ip).iter().any(is_forbidden_v4) {
164        return true;
165    }
166    let seg = ip.segments();
167    // fe80::/10 link-local (incl. RFC-4291 metadata equivalents).
168    let link_local = (seg[0] & 0xffc0) == 0xfe80;
169    // fec0::/10 site-local: deprecated (RFC 3879), but some networks still
170    // route it internally.
171    let site_local = (seg[0] & 0xffc0) == 0xfec0;
172    // fc00::/7 unique-local addresses.
173    let ula = (seg[0] & 0xfe00) == 0xfc00;
174    // 100::/64 discard-only (RFC 6666).
175    let discard = seg[..4] == [0x0100, 0, 0, 0];
176    // 2001:db8::/32 documentation (RFC 3849). Never globally routed.
177    let documentation = seg[0] == 0x2001 && seg[1] == 0x0db8;
178    link_local || site_local || ula || discard || documentation
179}
180
181/// Every IPv4 address `ip` embeds under a translation scheme, for re-checking
182/// against the v4 rules.
183///
184/// **`to_ipv4()` is not the whole story, and the gap was a live SSRF hole.** It
185/// handles `::ffff:a.b.c.d` and `::a.b.c.d`. These it does not:
186///
187/// * **NAT64** — `64:ff9b::/32`. RFC 6052's well-known prefix is defined as a
188///   `/96`, so inside it the IPv4 is the last 32 bits and is decoded. The rest
189///   of the `/32`, including RFC 8215's local-use `64:ff9b:1::/48`, is refused
190///   outright, because RFC 6052 §2.2 allows six embedding lengths and which one
191///   a local deployment used is not something this code can know.
192/// * **6to4** — `2002::/16` (RFC 3056), IPv4 in the next two groups.
193/// * **IPv4-translated** — `::ffff:0:0:0/96` (RFC 2765), one group away from the
194///   mapped form.
195/// * **Teredo** — `2001::/32` (RFC 4380): the relay's IPv4 in groups 2-3 and the
196///   client's in groups 6-7, the latter obfuscated by XOR with all-ones. Both are
197///   returned; either one reaching an internal address is enough to refuse.
198/// * **ISATAP** — RFC 5214, and the odd one out: **no prefix to anchor on.** The
199///   IPv4 is the low 32 bits behind the IANA-reserved `00-00-5E-FE` OUI, under
200///   ANY /64, so an ordinary-looking global address can carry one. A link-local
201///   ISATAP address was already refused for being `fe80::/10`; one under a
202///   global prefix was not refused at all.
203///
204/// Decoded rather than blanket-refused for 6to4, IPv4-translated and Teredo,
205/// because those prefixes carry public addresses too and a blocklist would take
206/// out ordinary traffic. `allows_ipv6_that_embeds_a_public_ipv4` holds that line.
207///
208/// Found while bumping a JavaScript dependency whose advisory was this class:
209/// "no classifier recognizes the NAT64 local-use range". Ours did not either.
210fn embedded_v4(ip: &Ipv6Addr) -> Vec<Ipv4Addr> {
211    let seg = ip.segments();
212    let v4 = |hi: u16, lo: u16| {
213        Ipv4Addr::new(
214            (hi >> 8) as u8,
215            (hi & 0xff) as u8,
216            (lo >> 8) as u8,
217            (lo & 0xff) as u8,
218        )
219    };
220    // NAT64, split by prefix length because only one of the two is unambiguous.
221    //
222    // RFC 6052's well-known prefix is DEFINED as `64:ff9b::/96`, so inside it
223    // the IPv4 is unambiguously the last 32 bits and decodes like the others.
224    // That matters for availability, not just tidiness: a DNS64 resolver
225    // (RFC 6147) synthesises a well-known-prefix AAAA for every IPv4-only host,
226    // and `first_vetted` rejects a whole DNS answer set if ANY address in it is
227    // forbidden — so refusing the prefix outright makes every IPv4-only feed
228    // publisher unfetchable on an IPv6-only network. Which is the network this
229    // guard was written for.
230    //
231    // Nothing is given up by decoding: `64:ff9b::a9fe:a9fe` still refuses,
232    // because 169.254.169.254 refuses on its own merits. RFC 6052 §3.1 also
233    // forbids the well-known prefix from carrying a non-global IPv4 at all, so
234    // such an address is malformed as well as hostile.
235    //
236    // The REST of `64:ff9b::/32` — notably RFC 8215's local-use
237    // `64:ff9b:1::/48` — stays refused outright, and that is deliberate rather
238    // than lazy. RFC 6052 §2.2 defines six embedding lengths, and which one a
239    // local-use deployment chose is a property of that deployment. Guessing
240    // wrong reads the wrong bits, which could turn an internal target into a
241    // public-looking one — so for anything but the /96 the conservative answer
242    // is the only safe one. `LOCALHOST` there is a stand-in for "forbidden",
243    // not a claim about where the address points.
244    if seg[0] == 0x0064 && seg[1] == 0xff9b {
245        if seg[2..6] == [0, 0, 0, 0] {
246            return vec![v4(seg[6], seg[7])];
247        }
248        return vec![Ipv4Addr::LOCALHOST];
249    }
250    // **From here the arms ACCUMULATE instead of returning.** An early return
251    // was a bypass: 6to4 delegates `2002:<site-v4>::/48` to whoever owns that
252    // IPv4 and the site assigns identifiers inside it, so a site running ISATAP
253    // in its own 6to4 space produces `2002:<site-v4>:0:0:5efe:<internal-v4>` —
254    // two readings of DISJOINT bits, both true at once. Returning the 6to4 site
255    // address alone reported a public address and skipped the tunnel endpoint.
256    //
257    // This is the opposite of the Teredo case below, and the difference is
258    // which bits each family claims, not which is more important.
259    let mut out = Vec::new();
260    // 6to4: the site's IPv4 in groups 1-2, disjoint from the identifier.
261    if seg[0] == 0x2002 {
262        out.push(v4(seg[1], seg[2]));
263    }
264    // IPv4-translated: `::ffff:0:a.b.c.d`.
265    //
266    // This one accumulates for uniformity rather than necessity, and the
267    // distinction is worth recording: it requires `seg[5] == 0` where ISATAP
268    // requires `0x5efe`, and `seg[..4] == 0` excludes 6to4 and Teredo too, so
269    // it can only ever be the sole match. Returning here instead is an
270    // EQUIVALENT mutant — no test can tell the difference, and one written to
271    // try would be asserting on nothing. It pushes so that an arm added below
272    // it later is not silently skipped, which is the mistake the 6to4 arm
273    // above made.
274    if seg[..4] == [0, 0, 0, 0] && seg[4] == 0xffff && seg[5] == 0 {
275        out.push(v4(seg[6], seg[7]));
276    }
277    // Teredo: relay, then the client with the RFC 4380 obfuscation undone.
278    //
279    // **The one arm that still returns, because it CLAIMS the identifier's
280    // bits.** Teredo's client address lives in groups 6-7 complemented — the
281    // same bits ISATAP reads uncomplemented — so the two readings are of one
282    // field and contradict each other. Accumulating both would refuse a
283    // legitimate Teredo address whenever the inverse of its client address
284    // happens to be internal. Returning here resolves that in favour of the
285    // prefix, which `a_teredo_address_is_read_as_teredo_not_as_isatap` pins.
286    if seg[0] == 0x2001 && seg[1] == 0 {
287        out.push(v4(seg[2], seg[3]));
288        out.push(v4(seg[6] ^ 0xffff, seg[7] ^ 0xffff));
289        return out;
290    }
291    // ISATAP, and it is last so that Teredo above can suppress it.
292    //
293    // The others are prefix-anchored; this one is not — the IPv4 sits in the low
294    // 32 bits behind the IANA `00-00-5E-FE` OUI under ANY /64, so the test is on
295    // the interface identifier and matches whatever the prefix. Being reachable
296    // under another family's prefix is the point, not an edge case: it is why
297    // the arms above accumulate rather than return.
298    //
299    // **`seg[4]` is deliberately not constrained.** RFC 5214 spells the
300    // identifier as `000000ug 00000000 0x5E 0xFE` + the IPv4, so a spec-exact
301    // test would require all of `seg[4]` except the `u` and `g` bits to be
302    // zero. Two drafts of this arm tried to be that precise and the first was
303    // wrong: it enumerated `0x0000` and `0x0200`, missed the two values with
304    // `g` set, and so was bypassable by flipping one bit while reading as
305    // complete.
306    //
307    // The asymmetry decides it. Reading the marker loosely costs a false
308    // positive only when a non-ISATAP address happens to carry `0x5efe` in
309    // group 5 AND its low 32 bits decode to a forbidden IPv4 — and `00-00-5E`
310    // is IANA's own OUI, reserved for this, so a real interface identifier does
311    // not land there. Reading it strictly costs a total bypass if any tunnel
312    // driver is more lenient than the RFC about the reserved bits. A guard
313    // should be conservative about what it accepts as safe, which here means
314    // the simpler condition, not the more exact one.
315    if seg[5] == 0x5efe {
316        out.push(v4(seg[6], seg[7]));
317    }
318    out
319}
320
321/// Validate a URL's scheme (http/https only). Returns the host as a string.
322fn check_scheme(url: &Url) -> Result<()> {
323    match url.scheme() {
324        "http" | "https" => Ok(()),
325        other => bail!("refusing non-http(s) URL scheme {other:?}"),
326    }
327}
328
329/// Resolve a URL's host to socket addresses, reject if *any* resolved IP is a
330/// forbidden (SSRF) target, and return the **vetted** `SocketAddr` to pin the
331/// connection to.
332///
333/// An IP literal host is checked directly (no DNS); a named host is resolved via
334/// the async resolver and *every* answer must pass — but the returned address is
335/// the specific one `connect` must use, so no independent second resolution can
336/// slip a rebound IP past the check (DNS-rebinding TOCTOU). Handles both IPv4 and
337/// IPv6 answers.
338async fn resolve_and_check(url: &Url) -> Result<SocketAddr> {
339    let host = url.host().context("URL has no host")?;
340    let port = url
341        .port_or_known_default()
342        .context("URL has no usable port")?;
343
344    match host {
345        Host::Ipv4(ip) => {
346            if is_forbidden_ip(&IpAddr::V4(ip)) {
347                bail!("refusing to fetch forbidden (internal) address {ip}");
348            }
349            Ok(SocketAddr::new(IpAddr::V4(ip), port))
350        }
351        Host::Ipv6(ip) => {
352            if is_forbidden_ip(&IpAddr::V6(ip)) {
353                bail!("refusing to fetch forbidden (internal) address {ip}");
354            }
355            Ok(SocketAddr::new(IpAddr::V6(ip), port))
356        }
357        Host::Domain(name) => {
358            // **Test seam — `#[cfg(test)]`, so it does not exist in a release
359            // build at all.** Not a parameter, not an env var, not a feature
360            // flag: the compiler removes it, so there is no runtime bypass to
361            // reason about. It exists because the guard is otherwise untestable
362            // end-to-end — a local test server lives on loopback, which
363            // `is_forbidden_ip` correctly refuses, so nothing could ever drive a
364            // real redirect through this function. See `test_host_override`.
365            #[cfg(test)]
366            if let Some(addr) = test_override_for(name, port) {
367                return Ok(addr);
368            }
369            let addrs = tokio::net::lookup_host((name, port))
370                .await
371                .with_context(|| format!("resolving host {name:?}"))?;
372            first_vetted(name, addrs)
373        }
374    }
375}
376
377/// Pick the address to pin to from a host's DNS answers, rejecting the whole
378/// set if ANY answer is forbidden.
379///
380/// **Extracted so it can be tested.** Inline in the resolver it was unreachable
381/// without real DNS returning a mixed answer set, and a mutation that checked
382/// only the FIRST answer left the entire suite green — a DNS-rebinding style
383/// attack that publishes `1.2.3.4, 127.0.0.1` would have been accepted on the
384/// strength of the first record.
385///
386/// Rejecting wholesale rather than filtering is deliberate: a host that resolves
387/// to any internal address is not a host we want to talk to, even on the answers
388/// that look fine.
389fn first_vetted(name: &str, addrs: impl Iterator<Item = SocketAddr>) -> Result<SocketAddr> {
390    let mut vetted: Option<SocketAddr> = None;
391    for sa in addrs {
392        let ip = sa.ip();
393        if is_forbidden_ip(&ip) {
394            bail!("refusing to fetch {name:?}: resolves to forbidden address {ip}");
395        }
396        // Keep the FIRST vetted answer as the address to pin the connect to.
397        // Every answer is still checked (the loop continues), so a mixed A/AAAA
398        // set with any forbidden entry is rejected wholesale.
399        if vetted.is_none() {
400            vetted = Some(sa);
401        }
402    }
403    vetted.ok_or_else(|| anyhow::anyhow!("host {name:?} did not resolve to any address"))
404}
405
406/// Test-only host→address overrides, consulted by [`resolve_and_check`] before
407/// real DNS. Keyed by host so tests using distinct hostnames never collide, and
408/// gone entirely from a release build.
409#[cfg(test)]
410static TEST_HOSTS: std::sync::Mutex<Option<std::collections::HashMap<String, SocketAddr>>> =
411    std::sync::Mutex::new(None);
412
413/// The TEST certificate authority, and the leaf it issues for test hostnames.
414///
415/// **Why this exists at all.** An OAuth issuer is required to be `https`
416/// (`discovery::validate_issuer_form`), so a plain-HTTP loopback server cannot
417/// stand in for an authorization server — which meant the real `login::complete`
418/// could never be driven end to end, and the wiring between its tested core and
419/// the network had no coverage. A review proved that gap was live: the
420/// authorization-server mix-up defence could be disabled in that wiring with the
421/// whole suite green.
422///
423/// **Why a CA rather than relaxing the rule.** The alternative was a test-only
424/// escape from the https requirement. That would *suspend* a security rule; this
425/// *satisfies* it — the server really presents a certificate and the client
426/// really validates the chain. It also keeps the existing tests that assert
427/// `http` issuers are REJECTED meaningful, which a blanket relaxation would not.
428///
429/// Generated once per process. `#[cfg(test)]`, so none of it — not the trust
430/// decision, not the key material — exists in a release build.
431#[cfg(test)]
432pub(crate) struct TestPki {
433    /// PEM of the CA certificate, for `reqwest`'s root store.
434    pub ca_pem: String,
435    /// PEM of the leaf certificate chain, for the server.
436    pub leaf_pem: String,
437    /// PEM of the leaf private key, for the server.
438    pub leaf_key_pem: String,
439}
440
441#[cfg(test)]
442pub(crate) fn test_pki() -> &'static TestPki {
443    static PKI: std::sync::OnceLock<TestPki> = std::sync::OnceLock::new();
444    PKI.get_or_init(|| {
445        use rcgen::{
446            BasicConstraints, CertificateParams, DnType, IsCa, KeyPair, KeyUsagePurpose, SanType,
447        };
448
449        let mut ca_params = CertificateParams::default();
450        ca_params
451            .distinguished_name
452            .push(DnType::CommonName, "featherreader test CA");
453        ca_params.is_ca = IsCa::Ca(BasicConstraints::Constrained(0));
454        ca_params.key_usages = vec![
455            KeyUsagePurpose::KeyCertSign,
456            KeyUsagePurpose::CrlSign,
457            KeyUsagePurpose::DigitalSignature,
458        ];
459        let ca_key = KeyPair::generate().expect("test CA key");
460        let ca_cert = ca_params
461            .clone()
462            .self_signed(&ca_key)
463            .expect("test CA cert");
464        let issuer = rcgen::Issuer::new(ca_params, ca_key);
465
466        // SANs for the hostnames the tests register with `test_host_override`.
467        // A wildcard would not cover the multi-label names, so they are listed.
468        let mut leaf_params = CertificateParams::default();
469        leaf_params
470            .distinguished_name
471            .push(DnType::CommonName, "featherreader test leaf");
472        leaf_params.subject_alt_names = TEST_TLS_HOSTS
473            .iter()
474            .map(|h| SanType::DnsName((*h).try_into().expect("test SAN")))
475            .collect();
476        let leaf_key = KeyPair::generate().expect("test leaf key");
477        let leaf_cert = leaf_params
478            .signed_by(&leaf_key, &issuer)
479            .expect("test leaf cert");
480
481        TestPki {
482            ca_pem: ca_cert.pem(),
483            leaf_pem: leaf_cert.pem(),
484            leaf_key_pem: leaf_key.serialize_pem(),
485        }
486    })
487}
488
489#[cfg(test)]
490/// A loopback HTTPS server presenting the test CA's leaf, routing by path.
491///
492/// The point of the TLS is not TLS: it is that an OAuth issuer must be
493/// `https`, so nothing could drive the real `login::complete` against a
494/// local server. The client validates this chain for real — no invalid-cert
495/// acceptance anywhere.
496///
497/// `routes` maps a path to a canned `(status, body)`. Unknown paths 404.
498/// Every request line is recorded.
499pub(crate) async fn spawn_tls<F>(
500    build_routes: F,
501) -> (SocketAddr, std::sync::Arc<std::sync::Mutex<Vec<String>>>)
502where
503    F: FnOnce(SocketAddr) -> std::collections::HashMap<String, Vec<TestResponse>>,
504{
505    use tokio::io::{AsyncReadExt, AsyncWriteExt};
506    use tokio_rustls::rustls::pki_types::{CertificateDer, PrivateKeyDer};
507
508    // Both `ring` and `aws-lc-rs` are reachable in this tree, so rustls refuses
509    // to guess a process-level provider for the SERVER side here. Install ring.
510    //
511    // **Two earlier versions of this comment were wrong in opposite directions;
512    // this is what reqwest 0.13 actually does** (`async_impl/client.rs`):
513    //
514    //     let provider = rustls::crypto::CryptoProvider::get_default()
515    //         .map(|arc| arc.clone())
516    //         .unwrap_or_else(default_rustls_crypto_provider);
517    //
518    // So it READS the process default and falls back to aws-lc-rs. Installing
519    // ring here therefore DOES affect reqwest clients built afterwards in the
520    // same test binary — which makes the client's provider depend on whether any
521    // test called `spawn_tls` first. Benign (ring and aws-lc-rs interoperate),
522    // and absent from release builds, where nothing installs a default and
523    // production is genuinely aws-lc-rs. Recorded precisely because two previous
524    // attempts at this comment stated a checkable fact without checking it.
525    //
526    // `install_default` errors if something got there first, which is fine.
527    static PROVIDER: std::sync::Once = std::sync::Once::new();
528    PROVIDER.call_once(|| {
529        let _ = tokio_rustls::rustls::crypto::ring::default_provider().install_default();
530    });
531
532    let pki = test_pki();
533    let certs: Vec<CertificateDer<'static>> = rustls_pemfile_certs(pki.leaf_pem.as_bytes());
534    let key: PrivateKeyDer<'static> = rustls_pemfile_key(pki.leaf_key_pem.as_bytes());
535
536    let config = tokio_rustls::rustls::ServerConfig::builder()
537        .with_no_client_auth()
538        .with_single_cert(certs, key)
539        .expect("test server TLS config");
540    let acceptor = tokio_rustls::TlsAcceptor::from(std::sync::Arc::new(config));
541
542    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
543    let addr = listener.local_addr().unwrap();
544    // Routes are built from the bound address: the documents have to name their
545    // own port, and the port is not known until the listener exists.
546    let routes = build_routes(addr);
547    let log = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
548    let sink = std::sync::Arc::clone(&log);
549    let hits: std::sync::Arc<std::sync::Mutex<std::collections::HashMap<String, usize>>> =
550        Default::default();
551
552    tokio::spawn(async move {
553        loop {
554            let Ok((sock, _)) = listener.accept().await else {
555                break;
556            };
557            let acceptor = acceptor.clone();
558            let routes = routes.clone();
559            let sink = std::sync::Arc::clone(&sink);
560            let hits = std::sync::Arc::clone(&hits);
561            tokio::spawn(async move {
562                let Ok(mut tls) = acceptor.accept(sock).await else {
563                    return;
564                };
565                // **The head, and the body when `content-length` says how
566                // much — before replying.**
567                //
568                // A single `read` is what the capturing sidecar on the #138
569                // branch did, and the review of that branch found the trap: if
570                // the head and the body land in separate segments, the capture
571                // holds only the head, and every `contains` assertion over it
572                // then passes for the wrong reason.
573                //
574                // Nothing here asserts on a body today — the assertions are the
575                // request line and the DPoP header, and both panic loudly when
576                // absent rather than passing — so that false green is not live
577                // in this harness. It is the NEXT body assertion that would
578                // inherit one, which is the whole reason the same shape was
579                // worth fixing there.
580                //
581                // **A chunked body is NOT drained.** With no `content-length`
582                // there is nothing to wait for, so this stops after the head —
583                // exactly what the single read did. Every request this harness
584                // sees is a GET or a reqwest-buffered form and carries a length,
585                // but nothing here enforces that, so a future chunked request
586                // would be captured short and quietly. Said plainly rather than
587                // left inside a claim to have read "the whole request".
588                //
589                // Draining also stops the reply being written while the client
590                // is still sending, which would make a split request a broken
591                // pipe rather than a response.
592                let mut raw: Vec<u8> = Vec::new();
593                let mut chunk = [0u8; 4096];
594                loop {
595                    let Ok(n) = tls.read(&mut chunk).await else {
596                        return;
597                    };
598                    if n == 0 {
599                        break;
600                    }
601                    raw.extend_from_slice(&chunk[..n]);
602                    let Some(split) = raw.windows(4).position(|w| w == b"\r\n\r\n") else {
603                        continue;
604                    };
605                    let (head, body) = raw.split_at(split + 4);
606                    let want = String::from_utf8_lossy(head).lines().find_map(|l| {
607                        let (k, v) = l.split_once(':')?;
608                        k.eq_ignore_ascii_case("content-length")
609                            .then(|| v.trim().parse::<usize>().ok())?
610                    });
611                    if want.is_none_or(|want| body.len() >= want) {
612                        break;
613                    }
614                }
615                let req = String::from_utf8_lossy(&raw).to_string();
616                let path = req
617                    .lines()
618                    .next()
619                    .and_then(|l| l.split_whitespace().nth(1))
620                    .unwrap_or("/")
621                    .to_string();
622                sink.lock().unwrap().push(req);
623                // Nth hit on this path picks the Nth canned reply; the last one
624                // repeats. That is what lets a route answer a nonce challenge
625                // once and something else afterwards — the only way to observe
626                // whether a request was RETRIED.
627                let n = {
628                    let mut c = hits.lock().unwrap();
629                    let e = c.entry(path.clone()).or_insert(0usize);
630                    let n = *e;
631                    *e += 1;
632                    n
633                };
634                let reply = routes
635                    .get(&path)
636                    .and_then(|v| v.get(n.min(v.len().saturating_sub(1))))
637                    .cloned()
638                    .unwrap_or_else(|| TestResponse::json(404, "not found"));
639                let extra: String = reply
640                    .headers
641                    .iter()
642                    .map(|(k, v)| format!("{k}: {v}\r\n"))
643                    .collect();
644                let (status, body) = (reply.status, reply.body);
645                let resp = format!(
646                    "HTTP/1.1 {status} X\r\nContent-Type: application/json\r\n{extra}\
647                     Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
648                    body.len()
649                );
650                let _ = tls.write_all(resp.as_bytes()).await;
651                let _ = tls.shutdown().await;
652            });
653        }
654    });
655    (addr, log)
656}
657
658#[cfg(test)]
659fn rustls_pemfile_certs(
660    pem: &[u8],
661) -> Vec<tokio_rustls::rustls::pki_types::CertificateDer<'static>> {
662    // Minimal PEM splitter — avoids another dependency for two blocks.
663    decode_pem_blocks(pem, "CERTIFICATE")
664        .into_iter()
665        .map(Into::into)
666        .collect()
667}
668
669#[cfg(test)]
670fn rustls_pemfile_key(pem: &[u8]) -> tokio_rustls::rustls::pki_types::PrivateKeyDer<'static> {
671    let der = decode_pem_blocks(pem, "PRIVATE KEY")
672        .into_iter()
673        .next()
674        .expect("a private key block");
675    tokio_rustls::rustls::pki_types::PrivatePkcs8KeyDer::from(der).into()
676}
677
678#[cfg(test)]
679fn decode_pem_blocks(pem: &[u8], label: &str) -> Vec<Vec<u8>> {
680    use base64::Engine as _;
681    let text = String::from_utf8_lossy(pem);
682    let begin = format!("-----BEGIN {label}-----");
683    let end = format!("-----END {label}-----");
684    let mut out = Vec::new();
685    let mut rest = text.as_ref();
686    while let Some(i) = rest.find(&begin) {
687        let after = &rest[i + begin.len()..];
688        let Some(j) = after.find(&end) else { break };
689        let b64: String = after[..j].chars().filter(|c| !c.is_whitespace()).collect();
690        out.push(
691            base64::engine::general_purpose::STANDARD
692                .decode(b64)
693                .expect("valid base64 in test PEM"),
694        );
695        rest = &after[j + end.len()..];
696    }
697    out
698}
699
700/// One canned reply from the TLS test server.
701#[cfg(test)]
702#[derive(Clone)]
703pub(crate) struct TestResponse {
704    pub status: u16,
705    pub body: String,
706    pub headers: Vec<(String, String)>,
707}
708
709#[cfg(test)]
710impl TestResponse {
711    pub fn json(status: u16, body: impl Into<String>) -> Self {
712        Self {
713            status,
714            body: body.into(),
715            headers: Vec::new(),
716        }
717    }
718
719    pub fn with_header(mut self, k: &str, v: &str) -> Self {
720        self.headers.push((k.to_string(), v.to_string()));
721        self
722    }
723}
724
725/// Hostnames the test leaf is valid for. Adding a new `.test` host to a test
726/// means adding it here, which is deliberate friction: the certificate is
727/// supposed to be narrow.
728#[cfg(test)]
729pub(crate) const TEST_TLS_HOSTS: &[&str] = &[
730    "pds-e2e.test",
731    "as-e2e.test",
732    "feed-tls.test",
733    "hop-tls.test",
734    "as-evil.test",
735];
736
737/// Point `host` at `addr` for the rest of the process, bypassing DNS **and** the
738/// forbidden-IP check for that host only.
739///
740/// **Registrations are process-global and last-write-wins.** Several tests
741/// register the SAME hostnames to different servers concurrently. What keeps
742/// them apart is not the host key — an earlier comment claimed it was — but that
743/// reqwest's `.resolve()` ignores the port, so every registration collapses to
744/// `127.0.0.1` and each test's URL port routes it back to its own listener. That
745/// is incidental, and would break the moment a test server bound anything other
746/// than loopback.
747///
748/// Bypassing the IP check is the entire point: the test server is on loopback,
749/// which the guard is right to refuse. Only the registered host is exempt —
750/// anything else in the same test, including every redirect target, still goes
751/// through the real check. That is what makes a redirect test meaningful.
752#[cfg(test)]
753pub(crate) fn test_host_override(host: &str, addr: SocketAddr) {
754    TEST_HOSTS
755        .lock()
756        .unwrap()
757        .get_or_insert_with(Default::default)
758        .insert(host.to_string(), addr);
759}
760
761#[cfg(test)]
762fn test_override_for(name: &str, port: u16) -> Option<SocketAddr> {
763    let guard = TEST_HOSTS.lock().unwrap();
764    let map = guard.as_ref()?;
765    map.get(name)
766        .copied()
767        .or_else(|| map.get(&format!("{name}:{port}")).copied())
768}
769
770/// How long an idle pinned client may be kept before it is rebuilt.
771///
772/// Not a security boundary — the address is re-resolved and re-checked on every
773/// single request, and a changed address misses the cache by construction. This
774/// only bounds how long a pooled connection to a once-vetted address may live,
775/// and keeps the map from holding entries for hosts nobody fetches any more.
776const PINNED_CLIENT_TTL: Duration = Duration::from_secs(300);
777
778/// Most distinct (host, address) pairs kept. A bound, not a target: the reader
779/// talks to one PDS, while the poller talks to as many hosts as there are feeds.
780const MAX_PINNED_CLIENTS: usize = 256;
781
782/// How long a pinned client may hold an IDLE socket open.
783///
784/// Deliberately shorter than [`PINNED_CLIENT_TTL`] so a client releases its
785/// sockets before the cache releases the client — otherwise the last minute of
786/// an entry's life is pure socket rent. See [`build_pinned_client`] for why the
787/// pool needs bounding at all.
788const POOL_IDLE_TIMEOUT: Duration = Duration::from_secs(60);
789
790/// Pinned clients, keyed by the **vetted address** they are pinned to.
791///
792/// ## Why this is safe to reuse
793///
794/// Building a fresh client per request meant a fresh connection pool, so every
795/// PDS call paid a full TCP + TLS handshake: measured at 91 ms against this
796/// project's PDS versus 30 ms on a warm connection. That is most of why the
797/// Rust repo backend measured ~3x slower than the Node sidecar, which pools.
798///
799/// Reuse does NOT weaken the DNS-rebinding defence, because the defence does not
800/// live in the client's lifetime:
801///
802/// * every request still resolves the host and runs [`is_forbidden_ip`] over
803///   EVERY answer before this cache is consulted — a host that now resolves to
804///   an internal address is refused before a pooled client could be returned;
805/// * the key includes the vetted [`SocketAddr`], so a host that legitimately
806///   moves to a different address MISSES the cache and gets a client pinned to
807///   the new one. A pooled connection can only ever be reused for an address
808///   that was just re-vetted this request.
809struct PinnedClients {
810    entries: Mutex<HashMap<(String, SocketAddr), (Client, Instant)>>,
811    /// How many clients have actually been constructed. Test-only bookkeeping:
812    /// it is the only way to observe that a hit avoided a rebuild, since
813    /// `reqwest::Client` exposes no identity.
814    builds: AtomicUsize,
815}
816
817impl PinnedClients {
818    fn new() -> Self {
819        Self {
820            entries: Mutex::new(HashMap::new()),
821            builds: AtomicUsize::new(0),
822        }
823    }
824
825    /// A client pinned to `addr` for `host`, reusing a pooled one when the
826    /// address is unchanged and the entry is fresh.
827    fn get(&self, host: &str, addr: SocketAddr, now: Instant) -> Result<Client> {
828        let key = (host.to_string(), addr);
829        // A poisoned lock here is NOT fatal and must not be treated as fatal: the
830        // guard is held across a fallible builder, so one panic inside it would
831        // otherwise make EVERY subsequent outbound request panic, forever, with a
832        // live-looking process and a green /health. Recover the data like the rate
833        // limiter already does — a torn entry is a cache entry, worst case a rebuild.
834        let mut entries = self.entries.lock().unwrap_or_else(|p| p.into_inner());
835
836        if let Some((client, last_used)) = entries.get_mut(&key) {
837            if now.duration_since(*last_used) < PINNED_CLIENT_TTL {
838                *last_used = now;
839                // Cloning a `reqwest::Client` shares its connection pool, which
840                // is the entire point — a clone is a handle, not a new pool.
841                return Ok(client.clone());
842            }
843        }
844
845        let client = build_pinned_client(host, addr)?;
846        self.builds.fetch_add(1, Ordering::Relaxed);
847
848        // Drop anything idle past the TTL before considering the bound, so a
849        // burst of one-off hosts does not evict the PDS client we use constantly.
850        entries.retain(|_, (_, last_used)| now.duration_since(*last_used) < PINNED_CLIENT_TTL);
851        if entries.len() >= MAX_PINNED_CLIENTS {
852            if let Some(oldest) = entries
853                .iter()
854                .min_by_key(|(_, (_, last_used))| *last_used)
855                .map(|(k, _)| k.clone())
856            {
857                entries.remove(&oldest);
858            }
859        }
860        entries.insert(key, (client.clone(), now));
861        Ok(client)
862    }
863}
864
865static PINNED_CLIENTS: LazyLock<PinnedClients> = LazyLock::new(PinnedClients::new);
866
867/// Build a per-hop client that **pins** DNS for `host` to the already-vetted
868/// `addr`, so reqwest's `connect` reuses the exact IP that passed the SSRF check
869/// instead of doing its own second resolution (the DNS-rebinding fix). The pin is
870/// scoped to `host`, keyed to the address family of `addr` (works for both IPv4
871/// and IPv6). Mirrors [`crate::feed::build_client`]'s policy: the same total
872/// [`FETCH_TIMEOUT`] + per-read [`READ_TIMEOUT`] (so the unattended poller keeps
873/// its slowloris / slow-upstream defence even though each hop is a freshly built
874/// client), and auto-redirect off — [`guarded_get`] follows + re-validates each
875/// hop itself.
876fn build_pinned_client(host: &str, addr: SocketAddr) -> Result<Client> {
877    let builder = Client::builder()
878        .user_agent(crate::USER_AGENT)
879        // Bound each hop the same way the feed client is bounded: a total
880        // request timeout plus a per-read idle timeout. Without these the
881        // per-hop client the poller actually connects through had NO timeouts,
882        // leaving the unattended poll with no defence against a slowloris /
883        // never-finishing upstream.
884        .timeout(FETCH_TIMEOUT)
885        .read_timeout(READ_TIMEOUT)
886        // Bound the idle connection pool too.
887        //
888        // These clients are CACHED — up to `MAX_PINNED_CLIENTS` of them, each
889        // holding its own pool — and every entry keeps live keep-alive TLS
890        // connections open until it is evicted. With reqwest's defaults
891        // (unlimited idle per host, no idle timeout) a poller touching many
892        // distinct feed hosts drives the cache toward its bound and each entry
893        // toward an unbounded number of sockets, on a 512 MB box with one shared
894        // core. The cache was given a size bound for the same reason; its pools
895        // were not.
896        //
897        // One idle connection per host is the right number here: reuse across
898        // the ~300 s TTL is what the cache exists for (measured 91 ms cold
899        // versus 30 ms warm), and nothing in this codebase issues concurrent
900        // requests to the SAME host through one client — `guarded_get` walks
901        // redirect hops sequentially, and the poller's concurrency is across
902        // DIFFERENT feeds. The idle timeout is well under the cache TTL so
903        // sockets are released before the client itself is.
904        .pool_max_idle_per_host(1)
905        .pool_idle_timeout(POOL_IDLE_TIMEOUT)
906        // **Ignore ambient proxy configuration.** reqwest defaults
907        // `auto_sys_proxy: true`, so `HTTP_PROXY` / `HTTPS_PROXY` / `ALL_PROXY`
908        // in the process environment silently route every request through a
909        // proxy — and a proxied request is sent in absolute form for the PROXY
910        // to resolve the hostname. That defeats the two mechanisms this whole
911        // module rests on at once: the `.resolve()` pin below never sees the
912        // connection, and `is_forbidden_ip` never sees the address, because we
913        // no longer do the resolving.
914        //
915        // Measured before this line existed, with `HTTP_PROXY` set: the vetted
916        // address received ZERO requests, the proxy received
917        // `GET http://pinned.invalid/feed HTTP/1.1`, and the call returned
918        // `Ok(200)`. It failed OPEN and silently.
919        //
920        // Not remotely triggerable — it needs a proxy variable in the server's
921        // own environment — but that is one `fly secrets set`, one debugging
922        // session, or one base image away, and nothing would have reported the
923        // guard had stopped working.
924        .no_proxy()
925        // Override reqwest's resolver for this host only: connect goes straight
926        // to the vetted socket address — no independent re-resolution.
927        .resolve(host, addr)
928        // No auto-redirect: guarded_get follows + re-validates each hop.
929        .redirect(reqwest::redirect::Policy::none());
930
931    // **The TEST certificate authority — `#[cfg(test)]`, so a release build has
932    // neither this call nor the certificate.**
933    //
934    // This is the one test seam in this file that touches TLS TRUST, so it is
935    // worth being exact about what it does and does not do. It ADDS one root:
936    // the built-in roots stay, nothing is disabled, and `danger_accept_invalid_
937    // certs` is NOT used — a server still has to present a chain that validates,
938    // and a hostname still has to match a SAN. What it buys is that a loopback
939    // test server can hold a certificate the client will accept, which is what
940    // makes it possible to drive the real `login::complete` (and the real
941    // redirect path) against a server at all: the OAuth issuer must be `https`.
942    //
943    // `test_pki()` is itself `#[cfg(test)]`, so removing the attribute here
944    // fails to compile rather than silently trusting an extra root in prod.
945    #[cfg(test)]
946    let builder = builder.add_root_certificate(
947        reqwest::Certificate::from_pem(test_pki().ca_pem.as_bytes())
948            .context("parsing the test CA")?,
949    );
950
951    builder
952        .build()
953        .context("failed to build IP-pinned fetch client")
954}
955
956/// The per-hop client for an already-vetted `(host, addr)`, pooled.
957///
958/// Callers must have run [`resolve_and_check`] for THIS request before calling
959/// this — the cache trusts its key, and the key is only as good as the check
960/// that produced it.
961fn pinned_client(host: &str, addr: SocketAddr) -> Result<Client> {
962    PINNED_CLIENTS.get(host, addr, Instant::now())
963}
964
965/// Fetch a user-supplied URL through the full SSRF guard: scheme + IP checks on
966/// the initial URL and on **every** redirect hop, following redirects manually.
967///
968/// The passed `client` is used only as a policy reference; each hop is actually
969/// sent through a freshly-built `pinned_client` whose DNS for the target host
970/// is pinned to the exact IP that just passed `resolve_and_check` — so the
971/// connect can't be rebound onto an internal address between the check and the
972/// TCP handshake.
973///
974/// `extra_headers` are applied to every hop (e.g. the conditional-GET
975/// `If-None-Match` / `If-Modified-Since` validators) — **except** credential
976/// headers (`Authorization`, `Cookie`, …), which are dropped the moment a
977/// redirect leaves the original origin, mirroring what reqwest's own redirect
978/// policy does for the shared client (see `hop_headers`). Returns the final
979/// `Response` (headers only; the body is read separately via [`read_capped`]).
980/// `Err` on a blocked scheme/address, an exhausted redirect budget, or a
981/// transport error.
982pub async fn guarded_get(
983    client: &Client,
984    url: &str,
985    extra_headers: &[(HeaderName, HeaderValue)],
986) -> Result<Response> {
987    guarded_get_inner(client, url, extra_headers, true, MAX_REDIRECTS).await
988}
989
990/// The SSRF core of [`guarded_get`] **without** the feed-privacy layer: scheme +
991/// IP allow-list, connect-pinning, and per-hop re-validation, but no
992/// `classify_feed_privacy` check.
993///
994/// This is the entry point for **non-feed** fetches of *user-influenced* URLs —
995/// notably atproto identity resolution (a handle's PDS host, a `did:web`
996/// well-known document, and a DID document's `serviceEndpoint`). Those are
997/// legitimate atproto XRPC / DID-doc requests, so the feed-privacy heuristic
998/// (which flags Substack/Patreon-style token URLs) must not apply — but the SSRF
999/// guard absolutely must, since a hostile `did:web` or `serviceEndpoint` can
1000/// otherwise point the server at `169.254.169.254`, loopback, or a private host.
1001pub async fn guarded_get_no_privacy(
1002    client: &Client,
1003    url: &str,
1004    extra_headers: &[(HeaderName, HeaderValue)],
1005) -> Result<Response> {
1006    guarded_get_inner(client, url, extra_headers, false, MAX_REDIRECTS).await
1007}
1008
1009/// Like [`guarded_get_no_privacy`] but **refuses redirects outright**.
1010///
1011/// For the OAuth discovery and DID documents, following a redirect is not a
1012/// convenience — it is a hole. The mix-up defence rests on comparing a
1013/// document's `issuer` against *the URL it was fetched from*; if a `302` can move
1014/// the fetch to another origin, that comparison is against the original URL while
1015/// the bytes came from somewhere else, and the check silently stops meaning
1016/// anything. The reference client sets `redirect: 'manual'`/`'error'` on every
1017/// one of these fetches for the same reason.
1018///
1019/// Applies to: `/.well-known/oauth-protected-resource`,
1020/// `/.well-known/oauth-authorization-server`, `plc.directory/<did>`, `did:web`
1021/// `did.json`, and the client-metadata self-fetch. It deliberately does NOT
1022/// apply to `/.well-known/atproto-did`, where the handle spec explicitly permits
1023/// redirects.
1024pub async fn guarded_get_no_redirect(
1025    client: &Client,
1026    url: &str,
1027    extra_headers: &[(HeaderName, HeaderValue)],
1028) -> Result<Response> {
1029    guarded_get_inner(client, url, extra_headers, false, 0).await
1030}
1031
1032/// Whether a header carries credentials that must never follow a redirect onto a
1033/// different origin. Mirrors reqwest's own `redirect::remove_sensitive_headers`
1034/// set (`Authorization`, `Cookie`, `Cookie2`, `Proxy-Authorization`,
1035/// `WWW-Authenticate`), which the shared client applies automatically — and which
1036/// [`guarded_get_inner`] must reimplement because it disables auto-redirect and
1037/// re-applies `extra_headers` by hand on every manually-followed hop.
1038fn is_sensitive_header(name: &HeaderName) -> bool {
1039    name == AUTHORIZATION
1040        || name == COOKIE
1041        || name == PROXY_AUTHORIZATION
1042        || name == WWW_AUTHENTICATE
1043        || name.as_str() == "cookie2"
1044}
1045
1046/// Same-origin in the web sense: identical scheme, host, and effective port.
1047fn same_origin(a: &Url, b: &Url) -> bool {
1048    a.scheme() == b.scheme()
1049        && a.host_str() == b.host_str()
1050        && a.port_or_known_default() == b.port_or_known_default()
1051}
1052
1053/// The headers to apply on THIS hop: all of `extra` while we are still on the
1054/// original origin, otherwise only the non-sensitive ones.
1055///
1056/// The comparison base is the **original** URL rather than the previous hop (what
1057/// reqwest does). That is strictly stricter: an `a → b → a` redirect chain never
1058/// re-attaches the credential, at the cost of a small, deliberate divergence from
1059/// the stock client's behaviour.
1060fn hop_headers<'a>(
1061    original: &Url,
1062    current: &Url,
1063    extra: &'a [(HeaderName, HeaderValue)],
1064) -> Vec<&'a (HeaderName, HeaderValue)> {
1065    let cross_origin = !same_origin(original, current);
1066    extra
1067        .iter()
1068        .filter(|(name, _)| !(cross_origin && is_sensitive_header(name)))
1069        .collect()
1070}
1071
1072async fn guarded_get_inner(
1073    client: &Client,
1074    url: &str,
1075    extra_headers: &[(HeaderName, HeaderValue)],
1076    check_privacy: bool,
1077    max_redirects: usize,
1078) -> Result<Response> {
1079    // `client` is retained in the signature for API stability + as the policy
1080    // template; the actual send goes through a per-hop IP-pinned client.
1081    let _ = client;
1082    let mut current = Url::parse(url).with_context(|| format!("not a valid URL {url:?}"))?;
1083    // The origin the caller's credentials belong to; a hop off it drops them.
1084    let original = current.clone();
1085
1086    for _ in 0..=max_redirects {
1087        check_scheme(&current)?;
1088        // Re-validate PRIVACY on EVERY hop: a public URL can `30x` to a
1089        // secret-bearing private feed (Substack/Patreon/tokened podcast). Without
1090        // this, the private target would be fetched — its body streamed and
1091        // reflected into the UI — before storage is refused, violating the
1092        // "never fetched" half of the public-feeds-only guarantee. Classify the
1093        // resolved target BEFORE the request and abort the whole fetch if private.
1094        // (Skipped for non-feed atproto identity fetches — see
1095        // [`guarded_get_no_privacy`].)
1096        if check_privacy {
1097            if let crate::feed::FeedPrivacy::Private(reason) =
1098                crate::feed::classify_feed_privacy(current.as_str())
1099            {
1100                bail!("refusing to fetch private/paid feed URL (redirect target): {reason}");
1101            }
1102        }
1103        // Re-validate on EVERY hop and capture the vetted address to pin to.
1104        let vetted = resolve_and_check(&current).await?;
1105        let host = current
1106            .host_str()
1107            .context("URL lost its host between hops")?
1108            .to_string();
1109        let hop_client = pinned_client(&host, vetted)?;
1110
1111        let mut req = hop_client.get(current.clone());
1112        // Sensitive headers (Authorization / Cookie / …) are applied only while
1113        // the hop is still on the ORIGINAL origin: a hostile upstream must not be
1114        // able to `302` a caller's bearer token onto a host it controls.
1115        for (name, value) in hop_headers(&original, &current, extra_headers) {
1116            req = req.header(name.clone(), value.clone());
1117        }
1118        let resp = req
1119            .send()
1120            .await
1121            .with_context(|| format!("fetching {current}"))?;
1122
1123        // **Only the statuses that actually relocate — NOT all of `3xx`.**
1124        //
1125        // `is_redirection()` is `300..=399`, which swallows `304 Not Modified`.
1126        // A 304 carries no `Location` *by definition*, so it fell into the
1127        // branch below and failed the whole fetch with "redirect response
1128        // without a usable Location header". `feed.rs` sends `If-None-Match` /
1129        // `If-Modified-Since` on every poll and has a correct 304 branch — which
1130        // could therefore never be reached. The effect was that "nothing new"
1131        // became a recorded failure plus exponential backoff, punishing exactly
1132        // the feeds that implement conditional GET properly. Observed in
1133        // production against 9to5mac.com, proton.me and kodi.tv, all live.
1134        //
1135        // **304 is the ONLY status carved out.** Everything else in `3xx`
1136        // relocates in some sense, and stays inside this branch — because
1137        // `guarded_get_no_redirect` documents that it "refuses redirects
1138        // outright", and the OAuth mix-up defence rests on that holding for all
1139        // of them, not just the five we would otherwise follow.
1140        if resp.status() != reqwest::StatusCode::NOT_MODIFIED && resp.status().is_redirection() {
1141            if max_redirects == 0 {
1142                bail!(
1143                    "refusing to follow a {} redirect while fetching {url:?} \u{2014} \
1144                     this document's origin is load-bearing and must not be moved",
1145                    resp.status()
1146                );
1147            }
1148            // Of the relocating statuses, only these five name a single target
1149            // worth following. `300 Multiple Choices` names no one target, and
1150            // `305 Use Proxy` names a PROXY — following it would route the
1151            // request through a host the RESPONSE chose.
1152            //
1153            // **Refused, not returned.** Handing one back would be worse than
1154            // erroring: callers do not uniformly check the status.
1155            // `web::resolve_feed_url` reads the body straight into feed
1156            // autodiscovery, so a `305` whose error page carries a
1157            // `<link rel="alternate">` would become a subscription.
1158            if !matches!(resp.status().as_u16(), 301 | 302 | 303 | 307 | 308) {
1159                bail!(
1160                    "refusing to act on a {} response while fetching {url:?} \u{2014} \
1161                     it names no single target that can be followed safely",
1162                    resp.status()
1163                );
1164            }
1165            let location = resp
1166                .headers()
1167                .get(reqwest::header::LOCATION)
1168                .and_then(|v| v.to_str().ok())
1169                .context("redirect response without a usable Location header")?;
1170            // Resolve the (possibly relative) Location against the current URL,
1171            // then loop to re-validate the new hop before touching it.
1172            current = current
1173                .join(location)
1174                .with_context(|| format!("resolving redirect Location {location:?}"))?;
1175            continue;
1176        }
1177
1178        return Ok(resp);
1179    }
1180
1181    bail!("too many redirects (> {max_redirects}) while fetching {url:?}")
1182}
1183
1184/// POST a JSON body to a **user-influenced** URL through the SSRF guard.
1185///
1186/// The write-side counterpart to [`guarded_get_no_privacy`], and the only way
1187/// [`crate::atproto::PdsClient`] is allowed to reach a PDS host it did not
1188/// choose. It runs the same scheme allow-list, the same IP allow-list, and the
1189/// same connect-pinning (via `pinned_client`), so the DNS-rebinding window
1190/// between "`assert_public_target` said this host is public" and "the TCP
1191/// handshake happens" is closed for writes exactly as it is for reads.
1192///
1193/// `Content-Type: application/json` is set here rather than by the caller, so
1194/// the one header the XRPC wire format requires cannot be forgotten; the caller
1195/// passes only its credential header(s).
1196///
1197/// **Redirects are refused, not followed** — the single deliberate divergence
1198/// from [`guarded_get`]. A `307`/`308` re-sends the method *and the body*
1199/// verbatim, and reqwest's cross-origin header sanitisation only strips
1200/// **headers**: an app password or a record body lives in the JSON payload, so a
1201/// hostile PDS answering `307 Location: https://evil.example/collect` would
1202/// exfiltrate it however carefully the headers were handled. There is no
1203/// legitimate reason for a PDS to redirect an `com.atproto.repo.*` write, so the
1204/// safe behaviour and the correct behaviour coincide: `Err`, loudly.
1205pub async fn guarded_post_json(
1206    client: &Client,
1207    url: &str,
1208    extra_headers: &[(HeaderName, HeaderValue)],
1209    body: Vec<u8>,
1210) -> Result<Response> {
1211    guarded_post(client, url, extra_headers, PostBody::Json(body)).await
1212}
1213
1214/// A request body together with the content type that describes it.
1215///
1216/// The two travel as ONE value deliberately. Passing the content type alongside
1217/// the bytes made it possible to send a JSON body labelled as a form, or the
1218/// reverse — a swap no test could see without a live server, and the SSRF guard
1219/// forbids pointing one of these at loopback. Deriving the header from the same
1220/// value that produces the bytes removes the failure mode instead of watching
1221/// for it.
1222pub(crate) enum PostBody<'a> {
1223    Json(Vec<u8>),
1224    Form(&'a [(&'a str, &'a str)]),
1225}
1226
1227impl PostBody<'_> {
1228    fn content_type(&self) -> HeaderValue {
1229        match self {
1230            PostBody::Json(_) => HeaderValue::from_static("application/json"),
1231            PostBody::Form(_) => HeaderValue::from_static("application/x-www-form-urlencoded"),
1232        }
1233    }
1234
1235    /// Every form value goes through the serializer rather than string
1236    /// interpolation: an OAuth form carries the authorization code, the PKCE
1237    /// verifier and the client assertion, and a raw `&` or `=` in any of them
1238    /// would otherwise splice an extra parameter into the request.
1239    fn into_bytes(self) -> Vec<u8> {
1240        match self {
1241            PostBody::Json(bytes) => bytes,
1242            PostBody::Form(params) => {
1243                let mut ser = url::form_urlencoded::Serializer::new(String::new());
1244                for (k, v) in params {
1245                    ser.append_pair(k, v);
1246                }
1247                ser.finish().into_bytes()
1248            }
1249        }
1250    }
1251}
1252
1253/// POST a form-encoded body to a **user-influenced** URL through the SSRF guard.
1254///
1255/// The OAuth counterpart to [`guarded_post_json`]: PAR, token exchange and
1256/// refresh are all `application/x-www-form-urlencoded`. It matters more here
1257/// than anywhere else that the guard applies — these are the requests that
1258/// carry the client assertion and the authorization code, so an issuer URL
1259/// that resolves to loopback or RFC1918 has to fail closed *before* the
1260/// credential leaves the process.
1261///
1262/// Redirects are refused for the same reason as [`guarded_post_json`], and more
1263/// acutely: a `307` would re-send the assertion and code to the new host.
1264pub async fn guarded_post_form(
1265    client: &Client,
1266    url: &str,
1267    extra_headers: &[(HeaderName, HeaderValue)],
1268    params: &[(&str, &str)],
1269) -> Result<Response> {
1270    guarded_post(client, url, extra_headers, PostBody::Form(params)).await
1271}
1272
1273/// The shared body of [`guarded_post_json`] and [`guarded_post_form`]. Kept as
1274/// one function so the guard cannot drift between the two content types.
1275async fn guarded_post(
1276    client: &Client,
1277    url: &str,
1278    extra_headers: &[(HeaderName, HeaderValue)],
1279    body: PostBody<'_>,
1280) -> Result<Response> {
1281    let content_type = body.content_type();
1282    let body = body.into_bytes();
1283    // As in `guarded_get_inner`: `client` is the policy template; the send goes
1284    // through a freshly built, IP-pinned client.
1285    let _ = client;
1286    let target = Url::parse(url).with_context(|| format!("not a valid URL {url:?}"))?;
1287    check_scheme(&target)?;
1288    let vetted = resolve_and_check(&target).await?;
1289    let host = target.host_str().context("URL has no host")?.to_string();
1290    let hop_client = pinned_client(&host, vetted)?;
1291
1292    let mut req = hop_client
1293        .post(target.clone())
1294        .header(CONTENT_TYPE, content_type)
1295        .body(body);
1296    for (name, value) in extra_headers {
1297        req = req.header(name.clone(), value.clone());
1298    }
1299    let resp = req
1300        .send()
1301        .await
1302        .with_context(|| format!("posting to {target}"))?;
1303
1304    // Unlike the GET path this refuses the WHOLE of `3xx`, `304` included, and
1305    // that is deliberate: nothing here sends `If-None-Match`/`If-Modified-Since`,
1306    // so a 304 to a POST is a server protocol violation rather than a
1307    // conditional-GET success, and there is no sane way to act on it.
1308    //
1309    // It is worded separately all the same. Calling a 304 "a redirect we refused
1310    // to follow" is the same misattribution that made the GET bug take a
1311    // production investigation to find — the message should not send the next
1312    // reader looking for a `Location` that was never supposed to exist.
1313    if resp.status().is_redirection() {
1314        if resp.status() == reqwest::StatusCode::NOT_MODIFIED {
1315            bail!(
1316                "a POST to {url:?} answered 304 Not Modified, which is not a valid \
1317                 response to a request carrying no conditional headers"
1318            );
1319        }
1320        let location = resp
1321            .headers()
1322            .get(reqwest::header::LOCATION)
1323            .and_then(|v| v.to_str().ok())
1324            .unwrap_or("<none>");
1325        bail!(
1326            "refusing to follow a {} redirect on a POST to {url:?} (Location: {location}) — \
1327             a 307/308 would re-send the request body to the new host",
1328            resp.status()
1329        );
1330    }
1331
1332    Ok(resp)
1333}
1334
1335/// Read a response body, streaming chunk-by-chunk and **aborting** the moment
1336/// the accumulated size would exceed [`MAX_BODY_BYTES`]. Never trusts
1337/// `Content-Length` (gzip strips it) and never fully buffers an over-cap body —
1338/// this is the decompression-bomb / OOM guard.
1339pub async fn read_capped(mut resp: Response) -> Result<Vec<u8>> {
1340    let mut buf: Vec<u8> = Vec::with_capacity(16 * 1024);
1341    while let Some(chunk) = resp.chunk().await.context("reading response body chunk")? {
1342        if buf.len() + chunk.len() > MAX_BODY_BYTES {
1343            bail!(
1344                "response body exceeded the {} byte cap; aborting",
1345                MAX_BODY_BYTES
1346            );
1347        }
1348        buf.extend_from_slice(&chunk);
1349    }
1350    Ok(buf)
1351}
1352
1353/// Validate that a URL is safe to use as an outbound target: `http`/`https`
1354/// scheme AND every resolved IP passes the SSRF allow-list. Returns `Ok(())` for
1355/// a public target, `Err` for a forbidden one (loopback / link-local / private /
1356/// ULA / CGNAT / metadata) or a bad scheme.
1357///
1358/// Use this to vet a URL *before* it is stashed and later fetched by a client
1359/// that does not itself route through [`guarded_get`] — notably an atproto PDS
1360/// `serviceEndpoint` resolved out of a (hostile-controllable) DID document, so a
1361/// `serviceEndpoint: "http://169.254.169.254/"` is rejected at resolve time
1362/// rather than reaching a raw XRPC client.
1363pub async fn assert_public_target(url: &str) -> Result<()> {
1364    let parsed = Url::parse(url).with_context(|| format!("not a valid URL {url:?}"))?;
1365    check_scheme(&parsed)?;
1366    resolve_and_check(&parsed).await?;
1367    Ok(())
1368}
1369
1370/// Scheme-allow-list a URL destined to be rendered as an `href` (an entry's
1371/// "View original" link, a feed's site link). Accepts only `http`/`https`;
1372/// anything else (notably `javascript:` / `data:` — stored-XSS vectors that
1373/// survive HTML escaping) yields `None` so the caller drops the link.
1374pub fn safe_link(raw: &str) -> Option<String> {
1375    let trimmed = raw.trim();
1376    if trimmed.is_empty() {
1377        return None;
1378    }
1379    match Url::parse(trimmed) {
1380        Ok(u) if matches!(u.scheme(), "http" | "https") => Some(trimmed.to_string()),
1381        _ => None,
1382    }
1383}
1384
1385#[cfg(test)]
1386pub(crate) mod tests {
1387    use super::*;
1388
1389    #[test]
1390    fn forbids_loopback_and_link_local_and_private_v4() {
1391        for ip in [
1392            "127.0.0.1",
1393            "127.1.2.3",
1394            "169.254.169.254", // cloud metadata
1395            "10.0.0.5",
1396            "172.16.9.9",
1397            "192.168.1.1",
1398            "0.0.0.0",
1399            "255.255.255.255",
1400            "100.64.0.1", // 100.64/10 CGNAT range (also overlay VPNs)
1401        ] {
1402            let ip: IpAddr = ip.parse().unwrap();
1403            assert!(is_forbidden_ip(&ip), "{ip} should be forbidden");
1404        }
1405    }
1406
1407    #[test]
1408    fn allows_public_v4() {
1409        for ip in ["1.1.1.1", "8.8.8.8", "93.184.216.34"] {
1410            let ip: IpAddr = ip.parse().unwrap();
1411            assert!(!is_forbidden_ip(&ip), "{ip} should be allowed");
1412        }
1413    }
1414
1415    #[test]
1416    fn forbids_internal_v6() {
1417        for ip in [
1418            "::1",
1419            "fe80::1",
1420            "fc00::1",
1421            "fd00::1",
1422            "::ffff:127.0.0.1",
1423            "::",
1424        ] {
1425            let ip: IpAddr = ip.parse().unwrap();
1426            assert!(is_forbidden_ip(&ip), "{ip} should be forbidden");
1427        }
1428    }
1429
1430    /// **An IPv6 address that EMBEDS a forbidden IPv4 one is a forbidden address,
1431    /// and four families of them were getting through.**
1432    ///
1433    /// `is_forbidden_v6` unwrapped IPv4-mapped (`::ffff:a.b.c.d`) and
1434    /// IPv4-compatible (`::a.b.c.d`) forms, which is where `to_ipv4()` stops. It
1435    /// did not unwrap:
1436    ///
1437    /// * **NAT64**, `64:ff9b::/32` — the well-known prefix of RFC 6052 and the
1438    ///   local-use prefix of RFC 8215. On a NAT64/DNS64 network,
1439    ///   `64:ff9b::a9fe:a9fe` is the cloud metadata service.
1440    /// * **6to4**, `2002::/16` (RFC 3056) — the IPv4 sits in the next two groups,
1441    ///   so `2002:a9fe:a9fe::` is the same address again.
1442    /// * **IPv4-translated**, `::ffff:0:0/96` (RFC 2765) — one group away from the
1443    ///   mapped form `to_ipv4()` does handle.
1444    /// * **Teredo**, `2001::/32` (RFC 4380) — carries the relay's IPv4 in groups
1445    ///   2-3 and the client's, obfuscated by XOR with all-ones, in groups 6-7.
1446    /// * **ISATAP**, RFC 5214 — the IPv4 in the low 32 bits behind the IANA
1447    ///   `00-00-5E-FE` OUI, under ANY /64. The only one of the five with no
1448    ///   prefix to anchor on, so `2606:4700::5efe:c0a8:1` is an entirely
1449    ///   ordinary-looking global address that names 192.168.0.1.
1450    ///
1451    /// Found while bumping a JavaScript dependency whose advisory was the same
1452    /// class: "no classifier recognizes the NAT64 local-use range". Ours did not
1453    /// either.
1454    ///
1455    /// Whether a given deployment can route these depends on a translator being on
1456    /// the path — but the attacker does not need to know that, only to try it, and
1457    /// an IPv6-only network with DNS64 is now the ordinary case rather than the
1458    /// exotic one. This guard is defence in depth against exactly the address that
1459    /// reaches the host's own network without looking like it.
1460    #[test]
1461    fn forbids_ipv6_that_embeds_a_forbidden_ipv4() {
1462        for (ip, what) in [
1463            ("64:ff9b::7f00:1", "NAT64 well-known -> 127.0.0.1"),
1464            ("64:ff9b::a9fe:a9fe", "NAT64 well-known -> 169.254.169.254"),
1465            ("64:ff9b::c0a8:1", "NAT64 well-known -> 192.168.0.1"),
1466            ("64:ff9b:1::7f00:1", "NAT64 local-use, RFC 8215"),
1467            ("64:ff9b:1:ffff::1", "anywhere in the NAT64 /32"),
1468            ("2002:7f00:1::", "6to4 -> 127.0.0.1"),
1469            ("2002:a9fe:a9fe::", "6to4 -> 169.254.169.254"),
1470            ("::ffff:0:7f00:1", "IPv4-translated -> 127.0.0.1"),
1471            // Teredo, laid out the way the format actually is: server IPv4 in
1472            // groups 2-3, client IPv4 in groups 6-7 XORed with all-ones. Each case
1473            // keeps the OTHER field public, so it fails for the reason its label
1474            // claims rather than because a zero field is forbidden anyway.
1475            ("2001:0:7f00:1:0:0:f7f7:fbfb", "Teredo server -> 127.0.0.1"),
1476            ("2001:0:808:808:0:0:80ff:fffe", "Teredo client -> 127.0.0.1"),
1477            (
1478                "2001:0:808:808:0:0:5601:5601",
1479                "Teredo client -> 169.254.169.254",
1480            ),
1481            // ISATAP (RFC 5214): the IPv4 sits in the low 32 bits behind the
1482            // IANA-reserved `00-00-5E-FE` OUI, under ANY /64 — so unlike the
1483            // four above there is no prefix to anchor on, and a perfectly
1484            // ordinary-looking global address can carry one.
1485            //
1486            // These sit under a real global prefix, not the `2001:db8::/32`
1487            // documentation one: that prefix is refused on its own (#217), so
1488            // a fixture there would pass with the ISATAP arm deleted.
1489            ("2606:4700::5efe:7f00:1", "ISATAP -> 127.0.0.1"),
1490            ("2606:4700::5efe:a9fe:a9fe", "ISATAP -> 169.254.169.254"),
1491            // All four values the IID's first byte can take, kept as named
1492            // regressions. RFC 5214 spells it `000000ug`, so `u` and `g` are
1493            // both free. The first draft of this guard enumerated only the two
1494            // with `g` clear, leaving the other two allowed — a one-bit bypass
1495            // of a guard that read as complete. Reverting the arm to that
1496            // enumeration fails on the `g=1` rows below.
1497            (
1498                "2606:4700::200:5efe:a9fe:a9fe",
1499                "ISATAP u=1 g=0 -> 169.254.169.254",
1500            ),
1501            ("2606:4700::100:5efe:7f00:1", "ISATAP u=0 g=1 -> 127.0.0.1"),
1502            ("2606:4700::300:5efe:7f00:1", "ISATAP u=1 g=1 -> 127.0.0.1"),
1503            (
1504                "2606:4700::5efe:c0a8:1",
1505                "ISATAP under a REAL public prefix -> 192.168.0.1",
1506            ),
1507            // **An ISATAP identifier INSIDE another family's prefix.** 6to4
1508            // delegates `2002:<site-v4>::/48` to whoever owns that IPv4, and
1509            // the site assigns identifiers inside it — so a site running ISATAP
1510            // in its own 6to4 space produces exactly this. The two families
1511            // read DISJOINT bits (6to4 the site address in groups 1-2, ISATAP
1512            // the tunnel endpoint in groups 6-7), so both readings are true at
1513            // once and checking only the first is a bypass.
1514            (
1515                "2002:808:808:0:0:5efe:a9fe:a9fe",
1516                "6to4 site 8.8.8.8 + ISATAP -> 169.254.169.254",
1517            ),
1518            (
1519                "2002:808:808:0:0:5efe:7f00:1",
1520                "6to4 site 8.8.8.8 + ISATAP -> 127.0.0.1",
1521            ),
1522            (
1523                "2002:101:101:0:0:5efe:c0a8:1",
1524                "6to4 site 1.1.1.1 + ISATAP -> 192.168.0.1",
1525            ),
1526        ] {
1527            let parsed: IpAddr = ip.parse().unwrap();
1528            assert!(
1529                is_forbidden_ip(&parsed),
1530                "{ip} reaches {what} and was allowed",
1531            );
1532        }
1533    }
1534
1535    /// The other direction, and it is not decoration: refusing every address that
1536    /// merely *looks* translated would take out ordinary public traffic. A 6to4
1537    /// address wrapping a PUBLIC IPv4, and a Teredo address wrapping one, must both
1538    /// still be allowed — that is what makes this a decode rather than a
1539    /// prefix-blocklist.
1540    #[test]
1541    fn allows_ipv6_that_embeds_a_public_ipv4() {
1542        for (ip, what) in [
1543            ("2002:0808:0808::", "6to4 -> 8.8.8.8"),
1544            (
1545                "2001:0:808:808:0:0:f7f7:fbfb",
1546                "Teredo, server 8.8.8.8 and client 8.8.4.4",
1547            ),
1548            ("::ffff:0:808:808", "IPv4-translated -> 8.8.8.8"),
1549            ("2606:4700::5efe:808:808", "ISATAP -> 8.8.8.8"),
1550            // The DNS64 case, and the reason NAT64 is decoded rather than
1551            // prefix-refused: a resolver doing DNS64 synthesises exactly this
1552            // for an IPv4-only host, so refusing the prefix outright makes
1553            // every IPv4-only feed publisher unfetchable on an IPv6-only
1554            // network — the very network that motivated the guard.
1555            ("64:ff9b::808:808", "NAT64 well-known prefix -> 8.8.8.8"),
1556            // Both readings of one address, both public. The arms accumulate,
1557            // so this is the case that keeps that a decode rather than "any
1558            // 6to4 address carrying a `5efe` identifier is refused".
1559            (
1560                "2002:808:808:0:0:5efe:808:404",
1561                "6to4 site 8.8.8.8 + ISATAP 8.8.4.4",
1562            ),
1563        ] {
1564            let parsed: IpAddr = ip.parse().unwrap();
1565            assert!(!is_forbidden_ip(&parsed), "{ip} is {what} and was refused");
1566        }
1567    }
1568
1569    /// **The well-known prefix decodes; the local-use one does not — and the
1570    /// difference is deliberate, so it needs a test and not just a comment.**
1571    ///
1572    /// `64:ff9b::/96` is a fixed-length prefix by definition (RFC 6052 §3.1), so
1573    /// the embedded IPv4 is unambiguously the last 32 bits. RFC 8215's local-use
1574    /// `64:ff9b:1::/48` is not: RFC 6052 §2.2 allows six embedding lengths and
1575    /// which one a deployment chose is a property of that deployment. Guessing
1576    /// wrong reads the wrong bits and could render an internal target as a
1577    /// public-looking address, so everything outside the /96 is refused whole.
1578    ///
1579    /// The cost is real and accepted: a site translating through its local-use
1580    /// prefix cannot fetch through this reader. The alternative is a decode that
1581    /// is wrong whenever the guess is wrong, in the one direction that matters.
1582    ///
1583    /// Extending the decode to the whole `/32` fails this test.
1584    #[test]
1585    fn a_local_use_nat64_prefix_is_refused_even_wrapping_a_public_address() {
1586        let ip: IpAddr = "64:ff9b:1::808:808".parse().unwrap();
1587        assert!(
1588            is_forbidden_ip(&ip),
1589            "the local-use NAT64 prefix was decoded as if its embedding length \
1590             were known",
1591        );
1592    }
1593
1594    /// **The DNS64 path, end to end through the function that rejects answer
1595    /// sets.** This is the interaction the unit cases cannot see.
1596    ///
1597    /// On an IPv6-only network a DNS64 resolver (RFC 6147) synthesises a
1598    /// well-known-prefix AAAA for every IPv4-only host, and that synthesised
1599    /// address is the ONLY answer — there is no "ordinary address we resolve
1600    /// anyway". Since `first_vetted` rejects a whole set if any member is
1601    /// forbidden, refusing `64:ff9b::/96` outright made every IPv4-only feed
1602    /// publisher unfetchable on exactly the network this guard was written for.
1603    ///
1604    /// Both directions, because the fix must not cost the guard: a synthesised
1605    /// answer for a PUBLIC host resolves, and a synthesised answer for the
1606    /// metadata service still poisons the set.
1607    #[test]
1608    fn a_dns64_answer_set_for_an_ipv4_only_host_is_fetchable() {
1609        let synthesised: SocketAddr = "[64:ff9b::808:808]:80".parse().unwrap();
1610        let public_v4: SocketAddr = "1.2.3.4:80".parse().unwrap();
1611
1612        // IPv6-only: the synthesised address is the whole answer.
1613        assert_eq!(
1614            first_vetted("v4only.example", [synthesised].into_iter()).unwrap(),
1615            synthesised,
1616            "a DNS64-synthesised answer for a public host was refused, which \
1617             makes every IPv4-only publisher unfetchable behind NAT64",
1618        );
1619        // Dual-stack with DNS64: the synthesised answer must not poison the set.
1620        assert!(first_vetted("both.example", [public_v4, synthesised].into_iter()).is_ok());
1621
1622        // And the guard still bites: synthesising the metadata service is
1623        // exactly the attack, and one such answer rejects the whole set.
1624        let hostile: SocketAddr = "[64:ff9b::a9fe:a9fe]:80".parse().unwrap();
1625        assert!(
1626            first_vetted("evil.example", [public_v4, hostile].into_iter()).is_err(),
1627            "a NAT64-synthesised metadata address was accepted",
1628        );
1629        assert!(first_vetted("evil.example", [hostile].into_iter()).is_err());
1630    }
1631
1632    /// **The ISATAP marker is read loosely ON PURPOSE, and this is the test that
1633    /// says so.**
1634    ///
1635    /// RFC 5214 spells the interface identifier `000000ug 00000000 0x5E 0xFE` +
1636    /// the IPv4, so a spec-exact test would also require the six reserved bits
1637    /// of `seg[4]` to be zero and would ALLOW the address below. `embedded_v4`
1638    /// tests only for `0x5efe` in group 5, so it refuses it.
1639    ///
1640    /// That is a deliberate over-refusal, and without this test it was a
1641    /// comment and nothing else: restoring the spec-exact mask
1642    /// (`seg[4] & !0x0300 == 0`) passed all 960 tests. The asymmetry is the
1643    /// argument — reading the marker loosely costs a false positive only if a
1644    /// non-ISATAP interface identifier carries IANA's own `00-00-5E` OUI *and*
1645    /// its low 32 bits decode to an internal address, while reading it strictly
1646    /// costs a total bypass if any tunnel driver is more lenient than the RFC.
1647    ///
1648    /// So if a future change tightens this arm toward the spec, that is a
1649    /// decision to take deliberately, by deleting this test and saying why —
1650    /// not something to discover from a bypass.
1651    #[test]
1652    fn a_reserved_bit_in_the_isatap_identifier_does_not_buy_a_bypass() {
1653        let ip: IpAddr = "2606:4700::400:5efe:7f00:1".parse().unwrap();
1654        assert!(
1655            is_forbidden_ip(&ip),
1656            "an identifier carrying 00-00-5E-FE and 127.0.0.1 was allowed \
1657             because a reserved bit was set",
1658        );
1659    }
1660
1661    /// **The ISATAP test is on the interface identifier, so it matches under any
1662    /// prefix — including prefixes that belong to one of the other four.**
1663    ///
1664    /// A Teredo address with zero flags whose obfuscated port happens to be
1665    /// `0x5efe` matches the ISATAP pattern too, and the two readings disagree:
1666    /// Teredo stores the client address complemented, so the ISATAP reading of
1667    /// the same bits is its bitwise inverse. Here the Teredo reading is server
1668    /// 8.8.8.8 and client 128.255.255.254 — both public, so the address is
1669    /// legitimate — while the ISATAP reading of those low 32 bits is 127.0.0.1.
1670    ///
1671    /// Teredo is the one arm that still RETURNS rather than accumulating, which
1672    /// suppresses the ISATAP reading of bits Teredo has already claimed.
1673    /// `2001:0000::/32` is IANA-assigned Teredo space, a real ISATAP host would
1674    /// not be using it, and refusing this would be a false positive on an
1675    /// address whose traffic goes to a Teredo relay rather than to loopback.
1676    ///
1677    /// Making the Teredo arm accumulate like the others — i.e. letting the
1678    /// ISATAP arm also read groups 6-7 here — fails this test. That is the
1679    /// whole difference between this case and the 6to4 one: there the two
1680    /// families read disjoint bits and both readings hold, here they read the
1681    /// same field and contradict each other.
1682    #[test]
1683    fn a_teredo_address_is_read_as_teredo_not_as_isatap() {
1684        let ip: IpAddr = "2001:0:808:808:0:5efe:7f00:1".parse().unwrap();
1685        assert!(
1686            !is_forbidden_ip(&ip),
1687            "an address in Teredo space was read as ISATAP and wrongly refused",
1688        );
1689    }
1690
1691    /// **The embedded-IPv4 arm may only ADD refusals, never grant permission.**
1692    ///
1693    /// It is checked before the link-local and ULA rules, so if it returned a
1694    /// verdict rather than falling through, an ISATAP address wrapping a PUBLIC
1695    /// IPv4 under an `fe80::/10` prefix would come back allowed — a link-local
1696    /// address let through because the thing it embeds happens to be fine.
1697    ///
1698    /// Changing `if embedded_v4(..).any(..) { return true; }` to return the
1699    /// condition fails this test — and also `forbids_internal_v6` and
1700    /// `every_blocklist_branch_is_load_bearing`, which were already standing
1701    /// guard over the fall-through in general. So this case is a NAMED
1702    /// regression for the ISATAP interaction rather than the only thing holding
1703    /// the property down; it is measured, not assumed, and stated that way
1704    /// because a test whose comment claims more than it catches is the defect
1705    /// this file keeps finding.
1706    #[test]
1707    fn a_link_local_isatap_address_is_still_refused_for_being_link_local() {
1708        let ip: IpAddr = "fe80::5efe:808:808".parse().unwrap();
1709        assert!(
1710            is_forbidden_ip(&ip),
1711            "fe80::/10 wrapping a public IPv4 escaped the link-local rule",
1712        );
1713    }
1714
1715    #[test]
1716    fn allows_public_v6() {
1717        let ip: IpAddr = "2606:4700:4700::1111".parse().unwrap();
1718        assert!(!is_forbidden_ip(&ip));
1719    }
1720
1721    #[tokio::test]
1722    async fn resolve_and_check_rejects_ip_literals() {
1723        for bad in [
1724            "http://127.0.0.1/feed.xml",
1725            "http://169.254.169.254/latest/meta-data/",
1726            "http://[::1]:80/x",
1727            "http://192.168.0.1/",
1728        ] {
1729            let u = Url::parse(bad).unwrap();
1730            assert!(
1731                resolve_and_check(&u).await.is_err(),
1732                "{bad} should be rejected"
1733            );
1734        }
1735    }
1736
1737    #[tokio::test]
1738    async fn resolve_and_check_allows_public_ip_literal() {
1739        let u = Url::parse("http://1.1.1.1/").unwrap();
1740        let addr = resolve_and_check(&u).await.unwrap();
1741        // The vetted address is pinned back verbatim (IP literal, no DNS).
1742        assert_eq!(addr, "1.1.1.1:80".parse::<SocketAddr>().unwrap());
1743    }
1744
1745    #[tokio::test]
1746    async fn resolve_and_check_pins_public_ipv6_literal() {
1747        let u = Url::parse("http://[2606:4700:4700::1111]:443/").unwrap();
1748        let addr = resolve_and_check(&u).await.unwrap();
1749        assert_eq!(
1750            addr,
1751            "[2606:4700:4700::1111]:443".parse::<SocketAddr>().unwrap()
1752        );
1753    }
1754
1755    // ── the pinned-client cache ──────────────────────────────────────────────
1756
1757    const V4: &str = "93.184.216.34:443";
1758    const V4_OTHER: &str = "93.184.216.35:443";
1759
1760    fn at(base: Instant, secs: u64) -> Instant {
1761        base + Duration::from_secs(secs)
1762    }
1763
1764    /// A repeat request to the same vetted address REUSES the client, so the
1765    /// connection pool survives and the TLS handshake is paid once.
1766    ///
1767    /// Measured motivation: a fresh connection to this project's PDS costs 91 ms
1768    /// against 30 ms warm, which was most of the ~3x gap between the Rust repo
1769    /// backend and the Node sidecar.
1770    #[test]
1771    fn the_same_vetted_address_reuses_one_client() {
1772        let cache = PinnedClients::new();
1773        let now = Instant::now();
1774        let addr: SocketAddr = V4.parse().unwrap();
1775
1776        for i in 0..5 {
1777            cache.get("example.com", addr, at(now, i)).unwrap();
1778        }
1779        assert_eq!(
1780            cache.builds.load(Ordering::Relaxed),
1781            1,
1782            "each request rebuilt the client, so every call pays a TLS handshake"
1783        );
1784    }
1785
1786    /// **A CHANGED ADDRESS MUST NOT REUSE THE POOL.**
1787    ///
1788    /// This is the property that makes the cache safe. The DNS-rebinding defence
1789    /// is that we connect only to an address vetted for THIS request; a cache
1790    /// keyed on the host alone would hand back a connection pinned to an address
1791    /// vetted minutes ago, quietly undoing it. The key includes the address, so
1792    /// a move is a miss.
1793    #[test]
1794    fn a_changed_address_does_not_reuse_the_pooled_client() {
1795        let cache = PinnedClients::new();
1796        let now = Instant::now();
1797
1798        cache.get("example.com", V4.parse().unwrap(), now).unwrap();
1799        cache
1800            .get("example.com", V4_OTHER.parse().unwrap(), at(now, 1))
1801            .unwrap();
1802
1803        assert_eq!(
1804            cache.builds.load(Ordering::Relaxed),
1805            2,
1806            "the same host at a DIFFERENT address reused a connection pinned to the old one"
1807        );
1808        assert_eq!(cache.entries.lock().unwrap().len(), 2);
1809    }
1810
1811    /// Two hosts that happen to resolve to the same address still get their own
1812    /// clients — the pin is per host, and SNI/Host differ.
1813    #[test]
1814    fn different_hosts_at_one_address_are_separate_clients() {
1815        let cache = PinnedClients::new();
1816        let now = Instant::now();
1817        let addr: SocketAddr = V4.parse().unwrap();
1818
1819        cache.get("a.example.com", addr, now).unwrap();
1820        cache.get("b.example.com", addr, now).unwrap();
1821        assert_eq!(cache.builds.load(Ordering::Relaxed), 2);
1822    }
1823
1824    /// An entry idle past the TTL is rebuilt, bounding how long a pooled
1825    /// connection to a once-vetted address can live.
1826    #[test]
1827    fn an_idle_entry_is_rebuilt_after_the_ttl() {
1828        let cache = PinnedClients::new();
1829        let now = Instant::now();
1830        let addr: SocketAddr = V4.parse().unwrap();
1831
1832        cache.get("example.com", addr, now).unwrap();
1833        cache
1834            .get(
1835                "example.com",
1836                addr,
1837                now + PINNED_CLIENT_TTL + Duration::from_secs(1),
1838            )
1839            .unwrap();
1840        assert_eq!(cache.builds.load(Ordering::Relaxed), 2);
1841    }
1842
1843    /// Use keeps an entry alive: a client fetched every minute must not be
1844    /// rebuilt just because it was first created more than a TTL ago. The TTL is
1845    /// idle time, not total age — otherwise the busiest client in the process
1846    /// would be the one thrown away on a schedule.
1847    #[test]
1848    fn continued_use_keeps_an_entry_alive() {
1849        let cache = PinnedClients::new();
1850        let now = Instant::now();
1851        let addr: SocketAddr = V4.parse().unwrap();
1852
1853        for minute in 0..20 {
1854            cache
1855                .get("example.com", addr, at(now, minute * 60))
1856                .unwrap();
1857        }
1858        assert_eq!(
1859            cache.builds.load(Ordering::Relaxed),
1860            1,
1861            "a continuously-used client was expired by age rather than idleness"
1862        );
1863    }
1864
1865    /// A client must release its idle sockets BEFORE the cache releases the
1866    /// client. The other way round, every entry spends the tail of its life
1867    /// holding connections nothing will reuse — which is the whole cost the pool
1868    /// bound exists to avoid.
1869    #[test]
1870    fn idle_sockets_are_released_before_their_client_is() {
1871        assert!(
1872            POOL_IDLE_TIMEOUT < PINNED_CLIENT_TTL,
1873            "pool idle timeout {POOL_IDLE_TIMEOUT:?} is not shorter than the \
1874             client TTL {PINNED_CLIENT_TTL:?}"
1875        );
1876    }
1877
1878    /// The map is bounded. The poller talks to as many hosts as there are feeds,
1879    /// so an unbounded map would be a slow leak of connection pools.
1880    #[test]
1881    fn the_cache_is_bounded() {
1882        let cache = PinnedClients::new();
1883        let now = Instant::now();
1884        for i in 0..(MAX_PINNED_CLIENTS + 50) {
1885            let addr: SocketAddr = format!("93.184.216.34:{}", 1024 + i).parse().unwrap();
1886            cache.get(&format!("h{i}.example.com"), addr, now).unwrap();
1887        }
1888        assert!(
1889            cache.entries.lock().unwrap().len() <= MAX_PINNED_CLIENTS,
1890            "the cache grew past its bound"
1891        );
1892    }
1893
1894    #[test]
1895    fn pinned_client_builds_for_both_families() {
1896        // Both address families must produce a usable pinned client.
1897        assert!(pinned_client("example.com", "93.184.216.34:80".parse().unwrap()).is_ok());
1898        assert!(
1899            pinned_client("example.com", "[2606:4700:4700::1111]:443".parse().unwrap()).is_ok()
1900        );
1901    }
1902
1903    #[test]
1904    fn scheme_allowlist_rejects_non_http() {
1905        assert!(check_scheme(&Url::parse("http://example.com/").unwrap()).is_ok());
1906        assert!(check_scheme(&Url::parse("https://example.com/").unwrap()).is_ok());
1907        // url::Url::parse rejects `javascript:` as opaque, but file/ftp parse.
1908        assert!(check_scheme(&Url::parse("file:///etc/passwd").unwrap()).is_err());
1909        assert!(check_scheme(&Url::parse("ftp://example.com/").unwrap()).is_err());
1910    }
1911
1912    /// A raw HTTP server on loopback that answers every request with `body`
1913    /// (fixed Content-Length). Returns its `http://127.0.0.1:port/` base URL.
1914    /// Used to exercise [`read_capped`] against a real reqwest `Response`.
1915    /// A JSON server that records every raw request (head and body, read to
1916    /// `content-length`) and answers each with `reply`. For asserting on the
1917    /// BYTES a client sent — the only assertion that catches a record that is
1918    /// wrong on the way out.
1919    pub(crate) async fn serve_json_capturing(
1920        reply: Vec<u8>,
1921    ) -> (String, std::sync::Arc<std::sync::Mutex<Vec<String>>>) {
1922        use tokio::io::{AsyncReadExt, AsyncWriteExt};
1923        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1924        let addr = listener.local_addr().unwrap();
1925        let log = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
1926        let sink = std::sync::Arc::clone(&log);
1927        tokio::spawn(async move {
1928            loop {
1929                let Ok((mut sock, _)) = listener.accept().await else {
1930                    break;
1931                };
1932                let mut raw: Vec<u8> = Vec::new();
1933                let mut chunk = [0u8; 4096];
1934                let text = loop {
1935                    let Ok(n) = sock.read(&mut chunk).await else {
1936                        break String::new();
1937                    };
1938                    if n == 0 {
1939                        break String::from_utf8_lossy(&raw).to_string();
1940                    }
1941                    raw.extend_from_slice(&chunk[..n]);
1942                    let Some(split) = raw.windows(4).position(|w| w == b"\r\n\r\n") else {
1943                        continue;
1944                    };
1945                    let (head, body) = raw.split_at(split + 4);
1946                    let want = String::from_utf8_lossy(head).lines().find_map(|l| {
1947                        let (k, v) = l.split_once(':')?;
1948                        k.eq_ignore_ascii_case("content-length")
1949                            .then(|| v.trim().parse::<usize>().ok())?
1950                    });
1951                    if want.is_none_or(|w| body.len() >= w) {
1952                        break String::from_utf8_lossy(&raw).to_string();
1953                    }
1954                };
1955                sink.lock().unwrap().push(text);
1956                let header = format!(
1957                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
1958                    reply.len()
1959                );
1960                let _ = sock.write_all(header.as_bytes()).await;
1961                let _ = sock.write_all(&reply).await;
1962                let _ = sock.flush().await;
1963            }
1964        });
1965        (format!("http://{addr}"), log)
1966    }
1967
1968    /// [`serve_body`] that also counts requests — for an assertion that a URL
1969    /// was NEVER fetched, which a body alone cannot make.
1970    pub(crate) async fn serve_body_counted(
1971        body: Vec<u8>,
1972    ) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
1973        use tokio::io::{AsyncReadExt, AsyncWriteExt};
1974        let hits = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
1975        let counter = std::sync::Arc::clone(&hits);
1976        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1977        let addr = listener.local_addr().unwrap();
1978        tokio::spawn(async move {
1979            loop {
1980                let Ok((mut sock, _)) = listener.accept().await else {
1981                    break;
1982                };
1983                counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1984                let body = body.clone();
1985                tokio::spawn(async move {
1986                    let mut buf = [0u8; 1024];
1987                    let _ = sock.read(&mut buf).await;
1988                    let header = format!(
1989                        "HTTP/1.1 200 OK\r\nContent-Type: application/rss+xml\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
1990                        body.len()
1991                    );
1992                    let _ = sock.write_all(header.as_bytes()).await;
1993                    let _ = sock.write_all(&body).await;
1994                    let _ = sock.flush().await;
1995                });
1996            }
1997        });
1998        (format!("http://{addr}/"), hits)
1999    }
2000
2001    /// Serve a different body per request, in order, repeating the last.
2002    ///
2003    /// **The fixed-body servers cannot test a walk.** `serve_body` answers every
2004    /// request identically, so a paging walk sees the same cursor twice and its
2005    /// repeat-detection guard stops it at two pages. Anything that only happens
2006    /// across pages — a budget accumulating, a cursor advancing — is therefore
2007    /// unreachable with them, which is how a cap that was per-page rather than
2008    /// per-walk once passed an entire suite.
2009    ///
2010    /// Each request is a fresh connection (`Connection: close`), so accept order
2011    /// is request order for the sequential walks that use this.
2012    pub(crate) async fn serve_bodies_in_sequence(bodies: Vec<Vec<u8>>) -> String {
2013        use tokio::io::{AsyncReadExt, AsyncWriteExt};
2014        assert!(!bodies.is_empty(), "serve_bodies_in_sequence needs a body");
2015        let bodies = std::sync::Arc::new(bodies);
2016        let next = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
2017        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
2018        let addr = listener.local_addr().unwrap();
2019        tokio::spawn(async move {
2020            loop {
2021                let Ok((mut sock, _)) = listener.accept().await else {
2022                    break;
2023                };
2024                let i = next.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2025                let body = bodies[i.min(bodies.len() - 1)].clone();
2026                tokio::spawn(async move {
2027                    // **Drain the whole request head, not one fixed read.** A
2028                    // DPoP-signed XRPC request head measures ~880 bytes, so a
2029                    // single 1024-byte read is within a longer NSID or cursor
2030                    // of leaving bytes unread — and closing with data still in
2031                    // the receive queue makes the kernel send RST instead of
2032                    // FIN, which can discard a response the client has not
2033                    // drained. That surfaces as an intermittent connection
2034                    // reset in a test whose failure would read as a budget bug.
2035                    let mut req = Vec::new();
2036                    let mut buf = [0u8; 1024];
2037                    // Drain the head, then the body it declares. Stopping at
2038                    // the head is not enough: the sidecar's list call is a POST,
2039                    // so on any platform that does not coalesce head and body
2040                    // into one segment the body stays in the receive queue, and
2041                    // closing on unread bytes is the RST-instead-of-FIN case
2042                    // this loop exists to avoid.
2043                    let mut want: Option<usize> = None;
2044                    loop {
2045                        match sock.read(&mut buf).await {
2046                            Ok(0) => break,
2047                            Ok(n) => {
2048                                req.extend_from_slice(&buf[..n]);
2049                                let Some(head_end) = req.windows(4).position(|w| w == b"\r\n\r\n")
2050                                else {
2051                                    continue;
2052                                };
2053                                let head_len = head_end + 4;
2054                                if want.is_none() {
2055                                    let head = String::from_utf8_lossy(&req[..head_len]);
2056                                    want = Some(
2057                                        head.lines()
2058                                            .find_map(|l| {
2059                                                let (k, v) = l.split_once(':')?;
2060                                                k.eq_ignore_ascii_case("content-length")
2061                                                    .then(|| v.trim().parse::<usize>().ok())?
2062                                            })
2063                                            .unwrap_or(0),
2064                                    );
2065                                }
2066                                if req.len() >= head_len + want.unwrap_or(0) {
2067                                    break;
2068                                }
2069                            }
2070                            Err(_) => break,
2071                        }
2072                    }
2073                    let header = format!(
2074                        "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
2075                        body.len()
2076                    );
2077                    let _ = sock.write_all(header.as_bytes()).await;
2078                    let _ = sock.write_all(&body).await;
2079                    let _ = sock.flush().await;
2080                });
2081            }
2082        });
2083        format!("http://{addr}/")
2084    }
2085
2086    pub(crate) async fn serve_body(body: Vec<u8>) -> String {
2087        use tokio::io::{AsyncReadExt, AsyncWriteExt};
2088        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
2089        let addr = listener.local_addr().unwrap();
2090        tokio::spawn(async move {
2091            loop {
2092                let (mut sock, _) = match listener.accept().await {
2093                    Ok(p) => p,
2094                    Err(_) => break,
2095                };
2096                let body = body.clone();
2097                tokio::spawn(async move {
2098                    // Drain the request headers (best-effort) then reply.
2099                    let mut buf = [0u8; 1024];
2100                    let _ = sock.read(&mut buf).await;
2101                    let header = format!(
2102                        "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
2103                        body.len()
2104                    );
2105                    let _ = sock.write_all(header.as_bytes()).await;
2106                    let _ = sock.write_all(&body).await;
2107                    let _ = sock.flush().await;
2108                });
2109            }
2110        });
2111        format!("http://{addr}/")
2112    }
2113
2114    #[tokio::test]
2115    async fn read_capped_rejects_over_cap_body() {
2116        // A body one byte over the cap must be rejected (and never fully
2117        // buffered past the cap). Fetch directly (bypassing the SSRF guard, which
2118        // rightly forbids loopback) to exercise read_capped on a real Response.
2119        let big = vec![b'x'; MAX_BODY_BYTES + 1];
2120        let base = serve_body(big).await;
2121        let client = reqwest::Client::builder().build().unwrap();
2122        let resp = client.get(&base).send().await.unwrap();
2123        let err = read_capped(resp).await.unwrap_err().to_string();
2124        assert!(err.contains("exceeded"), "unexpected error: {err}");
2125    }
2126
2127    #[tokio::test]
2128    async fn read_capped_accepts_small_body() {
2129        let base = serve_body(b"hello world".to_vec()).await;
2130        let client = reqwest::Client::builder().build().unwrap();
2131        let resp = client.get(&base).send().await.unwrap();
2132        let body = read_capped(resp).await.unwrap();
2133        assert_eq!(body, b"hello world");
2134    }
2135
2136    /// A raw HTTP server on loopback that answers `/final` with `200 arrived`
2137    /// and **everything else** with `302 Location: /final`. Returns its bound
2138    /// address, so a caller can pin a client to it by address rather than name.
2139    ///
2140    /// This is the fixture the two tests below need and that the module did not
2141    /// previously have. Note it returns the `SocketAddr`, not a URL: the whole
2142    /// point is to reach it under a hostname that does not resolve.
2143    pub(crate) async fn serve_redirect_to_final() -> SocketAddr {
2144        use tokio::io::{AsyncReadExt, AsyncWriteExt};
2145        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
2146        let addr = listener.local_addr().unwrap();
2147        tokio::spawn(async move {
2148            loop {
2149                let (mut sock, _) = match listener.accept().await {
2150                    Ok(p) => p,
2151                    Err(_) => break,
2152                };
2153                tokio::spawn(async move {
2154                    let mut buf = [0u8; 1024];
2155                    let n = sock.read(&mut buf).await.unwrap_or(0);
2156                    let req = String::from_utf8_lossy(&buf[..n]).to_string();
2157                    let resp = if req.starts_with("GET /final") {
2158                        "HTTP/1.1 200 OK\r\nContent-Length: 7\r\nConnection: close\r\n\r\narrived"
2159                    } else {
2160                        "HTTP/1.1 302 Found\r\nLocation: /final\r\nContent-Length: 0\r\n\
2161                         Connection: close\r\n\r\n"
2162                    };
2163                    let _ = sock.write_all(resp.as_bytes()).await;
2164                    let _ = sock.flush().await;
2165                });
2166            }
2167        });
2168        addr
2169    }
2170
2171    /// **The connect goes to the address the guard vetted — enforcement, not
2172    /// decision.**
2173    ///
2174    /// `resolve_and_check` vets an address and `build_pinned_client` then
2175    /// `.resolve()`s the host to exactly that address, so the TCP connect cannot
2176    /// be rebound onto an internal one in the window between the two. That is
2177    /// the DNS-rebinding defence the module doc spends 25 lines on.
2178    ///
2179    /// **Nothing observed it.** Deleting `.resolve(host, addr)` left all 659
2180    /// tests green, because every other test either passes an IP literal — where
2181    /// a second resolution is a no-op — or asserts on `is_forbidden_ip`
2182    /// directly. `is_forbidden_ip` is thoroughly tested; what carries its verdict
2183    /// to the socket was not tested at all.
2184    ///
2185    /// This pins it in the one way that cannot silently stop discriminating: the
2186    /// host **resolves nowhere**. `.invalid` is reserved by RFC 2606 and is
2187    /// guaranteed never to exist, so the only route to the stub is the pin. Drop
2188    /// `.resolve()` and the client falls back to real DNS and cannot connect —
2189    /// which is also why this test needs no network.
2190    #[tokio::test]
2191    async fn the_connect_is_pinned_to_the_vetted_address() {
2192        let addr = serve_redirect_to_final().await;
2193        let host = "pinned-target.invalid";
2194        let client = pinned_client(host, addr).expect("building a pinned client");
2195
2196        let resp = client
2197            .get(format!("http://{host}:{}/final", addr.port()))
2198            .send()
2199            .await
2200            .expect(
2201                "a pinned host must reach the vetted address without consulting DNS — \
2202                 if this failed to connect, the `.resolve()` pin is gone",
2203            );
2204        assert_eq!(resp.status(), 200);
2205        assert_eq!(resp.text().await.unwrap(), "arrived");
2206    }
2207
2208    /// **The per-hop client must not follow redirects on its own.**
2209    ///
2210    /// `guarded_get_inner` follows redirects *manually* so it can re-run the
2211    /// scheme check, the privacy check and `resolve_and_check` on every hop, and
2212    /// so it can strip credential headers when a hop leaves the original origin.
2213    /// All of that is bypassed if reqwest follows the redirect internally: the
2214    /// connect to hop 2 happens inside reqwest, against an address nothing
2215    /// vetted. For `guarded_post` it is worse still — reqwest would re-send a
2216    /// `307`'s BODY (a client assertion, an auth code) to the new origin before
2217    /// `guarded_post`'s own 3xx refusal ever ran.
2218    ///
2219    /// Flipping `Policy::none()` to `Policy::limited(10)` left all 659 tests
2220    /// green. The existing redirect test could not catch it: it builds a 302 stub
2221    /// and then discards the address with `let _ = addr`, because the guard
2222    /// forbids loopback and the stub was therefore unreachable *through* the
2223    /// guard. It asserts on a private URL passed directly in, so no redirect ever
2224    /// occurs in it.
2225    ///
2226    /// Pinning by address sidesteps that — `pinned_client` does not consult the
2227    /// guard, so the stub is reachable — and the assertion is on the status the
2228    /// caller receives: `302`, handed back for the loop to re-validate, not the
2229    /// `200` that reqwest would return after quietly following it.
2230    #[tokio::test]
2231    async fn the_pinned_client_does_not_follow_redirects_itself() {
2232        let addr = serve_redirect_to_final().await;
2233        let host = "redirector.invalid";
2234        let client = pinned_client(host, addr).expect("building a pinned client");
2235
2236        let resp = client
2237            .get(format!("http://{host}:{}/start", addr.port()))
2238            .send()
2239            .await
2240            .expect("the stub must answer the first hop");
2241
2242        assert_eq!(
2243            resp.status(),
2244            302,
2245            "the per-hop client must hand the 30x BACK to guarded_get_inner for \
2246             re-validation; a 200 here means reqwest followed it internally and the \
2247             second hop was connected to without passing resolve_and_check",
2248        );
2249        assert_eq!(
2250            resp.headers()
2251                .get(reqwest::header::LOCATION)
2252                .and_then(|v| v.to_str().ok()),
2253            Some("/final"),
2254            "the Location must reach the caller — it is what the next hop re-validates",
2255        );
2256    }
2257
2258    /// **Every branch of the v4/v6 blocklist is load-bearing.**
2259    ///
2260    /// Four branches were unreachable from the existing tests: `is_multicast()`
2261    /// on both families, `192.0.0.0/24` ("this host on this network", IETF
2262    /// protocol assignments) and `198.18.0.0/15` (benchmarking). Deleting all
2263    /// four at once left the suite green, so a quarter of the blocklist could
2264    /// have been dropped in a refactor without a single failure.
2265    ///
2266    /// These are not decorative: multicast to an internal group and the
2267    /// benchmarking range are both reachable on a real network and neither can
2268    /// host a legitimate public feed.
2269    #[test]
2270    fn every_blocklist_branch_is_load_bearing() {
2271        for ip in [
2272            "224.0.0.1",       // v4 multicast, all-systems group
2273            "239.255.255.250", // v4 multicast, SSDP — a real LAN discovery target
2274            "192.0.0.1",       // 192.0.0.0/24, IETF protocol assignments
2275            "192.0.0.171",     // same /24
2276            "198.18.0.1",      // 198.18/15 benchmarking
2277            "198.19.255.255",  // top of the benchmarking range
2278            "0.0.0.0",         // unspecified
2279            "0.1.2.3",         // rest of 0/8
2280            "255.255.255.255", // broadcast
2281            "100.64.0.1",      // CGNAT floor
2282            "100.127.255.255", // CGNAT ceiling
2283        ] {
2284            let parsed: IpAddr = ip.parse().unwrap();
2285            assert!(is_forbidden_ip(&parsed), "{ip} must be forbidden");
2286        }
2287        for ip in [
2288            "ff02::1",                // v6 multicast, all-nodes
2289            "::1",                    // v6 loopback
2290            "::",                     // v6 unspecified
2291            "fe80::1",                // v6 link-local
2292            "fc00::1",                // v6 ULA
2293            "fd00::1",                // v6 ULA
2294            "::ffff:127.0.0.1",       // v4-mapped loopback
2295            "::ffff:169.254.169.254", // v4-mapped cloud metadata
2296            "::ffff:10.0.0.1",        // v4-mapped RFC1918
2297        ] {
2298            let parsed: IpAddr = ip.parse().unwrap();
2299            assert!(is_forbidden_ip(&parsed), "{ip} must be forbidden");
2300        }
2301    }
2302
2303    /// **The blocklist must not over-block, and only boundaries can show that.**
2304    ///
2305    /// A guard that refuses everything passes every all-negative test, and the
2306    /// existing positive cases (`1.1.1.1`, `8.8.8.8`, `93.184.216.34`) sit
2307    /// nowhere near a blocked range, so none of them would notice. Widening
2308    /// `172.16/12` to all of `172/8` and `100.64/10` to all of `100/8` — which
2309    /// would silently refuse Google and AWS address space — left the suite green.
2310    ///
2311    /// Each address here is the one immediately OUTSIDE a blocked range, so an
2312    /// off-by-one in any CIDR boundary fails this test and nothing else.
2313    #[test]
2314    fn the_blocklist_does_not_over_block_adjacent_public_space() {
2315        for ip in [
2316            "9.255.255.255",   // just below 10/8
2317            "11.0.0.0",        // just above 10/8
2318            "172.15.255.255",  // just below 172.16/12
2319            "172.32.0.0",      // just above 172.16/12 (172.217.x is Google)
2320            "192.167.255.255", // just below 192.168/16
2321            "192.169.0.0",     // just above 192.168/16
2322            "169.253.255.255", // just below 169.254/16
2323            "169.255.0.0",     // just above 169.254/16
2324            "126.255.255.255", // just below 127/8
2325            "128.0.0.0",       // just above 127/8
2326            "100.63.255.255",  // just below 100.64/10 CGNAT
2327            "100.128.0.0",     // just above 100.64/10 (100.20.x is AWS)
2328            "192.0.1.0",       // just above 192.0.0.0/24
2329            "198.17.255.255",  // just below 198.18/15
2330            "198.20.0.0",      // just above 198.18/15
2331            "223.255.255.255", // just below 224/4 multicast
2332            "1.0.0.0",         // just above 0/8
2333        ] {
2334            let parsed: IpAddr = ip.parse().unwrap();
2335            assert!(
2336                !is_forbidden_ip(&parsed),
2337                "{ip} is public and adjacent to a blocked range — refusing it means a \
2338                 CIDR boundary is wrong and real feeds are unreachable",
2339            );
2340        }
2341        for ip in ["2606:4700:4700::1111", "2001:4860:4860::8888"] {
2342            let parsed: IpAddr = ip.parse().unwrap();
2343            assert!(
2344                !is_forbidden_ip(&parsed),
2345                "{ip} is public and must be allowed"
2346            );
2347        }
2348    }
2349
2350    /// **Reserved and documentation ranges no public feed can live in (#217).**
2351    ///
2352    /// Each range is pinned at its first, a middle and its last address, so a
2353    /// rule that is missing, or narrower than its CIDR, fails here. The
2354    /// neighbours just outside are in
2355    /// `the_reserved_ranges_stop_at_their_boundaries`.
2356    #[test]
2357    fn forbids_reserved_and_documentation_ranges() {
2358        for (ip, what) in [
2359            // 240.0.0.0/4, reserved (RFC 1112 §4). `is_broadcast()` only ever
2360            // covered the top address of it.
2361            ("240.0.0.0", "240/4 reserved, first"),
2362            ("247.255.0.1", "240/4 reserved, middle"),
2363            ("255.255.255.254", "240/4 reserved, last below broadcast"),
2364            ("255.255.255.255", "240/4 reserved, limited broadcast"),
2365            // RFC 5737 documentation ranges.
2366            ("192.0.2.0", "TEST-NET-1, first"),
2367            ("192.0.2.128", "TEST-NET-1, middle"),
2368            ("192.0.2.255", "TEST-NET-1, last"),
2369            ("198.51.100.0", "TEST-NET-2, first"),
2370            ("198.51.100.128", "TEST-NET-2, middle"),
2371            ("198.51.100.255", "TEST-NET-2, last"),
2372            ("203.0.113.0", "TEST-NET-3, first"),
2373            ("203.0.113.128", "TEST-NET-3, middle"),
2374            ("203.0.113.255", "TEST-NET-3, last"),
2375            // fec0::/10, deprecated site-local (RFC 3879).
2376            ("fec0::", "site-local, first"),
2377            ("fee0::1", "site-local, middle"),
2378            (
2379                "feff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
2380                "site-local, last",
2381            ),
2382            // 100::/64, discard-only (RFC 6666).
2383            ("100::", "discard-only, first"),
2384            ("100::8000:0:0:0", "discard-only, middle"),
2385            ("100::ffff:ffff:ffff:ffff", "discard-only, last"),
2386            // 2001:db8::/32, documentation (RFC 3849).
2387            ("2001:db8::", "IPv6 documentation, first"),
2388            ("2001:db8:8000::1", "IPv6 documentation, middle"),
2389            (
2390                "2001:db8:ffff:ffff:ffff:ffff:ffff:ffff",
2391                "IPv6 documentation, last",
2392            ),
2393        ] {
2394            let parsed: IpAddr = ip.parse().unwrap();
2395            assert!(is_forbidden_ip(&parsed), "{ip} is {what} and was allowed");
2396        }
2397    }
2398
2399    /// The other side of each boundary in `forbids_reserved_and_documentation_ranges`.
2400    ///
2401    /// Most of these are allowed, and an off-by-one or an over-wide mask fails
2402    /// on them. Three are not, because the range's neighbour is already refused
2403    /// by an older rule; they are asserted anyway, with the rule named, so that
2404    /// the new lines cannot quietly take over or drop what the old ones did.
2405    /// `240/4` has no upper neighbour and `fec0::/10` has none that is allowed:
2406    /// `fe80::/10` sits below it and `ff00::/8` above.
2407    #[test]
2408    fn the_reserved_ranges_stop_at_their_boundaries() {
2409        for ip in [
2410            "192.0.1.255",                            // below TEST-NET-1
2411            "192.0.3.0",                              // above TEST-NET-1
2412            "198.51.99.255",                          // below TEST-NET-2
2413            "198.51.101.0",                           // above TEST-NET-2
2414            "203.0.112.255",                          // below TEST-NET-3
2415            "203.0.114.0",                            // above TEST-NET-3
2416            "ff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",  // below 100::/64
2417            "100:0:0:1::",                            // above 100::/64
2418            "2001:db7:ffff:ffff:ffff:ffff:ffff:ffff", // below 2001:db8::/32
2419            "2001:db9::",                             // above 2001:db8::/32
2420        ] {
2421            let parsed: IpAddr = ip.parse().unwrap();
2422            assert!(
2423                !is_forbidden_ip(&parsed),
2424                "{ip} is just outside a reserved range and was refused — a \
2425                 boundary is wrong",
2426            );
2427        }
2428        for (ip, rule) in [
2429            ("239.255.255.255", "multicast, 224.0.0.0/4"),
2430            (
2431                "febf:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
2432                "link-local, fe80::/10",
2433            ),
2434            ("ff00::", "multicast, ff00::/8"),
2435        ] {
2436            let parsed: IpAddr = ip.parse().unwrap();
2437            assert!(is_forbidden_ip(&parsed), "{ip} must stay refused as {rule}");
2438        }
2439    }
2440
2441    /// **Every new IPv4 range is refused through every IPv6 wrapping the guard
2442    /// unwraps (#217 on top of #210).** That holds because `is_forbidden_v6`
2443    /// sends both the `to_ipv4()` result and every [`embedded_v4`] candidate
2444    /// through the one `is_forbidden_v4`. This test is what keeps that true if
2445    /// someone gives either path its own list.
2446    ///
2447    /// Teredo keeps the OTHER field at 8.8.8.8, so each case fails for the
2448    /// field its label names. The neighbours of the ranges, wrapped the same
2449    /// way, stay allowed.
2450    #[test]
2451    fn the_reserved_ipv4_ranges_are_refused_inside_ipv6() {
2452        fn wrappings(v4: Ipv4Addr) -> Vec<(&'static str, Ipv6Addr)> {
2453            let [a, b, c, d] = v4.octets();
2454            let hi = u16::from_be_bytes([a, b]);
2455            let lo = u16::from_be_bytes([c, d]);
2456            vec![
2457                ("mapped", v4.to_ipv6_mapped()),
2458                ("compatible", v4.to_ipv6_compatible()),
2459                ("NAT64", Ipv6Addr::new(0x64, 0xff9b, 0, 0, 0, 0, hi, lo)),
2460                ("6to4", Ipv6Addr::new(0x2002, hi, lo, 0, 0, 0, 0, 0)),
2461                ("translated", Ipv6Addr::new(0, 0, 0, 0, 0xffff, 0, hi, lo)),
2462                (
2463                    "Teredo server",
2464                    Ipv6Addr::new(0x2001, 0, hi, lo, 0, 0, 0xf7f7, 0xf7f7),
2465                ),
2466                (
2467                    "Teredo client",
2468                    Ipv6Addr::new(0x2001, 0, 0x0808, 0x0808, 0, 0, !hi, !lo),
2469                ),
2470                (
2471                    "ISATAP",
2472                    Ipv6Addr::new(0x2606, 0x4700, 0, 0, 0, 0x5efe, hi, lo),
2473                ),
2474            ]
2475        }
2476        for v4 in [
2477            "240.0.0.0",
2478            "247.255.0.1",
2479            "255.255.255.254",
2480            "192.0.2.0",
2481            "192.0.2.255",
2482            "198.51.100.0",
2483            "198.51.100.255",
2484            "203.0.113.0",
2485            "203.0.113.255",
2486        ] {
2487            for (form, v6) in wrappings(v4.parse().unwrap()) {
2488                assert!(
2489                    is_forbidden_ip(&IpAddr::V6(v6)),
2490                    "{v6} ({form} of {v4}) was allowed",
2491                );
2492            }
2493        }
2494        for v4 in ["192.0.3.0", "198.51.99.255", "203.0.114.0"] {
2495            for (form, v6) in wrappings(v4.parse().unwrap()) {
2496                assert!(
2497                    !is_forbidden_ip(&IpAddr::V6(v6)),
2498                    "{v6} ({form} of public {v4}) was refused",
2499                );
2500            }
2501        }
2502    }
2503
2504    /// **Regression (v0.2.8):** the write-side guard must refuse the same targets
2505    /// the read-side one does — loopback, cloud metadata, RFC1918, ULA — *before*
2506    /// the connect, so a rebound PDS host never receives a request body carrying
2507    /// an app password or a session bearer.
2508    ///
2509    /// (The companion rule — a `307`/`308` is refused rather than followed,
2510    /// because a redirect re-sends the BODY and reqwest only sanitises headers —
2511    /// is not exercised here for the same reason `read_capped`'s stub is fetched
2512    /// unguarded: the guard forbids loopback, so a local stub server can never be
2513    /// reached through it. It is enforced by construction in `guarded_post_json`.)
2514    #[tokio::test]
2515    async fn guarded_post_refuses_internal_targets() {
2516        let client = Client::builder().build().unwrap();
2517        for url in [
2518            "http://127.0.0.1:9/xrpc/com.atproto.server.createSession",
2519            "http://169.254.169.254/latest/meta-data/",
2520            "http://10.0.0.5/xrpc/com.atproto.repo.applyWrites",
2521            "http://[::1]/xrpc/com.atproto.repo.deleteRecord",
2522        ] {
2523            let err = guarded_post_json(&client, url, &[], b"{}".to_vec())
2524                .await
2525                .unwrap_err()
2526                .to_string();
2527            assert!(
2528                err.contains("forbidden") || err.contains("internal"),
2529                "{url}: expected an SSRF refusal, got: {err}"
2530            );
2531        }
2532    }
2533
2534    /// A non-http(s) scheme is refused on the write path too.
2535    #[tokio::test]
2536    async fn guarded_post_refuses_bad_schemes() {
2537        let client = Client::builder().build().unwrap();
2538        for url in ["file:///etc/passwd", "gopher://example.com/1"] {
2539            let err = guarded_post_json(&client, url, &[], b"{}".to_vec())
2540                .await
2541                .unwrap_err()
2542                .to_string();
2543            assert!(err.contains("scheme"), "{url}: got: {err}");
2544        }
2545    }
2546
2547    /// **A public first hop that `30x`es to a private, secret-bearing feed is
2548    /// refused BEFORE the private target is fetched** — the per-hop privacy
2549    /// re-check in [`guarded_get`].
2550    ///
2551    /// The previous version of this test spawned a redirecting server and then
2552    /// threw it away (`let _ = addr;`), asserting on the private URL passed in
2553    /// directly — so it exercised the FIRST-hop check only, and a mutation that
2554    /// skipped privacy on every later hop left the whole suite green. Now a
2555    /// real server really redirects, and the assertion that matters is on the
2556    /// private target's request log: **zero**. "Never fetched" is the half of
2557    /// the public-feeds-only guarantee this check exists for.
2558    #[tokio::test]
2559    async fn a_redirect_to_a_private_feed_is_refused_before_it_is_fetched() {
2560        let (target_addr, target_log) = spawn_http(vec![ok_200()]).await;
2561        test_host_override("private-target.test", target_addr);
2562        let (hop_addr, hop_log) = spawn_http(vec![redirect_to(&format!(
2563            "http://private-target.test:{}/feed/private/deadbeefcafe1234",
2564            target_addr.port()
2565        ))])
2566        .await;
2567        test_host_override("private-hop.test", hop_addr);
2568
2569        let err = guarded_get(
2570            &reqwest::Client::builder().build().unwrap(),
2571            &format!("http://private-hop.test:{}/feed.xml", hop_addr.port()),
2572            &[],
2573        )
2574        .await
2575        .expect_err("a redirect to a private feed was followed");
2576        let rendered = format!("{err:#}");
2577        assert!(
2578            rendered.contains("private/paid feed URL (redirect target)"),
2579            "refused for the wrong reason: {rendered}"
2580        );
2581        assert_eq!(
2582            hop_log.lock().unwrap().len(),
2583            1,
2584            "the public first hop is fetched"
2585        );
2586        assert_eq!(
2587            target_log.lock().unwrap().len(),
2588            0,
2589            "the private target was FETCHED before being refused"
2590        );
2591    }
2592
2593    /// Header names/values for the hop-header tests: one credential, one benign
2594    /// conditional-GET validator.
2595    fn hop_fixture() -> Vec<(HeaderName, HeaderValue)> {
2596        vec![
2597            (AUTHORIZATION, HeaderValue::from_static("Bearer secret")),
2598            (
2599                reqwest::header::IF_NONE_MATCH,
2600                HeaderValue::from_static("\"etag\""),
2601            ),
2602        ]
2603    }
2604
2605    #[test]
2606    fn sensitive_header_set() {
2607        assert!(is_sensitive_header(&AUTHORIZATION));
2608        assert!(is_sensitive_header(&COOKIE));
2609        assert!(is_sensitive_header(&PROXY_AUTHORIZATION));
2610        assert!(is_sensitive_header(&WWW_AUTHENTICATE));
2611        assert!(is_sensitive_header(&HeaderName::from_static("cookie2")));
2612        assert!(!is_sensitive_header(&reqwest::header::IF_NONE_MATCH));
2613        assert!(!is_sensitive_header(&reqwest::header::IF_MODIFIED_SINCE));
2614        assert!(!is_sensitive_header(&reqwest::header::ACCEPT));
2615    }
2616
2617    #[test]
2618    fn hop_headers_keeps_all_on_same_origin() {
2619        let extra = hop_fixture();
2620        let original = Url::parse("https://pds.example.com/xrpc/x").unwrap();
2621        // The very first hop (identical URL) keeps everything…
2622        assert_eq!(hop_headers(&original, &original, &extra).len(), 2);
2623        // …and so does a same-origin path change (a `302 /a → /b` on one host).
2624        let same = Url::parse("https://pds.example.com/other/path?q=1").unwrap();
2625        assert_eq!(hop_headers(&original, &same, &extra).len(), 2);
2626    }
2627
2628    #[test]
2629    fn hop_headers_strips_authorization_cross_host() {
2630        let extra = hop_fixture();
2631        let original = Url::parse("https://pds.example.com/x").unwrap();
2632        let evil = Url::parse("https://evil.example.net/y").unwrap();
2633        let kept = hop_headers(&original, &evil, &extra);
2634        assert_eq!(kept.len(), 1, "the bearer must not follow a cross-host 302");
2635        assert_eq!(kept[0].0, reqwest::header::IF_NONE_MATCH);
2636    }
2637
2638    #[test]
2639    fn hop_headers_strips_on_port_and_scheme_change() {
2640        let extra = hop_fixture();
2641        let original = Url::parse("https://a.example/x").unwrap();
2642        for downgraded in ["http://a.example/x", "https://a.example:8443/x"] {
2643            let current = Url::parse(downgraded).unwrap();
2644            let kept = hop_headers(&original, &current, &extra);
2645            assert_eq!(kept.len(), 1, "{downgraded} must drop the credential");
2646            assert_eq!(kept[0].0, reqwest::header::IF_NONE_MATCH);
2647        }
2648        // The default port spelled explicitly is still the same origin.
2649        let explicit = Url::parse("https://a.example:443/x").unwrap();
2650        assert_eq!(hop_headers(&original, &explicit, &extra).len(), 2);
2651    }
2652
2653    #[test]
2654    fn safe_link_allowlist() {
2655        assert_eq!(
2656            safe_link("https://ok.example/x").as_deref(),
2657            Some("https://ok.example/x")
2658        );
2659        assert_eq!(
2660            safe_link("  http://ok.example/  ").as_deref(),
2661            Some("http://ok.example/")
2662        );
2663        assert_eq!(safe_link("javascript:alert(document.domain)"), None);
2664        assert_eq!(safe_link("data:text/html,<script>alert(1)</script>"), None);
2665        assert_eq!(safe_link(""), None);
2666        assert_eq!(safe_link("   "), None);
2667        // A relative/naked path isn't an absolute http(s) URL → dropped.
2668        assert_eq!(safe_link("/relative/path"), None);
2669    }
2670
2671    /// The OAuth token/PAR calls are form POSTs carrying a client assertion and,
2672    /// on the token call, the authorization code. They must go through the SAME
2673    /// SSRF guard as everything else: a PDS or issuer URL that resolves to
2674    /// loopback/RFC1918 has to fail closed BEFORE the credential is sent.
2675    #[tokio::test]
2676    async fn guarded_post_form_fails_closed_on_a_forbidden_target() {
2677        let client = Client::new();
2678        for url in [
2679            "http://127.0.0.1:2583/oauth/token",
2680            "http://[::1]:2583/oauth/token",
2681            "http://169.254.169.254/latest/meta-data/",
2682            "http://10.0.0.5/oauth/token",
2683        ] {
2684            let err = guarded_post_form(&client, url, &[], &[("grant_type", "authorization_code")])
2685                .await
2686                .expect_err("must refuse {url}");
2687            let msg = err.to_string().to_lowercase();
2688            assert!(
2689                msg.contains("forbidden") || msg.contains("refus") || msg.contains("resolve"),
2690                "unexpected error for {url}: {err:#}"
2691            );
2692        }
2693    }
2694
2695    /// A non-http(s) scheme must be rejected before any DNS work.
2696    #[tokio::test]
2697    async fn guarded_post_form_rejects_non_http_schemes() {
2698        let client = Client::new();
2699        assert!(
2700            guarded_post_form(&client, "file:///etc/passwd", &[], &[("a", "b")])
2701                .await
2702                .is_err()
2703        );
2704    }
2705
2706    /// OAuth metadata and DID documents must be fetched WITHOUT following
2707    /// redirects, and still through the SSRF guard.
2708    /// Asserts on the GUARD's error, not merely `is_err()`. Connecting to
2709    /// `127.0.0.1` fails anyway (refused, or a slow timeout for an unrouted
2710    /// RFC1918 address), so an `is_err()`-only assertion passes with
2711    /// `resolve_and_check` deleted and proves nothing.
2712    #[tokio::test]
2713    async fn guarded_get_no_redirect_still_fails_closed_on_forbidden_targets() {
2714        let client = Client::new();
2715        for url in [
2716            "http://127.0.0.1/.well-known/oauth-authorization-server",
2717            "http://169.254.169.254/latest/meta-data/",
2718            "http://192.168.1.1/.well-known/did.json",
2719            "http://[::1]/.well-known/did.json",
2720        ] {
2721            let err = guarded_get_no_redirect(&client, url, &[])
2722                .await
2723                .expect_err("must refuse");
2724            let rendered = format!("{err:#}");
2725            assert!(
2726                rendered.contains("forbidden (internal) address"),
2727                "{url} failed for the wrong reason: {rendered}"
2728            );
2729        }
2730        // And the scheme check, which is a different branch entirely.
2731        let err = guarded_get_no_redirect(&client, "file:///etc/passwd", &[])
2732            .await
2733            .expect_err("must refuse");
2734        assert!(format!("{err:#}").contains("non-http(s) URL scheme"));
2735    }
2736
2737    /// **`guarded_get_no_redirect` does not follow even one hop.** Its sibling
2738    /// above proves the SSRF guard on this path; nothing proved the ZERO. Every
2739    /// case there is an internal address or a bad scheme, so `max_redirects =
2740    /// 0` — the function's reason to exist — was never exercised, and a
2741    /// mutation passing `MAX_REDIRECTS` instead left the whole suite green.
2742    ///
2743    /// That mutation is the authorization-server mix-up defence collapsing:
2744    /// OAuth metadata, `plc.directory`, `did:web` documents and the client
2745    /// metadata self-fetch would all be read from wherever a `302` pointed,
2746    /// while `issuer` is compared against the URL that was asked for.
2747    #[tokio::test]
2748    async fn guarded_get_no_redirect_refuses_to_follow_even_one_hop() {
2749        let (b_addr, b_log) = spawn_http(vec![ok_200()]).await;
2750        test_host_override("no-redirect-b.test", b_addr);
2751        let (a_addr, a_log) = spawn_http(vec![redirect_to(&format!(
2752            "http://no-redirect-b.test:{}/.well-known/oauth-authorization-server",
2753            b_addr.port()
2754        ))])
2755        .await;
2756        test_host_override("no-redirect-a.test", a_addr);
2757
2758        let err = guarded_get_no_redirect(
2759            &reqwest::Client::builder().build().unwrap(),
2760            &format!(
2761                "http://no-redirect-a.test:{}/.well-known/oauth-authorization-server",
2762                a_addr.port()
2763            ),
2764            &[],
2765        )
2766        .await
2767        .expect_err("a redirect was followed on the no-redirect path");
2768        let rendered = format!("{err:#}");
2769        assert!(
2770            rendered.contains("origin is load-bearing"),
2771            "refused for the wrong reason: {rendered}"
2772        );
2773        assert_eq!(a_log.lock().unwrap().len(), 1);
2774        assert_eq!(
2775            b_log.lock().unwrap().len(),
2776            0,
2777            "the redirect target was fetched — the hop was followed"
2778        );
2779    }
2780
2781    /// **A POST is never redirected.** The code comment on `guarded_post` says
2782    /// this branch is "not exercised here"; now it is. A `307` re-sends the
2783    /// method AND the body — an app password or an authorization code — to the
2784    /// host the response chose.
2785    #[tokio::test]
2786    async fn guarded_post_refuses_a_redirect_rather_than_resending_the_body() {
2787        let (elsewhere_addr, elsewhere_log) = spawn_http(vec![ok_200()]).await;
2788        test_host_override("post-elsewhere.test", elsewhere_addr);
2789        let (addr, log) = spawn_http(vec![format!(
2790            "HTTP/1.1 307 Temporary Redirect\r\nLocation: http://post-elsewhere.test:{}/token\r\n\
2791             Content-Length: 0\r\nConnection: close\r\n\r\n",
2792            elsewhere_addr.port()
2793        )])
2794        .await;
2795        test_host_override("post-redirect.test", addr);
2796
2797        let err = guarded_post_form(
2798            &reqwest::Client::builder().build().unwrap(),
2799            &format!("http://post-redirect.test:{}/token", addr.port()),
2800            &[],
2801            &[
2802                ("grant_type", "authorization_code"),
2803                ("code", "SECRET-CODE"),
2804            ],
2805        )
2806        .await
2807        .expect_err("a POST followed a redirect");
2808        let rendered = format!("{err:#}");
2809        assert!(
2810            rendered.contains("re-send the request body"),
2811            "refused for the wrong reason: {rendered}"
2812        );
2813        assert_eq!(log.lock().unwrap().len(), 1);
2814        assert_eq!(
2815            elsewhere_log.lock().unwrap().len(),
2816            0,
2817            "the body was re-sent to the host the response chose"
2818        );
2819    }
2820
2821    /// **The redirect budget is enforced.** `MAX_REDIRECTS` bounds every
2822    /// outbound fetch, and until now nothing drove a chain long enough to
2823    /// reach it. One host redirects to itself `MAX_REDIRECTS + 2` times; the
2824    /// guard must give up after `MAX_REDIRECTS + 1` requests, not loop on.
2825    #[tokio::test]
2826    async fn too_many_redirects_is_refused() {
2827        // Bound first so every Location can name this server's own port.
2828        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
2829        let port = listener.local_addr().unwrap().port();
2830        let hops: Vec<String> = (0..MAX_REDIRECTS + 2)
2831            .map(|i| redirect_to(&format!("http://redirect-loop.test:{port}/hop{i}")))
2832            .collect();
2833        let (addr, log) = spawn_http_on(listener, hops).await;
2834        test_host_override("redirect-loop.test", addr);
2835
2836        let err = guarded_get(
2837            &reqwest::Client::builder().build().unwrap(),
2838            &format!("http://redirect-loop.test:{port}/hop0"),
2839            &[],
2840        )
2841        .await
2842        .expect_err("an endless redirect chain was not refused");
2843        let rendered = format!("{err:#}");
2844        assert!(
2845            rendered.contains("too many redirects"),
2846            "refused for the wrong reason: {rendered}"
2847        );
2848        assert_eq!(
2849            log.lock().unwrap().len(),
2850            MAX_REDIRECTS + 1,
2851            "the guard made a different number of requests than its budget allows"
2852        );
2853    }
2854
2855    /// The content type must follow the body it describes. Because both come
2856    /// from the same value, a JSON body can never be labelled as a form.
2857    #[test]
2858    fn the_content_type_follows_the_body_kind() {
2859        assert_eq!(
2860            PostBody::Json(b"{}".to_vec()).content_type(),
2861            "application/json"
2862        );
2863        assert_eq!(
2864            PostBody::Form(&[("a", "b")]).content_type(),
2865            "application/x-www-form-urlencoded"
2866        );
2867        // And the bytes are encoded to match.
2868        assert_eq!(
2869            PostBody::Json(b"{\"a\":1}".to_vec()).into_bytes(),
2870            b"{\"a\":1}"
2871        );
2872        assert_eq!(PostBody::Form(&[("a", "b c")]).into_bytes(), b"a=b+c");
2873    }
2874
2875    /// Form encoding must percent-encode values; a value containing `&` or `=`
2876    /// must not be able to inject an extra parameter into the body.
2877    #[test]
2878    fn form_body_percent_encodes_and_cannot_inject_parameters() {
2879        let body = PostBody::Form(&[
2880            ("grant_type", "authorization_code"),
2881            ("code", "abc&scope=evil"),
2882            ("redirect_uri", "https://x.example/oauth/callback"),
2883        ])
2884        .into_bytes();
2885        let s = String::from_utf8(body).unwrap();
2886        assert!(s.contains("grant_type=authorization_code"));
2887        assert!(
2888            s.matches("scope=").count() == 0,
2889            "a `&` in a value injected a parameter: {s}"
2890        );
2891        assert!(s.contains("%26"), "the `&` was not encoded: {s}");
2892        assert!(s.contains("%3A%2F%2F"), "the `://` was not encoded: {s}");
2893    }
2894
2895    // ── SSRF ENFORCEMENT (not just the decision) ─────────────────────────────
2896    //
2897    // Everything below drives a REAL redirect through `guarded_get_inner`
2898    // against a real HTTP server. None of it was possible before the
2899    // `test_host_override` seam: the guard correctly refuses loopback, so a
2900    // local test server was unreachable through it, and three enforcement
2901    // properties had no coverage at all. Each had a mutation that left the
2902    // whole suite green.
2903
2904    /// A tiny HTTP server that replays canned responses and records every raw
2905    /// request it received. Returns its address and the request log.
2906    async fn spawn_http(
2907        responses: Vec<String>,
2908    ) -> (SocketAddr, std::sync::Arc<std::sync::Mutex<Vec<String>>>) {
2909        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
2910        spawn_http_on(listener, responses).await
2911    }
2912
2913    /// [`spawn_http`] on a listener the caller already bound — for a test whose
2914    /// canned responses must name the server's own port (a redirect loop).
2915    async fn spawn_http_on(
2916        listener: tokio::net::TcpListener,
2917        responses: Vec<String>,
2918    ) -> (SocketAddr, std::sync::Arc<std::sync::Mutex<Vec<String>>>) {
2919        use tokio::io::{AsyncReadExt, AsyncWriteExt};
2920        let addr = listener.local_addr().unwrap();
2921        let log = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
2922        let sink = std::sync::Arc::clone(&log);
2923        tokio::spawn(async move {
2924            let mut i = 0usize;
2925            loop {
2926                let Ok((mut sock, _)) = listener.accept().await else {
2927                    break;
2928                };
2929                // **The whole request, not the first 8 KB of it.**
2930                //
2931                // This used to be one `read` into a fixed buffer. Anything past
2932                // it was never captured, and the assertions over this log are
2933                // NEGATIVE — `!seen.contains("authorization:")` in the
2934                // cross-origin credential test — so a short capture satisfies
2935                // them exactly as well as a stripped header does. The two are
2936                // indistinguishable, and only one of them means the guard works.
2937                //
2938                // Same shape as `spawn_tls`, deliberately: three test servers
2939                // that read alike means the next one copied from any of them
2940                // starts correct. And the same limit applies — with no
2941                // `content-length` there is nothing to wait for, so a chunked
2942                // body stops after the head.
2943                let mut raw: Vec<u8> = Vec::new();
2944                let mut chunk = [0u8; 4096];
2945                loop {
2946                    // **A read error DISCARDS the connection rather than logging
2947                    // what arrived so far.** Breaking here and pushing the
2948                    // partial would put a truncated request in the log — the
2949                    // exact thing this change exists to stop, arriving by a
2950                    // different door. `spawn_tls` returns for the same reason.
2951                    let Ok(n) = sock.read(&mut chunk).await else {
2952                        return;
2953                    };
2954                    if n == 0 {
2955                        break;
2956                    }
2957                    raw.extend_from_slice(&chunk[..n]);
2958                    let Some(split) = raw.windows(4).position(|w| w == b"\r\n\r\n") else {
2959                        continue;
2960                    };
2961                    let (head, body) = raw.split_at(split + 4);
2962                    let want = String::from_utf8_lossy(head).lines().find_map(|l| {
2963                        let (k, v) = l.split_once(':')?;
2964                        k.eq_ignore_ascii_case("content-length")
2965                            .then(|| v.trim().parse::<usize>().ok())?
2966                    });
2967                    if want.is_none_or(|want| body.len() >= want) {
2968                        break;
2969                    }
2970                }
2971                if raw.is_empty() {
2972                    continue;
2973                }
2974                sink.lock()
2975                    .unwrap()
2976                    .push(String::from_utf8_lossy(&raw).to_string());
2977                let body = responses
2978                    .get(i)
2979                    .cloned()
2980                    .unwrap_or_else(|| responses.last().cloned().unwrap_or_default());
2981                i += 1;
2982                let _ = sock.write_all(body.as_bytes()).await;
2983                let _ = sock.flush().await;
2984            }
2985        });
2986        (addr, log)
2987    }
2988
2989    /// **The SSRF guard must ignore ambient proxy configuration.**
2990    ///
2991    /// reqwest defaults `auto_sys_proxy: true`. With `HTTP_PROXY` set in the
2992    /// process environment, a request is sent to the proxy in ABSOLUTE form —
2993    /// `GET http://host/path` — and over https as `CONNECT host:443`, for the
2994    /// PROXY to resolve the hostname.
2995    ///
2996    /// Precisely what breaks: `resolve_and_check` still runs its own lookup and
2997    /// still rejects forbidden IPs, so it is not that the check is skipped. It
2998    /// is that the checked address is no longer the address connected to — the
2999    /// proxy re-resolves the name on its own network, so the vetted result is
3000    /// decorative. DNS rebinding, split-horizon DNS and anything reachable from
3001    /// the proxy but not from here all come back. And the call returns 200, so
3002    /// it fails OPEN.
3003    ///
3004    /// Measured before `.no_proxy()` existed: vetted server 0 requests, proxy
3005    /// received `GET http://pin-vs-proxy.invalid/feed HTTP/1.1`, result
3006    /// `Ok(200)`.
3007    ///
3008    /// **Why this re-execs itself.** reqwest reads the proxy environment when
3009    /// the client is BUILT, so the variable has to be present before the
3010    /// builder runs. `set_var` is a data race against the ~39 `env::var` reads
3011    /// in this binary and is the one thing this codebase refuses to do in
3012    /// tests. So the parent owns both servers, and the child inherits
3013    /// `HTTP_PROXY` from birth — no mutation of a live environment anywhere.
3014    #[tokio::test]
3015    async fn the_pinned_client_ignores_ambient_proxy_configuration() {
3016        const VETTED: &str = "FR_AMBIENT_PROXY_VETTED";
3017        const HOST: &str = "ambient-proxy-probe.invalid";
3018
3019        if let Ok(vetted) = std::env::var(VETTED) {
3020            // ── child: HTTP_PROXY is already in our environment ──
3021            let addr: SocketAddr = vetted.parse().unwrap();
3022            let client = build_pinned_client(HOST, addr).expect("client");
3023            let _ = client.get(format!("http://{HOST}/probe")).send().await;
3024            return;
3025        }
3026
3027        // ── parent: owns both servers, so it can see who was contacted ──
3028        let (vetted_addr, vetted_log) = spawn_http(vec![ok_200()]).await;
3029        let (proxy_addr, proxy_log) = spawn_http(vec![ok_200()]).await;
3030
3031        // `tokio::process`, NOT `std::process`: a blocking `output()` here
3032        // would hold this single-threaded runtime, so the servers above could
3033        // never accept the child's connection — and the test would fail with
3034        // "did not reach the vetted address" for a reason that has nothing to
3035        // do with proxies. That exact false failure happened while writing it.
3036        let out = tokio::process::Command::new(std::env::current_exe().unwrap())
3037            // FULL path: `--exact` matches the whole test name including the
3038            // module. With the bare function name the child matched nothing,
3039            // ran zero tests, and exited 0 — so the parent saw a "successful"
3040            // child that had done nothing, and blamed the pin. The
3041            // `1 test` assertion below is there so that can never pass silently
3042            // again.
3043            .args([
3044                "net::tests::the_pinned_client_ignores_ambient_proxy_configuration",
3045                "--exact",
3046                "--test-threads=1",
3047            ])
3048            // **Clear the inherited proxy KILL-SWITCHES.**
3049            //
3050            // The child inherits this process's environment, and two inherited
3051            // values make the whole test vacuous — it passes with `.no_proxy()`
3052            // DELETED. Verified: `NO_PROXY='*'` and `REQUEST_METHOD=GET`
3053            // (hyper-util treats the latter as a CGI context and disables proxy
3054            // env entirely) each turn a genuine failure into `1 passed`.
3055            //
3056            // GitHub-hosted runners set none of these, so the gap was invisible
3057            // here — a self-hosted or corporate runner would have silently
3058            // neutered the regression test while it kept reporting success.
3059            .env_remove("NO_PROXY")
3060            .env_remove("no_proxy")
3061            .env_remove("REQUEST_METHOD")
3062            .env(VETTED, vetted_addr.to_string())
3063            .env("HTTP_PROXY", format!("http://{proxy_addr}"))
3064            .env("HTTPS_PROXY", format!("http://{proxy_addr}"))
3065            .env("ALL_PROXY", format!("http://{proxy_addr}"))
3066            .output()
3067            .await
3068            .expect("re-exec the test binary");
3069        let stdout = String::from_utf8_lossy(&out.stdout);
3070        assert!(
3071            out.status.success(),
3072            "child run failed: {}",
3073            String::from_utf8_lossy(&out.stderr)
3074        );
3075        assert!(
3076            stdout.contains("1 passed"),
3077            "the child ran no test, so this proves nothing about proxies — \
3078             check the --exact filter. Child stdout:\n{stdout}"
3079        );
3080
3081        let proxied = proxy_log.lock().unwrap().clone();
3082        let direct = vetted_log.lock().unwrap().len();
3083        assert!(
3084            proxied.is_empty(),
3085            "the pinned client used an ambient proxy, so the connect pin and \
3086             `is_forbidden_ip` were both bypassed — the proxy resolves the \
3087             hostname itself. Proxy saw: {proxied:?}"
3088        );
3089        assert_eq!(
3090            direct, 1,
3091            "the pinned client did not reach the vetted address it was pinned to",
3092        );
3093    }
3094
3095    fn ok_200() -> String {
3096        "HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nhi".to_string()
3097    }
3098    fn redirect_to(loc: &str) -> String {
3099        format!("HTTP/1.1 302 Found\r\nLocation: {loc}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
3100    }
3101    /// No `Location` and no body — which is what a 304 *is*, not a stub of one.
3102    fn not_modified_304() -> String {
3103        "HTTP/1.1 304 Not Modified\r\nETag: \"v1\"\r\nConnection: close\r\n\r\n".to_string()
3104    }
3105    /// `305 Use Proxy` — a relocating 3xx that names a PROXY, WITH a `Location`,
3106    /// so it would have been followed before the narrowing.
3107    fn use_proxy_305(loc: &str) -> String {
3108        format!("HTTP/1.1 305 Use Proxy\r\nLocation: {loc}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
3109    }
3110
3111    /// **An unfollowable 3xx is refused, not handed back.**
3112    ///
3113    /// Narrowing the follow set to `301|302|303|307|308` left a choice for the
3114    /// rest: return them, or refuse. Returning is the worse one, because callers
3115    /// do not uniformly check the status — `web::resolve_feed_url` reads the body
3116    /// straight into feed autodiscovery, so a `305` whose error page carries a
3117    /// `<link rel="alternate">` would quietly become a subscription.
3118    ///
3119    /// A 305 also carries a `Location`, so before the narrowing it was FOLLOWED:
3120    /// the request went through a proxy the response chose. Refusing is the
3121    /// stricter behaviour in both directions.
3122    #[tokio::test]
3123    async fn an_unfollowable_3xx_is_refused_rather_than_returned() {
3124        let (addr, log) = spawn_http(vec![use_proxy_305("http://proxy.invalid:3128/")]).await;
3125        test_host_override("use-proxy.test", addr);
3126
3127        let err = guarded_get(
3128            &reqwest::Client::builder().build().unwrap(),
3129            &format!("http://use-proxy.test:{}/feed.xml", addr.port()),
3130            &[],
3131        )
3132        .await
3133        .expect_err("a 305 was returned to the caller instead of refused");
3134
3135        let msg = format!("{err:#}");
3136        assert!(
3137            msg.contains("305") && msg.contains("no single target"),
3138            "refused, but not as an unfollowable status: {msg}",
3139        );
3140        // Refused at the first hop: the proxy it named was never contacted.
3141        assert_eq!(log.lock().unwrap().len(), 1);
3142    }
3143
3144    /// **A `304 Not Modified` must reach the caller, not be read as a redirect.**
3145    ///
3146    /// `is_redirection()` is `300..=399`, so 304 — which carries no `Location`
3147    /// by definition — fell into the redirect branch and failed the whole fetch
3148    /// with "redirect response without a usable Location header". `feed.rs`
3149    /// sends `If-None-Match`/`If-Modified-Since` on every poll and has a correct
3150    /// 304 branch (`feed.rs`, `status == StatusCode::NOT_MODIFIED`) that could
3151    /// never be reached, so every feed answering "unchanged" was recorded as a
3152    /// failure and backed off exponentially.
3153    ///
3154    /// This was not theoretical: production logged it against `9to5mac.com`,
3155    /// `proton.me` and `kodi.tv`, and `/stats` reported 68 of 111 feeds failing
3156    /// while its own copy explained them away as "usually gone rather than
3157    /// flaky". Re-running the poller's conditional GET by hand returned
3158    /// `HTTP 304` with zero `Location` headers.
3159    ///
3160    /// The hop count is asserted too: a 304 must not provoke a second request.
3161    /// Returning the response but still looping would satisfy a status-only
3162    /// assertion while re-fetching every unchanged feed.
3163    #[tokio::test]
3164    async fn a_304_reaches_the_caller_instead_of_being_read_as_a_redirect() {
3165        let (addr, log) = spawn_http(vec![not_modified_304()]).await;
3166        test_host_override("not-modified.test", addr);
3167
3168        let resp = guarded_get(
3169            &reqwest::Client::builder().build().unwrap(),
3170            &format!("http://not-modified.test:{}/feed.xml", addr.port()),
3171            &[],
3172        )
3173        .await
3174        .expect("a 304 was treated as a redirect");
3175
3176        assert_eq!(
3177            resp.status(),
3178            reqwest::StatusCode::NOT_MODIFIED,
3179            "the 304 did not survive the guard intact",
3180        );
3181        assert_eq!(
3182            log.lock().unwrap().len(),
3183            1,
3184            "a 304 caused more than one request — it was followed, not returned",
3185        );
3186    }
3187
3188    /// **A real redirect is still followed** — the other half of the narrowing
3189    /// above, which would otherwise be satisfied by never following anything.
3190    #[tokio::test]
3191    async fn a_302_is_still_followed_after_the_304_narrowing() {
3192        let (b_addr, _b_log) = spawn_http(vec![ok_200()]).await;
3193        test_host_override("still-follows-b.test", b_addr);
3194        let (a_addr, a_log) = spawn_http(vec![redirect_to(&format!(
3195            "http://still-follows-b.test:{}/final",
3196            b_addr.port()
3197        ))])
3198        .await;
3199        test_host_override("still-follows-a.test", a_addr);
3200
3201        let resp = guarded_get(
3202            &reqwest::Client::builder().build().unwrap(),
3203            &format!("http://still-follows-a.test:{}/feed.xml", a_addr.port()),
3204            &[],
3205        )
3206        .await
3207        .expect("the 302 was not followed");
3208
3209        assert_eq!(resp.status(), reqwest::StatusCode::OK);
3210        assert_eq!(a_log.lock().unwrap().len(), 1);
3211    }
3212
3213    /// **A redirect to a forbidden address is refused — the marquee SSRF
3214    /// property, and until now it had no end-to-end test.**
3215    ///
3216    /// `guarded_get_refuses_private_redirect_target` builds a 302 stub and then
3217    /// throws it away (`let _ = addr;`), asserting on a private URL passed in
3218    /// directly. Nothing drove a redirect through the guard, and a mutation that
3219    /// validated only the first hop — resolving redirect targets with a bare
3220    /// `lookup_host` and no `is_forbidden_ip` — left all 679 tests passing.
3221    ///
3222    /// Here a real server really 302s to the cloud metadata endpoint. Only the
3223    /// test server's own host is exempted from the IP check; the redirect target
3224    /// is an IP literal and goes through the real one.
3225    #[tokio::test]
3226    async fn a_redirect_to_a_forbidden_address_is_refused() {
3227        let (addr, log) = spawn_http(vec![redirect_to(
3228            "http://169.254.169.254/latest/meta-data/",
3229        )])
3230        .await;
3231        test_host_override("hop-forbidden.test", addr);
3232
3233        let err = guarded_get(
3234            &reqwest::Client::builder().build().unwrap(),
3235            &format!("http://hop-forbidden.test:{}/feed.xml", addr.port()),
3236            &[],
3237        )
3238        .await
3239        .expect_err("a 302 to the metadata endpoint was followed");
3240
3241        let msg = format!("{err:#}");
3242        assert!(
3243            msg.contains("169.254.169.254") && msg.contains("forbidden"),
3244            "refused, but not by the address check: {msg}",
3245        );
3246        // The hop happened; the SECOND hop is what was stopped.
3247        assert_eq!(log.lock().unwrap().len(), 1);
3248    }
3249
3250    /// **Credentials do not follow a redirect off the original origin.**
3251    ///
3252    /// `hop_headers` is tested as a pure function; nothing tested that
3253    /// `guarded_get_inner` actually calls it. Swapping the call for a plain
3254    /// `extra_headers` — so a bearer token rides to whatever host an upstream
3255    /// names — left the whole suite green.
3256    ///
3257    /// Two real servers on two hosts. The first 302s to the second; the second
3258    /// records what it was sent.
3259    #[tokio::test]
3260    async fn credentials_are_dropped_when_a_redirect_leaves_the_origin() {
3261        let (b_addr, b_log) = spawn_http(vec![ok_200()]).await;
3262        test_host_override("cred-b.test", b_addr);
3263        let (a_addr, _a_log) = spawn_http(vec![redirect_to(&format!(
3264            "http://cred-b.test:{}/next",
3265            b_addr.port()
3266        ))])
3267        .await;
3268        test_host_override("cred-a.test", a_addr);
3269
3270        let resp = guarded_get(
3271            &reqwest::Client::builder().build().unwrap(),
3272            &format!("http://cred-a.test:{}/feed.xml", a_addr.port()),
3273            &[(
3274                HeaderName::from_static("authorization"),
3275                HeaderValue::from_static("Bearer super-secret"),
3276            )],
3277        )
3278        .await
3279        .expect("the cross-origin hop should still succeed, just without the token");
3280        assert!(resp.status().is_success());
3281
3282        let seen = b_log.lock().unwrap().join("\n").to_ascii_lowercase();
3283        // **Anchor the two negatives below.** `!contains` is satisfied by the
3284        // header being absent OR by the capture being short, and those are
3285        // indistinguishable from here. Asserting the hop was recorded at all
3286        // means an empty or truncated capture fails loudly instead of reading
3287        // as a pass — which, for a check about not leaking a bearer token
3288        // across origins, is the difference that matters.
3289        assert!(
3290            seen.contains("get /next"),
3291            "hop B recorded no request, so the assertions below prove nothing:\n{seen}",
3292        );
3293        assert!(
3294            !seen.contains("super-secret"),
3295            "the bearer token was forwarded across origins:\n{seen}",
3296        );
3297        assert!(
3298            !seen.contains("authorization:"),
3299            "the Authorization header survived a cross-origin redirect:\n{seen}",
3300        );
3301    }
3302
3303    /// **...but they DO survive a same-origin redirect.**
3304    ///
3305    /// The other direction, without which the test above is satisfied by a guard
3306    /// that strips every header always — which would quietly break every
3307    /// authenticated fetch in the app.
3308    ///
3309    /// A RELATIVE `Location` keeps the hop on the same origin without the
3310    /// response needing to know its own port.
3311    #[tokio::test]
3312    async fn credentials_survive_a_same_origin_redirect() {
3313        let (addr, log) = spawn_http(vec![redirect_to("/second"), ok_200()]).await;
3314        test_host_override("cred-same.test", addr);
3315
3316        let resp = guarded_get(
3317            &reqwest::Client::builder().build().unwrap(),
3318            &format!("http://cred-same.test:{}/feed.xml", addr.port()),
3319            &[(
3320                HeaderName::from_static("authorization"),
3321                HeaderValue::from_static("Bearer keep-me"),
3322            )],
3323        )
3324        .await
3325        .expect("a same-origin redirect should be followed");
3326        assert!(resp.status().is_success());
3327
3328        let reqs = log.lock().unwrap().clone();
3329        assert_eq!(reqs.len(), 2, "the redirect was not followed");
3330        assert!(
3331            reqs[1].to_ascii_lowercase().contains("keep-me"),
3332            "the token was stripped on a SAME-origin redirect — over-stripping \
3333             would break every authenticated fetch:\n{}",
3334            reqs[1],
3335        );
3336    }
3337
3338    /// **Every DNS answer is checked, not just the first.**
3339    ///
3340    /// A host that publishes `1.2.3.4, 127.0.0.1` must be rejected wholesale.
3341    /// Checking only the first answer left the suite green, because nothing
3342    /// exercised a multi-answer set — real DNS in a test cannot be made to
3343    /// return one.
3344    #[test]
3345    fn a_mixed_dns_answer_set_is_rejected_wholesale() {
3346        let public: SocketAddr = "1.2.3.4:80".parse().unwrap();
3347        let private: SocketAddr = "127.0.0.1:80".parse().unwrap();
3348        let link_local: SocketAddr = "169.254.169.254:80".parse().unwrap();
3349
3350        // All public: the first is pinned.
3351        assert_eq!(
3352            first_vetted(
3353                "ok.example",
3354                [public, "5.6.7.8:80".parse().unwrap()].into_iter()
3355            )
3356            .unwrap(),
3357            public,
3358        );
3359        // A forbidden answer ANYWHERE rejects the set — including last, which is
3360        // exactly what a first-answer-only check would miss.
3361        for bad in [private, link_local] {
3362            assert!(
3363                first_vetted("evil.example", [public, bad].into_iter()).is_err(),
3364                "{bad} in the answer set was accepted because a good answer came first",
3365            );
3366            assert!(first_vetted("evil.example", [bad, public].into_iter()).is_err());
3367        }
3368        // No answers at all is an error, not a silent pass.
3369        assert!(first_vetted("empty.example", std::iter::empty()).is_err());
3370    }
3371
3372    /// **The capture must hold the whole request, not the first 8 KB of it.**
3373    ///
3374    /// `spawn_http` recorded one `sock.read()` into a fixed 8 KB buffer and
3375    /// treated that as the request. Anything past it was never captured — and
3376    /// never seen by the assertions that read the capture.
3377    ///
3378    /// That matters because the assertions downstream are NEGATIVE:
3379    /// `credentials_are_dropped_when_a_redirect_leaves_the_origin` checks
3380    /// `!seen.contains("authorization:")`. A short capture satisfies that exactly
3381    /// as well as a stripped header does, and the two are indistinguishable.
3382    ///
3383    /// A body larger than the buffer makes the truncation deterministic rather
3384    /// than waiting on TCP segmentation, which is why this test can go red at
3385    /// all.
3386    #[tokio::test]
3387    async fn the_request_capture_is_not_truncated_at_the_buffer_size() {
3388        let (addr, log) = spawn_http(vec![ok_200()]).await;
3389        test_host_override("big-body.test", addr);
3390
3391        // Comfortably past the old 8 KB read, with a sentinel at the very end.
3392        let filler = "x".repeat(32 * 1024);
3393        let body = format!("{{\"pad\":\"{filler}\",\"tail\":\"THE-LAST-BYTES\"}}");
3394
3395        // Not `let _ =`: a refused POST leaves the capture empty, and
3396        // "captured no request at all" would be the only symptom with the
3397        // cause thrown away.
3398        guarded_post_json(
3399            &reqwest::Client::builder().build().unwrap(),
3400            &format!("http://big-body.test:{}/ingest", addr.port()),
3401            &[],
3402            body.into_bytes(),
3403        )
3404        .await
3405        .expect("the POST to the test server failed before anything was captured");
3406
3407        let seen = log.lock().unwrap().join("\n");
3408        // Positive anchor first: without it, the tail assertion below could pass
3409        // vacuously on an empty capture in some future refactor.
3410        assert!(
3411            seen.contains("POST /ingest"),
3412            "the server captured no request at all: {} bytes",
3413            seen.len()
3414        );
3415        assert!(
3416            seen.contains("THE-LAST-BYTES"),
3417            "the capture stops short of the request's end, so every negative \
3418             assertion over it — including the one about not leaking an \
3419             Authorization header across origins — can pass for the wrong \
3420             reason. captured {} bytes",
3421            seen.len()
3422        );
3423    }
3424
3425    // ── TLS test server ──────────────────────────────────────────────────────
3426
3427    /// How many times [`guarded_get_for_a_verdict`] asks, while the answer keeps
3428    /// being a timeout rather than a verdict about the certificate.
3429    ///
3430    /// **Nothing pins this number, and that is disclosed rather than implied.**
3431    /// Any value above one behaves identically on a healthy run, so pinning it
3432    /// would need a server that stalls past the 15 s per-read bound — a 15 s
3433    /// test. What IS pinned, in both directions, is the classifier the loop turns
3434    /// on: `a_timeout_is_recognised_as_a_timeout_and_not_a_certificate_verdict`
3435    /// for one, the assertion inside
3436    /// `the_test_ca_is_trusted_and_still_validates_hostnames` for the other.
3437    const VERDICT_ATTEMPTS: usize = 3;
3438
3439    /// Whether an error out of [`guarded_get`] is a TIMEOUT rather than a verdict
3440    /// about the certificate.
3441    ///
3442    /// Classified from `reqwest::Error::is_timeout` through the `with_context`
3443    /// layer `guarded_get_inner` adds, not from the message text — the message
3444    /// is not a contract, and matching on it is how this file's other
3445    /// error-shape assertion passed for the wrong reason once already.
3446    fn is_timeout(err: &anyhow::Error) -> bool {
3447        err.downcast_ref::<reqwest::Error>()
3448            .is_some_and(reqwest::Error::is_timeout)
3449    }
3450
3451    /// [`guarded_get`], asked again while the only answer is a timeout.
3452    ///
3453    /// **The certificate test is about whether the chain validates, and a
3454    /// timeout is not a verdict on that.** It was observed failing on the first
3455    /// HTTPS request in a freshly linked test binary — 11.7 s and 20.3 s
3456    /// measured on one macOS machine, against the 15 s per-read bound
3457    /// `build_pinned_client` sets. Nine later attempts on the same machine
3458    /// measured 8–17 ms, so the cause is NOT pinned; the leading candidate is
3459    /// CPU starvation with ~900 tests in flight, which no amount of warming
3460    /// would fix.
3461    ///
3462    /// Two earlier attempts at this are worth naming, because both were wrong in
3463    /// ways this one avoids. Widening `READ_TIMEOUT` changed a production
3464    /// constant to accommodate a test. Warming the platform verifier once per
3465    /// process rested on a claim that is simply false — reqwest builds
3466    /// `rustls_platform_verifier` whether or not an extra root is present
3467    /// (`reqwest-0.13/src/async_impl/client.rs`: both arms of
3468    /// `if config.root_certs.is_empty()`), so there was no test-only path to
3469    /// warm; it also failed silently, and issued a request into the caller's
3470    /// captured log.
3471    ///
3472    /// Retrying the timeout is insensitive to *which* cause it was, changes no
3473    /// production bound, and cannot mask a validation failure: a certificate
3474    /// verdict is returned on the first ask.
3475    async fn guarded_get_for_a_verdict(client: &Client, url: &str) -> Result<Response> {
3476        for _ in 1..VERDICT_ATTEMPTS {
3477            match guarded_get(client, url, &[]).await {
3478                Err(err) if is_timeout(&err) => {
3479                    eprintln!("asking {url} again after a timeout, not a verdict: {err:#}");
3480                }
3481                verdict => return verdict,
3482            }
3483        }
3484        guarded_get(client, url, &[]).await
3485    }
3486
3487    /// **The retry turns entirely on this classifier, so pin it.**
3488    ///
3489    /// A classifier that stops recognising timeouts leaves the certificate test
3490    /// exactly as latency-sensitive as it was, with nothing to say so. The
3491    /// opposite direction — a certificate error must NOT read as a timeout, or a
3492    /// genuine validation failure would be retried and then reported as one — is
3493    /// asserted where such an error already exists, in
3494    /// `the_test_ca_is_trusted_and_still_validates_hostnames`.
3495    ///
3496    /// Uses a real timeout against a socket that is accepted and never answered,
3497    /// through the same `with_context` wrapping `guarded_get_inner` applies, so
3498    /// the downcast is exercised through a context layer rather than on a bare
3499    /// error.
3500    #[tokio::test]
3501    async fn a_timeout_is_recognised_as_a_timeout_and_not_a_certificate_verdict() {
3502        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
3503        let addr = listener.local_addr().unwrap();
3504        tokio::spawn(async move {
3505            // Accept and hold: answering nothing is the point, and dropping the
3506            // socket would end the request as a connection close instead.
3507            let mut held = Vec::new();
3508            while let Ok((sock, _)) = listener.accept().await {
3509                held.push(sock);
3510            }
3511        });
3512
3513        let client = Client::builder()
3514            .no_proxy()
3515            .timeout(Duration::from_millis(250))
3516            .build()
3517            .unwrap();
3518        let raw = client
3519            .get(format!("http://{addr}/never"))
3520            .send()
3521            .await
3522            .expect_err("a server that never answers must not produce a response");
3523        assert!(
3524            raw.is_timeout(),
3525            "the silent server ended the request some other way, so this test is \
3526             not exercising a timeout at all: {raw}",
3527        );
3528        let err = anyhow::Error::from(raw).context(format!("fetching http://{addr}/never"));
3529
3530        assert!(
3531            is_timeout(&err),
3532            "a real read timeout was not recognised as one, so the retry would \
3533             never retry and the certificate test stays latency-sensitive: {err:#}",
3534        );
3535    }
3536
3537    /// **The chain really validates — no invalid-cert acceptance anywhere.**
3538    ///
3539    /// The foundation every test below rests on. If this passed because
3540    /// validation were disabled rather than because the CA is trusted, none of
3541    /// the others would mean anything, so it is asserted directly: a host the
3542    /// leaf has NO SAN for must still fail.
3543    #[tokio::test]
3544    async fn the_test_ca_is_trusted_and_still_validates_hostnames() {
3545        let (addr, _log) = spawn_tls(|_| {
3546            let mut r = std::collections::HashMap::new();
3547            r.insert("/ok".to_string(), vec![TestResponse::json(200, "{}")]);
3548            r
3549        })
3550        .await;
3551        test_host_override("feed-tls.test", addr);
3552        // Registered, resolvable — but NOT in the leaf's SAN list.
3553        test_host_override("not-in-san.test", addr);
3554
3555        let client = reqwest::Client::builder().build().unwrap();
3556        // Asked again on a timeout — see `guarded_get_for_a_verdict`. A timeout
3557        // is not a verdict about this chain, and this test is only about the
3558        // verdict.
3559        let ok = guarded_get_for_a_verdict(
3560            &client,
3561            &format!("https://feed-tls.test:{}/ok", addr.port()),
3562        )
3563        .await
3564        .expect("a SAN-matching https host should be accepted");
3565        assert!(ok.status().is_success());
3566
3567        let err = guarded_get_for_a_verdict(
3568            &client,
3569            &format!("https://not-in-san.test:{}/ok", addr.port()),
3570        )
3571        .await
3572        .expect_err("a host with no SAN must still fail: validation is NOT disabled");
3573        // **The other half of the classifier, pinned where such an error exists.**
3574        // If a certificate verdict read as a timeout, this failure would be
3575        // retried `VERDICT_ATTEMPTS` times and then reported anyway — and the
3576        // retry would be masking exactly the failure it must never mask.
3577        assert!(
3578            !is_timeout(&err),
3579            "a certificate verdict was classified as a timeout, so the retry              would retry a genuine validation failure: {err:#}",
3580        );
3581        // **Assert the CERTIFICATE reason, not merely that it failed.**
3582        //
3583        // An earlier version accepted `msg.contains("name")`, which the DNS error
3584        // `nodename nor servname provided` also satisfies — so deleting the
3585        // `test_host_override` line above made this pass while proving nothing
3586        // about SAN validation. Verified: it did.
3587        let msg = format!("{err:#}").to_ascii_lowercase();
3588        assert!(
3589            msg.contains("notvalidforname") || msg.contains("invalid peer certificate"),
3590            "failed, but not because the certificate is invalid for this name — a \
3591             DNS or connect failure would prove nothing here: {msg}",
3592        );
3593    }
3594}