~ 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
358 lines · 12.9 KB Raw History
//! What sign-in keeps on disk, and how: a session (an account's atproto
//! tokens and DPoP key, and the SHA-256 of HUD's own tokens for it, never
//! the tokens), as JSON; and how a file is written, whole, mode 0600,
//! renamed into place so that a reader never sees half of one.

use atproto::jose;
use atproto::keys::{Curve, Keypair};
use serde_json::{Value, json};
use std::collections::BTreeMap;
use std::io::Write;
use std::path::Path;

/// The most replaced refresh tokens a session remembers, to know one used
/// again: the latest.
const REPLACED_MAX: usize = 50;

/// HUD's own tokens of a session, by their SHA-256: an MCP session's
/// access and refresh tokens; a web session's cookie, as its access token,
/// with no refresh token.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Mcp {
    pub access: String,
    pub access_exp: u64,
    pub refresh: Option<String>,
    pub refresh_exp: u64,
    /// Refresh tokens rotated out, newest last: one used again ends the
    /// session.
    pub replaced: Vec<String>,
}

impl Mcp {
    /// Note a refresh token rotated out.
    pub fn replace(&mut self, hash: String) {
        self.replaced.push(hash);
        if self.replaced.len() > REPLACED_MAX {
            self.replaced.remove(0);
        }
    }
}

/// Whom a session was given to: an MCP client, or the workspace's page.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum Kind {
    Mcp,
    Web,
}

/// A signed-in account: its atproto session at its PDS, and HUD's session
/// with the MCP client or the web page it was given to.
#[derive(Clone, Debug)]
pub(crate) struct Session {
    /// Random; its file is named by its SHA-256.
    pub id: String,
    pub did: String,
    /// Its handle, verified both ways when it signed in.
    pub handle: Option<String>,
    pub pds: String,
    /// The authorization server that signed it in.
    pub issuer: String,
    pub token_endpoint: String,
    pub revocation_endpoint: Option<String>,
    /// The atproto scope granted.
    pub scope: String,
    /// The atproto scope HUD asked for when it signed in (`scope::asked`
    /// then), which a PDS may have granted less of: what `scope::behind`
    /// holds against what HUD asks for now.
    pub asked: String,
    pub access_token: String,
    pub refresh_token: Option<String>,
    /// When the atproto access token expires, in seconds since 1970.
    pub expires_at: u64,
    /// The DPoP key its atproto tokens are bound to.
    pub dpop: Keypair,
    /// The last DPoP nonce each origin gave.
    pub nonces: BTreeMap<String, String>,
    /// The MCP client it was given to; empty for a web session.
    pub client_id: String,
    pub kind: Kind,
    pub mcp: Mcp,
    pub created_at: u64,
    /// Ended: kept no more, and refused to whoever still holds it.
    pub ended: bool,
}

impl Session {
    pub fn to_json(&self) -> Value {
        json!({
            "id": self.id,
            "did": self.did,
            "handle": self.handle,
            "pds": self.pds,
            "issuer": self.issuer,
            "tokenEndpoint": self.token_endpoint,
            "revocationEndpoint": self.revocation_endpoint,
            "scope": self.scope,
            "asked": self.asked,
            "accessToken": self.access_token,
            "refreshToken": self.refresh_token,
            "expiresAt": self.expires_at,
            "dpopKey": jose::b64(self.dpop.to_bytes()),
            "nonces": self.nonces,
            "clientId": self.client_id,
            "kind": match self.kind {
                Kind::Mcp => "mcp",
                Kind::Web => "web",
            },
            "mcp": {
                "access": self.mcp.access,
                "accessExp": self.mcp.access_exp,
                "refresh": self.mcp.refresh,
                "refreshExp": self.mcp.refresh_exp,
                "replaced": self.mcp.replaced,
            },
            "createdAt": self.created_at,
        })
    }

