~ 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
3502 lines · 128.3 KB Raw History
//! Sign-in, offline: the MCP authorization server's checks, and whole
//! sign-ins against a fake PDS and authorization server (axum, on a
//! loopback port), which holds HUD's client assertions and DPoP proofs to
//! what a PDS checks, asks for DPoP nonces, and counts what it is asked.

use super::*;
use crate::backlinks::Backlinks;
use crate::tools::Refusal;
use atproto::keys::PublicKey;
use axum::Router;
use axum::extract::{Path as UrlPath, State};
use axum::http::{HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use issuer::{Authorized, NotAuthorized};
use std::collections::HashMap;
use std::sync::Mutex as StdMutex;
use url::Url;

mod spaces;

const DID: &str = "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa";
const OTHER: &str = "did:plc:bbbbbbbbbbbbbbbbbbbbbbbb";
const ORIGIN: &str = "https://hud.test";
const REDIRECT: &str = "http://127.0.0.1/cb";
const CID: &str = "bafyreie5737gdxlw5i64vzichcalba3z2v5n6icifvx5xytvske7mr3hpm";

fn pairs(p: &[(&str, &str)]) -> Vec<(String, String)> {
    p.iter()
        .map(|(k, v)| (k.to_string(), v.to_string()))
        .collect()
}

fn query_of(url: &str) -> HashMap<String, String> {
    Url::parse(url)
        .unwrap()
        .query_pairs()
        .into_owned()
        .collect()
}

/// The configuration of a server with sign-in on, its data in a directory
/// of its own, its PLC directory `plc`.
fn config(plc: &str) -> crate::Config {
    let dir = std::env::temp_dir().join(format!("hud-oauth-{}", jose::random(6)));
    crate::Config {
        port: 0,
        bind: "::".parse().unwrap(),
        public_origin: ORIGIN.into(),
        cache_dir: dir.join("cache"),
        blob_cache_bytes: 0,
        cache_memory_bytes: 1 << 24,
        data_dir: dir,
        oauth: true,
        oauth_scope: crate::scope::asked(crate::view::views(), true, false),
        oauth_include: None,
        workspace: true,
        spaces: false,
        plc_url: plc.into(),
        handle_resolver: None,
        allow_private: true,
        backlinks: Backlinks::None,
        favicons: None,
        image_cdn: None,
        relay: None,
        sign_up_pds: crate::config::SIGN_UP_PDS.into(),
        client: Default::default(),
        operators: Vec::new(),
        logs: false,
        logs_keep: crate::logs::KEEP,
    }
}

/// A server with sign-in on, its data in a directory of its own, its PLC
/// directory `plc`.
fn hud(plc: &str) -> Arc<Hud> {
    Hud::new(config(plc)).unwrap()
}

/// A client registered with one loopback redirect URI, and the refresh
/// grant.
fn client(hud: &Hud) -> String {
    let body = json!({ "redirect_uris": [REDIRECT], "client_name": "Test host",
        "grant_types": ["authorization_code", "refresh_token"],
        "token_endpoint_auth_method": "none" });
    let c = hud.register(body.to_string().as_bytes()).unwrap();
    c["client_id"].as_str().unwrap().to_string()
}

/// An authorization request's params, with PKCE of `verifier`.
fn authorize_params(client_id: &str, verifier: &str) -> Vec<(String, String)> {
    pairs(&[
        ("client_id", client_id),
        ("redirect_uri", REDIRECT),
        ("response_type", "code"),
        ("code_challenge", &jose::sha256(verifier)),
        ("code_challenge_method", "S256"),
        ("resource", "https://hud.test/mcp"),
        ("state", "s1"),
    ])
}

#[test]
fn metadata_documents() {
    let h = hud("http://127.0.0.1:9");
    let a = h.auth().unwrap();
    assert_eq!(
        a.protected_resource(),
        json!({ "resource": "https://hud.test/mcp", "authorization_servers": [ORIGIN],
                "scopes_supported": ["hud"], "bearer_methods_supported": ["header"] })
    );
    let m = a.authorization_server();
    assert_eq!(m["issuer"], ORIGIN);
    for (k, path) in [
        ("authorization_endpoint", "/oauth/authorize"),
        ("token_endpoint", "/oauth/token"),
        ("revocation_endpoint", "/oauth/revoke"),
        ("registration_endpoint", "/oauth/register"),
    ] {
        assert_eq!(m[k], format!("{ORIGIN}{path}"), "{k}");
    }
    assert_eq!(m["code_challenge_methods_supported"], json!(["S256"]));
    assert_eq!(m["token_endpoint_auth_methods_supported"], json!(["none"]));
    assert_eq!(m["client_id_metadata_document_supported"], json!(true));
    assert_eq!(
        m["authorization_response_iss_parameter_supported"],
        json!(true)
    );
    assert_eq!(m["scopes_supported"], json!(["hud"]));
    let c = a.client_metadata();
    assert_eq!(
        c["client_id"],
        "https://hud.test/oauth/client-metadata.json"
    );
    assert_eq!(
        c["redirect_uris"],
        json!(["https://hud.test/oauth/callback"])
    );
    assert_eq!(c["token_endpoint_auth_method"], "private_key_jwt");
    assert_eq!(c["token_endpoint_auth_signing_alg"], "ES256");
    assert_eq!(c["jwks_uri"], "https://hud.test/oauth/jwks.json");
    assert_eq!(c["dpop_bound_access_tokens"], json!(true));
    assert_eq!(
        c["scope"],
        json!(crate::scope::asked(crate::view::views(), true, false))
    );
    assert_eq!(c["application_type"], "web");
    assert_eq!(c["client_uri"], ORIGIN);
    assert_eq!(c["client_name"], "HUD");
    assert!(c.get("logo_uri").is_none());
    // The key published is the one that signs, and outlives a restart.
    let jwk = &a.jwks()["keys"][0];
    assert!(jwk.get("d").is_none());
    assert_eq!(jwk["kid"], a.kid.as_str());
    assert_eq!(jwk["alg"], "ES256");
    let again = Auth::open(ORIGIN, "atproto", a.dir.parent().unwrap()).unwrap();
    assert_eq!(again.kid, a.kid);
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mode = std::fs::metadata(a.dir.join("client-key.json"))
            .unwrap()
            .permissions()
            .mode();
        assert_eq!(mode & 0o777, 0o600);
    }
}

#[test]
fn assertions_and_proofs() {
    let h = hud("http://127.0.0.1:9");
    let a = h.auth().unwrap();
    let key = jose::from_jwk(&a.jwks()["keys"][0]).unwrap();
    let (header, claims) =
        jose::verify(&client::client_assertion(a, "https://pds.example"), &key).unwrap();
    assert_eq!(header["alg"], "ES256");
    assert_eq!(header["kid"], a.kid.as_str());
    assert_eq!(claims["iss"], a.client_id());
    assert_eq!(claims["sub"], a.client_id());
    assert_eq!(claims["aud"], "https://pds.example");
    assert!(claims["jti"].as_str().is_some_and(|j| j.len() >= 16));
    let iat = claims["iat"].as_u64().unwrap();
    assert!(iat.abs_diff(now()) < 5);
    assert_eq!(claims["exp"].as_u64(), Some(iat + 60));
    // A DPoP proof: its key in its header, its claims the request's.
    let dpop = Keypair::generate(Curve::P256);
    let url = Url::parse("https://pds.example/xrpc/a.b.c?x=1#f").unwrap();
    let proof = client::dpop_proof(&dpop, "GET", &url, Some("n1"), Some("ath1"));
    let (header, _) = jose::parts(&proof).unwrap();
    assert_eq!(header["typ"], "dpop+jwt");
    let signer = jose::from_jwk(&header["jwk"]).unwrap();
    assert_eq!(signer, dpop.public());
    let (_, claims) = jose::verify(&proof, &signer).unwrap();
    assert_eq!(claims["htm"], "GET");
    assert_eq!(claims["htu"], "https://pds.example/xrpc/a.b.c");
    assert_eq!(claims["nonce"], "n1");
    assert_eq!(claims["ath"], "ath1");
    let bare = client::dpop_proof(&dpop, "POST", &url, None, None);
    let (_, claims) = jose::parts(&bare).unwrap();
    assert!(claims.get("nonce").is_none() && claims.get("ath").is_none());
}

#[test]
fn token_answers_checked() {
    let good = json!({ "access_token": "a", "token_type": "DPoP", "refresh_token": "r",
        "scope": "atproto transition:generic", "sub": DID, "expires_in": 60 });
    let t = client::tokens_of(&good).unwrap();
    assert_eq!((t.sub.as_str(), t.refresh.as_deref()), (DID, Some("r")));
    for (k, v) in [
        ("token_type", json!("Bearer")),
        ("sub", json!("alice.test")),
        ("scope", json!("transition:generic")),
        ("access_token", json!("")),
    ] {
        let mut bad = good.clone();
        bad[k] = v;
        assert!(client::tokens_of(&bad).is_err(), "{k}");
    }
    // A refresh token may be left out or null; anything else is refused.
    let mut none = good.clone();
    none["refresh_token"] = Value::Null;
    assert_eq!(client::tokens_of(&none).unwrap().refresh, None);
    none["refresh_token"] = json!(5);
    assert_eq!(
        client::tokens_of(&none).unwrap_err(),
        "its refresh token is not a string"
    );
}

#[tokio::test]
async fn authorize_checks_in_order() {
    let h = hud("http://127.0.0.1:9");
    let id = client(&h);
    let verifier = jose::random(32);
    let good = authorize_params(&id, &verifier);
    let with = |k: &str, v: Option<&str>| -> Vec<(String, String)> {
        let mut p: Vec<(String, String)> = good.iter().filter(|(n, _)| n != k).cloned().collect();
        if let Some(v) = v {
            p.push((k.into(), v.into()));
        }
        p
    };
    let page = |r: Result<issuer::Pending, NotAuthorized>| match r {
        Err(NotAuthorized::Page(why)) => why,
        other => panic!("not a page: {other:?}"),
    };
    let back = |r: Result<issuer::Pending, NotAuthorized>| match r {
        Err(NotAuthorized::Redirect(to)) => query_of(&to),
        other => panic!("not a redirect: {other:?}"),
    };
    // 1, 2: no client, an unknown one, a redirect URI not its own: a page,
    // even when later parameters are wrong too.
    assert_eq!(
        page(h.authorize(&with("client_id", None)).await),
        "client_id is required"
    );
    let mut wrong = with("client_id", Some("nobody"));
    wrong.retain(|(k, _)| k != "resource");
    assert!(page(h.authorize(&wrong).await).starts_with("Invalid client_id"));
    let mut wrong = with("redirect_uri", Some("https://evil.example/cb"));
    wrong.retain(|(k, _)| k != "response_type");
    assert_eq!(
        page(h.authorize(&wrong).await),
        "redirect_uri is not one of the client's"
    );
    let mut twice = good.clone();
    twice.push(("state".into(), "s2".into()));
    assert!(page(h.authorize(&twice).await).contains("more than once"));
    // 3-6: sent back, with iss and state, in order.
    let mut wrong = with("response_type", Some("token"));
    wrong.retain(|(k, _)| k != "code_challenge");
    let q = back(h.authorize(&wrong).await);
    assert_eq!(q["error"], "unsupported_response_type");
    assert_eq!((q["iss"].as_str(), q["state"].as_str()), (ORIGIN, "s1"));
    for (k, v, error) in [
        ("code_challenge", None, "invalid_request"),
        ("code_challenge_method", Some("plain"), "invalid_request"),
        ("code_challenge", Some("short"), "invalid_request"),
        ("resource", None, "invalid_target"),
        ("resource", Some("https://hud.test/other"), "invalid_target"),
        ("scope", Some("atproto"), "invalid_scope"),
        ("login_hint", Some("not a handle"), "invalid_request"),
    ] {
        assert_eq!(
            back(h.authorize(&with(k, v)).await)["error"],
            error,
            "{k} {v:?}"
        );
    }
    // Then the sign-in page: the client by name, the hint as given.
    let mut hinted = with("scope", Some("hud"));
    hinted.push(("login_hint".into(), "@Alice.Test".into()));
    let p = h.authorize(&hinted).await.unwrap();
    assert_eq!(p.client, "Test host");
    assert_eq!(p.login_hint.as_deref(), Some("alice.test"));
    assert_eq!(h.auth().unwrap().pending(&p.id), Some(p.clone()));
}

#[tokio::test]
async fn the_app_asks_with_the_document_hud_serves() {
    // No network to fetch a document from: HUD reads its own app's.
    let h = hud("http://127.0.0.1:9");
    let a = h.auth().unwrap();
    let id = a.app_client_id();
    assert_eq!(id, "https://hud.test/oauth/app-client.json");
    let doc = a.app_client_metadata();
    assert_eq!(doc["client_id"], id.as_str());
    assert_eq!(doc["redirect_uris"], json!([super::APP_REDIRECT]));
    assert_eq!(doc["token_endpoint_auth_method"], "none");
    let mut asked = authorize_params(&id, &jose::random(32));
    for (k, v) in &mut asked {
        if k == "redirect_uri" {
            *v = super::APP_REDIRECT.into();
        }
    }
    let p = h.authorize(&asked).await.unwrap();
    assert_eq!(p.client, "HUD for iOS");
    // Another app's own callback is asked as it would ask: each app comes
    // back to its own `<application id>:/oauth/callback`, which only it claims.
    for (k, v) in &mut asked {
        if k == "redirect_uri" {
            *v = "social.grain:/oauth/callback".into();
        }
    }
    assert!(h.authorize(&asked).await.is_ok());
    // Anything else is refused: another path, a query, a host, or the web.
    for refused in [
        "com.evil.app:/elsewhere",
        "com.evil.app:/oauth/callback?next=x",
        "com.evil.app://host/oauth/callback",
        "https://evil.example/oauth/callback",
    ] {
        for (k, v) in &mut asked {
            if k == "redirect_uri" {
                *v = refused.into();
            }
        }
        match h.authorize(&asked).await {
            Err(NotAuthorized::Page(why)) => {
                assert_eq!(why, "redirect_uri is not one of the client's", "{refused}")
            }
            other => panic!("{refused} not refused: {other:?}"),
        }
    }
}

/// A client registered with the one redirect URI `redirect`, and an
/// authorization request's params for it.
fn asked_by(hud: &Hud, redirect: &str) -> Vec<(String, String)> {
    let body = json!({ "redirect_uris": [redirect], "client_name": "Web app" });
    let c = hud.register(body.to_string().as_bytes()).unwrap();
    let mut asked = authorize_params(c["client_id"].as_str().unwrap(), &jose::random(32));
    for (k, v) in &mut asked {
        if k == "redirect_uri" {
            *v = redirect.into();
        }
    }
    asked
}

#[tokio::test]
async fn the_app_naming_its_account_goes_straight_to_its_server() {
    let (h, _f, base) = world().await;
    let a = h.auth().unwrap();
    let mut asked = authorize_params(&a.app_client_id(), &jose::random(32));
    for (k, v) in &mut asked {
        if k == "redirect_uri" {
            *v = super::APP_REDIRECT.into();
        }
    }
    // With no hint, the page, as for any client.
    match h.begin_sign_in(&asked).await.unwrap() {
        Authorized::Page(p) => assert!(p.straight && p.login_hint.is_none()),
        other => panic!("not the page: {other:?}"),
    }
    // Naming the account, on to its server: no page of HUD's.
    let mut hinted = asked.clone();
    hinted.push(("login_hint".into(), DID.into()));
    match h.begin_sign_in(&hinted).await.unwrap() {
        Authorized::Server(to) => assert!(to.starts_with(&format!("{base}/authorize?")), "{to}"),
        other => panic!("not on to the account's server: {other:?}"),
    }
    // Naming one that is no account here: sent back to the app, saying
    // why, for its own screen to show; the request let go.
    let waiting = a.lock().requests.len();
    let mut unknown = asked.clone();
    unknown.push(("login_hint".into(), OTHER.into()));
    match h.begin_sign_in(&unknown).await.unwrap_err() {
        NotAuthorized::Redirect(to) => {
            assert!(to.starts_with(super::APP_REDIRECT), "{to}");
            let q = query_of(&to);
            assert_eq!(q["error"], "access_denied");
            assert_eq!(
                q["error_description"],
                format!("{OTHER} does not resolve to an account")
            );
            assert_eq!((q["state"].as_str(), q["iss"].as_str()), ("s1", ORIGIN));
        }
        other => panic!("not sent back saying why: {other:?}"),
    }
    assert_eq!(a.lock().requests.len(), waiting);
    assert_eq!(a.sent_back("gone", "why"), None);
}

