~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
841 lines · 32.3 KB Raw History
//! The PLC directory: a new account's `did:plc`, by the genesis operation
//! `atproto/did-plc.md` describes, registered with the directory at
//! `PDS_PLC_URL` (`spec/ACCOUNTS.md`); and the update operations that change
//! an account's handle (`spec/IDENTITY.md`).

use crate::Config;
use crate::ops::Target;
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use k256::ecdsa::signature::hazmat::PrehashSigner;
use k256::ecdsa::{Signature, VerifyingKey};
use pds_repo::data::*;
use serde_json::Value as Json;
use sha2::{Digest, Sha256};

/// The multicodec of a secp256k1 public key, as a varint.
const SECP256K1_PUB: [u8; 2] = [0xe7, 0x01];

/// A secp256k1 public key as a `did:key`: its multicodec and compressed point, in base58btc.
pub fn did_key(key: &VerifyingKey) -> String {
    let mut bytes = SECP256K1_PUB.to_vec();
    bytes.extend_from_slice(key.to_sec1_point(true).as_bytes());
    format!("did:key:z{}", bs58::encode(bytes).into_string())
}

/// A signed genesis operation and the DID it makes.
pub struct Genesis {
    pub did: String,
    /// The signed operation, as JSON, as it is posted.
    pub op: Json,
}

/// The rotation keys of the DIDs the server creates: `PDS_RECOVERY_DID_KEY`
/// if set, then its own rotation key, each a `did:key`.
pub fn rotation_keys(config: &Config) -> Vec<String> {
    let rotation = did_key(config.rotation_key.verifying_key());
    let mut keys: Vec<String> = config
        .recovery_did_key
        .iter()
        .filter(|k| **k != rotation)
        .cloned()
        .collect();
    keys.push(rotation);
    keys
}

/// Sign an operation's fields with the server's rotation key: the DAG-CBOR
/// of the operation without `sig`, signed in low-S form, as base64url.
fn sign(config: &Config, mut fields: Vec<(String, V)>) -> V {
    let unsigned = encode(&V::Map(fields.clone()));
    let sig: Signature = config
        .rotation_key
        .sign_prehash(&Sha256::digest(&unsigned))
        .expect("signing a 32-byte digest");
    let sig = sig.normalize_s();
    fields.push((
        "sig".to_string(),
        V::Str(URL_SAFE_NO_PAD.encode(sig.to_bytes())),
    ));
    V::Map(fields)
}

/// The genesis operation of an account with this handle, signing key and
/// KEM key (`spec/SPACES.md`), signed with the server's rotation key.
pub fn genesis(
    config: &Config,
    signing: &VerifyingKey,
    kem: &pds_space::PublicKey,
    handle: &str,
) -> Genesis {
    let s = |x: &str| V::Str(x.to_string());
    let fields = vec![
        ("type".to_string(), s("plc_operation")),
        (
            "rotationKeys".to_string(),
            V::Arr(rotation_keys(config).iter().map(|k| s(k)).collect()),
        ),
        (
            "verificationMethods".to_string(),
            V::Map(vec![
                ("atproto".to_string(), s(&did_key(signing))),
                ("atproto_kem".to_string(), s(&kem.did_key())),
            ]),
        ),
        (
            "alsoKnownAs".to_string(),
            V::Arr(vec![s(&format!("at://{handle}"))]),
        ),
        (
            "services".to_string(),
            V::Map(vec![(
                "atproto_pds".to_string(),
                V::Map(vec![
                    ("type".to_string(), s("AtprotoPersonalDataServer")),
                    ("endpoint".to_string(), s(&config.public_url)),
                ]),
            )]),
        ),
        ("prev".to_string(), V::Null),
    ];
    let signed = sign(config, fields);
    Genesis {
        did: did_of(&encode(&signed)),
        op: to_json(&signed),
    }
}

