Skip to main content

rightkit_browser/
proxy.rs

1//! In-process pinning proxy. Chrome is started with `--proxy-server` pointing
2//! here (loopback included, no bypass), so Chrome never resolves names itself:
3//! this proxy resolves once through [`NetworkPolicy::pin`], checks the resolved
4//! addresses against the policy, and connects to the vetted address. A name
5//! that flips from public to private between check and connect (DNS
6//! rebinding), or a request that bypassed page interception (workers), can
7//! therefore never reach a blocked address.
8use crate::policy::BlockReason;
9use crate::policy::Guard;
10use std::collections::HashSet;
11use std::io;
12use std::net::{IpAddr, Ipv4Addr, SocketAddr};
13use std::sync::{Arc, Mutex};
14use std::time::{Duration, Instant};
15use tokio::io::{AsyncReadExt, AsyncWriteExt};
16use tokio::net::{TcpListener, TcpStream};
17use tokio::sync::watch;
18use tokio::task::{JoinHandle, JoinSet};
19
20const MAX_FIXTURE_HEADER_BYTES: usize = 16 * 1024;
21const FIXTURE_HEADER_TIMEOUT: Duration = Duration::from_secs(5);
22const FIXTURE_CONNECT_TIMEOUT: Duration = Duration::from_secs(3);
23const FIXTURE_IO_TIMEOUT: Duration = Duration::from_secs(30);
24const ACCEPT_POLL_INTERVAL: Duration = Duration::from_millis(100);
25const MAX_FIXTURE_CONNECTIONS: usize = 128;
26
27/// Immutable network boundary for a local browser fixture.
28#[derive(Clone)]
29pub(crate) struct FixtureProxyPolicy {
30    pub server_endpoint: SocketAddr,
31    pub permitted_urls: Arc<HashSet<String>>,
32    pub expires_at: Instant,
33}
34
35/// One connection the proxy made, with the address it pinned.
36#[derive(Clone, Debug, Eq, PartialEq)]
37pub struct PinnedConnection {
38    pub host: String,
39    pub port: u16,
40    pub ip: IpAddr,
41}
42
43pub(crate) struct PinProxy {
44    pub addr: SocketAddr,
45    pub log: Arc<Mutex<Vec<PinnedConnection>>>,
46    shutdown: watch::Sender<bool>,
47    task: Mutex<Option<JoinHandle<io::Result<()>>>>,
48}
49
50impl Drop for PinProxy {
51    fn drop(&mut self) {
52        let _ = self.shutdown.send(true);
53        if let Some(task) = self
54            .task
55            .get_mut()
56            .unwrap_or_else(|poisoned| poisoned.into_inner())
57            .take()
58        {
59            // The listener supervisor owns a JoinSet, whose drop aborts every
60            // connection task before the listener task is released.
61            task.abort();
62        }
63    }
64}
65
66impl PinProxy {
67    pub async fn start(guard: Arc<Guard>) -> std::io::Result<PinProxy> {
68        let listener = TcpListener::bind("127.0.0.1:0").await?;
69        let addr = listener.local_addr()?;
70        let log: Arc<Mutex<Vec<PinnedConnection>>> = Arc::default();
71        Ok(Self::spawn(listener, addr, guard, log, None))
72    }
73
74    pub async fn start_fixture(
75        guard: Arc<Guard>,
76        policy: FixtureProxyPolicy,
77    ) -> io::Result<PinProxy> {
78        validate_fixture_policy(&policy)?;
79        let listener = TcpListener::bind("127.0.0.1:0").await?;
80        let addr = listener.local_addr()?;
81        let log: Arc<Mutex<Vec<PinnedConnection>>> = Arc::default();
82        Ok(Self::spawn(listener, addr, guard, log, Some(policy)))
83    }
84
85    fn spawn(
86        listener: TcpListener,
87        addr: SocketAddr,
88        guard: Arc<Guard>,
89        log: Arc<Mutex<Vec<PinnedConnection>>>,
90        fixture: Option<FixtureProxyPolicy>,
91    ) -> PinProxy {
92        let (shutdown, receiver) = watch::channel(false);
93        let task = tokio::spawn(run_listener(
94            listener,
95            guard,
96            log.clone(),
97            fixture,
98            receiver,
99        ));
100        PinProxy {
101            addr,
102            log,
103            shutdown,
104            task: Mutex::new(Some(task)),
105        }
106    }
107
108    /// Stop accepting, abort active connections, and join them within `grace`.
109    pub async fn shutdown(&self, grace: Duration) -> io::Result<()> {
110        let Some(mut task) = self
111            .task
112            .lock()
113            .unwrap_or_else(|poisoned| poisoned.into_inner())
114            .take()
115        else {
116            return Ok(());
117        };
118        let _ = self.shutdown.send(true);
119        match tokio::time::timeout(grace, &mut task).await {
120            Ok(Ok(result)) => result,
121            Ok(Err(error)) => Err(io::Error::other(error)),
122            Err(_) => {
123                task.abort();
124                let _ = task.await;
125                Err(io::Error::new(
126                    io::ErrorKind::TimedOut,
127                    "proxy shutdown exceeded grace period",
128                ))
129            }
130        }
131    }
132}
133
134async fn run_listener(
135    listener: TcpListener,
136    guard: Arc<Guard>,
137    log: Arc<Mutex<Vec<PinnedConnection>>>,
138    fixture: Option<FixtureProxyPolicy>,
139    mut shutdown: watch::Receiver<bool>,
140) -> io::Result<()> {
141    let mut connections = JoinSet::new();
142    loop {
143        while connections.try_join_next().is_some() {}
144        if *shutdown.borrow() {
145            break;
146        }
147        match tokio::time::timeout(ACCEPT_POLL_INTERVAL, listener.accept()).await {
148            Ok(Ok((mut conn, _))) => {
149                let guard = guard.clone();
150                let log = log.clone();
151                if let Some(policy) = fixture.as_ref() {
152                    if connections.len() >= MAX_FIXTURE_CONNECTIONS {
153                        let _ = tokio::time::timeout(
154                            Duration::from_secs(1),
155                            refuse(
156                                &mut conn,
157                                "503 Service Unavailable",
158                                "fixture proxy connection limit reached",
159                            ),
160                        )
161                        .await;
162                        continue;
163                    }
164                    let policy = policy.clone();
165                    connections.spawn(async move {
166                        let _ = serve_fixture(conn, guard, log, policy).await;
167                    });
168                } else {
169                    connections.spawn(async move {
170                        let _ = serve(conn, guard, log).await;
171                    });
172                }
173            }
174            Ok(Err(error)) => {
175                connections.abort_all();
176                while connections.join_next().await.is_some() {}
177                return Err(error);
178            }
179            Err(_) => {
180                if shutdown.has_changed().unwrap_or(true) {
181                    let _ = shutdown.borrow_and_update();
182                }
183            }
184        }
185    }
186    connections.abort_all();
187    while connections.join_next().await.is_some() {}
188    Ok(())
189}
190
191#[derive(Debug, Eq, PartialEq)]
192struct FixtureRequest {
193    method: String,
194    path_and_query: String,
195    version: String,
196    headers: Vec<(String, String)>,
197}
198
199fn validate_fixture_policy(policy: &FixtureProxyPolicy) -> io::Result<()> {
200    if policy.server_endpoint.ip() != IpAddr::V4(Ipv4Addr::LOCALHOST)
201        || policy.server_endpoint.port() == 0
202    {
203        return Err(io::Error::new(
204            io::ErrorKind::InvalidInput,
205            "fixture endpoint must be 127.0.0.1 with a nonzero port",
206        ));
207    }
208    if policy.permitted_urls.is_empty() {
209        return Err(io::Error::new(
210            io::ErrorKind::InvalidInput,
211            "fixture URL allowlist must not be empty",
212        ));
213    }
214    if Instant::now() >= policy.expires_at {
215        return Err(io::Error::new(
216            io::ErrorKind::InvalidInput,
217            "fixture proxy policy is already expired",
218        ));
219    }
220    for raw in policy.permitted_urls.iter() {
221        let parsed = url::Url::parse(raw).map_err(|error| {
222            io::Error::new(
223                io::ErrorKind::InvalidInput,
224                format!("invalid permitted fixture URL: {error}"),
225            )
226        })?;
227        if parsed.as_str() != raw
228            || parsed.scheme() != "http"
229            || parsed.host_str() != Some("127.0.0.1")
230            || parsed.port_or_known_default() != Some(policy.server_endpoint.port())
231            || !parsed.username().is_empty()
232            || parsed.password().is_some()
233            || parsed.fragment().is_some()
234        {
235            return Err(io::Error::new(
236                io::ErrorKind::InvalidInput,
237                "permitted fixture URLs must be canonical HTTP URLs at the owned endpoint",
238            ));
239        }
240    }
241    Ok(())
242}
243
244fn parse_fixture_request(
245    bytes: &[u8],
246    trailing: &[u8],
247    policy: &FixtureProxyPolicy,
248    now: Instant,
249) -> Result<FixtureRequest, &'static str> {
250    if now >= policy.expires_at {
251        return Err("fixture proxy policy expired");
252    }
253    if !trailing.is_empty() {
254        return Err("fixture requests cannot contain a body or pipelined bytes");
255    }
256    let head = std::str::from_utf8(bytes).map_err(|_| "fixture headers must be ASCII")?;
257    if !head.is_ascii() || !head.ends_with("\r\n\r\n") {
258        return Err("malformed fixture request headers");
259    }
260    let fields = head[..head.len() - 4].split("\r\n").collect::<Vec<_>>();
261    let mut request_line = fields.first().copied().unwrap_or("").split(' ');
262    let method = request_line.next().unwrap_or("");
263    let target = request_line.next().unwrap_or("");
264    let version = request_line.next().unwrap_or("");
265    if request_line.next().is_some()
266        || target.is_empty()
267        || !matches!(method, "GET" | "HEAD")
268        || !matches!(version, "HTTP/1.0" | "HTTP/1.1")
269    {
270        return Err("only well-formed GET and HEAD fixture requests are allowed");
271    }
272    if !policy.permitted_urls.contains(target) {
273        return Err("fixture URL is not in the exact allowlist");
274    }
275    let url = url::Url::parse(target).map_err(|_| "fixture URL is invalid")?;
276    if url.as_str() != target
277        || url.scheme() != "http"
278        || url.host_str() != Some("127.0.0.1")
279        || url.port_or_known_default() != Some(policy.server_endpoint.port())
280        || !url.username().is_empty()
281        || url.password().is_some()
282        || url.fragment().is_some()
283    {
284        return Err("fixture URL must target the exact owned HTTP endpoint");
285    }
286
287    let mut seen = HashSet::new();
288    let mut host_seen = false;
289    let mut headers = Vec::new();
290    for line in fields.iter().skip(1) {
291        let (name, raw_value) = line.split_once(':').ok_or("malformed fixture header")?;
292        if name.is_empty()
293            || !name
294                .bytes()
295                .all(|byte| byte.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&byte))
296        {
297            return Err("malformed fixture header name");
298        }
299        let lower_name = name.to_ascii_lowercase();
300        if !seen.insert(lower_name.clone()) {
301            return Err("duplicate fixture header");
302        }
303        let value = raw_value.trim_matches(|character| character == ' ' || character == '\t');
304        if value
305            .bytes()
306            .any(|byte| (byte < 0x20 && byte != b'\t') || byte == 0x7f)
307        {
308            return Err("malformed fixture header value");
309        }
310        match lower_name.as_str() {
311            "host" => {
312                host_seen = true;
313                if !value.eq_ignore_ascii_case(&policy.server_endpoint.to_string()) {
314                    return Err("fixture Host must match the owned endpoint");
315                }
316            }
317            "content-length" if value == "0" => {}
318            "content-length" => return Err("fixture request bodies are not allowed"),
319            "connection" | "proxy-connection"
320                if value.eq_ignore_ascii_case("keep-alive")
321                    || value.eq_ignore_ascii_case("close") => {}
322            "connection" | "proxy-connection" => {
323                return Err("fixture connection tokens must be exactly keep-alive or close");
324            }
325            "transfer-encoding" | "te" | "trailer" | "expect" | "upgrade" | "keep-alive" => {
326                return Err("fixture connection and transfer controls are not allowed");
327            }
328            name if name.starts_with("proxy-") => {
329                return Err("proxy control headers are not allowed");
330            }
331            "accept" | "accept-encoding" | "accept-language" | "cache-control"
332            | "if-modified-since" | "if-none-match" | "range" => {
333                headers.push((lower_name, value.to_string()));
334            }
335            // Caller credentials, forwarding, origin, and browser-specific
336            // headers are intentionally not copied to the fixture server.
337            _ => {}
338        }
339    }
340    if !host_seen {
341        return Err("fixture request must include the owned Host header");
342    }
343    let path_and_query = match url.query() {
344        Some(query) => format!("{}?{query}", url.path()),
345        None => url.path().to_string(),
346    };
347    Ok(FixtureRequest {
348        method: method.to_string(),
349        path_and_query,
350        version: version.to_string(),
351        headers,
352    })
353}
354
355async fn read_fixture_headers(conn: &mut TcpStream) -> io::Result<(Vec<u8>, Vec<u8>)> {
356    let mut bytes = Vec::new();
357    let mut chunk = [0u8; 4096];
358    loop {
359        if let Some(index) = bytes.windows(4).position(|window| window == b"\r\n\r\n") {
360            let end = index + 4;
361            if end > MAX_FIXTURE_HEADER_BYTES {
362                return Err(io::Error::new(
363                    io::ErrorKind::InvalidData,
364                    "fixture request headers exceed limit",
365                ));
366            }
367            return Ok((bytes[..end].to_vec(), bytes[end..].to_vec()));
368        }
369        if bytes.len() >= MAX_FIXTURE_HEADER_BYTES {
370            return Err(io::Error::new(
371                io::ErrorKind::InvalidData,
372                "fixture request headers exceed limit",
373            ));
374        }
375        let count = conn.read(&mut chunk).await?;
376        if count == 0 {
377            return Err(io::Error::new(
378                io::ErrorKind::UnexpectedEof,
379                "fixture request ended before headers",
380            ));
381        }
382        bytes.extend_from_slice(&chunk[..count]);
383    }
384}
385
386async fn serve_fixture(
387    mut conn: TcpStream,
388    guard: Arc<Guard>,
389    log: Arc<Mutex<Vec<PinnedConnection>>>,
390    policy: FixtureProxyPolicy,
391) -> io::Result<()> {
392    if Instant::now() >= policy.expires_at {
393        let reason = "fixture proxy policy expired";
394        guard.denied_network(
395            None,
396            "FixtureProxy",
397            &BlockReason::InvalidUrl(reason.to_string()),
398        );
399        refuse(&mut conn, "403 Forbidden", reason).await;
400        return Ok(());
401    }
402    let read = tokio::time::timeout(FIXTURE_HEADER_TIMEOUT, read_fixture_headers(&mut conn)).await;
403    let (head, trailing) = match read {
404        Ok(Ok(headers)) => headers,
405        Ok(Err(error)) if error.kind() == io::ErrorKind::InvalidData => {
406            refuse(
407                &mut conn,
408                "413 Payload Too Large",
409                "fixture headers exceed limit",
410            )
411            .await;
412            return Ok(());
413        }
414        Ok(Err(_)) => return Ok(()),
415        Err(_) => {
416            refuse(
417                &mut conn,
418                "408 Request Timeout",
419                "fixture request headers timed out",
420            )
421            .await;
422            return Ok(());
423        }
424    };
425    let request = match parse_fixture_request(&head, &trailing, &policy, Instant::now()) {
426        Ok(request) => request,
427        Err(reason) => {
428            guard.denied_network(
429                None,
430                "FixtureProxy",
431                &BlockReason::InvalidUrl(reason.to_string()),
432            );
433            refuse(&mut conn, "403 Forbidden", reason).await;
434            return Ok(());
435        }
436    };
437    let upstream = tokio::time::timeout(
438        FIXTURE_CONNECT_TIMEOUT,
439        TcpStream::connect(policy.server_endpoint),
440    )
441    .await;
442    let mut upstream = match upstream {
443        Ok(Ok(stream)) => stream,
444        Ok(Err(_)) | Err(_) => {
445            refuse(
446                &mut conn,
447                "502 Bad Gateway",
448                "fixture server connect failed",
449            )
450            .await;
451            return Ok(());
452        }
453    };
454    log.lock().unwrap().push(PinnedConnection {
455        host: "127.0.0.1".to_string(),
456        port: policy.server_endpoint.port(),
457        ip: IpAddr::V4(Ipv4Addr::LOCALHOST),
458    });
459
460    let mut outbound = format!(
461        "{} {} {}\r\nHost: {}\r\nConnection: close\r\n",
462        request.method, request.path_and_query, request.version, policy.server_endpoint
463    )
464    .into_bytes();
465    for (name, value) in request.headers {
466        outbound.extend_from_slice(name.as_bytes());
467        outbound.extend_from_slice(b": ");
468        outbound.extend_from_slice(value.as_bytes());
469        outbound.extend_from_slice(b"\r\n");
470    }
471    outbound.extend_from_slice(b"\r\n");
472    if !matches!(
473        tokio::time::timeout(FIXTURE_CONNECT_TIMEOUT, upstream.write_all(&outbound)).await,
474        Ok(Ok(()))
475    ) {
476        refuse(
477            &mut conn,
478            "504 Gateway Timeout",
479            "fixture request write timed out",
480        )
481        .await;
482        return Ok(());
483    }
484    if tokio::time::timeout(
485        FIXTURE_IO_TIMEOUT,
486        tokio::io::copy(&mut upstream, &mut conn),
487    )
488    .await
489    .is_err()
490    {
491        // The response is already in flight; closing both sides is the only
492        // safe bounded outcome once its time budget expires.
493    }
494    Ok(())
495}
496
497async fn refuse(conn: &mut TcpStream, code: &str, why: &str) {
498    let body = format!("blocked by rightkit-browser network policy: {why}");
499    let _ = conn
500        .write_all(
501            format!(
502                "HTTP/1.1 {code}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
503                body.len()
504            )
505            .as_bytes(),
506        )
507        .await;
508}
509
510async fn serve(
511    mut conn: TcpStream,
512    guard: Arc<Guard>,
513    log: Arc<Mutex<Vec<PinnedConnection>>>,
514) -> std::io::Result<()> {
515    let mut buf = Vec::new();
516    let mut chunk = [0u8; 4096];
517    let head_end = loop {
518        if let Some(i) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
519            break i + 4;
520        }
521        if buf.len() > 64 * 1024 {
522            return Ok(());
523        }
524        let n = conn.read(&mut chunk).await?;
525        if n == 0 {
526            return Ok(());
527        }
528        buf.extend_from_slice(&chunk[..n]);
529    };
530    let head = String::from_utf8_lossy(&buf[..head_end]).to_string();
531    let rest = buf[head_end..].to_vec();
532    let mut lines = head.split("\r\n");
533    let first = lines.next().unwrap_or("");
534    let mut parts = first.split_whitespace();
535    let (method, target, version) = (
536        parts.next().unwrap_or(""),
537        parts.next().unwrap_or(""),
538        parts.next().unwrap_or("HTTP/1.1"),
539    );
540
541    let is_connect = method.eq_ignore_ascii_case("CONNECT");
542    let (host, port, forward_head) = if is_connect {
543        let (h, p) = target.rsplit_once(':').unwrap_or((target, "443"));
544        (h.to_string(), p.parse::<u16>().unwrap_or(443), None)
545    } else {
546        let Ok(u) = url::Url::parse(target) else {
547            refuse(
548                &mut conn,
549                "400 Bad Request",
550                "proxy requests must use absolute URLs",
551            )
552            .await;
553            return Ok(());
554        };
555        let Some(h) = u.host_str() else {
556            refuse(&mut conn, "400 Bad Request", "no host").await;
557            return Ok(());
558        };
559        let path = match u.query() {
560            Some(q) => format!("{}?{q}", u.path()),
561            None => u.path().to_string(),
562        };
563        let mut out = format!("{method} {path} {version}\r\n");
564        for l in lines.filter(|l| !l.is_empty()) {
565            let name = l.split(':').next().unwrap_or("").to_ascii_lowercase();
566            if matches!(
567                name.as_str(),
568                "connection" | "proxy-connection" | "keep-alive" | "proxy-authorization"
569            ) {
570                continue;
571            }
572            out.push_str(l);
573            out.push_str("\r\n");
574        }
575        out.push_str("Connection: close\r\n\r\n");
576        (
577            h.to_string(),
578            u.port_or_known_default().unwrap_or(80),
579            Some(out),
580        )
581    };
582
583    let ips = match guard.network.pin(&host).await {
584        Ok(ips) => ips,
585        Err(reason) => {
586            guard.denied_network(None, "Connect", &reason);
587            refuse(&mut conn, "403 Forbidden", &reason.to_string()).await;
588            return Ok(());
589        }
590    };
591    let mut upstream = None;
592    for ip in ips {
593        if let Ok(Ok(s)) = tokio::time::timeout(
594            Duration::from_secs(3),
595            TcpStream::connect(SocketAddr::new(ip, port)),
596        )
597        .await
598        {
599            log.lock().unwrap().push(PinnedConnection {
600                host: host.clone(),
601                port,
602                ip,
603            });
604            upstream = Some(s);
605            break;
606        }
607        log.lock().unwrap().push(PinnedConnection {
608            host: host.clone(),
609            port,
610            ip,
611        });
612    }
613    let Some(mut upstream) = upstream else {
614        refuse(&mut conn, "502 Bad Gateway", "connect failed").await;
615        return Ok(());
616    };
617    match forward_head {
618        None => {
619            conn.write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n")
620                .await?;
621            upstream.write_all(&rest).await?;
622        }
623        Some(h) => {
624            upstream.write_all(h.as_bytes()).await?;
625            upstream.write_all(&rest).await?;
626        }
627    }
628    let _ = tokio::io::copy_bidirectional(&mut conn, &mut upstream).await;
629    Ok(())
630}
631
632#[cfg(test)]
633mod fixture_tests {
634    use super::*;
635    use crate::policy::NetworkPolicy;
636    use std::time::Instant;
637
638    fn fixture_policy(endpoint: SocketAddr, urls: &[&str]) -> FixtureProxyPolicy {
639        FixtureProxyPolicy {
640            server_endpoint: endpoint,
641            permitted_urls: Arc::new(urls.iter().map(|url| (*url).to_string()).collect()),
642            expires_at: Instant::now() + Duration::from_secs(60),
643        }
644    }
645
646    fn endpoint() -> SocketAddr {
647        "127.0.0.1:43210".parse().unwrap()
648    }
649
650    #[test]
651    fn fixture_policy_accepts_only_canonical_urls_at_owned_endpoint() {
652        let endpoint = endpoint();
653        let url = "http://127.0.0.1:43210/index.html?view=one";
654        assert!(validate_fixture_policy(&fixture_policy(endpoint, &[url])).is_ok());
655
656        for invalid in [
657            "http://127.0.0.1:43211/index.html",
658            "https://127.0.0.1:43210/index.html",
659            "http://user@127.0.0.1:43210/index.html",
660            "http://127.0.0.1:43210/index.html#fragment",
661            "http://localhost:43210/index.html",
662        ] {
663            assert!(
664                validate_fixture_policy(&fixture_policy(endpoint, &[invalid])).is_err(),
665                "accepted {invalid}"
666            );
667        }
668    }
669
670    #[test]
671    fn fixture_parser_accepts_exact_get_and_strips_untrusted_headers() {
672        let endpoint = endpoint();
673        let url = "http://127.0.0.1:43210/index.html?view=one";
674        let policy = fixture_policy(endpoint, &[url]);
675        let request = format!(
676            "GET {url} HTTP/1.1\r\nHost: {endpoint}\r\nAccept: text/html\r\nAuthorization: Bearer secret\r\nCookie: session=secret\r\nX-Forwarded-For: 192.0.2.8\r\n\r\n"
677        );
678        let parsed =
679            parse_fixture_request(request.as_bytes(), &[], &policy, Instant::now()).unwrap();
680        assert_eq!(parsed.method, "GET");
681        assert_eq!(parsed.path_and_query, "/index.html?view=one");
682        assert_eq!(parsed.headers, vec![("accept".into(), "text/html".into())]);
683    }
684
685    #[test]
686    fn fixture_parser_accepts_chrome_keep_alive_headers_and_strips_them() {
687        let endpoint = endpoint();
688        let url = "http://127.0.0.1:43210/index.html";
689        let policy = fixture_policy(endpoint, &[url]);
690        let request = format!(
691            "GET {url} HTTP/1.1\r\nHost: {endpoint}\r\nConnection: keep-alive\r\nProxy-Connection: Keep-Alive\r\n\r\n"
692        );
693        let parsed =
694            parse_fixture_request(request.as_bytes(), &[], &policy, Instant::now()).unwrap();
695        assert!(parsed.headers.is_empty());
696
697        let request = format!(
698            "GET {url} HTTP/1.1\r\nHost: {endpoint}\r\nConnection: keep-alive, Upgrade\r\n\r\n"
699        );
700        assert!(parse_fixture_request(request.as_bytes(), &[], &policy, Instant::now()).is_err());
701    }
702
703    #[test]
704    fn fixture_parser_rejects_host_mismatch_duplicates_methods_and_body_data() {
705        let endpoint = endpoint();
706        let url = "http://127.0.0.1:43210/index.html";
707        let policy = fixture_policy(endpoint, &[url]);
708        for request in [
709            format!("GET {url} HTTP/1.1\r\nHost: 127.0.0.1:43211\r\n\r\n"),
710            format!("GET {url} HTTP/1.1\r\nHost: {endpoint}\r\nHost: {endpoint}\r\n\r\n"),
711            format!("POST {url} HTTP/1.1\r\nHost: {endpoint}\r\n\r\n"),
712            format!("GET {url} HTTP/1.1\r\nHost: {endpoint}\r\nContent-Length: 1\r\n\r\n"),
713            format!("GET {url} HTTP/1.1\r\nHost: {endpoint}\r\nTransfer-Encoding: chunked\r\n\r\n"),
714            format!("GET {url} HTTP/1.1\r\nHost: {endpoint}\r\nUpgrade: websocket\r\n\r\n"),
715        ] {
716            assert!(
717                parse_fixture_request(request.as_bytes(), &[], &policy, Instant::now()).is_err(),
718                "accepted request: {request:?}"
719            );
720        }
721        let request = format!("GET {url} HTTP/1.1\r\nHost: {endpoint}\r\n\r\n");
722        assert!(
723            parse_fixture_request(request.as_bytes(), b"late body", &policy, Instant::now())
724                .is_err()
725        );
726    }
727
728    #[test]
729    fn fixture_parser_rejects_urls_outside_allowlist_and_after_deadline() {
730        let endpoint = endpoint();
731        let url = "http://127.0.0.1:43210/index.html";
732        let policy = fixture_policy(endpoint, &[url]);
733        let other = "http://127.0.0.1:43210/other.html";
734        let request = format!("GET {other} HTTP/1.1\r\nHost: {endpoint}\r\n\r\n");
735        assert!(parse_fixture_request(request.as_bytes(), &[], &policy, Instant::now()).is_err());
736
737        let expired = FixtureProxyPolicy {
738            expires_at: Instant::now() - Duration::from_millis(1),
739            ..policy
740        };
741        let request = format!("GET {url} HTTP/1.1\r\nHost: {endpoint}\r\n\r\n");
742        assert!(parse_fixture_request(request.as_bytes(), &[], &expired, Instant::now()).is_err());
743    }
744
745    #[tokio::test]
746    async fn shutdown_closes_listener_and_joins_partial_request() {
747        let guard = Arc::new(Guard {
748            session_id: "fixture-test".into(),
749            admission: None,
750            network: NetworkPolicy::default(),
751            events: None,
752        });
753        let server_endpoint = endpoint();
754        let proxy = PinProxy::start_fixture(
755            guard,
756            fixture_policy(server_endpoint, &["http://127.0.0.1:43210/index.html"]),
757        )
758        .await
759        .unwrap();
760        let mut client = TcpStream::connect(proxy.addr).await.unwrap();
761        client.write_all(b"GET ").await.unwrap();
762
763        proxy.shutdown(Duration::from_secs(1)).await.unwrap();
764        let mut byte = [0u8; 1];
765        assert!(matches!(client.read(&mut byte).await, Ok(0) | Err(_)));
766        assert!(TcpStream::connect(proxy.addr).await.is_err());
767    }
768}