~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
1227 lines · 43.8 KB Raw History
//! The server, its accounts and their sessions: `describeServer`,
//! `createAccount`, `createSession` and `getSession`, as `spec/ACCOUNTS.md`
//! says, with the invite codes and the bounds of `spec/LIMITS.md`.

use crate::invites::{Held as HeldCode, Invites};
use crate::log::{self, AccountEntry};
use crate::{
    Account, Call, Handler, Resp, Service, Shared, Shown, XrpcError, durable, email, err, input,
    internal, invalid, opt, read, required, write,
};
use serde_json::{Map, Value as Json, json};
use std::sync::Arc;

pub(crate) fn handler(nsid: &str) -> Option<Handler> {
    Some(match nsid {
        "com.atproto.server.describeServer" => Handler::Query(describe_server),
        "com.atproto.server.getSession" => Handler::Query(get_session),
        "com.atproto.server.createSession" => {
            Handler::Procedure(|s, b| Box::pin(create_session(s, b)))
        }
        "com.atproto.server.createAccount" => {
            Handler::Call(|s, c, m| Box::pin(create_account_call(s, c, m)))
        }
        _ => return None,
    })
}

fn describe_server(
    s: &Service,
    _: &Call,
    _: &mut Shown,
    _: &Map<String, Json>,
) -> Result<Resp, XrpcError> {
    Ok(Resp::Json(json!({
        "did": format!("did:web:{}", s.config.hostname),
        "availableUserDomains": s.config.handle_domains,
        "inviteCodeRequired": s.config.invite_required,
        "blobUploadLimit": s.config.blob_upload_limit,
        "spacesAlpha": true,
    })))
}

/// A session's account, as `getSession`, `createSession` and `refreshSession`
/// answer it: `active`, or not and its status (`spec/LIFECYCLE.md`).
pub(crate) fn session_json(a: &Account) -> Json {
    let m = email::lock(&a.mail);
    let status = crate::lifecycle::status(a);
    let mut out = json!({ "did": a.did, "handle": a.handle(), "emailConfirmed": m.confirmed, "emailAuthFactor": m.auth_factor, "active": status.is_none() });
    if let Some(e) = &m.email {
        out["email"] = json!(e);
    }
    if let Some(st) = status {
        out["status"] = json!(st);
    }
    out
}

/// An OAuth session's answer has the email only if its scope allows reading it.
fn get_session(
    s: &Service,
    call: &Call,
    _: &mut Shown,
    _: &Map<String, Json>,
) -> Result<Resp, XrpcError> {
    let did = s.auth(call.bearer).did()?;
    let Some(a) = s.account(&did) else {
        return internal();
    };
    let mut out = session_json(&a);
    if let (false, Some(o)) = (crate::scopes::reads_email(call.bearer), out.as_object_mut()) {
        for k in ["email", "emailConfirmed", "emailAuthFactor"] {
            o.remove(k);
        }
    }
    Ok(Resp::Json(out))
}

/// The account an identifier names: a DID, or a handle or email in any case.
pub(crate) fn login(s: &Service, id: &str) -> Option<Arc<Account>> {
    if id.starts_with("did:") {
        return s.account(id);
    }
    let id = id.to_lowercase();
    s.by_email(&id).or_else(|| s.by_handle(&id))
}

/// `createSession`: the account's password, then its app passwords, exactly
/// as given; then the code its email factor asks for (`spec/EMAIL.md`). It
/// answers no sooner than `login_floor` after its input was checked,
/// whatever it answers.
async fn create_session(s: Shared, b: Map<String, Json>) -> Result<Resp, XrpcError> {
    let floor = tokio::time::Instant::now() + s.config.login_floor;
    let answer = start_session(&s, &b).await;
    tokio::time::sleep_until(floor).await;
    answer
}

async fn start_session(s: &Shared, b: &Map<String, Json>) -> Result<Resp, XrpcError> {
    let refuse = || {
        err(
            401,
            "AuthenticationRequired",
            "Invalid identifier or password",
        )
    };
    let (id, pw) = (
        required(b, "identifier")?,
        required(b, "password")?.to_string(),
    );
    // The empty code is none.
    let code = opt(b, "authFactorToken").filter(|c| !c.is_empty());
    let a = login(s, id);
    let (own, digest) = check_password(s, a.as_deref(), &pw).await;
    let Some(a) = a else { return refuse() };
    if read(&a.state).takedown.is_some() {
        // A taken-down account takes its own password alone, and only with
        // `allowTakendown`: a session that is not kept, of tokens that work
        // for little (`spec/LIFECYCLE.md`).
        if own.is_none() || email::lock(&a.mail).password != own {
            return refuse();
        }
        if b.get("allowTakendown").and_then(Json::as_bool) != Some(true) {
            return err(401, "AccountTakedown", "Account has been taken down");
        }
        let (access, refresh) = s.sessions.takendown_tokens(&a.did);
        let mut out = session_json(&a);
        out["accessJwt"] = json!(access);
        out["refreshJwt"] = json!(refresh);
        return Ok(Resp::Json(out));
    }
    let (access, refresh, n) = email::start_session(s, &a, &digest, own, code).await?;
    durable(s.log.clone(), n).await?;
    let mut out = session_json(&a);
    out["accessJwt"] = json!(access);
    out["refreshJwt"] = json!(refresh);
    Ok(Resp::Json(out))
}