/// The CID of an operation as the directory has it: of its DAG-CBOR, as
/// `atproto/did-plc.md` makes `prev`.
pub fn cid(op: &Json) -> Result<String, String> {
    Ok(cid_string(&cid_of(0x71, &encode(&from_json(op)?))))
}

/// The update operation that gives a DID `handle`, built on `last`, the
/// DID's last operation: its fields, with `prev` its CID and `alsoKnownAs`
/// changed and nothing else, its first `at://` entry `at://<handle>` (or,
/// with none, `at://<handle>` first); signed with the server's rotation key.
pub fn update(config: &Config, last: &Json, handle: &str) -> Result<Json, String> {
    if last["type"] != "plc_operation" {
        return Err(format!(
            "the DID's last operation is not a plc_operation: {last}"
        ));
    }
    let prev = cid(last)?;
    let V::Map(fields) = from_json(last)? else {
        return Err("an operation that is not an object".into());
    };
    let at = V::Str(format!("at://{handle}"));
    let mut out = Vec::with_capacity(fields.len());
    for (k, v) in fields {
        match (k.as_str(), v) {
            ("sig", _) => {}
            ("prev", _) => out.push((k, V::Str(prev.clone()))),
            ("alsoKnownAs", V::Arr(mut aka)) => {
                match aka
                    .iter()
                    .position(|u| matches!(u, V::Str(u) if u.starts_with("at://")))
                {
                    Some(i) => aka[i] = at.clone(),
                    None => aka.insert(0, at.clone()),
                }
                out.push((k, V::Arr(aka)));
            }
            ("alsoKnownAs", _) => {
                return Err(format!(
                    "an operation whose alsoKnownAs is not a list: {last}"
                ));
            }
            (_, v) => out.push((k, v)),
        }
    }
    if !out.iter().any(|(k, _)| k == "alsoKnownAs") {
        out.push(("alsoKnownAs".to_string(), V::Arr(vec![at])));
    }
    if !out.iter().any(|(k, _)| k == "prev") {
        out.push(("prev".to_string(), V::Str(prev)));
    }
    Ok(to_json(&sign(config, out)))
}

/// The fields of a DID's operation `signPlcOperation` may set (`spec/MIGRATION.md`).
pub const FIELDS: [&str; 4] = [
    "rotationKeys",
    "alsoKnownAs",
    "verificationMethods",
    "services",
];

/// The update operation built on `last`, the DID's last operation: its
/// fields, each of `FIELDS` `given`'s where it gives it, whole, with `prev`
/// its CID, signed with the server's rotation key.
pub fn update_with(
    config: &Config,
    last: &Json,
    given: &serde_json::Map<String, Json>,
) -> Result<Json, String> {
    let prev = cid(last)?;
    let V::Map(fields) = from_json(last)? else {
        return Err("an operation that is not an object".into());
    };
    let mut out: Vec<(String, V)> = fields
        .into_iter()
        .filter(|(k, _)| {
            k != "sig" && k != "prev" && !(FIELDS.contains(&k.as_str()) && given.contains_key(k))
        })
        .collect();
    for k in FIELDS {
        if let Some(v) = given.get(k) {
            out.push((k.to_string(), from_json(v)?));
        }
    }
    out.push(("prev".to_string(), V::Str(prev)));
    Ok(to_json(&sign(config, out)))
}

/// The DID a signed genesis operation, as DAG-CBOR, makes.
fn did_of(signed: &[u8]) -> String {
    format!("did:plc:{}", &base32_encode(&Sha256::digest(signed))[..24])
}

/// The HTTP client the server posts to the PLC directory with. It keeps no
/// idle connection: a server may close one it holds idle (Node's HTTP server
/// does after 5 seconds) just as the next request goes out on it, which then
/// fails, perhaps after the server has read it. Each post takes a
/// connection of its own, and none waits for ever (`spec/LIMITS.md`, "The
/// PLC directory").
pub fn client() -> reqwest::Result<reqwest::Client> {
    reqwest::Client::builder()
        .no_proxy()
        .pool_max_idle_per_host(0)
        .connect_timeout(std::time::Duration::from_secs(5))
        .timeout(std::time::Duration::from_secs(15))
        .build()
}

