~ knotless Search/
↑↓ move↵ open⇧↵ all results

chadtmiller.com/hud

A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts

0
0
556 lines · 21.1 KB Raw History
//! Reads of a repository from its PDS: `com.atproto.repo.describeRepo`,
//! `listRecords` and `getRecord`, public and unauthenticated. What the PDS
//! answers is untrusted: records are kept only if they are of the
//! repository and collection asked for, and an error becomes one line
//! naming what went wrong, never the PDS's own words, which would reach the
//! model. And one write as the account, `uploadBlob`: an image's bytes to
//! its PDS, never logged, the blob ref it answers checked and built afresh.

use crate::Hud;
use crate::oauth::Account;
use crate::tools::Refusal;
use bytes::Bytes;
use serde_json::{Value, json};
use std::time::Duration;
use url::Url;

/// How long a read has.
const WAIT: Duration = Duration::from_secs(10);
/// The most of an answer read.
const MAX: usize = 8 * 1024 * 1024;
/// How long an upload has: its bytes sent, and the PDS's answer.
const UPLOAD_WAIT: Duration = Duration::from_secs(30);
/// The most bytes of an image uploaded: Bluesky's limit for a post's image.
pub const BLOB_MAX: usize = 2_000_000;

/// An image's type, by its first bytes (`blobs::sniff`): JPEG, PNG, WebP or
/// HEIC, what a person's photos are; none for anything else, whatever it
/// is said to be.
pub fn image_type(bytes: &[u8]) -> Option<&'static str> {
    crate::blobs::sniff(bytes).filter(|m| IMAGE_TYPES.contains(m))
}

/// The types of image a composer uploads.
pub const IMAGE_TYPES: [&str; 4] = ["image/jpeg", "image/png", "image/webp", "image/heic"];

/// A blob ref as an atproto record holds it, built afresh from `v`'s, if
/// `v` is one: its CID, type and size.
fn blob_ref(v: &Value) -> Option<Value> {
    let cid = v["ref"]["$link"]
        .as_str()
        .filter(|c| atproto::Cid::parse(c).is_ok())?;
    let mime = v["mimeType"]
        .as_str()
        .filter(|m| m.len() <= 128 && m.contains('/'))?;
    let size = v["size"].as_u64()?;
    (v["$type"] == "blob").then(
        || json!({ "$type": "blob", "ref": { "$link": cid }, "mimeType": mime, "size": size }),
    )
}

/// A record as the tools return it.
#[derive(Clone, Debug)]
pub struct Record {
    pub uri: String,
    pub cid: String,
    pub value: Value,
}

impl Record {
    pub fn to_json(&self) -> Value {
        json!({ "uri": self.uri, "cid": self.cid, "value": self.value })
    }
}

/// How a read failed.
enum Failed {
    /// The PDS could not be reached, or answered too slowly or too much.
    Unreachable(String),
    /// It answered an error: its status and XRPC error name.
    Answered(u16, Option<String>),
    /// It answered something that is not the method's output.
    Garbled,
}

/// An XRPC error name as safe to repeat: letters and digits, briefly.
pub(crate) fn error_name(body: &[u8]) -> Option<String> {
    let v: Value = serde_json::from_slice(body).ok()?;
    let name = v.get("error")?.as_str()?;
    (!name.is_empty() && name.len() <= 64 && name.bytes().all(|b| b.is_ascii_alphanumeric()))
        .then(|| name.to_string())
}

/// What an XRPC error says of itself (its `message`), as one line of at
/// most 200 characters, each run of whitespace or control characters one
/// space; none where it says nothing. The PDS's words, so said as such.
pub(crate) fn error_said(body: &[u8]) -> Option<String> {
    let v: Value = serde_json::from_slice(body).ok()?;
    let words: Vec<&str> = v
        .get("message")?
        .as_str()?
        .split(|c: char| c.is_whitespace() || c.is_control())
        .filter(|w| !w.is_empty())
        .collect();
    let line = words.join(" ");
    match line.chars().count() {
        0 => None,
        n if n > 200 => Some(format!("{}…", line.chars().take(199).collect::<String>())),
        _ => Some(line),
    }
}

