OXYGENHUB

Coverage / crates/spectra-mcp/src/bridge.rs 94.7%

72 of 76 lines run, 16 of 25 functions · run #36 on main · run missed

1
//! The bridge (spec §18.1): a loopback proxy that signs as the owner, for a
2
//! program that cannot sign itself (the VS Code extension). It answers only
3
//! requests that carry its per-run token, from its own loopback host and
4
//! with no `Origin`, so no web page can use it, and it signs each with the
5
//! owner's key before forwarding it to the daemon, wherever that is.
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
/// The bridge's routes, forwarding to `upstream` (which signs) for the
22
/// holder of `token`, at `127.0.0.1:port`.
231×
pub fn router(upstream: Client, token: String, port: u16) -> axum::Router {
241×
    let b = Arc::new(Bridge { upstream, token, hosts: vec![format!("127.0.0.1:{port}"), format!("localhost:{port}")] });
251×
    axum::Router::new().fallback(forward).with_state(b)
261×
}
27
28
/// A fresh random token.
293×
pub fn token() -> String {
303×
    let mut b = [0u8; 32];
313×
    rand::RngCore::fill_bytes(&mut rand::rngs::OsRng, &mut b);
323×
    hex::encode(b)
333×
}
34
354×
fn refuse(status: StatusCode, why: &str) -> Response {
364×
    (status, axum::Json(serde_json::json!({ "title": why }))).into_response()
374×
}
38
396×
async fn forward(State(b): State<Arc<Bridge>>, req: Request) -> Response {
406×
    let h = req.headers();
416×
    let host = h.get(header::HOST).and_then(|v| v.to_str().ok()).unwrap_or("");
427×
    if !b.hosts.iter().any(|x| x == host) || h.contains_key(header::ORIGIN) {
432×
        return refuse(StatusCode::FORBIDDEN, "the bridge serves the program that started it, not web pages");
444×
    }
454×
    let given = h.get(header::AUTHORIZATION).and_then(|v| v.to_str().ok()).and_then(|v| v.strip_prefix("Bearer ")).unwrap_or("");
464×
    if !subtle_eq(given.as_bytes(), b.token.as_bytes()) {
472×
        return refuse(StatusCode::UNAUTHORIZED, "the bridge's token is missing or wrong");
482×
    }
492×
    let (parts, body) = req.into_parts();
502×
    let body: Bytes = match body.collect().await {
512×
        Ok(x) => x.to_bytes(),
520×
        Err(_) => return refuse(StatusCode::BAD_REQUEST, "an unreadable body"),
53
    };
542×
    let path = parts.uri.path_and_query().map(|p| p.as_str()).unwrap_or("/").to_string();
552×
    let method = parts.method.as_str().to_string();
562×
    let mut up = hyper::Request::builder()
572×
        .method(parts.method.clone())
582×
        .uri(&path)
592×
        .header(header::HOST, "spectra")
602×
        .header(header::CONNECTION, "close");
616×
    for k in [header::CONTENT_TYPE, header::ACCEPT, header::IF_NONE_MATCH] {
626×
        if let Some(v) = parts.headers.get(&k) {
631×
            up = up.header(k, v);
645×
        }
65
    }
662×
    if let Some(pair) = b.upstream.signer() {
678×
        for (k, v) in sign_headers(pair, &format!("{method} {path}"), &body) {
688×
            up = up.header(k, v);
698×
        }
700×
    }
712×
    let up = match up.body(Full::new(body)) {
722×
        Ok(r) => r,
730×
        Err(_) => return refuse(StatusCode::BAD_REQUEST, "not a request the bridge can pass on"),
74
    };
752×
    match b.upstream.forward(up).await {
762×
        Ok(resp) => {
772×
            let (parts, incoming) = resp.into_parts();
782×
            let mut out = Response::new(Body::new(incoming));
792×
            *out.status_mut() = parts.status;
809×
            for (k, v) in parts.headers.iter() {
819×
                if !matches!(k.as_str(), "connection" | "transfer-encoding" | "keep-alive") {
827×
                    out.headers_mut().append(k, v.clone());
837×
                }
84
            }
852×
            out
86
        }
870×
        Err(e) => refuse(StatusCode::BAD_GATEWAY, &format!("Spectra did not answer: {e:#}")),
88
    }
896×
}
90
91
/// Compare in time that does not depend on where the first difference is.
927×
fn subtle_eq(a: &[u8], b: &[u8]) -> bool {
937×
    if a.len() != b.len() {
943×
        return false;
954×
    }
96134×
    a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
977×
}
98
99
#[cfg(test)]
100
mod tests {
101
    #[test]
1021×
    fn tokens_are_fresh_and_compared_whole() {
1031×
        assert_ne!(super::token(), super::token());
1041×
        assert!(super::subtle_eq(b"abc", b"abc"));
1051×
        assert!(!super::subtle_eq(b"abc", b"abd"));
1061×
        assert!(!super::subtle_eq(b"abc", b"ab"));
1071×
    }
108
}