OXYGENHUB

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

168 of 189 lines run, 35 of 74 functions · run #29 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 {
31160×
    fn connect_info(stream: axum::serve::IncomingStream<'_, tokio::net::UnixListener>) -> Self {
32160×
        let cred = stream.io().peer_cred().ok();
33160×
        PeerInfo(cred.map(|c| Peer { uid: c.uid(), pid: c.pid() }))
34160×
    }
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 {
4468×
    fn connect_info(_: axum::serve::IncomingStream<'_, crate::tls::TlsListener>) -> Self {
4568×
        PeerInfo(None)
4668×
    }
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.
5921×
pub fn router(state: AppState) -> Router {
6021×
    Router::new()
6121×
        .route("/mcp", post(mcp).get(not_allowed).delete(not_allowed))
6221×
        .route("/api/v1/ledger/events", post(owner_events))
6321×
        .route("/api/v1/instance", axum::routing::get(instance))
6421×
        .route("/api/v1/claim", post(claim))
6521×
        .with_state(state)
6621×
}
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.
7131×
async fn instance(State(state): State<AppState>) -> Response {
7231×
    let (instance, owner) = {
7331×
        let p = state.daemon.principals.read().await;
7431×
        (p.instance().cloned(), p.owner().map(|o| o.hash().to_hex()))
75
    };
7631×
    let owner_missing = owner.is_none();
7731×
    let Some(instance) = instance else {
780×
        return (StatusCode::SERVICE_UNAVAILABLE, axum::Json(json!({ "title": "this Spectra has no instance key" }))).into_response();
79
    };
8031×
    let tls = match crate::instance::latest_tls(&state.daemon.ledger).await {
8131×
        Ok(Some(e)) => json!({ "payload": e.json(), "proof": e.auth.proof.as_ref().map(hex::encode) }),
820×
        _ => Json::Null,
83
    };
8431×
    axum::Json(json!({
8531×
        "name": instance.name,
8631×
        "instance": spectra_core::principals::identity_payload(&instance),
8731×
        "owner": owner,
88
        // Until claimed: the KeyId `spectra init --owner` named.
8931×
        "named_owner": if owner_missing { state.daemon.named_owner() } else { None },
9031×
        "tls": tls,
91
    }))
9231×
    .into_response()
9331×
}
94
95
/// `POST /api/v1/claim`: the owner named by `spectra init --owner` records
96
/// their identity (spec §8.6). The event proves itself: it is signed by
97
/// the identity it records, over its payload.
987×
async fn claim(State(state): State<AppState>, body: Bytes) -> Response {
997×
    let events: Vec<WireEvent> = match serde_json::from_slice(&body) {
1007×
        Ok(v) => v,
1010×
        Err(e) => return (StatusCode::BAD_REQUEST, axum::Json(json!({ "title": format!("not a list of events: {e}") }))).into_response(),
102
    };
1037×
    match state.daemon.claim(events).await {
1044×
        Ok(seqs) => axum::Json(json!({ "seqs": seqs })).into_response(),
1053×
        Err(e) => (StatusCode::FORBIDDEN, axum::Json(json!({ "title": format!("{e:#}") }))).into_response(),
106
    }
1077×
}
108
1091×
async fn not_allowed() -> StatusCode {
1101×
    StatusCode::METHOD_NOT_ALLOWED
1111×
}
112
113
/// The proof the signature headers carry, for `method_path` and `body`.
114130×
pub fn proof_from(headers: &HeaderMap, method_path: &str, body: &[u8]) -> Option<Proof> {
115514×
    let get = |k: &str| headers.get(k).and_then(|v| v.to_str().ok());
116130×
    let key = get("spectra-key")?;
117128×
    let time_ms = get("spectra-time")?.parse().ok()?;
118128×
    let nonce: [u8; 16] = hex::decode(get("spectra-nonce")?).ok()?.try_into().ok()?;
119128×
    let sig_bytes = hex::decode(get("spectra-signature")?).ok()?;
120128×
    let sig = spectra_core::cbor::decode(&sig_bytes).ok().and_then(|v| spectra_core::identity::Signature::from_value(&v).ok())?;
121128×
    if sig.key.to_hex() != key {
1220×
        return None;
123128×
    }
124128×
    Some(Proof { sig, method: method_path.into(), body_hash: *spectra_core::event::hash_body_plain(body), time_ms, nonce })
125130×
}
126
127
/// Refuse a browser request from a page that is not ours (spec §21.1).
128138×
pub fn origin_ok(headers: &HeaderMap, allowed: &[String]) -> bool {
129138×
    match headers.get("origin").and_then(|v| v.to_str().ok()) {
130136×
        None => true,
1316×
        Some(o) => allowed.iter().any(|a| a == o),
132
    }
133138×
}
134
135
/// Authenticate a request, or the status and reason that refuse it.
136131×
pub async fn authenticate_why(
137131×
    state: &AppState,
138131×
    peer: PeerInfo,
139131×
    headers: &HeaderMap,
140131×
    method_path: &str,
141131×
    body: &[u8],
142131×
) -> Result<Caller, (StatusCode, String)> {
143131×
    if !origin_ok(headers, &state.origins) {
1441×
        return Err((StatusCode::FORBIDDEN, "this origin may not call Spectra".into()));
145130×
    }
146130×
    let proof = proof_from(headers, method_path, body);
147130×
    state.daemon.authenticate(proof.as_ref(), method_path, body, peer.0).await.map_err(|why| {
1486×
        tracing::info!(%why, "refused a request");
149
        // The reason concerns the caller's own key, so the caller is told it:
150
        // an agent whose delegation expired must be able to say so.
1516×
        (StatusCode::UNAUTHORIZED, why.to_string())
1526×
    })
153131×
}
154
155
/// Authenticate a request, or the JSON-RPC response that refuses it.
15669×
pub async fn authenticate(
15769×
    state: &AppState,
15869×
    peer: PeerInfo,
15969×
    headers: &HeaderMap,
16069×
    method_path: &str,
16169×
    body: &[u8],
16269×
) -> Result<Caller, Response> {
16369×
    authenticate_why(state, peer, headers, method_path, body).await.map_err(|(status, why)| {
1645×
        let (code, msg) = if status == StatusCode::FORBIDDEN {
1651×
            (protocol::INVALID_REQUEST, why)
166
        } else {
1674×
            (protocol::UNAUTHENTICATED, format!("not authenticated: {why}"))
168
        };
1695×
        (status, axum::Json(protocol::error(&Json::Null, code, &msg))).into_response()
1705×
    })
17169×
}
172
17357×
async fn mcp(State(state): State<AppState>, ConnectInfo(peer): ConnectInfo<PeerInfo>, headers: HeaderMap, body: Bytes) -> Response {
17457×
    let caller = match authenticate(&state, peer, &headers, "POST /mcp", &body).await {
17552×
        Ok(c) => c,
1765×
        Err(r) => return r,
177
    };
17852×
    let req: Json = match serde_json::from_slice(&body) {
17952×
        Ok(v) => v,
1800×
        Err(e) => {
1810×
            return (StatusCode::BAD_REQUEST, axum::Json(protocol::error(&Json::Null, protocol::PARSE_ERROR, &format!("not JSON: {e}"))))
1820×
                .into_response()
183
        }
184
    };
18552×
    let new_session = req.pointer("/params/arguments/new_session").and_then(Json::as_bool).unwrap_or(false)
1860×
        && req.pointer("/params/name").and_then(Json::as_str) == Some("brief");
18752×
    let session = state.daemon.touch(&caller.principal, new_session).await;
18852×
    let h = Headers {
18952×
        version: headers.get("mcp-protocol-version").and_then(|v| v.to_str().ok()),
19052×
        method: headers.get("mcp-method").and_then(|v| v.to_str().ok()),
19152×
        name: headers.get("mcp-name").and_then(|v| v.to_str().ok()),
192
    };
19352×
    let version = h.version.unwrap_or("2025-03-26").to_string();
19452×
    let ctx = Ctx { daemon: state.daemon.clone(), caller, session };
19552×
    let meta = meta(&ctx).await;
19652×
    match protocol::handle(&ctx, &h, req, meta.clone()).await {
19744×
        Reply::Json(status, v) => (StatusCode::from_u16(status).unwrap_or(StatusCode::OK), axum::Json(v)).into_response(),
1982×
        Reply::Accepted => StatusCode::ACCEPTED.into_response(),
1996×
        Reply::Stream(id, tool, args) => {
2006×
            let fut = async move {
2016×
                let out = crate::tools::invoke(&ctx, tool, args).await;
2026×
                let meta = crate::http::meta(&ctx).await;
2036×
                let msg = protocol::stream_result(&id, &version, &out, meta);
2046×
                Ok::<_, Infallible>(SseEvent::default().event("message").data(msg.to_string()))
2056×
            };
2066×
            sse(stream::once(fut).boxed())
207
        }
2080×
        Reply::Listen(id, sub) => {
2090×
            let ack = json!({ "jsonrpc": "2.0", "method": "notifications/subscriptions/acknowledged", "params": { "_meta": { "io.modelcontextprotocol/subscriptionId": sub } } });
2100×
            let _ = id;
2110×
            let first = stream::once(async move { Ok::<_, Infallible>(SseEvent::default().event("message").data(ack.to_string())) });
212
            // Spectra's tool list never changes while it runs: the stream
213
            // stays open, quiet but for keep-alives, until the client closes it.
2140×
            sse(first.chain(stream::pending()).boxed())
215
        }
216
    }
21757×
}
218
2196×
fn sse(s: futures::stream::BoxStream<'static, Result<SseEvent, Infallible>>) -> Response {
2206×
    let mut r = Sse::new(s).keep_alive(KeepAlive::new().interval(Duration::from_secs(15)).text("")).into_response();
2216×
    r.headers_mut().insert("x-accel-buffering", "no".parse().unwrap());
2226×
    r
2236×
}
224
225
/// `_meta` on every result (spec §15.2): the rules version, the session and
226
/// the unread count.
22790×
pub async fn meta(ctx: &Ctx) -> Json {
22890×
    let mut m = serde_json::Map::new();
22990×
    if let Ok(r) = spectra_core::rules::compile(ctx.daemon.ledger.pool(), crate::tools::project_of(&ctx.caller.principal)).await {
23090×
        m.insert("spectra/rules_version".into(), json!(r.version));
23190×
    }
23290×
    if let Some(s) = &ctx.session {
23390×
        m.insert("spectra/session".into(), json!(s));
23490×
    }
23590×
    if let Ok(n) = spectra_core::conversation::unread(&ctx.daemon.ledger, &ctx.caller.principal.actor()).await {
23690×
        m.insert("spectra/inbox_unread".into(), json!(n));
23790×
    }
23890×
    Json::Object(m)
23990×
}
240
241
/// `POST /api/v1/ledger/events`: the owner's CLI hands over events it
242
/// signed over their payload, so `agent add` and `project add` work while
243
/// the daemon holds the ledger (spec §8.5, "One writer").
24410×
async fn owner_events(
24510×
    State(state): State<AppState>,
24610×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
24710×
    headers: HeaderMap,
24810×
    body: Bytes,
24910×
) -> Response {
25010×
    let caller = match authenticate(&state, peer, &headers, "POST /api/v1/ledger/events", &body).await {
25110×
        Ok(c) => c,
2520×
        Err(r) => return r,
253
    };
25410×
    if !matches!(caller.principal, Principal::Owner { .. }) {
2550×
        return (StatusCode::FORBIDDEN, axum::Json(json!({ "title": "only the owner hands events to the daemon" }))).into_response();
25610×
    }
25710×
    let events: Vec<WireEvent> = match serde_json::from_slice(&body) {
25810×
        Ok(v) => v,
2590×
        Err(e) => return (StatusCode::BAD_REQUEST, axum::Json(json!({ "title": format!("not a list of events: {e}") }))).into_response(),
260
    };
26110×
    match state.daemon.accept_owner_events(events).await {
26210×
        Ok(seqs) => axum::Json(json!({ "appended": seqs })).into_response(),
2630×
        Err(e) => (StatusCode::UNPROCESSABLE_ENTITY, axum::Json(json!({ "title": e.to_string() }))).into_response(),
264
    }
26510×
}