/// A web client of an app whose file draws its own sign-in screen
/// (Grain's, `signIn`), sent back to that app's domain or one under it,
/// or on a loopback host where HUD reaches private addresses, goes straight
/// on as HUD's own app does; any other client gets the page, whatever it
/// hints.
#[tokio::test]
async fn an_apps_own_sign_in_goes_straight_to_its_server() {
    let (h, _f, base) = world().await;
    assert_eq!(crate::view::views().sign_ins(), ["grain.social"]);
    for redirect in [
        "https://next.grain.social/auth/callback",
        "https://grain.social/auth/callback",
        REDIRECT,
    ] {
        let mut hinted = asked_by(&h, redirect);
        hinted.push(("login_hint".into(), DID.into()));
        match h.begin_sign_in(&hinted).await.unwrap() {
            Authorized::Server(to) => {
                assert!(to.starts_with(&format!("{base}/authorize?")), "{to}")
            }
            other => panic!("{redirect}: not on to the account's server: {other:?}"),
        }
    }
    for redirect in [
        "https://elsewhere.test/cb",
        "https://notgrain.social/cb",
        "https://grain.social.evil.test/cb",
    ] {
        let mut other = asked_by(&h, redirect);
        other.push(("login_hint".into(), DID.into()));
        match h.begin_sign_in(&other).await.unwrap() {
            Authorized::Page(p) => {
                assert!(!p.straight, "{redirect}");
                assert_eq!(p.login_hint.as_deref(), Some(DID));
            }
            other => panic!("{redirect}: not the page: {other:?}"),
        }
    }
}

#[tokio::test]
async fn token_endpoint_refusals() {
    let h = hud("http://127.0.0.1:9");
    let id = client(&h);
    let err = |r: Result<Value, issuer::Refused>| r.unwrap_err().error;
    assert_eq!(
        err(h
            .token(&pairs(&[("grant_type", "authorization_code")]))
            .await),
        "invalid_request"
    );
    assert_eq!(
        err(h
            .token(&pairs(&[
                ("client_id", "nobody"),
                ("grant_type", "refresh_token"),
                ("refresh_token", "x")
            ]))
            .await),
        "invalid_client"
    );
    assert_eq!(
        err(h
            .token(&pairs(&[("client_id", &id), ("grant_type", "password")]))
            .await),
        "unsupported_grant_type"
    );
    assert_eq!(
        err(h
            .token(&pairs(&[
                ("client_id", &id),
                ("grant_type", "authorization_code"),
                ("code", "c")
            ]))
            .await),
        "invalid_request"
    );
    assert_eq!(
        err(h
            .token(&pairs(&[
                ("client_id", &id),
                ("grant_type", "refresh_token"),
                ("refresh_token", "x"),
                ("resource", "https://elsewhere.example/mcp")
            ]))
            .await),
        "invalid_target"
    );
    assert_eq!(
        err(h
            .token(&pairs(&[
                ("client_id", &id),
                ("grant_type", "authorization_code"),
                ("code", "c"),
                ("redirect_uri", REDIRECT),
                ("code_verifier", "v")
            ]))
            .await),
        "invalid_grant"
    );
    assert_eq!(
        err(h
            .token(&pairs(&[
                ("client_id", &id),
                ("grant_type", "refresh_token"),
                ("refresh_token", "unknown")
            ]))
            .await),
        "invalid_grant"
    );
    // A client without the refresh grant takes none, whatever the token.
    let plain = h
        .register(
            json!({ "redirect_uris": [REDIRECT] })
                .to_string()
                .as_bytes(),
        )
        .unwrap();
    assert_eq!(
        err(h
            .token(&pairs(&[
                ("client_id", plain["client_id"].as_str().unwrap()),
                ("grant_type", "refresh_token"),
                ("refresh_token", "x")
            ]))
            .await),
        "unauthorized_client"
    );
    // Revocation answers alike whatever the token.
    assert!(h.revoke(&pairs(&[("token", "unknown")])).await.is_ok());
    assert_eq!(err_of(h.revoke(&pairs(&[])).await), "invalid_request");
}

fn err_of(r: Result<(), issuer::Refused>) -> &'static str {
    r.unwrap_err().error
}

// The fake PDS and authorization server.

/// What the fake has been asked, and holds.
#[derive(Default)]
struct World {
    /// DID documents, by DID.
    docs: HashMap<String, Value>,
    /// HUD's public key, which its assertions must be signed with.
    hud_key: Option<PublicKey>,
    /// The nonce asked for.
    nonce: String,
    /// Refusals for want of a nonce, at the authorization server and the
    /// PDS.
    nonce_refusals: usize,
    /// Codes given at PAR: their PKCE challenge.
    codes: HashMap<String, String>,
    /// The last PAR's state and code.
    last_par: Option<(String, String)>,
    /// The last PAR's form.
    last_par_form: HashMap<String, String>,
    /// The `sub` the token endpoint answers, if not the DID.
    sub: Option<String>,
    access: String,
    refresh: String,
    issued: usize,
    refreshes: usize,
    revocations: usize,
    writes: usize,
    /// Each record created, as the PDS was sent it.
    created: Vec<Value>,
    /// Generators' views read.
    generator_reads: usize,
    /// Interactions sent: each its `atproto-proxy` and its body.
    interactions: Vec<(String, Value)>,
    /// Chat messages sent: each its `atproto-proxy` and its body.
    messages: Vec<(String, Value)>,
    /// The account's preferences, as its PDS answers them.
    prefs: Value,
    /// Feed generators' display names, by uri; and how often they and the
    /// preferences were read.
    feed_names: HashMap<String, String>,
    prefs_reads: usize,
    /// The scope HUD's server is configured to ask for, which PAR checks.
    scope: String,
    /// The scope the token endpoint grants, if not the one asked.
    granted: Option<String>,
    /// What the account's spaces hold and what they were asked
    /// (`tests/spaces.rs`).
    spaces: spaces::Spaces,
    /// Query joins asked of the fake: each its method, its `atproto-proxy`
    /// and whether it came with the account's token.
    joined: Vec<(String, Option<String>, bool)>,
    /// The protected resource metadata answered, if not the fake's own.
    resource: Option<Value>,
    /// Fields of the authorization server's metadata in place of its own.
    meta: Option<Value>,
    /// What PAR answers, past the nonce, with no nonce, if not the request.
    par_answer: Option<(StatusCode, Value)>,
    /// What the token endpoint answers, past the nonce, if not tokens.
    token_answer: Option<(StatusCode, Value)>,
    /// Whether the token endpoint gives no refresh token, and keeps the one
    /// it gave.
    no_refresh: bool,
    /// Whether the PDS refuses every token a record is created with.
    refuse_all: bool,
    /// The error a token the PDS refuses is refused with, if not
    /// `invalid_token`.
    refused_as: Option<&'static str>,
    /// What HUD's server asks for first, with permission sets, which PAR
    /// takes too.
    include: Option<String>,
    /// Whether PAR refuses a scope with permission sets (`invalid_scope`),
    /// as a server that knows none, or cannot resolve them, does.
    refuse_sets: bool,
    /// The scope the last token was issued with, which a write is held to.
    issued_scope: Option<String>,
}

type Fake = Arc<StdMutex<World>>;

/// The origin a request was sent to, from its `Host`: the fake answers as
/// whichever it is asked as, 127.0.0.1 or localhost.
fn base(headers: &HeaderMap) -> String {
    format!("http://{}", headers["host"].to_str().unwrap())
}

/// A JSON answer, with the nonce `nonce`, if any.
fn json_response(status: StatusCode, v: Value, nonce: &str) -> Response {
    let mut r = (
        status,
        [("content-type", "application/json")],
        v.to_string(),
    )
        .into_response();
    if !nonce.is_empty() {
        r.headers_mut().insert("dpop-nonce", nonce.parse().unwrap());
    }
    r
}

/// Check a request's DPoP proof: its key's signature, method, URL, nonce
/// and, at a resource, the token's hash. Else the answer refusing it.
fn check_dpop(
    w: &mut World,
    headers: &HeaderMap,
    htm: &str,
    htu: &str,
    token: Option<&str>,
) -> Option<Response> {
    let proof = headers["dpop"].to_str().unwrap();
    let (header, _) = jose::parts(proof).unwrap();
    assert_eq!(header["typ"], "dpop+jwt");
    let key = jose::from_jwk(&header["jwk"]).unwrap();
    let (_, claims) = jose::verify(proof, &key).expect("a proof signed by its key");
    assert_eq!(claims["htm"], htm);
    assert_eq!(claims["htu"], htu);
    if let Some(t) = token {
        assert_eq!(claims["ath"], jose::sha256(t));
    }
    if claims["nonce"].as_str().unwrap_or_default() != w.nonce {
        w.nonce_refusals += 1;
        let nonce = w.nonce.clone();
        return Some(match token {
            None => json_response(
                StatusCode::BAD_REQUEST,
                json!({ "error": "use_dpop_nonce" }),
                &nonce,
            ),
            Some(_) => (
                StatusCode::UNAUTHORIZED,
                [
                    ("www-authenticate", "DPoP error=\"use_dpop_nonce\""),
                    ("dpop-nonce", nonce.as_str()),
                ],
                "",
            )
                .into_response(),
        });
    }
    None
}

/// Check a request's client assertion, signed by HUD's key for `issuer`.
fn check_client(w: &World, form: &HashMap<String, String>, issuer: &str) {
    assert_eq!(
        form["client_assertion_type"],
        "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
    );
    let key = w.hud_key.as_ref().unwrap();
    let (_, claims) = jose::verify(&form["client_assertion"], key).expect("signed by HUD");
    assert_eq!(claims["iss"], form["client_id"].as_str());
    assert_eq!(claims["sub"], form["client_id"].as_str());
    assert_eq!(claims["aud"], issuer);
    assert_eq!(
        form["client_id"],
        "https://hud.test/oauth/client-metadata.json"
    );
}

fn form_of(body: &str) -> HashMap<String, String> {
    url::form_urlencoded::parse(body.as_bytes())
        .into_owned()
        .collect()
}

async fn plc(State(f): State<Fake>, UrlPath(did): UrlPath<String>) -> Response {
    match f.lock().unwrap().docs.get(&did) {
        Some(doc) => json_response(StatusCode::OK, doc.clone(), "-"),
        None => StatusCode::NOT_FOUND.into_response(),
    }
}

async fn protected_resource(State(f): State<Fake>, headers: HeaderMap) -> Response {
    let b = base(&headers);
    let answer = f.lock().unwrap().resource.clone();
    json_response(
        StatusCode::OK,
        answer.unwrap_or_else(|| json!({ "resource": b, "authorization_servers": [b] })),
        "-",
    )
}

async fn authorization_server(State(f): State<Fake>, headers: HeaderMap) -> Response {
    let b = base(&headers);
    let mut meta = json!({
        "issuer": b,
        "authorization_endpoint": format!("{b}/authorize"),
        "pushed_authorization_request_endpoint": format!("{b}/par"),
        "token_endpoint": format!("{b}/token"),
        "revocation_endpoint": format!("{b}/revoke"),
        "dpop_signing_alg_values_supported": ["ES256"],
        "token_endpoint_auth_methods_supported": ["none", "private_key_jwt"],
        "token_endpoint_auth_signing_alg_values_supported": ["ES256"],
    });
    if let Some(Value::Object(patch)) = f.lock().unwrap().meta.clone() {
        for (k, v) in patch {
            meta[k] = v;
        }
    }
    json_response(StatusCode::OK, meta, "-")
}

/// An endpoint that moved, sending the request on to `landed`.
async fn moved() -> Response {
    (
        StatusCode::TEMPORARY_REDIRECT,
        [("location", "/landed")],
        "",
    )
        .into_response()
}

/// Where `moved` sends a request: an answer as PAR's.
async fn landed() -> Response {
    json_response(
        StatusCode::CREATED,
        json!({ "request_uri": "urn:ietf:params:oauth:request_uri:r2", "expires_in": 300 }),
        "",
    )
}

async fn par(State(f): State<Fake>, headers: HeaderMap, body: String) -> Response {
    let b = base(&headers);
    let form = form_of(&body);
    let mut w = f.lock().unwrap();
    check_client(&w, &form, &b);
    if let Some(r) = check_dpop(&mut w, &headers, "POST", &format!("{b}/par"), None) {
        return r;
    }
    assert_eq!(form["redirect_uri"], "https://hud.test/oauth/callback");
    assert_eq!(form["code_challenge_method"], "S256");
    let asked = form["scope"].as_str();
    assert!(
        asked == w.scope || w.include.as_deref() == Some(asked),
        "{asked}"
    );
    if w.refuse_sets && asked.contains("include:") {
        let nonce = w.nonce.clone();
        return json_response(
            StatusCode::BAD_REQUEST,
            json!({ "error": "invalid_scope" }),
            &nonce,
        );
    }
    if let Some((status, answer)) = w.par_answer.clone() {
        return json_response(status, answer, "");
    }
    let code = jose::random(8);
    w.codes.insert(code.clone(), form["code_challenge"].clone());
    w.last_par = Some((form["state"].clone(), code));
    w.last_par_form = form;
    let nonce = w.nonce.clone();
    json_response(
        StatusCode::CREATED,
        json!({ "request_uri": "urn:ietf:params:oauth:request_uri:r1", "expires_in": 300 }),
        &nonce,
    )
}

async fn token(State(f): State<Fake>, headers: HeaderMap, body: String) -> Response {
    let b = base(&headers);
    let form = form_of(&body);
    let refresh = form["grant_type"] == "refresh_token";
    {
        let mut w = f.lock().unwrap();
        check_client(&w, &form, &b);
        if let Some(r) = check_dpop(&mut w, &headers, "POST", &format!("{b}/token"), None) {
            return r;
        }
        if refresh {
            w.refreshes += 1;
        }
    }
    if refresh {
        // Slow, so refreshes that are not single-flight would overlap.
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
    }
    let mut w = f.lock().unwrap();
    let nonce = w.nonce.clone();
    if let Some((status, answer)) = w.token_answer.clone() {
        return json_response(status, answer, &nonce);
    }
    let invalid = || {
        json_response(
            StatusCode::BAD_REQUEST,
            json!({ "error": "invalid_grant" }),
            &nonce,
        )
    };
    if refresh {
        if form["refresh_token"] != w.refresh {
            return invalid();
        }
    } else {
        let Some(challenge) = w.codes.remove(&form["code"]) else {
            return invalid();
        };
        if jose::sha256(&form["code_verifier"]) != challenge {
            return invalid();
        }
    }
    w.issued += 1;
    w.access = format!("at{}", w.issued);
    if !w.no_refresh {
        w.refresh = format!("rt{}", w.issued);
    }
    let sub = w.sub.clone().unwrap_or_else(|| DID.to_string());
    let scope = w.granted.clone().unwrap_or_else(|| w.scope.clone());
    w.issued_scope = Some(scope.clone());
    let mut answer = json!({ "access_token": w.access, "token_type": "DPoP",
        "scope": scope, "sub": sub, "expires_in": 3600 });
    if !w.no_refresh {
        answer["refresh_token"] = w.refresh.clone().into();
    }
    json_response(StatusCode::OK, answer, &nonce)
}

async fn revoke(State(f): State<Fake>, headers: HeaderMap, body: String) -> Response {
    let b = base(&headers);
    let form = form_of(&body);
    let mut w = f.lock().unwrap();
    check_client(&w, &form, &b);
    if let Some(r) = check_dpop(&mut w, &headers, "POST", &format!("{b}/revoke"), None) {
        return r;
    }
    assert_eq!(form["token"], w.refresh);
    w.revocations += 1;
    let nonce = w.nonce.clone();
    json_response(StatusCode::OK, json!({}), &nonce)
}

/// A personal query: as the account, proxied to the AppView, its feed;
/// as no one, `AuthMissing`.
async fn timeline(State(f): State<Fake>, headers: HeaderMap) -> Response {
    let b = base(&headers);
    let mut w = f.lock().unwrap();
    let nonce = w.nonce.clone();
    let Some(auth) = headers.get("authorization") else {
        return json_response(
            StatusCode::UNAUTHORIZED,
            json!({ "error": "AuthMissing", "message": "Authentication Required" }),
            &nonce,
        );
    };
    let token = auth.to_str().unwrap().strip_prefix("DPoP ").unwrap();
    assert_eq!(token, w.access);
    assert_eq!(
        headers["atproto-proxy"],
        "did:web:api.bsky.app#bsky_appview"
    );
    let htu = format!("{b}/xrpc/app.bsky.feed.getTimeline");
    if let Some(r) = check_dpop(&mut w, &headers, "GET", &htu, Some(token)) {
        return r;
    }
    json_response(
        StatusCode::OK,
        json!({ "feed": [], "cursor": "c1" }),
        &nonce,
    )
}

