OXYGENHUB

Coverage / crates/spectra-mcp/src/client.rs 66.0%

107 of 162 lines run, 77 of 172 functions · run #25 on main · run missed

1
//! A client for the daemon over its Unix socket (spec §8.5), signing every
2
//! request with the caller's key: the shims and the CLI use it, and so do
3
//! the tests.
4
5
use anyhow::{Context, Result};
6
use http_body_util::{BodyExt, Full};
7
use hyper::body::Bytes;
8
use spectra_core::keys::KeyPair;
9
use spectra_core::proof::Proof;
10
use std::path::{Path, PathBuf};
11
12
/// A response, its body read whole.
13
#[derive(Debug)]
14
pub struct Response {
15
    pub status: u16,
16
    pub headers: Vec<(String, String)>,
17
    pub body: Vec<u8>,
18
}
19
20
impl Response {
2189×
    pub fn json(&self) -> Result<serde_json::Value> {
2289×
        serde_json::from_slice(&self.body).with_context(|| format!("not JSON: {}", String::from_utf8_lossy(&self.body)))
2389×
    }
2434×
    pub fn header(&self, name: &str) -> Option<&str> {
2543×
        self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
2634×
    }
27
}
28
29
/// Where the daemon is: its Unix socket, or a server over TLS with a
30
/// pinned certificate (spec §8.6).
31
#[derive(Clone)]
32
pub enum Endpoint {
33
    Unix(PathBuf),
34
    Tls { addr: String, config: std::sync::Arc<rustls::ClientConfig> },
35
}
36
37
impl Endpoint {
38
    /// `https://HOST:PORT` accepting exactly the certificate pinned by `pin`.
3925×
    pub fn tls(url: &str, pin: [u8; 32]) -> Result<Endpoint> {
4025×
        Ok(Endpoint::Tls { addr: host_port(url)?, config: crate::tls::Pinned::new(Some(pin)).client_config()? })
4125×
    }
42
430×
    pub fn describe(&self) -> String {
440×
        match self {
450×
            Endpoint::Unix(p) => p.display().to_string(),
460×
            Endpoint::Tls { addr, .. } => format!("https://{addr}"),
47
        }
480×
    }
49
}
50
51
/// `host:port` of an `https://` URL.
5241×
pub fn host_port(url: &str) -> Result<String> {
5341×
    let rest = url.strip_prefix("https://").with_context(|| format!("{url} is not an https:// URL"))?;
5441×
    let hp = rest.split('/').next().unwrap_or("");
5541×
    if hp.is_empty() {
560×
        anyhow::bail!("{url} names no host");
5741×
    }
58
    // The port defaults to Spectra's.
5941×
    let has_port = if hp.starts_with('[') { hp.contains("]:") } else { hp.contains(':') };
6041×
    Ok(if has_port { hp.to_string() } else { format!("{hp}:7350") })
6141×
}
62
63
trait Io: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send {}
64
impl<T: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send> Io for T {}
65
66
pub struct Client {
67
    endpoint: Endpoint,
68
    signer: Option<KeyPair>,
69
}
70
71
impl Client {
7227×
    pub fn new(socket: &Path, signer: Option<KeyPair>) -> Client {
7327×
        Client { endpoint: Endpoint::Unix(socket.to_path_buf()), signer }
7427×
    }
75
7650×
    pub fn at(endpoint: Endpoint, signer: Option<KeyPair>) -> Client {
7750×
        Client { endpoint, signer }
7850×
    }
79
800×
    pub fn endpoint(&self) -> &Endpoint {
810×
        &self.endpoint
820×
    }
83
84153×
    async fn io(&self) -> Result<Box<dyn Io>> {
85153×
        Ok(match &self.endpoint {
8692×
            Endpoint::Unix(socket) => Box::new(
8792×
                tokio::net::UnixStream::connect(socket)
8892×
                    .await
8992×
                    .with_context(|| format!("connecting to {} (is `spectra serve` running?)", socket.display()))?,
90
            ),
9161×
            Endpoint::Tls { addr, config } => Box::new(crate::tls::connect(addr, config.clone()).await?),
92
        })
93153×
    }
94
95
    /// Whether the daemon answers at the endpoint.
960×
    pub async fn reachable(&self) -> bool {
970×
        self.io().await.is_ok()
980×
    }
99
100
    /// Whether a daemon answers on the socket.
10181×
    pub async fn alive(socket: &Path) -> bool {
10281×
        tokio::net::UnixStream::connect(socket).await.is_ok()
10381×
    }
104
105
    /// Send `method path` with `body` and extra headers, signed.
106153×
    pub async fn send(&self, method: &str, path: &str, headers: &[(&str, String)], body: Vec<u8>) -> Result<Response> {
107153×
        let stream = self.io().await?;
108151×
        let (mut sender, conn) = hyper::client::conn::http1::handshake(hyper_util::rt::TokioIo::new(stream)).await?;
109151×
        tokio::spawn(async move {
110151×
            let _ = conn.await;
111151×
        });
112
        // One request a connection: the server closes it after answering, so
113
        // nothing lingers to hold up its shutdown.
114151×
        let mut req = hyper::Request::builder().method(method).uri(path).header("host", "spectra").header("connection", "close");
115
        // JSON unless the caller says otherwise (a form, say).
116162×
        if !headers.iter().any(|(k, _)| k.eq_ignore_ascii_case("content-type")) {
117147×
            req = req.header("content-type", "application/json");
118147×
        }
119163×
        for (k, v) in headers {
120163×
            req = req.header(*k, v);
121163×
        }
122151×
        if let Some(pair) = &self.signer {
123380×
            for (k, v) in sign_headers(pair, &format!("{method} {path}"), &body) {
124380×
                req = req.header(k, v);
125380×
            }
12656×
        }
127151×
        let resp = sender.send_request(req.body(Full::new(Bytes::from(body)))?).await?;
128151×
        let status = resp.status().as_u16();
129711×
        let headers = resp.headers().iter().map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string())).collect();
