~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
2140 lines · 67.9 KB Raw History
//! The lifecycle's methods, each state's answers to every method, the
//! admin, takedowns of records and blobs, deletion, and a restart.

use super::*;
use crate::email::testing::{last_token, open_with_sink, sent};
use crate::testing::*;
use std::path::PathBuf;

const DEACTIVATE: &str = "com.atproto.server.deactivateAccount";
const ACTIVATE: &str = "com.atproto.server.activateAccount";
const CHECK: &str = "com.atproto.server.checkAccountStatus";
const REQUEST_DELETE: &str = "com.atproto.server.requestAccountDelete";
const DELETE: &str = "com.atproto.server.deleteAccount";
const UPDATE: &str = "com.atproto.admin.updateSubjectStatus";
const GET: &str = "com.atproto.admin.getSubjectStatus";
const LOGIN: &str = "com.atproto.server.createSession";
const GET_SESSION: &str = "com.atproto.server.getSession";
const REFRESH: &str = "com.atproto.server.refreshSession";

struct Env {
    plc: String,
    dir: PathBuf,
    sink: PathBuf,
    s: Shared,
}

impl Env {
    async fn new(name: &str) -> Env {
        let plc = plc().await;
        let dir = scratch(name);
        let sink = scratch(&format!("{name}-mail"));
        let s = open_with_sink(&dir, &plc, &sink);
        Env { plc, dir, sink, s }
    }

    fn reopen(&mut self) {
        self.s = open_with_sink(&self.dir, &self.plc, &self.sink);
    }

    async fn call(&self, nsid: &str, token: Option<&str>, body: Json) -> Result<Json, String> {
        call(&self.s, nsid, token, body).await
    }

    /// A query, its future owning what it is given.
    fn query(
        &self,
        nsid: &str,
        token: Option<&str>,
        p: &[(&str, &str)],
    ) -> impl Future<Output = Result<Json, String>> + use<> {
        let (s, nsid, token) = (self.s.clone(), nsid.to_string(), token.map(str::to_string));
        let p: Vec<(String, String)> = p
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect();
        async move { call_with(&s, &nsid, token.as_deref(), &p, Json::Null).await }
    }

    /// A call with this `Authorization` header.
    async fn raw(
        &self,
        nsid: &str,
        header: &str,
        p: &[(&str, &str)],
        body: &str,
    ) -> Result<Json, String> {
        let p: Vec<(String, String)> = p
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect();
        call_raw(&self.s, nsid, Bearer::of(Some(header)), &p, body).await
    }

    async fn admin(&self, nsid: &str, body: Json) -> Result<Json, String> {
        self.raw(nsid, &admin_header(), &[], &body.to_string())
            .await
    }

    async fn admin_query(&self, p: &[(&str, &str)]) -> Result<Json, String> {
        self.raw(GET, &admin_header(), p, "").await
    }

    async fn takedown(&self, did: &str, on: bool) -> Result<Json, String> {
        let mut body =
            json!({ "subject": { "$type": REPO_REF, "did": did }, "takedown": { "applied": on } });
        if on {
            body["takedown"]["ref"] = json!("r1");
        }
        self.admin(UPDATE, body).await
    }

    /// Every event a subscription begun now replays: `$t` beside its body's fields.
    fn events(&self) -> Vec<Json> {
        self.s
            .events
            .get(&self.s, 0, u64::MAX - 1, self.s.events.drops())
            .iter()
            .map(|f| decoded(f))
            .collect()
    }
}

impl Drop for Env {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.dir);
        let _ = std::fs::remove_dir_all(&self.sink);
    }
}

fn decoded(f: &[u8]) -> Json {
    let (head, at) = pds_repo::data::decode_prefix(f).unwrap();
    let mut body = pds_repo::data::to_json(&pds_repo::data::decode(&f[at..]).unwrap());
    body["$t"] = pds_repo::data::to_json(&head)["t"].clone();
    body
}

fn admin_header() -> String {
    format!(
        "Basic {}",
        base64::engine::general_purpose::STANDARD.encode(format!("admin:{ADMIN_PASSWORD}"))
    )
}

/// What an event says, briefly: its type, account, and `active`, `status` or handle.
fn brief(e: &Json) -> String {
    let did = e["did"].as_str().or(e["repo"].as_str()).unwrap_or_default();
    match e["$t"].as_str().unwrap() {
        "#account" => format!(
            "account {did} {} {}",
            e["active"],
            e["status"].as_str().unwrap_or("-")
        ),
        "#identity" => format!("identity {did} {}", e["handle"].as_str().unwrap()),
        t => format!("{} {did}", &t[1..]),
    }
}

fn tokens(got: &Json) -> (String, String) {
    (
        got["accessJwt"].as_str().unwrap().to_string(),
        got["refreshJwt"].as_str().unwrap().to_string(),
    )
}

/// A session of an app password the account makes.
async fn app_session(e: &Env, token: &str, handle: &str) -> String {
    let app = e
        .call(
            "com.atproto.server.createAppPassword",
            Some(token),
            json!({ "name": format!("a{}", rand::random::<u32>()) }),
        )
        .await
        .unwrap();
    tokens(
        &e.call(
            LOGIN,
            None,
            json!({ "identifier": handle, "password": app["password"] }),
        )
        .await
        .unwrap(),
    )
    .0
}

fn put(did: &str, rkey: &str, record: Json) -> Json {
    json!({ "repo": did, "collection": "a.b.c", "rkey": rkey, "record": record })
}

/// `deactivateAccount`'s and `activateAccount`'s checks, in order, and
/// what each does: the state, every call's events, sessions untouched.
#[tokio::test]
async fn deactivating_and_activating() {
    let e = Env::new("life-deactivate").await;
    let (did, token) = create(&e.s, "alice").await;
    let (_, bob) = create(&e.s, "bob").await;
    let app = app_session(&e, &token, "alice.test").await;
    let refresh = tokens(
        &e.call(
            LOGIN,
            None,
            json!({ "identifier": "alice.test", "password": "alice-pw" }),
        )
        .await
        .unwrap(),
    )
    .1;
    let before = e.events().len();
    for (t, body, want) in [
        (None, "{}", "AuthMissing"),
        (Some(app.as_str()), "{}", "InvalidToken"),
        (Some(refresh.as_str()), "{}", "InvalidToken"),
        (Some(token.as_str()), "", "InvalidRequest"),
        (
            Some(token.as_str()),
            r#"{"deleteAfter":"tomorrow"}"#,
            "InvalidRequest",
        ),
    ] {
        let bearer = t.map_or(Bearer::None, Bearer::Token);
        assert_eq!(
            call_raw(&e.s, DEACTIVATE, bearer, &[], body).await,
            Err(want.into()),
            "{t:?} {body}"
        );
    }
    assert_eq!(e.events().len(), before);
    e.call(
        DEACTIVATE,
        Some(&token),
        json!({ "deleteAfter": "2030-01-01T00:00:00.000Z" }),
    )
    .await
    .unwrap();
    e.call(DEACTIVATE, Some(&token), json!({})).await.unwrap();
    let session = e.call(GET_SESSION, Some(&token), Json::Null).await.unwrap();
    assert_eq!(
        (&session["active"], &session["status"]),
        (&json!(false), &json!("deactivated"))
    );
    // Its sessions and app passwords stay.
    assert_eq!(
        e.call(REFRESH, Some(&refresh), Json::Null).await.unwrap()["status"],
        json!("deactivated")
    );
    assert_eq!(
        e.call(GET_SESSION, Some(&app), Json::Null).await.unwrap()["active"],
        json!(false)
    );
    // activateAccount: its token, then its body.
    assert_eq!(
        e.call(ACTIVATE, None, Json::Null).await,
        Err("AuthMissing".into())
    );
    assert_eq!(
        e.call(ACTIVATE, Some(&app), Json::Null).await,
        Err("InvalidToken".into())
    );
    assert_eq!(
        e.call(ACTIVATE, Some(&token), json!({})).await,
        Err("InvalidRequest".into())
    );
    e.call(ACTIVATE, Some(&token), Json::Null).await.unwrap();
    e.call(ACTIVATE, Some(&token), Json::Null).await.unwrap();
    assert_eq!(
        e.call(GET_SESSION, Some(&token), Json::Null).await.unwrap()["active"],
        json!(true)
    );
    let briefs: Vec<String> = e.events()[before..].iter().map(brief).collect();
    let account = |status: &str| {
        format!(
            "account {did} {}",
            if status == "-" {
                "true -".to_string()
            } else {
                format!("false {status}")
            }
        )
    };
    let activated = [
        account("-"),
        format!("identity {did} alice.test"),
        format!("sync {did}"),
    ];
    let mut want = vec![account("deactivated"), account("deactivated")];
    want.extend(activated.clone());
    want.extend(activated);
    assert_eq!(briefs, want);
    // The `#sync` is of its latest commit.
    let sync = e
        .events()
        .into_iter()
        .rev()
        .find(|e| e["$t"] == "#sync")
        .unwrap();
    assert_eq!(sync["rev"], json!(repo_of(&e.s, &did, |r| r.rev.clone())));
    // Another's token deactivates its own account alone.
    e.call(DEACTIVATE, Some(&bob), json!({})).await.unwrap();
    assert_eq!(
        e.call(GET_SESSION, Some(&token), Json::Null).await.unwrap()["active"],
        json!(true)
    );
}