/// A feed generator's view, as the account, proxied to the AppView: one
/// whose rkey is `closed` takes no interactions.
async fn feed_generator(
    State(f): State<Fake>,
    headers: HeaderMap,
    axum::extract::RawQuery(q): axum::extract::RawQuery,
) -> Response {
    let b = base(&headers);
    let mut w = f.lock().unwrap();
    let nonce = w.nonce.clone();
    let token = headers["authorization"]
        .to_str()
        .unwrap()
        .strip_prefix("DPoP ")
        .unwrap()
        .to_string();
    assert_eq!(token, w.access);
    assert_eq!(
        headers["atproto-proxy"],
        "did:web:api.bsky.app#bsky_appview"
    );
    let htu = format!("{b}/xrpc/app.bsky.feed.getFeedGenerator");
    if let Some(r) = check_dpop(&mut w, &headers, "GET", &htu, Some(&token)) {
        return r;
    }
    w.generator_reads += 1;
    let feed = form_of(&q.unwrap_or_default())["feed"].clone();
    let closed = feed.ends_with("/closed");
    let did = if closed {
        "did:web:closed.test"
    } else {
        "did:web:fg.test"
    };
    json_response(
        StatusCode::OK,
        json!({ "view": { "uri": feed, "did": did, "acceptsInteractions": !closed },
                "isOnline": true, "isValid": true }),
        &nonce,
    )
}

/// The account's preferences, as its PDS answers them itself.
async fn preferences(State(f): State<Fake>, headers: HeaderMap) -> Response {
    let b = base(&headers);
    let mut w = f.lock().unwrap();
    let nonce = w.nonce.clone();
    let token = headers["authorization"]
        .to_str()
        .unwrap()
        .strip_prefix("DPoP ")
        .unwrap()
        .to_string();
    assert_eq!(token, w.access);
    assert!(headers.get("atproto-proxy").is_none(), "the PDS's own");
    let htu = format!("{b}/xrpc/app.bsky.actor.getPreferences");
    if let Some(r) = check_dpop(&mut w, &headers, "GET", &htu, Some(&token)) {
        return r;
    }
    w.prefs_reads += 1;
    let prefs = w.prefs.clone();
    json_response(StatusCode::OK, prefs, &nonce)
}

/// Feed generators' views, proxied to the AppView: their names.
async fn feed_generators(
    State(f): State<Fake>,
    headers: HeaderMap,
    axum::extract::RawQuery(q): axum::extract::RawQuery,
) -> Response {
    let b = base(&headers);
    let mut w = f.lock().unwrap();
    let nonce = w.nonce.clone();
    let token = headers["authorization"]
        .to_str()
        .unwrap()
        .strip_prefix("DPoP ")
        .unwrap()
        .to_string();
    assert_eq!(token, w.access);
    assert_eq!(
        headers["atproto-proxy"],
        "did:web:api.bsky.app#bsky_appview"
    );
    let htu = format!("{b}/xrpc/app.bsky.feed.getFeedGenerators");
    if let Some(r) = check_dpop(&mut w, &headers, "GET", &htu, Some(&token)) {
        return r;
    }
    let feeds: Vec<Value> = url::form_urlencoded::parse(q.unwrap_or_default().as_bytes())
        .filter(|(k, _)| k == "feeds")
        .filter_map(|(_, uri)| {
            let name = w.feed_names.get(uri.as_ref())?;
            Some(json!({ "uri": uri, "displayName": name }))
        })
        .collect();
    json_response(StatusCode::OK, json!({ "feeds": feeds }), &nonce)
}

/// Interactions, as the account, proxied to the feed's generator.
async fn send_interactions(State(f): State<Fake>, headers: HeaderMap, body: String) -> Response {
    let b = base(&headers);
    let mut w = f.lock().unwrap();
    let nonce = w.nonce.clone();
    let token = headers["authorization"]
        .to_str()
        .unwrap()
        .strip_prefix("DPoP ")
        .unwrap()
        .to_string();
    assert_eq!(token, w.access);
    let htu = format!("{b}/xrpc/app.bsky.feed.sendInteractions");
    if let Some(r) = check_dpop(&mut w, &headers, "POST", &htu, Some(&token)) {
        return r;
    }
    let proxy = headers["atproto-proxy"].to_str().unwrap().to_string();
    w.interactions
        .push((proxy, serde_json::from_str(&body).unwrap()));
    json_response(StatusCode::OK, json!({}), &nonce)
}

/// A chat message, as the account, proxied to Bluesky's chat service: it
/// answers the message's view; a conversation named `gone` is refused.
async fn send_message(State(f): State<Fake>, headers: HeaderMap, body: String) -> Response {
    let b = base(&headers);
    let mut w = f.lock().unwrap();
    let nonce = w.nonce.clone();
    let token = headers["authorization"]
        .to_str()
        .unwrap()
        .strip_prefix("DPoP ")
        .unwrap()
        .to_string();
    assert_eq!(token, w.access);
    let htu = format!("{b}/xrpc/chat.bsky.convo.sendMessage");
    if let Some(r) = check_dpop(&mut w, &headers, "POST", &htu, Some(&token)) {
        return r;
    }
    let proxy = headers["atproto-proxy"].to_str().unwrap().to_string();
    let input: Value = serde_json::from_str(&body).unwrap();
    w.messages.push((proxy, input.clone()));
    if input["convoId"] == "gone" {
        return json_response(
            StatusCode::BAD_REQUEST,
            json!({ "error": "InvalidConvo", "message": "Convo not found" }),
            &nonce,
        );
    }
    let view = json!({ "$type": "chat.bsky.convo.defs#messageView", "id": "m1", "rev": "r1",
                       "text": input["message"]["text"], "sender": { "did": DID },
                       "sentAt": "2026-11-16T09:00:00.000Z" });
    json_response(StatusCode::OK, view, &nonce)
}

async fn create_record(State(f): State<Fake>, headers: HeaderMap, body: String) -> Response {
    let b = base(&headers);
    let mut w = f.lock().unwrap();
    let nonce = w.nonce.clone();
    let token = headers["authorization"]
        .to_str()
        .unwrap()
        .strip_prefix("DPoP ")
        .unwrap()
        .to_string();
    if token != w.access || w.refuse_all {
        return (
            StatusCode::UNAUTHORIZED,
            [
                ("www-authenticate", "DPoP error=\"invalid_token\""),
                ("dpop-nonce", nonce.as_str()),
            ],
            json!({ "error": w.refused_as.unwrap_or("invalid_token") }).to_string(),
        )
            .into_response();
    }
    let htu = format!("{b}/xrpc/com.atproto.repo.createRecord");
    if let Some(r) = check_dpop(&mut w, &headers, "POST", &htu, Some(&token)) {
        return r;
    }
    let input: Value = serde_json::from_str(&body).unwrap();
    assert_eq!(input["repo"], DID);
    // Held to the scope granted, as a PDS holds a write.
    let collection = input["collection"].as_str().unwrap();
    let granted = w.issued_scope.clone().unwrap_or_else(|| w.scope.clone());
    let allowed = format!("repo:{collection}");
    if !granted
        .split(' ')
        .any(|t| t == "transition:generic" || t == allowed)
    {
        let message = format!("Missing required scope \"{allowed}?action=create\"");
        return json_response(
            StatusCode::FORBIDDEN,
            json!({ "error": "ScopeMissingError", "message": message }),
            &nonce,
        );
    }
    w.writes += 1;
    w.created.push(input["record"].clone());
    let uri = format!(
        "at://{DID}/{}/3kfake{}",
        input["collection"].as_str().unwrap(),
        w.writes
    );
    json_response(StatusCode::OK, json!({ "uri": uri, "cid": CID }), &nonce)
}

/// The fake, serving on a loopback port: its state, and its port.
async fn fake() -> (Fake, u16) {
    let f: Fake = Arc::new(StdMutex::new(World {
        nonce: "n1".into(),
        ..World::default()
    }));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let port = listener.local_addr().unwrap().port();
    let doc = |pds: String| {
        json!({ "id": DID, "service": [{ "id": "#atproto_pds",
            "type": "AtprotoPersonalDataServer", "serviceEndpoint": pds }] })
    };
    f.lock()
        .unwrap()
        .docs
        .insert(DID.into(), doc(format!("http://127.0.0.1:{port}")));
    let app = Router::new()
        .route("/{did}", get(plc))
        .route(
            "/.well-known/oauth-protected-resource",
            get(protected_resource),
        )
        .route(
            "/.well-known/oauth-authorization-server",
            get(authorization_server),
        )
        .route("/par", post(par))
        .route("/moved", post(moved))
        .route("/landed", post(landed))
        .route("/token", post(token))
        .route("/revoke", post(revoke))
        .route("/xrpc/com.atproto.repo.createRecord", post(create_record))
        .route("/xrpc/app.bsky.feed.getTimeline", get(timeline))
        .route("/xrpc/app.bsky.feed.getFeedGenerator", get(feed_generator))
        .route("/xrpc/app.bsky.actor.getPreferences", get(preferences))
        .route(
            "/xrpc/app.bsky.feed.getFeedGenerators",
            get(feed_generators),
        )
        .route(
            "/xrpc/app.bsky.feed.sendInteractions",
            post(send_interactions),
        )
        .route("/xrpc/chat.bsky.convo.sendMessage", post(send_message))
        .route("/xrpc/app.bsky.feed.getAuthorFeed", get(joined))
        .route("/xrpc/app.bsky.feed.getActorFeeds", get(joined));
    let app = spaces::routes(app).with_state(f.clone());
    tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
    (f, port)
}

/// A query a view joins: asked as no one, straight; as the account, its
/// token and proof checked, proxied on to the service named.
async fn joined(State(f): State<Fake>, headers: HeaderMap, uri: axum::http::Uri) -> Response {
    let b = base(&headers);
    let method = uri.path().trim_start_matches("/xrpc/").to_string();
    let mut w = f.lock().unwrap();
    let nonce = w.nonce.clone();
    let signed = headers.contains_key("authorization");
    if signed {
        let token = headers["authorization"]
            .to_str()
            .unwrap()
            .strip_prefix("DPoP ")
            .unwrap()
            .to_string();
        assert_eq!(token, w.access);
        let htu = format!("{b}/xrpc/{method}");
        if let Some(r) = check_dpop(&mut w, &headers, "GET", &htu, Some(&token)) {
            return r;
        }
    }
    let proxy = headers
        .get("atproto-proxy")
        .map(|p| p.to_str().unwrap().to_string());
    w.joined.push((method.clone(), proxy, signed));
    let answer = match method.as_str() {
        "app.bsky.feed.getAuthorFeed" => json!({ "feed": [] }),
        _ => json!({ "feeds": [] }),
    };
    json_response(StatusCode::OK, answer, &nonce)
}

/// HUD, and the fake it signs in at.
async fn world() -> (Arc<Hud>, Fake, String) {
    world_with(|_| {}).await
}

/// HUD, configured by `with`, and the fake it signs in at.
async fn world_with(with: impl FnOnce(&mut crate::Config)) -> (Arc<Hud>, Fake, String) {
    let (f, port) = fake().await;
    let base = format!("http://127.0.0.1:{port}");
    let mut c = config(&base);
    // The fake is the sign-up PDS too.
    c.sign_up_pds = base.clone();
    with(&mut c);
    let h = Hud::new(c).unwrap();
    let key = jose::from_jwk(&h.auth().unwrap().jwks()["keys"][0]).unwrap();
    {
        let mut w = f.lock().unwrap();
        w.hud_key = Some(key);
        w.scope = h.config.oauth_scope.clone();
        w.include = h.config.oauth_include.clone();
    }
    (h, f, base)
}

/// A sign-in up to the account's server's answer: the URL HUD sends the
/// browser back to the client with, and the PKCE verifier.
async fn signed_in_at_pds(h: &Hud, f: &Fake, base: &str, client_id: &str) -> (String, String) {
    let verifier = jose::random(32);
    let pending = h
        .authorize(&authorize_params(client_id, &verifier))
        .await
        .unwrap();
    let to = h.sign_in(&pending.id, DID).await.unwrap();
    let q = query_of(&to);
    assert!(to.starts_with(&format!("{base}/authorize?")), "{to}");
    assert_eq!(
        q["client_id"],
        "https://hud.test/oauth/client-metadata.json"
    );
    assert_eq!(q["request_uri"], "urn:ietf:params:oauth:request_uri:r1");
    let (state, code) = f.lock().unwrap().last_par.clone().unwrap();
    let back = h
        .callback(&pairs(&[("state", &state), ("iss", base), ("code", &code)]))
        .await
        .unwrap();
    (to_client(back), verifier)
}

/// Where a callback sends the person on to: an MCP client's redirect URI.
fn to_client(c: client::Callback) -> String {
    match c {
        client::Callback::Client(to) => to,
        other => panic!("not back to the client: {other:?}"),
    }
}

/// A whole sign-in: HUD's access and refresh tokens.
async fn signed_in(h: &Hud, f: &Fake, base: &str, client_id: &str) -> (String, String) {
    let (back, verifier) = signed_in_at_pds(h, f, base, client_id).await;
    let q = query_of(&back);
    assert!(back.starts_with(REDIRECT), "{back}");
    assert_eq!((q["iss"].as_str(), q["state"].as_str()), (ORIGIN, "s1"));
    let t = h
        .token(&pairs(&[
            ("grant_type", "authorization_code"),
            ("client_id", client_id),
            ("code", &q["code"]),
            ("redirect_uri", REDIRECT),
            ("code_verifier", &verifier),
            ("resource", "https://hud.test/mcp"),
        ]))
        .await
        .unwrap();
    assert_eq!(t["token_type"], "Bearer");
    assert_eq!(t["expires_in"], ACCESS_LIFE);
    assert_eq!(t["scope"], "hud");
    assert_eq!(t["sub"], DID);
    (
        t["access_token"].as_str().unwrap().to_string(),
        t["refresh_token"].as_str().unwrap().to_string(),
    )
}

