| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | |
|
| 6 | |
|
| 7 | | use crate::client::{sign_headers, Client}; |
| 8 | | use axum::body::{Body, Bytes}; |
| 9 | | use axum::extract::{Request, State}; |
| 10 | | use axum::http::{header, StatusCode}; |
| 11 | | use axum::response::{IntoResponse, Response}; |
| 12 | | use http_body_util::{BodyExt, Full}; |
| 13 | | use std::sync::Arc; |
| 14 | |
|
| 15 | | struct Bridge { |
| 16 | | upstream: Client, |
| 17 | | token: String, |
| 18 | | hosts: Vec<String>, |
| 19 | | } |
| 20 | |
|
| 21 | |
|
| 22 | |
|
| 23 | 1× | pub fn router(upstream: Client, token: String, port: u16) -> axum::Router { |
| 24 | 1× | let b = Arc::new(Bridge { upstream, token, hosts: vec![format!("127.0.0.1:{port}"), format!("localhost:{port}")] }); |
| 25 | 1× | axum::Router::new().fallback(forward).with_state(b) |
| 26 | 1× | } |
| 27 | |
|
| 28 | |
|
| 29 | 3× | pub fn token() -> String { |
| 30 | 3× | let mut b = [0u8; 32]; |
| 31 | 3× | rand::RngCore::fill_bytes(&mut rand::rngs::OsRng, &mut b); |
| 32 | 3× | hex::encode(b) |
| 33 | 3× | } |
| 34 | |
|
| 35 | 4× | fn refuse(status: StatusCode, why: &str) -> Response { |
| 36 | 4× | (status, axum::Json(serde_json::json!({ "title": why }))).into_response() |
| 37 | 4× | } |
| 38 | |
|
| 39 | 6× | async fn forward(State(b): State<Arc<Bridge>>, req: Request) -> Response { |
| 40 | 6× | let h = req.headers(); |
| 41 | 6× | let host = h.get(header::HOST).and_then(|v| v.to_str().ok()).unwrap_or(""); |
| 42 | 7× | if !b.hosts.iter().any(|x| x == host) || h.contains_key(header::ORIGIN) { |
| 43 | 2× | return refuse(StatusCode::FORBIDDEN, "the bridge serves the program that started it, not web pages"); |
| 44 | 4× | } |
| 45 | 4× | let given = h.get(header::AUTHORIZATION).and_then(|v| v.to_str().ok()).and_then(|v| v.strip_prefix("Bearer ")).unwrap_or(""); |
| 46 | 4× | if !subtle_eq(given.as_bytes(), b.token.as_bytes()) { |
| 47 | 2× | return refuse(StatusCode::UNAUTHORIZED, "the bridge's token is missing or wrong"); |
| 48 | 2× | } |
| 49 | 2× | let (parts, body) = req.into_parts(); |
| 50 | 2× | let body: Bytes = match body.collect().await { |
| 51 | 2× | Ok(x) => x.to_bytes(), |
| 52 | 0× | Err(_) => return refuse(StatusCode::BAD_REQUEST, "an unreadable body"), |
| 53 | | }; |
| 54 | 2× | let path = parts.uri.path_and_query().map(|p| p.as_str()).unwrap_or("/").to_string(); |
| 55 | 2× | let method = parts.method.as_str().to_string(); |
| 56 | 2× | let mut up = hyper::Request::builder() |
| 57 | 2× | .method(parts.method.clone()) |
| 58 | 2× | .uri(&path) |
| 59 | 2× | .header(header::HOST, "spectra") |
| 60 | 2× | .header(header::CONNECTION, "close"); |
| 61 | 6× | for k in [header::CONTENT_TYPE, header::ACCEPT, header::IF_NONE_MATCH] { |
| 62 | 6× | if let Some(v) = parts.headers.get(&k) { |
| 63 | 1× | up = up.header(k, v); |
| 64 | 5× | } |
| 65 | | } |
| 66 | 2× | if let Some(pair) = b.upstream.signer() { |
| 67 | 8× | for (k, v) in sign_headers(pair, &format!("{method} {path}"), &body) { |
| 68 | 8× | up = up.header(k, v); |
| 69 | 8× | } |
| 70 | 0× | } |
| 71 | 2× | let up = match up.body(Full::new(body)) { |
| 72 | 2× | Ok(r) => r, |
| 73 | 0× | Err(_) => return refuse(StatusCode::BAD_REQUEST, "not a request the bridge can pass on"), |
| 74 | | }; |
| 75 | 2× | match b.upstream.forward(up).await { |
| 76 | 2× | Ok(resp) => { |
| 77 | 2× | let (parts, incoming) = resp.into_parts(); |
| 78 | 2× | let mut out = Response::new(Body::new(incoming)); |
| 79 | 2× | *out.status_mut() = parts.status; |
| 80 | 9× | for (k, v) in parts.headers.iter() { |
| 81 | 9× | if !matches!(k.as_str(), "connection" | "transfer-encoding" | "keep-alive") { |
| 82 | 7× | out.headers_mut().append(k, v.clone()); |
| 83 | 7× | } |
| 84 | | } |
| 85 | 2× | out |
| 86 | | } |
| 87 | 0× | Err(e) => refuse(StatusCode::BAD_GATEWAY, &format!("Spectra did not answer: {e:#}")), |
| 88 | | } |
| 89 | 6× | } |
| 90 | |
|
| 91 | |
|
| 92 | 7× | fn subtle_eq(a: &[u8], b: &[u8]) -> bool { |
| 93 | 7× | if a.len() != b.len() { |
| 94 | 3× | return false; |
| 95 | 4× | } |
| 96 | 134× | a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 |
| 97 | 7× | } |
| 98 | |
|
| 99 | | #[cfg(test)] |
| 100 | | mod tests { |
| 101 | | #[test] |
| 102 | 1× | fn tokens_are_fresh_and_compared_whole() { |
| 103 | 1× | assert_ne!(super::token(), super::token()); |
| 104 | 1× | assert!(super::subtle_eq(b"abc", b"abc")); |
| 105 | 1× | assert!(!super::subtle_eq(b"abc", b"abd")); |
| 106 | 1× | assert!(!super::subtle_eq(b"abc", b"ab")); |
| 107 | 1× | } |
| 108 | | } |