Skip to main content

rightkit_browser/
fixture_server.rs

1//! Immutable loopback HTTP server that only serves an owned fixture bundle.
2
3use crate::fixture_protocol::{
4    explicit_fixture_port, parse_fixture_url, validate_fixture_path, FixtureBundle, FixtureError,
5};
6use std::collections::{HashMap, HashSet};
7use std::net::{IpAddr, Ipv4Addr, SocketAddr};
8use std::sync::atomic::{AtomicU64, Ordering};
9use std::sync::Arc;
10use std::time::Duration;
11use tokio::io::{AsyncReadExt, AsyncWriteExt};
12use tokio::net::{TcpListener, TcpStream};
13use tokio::sync::oneshot;
14use tokio::task::{JoinHandle, JoinSet};
15
16const MAX_HEADER_BYTES: usize = 16 * 1024;
17const MAX_CONNECTIONS: usize = 128;
18const CONNECTION_TIMEOUT: Duration = Duration::from_secs(5);
19const CSP: &str = "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'none'; frame-src 'none'; child-src 'none'; object-src 'none'; media-src 'self'; form-action 'none'; base-uri 'none'; frame-ancestors 'none'; sandbox allow-scripts allow-same-origin";
20type FixtureFiles = Arc<HashMap<String, (String, Arc<[u8]>)>>;
21
22static NEXT_INSTANCE: AtomicU64 = AtomicU64::new(1);
23
24/// An exclusively owned server for one verified, immutable fixture bundle.
25pub struct FixtureServer {
26    bundle: FixtureBundle,
27    addr: SocketAddr,
28    instance_id: String,
29    accept_task: Option<JoinHandle<()>>,
30    shutdown_signal: Option<oneshot::Sender<()>>,
31}
32
33#[cfg(windows)]
34pub(crate) struct FixtureResponse {
35    pub(crate) status: u16,
36    pub(crate) headers: Vec<(String, String)>,
37    pub(crate) body: Arc<[u8]>,
38}
39
40impl FixtureServer {
41    /// Bind an available ephemeral port on IPv4 loopback.
42    pub async fn prepare(bundle: FixtureBundle) -> Result<Self, FixtureError> {
43        Self::bind(bundle, SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0)).await
44    }
45
46    /// Bind the exact loopback port named in `exact_url`, after checking that
47    /// its path belongs to this bundle. An existing listener makes this fail.
48    pub async fn prepare_at(bundle: FixtureBundle, exact_url: &str) -> Result<Self, FixtureError> {
49        let url = parse_fixture_url(exact_url)?;
50        if !bundle.files().iter().any(|file| file.path == url.path()) {
51            return Err(FixtureError::Invalid(
52                "exact_url does not point to a fixture manifest resource".into(),
53            ));
54        }
55        let port = explicit_fixture_port(exact_url)?;
56        Self::bind(
57            bundle,
58            SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port),
59        )
60        .await
61    }
62
63    async fn bind(bundle: FixtureBundle, addr: SocketAddr) -> Result<Self, FixtureError> {
64        let listener = TcpListener::bind(addr).await.map_err(|error| {
65            FixtureError::FixtureServerNotOwned(format!("cannot exclusively bind {addr}: {error}"))
66        })?;
67        let addr = listener.local_addr().map_err(|error| {
68            FixtureError::FixtureServerNotOwned(format!(
69                "cannot inspect bound fixture socket: {error}"
70            ))
71        })?;
72        let files: FixtureFiles = Arc::new(
73            bundle
74                .files()
75                .iter()
76                .map(|file| {
77                    (
78                        file.path.clone(),
79                        (
80                            file.content_type.clone(),
81                            Arc::<[u8]>::from(file.body.clone()),
82                        ),
83                    )
84                })
85                .collect(),
86        );
87        let (shutdown_signal, mut shutdown_receiver) = oneshot::channel();
88        let task = tokio::spawn(async move {
89            let mut connections = JoinSet::new();
90            loop {
91                tokio::select! {
92                    _ = &mut shutdown_receiver => break,
93                    accepted = listener.accept() => match accepted {
94                        Ok((stream, peer)) if peer.ip().is_loopback() && connections.len() < MAX_CONNECTIONS => {
95                            let files = Arc::clone(&files);
96                            connections.spawn(async move { serve_connection(stream, files).await });
97                        }
98                        Ok((_stream, _peer)) => {}
99                        Err(_) => break,
100                    },
101                    _ = connections.join_next(), if !connections.is_empty() => {}
102                }
103            }
104            connections.abort_all();
105            while connections.join_next().await.is_some() {}
106        });
107        let instance_id = format!(
108            "fixture-server-{}-{}",
109            std::process::id(),
110            NEXT_INSTANCE.fetch_add(1, Ordering::Relaxed)
111        );
112        Ok(Self {
113            bundle,
114            addr,
115            instance_id,
116            accept_task: Some(task),
117            shutdown_signal: Some(shutdown_signal),
118        })
119    }
120
121    /// Build an exact URL for a resource in the owned bundle.
122    pub fn url(&self, path: &str) -> Result<String, FixtureError> {
123        validate_fixture_path(path)?;
124        if !self.bundle.files().iter().any(|file| file.path == path) {
125            return Err(FixtureError::Invalid(
126                "path is not present in the owned fixture bundle".into(),
127            ));
128        }
129        Ok(format!("http://127.0.0.1:{}{path}", self.addr.port()))
130    }
131
132    pub(crate) fn addr(&self) -> SocketAddr {
133        self.addr
134    }
135
136    pub(crate) fn bundle(&self) -> &FixtureBundle {
137        &self.bundle
138    }
139
140    pub(crate) fn instance_id(&self) -> &str {
141        &self.instance_id
142    }
143
144    pub(crate) fn is_alive(&self) -> bool {
145        self.accept_task
146            .as_ref()
147            .is_some_and(|task| !task.is_finished())
148    }
149
150    pub(crate) fn permitted_urls(&self) -> Arc<HashSet<String>> {
151        Arc::new(
152            self.bundle
153                .files()
154                .iter()
155                .map(|file| format!("http://127.0.0.1:{}{}", self.addr.port(), file.path))
156                .collect(),
157        )
158    }
159
160    #[cfg(windows)]
161    pub(crate) fn response_for(
162        &self,
163        method: &str,
164        exact_url: &str,
165    ) -> Result<FixtureResponse, FixtureError> {
166        if !self.is_alive() {
167            return Err(FixtureError::FixtureServerNotOwned(
168                "owned fixture server is no longer alive".into(),
169            ));
170        }
171        if !matches!(method, "GET" | "HEAD") {
172            return Err(FixtureError::Invalid(
173                "fixture responses permit GET and HEAD only".into(),
174            ));
175        }
176        if !self.permitted_urls().contains(exact_url) {
177            return Err(FixtureError::Invalid(
178                "URL is not an exact permitted fixture resource".into(),
179            ));
180        }
181        let url = parse_fixture_url(exact_url)?;
182        let file = self
183            .bundle
184            .files()
185            .iter()
186            .find(|file| file.path == url.path())
187            .ok_or_else(|| {
188                FixtureError::Invalid("URL has no matching fixture manifest resource".into())
189            })?;
190        let headers = response_headers(&file.content_type, file.body.len());
191        let body = if method == "HEAD" {
192            Arc::<[u8]>::from(&[][..])
193        } else {
194            Arc::<[u8]>::from(file.body.clone())
195        };
196        Ok(FixtureResponse {
197            status: 200,
198            headers,
199            body,
200        })
201    }
202
203    /// Stop accepting, abort owned connections, and wait for their cleanup.
204    pub async fn shutdown(&mut self) -> Result<(), FixtureError> {
205        let Some(mut task) = self.accept_task.take() else {
206            return Ok(());
207        };
208        if let Some(signal) = self.shutdown_signal.take() {
209            let _ = signal.send(());
210        }
211        match tokio::time::timeout(CONNECTION_TIMEOUT, &mut task).await {
212            Ok(Ok(())) => Ok(()),
213            Ok(Err(error)) => Err(FixtureError::Cleanup(format!(
214                "fixture server task failed during shutdown: {error}"
215            ))),
216            Err(_) => {
217                task.abort();
218                let _ = task.await;
219                Err(FixtureError::Cleanup(
220                    "fixture server cleanup exceeded its time limit".into(),
221                ))
222            }
223        }
224    }
225}
226
227impl Drop for FixtureServer {
228    fn drop(&mut self) {
229        self.shutdown_signal.take();
230        if let Some(task) = self.accept_task.take() {
231            task.abort();
232        }
233    }
234}
235
236async fn serve_connection(mut stream: TcpStream, files: FixtureFiles) {
237    let _ = tokio::time::timeout(CONNECTION_TIMEOUT, async {
238        let request = match read_request(&mut stream).await {
239            Ok(request) => request,
240            Err(status) => {
241                let _ = write_response(
242                    &mut stream,
243                    status,
244                    "text/plain; charset=utf-8",
245                    b"fixture request rejected",
246                    false,
247                )
248                .await;
249                return;
250            }
251        };
252        match files.get(&request.path) {
253            Some((content_type, body)) => {
254                let _ = write_response(
255                    &mut stream,
256                    "200 OK",
257                    content_type,
258                    body,
259                    request.method == "HEAD",
260                )
261                .await;
262            }
263            None => {
264                let _ = write_response(
265                    &mut stream,
266                    "404 Not Found",
267                    "text/plain; charset=utf-8",
268                    b"not found",
269                    request.method == "HEAD",
270                )
271                .await;
272            }
273        }
274    })
275    .await;
276}
277
278struct Request {
279    method: String,
280    path: String,
281}
282
283async fn read_request(stream: &mut TcpStream) -> Result<Request, &'static str> {
284    let mut bytes = Vec::with_capacity(1024);
285    let mut chunk = [0u8; 1024];
286    let header_end = loop {
287        if let Some(index) = bytes.windows(4).position(|window| window == b"\r\n\r\n") {
288            break index + 4;
289        }
290        if bytes.len() >= MAX_HEADER_BYTES {
291            return Err("431 Request Header Fields Too Large");
292        }
293        let count = stream
294            .read(&mut chunk)
295            .await
296            .map_err(|_| "400 Bad Request")?;
297        if count == 0 {
298            return Err("400 Bad Request");
299        }
300        bytes.extend_from_slice(&chunk[..count]);
301        if bytes.len() > MAX_HEADER_BYTES {
302            return Err("431 Request Header Fields Too Large");
303        }
304    };
305    if header_end != bytes.len() {
306        return Err("400 Bad Request");
307    }
308    let text = std::str::from_utf8(&bytes[..header_end]).map_err(|_| "400 Bad Request")?;
309    let mut lines = text[..header_end - 4].split("\r\n");
310    let request_line = lines.next().ok_or("400 Bad Request")?;
311    let mut request_parts = request_line.split(' ');
312    let method = request_parts.next().ok_or("400 Bad Request")?;
313    let target = request_parts.next().ok_or("400 Bad Request")?;
314    let version = request_parts.next().ok_or("400 Bad Request")?;
315    if request_parts.next().is_some() || !matches!(version, "HTTP/1.0" | "HTTP/1.1") {
316        return Err("400 Bad Request");
317    }
318    if method == "CONNECT" {
319        return Err("405 Method Not Allowed");
320    }
321    if !matches!(method, "GET" | "HEAD") {
322        return Err("405 Method Not Allowed");
323    }
324    if !target.starts_with('/')
325        || target.starts_with("//")
326        || target.contains(['?', '#', '\\', '%'])
327    {
328        return Err("400 Bad Request");
329    }
330
331    let mut host: Option<&str> = None;
332    let mut content_length: Option<&str> = None;
333    let mut seen_headers = HashSet::new();
334    for line in lines {
335        let (name, value) = line.split_once(':').ok_or("400 Bad Request")?;
336        if name.is_empty()
337            || !name.bytes().all(is_token_byte)
338            || value.bytes().any(|b| b == b'\r' || b == b'\n')
339        {
340            return Err("400 Bad Request");
341        }
342        if !seen_headers.insert(name.to_ascii_lowercase()) {
343            return Err("400 Bad Request");
344        }
345        let value = value.trim();
346        if name.eq_ignore_ascii_case("host") {
347            if host.replace(value).is_some() {
348                return Err("400 Bad Request");
349            }
350        } else if name.eq_ignore_ascii_case("content-length") {
351            if content_length.replace(value).is_some() {
352                return Err("400 Bad Request");
353            }
354        } else if name.eq_ignore_ascii_case("transfer-encoding")
355            || name.eq_ignore_ascii_case("upgrade")
356            || (name.eq_ignore_ascii_case("connection")
357                && value.to_ascii_lowercase().contains("upgrade"))
358        {
359            return Err("400 Bad Request");
360        }
361    }
362    let host = host.ok_or("400 Bad Request")?;
363    if host
364        != format!(
365            "127.0.0.1:{}",
366            stream.local_addr().map_err(|_| "400 Bad Request")?.port()
367        )
368    {
369        return Err("400 Bad Request");
370    }
371    if let Some(length) = content_length {
372        if length != "0" {
373            return Err("400 Bad Request");
374        }
375    }
376    let path = target.to_owned();
377    validate_fixture_path(&path).map_err(|_| "400 Bad Request")?;
378    Ok(Request {
379        method: method.to_owned(),
380        path,
381    })
382}
383
384fn is_token_byte(byte: u8) -> bool {
385    byte.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&byte)
386}
387
388async fn write_response(
389    stream: &mut TcpStream,
390    status: &str,
391    content_type: &str,
392    body: &[u8],
393    head_only: bool,
394) -> Result<(), std::io::Error> {
395    let mut header = format!("HTTP/1.1 {status}\r\n");
396    for (name, value) in response_headers(content_type, body.len()) {
397        header.push_str(&name);
398        header.push_str(": ");
399        header.push_str(&value);
400        header.push_str("\r\n");
401    }
402    header.push_str("Connection: close\r\n\r\n");
403    stream.write_all(header.as_bytes()).await?;
404    if !head_only {
405        stream.write_all(body).await?;
406    }
407    stream.shutdown().await
408}
409
410fn response_headers(content_type: &str, content_length: usize) -> Vec<(String, String)> {
411    vec![
412        ("Content-Type".into(), content_type.into()),
413        ("Content-Length".into(), content_length.to_string()),
414        ("Cache-Control".into(), "no-store".into()),
415        ("X-Content-Type-Options".into(), "nosniff".into()),
416        ("Content-Security-Policy".into(), CSP.into()),
417    ]
418}