/// `checkAccountStatus`: any access token of the account's but a taken-down
/// one; its counts; `validDid` as the directory's data says.
#[tokio::test]
async fn checking_status() {
    let e = Env::new("life-check").await;
    let (did, token) = create(&e.s, "alice").await;
    let app = app_session(&e, &token, "alice.test").await;
    let blob = crate::blobs::test_upload(
        &e.s,
        Some(&token),
        Some("text/plain"),
        b"one blob".to_vec(),
        false,
    )
    .await
    .unwrap();
    crate::blobs::test_upload(
        &e.s,
        Some(&token),
        Some("text/plain"),
        b"another".to_vec(),
        false,
    )
    .await
    .unwrap();
    e.call(
        "com.atproto.repo.putRecord",
        Some(&token),
        put(&did, "one", json!({ "b": blob["blob"] })),
    )
    .await
    .unwrap();
    e.call(
        "com.atproto.repo.putRecord",
        Some(&token),
        put(&did, "two", json!({ "b": blob["blob"] })),
    )
    .await
    .unwrap();
    assert_eq!(
        e.call(CHECK, None, Json::Null).await,
        Err("AuthMissing".into())
    );
    let got = e.call(CHECK, Some(&app), Json::Null).await.unwrap();
    let (head, rev, blocks) = repo_of(&e.s, &did, |r| {
        (r.head_string(), r.rev.clone(), r.block_count())
    });
    assert_eq!(
        got,
        json!({
            "activated": true, "validDid": true, "repoCommit": head, "repoRev": rev, "repoBlocks": blocks,
            "indexedRecords": 2, "privateStateValues": 0, "expectedBlobs": 1, "importedBlobs": 2,
        })
    );
    // The commit, the tree's nodes, and the one record block both records are.
    assert!(blocks >= 3);
    e.call(DEACTIVATE, Some(&token), json!({})).await.unwrap();
    assert_eq!(
        e.call(CHECK, Some(&token), Json::Null).await.unwrap()["activated"],
        json!(false)
    );
    // The DID moved elsewhere: not valid, and neither the owner nor the admin activates it.
    let moved = reqwest::Client::new()
        .put(format!("{}/{did}/data", e.plc))
        .body("https://elsewhere.example")
        .send()
        .await
        .unwrap();
    assert!(moved.status().is_success());
    assert_eq!(
        e.call(CHECK, Some(&token), Json::Null).await.unwrap()["validDid"],
        json!(false)
    );
    assert_eq!(
        e.call(ACTIVATE, Some(&token), Json::Null).await,
        Err("InvalidRequest".into())
    );
    let activate = json!({ "subject": { "$type": REPO_REF, "did": did }, "deactivated": { "applied": false } });
    assert_eq!(
        e.admin(UPDATE, activate.clone()).await,
        Err("InvalidRequest".into())
    );
    // Taken down and lifted in the same call: the lifting stays, with its event.
    e.takedown(&did, true).await.unwrap();
    let before = e.events().len();
    let mut both = activate.clone();
    both["takedown"] = json!({ "applied": false });
    assert_eq!(e.admin(UPDATE, both).await, Err("InvalidRequest".into()));
    let state = e.admin_query(&[("did", &did)]).await.unwrap();
    assert_eq!(
        (&state["takedown"], &state["deactivated"]),
        (&json!({ "applied": false }), &json!({ "applied": true }))
    );
    assert_eq!(
        e.events()[before..].iter().map(brief).collect::<Vec<_>>(),
        [format!("account {did} false deactivated")]
    );
    // Moved back, it is.
    reqwest::Client::new()
        .put(format!("{}/{did}/data", e.plc))
        .body("http://127.0.0.1:2583")
        .send()
        .await
        .unwrap();
    e.admin(UPDATE, activate).await.unwrap();
    assert_eq!(
        e.call(CHECK, Some(&token), Json::Null).await.unwrap()["activated"],
        json!(true)
    );
}

/// The admin's auth, before its input, each wrong kind answered as
/// `spec/LIFECYCLE.md` says; and none while `PDS_ADMIN_PASSWORD` is unset.
#[tokio::test]
async fn the_admins_auth() {
    let e = Env::new("life-admin").await;
    let (did, token) = create(&e.s, "alice").await;
    let refresh = tokens(
        &e.call(
            LOGIN,
            None,
            json!({ "identifier": "alice.test", "password": "alice-pw" }),
        )
        .await
        .unwrap(),
    )
    .1;
    let basic = |up: &str| {
        format!(
            "Basic {}",
            base64::engine::general_purpose::STANDARD.encode(up)
        )
    };
    let good = json!({ "subject": { "$type": REPO_REF, "did": did } }).to_string();
    for (header, want) in [
        (basic("admin:wrong"), "AuthenticationRequired"),
        (
            basic(&format!("root:{ADMIN_PASSWORD}")),
            "AuthenticationRequired",
        ),
        ("Basic not-base64!".into(), "AuthenticationRequired"),
        (basic("no colon"), "AuthenticationRequired"),
        ("DPoP abc".into(), "AuthenticationRequired"),
        (format!("Bearer {token}"), "BadJwtType"),
        (format!("Bearer {refresh}"), "BadJwtType"),
        ("Bearer not.a.jwt".into(), "BadJwt"),
        (format!("BASIC {} x", ADMIN_PASSWORD), "InvalidToken"),
        ("Bearer".into(), "InvalidToken"),
    ] {
        for body in [good.as_str(), "{}"] {
            assert_eq!(
                e.raw(UPDATE, &header, &[], body).await,
                Err(want.into()),
                "{header} {body}"
            );
        }
        assert_eq!(
            e.raw(GET, &header, &[("did", "not a did")], "").await,
            Err(want.into()),
            "{header}"
        );
    }
    assert_eq!(
        call_raw(&e.s, UPDATE, Bearer::None, &[], &good).await,
        Err("AuthenticationRequired".into())
    );
    // The scheme in any case; then the input.
    let lower = admin_header().replacen("Basic", "bAsIc", 1);
    assert!(e.raw(UPDATE, &lower, &[], &good).await.is_ok());
    for bad in [
        json!({}),
        json!({ "subject": { "did": did } }),
        json!({ "subject": { "$type": REPO_REF, "did": "nope" } }),
        json!({ "subject": { "$type": REPO_REF, "did": did }, "takedown": {} }),
    ] {
        assert_eq!(
            e.admin(UPDATE, bad.clone()).await,
            Err("InvalidRequest".into()),
            "{bad}"
        );
    }
    assert_eq!(e.admin_query(&[]).await, Err("InvalidRequest".into()));
    let unset = open_with(&scratch("life-admin-unset"), &e.plc, |c| {
        c.admin_password = None
    });
    let p = [("did".to_string(), did.clone())];
    assert_eq!(
        call_raw(&unset, GET, Bearer::of(Some(&admin_header())), &p, "").await,
        Err("AuthenticationRequired".into())
    );
}

