~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
1928 lines · 64.0 KB Raw History
//! The credentials, each rule and error of `spec/SPACES-CREDENTIALS.md`.

use super::*;
use crate::testing::*;
use axum::Router;
use axum::body::Bytes;
use axum::extract::{Path, State};
use axum::http::{HeaderName, HeaderValue, Method, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use base64::Engine;
use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD as B64};
use p256::ecdsa::signature::Signer;
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::Ordering;

/// A PLC directory as `testing::plc` serves one, taking any operation, whose
/// documents a test may replace, counting the reads of each.
#[derive(Clone, Default)]
pub(crate) struct Directory {
    ops: Arc<std::sync::Mutex<HashMap<String, Json>>>,
    docs: Arc<std::sync::Mutex<HashMap<String, Json>>>,
    reads: Arc<std::sync::Mutex<HashMap<String, usize>>>,
}

impl Directory {
    pub async fn start() -> (Directory, String) {
        async fn post(
            State(d): State<Directory>,
            Path(did): Path<String>,
            body: Bytes,
        ) -> StatusCode {
            let Ok(op) = serde_json::from_slice::<Json>(&body) else {
                return StatusCode::BAD_REQUEST;
            };
            d.ops.lock().unwrap().insert(did, op);
            StatusCode::OK
        }
        async fn get_doc(State(d): State<Directory>, Path(did): Path<String>) -> Response {
            *d.reads.lock().unwrap().entry(did.clone()).or_default() += 1;
            let doc = d.docs.lock().unwrap().get(&did).cloned().or_else(|| {
                d.ops
                    .lock()
                    .unwrap()
                    .get(&did)
                    .map(|op| did_document(&did, op))
            });
            match doc {
                Some(doc) => (
                    [(header::CONTENT_TYPE, "application/json")],
                    doc.to_string(),
                )
                    .into_response(),
                None => StatusCode::NOT_FOUND.into_response(),
            }
        }
        // Its current data, as `activateAccount` reads it.
        async fn get_data(State(d): State<Directory>, Path(did): Path<String>) -> Response {
            let Some(op) = d.ops.lock().unwrap().get(&did).cloned() else {
                return StatusCode::NOT_FOUND.into_response();
            };
            let data = json!({ "did": did, "verificationMethods": op["verificationMethods"], "rotationKeys": op["rotationKeys"], "alsoKnownAs": op["alsoKnownAs"], "services": op["services"] });
            (
                [(header::CONTENT_TYPE, "application/json")],
                data.to_string(),
            )
                .into_response()
        }
        let d = Directory::default();
        let app = Router::new()
            .route("/{did}", get(get_doc).post(post))
            .route("/{did}/data", get(get_data))
            .with_state(d.clone());
        let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0))
            .await
            .unwrap();
        let url = format!("http://{}", listener.local_addr().unwrap());
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        (d, url)
    }

    /// Serve `did`'s document with its `#atproto` key `key` in its place.
    fn rotate(&self, did: &str, key: &k256::ecdsa::SigningKey) {
        let mut op = self.ops.lock().unwrap()[did].clone();
        op["verificationMethods"]["atproto"] = json!(crate::plc::did_key(key.verifying_key()));
        self.docs
            .lock()
            .unwrap()
            .insert(did.to_string(), did_document(did, &op));
    }

    /// Serve the document of `did`, no account's, with `key` its `#atproto` key.
    fn serve(&self, did: &str, key: &k256::ecdsa::SigningKey) {
        let op = json!({ "verificationMethods": { "atproto": crate::plc::did_key(key.verifying_key()) }, "alsoKnownAs": [], "services": {} });
        self.docs
            .lock()
            .unwrap()
            .insert(did.to_string(), did_document(did, &op));
    }

    /// How many times `did`'s document was read.
    fn reads(&self, did: &str) -> usize {
        self.reads.lock().unwrap().get(did).copied().unwrap_or(0)
    }
}

/// A JWT of these parts, its signature `sign` makes of the bytes signed.
pub(crate) fn jwt_of(header: &Json, payload: &Json, sign: impl FnOnce(&[u8]) -> Vec<u8>) -> String {
    let signed = format!(
        "{}.{}",
        B64.encode(header.to_string()),
        B64.encode(payload.to_string())
    );
    let sig = sign(signed.as_bytes());
    format!("{signed}.{}", B64.encode(sig))
}

/// A signer with the key of account `did`.
pub(crate) fn account_key(s: &Service, did: &str) -> impl FnOnce(&[u8]) -> Vec<u8> {
    let a = s.account(did).unwrap();
    move |m: &[u8]| read(&a.store).repo.sign(m).to_vec()
}

fn k256_key(key: &k256::ecdsa::SigningKey) -> impl FnOnce(&[u8]) -> Vec<u8> + '_ {
    move |m: &[u8]| {
        let sig: k256::ecdsa::Signature = key.sign(m);
        sig.normalize_s().to_bytes().to_vec()
    }
}

/// The same signature with `s` in the upper half.
pub(crate) fn high_s(sig: Vec<u8>) -> Vec<u8> {
    let (r, s) = k256::ecdsa::Signature::from_slice(&sig)
        .unwrap()
        .split_scalars();
    k256::ecdsa::Signature::from_scalars(k256::FieldBytes::from(r), k256::FieldBytes::from(-s))
        .unwrap()
        .to_bytes()
        .to_vec()
}

/// A service-auth token of `iss`'s, signed with its key.
pub(crate) fn service_auth_token(s: &Service, iss: &str, aud: &str) -> String {
    let payload = json!({ "iss": iss, "aud": aud, "lxm": NOTIFY, "exp": s.sessions.now() + 60, "iat": s.sessions.now() });
    jwt_of(
        &json!({ "alg": "ES256K", "typ": "JWT" }),
        &payload,
        account_key(s, iss),
    )
}

fn now(s: &Service) -> u64 {
    s.sessions.now()
}

/// A P-256 key a client binds credentials to.
pub(crate) struct Client {
    key: p256::ecdsa::SigningKey,
    pub kid: String,
}

pub(crate) fn client(seed: u8) -> Client {
    let key = p256::ecdsa::SigningKey::from_slice(&[seed; 32]).unwrap();
    let mut bytes = vec![0x80, 0x24];
    bytes.extend_from_slice(key.verifying_key().to_sec1_point(true).as_bytes());
    Client {
        key,
        kid: format!("did:key:z{}", bs58::encode(bytes).into_string()),
    }
}

const PARAMS: &str = r#"("authorization" "atproto-space-audience");tag="atproto-space-credential""#;

fn headers_of(pairs: &[(&str, &str)]) -> HeaderMap {
    let mut h = HeaderMap::new();
    for (k, v) in pairs {
        h.append(
            HeaderName::from_bytes(k.as_bytes()).unwrap(),
            HeaderValue::from_str(v).unwrap(),
        );
    }
    h
}

/// A request presenting `credential`, signed by `c` for `audience`.
pub(crate) fn signed(c: &Client, credential: &str, audience: &str) -> HeaderMap {
    signed_with(
        c,
        &format!("Atproto-Space-Credential {credential}"),
        audience,
        PARAMS,
    )
}

fn signed_with(c: &Client, authorization: &str, audience: &str, params: &str) -> HeaderMap {
    let base = pds_space::signature::signature_base(authorization, audience, params);
    let sig: p256::ecdsa::Signature = c.key.sign(base.as_bytes());
    headers_of(&[
        ("authorization", authorization),
        ("atproto-space-audience", audience),
        (
            "signature-input",
            &format!("atproto-space-credential={params}"),
        ),
        (
            "signature",
            &format!(
                "atproto-space-credential=:{}:",
                STANDARD.encode(sig.to_bytes())
            ),
        ),
    ])
}

/// A call as sent over HTTP; an error as its status and name.
async fn http(
    s: &Shared,
    method: Method,
    nsid: &str,
    params: &[(&str, &str)],
    headers: &HeaderMap,
    body: &str,
) -> Result<Json, String> {
    let authorization = crate::authorization(headers);
    let bearer = crate::sessions::Bearer::of(authorization.as_deref());
    let params: Vec<(String, String)> = params
        .iter()
        .map(|(k, v)| (k.to_string(), v.to_string()))
        .collect();
    let call = Call {
        nsid,
        method: &method,
        params: &params,
        body: body.as_bytes(),
        bearer,
        headers,
        client: "127.0.0.1".into(),
        charged: Default::default(),
        http: None,
    };
    match crate::answer(s, &call).await {
        Ok(Resp::Json(j)) => Ok(j),
        Ok(Resp::Nothing) => Ok(Json::Null),
        Ok(_) => Err("not JSON".into()),
        Err(e) => Err(format!("{} {}", e.status, e.name)),
    }
}