/// The hashes `createSession` and OAuth's sign-in compute for a password
/// given for the account `a` (`spec/LIMITS.md`, "Passwords"): the same
/// whoever the identifier names, or none, the scrypt of the account's
/// password, or of none, on the hash threads, then one digest for its app
/// passwords. Answers the hash of the account's password if `pw` is that
/// password, and the digest.
pub(crate) async fn check_password(
    s: &Service,
    a: Option<&Account>,
    pw: &str,
) -> (Option<String>, [u8; 32]) {
    let stored = a.and_then(|a| email::lock(&a.mail).password.clone());
    let (given, own) = (pw.to_string(), stored.clone());
    let full = s
        .limits
        .hashes
        .run(move || password::verify_or_none(&given, stored.as_deref()))
        .await
        .unwrap_or(false);
    (
        own.filter(|_| full),
        crate::sessions::app_password_digest(pw),
    )
}

/// The top-level domains `atproto/handle.md` disallows.
const DISALLOWED_TLDS: &[&str] = &[
    "alt",
    "arpa",
    "example",
    "internal",
    "invalid",
    "local",
    "localhost",
    "onion",
];

/// The labels no handle may have before its domain.
static RESERVED: std::sync::LazyLock<std::collections::HashSet<&'static str>> =
    std::sync::LazyLock::new(|| {
        include_str!("../../../spec/data/reserved-handles.txt")
            .lines()
            .map(str::trim)
            .filter(|l| !l.is_empty())
            .collect()
    });

/// A lowercased handle, as `createAccount` checks it once the lexicon has,
/// and `updateHandle` too; `external` when a handle outside the server's
/// domains is an external one, as with `createAccount`'s `did`, and always
/// for `updateHandle`. Answers whether it is such an external one, which
/// the caller must then see resolve to the account's DID
/// (`identity::handle_resolves_to`), else answer `400 InvalidRequest`.
pub(crate) fn check_handle(s: &Service, handle: &str, external: bool) -> Result<bool, XrpcError> {
    let invalid_handle = |why: &str| err(400, "InvalidHandle", why);
    if handle
        .rsplit('.')
        .next()
        .is_some_and(|tld| DISALLOWED_TLDS.contains(&tld))
    {
        return invalid_handle("Handle TLD is invalid or disallowed");
    }
    // The longest domain it ends in, should one be within another.
    let Some(domain) = s
        .config
        .handle_domains
        .iter()
        .filter(|d| handle.ends_with(d.as_str()))
        .max_by_key(|d| d.len())
    else {
        if external {
            return Ok(true);
        }
        return err(400, "UnsupportedDomain", "Not a supported handle domain");
    };
    let front = &handle[..handle.len() - domain.len()];
    if front.contains('.') {
        return invalid_handle("Invalid characters in handle");
    }
    if front.len() < 3 {
        return invalid_handle("Handle too short");
    }
    if front.len() > 18 {
        return invalid_handle("Handle too long");
    }
    if RESERVED.contains(front) {
        return err(400, "HandleNotAvailable", "Reserved handle");
    }
    Ok(false)
}

/// Whether an email is an address as `createAccount` takes one: a local
/// part of at most 64 characters, dot-separated runs of letters (any
/// script), digits and ``!#$%&'*+/=?^_`{|}~-``; `@`; and a domain of two or
/// more dot-separated labels of 1 to 63 letters, digits or hyphens, not
/// starting with a hyphen, the last not all digits.
pub(crate) fn valid_email(e: &str) -> bool {
    let Some((local, domain)) = e.split_once('@') else {
        return false;
    };
    let letter_or_digit = |c: char| c.is_alphabetic() || c.is_ascii_digit();
    let run = |r: &str| {
        !r.is_empty()
            && r.chars()
                .all(|c| letter_or_digit(c) || "!#$%&'*+/=?^_`{|}~-".contains(c))
    };
    let label = |l: &str| {
        let n = l.chars().count();
        (1..=63).contains(&n)
            && !l.starts_with('-')
            && l.chars().all(|c| letter_or_digit(c) || c == '-')
    };
    let labels: Vec<&str> = domain.split('.').collect();
    local.chars().count() <= 64
        && local.split('.').all(run)
        && labels.len() >= 2
        && labels.iter().all(|l| label(l))
        && labels
            .last()
            .is_some_and(|t| !t.chars().all(|c| c.is_ascii_digit()))
}

/// A password's length as `createAccount` counts it: in UTF-16 code units, as JavaScript does.
pub(crate) fn password_length(p: &str) -> usize {
    p.encode_utf16().count()
}

/// A handle, the email of an account with a password, and the DID of one
/// moving here, held for an account being created, so that no other takes
/// them meanwhile; let go when it is dropped.
struct Claim {
    s: Shared,
    handle: String,
    email: Option<String>,
    /// The account's DID, once it has one, its own or the one it moves here
    /// with: its directory in `repos/` is its own while it is being made
    /// (`directory`).
    did: Option<String>,
}

impl Drop for Claim {
    fn drop(&mut self) {
        let mut d = write(&self.s.directory);
        d.claimed_handles.remove(&self.handle);
        if let Some(e) = &self.email {
            d.claimed_emails.remove(e);
        }
        if let Some(did) = &self.did {
            d.made(did);
            d.claimed_dids.remove(did);
        }
    }
}

