From ddc335ce65b078f65924e5aad8df796437ec1284 Mon Sep 17 00:00:00 2001 From: enricobuehler Date: Thu, 5 Nov 2026 21:17:00 +0100 Subject: [PATCH] fix(server): guard the page's origin against other sites The server held no line around its origin. A site that rebinds its name to the server's address was same-origin with it, and any other site could call /h/, /a/ and /config.json, read host answers through the relay, and reach into the LAN through a server nobody exposed. A request now names an address, a local name or one in TLS_NAMES, or gets 421; only an operator certificate with no names skips that. Every route but the static files refuses another site's request, with one check where the bridge and wake had two. The relay passes an allowlist of headers each way, so a visitor cannot vouch for itself to a host and a host cannot set cookies, prompts, CORS or storage wipes on the page's origin. The page carries a CSP, nosniff, no-referrer and COOP. BREAKING CHANGE: a page opened at a domain, behind a proxy or tunnel, needs that domain in TLS_NAMES, and the proxy must pass Host through. --- README.md | 2 +- deploy/compose.proxy.yaml | 9 +- deploy/compose.tailscale.yaml | 3 + server/src/bridge.rs | 20 +-- server/src/config.rs | 35 ++++- server/src/main.rs | 30 ++--- server/src/origin.rs | 247 ++++++++++++++++++++++++++++++++++ server/src/proxy.rs | 149 +++++++++++++++----- 8 files changed, 420 insertions(+), 75 deletions(-) create mode 100644 server/src/origin.rs diff --git a/README.md b/README.md index 3b937d1..81b2d55 100644 --- a/README.md +++ b/README.md @@ -80,7 +80,7 @@ away from home (`compose.tailscale.yaml`). |---|---|---| | `LISTEN` | `0.0.0.0:8443` | | | `TLS` | `self-signed` | `self-signed`, `off` behind a proxy, or `cert.pem,key.pem` | -| `TLS_NAMES` | | Names and addresses the page is opened at, for the self-signed certificate | +| `TLS_NAMES` | | Domains the page is opened at. It answers only to these, IP addresses and names no public DNS holds (`localhost`, `desk`, `.local`, `.home.arpa`, `.internal`); with your own certificate and none listed, to any name. The self-signed certificate covers them too | | `PUNKTFUNK_HOSTS` | | Hosts mDNS cannot find: `name=address[:port][#fingerprint]`, comma-separated | | `DISCOVER` | on | `0` turns the mDNS browse off | | `ADD_HOSTS` | on | `0` stops the page reaching a host typed by address. Set it when the page is reachable from outside your network | diff --git a/deploy/compose.proxy.yaml b/deploy/compose.proxy.yaml index 75e5ae9..a6881f5 100644 --- a/deploy/compose.proxy.yaml +++ b/deploy/compose.proxy.yaml @@ -4,9 +4,8 @@ # The page's origin is your proxy's domain: add it to each host's Browser origins (console, # Streaming, advanced), or leave that list empty to allow any page. # -# On networks that block UDP the page streams through this server. For that, the proxy must -# pass the browser's Host header through unchanged, or the stream is refused. The host then -# sees every such stream as coming from the proxy's address, so it treats it as local. +# On networks that block UDP the page streams through this server. The host then sees every +# such stream as coming from the proxy's address, so it treats it as local. services: punktfunk-web: image: git.unom.io/unom/punktfunk-client-web:latest @@ -15,6 +14,10 @@ services: environment: TLS: "off" LISTEN: 0.0.0.0:8080 + # Your proxy's domain. The page answers only to addresses, local names and the names here. + # The proxy must pass the browser's Host header through unchanged (nginx: + # `proxy_set_header Host $host;`), or the page's own requests are refused. + TLS_NAMES: play.example.com # PUNKTFUNK_HOSTS: desk=192.168.1.21 volumes: - punktfunk-web:/data diff --git a/deploy/compose.tailscale.yaml b/deploy/compose.tailscale.yaml index 469b485..d62807e 100644 --- a/deploy/compose.tailscale.yaml +++ b/deploy/compose.tailscale.yaml @@ -29,6 +29,9 @@ services: environment: TLS: "off" LISTEN: 127.0.0.1:8080 + # This machine's tailnet name. The page answers only to addresses, local names and the + # names here; `tailscale serve` passes the browser's Host header through, as it must. + TLS_NAMES: punktfunk.your-tailnet.ts.net PUNKTFUNK_HOSTS: desk=100.64.0.5 volumes: - punktfunk-web:/data diff --git a/server/src/bridge.rs b/server/src/bridge.rs index 22e2842..8cbb3fa 100644 --- a/server/src/bridge.rs +++ b/server/src/bridge.rs @@ -85,9 +85,6 @@ async fn open( req: Request, ) -> Response { let (mut parts, _) = req.into_parts(); - if !same_origin(&parts) { - return StatusCode::FORBIDDEN.into_response(); - } let addr = match addr { Ok(a) => a, Err(status) => return status.into_response(), @@ -120,21 +117,6 @@ async fn open( .on_upgrade(move |socket| session(socket, target, host, slot)) } -/// The `wake` route's rule, and an `Origin`, when sent, that names this server: a page on another -/// site that could open the bridge could drive a host it has no right to. -fn same_origin(parts: &Parts) -> bool { - if header_str(parts, "sec-fetch-site") == Some("cross-site") { - return false; - } - let Some(origin) = header_str(parts, header::ORIGIN.as_str()) else { - return true; - }; - let own = proxy::own_authority(&parts.uri, &parts.headers); - let theirs = origin.split_once("://").map(|(_, authority)| authority); - own.zip(theirs) - .is_some_and(|(a, b)| a.eq_ignore_ascii_case(b)) -} - fn header_str<'a>(parts: &'a Parts, name: &str) -> Option<&'a str> { parts.headers.get(name).and_then(|v| v.to_str().ok()) } @@ -418,7 +400,7 @@ mod tests { pin: None, }; let hosts = Hosts::new(vec![desk], &dir, true).unwrap(); - let app = crate::router(hosts, dir); + let app = crate::router(hosts, dir, None); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let at = listener.local_addr().unwrap(); tokio::spawn(async move { diff --git a/server/src/config.rs b/server/src/config.rs index 70384d9..a90ce6b 100644 --- a/server/src/config.rs +++ b/server/src/config.rs @@ -10,7 +10,8 @@ pub const MGMT_PORT: u16 = 47990; pub struct Config { pub listen: SocketAddr, pub tls: Tls, - /// Names the self-signed certificate is issued for, beyond `localhost`. + /// Names the page is opened at: the only names it answers to besides addresses and local + /// ones, and the self-signed certificate's beyond `localhost`. pub tls_names: Vec, pub hosts: Vec, /// Browse mDNS for hosts. Needs the container on the host's network to see anything. @@ -76,6 +77,20 @@ impl Config { data: get("DATA_DIR").unwrap_or_else(|| "data".into()).into(), }) } + + /// The names the page answers to besides addresses and local names. None to check with the + /// operator's certificate and no `TLS_NAMES`: a browser that trusts it refuses other names. + pub fn names(&self) -> crate::origin::Names { + if matches!(self.tls, Tls::Files { .. }) && self.tls_names.is_empty() { + return None; + } + let names = self.tls_names.iter(); + Some( + names + .map(|n| n.trim_end_matches('.').to_ascii_lowercase()) + .collect(), + ) + } } /// A switch that is on unless set: `0`, `false`, `no` or `off` turn it off. A value it does not @@ -205,4 +220,22 @@ mod tests { let off = Config::from_lookup(|k| (k == "TLS").then(|| "off".into())).unwrap(); assert!(matches!(off.tls, Tls::Off)); } + + #[test] + fn only_the_operators_certificate_alone_checks_no_name() { + let names = |tls: &str, names: &str| { + let env = [("TLS", tls), ("TLS_NAMES", names)]; + let get = |k: &str| env.iter().find(|e| e.0 == k && !e.1.is_empty()); + Config::from_lookup(|k| get(k).map(|e| e.1.into())) + .unwrap() + .names() + .map(|n| n.to_vec()) + }; + assert_eq!(names("c.pem,k.pem", ""), None); + let play = Some(vec!["play.example.com".to_string()]); + assert_eq!(names("c.pem,k.pem", "Play.Example.com."), play); + assert_eq!(names("off", "play.example.com"), play); + assert_eq!(names("off", ""), Some(Vec::new())); + assert_eq!(names("self-signed", ""), Some(Vec::new())); + } } diff --git a/server/src/main.rs b/server/src/main.rs index c2cfb36..eace969 100644 --- a/server/src/main.rs +++ b/server/src/main.rs @@ -9,11 +9,12 @@ mod bridge; mod config; mod hosts; +mod origin; mod proxy; mod tls; use axum::extract::{Path, Request, State}; -use axum::http::{header, HeaderMap, HeaderValue, StatusCode}; +use axum::http::{header, HeaderValue, StatusCode}; use axum::middleware::Next; use axum::response::{IntoResponse, Response}; use axum::routing::{any, get, post}; @@ -40,7 +41,7 @@ async fn main() -> anyhow::Result<()> { if cfg.discover { hosts::discover(hosts.clone()); } - let app = router(hosts, cfg.dist.clone()); + let app = router(hosts, cfg.dist.clone(), cfg.names()); let handle = axum_server::Handle::new(); tokio::spawn(shutdown(handle.clone())); @@ -68,7 +69,9 @@ async fn main() -> anyhow::Result<()> { Ok(()) } -pub(crate) fn router(hosts: Arc, dist: PathBuf) -> Router { +/// Every route but the static files answers only this server's own page; every response, the +/// files included, answers only the names in `names`. +pub(crate) fn router(hosts: Arc, dist: PathBuf, names: origin::Names) -> Router { Router::new() .route("/config.json", get(config_json)) .route("/h/{id}/{*rest}", any(proxy::listed)) @@ -76,10 +79,12 @@ pub(crate) fn router(hosts: Arc, dist: PathBuf) -> Router { .route("/wake/{id}", post(wake)) .route("/w/{id}", get(bridge::listed)) .route("/wa/{target}", get(bridge::typed)) + .route_layer(axum::middleware::from_fn(origin::own_page)) .with_state(hosts) .layer(Extension(Arc::new(Semaphore::new(bridge::SESSIONS)))) .fallback_service(tower_http::services::ServeDir::new(dist)) .layer(axum::middleware::from_fn(cache)) + .layer(axum::middleware::from_fn_with_state(names, origin::guard)) } /// The hosts the page lists, and whether it may reach others by address through `/a/`. `api` and @@ -102,19 +107,8 @@ async fn config_json(State(state): State>) -> impl IntoResponse { } /// Wake a listed host: a magic packet to every MAC it announced while awake, from this machine, -/// which is on the host's network where a browser cannot send one. Only this page may ask, not one -/// on another site: a cross-site request is refused. -async fn wake( - State(state): State>, - Path(id): Path, - headers: HeaderMap, -) -> StatusCode { - if headers - .get("sec-fetch-site") - .is_some_and(|v| v == "cross-site") - { - return StatusCode::FORBIDDEN; - } +/// which is on the host's network where a browser cannot send one. +async fn wake(State(state): State>, Path(id): Path) -> StatusCode { let Some(host) = state.get(&id) else { return StatusCode::NOT_FOUND; }; @@ -196,7 +190,7 @@ mod tests { }; for add in [true, false] { let hosts = crate::Hosts::new(vec![desk.clone()], &dir, add).unwrap(); - let res = crate::router(hosts, dir.clone()) + let res = crate::router(hosts, dir.clone(), None) .oneshot(Request::get("/config.json").body(Body::empty()).unwrap()) .await .unwrap(); @@ -229,7 +223,7 @@ mod tests { .unwrap() }; let status = |req: Request| { - let app = crate::router(hosts.clone(), dir.clone()); + let app = crate::router(hosts.clone(), dir.clone(), None); async move { app.oneshot(req).await.unwrap().status() } }; assert_eq!(status(wake("/wake/desk", "cross-site")).await, 403); diff --git a/server/src/origin.rs b/server/src/origin.rs new file mode 100644 index 0000000..93c8556 --- /dev/null +++ b/server/src/origin.rs @@ -0,0 +1,247 @@ +//! The page's origin answers only to its own names and its own pages. +//! +//! The device key lives in the origin, so a site that rebinds a name to this server, or a page on +//! another site that calls its routes, must get nothing back. + +use crate::proxy::own_authority; +use axum::extract::{Request, State}; +use axum::http::{header, HeaderMap, HeaderValue, StatusCode, Uri}; +use axum::middleware::Next; +use axum::response::{IntoResponse, Response}; +use std::net::{Ipv4Addr, Ipv6Addr}; +use std::sync::Arc; + +/// `TLS_NAMES`, lowercase, without a trailing dot. `None` checks no name at all. +pub type Names = Option>; + +/// The page's own scripts and wasm, nothing injected, never framed. `blob:` scripts are the audio +/// worklets; `blob:` fetches and images, the art read from a host; `data:` images, its cursor; +/// `https:`, every host the page dials and every cover it shows. Inline styles are `index.html`'s +/// ground and what the UI libraries inject. +const CSP: &str = "default-src 'self'; script-src 'self' 'wasm-unsafe-eval' blob:; \ + style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; \ + connect-src 'self' https: blob:; object-src 'none'; base-uri 'none'; \ + form-action 'none'; frame-ancestors 'none'"; + +/// Every request: the name first, then this server's word on the origin. A host's reply keeps the +/// `sandbox` CSP the relay gave it; the rest is set over whatever the host sent. +pub async fn guard(State(names): State, req: Request, next: Next) -> Response { + let name = own_authority(req.uri(), req.headers()).map(name_of); + let mut res = match name { + Some(name) if !answers(names.as_deref(), &name) => { + tracing::warn!(name, "refused a name not in TLS_NAMES"); + let say = format!("Add {name} to TLS_NAMES to open the page at that name."); + (StatusCode::MISDIRECTED_REQUEST, say).into_response() + } + _ => next.run(req).await, + }; + let h = res.headers_mut(); + h.entry(header::CONTENT_SECURITY_POLICY) + .or_insert(HeaderValue::from_static(CSP)); + for (name, value) in [ + (header::X_CONTENT_TYPE_OPTIONS, "nosniff"), + (header::REFERRER_POLICY, "no-referrer"), + ( + header::HeaderName::from_static("cross-origin-opener-policy"), + "same-origin", + ), + ] { + h.insert(name, HeaderValue::from_static(value)); + } + res +} + +/// Every route but the static files: only this server's own page, or no page at all. +pub async fn own_page(req: Request, next: Next) -> Response { + if !same_origin(req.uri(), req.headers()) { + return StatusCode::FORBIDDEN.into_response(); + } + next.run(req).await +} + +/// Refuses what a browser marks as another site's, and an `Origin` that is not this server. A +/// caller that sends neither is no browser page, and could send the right ones anyway. +fn same_origin(uri: &Uri, headers: &HeaderMap) -> bool { + let get = |name: &str| headers.get(name).and_then(|v| v.to_str().ok()); + if matches!(get("sec-fetch-site"), Some("cross-site" | "same-site")) { + return false; + } + let Some(origin) = headers.get(header::ORIGIN) else { + return true; + }; + let theirs = origin + .to_str() + .ok() + .and_then(|o| o.split_once("://")) + .map(|(_, authority)| authority); + own_authority(uri, headers) + .zip(theirs) + .is_some_and(|(a, b)| a.eq_ignore_ascii_case(b)) +} + +/// The host of `host[:port]`, lowercase, without a trailing dot. An IPv6 one keeps its brackets. +fn name_of(authority: &str) -> String { + let host = match authority.parse::() { + Ok(a) => a.host().to_owned(), + Err(_) => authority.to_owned(), + }; + host.trim_end_matches('.').to_ascii_lowercase() +} + +/// An address, a name no public DNS can hold, or one the operator listed. A rebinding site always +/// arrives under a public name of its own. +fn answers(listed: Option<&[String]>, name: &str) -> bool { + let Some(listed) = listed else { return true }; + let ip = match name.strip_prefix('[').and_then(|v| v.strip_suffix(']')) { + Some(v6) => v6.parse::().is_ok(), + None => name.parse::().is_ok(), + }; + ip || !name.contains('.') + || [".local", ".home.arpa", ".internal"] + .iter() + .any(|zone| name.ends_with(zone)) + || listed.iter().any(|n| n == name) +} + +#[cfg(test)] +mod tests { + use crate::config::Listed; + use crate::hosts::Hosts; + use axum::body::Body; + use axum::http::Request; + use std::sync::Arc; + use tower::ServiceExt; + + fn app(name: &str, names: super::Names) -> axum::Router { + let dir = std::env::temp_dir().join(format!("pf-origin-{name}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("index.html"), "").unwrap(); + let desk = Listed { + name: "desk".into(), + addr: "10.0.0.2".into(), + port: 47990, + pin: None, + }; + let hosts = Hosts::new(vec![desk], &dir, true).unwrap(); + crate::router(hosts, dir, names) + } + + async fn send(app: &axum::Router, req: Request) -> axum::response::Response { + app.clone().oneshot(req).await.unwrap() + } + + fn at(host: &str, path: &str) -> Request { + Request::get(path) + .header("host", host) + .body(Body::empty()) + .unwrap() + } + + #[tokio::test] + async fn a_rebinding_name_gets_421() { + let listed = app("names", Some(Arc::from(["play.example.com".to_string()]))); + for (host, status) in [ + ("evil.example:8443", 421), + ("play.example.com.evil.example", 421), + ("PLAY.example.com:8443", 200), + ("play.example.com.", 200), + ("192.168.1.5:8443", 200), + ("[fd00::5]:8443", 200), + ("desk.local", 200), + ("desk.home.arpa", 200), + ("box.internal:8443", 200), + ("localhost:8443", 200), + ("desk", 200), + ] { + let res = send(&listed, at(host, "/")).await; + assert_eq!(res.status(), status, "{host}"); + } + let res = send(&listed, at("evil.example", "/config.json")).await; + let body = axum::body::to_bytes(res.into_body(), 1 << 16) + .await + .unwrap(); + assert!(String::from_utf8_lossy(&body).contains("TLS_NAMES")); + // HTTP/2 names the server in the URI rather than in `Host`. + let h2 = Request::get("https://evil.example/").body(Body::empty()); + assert_eq!(send(&listed, h2.unwrap()).await.status(), 421); + + // `TLS=off` or self-signed with no names: addresses and local names only. + let none = app("no-names", Some(Arc::from([]))); + assert_eq!(send(&none, at("play.example.com", "/")).await.status(), 421); + assert_eq!(send(&none, at("desk.local", "/")).await.status(), 200); + // The operator's own certificate with no names: the browser has checked the name. + let any = app("any-name", None); + assert_eq!(send(&any, at("evil.example", "/")).await.status(), 200); + } + + #[tokio::test] + async fn another_site_reaches_no_route_but_the_page() { + let app = app("sites", Some(Arc::from([]))); + for (method, path) in [ + ("GET", "/config.json"), + ("GET", "/h/desk/api/v1/health"), + ("GET", "/a/10.0.0.9/api/v1/health"), + ("POST", "/wake/desk"), + ("GET", "/w/desk?port=1&hash=00"), + ("GET", "/wa/10.0.0.9?port=1&hash=00"), + ] { + for (name, value) in [ + ("sec-fetch-site", "cross-site"), + ("sec-fetch-site", "same-site"), + ("origin", "https://evil.example"), + ("origin", "null"), + ] { + let req = Request::builder() + .method(method) + .uri(path) + .header("host", "192.168.1.5:8443") + .header(name, value) + .body(Body::empty()) + .unwrap(); + let res = send(&app, req).await; + assert_eq!(res.status(), 403, "{method} {path} {name}: {value}"); + } + } + let own = Request::get("/config.json") + .header("host", "192.168.1.5:8443") + .header("sec-fetch-site", "same-origin") + .header("origin", "https://192.168.1.5:8443") + .body(Body::empty()) + .unwrap(); + assert_eq!(send(&app, own).await.status(), 200); + for site in ["cross-site", "same-site"] { + let page = Request::get("/") + .header("host", "192.168.1.5:8443") + .header("sec-fetch-site", site) + .body(Body::empty()) + .unwrap(); + assert_eq!(send(&app, page).await.status(), 200, "{site}"); + } + } + + #[tokio::test] + async fn the_page_carries_its_policy() { + let app = app("headers", Some(Arc::from([]))); + for req in [ + at("192.168.1.5", "/"), + at("192.168.1.5", "/config.json"), + at("evil.example", "/"), + ] { + let res = send(&app, req).await; + let h = res.headers(); + let csp = h["content-security-policy"].to_str().unwrap(); + for part in [ + "script-src 'self' 'wasm-unsafe-eval' blob:", + "frame-ancestors 'none'", + "base-uri 'none'", + "form-action 'none'", + "object-src 'none'", + ] { + assert!(csp.contains(part), "{csp}"); + } + assert_eq!(h["x-content-type-options"], "nosniff"); + assert_eq!(h["referrer-policy"], "no-referrer"); + assert_eq!(h["cross-origin-opener-policy"], "same-origin"); + } + } +} diff --git a/server/src/proxy.rs b/server/src/proxy.rs index 559f036..f505c67 100644 --- a/server/src/proxy.rs +++ b/server/src/proxy.rs @@ -181,7 +181,7 @@ async fn relay( let mut out = up .client .request(parts.method, url) - .headers(strip(parts.headers)); + .headers(only(&parts.headers, &UP)); if has_body { out = out.body(reqwest::Body::wrap_stream(body.into_data_stream())); } @@ -200,7 +200,7 @@ async fn relay( .remove(&(addr.to_string(), port, None)); } } - let (status, mut headers) = (resp.status(), strip(resp.headers().clone())); + let (status, mut headers) = (resp.status(), only(resp.headers(), &DOWN)); // A host's reply is served on the page's origin: never as a document that runs there. headers.insert( header::CONTENT_SECURITY_POLICY, @@ -273,34 +273,41 @@ fn client(pin: Option<[u8; 32]>, seen: Seen) -> anyhow::Result .build()?) } -/// Never forwarded either way: headers about one connection rather than the message, and the -/// page origin's own cookies and identity. A host's management API sets and reads no cookies. -fn strip(mut h: HeaderMap) -> HeaderMap { - for name in [ - header::CONNECTION, - header::HOST, - header::PROXY_AUTHENTICATE, - header::PROXY_AUTHORIZATION, - header::TE, - header::TRAILER, - header::TRANSFER_ENCODING, - header::UPGRADE, - header::COOKIE, - header::SET_COOKIE, - HeaderName::from_static("keep-alive"), - ] { - h.remove(name); - } - // `tailscale serve` names the tailnet user to the page's server, not to a host. - let tailscale: Vec = h - .keys() - .filter(|k| k.as_str().starts_with("tailscale-")) - .cloned() - .collect(); - for name in tailscale { - h.remove(name); +/// What crosses the relay, by name; nothing else does, either way. Going up, what the page's API +/// calls carry, as the host's own tunnel passes them, and the body's length. Coming back, what +/// describes the body and its caching: a host cannot set a cookie, a prompt, a redirect target, +/// CORS or anything else on the page's origin. +const UP: [HeaderName; 5] = [ + header::AUTHORIZATION, + header::CONTENT_TYPE, + header::ACCEPT, + header::IF_NONE_MATCH, + header::CONTENT_LENGTH, +]; +const DOWN: [HeaderName; 13] = [ + header::CONTENT_TYPE, + header::CONTENT_LENGTH, + header::CONTENT_ENCODING, + header::CONTENT_DISPOSITION, + header::CONTENT_RANGE, + header::ACCEPT_RANGES, + header::CACHE_CONTROL, + header::ETAG, + header::LAST_MODIFIED, + header::EXPIRES, + header::VARY, + header::DATE, + header::RETRY_AFTER, +]; + +fn only(from: &HeaderMap, names: &[HeaderName]) -> HeaderMap { + let mut out = HeaderMap::new(); + for name in names { + for value in from.get_all(name) { + out.append(name.clone(), value.clone()); + } } - h + out } #[cfg(test)] @@ -334,7 +341,24 @@ mod tests { "/api/v1/hop", axum::routing::get(|| async { axum::response::Redirect::to("/secret") }), ) - .route("/secret", axum::routing::get(|| async { "secret" })); + .route("/secret", axum::routing::get(|| async { "secret" })) + .route( + "/api/v1/headers", + axum::routing::get(|h: axum::http::HeaderMap| async move { + let names: Vec<_> = h.keys().map(|k| k.as_str()).collect(); + let reply = [ + ("content-type", "text/plain"), + ("etag", "\"v1\""), + ("clear-site-data", "\"storage\""), + ("www-authenticate", "Basic realm=\"desk\""), + ("alt-svc", "h3=\":443\""), + ("location", "https://elsewhere.example/"), + ("set-cookie", "a=b"), + ("access-control-allow-origin", "*"), + ]; + (reply, names.join(",")) + }), + ); let server = axum_server::from_tcp_rustls(listener, tls).unwrap(); tokio::spawn(server.serve(app.into_make_service())); (port, fp) @@ -345,7 +369,7 @@ mod tests { } async fn get(hosts: std::sync::Arc, path: &str) -> (StatusCode, String) { - let app = crate::router(hosts, std::env::temp_dir()); + let app = crate::router(hosts, std::env::temp_dir(), None); let res = app .oneshot(Request::get(path).body(Body::empty()).unwrap()) .await @@ -409,7 +433,7 @@ mod tests { (StatusCode::OK, "ok".into()) ); assert_eq!(hosts.pin_at(&format!("127.0.0.1:{port}")), Some(fp)); - let res = crate::router(hosts.clone(), std::env::temp_dir()) + let res = crate::router(hosts.clone(), std::env::temp_dir(), None) .oneshot(Request::get(&health).body(Body::empty()).unwrap()) .await .unwrap(); @@ -444,7 +468,7 @@ mod tests { .body(Body::empty()) .unwrap(); for req in [own, own_h2] { - let res = crate::router(hosts.clone(), std::env::temp_dir()) + let res = crate::router(hosts.clone(), std::env::temp_dir(), None) .oneshot(req) .await .unwrap(); @@ -456,6 +480,65 @@ mod tests { let _ = std::fs::remove_dir_all(dir); } + #[tokio::test] + async fn a_visitor_vouches_for_nothing_and_a_host_opens_nothing() { + punktfunk_core::tls::install_default_provider(); + let (port, fp) = upstream().await; + let dir = std::env::temp_dir().join(format!("pf-scrub-{}", std::process::id())); + let desk = Listed { + name: "desk".into(), + addr: "127.0.0.1".into(), + port, + pin: Some(fp), + }; + let hosts = Hosts::new(vec![desk], &dir, true).unwrap(); + let mut req = Request::get("/h/desk/api/v1/headers") + .header("host", "192.168.1.5:8443") + .header("origin", "https://192.168.1.5:8443"); + for (name, value) in [ + ("authorization", "Bearer x"), + ("accept", "application/json"), + ("if-none-match", "\"v0\""), + ("cookie", "a=b"), + ("pf-client-addr", "203.0.113.9"), + ("x-punktfunk-device", "x"), + ("x-forwarded-for", "203.0.113.9"), + ("accept-encoding", "gzip"), + ("user-agent", "visitor"), + ] { + req = req.header(name, value); + } + let res = crate::router(hosts, dir.clone(), Some([].into())) + .oneshot(req.body(Body::empty()).unwrap()) + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::OK); + let h = res.headers(); + for gone in [ + "clear-site-data", + "www-authenticate", + "alt-svc", + "location", + "set-cookie", + "access-control-allow-origin", + ] { + assert!(h.get(gone).is_none(), "{gone} reached the caller"); + } + assert_eq!(h["content-type"], "text/plain"); + assert_eq!(h["etag"], "\"v1\""); + assert_eq!(h["content-security-policy"], "sandbox"); + let body = axum::body::to_bytes(res.into_body(), 1 << 16) + .await + .unwrap(); + let seen = String::from_utf8_lossy(&body).into_owned(); + let mut seen: Vec<_> = seen.split(',').collect(); + // The upstream's own `Host`, which the HTTP client adds for HTTP/1.1, is not the visitor's. + seen.retain(|n| *n != "host"); + seen.sort_unstable(); + assert_eq!(seen, ["accept", "authorization", "if-none-match"]); + let _ = std::fs::remove_dir_all(dir); + } + #[test] fn private_means_a_home_network() { for ok in [