pub(crate) async fn delegation_token(
    s: &Shared,
    token: &str,
    space: &str,
) -> Result<String, String> {
    let got = http(
        s,
        Method::GET,
        "com.atproto.space.getDelegationToken",
        &[("space", space)],
        &headers_of(&[("authorization", &format!("Bearer {token}"))]),
        "",
    )
    .await?;
    Ok(got["token"].as_str().unwrap().to_string())
}

/// A credential from `authorizeSpaceSync` with this body.
pub(crate) async fn credential(s: &Shared, body: Json) -> Result<String, String> {
    authorized(s, body)
        .await
        .map(|got| got["credential"].as_str().unwrap().to_string())
}

/// `authorizeSpaceSync`'s answer to this body.
pub(crate) async fn authorized(s: &Shared, body: Json) -> Result<Json, String> {
    http(
        s,
        Method::POST,
        AUTHORIZE,
        &[],
        &HeaderMap::new(),
        &body.to_string(),
    )
    .await
}

const AUTHORIZE: &str = "com.atproto.space.authorizeSpaceSync";

async fn verify(
    s: &Shared,
    headers: &HeaderMap,
    audience: &str,
) -> Result<SpaceCredential, String> {
    let method = Method::GET;
    let call = Call {
        nsid: "com.atproto.space.listWriters",
        method: &method,
        params: &[],
        body: b"",
        bearer: crate::sessions::Bearer::None,
        headers,
        client: "127.0.0.1".into(),
        charged: Default::default(),
        http: None,
    };
    verify_space_credential(s, &call, audience)
        .await
        .map_err(|e| format!("{} {}", e.status, e.name))
}

/// A plain TCP listener on `127.0.0.1` that takes each connection, counts
/// it and closes it: its port, and the count.
pub(crate) async fn counting() -> (u16, Arc<std::sync::atomic::AtomicUsize>) {
    let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0))
        .await
        .unwrap();
    let port = listener.local_addr().unwrap().port();
    let n = Arc::new(std::sync::atomic::AtomicUsize::new(0));
    let counted = n.clone();
    tokio::spawn(async move {
        while let Ok((socket, _)) = listener.accept().await {
            counted.fetch_add(1, Ordering::SeqCst);
            drop(socket);
        }
    });
    (port, n)
}

pub(crate) async fn revoke(
    s: &Shared,
    authorization: Option<&str>,
    body: Json,
) -> Result<Json, String> {
    let headers =
        authorization.map_or_else(HeaderMap::new, |a| headers_of(&[("authorization", a)]));
    http(s, Method::POST, NOTIFY, &[], &headers, &body.to_string()).await
}

fn parts(token: &str) -> (Json, Json, Vec<u8>) {
    let p: Vec<&str> = token.split('.').collect();
    let json = |s: &str| serde_json::from_slice(&B64.decode(s).unwrap()).unwrap();
    (json(p[0]), json(p[1]), B64.decode(p[2]).unwrap())
}

/// The claims' names, in order.
fn names(payload: &Json) -> Vec<&str> {
    let mut n: Vec<&str> = payload
        .as_object()
        .unwrap()
        .keys()
        .map(String::as_str)
        .collect();
    n.sort();
    n
}

/// Whether `token` is signed, low-S, by `did`'s key as the directory serves it.
async fn signed_by(s: &Shared, did: &str, token: &str) -> bool {
    let jwt = Jwt::parse(token).unwrap();
    issuers::verify_issuer(s, did, &jwt, false).await.is_ok()
}

struct World {
    s: Shared,
    directory: Directory,
    plc: String,
    dir: std::path::PathBuf,
    alice: (String, String),
    bob: (String, String),
    /// Alice's space.
    space: String,
}

async fn world(name: &str) -> World {
    world_with(name, |_| {}).await
}

async fn world_with(name: &str, change: impl FnOnce(&mut crate::Config)) -> World {
    let (directory, plc) = Directory::start().await;
    let dir = scratch(name);
    let s = open_with(&dir, &plc, change);
    let alice = create(&s, "alice").await;
    let bob = create(&s, "bob").await;
    let space = format!("at://{}/space/com.example.forum/main", alice.0);
    // Alice's personalspace: she alone reads it.
    let policy = json!({ "$type": "com.atproto.personalspace.policy" });
    call(
        &s,
        "com.atproto.space.createSpace",
        Some(&alice.1),
        json!({ "spaceType": "com.example.forum", "skey": "main", "policy": policy }),
    )
    .await
    .unwrap();
    World {
        s,
        directory,
        plc,
        dir,
        alice,
        bob,
        space,
    }
}

#[tokio::test]
async fn delegation_tokens_are_minted_for_full_sessions() {
    let w = world("cred-delegation").await;
    let s = &w.s;
    let token = delegation_token(s, &w.bob.1, &w.space).await.unwrap();
    let (header, payload, sig) = parts(&token);
    assert_eq!(
        header,
        json!({ "alg": "ES256K", "typ": DELEGATION_TYP, "kid": "#atproto" })
    );
    assert_eq!(names(&payload), ["aud", "exp", "iat", "iss", "jti", "sub"]);
    assert_eq!(
        (&payload["iss"], &payload["sub"]),
        (&json!(w.bob.0), &json!(w.space))
    );
    assert_eq!(payload["aud"], json!(format!("{}#atproto_pds", w.alice.0)));
    assert_eq!(
        payload["exp"].as_u64().unwrap() - payload["iat"].as_u64().unwrap(),
        60
    );
    let jti = payload["jti"].as_str().unwrap();
    assert!(
        jti.len() == 32
            && jti
                .bytes()
                .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)),
        "{jti}"
    );
    assert_eq!(sig.len(), 64);
    assert!(signed_by(s, &w.bob.0, &token).await);
    assert_ne!(
        parts(&delegation_token(s, &w.bob.1, &w.space).await.unwrap()).1["jti"],
        payload["jti"]
    );
    // Any space is answered, its authority here or not.
    delegation_token(s, &w.bob.1, "at://did:plc:nowhere/space/com.example.x/k")
        .await
        .unwrap();

    // The space first, whatever the token.
    let get = |space: Option<&str>, authorization: Option<String>| {
        let headers =
            authorization.map_or_else(HeaderMap::new, |a| headers_of(&[("authorization", &a)]));
        let params: Vec<(&str, &str)> = space.map(|sp| vec![("space", sp)]).unwrap_or_default();
        let params: Vec<(String, String)> = params
            .into_iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect();
        async move {
            let p: Vec<(&str, &str)> = params
                .iter()
                .map(|(k, v)| (k.as_str(), v.as_str()))
                .collect();
            http(
                s,
                Method::GET,
                "com.atproto.space.getDelegationToken",
                &p,
                &headers,
                "",
            )
            .await
            .map(|_| ())
        }
    };
    let bearer = |t: &str| Some(format!("Bearer {t}"));
    for space in [
        None,
        Some("at://did:plc:x/space/forum/k"),
        Some(&*format!("at://{}/app.bsky.feed.post/k", w.alice.0)),
    ] {
        assert_eq!(
            get(space, None).await,
            Err("400 InvalidRequest".into()),
            "{space:?}"
        );
        assert_eq!(
            get(space, bearer("nonsense")).await,
            Err("400 InvalidRequest".into()),
            "{space:?}"
        );
    }
    let sp = Some(w.space.as_str());
    assert_eq!(get(sp, None).await, Err("401 AuthMissing".into()));
    assert_eq!(
        get(sp, bearer("nonsense")).await,
        Err("400 InvalidToken".into())
    );
    assert_eq!(
        get(
            sp,
            Some(format!("Basic {}", STANDARD.encode("bob.test:bob-pw")))
        )
        .await,
        Err("400 InvalidToken".into())
    );
    assert_eq!(
        get(sp, Some("Atproto-Space-Credential a.b.c".into())).await,
        Err("400 InvalidToken".into())
    );
    assert_eq!(get(sp, Some(format!("bearer {}", w.bob.1))).await, Ok(()));
    let login = |pw: &str| json!({ "identifier": "bob.test", "password": pw });
    let sess = call(s, "com.atproto.server.createSession", None, login("bob-pw"))
        .await
        .unwrap();
    assert_eq!(
        get(sp, bearer(sess["refreshJwt"].as_str().unwrap())).await,
        Err("400 InvalidToken".into())
    );
    for privileged in [false, true] {
        let app = call(
            s,
            "com.atproto.server.createAppPassword",
            Some(&w.bob.1),
            json!({ "name": format!("p{privileged}"), "privileged": privileged }),
        )
        .await
        .unwrap();
        let sess = call(
            s,
            "com.atproto.server.createSession",
            None,
            login(app["password"].as_str().unwrap()),
        )
        .await
        .unwrap();
        assert_eq!(
            get(sp, bearer(sess["accessJwt"].as_str().unwrap())).await,
            Err("400 InvalidToken".into()),
            "{privileged}"
        );
    }
    let post = http(
        s,
        Method::POST,
        "com.atproto.space.getDelegationToken",
        &[("space", &w.space)],
        &headers_of(&[("authorization", &format!("Bearer {}", w.bob.1))]),
        "",
    )
    .await;
    assert_eq!(post, Err("400 InvalidRequest".into()));
    s.sessions.skew.store(3 * 60 * 60, Ordering::SeqCst);
    assert_eq!(
        get(sp, bearer(&w.bob.1)).await,
        Err("400 ExpiredToken".into())
    );
    let _ = std::fs::remove_dir_all(&w.dir);
}