fn invalid_code<T>() -> Result<T, XrpcError> {
    err(
        400,
        "InvalidInviteCode",
        "Provided invite code not available",
    )
}

/// A use of an invite code, held for the account being created.
fn hold_code(s: &Shared, code: &str) -> Result<HeldCode, XrpcError> {
    Invites::hold(s, code).map_or_else(invalid_code, Ok)
}

/// `createAccount`: its `Authorization`, a service token by which an account
/// moves here (`spec/MIGRATION.md`), before its input; it pays its rate
/// limits once both are checked.
async fn create_account_call(
    s: &Shared,
    call: &Call<'_>,
    m: &'static pds_lexicon::Method,
) -> Result<Resp, XrpcError> {
    let caller = crate::migration::service_caller(s, call).await?;
    let b = input(call, m)?;
    crate::limits::guard(s, call, None, Some(&b))?;
    crate::ops::spawn(create_account(s.clone(), b, caller))
        .await
        .unwrap_or_else(|_| internal())
}

#[cfg(test)]
std::thread_local! {
    /// Whether the next `createAccount` on this thread is undone once its
    /// log is durable, as a failure after it undoes one.
    pub(crate) static UNDO_NEXT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// `caller` is the `iss` of the service token the call came with, if any.
async fn create_account(
    s: Shared,
    b: Map<String, Json>,
    caller: Option<String>,
) -> Result<Resp, XrpcError> {
    if b.contains_key("plcOp") {
        return invalid("Unsupported input: \"plcOp\"");
    }
    let password = opt(&b, "password");
    if password.is_some_and(|p| password_length(p) > 256) {
        return invalid("Password too long");
    }
    // An empty password is none, and so is an empty code.
    let password = password.filter(|p| !p.is_empty()).map(str::to_string);
    let code = opt(&b, "inviteCode").filter(|c| !c.is_empty());
    let required_code = s.config.invite_required;
    if required_code && code.is_none() {
        return invalid_code();
    }
    let Some(email) = opt(&b, "email") else {
        return invalid("Email is required");
    };
    if !valid_email(email) {
        return invalid("This email address is not supported, please use a different email.");
    }
    let email = email.to_lowercase();
    let handle = required(&b, "handle")?.to_lowercase();
    // An account moving here keeps its DID (`spec/MIGRATION.md`).
    let moving = opt(&b, "did").map(str::to_string);
    if let Some(did) = &moving
        && check_handle(&s, &handle, true)?
        && !crate::identity::handle_resolves_to(&s, &handle, did).await
    {
        return invalid("External handle did not resolve to DID");
    }
    if moving.is_none() {
        check_handle(&s, &handle, false)?;
    }
    // Required, the code is checked here; else after everything else.
    let mut held = match code.filter(|_| required_code) {
        Some(c) => Some(hold_code(&s, c)?),
        None => None,
    };
    // The accounts not loaded that may have the handle or the email are
    // loaded first: then those loaded say whether each is taken.
    s.load_hinted(crate::compact::HANDLE, &handle);
    s.load_hinted(crate::compact::EMAIL, &email);
    // And the account of the DID moving here, if it is one already.
    if let Some(did) = &moving {
        s.by_did(did);
    }
    let mut claim = {
        let mut d = write(&s.directory);
        if d.handles.contains_key(&handle) || d.claimed_handles.contains(&handle) {
            return invalid(format!("Handle already taken: {handle}"));
        }
        if d.emails.contains_key(&email) || d.claimed_emails.contains(&email) {
            return invalid(format!("Email already taken: {email}"));
        }
        if let Some(did) = &moving {
            if caller.as_deref() != Some(did.as_str()) {
                return err(
                    401,
                    "AuthenticationRequired",
                    "Missing auth to create account with did",
                );
            }
            let web = crate::identity::is_web(did)
                && pds_repo::data::valid_did(did)
                && crate::outbound::atproto_did_web(did);
            if !did.starts_with("did:plc:") && !web {
                return invalid("Only did:plc and did:web accounts may move here");
            }
            if d.by_did.contains_key(did) || d.claimed_dids.contains(did) {
                return err(400, "AlreadyExists", "Repo already exists");
            }
        }
        if let Some(c) = code.filter(|_| !required_code) {
            held = Some(hold_code(&s, c)?);
        }
        d.claimed_handles.insert(handle.clone());
        // An account without a password keeps no email, so takes none from others.
        let email = password.is_some().then_some(email);
        if let Some(e) = &email {
            d.claimed_emails.insert(e.clone());
        }
        if let Some(did) = &moving {
            d.claimed_dids.insert(did.clone());
        }
        Claim {
            s: s.clone(),
            handle: handle.clone(),
            email,
            did: moving.clone(),
        }
    };
    let password = match password {
        Some(p) => Some(
            s.limits
                .hashes
                .run(move || password::hash(&p))
                .await
                .map_or_else(internal, Ok)?,
        ),
        None => None,
    };
    let key = <k256::ecdsa::SigningKey as k256::elliptic_curve::Generate>::generate();
    let kem = pds_space::KemKey::generate();
    let (did, did_doc) = match &moving {
        // Its DID is its own already: no operation goes to the directory, and
        // its document is the one the directory, or a `did:web`'s host, serves
        // for it now; a `did:web`'s as the service token's check read it.
        Some(did) if crate::identity::is_web(did) => {
            let life = std::time::Duration::from_secs(s.config.did_cache);
            match crate::proxy::resolve_did_within(&s, did, life).await {
                Ok(doc) => (did.clone(), Json::clone(&doc)),
                Err(e) => {
                    crate::ops::failed_for(
                        crate::ops::Level::Warn,
                        "createAccount failed",
                        did,
                        e.message,
                    );
                    return internal();
                }
            }
        }
        Some(did) => {
            let url = format!("{}/{did}", s.config.plc_url.trim_end_matches('/'));
            match crate::plc::document(&s.http, &url).await {
                Ok(Some(doc)) => (did.clone(), doc),
                Ok(None) => {
                    crate::ops::failed_for(
                        crate::ops::Level::Warn,
                        "createAccount failed",
                        did,
                        "no document at the PLC directory",
                    );
                    return internal();
                }
                Err(why) => {
                    crate::ops::failed_for(
                        crate::ops::Level::Warn,
                        "createAccount failed",
                        did,
                        why,
                    );
                    return internal();
                }
            }
        }
        None => {
            let genesis =
                crate::plc::genesis(&s.config, key.verifying_key(), &kem.public(), &handle);
            match crate::plc::register(&s.http, &s.config.plc_url, &genesis).await {
                Ok(doc) => (genesis.did, doc),
                Err(why) => {
                    crate::ops::failed_for(
                        crate::ops::Level::Warn,
                        "createAccount failed",
                        &genesis.did,
                        why,
                    );
                    return internal();
                }
            }
        }
    };
    write(&s.directory).making(&did);
    claim.did = Some(did.clone());
    // The account's log, with its repository's first commit, is on disk
    // before anything of the account is in `accounts.log`: should it fail,
    // the account is not made, then or after a restart.
    let account_dir = s.dir.join("repos").join(&did);
    // Its files go as a deletion's do: the journal forgets the directory,
    // durably, first, so that the same DID made again, as a move here
    // tried again makes it, never has what the journal held of these
    // files written into its own. If it cannot, the directory stays, for a
    // start to remove as one of no account.
    let undo = |why: String| {
        crate::ops::failed_for(crate::ops::Level::Error, "createAccount failed", &did, why);
        let forgotten = s
            .ctx
            .files
            .journal()
            .map_or(Ok(()), |j| j.forget(&account_dir));
        match forgotten {
            Ok(()) => {
                let _ = std::fs::remove_dir_all(&account_dir);
            }
            Err(e) => crate::ops::failed_for(
                crate::ops::Level::Error,
                "createAccount failed",
                &did,
                format!("{}: {e}", account_dir.display()),
            ),
        }
        internal()
    };
    let opening = (s.ctx.clone(), did.clone(), key.clone());
    let mut store = match tokio::task::spawn_blocking(move || {
        log::new_repo(&opening.0, &opening.1, &opening.2)
    })
    .await
    {
        Ok(Ok(store)) => store,
        Ok(Err(e)) => return undo(e.to_string()),
        Err(e) => return undo(e.to_string()),
    };
    // An account moving here is made deactivated, with nothing on the firehose.
    let landing = match log::first_commit(&s.events, &did, &handle, &mut store, moving.is_some()) {
        Ok(l) => l,
        Err(e) => return undo(e.to_string()),
    };
    let unland = |landing: &Option<crate::events::Landing>| {
        if let Some(l) = landing {
            s.events.fail(l.seq, l.frames.len());
        }
    };
    if Shown::after(
        landing.as_ref(),
        vec![(store.wal.clone(), store.wal.written())],
    )
    .durable()
    .await
    .is_err()
    {
        unland(&landing);
        return undo("its log could not be synced".into());
    }
    let at = crate::events::timestamp();
    #[cfg(test)]
    if UNDO_NEXT.with(|u| u.replace(false)) {
        unland(&landing);
        drop(store);
        return undo("undone, as a test has it".into());
    }
    let entry = AccountEntry {
        did: did.clone(),
        handle: handle.clone(),
        email: claim.email.clone(),
        password,
        key: crate::cache::Key::made(key),
        kem: Some(kem),
        did_doc: did_doc.to_string().into(),
    };
    let started = {
        // Logged under the directory's lock, so that the accounts' ordinals,
        // the order `listRepos` lists them in, are in the order
        // `accounts.log` has them.
        let mut d = write(&s.directory);
        let mut before = vec![entry.entry()];
        if moving.is_some() {
            before.push(crate::lifecycle::deactivated_entry(&did, true));
        }
        before.extend(held.as_ref().map(|h| h.entry(&did, &at)));
        let started = s.sessions.start(&s.log, &did, None, before);
        if let Ok(Some(_)) = started {
            d.logged(&did);
            if let Some(h) = held.take() {
                h.used(&did, &at);
            }
        }
        started
    };
    let (access, refresh, n) = match started {
        Ok(Some(x)) => x,
        Ok(None) => unreachable!("a session made with the account's password"),
        Err(e) => {
            unland(&landing);
            drop(store);
            return undo(format!("{}: {e}", log::ACCOUNTS_LOG));
        }
    };
    let synced = durable(s.log.clone(), n).await;
    let doc: Json = serde_json::from_str(&entry.did_doc).unwrap_or(Json::Null);
    let account = entry.account(
        Some(store),
        Some(s.limits.clock.now()),
        &s.ctx,
        None,
        crate::lifecycle::State {
            deactivated: moving.is_some(),
            ..Default::default()
        },
    );
    write(&s.directory).insert_new(account);
    drop(claim);
    if let Some(l) = landing {
        s.events.land(l);
    }
    synced?;
    Ok(Resp::Json(
        json!({ "handle": handle, "did": did, "didDoc": doc, "accessJwt": access, "refreshJwt": refresh }),
    ))
}

/// Passwords, kept as scrypt hashes: `scrypt$<log2 N>$<r>$<p>$<salt>$<hash>`, in hex.
pub(crate) mod password {
    const LOG_N: u8 = 14;
    const R: u32 = 8;
    const P: u32 = 1;

    /// A hash no password is checked against but for an account that has
    /// none, or no account, so that it costs the same as one that has.
    pub static NONE: std::sync::LazyLock<String> =
        std::sync::LazyLock::new(|| hash(&hex::encode(rand::random::<[u8; 16]>())));

    fn derive(pw: &str, salt: &[u8], log_n: u8, r: u32, p: u32) -> Option<[u8; 32]> {
        let params = scrypt::Params::new(log_n, r, p, 32).ok()?;
        let mut out = [0u8; 32];
        scrypt::scrypt(pw.as_bytes(), salt, &params, &mut out).ok()?;
        Some(out)
    }

    pub fn hash(pw: &str) -> String {
        let salt: [u8; 16] = rand::random();
        let out = derive(pw, &salt, LOG_N, R, P).expect("scrypt with fixed parameters");
        format!(
            "scrypt${LOG_N}${R}${P}${}${}",
            hex::encode(salt),
            hex::encode(out)
        )
    }

    pub fn verify(pw: &str, stored: &str) -> bool {
        let parts: Vec<&str> = stored.split('$').collect();
        let ["scrypt", log_n, r, p, salt, want] = parts[..] else {
            return false;
        };
        let (Ok(log_n), Ok(r), Ok(p), Ok(salt), Ok(want)) = (
            log_n.parse(),
            r.parse(),
            p.parse(),
            hex::decode(salt),
            hex::decode(want),
        ) else {
            return false;
        };
        // Parameters this server does not use are refused, rather than run for however long they take.
        if (log_n, r, p) != (LOG_N, R, P) {
            return false;
        }
        let Some(got) = derive(pw, &salt, log_n, r, p) else {
            return false;
        };
        want.len() == got.len() && want.iter().zip(got).fold(0u8, |acc, (a, b)| acc | (a ^ b)) == 0
    }

    /// `verify` against `stored`, or, for no password, against `NONE`, which
    /// is false but costs the same. `NONE` is made by the first call, so it
    /// is called on the hash threads alone.
    pub fn verify_or_none(pw: &str, stored: Option<&str>) -> bool {
        let right = verify(pw, stored.unwrap_or(&NONE));
        right && stored.is_some()
    }

    #[test]
    fn hashes() {
        let h = hash("pw");
        assert!(verify("pw", &h));
        assert!(!verify("pW", &h));
        assert!(!verify("", &h));
        assert_ne!(hash("pw"), h);
        assert!(!verify("pw", "nonsense"));
    }
}

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

    const CREATE: &str = "com.atproto.server.createAccount";

    fn account(handle: &str, email: &str) -> Json {
        json!({ "handle": handle, "email": email, "password": "pw" })
    }

    #[tokio::test]
    async fn describe_server() {
        let plc = plc().await;
        let dir = scratch("describe");
        let s = open(&dir, &plc);
        let got = call(&s, "com.atproto.server.describeServer", None, json!({}))
            .await
            .unwrap();
        assert_eq!(
            got,
            json!({ "did": "did:web:localhost", "availableUserDomains": [".test", ".example"], "inviteCodeRequired": false, "blobUploadLimit": 5242880, "spacesAlpha": true })
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Each of `createAccount`'s checks, in their order.
    #[tokio::test]
    async fn create_account_checks_in_order() {
        let plc = plc().await;
        let dir = scratch("create-checks");
        let s = open(&dir, &plc);
        create(&s, "taken").await;
        let long = "x".repeat(257);
        let cases = [
            // The lexicon first.
            (json!({ "email": "a@b.com" }), "InvalidRequest"),
            (
                json!({ "handle": "not a handle", "did": "did:plc:x", "password": long }),
                "InvalidRequest",
            ),
            (json!({ "handle": "ok.test", "email": 5 }), "InvalidRequest"),
            (
                json!({ "handle": "ok.test", "did": "nope" }),
                "InvalidRequest",
            ),
            // The password's length, then the email.
            (
                json!({ "handle": "x.example", "password": long }),
                "InvalidRequest",
            ),
            (
                json!({ "handle": "x.example", "password": "x".repeat(256) }),
                "InvalidRequest",
            ),
            (
                json!({ "handle": "x.example", "email": "not-an-email" }),
                "InvalidRequest",
            ),
            // The handle.
            (
                json!({ "handle": "ab.example", "email": "a@b.com", "did": "did:plc:x" }),
                "InvalidHandle",
            ),
            (
                json!({ "handle": "abc.local", "email": "a@b.com" }),
                "InvalidHandle",
            ),
            (
                json!({ "handle": "abc.com", "email": "a@b.com" }),
                "UnsupportedDomain",
            ),
            (
                json!({ "handle": "abc.com", "email": "a@b.com", "inviteCode": "x" }),
                "UnsupportedDomain",
            ),
            // With `did`, a handle in none of the domains is external, which
            // no one resolves; the disallowed TLD still comes first.
            (
                json!({ "handle": "ac.test.com", "email": "a@b.com", "did": "did:plc:x" }),
                "InvalidRequest",
            ),
            (
                json!({ "handle": "ac.test.com", "email": "a@b.com", "did": "did:plc:x", "inviteCode": "x" }),
                "InvalidRequest",
            ),
            (
                json!({ "handle": "abcd.example", "email": "a@b.com", "did": "did:plc:x" }),
                "InvalidHandle",
            ),
            (
                json!({ "handle": "a.bc.test", "email": "a@b.com", "did": "did:plc:x" }),
                "InvalidHandle",
            ),
            (
                json!({ "handle": "admin.test", "email": "a@b.com", "did": "did:plc:x" }),
                "HandleNotAvailable",
            ),
            (
                json!({ "handle": "a.bc.test", "email": "a@b.com" }),
                "InvalidHandle",
            ),
            (
                json!({ "handle": "ab.test", "email": "a@b.com" }),
                "InvalidHandle",
            ),
            (
                json!({ "handle": format!("{}.test", "a".repeat(19)), "email": "a@b.com" }),
                "InvalidHandle",
            ),
            (
                json!({ "handle": "ADMIN.test", "email": "a@b.com", "inviteCode": "x" }),
                "HandleNotAvailable",
            ),
            // Taken handle, then taken email, in any case.
            (
                json!({ "handle": "TAKEN.test", "email": "TAKEN@mail.com", "did": "did:plc:x" }),
                "InvalidRequest",
            ),
            (
                json!({ "handle": "fresh.test", "email": "Taken@Mail.com", "did": "did:plc:x" }),
                "InvalidRequest",
            ),
            // Then an imported DID, then an invite code.
            (
                json!({ "handle": "fresh.test", "email": "fresh@mail.com", "did": "did:plc:x", "inviteCode": "x" }),
                "AuthenticationRequired",
            ),
            (
                json!({ "handle": "fresh.test", "email": "fresh@mail.com", "inviteCode": "x" }),
                "InvalidInviteCode",
            ),
        ];
        for (body, want) in cases {
            assert_eq!(
                call(&s, CREATE, None, body.clone()).await,
                Err(want.to_string()),
                "{body}"
            );
        }
        // Nothing refused made an account, or held its handle.
        let fresh = call(&s, CREATE, None, json!({ "handle": "Fresh.TEST", "email": "Fresh@Mail.com", "password": "x".repeat(256) })).await.unwrap();
        assert_eq!(fresh["handle"], json!("fresh.test"));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn emails() {
        let ok = [
            "a@b.com",
            "a.b+c@d-e.co.uk",
            "x_y@z.io",
            "a@b.c",
            "a@b.c1",
            "ü@x.io",
            "a@ü.io",
            "a@b-.io",
            "!#$%&'*+/=?^_`{|}~-@x.io",
        ];
        for e in ok {
            assert!(valid_email(e), "{e}");
        }
        assert!(valid_email(&format!("{}@x.io", "a".repeat(64))));
        assert!(valid_email(&format!("a@{}.io", "b".repeat(63))));
        let long_local = format!("{}@x.io", "a".repeat(65));
        let long_label = format!("a@{}.io", "b".repeat(64));
        let bad = [
            "",
            "a",
            "a@",
            "@b.com",
            "a@b",
            "a@b.123",
            "a@x_y.io",
            "a..b@x.io",
            ".a@x.io",
            "a.@x.io",
            "a b@c.com",
            "\"a\"@x.io",
            "a@-b.com",
            "a@b..com",
            "a@b.com.",
            "a@[1.2.3.4]",
            "a@1.2.3.4",
            "a@b@c.io",
            "a(b)@x.io",
            long_local.as_str(),
            long_label.as_str(),
        ];
        for e in bad {
            assert!(!valid_email(e), "{e}");
        }
    }

    /// 128 emoji are 256 UTF-16 code units, the most a password may have; 129 are too many.
    #[test]
    fn password_lengths() {
        assert_eq!(password_length(&"😀".repeat(128)), 256);
        assert_eq!(password_length(&"😀".repeat(129)), 258);
        assert_eq!(password_length(&"é".repeat(256)), 256);
    }

    /// The account made: its answer, its DID document, its session.
    #[tokio::test]
    async fn create_account_answers_a_session() {
        let plc = plc().await;
        let dir = scratch("create");
        let s = open(&dir, &plc);
        let got = call(&s, CREATE, None, account("Alice.test", "Alice@Mail.com"))
            .await
            .unwrap();
        let did = got["did"].as_str().unwrap();
        assert!(did.starts_with("did:plc:") && did.len() == 32);
        assert_eq!(got["handle"], json!("alice.test"));
        let doc = reqwest::get(format!("{plc}/{did}"))
            .await
            .unwrap()
            .text()
            .await
            .unwrap();
        assert_eq!(got["didDoc"], serde_json::from_str::<Json>(&doc).unwrap());
        let mut keys: Vec<&str> = got
            .as_object()
            .unwrap()
            .keys()
            .map(String::as_str)
            .collect();
        keys.sort();
        assert_eq!(keys, ["accessJwt", "did", "didDoc", "handle", "refreshJwt"]);
        let session = call(
            &s,
            "com.atproto.server.getSession",
            got["accessJwt"].as_str(),
            json!({}),
        )
        .await
        .unwrap();
        assert_eq!(
            session,
            json!({ "did": did, "handle": "alice.test", "email": "alice@mail.com", "emailConfirmed": false, "emailAuthFactor": false, "active": true })
        );
        // Its repository: one empty commit, and four events.
        assert!(repo_of(&s, did, |r| r.record_count() == 0 && !r.rev.is_empty()));
        assert_eq!(s.events.len(), 4);
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// The genesis operation `createAccount` posts names the account's own
    /// P-256 KEM key beside its signing key, and the DID document it answers
    /// is the directory's, with the KEM key in it (`spec/SPACES.md`).
    #[tokio::test]
    async fn create_account_makes_a_kem_key() {
        let plc = crate::identity::stub::Plc::start().await;
        let dir = scratch("create-kem");
        let s = open(&dir, &plc.url);
        let got = call(&s, CREATE, None, account("alice.test", "alice@mail.com"))
            .await
            .unwrap();
        let did = got["did"].as_str().unwrap().to_string();
        let (bob, _) = create(&s, "bob").await;
        let ops = plc.log(&did);
        assert_eq!(ops.len(), 1);
        crate::plc::verify(&did, &ops[0]).unwrap();
        let methods = &ops[0]["verificationMethods"];
        let mut names: Vec<&String> = methods.as_object().unwrap().keys().collect();
        names.sort();
        assert_eq!(names, ["atproto", "atproto_kem"]);
        let account = s.account(&did).unwrap();
        let kem = account.kem.as_ref().unwrap().public();
        assert_eq!(methods["atproto_kem"], json!(kem.did_key()));
        assert!(kem.did_key().starts_with("did:key:zDn"));
        assert_eq!(
            methods["atproto"],
            json!(repo_of(&s, &did, |r| crate::plc::did_key(
                r.verifying_key()
            )))
        );
        assert_ne!(methods["atproto_kem"], methods["atproto"]);
        assert_ne!(
            methods["atproto_kem"],
            plc.log(&bob)[0]["verificationMethods"]["atproto_kem"]
        );
        // The document the directory serves, the KEM key in it as it renders one.
        let doc: Json = serde_json::from_str(
            &reqwest::get(format!("{}/{did}", plc.url))
                .await
                .unwrap()
                .text()
                .await
                .unwrap(),
        )
        .unwrap();
        assert_eq!(got["didDoc"], doc);
        let point = format!("z{}", bs58::encode(kem.uncompressed()).into_string());
        let rendered = doc["verificationMethod"]
            .as_array()
            .unwrap()
            .iter()
            .find(|m| m["id"] == "#atproto_kem")
            .unwrap();
        assert_eq!(rendered["publicKeyMultibase"], json!(point));
        // A restart keeps it, and posts nothing.
        drop(account);
        drop(s);
        let s = open(&dir, &plc.url);
        assert_eq!(s.account(&did).unwrap().kem.as_ref().unwrap().public(), kem);
        assert_eq!(plc.log(&did).len(), 1);
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A directory that refuses the operation leaves no account.
    #[tokio::test]
    async fn refused_by_the_directory() {
        let plc = plc().await;
        let dir = scratch("refused");
        let s = open(&dir, &plc);
        assert_eq!(
            call(&s, CREATE, None, account("refused.test", "r@mail.com")).await,
            Err("InternalServerError".into())
        );
        assert!(read(&s.directory).by_did.is_empty());
        assert_eq!(s.events.len(), 0);
        let login = json!({ "identifier": "refused.test", "password": "pw" });
        assert_eq!(
            call(&s, "com.atproto.server.createSession", None, login).await,
            Err("AuthenticationRequired".into())
        );
        // Its email is free again.
        call(&s, CREATE, None, account("carol.test", "r@mail.com"))
            .await
            .unwrap();
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Creates at once with the same handle or email make one account.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn concurrent_creates_make_one() {
        let plc = plc().await;
        let dir = scratch("concurrent");
        let s = open(&dir, &plc);
        let bodies = [
            account("same.test", "one@mail.com"),
            account("same.test", "two@mail.com"),
            account("carol.test", "one@mail.com"),
        ];
        let calls = bodies.iter().cycle().take(9).map(|b| {
            let (s, b) = (s.clone(), b.clone());
            tokio::spawn(async move { call(&s, CREATE, None, b).await })
        });
        let mut made = 0;
        for c in calls.collect::<Vec<_>>() {
            if c.await.unwrap().is_ok() {
                made += 1;
            }
        }
        let d = read(&s.directory);
        assert_eq!(d.by_did.len(), made);
        assert!(made == 1 || made == 2);
        assert!(d.handles.len() == made && d.emails.len() == made);
        if made == 2 {
            assert!(d.handles.contains_key("same.test") && d.handles.contains_key("carol.test"));
            assert_eq!(d.handles["same.test"], d.emails["two@mail.com"]);
            assert_eq!(d.handles["carol.test"], d.emails["one@mail.com"]);
        }
        drop(d);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[tokio::test]
    async fn sessions_by_handle_email_or_did() {
        let plc = plc().await;
        let dir = scratch("sessions");
        let s = open(&dir, &plc);
        let (did, _) = create(&s, "alice").await;
        create(&s, "bob").await;
        let login = |id: &str, pw: &str| json!({ "identifier": id, "password": pw });
        for id in [
            "alice.test",
            "ALICE.test",
            "alice@mail.com",
            "Alice@MAIL.com",
            did.as_str(),
        ] {
            let got = call(
                &s,
                "com.atproto.server.createSession",
                None,
                login(id, "alice-pw"),
            )
            .await
            .unwrap();
            assert_eq!(got["did"], json!(did), "{id}");
            let mut keys: Vec<&str> = got
                .as_object()
                .unwrap()
                .keys()
                .map(String::as_str)
                .collect();
            keys.sort();
            assert_eq!(
                keys,
                [
                    "accessJwt",
                    "active",
                    "did",
                    "email",
                    "emailAuthFactor",
                    "emailConfirmed",
                    "handle",
                    "refreshJwt"
                ]
            );
            let session = call(
                &s,
                "com.atproto.server.getSession",
                got["accessJwt"].as_str(),
                json!({}),
            )
            .await
            .unwrap();
            assert_eq!(session["did"], json!(did));
            assert_eq!(session["email"], json!("alice@mail.com"));
        }
        for (id, pw) in [
            ("alice.test", "bob-pw"),
            ("alice.test", ""),
            ("nobody.test", "alice-pw"),
            ("did:plc:nobody", "alice-pw"),
            (did.to_uppercase().as_str(), "alice-pw"),
        ] {
            assert_eq!(
                call(&s, "com.atproto.server.createSession", None, login(id, pw)).await,
                Err("AuthenticationRequired".into()),
                "{id}"
            );
        }
        let get = "com.atproto.server.getSession";
        assert_eq!(
            call(&s, get, None, json!({})).await,
            Err("AuthMissing".into())
        );
        assert_eq!(
            call(&s, get, Some("forged"), json!({})).await,
            Err("InvalidToken".into())
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// An account with no password, or an empty one, exists but cannot log
    /// in, and keeps no email: its sessions leave it out, it is not found by
    /// it, and another account may take it.
    #[tokio::test]
    async fn no_password_no_login() {
        let plc = plc().await;
        let dir = scratch("no-password");
        let s = open(&dir, &plc);
        create(&s, "alice").await;
        for (name, pw) in [("nopw", None), ("emptypw", Some(""))] {
            let body = |email: &str| {
                let mut body = json!({ "handle": format!("{name}.test"), "email": email });
                if let Some(pw) = pw {
                    body["password"] = json!(pw);
                }
                body
            };
            // Not an email a password account has.
            assert_eq!(
                call(&s, CREATE, None, body("ALICE@mail.com")).await,
                Err("InvalidRequest".into())
            );
            assert_eq!(
                call(&s, CREATE, None, body("not-an-email")).await,
                Err("InvalidRequest".into())
            );
            let got = call(&s, CREATE, None, body(&format!("{name}@mail.com")))
                .await
                .unwrap();
            let session = call(
                &s,
                "com.atproto.server.getSession",
                got["accessJwt"].as_str(),
                json!({}),
            )
            .await
            .unwrap();
            assert_eq!(
                session,
                json!({ "did": got["did"], "handle": format!("{name}.test"), "emailConfirmed": false, "emailAuthFactor": false, "active": true })
            );
            for id in [
                format!("{name}.test"),
                format!("{name}@mail.com"),
                got["did"].as_str().unwrap().to_string(),
            ] {
                for try_pw in ["", "pw"] {
                    let login = json!({ "identifier": id, "password": try_pw });
                    assert_eq!(
                        call(&s, "com.atproto.server.createSession", None, login).await,
                        Err("AuthenticationRequired".into())
                    );
                }
            }
            // Its handle is taken; its email is not.
            assert_eq!(
                call(&s, CREATE, None, body("x@mail.com")).await,
                Err("InvalidRequest".into())
            );
            let other = json!({ "handle": format!("{name}2.test"), "email": format!("{}@MAIL.com", name.to_uppercase()), "password": "pw2" });
            let got = call(&s, CREATE, None, other).await.unwrap();
            let login = json!({ "identifier": format!("{name}@mail.com"), "password": "pw2" });
            assert_eq!(
                call(&s, "com.atproto.server.createSession", None, login)
                    .await
                    .unwrap()["did"],
                got["did"]
            );
        }
        // All of it survives a restart.
        drop(s);
        let s = open(&dir, &plc);
        let login = json!({ "identifier": "nopw@mail.com", "password": "pw2" });
        assert_eq!(
            call(&s, "com.atproto.server.createSession", None, login)
                .await
                .unwrap()["handle"],
            json!("nopw2.test")
        );
        let _ = std::fs::remove_dir_all(&dir);
    }
}