1use crate::policy::BlockReason;
12use crate::policy::Guard;
13use std::collections::HashSet;
14use std::io;
15use std::net::{IpAddr, Ipv4Addr, SocketAddr};
16use std::sync::{Arc, Mutex};
17use std::time::{Duration, Instant};
18use tokio::io::{AsyncReadExt, AsyncWriteExt};
19use tokio::net::{TcpListener, TcpStream};
20use tokio::sync::watch;
21use tokio::task::{JoinHandle, JoinSet};
22
23const MAX_FIXTURE_HEADER_BYTES: usize = 16 * 1024;
24const FIXTURE_HEADER_TIMEOUT: Duration = Duration::from_secs(5);
25const FIXTURE_CONNECT_TIMEOUT: Duration = Duration::from_secs(3);
26const FIXTURE_IO_TIMEOUT: Duration = Duration::from_secs(30);
27const ACCEPT_POLL_INTERVAL: Duration = Duration::from_millis(100);
28const MAX_FIXTURE_CONNECTIONS: usize = 128;
29
30#[derive(Clone)]
32pub(crate) struct FixtureProxyPolicy {
33 pub server_endpoint: SocketAddr,
34 pub permitted_urls: Arc<HashSet<String>>,
35 pub expires_at: Instant,
36}
37
38#[derive(Clone, Debug, Eq, PartialEq)]
40pub struct PinnedConnection {
41 pub host: String,
42 pub port: u16,
43 pub ip: IpAddr,
44}
45
46pub(crate) struct PinProxy {
47 pub addr: SocketAddr,
48 pub log: Arc<Mutex<Vec<PinnedConnection>>>,
49 shutdown: watch::Sender<bool>,
50 task: Mutex<Option<JoinHandle<io::Result<()>>>>,
51}
52
53impl Drop for PinProxy {
54 fn drop(&mut self) {
55 let _ = self.shutdown.send(true);
56 if let Some(task) = self
57 .task
58 .get_mut()
59 .unwrap_or_else(|poisoned| poisoned.into_inner())
60 .take()
61 {
62 task.abort();
65 }
66 }
67}
68
69impl PinProxy {
70 pub async fn start(guard: Arc<Guard>) -> std::io::Result<PinProxy> {
71 let listener = TcpListener::bind("127.0.0.1:0").await?;
72 let addr = listener.local_addr()?;
73 let log: Arc<Mutex<Vec<PinnedConnection>>> = Arc::default();
74 Ok(Self::spawn(listener, addr, guard, log, None))
75 }
76
77 pub async fn start_fixture(
78 guard: Arc<Guard>,
79 policy: FixtureProxyPolicy,
80 ) -> io::Result<PinProxy> {
81 validate_fixture_policy(&policy)?;
82 let listener = TcpListener::bind("127.0.0.1:0").await?;
83 let addr = listener.local_addr()?;
84 let log: Arc<Mutex<Vec<PinnedConnection>>> = Arc::default();
85 Ok(Self::spawn(listener, addr, guard, log, Some(policy)))
86 }
87
88 fn spawn(
89 listener: TcpListener,
90 addr: SocketAddr,
91 guard: Arc<Guard>,
92 log: Arc<Mutex<Vec<PinnedConnection>>>,
93 fixture: Option<FixtureProxyPolicy>,
94 ) -> PinProxy {
95 let (shutdown, receiver) = watch::channel(false);
96 let task = tokio::spawn(run_listener(
97 listener,
98 guard,
99 log.clone(),
100 fixture,
101 receiver,
102 ));
103 PinProxy {
104 addr,
105 log,
106 shutdown,
107 task: Mutex::new(Some(task)),
108 }
109 }
110
111 pub async fn shutdown(&self, grace: Duration) -> io::Result<()> {
113 let Some(mut task) = self
114 .task
115 .lock()
116 .unwrap_or_else(|poisoned| poisoned.into_inner())
117 .take()
118 else {
119 return Ok(());
120 };
121 let _ = self.shutdown.send(true);
122 match tokio::time::timeout(grace, &mut task).await {
123 Ok(Ok(result)) => result,
124 Ok(Err(error)) => Err(io::Error::other(error)),
125 Err(_) => {
126 task.abort();
127 let _ = task.await;
128 Err(io::Error::new(
129 io::ErrorKind::TimedOut,
130 "proxy shutdown exceeded grace period",
131 ))
132 }
133 }
134 }
135}
136
137async fn run_listener(
138 listener: TcpListener,
139 guard: Arc<Guard>,
140 log: Arc<Mutex<Vec<PinnedConnection>>>,
141 fixture: Option<FixtureProxyPolicy>,
142 mut shutdown: watch::Receiver<bool>,
143) -> io::Result<()> {
144 let mut connections = JoinSet::new();
145 loop {
146 while connections.try_join_next().is_some() {}
147 if *shutdown.borrow() {
148 break;
149 }
150 match tokio::time::timeout(ACCEPT_POLL_INTERVAL, listener.accept()).await {
151 Ok(Ok((mut conn, _))) => {
152 let guard = guard.clone();
153 let log = log.clone();
154 if let Some(policy) = fixture.as_ref() {
155 if connections.len() >= MAX_FIXTURE_CONNECTIONS {
156 let _ = tokio::time::timeout(
157 Duration::from_secs(1),
158 refuse(
159 &mut conn,
160 "503 Service Unavailable",
161 "fixture proxy connection limit reached",
162 ),
163 )
164 .await;
165 continue;
166 }
167 let policy = policy.clone();
168 connections.spawn(async move {
169 let _ = serve_fixture(conn, guard, log, policy).await;
170 });
171 } else {
172 connections.spawn(async move {
173 let _ = serve(conn, guard, log).await;
174 });
175 }
176 }
177 Ok(Err(error)) => {
178 connections.abort_all();
179 while connections.join_next().await.is_some() {}
180 return Err(error);
181 }
182 Err(_) => {
183 if shutdown.has_changed().unwrap_or(true) {
184 let _ = shutdown.borrow_and_update();
185 }
186 }
187 }
188 }
189 connections.abort_all();
190 while connections.join_next().await.is_some() {}
191 Ok(())
192}
193
194#[derive(Debug, Eq, PartialEq)]
195struct FixtureRequest {
196 method: String,
197 path_and_query: String,
198 version: String,
199 headers: Vec<(String, String)>,
200}
201
202fn validate_fixture_policy(policy: &FixtureProxyPolicy) -> io::Result<()> {
203 if policy.server_endpoint.ip() != IpAddr::V4(Ipv4Addr::LOCALHOST)
204 || policy.server_endpoint.port() == 0
205 {
206 return Err(io::Error::new(
207 io::ErrorKind::InvalidInput,
208 "fixture endpoint must be 127.0.0.1 with a nonzero port",
209 ));
210 }
211 if policy.permitted_urls.is_empty() {
212 return Err(io::Error::new(
213 io::ErrorKind::InvalidInput,
214 "fixture URL allowlist must not be empty",
215 ));
216 }
217 if Instant::now() >= policy.expires_at {
218 return Err(io::Error::new(
219 io::ErrorKind::InvalidInput,
220 "fixture proxy policy is already expired",
221 ));
222 }
223 for raw in policy.permitted_urls.iter() {
224 let parsed = url::Url::parse(raw).map_err(|error| {
225 io::Error::new(
226 io::ErrorKind::InvalidInput,
227 format!("invalid permitted fixture URL: {error}"),
228 )
229 })?;
230 if parsed.as_str() != raw
231 || parsed.scheme() != "http"
232 || parsed.host_str() != Some("127.0.0.1")
233 || parsed.port_or_known_default() != Some(policy.server_endpoint.port())
234 || !parsed.username().is_empty()
235 || parsed.password().is_some()
236 || parsed.fragment().is_some()
237 {
238 return Err(io::Error::new(
239 io::ErrorKind::InvalidInput,
240 "permitted fixture URLs must be canonical HTTP URLs at the owned endpoint",
241 ));
242 }
243 }
244 Ok(())
245}
246
247fn parse_fixture_request(
248 bytes: &[u8],
249 trailing: &[u8],
250 policy: &FixtureProxyPolicy,
251 now: Instant,
252) -> Result<FixtureRequest, &'static str> {
253 if now >= policy.expires_at {
254 return Err("fixture proxy policy expired");
255 }
256 if !trailing.is_empty() {
257 return Err("fixture requests cannot contain a body or pipelined bytes");
258 }
259 let head = std::str::from_utf8(bytes).map_err(|_| "fixture headers must be ASCII")?;
260 if !head.is_ascii() || !head.ends_with("\r\n\r\n") {
261 return Err("malformed fixture request headers");
262 }
263 let fields = head[..head.len() - 4].split("\r\n").collect::<Vec<_>>();
264 let mut request_line = fields.first().copied().unwrap_or("").split(' ');
265 let method = request_line.next().unwrap_or("");
266 let target = request_line.next().unwrap_or("");
267 let version = request_line.next().unwrap_or("");
268 if request_line.next().is_some()
269 || target.is_empty()
270 || !matches!(method, "GET" | "HEAD")
271 || !matches!(version, "HTTP/1.0" | "HTTP/1.1")
272 {
273 return Err("only well-formed GET and HEAD fixture requests are allowed");
274 }
275 if !policy.permitted_urls.contains(target) {
276 return Err("fixture URL is not in the exact allowlist");
277 }
278 let url = url::Url::parse(target).map_err(|_| "fixture URL is invalid")?;
279 if url.as_str() != target
280 || url.scheme() != "http"
281 || url.host_str() != Some("127.0.0.1")
282 || url.port_or_known_default() != Some(policy.server_endpoint.port())
283 || !url.username().is_empty()
284 || url.password().is_some()
285 || url.fragment().is_some()
286 {
287 return Err("fixture URL must target the exact owned HTTP endpoint");
288 }
289
290 let mut seen = HashSet::new();
291 let mut host_seen = false;
292 let mut headers = Vec::new();
293 for line in fields.iter().skip(1) {
294 let (name, raw_value) = line.split_once(':').ok_or("malformed fixture header")?;
295 if name.is_empty()
296 || !name
297 .bytes()
298 .all(|byte| byte.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&byte))
299 {
300 return Err("malformed fixture header name");
301 }
302 let lower_name = name.to_ascii_lowercase();
303 if !seen.insert(lower_name.clone()) {
304 return Err("duplicate fixture header");
305 }
306 let value = raw_value.trim_matches(|character| character == ' ' || character == '\t');
307 if value
308 .bytes()
309 .any(|byte| (byte < 0x20 && byte != b'\t') || byte == 0x7f)
310 {
311 return Err("malformed fixture header value");
312 }
313 match lower_name.as_str() {
314 "host" => {
315 host_seen = true;
316 if !value.eq_ignore_ascii_case(&policy.server_endpoint.to_string()) {
317 return Err("fixture Host must match the owned endpoint");
318 }
319 }
320 "content-length" if value == "0" => {}
321 "content-length" => return Err("fixture request bodies are not allowed"),
322 "connection" | "proxy-connection"
323 if value.eq_ignore_ascii_case("keep-alive")
324 || value.eq_ignore_ascii_case("close") => {}
325 "connection" | "proxy-connection" => {
326 return Err("fixture connection tokens must be exactly keep-alive or close");
327 }
328 "transfer-encoding" | "te" | "trailer" | "expect" | "upgrade" | "keep-alive" => {
329 return Err("fixture connection and transfer controls are not allowed");
330 }
331 name if name.starts_with("proxy-") => {
332 return Err("proxy control headers are not allowed");
333 }
334 "accept" | "accept-encoding" | "accept-language" | "cache-control"
335 | "if-modified-since" | "if-none-match" | "range" => {
336 headers.push((lower_name, value.to_string()));
337 }
338 _ => {}
341 }
342 }
343 if !host_seen {
344 return Err("fixture request must include the owned Host header");
345 }
346 let path_and_query = match url.query() {
347 Some(query) => format!("{}?{query}", url.path()),
348 None => url.path().to_string(),
349 };
350 Ok(FixtureRequest {
351 method: method.to_string(),
352 path_and_query,
353 version: version.to_string(),
354 headers,
355 })
356}
357
358async fn read_fixture_headers(conn: &mut TcpStream) -> io::Result<(Vec<u8>, Vec<u8>)> {
359 let mut bytes = Vec::new();
360 let mut chunk = [0u8; 4096];
361 loop {
362 if let Some(index) = bytes.windows(4).position(|window| window == b"\r\n\r\n") {
363 let end = index + 4;
364 if end > MAX_FIXTURE_HEADER_BYTES {
365 return Err(io::Error::new(
366 io::ErrorKind::InvalidData,
367 "fixture request headers exceed limit",
368 ));
369 }
370 return Ok((bytes[..end].to_vec(), bytes[end..].to_vec()));
371 }
372 if bytes.len() >= MAX_FIXTURE_HEADER_BYTES {
373 return Err(io::Error::new(
374 io::ErrorKind::InvalidData,
375 "fixture request headers exceed limit",
376 ));
377 }
378 let count = conn.read(&mut chunk).await?;
379 if count == 0 {
380 return Err(io::Error::new(
381 io::ErrorKind::UnexpectedEof,
382 "fixture request ended before headers",
383 ));
384 }
385 bytes.extend_from_slice(&chunk[..count]);
386 }
387}
388
389async fn serve_fixture(
390 mut conn: TcpStream,
391 guard: Arc<Guard>,
392 log: Arc<Mutex<Vec<PinnedConnection>>>,
393 policy: FixtureProxyPolicy,
394) -> io::Result<()> {
395 if Instant::now() >= policy.expires_at {
396 let reason = "fixture proxy policy expired";
397 guard.denied_network(
398 None,
399 "FixtureProxy",
400 &BlockReason::InvalidUrl(reason.to_string()),
401 );
402 refuse(&mut conn, "403 Forbidden", reason).await;
403 return Ok(());
404 }
405 let read = tokio::time::timeout(FIXTURE_HEADER_TIMEOUT, read_fixture_headers(&mut conn)).await;
406 let (head, trailing) = match read {
407 Ok(Ok(headers)) => headers,
408 Ok(Err(error)) if error.kind() == io::ErrorKind::InvalidData => {
409 refuse(
410 &mut conn,
411 "413 Payload Too Large",
412 "fixture headers exceed limit",
413 )
414 .await;
415 return Ok(());
416 }
417 Ok(Err(_)) => return Ok(()),
418 Err(_) => {
419 refuse(
420 &mut conn,
421 "408 Request Timeout",
422 "fixture request headers timed out",
423 )
424 .await;
425 return Ok(());
426 }
427 };
428 let request = match parse_fixture_request(&head, &trailing, &policy, Instant::now()) {
429 Ok(request) => request,
430 Err(reason) => {
431 guard.denied_network(
432 None,
433 "FixtureProxy",
434 &BlockReason::InvalidUrl(reason.to_string()),
435 );
436 refuse(&mut conn, "403 Forbidden", reason).await;
437 return Ok(());
438 }
439 };
440 let upstream = tokio::time::timeout(
441 FIXTURE_CONNECT_TIMEOUT,
442 TcpStream::connect(policy.server_endpoint),
443 )
444 .await;
445 let mut upstream = match upstream {
446 Ok(Ok(stream)) => stream,
447 Ok(Err(_)) | Err(_) => {
448 refuse(
449 &mut conn,
450 "502 Bad Gateway",
451 "fixture server connect failed",
452 )
453 .await;
454 return Ok(());
455 }
456 };
457 log.lock().unwrap().push(PinnedConnection {
458 host: "127.0.0.1".to_string(),
459 port: policy.server_endpoint.port(),
460 ip: IpAddr::V4(Ipv4Addr::LOCALHOST),
461 });
462
463 let mut outbound = format!(
464 "{} {} {}\r\nHost: {}\r\nConnection: close\r\n",
465 request.method, request.path_and_query, request.version, policy.server_endpoint
466 )
467 .into_bytes();
468 for (name, value) in request.headers {
469 outbound.extend_from_slice(name.as_bytes());
470 outbound.extend_from_slice(b": ");
471 outbound.extend_from_slice(value.as_bytes());
472 outbound.extend_from_slice(b"\r\n");
473 }
474 outbound.extend_from_slice(b"\r\n");
475 if !matches!(
476 tokio::time::timeout(FIXTURE_CONNECT_TIMEOUT, upstream.write_all(&outbound)).await,
477 Ok(Ok(()))
478 ) {
479 refuse(
480 &mut conn,
481 "504 Gateway Timeout",
482 "fixture request write timed out",
483 )
484 .await;
485 return Ok(());
486 }
487 if tokio::time::timeout(
488 FIXTURE_IO_TIMEOUT,
489 tokio::io::copy(&mut upstream, &mut conn),
490 )
491 .await
492 .is_err()
493 {
494 }
497 Ok(())
498}
499
500async fn refuse(conn: &mut TcpStream, code: &str, why: &str) {
501 let body = format!("blocked by rightkit-browser network policy: {why}");
502 let _ = conn
503 .write_all(
504 format!(
505 "HTTP/1.1 {code}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
506 body.len()
507 )
508 .as_bytes(),
509 )
510 .await;
511}
512
513async fn serve(
514 mut conn: TcpStream,
515 guard: Arc<Guard>,
516 log: Arc<Mutex<Vec<PinnedConnection>>>,
517) -> std::io::Result<()> {
518 let mut buf = Vec::new();
519 let mut chunk = [0u8; 4096];
520 let head_end = loop {
521 if let Some(i) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
522 break i + 4;
523 }
524 if buf.len() > 64 * 1024 {
525 return Ok(());
526 }
527 let n = conn.read(&mut chunk).await?;
528 if n == 0 {
529 return Ok(());
530 }
531 buf.extend_from_slice(&chunk[..n]);
532 };
533 let head = String::from_utf8_lossy(&buf[..head_end]).to_string();
534 let rest = buf[head_end..].to_vec();
535 let mut lines = head.split("\r\n");
536 let first = lines.next().unwrap_or("");
537 let mut parts = first.split_whitespace();
538 let (method, target, version) = (
539 parts.next().unwrap_or(""),
540 parts.next().unwrap_or(""),
541 parts.next().unwrap_or("HTTP/1.1"),
542 );
543
544 let is_connect = method.eq_ignore_ascii_case("CONNECT");
545 let (host, port, forward_head) = if is_connect {
546 let (h, p) = target.rsplit_once(':').unwrap_or((target, "443"));
547 (h.to_string(), p.parse::<u16>().unwrap_or(443), None)
548 } else {
549 let Ok(u) = url::Url::parse(target) else {
550 refuse(
551 &mut conn,
552 "400 Bad Request",
553 "proxy requests must use absolute URLs",
554 )
555 .await;
556 return Ok(());
557 };
558 let Some(h) = u.host_str() else {
559 refuse(&mut conn, "400 Bad Request", "no host").await;
560 return Ok(());
561 };
562 let path = match u.query() {
563 Some(q) => format!("{}?{q}", u.path()),
564 None => u.path().to_string(),
565 };
566 let mut out = format!("{method} {path} {version}\r\n");
567 for l in lines.filter(|l| !l.is_empty()) {
568 let name = l.split(':').next().unwrap_or("").to_ascii_lowercase();
569 if matches!(
570 name.as_str(),
571 "connection" | "proxy-connection" | "keep-alive" | "proxy-authorization"
572 ) {
573 continue;
574 }
575 out.push_str(l);
576 out.push_str("\r\n");
577 }
578 out.push_str("Connection: close\r\n\r\n");
579 (
580 h.to_string(),
581 u.port_or_known_default().unwrap_or(80),
582 Some(out),
583 )
584 };
585
586 let ips = match guard
587 .admit_proxied(&host, port, (!is_connect).then_some(target))
588 .await
589 {
590 Ok(ips) => ips,
591 Err(reason) => {
592 guard.denied_network(None, "Connect", &reason);
593 refuse(&mut conn, "403 Forbidden", &reason.to_string()).await;
594 return Ok(());
595 }
596 };
597 let mut upstream = None;
598 for ip in ips {
599 if let Ok(Ok(s)) = tokio::time::timeout(
600 Duration::from_secs(3),
601 TcpStream::connect(SocketAddr::new(ip, port)),
602 )
603 .await
604 {
605 log.lock().unwrap().push(PinnedConnection {
606 host: host.clone(),
607 port,
608 ip,
609 });
610 upstream = Some(s);
611 break;
612 }
613 log.lock().unwrap().push(PinnedConnection {
614 host: host.clone(),
615 port,
616 ip,
617 });
618 }
619 let Some(mut upstream) = upstream else {
620 refuse(&mut conn, "502 Bad Gateway", "connect failed").await;
621 return Ok(());
622 };
623 match forward_head {
624 None => {
625 conn.write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n")
626 .await?;
627 upstream.write_all(&rest).await?;
628 }
629 Some(h) => {
630 upstream.write_all(h.as_bytes()).await?;
631 upstream.write_all(&rest).await?;
632 }
633 }
634 let _ = tokio::io::copy_bidirectional(&mut conn, &mut upstream).await;
635 Ok(())
636}
637
638#[cfg(test)]
639mod fixture_tests {
640 use super::*;
641 use crate::policy::NetworkPolicy;
642 use std::time::Instant;
643
644 fn fixture_policy(endpoint: SocketAddr, urls: &[&str]) -> FixtureProxyPolicy {
645 FixtureProxyPolicy {
646 server_endpoint: endpoint,
647 permitted_urls: Arc::new(urls.iter().map(|url| (*url).to_string()).collect()),
648 expires_at: Instant::now() + Duration::from_secs(60),
649 }
650 }
651
652 fn endpoint() -> SocketAddr {
653 "127.0.0.1:43210".parse().unwrap()
654 }
655
656 #[test]
657 fn fixture_policy_accepts_only_canonical_urls_at_owned_endpoint() {
658 let endpoint = endpoint();
659 let url = "http://127.0.0.1:43210/index.html?view=one";
660 assert!(validate_fixture_policy(&fixture_policy(endpoint, &[url])).is_ok());
661
662 for invalid in [
663 "http://127.0.0.1:43211/index.html",
664 "https://127.0.0.1:43210/index.html",
665 "http://user@127.0.0.1:43210/index.html",
666 "http://127.0.0.1:43210/index.html#fragment",
667 "http://localhost:43210/index.html",
668 ] {
669 assert!(
670 validate_fixture_policy(&fixture_policy(endpoint, &[invalid])).is_err(),
671 "accepted {invalid}"
672 );
673 }
674 }
675
676 #[test]
677 fn fixture_parser_accepts_exact_get_and_strips_untrusted_headers() {
678 let endpoint = endpoint();
679 let url = "http://127.0.0.1:43210/index.html?view=one";
680 let policy = fixture_policy(endpoint, &[url]);
681 let request = format!(
682 "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"
683 );
684 let parsed =
685 parse_fixture_request(request.as_bytes(), &[], &policy, Instant::now()).unwrap();
686 assert_eq!(parsed.method, "GET");
687 assert_eq!(parsed.path_and_query, "/index.html?view=one");
688 assert_eq!(parsed.headers, vec![("accept".into(), "text/html".into())]);
689 }
690
691 #[test]
692 fn fixture_parser_accepts_chrome_keep_alive_headers_and_strips_them() {
693 let endpoint = endpoint();
694 let url = "http://127.0.0.1:43210/index.html";
695 let policy = fixture_policy(endpoint, &[url]);
696 let request = format!(
697 "GET {url} HTTP/1.1\r\nHost: {endpoint}\r\nConnection: keep-alive\r\nProxy-Connection: Keep-Alive\r\n\r\n"
698 );
699 let parsed =
700 parse_fixture_request(request.as_bytes(), &[], &policy, Instant::now()).unwrap();
701 assert!(parsed.headers.is_empty());
702
703 let request = format!(
704 "GET {url} HTTP/1.1\r\nHost: {endpoint}\r\nConnection: keep-alive, Upgrade\r\n\r\n"
705 );
706 assert!(parse_fixture_request(request.as_bytes(), &[], &policy, Instant::now()).is_err());
707 }
708
709 #[test]
710 fn fixture_parser_rejects_host_mismatch_duplicates_methods_and_body_data() {
711 let endpoint = endpoint();
712 let url = "http://127.0.0.1:43210/index.html";
713 let policy = fixture_policy(endpoint, &[url]);
714 for request in [
715 format!("GET {url} HTTP/1.1\r\nHost: 127.0.0.1:43211\r\n\r\n"),
716 format!("GET {url} HTTP/1.1\r\nHost: {endpoint}\r\nHost: {endpoint}\r\n\r\n"),
717 format!("POST {url} HTTP/1.1\r\nHost: {endpoint}\r\n\r\n"),
718 format!("GET {url} HTTP/1.1\r\nHost: {endpoint}\r\nContent-Length: 1\r\n\r\n"),
719 format!("GET {url} HTTP/1.1\r\nHost: {endpoint}\r\nTransfer-Encoding: chunked\r\n\r\n"),
720 format!("GET {url} HTTP/1.1\r\nHost: {endpoint}\r\nUpgrade: websocket\r\n\r\n"),
721 ] {
722 assert!(
723 parse_fixture_request(request.as_bytes(), &[], &policy, Instant::now()).is_err(),
724 "accepted request: {request:?}"
725 );
726 }
727 let request = format!("GET {url} HTTP/1.1\r\nHost: {endpoint}\r\n\r\n");
728 assert!(
729 parse_fixture_request(request.as_bytes(), b"late body", &policy, Instant::now())
730 .is_err()
731 );
732 }
733
734 #[test]
735 fn fixture_parser_rejects_urls_outside_allowlist_and_after_deadline() {
736 let endpoint = endpoint();
737 let url = "http://127.0.0.1:43210/index.html";
738 let policy = fixture_policy(endpoint, &[url]);
739 let other = "http://127.0.0.1:43210/other.html";
740 let request = format!("GET {other} HTTP/1.1\r\nHost: {endpoint}\r\n\r\n");
741 assert!(parse_fixture_request(request.as_bytes(), &[], &policy, Instant::now()).is_err());
742
743 let expired = FixtureProxyPolicy {
744 expires_at: Instant::now() - Duration::from_millis(1),
745 ..policy
746 };
747 let request = format!("GET {url} HTTP/1.1\r\nHost: {endpoint}\r\n\r\n");
748 assert!(parse_fixture_request(request.as_bytes(), &[], &expired, Instant::now()).is_err());
749 }
750
751 #[tokio::test]
752 async fn shutdown_closes_listener_and_joins_partial_request() {
753 let guard = Arc::new(Guard {
754 session_id: "fixture-test".into(),
755 admission: None,
756 network: NetworkPolicy::default(),
757 events: None,
758 page_allowed: Mutex::default(),
759 });
760 let server_endpoint = endpoint();
761 let proxy = PinProxy::start_fixture(
762 guard,
763 fixture_policy(server_endpoint, &["http://127.0.0.1:43210/index.html"]),
764 )
765 .await
766 .unwrap();
767 let mut client = TcpStream::connect(proxy.addr).await.unwrap();
768 client.write_all(b"GET ").await.unwrap();
769
770 proxy.shutdown(Duration::from_secs(1)).await.unwrap();
771 let mut byte = [0u8; 1];
772 assert!(matches!(client.read(&mut byte).await, Ok(0) | Err(_)));
773 assert!(TcpStream::connect(proxy.addr).await.is_err());
774 }
775}
776
777#[cfg(test)]
779mod connect_policy_tests {
780 use super::*;
781 use crate::policy::{
782 BrowserEvent, BrowserRequest, LifecycleKind, NetworkPolicy, PolicyDecision,
783 };
784
785 type Calls = Arc<Mutex<Vec<(String, String)>>>;
786
787 fn offline() -> NetworkPolicy {
790 NetworkPolicy::default().with_resolver(|h| match h {
791 "public.example" => vec!["93.184.216.34".parse().unwrap()],
792 "allowed.example" | "other.example" => vec!["127.0.0.1".parse().unwrap()],
793 _ => vec![],
794 })
795 }
796
797 fn recording(
798 decide: impl Fn(&BrowserRequest) -> PolicyDecision + Send + Sync + 'static,
799 ) -> (NetworkPolicy, Calls) {
800 let calls: Calls = Arc::default();
801 let c = calls.clone();
802 let network = offline().allow_with(move |r: &BrowserRequest| {
803 c.lock()
804 .unwrap()
805 .push((r.resource_type.clone(), r.url.clone()));
806 decide(r)
807 });
808 (network, calls)
809 }
810
811 struct Harness {
812 guard: Arc<Guard>,
813 proxy: PinProxy,
814 denied: Arc<Mutex<Vec<BrowserEvent>>>,
815 }
816
817 impl Harness {
818 async fn start(network: NetworkPolicy) -> Harness {
819 let denied: Arc<Mutex<Vec<BrowserEvent>>> = Arc::default();
820 let d = denied.clone();
821 let guard = Arc::new(Guard {
822 session_id: "connect-test".into(),
823 admission: None,
824 network,
825 events: Some(Arc::new(move |e: &BrowserEvent| {
826 if matches!(e.kind, LifecycleKind::Denied) {
827 d.lock().unwrap().push(e.clone());
828 }
829 })),
830 page_allowed: Mutex::default(),
831 });
832 let proxy = PinProxy::start(guard.clone()).await.unwrap();
833 Harness {
834 guard,
835 proxy,
836 denied,
837 }
838 }
839
840 async fn send(&self, head: &str) -> String {
842 let mut client = TcpStream::connect(self.proxy.addr).await.unwrap();
843 client.write_all(head.as_bytes()).await.unwrap();
844 let mut buf = vec![0u8; 512];
845 let n = tokio::time::timeout(Duration::from_secs(10), client.read(&mut buf))
846 .await
847 .unwrap()
848 .unwrap();
849 String::from_utf8_lossy(&buf[..n])
850 .lines()
851 .next()
852 .unwrap_or("")
853 .to_string()
854 }
855
856 async fn connect(&self, target: &str) -> String {
857 self.send(&format!(
858 "CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n\r\n"
859 ))
860 .await
861 }
862
863 fn connect_denials(&self) -> usize {
864 self.denied
865 .lock()
866 .unwrap()
867 .iter()
868 .filter(|e| e.what.as_deref() == Some("Connect"))
869 .count()
870 }
871
872 fn logged(&self) -> Vec<PinnedConnection> {
873 self.proxy.log.lock().unwrap().clone()
874 }
875 }
876
877 async fn listener() -> (u16, JoinHandle<io::Result<TcpStream>>) {
878 let upstream = TcpListener::bind("127.0.0.1:0").await.unwrap();
879 let port = upstream.local_addr().unwrap().port();
880 (
881 port,
882 tokio::spawn(async move { upstream.accept().await.map(|(s, _)| s) }),
883 )
884 }
885
886 #[tokio::test]
888 async fn deny_all_callback_refuses_connect_before_any_upstream() {
889 let (network, calls) = recording(|_| PolicyDecision::Deny("deny all".into()));
890 let h = Harness::start(network).await;
891 let status = h.connect("public.example:443").await;
892 assert!(status.contains("403"), "{status}");
893 assert!(h.logged().is_empty(), "no upstream connection may be made");
894 assert_eq!(h.connect_denials(), 1);
895 assert_eq!(
896 *calls.lock().unwrap(),
897 [(
898 "Connect".to_string(),
899 "https://public.example:443/".to_string()
900 )]
901 );
902 }
903
904 #[tokio::test]
906 async fn plain_http_absolute_form_is_checked_with_its_full_url() {
907 let (network, calls) = recording(|_| PolicyDecision::Deny("deny all".into()));
908 let h = Harness::start(network).await;
909 let url = "http://public.example/path?q=1";
910 let status = h
911 .send(&format!(
912 "GET {url} HTTP/1.1\r\nHost: public.example\r\n\r\n"
913 ))
914 .await;
915 assert!(status.contains("403"), "{status}");
916 assert!(h.logged().is_empty());
917 assert_eq!(h.connect_denials(), 1);
918 assert_eq!(
919 *calls.lock().unwrap(),
920 [("Connect".to_string(), url.to_string())]
921 );
922 }
923
924 #[tokio::test]
926 async fn callback_allowing_one_host_admits_exactly_that_host() {
927 let (port, accepted) = listener().await;
928 let (network, _) = recording(|r| {
929 if r.host == "allowed.example" {
930 PolicyDecision::Allow
931 } else {
932 PolicyDecision::Deny("not listed".into())
933 }
934 });
935 let h = Harness::start(network).await;
936 let status = h.connect(&format!("allowed.example:{port}")).await;
937 assert!(status.contains("200"), "{status}");
938 assert!(accepted.await.unwrap().is_ok());
939 let status = h.connect(&format!("other.example:{port}")).await;
940 assert!(status.contains("403"), "{status}");
941 let log = h.logged();
942 assert_eq!(log.len(), 1, "{log:?}");
943 assert_eq!(
944 (log[0].host.as_str(), log[0].port),
945 ("allowed.example", port)
946 );
947 assert_eq!(h.connect_denials(), 1);
948 }
949
950 #[tokio::test]
952 async fn a_pair_a_page_check_allowed_is_not_decided_again() {
953 let (port, accepted) = listener().await;
954 let (network, calls) = recording(|r| PolicyDecision::from(r.host == "allowed.example"));
955 let h = Harness::start(network).await;
956 let url = format!("https://allowed.example:{port}/page?q=1");
958 h.guard.check_request(&url, "Document").await.unwrap();
959 let status = h.connect(&format!("allowed.example:{port}")).await;
960 assert!(status.contains("200"), "{status}");
961 assert!(accepted.await.unwrap().is_ok());
962 assert_eq!(*calls.lock().unwrap(), [("Document".to_string(), url)]);
963 assert_eq!(h.connect_denials(), 0);
964 }
965
966 #[tokio::test]
968 async fn without_a_callback_the_decision_is_unchanged() {
969 let guard = Harness::start(offline()).await.guard;
970 assert_eq!(
971 guard.admit_proxied("public.example", 443, None).await,
972 guard.network.pin("public.example").await
973 );
974 assert!(guard
975 .admit_proxied("public.example", 443, None)
976 .await
977 .is_ok());
978 assert!(guard
979 .admit_proxied("allowed.example", 443, None)
980 .await
981 .is_err());
982 assert!(guard.page_allowed.lock().unwrap().is_empty());
983 }
984
985 #[tokio::test]
987 async fn allow_callback_cannot_open_metadata_or_link_local() {
988 let (network, _) = recording(|_| PolicyDecision::Allow);
989 let h = Harness::start(network).await;
990 for target in [
991 "169.254.169.254:80",
992 "metadata.google.internal:80",
993 "[fe80::1]:443",
994 ] {
995 let status = h.connect(target).await;
996 assert!(status.contains("403"), "{target}: {status}");
997 }
998 assert!(h.logged().is_empty());
999 assert_eq!(h.connect_denials(), 3);
1000 }
1001}