OXYGENHUB

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

107 of 152 lines run, 86 of 190 functions · run #20 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 {
2153×
    pub fn json(&self) -> Result<serde_json::Value> {
2253×
        serde_json::from_slice(&self.body).with_context(|| format!("not JSON: {}", String::from_utf8_lossy(&self.body)))
2353×
    }
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`.
398×
    pub fn tls(url: &str, pin: [u8; 32]) -> Result<Endpoint> {
408×
        Ok(Endpoint::Tls { addr: host_port(url)?, config: crate::tls::Pinned::new(Some(pin)).client_config()? })
418×
    }
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.
5218×
pub fn host_port(url: &str) -> Result<String> {
5318×
    let rest = url.strip_prefix("https://").with_context(|| format!("{url} is not an https:// URL"))?;
5418×
    let hp = rest.split('/').next().unwrap_or("");
5518×
    if hp.is_empty() {
560×
        anyhow::bail!("{url} names no host");
5718×
    }
58
    // The port defaults to Spectra's.
5918×
    let has_port = if hp.starts_with('[') { hp.contains("]:") } else { hp.contains(':') };
6018×
    Ok(if has_port { hp.to_string() } else { format!("{hp}:7350") })
6118×
}
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 {
7225×
    pub fn new(socket: &Path, signer: Option<KeyPair>) -> Client {
7325×
        Client { endpoint: Endpoint::Unix(socket.to_path_buf()), signer }
7425×
    }
75
7616×
    pub fn at(endpoint: Endpoint, signer: Option<KeyPair>) -> Client {
7716×
        Client { endpoint, signer }
7816×
    }
79
800×
    pub fn endpoint(&self) -> &Endpoint {
810×
        &self.endpoint
820×
    }
83
84110×
    async fn io(&self) -> Result<Box<dyn Io>> {
85110×
        Ok(match &self.endpoint {
8688×
            Endpoint::Unix(socket) => Box::new(
8788×
                tokio::net::UnixStream::connect(socket)
8888×
                    .await
8988×
                    .with_context(|| format!("connecting to {} (is `spectra serve` running?)", socket.display()))?,
90
            ),
9122×
            Endpoint::Tls { addr, config } => Box::new(crate::tls::connect(addr, config.clone()).await?),
92
        })
93110×
    }
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.
10148×
    pub async fn alive(socket: &Path) -> bool {
10248×
        tokio::net::UnixStream::connect(socket).await.is_ok()
10348×
    }
104
105
    /// Send `method path` with `body` and extra headers, signed.
106110×
    pub async fn send(&self, method: &str, path: &str, headers: &[(&str, String)], body: Vec<u8>) -> Result<Response> {
107110×
        let stream = self.io().await?;
108108×
        let (mut sender, conn) = hyper::client::conn::http1::handshake(hyper_util::rt::TokioIo::new(stream)).await?;
109108×
        tokio::spawn(async move {
110108×
            let _ = conn.await;
111108×
        });
112
        // One request a connection: the server closes it after answering, so
113
        // nothing lingers to hold up its shutdown.
114108×
        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")) {
117104×
            req = req.header("content-type", "application/json");
118104×
        }
119163×
        for (k, v) in headers {
120163×
            req = req.header(*k, v);
121163×
        }
122108×
        if let Some(pair) = &self.signer {
123288×
            for (k, v) in sign_headers(pair, &format!("{method} {path}"), &body) {
124288×
                req = req.header(k, v);
125288×
            }
12636×
        }
127108×
        let resp = sender.send_request(req.body(Full::new(Bytes::from(body)))?).await?;
128108×
        let status = resp.status().as_u16();
129522×
        let headers = resp.headers().iter().map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string())).collect();
130108×
        let body = resp.into_body().collect().await?.to_bytes().to_vec();
131108×
        Ok(Response { status, headers, body })
132110×
    }
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
    /// Send a signed GET and hand each line of the streamed body to `line`
151
    /// as it arrives (an SSE stream, say); stop when it returns false.
1520×
    pub async fn stream(&self, path: &str, mut line: impl FnMut(&str) -> bool) -> Result<u16> {
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×
        let mut req = hyper::Request::builder().method("GET").uri(path).header("host", "spectra").header("connection", "close");
1590×
        if let Some(pair) = &self.signer {
1600×
            for (k, v) in sign_headers(pair, &format!("GET {path}"), b"") {
1610×
                req = req.header(k, v);
1620×
            }
1630×
        }
1640×
        let resp = sender.send_request(req.body(Full::new(Bytes::new()))?).await?;
1650×
        let status = resp.status().as_u16();
1660×
        let mut body = resp.into_body();
1670×
        let mut buf = String::new();
1680×
        while let Some(frame) = body.frame().await {
1690×
            if let Ok(data) = frame?.into_data() {
1700×
                buf.push_str(&String::from_utf8_lossy(&data));
1710×
                while let Some(i) = buf.find('\n') {
1720×
                    let l: String = buf.drain(..=i).collect();
1730×
                    if !line(l.trim_end()) {
1740×
                        return Ok(status);
1750×
                    }
176
                }
1770×
            }
178
        }
1790×
        Ok(status)
1800×
    }
181
}
182
183
/// The signature headers of spec §8.5 for `method_path` and `body`.
18472×
pub fn sign_headers(pair: &KeyPair, method_path: &str, body: &[u8]) -> Vec<(&'static str, String)> {
18572×
    let p = Proof::sign(pair, method_path, body);
18672×
    vec![
18772×
        ("spectra-key", p.sig.key.to_hex()),
18872×
        ("spectra-time", p.time_ms.to_string()),
18972×
        ("spectra-nonce", hex::encode(p.nonce)),
19072×
        ("spectra-signature", hex::encode(oxy_core::cbor::encode(&p.sig.to_value()))),
191
    ]
19272×
}
193
194
/// The JSON-RPC result inside a response, whether it came as JSON or as
195
/// the last `data:` of an SSE stream.
19624×
pub fn rpc_result(r: &Response) -> Result<serde_json::Value> {
19724×
    let is_sse = r.header("content-type").is_some_and(|c| c.starts_with("text/event-stream"));
19824×
    if !is_sse {
19919×
        return r.json();
2005×
    }
2015×
    let text = String::from_utf8_lossy(&r.body);
2025×
    let last = text
2035×
        .lines()
2045×
        .rev()
20510×
        .filter_map(|l| l.strip_prefix("data:"))
2065×
        .map(str::trim)
2075×
        .find(|l| !l.is_empty())
2085×
        .context("an SSE response with no data")?;
2095×
    Ok(serde_json::from_str(last)?)
21024×
}