#[tokio::test]
async fn credentials_are_issued_and_verified() {
    let w = world("cred-issue").await;
    let s = &w.s;
    let c = client(1);
    let token = delegation_token(s, &w.alice.1, &w.space).await.unwrap();
    let got = authorized(
        s,
        json!({ "space": w.space, "credentialKey": c.kid, "delegationToken": token }),
    )
    .await
    .unwrap();
    // No `spaceRev` while the space's writer set is empty.
    assert_eq!(
        got.as_object().unwrap().keys().collect::<Vec<_>>(),
        ["credential"]
    );
    let cred = got["credential"].as_str().unwrap().to_string();
    let (header, payload, sig) = parts(&cred);
    assert_eq!(
        header,
        json!({ "alg": "ES256K", "typ": CREDENTIAL_TYP, "kid": "#atproto" })
    );
    assert_eq!(names(&payload), ["cnf", "exp", "iat", "iss", "jti", "sub"]);
    assert_eq!(
        (&payload["iss"], &payload["sub"], &payload["cnf"]),
        (&json!(w.alice.0), &json!(w.space), &json!({ "kid": c.kid }))
    );
    assert_eq!(
        payload["exp"].as_u64().unwrap() - payload["iat"].as_u64().unwrap(),
        600
    );
    assert_eq!(sig.len(), 64);
    assert!(signed_by(s, &w.alice.0, &cred).await);
    // It works at any host, for any audience, as many times as it is sent.
    let want = SpaceCredential {
        space: w.space.clone(),
        jti: payload["jti"].as_str().unwrap().into(),
        kid: c.kid.clone(),
    };
    for audience in [&w.bob.0, &w.alice.0, &"did:plc:elsewhere".to_string()] {
        assert_eq!(
            verify(s, &signed(&c, &cred, audience), audience).await,
            Ok(want.clone())
        );
        assert_eq!(
            verify(s, &signed(&c, &cred, audience), audience).await,
            Ok(want.clone())
        );
    }
    // The scheme in any case, kept in the signature base as sent.
    let auth = format!("atproto-space-credential {cred}");
    assert_eq!(
        verify(s, &signed_with(&c, &auth, &w.bob.0, PARAMS), &w.bob.0).await,
        Ok(want.clone())
    );
    assert!(presents_credential(&signed_with(
        &c, &auth, &w.bob.0, PARAMS
    )));
    assert!(!presents_credential(&headers_of(&[(
        "authorization",
        "Bearer x"
    )])));
    // An Authorization header of another form.
    for (h, e) in [
        (None, "401 AuthMissing"),
        (Some("Atproto-Space-Credential"), "400 InvalidToken"),
        (Some("Atproto-Space-Credential  x"), "400 InvalidToken"),
        (Some("Bearer x"), "400 InvalidToken"),
    ] {
        let headers = h.map_or_else(HeaderMap::new, |h| headers_of(&[("authorization", h)]));
        assert_eq!(verify(s, &headers, &w.bob.0).await, Err(e.into()), "{h:?}");
    }
    let _ = std::fs::remove_dir_all(&w.dir);
}

/// `body` with `extra`'s members added.
fn merged(mut body: Json, extra: &Json) -> Json {
    for (k, v) in extra.as_object().unwrap() {
        body[k] = v.clone();
    }
    body
}

/// Create a space of the account `token` is a session of, under `policy`.
async fn make_space(s: &Shared, token: &str, skey: &str, policy: Json) -> String {
    let body = json!({ "spaceType": "com.example.forum", "skey": skey, "policy": policy });
    call(s, "com.atproto.space.createSpace", Some(token), body)
        .await
        .unwrap()["space"]
        .as_str()
        .unwrap()
        .to_string()
}

