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