OXYGENHUB

Coverage / crates/spectra-mcp/src/http.rs 88.2%

150 of 170 lines run, 30 of 64 functions · run #18 on main · run missed

1
//! Tuner over HTTP (spec §15.1, §8.5, §21.1): `POST /mcp` on the Unix
2
//! socket and the loopback port, every request signed and checked before
3
//! anything else; the peer's uid read from the socket; `Origin` checked
4
//! against DNS rebinding.
5
6
use crate::protocol::{self, Headers, Reply};
7
use crate::tools::Ctx;
8
use axum::body::Bytes;
9
use axum::extract::connect_info::{ConnectInfo, Connected};
10
use axum::extract::State;
11
use axum::http::{HeaderMap, StatusCode};
12
use axum::response::sse::{Event as SseEvent, KeepAlive, Sse};
13
use axum::response::{IntoResponse, Response};
14
use axum::routing::post;
15
use axum::Router;
16
use futures::stream::{self, StreamExt};
17
use serde_json::{json, Value as Json};
18
use spectra_core::authn::Caller;
19
use spectra_core::daemon::{Daemon, Peer, WireEvent};
20
use spectra_core::principals::Principal;
21
use spectra_core::proof::Proof;
22
use std::convert::Infallible;
23
use std::sync::Arc;
24
use std::time::Duration;
25
26
/// Who is on the other end of a connection: a Unix peer, or TCP.
27
#[derive(Clone, Copy, Debug)]
28
pub struct PeerInfo(pub Option<Peer>);
29
30
impl Connected<axum::serve::IncomingStream<'_, tokio::net::UnixListener>> for PeerInfo {
31111×
    fn connect_info(stream: axum::serve::IncomingStream<'_, tokio::net::UnixListener>) -> Self {
32111×
        let cred = stream.io().peer_cred().ok();
33111×
        PeerInfo(cred.map(|c| Peer { uid: c.uid(), pid: c.pid() }))
34111×
    }
35
}
36
37
impl Connected<axum::serve::IncomingStream<'_, tokio::net::TcpListener>> for PeerInfo {
380×
    fn connect_info(_: axum::serve::IncomingStream<'_, tokio::net::TcpListener>) -> Self {
390×
        PeerInfo(None)
400×
    }
41
}
42
43
impl Connected<axum::serve::IncomingStream<'_, crate::tls::TlsListener>> for PeerInfo {
445×
    fn connect_info(_: axum::serve::IncomingStream<'_, crate::tls::TlsListener>) -> Self {
455×
        PeerInfo(None)
465×
    }