    /// A session as `to_json` wrote it; none if it is not one.
    pub fn from_json(v: &Value) -> Option<Session> {
        let text = |k: &str| v.get(k)?.as_str().map(str::to_string);
        let maybe = |k: &str| match v.get(k) {
            None | Some(Value::Null) => Some(None),
            Some(Value::String(s)) => Some(Some(s.clone())),
            Some(_) => None,
        };
        let number = |o: &Value, k: &str| o.get(k)?.as_u64();
        let secret = jose::unb64(&text("dpopKey")?)?;
        let m = v.get("mcp")?;
        let strings = |o: &Value, k: &str| -> Option<Vec<String>> {
            o.get(k)?
                .as_array()?
                .iter()
                .map(|s| s.as_str().map(str::to_string))
                .collect()
        };
        let nonces: Option<BTreeMap<String, String>> = v
            .get("nonces")?
            .as_object()?
            .iter()
            .map(|(k, n)| Some((k.clone(), n.as_str()?.to_string())))
            .collect();
        let mcp_refresh = match m.get("refresh") {
            None | Some(Value::Null) => None,
            Some(r) => Some(r.as_str()?.to_string()),
        };
        // Sessions kept before web sessions were are MCP sessions.
        let kind = match v.get("kind").and_then(Value::as_str) {
            None | Some("mcp") => Kind::Mcp,
            Some("web") => Kind::Web,
            Some(_) => return None,
        };
        Some(Session {
            id: text("id")?,
            did: text("did")?,
            handle: maybe("handle")?,
            pds: text("pds")?,
            issuer: text("issuer")?,
            token_endpoint: text("tokenEndpoint")?,
            revocation_endpoint: maybe("revocationEndpoint")?,
            scope: text("scope")?,
            // Kept before what was asked was: what was granted.
            asked: text("asked").or_else(|| text("scope"))?,
            access_token: text("accessToken")?,
            refresh_token: maybe("refreshToken")?,
            expires_at: number(v, "expiresAt")?,
            dpop: Keypair::from_bytes(Curve::P256, &secret).ok()?,
            nonces: nonces?,
            client_id: text("clientId")?,
            kind,
            mcp: Mcp {
                access: m.get("access")?.as_str()?.to_string(),
                access_exp: number(m, "accessExp")?,
                refresh: mcp_refresh,
                refresh_exp: number(m, "refreshExp")?,
                replaced: strings(m, "replaced")?,
            },
            created_at: number(v, "createdAt")?,
            ended: false,
        })
    }
}

/// Make `dir` and its parents, mode 0700 where made.
pub(crate) fn make_dir(dir: &Path) -> std::io::Result<()> {
    let mut b = std::fs::DirBuilder::new();
    b.recursive(true);
    #[cfg(unix)]
    std::os::unix::fs::DirBuilderExt::mode(&mut b, 0o700);
    b.create(dir)
}

/// Write `bytes` to `path` whole: to a scratch file beside it, mode 0600,
/// renamed over it.
pub(crate) fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
    if let Some(dir) = path.parent() {
        make_dir(dir)?;
    }
    let scratch = path.with_extension(format!("tmp.{}", jose::random(6)));
    let write = || -> std::io::Result<()> {
        let mut o = std::fs::OpenOptions::new();
        o.write(true).create_new(true);
        #[cfg(unix)]
        std::os::unix::fs::OpenOptionsExt::mode(&mut o, 0o600);
        let mut f = o.open(&scratch)?;
        f.write_all(bytes)?;
        f.sync_all()?;
        std::fs::rename(&scratch, path)
    };
    write().inspect_err(|_| {
        let _ = std::fs::remove_file(&scratch);
    })
}

/// HUD's client key as a private JWK, to keep.
pub(crate) fn key_to_jwk(key: &Keypair, kid: &str) -> Value {
    let mut jwk = jose::jwk(&key.public());
    jwk["d"] = jose::b64(key.to_bytes()).into();
    jwk["kid"] = kid.into();
    jwk
}