#[tokio::test]
async fn signs_in_writes_refreshes_and_revokes() {
    let (h, f, base) = world().await;
    let id = client(&h);
    let (access, refresh) = signed_in(&h, &f, &base, &id).await;
    // PAR was refused once for want of a nonce, then sent again with it.
    assert_eq!(f.lock().unwrap().nonce_refusals, 1);
    let a = h.auth().unwrap();
    let account = a.account(&access).expect("the token is the account's");
    assert_eq!(account.did, DID);
    // The session is on disk, its tokens hashed, never as given.
    let file = std::fs::read_to_string(json_files(&a.dir.join("sessions"))[0].clone()).unwrap();
    assert!(!file.contains(&access) && !file.contains(&refresh));
    assert!(file.contains(&jose::sha256(&access)));
    // A like, as the account, checked against its lexicon, with a new nonce
    // the PDS asks for on the way.
    f.lock().unwrap().nonce = "n2".into();
    let like = json!({ "collection": "app.bsky.feed.like", "record": {
        "subject": { "uri": format!("at://{OTHER}/app.bsky.feed.post/3k2a"), "cid": CID },
        "createdAt": "2026-11-14T12:00:00.000Z" } });
    let out = h
        .call_tool("create_record", Some(&like), Some(&account))
        .await
        .unwrap()
        .unwrap();
    assert_eq!(out.structured["cid"], CID);
    assert!(
        out.text
            .starts_with(&format!("Created at://{DID}/app.bsky.feed.like/"))
    );
    assert_eq!(out.meta["viewer"], json!({ "did": DID, "handle": null }));
    assert_eq!(f.lock().unwrap().nonce_refusals, 2);
    // A reply: its facets made from its text, a link and a tag marked by
    // their bytes, a mention whose handle resolves to no DID left unmarked;
    // a text with none, no facets at all.
    let parent = json!({ "uri": format!("at://{OTHER}/app.bsky.feed.post/3k2a"), "cid": CID });
    let post = |text: &str| {
        json!({ "collection": "app.bsky.feed.post", "record": {
            "text": text, "facets": { "$facets": "text" }, "createdAt": "2026-11-14T12:00:00.000Z",
            "reply": { "root": parent, "parent": parent } } })
    };
    let text = "yes! see https://a.example/x, #atproto @nobody.invalid";
    h.call_tool("create_record", Some(&post(text)), Some(&account))
        .await
        .unwrap()
        .unwrap();
    h.call_tool("create_record", Some(&post("plain")), Some(&account))
        .await
        .unwrap()
        .unwrap();
    let created = f.lock().unwrap().created.clone();
    let reply = &created[created.len() - 2];
    let link = text.find("https").unwrap();
    let tag = text.find('#').unwrap();
    assert_eq!(
        reply["facets"],
        json!([
            { "index": { "byteStart": link, "byteEnd": link + "https://a.example/x".len() },
              "features": [{ "$type": "app.bsky.richtext.facet#link", "uri": "https://a.example/x" }] },
            { "index": { "byteStart": tag, "byteEnd": tag + "#atproto".len() },
              "features": [{ "$type": "app.bsky.richtext.facet#tag", "tag": "atproto" }] },
        ])
    );
    assert_eq!(reply["reply"]["parent"], parent);
    assert!(created[created.len() - 1].get("facets").is_none());
    // Without an account, a write asks for sign-in.
    assert_eq!(
        h.call_tool("create_record", Some(&like), None)
            .await
            .unwrap()
            .err(),
        Some(Refusal::SignIn)
    );
    // So do a composer's lookups: no one searches or fetches through HUD
    // signed out.
    for (tool, args) in [
        ("find_place", json!({ "q": "Lisbon" })),
        ("link_card", json!({ "url": "https://a.example/x" })),
    ] {
        assert_eq!(
            h.call_tool(tool, Some(&args), None).await.unwrap().err(),
            Some(Refusal::SignIn),
            "{tool}"
        );
    }
    // Expired, the atproto token is refreshed once, however many calls
    // need it at once.
    account.session.lock().await.expires_at = 0;
    let calls = (0..4).map(|_| h.call_tool("create_record", Some(&like), Some(&account)));
    for r in futures::future::join_all(calls).await {
        assert!(r.unwrap().is_ok());
    }
    assert_eq!(f.lock().unwrap().refreshes, 1);
    // A token the PDS refuses is refreshed, and the call made again.
    f.lock().unwrap().access = "revoked".into();
    assert!(
        h.call_tool("create_record", Some(&like), Some(&account))
            .await
            .unwrap()
            .is_ok()
    );
    assert_eq!(f.lock().unwrap().refreshes, 2);
    // So is one refused by the names Bluesky's PDS gives.
    for (n, name) in [(3, "ExpiredToken"), (4, "InvalidToken")] {
        {
            let mut w = f.lock().unwrap();
            w.access = "revoked".into();
            w.refused_as = Some(name);
        }
        assert!(
            h.call_tool("create_record", Some(&like), Some(&account))
                .await
                .unwrap()
                .is_ok(),
            "{name}"
        );
        assert_eq!(f.lock().unwrap().refreshes, n, "{name}");
    }
    // HUD's refresh grant rotates both tokens: the old access token no
    // longer works, and the old refresh token, used again, ends the session.
    let rotate = |r: &str| {
        pairs(&[
            ("grant_type", "refresh_token"),
            ("client_id", &id),
            ("refresh_token", r),
        ])
    };
    let t = h.token(&rotate(&refresh)).await.unwrap();
    let (access2, refresh2) = (
        t["access_token"].as_str().unwrap().to_string(),
        t["refresh_token"].as_str().unwrap().to_string(),
    );
    assert_ne!(refresh2, refresh);
    assert!(a.account(&access).is_none());
    assert!(a.account(&access2).is_some());
    assert_eq!(
        h.token(&rotate(&refresh)).await.unwrap_err().error,
        "invalid_grant"
    );
    assert!(a.account(&access2).is_none(), "reuse ended the session");
    assert_eq!(
        h.token(&rotate(&refresh2)).await.unwrap_err().error,
        "invalid_grant"
    );
    assert!(json_files(&a.dir.join("sessions")).is_empty());
    // A session ended mid-call asks for sign-in again.
    assert_eq!(
        h.call_tool("create_record", Some(&like), Some(&account))
            .await
            .unwrap()
            .err(),
        Some(Refusal::SignIn)
    );
    // Revocation ends a session, its atproto refresh token revoked at its
    // server first.
    let (access3, _) = signed_in(&h, &f, &base, &id).await;
    assert!(
        h.revoke(&pairs(&[
            ("token", &access3),
            ("client_id", "someone-else")
        ]))
        .await
        .is_ok()
    );
    assert!(a.account(&access3).is_some(), "another client's revocation");
    h.revoke(&pairs(&[("token", &access3), ("client_id", &id)]))
        .await
        .unwrap();
    assert!(a.account(&access3).is_none());
    assert_eq!(f.lock().unwrap().revocations, 1);
}

/// HUD writes only what it asks to write. A sign-in that asked for less
/// than HUD asks for now is behind: a write its PDS refuses for want of
/// scope asks for sign-in again. One that asked for all of it but was
/// granted less is told so, as signing in again would not change it.
#[tokio::test]
async fn writes_held_to_the_scope_asked() {
    let (h, f, base) = world().await;
    let id = client(&h);
    let (access, _) = signed_in(&h, &f, &base, &id).await;
    let account = h.auth().unwrap().account(&access).unwrap();
    assert!(!h.behind(&account).await);
    let like = json!({ "collection": "app.bsky.feed.like", "record": {
        "subject": { "uri": format!("at://{OTHER}/app.bsky.feed.post/3k2a"), "cid": CID },
        "createdAt": "2026-11-14T12:00:00.000Z" } });
    let made = h
        .call_tool("create_record", Some(&like), Some(&account))
        .await;
    assert!(made.unwrap().is_ok());
    // A collection no view writes is refused before the PDS is asked.
    let follow = json!({ "collection": "app.bsky.graph.follow", "record": {
        "subject": OTHER, "createdAt": "2026-11-14T12:00:00.000Z" } });
    let writes = f.lock().unwrap().writes;
    let refused = h
        .call_tool("create_record", Some(&follow), Some(&account))
        .await;
    assert!(matches!(
        refused.unwrap(),
        Err(Refusal::Error(e)) if e.starts_with("HUD does not write app.bsky.graph.follow records")
    ));
    assert_eq!(f.lock().unwrap().writes, writes);
    // Granted less than asked: what the sign-in does not allow.
    f.lock().unwrap().granted = Some("atproto".into());
    let (access, _) = signed_in(&h, &f, &base, &id).await;
    let narrow = h.auth().unwrap().account(&access).unwrap();
    let refused = h
        .call_tool("create_record", Some(&like), Some(&narrow))
        .await;
    assert_eq!(
        refused.unwrap().err(),
        Some(Refusal::Error(
            "Your sign-in does not allow repo:app.bsky.feed.like?action=create".into()
        ))
    );
    // Signed in before HUD asked for it: sign in again.
    narrow.session.lock().await.asked = "atproto transition:generic".into();
    assert!(h.behind(&narrow).await);
    let refused = h
        .call_tool("create_record", Some(&like), Some(&narrow))
        .await;
    assert_eq!(refused.unwrap().err(), Some(Refusal::SignIn));
}

/// A sign-in that asks for permission sets: they are asked first, and kept
/// as asked; a write its server refuses for want of scope is sent again
/// once, with the token refreshed, as the server expands the set again on
/// refresh; refused still, the sign-in does not allow it, until it is older
/// than a set is kept, when it signs in again. A server that refuses the
/// sets is asked for what the views do instead.
#[tokio::test]
async fn permission_sets_asked_first_and_refreshed_for() {
    let include = "atproto include:social.grain.authFull?aud=did:web:grain.social%23grain_appview blob:image/png";
    let (h, f, base) = world_with(|c| c.oauth_include = Some(include.into())).await;
    let a = h.auth().unwrap();
    // The client's document declares both, each once.
    let declared = a.client_metadata()["scope"].as_str().unwrap().to_string();
    assert!(declared.starts_with(&format!("{include} ")), "{declared}");
    let tokens: Vec<&str> = declared.split(' ').collect();
    assert!(a.scope.split(' ').all(|t| tokens.contains(&t)));
    assert_eq!(tokens.iter().filter(|t| **t == "blob:image/png").count(), 1);
    // The set as the server expands it, without favorites at first.
    f.lock().unwrap().granted = Some("atproto repo:social.grain.comment".into());
    let id = client(&h);
    let (access, _) = signed_in(&h, &f, &base, &id).await;
    assert_eq!(f.lock().unwrap().last_par_form["scope"], include);
    let account = a.account(&access).unwrap();
    assert_eq!(account.session.lock().await.asked, include);
    assert!(!h.behind(&account).await);
    // The set grown: a write of what it holds now lands, once refreshed.
    f.lock().unwrap().granted =
        Some("atproto repo:social.grain.comment repo:social.grain.favorite".into());
    let favorite = json!({ "collection": "social.grain.favorite", "record": {
        "subject": format!("at://{OTHER}/social.grain.gallery/3k2a"),
        "createdAt": "2026-11-14T12:00:00.000Z" } });
    let refreshes = f.lock().unwrap().refreshes;
    let made = h
        .call_tool("create_record", Some(&favorite), Some(&account))
        .await;
    assert!(made.unwrap().is_ok());
    assert_eq!(f.lock().unwrap().refreshes, refreshes + 1);
    // What it does not hold: refreshed once, and refused still.
    let like = json!({ "collection": "app.bsky.feed.like", "record": {
        "subject": { "uri": format!("at://{OTHER}/app.bsky.feed.post/3k2a"), "cid": CID },
        "createdAt": "2026-11-14T12:00:00.000Z" } });
    let refused = h
        .call_tool("create_record", Some(&like), Some(&account))
        .await;
    assert_eq!(
        refused.unwrap().err(),
        Some(Refusal::Error(
            "Your sign-in does not allow repo:app.bsky.feed.like?action=create".into()
        ))
    );
    assert_eq!(f.lock().unwrap().refreshes, refreshes + 2);
    // Signed in longer ago than a set is kept: sign in again.
    account.session.lock().await.created_at = now() - SET_FRESH - 1;
    let refused = h
        .call_tool("create_record", Some(&like), Some(&account))
        .await;
    assert_eq!(refused.unwrap().err(), Some(Refusal::SignIn));
    // Asked for other sets than HUD asks for now: behind.
    account.session.lock().await.asked = "atproto include:social.grain.authBasic".into();
    assert!(h.behind(&account).await);
    // A server that refuses the sets is asked for what the views do, which
    // a sign-in is then held to; refused for want of scope, it is not
    // refreshed.
    {
        let mut w = f.lock().unwrap();
        w.refuse_sets = true;
        w.granted = Some("atproto".into());
    }
    let (access, _) = signed_in(&h, &f, &base, &id).await;
    assert_eq!(f.lock().unwrap().last_par_form["scope"], a.scope);
    let plain = a.account(&access).unwrap();
    assert_eq!(plain.session.lock().await.asked, a.scope);
    assert!(!h.behind(&plain).await);
    let refreshes = f.lock().unwrap().refreshes;
    let refused = h
        .call_tool("create_record", Some(&like), Some(&plain))
        .await;
    assert!(matches!(refused.unwrap(), Err(Refusal::Error(_))));
    assert_eq!(f.lock().unwrap().refreshes, refreshes);
}

#[tokio::test]
async fn codes_spent_once_and_held_to_their_request() {
    let (h, f, base) = world().await;
    let id = client(&h);
    let (back, verifier) = signed_in_at_pds(&h, &f, &base, &id).await;
    let code = query_of(&back)["code"].clone();
    let exchange = |code: &str, verifier: &str| {
        pairs(&[
            ("grant_type", "authorization_code"),
            ("client_id", &id),
            ("code", code),
            ("redirect_uri", REDIRECT),
            ("code_verifier", verifier),
        ])
    };
    // A wrong verifier spends the code.
    assert_eq!(
        h.token(&exchange(&code, "wrong")).await.unwrap_err().error,
        "invalid_grant"
    );
    assert_eq!(
        h.token(&exchange(&code, &verifier))
            .await
            .unwrap_err()
            .error,
        "invalid_grant"
    );
    // A code exchanged, used again, ends the session it made.
    let (back, verifier) = signed_in_at_pds(&h, &f, &base, &id).await;
    let code = query_of(&back)["code"].clone();
    let t = h.token(&exchange(&code, &verifier)).await.unwrap();
    let access = t["access_token"].as_str().unwrap();
    assert!(h.auth().unwrap().account(access).is_some());
    assert!(h.token(&exchange(&code, &verifier)).await.is_err());
    assert!(h.auth().unwrap().account(access).is_none());
}

#[tokio::test]
async fn sub_checked_and_resolved_again() {
    let (h, f, base) = world().await;
    let id = client(&h);
    // The account's server answers for another account than the one named.
    f.lock().unwrap().sub = Some(OTHER.into());
    let (back, _) = signed_in_at_pds(&h, &f, &base, &id).await;
    let q = query_of(&back);
    assert_eq!(q["error"], "access_denied");
    assert_eq!(q["state"], "s1");
    assert!(!q.contains_key("code"));
    f.lock().unwrap().sub = None;
    // The account's PDS, resolved again after the code, is now one whose
    // authorization server is another: refused.
    let verifier = jose::random(32);
    let pending = h
        .authorize(&authorize_params(&id, &verifier))
        .await
        .unwrap();
    h.sign_in(&pending.id, DID).await.unwrap();
    let port = Url::parse(&base).unwrap().port().unwrap();
    f.lock().unwrap().docs.insert(
        DID.into(),
        json!({ "id": DID, "service": [{ "id": "#atproto_pds",
            "type": "AtprotoPersonalDataServer",
            "serviceEndpoint": format!("http://localhost:{port}") }] }),
    );
    let (state, code) = f.lock().unwrap().last_par.clone().unwrap();
    let back = h
        .callback(&pairs(&[
            ("state", &state),
            ("iss", &base),
            ("code", &code),
        ]))
        .await
        .unwrap();
    let back = to_client(back);
    assert_eq!(query_of(&back)["error"], "access_denied");
    // An answer from another issuer than the one asked (the account's now
    // at localhost), or for a state HUD did not give, goes no further.
    let pending = h
        .authorize(&authorize_params(&id, &verifier))
        .await
        .unwrap();
    h.sign_in(&pending.id, DID).await.unwrap();
    let (state, code) = f.lock().unwrap().last_par.clone().unwrap();
    let back = h
        .callback(&pairs(&[
            ("state", &state),
            ("iss", &base),
            ("code", &code),
        ]))
        .await
        .unwrap();
    let back = to_client(back);
    let q = query_of(&back);
    assert_eq!(q["error"], "access_denied");
    assert!(!q.contains_key("code"));
    assert!(
        h.callback(&pairs(&[
            ("state", &state),
            ("iss", &base),
            ("code", &code)
        ]))
        .await
        .is_err(),
        "a state answers once"
    );
    assert!(
        h.callback(&pairs(&[
            ("state", "unknown"),
            ("iss", &base),
            ("code", "c")
        ]))
        .await
        .is_err()
    );
}