130151×
        let body = resp.into_body().collect().await?.to_bytes().to_vec();
131151×
        Ok(Response { status, headers, body })
132153×
    }
133
134
    /// A JSON-RPC request to `/mcp` with the protocol headers of `version`.
13538×
    pub async fn mcp(&self, version: &str, request: &serde_json::Value) -> Result<Response> {
13638×
        let method = request.get("method").and_then(|m| m.as_str()).unwrap_or("").to_string();
13738×
        let mut headers = vec![
13838×
            ("accept", "application/json, text/event-stream".to_string()),
13938×
            ("mcp-protocol-version", version.to_string()),
14038×
            ("mcp-method", method.clone()),
141
        ];
14238×
        if let Some(name) = request.pointer("/params/name").or_else(|| request.pointer("/params/uri")).and_then(|n| n.as_str()) {
14327×
            headers.push(("mcp-name", name.to_string()));
14427×
        }
14538×
        self.send("POST", "/mcp", &headers, serde_json::to_vec(request)?).await
14638×
    }
147
}
148
149
impl Client {
150
    /// Pass a request through as it is, unsigned, and hand back the
151
    /// response with its body still streaming (Radar's proxy, spec §8.6).
1520×
    pub async fn forward(&self, req: hyper::Request<Full<Bytes>>) -> Result<hyper::Response<hyper::body::Incoming>> {
1530×
        let stream = self.io().await?;
1540×
        let (mut sender, conn) = hyper::client::conn::http1::handshake(hyper_util::rt::TokioIo::new(stream)).await?;
1550×
        tokio::spawn(async move {
1560×
            let _ = conn.await;
1570×
        });
1580×
        Ok(sender.send_request(req).await?)
1590×
    }
160
161
    /// Send a signed GET and hand each line of the streamed body to `line`
162
    /// as it arrives (an SSE stream, say); stop when it returns false.
1630×
    pub async fn stream(&self, path: &str, mut line: impl FnMut(&str) -> bool) -> Result<u16> {
1640×
        let stream = self.io().await?;
1650×
        let (mut sender, conn) = hyper::client::conn::http1::handshake(hyper_util::rt::TokioIo::new(stream)).await?;
1660×
        tokio::spawn(async move {
1670×
            let _ = conn.await;
1680×
        });
1690×
        let mut req = hyper::Request::builder().method("GET").uri(path).header("host", "spectra").header("connection", "close");
1700×
        if let Some(pair) = &self.signer {
1710×
            for (k, v) in sign_headers(pair, &format!("GET {path}"), b"") {
1720×
                req = req.header(k, v);
1730×
            }
1740×
        }
1750×
        let resp = sender.send_request(req.body(Full::new(Bytes::new()))?).await?;
1760×
        let status = resp.status().as_u16();
1770×
        let mut body = resp.into_body();
1780×
        let mut buf = String::new();
1790×
        while let Some(frame) = body.frame().await {
1800×
            if let Ok(data) = frame?.into_data() {
1810×
                buf.push_str(&String::from_utf8_lossy(&data));
1820×
                while let Some(i) = buf.find('\n') {
1830×
                    let l: String = buf.drain(..=i).collect();
1840×
                    if !line(l.trim_end()) {
1850×
                        return Ok(status);
1860×
                    }
187
                }
1880×
            }
189
        }
1900×
        Ok(status)
1910×
    }
192
}
193
194
/// The signature headers of spec §8.5 for `method_path` and `body`.
19595×
pub fn sign_headers(pair: &KeyPair, method_path: &str, body: &[u8]) -> Vec<(&'static str, String)> {
19695×
    let p = Proof::sign(pair, method_path, body);
19795×
    vec![
19895×
        ("spectra-key", p.sig.key.to_hex()),
19995×
        ("spectra-time", p.time_ms.to_string()),
20095×
        ("spectra-nonce", hex::encode(p.nonce)),
20195×
        ("spectra-signature", hex::encode(spectra_core::cbor::encode(&p.sig.to_value()))),
202
    ]
20395×
}
204
205
/// The JSON-RPC result inside a response, whether it came as JSON or as
206
/// the last `data:` of an SSE stream.
20724×
pub fn rpc_result(r: &Response) -> Result<serde_json::Value> {
20824×
    let is_sse = r.header("content-type").is_some_and(|c| c.starts_with("text/event-stream"));
20924×
    if !is_sse {
21019×
        return r.json();
2115×
    }
2125×
    let text = String::from_utf8_lossy(&r.body);
2135×
    let last = text
2145×
        .lines()
2155×
        .rev()
21610×
        .filter_map(|l| l.strip_prefix("data:"))
2175×
        .map(str::trim)
2185×
        .find(|l| !l.is_empty())
2195×
        .context("an SSE response with no data")?;
2205×
    Ok(serde_json::from_str(last)?)
22124×
}