/// `updateSubjectStatus` of an account: its rules, and the events of each
/// call; `getSubjectStatus` of it.
#[tokio::test]
async fn the_admin_and_an_account() {
    let e = Env::new("life-admin-account").await;
    let (did, token) = create(&e.s, "alice").await;
    let subject = json!({ "$type": REPO_REF, "did": did });
    let body = |t: Option<Json>, d: Option<Json>| {
        let mut b = json!({ "subject": subject });
        if let Some(t) = t {
            b["takedown"] = t;
        }
        if let Some(d) = d {
            b["deactivated"] = d;
        }
        b
    };
    let before = e.events().len();
    // The pair it refuses, and a takedown of what is no subject.
    assert_eq!(
        e.admin(
            UPDATE,
            body(
                Some(json!({ "applied": true })),
                Some(json!({ "applied": false }))
            )
        )
        .await,
        Err("InvalidRequest".into())
    );
    let other = json!({ "subject": { "$type": "com.example.thing", "did": did }, "takedown": { "applied": true } });
    assert!(e.admin(UPDATE, other).await.is_err());
    assert_eq!(e.events().len(), before);
    // Neither: its status, and nothing changes.
    assert_eq!(
        e.admin(UPDATE, body(None, None)).await.unwrap(),
        json!({ "subject": subject })
    );
    // A takedown with no ref takes the time; its answer is its input.
    let got = e
        .admin(UPDATE, body(Some(json!({ "applied": true })), None))
        .await
        .unwrap();
    assert_eq!(
        got,
        json!({ "subject": subject, "takedown": { "applied": true } })
    );
    let status = e.admin_query(&[("did", &did)]).await.unwrap();
    assert!(
        status["takedown"]["ref"].as_str().unwrap().ends_with('Z'),
        "{status}"
    );
    // Again, with a ref: it replaces the time; deactivated besides.
    e.admin(
        UPDATE,
        body(
            Some(json!({ "applied": true, "ref": "case-1" })),
            Some(json!({ "applied": true })),
        ),
    )
    .await
    .unwrap();
    let status = e.admin_query(&[("did", &did)]).await.unwrap();
    assert_eq!(
        status,
        json!({ "subject": subject, "takedown": { "applied": true, "ref": "case-1" }, "deactivated": { "applied": true } })
    );
    // Taken down, it is refused activation, by the admin too.
    assert_eq!(
        e.admin(UPDATE, body(None, Some(json!({ "applied": false }))))
            .await,
        Err("AccountNotFound".into())
    );
    // Lifted, it is still deactivated.
    e.takedown(&did, false).await.unwrap();
    assert_eq!(
        e.call(GET_SESSION, Some(&token), Json::Null).await.unwrap()["status"],
        json!("deactivated")
    );
    e.admin(UPDATE, body(None, Some(json!({ "applied": false }))))
        .await
        .unwrap();
    let briefs: Vec<String> = e.events()[before..].iter().map(brief).collect();
    let account = |s: &str| format!("account {did} {s}");
    assert_eq!(
        briefs,
        [
            account("true -"),
            account("false takendown"),
            account("false takendown"),
            account("false takendown"),
            account("false deactivated"),
            account("true -"),
            format!("identity {did} alice.test"),
            format!("sync {did}"),
        ]
    );
    // A DID no account here has: `#account` of a deletion; deactivating it is refused.
    let nobody = "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa";
    let gone = json!({ "$type": REPO_REF, "did": nobody });
    let n = e.events().len();
    e.admin(
        UPDATE,
        json!({ "subject": gone, "takedown": { "applied": true } }),
    )
    .await
    .unwrap();
    e.admin(UPDATE, json!({ "subject": gone })).await.unwrap();
    assert_eq!(
        e.events()[n..].iter().map(brief).collect::<Vec<_>>(),
        [
            format!("account {nobody} false deleted"),
            format!("account {nobody} false deleted")
        ]
    );
    assert_eq!(
        e.admin(
            UPDATE,
            json!({ "subject": gone, "deactivated": { "applied": true } })
        )
        .await,
        Err("InvalidRequest".into())
    );
    // Activating one: the directory does not know it, or knows it as a deleted account's.
    assert_eq!(
        e.admin(
            UPDATE,
            json!({ "subject": gone, "deactivated": { "applied": false } })
        )
        .await,
        Err("InvalidRequest".into())
    );
    assert_eq!(e.events().len(), n + 2);
    assert_eq!(
        e.admin_query(&[("did", nobody)]).await,
        Err("NotFound".into())
    );
}

/// Records and blobs taken down: what each read answers, what a write of
/// them does, and their status.
#[tokio::test]
async fn records_and_blobs_taken_down() {
    let e = Env::new("life-content").await;
    let (did, token) = create(&e.s, "alice").await;
    let (_, bob) = create(&e.s, "bob").await;
    let bytes = b"a blob taken down".to_vec();
    let blob =
        crate::blobs::test_upload(&e.s, Some(&token), Some("text/plain"), bytes.clone(), false)
            .await
            .unwrap()["blob"]
            .clone();
    let cid = blob["ref"]["$link"].as_str().unwrap().to_string();
    let rec = e
        .call(
            "com.atproto.repo.putRecord",
            Some(&token),
            put(&did, "one", json!({ "b": blob })),
        )
        .await
        .unwrap();
    e.call(
        "com.atproto.repo.putRecord",
        Some(&token),
        put(&did, "two", json!({ "n": 2 })),
    )
    .await
    .unwrap();
    // A record of another collection keeps the blob held throughout.
    let keep = |value: Json| json!({ "repo": did, "collection": "a.b.d", "rkey": "keep", "record": value });
    e.call(
        "com.atproto.repo.putRecord",
        Some(&token),
        keep(json!({ "b": blob })),
    )
    .await
    .unwrap();
    let uri = rec["uri"].as_str().unwrap().to_string();
    let strong = |uri: &str, cid: &Json| json!({ "$type": STRONG_REF, "uri": uri, "cid": cid });
    let before = e.events().len();
    // A record: by its key, whatever its cid says.
    e.admin(UPDATE, json!({ "subject": strong(&uri, &json!("bafyreidfayvfuwqa7qlnopdjiqrxzs6blmoeu4rujcjtnci5beludirz2a")), "takedown": { "applied": true, "ref": "rec" } })).await.unwrap();
    let get = |rkey: &str, t: Option<&str>| {
        e.query(
            "com.atproto.repo.getRecord",
            t,
            &[("repo", &did), ("collection", "a.b.c"), ("rkey", rkey)],
        )
    };
    assert_eq!(get("one", None).await, Err("RecordNotFound".into()));
    assert_eq!(get("one", Some(&token)).await, Err("RecordNotFound".into()));
    let listed = e
        .query(
            "com.atproto.repo.listRecords",
            None,
            &[("repo", &did), ("collection", "a.b.c")],
        )
        .await
        .unwrap();
    assert_eq!(
        listed["records"]
            .as_array()
            .unwrap()
            .iter()
            .map(|r| r["uri"]
                .as_str()
                .unwrap()
                .rsplit('/')
                .next()
                .unwrap()
                .to_string())
            .collect::<Vec<_>>(),
        ["two"]
    );
    // Still in the repository.
    let sync = e
        .query(
            "com.atproto.sync.getRecord",
            None,
            &[("did", &did), ("collection", "a.b.c"), ("rkey", "one")],
        )
        .await;
    assert_eq!(sync, Err("a CAR file".into()));
    let status = e.admin_query(&[("uri", &uri)]).await.unwrap();
    assert_eq!(
        status,
        json!({ "subject": strong(&uri, &rec["cid"]), "takedown": { "applied": true, "ref": "rec" } })
    );
    // Updated, it stays down, the status of the record as it is now.
    let updated = e
        .call(
            "com.atproto.repo.putRecord",
            Some(&token),
            put(&did, "one", json!({ "b": null })),
        )
        .await
        .unwrap();
    assert_eq!(get("one", None).await, Err("RecordNotFound".into()));
    assert_eq!(
        e.admin_query(&[("uri", &uri)]).await.unwrap()["subject"]["cid"],
        updated["cid"]
    );
    // A key not held is taken down by nothing.
    let none = format!("at://{did}/a.b.c/none");
    e.admin(
        UPDATE,
        json!({ "subject": strong(&none, &rec["cid"]), "takedown": { "applied": true } }),
    )
    .await
    .unwrap();
    assert_eq!(
        e.admin_query(&[("uri", &none)]).await,
        Err("NotFound".into())
    );
    // Deleted, it is no longer down: made again, it is served.
    e.call(
        "com.atproto.repo.deleteRecord",
        Some(&token),
        json!({ "repo": did, "collection": "a.b.c", "rkey": "one" }),
    )
    .await
    .unwrap();
    e.call(
        "com.atproto.repo.putRecord",
        Some(&token),
        put(&did, "one", json!({ "n": 1 })),
    )
    .await
    .unwrap();
    assert!(get("one", None).await.is_ok());
    // A handle, or a DID no account here has, is 500.
    for bad in [
        "at://alice.test/a.b.c/two",
        "at://did:plc:aaaaaaaaaaaaaaaaaaaaaaaa/a.b.c/two",
    ] {
        assert_eq!(
            e.admin(
                UPDATE,
                json!({ "subject": strong(bad, &rec["cid"]), "takedown": { "applied": true } })
            )
            .await,
            Err("InternalServerError".into())
        );
    }
    // A blob, referenced again.
    e.call(
        "com.atproto.repo.putRecord",
        Some(&token),
        put(&did, "three", json!({ "b": blob })),
    )
    .await
    .unwrap();
    let blob_ref = json!({ "$type": BLOB_REF, "did": did, "cid": cid });
    e.admin(
        UPDATE,
        json!({ "subject": blob_ref, "takedown": { "applied": true } }),
    )
    .await
    .unwrap();
    let get_blob = |t: Option<&str>| {
        e.query(
            "com.atproto.sync.getBlob",
            t,
            &[("did", &did), ("cid", &cid)],
        )
    };
    assert_eq!(get_blob(None).await, Err("InvalidRequest".into()));
    assert_eq!(get_blob(Some(&token)).await, Err("InvalidRequest".into()));
    assert_eq!(
        e.raw(
            "com.atproto.sync.getBlob",
            &admin_header(),
            &[("did", &did), ("cid", &cid)],
            ""
        )
        .await,
        Err("InvalidRequest".into())
    );
    let listed = e
        .query("com.atproto.sync.listBlobs", None, &[("did", &did)])
        .await
        .unwrap();
    assert_eq!(listed["cids"], json!([cid]));
    assert_eq!(
        e.call(
            "com.atproto.repo.putRecord",
            Some(&token),
            put(&did, "four", json!({ "b": blob }))
        )
        .await,
        Err("BlobNotFound".into())
    );
    assert_eq!(
        crate::blobs::test_upload(&e.s, Some(&token), Some("text/plain"), bytes.clone(), false)
            .await,
        Err((400, "InvalidRequest".into()))
    );
    let status = e
        .admin_query(&[("did", &did), ("blob", &cid)])
        .await
        .unwrap();
    assert_eq!(status["takedown"]["applied"], json!(true));
    assert!(status["takedown"]["ref"].is_string());
    assert_eq!(
        e.admin_query(&[("blob", &cid)]).await,
        Err("InvalidRequest".into())
    );
    // Another account's blob, or a DID no account has.
    assert_eq!(
        e.admin_query(&[
            ("did", &did),
            (
                "blob",
                "bafkreihdwdcefgh4dqkjv67uzcmw7ojee6xedzdetojuzjevtenxquvyku"
            )
        ])
        .await,
        Err("NotFound".into())
    );
    let nobody =
        json!({ "$type": BLOB_REF, "did": "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa", "cid": cid });
    assert_eq!(
        e.admin(
            UPDATE,
            json!({ "subject": nobody, "takedown": { "applied": true } })
        )
        .await,
        Err("InternalServerError".into())
    );
    // Lifted, it is served again.
    e.admin(
        UPDATE,
        json!({ "subject": blob_ref, "takedown": { "applied": false } }),
    )
    .await
    .unwrap();
    assert_eq!(get_blob(None).await, Err("a blob".into()));
    // Taken down, then no longer held: the takedown goes with it.
    e.admin(
        UPDATE,
        json!({ "subject": blob_ref, "takedown": { "applied": true } }),
    )
    .await
    .unwrap();
    for rkey in ["three", "one"] {
        e.call(
            "com.atproto.repo.putRecord",
            Some(&token),
            put(&did, rkey, json!({ "n": 0 })),
        )
        .await
        .unwrap();
    }
    e.call(
        "com.atproto.repo.putRecord",
        Some(&token),
        keep(json!({ "n": 0 })),
    )
    .await
    .unwrap();
    assert_eq!(
        e.admin_query(&[("did", &did), ("blob", &cid)]).await,
        Err("NotFound".into())
    );
    crate::blobs::test_upload(&e.s, Some(&token), Some("text/plain"), bytes, false)
        .await
        .unwrap();
    e.call(
        "com.atproto.repo.putRecord",
        Some(&token),
        put(&did, "five", json!({ "b": blob })),
    )
    .await
    .unwrap();
    assert_eq!(get_blob(None).await, Err("a blob".into()));
    // None of it is on the firehose, but the commits.
    assert!(e.events()[before..].iter().all(|ev| ev["$t"] == "#commit"));
    let _ = bob;
}