#[tokio::test]
async fn feeds_by_their_names() {
    let (h, f, base) = world().await;
    let id = client(&h);
    let uri = |r: &str| format!("at://{OTHER}/app.bsky.feed.generator/{r}");
    let call = |method: &str, params: Value| (method.to_string(), params);
    let as_map = |v: Value| v.as_object().unwrap().clone();
    // Signed out, a name, or saved, asks for sign-in; an at-uri goes on.
    for (method, params) in [
        call("app.bsky.feed.getFeed", json!({ "feed": "For You" })),
        call("app.bsky.feed.getFeed", json!({ "feed": "following" })),
        call(
            "app.bsky.feed.getFeedGenerators",
            json!({ "feeds": "saved" }),
        ),
    ] {
        let mut p = as_map(params);
        assert_eq!(
            h.feeds_by_name(&method, &mut p, None).await,
            Err(Refusal::SignIn),
            "{method}"
        );
    }
    let mut p = as_map(json!({ "feed": uri("for-you") }));
    assert_eq!(
        h.feeds_by_name("app.bsky.feed.getFeed", &mut p, None)
            .await
            .unwrap(),
        "app.bsky.feed.getFeed"
    );
    // Signed in: the saved feeds from the preferences, named by the AppView.
    {
        let mut w = f.lock().unwrap();
        w.prefs = json!({ "preferences": [{ "$type": "app.bsky.actor.defs#savedFeedsPrefV2", "items": [
            { "id": "a", "type": "timeline", "value": "following", "pinned": true },
            { "id": "b", "type": "feed", "value": uri("for-you"), "pinned": true },
            { "id": "c", "type": "feed", "value": uri("art"), "pinned": false },
            { "id": "d", "type": "feed", "value": uri("unnamed"), "pinned": false } ] }] });
        w.feed_names = HashMap::from([
            (uri("for-you"), "For You".to_string()),
            (uri("art"), "Art History".to_string()),
        ]);
    }
    let (access, _) = signed_in(&h, &f, &base, &id).await;
    let account = h.auth().unwrap().account(&access).unwrap();
    let by_name = |name: &str| as_map(json!({ "feed": name, "limit": 5 }));
    let mut p = by_name(" for you");
    assert_eq!(
        h.feeds_by_name("app.bsky.feed.getFeed", &mut p, Some(&account))
            .await
            .unwrap(),
        "app.bsky.feed.getFeed"
    );
    assert_eq!(p, as_map(json!({ "feed": uri("for-you"), "limit": 5 })));
    // A name it holds; a generator with no name goes by its rkey.
    let mut p = by_name("history");
    h.feeds_by_name("app.bsky.feed.getFeed", &mut p, Some(&account))
        .await
        .unwrap();
    assert_eq!(p["feed"], uri("art"));
    let mut p = by_name("unnamed");
    h.feeds_by_name("app.bsky.feed.getFeed", &mut p, Some(&account))
        .await
        .unwrap();
    assert_eq!(p["feed"], uri("unnamed"));
    // None: the feeds named, pinned first.
    let mut p = by_name("News");
    assert_eq!(
        h.feeds_by_name("app.bsky.feed.getFeed", &mut p, Some(&account))
            .await,
        Err(Refusal::Error(
            "No saved feed is named \"News\". Your feeds: Following, For You, Art History, unnamed"
                .into()
        ))
    );
    // Following is the timeline, its other params kept.
    let mut p = by_name("Following");
    assert_eq!(
        h.feeds_by_name("app.bsky.feed.getFeed", &mut p, Some(&account))
            .await
            .unwrap(),
        "app.bsky.feed.getTimeline"
    );
    assert_eq!(p, as_map(json!({ "limit": 5 })));
    // saved and pinned: the account's feeds, in their order.
    let mut p = as_map(json!({ "feeds": "saved" }));
    h.feeds_by_name("app.bsky.feed.getFeedGenerators", &mut p, Some(&account))
        .await
        .unwrap();
    assert_eq!(
        p["feeds"],
        json!([uri("for-you"), uri("art"), uri("unnamed")])
    );
    let mut p = as_map(json!({ "feeds": "Pinned" }));
    h.feeds_by_name("app.bsky.feed.getFeedGenerators", &mut p, Some(&account))
        .await
        .unwrap();
    assert_eq!(p["feeds"], json!([uri("for-you")]));
    // Read once, kept for the rest.
    assert_eq!(f.lock().unwrap().prefs_reads, 1);
}

#[tokio::test]
async fn sends_interactions_to_the_feed_generator() {
    let (h, f, base) = world().await;
    let id = client(&h);
    let feed = format!("at://{OTHER}/app.bsky.feed.generator/open");
    let seen = |feed: &str| {
        json!({ "feed": feed, "interactions": [
            { "item": format!("at://{OTHER}/app.bsky.feed.post/3k1"),
              "event": "app.bsky.feed.defs#interactionSeen", "feedContext": "ctx", "reqId": "r1" },
            { "item": format!("at://{OTHER}/app.bsky.feed.post/3k2"),
              "event": "app.bsky.feed.defs#requestMore" } ] })
    };
    // Signed out, it asks for sign-in.
    assert_eq!(
        h.call_tool("send_interactions", Some(&seen(&feed)), None)
            .await
            .unwrap()
            .err(),
        Some(Refusal::SignIn)
    );
    let (access, _) = signed_in(&h, &f, &base, &id).await;
    let account = h.auth().unwrap().account(&access).unwrap();
    // Through the PDS to the generator's service, as its feed generator.
    let out = h
        .call_tool("send_interactions", Some(&seen(&feed)), Some(&account))
        .await
        .unwrap()
        .unwrap();
    assert_eq!(out.structured, json!({ "sent": 2 }));
    assert_eq!(out.text, "Sent 2 interactions to did:web:fg.test.");
    {
        let w = f.lock().unwrap();
        let (proxy, body) = &w.interactions[0];
        assert_eq!(proxy, "did:web:fg.test#bsky_fg");
        assert_eq!(body, &seen(&feed));
    }
    // The generator is kept: read once for two sends.
    h.call_tool("send_interactions", Some(&seen(&feed)), Some(&account))
        .await
        .unwrap()
        .unwrap();
    assert_eq!(f.lock().unwrap().generator_reads, 1);
    assert_eq!(f.lock().unwrap().interactions.len(), 2);
    // A feed that takes none: a quiet answer, nothing sent.
    let closed = format!("at://{OTHER}/app.bsky.feed.generator/closed");
    let out = h
        .call_tool("send_interactions", Some(&seen(&closed)), Some(&account))
        .await
        .unwrap()
        .unwrap();
    assert_eq!(
        out.structured,
        json!({ "sent": 0, "reason": "the feed doesn't take interactions" })
    );
    assert_eq!(f.lock().unwrap().interactions.len(), 2);
    // Bad input is the tool's error, before anything is read.
    let bad = json!({ "feed": feed, "interactions": [{ "item": "x", "event": "y" }] });
    assert!(matches!(
        h.call_tool("send_interactions", Some(&bad), Some(&account)).await.unwrap(),
        Err(Refusal::Error(e)) if e.starts_with("interactions[0].item")
    ));
    assert_eq!(f.lock().unwrap().generator_reads, 2);
}

#[tokio::test]
async fn calls_procedures_bundled_views_call_through_the_pds() {
    let (h, f, base) = world().await;
    let id = client(&h);
    let send = |convo: &str, text: String| {
        json!({ "method": "chat.bsky.convo.sendMessage", "service": "did:web:api.bsky.chat#bsky_chat",
                "input": { "convoId": convo, "message": { "text": text } } })
    };
    let hi = send("3l2abc", "hi there".into());
    // Signed out, it asks for sign-in.
    assert_eq!(
        h.call_tool("call_procedure", Some(&hi), None)
            .await
            .unwrap()
            .err(),
        Some(Refusal::SignIn)
    );
    let (access, _) = signed_in(&h, &f, &base, &id).await;
    let account = h.auth().unwrap().account(&access).unwrap();
    // Through the PDS to Bluesky's chat service; the message's view back.
    let out = h
        .call_tool("call_procedure", Some(&hi), Some(&account))
        .await
        .unwrap()
        .unwrap();
    assert_eq!(out.text, "Called chat.bsky.convo.sendMessage.");
    assert_eq!(out.structured["output"]["text"], "hi there");
    assert_eq!(out.structured["output"]["sender"]["did"], DID);
    {
        let w = f.lock().unwrap();
        let (proxy, body) = &w.messages[0];
        assert_eq!(proxy, "did:web:api.bsky.chat#bsky_chat");
        assert_eq!(body, &hi["input"]);
    }
    // The service's refusal is the tool's error, by its error's name.
    assert!(matches!(
        h.call_tool("call_procedure", Some(&send("gone", "x".into())), Some(&account)).await.unwrap(),
        Err(Refusal::Error(e)) if e == "did:web:api.bsky.chat refused chat.bsky.convo.sendMessage: InvalidConvo (400)"
    ));
    // Input its lexicon refuses, or a procedure no bundled view calls,
    // never goes.
    for refused in [
        send("3l2abc", "x".repeat(1001)),
        json!({ "method": "chat.bsky.convo.sendMessage", "service": "did:web:api.bsky.chat#bsky_chat",
                "input": { "convoId": "3l2abc" } }),
        json!({ "method": "chat.bsky.convo.deleteMessageForSelf", "service": "did:web:api.bsky.chat#bsky_chat",
                "input": { "convoId": "3l2abc", "messageId": "m1" } }),
    ] {
        assert!(matches!(
            h.call_tool("call_procedure", Some(&refused), Some(&account))
                .await
                .unwrap(),
            Err(Refusal::Error(_))
        ));
    }
    assert_eq!(f.lock().unwrap().messages.len(), 2);
}

#[tokio::test]
async fn queries_through_the_pds_when_signed_in() {
    let (h, f, base) = world().await;
    let id = client(&h);
    let service = crate::xrpc::Service::parse("did:web:api.bsky.app#bsky_appview").unwrap();
    let method = "app.bsky.feed.getTimeline";
    let pairs = [("limit".to_string(), "5".to_string())];
    // As no one, a query that wants an account asks for sign-in.
    let public = crate::xrpc::Caller::Public;
    assert_eq!(
        h.call_query(public, &base, &service, method, &pairs).await,
        Err(Refusal::SignIn)
    );
    // Signed in, it goes through the account's PDS, proxied to the service.
    let (access, _) = signed_in(&h, &f, &base, &id).await;
    let account = h.auth().unwrap().account(&access).unwrap();
    let answer = h
        .call_query(
            crate::xrpc::Caller::Account(&account),
            "https://api.bsky.app",
            &service,
            method,
            &pairs,
        )
        .await
        .unwrap();
    assert_eq!(answer, json!({ "feed": [], "cursor": "c1" }));
    // With sign-in off, the refusal is the tool's error, as before.
    let mut off = config(&base);
    off.oauth = false;
    let off = Hud::new(off).unwrap();
    assert!(matches!(
        off.call_query(public, &base, &service, method, &pairs).await,
        Err(Refusal::Error(e)) if e.ends_with("refused app.bsky.feed.getTimeline: AuthMissing (401)")
    ));
}

/// A view's query joins ask as the person asking, as the query tool does:
/// signed out, straight to each service; signed in, through their PDS,
/// each proxied to its own service.
#[tokio::test]
async fn query_joins_ask_as_the_person() {
    let (h, f, base) = world().await;
    let id = client(&h);
    // Two services, both answered by the fake.
    for did in ["did:web:api.bsky.app", "did:web:other.test"] {
        let doc = json!({ "id": did, "service": [{ "id": "#bsky_appview",
            "type": "BskyAppView", "serviceEndpoint": base }] });
        h.docs.put(
            did.to_string(),
            Ok(Arc::new(doc)),
            std::time::Duration::from_secs(600),
        );
    }
    let view = json!({ "method": "app.bsky.actor.getProfile", "service": "did:web:api.bsky.app#bsky_appview",
        "description": "d", "query": { "join": [
            { "as": "posts", "query": "app.bsky.feed.getAuthorFeed",
              "params": { "actor": { "$": "response.did" }, "limit": 5 } },
            { "as": "feeds", "query": "app.bsky.feed.getActorFeeds", "service": "did:web:other.test#bsky_appview",
              "params": { "actor": { "$": "response.did" } } }
        ], "layout": { "component": "Badge", "props": { "value": "x" } } } });
    let joins = crate::view::parse(&view, false)
        .unwrap()
        .query
        .unwrap()
        .queries;
    let scope = json!({ "response": { "did": DID } });
    let own = Some("did:web:api.bsky.app#bsky_appview");
    let (hud, joins, scope, fake) = (&*h, &joins, &scope, &f);
    let ask = |caller| async move {
        let asker = crate::xrpc::As { hud, caller };
        let got =
            crate::join::queries(&asker, joins.iter(), own, scope, crate::join::QUERY_WAIT).await;
        let mut asked = std::mem::take(&mut fake.lock().unwrap().joined);
        asked.sort();
        (Value::Object(got), asked)
    };
    let answers = json!({ "posts": { "feed": [] }, "feeds": { "feeds": [] } });
    let method = |m: &str| format!("app.bsky.feed.{m}");
    // Signed out: straight to each service, with no token.
    let (got, asked) = ask(crate::xrpc::Caller::Public).await;
    assert_eq!(got, answers);
    assert_eq!(
        asked,
        [
            (method("getActorFeeds"), None, false),
            (method("getAuthorFeed"), None, false)
        ]
    );
    // Signed in: through the account's PDS to a service HUD asks to call
    // as the account; to any other, straight, as no one.
    let (access, _) = signed_in(&h, &f, &base, &id).await;
    let account = h.auth().unwrap().account(&access).unwrap();
    let (got, asked) = ask(crate::xrpc::Caller::Account(&account)).await;
    assert_eq!(got, answers);
    assert_eq!(
        asked,
        [
            (method("getActorFeeds"), None, false),
            (
                method("getAuthorFeed"),
                Some("did:web:api.bsky.app#bsky_appview".into()),
                true
            )
        ]
    );
}

#[tokio::test]
async fn sign_in_page_refusals() {
    let (h, _f, _base) = world().await;
    let id = client(&h);
    let pending = h
        .authorize(&authorize_params(&id, &jose::random(32)))
        .await
        .unwrap();
    assert_eq!(
        h.sign_in("unknown", DID).await,
        Err(client::SignIn::Expired)
    );
    // A failure is the page again, the handle as typed, saying why.
    for (login, hint, why) in [
        (
            "",
            None,
            "Enter your handle, as alice.bsky.social".to_string(),
        ),
        (
            " Not A Handle ",
            Some("Not A Handle"),
            "not a handle is not a handle or a DID".to_string(),
        ),
        (
            OTHER,
            Some(OTHER),
            format!("{OTHER} does not resolve to an account"),
        ),
    ] {
        let page = issuer::Pending {
            login_hint: hint.map(str::to_string),
            ..pending.clone()
        };
        assert_eq!(
            h.sign_in(&pending.id, login).await,
            Err(client::SignIn::Failed(page, why)),
            "{login}"
        );
    }
    // A failure leaves the request waiting, to try again.
    assert!(h.auth().unwrap().pending(&pending.id).is_some());
    // With sign-in off, no request waits.
    let mut off = config("http://127.0.0.1:9");
    off.oauth = false;
    let off = Hud::new(off).unwrap();
    assert_eq!(
        off.sign_in(&pending.id, DID).await,
        Err(client::SignIn::Expired)
    );
    assert_eq!(off.sign_up(&pending.id).await, Err(client::SignIn::Expired));
}

#[tokio::test]
async fn web_sign_in_gives_a_cookie_for_the_workspace_alone() {
    let (h, f, base) = world().await;
    let a = h.auth().unwrap();
    // An MCP session of the account first: the web session is another.
    let id = client(&h);
    let (access, _) = signed_in(&h, &f, &base, &id).await;
    // Named, the account's server's authorization page; no handle, or one
    // that is none, is refused in words, nothing kept waiting.
    for (login, why) in [
        ("", "Enter your handle, as alice.bsky.social"),
        ("not a handle", "not a handle is not a handle or a DID"),
    ] {
        assert_eq!(h.web_sign_in(login).await, Err(why.to_string()));
    }
    assert!(a.lock().requests.is_empty());
    let to = h.web_sign_in(DID).await.unwrap();
    assert!(to.starts_with(&format!("{base}/authorize?")), "{to}");
    let (state, code) = f.lock().unwrap().last_par.clone().unwrap();
    let back = h
        .callback(&pairs(&[
            ("state", &state),
            ("iss", &base),
            ("code", &code),
        ]))
        .await
        .unwrap();
    let client::Callback::Web(cookie) = back else {
        panic!("not a web session: {back:?}");
    };
    assert_eq!(a.web_account(&cookie).unwrap().did, DID);
    // The cookie is never a bearer token, nor an MCP token a cookie.
    assert!(a.account(&cookie).is_none());
    assert!(a.web_account(&access).is_none());
    // Kept on disk as a web session, the cookie hashed; read again after a
    // restart.
    let web = json_files(&a.dir.join("sessions"))
        .into_iter()
        .map(|p| std::fs::read_to_string(p).unwrap())
        .find(|s| s.contains("\"kind\":\"web\""))
        .unwrap();
    assert!(!web.contains(&cookie) && web.contains(&jose::sha256(&cookie)));
    let again = Auth::open(ORIGIN, "atproto", a.dir.parent().unwrap()).unwrap();
    assert_eq!(again.web_account(&cookie).unwrap().did, DID);
    assert!(again.account(&cookie).is_none());
    // The MCP revocation endpoint does not take a cookie.
    h.revoke(&pairs(&[("token", &cookie)])).await.unwrap();
    assert!(a.web_account(&cookie).is_some());
    // Signing out ends the web session alone, its atproto refresh token
    // revoked at its server.
    h.sign_out(&cookie).await;
    assert!(a.web_account(&cookie).is_none());
    assert_eq!(f.lock().unwrap().revocations, 1);
    assert!(a.account(&access).is_some());
    h.sign_out(&cookie).await;
    assert_eq!(f.lock().unwrap().revocations, 1);
    // A web sign-in the PDS refuses ends on HUD's own page, not at a client.
    h.web_sign_in(DID).await.unwrap();
    let (state, _) = f.lock().unwrap().last_par.clone().unwrap();
    assert_eq!(
        h.callback(&pairs(&[("state", &state), ("error", "access_denied")]))
            .await
            .unwrap(),
        client::Callback::WebRefused("The sign-in at your account's server did not finish".into())
    );
}