/// Each refusal of `authorizeSpaceSync`, in the order the spec gives them,
/// each before the next (`spec/SPACES-CREDENTIALS.md`, "authorizeSpaceSync").
#[tokio::test]
async fn credential_requests_are_refused_in_order() {
    let w = world("cred-refused").await;
    let s = &w.s;
    let kid = client(1).kid;
    let ask = |body: Json| credential(s, body);
    let elsewhere = "at://did:plc:nowhere/space/com.example.forum/main";
    let notify = json!({ "endpoint": "https://syncer.example", "token": "t" });
    // 1. The lexicon, `notify` too, the HTTP method and the body.
    let with_notify = |n: Json| json!({ "space": w.space, "credentialKey": kid, "notify": n });
    for body in [
        json!({ "credentialKey": kid }),
        json!({ "space": w.space }),
        json!({ "space": "at://did:plc:x/space/forum/k", "credentialKey": kid }),
        json!({ "space": w.space, "credentialKey": 1 }),
        json!({ "space": w.space, "credentialKey": kid, "delegationToken": 1 }),
        json!({ "space": w.space, "credentialKey": kid, "clientAttestation": false }),
        with_notify(json!("https://syncer.example")),
        with_notify(json!({ "endpoint": "https://syncer.example" })),
        with_notify(json!({ "token": "t" })),
        with_notify(json!({ "endpoint": "not a uri", "token": "t" })),
        with_notify(json!({ "endpoint": "https://syncer.example", "token": "x".repeat(513) })),
        with_notify(json!({ "endpoint": "https://syncer.example", "token": 7 })),
    ] {
        assert_eq!(
            ask(body.clone()).await,
            Err("400 InvalidRequest".into()),
            "{body}"
        );
    }
    // A token of 512 bytes, or none, and other members, pass it.
    for n in [
        json!({ "endpoint": "https://syncer.example", "token": "x".repeat(512) }),
        json!({ "endpoint": "https://syncer.example", "token": "" }),
        json!({ "endpoint": "https://syncer.example", "token": "t", "other": 1 }),
    ] {
        assert_eq!(ask(with_notify(n)).await, Err("400 SpaceNotFound".into()));
    }
    assert_eq!(
        http(s, Method::POST, AUTHORIZE, &[], &HeaderMap::new(), "x").await,
        Err("400 InvalidRequest".into())
    );
    let get = http(
        s,
        Method::GET,
        AUTHORIZE,
        &[("space", &w.space), ("credentialKey", &kid)],
        &HeaderMap::new(),
        "",
    )
    .await;
    assert_eq!(get, Err("400 InvalidRequest".into()));
    // 2. A credentialKey that is no P-256 key, before the authority.
    let signing = crate::plc::did_key(
        crate::read(&s.account(&w.alice.0).unwrap().store)
            .repo
            .verifying_key(),
    );
    for bad in [
        signing.as_str(),
        "did:key:zDnaefoo",
        "nonsense",
        "",
        "did:plc:abc",
    ] {
        for space in [w.space.as_str(), elsewhere] {
            assert_eq!(
                ask(json!({ "space": space, "credentialKey": bad, "delegationToken": "x" })).await,
                Err("400 InvalidRequest".into()),
                "{bad}"
            );
        }
    }
    // 3. The authority an account here, before the token, the attestation
    // and `notify`, none of which is read.
    let elsewhere_token = delegation_token(s, &w.bob.1, elsewhere).await.unwrap();
    let base = |space: &str| json!({ "space": space, "credentialKey": kid });
    for extra in [
        json!({}),
        json!({ "delegationToken": "x.y.z" }),
        json!({ "clientAttestation": "x" }),
        json!({ "delegationToken": elsewhere_token }),
        json!({ "notify": notify }),
    ] {
        assert_eq!(
            ask(merged(base(elsewhere), &extra)).await,
            Err("400 SpaceNotFound".into()),
            "{extra}"
        );
    }
    // 4. A space deleted, before the token: one presented for it is not
    // spent, and is taken once the space is created again.
    let personal = json!({ "$type": "com.atproto.personalspace.policy" });
    let gone = make_space(s, &w.alice.1, "gone", personal.clone()).await;
    call(
        s,
        "com.atproto.space.deleteSpace",
        Some(&w.alice.1),
        json!({ "space": gone }),
    )
    .await
    .unwrap();
    let for_gone = delegation_token(s, &w.alice.1, &gone).await.unwrap();
    for extra in [
        json!({}),
        json!({ "delegationToken": "x.y.z" }),
        json!({ "clientAttestation": "x" }),
        json!({ "delegationToken": for_gone }),
        json!({ "notify": notify }),
    ] {
        assert_eq!(
            ask(merged(base(&gone), &extra)).await,
            Err("400 SpaceDeleted".into()),
            "{extra}"
        );
    }
    make_space(s, &w.alice.1, "gone", personal).await;
    ask(merged(base(&gone), &json!({ "delegationToken": for_gone })))
        .await
        .unwrap();
    // 5. The token, before the attestation; 6. the attestation, before
    // whether the space was created. An empty one, of either, is as none.
    let never = format!("at://{}/space/com.example.forum/never", w.alice.0);
    assert_eq!(
        ask(merged(
            base(&never),
            &json!({ "delegationToken": "x.y.z", "clientAttestation": "x" })
        ))
        .await,
        Err("400 InvalidDelegationToken".into())
    );
    for bad in ["x", "a.b.c", "https://app.example/client.json"] {
        for space in [&w.space, &never] {
            assert_eq!(
                ask(merged(base(space), &json!({ "clientAttestation": bad }))).await,
                Err("400 InvalidClientAttestation".into()),
                "{bad}"
            );
        }
    }
    assert_eq!(
        ask(merged(
            base(&w.space),
            &json!({ "clientAttestation": "", "delegationToken": "" })
        ))
        .await,
        Err("400 SpaceNotFound".into())
    );
    // 7. A space never created; a token verified is spent all the same.
    let for_never = delegation_token(s, &w.alice.1, &never).await.unwrap();
    assert_eq!(
        ask(merged(
            base(&never),
            &json!({ "delegationToken": for_never })
        ))
        .await,
        Err("400 SpaceNotFound".into())
    );
    assert_eq!(
        ask(merged(
            base(&never),
            &json!({ "delegationToken": for_never })
        ))
        .await,
        Err("400 InvalidDelegationToken".into())
    );
    assert_eq!(ask(base(&never)).await, Err("400 SpaceNotFound".into()));
    // 8. The user perimeter: no token, or a user the space refuses.
    assert_eq!(ask(base(&w.space)).await, Err("400 SpaceNotFound".into()));
    let bobs = delegation_token(s, &w.bob.1, &w.space).await.unwrap();
    assert_eq!(
        ask(merged(base(&w.space), &json!({ "delegationToken": bobs }))).await,
        Err("400 SpaceNotFound".into())
    );
    // A token refused there was spent all the same.
    assert_eq!(
        ask(merged(base(&w.space), &json!({ "delegationToken": bobs }))).await,
        Err("400 InvalidDelegationToken".into())
    );
    // Replays, and a token for another space, which is spent too.
    let alices = delegation_token(s, &w.alice.1, &w.space).await.unwrap();
    let with_alices = |space: &str, t: &str| merged(base(space), &json!({ "delegationToken": t }));
    ask(with_alices(&w.space, &alices)).await.unwrap();
    assert_eq!(
        ask(with_alices(&w.space, &alices)).await,
        Err("400 InvalidDelegationToken".into())
    );
    let other = format!("at://{}/space/com.example.forum/other", w.alice.0);
    let alices = delegation_token(s, &w.alice.1, &w.space).await.unwrap();
    assert_eq!(
        ask(with_alices(&other, &alices)).await,
        Err("400 InvalidDelegationToken".into())
    );
    assert_eq!(
        ask(with_alices(&w.space, &alices)).await,
        Err("400 InvalidDelegationToken".into())
    );
    // No Authorization is read.
    let headers = headers_of(&[("authorization", "Bearer nonsense")]);
    let alices = delegation_token(s, &w.alice.1, &w.space).await.unwrap();
    let body = with_alices(&w.space, &alices).to_string();
    http(s, Method::POST, AUTHORIZE, &[], &headers, &body)
        .await
        .unwrap();
    let _ = std::fs::remove_dir_all(&w.dir);
}

#[tokio::test]
async fn delegation_tokens_each_with_one_thing_wrong() {
    let w = world("cred-delegation-wrong").await;
    let s = &w.s;
    let kid = client(1).kid;
    let alice = w.alice.0.clone();
    let n = now(s);
    let header = json!({ "alg": "ES256K", "typ": DELEGATION_TYP, "kid": "#atproto" });
    let payload = |jti: &str| json!({ "iss": alice, "sub": w.space, "aud": format!("{alice}#atproto_pds"), "iat": n, "exp": n + 60, "jti": jti });
    let trade = |token: String| {
        credential(
            s,
            json!({ "space": w.space, "credentialKey": kid, "delegationToken": token }),
        )
    };
    let mut count = 0;
    let mut fresh = || {
        count += 1;
        format!("j{count}")
    };
    // Each refused.
    let header_with = |k: &str, v: Json| {
        let mut h = header.clone();
        h[k] = v;
        h
    };
    let mut wrong: Vec<(String, String)> = Vec::new();
    for h in [
        header_with("typ", json!("JWT")),
        header_with("typ", Json::Null),
        header_with("alg", json!("")),
        header_with("alg", json!(1)),
        header_with("kid", json!("#atproto_kem")),
        header_with("kid", Json::Null),
        header_with("alg", json!("ES256")),
    ] {
        wrong.push((
            format!("header {h}"),
            jwt_of(&h, &payload(&fresh()), account_key(s, &alice)),
        ));
    }
    for (k, v) in [
        ("iss", Json::Null),
        ("sub", Json::Null),
        ("aud", Json::Null),
        ("exp", json!("soon")),
        ("exp", Json::Null),
        ("exp", json!(n - 5)),
        ("exp", json!(n - 100)),
        // More than an hour ahead.
        ("exp", json!(n + 3700)),
        ("exp", json!(n + 86400)),
        ("jti", json!("")),
        ("jti", json!(7)),
        ("jti", Json::Null),
        ("iss", json!("alice.test")),
        ("iss", json!("did:plc:unknown")),
        ("iss", json!(w.bob.0)),
        ("sub", json!(format!("at://{alice}/com.example.forum/main"))),
        ("aud", json!(alice)),
        ("aud", json!(format!("{}#atproto_pds", w.bob.0))),
        ("aud", json!(format!("{alice}#atproto_labeler"))),
    ] {
        let mut p = payload(&fresh());
        p[k] = v;
        wrong.push((
            format!("payload {p}"),
            jwt_of(&header, &p, account_key(s, &alice)),
        ));
    }
    let good = jwt_of(&header, &payload(&fresh()), account_key(s, &alice));
    let other_key = k256::ecdsa::SigningKey::from_slice(&[42u8; 32]).unwrap();
    wrong.push((
        "another key".into(),
        jwt_of(&header, &payload(&fresh()), k256_key(&other_key)),
    ));
    wrong.push((
        "high-S".into(),
        jwt_of(&header, &payload(&fresh()), |m| {
            high_s(account_key(s, &alice)(m))
        }),
    ));
    let dots: Vec<&str> = good.split('.').collect();
    for (what, t) in [
        ("two parts", format!("{}.{}", dots[0], dots[1])),
        ("four parts", format!("{good}.x")),
        ("a header not base64", format!("!.{}.{}", dots[1], dots[2])),
        (
            "a header not an object",
            format!("{}.{}.{}", B64.encode("[1]"), dots[1], dots[2]),
        ),
        (
            "a signature not base64",
            format!("{}.{}.!!", dots[0], dots[1]),
        ),
        (
            "a padded payload",
            format!("{}.{}=.{}", dots[0], dots[1], dots[2]),
        ),
    ] {
        wrong.push((what.into(), t));
    }
    for (what, t) in wrong {
        assert_eq!(
            trade(t).await,
            Err("400 InvalidDelegationToken".into()),
            "{what}"
        );
    }
    trade(good).await.unwrap();
    // Each taken, though unusual: no iat, an hour's life, an extra claim, `exp` 2 seconds past.
    for (k, v) in [
        ("iat", Json::Null),
        ("exp", json!(n + 3600)),
        ("lxm", json!("com.example.x")),
        ("exp", json!(n - 2)),
        ("iat", json!("then")),
    ] {
        let mut p = payload(&fresh());
        if v.is_null() {
            p.as_object_mut().unwrap().remove(k);
        } else {
            p[k] = v;
        }
        assert!(
            trade(jwt_of(&header, &p, account_key(s, &alice)))
                .await
                .is_ok(),
            "{p}"
        );
    }
    // A `jti` another account used.
    let mut p = payload("shared");
    trade(jwt_of(&header, &p, account_key(s, &alice)))
        .await
        .unwrap();
    p["iss"] = json!(w.bob.0);
    assert_eq!(
        trade(jwt_of(&header, &p, account_key(s, &w.bob.0))).await,
        Err("400 SpaceNotFound".into())
    );
    let _ = std::fs::remove_dir_all(&w.dir);
}

