OXYGENHUB

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

167 of 188 lines run, 35 of 74 functions · run #19 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 {
4413×
    fn connect_info(_: axum::serve::IncomingStream<'_, crate::tls::TlsListener>) -> Self {
4513×
        PeerInfo(None)
4613×
    }
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.
5914×
pub fn router(state: AppState) -> Router {
6014×
    Router::new()
6114×
        .route("/mcp", post(mcp).get(not_allowed).delete(not_allowed))
6214×
        .route("/api/v1/ledger/events", post(owner_events))
6314×
        .route("/api/v1/instance", axum::routing::get(instance))
6414×
        .route("/api/v1/claim", post(claim))
6514×
        .with_state(state)
6614×
}
67
68
/// `GET /api/v1/instance`, unauthenticated (spec §8.6): who this Spectra
69
/// is, whose it is, and the instance key's word for its TLS certificate, so
70
/// a client can decide whether to trust it before it signs anything.
715×
async fn instance(State(state): State<AppState>) -> Response {
725×
    let (instance, owner) = {
735×
        let p = state.daemon.principals.read().await;
745×
        (p.instance().cloned(), p.owner().map(|o| o.hash().to_hex()))
75
    };
765×
    let Some(instance) = instance else {
770×
        return (StatusCode::SERVICE_UNAVAILABLE, axum::Json(json!({ "title": "this Spectra has no instance key" }))).into_response();
78
    };
795×
    let tls = match crate::instance::latest_tls(&state.daemon.ledger).await {
805×
        Ok(Some(e)) => json!({ "payload": e.json(), "proof": e.auth.proof.as_ref().map(hex::encode) }),
810×
        _ => Json::Null,
82
    };
835×
    axum::Json(json!({
845×
        "name": instance.name,
855×
        "instance": spectra_core::principals::identity_payload(&instance),
865×
        "owner": owner,
875×
        "tls": tls,
885×
    }))
895×
    .into_response()
905×
}
91
92
/// `POST /api/v1/claim`: the owner named by `spectra init --owner` records
93
/// their identity (spec §8.6). The event proves itself: it is signed by
94
/// the identity it records, over its payload.
954×
async fn claim(State(state): State<AppState>, body: Bytes) -> Response {
964×
    let w: WireEvent = match serde_json::from_slice(&body) {
974×
        Ok(v) => v,
980×
        Err(e) => return (StatusCode::BAD_REQUEST, axum::Json(json!({ "title": format!("not an event: {e}") }))).into_response(),
99
    };
1004×
    match state.daemon.claim(w).await {
1011×
        Ok(seq) => axum::Json(json!({ "seq": seq })).into_response(),
1023×
        Err(e) => (StatusCode::FORBIDDEN, axum::Json(json!({ "title": format!("{e:#}") }))).into_response(),
103
    }
1044×
}
105
1061×
async fn not_allowed() -> StatusCode {
1071×
    StatusCode::METHOD_NOT_ALLOWED
1081×
}
109
110
/// The proof the signature headers carry, for `method_path` and `body`.
11179×
pub fn proof_from(headers: &HeaderMap, method_path: &str, body: &[u8]) -> Option<Proof> {
112310×
    let get = |k: &str| headers.get(k).and_then(|v| v.to_str().ok());
11379×
    let key = get("spectra-key")?;
11477×
    let time_ms = get("spectra-time")?.parse().ok()?;
11577×
    let nonce: [u8; 16] = hex::decode(get("spectra-nonce")?).ok()?.try_into().ok()?;
11677×
    let sig_bytes = hex::decode(get("spectra-signature")?).ok()?;
11777×
    let sig = oxy_core::cbor::decode(&sig_bytes).ok().and_then(|v| oxy_core::identity::Signature::from_value(&v).ok())?;
11877×
    if sig.key.to_hex() != key {
1190×
        return None;
12077×
    }
12177×
    Some(Proof { sig, method: method_path.into(), body_hash: *spectra_core::event::hash_body_plain(body), time_ms, nonce })
12279×
}
123
124
/// Refuse a browser request from a page that is not ours (spec §21.1).
12584×
pub fn origin_ok(headers: &HeaderMap, allowed: &[String]) -> bool {
12684×
    match headers.get("origin").and_then(|v| v.to_str().ok()) {
12782×
        None => true,
1286×
        Some(o) => allowed.iter().any(|a| a == o),
129
    }
13084×
}
131
132
/// Authenticate a request, or the status and reason that refuse it.
13380×
pub async fn authenticate_why(
13480×
    state: &AppState,
13580×
    peer: PeerInfo,
13680×
    headers: &HeaderMap,
13780×
    method_path: &str,
13880×
    body: &[u8],
13980×
) -> Result<Caller, (StatusCode, String)> {
14080×
    if !origin_ok(headers, &state.origins) {
1411×
        return Err((StatusCode::FORBIDDEN, "this origin may not call Spectra".into()));
14279×
    }
14379×
    let proof = proof_from(headers, method_path, body);
14479×
    state.daemon.authenticate(proof.as_ref(), method_path, body, peer.0).await.map_err(|why| {
1456×
        tracing::info!(%why, "refused a request");
146
        // The reason concerns the caller's own key, so the caller is told it:
147
        // an agent whose delegation expired must be able to say so.
1486×
        (StatusCode::UNAUTHORIZED, why.to_string())
1496×
    })
15080×
}
151
152
/// Authenticate a request, or the JSON-RPC response that refuses it.
15350×
pub async fn authenticate(
15450×
    state: &AppState,
15550×
    peer: PeerInfo,
15650×
    headers: &HeaderMap,
15750×
    method_path: &str,
15850×
    body: &[u8],
15950×
) -> Result<Caller, Response> {
16050×
    authenticate_why(state, peer, headers, method_path, body).await.map_err(|(status, why)| {
1615×
        let (code, msg) = if status == StatusCode::FORBIDDEN {
1621×
            (protocol::INVALID_REQUEST, why)
163
        } else {
1644×
            (protocol::UNAUTHENTICATED, format!("not authenticated: {why}"))
165
        };
1665×
        (status, axum::Json(protocol::error(&Json::Null, code, &msg))).into_response()
1675×
    })
16850×
}
169
17047×
async fn mcp(State(state): State<AppState>, ConnectInfo(peer): ConnectInfo<PeerInfo>, headers: HeaderMap, body: Bytes) -> Response {
17147×
    let caller = match authenticate(&state, peer, &headers, "POST /mcp", &body).await {
17242×
        Ok(c) => c,
1735×
        Err(r) => return r,
174
    };
17542×
    let req: Json = match serde_json::from_slice(&body) {
17642×
        Ok(v) => v,
1770×
        Err(e) => {
1780×
            return (StatusCode::BAD_REQUEST, axum::Json(protocol::error(&Json::Null, protocol::PARSE_ERROR, &format!("not JSON: {e}"))))
1790×
                .into_response()
180
        }
181
    };
18242×
    let new_session = req.pointer("/params/arguments/new_session").and_then(Json::as_bool).unwrap_or(false)
1830×
        && req.pointer("/params/name").and_then(Json::as_str) == Some("brief");
18442×
    let session = state.daemon.touch(&caller.principal, new_session).await;
18542×
    let h = Headers {
18642×
        version: headers.get("mcp-protocol-version").and_then(|v| v.to_str().ok()),
18742×
        method: headers.get("mcp-method").and_then(|v| v.to_str().ok()),
18842×
        name: headers.get("mcp-name").and_then(|v| v.to_str().ok()),
189
    };
19042×
    let version = h.version.unwrap_or("2025-03-26").to_string();
19142×
    let ctx = Ctx { daemon: state.daemon.clone(), caller, session };
19242×
    let meta = meta(&ctx).await;
19342×
    match protocol::handle(&ctx, &h, req, meta.clone()).await {
19434×
        Reply::Json(status, v) => (StatusCode::from_u16(status).unwrap_or(StatusCode::OK), axum::Json(v)).into_response(),
1952×
        Reply::Accepted => StatusCode::ACCEPTED.into_response(),
1966×
        Reply::Stream(id, tool, args) => {
1976×
            let fut = async move {
1986×
                let out = crate::tools::invoke(&ctx, tool, args).await;
1996×
                let meta = crate::http::meta(&ctx).await;
2006×
                let msg = protocol::stream_result(&id, &version, &out, meta);
2016×
                Ok::<_, Infallible>(SseEvent::default().event("message").data(msg.to_string()))
2026×
            };
2036×
            sse(stream::once(fut).boxed())
204
        }
2050×
        Reply::Listen(id, sub) => {
2060×
            let ack = json!({ "jsonrpc": "2.0", "method": "notifications/subscriptions/acknowledged", "params": { "_meta": { "io.modelcontextprotocol/subscriptionId": sub } } });
2070×
            let _ = id;
2080×
            let first = stream::once(async move { Ok::<_, Infallible>(SseEvent::default().event("message").data(ack.to_string())) });
209
            // Spectra's tool list never changes while it runs: the stream
210
            // stays open, quiet but for keep-alives, until the client closes it.
2110×
            sse(first.chain(stream::pending()).boxed())
212
        }
213
    }
21447×
}
215
2166×
fn sse(s: futures::stream::BoxStream<'static, Result<SseEvent, Infallible>>) -> Response {
2176×
    let mut r = Sse::new(s).keep_alive(KeepAlive::new().interval(Duration::from_secs(15)).text("")).into_response();
2186×
    r.headers_mut().insert("x-accel-buffering", "no".parse().unwrap());
2196×
    r
2206×
}
221
222
/// `_meta` on every result (spec §15.2): the rules version, the session and
223
/// the unread count.
22471×
pub async fn meta(ctx: &Ctx) -> Json {
22571×
    let mut m = serde_json::Map::new();
22671×
    if let Ok(r) = spectra_core::rules::compile(&ctx.daemon.data) {
22771×
        m.insert("spectra/rules_version".into(), json!(r.version));
22871×
    }
22971×
    if let Some(s) = &ctx.session {
23071×
        m.insert("spectra/session".into(), json!(s));
23171×
    }
23271×
    if let Ok(n) = spectra_core::conversation::unread(&ctx.daemon.ledger, &ctx.caller.principal.actor()).await {
23371×
        m.insert("spectra/inbox_unread".into(), json!(n));
23471×
    }
23571×
    Json::Object(m)
23671×
}
237
238
/// `POST /api/v1/ledger/events`: the owner's CLI hands over events it
239
/// signed over their payload, so `agent add` and `project add` work while
240
/// the daemon holds the ledger (spec §8.5, "One writer").
2412×
async fn owner_events(
2422×
    State(state): State<AppState>,
2432×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
2442×
    headers: HeaderMap,
2452×
    body: Bytes,
2462×
) -> Response {
2472×
    let caller = match authenticate(&state, peer, &headers, "POST /api/v1/ledger/events", &body).await {
2482×
        Ok(c) => c,
2490×
        Err(r) => return r,
250
    };
2512×
    if !matches!(caller.principal, Principal::Owner { .. }) {
2520×
        return (StatusCode::FORBIDDEN, axum::Json(json!({ "title": "only the owner hands events to the daemon" }))).into_response();
2532×
    }
2542×
    let events: Vec<WireEvent> = match serde_json::from_slice(&body) {
2552×
        Ok(v) => v,
2560×
        Err(e) => return (StatusCode::BAD_REQUEST, axum::Json(json!({ "title": format!("not a list of events: {e}") }))).into_response(),
257
    };
2582×
    match state.daemon.accept_owner_events(events).await {
2592×
        Ok(seqs) => axum::Json(json!({ "appended": seqs })).into_response(),
2600×
        Err(e) => (StatusCode::UNPROCESSABLE_ENTITY, axum::Json(json!({ "title": e.to_string() }))).into_response(),
261
    }
2622×
}