/// The HTTP client the server reads from the directory with: as `client`,
/// but keeping a connection unused for up to 90 seconds, so that a read
/// after another needs no new connection and TLS handshake. A read changes
/// nothing, so one that fails over a connection the directory closed is
/// sent again over one of its own (`document`). Built as `client` is, so it
/// fails only where that did first, and the server would not have started.
static READS: std::sync::LazyLock<reqwest::Result<reqwest::Client>> =
    std::sync::LazyLock::new(|| {
        reqwest::Client::builder()
            .no_proxy()
            .pool_idle_timeout(std::time::Duration::from_secs(90))
            .connect_timeout(std::time::Duration::from_secs(5))
            .timeout(std::time::Duration::from_secs(15))
            .build()
    });

/// The most requests to the directory in flight at once, of every kind.
const AT_ONCE: usize = 8;
/// How long a request waits for its turn before it is answered as if the
/// directory could not be reached.
const TURN_WAIT: std::time::Duration = std::time::Duration::from_secs(15);

static TURNS: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(AT_ONCE);

/// A request's turn to go to the directory, held while it is in flight.
async fn turn() -> Result<tokio::sync::SemaphorePermit<'static>, String> {
    match tokio::time::timeout(TURN_WAIT, TURNS.acquire()).await {
        Ok(Ok(p)) => Ok(p),
        _ => Err("the PLC directory has too many requests in flight".into()),
    }
}

/// The JSON the directory serves at `url`, or None if it serves none (404):
/// read over a connection kept from an earlier read, if one is open.
/// Reading changes nothing, so a read that failed on its way is sent once
/// more, with `http`, over a connection of its own.
pub(crate) async fn document(http: &reqwest::Client, url: &str) -> Result<Option<Json>, String> {
    let turn = turn().await?;
    let reads = READS.as_ref().unwrap_or(http);
    let res = match crate::ops::send(Target::Plc, reads.get(url)).await {
        Ok(res) => res,
        Err(e) if !e.is_timeout() => crate::ops::send(Target::Plc, http.get(url))
            .await
            .map_err(|e| format!("reading {url}: {e}"))?,
        Err(e) => return Err(format!("reading {url}: {e}")),
    };
    if res.status() == reqwest::StatusCode::NOT_FOUND {
        return Ok(None);
    }
    if !res.status().is_success() {
        return Err(format!("{url} answered {}", res.status()));
    }
    let bytes = res
        .bytes()
        .await
        .map_err(|e| format!("reading {url}: {e}"))?;
    drop(turn);
    serde_json::from_slice(&bytes)
        .map(Some)
        .map_err(|e| format!("the JSON at {url}: {e}"))
}

/// Why the directory did not take an update operation.
pub enum Upstream {
    /// It answered, refusing it, with this message.
    Refused(String),
    /// It could not be reached; `sent` if the request may have reached it.
    Unreachable { why: String, sent: bool },
}

fn url_of(plc_url: &str, did: &str) -> String {
    format!("{}/{did}", plc_url.trim_end_matches('/'))
}

/// The DID's last operation, as `GET <PLC>/<did>/log/last` answers it.
pub async fn last_operation(
    http: &reqwest::Client,
    plc_url: &str,
    did: &str,
) -> Result<Json, Upstream> {
    let url = format!("{}/log/last", url_of(plc_url, did));
    match document(http, &url).await {
        Ok(Some(op)) => Ok(op),
        Ok(None) => Err(Upstream::Refused(format!(
            "the directory has no operation for {did}"
        ))),
        Err(why) => Err(Upstream::Unreachable { why, sent: false }),
    }
}