// Logs, as an operator reads them.

/// The events logged while a future runs or a closure is called, each as
/// its message and fields, `message k=v …`.
#[derive(Clone, Default)]
struct Logs(Arc<StdMutex<Vec<String>>>);

impl Logs {
    fn lines(&self) -> Vec<String> {
        self.0.lock().unwrap().clone()
    }

    /// A dispatcher of these logs. Another is kept registered for good:
    /// with one alone, a callsite another test's thread meets first is
    /// asked of that thread's dispatcher, none, and told never to log. As
    /// each answers `sometimes`, a thread logging to none evaluates nothing.
    fn dispatch(&self) -> tracing::Dispatch {
        static KEEPER: std::sync::LazyLock<tracing::Dispatch> =
            std::sync::LazyLock::new(|| tracing::Dispatch::new(Logs::default()));
        std::sync::LazyLock::force(&KEEPER);
        tracing::Dispatch::new(self.clone())
    }
}

impl tracing::Subscriber for Logs {
    fn register_callsite(
        &self,
        _: &'static tracing::Metadata<'static>,
    ) -> tracing::subscriber::Interest {
        tracing::subscriber::Interest::sometimes()
    }
    fn enabled(&self, _: &tracing::Metadata<'_>) -> bool {
        true
    }
    fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id {
        tracing::span::Id::from_u64(1)
    }
    fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {}
    fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {}
    fn event(&self, e: &tracing::Event<'_>) {
        struct Line(String, Vec<String>);
        impl tracing::field::Visit for Line {
            fn record_debug(&mut self, f: &tracing::field::Field, v: &dyn std::fmt::Debug) {
                match f.name() {
                    "message" => self.0 = format!("{v:?}"),
                    name => self.1.push(format!("{name}={v:?}")),
                }
            }
        }
        let mut line = Line(String::new(), Vec::new());
        e.record(&mut line);
        let mut text = line.0;
        for field in line.1 {
            text = format!("{text} {field}");
        }
        self.0.lock().unwrap().push(text);
    }
    fn enter(&self, _: &tracing::span::Id) {}
    fn exit(&self, _: &tracing::span::Id) {}
}

// Sign-ins at their edges.

/// The account's PDS, as PLC and HUD's cache of its document name it.
fn set_pds(h: &Hud, f: &Fake, pds: &str) {
    let doc = json!({ "id": DID, "service": [{ "id": "#atproto_pds",
        "type": "AtprotoPersonalDataServer", "serviceEndpoint": pds }] });
    f.lock().unwrap().docs.insert(DID.into(), doc.clone());
    h.docs.put(
        DID.to_string(),
        Ok(Arc::new(doc)),
        std::time::Duration::from_secs(600),
    );
}

/// An authorization request of `client_id` pushed to the fake: its
/// `state`.
async fn pushed(h: &Hud, f: &Fake, client_id: &str) -> String {
    let pending = h
        .authorize(&authorize_params(client_id, &jose::random(32)))
        .await
        .unwrap();
    h.sign_in(&pending.id, DID).await.unwrap();
    f.lock().unwrap().last_par.clone().unwrap().0
}

/// Why a sign-in at the fake failed, as its page says it, the request
/// still waiting.
async fn sign_in_failure(h: &Hud, client_id: &str) -> String {
    let pending = h
        .authorize(&authorize_params(client_id, &jose::random(32)))
        .await
        .unwrap();
    match h.sign_in(&pending.id, DID).await {
        Err(client::SignIn::Failed(page, why)) => {
            assert_eq!(page.id, pending.id);
            assert!(h.auth().unwrap().pending(&pending.id).is_some());
            why
        }
        other => panic!("not refused: {other:?}"),
    }
}

/// A session of `did`, signed in, not yet kept.
fn session(did: &str) -> Session {
    Session {
        id: jose::random(32),
        did: did.to_string(),
        handle: None,
        pds: "https://pds.invalid".into(),
        issuer: "https://pds.invalid".into(),
        token_endpoint: "https://pds.invalid/oauth/token".into(),
        revocation_endpoint: None,
        scope: "atproto".into(),
        asked: "atproto".into(),
        access_token: "at".into(),
        refresh_token: None,
        expires_at: now() + 3600,
        dpop: Keypair::generate(Curve::P256),
        nonces: Default::default(),
        client_id: String::new(),
        kind: Kind::Mcp,
        mcp: issuer::unissued(),
        created_at: now(),
        ended: false,
    }
}

/// The session an MCP access token or a web cookie is of.
fn cell_of(a: &Auth, token: &str) -> Arc<tokio::sync::Mutex<Session>> {
    a.account(token)
        .or_else(|| a.web_account(token))
        .unwrap()
        .session
}

#[tokio::test]
async fn account_servers_held_to_what_hud_signs_in_with() {
    let (h, f, base) = world().await;
    let id = client(&h);
    let no_oauth = "Your account's server does not offer OAuth sign-in";
    // A PDS with no protected resource metadata, or one that is not an
    // object, or names no authorization server.
    set_pds(&h, &f, &format!("{base}/nowhere"));
    assert_eq!(sign_in_failure(&h, &id).await, no_oauth);
    set_pds(&h, &f, &base);
    for resource in [json!([]), json!({})] {
        f.lock().unwrap().resource = Some(resource);
        assert_eq!(sign_in_failure(&h, &id).await, no_oauth);
    }
    // One naming an authorization server by more than its origin, or one
    // that does not answer.
    for (server, why) in [
        (
            format!("{base}/as"),
            "Your account's server names an authorization server HUD cannot use",
        ),
        (
            "http://127.0.0.1:1".into(),
            "Your account's authorization server could not be read",
        ),
    ] {
        f.lock().unwrap().resource = Some(json!({ "authorization_servers": [server] }));
        assert_eq!(sign_in_failure(&h, &id).await, why);
    }
    f.lock().unwrap().resource = None;
    // An authorization server naming another issuer, lacking what HUD
    // signs in with, or an endpoint HUD may call.
    let lacks = "Your account's authorization server does not offer what HUD signs in with (DPoP and private_key_jwt, ES256)";
    let no_endpoint = "Your account's authorization server lacks an endpoint HUD needs";
    for (meta, why) in [
        (
            json!({ "issuer": "https://other.example" }),
            "Your account's authorization server names another issuer",
        ),
        (
            json!({ "dpop_signing_alg_values_supported": ["RS256"] }),
            lacks,
        ),
        (
            json!({ "token_endpoint_auth_methods_supported": ["none"] }),
            lacks,
        ),
        (
            json!({ "token_endpoint_auth_signing_alg_values_supported": ["RS256"] }),
            lacks,
        ),
        (
            json!({ "pushed_authorization_request_endpoint": "http://u:p@127.0.0.1/par" }),
            no_endpoint,
        ),
        (json!({ "token_endpoint": "not a url" }), no_endpoint),
        // PAR answered from elsewhere than its endpoint.
        (
            json!({ "pushed_authorization_request_endpoint": format!("{base}/moved") }),
            "Your account's server could not be reached: it answered from elsewhere",
        ),
    ] {
        f.lock().unwrap().meta = Some(meta.clone());
        assert_eq!(sign_in_failure(&h, &id).await, why, "{meta}");
    }
    // PAR at no server at all.
    f.lock().unwrap().meta =
        Some(json!({ "pushed_authorization_request_endpoint": "http://127.0.0.1:1/par" }));
    let why = sign_in_failure(&h, &id).await;
    assert!(
        why.starts_with("Your account's server could not be reached: "),
        "{why}"
    );
    // PAR refused: by its error's name, where that is safe to repeat, else
    // by its status; logged so too.
    f.lock().unwrap().meta = None;
    let logs = Logs::default();
    for (error, why) in [
        (
            "invalid_request",
            "Your account's server refused the sign-in: invalid_request",
        ),
        (
            "<b>no</b>",
            "Your account's server refused the sign-in (400)",
        ),
    ] {
        f.lock().unwrap().par_answer = Some((StatusCode::BAD_REQUEST, json!({ "error": error })));
        let failure = tracing::instrument::WithSubscriber::with_subscriber(
            sign_in_failure(&h, &id),
            logs.dispatch(),
        );
        assert_eq!(failure.await, why);
    }
    let refused: Vec<String> = logs
        .lines()
        .into_iter()
        .filter(|l| l.starts_with("PAR refused"))
        .collect();
    assert_eq!(
        refused,
        [
            format!("PAR refused status=400 error=\"invalid_request\" issuer=\"{base}\""),
            format!("PAR refused status=400 issuer=\"{base}\""),
        ]
    );
    // A server naming no signing algorithms is taken to sign with ES256.
    f.lock().unwrap().par_answer = None;
    f.lock().unwrap().meta =
        Some(json!({ "token_endpoint_auth_signing_alg_values_supported": null }));
    pushed(&h, &f, &id).await;
}

#[tokio::test]
async fn callbacks_that_go_no_further() {
    let (h, f, base) = world().await;
    let id = client(&h);
    let back = |c: Result<client::Callback, String>| query_of(&to_client(c.unwrap()));
    let said = |q: &HashMap<String, String>| (q["error"].clone(), q["error_description"].clone());
    let did_not_finish = "The sign-in at your account's server did not finish";
    // The server's error, by one of the names a client is told, else as
    // access denied.
    for (error, told) in [
        ("login_required", "login_required"),
        ("server_error", "access_denied"),
    ] {
        let state = pushed(&h, &f, &id).await;
        let q = back(
            h.callback(&pairs(&[("state", &state), ("error", error)]))
                .await,
        );
        assert_eq!(said(&q), (told.into(), did_not_finish.into()));
    }
    // No code.
    let state = pushed(&h, &f, &id).await;
    let q = back(
        h.callback(&pairs(&[("state", &state), ("iss", &base)]))
            .await,
    );
    assert_eq!(
        said(&q),
        (
            "server_error".into(),
            "Your account's server gave no code".into()
        )
    );
    // A code the server refuses, by name or by status.
    let exchange = |state: String| {
        let h = h.clone();
        let base = base.clone();
        async move {
            let q = pairs(&[("state", &state), ("iss", &base), ("code", "bogus")]);
            h.callback(&q).await
        }
    };
    let state = pushed(&h, &f, &id).await;
    assert_eq!(
        said(&back(exchange(state).await)),
        (
            "access_denied".into(),
            "Your account's server refused the code: invalid_grant".into()
        )
    );
    f.lock().unwrap().token_answer = Some((StatusCode::INTERNAL_SERVER_ERROR, json!({})));
    let state = pushed(&h, &f, &id).await;
    assert_eq!(
        said(&back(exchange(state).await)).1,
        "Your account's server refused the code (500)"
    );
    // An answer that is not the tokens HUD signs in with.
    f.lock().unwrap().token_answer = Some((StatusCode::OK, json!({ "token_type": "Bearer" })));
    let state = pushed(&h, &f, &id).await;
    assert_eq!(
        said(&back(exchange(state).await)).1,
        "Your account's server's answer: its tokens are not DPoP-bound"
    );
    f.lock().unwrap().token_answer = None;
    // A token endpoint that does not answer.
    f.lock().unwrap().meta = Some(json!({ "token_endpoint": "http://127.0.0.1:1/token" }));
    let state = pushed(&h, &f, &id).await;
    let (error, why) = said(&back(exchange(state).await));
    assert_eq!(error, "access_denied");
    assert!(
        why.starts_with("Your account's server could not be reached: "),
        "{why}"
    );
    f.lock().unwrap().meta = None;
    // Signed in at the PDS, but too many codes are waiting for HUD to give
    // one more.
    let state = pushed(&h, &f, &id).await;
    let code = f.lock().unwrap().last_par.clone().unwrap().1;
    {
        let a = h.auth().unwrap();
        let s = session(DID);
        let mut st = a.lock();
        for i in 0..PENDING_MAX {
            st.codes.insert(
                i.to_string(),
                issuer::Code {
                    client_id: id.clone(),
                    redirect_uri: REDIRECT.into(),
                    challenge: String::new(),
                    session: s.clone(),
                    refresh: false,
                    created: now(),
                },
            );
        }
    }
    let q = back(
        h.callback(&pairs(&[
            ("state", &state),
            ("iss", &base),
            ("code", &code),
        ]))
        .await,
    );
    assert_eq!(
        said(&q),
        (
            "temporarily_unavailable".into(),
            "Too many sign-ins are waiting".into()
        )
    );
}

#[tokio::test]
async fn named_as_configured_to_accounts_servers() {
    let shown = crate::config::Client {
        name: "Grain".into(),
        logo: Some("https://grain.test/icon.png".into()),
    };
    let (h, _f, _base) = world_with(|c| c.client = shown.clone()).await;
    let a = h.auth().unwrap();
    let c = a.client_metadata();
    assert_eq!(c["client_name"], "Grain");
    assert_eq!(c["logo_uri"], "https://grain.test/icon.png");
    // The workspace's own sign-in page names it so too.
    a.lock()
        .requests
        .insert("w".into(), Asker::Web { created: now() });
    assert_eq!(a.pending("w").unwrap().client, "Grain");
}

#[tokio::test]
async fn too_many_waiting() {
    let (h, _f, _base) = world().await;
    let id = client(&h);
    let a = h.auth().unwrap();
    let busy = "Too many sign-ins are waiting; try again in a few minutes";
    // Requests waiting for their account.
    {
        let mut st = a.lock();
        for i in 0..PENDING_MAX {
            st.requests
                .insert(i.to_string(), Asker::Web { created: now() });
        }
    }
    assert_eq!(h.web_sign_in(DID).await.unwrap_err(), busy);
    assert_eq!(
        h.authorize(&authorize_params(&id, "v")).await.unwrap_err(),
        NotAuthorized::Page(busy.into())
    );
    a.lock().requests.clear();
    // Sign-ins in progress at accounts' servers: by then the request was
    // taken, so its page says it expired.
    let pending = h.authorize(&authorize_params(&id, "v")).await.unwrap();
    {
        let dpop = Keypair::generate(Curve::P256);
        let server = client::Server {
            issuer: "https://pds.invalid".into(),
            par: "https://pds.invalid/par".into(),
            authorization: "https://pds.invalid/authorize".into(),
            token: "https://pds.invalid/token".into(),
            revocation: None,
        };
        let mut st = a.lock();
        for i in 0..PENDING_MAX {
            let flow = Flow {
                asker: Asker::Web { created: now() },
                verifier: String::new(),
                dpop: dpop.clone(),
                server: server.clone(),
                did: Some(DID.into()),
                nonce: None,
                asked: String::new(),
                created: now(),
            };
            st.flows.insert(i.to_string(), flow);
        }
    }
    assert_eq!(
        h.sign_in(&pending.id, DID).await,
        Err(client::SignIn::Expired)
    );
    assert!(a.pending(&pending.id).is_none());
    // So too the workspace's, and the app's naming its account.
    assert_eq!(
        h.web_sign_in(DID).await,
        Err("This sign-in took too long; try again".into())
    );
    let mut app = authorize_params(&a.app_client_id(), "v");
    for (k, v) in &mut app {
        if k == "redirect_uri" {
            *v = super::APP_REDIRECT.into();
        }
    }
    app.push(("login_hint".into(), DID.into()));
    assert_eq!(
        h.begin_sign_in(&app).await.unwrap_err(),
        NotAuthorized::Page("This sign-in has expired; start again from your app".into())
    );
    // Clients registered.
    {
        let mut st = a.lock();
        for i in 0..10_000 {
            let c = issuer::Client {
                id: i.to_string(),
                name: None,
                redirect_uris: vec![REDIRECT.into()],
                refresh: false,
            };
            st.registered.insert(c.id.clone(), c);
        }
    }
    let full = h
        .register(
            json!({ "redirect_uris": [REDIRECT] })
                .to_string()
                .as_bytes(),
        )
        .unwrap_err();
    assert_eq!(
        full.to_json(),
        json!({ "error": "temporarily_unavailable",
                "error_description": "No more clients are registered here" })
    );
    assert_eq!(full.status, 503);
}