/// The key a private JWK `key_to_jwk` wrote holds.
pub(crate) fn key_from_jwk(jwk: &Value) -> Option<Keypair> {
    if jwk["kty"] != "EC" || jwk["crv"] != "P-256" {
        return None;
    }
    let secret = jose::unb64(jwk["d"].as_str()?)?;
    let key = Keypair::from_bytes(Curve::P256, &secret).ok()?;
    // Its public part, if written, must be this key's.
    let public = jose::jwk(&key.public());
    (jwk["x"] == public["x"] && jwk["y"] == public["y"]).then_some(key)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn session() -> Session {
        Session {
            id: "sid".into(),
            did: "did:plc:alice".into(),
            handle: Some("alice.test".into()),
            pds: "https://pds.example".into(),
            issuer: "https://pds.example".into(),
            token_endpoint: "https://pds.example/oauth/token".into(),
            revocation_endpoint: None,
            scope: "atproto repo:app.bsky.feed.like".into(),
            asked: "atproto repo:app.bsky.feed.like space:place.hud.workspace".into(),
            access_token: "at".into(),
            refresh_token: Some("rt".into()),
            expires_at: 10,
            dpop: Keypair::generate(Curve::P256),
            nonces: BTreeMap::from([("https://pds.example".into(), "n1".into())]),
            client_id: "https://client.example/meta.json".into(),
            kind: Kind::Mcp,
            mcp: Mcp {
                access: "a".into(),
                access_exp: 20,
                refresh: None,
                refresh_exp: 30,
                replaced: vec!["old".into()],
            },
            created_at: 1,
            ended: false,
        }
    }

    #[test]
    fn sessions_round_trip() {
        let s = session();
        let back = Session::from_json(&s.to_json()).unwrap();
        assert_eq!(back.to_json(), s.to_json());
        assert_eq!(back.dpop.to_bytes(), s.dpop.to_bytes());
        let mut broken = s.to_json();
        broken["mcp"]["accessExp"] = "soon".into();
        assert!(Session::from_json(&broken).is_none());
        // A web session reads back as one; a session kept before web
        // sessions were, with no kind, as an MCP session.
        let mut web = s.clone();
        web.kind = Kind::Web;
        assert_eq!(Session::from_json(&web.to_json()).unwrap().kind, Kind::Web);
        let mut old = s.to_json();
        old.as_object_mut().unwrap().remove("kind");
        assert_eq!(Session::from_json(&old).unwrap().kind, Kind::Mcp);
        // A session kept before what was asked was: what was granted.
        old.as_object_mut().unwrap().remove("asked");
        assert_eq!(Session::from_json(&old).unwrap().asked, s.scope);
        // Anything else of the wrong shape is no session.
        for (k, v) in [
            ("handle", json!(5)),
            ("nonces", json!([])),
            ("kind", json!("robot")),
        ] {
            let mut bad = s.to_json();
            bad[k] = v;
            assert!(Session::from_json(&bad).is_none(), "{k}");
        }
        let mut bad = s.to_json();
        bad["mcp"]["replaced"] = json!("old");
        assert!(Session::from_json(&bad).is_none());
    }

    #[test]
    fn replaced_tokens_remembered_to_the_latest_fifty() {
        let mut m = session().mcp;
        for i in 0..60 {
            m.replace(format!("r{i}"));
        }
        assert_eq!(m.replaced.len(), REPLACED_MAX);
        assert_eq!(m.replaced.first().map(String::as_str), Some("r10"));
        assert_eq!(m.replaced.last().map(String::as_str), Some("r59"));
    }

    #[test]
    fn keys_and_files() {
        let key = Keypair::generate(Curve::P256);
        let jwk = key_to_jwk(&key, "k1");
        assert_eq!(
            key_from_jwk(&jwk).unwrap().to_bytes(),
            key.to_bytes(),
            "a key read back is the key written"
        );
        let mut other = jwk.clone();
        other["x"] = jose::jwk(&Keypair::generate(Curve::P256).public())["x"].clone();
        assert!(key_from_jwk(&other).is_none());
        let mut rsa = jwk.clone();
        rsa["kty"] = "RSA".into();
        assert!(key_from_jwk(&rsa).is_none());
        let dir = std::env::temp_dir().join(format!("hud-store-{}", jose::random(6)));
        let path = dir.join("a/b.json");
        write_private(&path, b"one").unwrap();
        write_private(&path, b"two").unwrap();
        assert_eq!(std::fs::read(&path).unwrap(), b"two");
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = std::fs::metadata(&path).unwrap().permissions().mode();
            assert_eq!(mode & 0o777, 0o600);
        }
        assert_eq!(
            std::fs::read_dir(path.parent().unwrap()).unwrap().count(),
            1
        );
        // A file that cannot be put in place leaves no scratch file behind;
        // a path that names no file is refused.
        let taken = dir.join("taken");
        std::fs::create_dir_all(taken.join("inside")).unwrap();
        assert!(write_private(&taken, b"x").is_err());
        let mut left: Vec<_> = std::fs::read_dir(&dir)
            .unwrap()
            .map(|e| e.unwrap().file_name())
            .collect();
        left.sort();
        assert_eq!(left, ["a", "taken"]);
        assert!(write_private(Path::new("/"), b"x").is_err());
        std::fs::remove_dir_all(dir).unwrap();
    }
}