/// Each state's answer to every method of the tables, for the account's
/// own token, no token, an app password's, another account's, and the admin.
#[tokio::test]
async fn what_each_state_does() {
    let mut e = Env::new("life-table").await;
    let (did, token) = create(&e.s, "alice").await;
    let (bob_did, bob) = create(&e.s, "bob").await;
    let app = app_session(&e, &token, "alice.test").await;
    let (_, refresh) = tokens(
        &e.call(
            LOGIN,
            None,
            json!({ "identifier": "alice.test", "password": "alice-pw" }),
        )
        .await
        .unwrap(),
    );
    let blob = crate::blobs::test_upload(
        &e.s,
        Some(&token),
        Some("text/plain"),
        b"bytes".to_vec(),
        false,
    )
    .await
    .unwrap()["blob"]
        .clone();
    let cid = blob["ref"]["$link"].as_str().unwrap().to_string();
    e.call(
        "com.atproto.repo.putRecord",
        Some(&token),
        put(&did, "one", json!({ "b": blob })),
    )
    .await
    .unwrap();
    let head = repo_of(&e.s, &did, |r| r.head_string());

    // The reads anyone makes, by a parameter: each answer for no token, its own, and the admin's.
    async fn reads(e: &Env, did: &str, cid: &str, head: &str, auth: Option<&str>) -> Vec<String> {
        let mut out = Vec::new();
        let rec = [("did", did), ("collection", "a.b.c"), ("rkey", "one")];
        let queries: Vec<(&str, Vec<(&str, &str)>)> = vec![
            ("com.atproto.repo.describeRepo", vec![("repo", did)]),
            (
                "com.atproto.repo.getRecord",
                vec![("repo", did), ("collection", "a.b.c"), ("rkey", "one")],
            ),
            (
                "com.atproto.repo.listRecords",
                vec![("repo", did), ("collection", "a.b.c")],
            ),
            ("com.atproto.sync.getLatestCommit", vec![("did", did)]),
            ("com.atproto.sync.getRepo", vec![("did", did)]),
            (
                "com.atproto.sync.getBlocks",
                vec![("did", did), ("cids", head)],
            ),
            ("com.atproto.sync.getRecord", rec.to_vec()),
            ("com.atproto.sync.getBlob", vec![("did", did), ("cid", cid)]),
            ("com.atproto.sync.listBlobs", vec![("did", did)]),
        ];
        for (nsid, p) in queries {
            let got = match auth {
                None => e.query(nsid, None, &p).await,
                Some(h) => e.raw(nsid, h, &p, "").await,
            };
            out.push(match got {
                Ok(_) => "ok".into(),
                Err(x) if x.starts_with("a ") => "ok".into(),
                Err(x) => x,
            });
        }
        out
    }
    let ok = vec!["ok".to_string(); 9];
    let own = format!("Bearer {token}");
    let other = format!("Bearer {bob}");
    assert_eq!(reads(&e, &did, &cid, &head, None).await, ok);
    // Any Authorization that is not good is refused, an active account's too.
    let refused = reads(&e, &did, &cid, &head, Some(&format!("Bearer {refresh}"))).await;
    assert_eq!(&refused[3..], ["InvalidToken"; 6]);
    let wrong = format!(
        "Basic {}",
        base64::engine::general_purpose::STANDARD.encode("admin:wrong")
    );
    assert_eq!(
        &reads(&e, &did, &cid, &head, Some(&wrong)).await[3..],
        ["AuthenticationRequired"; 6]
    );

    let deactivated: Vec<String> = [
        "RepoDeactivated",
        "InvalidRequest",
        "InvalidRequest",
        "RepoDeactivated",
        "RepoDeactivated",
        "RepoDeactivated",
        "RepoDeactivated",
        "RepoDeactivated",
        "RepoDeactivated",
    ]
    .map(String::from)
    .to_vec();
    let takendown: Vec<String> = [
        "RepoTakendown",
        "InvalidRequest",
        "InvalidRequest",
        "RepoTakendown",
        "RepoTakendown",
        "RepoTakendown",
        "RepoTakendown",
        "RepoTakendown",
        "RepoTakendown",
    ]
    .map(String::from)
    .to_vec();
    let mut own_reads = ok.clone();
    own_reads[0] = "RepoDeactivated".into();
    own_reads[1] = "InvalidRequest".into();
    own_reads[2] = "InvalidRequest".into();

    // Its own calls: each with its token.
    async fn own_calls(e: &Env, did: &str, token: &str, refresh: &str) -> Vec<String> {
        let w = put(did, "w", json!({ "n": 1 }));
        let calls: Vec<(&str, Option<&str>, Json)> = vec![
            ("com.atproto.server.getSession", Some(token), Json::Null),
            (
                "com.atproto.server.createAppPassword",
                Some(token),
                json!({ "name": format!("t{}", rand::random::<u32>()) }),
            ),
            (
                "com.atproto.server.listAppPasswords",
                Some(token),
                Json::Null,
            ),
            (
                "com.atproto.server.revokeAppPassword",
                Some(token),
                json!({ "name": "none" }),
            ),
            ("com.atproto.repo.putRecord", Some(token), w),
            (
                "com.atproto.identity.getRecommendedDidCredentials",
                Some(token),
                Json::Null,
            ),
            (CHECK, Some(token), Json::Null),
            (
                "com.atproto.server.refreshSession",
                Some(refresh),
                Json::Null,
            ),
        ];
        let mut out = Vec::new();
        for (nsid, t, b) in calls {
            out.push(match call(&e.s, nsid, t, b).await {
                Ok(_) => "ok".into(),
                Err(x) => x,
            });
        }
        let upload = crate::blobs::test_upload(&e.s, Some(token), None, vec![1; 10], false).await;
        out.push(match upload {
            Ok(_) => "ok".into(),
            Err((_, x)) => x,
        });
        out
    }

    // Deactivated.
    e.call(DEACTIVATE, Some(&token), json!({})).await.unwrap();
    assert_eq!(reads(&e, &did, &cid, &head, None).await, deactivated);
    assert_eq!(
        reads(&e, &did, &cid, &head, Some(&other)).await,
        deactivated
    );
    assert_eq!(reads(&e, &did, &cid, &head, Some(&own)).await, own_reads);
    let mut admin_reads = own_reads.clone();
    admin_reads[0] = "RepoDeactivated".into();
    assert_eq!(
        reads(&e, &did, &cid, &head, Some(&admin_header())).await,
        admin_reads
    );
    let calls = own_calls(&e, &did, &token, &refresh).await;
    // uploadBlob goes on to its own checks: no Content-Type.
    assert_eq!(
        calls,
        [
            "ok",
            "ok",
            "ok",
            "ok",
            "AccountDeactivated",
            "ok",
            "ok",
            "ok",
            "InvalidRequest"
        ]
    );
    // Another's write to its repository is refused by its state first; its write to another's, by the token.
    assert_eq!(
        e.call(
            "com.atproto.repo.putRecord",
            Some(&bob),
            put(&did, "x", json!({}))
        )
        .await,
        Err("AccountDeactivated".into())
    );
    assert_eq!(
        e.call(
            "com.atproto.repo.putRecord",
            Some(&token),
            put(&bob_did, "x", json!({}))
        )
        .await,
        Err("AuthenticationRequired".into())
    );
    assert_eq!(
        e.query(
            "com.atproto.identity.resolveHandle",
            None,
            &[("handle", "alice.test")]
        )
        .await,
        Err("HandleNotFound".into())
    );
    assert_eq!(
        e.query("com.atproto.sync.getRepoStatus", None, &[("did", &did)])
            .await
            .unwrap(),
        json!({ "did": did, "active": false, "status": "deactivated" })
    );
    let listed = e
        .query("com.atproto.sync.listRepos", None, &[])
        .await
        .unwrap();
    assert_eq!(listed["repos"][0]["status"], json!("deactivated"));
    assert_eq!(listed["repos"][0]["active"], json!(false));
    assert!(listed["repos"][0]["head"].is_string());
    let login = e
        .call(
            LOGIN,
            None,
            json!({ "identifier": "alice.test", "password": "alice-pw" }),
        )
        .await
        .unwrap();
    assert_eq!(login["status"], json!("deactivated"));
    // Its handle and email are still taken; its handle changes, and does not resolve.
    let taken = json!({ "handle": "alice.test", "email": "new@mail.com", "password": "pw" });
    assert_eq!(
        e.call("com.atproto.server.createAccount", None, taken)
            .await,
        Err("InvalidRequest".into())
    );
    let taken = json!({ "handle": "carol.test", "email": "alice@mail.com", "password": "pw" });
    assert_eq!(
        e.call("com.atproto.server.createAccount", None, taken)
            .await,
        Err("InvalidRequest".into())
    );
    assert_eq!(
        e.query(
            "com.atproto.identity.resolveHandle",
            None,
            &[("handle", "alice.test")]
        )
        .await,
        Err("HandleNotFound".into())
    );
    assert_eq!(identity_well_known(&e.s, "alice.test").await, 404);
    assert_eq!(identity_well_known(&e.s, "bob.test").await, 200);

    // Taken down too: answered as taken down.
    e.takedown(&did, true).await.unwrap();
    assert_eq!(reads(&e, &did, &cid, &head, None).await, takendown);
    assert_eq!(reads(&e, &did, &cid, &head, Some(&own)).await[3..], ok[3..]);
    assert_eq!(
        e.call(GET_SESSION, Some(&token), Json::Null).await,
        Err("InvalidRequest".into())
    );
    let calls = own_calls(&e, &did, &token, &refresh).await;
    assert_eq!(
        calls,
        [
            "InvalidRequest",
            "AccountTakedown",
            "ok",
            "ok",
            "AccountTakedown",
            "ok",
            "ok",
            "AccountTakedown",
            "AccountTakedown"
        ]
    );
    let creds = e
        .call(
            "com.atproto.identity.getRecommendedDidCredentials",
            Some(&token),
            Json::Null,
        )
        .await
        .unwrap();
    assert!(creds.get("alsoKnownAs").is_none());
    assert_eq!(
        e.call(ACTIVATE, Some(&token), Json::Null).await,
        Err("AccountNotFound".into())
    );
    assert_eq!(
        e.call(REQUEST_DELETE, Some(&token), Json::Null).await,
        Err("AccountTakedown".into())
    );
    e.call(DEACTIVATE, Some(&token), json!({})).await.unwrap();
    assert_eq!(
        e.call(
            "com.atproto.identity.updateHandle",
            Some(&token),
            json!({ "handle": "alice2.test" })
        )
        .await,
        Err("AccountTakedown".into())
    );
    // Before the handle's own checks.
    assert_eq!(
        e.call(
            "com.atproto.identity.updateHandle",
            Some(&token),
            json!({ "handle": "alice.com" })
        )
        .await,
        Err("AccountTakedown".into())
    );
    assert_eq!(
        e.query("com.atproto.sync.getRepoStatus", None, &[("did", &did)])
            .await
            .unwrap()["status"],
        json!("takendown")
    );
    // Its state survives a restart.
    e.reopen();
    assert_eq!(reads(&e, &did, &cid, &head, None).await, takendown);
    assert_eq!(
        e.query("com.atproto.sync.getRepoStatus", None, &[("did", &did)])
            .await
            .unwrap()["status"],
        json!("takendown")
    );
    // Lifted, it is deactivated still; activated, it is active.
    e.takedown(&did, false).await.unwrap();
    assert_eq!(reads(&e, &did, &cid, &head, None).await, deactivated);
    e.call(ACTIVATE, Some(&token), Json::Null).await.unwrap();
    assert_eq!(reads(&e, &did, &cid, &head, None).await, ok);
    assert_eq!(
        e.query(
            "com.atproto.identity.resolveHandle",
            None,
            &[("handle", "alice.test")]
        )
        .await
        .unwrap()["did"],
        json!(did)
    );
    assert_eq!(identity_well_known(&e.s, "alice.test").await, 200);
    let _ = app;
}