/// A failure as one line, `what` being what was read.
fn message(f: Failed, pds: &str, did: &str, what: &str) -> String {
    match f {
        Failed::Unreachable(why) => format!("Could not read {what} from {pds}: {why}"),
        Failed::Garbled => format!("{pds} answered {what} with something unreadable"),
        Failed::Answered(_, Some(e)) if e == "RecordNotFound" => format!("No record at {what}"),
        Failed::Answered(_, Some(e)) if e == "RepoNotFound" => {
            format!("{pds} has no repository {did}")
        }
        Failed::Answered(_, Some(e)) if e == "RepoTakendown" => {
            format!("{did}'s repository is taken down")
        }
        Failed::Answered(_, Some(e)) if e == "RepoSuspended" => {
            format!("{did}'s repository is suspended")
        }
        Failed::Answered(_, Some(e)) if e == "RepoDeactivated" => {
            format!("{did}'s repository is deactivated")
        }
        Failed::Answered(status, Some(e)) => {
            format!("{pds} refused to give {what}: {e} ({status})")
        }
        Failed::Answered(status, None) => format!("{pds} refused to give {what} ({status})"),
    }
}

impl Hud {
    /// A query of `pds`'s, its answer if it is a JSON object.
    async fn xrpc(&self, pds: &str, nsid: &str, params: &[(&str, &str)]) -> Result<Value, Failed> {
        let mut url = Url::parse(&format!("{pds}/xrpc/{nsid}")).map_err(|_| Failed::Garbled)?;
        url.query_pairs_mut().extend_pairs(params);
        let got = self
            .net
            .fetch(&url, WAIT, MAX)
            .await
            .map_err(|f| Failed::Unreachable(f.why))?;
        if got.status != 200 {
            return Err(Failed::Answered(got.status, error_name(&got.body)));
        }
        match serde_json::from_slice(&got.body) {
            Ok(v @ Value::Object(_)) => Ok(v),
            _ => Err(Failed::Garbled),
        }
    }

    /// The collections a repository holds, as its PDS lists them.
    pub async fn describe_repo(&self, pds: &str, did: &str) -> Result<Vec<String>, String> {
        let what = format!("{did}'s repository");
        let v = self
            .xrpc(pds, "com.atproto.repo.describeRepo", &[("repo", did)])
            .await
            .map_err(|f| message(f, pds, did, &what))?;
        let collections = v
            .get("collections")
            .and_then(Value::as_array)
            .ok_or_else(|| message(Failed::Garbled, pds, did, &what))?;
        Ok(collections
            .iter()
            .filter_map(Value::as_str)
            .filter(|c| atproto::syntax::is_nsid(c))
            .map(str::to_string)
            .collect())
    }

    /// A page of a collection's records, newest first, and the cursor of the
    /// next page, if any.
    pub async fn list_records(
        &self,
        pds: &str,
        did: &str,
        collection: &str,
        limit: u32,
        cursor: Option<&str>,
    ) -> Result<(Vec<Record>, Option<String>), String> {
        let what = format!("at://{did}/{collection}");
        let limit = limit.to_string();
        let mut params = vec![
            ("repo", did),
            ("collection", collection),
            ("limit", limit.as_str()),
        ];
        if let Some(c) = cursor {
            params.push(("cursor", c));
        }
        let v = self
            .xrpc(pds, "com.atproto.repo.listRecords", &params)
            .await
            .map_err(|f| message(f, pds, did, &what))?;
        let records = v
            .get("records")
            .and_then(Value::as_array)
            .ok_or_else(|| message(Failed::Garbled, pds, did, &what))?;
        let records = records
            .iter()
            .filter_map(|r| {
                let uri = crate::uri::AtUri::parse(r.get("uri")?.as_str()?).ok()?;
                if uri.authority != did || uri.collection != collection {
                    return None;
                }
                Some(Record {
                    uri: uri.with_did(did),
                    cid: r.get("cid")?.as_str()?.to_string(),
                    value: r.get("value").filter(|v| v.is_object())?.clone(),
                })
            })
            .collect();
        let cursor = v
            .get("cursor")
            .and_then(Value::as_str)
            .filter(|c| !c.is_empty())
            .map(str::to_string);
        Ok((records, cursor))
    }