#[tokio::test]
async fn credentials_are_verified_row_by_row() {
    let w = world("cred-rows").await;
    let s = &w.s;
    let c = client(1);
    let alice = w.alice.0.clone();
    let audience = w.bob.0.clone();
    let n = now(s);
    let header = json!({ "alg": "ES256K", "typ": CREDENTIAL_TYP, "kid": "#atproto" });
    let payload = json!({ "iss": alice, "sub": w.space, "cnf": { "kid": c.kid }, "iat": n, "exp": n + 600, "jti": "j" });
    let with = |base: &Json, k: &str, v: Json| {
        let mut p = base.clone();
        if v.is_null() {
            p.as_object_mut().unwrap().remove(k);
        } else {
            p[k] = v;
        }
        p
    };
    let check = |token: String| {
        let h = signed(&c, &token, &audience);
        let audience = audience.clone();
        async move { verify(s, &h, &audience).await.map(|_| ()) }
    };
    let good = jwt_of(&header, &payload, account_key(s, &alice));
    assert_eq!(check(good.clone()).await, Ok(()));
    let dots: Vec<&str> = good.split('.').collect();
    let other_key = k256::ecdsa::SigningKey::from_slice(&[42u8; 32]).unwrap();
    let mut rows: Vec<(String, String, &str)> = vec![
        (
            "two parts".into(),
            format!("{}.{}", dots[0], dots[1]),
            "BadJwt",
        ),
        (
            "a payload not an object".into(),
            format!("{}.{}.{}", dots[0], B64.encode("1"), dots[2]),
            "BadJwt",
        ),
        (
            "a signature not base64".into(),
            format!("{}.{}.*", dots[0], dots[1]),
            "BadJwt",
        ),
    ];
    for (k, v, e) in [
        ("typ", json!("at+jwt"), "BadJwtType"),
        ("typ", Json::Null, "BadJwtType"),
        ("alg", json!(""), "BadJwt"),
        ("kid", json!("#other"), "BadJwt"),
        ("alg", json!("ES256"), "BadJwtSignature"),
    ] {
        let h = with(&header, k, v);
        rows.push((
            format!("header {h}"),
            jwt_of(&h, &payload, account_key(s, &alice)),
            e,
        ));
    }
    for (p, e) in [
        (with(&payload, "iss", Json::Null), "BadJwtIss"),
        (with(&payload, "sub", Json::Null), "BadJwtSub"),
        (with(&payload, "exp", json!("later")), "BadJwt"),
        (with(&payload, "cnf", Json::Null), "BadJwtCnf"),
        (with(&payload, "cnf", json!({ "kid": "zDn" })), "BadJwtCnf"),
        (with(&payload, "jti", json!("")), "BadJwt"),
        (with(&payload, "iat", Json::Null), "BadJwt"),
        (with(&payload, "iat", json!(n + 600)), "BadJwt"),
        (
            with(&with(&payload, "iat", json!(n)), "exp", json!(n + 3601)),
            "BadJwt",
        ),
        (
            with(&with(&payload, "iat", json!(n + 6)), "exp", json!(n + 600)),
            "BadJwt",
        ),
        (
            with(&with(&payload, "iat", json!(n - 600)), "exp", json!(n - 5)),
            "JwtExpired",
        ),
        (with(&payload, "iss", json!("alice.test")), "BadJwt"),
        (
            with(
                &with(&payload, "iss", json!("did:plc:unknown")),
                "sub",
                json!("at://did:plc:unknown/space/com.example.forum/main"),
            ),
            "BadJwtIss",
        ),
        (
            with(&payload, "sub", json!("at://did:plc:x/space/forum/main")),
            "BadJwtSub",
        ),
        (
            with(
                &payload,
                "cnf",
                json!({ "kid": crate::plc::did_key(other_key.verifying_key()) }),
            ),
            "BadSpaceSignature",
        ),
        (
            with(&payload, "cnf", json!({ "kid": client(2).kid })),
            "BadSpaceSignature",
        ),
    ] {
        rows.push((
            format!("payload {p}"),
            jwt_of(&header, &p, account_key(s, &alice)),
            e,
        ));
    }
    // Taken: an exp less than an hour after iat, iat up to 5 seconds ahead, exp up to 5 seconds past, an `aud`.
    for p in [
        with(&with(&payload, "iat", json!(n)), "exp", json!(n + 3600)),
        with(&with(&payload, "iat", json!(n + 5)), "exp", json!(n + 600)),
        with(&with(&payload, "iat", json!(n - 600)), "exp", json!(n - 4)),
        with(&payload, "aud", json!("did:plc:whoever")),
    ] {
        assert_eq!(
            check(jwt_of(&header, &p, account_key(s, &alice))).await,
            Ok(()),
            "{p}"
        );
    }
    rows.push((
        "another key".into(),
        jwt_of(&header, &payload, k256_key(&other_key)),
        "BadJwtSignature",
    ));
    rows.push((
        "high-S".into(),
        jwt_of(&header, &payload, |m| high_s(account_key(s, &alice)(m))),
        "BadJwtSignature",
    ));
    let bobs = with(&payload, "iss", json!(w.bob.0));
    rows.push((
        "another's space".into(),
        jwt_of(&header, &bobs, account_key(s, &w.bob.0)),
        "BadJwtIss",
    ));
    // In order: the first that fails answers.
    let expired_and_unsigned = with(&with(&payload, "iat", json!(n - 600)), "exp", json!(n - 10));
    rows.push((
        "expired, by another key".into(),
        jwt_of(&header, &expired_and_unsigned, k256_key(&other_key)),
        "JwtExpired",
    ));
    let typ_and_iss = with(&header, "typ", json!("JWT"));
    rows.push((
        "wrong typ, no iss".into(),
        jwt_of(
            &typ_and_iss,
            &with(&payload, "iss", Json::Null),
            account_key(s, &alice),
        ),
        "BadJwtType",
    ));
    for (what, token, e) in rows {
        assert_eq!(check(token).await, Err(format!("401 {e}")), "{what}");
    }

    // 17–18: the HTTP Message Signature, each with one thing wrong.
    let auth = format!("Atproto-Space-Credential {good}");
    let ok = signed(&c, &good, &audience);
    let swap = |name: &str, value: Option<&str>| {
        let mut h = ok.clone();
        h.remove(name);
        if let Some(v) = value {
            h.insert(
                HeaderName::from_bytes(name.as_bytes()).unwrap(),
                HeaderValue::from_str(v).unwrap(),
            );
        }
        h
    };
    let sig_of = |h: &HeaderMap| h["signature"].to_str().unwrap().to_string();
    let other_sig = sig_of(&signed(&client(2), &good, &audience));
    let other_audience = sig_of(&signed(&c, &good, &alice));
    let keyid_params = format!("{PARAMS};keyid=\"{}\"", client(2).kid);
    for (what, h) in [
        ("no audience", swap("atproto-space-audience", None)),
        (
            "an audience not a DID",
            signed_with(&c, &auth, "bob.test", PARAMS),
        ),
        ("no Signature", swap("signature", None)),
        ("no Signature-Input", swap("signature-input", None)),
        (
            "another key's signature",
            swap("signature", Some(&other_sig)),
        ),
        (
            "signed for another audience",
            swap("signature", Some(&other_audience)),
        ),
        (
            "no tag",
            signed_with(
                &c,
                &auth,
                &audience,
                r#"("authorization" "atproto-space-audience")"#,
            ),
        ),
        (
            "components reversed",
            signed_with(
                &c,
                &auth,
                &audience,
                r#"("atproto-space-audience" "authorization");tag="atproto-space-credential""#,
            ),
        ),
        (
            "another alg",
            signed_with(&c, &auth, &audience, &format!("{PARAMS};alg=\"ed25519\"")),
        ),
        (
            "another keyid",
            signed_with(&c, &auth, &audience, &keyid_params),
        ),
        (
            "a DER signature",
            swap("signature", Some("atproto-space-credential=:MEUCIQ==:")),
        ),
    ] {
        assert_eq!(
            verify(s, &h, &audience).await,
            Err("401 BadSpaceSignature".into()),
            "{what}"
        );
    }
    assert_eq!(
        verify(
            s,
            &signed_with(
                &c,
                &auth,
                &audience,
                &format!("{PARAMS};alg=\"ecdsa-p256-sha256\";keyid=\"{}\"", c.kid)
            ),
            &audience
        )
        .await
        .map(|_| ()),
        Ok(())
    );
    // 20: signed for one audience, refused at another.
    assert_eq!(
        verify(s, &ok, &alice).await,
        Err("401 BadSpaceAudience".into())
    );
    // 19: revoked here, before the audience; another space's `jti` is not.
    s.space_credentials
        .revoke(&s.log, &w.space, &["j"], now(s))
        .unwrap();
    assert_eq!(
        verify(s, &ok, &audience).await,
        Err("401 CredentialRevoked".into())
    );
    assert_eq!(
        verify(s, &ok, &alice).await,
        Err("401 CredentialRevoked".into())
    );
    let other_space = format!("at://{alice}/space/com.example.forum/other");
    let other = jwt_of(
        &header,
        &with(&payload, "sub", json!(other_space)),
        account_key(s, &alice),
    );
    assert_eq!(
        verify(s, &signed(&c, &other, &audience), &audience)
            .await
            .map(|v| v.space),
        Ok(other_space)
    );
    let _ = std::fs::remove_dir_all(&w.dir);
}