/// Post an update operation for `did`.
pub async fn post(
    http: &reqwest::Client,
    plc_url: &str,
    did: &str,
    op: &Json,
) -> Result<(), Upstream> {
    let url = url_of(plc_url, did);
    let _turn = turn()
        .await
        .map_err(|why| Upstream::Unreachable { why, sent: false })?;
    match crate::ops::send(
        Target::Plc,
        http.post(&url)
            .header(reqwest::header::CONTENT_TYPE, "application/json")
            .body(op.to_string()),
    )
    .await
    {
        Ok(res) if res.status().is_success() => Ok(()),
        Ok(res) => {
            let status = res.status();
            let text = res.text().await.unwrap_or_default();
            // The directory says why as `{message}`.
            let message = serde_json::from_str::<Json>(&text)
                .ok()
                .and_then(|j| j["message"].as_str().map(str::to_string));
            Err(Upstream::Refused(
                message.unwrap_or_else(|| format!("{status} {text}")),
            ))
        }
        Err(e) => Err(Upstream::Unreachable {
            why: format!("posting to {url}: {e}"),
            sent: !e.is_connect(),
        }),
    }
}

/// Whether the directory's log of `did` holds the operation with this CID,
/// as `GET <PLC>/<did>/log/audit` lists them.
pub async fn holds(
    http: &reqwest::Client,
    plc_url: &str,
    did: &str,
    cid: &str,
) -> Result<bool, String> {
    let url = format!("{}/log/audit", url_of(plc_url, did));
    let log = document(http, &url).await?.unwrap_or_default();
    let entries = log
        .as_array()
        .ok_or_else(|| format!("{url} is not a list: {log}"))?;
    Ok(entries.iter().any(|e| e["cid"] == cid))
}

/// Register a genesis operation with the directory, and answer the DID
/// document it then serves for the DID.
///
/// A post that fails on its way may or may not have reached the directory.
/// The DID is the hash of this very operation, so no other operation can
/// have made it: a document served for it means the directory took this
/// one, and none means it has no operation for the DID, so posting this one
/// again is its first genesis, not a second.
pub async fn register(http: &reqwest::Client, plc_url: &str, g: &Genesis) -> Result<Json, String> {
    async fn refused(url: &str, res: reqwest::Response) -> Result<Json, String> {
        let status = res.status();
        Err(format!(
            "{url} refused the operation: {status} {}",
            res.text().await.unwrap_or_default()
        ))
    }
    let url = format!("{}/{}", plc_url.trim_end_matches('/'), g.did);
    // Each post in its turn, given up before the next request takes its own.
    let post = || async {
        let _turn = turn().await?;
        Ok::<_, String>(
            crate::ops::send(
                Target::Plc,
                http.post(&url)
                    .header(reqwest::header::CONTENT_TYPE, "application/json")
                    .body(g.op.to_string()),
            )
            .await,
        )
    };
    match post().await? {
        Ok(res) if res.status().is_success() => {}
        Ok(res) => return refused(&url, res).await,
        Err(e) => {
            crate::ops::failed_for(
                crate::ops::Level::Warn,
                "registering a DID failed, asking whether it was taken",
                &g.did,
                e,
            );
            if document(http, &url).await?.is_none() {
                match post().await? {
                    Ok(res) if res.status().is_success() => {}
                    Ok(res) => return refused(&url, res).await,
                    Err(e) => return Err(format!("posting to {url}: {e}")),
                }
            }
        }
    }
    document(http, &url)
        .await?
        .ok_or_else(|| format!("{url} serves no DID document for the operation it took"))
}

/// The public key of a secp256k1 `did:key`.
#[cfg(test)]
pub fn parse_did_key(k: &str) -> Option<VerifyingKey> {
    let bytes = bs58::decode(k.strip_prefix("did:key:z")?).into_vec().ok()?;
    VerifyingKey::from_sec1_bytes(bytes.strip_prefix(&SECP256K1_PUB[..])?).ok()
}