/// `GET /.well-known/atproto-did` with `host` as its `Host`: its status.
async fn identity_well_known(s: &Shared, host: &str) -> u16 {
    let mut headers = axum::http::HeaderMap::new();
    headers.insert(axum::http::header::HOST, host.parse().unwrap());
    crate::identity::well_known(axum::extract::State(s.clone()), headers)
        .await
        .status()
        .as_u16()
}

/// A taken-down account's sessions: ended by the takedown; made again only
/// with its password and `allowTakendown`, of tokens that work for little.
#[tokio::test]
async fn taken_down_sessions() {
    let e = Env::new("life-takendown").await;
    let (did, token) = create(&e.s, "alice").await;
    let app = e
        .call(
            "com.atproto.server.createAppPassword",
            Some(&token),
            json!({ "name": "app" }),
        )
        .await
        .unwrap()["password"]
        .as_str()
        .unwrap()
        .to_string();
    let (_, refresh) = tokens(
        &e.call(
            LOGIN,
            None,
            json!({ "identifier": "alice.test", "password": "alice-pw" }),
        )
        .await
        .unwrap(),
    );
    e.takedown(&did, true).await.unwrap();
    assert_eq!(e.s.sessions.count(&did), 0);
    assert_eq!(
        e.call(REFRESH, Some(&refresh), Json::Null).await,
        Err("AccountTakedown".into())
    );
    let login = |pw: &str, allow: Option<bool>| {
        let mut b = json!({ "identifier": "alice.test", "password": pw });
        if let Some(a) = allow {
            b["allowTakendown"] = json!(a);
        }
        e.call(LOGIN, None, b)
    };
    assert_eq!(
        login("wrong", Some(true)).await,
        Err("AuthenticationRequired".into())
    );
    assert_eq!(
        login(&app, Some(true)).await,
        Err("AuthenticationRequired".into())
    );
    assert_eq!(login("alice-pw", None).await, Err("AccountTakedown".into()));
    assert_eq!(
        login("alice-pw", Some(false)).await,
        Err("AccountTakedown".into())
    );
    let got = login("alice-pw", Some(true)).await.unwrap();
    assert_eq!(
        (&got["active"], &got["status"], &got["did"]),
        (&json!(false), &json!("takendown"), &json!(did))
    );
    let (access, down_refresh) = tokens(&got);
    let claims = |t: &str| {
        serde_json::from_slice::<Json>(
            &base64::engine::general_purpose::URL_SAFE_NO_PAD
                .decode(t.split('.').nth(1).unwrap())
                .unwrap(),
        )
        .unwrap()
    };
    assert_eq!(claims(&access)["scope"], json!("com.atproto.takendown"));
    assert_eq!(claims(&down_refresh)["scope"], json!("com.atproto.refresh"));
    assert_eq!(e.s.sessions.count(&did), 0);
    // It reads its repository and blobs, deactivates its account, and nothing else.
    let p = [("did", did.as_str())];
    assert_eq!(
        e.query("com.atproto.sync.getRepo", Some(&access), &p).await,
        Err("a CAR file".into())
    );
    assert!(
        e.query("com.atproto.sync.listBlobs", Some(&access), &p)
            .await
            .is_ok()
    );
    assert_eq!(
        e.query("com.atproto.sync.getLatestCommit", Some(&access), &p)
            .await,
        Err("InvalidToken".into())
    );
    assert_eq!(
        e.query(GET_SESSION, Some(&access), &[]).await,
        Err("InvalidToken".into())
    );
    assert_eq!(
        e.call(CHECK, Some(&access), Json::Null).await,
        Err("InvalidToken".into())
    );
    assert_eq!(
        e.call(ACTIVATE, Some(&access), Json::Null).await,
        Err("InvalidToken".into())
    );
    e.call(DEACTIVATE, Some(&access), json!({})).await.unwrap();
    assert_eq!(
        e.call(REFRESH, Some(&down_refresh), Json::Null).await,
        Err("AccountTakedown".into())
    );
    assert_eq!(
        e.call(
            "com.atproto.server.deleteSession",
            Some(&down_refresh),
            Json::Null
        )
        .await,
        Ok(Json::Null)
    );
    // Lifted: the refresh tokens are expired; access tokens work until their `exp`.
    e.takedown(&did, false).await.unwrap();
    assert_eq!(
        e.call(REFRESH, Some(&refresh), Json::Null).await,
        Err("ExpiredToken".into())
    );
    assert_eq!(
        e.call(REFRESH, Some(&down_refresh), Json::Null).await,
        Err("ExpiredToken".into())
    );
    assert_eq!(
        e.call(GET_SESSION, Some(&token), Json::Null).await.unwrap()["status"],
        json!("deactivated")
    );
    // `allowTakendown` changes nothing for an account not taken down.
    let got = login("alice-pw", Some(true)).await.unwrap();
    assert_eq!(
        claims(got["accessJwt"].as_str().unwrap())["scope"],
        json!("com.atproto.access")
    );
}

