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