47
}
48
49
/// The app state: the daemon, and the origins a browser may send from.
50
#[derive(Clone)]
51
pub struct AppState {
52
    pub daemon: Arc<Daemon>,
53
    pub origins: Arc<Vec<String>>,
54
    /// The owner's browser sessions (Radar's sign-in link).
55
    pub sessions: Arc<crate::session::Sessions>,
56
}
57
58
/// Tuner's routes; the binary adds the API and Radar beside them.
5913×
pub fn router(state: AppState) -> Router {
6013×
    Router::new()
6113×
        .route("/mcp", post(mcp).get(not_allowed).delete(not_allowed))
6213×
        .route("/api/v1/ledger/events", post(owner_events))
6313×
        .route("/api/v1/instance", axum::routing::get(instance))
6413×
        .with_state(state)
6513×
}
66
67
/// `GET /api/v1/instance`, unauthenticated (spec §8.6): who this Spectra
68
/// is, whose it is, and the instance key's word for its TLS certificate, so
69
/// a client can decide whether to trust it before it signs anything.
703×
async fn instance(State(state): State<AppState>) -> Response {
713×
    let (instance, owner) = {
723×
        let p = state.daemon.principals.read().await;
733×
        (p.instance().cloned(), p.owner().map(|o| o.hash().to_hex()))
74
    };
753×
    let Some(instance) = instance else {
760×
        return (StatusCode::SERVICE_UNAVAILABLE, axum::Json(json!({ "title": "this Spectra has no instance key" }))).into_response();
77
    };
783×
    let tls = match crate::instance::latest_tls(&state.daemon.ledger).await {
793×
        Ok(Some(e)) => json!({ "payload": e.json(), "proof": e.auth.proof.as_ref().map(hex::encode) }),
800×
        _ => Json::Null,
81
    };
823×
    axum::Json(json!({
833×
        "name": instance.name,
843×
        "instance": spectra_core::principals::identity_payload(&instance),
853×
        "owner": owner,
863×
        "tls": tls,
873×
    }))
883×
    .into_response()
893×
}
90
911×
async fn not_allowed() -> StatusCode {
921×
    StatusCode::METHOD_NOT_ALLOWED
931×
}
94
95
/// The proof the signature headers carry, for `method_path` and `body`.
9677×
pub fn proof_from(headers: &HeaderMap, method_path: &str, body: &[u8]) -> Option<Proof> {
97302×
    let get = |k: &str| headers.get(k).and_then(|v| v.to_str().ok());
9877×
    let key = get("spectra-key")?;
9975×
    let time_ms = get("spectra-time")?.parse().ok()?;
10075×
    let nonce: [u8; 16] = hex::decode(get("spectra-nonce")?).ok()?.try_into().ok()?;
10175×
    let sig_bytes = hex::decode(get("spectra-signature")?).ok()?;
10275×
    let sig = oxy_core::cbor::decode(&sig_bytes).ok().and_then(|v| oxy_core::identity::Signature::from_value(&v).ok())?;
10375×
    if sig.key.to_hex() != key {
1040×
        return None;
10575×
    }
10675×
    Some(Proof { sig, method: method_path.into(), body_hash: *spectra_core::event::hash_body_plain(body), time_ms, nonce })
10777×
}
108
109
/// Refuse a browser request from a page that is not ours (spec §21.1).
11082×
pub fn origin_ok(headers: &HeaderMap, allowed: &[String]) -> bool {
11182×
    match headers.get("origin").and_then(|v| v.to_str().ok()) {
11280×
        None => true,
1136×
        Some(o) => allowed.iter().any(|a| a == o),
114
    }
11582×
}
116
117
/// Authenticate a request, or the response that refuses it.
11878×
pub async fn authenticate(
11978×
    state: &AppState,
12078×
    peer: PeerInfo,
12178×
    headers: &HeaderMap,
12278×
    method_path: &str,
12378×
    body: &[u8],
12478×
) -> Result<Caller, Response> {
12578×
    if !origin_ok(headers, &state.origins) {
1261×
        return Err((
1271×
            StatusCode::FORBIDDEN,
1281×
            axum::Json(protocol::error(&Json::Null, protocol::INVALID_REQUEST, "this origin may not call Spectra")),
1291×
        )
1301×
            .into_response());
13177×
    }
13277×
    let proof = proof_from(headers, method_path, body);
13377×
    state.daemon.authenticate(proof.as_ref(), method_path, body, peer.0).await.map_err(|why| {
1345×
        tracing::info!(%why, "refused a request");
135
        // The reason concerns the caller's own key, so the caller is told it:
136
        // an agent whose delegation expired must be able to say so.
1375×
        (
1385×
            StatusCode::UNAUTHORIZED,
1395×
            axum::Json(protocol::error(&Json::Null, protocol::UNAUTHENTICATED, &format!("not authenticated: {why}"))),
1405×
        )
1415×
            .into_response()
1425×
    })
14378×
}
144
14547×
async fn mcp(State(state): State<AppState>, ConnectInfo(peer): ConnectInfo<PeerInfo>, headers: HeaderMap, body: Bytes) -> Response {
14647×
    let caller = match authenticate(&state, peer, &headers, "POST /mcp", &body).await {
14742×
        Ok(c) => c,
1485×
        Err(r) => return r,
149
    };
15042×
    let req: Json = match serde_json::from_slice(&body) {
15142×
        Ok(v) => v,
1520×
        Err(e) => {
1530×
            return (StatusCode::BAD_REQUEST, axum::Json(protocol::error(&Json::Null, protocol::PARSE_ERROR, &format!("not JSON: {e}"))))
1540×
                .into_response()
155
        }
156
    };
15742×
    let new_session = req.pointer("/params/arguments/new_session").and_then(Json::as_bool).unwrap_or(false)
1580×
        && req.pointer("/params/name").and_then(Json::as_str) == Some("brief");
15942×
    let session = state.daemon.touch(&caller.principal, new_session).await;
16042×
    let h = Headers {
16142×
        version: headers.get("mcp-protocol-version").and_then(|v| v.to_str().ok()),
16242×
        method: headers.get("mcp-method").and_then(|v| v.to_str().ok()),
16342×
        name: headers.get("mcp-name").and_then(|v| v.to_str().ok()),
164
    };
16542×
    let version = h.version.unwrap_or("2025-03-26").to_string();
16642×
    let ctx = Ctx { daemon: state.daemon.clone(), caller, session };
16742×
    let meta = meta(&ctx).await;
16842×
    match protocol::handle(&ctx, &h, req, meta.clone()).await {
16934×
        Reply::Json(status, v) => (StatusCode::from_u16(status).unwrap_or(StatusCode::OK), axum::Json(v)).into_response(),
1702×
        Reply::Accepted => StatusCode::ACCEPTED.into_response(),
1716×
        Reply::Stream(id, tool, args) => {
1726×
            let fut = async move {
1736×
                let out = crate::tools::invoke(&ctx, tool, args).await;
1746×
                let meta = crate::http::meta(&ctx).await;
1756×
                let msg = protocol::stream_result(&id, &version, &out, meta);
1766×
                Ok::<_, Infallible>(SseEvent::default().event("message").data(msg.to_string()))
1776×
            };
1786×
            sse(stream::once(fut).boxed())
179
        }
1800×
        Reply::Listen(id, sub) => {
1810×
            let ack = json!({ "jsonrpc": "2.0", "method": "notifications/subscriptions/acknowledged", "params": { "_meta": { "io.modelcontextprotocol/subscriptionId": sub } } });
1820×
            let _ = id;
1830×
            let first = stream::once(async move { Ok::<_, Infallible>(SseEvent::default().event("message").data(ack.to_string())) });
184
            // Spectra's tool list never changes while it runs: the stream
185
            // stays open, quiet but for keep-alives, until the client closes it.
1860×
            sse(first.chain(stream::pending()).boxed())
187
        }
188
    }
18947×
}
190
1916×
fn sse(s: futures::stream::BoxStream<'static, Result<SseEvent, Infallible>>) -> Response {
1926×
    let mut r = Sse::new(s).keep_alive(KeepAlive::new().interval(Duration::from_secs(15)).text("")).into_response();
1936×
    r.headers_mut().insert("x-accel-buffering", "no".parse().unwrap());
1946×
    r
1956×
}
196
197
/// `_meta` on every result (spec §15.2): the rules version, the session and
198
/// the unread count.
19971×
pub async fn meta(ctx: &Ctx) -> Json {
20071×
    let mut m = serde_json::Map::new();
20171×
    if let Ok(r) = spectra_core::rules::compile(&ctx.daemon.data) {
20271×
        m.insert("spectra/rules_version".into(), json!(r.version));
20371×
    }
20471×
    if let Some(s) = &ctx.session {
20571×
        m.insert("spectra/session".into(), json!(s));
20671×
    }
20771×
    if let Ok(n) = spectra_core::conversation::unread(&ctx.daemon.ledger, &ctx.caller.principal.actor()).await {
20871×
        m.insert("spectra/inbox_unread".into(), json!(n));
20971×
    }
21071×
    Json::Object(m)
21171×
}
212
213
/// `POST /api/v1/ledger/events`: the owner's CLI hands over events it
214
/// signed over their payload, so `agent add` and `project add` work while
215
/// the daemon holds the ledger (spec §8.5, "One writer").
2162×
async fn owner_events(
2172×
    State(state): State<AppState>,
2182×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
2192×
    headers: HeaderMap,
2202×
    body: Bytes,
2212×
) -> Response {
2222×
    let caller = match authenticate(&state, peer, &headers, "POST /api/v1/ledger/events", &body).await {
2232×
        Ok(c) => c,
2240×
        Err(r) => return r,
225
    };
2262×
    if !matches!(caller.principal, Principal::Owner { .. }) {
2270×
        return (StatusCode::FORBIDDEN, axum::Json(json!({ "title": "only the owner hands events to the daemon" }))).into_response();
2282×
    }
2292×
    let events: Vec<WireEvent> = match serde_json::from_slice(&body) {
2302×
        Ok(v) => v,
2310×
        Err(e) => return (StatusCode::BAD_REQUEST, axum::Json(json!({ "title": format!("not a list of events: {e}") }))).into_response(),
232
    };
2332×
    match state.daemon.accept_owner_events(events).await {
2342×
        Ok(seqs) => axum::Json(json!({ "appended": seqs })).into_response(),
2350×
        Err(e) => (StatusCode::UNPROCESSABLE_ENTITY, axum::Json(json!({ "title": e.to_string() }))).into_response(),
236
    }
2372×
}