/// Deleting an account: the token mailed, `deleteAccount`'s checks in
/// order, and an account gone with nothing left of it but its deletion's
/// event, its handle and email free; across a restart too.
#[tokio::test]
async fn deleting_an_account() {
    let mut e = Env::new("life-delete").await;
    let (did, token) = create(&e.s, "alice").await;
    let (bob_did, bob) = create(&e.s, "bob").await;
    let app = app_session(&e, &token, "alice.test").await;
    let (_, refresh) = tokens(
        &e.call(
            LOGIN,
            None,
            json!({ "identifier": "alice.test", "password": "alice-pw" }),
        )
        .await
        .unwrap(),
    );
    crate::blobs::test_upload(
        &e.s,
        Some(&token),
        Some("text/plain"),
        b"bytes".to_vec(),
        false,
    )
    .await
    .unwrap();
    e.call(
        "com.atproto.repo.putRecord",
        Some(&token),
        put(&did, "one", json!({ "n": 1 })),
    )
    .await
    .unwrap();
    e.call(
        "com.atproto.repo.putRecord",
        Some(&bob),
        put(&bob_did, "one", json!({ "n": 1 })),
    )
    .await
    .unwrap();
    e.call(DEACTIVATE, Some(&token), json!({})).await.unwrap();
    // requestAccountDelete: its token, its body, then the mail; deactivated, it may.
    assert_eq!(
        e.call(REQUEST_DELETE, Some(&app), Json::Null).await,
        Err("InvalidToken".into())
    );
    assert_eq!(
        e.call(REQUEST_DELETE, Some(&token), json!({})).await,
        Err("InvalidRequest".into())
    );
    e.call(REQUEST_DELETE, Some(&token), Json::Null)
        .await
        .unwrap();
    let old = last_token(&e.sink);
    e.call(REQUEST_DELETE, Some(&token), Json::Null)
        .await
        .unwrap();
    let mail = sent(&e.sink).pop().unwrap();
    assert_eq!(
        (&mail["to"], &mail["kind"]),
        (&json!("alice@mail.com"), &json!("deleteAccount"))
    );
    let tok = mail["token"].as_str().unwrap().to_string();
    // A token survives a restart.
    e.reopen();
    let del =
        |did: &str, pw: &str, token: &str| json!({ "did": did, "password": pw, "token": token });
    for (body, want) in [
        (
            json!({ "did": did, "password": "alice-pw" }),
            "InvalidRequest",
        ),
        (del("not-a-did", "alice-pw", &tok), "InvalidRequest"),
        (
            del(&did, &"x".repeat(513), "nonsense"),
            "AuthenticationRequired",
        ),
        (
            del("did:plc:aaaaaaaaaaaaaaaaaaaaaaaa", "alice-pw", &tok),
            "InvalidRequest",
        ),
        (del(&did, "wrong", &tok), "AuthenticationRequired"),
        (del(&did, "bob-pw", &tok), "AuthenticationRequired"),
        (del(&did, "alice-pw", &old), "InvalidToken"),
        (del(&did, "alice-pw", "AAAAA-AAAAA"), "InvalidToken"),
        (del(&bob_did, "bob-pw", &tok), "InvalidToken"),
    ] {
        assert_eq!(
            e.call(DELETE, None, body.clone()).await,
            Err(want.into()),
            "{body}"
        );
    }
    let events_before: Vec<Json> = e.events();
    let n = e.s.events.len();
    // An Authorization header is ignored; the token in lower case is taken.
    assert_eq!(
        call_raw(
            &e.s,
            DELETE,
            Bearer::of(Some("Garbage header here")),
            &[],
            &del(&did, "alice-pw", &tok.to_lowercase()).to_string()
        )
        .await,
        Ok(Json::Null)
    );
    // Nothing of it is left: its files, its account, its sessions, its events.
    assert!(!e.dir.join("repos").join(&did).exists());
    assert!(e.s.account(&did).is_none());
    assert!(!e.s.sessions.snapshot().contains_key(&did));
    let events = e.events();
    assert!(
        events
            .iter()
            .filter(|ev| ev["did"] == json!(did) || ev["repo"] == json!(did))
            .map(brief)
            .eq([format!("account {did} false deleted")])
    );
    let others: Vec<&Json> = events_before
        .iter()
        .filter(|ev| ev["did"] != json!(did) && ev["repo"] != json!(did))
        .collect();
    assert_eq!(
        events
            .iter()
            .filter(|ev| ev["did"] != json!(did))
            .collect::<Vec<_>>(),
        others
    );
    assert_eq!(events.last().unwrap()["seq"], json!(n + 1));
    // Every method answers it as deleted.
    let p = [("did", did.as_str())];
    assert_eq!(
        e.call(GET_SESSION, Some(&token), Json::Null).await,
        Err("InvalidRequest".into())
    );
    assert_eq!(
        e.call(
            "com.atproto.server.listAppPasswords",
            Some(&token),
            Json::Null
        )
        .await
        .unwrap(),
        json!({ "passwords": [] })
    );
    assert_eq!(
        e.call(
            "com.atproto.server.createAppPassword",
            Some(&token),
            json!({ "name": "x" })
        )
        .await,
        Err("AccountNotFound".into())
    );
    assert_eq!(
        e.call(
            "com.atproto.repo.putRecord",
            Some(&token),
            put(&did, "x", json!({}))
        )
        .await,
        Err("AccountNotFound".into())
    );
    assert_eq!(
        e.call(CHECK, Some(&token), Json::Null).await,
        Err("NotFound".into())
    );
    assert_eq!(
        e.call(DEACTIVATE, Some(&token), json!({})).await,
        Err("InvalidRequest".into())
    );
    assert_eq!(
        e.call(ACTIVATE, Some(&token), Json::Null).await,
        Err("InternalServerError".into())
    );
    assert_eq!(
        e.call(REQUEST_DELETE, Some(&token), Json::Null).await,
        Err("AccountNotFound".into())
    );
    assert_eq!(
        e.call(
            "com.atproto.identity.getRecommendedDidCredentials",
            Some(&token),
            Json::Null
        )
        .await,
        Err("InternalServerError".into())
    );
    assert_eq!(
        e.call(
            "com.atproto.server.deleteSession",
            Some(&refresh),
            Json::Null
        )
        .await,
        Ok(Json::Null)
    );
    assert_eq!(
        e.call(REFRESH, Some(&refresh), Json::Null).await,
        Err("InvalidRequest".into())
    );
    assert_eq!(
        crate::blobs::test_upload(&e.s, Some(&token), None, vec![1], false).await,
        Err((403, "AccountNotFound".into()))
    );
    assert_eq!(
        e.call(
            LOGIN,
            None,
            json!({ "identifier": "alice.test", "password": "alice-pw" })
        )
        .await,
        Err("AuthenticationRequired".into())
    );
    assert_eq!(
        e.query("com.atproto.sync.getRepoStatus", None, &p).await,
        Err("RepoNotFound".into())
    );
    assert_eq!(
        e.query("com.atproto.sync.getLatestCommit", Some(&token), &p)
            .await,
        Err("RepoNotFound".into())
    );
    assert_eq!(
        e.raw("com.atproto.sync.getRepo", &admin_header(), &p, "")
            .await,
        Err("RepoNotFound".into())
    );
    assert_eq!(
        e.query("com.atproto.repo.describeRepo", None, &[("repo", &did)])
            .await,
        Err("RepoNotFound".into())
    );
    assert_eq!(
        e.call(DELETE, None, del(&did, "alice-pw", &tok)).await,
        Err("InvalidRequest".into())
    );
    let listed = e
        .query("com.atproto.sync.listRepos", None, &[])
        .await
        .unwrap();
    assert_eq!(
        listed["repos"]
            .as_array()
            .unwrap()
            .iter()
            .map(|r| r["did"].clone())
            .collect::<Vec<_>>(),
        [json!(bob_did)]
    );
    assert_eq!(listed["cursor"], json!("2"));
    assert_eq!(
        e.admin_query(&[("did", &did)]).await,
        Err("NotFound".into())
    );
    // The same after a restart, the firehose too.
    let before = e.events();
    e.reopen();
    assert_eq!(e.events(), before);
    // Numbered on after every event given out, the deleted account's too.
    assert_eq!(*e.s.events.subscribe().borrow(), n as u64 + 1);
    assert!(e.s.account(&did).is_none());
    // Its handle and email are free: a new account takes them.
    let again = json!({ "handle": "alice.test", "email": "alice@mail.com", "password": "pw" });
    e.call("com.atproto.server.createAccount", None, again)
        .await
        .unwrap();
    let carol = json!({ "handle": "carol.test", "email": "carol@mail.com", "password": "pw" });
    e.call("com.atproto.server.createAccount", None, carol)
        .await
        .unwrap();
    // New events are numbered after every one given out.
    let last = e.events().pop().unwrap();
    assert!(last["seq"].as_u64().unwrap() > n as u64 + 1);
}

