OXYGENHUB

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

129 of 147 lines run, 26 of 56 functions · run #11 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 {
3154×
    fn connect_info(stream: axum::serve::IncomingStream<'_, tokio::net::UnixListener>) -> Self {
3254×
        let cred = stream.io().peer_cred().ok();
3354×
        PeerInfo(cred.map(|c| Peer { uid: c.uid(), pid: c.pid() }))
3454×
    }
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
}
49
50
/// Tuner's routes; the binary adds the API and Radar beside them.
517×
pub fn router(state: AppState) -> Router {
527×
    Router::new()
537×
        .route("/mcp", post(mcp).get(not_allowed).delete(not_allowed))
547×
        .route("/api/v1/ledger/events", post(owner_events))
557×
        .with_state(state)
567×
}
57
581×
async fn not_allowed() -> StatusCode {
591×
    StatusCode::METHOD_NOT_ALLOWED
601×
}
61
62
/// The proof the signature headers carry, for `method_path` and `body`.
6343×
pub fn proof_from(headers: &HeaderMap, method_path: &str, body: &[u8]) -> Option<Proof> {
64169×
    let get = |k: &str| headers.get(k).and_then(|v| v.to_str().ok());
6543×
    let key = get("spectra-key")?;
6642×
    let time_ms = get("spectra-time")?.parse().ok()?;
6742×
    let nonce: [u8; 16] = hex::decode(get("spectra-nonce")?).ok()?.try_into().ok()?;
6842×
    let sig_bytes = hex::decode(get("spectra-signature")?).ok()?;
6942×
    let sig = oxy_core::cbor::decode(&sig_bytes).ok().and_then(|v| oxy_core::identity::Signature::from_value(&v).ok())?;
7042×
    if sig.key.to_hex() != key {
710×
        return None;
7242×
    }
7342×
    Some(Proof { sig, method: method_path.into(), body_hash: *spectra_core::event::hash_body_plain(body), time_ms, nonce })
7443×
}
75
76
/// Refuse a browser request from a page that is not ours (spec §21.1).
7744×
pub fn origin_ok(headers: &HeaderMap, allowed: &[String]) -> bool {
7844×
    match headers.get("origin").and_then(|v| v.to_str().ok()) {
7943×
        None => true,
803×
        Some(o) => allowed.iter().any(|a| a == o),
81
    }
8244×
}
83
84
/// Authenticate a request, or the response that refuses it.
8544×
pub async fn authenticate(
8644×
    state: &AppState,
8744×
    peer: PeerInfo,
8844×
    headers: &HeaderMap,
8944×
    method_path: &str,
9044×
    body: &[u8],
9144×
) -> Result<Caller, Response> {
9244×
    if !origin_ok(headers, &state.origins) {
931×
        return Err((
941×
            StatusCode::FORBIDDEN,
951×
            axum::Json(protocol::error(&Json::Null, protocol::INVALID_REQUEST, "this origin may not call Spectra")),
961×
        )
971×
            .into_response());
9843×
    }
9943×
    let proof = proof_from(headers, method_path, body);
10043×
    state.daemon.authenticate(proof.as_ref(), method_path, body, peer.0).await.map_err(|why| {
1013×
        tracing::info!(%why, "refused a request");
102
        // The reason concerns the caller's own key, so the caller is told it:
103
        // an agent whose delegation expired must be able to say so.
1043×
        (
1053×
            StatusCode::UNAUTHORIZED,
1063×
            axum::Json(protocol::error(&Json::Null, protocol::UNAUTHENTICATED, &format!("not authenticated: {why}"))),
1073×
        )
1083×
            .into_response()
1093×
    })
11044×
}
111
11242×
async fn mcp(State(state): State<AppState>, ConnectInfo(peer): ConnectInfo<PeerInfo>, headers: HeaderMap, body: Bytes) -> Response {
11342×
    let caller = match authenticate(&state, peer, &headers, "POST /mcp", &body).await {
11438×
        Ok(c) => c,
1154×
        Err(r) => return r,
116
    };
11738×
    let req: Json = match serde_json::from_slice(&body) {
11838×
        Ok(v) => v,
1190×
        Err(e) => {
1200×
            return (StatusCode::BAD_REQUEST, axum::Json(protocol::error(&Json::Null, protocol::PARSE_ERROR, &format!("not JSON: {e}"))))
1210×
                .into_response()
122
        }
123
    };
12438×
    let new_session = req.pointer("/params/arguments/new_session").and_then(Json::as_bool).unwrap_or(false)
1250×
        && req.pointer("/params/name").and_then(Json::as_str) == Some("brief");
12638×
    let session = state.daemon.touch(&caller.principal, new_session).await;
12738×
    let h = Headers {
12838×
        version: headers.get("mcp-protocol-version").and_then(|v| v.to_str().ok()),
12938×
        method: headers.get("mcp-method").and_then(|v| v.to_str().ok()),
13038×
        name: headers.get("mcp-name").and_then(|v| v.to_str().ok()),
131
    };
13238×
    let version = h.version.unwrap_or("2025-03-26").to_string();
13338×
    let ctx = Ctx { daemon: state.daemon.clone(), caller, session };
13438×
    let meta = meta(&ctx).await;
13538×
    match protocol::handle(&ctx, &h, req, meta.clone()).await {
13630×
        Reply::Json(status, v) => (StatusCode::from_u16(status).unwrap_or(StatusCode::OK), axum::Json(v)).into_response(),
1372×
        Reply::Accepted => StatusCode::ACCEPTED.into_response(),
1386×
        Reply::Stream(id, tool, args) => {
1396×
            let fut = async move {
1406×
                let out = crate::tools::invoke(&ctx, tool, args).await;
1416×
                let meta = crate::http::meta(&ctx).await;
1426×
                let msg = protocol::stream_result(&id, &version, &out, meta);
1436×
                Ok::<_, Infallible>(SseEvent::default().event("message").data(msg.to_string()))
1446×
            };
1456×
            sse(stream::once(fut).boxed())
146
        }
1470×
        Reply::Listen(id, sub) => {
1480×
            let ack = json!({ "jsonrpc": "2.0", "method": "notifications/subscriptions/acknowledged", "params": { "_meta": { "io.modelcontextprotocol/subscriptionId": sub } } });
1490×
            let _ = id;
1500×
            let first = stream::once(async move { Ok::<_, Infallible>(SseEvent::default().event("message").data(ack.to_string())) });
151
            // Spectra's tool list never changes while it runs: the stream
152
            // stays open, quiet but for keep-alives, until the client closes it.
1530×
            sse(first.chain(stream::pending()).boxed())
154
        }
155
    }
15642×
}
157
1586×
fn sse(s: futures::stream::BoxStream<'static, Result<SseEvent, Infallible>>) -> Response {
1596×
    let mut r = Sse::new(s).keep_alive(KeepAlive::new().interval(Duration::from_secs(15)).text("")).into_response();
1606×
    r.headers_mut().insert("x-accel-buffering", "no".parse().unwrap());
1616×
    r
1626×
}
163
164
/// `_meta` on every result (spec §15.2): the rules version, the session and
165
/// the unread count.
16664×
pub async fn meta(ctx: &Ctx) -> Json {
16764×
    let mut m = serde_json::Map::new();
16864×
    if let Ok(r) = spectra_core::rules::compile(&ctx.daemon.data) {
16964×
        m.insert("spectra/rules_version".into(), json!(r.version));
17064×
    }
17164×
    if let Some(s) = &ctx.session {
17264×
        m.insert("spectra/session".into(), json!(s));
17364×
    }
17464×
    if let Ok(n) = spectra_core::conversation::unread(&ctx.daemon.ledger, &ctx.caller.principal.actor()).await {
17564×
        m.insert("spectra/inbox_unread".into(), json!(n));
17664×
    }
17764×
    Json::Object(m)
17864×
}
179
180
/// `POST /api/v1/ledger/events`: the owner's CLI hands over events it
181
/// signed over their payload, so `agent add` and `project add` work while
182
/// the daemon holds the ledger (spec §8.5, "One writer").
1832×
async fn owner_events(
1842×
    State(state): State<AppState>,
1852×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
1862×
    headers: HeaderMap,
1872×
    body: Bytes,
1882×
) -> Response {
1892×
    let caller = match authenticate(&state, peer, &headers, "POST /api/v1/ledger/events", &body).await {
1902×
        Ok(c) => c,
1910×
        Err(r) => return r,
192
    };
1932×
    if !matches!(caller.principal, Principal::Owner { .. }) {
1940×
        return (StatusCode::FORBIDDEN, axum::Json(json!({ "title": "only the owner hands events to the daemon" }))).into_response();
1952×
    }
1962×
    let events: Vec<WireEvent> = match serde_json::from_slice(&body) {
1972×
        Ok(v) => v,
1980×
        Err(e) => return (StatusCode::BAD_REQUEST, axum::Json(json!({ "title": format!("not a list of events: {e}") }))).into_response(),
199
    };
2002×
    match state.daemon.accept_owner_events(events).await {
2012×
        Ok(seqs) => axum::Json(json!({ "appended": seqs })).into_response(),
2020×
        Err(e) => (StatusCode::UNPROCESSABLE_ENTITY, axum::Json(json!({ "title": e.to_string() }))).into_response(),
203
    }
2042×
}