/// An issuer no account here is, its document served with `key`, and a
/// space of it.
fn elsewhere(w: &World, key: &k256::ecdsa::SigningKey) -> (&'static str, String) {
    let did = "did:plc:zzzzzzzzzzzzzzzzzzzzzzzz";
    w.directory.serve(did, key);
    (did, format!("at://{did}/space/com.example.forum/main"))
}

#[tokio::test]
async fn a_rotated_key_is_read_again() {
    // Issuers' keys kept, as they are with `PDS_DID_CACHE_SECS` above 0.
    let w = world_with("cred-rotated", |c| c.did_cache = 3600).await;
    let s = &w.s;
    let c = client(1);
    let first = k256::ecdsa::SigningKey::from_slice(&[42u8; 32]).unwrap();
    let (iss, space) = elsewhere(&w, &first);
    let header = json!({ "alg": "ES256K", "typ": CREDENTIAL_TYP, "kid": "#atproto" });
    let n = now(s);
    let payload = json!({ "iss": iss, "sub": space, "cnf": { "kid": c.kid }, "iat": n, "exp": n + 600, "jti": "j" });
    let bob = w.bob.0.as_str();
    let check = |token: &str| {
        let h = signed(&c, token, bob);
        async move { verify(s, &h, bob).await }
    };
    let old = jwt_of(&header, &payload, k256_key(&first));
    check(&old).await.unwrap();
    assert_eq!(w.directory.reads(iss), 1);
    let rotated = k256::ecdsa::SigningKey::from_slice(&[43u8; 32]).unwrap();
    w.directory.serve(iss, &rotated);
    // The key kept still verifies what it signed, with nothing read, until
    // a token signed with another is sent.
    check(&old).await.unwrap();
    assert_eq!(w.directory.reads(iss), 1);
    let new = jwt_of(&header, &payload, k256_key(&rotated));
    check(&new).await.unwrap();
    assert_eq!(w.directory.reads(iss), 2);
    assert_eq!(check(&old).await, Err("401 BadJwtSignature".into()));
    // Service auth, too, with a high-S signature.
    let p = json!({ "iss": iss, "aud": w.bob.0, "lxm": NOTIFY, "exp": n + 60 });
    let t = jwt_of(&json!({ "alg": "ES256K" }), &p, |m| {
        high_s(k256_key(&rotated)(m))
    });
    assert_eq!(
        revoke(
            s,
            Some(&format!("Bearer {t}")),
            json!({ "space": space, "credentials": ["x"] })
        )
        .await,
        Ok(Json::Null)
    );
    let _ = std::fs::remove_dir_all(&w.dir);
}

#[tokio::test]
async fn an_account_here_is_held_to_its_own_key_first() {
    let w = world("cred-held").await;
    let s = &w.s;
    let c = client(1);
    let alice = w.alice.0.clone();
    let rotated = k256::ecdsa::SigningKey::from_slice(&[43u8; 32]).unwrap();
    w.directory.rotate(&alice, &rotated);
    let header = json!({ "alg": "ES256K", "typ": CREDENTIAL_TYP, "kid": "#atproto" });
    let n = now(s);
    let payload = json!({ "iss": alice, "sub": w.space, "cnf": { "kid": c.kid }, "iat": n, "exp": n + 600, "jti": "j" });
    let bob = w.bob.0.as_str();
    let check = |token: &str| {
        let h = signed(&c, token, bob);
        async move { verify(s, &h, bob).await }
    };
    let before = w.directory.reads(&alice);
    // Signed with the key the server holds: nothing read, whatever her
    // document says, though no key is kept (`PDS_DID_CACHE_SECS=0`).
    for _ in 0..3 {
        check(&jwt_of(&header, &payload, account_key(s, &alice)))
            .await
            .unwrap();
    }
    assert_eq!(w.directory.reads(&alice), before);
    // Signed with another, it is held to her document as any issuer's is.
    check(&jwt_of(&header, &payload, k256_key(&rotated)))
        .await
        .unwrap();
    assert_eq!(w.directory.reads(&alice), before + 1);
    let other = k256::ecdsa::SigningKey::from_slice(&[44u8; 32]).unwrap();
    assert_eq!(
        check(&jwt_of(&header, &payload, k256_key(&other))).await,
        Err("401 BadJwtSignature".into())
    );
    let _ = std::fs::remove_dir_all(&w.dir);
}

#[tokio::test]
async fn a_key_past_its_time_is_used_while_it_is_read_again() {
    let w = world_with("cred-renewed", |c| {
        c.did_cache = 10;
        c.did_cache_max = 100;
    })
    .await;
    let s = &w.s;
    let key = k256::ecdsa::SigningKey::from_slice(&[42u8; 32]).unwrap();
    let (iss, space) = elsewhere(&w, &key);
    let n = now(s);
    let p = json!({ "iss": iss, "aud": w.bob.0, "lxm": NOTIFY, "exp": n + 600 });
    let t = jwt_of(&json!({ "alg": "ES256K" }), &p, k256_key(&key));
    let send = || {
        let body = json!({ "space": space, "credentials": ["x"] });
        let auth = format!("Bearer {t}");
        async move { revoke(s, Some(&auth), body).await }
    };
    let skew = |secs| s.limits.clock.skew.store(secs, Ordering::SeqCst);
    send().await.unwrap();
    send().await.unwrap();
    assert_eq!(w.directory.reads(iss), 1);
    // Past `PDS_DID_CACHE_SECS`: answered with the key kept, read again after.
    skew(20);
    send().await.unwrap();
    for _ in 0..200 {
        if w.directory.reads(iss) == 2 {
            break;
        }
        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
    }
    assert_eq!(w.directory.reads(iss), 2);
    send().await.unwrap();
    assert_eq!(w.directory.reads(iss), 2);
    // Past `PDS_DID_CACHE_MAX_SECS` since that read: read first.
    skew(200);
    send().await.unwrap();
    assert_eq!(w.directory.reads(iss), 3);
    let _ = std::fs::remove_dir_all(&w.dir);
}