/// A subscriber live when an account is deleted has had its events, and
/// gets its deletion's after them; one begun after gets neither but the deletion's.
#[tokio::test]
async fn the_firehose_across_a_deletion() {
    let e = Env::new("life-firehose").await;
    let (did, token) = create(&e.s, "alice").await;
    create(&e.s, "bob").await;
    let live = e.s.events.drops();
    e.call(REQUEST_DELETE, Some(&token), Json::Null)
        .await
        .unwrap();
    e.call(
        DELETE,
        None,
        json!({ "did": did, "password": "alice-pw", "token": last_token(&e.sink) }),
    )
    .await
    .unwrap();
    let of = |drops: u64| -> Vec<String> {
        e.s.events
            .get(&e.s, 0, u64::MAX - 1, drops)
            .iter()
            .map(|f| brief(&decoded(f)))
            .filter(|b| b.contains(&did))
            .collect()
    };
    let all = of(live);
    assert_eq!(all.len(), 5);
    assert_eq!(all.last().unwrap(), &format!("account {did} false deleted"));
    assert_eq!(
        of(e.s.events.drops()),
        [format!("account {did} false deleted")]
    );
}

/// A deletion's entry, cut at every byte: the account is there with
/// everything it had, or gone with nothing of it served, its handle and
/// email free, its deletion on the firehose, and its files gone once the
/// directories of no account are swept.
#[tokio::test]
async fn a_deletion_cut_short() {
    for sync in SYNCS {
        syncing(sync);
        a_deletion_cut_short_once().await;
    }
}

async fn a_deletion_cut_short_once() {
    let e = Env::new("life-cut").await;
    let (did, token) = create(&e.s, "alice").await;
    create(&e.s, "bob").await;
    e.call(
        "com.atproto.repo.putRecord",
        Some(&token),
        put(&did, "one", json!({ "n": 1 })),
    )
    .await
    .unwrap();
    e.call(REQUEST_DELETE, Some(&token), Json::Null)
        .await
        .unwrap();
    let log = crate::log::accounts_log(&e.dir);
    let before = crate::log::log_bytes(&log);
    let repo = std::fs::read(crate::log::repo_log(&e.dir, &did)).unwrap();
    e.call(
        DELETE,
        None,
        json!({ "did": did, "password": "alice-pw", "token": last_token(&e.sink) }),
    )
    .await
    .unwrap();
    let after = crate::log::log_bytes(&log);
    assert!(after.len() > before.len() && after.starts_with(&before));
    let work = scratch("life-cut-work");
    for cut in before.len()..=after.len() {
        let _ = std::fs::remove_dir_all(&work);
        std::fs::create_dir_all(work.join("repos").join(&did)).unwrap();
        std::fs::copy(e.dir.join("jwt.key"), work.join("jwt.key")).unwrap();
        std::fs::write(crate::log::accounts_log(&work), &after[..cut]).unwrap();
        std::fs::write(crate::log::repo_log(&work, &did), &repo).unwrap();
        let bob = e.s.account("bob.test").unwrap().did.clone();
        let bob_dir = e.dir.join("repos").join(&bob);
        std::fs::create_dir_all(work.join("repos").join(&bob)).unwrap();
        std::fs::copy(
            bob_dir.join("repo.0.log"),
            work.join("repos").join(&bob).join("repo.0.log"),
        )
        .unwrap();
        let s = open(&work, &e.plc);
        s.sweep_repos();
        let gone = s.account(&did).is_none();
        assert_eq!(gone, cut == after.len(), "cut at {cut}");
        assert_eq!(
            work.join("repos").join(&did).exists(),
            !gone,
            "cut at {cut}"
        );
        let deletions = s
            .events
            .get(&s, 0, u64::MAX - 1, s.events.drops())
            .iter()
            .map(|f| decoded(f))
            .filter(|ev| ev["status"] == json!("deleted"))
            .count();
        assert_eq!(deletions, usize::from(gone), "cut at {cut}");
        let free = call(
            &s,
            "com.atproto.server.createAccount",
            None,
            json!({ "handle": "alice.test", "email": "alice@mail.com", "password": "pw" }),
        )
        .await;
        assert_eq!(free.is_ok(), gone, "cut at {cut}");
    }
    let _ = std::fs::remove_dir_all(&work);
}

/// The PLC directory cannot be read: `validDid` is `false`, the answer
/// `200`; an activation, by the owner or the admin, of an account or of a
/// DID no account has, is `502`, and a takedown lifted in the same call
/// stays lifted.
#[tokio::test]
async fn the_directory_down() {
    let mut e = Env::new("life-plc-down").await;
    let (did, token) = create(&e.s, "alice").await;
    e.call(DEACTIVATE, Some(&token), json!({})).await.unwrap();
    e.takedown(&did, true).await.unwrap();
    let plc = std::mem::replace(&mut e.plc, "http://127.0.0.1:1".into());
    e.reopen();
    let got = e.call(CHECK, Some(&token), Json::Null).await.unwrap();
    assert_eq!(
        (&got["validDid"], &got["activated"]),
        (&json!(false), &json!(false))
    );
    // The directory before the takedown.
    assert_eq!(
        e.call(ACTIVATE, Some(&token), Json::Null).await,
        Err("UpstreamFailure".into())
    );
    let before = e.events().len();
    let both = json!({ "subject": { "$type": REPO_REF, "did": did }, "takedown": { "applied": false }, "deactivated": { "applied": false } });
    assert_eq!(e.admin(UPDATE, both).await, Err("UpstreamFailure".into()));
    let state = e.admin_query(&[("did", &did)]).await.unwrap();
    assert_eq!(
        (&state["takedown"], &state["deactivated"]),
        (&json!({ "applied": false }), &json!({ "applied": true }))
    );
    assert_eq!(
        e.events()[before..].iter().map(brief).collect::<Vec<_>>(),
        [format!("account {did} false deactivated")]
    );
    let nobody = json!({ "subject": { "$type": REPO_REF, "did": "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa" }, "deactivated": { "applied": false } });
    assert_eq!(e.admin(UPDATE, nobody).await, Err("UpstreamFailure".into()));
    assert_eq!(e.events().len(), before + 1);
    // Deactivating reads no directory.
    e.call(DEACTIVATE, Some(&token), json!({})).await.unwrap();
    // Up again, it is activated.
    e.plc = plc;
    e.reopen();
    e.call(ACTIVATE, Some(&token), Json::Null).await.unwrap();
    assert_eq!(
        e.call(CHECK, Some(&token), Json::Null).await.unwrap()["validDid"],
        json!(true)
    );
}

