OXYGENHUB

Coverage / crates/spectra-mcp/src/api.rs 91.8%

360 of 392 lines run, 63 of 140 functions · run #16 on main · run missed

1
//! The JSON API (spec §18): what spectra-vscode, scripts and SpectraHub
2
//! read and write. Every request is a signed request (spec §8.5); a read
3
//! may instead carry the owner's Radar session. Errors are RFC 7807
4
//! problems; lists page with `?after=`; reads carry an ETag.
5
6
use crate::http::{authenticate, AppState, PeerInfo};
7
use axum::body::Bytes;
8
use axum::extract::connect_info::ConnectInfo;
9
use axum::extract::{Path, Query, State};
10
use axum::http::{header, HeaderMap, StatusCode};
11
use axum::response::sse::{Event as SseEvent, KeepAlive, Sse};
12
use axum::response::{IntoResponse, Response};
13
use axum::routing::{get, post};
14
use axum::Router;
15
use futures::StreamExt;
16
use serde::Deserialize;
17
use spectra_api as api;
18
use spectra_core::authn::Caller;
19
use spectra_core::conversation::{self as conv, Author, Post, Posted, Signer};
20
use spectra_core::event::{Auth, Method};
21
use spectra_core::ids::now_ms;
22
use spectra_core::principals::Principal;
23
use std::time::Duration;
24
2510×
pub fn router(state: AppState) -> Router {
2610×
    Router::new()
2710×
        .route("/api/v1/health", get(health))
2810×
        .route("/api/v1/version", get(version))
2910×
        .route("/api/v1/brief", get(brief))
3010×
        .route("/api/v1/agents", get(agents))
3110×
        .route("/api/v1/projects", get(projects))
3210×
        .route("/api/v1/channels", get(channels))
3310×
        .route("/api/v1/channels/{name}/messages", get(messages).post(post_message))
3410×
        .route("/api/v1/threads/{id}", get(thread))
3510×
        .route("/api/v1/inbox", get(inbox))
3610×
        .route("/api/v1/inbox/ack", post(ack))
3710×
        .route("/api/v1/search", get(search))
3810×
        .route("/api/v1/events", get(events))
3910×
        .with_state(state)
4010×
}
41
42
/// An RFC 7807 problem.
433×
pub fn problem(status: StatusCode, title: &str, detail: Option<String>) -> Response {
443×
    let p = api::Problem { kind: "about:blank".into(), title: title.into(), status: status.as_u16(), detail };
453×
    let mut r = (status, axum::Json(p)).into_response();
463×
    r.headers_mut().insert(header::CONTENT_TYPE, "application/problem+json".parse().unwrap());
473×
    r
483×
}
49
501×
fn bad(e: anyhow::Error) -> Response {
511×
    problem(StatusCode::BAD_REQUEST, "the request cannot be done", Some(format!("{e:#}")))
521×
}
53
54
/// JSON with an ETag; 304 when the client has it already.
5514×
fn json_etag<T: serde::Serialize>(headers: &HeaderMap, v: &T) -> Response {
5614×
    let body = serde_json::to_vec(v).unwrap_or_default();
5714×
    let tag = format!("\"{}\"", &blake3_hex(&body)[..32]);
5814×
    if headers.get(header::IF_NONE_MATCH).and_then(|h| h.to_str().ok()) == Some(tag.as_str()) {
591×
        return StatusCode::NOT_MODIFIED.into_response();
6013×
    }
6113×
    ([(header::CONTENT_TYPE, "application/json".to_string()), (header::ETAG, tag)], body).into_response()
6214×
}
63
6414×
fn blake3_hex(b: &[u8]) -> String {
6514×
    hex::encode(*spectra_core::event::hash_body_plain(b))
6614×
}
67
68
/// Who is asking: a signed request, or for a read the owner's session.
6928×
async fn caller(
7028×
    st: &AppState,
7128×
    peer: PeerInfo,
7228×
    headers: &HeaderMap,
7328×
    method_path: &str,
7428×
    body: &[u8],
7528×
    read: bool,
7628×
) -> Result<Caller, Response> {
7728×
    if read && headers.get("spectra-key").is_none() {
781×
        let cookie = headers.get(header::COOKIE).and_then(|c| c.to_str().ok()).unwrap_or("");
791×
        let id = cookie.split(';').map(str::trim).find_map(|kv| kv.strip_prefix("spectra_session=")).unwrap_or("");
801×
        if let Some(s) = st.sessions.get(id, now_ms()) {
810×
            if !crate::http::origin_ok(headers, &st.origins) {
820×
                return Err(problem(StatusCode::FORBIDDEN, "this origin may not read Spectra", None));
830×
            }
840×
            let key = oxy_core::hash::ObjectRef(s.key);
850×
            let principal = st
860×
                .daemon
870×
                .principals
880×
                .read()
890×
                .await
900×
                .principal(&key, now_ms())
910×
                .map_err(|why| problem(StatusCode::UNAUTHORIZED, "not authenticated", Some(why)))?;
920×
            return Ok(Caller {
930×
                principal,
940×
                auth: Auth { key: Some(s.key), method: Method::Session, assurance: 2, proof: Some(s.proof) },
950×
                learn_uid: None,
960×
            });
971×
        }
9827×
    }
9928×
    authenticate(st, peer, headers, method_path, body).await.map_err(|_| {
1001×
        problem(
101
            StatusCode::UNAUTHORIZED,
1021×
            "not authenticated",
1031×
            Some("sign the request with your key (spectra's client does), or open Radar with `spectra open`".into()),
104
        )
1051×
    })
10628×
}
107
10828×
fn path_of(uri: &axum::http::Uri) -> String {
10928×
    uri.path_and_query().map(|p| p.as_str().to_string()).unwrap_or_else(|| uri.path().to_string())
11028×
}
111
112
macro_rules! who {
113
    ($st:expr, $peer:expr, $headers:expr, $uri:expr, $method:literal, $body:expr, $read:expr) => {
114
        match caller(&$st, $peer, &$headers, &format!("{} {}", $method, path_of(&$uri)), $body, $read).await {
115
            Ok(c) => c,
116
            Err(r) => return r,
117
        }
118
    };
119
}
120
1211×
async fn health() -> Response {
1221×
    axum::Json(serde_json::json!({ "ok": true })).into_response()
1231×
}
124
1251×
async fn version() -> Response {
126
    axum::Json(api::Version {
1271×
        version: env!("CARGO_PKG_VERSION").into(),
128
        ledger_format: spectra_core::LEDGER_FORMAT,
1294×
        mcp_protocol_versions: crate::PROTOCOL_VERSIONS.iter().map(|v| v.to_string()).collect(),
130
    })
1311×
    .into_response()
1321×
}
133
1343×
async fn agent_list(st: &AppState) -> Vec<api::Agent> {
135
    #[allow(clippy::type_complexity)]
1363×
    let rows: Vec<(String, String, String, String, String, Option<String>, Option<i64>)> = sqlx::query_as(
1373×
        "SELECT a.name, a.owner_name, a.key, a.kind, a.project, p.status_text, a.disabled_ms FROM agents a LEFT JOIN presence p ON p.agent = a.name ORDER BY a.name",
1383×
    )
1393×
    .fetch_all(st.daemon.ledger.pool())
1403×
    .await
1413×
    .unwrap_or_default();
1423×
    let presence = st.daemon.presence.lock().await;
1433×
    let now = now_ms();
1443×
    rows.into_iter()
1453×
        .map(|(name, owner, key, kind, project, status, disabled)| api::Agent {
1463×
            display: format!("{name} · {owner}'s agent"),
1473×
            presence: if disabled.is_some() { "offline".into() } else { presence.state(&name, now).into() },
1483×
            disabled: disabled.is_some(),
1493×
            name,
1503×
            owner,
1513×
            key,
1523×
            kind,
1533×
            project,
1543×
            status,
1553×
        })
1563×
        .collect()
1573×
}
158
1592×
async fn agents(
1602×
    State(st): State<AppState>,
1612×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
1622×
    headers: HeaderMap,
1632×
    uri: axum::http::Uri,
1642×
) -> Response {
1652×
    let _ = who!(st, peer, headers, uri, "GET", b"", true);
1661×
    json_etag(&headers, &agent_list(&st).await)
1672×
}
168
1693×
async fn projects(
1703×
    State(st): State<AppState>,
1713×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
1723×
    headers: HeaderMap,
1733×
    uri: axum::http::Uri,
1743×
) -> Response {
1753×
    let _ = who!(st, peer, headers, uri, "GET", b"", true);
1763×
    let pool = st.daemon.ledger.pool();
1773×
    let rows: Vec<(String, String, Option<String>)> =
1783×
        sqlx::query_as("SELECT name, path, remote FROM projects ORDER BY name").fetch_all(pool).await.unwrap_or_default();
1793×
    let mut out = Vec::new();
1803×
    for (name, path, remote) in rows {
1813×
        let depends_on = sqlx::query_scalar("SELECT depends_on FROM project_relations WHERE project = ? ORDER BY 1")
1823×
            .bind(&name)
1833×
            .fetch_all(pool)
1843×
            .await
1853×
            .unwrap_or_default();
1863×
        let depended_on_by = sqlx::query_scalar("SELECT project FROM project_relations WHERE depends_on = ? ORDER BY 1")
1873×
            .bind(&name)
1883×
            .fetch_all(pool)
1893×
            .await
1903×
            .unwrap_or_default();
1913×
        out.push(api::Project { name, path, remote, depends_on, depended_on_by });
192
    }
1933×
    json_etag(&headers, &out)
1943×
}
195
1961×
async fn channels(
1971×
    State(st): State<AppState>,
1981×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
1991×
    headers: HeaderMap,
2001×
    uri: axum::http::Uri,
2011×
) -> Response {
2021×
    let c = who!(st, peer, headers, uri, "GET", b"", true);
2031×
    let all = match conv::channels(&st.daemon.ledger).await {
2041×
        Ok(a) => a,
2050×
        Err(e) => return bad(e),
206
    };
2071×
    let mut out = Vec::new();
2084×
    for ch in all.into_iter().filter(|ch| conv::can_read(&c.principal, ch)) {
2094×
        let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM messages WHERE channel = ?")
2104×
            .bind(&ch.id)
2114×
            .fetch_one(st.daemon.ledger.pool())
2124×
            .await
2134×
            .unwrap_or(0);
2144×
        out.push(api::Channel { display: ch.display(), id: ch.id, name: ch.name, kind: ch.kind, purpose: ch.purpose, messages: n });
215
    }
2161×
    json_etag(&headers, &out)
2171×
}
218
2194×
async fn to_api(st: &AppState, m: conv::Message, ch: &str) -> api::Message {
220
    api::Message {
2214×
        author_display: conv::display_name(&st.daemon.ledger, &m.author).await,
2224×
        mentions: serde_json::from_str(&m.mentions).unwrap_or_default(),
2234×
        refs: serde_json::from_str(&m.refs).unwrap_or_default(),
2244×
        redacted: m.redacted.is_some(),
2254×
        id: m.id,
2264×
        channel: ch.to_string(),
2274×
        reply_to: m.reply_to,
2284×
        author: m.author,
2294×
        kind: m.kind,
2304×
        body: m.body,
2314×
        at_ms: m.at_ms,
2324×
        replies: m.replies,
233
    }
2344×
}
235
236
#[derive(Deserialize)]
237
struct PageQuery {
238
    after: Option<String>,
239
    limit: Option<u32>,
240
}
241
2421×
async fn messages(
2431×
    State(st): State<AppState>,
2441×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
2451×
    headers: HeaderMap,
2461×
    uri: axum::http::Uri,
2471×
    Path(name): Path<String>,
2481×
    Query(q): Query<PageQuery>,
2491×
) -> Response {
2501×
    let c = who!(st, peer, headers, uri, "GET", b"", true);
2511×
    let limit = q.limit.unwrap_or(50).clamp(1, 500);
2521×
    match conv::read(&st.daemon.ledger, &c.principal, Some(&name), None, q.after.as_deref(), limit).await {
2531×
        Ok((ch, msgs)) => {
2541×
            let next = (msgs.len() as u32 == limit).then(|| msgs.last().map(|m| m.id.clone())).flatten();
2551×
            let mut items = Vec::new();
2562×
            for m in msgs {
2572×
                items.push(to_api(&st, m, &ch.display()).await);
258
            }
2591×
            json_etag(&headers, &api::Messages { channel: ch.display(), items, next })
260
        }
2610×
        Err(e) => problem(StatusCode::NOT_FOUND, "no such channel, or not yours to read", Some(format!("{e:#}"))),
262
    }
2631×
}
264
2651×
async fn thread(
2661×
    State(st): State<AppState>,
2671×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
2681×
    headers: HeaderMap,
2691×
    uri: axum::http::Uri,
2701×
    Path(id): Path<String>,
2711×
    Query(q): Query<PageQuery>,
2721×
) -> Response {
2731×
    let c = who!(st, peer, headers, uri, "GET", b"", true);
2741×
    let limit = q.limit.unwrap_or(200).clamp(1, 500);
2751×
    match conv::read(&st.daemon.ledger, &c.principal, None, Some(&id), q.after.as_deref(), limit).await {
2761×
        Ok((ch, msgs)) => {
2771×
            let next = (msgs.len() as u32 == limit).then(|| msgs.last().map(|m| m.id.clone())).flatten();
2781×
            let mut items = Vec::new();
2792×
            for m in msgs {
2802×
                items.push(to_api(&st, m, &ch.display()).await);
281
            }
2821×
            json_etag(&headers, &api::Messages { channel: ch.display(), items, next })
283
        }
2840×
        Err(e) => problem(StatusCode::NOT_FOUND, "no such thread, or not yours to read", Some(format!("{e:#}"))),
285
    }
2861×
}
287
2889×
async fn post_message(
2899×
    State(st): State<AppState>,
2909×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
2919×
    headers: HeaderMap,
2929×
    uri: axum::http::Uri,
2939×
    Path(name): Path<String>,
2949×
    body: Bytes,
2959×
) -> Response {
2969×
    let c = who!(st, peer, headers, uri, "POST", &body, false);
2979×
    let n: api::NewMessage = match serde_json::from_slice(&body) {
2989×
        Ok(n) => n,
2990×
        Err(e) => return problem(StatusCode::BAD_REQUEST, "not a message", Some(e.to_string())),
300
    };
3019×
    let author = Author { principal: c.principal.clone(), signer: Signer::Request(c.auth.clone()) };
3029×
    let post = Post {
3039×
        channel: if n.reply_to.is_some() { None } else { Some(name) },
3049×
        body: n.body,
3059×
        reply_to: n.reply_to,
3069×
        kind: n.kind,
3079×
        ..Default::default()
308
    };
3099×
    match conv::post(&st.daemon.ledger, &author, post, now_ms()).await {
3108×
        Ok(Posted::Message { id, channel }) => {
3118×
            (StatusCode::CREATED, axum::Json(api::Posted { id, channel, duplicate: false })).into_response()
312
        }
3130×
        Ok(Posted::Duplicate { id }) => axum::Json(api::Posted { id, channel: String::new(), duplicate: true }).into_response(),
3141×
        Err(e) => bad(e),
315
    }
3169×
}
317
3184×
async fn inbox_items(st: &AppState, actor: &str) -> Vec<api::InboxItem> {
3194×
    conv::inbox(&st.daemon.ledger, actor, None)
3204×
        .await
3214×
        .unwrap_or_default()
3224×
        .into_iter()
3235×
        .map(|i| api::InboxItem { id: i.id, kind: i.kind, at_ms: i.at_ms, from: i.from, channel: i.channel, summary: i.summary })
3244×
        .collect()
3254×
}
326
3272×
async fn inbox(State(st): State<AppState>, ConnectInfo(peer): ConnectInfo<PeerInfo>, headers: HeaderMap, uri: axum::http::Uri) -> Response {
3282×
    let c = who!(st, peer, headers, uri, "GET", b"", true);
3292×
    json_etag(&headers, &inbox_items(&st, &c.principal.actor()).await)
3302×
}
331
3321×
async fn ack(
3331×
    State(st): State<AppState>,
3341×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
3351×
    headers: HeaderMap,
3361×
    uri: axum::http::Uri,
3371×
    body: Bytes,
3381×
) -> Response {
3391×
    let c = who!(st, peer, headers, uri, "POST", &body, false);
3401×
    let a: api::Ack = match serde_json::from_slice(&body) {
3411×
        Ok(a) => a,
3420×
        Err(e) => return problem(StatusCode::BAD_REQUEST, "not an ack", Some(e.to_string())),
343
    };
3441×
    let author = Author { principal: c.principal, signer: Signer::Request(c.auth) };
3451×
    match conv::ack(&st.daemon.ledger, &author, &a.ids, a.reaction.as_deref()).await {
3461×
        Ok(n) => axum::Json(serde_json::json!({ "read": n })).into_response(),
3470×
        Err(e) => bad(e),
348
    }
3491×
}
350
3512×
async fn brief(State(st): State<AppState>, ConnectInfo(peer): ConnectInfo<PeerInfo>, headers: HeaderMap, uri: axum::http::Uri) -> Response {
3522×
    let c = who!(st, peer, headers, uri, "GET", b"", true);
3532×
    let project = match &c.principal {
3541×
        Principal::Agent { project, .. } => Some(project.clone()),
3551×
        _ => None,
356
    };
3572×
    let rules = spectra_core::rules::compile(&st.daemon.data).map(|r| r.version).unwrap_or_default();
3582×
    let inbox = inbox_items(&st, &c.principal.actor()).await;
3592×
    let b = api::Brief {
3602×
        you: c.principal.display(),
3612×
        actor: c.principal.actor(),
3622×
        project,
3632×
        rules_version: rules,
3642×
        unread: inbox.len() as i64,
3652×
        inbox,
3662×
        agents: agent_list(&st).await,
3672×
        head: st.daemon.ledger.head().await.0,
368
    };
3692×
    json_etag(&headers, &b)
3702×
}
371
372
#[derive(Deserialize)]
373
struct SearchQuery {
374
    q: String,
375
    channel: Option<String>,
376
    author: Option<String>,
377
    since: Option<String>,
378
    limit: Option<u32>,
379
}
380
3811×
async fn search(
3821×
    State(st): State<AppState>,
3831×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
3841×
    headers: HeaderMap,
3851×
    uri: axum::http::Uri,
3861×
    Query(q): Query<SearchQuery>,
3871×
) -> Response {
3881×
    let c = who!(st, peer, headers, uri, "GET", b"", true);
3891×
    let since = q.since.as_deref().and_then(|s| crate::tools::parse_since(s, now_ms()));
3901×
    match conv::search(&st.daemon.ledger, &c.principal, &q.q, q.channel.as_deref(), q.author.as_deref(), since, q.limit.unwrap_or(20)).await
391
    {
3921×
        Ok(hits) => {
3931×
            let out: Vec<api::Hit> = hits
3941×
                .into_iter()
3953×
                .map(|h| api::Hit { id: h.id, channel: h.channel, author: h.author, at_ms: h.at_ms, snippet: h.snippet, thread: h.thread })
3961×
                .collect();
3971×
            json_etag(&headers, &out)
398
        }
3990×
        Err(e) => bad(e),
400
    }
4011×
}
402
403
#[derive(Deserialize)]
404
struct EventsQuery {
405
    after: Option<u64>,
406
    kind: Option<String>,
407
    limit: Option<u32>,
408
    follow: Option<u8>,
409
    /// With `follow`, end the stream after this many events.
410
    max: Option<usize>,
411
}
412
41313×
fn summary(e: &spectra_core::event::Event) -> api::EventSummary {
41413×
    api::EventSummary {
41513×
        seq: e.seq,
41613×
        id: e.id.clone(),
41713×
        at_ms: e.at_ms,
41813×
        kind: e.kind.clone(),
41913×
        actor: e.actor.clone(),
42013×
        subject: e.subject.clone(),
42113×
        method: e.auth.method.name().into(),
42213×
        assurance: e.auth.assurance,
42313×
        hash: hex::encode(e.hash),
42413×
    }
42513×
}
426
427
/// The log as summaries; `follow=1` streams new ones as SSE instead.
4285×
async fn events(
4295×
    State(st): State<AppState>,
4305×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
4315×
    headers: HeaderMap,
4325×
    uri: axum::http::Uri,
4335×
    Query(q): Query<EventsQuery>,
4345×
) -> Response {
4355×
    let c = who!(st, peer, headers, uri, "GET", b"", true);
436
    // The log is the owner's to read; an agent reads what concerns it
437
    // through the conversation and its inbox.
4385×
    if !matches!(c.principal, Principal::Owner { .. }) {
4391×
        return problem(StatusCode::FORBIDDEN, "the event log is the owner's", None);
4404×
    }
4414×
    if q.follow == Some(1) {
4422×
        let kind = q.kind.clone();
4432×
        let rx = st.daemon.ledger.subscribe();
4442×
        let stream = tokio_stream::wrappers::BroadcastStream::new(rx)
4454×
            .filter_map(move |e| {
4464×
                let kind = kind.clone();
4474×
                async move {
4484×
                    let e = e.ok()?;
4494×
                    if kind.as_ref().is_some_and(|k| *k != e.kind) {
4502×
                        return None;
4512×
                    }
4522×
                    Some(Ok::<_, std::convert::Infallible>(
4532×
                        SseEvent::default().data(serde_json::to_string(&summary(&e)).unwrap_or_default()),
4542×
                    ))
4554×
                }
4564×
            })
4572×
            .take(q.max.unwrap_or(usize::MAX));
4582×
        return Sse::new(stream).keep_alive(KeepAlive::new().interval(Duration::from_secs(15))).into_response();
4592×
    }
4602×
    let limit = q.limit.unwrap_or(100).clamp(1, 1000);
4612×
    let from = q.after.map(|a| a + 1).unwrap_or(1);
4622×
    let evs = match &q.kind {
4631×
        Some(k) => st.daemon.ledger.events_of_kinds(from, &[k.as_str()], limit).await,
4641×
        None => st.daemon.ledger.events(from, limit).await,
465
    };
4662×
    match evs {
4672×
        Ok(evs) => {
4682×
            let next = (evs.len() as u32 == limit).then(|| evs.last().map(|e| e.seq)).flatten();
4692×
            json_etag(&headers, &api::Events { items: evs.iter().map(summary).collect(), next })
470
        }
4710×
        Err(e) => bad(e),
472
    }
4735×
}