#[tokio::test]
async fn revocations_take_service_auth() {
    let w = world("cred-revoke").await;
    let s = &w.s;
    let alice = w.alice.0.clone();
    let n = now(s);
    let body = json!({ "space": w.space, "credentials": ["j1", "j2"] });
    let payload = json!({ "iss": alice, "aud": w.bob.0, "lxm": NOTIFY, "exp": n + 60, "iat": n });
    let header = json!({ "alg": "ES256K", "typ": "JWT" });
    let bearer = |h: &Json, p: &Json| format!("Bearer {}", jwt_of(h, p, account_key(s, &alice)));
    let with = |base: &Json, k: &str, v: Json| {
        let mut p = base.clone();
        if v.is_null() {
            p.as_object_mut().unwrap().remove(k);
        } else {
            p[k] = v;
        }
        p
    };
    let other_key = k256::ecdsa::SigningKey::from_slice(&[42u8; 32]).unwrap();
    let mut rows: Vec<(String, Option<String>, &str)> = vec![
        ("none".into(), None, "401 MissingJwt"),
        (
            "an empty header".into(),
            Some(String::new()),
            "401 MissingJwt",
        ),
        (
            "Basic".into(),
            Some(format!("Basic {}", STANDARD.encode("a:b"))),
            "401 MissingJwt",
        ),
        ("DPoP".into(), Some("DPoP x".into()), "401 MissingJwt"),
        (
            "a credential".into(),
            Some("atproto-space-credential x".into()),
            "401 MissingJwt",
        ),
        (
            "another scheme".into(),
            Some("Token x".into()),
            "400 InvalidToken",
        ),
        ("one word".into(), Some("Bearer".into()), "400 InvalidToken"),
        (
            "three words".into(),
            Some("Bearer a b".into()),
            "400 InvalidToken",
        ),
        ("two parts".into(), Some("Bearer a.b".into()), "401 BadJwt"),
        (
            "no alg".into(),
            Some(bearer(&json!({ "typ": "JWT" }), &payload)),
            "401 BadJwt",
        ),
        (
            "no exp".into(),
            Some(bearer(&header, &with(&payload, "exp", Json::Null))),
            "401 BadJwt",
        ),
        (
            "an access token's typ".into(),
            Some(bearer(&with(&header, "typ", json!("at+jwt")), &payload)),
            "401 BadJwtType",
        ),
        (
            "a refresh token's typ".into(),
            Some(bearer(
                &with(&header, "typ", json!("refresh+jwt")),
                &payload,
            )),
            "401 BadJwtType",
        ),
        (
            "a DPoP proof's typ".into(),
            Some(bearer(&with(&header, "typ", json!("dpop+jwt")), &payload)),
            "401 BadJwtType",
        ),
        (
            "expired".into(),
            Some(bearer(&header, &with(&payload, "exp", json!(n - 1)))),
            "401 JwtExpired",
        ),
        (
            "no lxm".into(),
            Some(bearer(&header, &with(&payload, "lxm", Json::Null))),
            "401 BadJwtLexiconMethod",
        ),
        (
            "another lxm".into(),
            Some(bearer(
                &header,
                &with(
                    &payload,
                    "lxm",
                    json!("com.atproto.space.authorizeSpaceSync"),
                ),
            )),
            "401 BadJwtLexiconMethod",
        ),
        (
            "an iss with a fragment, not the authority".into(),
            Some(bearer(
                &header,
                &with(&payload, "iss", json!(format!("{alice}#atproto_pds"))),
            )),
            "403 Forbidden",
        ),
        (
            "no iss".into(),
            Some(bearer(&header, &with(&payload, "iss", Json::Null))),
            "401 BadJwtIss",
        ),
        (
            "an unknown iss".into(),
            Some(bearer(
                &header,
                &with(&payload, "iss", json!("did:plc:unknown")),
            )),
            "401 AuthenticationRequired",
        ),
        (
            "another key".into(),
            Some(format!(
                "Bearer {}",
                jwt_of(&header, &payload, k256_key(&other_key))
            )),
            "401 BadJwtSignature",
        ),
        (
            "ES256".into(),
            Some(bearer(&with(&header, "alg", json!("ES256")), &payload)),
            "401 BadJwtSignature",
        ),
    ];
    // Then the input, then who may.
    let ok = bearer(&header, &payload);
    for b in [
        json!({ "space": w.space }),
        json!({ "space": w.space, "credentials": [] }),
        json!({ "space": w.space, "credentials": [""] }),
        json!({ "space": "x", "credentials": ["j"] }),
    ] {
        assert_eq!(
            revoke(s, Some(&ok), b.clone()).await,
            Err("400 InvalidRequest".into()),
            "{b}"
        );
    }
    let many: Vec<String> = (0..101).map(|i| format!("j{i}")).collect();
    assert_eq!(
        revoke(
            s,
            Some(&ok),
            json!({ "space": w.space, "credentials": many })
        )
        .await,
        Err("400 InvalidRequest".into())
    );
    assert_eq!(
        revoke(s, Some("Bearer a.b"), json!({})).await,
        Err("401 BadJwt".into()),
        "the token before the input"
    );
    let bobs = format!("at://{}/space/com.example.forum/main", w.bob.0);
    rows.push((
        "another authority's space".into(),
        Some(ok.clone()),
        "403 Forbidden",
    ));
    for aud in [
        json!(format!("{}#atproto_pds", w.bob.0)),
        json!("did:web:localhost"),
        json!("did:plc:elsewhere"),
        Json::Null,
        json!(5),
    ] {
        rows.push((
            format!("aud {aud}"),
            Some(bearer(&header, &with(&payload, "aud", aud))),
            "403 Forbidden",
        ));
    }
    for (what, authorization, e) in rows {
        let b = if what == "another authority's space" {
            json!({ "space": bobs, "credentials": ["j1"] })
        } else {
            body.clone()
        };
        assert_eq!(
            revoke(s, authorization.as_deref(), b).await,
            Err(e.into()),
            "{what}"
        );
    }
    assert!(!s.space_credentials.is_revoked(&w.space, "j1", n));
    // Taken: no typ, any other typ, the authority's own account as aud, and again.
    for h in [
        json!({ "alg": "ES256K" }),
        json!({ "alg": "ES256K", "typ": "x" }),
    ] {
        assert_eq!(
            revoke(s, Some(&bearer(&h, &payload)), body.clone()).await,
            Ok(Json::Null)
        );
    }
    assert_eq!(
        revoke(
            s,
            Some(&bearer(&header, &with(&payload, "aud", json!(alice)))),
            body.clone()
        )
        .await,
        Ok(Json::Null)
    );
    assert!(
        s.space_credentials.is_revoked(&w.space, "j1", n)
            && s.space_credentials.is_revoked(&w.space, "j2", n)
    );
    assert!(!s.space_credentials.is_revoked(
        &format!("at://{alice}/space/com.example.forum/other"),
        "j1",
        n
    ));
    // Kept 3610 seconds after it was last received.
    assert!(
        s.space_credentials
            .is_revoked(&w.space, "j1", now(s) + 3609)
    );
    assert!(
        !s.space_credentials
            .is_revoked(&w.space, "j1", now(s) + 3611)
    );
    s.sessions.skew.store(1000, Ordering::SeqCst);
    let again = bearer(&header, &with(&payload, "exp", json!(now(s) + 60)));
    assert_eq!(
        revoke(
            s,
            Some(&again),
            json!({ "space": w.space, "credentials": ["j1"] })
        )
        .await,
        Ok(Json::Null)
    );
    assert!(
        s.space_credentials
            .is_revoked(&w.space, "j1", n + 1000 + 3609)
    );
    assert!(
        !s.space_credentials
            .is_revoked(&w.space, "j2", n + 1000 + 3609)
    );
    let _ = std::fs::remove_dir_all(&w.dir);
}