/// A deleted account's activation, by its token or the admin: its token,
/// its body, then its DID document, whose rotation keys and endpoint are
/// looked at before its signing key, which is gone.
#[tokio::test]
async fn a_deleted_account_activated() {
    let e = Env::new("life-deleted-activate").await;
    let (did, token) = create(&e.s, "alice").await;
    let app = app_session(&e, &token, "alice.test").await;
    e.call(REQUEST_DELETE, Some(&token), Json::Null)
        .await
        .unwrap();
    e.call(
        DELETE,
        None,
        json!({ "did": did, "password": "alice-pw", "token": last_token(&e.sink) }),
    )
    .await
    .unwrap();
    let activate = json!({ "subject": { "$type": REPO_REF, "did": did }, "deactivated": { "applied": false } });
    assert_eq!(
        e.call(ACTIVATE, Some(&app), Json::Null).await,
        Err("InvalidToken".into())
    );
    assert_eq!(
        e.call(ACTIVATE, Some(&token), json!({})).await,
        Err("InvalidRequest".into())
    );
    // Its document still names this server.
    assert_eq!(
        e.call(ACTIVATE, Some(&token), Json::Null).await,
        Err("InternalServerError".into())
    );
    assert_eq!(
        e.admin(UPDATE, activate.clone()).await,
        Err("InternalServerError".into())
    );
    // Moved elsewhere.
    let moved = reqwest::Client::new()
        .put(format!("{}/{did}/data", e.plc))
        .body("https://elsewhere.example")
        .send()
        .await
        .unwrap();
    assert!(moved.status().is_success());
    assert_eq!(
        e.call(ACTIVATE, Some(&token), Json::Null).await,
        Err("InvalidRequest".into())
    );
    assert_eq!(
        e.admin(UPDATE, activate).await,
        Err("InvalidRequest".into())
    );
}

/// A record's `uri` that names no record, of an account here, taken down
/// or not: `updateSubjectStatus` takes down nothing, `getSubjectStatus` is
/// `400 NotFound`; a handle as its authority is `500` to both.
#[tokio::test]
async fn uris_naming_no_record() {
    let e = Env::new("life-uris").await;
    let (did, token) = create(&e.s, "alice").await;
    let rec = e
        .call(
            "com.atproto.repo.putRecord",
            Some(&token),
            put(&did, "one", json!({ "n": 1 })),
        )
        .await
        .unwrap();
    let strong = |uri: &str| json!({ "$type": STRONG_REF, "uri": uri, "cid": rec["cid"] });
    for down in [false, true] {
        e.takedown(&did, down).await.unwrap();
        for uri in [format!("at://{did}"), format!("at://{did}/a.b.c")] {
            let got = e
                .admin(
                    UPDATE,
                    json!({ "subject": strong(&uri), "takedown": { "applied": true, "ref": "x" } }),
                )
                .await
                .unwrap();
            assert_eq!(got["subject"]["uri"], json!(uri));
            assert_eq!(
                e.admin_query(&[("uri", &uri)]).await,
                Err("NotFound".into()),
                "{uri}"
            );
        }
        let status = e
            .admin_query(&[("uri", rec["uri"].as_str().unwrap())])
            .await
            .unwrap();
        assert_eq!(status["takedown"], json!({ "applied": false }));
    }
    for uri in [
        "at://alice.test/a.b.c/one",
        "at://nobody.test/a.b.c/one",
        "at://alice.test",
    ] {
        assert_eq!(
            e.admin_query(&[("uri", uri)]).await,
            Err("InternalServerError".into()),
            "{uri}"
        );
    }
    assert_eq!(
        e.admin_query(&[("uri", "at://did:plc:aaaaaaaaaaaaaaaaaaaaaaaa/a.b.c/one")])
            .await,
        Err("NotFound".into())
    );
}

/// The email methods, `getAccountInviteCodes` and the preferences, of an
/// account in each state: refused with the token, before the input, a
/// taken-down account `401 AccountTakedown` and a deleted one `403
/// AccountNotFound`, with no mail sent.
#[tokio::test]
async fn own_calls_by_state() {
    let e = Env::new("life-own-rows").await;
    let mut c = crate::Config {
        mailer: crate::email::Mailer::sink(&e.sink),
        ..config(&e.plc)
    };
    c.proxy.appview = Some(crate::proxy::AppView {
        url: "http://127.0.0.1:1".into(),
        did: "did:web:appview.test".into(),
    });
    let dir = scratch("life-own-rows-app");
    let s: Shared = Arc::new(Service::open(&dir, c).unwrap());
    let (did, token) = create(&s, "alice").await;
    let app = {
        let pw = call(
            &s,
            "com.atproto.server.createAppPassword",
            Some(&token),
            json!({ "name": "app" }),
        )
        .await
        .unwrap()["password"]
            .clone();
        tokens(
            &call(
                &s,
                LOGIN,
                None,
                json!({ "identifier": "alice.test", "password": pw }),
            )
            .await
            .unwrap(),
        )
        .0
    };
    /// A call: its method, its parameters and its input.
    type Row<'a> = (&'a str, &'a [(String, String)], Json);
    async fn rows(s: &Shared, token: &str) -> Vec<String> {
        let none: &[(String, String)] = &[];
        let bad = [("includeUsed".to_string(), "nope".to_string())];
        let calls: Vec<Row> = vec![
            (
                "com.atproto.server.requestEmailConfirmation",
                none,
                Json::Null,
            ),
            (
                "com.atproto.server.confirmEmail",
                none,
                json!({ "email": 5 }),
            ),
            ("com.atproto.server.requestEmailUpdate", none, Json::Null),
            (
                "com.atproto.server.updateEmail",
                none,
                json!({ "email": 5 }),
            ),
            ("com.atproto.server.getAccountInviteCodes", none, Json::Null),
            ("com.atproto.server.getAccountInviteCodes", &bad, Json::Null),
            ("app.bsky.actor.getPreferences", none, Json::Null),
            (
                "app.bsky.actor.putPreferences",
                none,
                json!({ "preferences": 5 }),
            ),
            (
                "app.bsky.actor.putPreferences",
                none,
                json!({ "preferences": [] }),
            ),
        ];
        let mut out = Vec::new();
        for (nsid, p, b) in calls {
            out.push(
                call_with(s, nsid, Some(token), p, b)
                    .await
                    .map_or_else(|x| x, |_| "ok".to_string()),
            );
        }
        out
    }
    let (inv, td, nf) = ("InvalidRequest", "AccountTakedown", "AccountNotFound");
    assert_eq!(
        rows(&s, &token).await,
        ["ok", inv, "ok", inv, "ok", inv, "ok", inv, "ok"]
    );
    call(&s, DEACTIVATE, Some(&token), json!({})).await.unwrap();
    assert_eq!(
        rows(&s, &token).await,
        ["ok", inv, "ok", inv, "NotFound", inv, "ok", inv, "ok"]
    );
    let mailed = sent(&e.sink).len();
    let takedown = json!({ "subject": { "$type": REPO_REF, "did": did }, "takedown": { "applied": true, "ref": "r" } });
    call_raw(
        &s,
        UPDATE,
        Bearer::of(Some(&admin_header())),
        &[],
        &takedown.to_string(),
    )
    .await
    .unwrap();
    assert_eq!(
        rows(&s, &token).await,
        [td, td, td, td, td, inv, "ok", td, td]
    );
    // The token's own checks first.
    for nsid in [
        "com.atproto.server.requestEmailUpdate",
        "com.atproto.server.getAccountInviteCodes",
    ] {
        assert_eq!(
            call(&s, nsid, Some(&app), Json::Null).await,
            Err("InvalidToken".into()),
            "{nsid}"
        );
    }
    // A takendown session's token works for getPreferences alone.
    let login =
        json!({ "identifier": "alice.test", "password": "alice-pw", "allowTakendown": true });
    let down = tokens(&call(&s, LOGIN, None, login).await.unwrap()).0;
    assert_eq!(
        call(&s, "app.bsky.actor.getPreferences", Some(&down), Json::Null).await,
        Ok(json!({ "preferences": [] }))
    );
    for nsid in [
        "app.bsky.actor.putPreferences",
        "com.atproto.server.requestEmailConfirmation",
    ] {
        assert_eq!(
            call(&s, nsid, Some(&down), json!({ "preferences": [] })).await,
            Err("InvalidToken".into()),
            "{nsid}"
        );
    }
    assert_eq!(sent(&e.sink).len(), mailed);
    // Deleted.
    let lift =
        json!({ "subject": { "$type": REPO_REF, "did": did }, "takedown": { "applied": false } });
    call_raw(
        &s,
        UPDATE,
        Bearer::of(Some(&admin_header())),
        &[],
        &lift.to_string(),
    )
    .await
    .unwrap();
    call(&s, REQUEST_DELETE, Some(&token), Json::Null)
        .await
        .unwrap();
    call(
        &s,
        DELETE,
        None,
        json!({ "did": did, "password": "alice-pw", "token": last_token(&e.sink) }),
    )
    .await
    .unwrap();
    let mailed = sent(&e.sink).len();
    assert_eq!(
        rows(&s, &token).await,
        [nf, nf, nf, nf, nf, inv, "NotFound", nf, nf]
    );
    assert_eq!(
        call(&s, "app.bsky.actor.getPreferences", Some(&down), Json::Null).await,
        Err("NotFound".into())
    );
    assert_eq!(sent(&e.sink).len(), mailed);
    let _ = std::fs::remove_dir_all(&dir);
}