#[tokio::test]
async fn refreshes_as_the_server_answers_them() {
    // A server that asks for no DPoP nonce: none is sent, or kept.
    let (h, f, base) = world().await;
    f.lock().unwrap().nonce = String::new();
    let id = client(&h);
    let (access, _) = signed_in(&h, &f, &base, &id).await;
    let a = h.auth().unwrap();
    let account = a.account(&access).unwrap();
    let like = json!({ "collection": "app.bsky.feed.like", "record": {
        "subject": { "uri": format!("at://{OTHER}/app.bsky.feed.post/3k2a"), "cid": CID },
        "createdAt": "2026-11-14T12:00:00.000Z" } });
    let write = |account: &Account| {
        let (h, like, account) = (h.clone(), like.clone(), account.clone());
        async move {
            h.call_tool("create_record", Some(&like), Some(&account))
                .await
                .unwrap()
                .err()
        }
    };
    let expire = |account: &Account| {
        let cell = account.session.clone();
        async move { cell.lock().await.expires_at = 0 }
    };
    assert_eq!(write(&account).await, None);
    assert_eq!(f.lock().unwrap().nonce_refusals, 0);
    // A refresh answered with no new refresh token keeps the one it had.
    f.lock().unwrap().no_refresh = true;
    expire(&account).await;
    assert_eq!(write(&account).await, None);
    let kept = account.session.lock().await.refresh_token.clone();
    assert_eq!(kept.as_deref(), Some("rt1"));
    expire(&account).await;
    assert_eq!(write(&account).await, None);
    assert_eq!(f.lock().unwrap().refreshes, 2);
    assert!(account.session.lock().await.nonces.is_empty());
    // A server failing: the call fails, the session stays.
    f.lock().unwrap().token_answer = Some((StatusCode::SERVICE_UNAVAILABLE, json!({})));
    expire(&account).await;
    assert_eq!(
        write(&account).await,
        Some(Refusal::Error(
            "Your account's server could not renew your sign-in: it answered 503".into()
        ))
    );
    assert!(a.account(&access).is_some());
    // A refresh refused ends the session, logged by the error's name.
    f.lock().unwrap().token_answer =
        Some((StatusCode::BAD_REQUEST, json!({ "error": "invalid_grant" })));
    let logs = Logs::default();
    let refused =
        tracing::instrument::WithSubscriber::with_subscriber(write(&account), logs.dispatch());
    assert_eq!(refused.await, Some(Refusal::SignIn));
    assert!(a.account(&access).is_none());
    assert!(
        logs.lines().contains(&format!(
            "refresh refused did=\"{DID}\" status=400 error=\"invalid_grant\""
        )),
        "{:?}",
        logs.lines()
    );
    // A session given no refresh token ends when its access token expires.
    f.lock().unwrap().token_answer = None;
    let (access, _) = signed_in(&h, &f, &base, &id).await;
    let account = a.account(&access).unwrap();
    assert_eq!(account.session.lock().await.refresh_token, None);
    expire(&account).await;
    assert_eq!(write(&account).await, Some(Refusal::SignIn));
    assert_eq!(f.lock().unwrap().refreshes, 4);
}

#[tokio::test]
async fn pds_calls_that_fail() {
    let (h, f, base) = world().await;
    let a = h.auth().unwrap();
    let read = |token: String| {
        let h = h.clone();
        async move {
            let account = h.auth().unwrap().account(&token).unwrap();
            h.pds_call(&account, "app.bsky.feed.getTimeline", &[], None, None)
                .await
                .err()
        }
    };
    // A PDS that is not a URL, or answers nothing.
    let token = a.signed_in_offline_at(DID, None, false, "not a url");
    assert_eq!(
        read(token).await,
        Some(Refusal::Error("not a url is not a usable PDS".into()))
    );
    // A session kept with a token endpoint that is no URL cannot be renewed.
    let kept = a.signed_in_offline_at(DID, None, false, "kept badly");
    {
        let cell = cell_of(a, &kept);
        let mut s = cell.lock().await;
        s.refresh_token = Some("rt".into());
        s.expires_at = 0;
    }
    assert_eq!(
        read(kept).await,
        Some(Refusal::Error(
            "Your account's server could not renew your sign-in: not a URL".into()
        ))
    );
    // A session kept with a PDS and token endpoint HUD may not call: a
    // read, a write, a renewal, each refused before anything is sent.
    let unsafe_at = || a.signed_in_offline_at(DID, None, false, "ftp://pds.example");
    let token = unsafe_at();
    let not_https = Some(Refusal::Error("ftp://pds.example is not https".into()));
    assert_eq!(read(token.clone()).await, not_https);
    let account = a.account(&token).unwrap();
    let write = h
        .pds_call(
            &account,
            "com.atproto.repo.createRecord",
            &[],
            Some(&json!({})),
            None,
        )
        .await
        .err();
    assert_eq!(write, not_https);
    let token = unsafe_at();
    {
        let cell = cell_of(a, &token);
        let mut s = cell.lock().await;
        s.refresh_token = Some("rt".into());
        s.expires_at = 0;
    }
    assert_eq!(
        read(token).await,
        Some(Refusal::Error(
            "Your account's server could not renew your sign-in: ftp://pds.example is not https"
                .into()
        ))
    );
    let token = a.signed_in_offline_at(DID, None, false, "http://127.0.0.1:1");
    assert!(matches!(
        read(token).await,
        Some(Refusal::Error(e)) if e.starts_with("Could not reach 127.0.0.1: ")
    ));
    // A PDS that refuses the token even once refreshed: its answer, after
    // one refresh.
    let id = client(&h);
    let (access, _) = signed_in(&h, &f, &base, &id).await;
    let account = a.account(&access).unwrap();
    f.lock().unwrap().refuse_all = true;
    let got = h
        .pds_call(
            &account,
            "com.atproto.repo.createRecord",
            &[],
            Some(&json!({})),
            None,
        )
        .await
        .unwrap();
    assert_eq!(got.status, 401);
    assert_eq!(f.lock().unwrap().refreshes, 1);
}

#[tokio::test]
async fn revocation_at_a_server_that_does_not_answer() {
    let (h, f, base) = world().await;
    f.lock().unwrap().meta = Some(json!({ "revocation_endpoint": "http://127.0.0.1:1/revoke" }));
    let id = client(&h);
    let (access, _) = signed_in(&h, &f, &base, &id).await;
    let a = h.auth().unwrap();
    let logs = Logs::default();
    let asked = pairs(&[("token", &access)]);
    let revoked =
        tracing::instrument::WithSubscriber::with_subscriber(h.revoke(&asked), logs.dispatch());
    revoked.await.unwrap();
    // The session ends at HUD all the same.
    assert!(a.account(&access).is_none());
    assert_eq!(f.lock().unwrap().revocations, 0);
    assert!(logs.lines().iter().any(|l| l.starts_with(&format!(
        "revocation at the account's server failed did=\"{DID}\" why="
    ))));
}

#[tokio::test]
async fn requests_and_grants_at_their_edges() {
    let (h, f, base) = world().await;
    let a = h.auth().unwrap();
    // A client with no name is shown by its id; with no refresh grant, it
    // is given no refresh token.
    let plain = h
        .register(
            json!({ "redirect_uris": [REDIRECT] })
                .to_string()
                .as_bytes(),
        )
        .unwrap()["client_id"]
        .as_str()
        .unwrap()
        .to_string();
    let p = h.authorize(&authorize_params(&plain, "v")).await.unwrap();
    assert_eq!(p.client, plain);
    let (back, verifier) = signed_in_at_pds(&h, &f, &base, &plain).await;
    let code = query_of(&back)["code"].clone();
    let exchange = |client: &str, code: &str, redirect: &str, verifier: &str| {
        pairs(&[
            ("grant_type", "authorization_code"),
            ("client_id", client),
            ("code", code),
            ("redirect_uri", redirect),
            ("code_verifier", verifier),
        ])
    };
    let t = h
        .token(&exchange(&plain, &code, REDIRECT, &verifier))
        .await
        .unwrap();
    assert!(t.get("refresh_token").is_none() && t["access_token"].is_string());
    // A code used again after its session ended is refused, as any.
    let access = t["access_token"].as_str().unwrap();
    h.revoke(&pairs(&[("token", access)])).await.unwrap();
    assert_eq!(
        h.token(&exchange(&plain, &code, REDIRECT, &verifier))
            .await
            .unwrap_err()
            .description,
        "The code is not one HUD gave, or was used, or expired"
    );
    // A code is its client's, and its redirect URI's.
    let id = client(&h);
    let mismatch = [
        (
            plain.as_str(),
            REDIRECT,
            "The code was given to another client",
        ),
        (
            id.as_str(),
            "http://127.0.0.1:8080/cb",
            "redirect_uri is not the request's",
        ),
    ];
    for (client_id, redirect, why) in mismatch {
        let (back, verifier) = signed_in_at_pds(&h, &f, &base, &id).await;
        let code = query_of(&back)["code"].clone();
        let refused = h
            .token(&exchange(client_id, &code, redirect, &verifier))
            .await
            .unwrap_err();
        assert_eq!(
            (refused.error, refused.description.as_str()),
            ("invalid_grant", why)
        );
    }
    // Refused back to the client: with no state given, none comes back; a
    // state too long is not repeated.
    let refusal = |p: Vec<(String, String)>| {
        let h = h.clone();
        async move {
            match h.authorize(&p).await {
                Err(NotAuthorized::Redirect(to)) => query_of(&to),
                other => panic!("not sent back: {other:?}"),
            }
        }
    };
    let mut p = authorize_params(&id, "v");
    p.retain(|(k, _)| k != "state" && k != "response_type");
    let q = refusal(p).await;
    assert_eq!(q["error"], "unsupported_response_type");
    assert!(!q.contains_key("state"));
    let mut p = authorize_params(&id, "v");
    p.retain(|(k, _)| k != "state");
    p.push(("state".into(), "s".repeat(1025)));
    let q = refusal(p).await;
    assert_eq!(
        (q["error"].as_str(), q["error_description"].as_str()),
        ("invalid_request", "state is too long")
    );
    assert!(!q.contains_key("state"));
    // A redirect URI that is no URL at all is no client's.
    let mut p = authorize_params(&id, "v");
    p.retain(|(k, _)| k != "redirect_uri");
    p.push(("redirect_uri".into(), "not a url".into()));
    assert_eq!(
        h.authorize(&p).await.unwrap_err(),
        NotAuthorized::Page("redirect_uri is not one of the client's".into())
    );
    // A refresh token used by another client, or past its time, ends its
    // session.
    let other = client(&h);
    let rotate = |client: &str, r: &str| {
        pairs(&[
            ("grant_type", "refresh_token"),
            ("client_id", client),
            ("refresh_token", r),
        ])
    };
    let (access, refresh) = signed_in(&h, &f, &base, &id).await;
    let refused = h.token(&rotate(&other, &refresh)).await.unwrap_err();
    assert_eq!(refused.description, "The refresh token is another client's");
    assert!(a.account(&access).is_none());
    let (access, refresh) = signed_in(&h, &f, &base, &id).await;
    cell_of(a, &access).lock().await.mcp.refresh_exp = 0;
    let refused = h.token(&rotate(&id, &refresh)).await.unwrap_err();
    assert_eq!(refused.description, "The refresh token expired");
    assert!(a.account(&access).is_none());
    // Revocation's hint, if given, names a kind of token.
    let (access, _) = signed_in(&h, &f, &base, &id).await;
    let refused = h
        .revoke(&pairs(&[
            ("token", &access),
            ("token_type_hint", "id_token"),
        ]))
        .await
        .unwrap_err();
    assert_eq!(
        refused.description,
        "token_type_hint must be access_token or refresh_token"
    );
    assert!(a.account(&access).is_some());
    h.revoke(&pairs(&[
        ("token", &access),
        ("token_type_hint", "access_token"),
    ]))
    .await
    .unwrap();
    assert!(a.account(&access).is_none());
}

#[tokio::test]
async fn racing_ends_end_once() {
    let (h, f, base) = world().await;
    let id = client(&h);
    let a = h.auth().unwrap();
    let rotate = |r: &str| {
        pairs(&[
            ("grant_type", "refresh_token"),
            ("client_id", &id),
            ("refresh_token", r),
        ])
    };
    // Two refreshes with one token, the second waiting on the first: the
    // first rotates, the second ends the session as a replaced token's use.
    let (access, refresh) = signed_in(&h, &f, &base, &id).await;
    let cell = cell_of(a, &access);
    let held = cell.lock().await;
    let (one, two) = (rotate(&refresh), rotate(&refresh));
    let mut first = std::pin::pin!(h.token(&one));
    let mut second = std::pin::pin!(h.token(&two));
    assert!(futures::poll!(first.as_mut()).is_pending());
    assert!(futures::poll!(second.as_mut()).is_pending());
    drop(held);
    let t = first.await.unwrap();
    assert_eq!(
        second.await.unwrap_err().description,
        "The refresh token was replaced; its session is ended"
    );
    assert!(a.account(t["access_token"].as_str().unwrap()).is_none());
    // A refresh waiting on a session that ends meanwhile.
    let (access, refresh) = signed_in(&h, &f, &base, &id).await;
    let cell = cell_of(a, &access);
    let mut held = cell.lock().await;
    let grant = rotate(&refresh);
    let mut waiting = std::pin::pin!(h.token(&grant));
    assert!(futures::poll!(waiting.as_mut()).is_pending());
    a.end_locked(&mut held);
    drop(held);
    assert_eq!(
        waiting.await.unwrap_err().description,
        "The session is ended"
    );
    // A web session signed out while it ends otherwise: revoked at its
    // server by neither.
    let state = {
        h.web_sign_in(DID).await.unwrap();
        f.lock().unwrap().last_par.clone().unwrap()
    };
    let back = h
        .callback(&pairs(&[
            ("state", &state.0),
            ("iss", &base),
            ("code", &state.1),
        ]))
        .await
        .unwrap();
    let client::Callback::Web(cookie) = back else {
        panic!("not a web session: {back:?}");
    };
    let cell = cell_of(a, &cookie);
    let mut held = cell.lock().await;
    let mut out = std::pin::pin!(h.sign_out(&cookie));
    assert!(futures::poll!(out.as_mut()).is_pending());
    a.end_locked(&mut held);
    drop(held);
    out.await;
    assert_eq!(f.lock().unwrap().revocations, 0);
    // A session ended while another end waits for it is ended, and
    // logged, once.
    let (access, _) = signed_in(&h, &f, &base, &id).await;
    let sid = cell_of(a, &access).lock().await.id.clone();
    let logs = Logs::default();
    let ends = async {
        let cell = cell_of(a, &access);
        let mut held = cell.lock().await;
        let mut end = std::pin::pin!(a.end(&sid));
        assert!(futures::poll!(end.as_mut()).is_pending());
        a.end_locked(&mut held);
        drop(held);
        end.await;
    };
    tracing::instrument::WithSubscriber::with_subscriber(ends, logs.dispatch()).await;
    let ended = logs
        .lines()
        .into_iter()
        .filter(|l| l.starts_with("session ended"))
        .count();
    assert_eq!(ended, 1);
    assert!(a.account(&access).is_none());
}