/// A revocation answered, and a delegation token spent, are kept across a restart.
#[tokio::test]
async fn revocations_and_spent_tokens_survive_a_restart() {
    let w = world("cred-restart").await;
    let c = client(1);
    let token = delegation_token(&w.s, &w.alice.1, &w.space).await.unwrap();
    let ask = json!({ "space": w.space, "credentialKey": c.kid, "delegationToken": token });
    let cred = credential(&w.s, ask.clone()).await.unwrap();
    let jti = parts(&cred).1["jti"].as_str().unwrap().to_string();
    let auth = format!("Bearer {}", service_auth_token(&w.s, &w.alice.0, &w.bob.0));
    revoke(
        &w.s,
        Some(&auth),
        json!({ "space": w.space, "credentials": [jti] }),
    )
    .await
    .unwrap();
    let before = (
        w.s.single_use.snapshot(0),
        w.s.space_credentials.snapshot(0),
    );
    drop(w.s);
    let s = open(&w.dir, &w.plc);
    assert_eq!(
        (s.single_use.snapshot(0), s.space_credentials.snapshot(0)),
        before
    );
    assert_eq!(
        credential(&s, ask).await,
        Err("400 InvalidDelegationToken".into())
    );
    assert_eq!(
        verify(&s, &signed(&c, &cred, &w.bob.0), &w.bob.0).await,
        Err("401 CredentialRevoked".into())
    );
    // Past its time, a revocation is forgotten on replay.
    drop(s);
    let s = open(&w.dir, &w.plc);
    s.sessions.skew.store(0, Ordering::SeqCst);
    let later = s.sessions.now() + REVOCATION_KEPT + 1;
    assert!(s.space_credentials.snapshot(later).is_empty());
    let _ = std::fs::remove_dir_all(&w.dir);
}

/// Take an account down, or lift that, as the admin does.
pub(crate) async fn take_down(s: &Shared, did: &str, on: bool) {
    let admin = format!(
        "Basic {}",
        STANDARD.encode(format!("admin:{ADMIN_PASSWORD}"))
    );
    let mut takedown = json!({ "applied": on });
    if on {
        takedown["ref"] = json!("r1");
    }
    let body = json!({ "subject": { "$type": "com.atproto.admin.defs#repoRef", "did": did }, "takedown": takedown });
    call_raw(
        s,
        "com.atproto.admin.updateSubjectStatus",
        crate::sessions::Bearer::of(Some(&admin)),
        &[],
        &body.to_string(),
    )
    .await
    .unwrap();
}

/// Deactivate an account with its token, or activate it again.
pub(crate) async fn deactivate(s: &Shared, token: &str, on: bool) {
    let (nsid, body) = if on {
        ("com.atproto.server.deactivateAccount", json!({}))
    } else {
        ("com.atproto.server.activateAccount", Json::Null)
    };
    call(s, nsid, Some(token), body).await.unwrap();
}

/// `getDelegationToken` of a deactivated or taken-down account, with a
/// token made before: refused after its space and its token are checked.
#[tokio::test]
async fn delegation_tokens_are_refused_to_an_account_not_active() {
    let w = world("cred-delegation-state").await;
    let s = &w.s;
    let (bob, t) = (&w.bob.0, &w.bob.1);
    let sess = call(
        s,
        "com.atproto.server.createSession",
        None,
        json!({ "identifier": "bob.test", "password": "bob-pw" }),
    )
    .await
    .unwrap();
    let refresh = sess["refreshJwt"].as_str().unwrap().to_string();
    let app = call(
        s,
        "com.atproto.server.createAppPassword",
        Some(t),
        json!({ "name": "app" }),
    )
    .await
    .unwrap();
    let app_sess = call(
        s,
        "com.atproto.server.createSession",
        None,
        json!({ "identifier": "bob.test", "password": app["password"] }),
    )
    .await
    .unwrap();
    let app_token = app_sess["accessJwt"].as_str().unwrap().to_string();
    let earlier = |state: &str| {
        let state = state.to_string();
        let (refresh, app_token, space) = (refresh.clone(), app_token.clone(), w.space.clone());
        async move {
            let space = space.as_str();
            // Its space first, then its token, then the account's state.
            assert_eq!(
                delegation_token(s, t, "at://did:plc:x/space/forum/k").await,
                Err("400 InvalidRequest".into()),
                "{state}"
            );
            assert_eq!(
                delegation_token(s, "nonsense", space).await,
                Err("400 InvalidToken".into()),
                "{state}"
            );
            assert_eq!(
                delegation_token(s, &refresh, space).await,
                Err("400 InvalidToken".into()),
                "{state}"
            );
            assert_eq!(
                delegation_token(s, &app_token, space).await,
                Err("400 InvalidToken".into()),
                "{state}"
            );
            assert_eq!(
                delegation_token(s, t, space).await,
                Err(state.clone()),
                "{state}"
            );
            assert_eq!(
                delegation_token(s, t, "at://did:plc:nowhere/space/com.example.x/k").await,
                Err(state.clone()),
                "{state}"
            );
        }
    };
    deactivate(s, t, true).await;
    earlier("401 AccountDeactivated").await;
    take_down(s, bob, true).await;
    earlier("401 AccountTakedown").await;
    take_down(s, bob, false).await;
    earlier("401 AccountDeactivated").await;
    deactivate(s, t, false).await;
    take_down(s, bob, true).await;
    earlier("401 AccountTakedown").await;
    // A taken-down account's own session is refused with its token.
    let down = json!({ "identifier": "bob.test", "password": "bob-pw", "allowTakendown": true });
    let down = call(s, "com.atproto.server.createSession", None, down)
        .await
        .unwrap();
    assert_eq!(
        delegation_token(s, down["accessJwt"].as_str().unwrap(), &w.space).await,
        Err("400 InvalidToken".into())
    );
    take_down(s, bob, false).await;
    delegation_token(s, t, &w.space).await.unwrap();
    let _ = std::fs::remove_dir_all(&w.dir);
}

/// `authorizeSpaceSync` of a space whose authority is deactivated or taken
/// down: refused at step 3, after the input and the key, whatever the
/// space, the token, the attestation and `notify`, none of which is read:
/// a token presented then is not spent.
#[tokio::test]
async fn credentials_are_refused_for_an_authority_not_active() {
    let w = world("cred-authority-state").await;
    let s = &w.s;
    let (alice, t) = (&w.alice.0, &w.alice.1);
    let kid = client(1).kid;
    let ask = |body: Json| credential(s, body);
    // Tokens made while every account is active: the authority's and another user's.
    let alices = delegation_token(s, t, &w.space).await.unwrap();
    let bobs = delegation_token(s, &w.bob.1, &w.space).await.unwrap();
    let base = |space: &str| json!({ "space": space, "credentialKey": kid });
    let refused = |state: &'static str| {
        let (alices, bobs, space) = (alices.clone(), bobs.clone(), w.space.clone());
        async move {
            let space = space.as_str();
            // 2. A credentialKey that is no key, first.
            assert_eq!(
                ask(json!({ "space": space, "credentialKey": "nonsense", "delegationToken": alices })).await,
                Err("400 InvalidRequest".into())
            );
            // 3. The authority's state, before all else.
            let other = format!("at://{alice}/space/com.example.forum/none");
            assert_eq!(ask(base(&other)).await, Err(state.into()));
            for extra in [
                json!({}),
                json!({ "delegationToken": "x.y.z" }),
                json!({ "clientAttestation": "x" }),
                json!({ "delegationToken": alices }),
                json!({ "delegationToken": bobs, "clientAttestation": "x" }),
                json!({ "notify": { "endpoint": "https://syncer.example", "token": "t" } }),
            ] {
                assert_eq!(
                    ask(merged(base(space), &extra)).await,
                    Err(state.into()),
                    "{extra}"
                );
            }
        }
    };
    deactivate(s, t, true).await;
    refused("400 RepoDeactivated").await;
    take_down(s, alice, true).await;
    refused("400 RepoTakendown").await;
    take_down(s, alice, false).await;
    refused("400 RepoDeactivated").await;
    deactivate(s, t, false).await;
    // Neither token was spent.
    ask(merged(
        base(&w.space),
        &json!({ "delegationToken": alices }),
    ))
    .await
    .unwrap();
    assert_eq!(
        ask(merged(base(&w.space), &json!({ "delegationToken": bobs }))).await,
        Err("400 SpaceNotFound".into())
    );
    let _ = std::fs::remove_dir_all(&w.dir);
}

#[test]
fn the_methods_are_tools() {
    // Hints by what each does (`spec/COMMANDS.md`, "Hints"): the delegation
    // token is signed, the credential only added, and a revocation ends one.
    for (nsid, tool, destroys) in [
        (
            "com.atproto.space.getDelegationToken",
            "space_get_delegation_token",
            false,
        ),
        (AUTHORIZE, "space_authorize_space_sync", false),
        (NOTIFY, "space_notify_credentials_revoked", true),
    ] {
        let m = pds_lexicon::method(nsid).unwrap();
        assert_eq!(m.tool().as_deref(), Some(tool));
        assert_eq!(
            m.annotations(),
            Some(json!({ "readOnlyHint": false, "destructiveHint": destroys })),
            "{nsid}"
        );
        assert!(handler(nsid).is_some());
    }
}