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}