#[tokio::test]
async fn client_documents_read_and_kept() {
    let h = hud("http://127.0.0.1:9");
    let a = h.auth().unwrap();
    let id = "https://client.example/meta.json";
    let doc = json!({ "client_id": id, "client_name": "Client",
        "redirect_uris": ["https://client.example/cb"], "token_endpoint_auth_method": "none" });
    let answer = |status: u16, kind: Option<&str>, body: Vec<u8>, redirected: bool| {
        let mut headers = reqwest::header::HeaderMap::new();
        if let Some(k) = kind {
            headers.insert(reqwest::header::CONTENT_TYPE, k.parse().unwrap());
        }
        Ok(crate::net::Fetched {
            status,
            headers,
            body,
            redirected,
        })
    };
    let json = Some("Application/JSON; charset=utf-8");
    let failed = crate::net::Failure {
        why: "it did not answer in time".into(),
        answered: false,
    };
    for (got, why) in [
        (
            Err(failed),
            "its metadata could not be read: it did not answer in time",
        ),
        (
            answer(404, json, Vec::new(), false),
            "its metadata could not be read (answered 404)",
        ),
        (
            answer(200, json, Vec::new(), true),
            "its metadata could not be read (answered 200, redirected)",
        ),
        (
            answer(200, Some("text/html"), doc.to_string().into_bytes(), false),
            "its metadata is not application/json",
        ),
        (
            answer(200, None, doc.to_string().into_bytes(), false),
            "its metadata is not application/json",
        ),
        (
            answer(200, json, b"{".to_vec(), false),
            "its metadata is not JSON",
        ),
        (
            answer(200, json, b"[]".to_vec(), false),
            "its metadata is not a JSON object",
        ),
    ] {
        assert_eq!(a.fetched_document(id, got).unwrap_err(), why);
    }
    // A document read is kept: asked again, it is not fetched.
    let c = a
        .fetched_document(id, answer(200, json, doc.to_string().into_bytes(), false))
        .unwrap();
    assert_eq!(c.name.as_deref(), Some("Client"));
    assert_eq!(h.mcp_client(id).await, Ok(c.clone()));
    // Kept 10,000 at most: full of live ones, no more is kept; those past
    // their time make room.
    let other = "https://other.example/meta.json";
    let other_doc = json!({ "client_id": other,
        "redirect_uris": ["https://other.example/cb"], "token_endpoint_auth_method": "none" });
    {
        let mut st = a.lock();
        for i in 0..PENDING_MAX {
            st.documents
                .insert(i.to_string(), (c.clone(), now() + 3600));
        }
    }
    let read = || answer(200, json, other_doc.to_string().into_bytes(), false);
    assert!(a.fetched_document(other, read()).is_ok());
    assert!(a.kept_document(other).is_none());
    for (_, until) in a.lock().documents.values_mut() {
        *until = 0;
    }
    assert!(a.fetched_document(other, read()).is_ok());
    assert!(a.kept_document(other).is_some());
    assert_eq!(a.lock().documents.len(), 1);
    // Fetched for real, through the client that refuses what is not
    // public: a host under .invalid is refused before any request.
    let mut public = config("http://127.0.0.1:9");
    public.allow_private = false;
    let public = Hud::new(public).unwrap();
    let why = public
        .mcp_client("https://client.invalid/meta.json")
        .await
        .unwrap_err();
    assert!(why.starts_with("its metadata could not be read: "), "{why}");
}

#[tokio::test]
async fn endpoints_with_sign_in_off() {
    let mut off = config("http://127.0.0.1:9");
    off.oauth = false;
    let h = Hud::new(off).unwrap();
    let off = issuer::Refused {
        status: 400,
        error: "invalid_request",
        description: "Sign-in is off on this server".into(),
    };
    assert_eq!(
        h.token(&pairs(&[("client_id", "c")])).await,
        Err(off.clone())
    );
    assert_eq!(h.revoke(&pairs(&[("token", "t")])).await, Err(off.clone()));
    assert_eq!(h.register(b"{}"), Err(off));
    // With it on, a registration that is not JSON.
    let on = hud("http://127.0.0.1:9");
    assert_eq!(
        on.register(b"<xml/>").unwrap_err().error,
        "invalid_client_metadata"
    );
    // A parameter given twice, to the token or revocation endpoint.
    let twice = pairs(&[("token", "a"), ("token", "b")]);
    let why = "Parameter token is given more than once";
    assert_eq!(on.token(&twice).await.unwrap_err().description, why);
    assert_eq!(on.revoke(&twice).await.unwrap_err().description, why);
    // A session whose server names no revocation endpoint ends at HUD
    // alone.
    let a = on.auth().unwrap();
    let token = a.signed_in_offline(DID, None, false);
    on.revoke(&pairs(&[("token", &token)])).await.unwrap();
    assert!(a.account(&token).is_none());
}

#[test]
fn auth_opened_from_what_is_kept() {
    let h = hud("http://127.0.0.1:9");
    let a = h.auth().unwrap();
    let data = a.dir.parent().unwrap().to_path_buf();
    // An account names its DID alone, never its session.
    let live = a.signed_in_offline(DID, Some("alice.test"), false);
    assert_eq!(
        format!("{:?}", a.account(&live).unwrap()),
        format!("Account({DID})")
    );
    client(&h);
    // A session past its time is deleted at start; files that are not a
    // session or a client are left as they are.
    let past = a.signed_in_offline(OTHER, None, false);
    let past_file = a.session_path(&cell_of(a, &past).try_lock().unwrap().id);
    let mut kept: Value = serde_json::from_slice(&std::fs::read(&past_file).unwrap()).unwrap();
    kept["mcp"]["accessExp"] = 0.into();
    std::fs::write(&past_file, kept.to_string()).unwrap();
    let junk_session = a.dir.join("sessions/junk.json");
    let junk_client = a.dir.join("clients/junk.json");
    std::fs::write(&junk_session, "{}").unwrap();
    std::fs::write(&junk_client, "[]").unwrap();
    let logs = Logs::default();
    let again = tracing::dispatcher::with_default(&logs.dispatch(), || {
        Auth::open(ORIGIN, "atproto", &data).unwrap()
    });
    assert_eq!(again.account(&live).unwrap().did, DID);
    assert!(again.account(&past).is_none());
    assert!(!past_file.exists());
    assert!(junk_session.exists() && junk_client.exists());
    assert!(
        logs.lines()
            .contains(&"sign-ins loaded sessions=1 clients=1".to_string()),
        "{:?}",
        logs.lines()
    );
    // Tokens past their time name no account.
    let cookie = a.signed_in_offline(DID, None, true);
    for k in a.lock().tokens.values_mut() {
        if let Kept::Access { exp, .. } | Kept::Web { exp, .. } = k {
            *exp = 0;
        }
    }
    assert!(a.account(&live).is_none() && a.web_account(&cookie).is_none());
    // A session that cannot be kept on disk goes on in memory.
    std::fs::remove_dir_all(a.dir.join("sessions")).unwrap();
    std::fs::write(a.dir.join("sessions"), "").unwrap();
    let unkept = a.signed_in_offline(DID, None, false);
    assert_eq!(a.account(&unkept).unwrap().did, DID);
    // A client that cannot be kept is not registered.
    std::fs::remove_dir_all(a.dir.join("clients")).unwrap();
    std::fs::write(a.dir.join("clients"), "").unwrap();
    let refused = h
        .register(
            json!({ "redirect_uris": [REDIRECT] })
                .to_string()
                .as_bytes(),
        )
        .unwrap_err();
    assert_eq!((refused.status, refused.error), (500, "server_error"));
}

#[test]
fn auth_refuses_a_key_it_cannot_use() {
    let dir = || std::env::temp_dir().join(format!("hud-oauth-{}", jose::random(6)));
    // A key that is not a P-256 private JWK.
    let data = dir();
    std::fs::create_dir_all(data.join("oauth")).unwrap();
    std::fs::write(data.join("oauth/client-key.json"), "{}").unwrap();
    let why = Auth::open(ORIGIN, "atproto", &data).err().unwrap();
    assert!(
        why.ends_with("client-key.json is not a P-256 private JWK"),
        "{why}"
    );
    // A key that cannot be read.
    let data = dir();
    std::fs::create_dir_all(data.join("oauth/client-key.json")).unwrap();
    let why = Auth::open(ORIGIN, "atproto", &data).err().unwrap();
    assert!(why.starts_with("reading "), "{why}");
    // A key that cannot be kept: its directory is a link to nowhere.
    #[cfg(unix)]
    {
        let data = dir();
        std::fs::create_dir_all(&data).unwrap();
        std::os::unix::fs::symlink(data.join("nowhere"), data.join("oauth")).unwrap();
        let why = Auth::open(ORIGIN, "atproto", &data).err().unwrap();
        assert!(why.starts_with("keeping "), "{why}");
    }
}

#[tokio::test]
async fn swept_and_reached() {
    let h = hud("http://127.0.0.1:9");
    let a = h.auth().unwrap();
    // Sweeping: what waited past its time goes, and sessions past theirs
    // end.
    let live = a.signed_in_offline(DID, None, false);
    let old = a.signed_in_offline(OTHER, None, false);
    let old_file = {
        let cell = cell_of(a, &old);
        let mut s = cell.lock().await;
        s.mcp.access_exp = 0;
        a.session_path(&s.id)
    };
    let fresh = a.keep_request(Asker::Web { created: now() }).unwrap();
    {
        let mut st = a.lock();
        st.requests.insert("old".into(), Asker::Web { created: 0 });
        st.flows.insert(
            "old".into(),
            Flow {
                asker: Asker::Web { created: 0 },
                verifier: String::new(),
                dpop: Keypair::generate(Curve::P256),
                server: client::Server {
                    issuer: String::new(),
                    par: String::new(),
                    authorization: String::new(),
                    token: String::new(),
                    revocation: None,
                },
                did: Some(DID.into()),
                nonce: None,
                asked: String::new(),
                created: 0,
            },
        );
        st.codes.insert(
            "old".into(),
            issuer::Code {
                client_id: String::new(),
                redirect_uri: String::new(),
                challenge: String::new(),
                session: session(DID),
                refresh: false,
                created: 0,
            },
        );
        st.spent.insert("old".into(), ("sid".into(), 0));
        let c = issuer::Client {
            id: "d".into(),
            name: None,
            redirect_uris: Vec::new(),
            refresh: false,
        };
        st.documents.insert("d".into(), (c, 0));
    }
    a.sweep().await;
    assert!(a.account(&live).is_some());
    assert!(a.account(&old).is_none() && !old_file.exists());
    {
        let st = a.lock();
        assert_eq!(st.requests.keys().collect::<Vec<_>>(), [&fresh]);
        assert!(st.flows.is_empty() && st.codes.is_empty());
        assert!(st.spent.is_empty() && st.documents.is_empty());
    }
    // Reaching an account: its newest live session whose scope fits, else
    // its newest; never one past its time.
    let at = |pds: &str, scope: &str, created: u64, exp: u64| {
        let token = a.signed_in_offline_at(DID, None, false, pds);
        let cell = cell_of(a, &token);
        let mut s = cell.try_lock().unwrap();
        s.scope = scope.into();
        s.created_at = created;
        s.mcp.access_exp = exp;
    };
    let soon = now() + 3600;
    at("https://fits.example", "atproto spaces", 9, soon);
    at("https://older.example", "atproto", 1, soon);
    at("https://older.example", "atproto", 1, soon);
    at("https://past.example", "atproto spaces", 20, 0);
    let r = a.reach(DID, |s| s.contains("spaces")).await.unwrap();
    assert_eq!(
        (r.pds.as_str(), r.scope.as_str()),
        ("https://fits.example", "atproto spaces")
    );
    assert!(a.reach("did:plc:nobody", |_| true).await.is_none());
}

#[tokio::test]
async fn every_session_of_an_account_ended_once() {
    let (h, f, base) = world().await;
    let id = client(&h);
    let a = h.auth().unwrap();
    let (first, _) = signed_in(&h, &f, &base, &id).await;
    let (second, _) = signed_in(&h, &f, &base, &id).await;
    // One ended otherwise while every one ends: counted once, by that.
    let cell = cell_of(a, &first);
    let mut held = cell.lock().await;
    let mut all = std::pin::pin!(h.sign_out_everywhere(DID));
    assert!(futures::poll!(all.as_mut()).is_pending());
    a.end_locked(&mut held);
    drop(held);
    assert_eq!(all.await, 1);
    assert!(a.account(&first).is_none() && a.account(&second).is_none());
}

#[tokio::test]
async fn create_one_signs_up_at_the_sign_up_pds() {
    let (h, f, base) = world().await;
    let a = h.auth().unwrap();
    // The workspace's "Create one": on to the sign-up PDS's server, asking
    // it to make an account, naming none.
    let to = h.web_sign_up().await.unwrap();
    assert!(to.starts_with(&format!("{base}/authorize?")), "{to}");
    let form = f.lock().unwrap().last_par_form.clone();
    assert_eq!(form["prompt"], "create");
    assert!(!form.contains_key("login_hint"));
    // The account made, whichever it is, is the one signed in, once its
    // PDS's authorization server is the one that answered.
    let port = Url::parse(&base).unwrap().port().unwrap();
    let doc = |host: &str| {
        json!({ "id": OTHER, "service": [{ "id": "#atproto_pds",
            "type": "AtprotoPersonalDataServer", "serviceEndpoint": format!("http://{host}:{port}") }] })
    };
    {
        let mut w = f.lock().unwrap();
        w.sub = Some(OTHER.into());
        w.docs.insert(OTHER.into(), doc("127.0.0.1"));
    }
    let (state, code) = f.lock().unwrap().last_par.clone().unwrap();
    let back = h
        .callback(&pairs(&[
            ("state", &state),
            ("iss", &base),
            ("code", &code),
        ]))
        .await
        .unwrap();
    let client::Callback::Web(cookie) = back else {
        panic!("not a web session: {back:?}");
    };
    assert_eq!(a.web_account(&cookie).unwrap().did, OTHER);
    // One whose PDS answers to another authorization server: refused.
    h.web_sign_up().await.unwrap();
    f.lock()
        .unwrap()
        .docs
        .insert(OTHER.into(), doc("localhost"));
    let (state, code) = f.lock().unwrap().last_par.clone().unwrap();
    assert_eq!(
        h.callback(&pairs(&[
            ("state", &state),
            ("iss", &base),
            ("code", &code),
        ]))
        .await
        .unwrap(),
        client::Callback::WebRefused(
            "Your account's server is not the one that signed you in".into()
        )
    );
    // HUD's own app asking for a new account goes straight on, and so does
    // a web client of an app drawing its own sign-in screen; any other
    // client's asking gets the page.
    let mut asked = authorize_params(&a.app_client_id(), &jose::random(32));
    for (k, v) in &mut asked {
        if k == "redirect_uri" {
            *v = super::APP_REDIRECT.into();
        }
    }
    let web = asked_by(&h, "https://next.grain.social/auth/callback");
    for mut asked in [asked, web] {
        asked.push(("prompt".into(), "create".into()));
        match h.begin_sign_in(&asked).await.unwrap() {
            Authorized::Server(to) => {
                assert!(to.starts_with(&format!("{base}/authorize?")), "{to}")
            }
            other => panic!("not on to the sign-up PDS's server: {other:?}"),
        }
        assert_eq!(f.lock().unwrap().last_par_form["prompt"], "create");
    }
    let mut other = asked_by(&h, "https://elsewhere.test/cb");
    other.push(("prompt".into(), "create".into()));
    match h.begin_sign_in(&other).await.unwrap() {
        Authorized::Page(p) => assert!(!p.straight),
        other => panic!("not the page: {other:?}"),
    }
    // The sign-in page's "Create one" for that request: on to the
    // sign-up PDS's server too.
    let pending = h
        .authorize(&authorize_params(&client(&h), &jose::random(32)))
        .await
        .unwrap();
    let to = h.sign_up(&pending.id).await.unwrap();
    assert!(to.starts_with(&format!("{base}/authorize?")), "{to}");
    assert_eq!(h.sign_up(&pending.id).await, Err(client::SignIn::Expired));
}

#[tokio::test]
async fn create_one_says_when_the_sign_up_pds_cannot_be_used() {
    let (h, _f, _base) = world_with(|c| c.sign_up_pds = "http://127.0.0.1:9".into()).await;
    assert_eq!(
        h.web_sign_up().await,
        Err("Accounts can't be made at 127.0.0.1 now; try again later".into())
    );
    assert!(h.auth().unwrap().lock().requests.is_empty());
    // An app's web client drawing its own sign-in screen is sent back,
    // saying so.
    let mut asked = asked_by(&h, "https://next.grain.social/auth/callback");
    asked.push(("prompt".into(), "create".into()));
    match h.begin_sign_in(&asked).await.unwrap_err() {
        NotAuthorized::Redirect(to) => {
            assert!(
                to.starts_with("https://next.grain.social/auth/callback?"),
                "{to}"
            );
            assert_eq!(
                query_of(&to)["error_description"],
                "Accounts can't be made at 127.0.0.1 now; try again later"
            );
        }
        other => panic!("not sent back saying why: {other:?}"),
    }
    assert!(h.auth().unwrap().lock().requests.is_empty());
    // Named by no URL, it is named as it is.
    let (h, _f, _base) = world_with(|c| c.sign_up_pds = "nowhere".into()).await;
    assert_eq!(
        h.web_sign_up().await,
        Err("Accounts can't be made at nowhere now; try again later".into())
    );
    // Its server refusing the request.
    let (h, f, _base) = world().await;
    f.lock().unwrap().par_answer = Some((
        StatusCode::BAD_REQUEST,
        json!({ "error": "invalid_request" }),
    ));
    assert_eq!(
        h.web_sign_up().await,
        Err("127.0.0.1 refused the sign-in: invalid_request".into())
    );
}