//! The bridge (spec ยง18.1): a loopback proxy that signs as the owner, for a //! program that cannot sign itself (the VS Code extension). It answers only //! requests that carry its per-run token, from its own loopback host and //! with no `Origin`, so no web page can use it, and it signs each with the //! owner's key before forwarding it to the daemon, wherever that is. use crate::client::{sign_headers, Client}; use axum::body::{Body, Bytes}; use axum::extract::{Request, State}; use axum::http::{header, StatusCode}; use axum::response::{IntoResponse, Response}; use http_body_util::{BodyExt, Full}; use std::sync::Arc; struct Bridge { upstream: Client, token: String, hosts: Vec, } /// The bridge's routes, forwarding to `upstream` (which signs) for the /// holder of `token`, at `127.0.0.1:port`. pub fn router(upstream: Client, token: String, port: u16) -> axum::Router { let b = Arc::new(Bridge { upstream, token, hosts: vec![format!("127.0.0.1:{port}"), format!("localhost:{port}")] }); axum::Router::new().fallback(forward).with_state(b) } /// A fresh random token. pub fn token() -> String { let mut b = [0u8; 32]; rand::RngCore::fill_bytes(&mut rand::rngs::OsRng, &mut b); hex::encode(b) } fn refuse(status: StatusCode, why: &str) -> Response { (status, axum::Json(serde_json::json!({ "title": why }))).into_response() } async fn forward(State(b): State>, req: Request) -> Response { let h = req.headers(); let host = h.get(header::HOST).and_then(|v| v.to_str().ok()).unwrap_or(""); if !b.hosts.iter().any(|x| x == host) || h.contains_key(header::ORIGIN) { return refuse(StatusCode::FORBIDDEN, "the bridge serves the program that started it, not web pages"); } let given = h.get(header::AUTHORIZATION).and_then(|v| v.to_str().ok()).and_then(|v| v.strip_prefix("Bearer ")).unwrap_or(""); if !subtle_eq(given.as_bytes(), b.token.as_bytes()) { return refuse(StatusCode::UNAUTHORIZED, "the bridge's token is missing or wrong"); } let (parts, body) = req.into_parts(); let body: Bytes = match body.collect().await { Ok(x) => x.to_bytes(), Err(_) => return refuse(StatusCode::BAD_REQUEST, "an unreadable body"), }; let path = parts.uri.path_and_query().map(|p| p.as_str()).unwrap_or("/").to_string(); let method = parts.method.as_str().to_string(); let mut up = hyper::Request::builder() .method(parts.method.clone()) .uri(&path) .header(header::HOST, "spectra") .header(header::CONNECTION, "close"); for k in [header::CONTENT_TYPE, header::ACCEPT, header::IF_NONE_MATCH] { if let Some(v) = parts.headers.get(&k) { up = up.header(k, v); } } if let Some(pair) = b.upstream.signer() { for (k, v) in sign_headers(pair, &format!("{method} {path}"), &body) { up = up.header(k, v); } } let up = match up.body(Full::new(body)) { Ok(r) => r, Err(_) => return refuse(StatusCode::BAD_REQUEST, "not a request the bridge can pass on"), }; match b.upstream.forward(up).await { Ok(resp) => { let (parts, incoming) = resp.into_parts(); let mut out = Response::new(Body::new(incoming)); *out.status_mut() = parts.status; for (k, v) in parts.headers.iter() { if !matches!(k.as_str(), "connection" | "transfer-encoding" | "keep-alive") { out.headers_mut().append(k, v.clone()); } } out } Err(e) => refuse(StatusCode::BAD_GATEWAY, &format!("Spectra did not answer: {e:#}")), } } /// Compare in time that does not depend on where the first difference is. fn subtle_eq(a: &[u8], b: &[u8]) -> bool { if a.len() != b.len() { return false; } a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 } #[cfg(test)] mod tests { #[test] fn tokens_are_fresh_and_compared_whole() { assert_ne!(super::token(), super::token()); assert!(super::subtle_eq(b"abc", b"abc")); assert!(!super::subtle_eq(b"abc", b"abd")); assert!(!super::subtle_eq(b"abc", b"ab")); } }