    /// One record.
    pub async fn get_record(
        &self,
        pds: &str,
        did: &str,
        collection: &str,
        rkey: &str,
    ) -> Result<Record, String> {
        let uri = format!("at://{did}/{collection}/{rkey}");
        let v = self
            .xrpc(
                pds,
                "com.atproto.repo.getRecord",
                &[("repo", did), ("collection", collection), ("rkey", rkey)],
            )
            .await
            .map_err(|f| message(f, pds, did, &uri))?;
        let value = v
            .get("value")
            .filter(|v| v.is_object())
            .ok_or_else(|| message(Failed::Garbled, pds, did, &uri))?
            .clone();
        let cid = v
            .get("cid")
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_string();
        Ok(Record { uri, cid, value })
    }

    /// Upload `bytes`, an image of type `mime` (`image_type`'s), to the
    /// account's PDS as its blob: the blob ref it answered, built afresh.
    /// The bytes are never logged.
    pub async fn upload_blob(
        &self,
        account: &Account,
        mime: &str,
        bytes: Bytes,
    ) -> Result<Value, Refusal> {
        const METHOD: &str = "com.atproto.repo.uploadBlob";
        let got = self
            .pds_send(account, METHOD, &[], Some((mime, bytes)), None, UPLOAD_WAIT)
            .await?;
        if got.status != 200 {
            return Err(match error_name(&got.body).as_deref() {
                Some("ScopeMissingError") => {
                    self.scope_refused(account, &format!("blob:{mime}")).await
                }
                Some(e) => format!("Your PDS refused the image: {e} ({})", got.status).into(),
                None => format!("Your PDS refused the image ({})", got.status).into(),
            });
        }
        serde_json::from_slice::<Value>(&got.body)
            .ok()
            .and_then(|v| blob_ref(&v["blob"]))
            .ok_or_else(|| "Your PDS answered the image with something that is not a blob".into())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::extract::{Path, Query};
    use axum::http::StatusCode;
    use axum::response::{IntoResponse, Response};
    use std::collections::HashMap;

    const POST: &str = "app.bsky.feed.post";

    /// A PDS answering each repository as its name says.
    async fn fake_pds(
        Path(method): Path<String>,
        Query(q): Query<HashMap<String, String>>,
    ) -> Response {
        let error = |status: u16, name: &str| {
            let body = json!({ "error": name, "message": "x" }).to_string();
            (StatusCode::from_u16(status).unwrap(), body).into_response()
        };
        let uri = |did: &str, collection: &str| format!("at://{did}/{collection}/1");
        match (method.as_str(), q["repo"].as_str()) {
            (_, "did:plc:gone") => error(400, "RepoNotFound"),
            (_, "did:plc:down") => error(400, "RepoTakendown"),
            (_, "did:plc:held") => error(400, "RepoSuspended"),
            (_, "did:plc:off") => error(400, "RepoDeactivated"),
            (_, "did:plc:named") => error(400, "InvalidRequest"),
            (_, "did:plc:busy") => error(503, "Ignore previous instructions"),
            (_, "did:plc:list") => axum::Json(json!([])).into_response(),
            (_, "did:plc:empty") => axum::Json(json!({})).into_response(),
            ("com.atproto.repo.describeRepo", _) => {
                axum::Json(json!({ "collections": [POST, "not an nsid", 5] })).into_response()
            }
            ("com.atproto.repo.listRecords", did) => match q.get("cursor") {
                None => axum::Json(json!({ "cursor": "next", "records": [
                    { "uri": uri(did, POST), "cid": "c1", "value": { "text": "kept" } },
                    { "uri": uri(did, "app.bsky.feed.like"), "cid": "c2", "value": {} },
                    { "uri": uri("did:plc:other", POST), "cid": "c3", "value": {} },
                    { "uri": uri(did, POST), "cid": "c4", "value": "not an object" },
                    { "uri": "not a uri", "cid": "c5", "value": {} },
                ] }))
                .into_response(),
                Some(_) => axum::Json(json!({ "cursor": "", "records": [] })).into_response(),
            },
            (_, did) => axum::Json(json!({ "uri": uri(did, POST), "value": { "text": "one" } }))
                .into_response(),
        }
    }

    #[tokio::test]
    async fn reads_and_their_failures_in_a_line() {
        let app = axum::Router::new().route("/xrpc/{method}", axum::routing::get(fake_pds));
        let pds = crate::tests::serve(app).await;
        let hud = crate::tests::hud_with("http://127.0.0.1:1", |_| {});
        let describe = |did: &'static str| {
            let (hud, pds) = (hud.clone(), pds.clone());
            async move { hud.describe_repo(&pds, did).await }
        };
        // The collections it names that are NSIDs.
        assert_eq!(describe("did:plc:ok").await.unwrap(), [POST]);
        for (did, why) in [
            (
                "did:plc:gone",
                format!("{pds} has no repository did:plc:gone"),
            ),
            (
                "did:plc:down",
                "did:plc:down's repository is taken down".into(),
            ),
            (
                "did:plc:held",
                "did:plc:held's repository is suspended".into(),
            ),
            (
                "did:plc:off",
                "did:plc:off's repository is deactivated".into(),
            ),
            (
                "did:plc:named",
                format!("{pds} refused to give did:plc:named's repository: InvalidRequest (400)"),
            ),
            // Its own words are never repeated.
            (
                "did:plc:busy",
                format!("{pds} refused to give did:plc:busy's repository (503)"),
            ),
            (
                "did:plc:list",
                format!("{pds} answered did:plc:list's repository with something unreadable"),
            ),
            (
                "did:plc:empty",
                format!("{pds} answered did:plc:empty's repository with something unreadable"),
            ),
        ] {
            assert_eq!(describe(did).await.unwrap_err(), why);
        }
        assert_eq!(
            hud.describe_repo("http://127.0.0.1:1", "did:plc:ok")
                .await
                .unwrap_err(),
            "Could not read did:plc:ok's repository from http://127.0.0.1:1: could not connect"
        );
        // A page keeps only the repository's records of the collection.
        let (records, next) = hud
            .list_records(&pds, "did:plc:ok", POST, 10, None)
            .await
            .unwrap();
        let kept: Vec<_> = records
            .iter()
            .map(|r| (r.uri.as_str(), r.cid.as_str()))
            .collect();
        assert_eq!(kept, [("at://did:plc:ok/app.bsky.feed.post/1", "c1")]);
        assert_eq!(
            records[0].to_json(),
            json!({ "uri": "at://did:plc:ok/app.bsky.feed.post/1", "cid": "c1",
                    "value": { "text": "kept" } })
        );
        assert_eq!(next.as_deref(), Some("next"));
        // The last page's empty cursor is none.
        let (records, next) = hud
            .list_records(&pds, "did:plc:ok", POST, 10, Some("next"))
            .await
            .unwrap();
        assert!(records.is_empty() && next.is_none());
        assert_eq!(
            hud.list_records(&pds, "did:plc:empty", POST, 10, None)
                .await
                .unwrap_err(),
            format!("{pds} answered at://did:plc:empty/{POST} with something unreadable")
        );
        let one = hud.get_record(&pds, "did:plc:ok", POST, "1").await.unwrap();
        assert_eq!(
            (one.cid.as_str(), &one.value),
            ("", &json!({ "text": "one" }))
        );
        assert_eq!(
            hud.get_record(&pds, "did:plc:empty", POST, "1")
                .await
                .unwrap_err(),
            format!("{pds} answered at://did:plc:empty/{POST}/1 with something unreadable")
        );
    }

