OXYGENHUB

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

129 of 147 lines run, 26 of 56 functions · run #17 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 {
31110×
    fn connect_info(stream: axum::serve::IncomingStream<'_, tokio::net::UnixListener>) -> Self {
32110×
        let cred = stream.io().peer_cred().ok();
33110×
        PeerInfo(cred.map(|c| Peer { uid: c.uid(), pid: c.pid() }))
34110×
    }
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
/// The app state: the daemon, and the origins a browser may send from.
44
#[derive(Clone)]
45
pub struct AppState {
46
    pub daemon: Arc<Daemon>,
47
    pub origins: Arc<Vec<String>>,
48
    /// The owner's browser sessions (Radar's sign-in link).
49
    pub sessions: Arc<crate::session::Sessions>,
50
}
51
52
/// Tuner's routes; the binary adds the API and Radar beside them.
5310×
pub fn router(state: AppState) -> Router {
5410×
    Router::new()
5510×
        .route("/mcp", post(mcp).get(not_allowed).delete(not_allowed))
5610×
        .route("/api/v1/ledger/events", post(owner_events))
5710×
        .with_state(state)
5810×
}
59
601×
async fn not_allowed() -> StatusCode {
611×
    StatusCode::METHOD_NOT_ALLOWED
621×
}
63
64
/// The proof the signature headers carry, for `method_path` and `body`.
6574×
pub fn proof_from(headers: &HeaderMap, method_path: &str, body: &[u8]) -> Option<Proof> {
66290×
    let get = |k: &str| headers.get(k).and_then(|v| v.to_str().ok());
6774×
    let key = get("spectra-key")?;
6872×
    let time_ms = get("spectra-time")?.parse().ok()?;
6972×
    let nonce: [u8; 16] = hex::decode(get("spectra-nonce")?).ok()?.try_into().ok()?;
7072×
    let sig_bytes = hex::decode(get("spectra-signature")?).ok()?;
7172×
    let sig = oxy_core::cbor::decode(&sig_bytes).ok().and_then(|v| oxy_core::identity::Signature::from_value(&v).ok())?;
7272×
    if sig.key.to_hex() != key {
730×
        return None;
7472×
    }
7572×
    Some(Proof { sig, method: method_path.into(), body_hash: *spectra_core::event::hash_body_plain(body), time_ms, nonce })
7674×
}
77
78
/// Refuse a browser request from a page that is not ours (spec §21.1).
7979×
pub fn origin_ok(headers: &HeaderMap, allowed: &[String]) -> bool {
8079×
    match headers.get("origin").and_then(|v| v.to_str().ok()) {
8177×
        None => true,
826×
        Some(o) => allowed.iter().any(|a| a == o),
83
    }
8479×
}
85
86
/// Authenticate a request, or the response that refuses it.
8775×
pub async fn authenticate(
8875×
    state: &AppState,
8975×
    peer: PeerInfo,
9075×
    headers: &HeaderMap,
9175×
    method_path: &str,
9275×
    body: &[u8],
9375×
) -> Result<Caller, Response> {
9475×
    if !origin_ok(headers, &state.origins) {
951×
        return Err((
961×
            StatusCode::FORBIDDEN,
971×
            axum::Json(protocol::error(&Json::Null, protocol::INVALID_REQUEST, "this origin may not call Spectra")),
981×
        )
991×
            .into_response());
10074×
    }
10174×
    let proof = proof_from(headers, method_path, body);
10274×
    state.daemon.authenticate(proof.as_ref(), method_path, body, peer.0).await.map_err(|why| {
1034×
        tracing::info!(%why, "refused a request");
104
        // The reason concerns the caller's own key, so the caller is told it:
105
        // an agent whose delegation expired must be able to say so.
1064×
        (
1074×
            StatusCode::UNAUTHORIZED,
1084×
            axum::Json(protocol::error(&Json::Null, protocol::UNAUTHENTICATED, &format!("not authenticated: {why}"))),
1094×
        )
1104×
            .into_response()
1114×
    })
11275×
}
113
11444×
async fn mcp(State(state): State<AppState>, ConnectInfo(peer): ConnectInfo<PeerInfo>, headers: HeaderMap, body: Bytes) -> Response {
11544×
    let caller = match authenticate(&state, peer, &headers, "POST /mcp", &body).await {
11640×
        Ok(c) => c,
1174×
        Err(r) => return r,
118
    };
11940×
    let req: Json = match serde_json::from_slice(&body) {
12040×
        Ok(v) => v,
1210×
        Err(e) => {
1220×
            return (StatusCode::BAD_REQUEST, axum::Json(protocol::error(&Json::Null, protocol::PARSE_ERROR, &format!("not JSON: {e}"))))
1230×
                .into_response()
124
        }
125
    };
12640×
    let new_session = req.pointer("/params/arguments/new_session").and_then(Json::as_bool).unwrap_or(false)
1270×
        && req.pointer("/params/name").and_then(Json::as_str) == Some("brief");
12840×
    let session = state.daemon.touch(&caller.principal, new_session).await;
12940×
    let h = Headers {
13040×
        version: headers.get("mcp-protocol-version").and_then(|v| v.to_str().ok()),
13140×
        method: headers.get("mcp-method").and_then(|v| v.to_str().ok()),
13240×
        name: headers.get("mcp-name").and_then(|v| v.to_str().ok()),
133
    };
13440×
    let version = h.version.unwrap_or("2025-03-26").to_string();
13540×
    let ctx = Ctx { daemon: state.daemon.clone(), caller, session };
13640×
    let meta = meta(&ctx).await;
13740×
    match protocol::handle(&ctx, &h, req, meta.clone()).await {
13832×
        Reply::Json(status, v) => (StatusCode::from_u16(status).unwrap_or(StatusCode::OK), axum::Json(v)).into_response(),
1392×
        Reply::Accepted => StatusCode::ACCEPTED.into_response(),
1406×
        Reply::Stream(id, tool, args) => {
1416×
            let fut = async move {
1426×
                let out = crate::tools::invoke(&ctx, tool, args).await;
1436×
                let meta = crate::http::meta(&ctx).await;
1446×
                let msg = protocol::stream_result(&id, &version, &out, meta);
1456×
                Ok::<_, Infallible>(SseEvent::default().event("message").data(msg.to_string()))
1466×
            };
1476×
            sse(stream::once(fut).boxed())
148
        }
1490×
        Reply::Listen(id, sub) => {
1500×
            let ack = json!({ "jsonrpc": "2.0", "method": "notifications/subscriptions/acknowledged", "params": { "_meta": { "io.modelcontextprotocol/subscriptionId": sub } } });
1510×
            let _ = id;
1520×
            let first = stream::once(async move { Ok::<_, Infallible>(SseEvent::default().event("message").data(ack.to_string())) });
153
            // Spectra's tool list never changes while it runs: the stream
154
            // stays open, quiet but for keep-alives, until the client closes it.
1550×
            sse(first.chain(stream::pending()).boxed())
156
        }
157
    }
15844×
}
159
1606×
fn sse(s: futures::stream::BoxStream<'static, Result<SseEvent, Infallible>>) -> Response {
1616×
    let mut r = Sse::new(s).keep_alive(KeepAlive::new().interval(Duration::from_secs(15)).text("")).into_response();
1626×
    r.headers_mut().insert("x-accel-buffering", "no".parse().unwrap());
1636×
    r
1646×
}
165
166
/// `_meta` on every result (spec §15.2): the rules version, the session and
167
/// the unread count.
16868×
pub async fn meta(ctx: &Ctx) -> Json {
16968×
    let mut m = serde_json::Map::new();
17068×
    if let Ok(r) = spectra_core::rules::compile(&ctx.daemon.data) {
17168×
        m.insert("spectra/rules_version".into(), json!(r.version));
17268×
    }
17368×
    if let Some(s) = &ctx.session {
17468×
        m.insert("spectra/session".into(), json!(s));
17568×
    }
17668×
    if let Ok(n) = spectra_core::conversation::unread(&ctx.daemon.ledger, &ctx.caller.principal.actor()).await {
17768×
        m.insert("spectra/inbox_unread".into(), json!(n));
17868×
    }
17968×
    Json::Object(m)
18068×
}
181
182
/// `POST /api/v1/ledger/events`: the owner's CLI hands over events it
183
/// signed over their payload, so `agent add` and `project add` work while
184
/// the daemon holds the ledger (spec §8.5, "One writer").
1852×
async fn owner_events(
1862×
    State(state): State<AppState>,
1872×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
1882×
    headers: HeaderMap,
1892×
    body: Bytes,
1902×
) -> Response {
1912×
    let caller = match authenticate(&state, peer, &headers, "POST /api/v1/ledger/events", &body).await {
1922×
        Ok(c) => c,
1930×
        Err(r) => return r,
194
    };
1952×
    if !matches!(caller.principal, Principal::Owner { .. }) {
1960×
        return (StatusCode::FORBIDDEN, axum::Json(json!({ "title": "only the owner hands events to the daemon" }))).into_response();
1972×
    }
1982×
    let events: Vec<WireEvent> = match serde_json::from_slice(&body) {
1992×
        Ok(v) => v,
2000×
        Err(e) => return (StatusCode::BAD_REQUEST, axum::Json(json!({ "title": format!("not a list of events: {e}") }))).into_response(),
201
    };
2022×
    match state.daemon.accept_owner_events(events).await {
2032×
        Ok(seqs) => axum::Json(json!({ "appended": seqs })).into_response(),
2040×
        Err(e) => (StatusCode::UNPROCESSABLE_ENTITY, axum::Json(json!({ "title": e.to_string() }))).into_response(),
205
    }
2062×
}