/// Check a genesis operation as a directory would: signed, in low-S form,
/// by one of its rotation keys, and making `did`.
#[cfg(test)]
pub fn verify(did: &str, op: &Json) -> Result<(), String> {
    if did_of(&encode(&from_json(op)?)) != did {
        return Err(format!("the operation does not make {did}"));
    }
    signer(op, &op["rotationKeys"]).map(|_| ())
}

/// Check an update operation as a directory would: its `prev` the CID of
/// `last`, and signed, in low-S form, by one of `last`'s rotation keys.
/// Answers the `did:key` that signed it.
#[cfg(test)]
pub fn verify_update(last: &Json, op: &Json) -> Result<String, String> {
    if op["prev"] != cid(last)? {
        return Err(format!(
            "prev is {}, not the CID of the last operation",
            op["prev"]
        ));
    }
    signer(op, &last["rotationKeys"])
}

/// An operation signed again with the server's rotation key, as a test
/// posts one of its own.
#[cfg(test)]
pub fn signed(config: &Config, op: &Json) -> Json {
    let V::Map(fields) = from_json(op).expect("an operation in the data model") else {
        panic!("an operation that is not an object")
    };
    to_json(&sign(
        config,
        fields.into_iter().filter(|(k, _)| k != "sig").collect(),
    ))
}