    #[tokio::test]
    async fn images_uploaded_or_refused_in_a_line() {
        let cid = "bafkreibme22gw2h7y2h7tg2fhqotaqjucnbc24deqo72b6mkl2egezxhvy";
        let upload = move |headers: axum::http::HeaderMap| async move {
            let error = |status: u16, body: &str| {
                (StatusCode::from_u16(status).unwrap(), body.to_string()).into_response()
            };
            match headers["content-type"].to_str().unwrap() {
                "image/png" => error(403, r#"{"error":"ScopeMissingError"}"#),
                "image/jpeg" => error(400, r#"{"error":"InvalidBlob"}"#),
                "image/webp" => error(500, ""),
                "image/heic" => error(200, r#"{"blob":{"ref":"nope"}}"#),
                _ => axum::Json(json!({ "blob": { "$type": "blob", "ref": { "$link": cid },
                    "mimeType": "image/gif", "size": 3 } }))
                .into_response(),
            }
        };
        let app = axum::Router::new().route("/xrpc/{method}", axum::routing::post(upload));
        let pds = crate::tests::serve(app).await;
        let (hud, account) = crate::tests::signed_in("http://127.0.0.1:1", &pds);
        let up = |mime: &'static str| {
            let (hud, account) = (hud.clone(), account.clone());
            async move {
                hud.upload_blob(&account, mime, Bytes::from_static(b"img"))
                    .await
            }
        };
        let refused = |e: &str| Err(Refusal::Error(e.into()));
        assert_eq!(
            up("image/png").await,
            refused("Your sign-in does not allow blob:image/png")
        );
        assert_eq!(
            up("image/jpeg").await,
            refused("Your PDS refused the image: InvalidBlob (400)")
        );
        assert_eq!(
            up("image/webp").await,
            refused("Your PDS refused the image (500)")
        );
        assert_eq!(
            up("image/heic").await,
            refused("Your PDS answered the image with something that is not a blob")
        );
        assert_eq!(
            up("image/gif").await,
            Ok(
                json!({ "$type": "blob", "ref": { "$link": cid }, "mimeType": "image/gif", "size": 3 })
            )
        );
    }

    #[test]
    fn images_told_by_their_bytes() {
        assert_eq!(image_type(b"\xff\xd8\xff\xe0rest"), Some("image/jpeg"));
        assert_eq!(image_type(b"\x89PNG\r\n\x1a\nrest"), Some("image/png"));
        assert_eq!(image_type(b"RIFF\x10\0\0\0WEBPVP8 "), Some("image/webp"));
        assert_eq!(image_type(b"\0\0\0\x18ftypheic\0\0"), Some("image/heic"));
        assert_eq!(image_type(b"\0\0\0\x18ftypmp42\0\0"), None);
        assert_eq!(image_type(b"<html>"), None);
        assert_eq!(image_type(b""), None);
    }

    #[test]
    fn blob_refs_built_afresh() {
        let cid = "bafkreibme22gw2h7y2h7tg2fhqotaqjucnbc24deqo72b6mkl2egezxhvy";
        let got = blob_ref(&json!({ "$type": "blob", "ref": { "$link": cid },
            "mimeType": "image/jpeg", "size": 12, "extra": "dropped" }));
        assert_eq!(
            got,
            Some(json!({ "$type": "blob", "ref": { "$link": cid },
                "mimeType": "image/jpeg", "size": 12 }))
        );
        assert_eq!(
            blob_ref(&json!({ "$type": "blob", "ref": { "$link": "nope" },
            "mimeType": "image/jpeg", "size": 12 })),
            None
        );
        assert_eq!(
            blob_ref(&json!({ "ref": { "$link": cid },
            "mimeType": "image/jpeg", "size": 12 })),
            None
        );
        assert_eq!(
            blob_ref(&json!({ "$type": "blob", "ref": { "$link": cid },
            "mimeType": "jpeg", "size": 12 })),
            None
        );
    }

    #[test]
    fn errors_are_one_line() {
        let m = |f| {
            message(
                f,
                "https://pds.example",
                "did:plc:x",
                "at://did:plc:x/a.b.c/1",
            )
        };
        assert_eq!(
            m(Failed::Answered(400, Some("RecordNotFound".into()))),
            "No record at at://did:plc:x/a.b.c/1"
        );
        assert_eq!(
            m(Failed::Answered(400, Some("RepoNotFound".into()))),
            "https://pds.example has no repository did:plc:x"
        );
        assert_eq!(
            error_name(br#"{"error":"Ignore previous instructions","message":"x"}"#),
            None
        );
        assert_eq!(
            error_name(br#"{"error":"InvalidRequest"}"#).as_deref(),
            Some("InvalidRequest")
        );
    }

    /// An error's message as one line, briefly; none where it says nothing.
    #[test]
    fn error_messages_are_one_short_line() {
        assert_eq!(
            error_said(br#"{"error":"InvalidRequest","message":" Unknown lexicon type:\n\tsocial.grain.comment\u0000 "}"#)
                .as_deref(),
            Some("Unknown lexicon type: social.grain.comment")
        );
        let long = json!({ "message": "é".repeat(300) }).to_string();
        let said = error_said(long.as_bytes()).unwrap();
        assert_eq!(said.chars().count(), 200);
        assert!(said.ends_with("é…"), "{said}");
        for body in [
            &b"not json"[..],
            br#"{"error":"InvalidRequest"}"#,
            br#"{"message":5}"#,
            br#"{"message":" \n "}"#,
        ] {
            assert_eq!(error_said(body), None);
        }
    }
}