/// Which of `keys` signed `op`, as `atproto/did-plc.md` asks: the DAG-CBOR
/// of the operation without `sig`, and a low-S signature in base64url.
#[cfg(test)]
fn signer(op: &Json, keys: &Json) -> Result<String, String> {
    use k256::ecdsa::signature::hazmat::PrehashVerifier;
    let V::Map(mut fields) = from_json(op)? else {
        return Err("not an object".into());
    };
    let at = fields
        .iter()
        .position(|(k, _)| k == "sig")
        .ok_or("no sig")?;
    let V::Str(sig) = fields.remove(at).1 else {
        return Err("sig is not a string".into());
    };
    let sig = URL_SAFE_NO_PAD.decode(&sig).map_err(|e| e.to_string())?;
    let sig = Signature::from_slice(&sig).map_err(|e| e.to_string())?;
    if sig.normalize_s() != sig {
        return Err("a high-S signature".into());
    }
    let hash = Sha256::digest(encode(&V::Map(fields)));
    let keys = keys.as_array().ok_or("no rotationKeys")?;
    keys.iter()
        .filter_map(Json::as_str)
        .find(|k| parse_did_key(k).is_some_and(|key| key.verify_prehash(&hash, &sig).is_ok()))
        .map(str::to_string)
        .ok_or_else(|| "no rotation key signed it".into())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::testing::config;
    use k256::ecdsa::SigningKey;
    use serde_json::json;

    /// A fixed KEM key.
    fn kem() -> pds_space::PublicKey {
        pds_space::KemKey::from_bytes(&[4u8; 32]).unwrap().public()
    }

    /// `did:key`s as the interop vectors have them.
    #[test]
    fn did_keys() {
        let text = std::fs::read_to_string(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../spec/interop/crypto/w3c_didkey_K256.json"
        ))
        .unwrap();
        let vectors: Vec<Json> = serde_json::from_str(&text).unwrap();
        assert!(!vectors.is_empty());
        for v in vectors {
            let key = SigningKey::from_slice(
                &hex::decode(v["privateKeyBytesHex"].as_str().unwrap()).unwrap(),
            )
            .unwrap();
            assert_eq!(
                did_key(key.verifying_key()),
                v["publicDidKey"].as_str().unwrap()
            );
        }
    }

    /// No more than `AT_ONCE` requests are in flight to the directory, however
    /// many are asked for at once.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn few_requests_at_once() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicUsize, Ordering};
        type Counts = Arc<(AtomicUsize, AtomicUsize)>;
        async fn slow(axum::extract::State(c): axum::extract::State<Counts>) -> &'static str {
            let n = c.0.fetch_add(1, Ordering::SeqCst) + 1;
            c.1.fetch_max(n, Ordering::SeqCst);
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
            c.0.fetch_sub(1, Ordering::SeqCst);
            "{}"
        }
        let counts = Counts::default();
        let app = axum::Router::new()
            .route("/{did}", axum::routing::get(slow))
            .with_state(counts.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() });
        let http = client().unwrap();
        let asks: Vec<_> = (0..24)
            .map(|i| {
                let (http, url) = (http.clone(), format!("{url}/did{i}"));
                tokio::spawn(async move { document(&http, &url).await })
            })
            .collect();
        for a in asks {
            assert_eq!(a.await.unwrap().unwrap(), Some(json!({})));
        }
        let most = counts.1.load(Ordering::SeqCst);
        assert!((1..=AT_ONCE).contains(&most), "{most} at once");
    }

    /// A genesis operation as `atproto/did-plc.md` says, with fixed keys,
    /// the KEM key beside the signing key (`spec/SPACES.md`).
    #[test]
    fn genesis_operation() {
        let config = config("http://plc.invalid");
        let signing = SigningKey::from_slice(&[3u8; 32]).unwrap();
        let g = genesis(&config, signing.verifying_key(), &kem(), "alice.test");
        let rotation = did_key(config.rotation_key.verifying_key());
        let sig = g.op["sig"].as_str().unwrap().to_string();
        assert_eq!(
            g.op,
            json!({
                "type": "plc_operation",
                "rotationKeys": [config.recovery_did_key.clone().unwrap(), rotation],
                "verificationMethods": { "atproto": did_key(signing.verifying_key()), "atproto_kem": kem().did_key() },
                "alsoKnownAs": ["at://alice.test"],
                "services": { "atproto_pds": { "type": "AtprotoPersonalDataServer", "endpoint": "http://127.0.0.1:2583" } },
                "prev": null,
                "sig": sig,
            })
        );
        // The signature: 64 bytes, base64url without padding.
        assert_eq!(sig.len(), 86);
        assert!(
            sig.bytes()
                .all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_')
        );
        // The DID: 24 characters of base32, lower case, without 0, 1, 8 or 9.
        let id = g.did.strip_prefix("did:plc:").unwrap();
        assert_eq!(id.len(), 24);
        assert!(
            id.bytes()
                .all(|c| c.is_ascii_lowercase() || (b'2'..=b'7').contains(&c))
        );
        verify(&g.did, &g.op).unwrap();
        let kem_key = g.op["verificationMethods"]["atproto_kem"].as_str().unwrap();
        assert!(kem_key.starts_with("did:key:zDn"));
        assert_eq!(pds_space::PublicKey::from_did_key(kem_key).unwrap(), kem());
        // The same keys and handle make the same DID; signing is deterministic.
        assert_eq!(
            genesis(&config, signing.verifying_key(), &kem(), "alice.test").did,
            g.did
        );
        assert_ne!(
            genesis(&config, signing.verifying_key(), &kem(), "bob.test").did,
            g.did
        );
        let other_kem = pds_space::KemKey::from_bytes(&[5u8; 32]).unwrap().public();
        assert_ne!(
            genesis(&config, signing.verifying_key(), &other_kem, "alice.test").did,
            g.did
        );
        // Changing any field breaks it.
        let mut tampered = g.op.clone();
        tampered["alsoKnownAs"] = json!(["at://mallory.test"]);
        assert!(verify(&g.did, &tampered).is_err());
        // Without a recovery key, the server's own is the only rotation key.
        let mut alone = config;
        alone.recovery_did_key = None;
        assert_eq!(
            genesis(&alone, signing.verifying_key(), &kem(), "alice.test").op["rotationKeys"],
            json!([rotation])
        );
    }

    /// An update operation as `atproto/did-plc.md` says: the last
    /// operation's fields, `prev` its CID, `alsoKnownAs` changed and nothing
    /// else, signed by the server's rotation key.
    #[test]
    fn update_operation() {
        let config = config("http://plc.invalid");
        let signing = SigningKey::from_slice(&[3u8; 32]).unwrap();
        let g = genesis(&config, signing.verifying_key(), &kem(), "alice.test");
        let op = update(&config, &g.op, "carol.test").unwrap();
        // `prev`: CIDv1, dag-cbor, sha-256 of the last operation's DAG-CBOR, in base32.
        let prev = op["prev"].as_str().unwrap();
        let bytes = parse_cid(prev).unwrap();
        assert_eq!(bytes[..4], [1, 0x71, 0x12, 0x20]);
        assert_eq!(
            bytes[4..],
            Sha256::digest(encode(&from_json(&g.op).unwrap()))[..]
        );
        let mut want = g.op.clone();
        want["prev"] = json!(prev);
        want["alsoKnownAs"] = json!(["at://carol.test"]);
        want["sig"] = op["sig"].clone();
        assert_eq!(op, want);
        assert_eq!(
            verify_update(&g.op, &op).unwrap(),
            did_key(config.rotation_key.verifying_key())
        );
        // Built on it again, `prev` is its CID; a change to any field breaks the signature.
        let next = update(&config, &op, "dave.test").unwrap();
        assert_eq!(next["prev"], json!(cid(&op).unwrap()));
        verify_update(&op, &next).unwrap();
        assert!(verify_update(&g.op, &next).is_err());
        let mut tampered = op.clone();
        tampered["services"]["atproto_pds"]["endpoint"] = json!("https://elsewhere.test");
        assert!(verify_update(&g.op, &tampered).is_err());
        // The first `at://` entry changes, wherever it is; with none, one goes first.
        for (aka, after) in [
            (
                json!(["at://alice.test", "https://alice.example.com"]),
                json!(["at://carol.test", "https://alice.example.com"]),
            ),
            (
                json!([
                    "https://alice.example.com",
                    "at://alice.test",
                    "at://old.test"
                ]),
                json!([
                    "https://alice.example.com",
                    "at://carol.test",
                    "at://old.test"
                ]),
            ),
            (
                json!(["https://alice.example.com"]),
                json!(["at://carol.test", "https://alice.example.com"]),
            ),
            (json!([]), json!(["at://carol.test"])),
        ] {
            let mut last = g.op.clone();
            last["alsoKnownAs"] = aka;
            last["prev"] = json!(cid(&g.op).unwrap());
            let op = update(&config, &last, "carol.test").unwrap();
            assert_eq!(op["alsoKnownAs"], after);
            assert_eq!(op["rotationKeys"], last["rotationKeys"]);
            assert_eq!(op["verificationMethods"], last["verificationMethods"]);
            assert_eq!(op["services"], last["services"]);
            assert_eq!(op["prev"], json!(cid(&last).unwrap()));
        }
        // A tombstone cannot be built on.
        assert!(
            update(
                &config,
                &json!({ "type": "plc_tombstone", "prev": prev, "sig": "x" }),
                "carol.test"
            )
            .is_err()
        );
    }

    /// How the stub directory loses the first operation posted to it.
    #[derive(Clone, Copy, PartialEq)]
    enum Lose {
        Nothing,
        /// It closes the connection having read the post, before taking it.
        Request,
        /// It takes the operation, then closes the connection unanswered.
        Answer,
    }

    /// A directory that, like a server closing a connection it held idle just
    /// as a request arrives on it, answers only the first request on each
    /// connection and closes it on reading the next. It takes any operation,
    /// serving `{id}` as its DID's document. Answers its URL.
    async fn closing_plc(lose: Lose) -> String {
        use std::collections::HashMap;
        use std::sync::{Arc, Mutex};
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0))
            .await
            .unwrap();
        let url = format!("http://{}", listener.local_addr().unwrap());
        let ops: Arc<Mutex<(HashMap<String, Json>, bool)>> = Arc::default();
        tokio::spawn(async move {
            loop {
                let (mut conn, _) = listener.accept().await.unwrap();
                let ops = ops.clone();
                tokio::spawn(async move {
                    let mut buf = Vec::new();
                    for served in 0.. {
                        // Read one request: its head, then a body as long as it says.
                        let head_end = loop {
                            if let Some(i) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
                                break i + 4;
                            }
                            let mut chunk = [0u8; 4096];
                            match conn.read(&mut chunk).await {
                                Ok(0) | Err(_) => return,
                                Ok(n) => buf.extend_from_slice(&chunk[..n]),
                            }
                        };
                        let head = String::from_utf8_lossy(&buf[..head_end]).to_lowercase();
                        let len = head
                            .lines()
                            .find_map(|l| l.strip_prefix("content-length:"))
                            .map_or(0, |n| n.trim().parse().unwrap());
                        while buf.len() < head_end + len {
                            let mut chunk = [0u8; 4096];
                            match conn.read(&mut chunk).await {
                                Ok(0) | Err(_) => return,
                                Ok(n) => buf.extend_from_slice(&chunk[..n]),
                            }
                        }
                        let body: Vec<u8> = buf.drain(..head_end + len).skip(head_end).collect();
                        if served > 0 {
                            return;
                        }
                        let did = head
                            .split_whitespace()
                            .nth(1)
                            .unwrap()
                            .trim_start_matches('/')
                            .to_string();
                        let answer = if head.starts_with("post") {
                            let mut ops = ops.lock().unwrap();
                            let first = !std::mem::replace(&mut ops.1, true);
                            if first && lose == Lose::Request {
                                return;
                            }
                            ops.0.insert(did, serde_json::from_slice(&body).unwrap());
                            if first && lose == Lose::Answer {
                                return;
                            }
                            "HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: keep-alive\r\n\r\n"
                                .to_string()
                        } else if ops.lock().unwrap().0.contains_key(&did) {
                            let doc = json!({ "id": did }).to_string();
                            format!(
                                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: keep-alive\r\n\r\n{doc}",
                                doc.len()
                            )
                        } else {
                            "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: keep-alive\r\n\r\n".to_string()
                        };
                        if conn.write_all(answer.as_bytes()).await.is_err() {
                            return;
                        }
                    }
                });
            }
        });
        url
    }

    fn op(handle: &str) -> Genesis {
        genesis(
            &config("http://plc.invalid"),
            SigningKey::from_slice(&[3u8; 32]).unwrap().verifying_key(),
            &kem(),
            handle,
        )
    }

    /// A pooled connection the directory closes as the next request arrives
    /// fails that request; the server's client keeps none, so requests and
    /// registrations one after another each succeed.
    #[tokio::test]
    async fn no_idle_connection_is_reused() {
        let plc = closing_plc(Lose::Nothing).await;
        let url = format!("{plc}/did:plc:nobody");
        let pooled = reqwest::Client::builder().no_proxy().build().unwrap();
        assert_eq!(pooled.get(&url).send().await.unwrap().status(), 404);
        let e = pooled.get(&url).send().await.unwrap_err();
        assert!(!e.is_timeout() && !e.is_connect(), "{e:?}");
        let http = client().unwrap();
        for _ in 0..3 {
            assert_eq!(http.get(&url).send().await.unwrap().status(), 404);
        }
        for h in ["a.test", "b.test", "c.test"] {
            let g = op(h);
            assert_eq!(
                register(&http, &plc, &g).await.unwrap(),
                json!({ "id": g.did })
            );
        }
    }

    /// A post lost on its way is found taken, or posted again if it was not.
    #[tokio::test]
    async fn a_lost_post_is_settled() {
        for lose in [Lose::Request, Lose::Answer] {
            let plc = closing_plc(lose).await;
            let g = op("lost.test");
            assert_eq!(
                register(&client().unwrap(), &plc, &g).await.unwrap(),
                json!({ "id": g.did })
            );
        }
    }
}