~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
4227 lines · 143.2 KB Raw History
//! OAuth's tests: the server on a socket, driven by a minimal client app
//! (its own DPoP key and proofs, PKCE and PAR) and a minimal browser (the
//! page's navigations and API calls, with their `Sec-Fetch-*`, `Origin`,
//! `Referer`, cookies and CSRF header).

use super::*;
use crate::testing::{create, open, plc, scratch};
use p256::ecdsa::{Signature, SigningKey, signature::Signer};
use std::sync::atomic::Ordering::SeqCst;

/// The server, serving on a socket of its own until dropped.
pub(crate) struct Server {
    pub svc: Shared,
    base: String,
    task: tokio::task::JoinHandle<()>,
    http: reqwest::Client,
}

impl Drop for Server {
    fn drop(&mut self) {
        self.task.abort();
    }
}

pub(crate) async fn serve(svc: Shared) -> Server {
    let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0))
        .await
        .unwrap();
    let base = format!("http://{}", listener.local_addr().unwrap());
    let app = crate::router(svc.clone());
    let task = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
    let http = reqwest::Client::builder()
        .redirect(reqwest::redirect::Policy::none())
        .build()
        .unwrap();
    Server {
        svc,
        base,
        task,
        http,
    }
}

impl Server {
    fn iss(&self) -> String {
        self.svc.oauth.issuer.clone()
    }

    fn now(&self) -> u64 {
        self.svc.sessions.now()
    }

    /// Move the server's clock on to `secs` past the real one.
    fn skew(&self, secs: u64) {
        self.svc.sessions.skew.store(secs, SeqCst);
    }

    pub fn request(&self, method: &str, path: &str) -> reqwest::RequestBuilder {
        self.http.request(
            reqwest::Method::from_bytes(method.as_bytes()).unwrap(),
            format!("{}{path}", self.base),
        )
    }
}

/// An answer, read whole.
pub(crate) struct Got {
    pub status: u16,
    pub headers: HeaderMap,
    pub body: String,
}

pub(crate) async fn got(r: reqwest::RequestBuilder) -> Got {
    let res = r.send().await.unwrap();
    let status = res.status().as_u16();
    let headers = res.headers().clone();
    Got {
        status,
        headers,
        body: res.text().await.unwrap(),
    }
}

impl Got {
    pub fn json(&self) -> Json {
        serde_json::from_str(&self.body).unwrap_or(Json::Null)
    }

    /// The `error` of a JSON answer, or of an error page.
    pub fn error(&self) -> String {
        let e = self.json()["error"].as_str().map(str::to_string);
        e.or_else(|| {
            self.page("__errorData")
                .and_then(|d| d["error"].as_str().map(str::to_string))
        })
        .unwrap_or_default()
    }

    pub fn header(&self, k: &str) -> Option<String> {
        self.headers.get(k).map(|v| v.to_str().unwrap().to_string())
    }

    /// The `error` named in `WWW-Authenticate`.
    fn www_error(&self) -> Option<String> {
        let w = self.header("www-authenticate")?;
        let at = w.find("error=\"")? + 7;
        Some(w[at..at + w[at..].find('"')?].to_string())
    }

    /// What a page sets `window[name]` to.
    pub fn page(&self, name: &str) -> Option<Json> {
        let prefix = format!("window[\"{name}\"]=JSON.parse(");
        let at = self.body.find(&prefix)? + prefix.len();
        let text: String = serde_json::Deserializer::from_str(&self.body[at..])
            .into_iter::<String>()
            .next()?
            .ok()?;
        serde_json::from_str(&text).ok()
    }

    /// The parameters of a redirect's `Location`, from its query or fragment.
    fn location(&self) -> (String, HashMap<String, String>) {
        let u = url::Url::parse(&self.header("location").expect("a redirect")).unwrap();
        let params = u
            .query_pairs()
            .chain(url::form_urlencoded::parse(
                u.fragment().unwrap_or_default().as_bytes(),
            ))
            .map(|(k, v)| (k.into_owned(), v.into_owned()))
            .collect();
        let mut base = u.clone();
        base.set_query(None);
        base.set_fragment(None);
        (base.to_string(), params)
    }
}

fn form(pairs: &[(&str, &str)]) -> String {
    url::form_urlencoded::Serializer::new(String::new())
        .extend_pairs(pairs)
        .finish()
}

fn b64(bytes: impl AsRef<[u8]>) -> String {
    B64.encode(bytes)
}

/// A DPoP key.
pub(crate) struct Key {
    sk: SigningKey,
    jwk: Json,
}

impl Key {
    pub fn new() -> Key {
        let sk = SigningKey::from_slice(&rand::random::<[u8; 32]>()).unwrap();
        let p = sk.verifying_key().to_sec1_point(false);
        let jwk = json!({ "kty": "EC", "crv": "P-256", "x": b64(p.x().unwrap()), "y": b64(p.y().unwrap()) });
        Key { sk, jwk }
    }

    pub fn jkt(&self) -> String {
        dpop::thumbprint(self.jwk.as_object().unwrap())
    }

    fn sign(&self, header: &Json, claims: &Json) -> String {
        let input = format!("{}.{}", b64(header.to_string()), b64(claims.to_string()));
        let sig: Signature = self.sk.sign(input.as_bytes());
        format!("{input}.{}", b64(sig.to_bytes()))
    }
}

/// A proof's header and claims, to change before it is signed.
struct Proof {
    header: Json,
    claims: Json,
}

/// A client app: a loopback client with its DPoP key and the nonce it last got.
pub(crate) struct App<'s> {
    srv: &'s Server,
    pub key: Key,
    pub client_id: String,
    pub redirect_uri: String,
    /// The scope its requests ask for.
    pub scope: String,
    pub nonce: Option<String>,
}

/// A request a client pushed, and what it keeps of it.
pub(crate) struct Pushed {
    pub request_uri: String,
    pub state: String,
    pub verifier: String,
}

impl<'s> App<'s> {
    pub fn new(srv: &'s Server, scope: &str) -> App<'s> {
        let redirect_uri = "http://127.0.0.1/cb".to_string();
        let client_id = format!(
            "http://localhost/?{}",
            form(&[("scope", scope), ("redirect_uri", &redirect_uri)])
        );
        App {
            srv,
            key: Key::new(),
            client_id,
            redirect_uri,
            scope: scope.to_string(),
            nonce: None,
        }
    }

    fn proof_parts(&self, method: &str, path: &str, ath: Option<&str>) -> Proof {
        let mut claims = json!({ "jti": hex::encode(rand::random::<[u8; 12]>()), "htm": method, "htu": format!("{}{path}", self.srv.iss()), "iat": self.srv.now() });
        if let Some(n) = &self.nonce {
            claims["nonce"] = json!(n);
        }
        if let Some(t) = ath {
            claims["ath"] = json!(dpop::ath(t));
        }
        Proof {
            header: json!({ "typ": "dpop+jwt", "alg": "ES256", "jwk": self.key.jwk }),
            claims,
        }
    }

    pub fn proof(&self, method: &str, path: &str, ath: Option<&str>) -> String {
        let p = self.proof_parts(method, path, ath);
        self.key.sign(&p.header, &p.claims)
    }

    /// A proof with one thing changed.
    fn proof_with(
        &self,
        method: &str,
        path: &str,
        ath: Option<&str>,
        change: impl FnOnce(&mut Proof),
    ) -> String {
        let mut p = self.proof_parts(method, path, ath);
        change(&mut p);
        self.key.sign(&p.header, &p.claims)
    }

    fn keep_nonce(&mut self, g: &Got) {
        if let Some(n) = g.header("dpop-nonce") {
            self.nonce = Some(n);
        }
    }

    /// POST a form to an endpoint with these DPoP headers.
    async fn send(&mut self, path: &str, body: &str, proofs: &[String]) -> Got {
        let mut r = self
            .srv
            .request("POST", path)
            .header("content-type", "application/x-www-form-urlencoded")
            .body(body.to_string());
        for p in proofs {
            r = r.header("dpop", p);
        }
        let g = got(r).await;
        self.keep_nonce(&g);
        g
    }

    /// POST a form with a fresh proof, once more with the nonce if asked for one.
    pub async fn call(&mut self, path: &str, pairs: &[(&str, &str)]) -> Got {
        let body = form(pairs);
        for _ in 0..2 {
            let proof = self.proof("POST", path, None);
            let g = self.send(path, &body, &[proof]).await;
            if g.error() != "use_dpop_nonce" {
                return g;
            }
        }
        panic!("the server kept asking for a nonce");
    }

    /// Make sure the app holds a nonce the server takes.
    async fn fresh_nonce(&mut self) {
        let g = got(self
            .srv
            .request("POST", "/oauth/par")
            .header("content-type", "application/x-www-form-urlencoded")
            .body(""))
        .await;
        self.keep_nonce(&g);
    }

    /// The PAR parameters of a good request, with `extra` changed or added.
    fn par_params(
        &self,
        verifier: &str,
        state: &str,
        extra: &[(&'static str, Option<&str>)],
    ) -> Vec<(String, String)> {
        let challenge = b64(Sha256::digest(verifier.as_bytes()));
        let mut out: Vec<(String, String)> = [
            ("client_id", self.client_id.as_str()),
            ("response_type", "code"),
            ("redirect_uri", &self.redirect_uri),
            ("scope", &self.scope),
            ("state", state),
            ("code_challenge", &challenge),
            ("code_challenge_method", "S256"),
        ]
        .iter()
        .map(|(k, v)| (k.to_string(), v.to_string()))
        .collect();
        for (k, v) in extra {
            out.retain(|(n, _)| n != k);
            if let Some(v) = v {
                out.push((k.to_string(), v.to_string()));
            }
        }
        out
    }

    /// Push a request with `extra` changed: the answer, and what the app keeps.
    pub async fn par(&mut self, extra: &[(&'static str, Option<&str>)]) -> (Got, Pushed) {
        self.push(extra, true).await
    }

    /// Push a request with `extra` changed and no DPoP proof (PAR's step 4).
    pub async fn par_unproven(&mut self, extra: &[(&'static str, Option<&str>)]) -> (Got, Pushed) {
        self.push(extra, false).await
    }

    async fn push(
        &mut self,
        extra: &[(&'static str, Option<&str>)],
        proven: bool,
    ) -> (Got, Pushed) {
        let verifier = b64(rand::random::<[u8; 32]>());
        let state = hex::encode(rand::random::<[u8; 8]>());
        let params = self.par_params(&verifier, &state, extra);
        let pairs: Vec<(&str, &str)> = params
            .iter()
            .map(|(k, v)| (k.as_str(), v.as_str()))
            .collect();
        let g = if proven {
            self.call("/oauth/par", &pairs).await
        } else {
            self.send("/oauth/par", &form(&pairs), &[]).await
        };
        let request_uri = g.json()["request_uri"]
            .as_str()
            .unwrap_or_default()
            .to_string();
        (
            g,
            Pushed {
                request_uri,
                state,
                verifier,
            },
        )
    }

    pub async fn token(&mut self, pairs: &[(&str, &str)]) -> Got {
        let mut all = vec![("client_id", self.client_id.clone())];
        all.extend(pairs.iter().map(|(k, v)| (*k, v.to_string())));
        let pairs: Vec<(&str, &str)> = all.iter().map(|(k, v)| (*k, v.as_str())).collect();
        self.call("/oauth/token", &pairs).await
    }

    pub async fn exchange(&mut self, code: &str, pushed: &Pushed) -> Got {
        let redirect = self.redirect_uri.clone();
        self.token(&[
            ("grant_type", "authorization_code"),
            ("code", code),
            ("redirect_uri", &redirect),
            ("code_verifier", &pushed.verifier),
        ])
        .await
    }

    pub async fn refresh(&mut self, refresh_token: &str) -> Got {
        self.token(&[
            ("grant_type", "refresh_token"),
            ("refresh_token", refresh_token),
        ])
        .await
    }

    pub async fn revoke(&mut self, token: &str) -> Got {
        let client_id = self.client_id.clone();
        self.call(
            "/oauth/revoke",
            &[("client_id", &client_id), ("token", token)],
        )
        .await
    }

    /// `getSession` with an access token and these DPoP headers.
    async fn get_session_with(&mut self, access: &str, proofs: &[String]) -> Got {
        let mut r = self
            .srv
            .request("GET", "/xrpc/com.atproto.server.getSession")
            .header("authorization", format!("DPoP {access}"));
        for p in proofs {
            r = r.header("dpop", p);
        }
        let g = got(r).await;
        self.keep_nonce(&g);
        g
    }

    pub async fn get_session(&mut self, access: &str) -> Got {
        for _ in 0..2 {
            let proof = self.proof("GET", "/xrpc/com.atproto.server.getSession", Some(access));
            let g = self.get_session_with(access, &[proof]).await;
            if g.error() != "use_dpop_nonce" {
                return g;
            }
        }
        panic!("the server kept asking for a nonce");
    }

    /// A JSON procedure with an access token and a proof.
    pub async fn post(&mut self, nsid: &str, access: &str, body: Json) -> Got {
        let path = format!("/xrpc/{nsid}");
        for _ in 0..2 {
            let proof = self.proof("POST", &path, Some(access));
            let r = self
                .srv
                .request("POST", &path)
                .header("authorization", format!("DPoP {access}"))
                .header("dpop", proof)
                .header("content-type", "application/json")
                .body(body.to_string());
            let g = got(r).await;
            self.keep_nonce(&g);
            if g.error() != "use_dpop_nonce" {
                return g;
            }
        }
        panic!("the server kept asking for a nonce");
    }
}

/// A browser: the cookies it was given.
pub(crate) struct Browser<'s> {
    srv: &'s Server,
    pub cookies: Vec<(String, String)>,
}

impl<'s> Browser<'s> {
    pub fn new(srv: &'s Server) -> Browser<'s> {
        Browser {
            srv,
            cookies: Vec::new(),
        }
    }

    fn cookie_header(&self) -> String {
        self.cookies
            .iter()
            .map(|(k, v)| format!("{k}={v}"))
            .collect::<Vec<_>>()
            .join("; ")
    }

    fn keep_cookies(&mut self, g: &Got) {
        for c in g.headers.get_all("set-cookie") {
            let (kv, _) = c.to_str().unwrap().split_once(';').unwrap();
            let (k, v) = kv.split_once('=').unwrap();
            self.cookies.retain(|(n, _)| n != k);
            self.cookies.push((k.to_string(), v.to_string()));
        }
    }

    fn cookie(&self, k: &str) -> Option<String> {
        self.cookies
            .iter()
            .find(|(n, _)| n == k)
            .map(|(_, v)| v.clone())
    }

    fn navigation(&self, path: &str, site: &str) -> reqwest::RequestBuilder {
        let r = self
            .srv
            .request("GET", path)
            .header("sec-fetch-mode", "navigate")
            .header("sec-fetch-dest", "document")
            .header("sec-fetch-site", site);
        if self.cookies.is_empty() {
            r
        } else {
            r.header("cookie", self.cookie_header())
        }
    }

    fn page_url(&self, client_id: &str, request_uri: &str) -> String {
        format!(
            "/oauth/authorize?{}",
            form(&[("client_id", client_id), ("request_uri", request_uri)])
        )
    }

    /// Load the authorization page, as the client sends the browser to it.
    pub async fn page(&mut self, client_id: &str, request_uri: &str) -> Got {
        let g = got(self.navigation(&self.page_url(client_id, request_uri), "cross-site")).await;
        self.keep_cookies(&g);
        g
    }

    /// A call of the page's script, from the page of `request_uri`.
    /// A call of the page's script, from the page of `request_uri`, with
    /// headers in `over` in place of its own (an empty one left out).
    fn api_request(
        &self,
        client_id: &str,
        request_uri: &str,
        endpoint: &str,
        body: &Json,
        over: &[(&str, &str)],
    ) -> reqwest::RequestBuilder {
        let mut headers = vec![
            ("sec-fetch-mode", "same-origin".to_string()),
            ("sec-fetch-site", "same-origin".to_string()),
            ("origin", self.srv.iss()),
            (
                "referer",
                format!(
                    "{}{}",
                    self.srv.iss(),
                    self.page_url(client_id, request_uri)
                ),
            ),
            (
                "x-csrf-token",
                self.cookie("csrf-token").unwrap_or_default(),
            ),
            ("cookie", self.cookie_header()),
            ("content-type", "application/json".to_string()),
        ];
        for (k, v) in over {
            headers.retain(|(n, _)| n != k);
            if !v.is_empty() {
                headers.push((k, v.to_string()));
            }
        }
        let mut r = self
            .srv
            .request("POST", &format!("/@atproto/oauth-provider/~api/{endpoint}"))
            .body(body.to_string());
        for (k, v) in headers {
            r = r.header(k, v);
        }
        r
    }

    pub async fn api(
        &mut self,
        client_id: &str,
        request_uri: &str,
        endpoint: &str,
        body: Json,
        bearer: Option<&str>,
    ) -> Got {
        let mut r = self.api_request(client_id, request_uri, endpoint, &body, &[]);
        if let Some(t) = bearer {
            r = r.header("authorization", format!("Bearer {t}"));
        }
        let g = got(r).await;
        self.keep_cookies(&g);
        g
    }

    /// Follow a `url` the API answered, from the page of `request_uri`.
    pub async fn follow(&mut self, url: &str, client_id: &str, request_uri: &str) -> Got {
        let path = url.strip_prefix(&self.srv.iss()).unwrap();
        let referer = format!(
            "{}{}",
            self.srv.iss(),
            self.page_url(client_id, request_uri)
        );
        got(self
            .navigation(path, "same-origin")
            .header("referer", referer))
        .await
    }
}

/// A full sign-in: PAR, the page, sign-in with the account's password,
/// consent (narrowed to `consented`, if given), the redirect, and the code
/// exchanged. Answers the token endpoint's answer.
pub(crate) async fn sign_in(
    app: &mut App<'_>,
    browser: &mut Browser<'_>,
    name: &str,
    consented: Option<&str>,
) -> Got {
    let (g, pushed) = app.par(&[]).await;
    assert_eq!(g.status, 201, "{}", g.body);
    let page = browser.page(&app.client_id, &pushed.request_uri).await;
    assert_eq!(page.status, 200, "{}", page.body);
    let signed = browser
        .api(&app.client_id, &pushed.request_uri, "sign-in", json!({ "locale": "en", "identifier": format!("{name}.test"), "password": format!("{name}-pw"), "remember": true }), None)
        .await;
    assert_eq!(signed.status, 200, "{}", signed.body);
    let mut body = json!({ "did": signed.json()["account"]["did"] });
    if let Some(s) = consented {
        body["scope"] = json!(s);
    }
    let consent = browser
        .api(&app.client_id, &pushed.request_uri, "consent", body, None)
        .await;
    assert_eq!(consent.status, 200, "{}", consent.body);
    let back = browser
        .follow(
            consent.json()["url"].as_str().unwrap(),
            &app.client_id,
            &pushed.request_uri,
        )
        .await;
    assert_eq!(back.status, 303, "{}", back.body);
    let (to, params) = back.location();
    assert_eq!(to, app.redirect_uri);
    assert_eq!(params["state"], pushed.state);
    assert_eq!(params["iss"], app.srv.iss());
    app.exchange(&params["code"], &pushed).await
}

/// A request approved, its code not yet exchanged.
pub(crate) async fn approved(
    app: &mut App<'_>,
    browser: &mut Browser<'_>,
    name: &str,
) -> (Pushed, String) {
    let (_, pushed) = app.par(&[]).await;
    let code = approve(app, browser, name, &pushed).await;
    (pushed, code)
}

/// A request pushed, approved: its code, not yet exchanged.
async fn approve(app: &App<'_>, browser: &mut Browser<'_>, name: &str, pushed: &Pushed) -> String {
    browser.page(&app.client_id, &pushed.request_uri).await;
    let signed = browser.api(&app.client_id, &pushed.request_uri, "sign-in", json!({ "locale": "en", "identifier": format!("{name}.test"), "password": format!("{name}-pw") }), None).await;
    // Signed in on this device already, it stays so, with no ephemeral token.
    let token = signed.json()["ephemeralToken"].as_str().map(str::to_string);
    let consent = browser
        .api(
            &app.client_id,
            &pushed.request_uri,
            "consent",
            json!({ "did": signed.json()["account"]["did"] }),
            token.as_deref(),
        )
        .await;
    let url = url::Url::parse(consent.json()["url"].as_str().unwrap()).unwrap();
    url.query_pairs()
        .find(|(k, _)| k == "code")
        .map(|(_, v)| v.into_owned())
        .expect("a code")
}

pub(crate) fn text(j: &Json, k: &str) -> String {
    j[k].as_str().unwrap_or_default().to_string()
}

async fn setup(name: &str) -> (std::path::PathBuf, Server, String) {
    let plc = plc().await;
    let dir = scratch(name);
    let srv = serve(open(&dir, &plc)).await;
    create(&srv.svc, "alice").await;
    (dir, srv, plc)
}

#[tokio::test]
async fn metadata() {
    let (dir, srv, _) = setup("oauth-metadata").await;
    let iss = srv.iss();
    assert_eq!(iss, "http://127.0.0.1:2583");
    let pr = got(srv.request("GET", "/.well-known/oauth-protected-resource")).await;
    assert_eq!(pr.status, 200);
    assert_eq!(
        pr.header("access-control-allow-origin").as_deref(),
        Some("*")
    );
    assert_eq!(
        pr.json(),
        json!({ "resource": iss, "authorization_servers": [iss], "scopes_supported": [], "bearer_methods_supported": ["header"], "resource_documentation": "https://atproto.com" })
    );
    let asm = got(srv.request("GET", "/.well-known/oauth-authorization-server")).await;
    let m = asm.json();
    assert_eq!(m.as_object().unwrap().len(), 25);
    assert_eq!(m["issuer"], json!(iss));
    assert_eq!(
        m["pushed_authorization_request_endpoint"],
        json!(format!("{iss}/oauth/par"))
    );
    assert_eq!(m["require_pushed_authorization_requests"], json!(true));
    assert!(
        m["dpop_signing_alg_values_supported"]
            .as_array()
            .unwrap()
            .contains(&json!("ES256"))
    );
    assert_eq!(m["code_challenge_methods_supported"], json!(["S256"]));
    assert_eq!(
        asm.header("access-control-allow-headers").as_deref(),
        Some("Content-Type,DPoP")
    );
    assert_eq!(
        got(srv.request("GET", "/oauth/jwks")).await.json(),
        json!({ "keys": [] })
    );
    for path in [
        "/.well-known/oauth-authorization-server",
        "/oauth/jwks",
        "/oauth/par",
        "/oauth/token",
        "/oauth/revoke",
    ] {
        let g = got(srv.request("OPTIONS", path)).await;
        assert_eq!(g.status, 200, "{path}");
        for (k, v) in [
            ("access-control-allow-origin", "*"),
            ("access-control-allow-methods", "*"),
            ("access-control-max-age", "86400"),
        ] {
            assert_eq!(g.header(k).as_deref(), Some(v), "{path} {k}");
        }
        assert!(
            g.header("dpop-nonce").is_none()
                && g.header("cache-control").is_none()
                && g.header("pragma").is_none(),
            "{path}"
        );
    }
    // The endpoints' answers carry the nonce, and say so to browsers.
    let g = got(srv
        .request("POST", "/oauth/token")
        .header("content-type", "text/plain"))
    .await;
    assert_eq!((g.status, g.error().as_str()), (415, "invalid_request"));
    assert!(g.header("dpop-nonce").is_some());
    assert_eq!(
        g.header("access-control-expose-headers").as_deref(),
        Some("DPoP-Nonce")
    );
    assert_eq!(
        (
            g.header("cache-control").as_deref(),
            g.header("pragma").as_deref()
        ),
        (Some("no-store"), Some("no-cache"))
    );
    assert_eq!(got(srv.request("GET", "/oauth/par")).await.status, 405);
    assert_eq!(got(srv.request("GET", "/oauth/token")).await.status, 404);
    assert_eq!(got(srv.request("GET", "/oauth/revoke")).await.status, 404);
    let _ = std::fs::remove_dir_all(&dir);
}

#[tokio::test]
async fn par_checks_in_order() {
    let (dir, srv, _) = setup("oauth-par").await;
    let mut app = App::new(
        &srv,
        "atproto transition:generic openid include:com.example.set",
    );
    app.scope = "atproto transition:generic".into();
    app.fresh_nonce().await;
    let refused = |g: &Got| (g.status, g.error());
    // 1. The body.
    let g = got(srv.request("POST", "/oauth/par").body("client_id=x")).await;
    assert_eq!(refused(&g), (415, "invalid_request".into()));
    let g = got(srv
        .request("POST", "/oauth/par")
        .header("content-type", "application/json")
        .body("{"))
    .await;
    assert_eq!(refused(&g), (400, "invalid_request".into()));
    let twice = form(&[("client_id", "a"), ("client_id", "a")]);
    assert_eq!(
        refused(&app.send("/oauth/par", &twice, &[]).await),
        (400, "invalid_request".into())
    );
    let g = got(srv
        .request("POST", "/oauth/par")
        .header("content-type", "application/json")
        .body(r#"{"client_id":"a","client_id":"a"}"#))
    .await;
    assert_eq!(refused(&g), (400, "invalid_request".into()));
    // 2-16, one thing wrong each.
    let cases: Vec<(Extra, u16, &str)> = vec![
        (&[("client_id", None)], 400, "invalid_client"),
        (&[("client_id", Some(""))], 400, "invalid_client"),
        (&[("response_type", Some("bogus"))], 400, "invalid_request"),
        (&[("response_type", None)], 400, "invalid_request"),
        (
            &[("redirect_uri", Some("http://localhost/cb"))],
            400,
            "invalid_request",
        ),
        (
            &[("scope", Some("atproto  transition:generic"))],
            400,
            "invalid_request",
        ),
        (&[("scope", None)], 400, "invalid_scope"),
        (
            &[("code_challenge_method", Some("S512"))],
            400,
            "invalid_request",
        ),
        (&[("prompt", Some("never"))], 400, "invalid_request"),
        (
            &[("response_mode", Some("web_message"))],
            400,
            "invalid_request",
        ),
        (&[("ui_locales", Some("en_US"))], 400, "invalid_request"),
        (&[("display", Some("tv"))], 400, "invalid_request"),
        (&[("max_age", Some("-1"))], 400, "invalid_request"),
        (&[("login_hint", Some(""))], 400, "invalid_request"),
        (
            &[("id_token_hint", Some("not-a-jwt"))],
            400,
            "invalid_request",
        ),
        (&[("claims", Some("[]"))], 400, "invalid_request"),
        (
            &[("client_id", Some("https://example.com/client.json"))],
            400,
            "invalid_client_metadata",
        ),
        (
            &[(
                "client_id",
                Some("http://localhost?redirect_uri=http://u:p@127.0.0.1/"),
            )],
            400,
            "invalid_redirect_uri",
        ),
        (&[("dpop_jkt", Some("AAAA"))], 401, "invalid_token"),
        (&[("claims", Some("{}"))], 400, "invalid_request"),
        (&[("nonce", Some("n"))], 400, "invalid_request"),
        (
            &[("response_type", Some("token"))],
            400,
            "unsupported_response_type",
        ),
        (
            &[("scope", Some("atproto transition:email"))],
            400,
            "invalid_scope",
        ),
        (
            &[("redirect_uri", Some("http://127.0.0.1/other"))],
            400,
            "invalid_request",
        ),
        (&[("code_challenge", None)], 400, "invalid_request"),
        (
            &[("scope", Some("transition:generic"))],
            400,
            "invalid_scope",
        ),
        (&[("scope", Some("atproto openid"))], 400, "invalid_scope"),
        (
            &[("code_challenge_method", Some("plain"))],
            400,
            "invalid_request",
        ),
        (&[("code_challenge_method", None)], 400, "invalid_request"),
        (&[("prompt", Some("none"))], 400, "invalid_request"),
        (
            &[("login_hint", Some("not a handle"))],
            400,
            "invalid_request",
        ),
        (
            &[("scope", Some("atproto include:com.example.set"))],
            400,
            "invalid_scope",
        ),
        (&[("state", None)], 400, "invalid_request"),
        (&[("state", Some(""))], 400, "invalid_request"),
    ];
    for &(extra, status, error) in &cases {
        let (g, _) = app.par(extra).await;
        assert_eq!(
            refused(&g),
            (status, error.to_string()),
            "{extra:?}: {}",
            g.body
        );
        assert!(g.header("dpop-nonce").is_some());
        if status == 401 {
            assert_eq!(g.www_error().as_deref(), Some(error));
            assert_eq!(
                g.header("access-control-expose-headers").as_deref(),
                Some("DPoP-Nonce, WWW-Authenticate")
            );
        }
    }
    // 4. No proof: checked as any other request, in the same order, and
    // `dpop_jkt`, with no proof to match, kept as the request's key.
    for &(extra, status, error) in &cases {
        let (g, _) = app.par_unproven(extra).await;
        let want = if status == 401 {
            (201, String::new())
        } else {
            (status, error.to_string())
        };
        assert_eq!(refused(&g), want, "{extra:?} with no proof: {}", g.body);
    }
    let (g, keyless) = app.par_unproven(&[]).await;
    assert_eq!(g.status, 201, "{}", g.body);
    let (g, given) = app.par_unproven(&[("dpop_jkt", Some("AAAA"))]).await;
    assert_eq!(g.status, 201, "{}", g.body);
    let st = srv.svc.oauth.snapshot();
    assert_eq!(st.requests[request_id_of(&keyless.request_uri)].jkt, None);
    assert_eq!(
        st.requests[request_id_of(&given.request_uri)]
            .jkt
            .as_deref(),
        Some("AAAA")
    );
    // One that passes, as JSON too, and one whose state the client used before.
    let (g, pushed) = app
        .par(&[
            ("login_hint", Some("Alice.Test")),
            ("dpop_jkt", Some(&app.key.jkt())),
            ("max_age", Some("0")),
        ])
        .await;
    assert_eq!(g.status, 201, "{}", g.body);
    assert!(pushed.request_uri.starts_with(REQUEST_URI));
    assert_eq!(g.json()["expires_in"], json!(300));
    let (g, _) = app.par(&[("state", Some(&pushed.state))]).await;
    assert_eq!(refused(&g), (400, "invalid_request".into()));
    let verifier = b64(rand::random::<[u8; 32]>());
    let params: serde_json::Map<String, Json> = app
        .par_params(&verifier, "json-state", &[])
        .into_iter()
        .map(|(k, v)| (k, json!(v)))
        .collect();
    let proof = app.proof("POST", "/oauth/par", None);
    let g = got(srv
        .request("POST", "/oauth/par")
        .header("content-type", "application/json; charset=utf-8")
        .header("dpop", proof)
        .body(Json::Object(params).to_string()))
    .await;
    assert_eq!(g.status, 201, "{}", g.body);
    // What is kept: the scopes the server knows, the hint lower-cased, consent prompted.
    let st = srv.svc.oauth.snapshot();
    let id = request_id_of(&pushed.request_uri);
    let r = &st.requests[id];
    assert_eq!(r.scope, ["atproto", "transition:generic"]);
    assert_eq!(
        (
            r.login_hint.as_deref(),
            r.prompt.as_deref(),
            r.response_mode.as_str()
        ),
        (Some("alice.test"), Some("consent"), "query")
    );
    assert_eq!(r.jkt.as_deref(), Some(app.key.jkt().as_str()));
    let _ = std::fs::remove_dir_all(&dir);
}

/// PAR parameters changed or left out.
type Extra<'a> = &'a [(&'static str, Option<&'a str>)];

/// One thing to change of a proof.
type Change = Box<dyn FnOnce(&mut Proof)>;

fn request_id_of(request_uri: &str) -> &str {
    request_uri.strip_prefix(REQUEST_URI).unwrap()
}

#[tokio::test]
async fn dpop_proofs() {
    let (dir, srv, _) = setup("oauth-dpop").await;
    let mut app = App::new(&srv, "atproto");
    let body = form(&[("client_id", "http://localhost"), ("token", "x")]);
    let path = "/oauth/revoke";
    let refused = |g: &Got| (g.status, g.error(), g.www_error());
    // No nonce: use_dpop_nonce, with no WWW-Authenticate at the endpoints.
    let p = app.proof("POST", path, None);
    let g = app.send(path, &body, &[p]).await;
    assert_eq!(refused(&g), (400, "use_dpop_nonce".into(), None));
    let invalid = (
        401,
        "invalid_dpop_proof".to_string(),
        Some("invalid_dpop_proof".to_string()),
    );
    let now = srv.now() as i64;
    let other = Key::new();
    let wrong: Vec<(&str, Change)> = vec![
        ("typ", Box::new(|p| p.header["typ"] = json!("jwt"))),
        ("alg", Box::new(|p| p.header["alg"] = json!("none"))),
        ("alg RS256", Box::new(|p| p.header["alg"] = json!("RS256"))),
        (
            "no jwk",
            Box::new(|p| {
                p.header
                    .as_object_mut()
                    .unwrap()
                    .remove("jwk")
                    .map(drop)
                    .unwrap_or(())
            }),
        ),
        (
            "private jwk",
            Box::new(|p| p.header["jwk"]["d"] = json!("AAAA")),
        ),
        (
            "other key",
            Box::new(move |p| p.header["jwk"] = other.jwk.clone()),
        ),
        (
            "no iat",
            Box::new(|p| {
                p.claims
                    .as_object_mut()
                    .unwrap()
                    .remove("iat")
                    .map(drop)
                    .unwrap_or(())
            }),
        ),
        (
            "old iat",
            Box::new(move |p| p.claims["iat"] = json!(now - 200)),
        ),
        (
            "future iat",
            Box::new(move |p| p.claims["iat"] = json!(now + 200)),
        ),
        (
            "exp past",
            Box::new(move |p| p.claims["exp"] = json!(now - 200)),
        ),
        (
            "nonce not a string",
            Box::new(|p| p.claims["nonce"] = json!(1)),
        ),
        ("no jti", Box::new(|p| p.claims["jti"] = json!(""))),
        ("htm", Box::new(|p| p.claims["htm"] = json!("GET"))),
        (
            "htu path",
            Box::new(|p| p.claims["htu"] = json!("http://127.0.0.1:2583/oauth/token")),
        ),
        (
            "htu host",
            Box::new(|p| p.claims["htu"] = json!("http://127.0.0.2:2583/oauth/revoke")),
        ),
        (
            "htu user",
            Box::new(|p| p.claims["htu"] = json!("http://u@127.0.0.1:2583/oauth/revoke")),
        ),
        (
            "htu scheme",
            Box::new(|p| p.claims["htu"] = json!("ftp://127.0.0.1:2583/oauth/revoke")),
        ),
        ("ath", Box::new(|p| p.claims["ath"] = json!("x"))),
    ];
    for (what, change) in wrong {
        let p = app.proof_with("POST", path, None, change);
        assert_eq!(
            refused(&app.send(path, &body, &[p]).await),
            invalid,
            "{what}"
        );
    }
    // A bad signature, and two headers.
    let mut p = app.proof("POST", path, None);
    p.push('A');
    assert_eq!(refused(&app.send(path, &body, &[p]).await), invalid);
    let two = [app.proof("POST", path, None), app.proof("POST", path, None)];
    assert_eq!(refused(&app.send(path, &body, &two).await), invalid);
    // A nonce the server did not give.
    let p = app.proof_with("POST", path, None, |p| p.claims["nonce"] = json!("made-up"));
    assert_eq!(
        refused(&app.send(path, &body, &[p]).await),
        (400, "use_dpop_nonce".into(), None)
    );
    // A good one, whose htu has a query, an upper-case host and the default port of a scheme; then its replay.
    let p = app.proof_with("POST", path, None, |p| {
        p.claims["htu"] = json!("http://127.0.0.1:2583/oauth/revoke?x=1#y")
    });
    assert_eq!(
        app.send(path, &body, std::slice::from_ref(&p)).await.status,
        200
    );
    assert_eq!(refused(&app.send(path, &body, &[p]).await), invalid);
    // A proof refused for its nonce is not spent.
    let p = app.proof_with("POST", path, None, |p| p.claims["nonce"] = json!("made-up"));
    app.send(path, &body, std::slice::from_ref(&p)).await;
    let mut parts = p.split('.');
    let (_, claims) = (parts.next(), parts.next().unwrap());
    let mut claims: Json = serde_json::from_slice(&B64.decode(claims).unwrap()).unwrap();
    claims["nonce"] = json!(app.nonce.clone().unwrap());
    let again = app.key.sign(
        &json!({ "typ": "dpop+jwt", "alg": "ES256", "jwk": app.key.jwk }),
        &claims,
    );
    assert_eq!(app.send(path, &body, &[again]).await.status, 200);
    // Nonces: the one given works for the next period too, and not two after.
    let given = app.nonce.clone().unwrap();
    srv.skew(60);
    let p = app.proof("POST", path, None);
    assert_eq!(app.send(path, &body, &[p]).await.status, 200);
    app.nonce = Some(given.clone());
    srv.skew(180);
    let p = app.proof("POST", path, None);
    assert_eq!(app.send(path, &body, &[p]).await.error(), "use_dpop_nonce");
    srv.skew(0);
    // ES256K proofs are taken too.
    app.fresh_nonce().await;
    let k = k256::ecdsa::SigningKey::from_slice(&rand::random::<[u8; 32]>()).unwrap();
    let pt = k.verifying_key().to_sec1_point(false);
    let header = json!({ "typ": "dpop+jwt", "alg": "ES256K", "jwk": { "kty": "EC", "crv": "secp256k1", "x": b64(pt.x().unwrap()), "y": b64(pt.y().unwrap()) } });
    let mut claims = app.proof_parts("POST", path, None).claims;
    claims["nonce"] = json!(app.nonce.clone().unwrap());
    let input = format!("{}.{}", b64(header.to_string()), b64(claims.to_string()));
    let sig: k256::ecdsa::Signature = k256::ecdsa::signature::Signer::sign(&k, input.as_bytes());
    assert_eq!(
        app.send(path, &body, &[format!("{input}.{}", b64(sig.to_bytes()))])
            .await
            .status,
        200
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[tokio::test]
async fn the_authorization_page() {
    let (dir, srv, _) = setup("oauth-page").await;
    let alice = srv.svc.account("alice.test").unwrap().did.clone();
    let mut app = App::new(&srv, "atproto transition:generic");
    let mut browser = Browser::new(&srv);
    let (_, pushed) = app
        .par(&[
            ("login_hint", Some(&alice)),
            ("ui_locales", Some("fr-CA en")),
        ])
        .await;
    let page_url = browser.page_url(&app.client_id, &pushed.request_uri);
    // The navigation check.
    let bad = |g: Got| (g.status, g.error());
    let refused = (400, "invalid_request".to_string());
    let base = || {
        srv.request("GET", &page_url)
            .header("sec-fetch-mode", "navigate")
            .header("sec-fetch-dest", "document")
    };
    assert_eq!(bad(got(base()).await), refused);
    assert_eq!(
        bad(got(base()
            .header("sec-fetch-site", "same-origin")
            .header("origin", "http://evil.test"))
        .await),
        refused
    );
    assert_eq!(
        bad(got(srv
            .request("GET", &page_url)
            .header("sec-fetch-site", "none"))
        .await),
        refused
    );
    assert_eq!(got(srv.request("POST", &page_url)).await.status, 404);
    // 1. Its parameters.
    assert_eq!(bad(browser.page(&app.client_id, "").await), refused);
    let g = got(browser.navigation(
        &format!(
            "/oauth/authorize?{}",
            form(&[("client_id", &app.client_id)])
        ),
        "none",
    ))
    .await;
    assert_eq!(bad(g), refused);
    assert_eq!(
        bad(browser.page(&app.client_id, "urn:other").await),
        refused
    );
    // 2. The client.
    assert_eq!(
        bad(browser
            .page("https://example.com/c.json", &pushed.request_uri)
            .await),
        (400, "invalid_client_metadata".into())
    );
    // 3. A request not kept.
    assert_eq!(
        bad(browser
            .page(&app.client_id, &format!("{REQUEST_URI}req-none"))
            .await),
        refused
    );
    // The page.
    let page = browser.page(&app.client_id, &pushed.request_uri).await;
    assert_eq!(page.status, 200, "{}", page.body);
    assert_eq!(page.header("cache-control").as_deref(), Some("no-store"));
    let cookies: Vec<String> = page
        .headers
        .get_all("set-cookie")
        .iter()
        .map(|c| c.to_str().unwrap().to_string())
        .collect();
    assert!(cookies.iter().any(|c| c.starts_with("device-id=")
        && c.contains("HttpOnly")
        && c.contains("SameSite=Lax")
        && c.contains("Path=/")));
    assert!(cookies.iter().any(|c| c.starts_with("csrf-token=")
        && !c.contains("HttpOnly")
        && c.contains("SameSite=Lax")));
    let data = page.page("__authorizeData").unwrap();
    assert_eq!(data["requestUri"], json!(pushed.request_uri));
    assert_eq!(data["clientId"], json!(app.client_id));
    assert_eq!(
        data["clientMetadata"]["redirect_uris"],
        json!([app.redirect_uri])
    );
    assert_eq!(
        data["clientMetadata"]["dpop_bound_access_tokens"],
        json!(true)
    );
    assert_eq!(
        (
            data["scope"].clone(),
            data["promptMode"].clone(),
            data["permissionSets"].clone()
        ),
        (
            json!("atproto transition:generic"),
            json!("consent"),
            json!({})
        )
    );
    assert_eq!(
        (
            data["clientTrusted"].clone(),
            data["clientFirstParty"].clone()
        ),
        (json!(false), json!(false))
    );
    assert_eq!(data["uiLocales"], json!("fr-CA en"));
    // A DID hint is shown as the account's handle; none is signed in here yet.
    assert_eq!(data["loginHint"], json!("alice.test"));
    assert!(data.get("selectedDid").is_none());
    assert_eq!(page.page("__sessions"), Some(json!([])));
    // Signed in and remembered, the account is listed, and selected by the hint.
    browser.api(&app.client_id, &pushed.request_uri, "sign-in", json!({ "locale": "en", "identifier": "alice.test", "password": "alice-pw", "remember": true }), None).await;
    let again = browser.page(&app.client_id, &pushed.request_uri).await;
    let sessions = again.page("__sessions").unwrap();
    assert_eq!(sessions[0]["loginRequired"], json!(false));
    let account = &sessions[0]["account"];
    assert_eq!(
        account,
        &json!({ "did": alice, "pds": "did:web:localhost", "email": "alice@mail.com", "emailVerified": false, "emailAuthFactor": false, "handle": "alice.test", "deactivated": false })
    );
    assert_eq!(
        again.page("__authorizeData").unwrap()["selectedDid"],
        json!(alice)
    );
    // Not when asked to create an account.
    let (_, create) = app
        .par(&[
            ("login_hint", Some("alice.test")),
            ("prompt", Some("create")),
        ])
        .await;
    let data = browser
        .page(&app.client_id, &create.request_uri)
        .await
        .page("__authorizeData")
        .unwrap();
    assert_eq!(
        (data["promptMode"].clone(), data.get("selectedDid")),
        (json!("create"), None)
    );
    // Another device: the request is ended, and the browser sent back with access_denied.
    let mut other = Browser::new(&srv);
    let g = other.page(&app.client_id, &pushed.request_uri).await;
    assert_eq!(g.status, 303);
    let (to, params) = g.location();
    assert_eq!(
        (
            to.as_str(),
            params["error"].as_str(),
            params["state"].as_str(),
            params["iss"].as_str()
        ),
        (
            app.redirect_uri.as_str(),
            "access_denied",
            pushed.state.as_str(),
            srv.iss().as_str()
        )
    );
    assert_eq!(
        bad(browser.page(&app.client_id, &pushed.request_uri).await),
        refused
    );
    // Another client, past its time, or approved: ended likewise.
    let (_, p) = app.par(&[("response_mode", Some("fragment"))]).await;
    let g = browser.page("http://localhost", &p.request_uri).await;
    assert_eq!(
        (g.status, g.location().1["error"].as_str()),
        (303, "access_denied")
    );
    assert!(g.header("location").unwrap().contains("#"));
    let (_, p) = app.par(&[("response_mode", Some("form_post"))]).await;
    srv.skew(REQUEST_LIFE);
    let g = browser.page(&app.client_id, &p.request_uri).await;
    srv.skew(0);
    assert_eq!(g.status, 200);
    assert!(
        g.body
            .contains("<form method=\"post\" action=\"http://127.0.0.1/cb\">")
            && g.body.contains("name=\"error\" value=\"access_denied\"")
    );
    let (p, code) = approved(&mut app, &mut browser, "alice").await;
    assert_eq!(
        browser
            .page(&app.client_id, &p.request_uri)
            .await
            .location()
            .1["error"],
        "access_denied"
    );
    // An approved request ended takes its code with it.
    assert_eq!(app.exchange(&code, &p).await.error(), "invalid_grant");
    // A week on, it must sign in again.
    srv.skew(LOGIN_LIFE + 1);
    let (_, later) = app.par(&[]).await;
    assert_eq!(
        browser
            .page(&app.client_id, &later.request_uri)
            .await
            .page("__sessions")
            .unwrap()[0]["loginRequired"],
        json!(true)
    );
    // Signing in again, remember left out, keeps it signed in here, from now.
    let again = json!({ "locale": "en", "identifier": "alice.test", "password": "alice-pw" });
    let g = browser
        .api(&app.client_id, &later.request_uri, "sign-in", again, None)
        .await;
    assert!(g.json().get("ephemeralToken").is_none(), "{}", g.body);
    let page = browser.page(&app.client_id, &later.request_uri).await;
    assert_eq!(
        page.page("__sessions").unwrap()[0]["loginRequired"],
        json!(false)
    );
    srv.skew(0);
    let _ = std::fs::remove_dir_all(&dir);
}

#[tokio::test]
async fn the_api() {
    let (dir, srv, _) = setup("oauth-api").await;
    let (alice_did, alice_token) = (
        srv.svc.account("alice.test").unwrap().did.clone(),
        crate::testing::session(&srv.svc, "alice").await,
    );
    let mut app = App::new(&srv, "atproto transition:generic transition:email");
    let mut browser = Browser::new(&srv);
    let (_, pushed) = app.par(&[]).await;
    browser.page(&app.client_id, &pushed.request_uri).await;
    let cid = app.client_id.clone();
    let sign_in = json!({ "locale": "en", "identifier": "alice.test", "password": "alice-pw" });
    // Checks 1-5, each refused alone.
    let refused = |g: Got| (g.status, g.error());
    let req = |over: &[(&str, &str)]| {
        browser.api_request(&cid, &pushed.request_uri, "sign-in", &sign_in, over)
    };
    let invalid = (400, "invalid_request".to_string());
    let (other_page, bad_request_uri) = (
        format!("{}/oauth/other", srv.iss()),
        format!("{}/oauth/authorize?request_uri=x", srv.iss()),
    );
    for over in [
        [("sec-fetch-mode", "cors")],
        [("sec-fetch-mode", "")],
        [("sec-fetch-site", "cross-site")],
        [("origin", "http://evil.test")],
        [("referer", "")],
        [("referer", other_page.as_str())],
        [("referer", bad_request_uri.as_str())],
        [("x-csrf-token", "forged")],
        [("x-csrf-token", "")],
    ] {
        assert_eq!(refused(got(req(&over)).await), invalid, "{over:?}");
    }
    assert_eq!(
        refused(got(req(&[("content-type", "text/plain")])).await),
        (415, "invalid_request".into())
    );
    // No Origin is taken.
    assert_eq!(got(req(&[("origin", "")])).await.status, 200);
    for body in [
        json!({ "locale": "en", "identifier": "alice.test" }),
        json!({ "locale": "en", "identifier": "alice.test", "password": "alice-pw", "extra": 1 }),
        json!({ "locale": "english", "identifier": "alice.test", "password": "alice-pw" }),
        json!({ "locale": "en", "identifier": "alice.test", "password": "" }),
        json!({ "locale": "en", "identifier": "alice.test", "password": "alice-pw", "remember": "yes" }),
        json!({ "locale": "en", "identifier": "not an identifier", "password": "alice-pw" }),
        json!({ "locale": "en", "identifier": "alice@mail.c1", "password": "alice-pw" }),
    ] {
        assert_eq!(
            refused(
                browser
                    .api(&cid, &pushed.request_uri, "sign-in", body.clone(), None)
                    .await
            ),
            invalid,
            "{body}"
        );
    }
    assert_eq!(
        got(srv.request("GET", "/@atproto/oauth-provider/~api/sign-in"))
            .await
            .status,
        404
    );
    assert_eq!(
        got(srv.request("POST", "/@atproto/oauth-provider/~api/other"))
            .await
            .status,
        404
    );
    // A wrong password, an app password, an account without one.
    let wrong = json!({ "locale": "en", "identifier": "alice.test", "password": "nope" });
    assert_eq!(
        refused(
            browser
                .api(&cid, &pushed.request_uri, "sign-in", wrong, None)
                .await
        ),
        invalid
    );
    let app_pw = crate::testing::call(
        &srv.svc,
        "com.atproto.server.createAppPassword",
        Some(&alice_token),
        json!({ "name": "x" }),
    )
    .await
    .unwrap();
    let with_app_pw =
        json!({ "locale": "en", "identifier": "alice.test", "password": app_pw["password"] });
    assert_eq!(
        refused(
            browser
                .api(&cid, &pushed.request_uri, "sign-in", with_app_pw, None)
                .await
        ),
        invalid
    );
    // Consent before signing in on this device: ended, with invalid_request.
    let consent = browser
        .api(
            &cid,
            &pushed.request_uri,
            "consent",
            json!({ "did": alice_did }),
            None,
        )
        .await;
    assert_eq!(consent.status, 200);
    assert!(
        consent.json()["url"]
            .as_str()
            .unwrap()
            .contains("error=invalid_request")
    );
    assert_eq!(
        refused(
            browser
                .api(
                    &cid,
                    &pushed.request_uri,
                    "consent",
                    json!({ "did": alice_did }),
                    None
                )
                .await
        ),
        invalid
    );
    assert_eq!(
        refused(
            browser
                .api(&cid, &pushed.request_uri, "reject", json!({}), None)
                .await
        ),
        invalid
    );
    // Signing in without remembering: an ephemeral token, for this request alone.
    let (_, pushed) = app.par(&[]).await;
    browser.page(&cid, &pushed.request_uri).await;
    let signed = browser
        .api(&cid, &pushed.request_uri, "sign-in", sign_in.clone(), None)
        .await;
    assert_eq!(signed.status, 200, "{}", signed.body);
    assert_eq!(signed.json()["account"]["did"], json!(alice_did));
    let eph = text(&signed.json(), "ephemeralToken");
    assert!(!eph.is_empty());
    assert_eq!(
        browser
            .page(&cid, &pushed.request_uri)
            .await
            .page("__sessions"),
        Some(json!([]))
    );
    // Malformed scope or did: 400 with no url, the request kept.
    assert_eq!(
        refused(
            browser
                .api(
                    &cid,
                    &pushed.request_uri,
                    "consent",
                    json!({ "did": alice_did, "scope": "atproto " }),
                    Some(&eph)
                )
                .await
        ),
        invalid
    );
    assert_eq!(
        refused(
            browser
                .api(
                    &cid,
                    &pushed.request_uri,
                    "consent",
                    json!({ "did": "alice" }),
                    Some(&eph)
                )
                .await
        ),
        invalid
    );
    // Another request's ephemeral token does not do.
    let (_, other) = app.par(&[]).await;
    browser.page(&cid, &other.request_uri).await;
    let g = browser
        .api(
            &cid,
            &other.request_uri,
            "consent",
            json!({ "did": alice_did }),
            Some(&eph),
        )
        .await;
    assert!(
        g.json()["url"]
            .as_str()
            .unwrap()
            .contains("error=invalid_request")
    );
    // Consent narrows, never widens: a token the request lacks is dropped.
    let g = browser
        .api(
            &cid,
            &pushed.request_uri,
            "consent",
            json!({ "did": alice_did, "scope": "transition:email atproto repo:*" }),
            Some(&eph),
        )
        .await;
    let url = url::Url::parse(g.json()["url"].as_str().unwrap()).unwrap();
    assert!(
        url.as_str()
            .starts_with(&format!("{}/oauth/authorize/redirect?", srv.iss()))
    );
    let q: HashMap<String, String> = url.query_pairs().into_owned().collect();
    assert_eq!(
        (
            q["redirect_mode"].as_str(),
            q["redirect_uri"].as_str(),
            q["iss"].as_str(),
            q["state"].as_str()
        ),
        (
            "query",
            app.redirect_uri.as_str(),
            srv.iss().as_str(),
            pushed.state.as_str()
        )
    );
    let id = request_id_of(&pushed.request_uri);
    assert_eq!(
        srv.svc.oauth.snapshot().requests[id]
            .approval
            .as_ref()
            .unwrap()
            .scope,
        ["atproto", "transition:email"]
    );
    // Approved: it cannot be approved again, and that ends it.
    let g = browser
        .api(
            &cid,
            &pushed.request_uri,
            "consent",
            json!({ "did": alice_did }),
            Some(&eph),
        )
        .await;
    assert!(
        g.json()["url"]
            .as_str()
            .unwrap()
            .contains("error=access_denied")
    );
    assert!(!srv.svc.oauth.snapshot().requests.contains_key(id));
    // A narrowed scope without atproto is denied.
    let (_, p) = app.par(&[]).await;
    browser.page(&cid, &p.request_uri).await;
    let eph = text(
        &browser
            .api(&cid, &p.request_uri, "sign-in", sign_in.clone(), None)
            .await
            .json(),
        "ephemeralToken",
    );
    let g = browser
        .api(
            &cid,
            &p.request_uri,
            "consent",
            json!({ "did": alice_did, "scope": "transition:generic" }),
            Some(&eph),
        )
        .await;
    assert!(
        g.json()["url"]
            .as_str()
            .unwrap()
            .contains("error=access_denied")
    );
    // Reject.
    let (_, p) = app.par(&[]).await;
    browser.page(&cid, &p.request_uri).await;
    let g = browser
        .api(&cid, &p.request_uri, "reject", json!({}), None)
        .await;
    let url = g.json()["url"].as_str().unwrap().to_string();
    assert!(url.contains("error=access_denied"));
    // The redirect: its checks, then where it sends the browser.
    let back = browser.follow(&url, &cid, &p.request_uri).await;
    assert_eq!(back.status, 303);
    assert_eq!(back.location().1["error"], "access_denied");
    let path = url.strip_prefix(&srv.iss()).unwrap();
    assert_eq!(
        refused(got(browser.navigation(path, "same-origin")).await),
        invalid
    );
    let referer = format!("{}{}", srv.iss(), browser.page_url(&cid, &p.request_uri));
    assert_eq!(
        refused(
            got(browser
                .navigation(path, "cross-site")
                .header("referer", &referer))
            .await
        ),
        invalid
    );
    let neither = format!(
        "/oauth/authorize/redirect?{}",
        form(&[
            ("redirect_mode", "query"),
            ("redirect_uri", "http://127.0.0.1/cb"),
            ("state", "s")
        ])
    );
    assert_eq!(
        refused(
            got(browser
                .navigation(&neither, "same-origin")
                .header("referer", &referer))
            .await
        ),
        invalid
    );
    let fragment = format!(
        "/oauth/authorize/redirect?{}",
        form(&[
            ("redirect_mode", "fragment"),
            ("redirect_uri", "http://127.0.0.1/cb"),
            ("code", "c"),
            ("state", "s"),
            ("iss", "i")
        ])
    );
    let g = got(browser
        .navigation(&fragment, "same-origin")
        .header("referer", &referer))
    .await;
    assert_eq!(
        g.header("location").as_deref(),
        Some("http://127.0.0.1/cb#state=s&iss=i&code=c")
    );
    // Remember, then sign out.
    let remember = json!({ "locale": "en", "identifier": alice_did, "password": "alice-pw", "remember": true });
    let g = browser
        .api(&cid, &p.request_uri, "sign-in", remember, None)
        .await;
    assert!(g.json().get("ephemeralToken").is_none());
    let (_, p) = app.par(&[]).await;
    assert_eq!(
        browser
            .page(&cid, &p.request_uri)
            .await
            .page("__sessions")
            .unwrap()
            .as_array()
            .unwrap()
            .len(),
        1
    );
    // Signed in on this device, consent needs no token.
    let g = browser
        .api(
            &cid,
            &p.request_uri,
            "consent",
            json!({ "did": alice_did }),
            None,
        )
        .await;
    assert!(g.json()["url"].as_str().unwrap().contains("code="));
    assert_eq!(
        browser
            .api(
                &cid,
                &p.request_uri,
                "sign-out",
                json!({ "did": alice_did }),
                None
            )
            .await
            .json(),
        json!({ "success": true })
    );
    let (_, p) = app.par(&[]).await;
    assert_eq!(
        browser.page(&cid, &p.request_uri).await.page("__sessions"),
        Some(json!([]))
    );
    let _ = std::fs::remove_dir_all(&dir);
}

/// A sign-in on `browser`'s page of a new request.
async fn sign_in_with(app: &mut App<'_>, browser: &mut Browser<'_>, body: Json) -> Got {
    let (_, pushed) = app.par(&[]).await;
    browser.page(&app.client_id, &pushed.request_uri).await;
    browser
        .api(&app.client_id, &pushed.request_uri, "sign-in", body, None)
        .await
}

fn signing_in(id: &str, pw: &str) -> Json {
    json!({ "locale": "en", "identifier": id, "password": pw })
}

#[tokio::test]
async fn sign_in_pays_the_login_limits() {
    let plc = plc().await;
    let dir = scratch("oauth-sign-in-limits");
    let srv = serve(crate::testing::open_with(&dir, &plc, |c| {
        c.rate_limits = true
    }))
    .await;
    create(&srv.svc, "alice").await;
    let mut app = App::new(&srv, "atproto");
    let mut browser = Browser::new(&srv);
    let create_session = |id: &str, pw: &str| {
        got(srv
            .request("POST", "/xrpc/com.atproto.server.createSession")
            .header("content-type", "application/json")
            .body(json!({ "identifier": id, "password": pw }).to_string()))
    };
    // 20 wrong passwords by createSession and 10 by the sign-in, from one
    // address (the tests' connections carry none: all are ""), count together.
    for _ in 0..20 {
        assert_eq!(create_session("alice.test", "wrong").await.status, 401);
    }
    for _ in 0..10 {
        let g = sign_in_with(&mut app, &mut browser, signing_in("alice.test", "wrong")).await;
        assert_eq!(
            (g.status, g.error()),
            (400, "invalid_request".into()),
            "{}",
            g.body
        );
        assert_eq!(g.header("ratelimit-limit"), None);
    }
    // Then the right password is refused by either.
    let g = sign_in_with(&mut app, &mut browser, signing_in("alice.test", "alice-pw")).await;
    assert_eq!(
        (g.status, g.error()),
        (429, "invalid_request".into()),
        "{}",
        g.body
    );
    assert!(g.json()["error_description"].is_string());
    let retry: u64 = g.header("retry-after").unwrap().parse().unwrap();
    assert!((1..=300).contains(&retry), "{retry}");
    assert!(
        g.headers
            .keys()
            .all(|k| !k.as_str().starts_with("ratelimit-")),
        "{:?}",
        g.headers
    );
    assert_eq!(create_session("alice.test", "alice-pw").await.status, 429);
    // Another case of the identifier is another key.
    let g = sign_in_with(&mut app, &mut browser, signing_in("ALICE.TEST", "alice-pw")).await;
    assert_eq!(g.status, 200, "{}", g.body);
    // A body the check refuses costs nothing.
    for _ in 0..40 {
        assert_eq!(
            sign_in_with(&mut app, &mut browser, signing_in("bob.test", ""))
                .await
                .status,
            400
        );
    }
    let g = sign_in_with(&mut app, &mut browser, signing_in("bob.test", "x")).await;
    assert_eq!(
        (g.status, g.header("retry-after")),
        (400, None),
        "{}",
        g.body
    );
    // Five minutes on, the right one is taken again.
    srv.svc.limits.clock.skew.store(301, SeqCst);
    assert_eq!(
        sign_in_with(&mut app, &mut browser, signing_in("alice.test", "alice-pw"))
            .await
            .status,
        200
    );
    drop(srv);
    let _ = std::fs::remove_dir_all(&dir);
}

#[tokio::test]
async fn sign_in_takes_its_time() {
    let plc = plc().await;
    let dir = scratch("oauth-sign-in-time");
    let srv = serve(crate::testing::open_with(&dir, &plc, |c| {
        c.sign_in_floor = std::time::Duration::from_millis(400)
    }))
    .await;
    create(&srv.svc, "alice").await;
    let mut app = App::new(&srv, "atproto");
    let mut browser = Browser::new(&srv);
    for (id, pw, status) in [
        ("nobody.test", "x", 400),
        ("alice.test", "x", 400),
        ("alice.test", "alice-pw", 200),
    ] {
        let (_, pushed) = app.par(&[]).await;
        browser.page(&app.client_id, &pushed.request_uri).await;
        let started = std::time::Instant::now();
        let g = browser
            .api(
                &app.client_id,
                &pushed.request_uri,
                "sign-in",
                signing_in(id, pw),
                None,
            )
            .await;
        let took = started.elapsed();
        assert_eq!(g.status, status, "{id}: {}", g.body);
        assert!(
            took >= std::time::Duration::from_millis(400),
            "{id}: {took:?}"
        );
        assert!(
            took < std::time::Duration::from_millis(1500),
            "{id}: {took:?}"
        );
    }
    drop(srv);
    let _ = std::fs::remove_dir_all(&dir);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn sign_in_hashes_on_the_hash_threads() {
    let (dir, srv, _) = setup("oauth-sign-in-hashes").await;
    let mut app = App::new(&srv, "atproto");
    let (mut one, mut two) = (Browser::new(&srv), Browser::new(&srv));
    let mut pages = Vec::new();
    for browser in [&mut one, &mut two] {
        let (_, pushed) = app.par(&[]).await;
        browser.page(&app.client_id, &pushed.request_uri).await;
        pages.push(pushed.request_uri);
    }
    // Every hash thread busy, held until the gate opens.
    let gate = std::sync::Arc::new(tokio::sync::RwLock::new(()));
    let closed = gate.write().await;
    let busy = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
    let cores = std::thread::available_parallelism().unwrap().get();
    let held: Vec<_> = (0..cores)
        .map(|_| {
            let (svc, gate, busy) = (srv.svc.clone(), gate.clone(), busy.clone());
            tokio::spawn(async move {
                svc.limits
                    .hashes
                    .run(move || {
                        busy.fetch_add(1, SeqCst);
                        drop(gate.blocking_read());
                    })
                    .await
            })
        })
        .collect();
    while busy.load(SeqCst) < cores {
        tokio::time::sleep(std::time::Duration::from_millis(5)).await;
    }
    // A sign-in, of an account and of no account, waits for a hash thread.
    let cid = app.client_id.clone();
    let signed = async {
        tokio::join!(
            one.api(
                &cid,
                &pages[0],
                "sign-in",
                signing_in("alice.test", "alice-pw"),
                None
            ),
            two.api(
                &cid,
                &pages[1],
                "sign-in",
                signing_in("nobody.test", "alice-pw"),
                None
            ),
        )
    };
    tokio::pin!(signed);
    assert!(
        tokio::time::timeout(std::time::Duration::from_millis(500), &mut signed)
            .await
            .is_err(),
        "a sign-in hashed while every hash thread was busy"
    );
    drop(closed);
    let (known, unknown) = signed.await;
    assert_eq!(
        (known.status, unknown.status),
        (200, 400),
        "{} {}",
        known.body,
        unknown.body
    );
    for h in held {
        h.await.unwrap().unwrap();
    }
    let _ = std::fs::remove_dir_all(&dir);
}

#[tokio::test]
async fn sign_in_with_the_email_factor() {
    use crate::email::testing::{open_with_sink, sent};
    let plc = plc().await;
    let (dir, sink) = (scratch("oauth-factor"), scratch("oauth-factor-mail"));
    let srv = serve(open_with_sink(&dir, &plc, &sink)).await;
    let (_, token) = create(&srv.svc, "alice").await;
    let call =
        |nsid: &'static str, body: Json| crate::testing::call(&srv.svc, nsid, Some(&token), body);
    call("com.atproto.server.requestEmailConfirmation", Json::Null)
        .await
        .unwrap();
    let confirm = sent(&sink).last().unwrap()["token"].clone();
    call(
        "com.atproto.server.confirmEmail",
        json!({ "email": "alice@mail.com", "token": confirm }),
    )
    .await
    .unwrap();
    call(
        "com.atproto.server.updateEmail",
        json!({ "email": "alice@mail.com", "emailAuthFactor": true }),
    )
    .await
    .unwrap();
    let app_pw = call(
        "com.atproto.server.createAppPassword",
        json!({ "name": "x" }),
    )
    .await
    .unwrap()["password"]
        .clone();
    let mut app = App::new(&srv, "atproto");
    let mut browser = Browser::new(&srv);
    let with = |extra: Json| {
        let mut b = json!({ "locale": "en", "identifier": "alice.test", "password": "alice-pw", "remember": true });
        b.as_object_mut()
            .unwrap()
            .extend(extra.as_object().unwrap().clone());
        b
    };
    // The right password alone: a code mailed, and 401, nothing signed in.
    let mails = sent(&sink).len();
    let g = sign_in_with(&mut app, &mut browser, with(json!({}))).await;
    assert_eq!(
        (g.status, g.error()),
        (401, "second_authentication_factor_required".into()),
        "{}",
        g.body
    );
    assert!(g.json()["error_description"].is_string());
    let mail = sent(&sink);
    assert_eq!(mail.len(), mails + 1);
    assert_eq!(
        (&mail[mails]["to"], &mail[mails]["kind"]),
        (&json!("alice@mail.com"), &json!("signInAuthFactor"))
    );
    let first = mail[mails]["token"].as_str().unwrap().to_string();
    let (_, p) = app.par(&[]).await;
    assert_eq!(
        browser
            .page(&app.client_id, &p.request_uri)
            .await
            .page("__sessions"),
        Some(json!([]))
    );
    // The empty code is none; a wrong one is refused; an app password signs in in no case.
    assert_eq!(
        sign_in_with(&mut app, &mut browser, with(json!({ "emailOtp": "" })))
            .await
            .status,
        401
    );
    let code = sent(&sink).last().unwrap()["token"]
        .as_str()
        .unwrap()
        .to_string();
    assert_ne!(code, first);
    let g = sign_in_with(
        &mut app,
        &mut browser,
        with(json!({ "emailOtp": "AAAAA-AAAAA" })),
    )
    .await;
    assert_eq!(
        (g.status, g.error()),
        (400, "invalid_request".into()),
        "{}",
        g.body
    );
    let g = sign_in_with(
        &mut app,
        &mut browser,
        with(json!({ "password": app_pw, "emailOtp": code })),
    )
    .await;
    assert_eq!(
        (g.status, g.error()),
        (400, "invalid_request".into()),
        "{}",
        g.body
    );
    // The code, in lower case too, signs in, and is used up.
    let g = sign_in_with(
        &mut app,
        &mut browser,
        with(json!({ "emailOtp": code.to_lowercase() })),
    )
    .await;
    assert_eq!(g.status, 200, "{}", g.body);
    let mut elsewhere = Browser::new(&srv);
    let g = sign_in_with(&mut app, &mut elsewhere, with(json!({ "emailOtp": code }))).await;
    assert_eq!(
        (g.status, g.error()),
        (400, "invalid_request".into()),
        "{}",
        g.body
    );
    // The device it signed in on, remembered, needs no code, and mails none.
    let mails = sent(&sink).len();
    assert_eq!(
        sign_in_with(&mut app, &mut browser, with(json!({})))
            .await
            .status,
        200
    );
    assert_eq!(sent(&sink).len(), mails);
    // Another device does.
    assert_eq!(
        sign_in_with(&mut app, &mut elsewhere, with(json!({})))
            .await
            .status,
        401
    );
    // Past 30 days, so does the remembered one.
    srv.skew(30 * 24 * 60 * 60 + 1);
    assert_eq!(
        sign_in_with(&mut app, &mut browser, with(json!({})))
            .await
            .status,
        401
    );
    // With the code, the factor is used up across restarts: kept in the log.
    let code = sent(&sink).last().unwrap()["token"]
        .as_str()
        .unwrap()
        .to_string();
    assert_eq!(
        sign_in_with(&mut app, &mut browser, with(json!({ "emailOtp": code })))
            .await
            .status,
        200
    );
    let cookies = browser.cookies.clone();
    drop(srv);
    let srv = serve(open_with_sink(&dir, &plc, &sink)).await;
    srv.skew(30 * 24 * 60 * 60 + 1);
    let mut app = App::new(&srv, "atproto");
    let mut browser = Browser { srv: &srv, cookies };
    let g = sign_in_with(&mut app, &mut browser, with(json!({ "emailOtp": code }))).await;
    assert_eq!(
        (g.status, g.error()),
        (400, "invalid_request".into()),
        "{}",
        g.body
    );
    assert_eq!(
        sign_in_with(&mut app, &mut browser, with(json!({})))
            .await
            .status,
        200
    );
    drop(srv);
    let _ = std::fs::remove_dir_all(&dir);
    let _ = std::fs::remove_dir_all(&sink);
}

/// How many accounts a new request's page lists as signed in on `browser`.
async fn listed(app: &mut App<'_>, browser: &mut Browser<'_>) -> usize {
    let (_, pushed) = app.par(&[]).await;
    browser
        .page(&app.client_id, &pushed.request_uri)
        .await
        .page("__sessions")
        .unwrap()
        .as_array()
        .unwrap()
        .len()
}

#[tokio::test]
async fn sign_in_renews_the_device_cookies() {
    const DEVICE_COOKIE: &str = "device-id";
    let (dir, srv, plc) = setup("oauth-device-cookies").await;
    let mut app = App::new(&srv, "atproto");
    let mut first = Browser::new(&srv);
    assert_eq!(listed(&mut app, &mut first).await, 0);
    let copy = |b: &Browser<'_>| b.cookies.clone();
    let mut second = Browser {
        srv: &srv,
        cookies: copy(&first),
    };
    let before = first.cookie(DEVICE_COOKIE).unwrap();
    // A sign-in gives the device new cookies.
    let remember = json!({ "locale": "en", "identifier": "alice.test", "password": "alice-pw", "remember": true });
    assert_eq!(
        sign_in_with(&mut app, &mut first, remember.clone())
            .await
            .status,
        200
    );
    let renewed = first.cookie(DEVICE_COOKIE).unwrap();
    assert_ne!(renewed, before);
    // A refused sign-in gives none.
    let wrong = json!({ "locale": "en", "identifier": "alice.test", "password": "wrong" });
    let mut third = Browser {
        srv: &srv,
        cookies: copy(&first),
    };
    assert_eq!(sign_in_with(&mut app, &mut third, wrong).await.status, 400);
    assert_eq!(third.cookie(DEVICE_COOKIE).unwrap(), renewed);
    // At once, the old cookies are still the device, and are given the new ones.
    assert_eq!(listed(&mut app, &mut second).await, 1);
    assert_eq!(second.cookie(DEVICE_COOKIE).unwrap(), renewed);
    assert_eq!(listed(&mut app, &mut first).await, 1);
    // A sign-in that does not remember the account renews them too.
    let mut older = Browser {
        srv: &srv,
        cookies: copy(&first),
    };
    let again = json!({ "locale": "en", "identifier": "alice.test", "password": "alice-pw" });
    assert_eq!(sign_in_with(&mut app, &mut first, again).await.status, 200);
    assert_ne!(first.cookie(DEVICE_COOKIE).unwrap(), renewed);
    // Within 30 seconds, the old ones are still the device.
    srv.skew(29);
    assert_eq!(
        listed(
            &mut app,
            &mut Browser {
                srv: &srv,
                cookies: copy(&older)
            }
        )
        .await,
        1
    );
    // Past that, they end it: signed out for every browser holding any of
    // its cookies, and the browser that sent them is a new device.
    srv.skew(31);
    assert_eq!(listed(&mut app, &mut older).await, 0);
    assert_ne!(
        older.cookie(DEVICE_COOKIE).unwrap(),
        first.cookie(DEVICE_COOKIE).unwrap()
    );
    assert_eq!(listed(&mut app, &mut first).await, 0);
    assert_eq!(listed(&mut app, &mut second).await, 0);
    // On the new device it signs in again; the ended device stays ended across a restart.
    assert_eq!(
        sign_in_with(&mut app, &mut older, remember).await.status,
        200
    );
    let cookies = (copy(&first), copy(&older));
    drop(app);
    drop((first, second, third, older));
    drop(srv);
    let srv = serve(open(&dir, &plc)).await;
    srv.skew(31);
    let mut app = App::new(&srv, "atproto");
    assert_eq!(
        listed(
            &mut app,
            &mut Browser {
                srv: &srv,
                cookies: cookies.0
            }
        )
        .await,
        0
    );
    assert_eq!(
        listed(
            &mut app,
            &mut Browser {
                srv: &srv,
                cookies: cookies.1
            }
        )
        .await,
        1
    );
    drop(app);
    drop(srv);
    let _ = std::fs::remove_dir_all(&dir);
}

#[tokio::test]
async fn tokens_and_rotation() {
    let (dir, srv, _) = setup("oauth-token").await;
    let alice = srv.svc.account("alice.test").unwrap().did.clone();
    let mut app = App::new(&srv, "atproto transition:generic");
    let mut browser = Browser::new(&srv);
    // The token endpoint's checks, in order.
    let refused = |g: Got| (g.status, g.error());
    let grant = (400, "invalid_grant".to_string());
    let g = got(srv
        .request("POST", "/oauth/token")
        .header("content-type", "application/json")
        .body("["))
    .await;
    assert_eq!(refused(g), (400, "invalid_request".into()));
    assert_eq!(
        refused(
            app.call(
                "/oauth/token",
                &[("grant_type", "refresh_token"), ("refresh_token", "x")]
            )
            .await
        ),
        grant
    );
    for pairs in [
        vec![("grant_type", "implicit")],
        vec![
            ("grant_type", "authorization_code"),
            ("code", "c"),
            ("code_verifier", &"a".repeat(43)),
        ],
        vec![
            ("grant_type", "authorization_code"),
            ("code", "c"),
            ("redirect_uri", "http://localhost/cb"),
        ],
        vec![
            ("grant_type", "authorization_code"),
            ("code", "c"),
            ("redirect_uri", "http://127.0.0.1/cb"),
            ("code_verifier", "short"),
        ],
        vec![("grant_type", "refresh_token")],
    ] {
        assert_eq!(refused(app.token(&pairs).await), grant, "{pairs:?}");
    }
    let bad_client = form(&[
        ("client_id", "https://example.com/"),
        ("grant_type", "refresh_token"),
        ("refresh_token", "x"),
    ]);
    let p = app.proof("POST", "/oauth/token", None);
    assert_eq!(
        refused(app.send("/oauth/token", &bad_client, &[p]).await),
        (400, "invalid_client_metadata".into())
    );
    let no_proof = form(&[
        ("client_id", &app.client_id),
        ("grant_type", "refresh_token"),
        ("refresh_token", "x"),
    ]);
    let g = app.send("/oauth/token", &no_proof, &[]).await;
    assert_eq!(
        (g.status, g.error(), g.www_error()),
        (
            401,
            "invalid_dpop_proof".into(),
            Some("invalid_dpop_proof".into())
        )
    );
    assert_eq!(
        refused(app.token(&[("grant_type", "password")]).await),
        grant
    );
    // A full sign-in.
    let t = sign_in(&mut app, &mut browser, "alice", None).await;
    assert_eq!(t.status, 200, "{}", t.body);
    assert_eq!(
        (
            t.header("cache-control").as_deref(),
            t.header("pragma").as_deref()
        ),
        (Some("no-store"), Some("no-cache"))
    );
    let j = t.json();
    assert_eq!(
        (
            j["token_type"].clone(),
            j["scope"].clone(),
            j["sub"].clone()
        ),
        (
            json!("DPoP"),
            json!("atproto transition:generic"),
            json!(alice)
        )
    );
    assert!((899..=900).contains(&j["expires_in"].as_u64().unwrap()));
    let b64token = |s: &str| {
        !s.is_empty()
            && s.bytes()
                .all(|b| b.is_ascii_alphanumeric() || b"-._~+/".contains(&b))
    };
    let (access, refresh) = (text(&j, "access_token"), text(&j, "refresh_token"));
    assert!(b64token(&access) && b64token(&refresh));
    let s = app.get_session(&access).await;
    assert_eq!(s.status, 200, "{}", s.body);
    assert_eq!(
        s.json(),
        json!({ "did": alice, "handle": "alice.test", "active": true })
    );
    // Refresh: new tokens replace the old at once.
    let r = app.refresh(&refresh).await;
    assert_eq!(r.status, 200, "{}", r.body);
    let (access2, refresh2) = (
        text(&r.json(), "access_token"),
        text(&r.json(), "refresh_token"),
    );
    assert_eq!(r.json()["scope"], j["scope"]);
    assert_eq!(app.get_session(&access).await.error(), "invalid_token");
    assert_eq!(app.get_session(&access2).await.status, 200);
    // A replaced refresh token is refused, and ends the session.
    assert_eq!(refused(app.refresh(&refresh).await), grant);
    assert_eq!(app.get_session(&access2).await.error(), "invalid_token");
    assert_eq!(refused(app.refresh(&refresh2).await), grant);
    // Another key, or another client, ends it too.
    let t = sign_in(&mut app, &mut browser, "alice", None).await;
    let (access, refresh) = (
        text(&t.json(), "access_token"),
        text(&t.json(), "refresh_token"),
    );
    let key = std::mem::replace(&mut app.key, Key::new());
    assert_eq!(refused(app.refresh(&refresh).await), grant);
    app.key = key;
    assert_eq!(app.get_session(&access).await.error(), "invalid_token");
    let t = sign_in(&mut app, &mut browser, "alice", None).await;
    let refresh = text(&t.json(), "refresh_token");
    let client_id = std::mem::replace(&mut app.client_id, "http://localhost".into());
    assert_eq!(refused(app.refresh(&refresh).await), grant);
    app.client_id = client_id;
    assert_eq!(refused(app.refresh(&refresh).await), grant);
    // Two weeks on, the session is over.
    let t = sign_in(&mut app, &mut browser, "alice", None).await;
    srv.skew(SESSION_LIFE - ACCESS_LIFE / 2);
    let r = app.refresh(&text(&t.json(), "refresh_token")).await;
    assert_eq!(r.status, 200);
    assert!(r.json()["expires_in"].as_u64().unwrap() <= ACCESS_LIFE / 2);
    srv.skew(SESSION_LIFE);
    assert_eq!(
        refused(app.refresh(&text(&r.json(), "refresh_token")).await),
        grant
    );
    srv.skew(0);
    // The access token lasts its expires_in.
    let t = sign_in(&mut app, &mut browser, "alice", None).await;
    let access = text(&t.json(), "access_token");
    srv.skew(ACCESS_LIFE);
    assert_eq!(app.get_session(&access).await.error(), "invalid_token");
    srv.skew(0);
    let _ = std::fs::remove_dir_all(&dir);
}

#[tokio::test]
async fn codes() {
    let (dir, srv, _) = setup("oauth-codes").await;
    let mut app = App::new(&srv, "atproto");
    let mut browser = Browser::new(&srv);
    let grant = "invalid_grant";
    // Each thing wrong refuses the code, and spends it.
    for wrong in ["key", "redirect", "verifier", "none", "late"] {
        let (pushed, code) = approved(&mut app, &mut browser, "alice").await;
        let g = match wrong {
            "key" => {
                let key = std::mem::replace(&mut app.key, Key::new());
                let g = app.exchange(&code, &pushed).await;
                app.key = key;
                g
            }
            "redirect" => {
                app.token(&[
                    ("grant_type", "authorization_code"),
                    ("code", &code),
                    ("redirect_uri", "http://127.0.0.1:9/cb"),
                    ("code_verifier", &pushed.verifier),
                ])
                .await
            }
            "verifier" => {
                app.token(&[
                    ("grant_type", "authorization_code"),
                    ("code", &code),
                    ("redirect_uri", "http://127.0.0.1/cb"),
                    ("code_verifier", &"x".repeat(43)),
                ])
                .await
            }
            "none" => {
                app.token(&[
                    ("grant_type", "authorization_code"),
                    ("code", &code),
                    ("redirect_uri", "http://127.0.0.1/cb"),
                ])
                .await
            }
            _ => {
                srv.skew(CODE_LIFE);
                let g = app.exchange(&code, &pushed).await;
                srv.skew(0);
                g
            }
        };
        assert_eq!(g.error(), grant, "{wrong}");
        assert_eq!(
            app.exchange(&code, &pushed).await.error(),
            grant,
            "{wrong} spends it"
        );
        // And ends its request: its page is no more.
        let page = browser.page(&app.client_id, &pushed.request_uri).await;
        assert_eq!(
            (page.status, page.error()),
            (400, "invalid_request".into()),
            "{wrong}"
        );
    }
    // A code used twice ends the session the first use made.
    let (pushed, code) = approved(&mut app, &mut browser, "alice").await;
    let t = app.exchange(&code, &pushed).await;
    assert_eq!(t.status, 200);
    let page = browser.page(&app.client_id, &pushed.request_uri).await;
    assert_eq!((page.status, page.error()), (400, "invalid_request".into()));
    let consent = browser
        .api(
            &app.client_id,
            &pushed.request_uri,
            "consent",
            json!({ "did": t.json()["sub"] }),
            None,
        )
        .await;
    assert_eq!(
        (consent.status, consent.error()),
        (400, "invalid_request".into())
    );
    let access = text(&t.json(), "access_token");
    assert_eq!(app.get_session(&access).await.status, 200);
    assert_eq!(app.exchange(&code, &pushed).await.error(), grant);
    assert_eq!(app.get_session(&access).await.error(), "invalid_token");
    assert_eq!(
        app.refresh(&text(&t.json(), "refresh_token")).await.error(),
        grant
    );
    // Another client cannot exchange it.
    let (pushed, code) = approved(&mut app, &mut browser, "alice").await;
    let client_id = std::mem::replace(
        &mut app.client_id,
        "http://localhost?redirect_uri=http://127.0.0.1/cb".into(),
    );
    assert_eq!(app.exchange(&code, &pushed).await.error(), grant);
    app.client_id = client_id;
    let _ = std::fs::remove_dir_all(&dir);
}

#[tokio::test]
async fn a_request_with_no_key_takes_the_token_requests() {
    let (dir, srv, _) = setup("oauth-codes-keyless").await;
    let mut app = App::new(&srv, "atproto");
    let mut browser = Browser::new(&srv);
    let grant = "invalid_grant";
    // Pushed with no proof and no `dpop_jkt`, it takes the key its code is
    // exchanged with, and its session is bound to it.
    let (g, pushed) = app.par_unproven(&[]).await;
    assert_eq!(g.status, 201, "{}", g.body);
    let code = approve(&app, &mut browser, "alice", &pushed).await;
    let t = app.exchange(&code, &pushed).await;
    assert_eq!(t.status, 200, "{}", t.body);
    let jkt = app.key.jkt();
    let st = srv.svc.oauth.snapshot();
    assert_eq!(
        st.sessions
            .values()
            .filter(|s| s.code == code)
            .map(|s| s.jkt.as_str())
            .collect::<Vec<_>>(),
        [jkt.as_str()]
    );
    let access = text(&t.json(), "access_token");
    assert_eq!(app.get_session(&access).await.status, 200);
    let r = app.refresh(&text(&t.json(), "refresh_token")).await;
    assert_eq!(r.status, 200, "{}", r.body);
    // A second key is then refused, as for any session, and ends it.
    let key = std::mem::replace(&mut app.key, Key::new());
    let refused = app.refresh(&text(&r.json(), "refresh_token")).await;
    assert_eq!(refused.error(), grant);
    app.key = key;
    assert_eq!(
        app.get_session(&text(&r.json(), "access_token"))
            .await
            .error(),
        "invalid_token"
    );
    // Pushed with no proof but a `dpop_jkt`, its code is that key's alone.
    let (g, pushed) = app.par_unproven(&[("dpop_jkt", Some(&jkt))]).await;
    assert_eq!(g.status, 201, "{}", g.body);
    let code = approve(&app, &mut browser, "alice", &pushed).await;
    let key = std::mem::replace(&mut app.key, Key::new());
    assert_eq!(app.exchange(&code, &pushed).await.error(), grant);
    app.key = key;
    assert_eq!(app.exchange(&code, &pushed).await.error(), grant, "spent");
    let (_, pushed) = app.par_unproven(&[("dpop_jkt", Some(&jkt))]).await;
    let code = approve(&app, &mut browser, "alice", &pushed).await;
    let t = app.exchange(&code, &pushed).await;
    assert_eq!(t.status, 200, "{}", t.body);
    let _ = std::fs::remove_dir_all(&dir);
}

#[tokio::test]
async fn revocation() {
    let (dir, srv, _) = setup("oauth-revoke").await;
    let mut app = App::new(&srv, "atproto");
    let mut browser = Browser::new(&srv);
    let refused = |g: Got| (g.status, g.error());
    let invalid = (400, "invalid_request".to_string());
    let cid = app.client_id.clone();
    assert_eq!(
        refused(app.call("/oauth/revoke", &[("token", "x")]).await),
        invalid
    );
    assert_eq!(
        refused(app.call("/oauth/revoke", &[("client_id", &cid)]).await),
        invalid
    );
    assert_eq!(
        refused(
            app.call("/oauth/revoke", &[("client_id", &cid), ("token", "")])
                .await
        ),
        invalid
    );
    assert_eq!(
        refused(
            app.call(
                "/oauth/revoke",
                &[
                    ("client_id", &cid),
                    ("token", "x"),
                    ("token_type_hint", "code")
                ]
            )
            .await
        ),
        invalid
    );
    let g = app
        .call(
            "/oauth/revoke",
            &[
                ("client_id", &cid),
                ("token", "x"),
                ("token_type_hint", "refresh_token"),
            ],
        )
        .await;
    assert_eq!((g.status, g.json()), (200, json!({})));
    // Each kind of token ends its session.
    for which in ["access", "refresh", "replaced", "code"] {
        let (pushed, code) = approved(&mut app, &mut browser, "alice").await;
        let t = app.exchange(&code, &pushed).await.json();
        let r = app.refresh(&text(&t, "refresh_token")).await.json();
        let token = match which {
            "access" => text(&r, "access_token"),
            "refresh" => text(&r, "refresh_token"),
            "replaced" => text(&t, "refresh_token"),
            _ => code,
        };
        // Not without a proof, nor from another client, nor with a replaced access token.
        let body = form(&[("client_id", &cid), ("token", &token)]);
        assert_eq!(app.send("/oauth/revoke", &body, &[]).await.status, 200);
        assert_eq!(
            app.call(
                "/oauth/revoke",
                &[("client_id", "http://localhost"), ("token", &token)]
            )
            .await
            .status,
            200
        );
        assert_eq!(app.revoke(&text(&t, "access_token")).await.status, 200);
        assert_eq!(
            app.get_session(&text(&r, "access_token")).await.status,
            200,
            "{which}"
        );
        assert_eq!(app.revoke(&token).await.status, 200);
        assert_eq!(
            app.get_session(&text(&r, "access_token")).await.error(),
            "invalid_token",
            "{which}"
        );
        assert_eq!(
            app.refresh(&text(&r, "refresh_token")).await.error(),
            "invalid_grant",
            "{which}"
        );
    }
    let _ = std::fs::remove_dir_all(&dir);
}

#[tokio::test]
async fn get_session_with_dpop() {
    let (dir, srv, _) = setup("oauth-xrpc").await;
    let alice = srv.svc.account("alice.test").unwrap().did.clone();
    let password_token = crate::testing::session(&srv.svc, "alice").await;
    let mut app = App::new(&srv, "atproto transition:email");
    let mut browser = Browser::new(&srv);
    let t = sign_in(&mut app, &mut browser, "alice", None).await.json();
    let access = text(&t, "access_token");
    let g = app.get_session(&access).await;
    assert!(g.header("dpop-nonce").is_some());
    assert_eq!(
        g.json(),
        json!({ "did": alice, "handle": "alice.test", "active": true, "email": "alice@mail.com", "emailConfirmed": false, "emailAuthFactor": false })
    );
    let path = "/xrpc/com.atproto.server.getSession";
    let refused = |g: Got| {
        (
            g.status,
            g.error(),
            g.www_error(),
            g.header("dpop-nonce").is_some(),
        )
    };
    let as_xrpc = |e: &str| (401, e.to_string(), Some(e.to_string()), true);
    // 1. The proof: no nonce, a bad one, no ath, another token's.
    let nonce = app.nonce.take();
    let p = app.proof("GET", path, Some(&access));
    assert_eq!(
        refused(app.get_session_with(&access, &[p]).await),
        as_xrpc("use_dpop_nonce")
    );
    app.nonce = nonce;
    let p = app.proof("GET", path, None);
    assert_eq!(
        refused(app.get_session_with(&access, &[p]).await),
        as_xrpc("invalid_dpop_proof")
    );
    let p = app.proof("GET", path, Some("another"));
    assert_eq!(
        refused(app.get_session_with(&access, &[p]).await),
        as_xrpc("invalid_dpop_proof")
    );
    let p = app.proof("POST", path, Some(&access));
    assert_eq!(
        refused(app.get_session_with(&access, &[p]).await),
        as_xrpc("invalid_dpop_proof")
    );
    // 2. A token never issued, before 3. no proof.
    assert_eq!(
        refused(app.get_session_with("forged", &[]).await),
        as_xrpc("invalid_token")
    );
    assert_eq!(
        refused(app.get_session_with(&password_token, &[]).await),
        as_xrpc("invalid_token")
    );
    assert_eq!(
        refused(app.get_session_with(&access, &[]).await),
        as_xrpc("invalid_dpop_proof")
    );
    // 4. Another key.
    let key = std::mem::replace(&mut app.key, Key::new());
    assert_eq!(app.get_session(&access).await.error(), "invalid_token");
    app.key = key;
    // An OAuth token as Bearer is no token the server gave out as one, and that answer carries no nonce.
    let g = got(srv
        .request("GET", path)
        .header("authorization", format!("Bearer {access}")))
    .await;
    assert_eq!(
        (g.status, g.error(), g.header("dpop-nonce")),
        (400, "InvalidToken".into(), None)
    );
    // refreshSession and deleteSession take a DPoP header as none.
    for nsid in [
        "com.atproto.server.refreshSession",
        "com.atproto.server.deleteSession",
    ] {
        let p = app.proof("POST", &format!("/xrpc/{nsid}"), Some(&access));
        let g = got(srv
            .request("POST", &format!("/xrpc/{nsid}"))
            .header("authorization", format!("DPoP {access}"))
            .header("dpop", p))
        .await;
        assert_eq!((g.status, g.error()), (401, "AuthMissing".into()), "{nsid}");
    }
    // The scheme in any case.
    let p = app.proof("GET", path, Some(&access));
    let g = got(srv
        .request("GET", path)
        .header("authorization", format!("dpop {access}"))
        .header("dpop", p))
    .await;
    assert_eq!(g.status, 200, "{}", g.body);
    let _ = std::fs::remove_dir_all(&dir);
}

/// What OAuth keeps across a restart: its state and the single-use values.
pub(crate) type Kept = (State, std::collections::BTreeMap<(String, String), u64>);

pub(crate) fn kept(s: &Service) -> Kept {
    (s.oauth.snapshot(), s.replay.snapshot(s.sessions.now()))
}

/// What OAuth keeps, as it is held at `now`: the single-use values whose
/// time has passed are forgotten, whenever they were held, and what OAuth
/// forgets by `now`, as a restart does. A test that runs longer than a value
/// or a request is held compares what it kept so.
pub(crate) fn held_at(k: &Kept, now: u64) -> Kept {
    let mut oauth = k.0.clone();
    oauth.forget(now);
    (
        oauth,
        k.1.iter()
            .filter(|(_, t)| **t > now)
            .map(|(k, t)| (k.clone(), *t))
            .collect(),
    )
}

#[tokio::test]
async fn restarts_keep_everything() {
    let plc = plc().await;
    let dir = scratch("oauth-restart");
    let srv = serve(open(&dir, &plc)).await;
    create(&srv.svc, "alice").await;
    let mut app = App::new(&srv, "atproto");
    let mut browser = Browser::new(&srv);
    // A session, a request approved, one pushed, and a device signed in.
    let t = sign_in(&mut app, &mut browser, "alice", None).await.json();
    let (approved_req, code) = approved(&mut app, &mut browser, "alice").await;
    let (_, pushed) = app.par(&[]).await;
    // A proof whose call passed is kept; one whose call was refused for its
    // token is held in memory alone, and refused again until a restart.
    let (access, path) = (
        text(&t, "access_token"),
        "/xrpc/com.atproto.server.getSession",
    );
    let used_proof = app.proof("GET", path, Some(&access));
    assert_eq!(
        app.get_session_with(&access, std::slice::from_ref(&used_proof))
            .await
            .status,
        200
    );
    let refused_proof = app.proof("GET", path, Some("forged"));
    assert_eq!(
        app.get_session_with("forged", std::slice::from_ref(&refused_proof))
            .await
            .error(),
        "invalid_token"
    );
    assert_eq!(
        app.get_session_with("forged", std::slice::from_ref(&refused_proof))
            .await
            .error(),
        "invalid_dpop_proof"
    );
    let before = kept(&srv.svc);
    let (key, client_id, nonce, cookies) = (
        std::mem::replace(&mut app.key, Key::new()),
        app.client_id.clone(),
        app.nonce.clone(),
        browser.cookies.clone(),
    );
    drop(app);
    drop(browser);
    drop(srv);
    let srv = serve(open(&dir, &plc)).await;
    assert_eq!(kept(&srv.svc), before);
    let mut app = App::new(&srv, "atproto");
    (app.key, app.client_id, app.nonce) = (key, client_id, nonce);
    let mut browser = Browser::new(&srv);
    browser.cookies = cookies;
    // The nonce given before still works; a proof kept before is still spent,
    // and one held in memory alone is checked as new, and refused for its token again.
    let g = app.get_session(&access).await;
    assert_eq!(g.status, 200, "{}", g.body);
    assert_eq!(
        app.get_session_with(&access, &[used_proof]).await.error(),
        "invalid_dpop_proof"
    );
    assert_eq!(
        app.get_session_with("forged", &[refused_proof])
            .await
            .error(),
        "invalid_token"
    );
    // The session refreshes, the code exchanges, the request loads on its device, with the account signed in there.
    assert_eq!(app.refresh(&text(&t, "refresh_token")).await.status, 200);
    assert_eq!(app.exchange(&code, &approved_req).await.status, 200);
    let page = browser.page(&app.client_id, &pushed.request_uri).await;
    assert_eq!(page.status, 200);
    assert_eq!(
        page.page("__sessions").unwrap().as_array().unwrap().len(),
        1
    );
    // A state used before is still refused.
    let (g, _) = app.par(&[("state", Some(&pushed.state))]).await;
    assert_eq!(g.error(), "invalid_request");
    drop(srv);
    // The secret is kept: nothing sealed with it may be lost.
    std::fs::remove_file(dir.join(KEY_FILE)).unwrap();
    assert!(
        crate::testing::try_open(&dir, &plc)
            .err()
            .unwrap()
            .contains(KEY_FILE)
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn pending_requests_by_address() {
    // One address holds 1000; a 1001st from it is refused, from another not.
    let mut p = Pending::default();
    for i in 0..1000 {
        assert_eq!(p.full("1.2.3.4"), None, "{i}");
        p.add(&format!("a{i}"), "1.2.3.4", 1000);
    }
    assert!(p.full("1.2.3.4").is_some_and(|why| why.contains("address")));
    assert_eq!(p.full("1.2.3.5"), None);
    // 20000 from all addresses together; a 20001st from any is refused.
    for i in 1000..20000 {
        let addr = format!("10.0.{}.{}", i / 1000, i % 1000 / 4);
        assert_eq!(p.full(&addr), None, "{i}");
        p.add(&format!("a{i}"), &addr, 1000 + i as u64);
    }
    assert_eq!(p.len(), 20000);
    assert_eq!(
        p.full("1.2.3.5"),
        Some("Too many pending authorization requests")
    );
    // Approved, ended or past its time, a request is pending no longer.
    p.remove("a0");
    p.remove("a0");
    assert_eq!((p.len(), p.full("1.2.3.4")), (19999, None));
    p.extend("a1", 5000);
    p.expire(1000);
    assert_eq!(
        p.len(),
        19999 - 998,
        "the others of 1.2.3.4 were due at 1000"
    );
    assert_eq!(p.per["1.2.3.4"], 1);
    p.expire(4999);
    assert_eq!(p.per.get("1.2.3.4"), Some(&1));
    p.expire(5000);
    assert_eq!(p.per.get("1.2.3.4"), None);
    // An IPv6 address counts by its first 64 bits; an IPv4 one, mapped or not, as itself.
    assert_eq!(
        pending_key("2001:db8:1:2:aaaa::1"),
        pending_key("2001:db8:1:2:bbbb:cccc:dddd:eeee")
    );
    assert_eq!(pending_key("2001:db8:1:2::1"), "2001:db8:1:2::/64");
    assert_ne!(
        pending_key("2001:db8:1:2::1"),
        pending_key("2001:db8:1:3::1")
    );
    assert_eq!(pending_key("::ffff:1.2.3.4"), "1.2.3.4");
    assert_eq!(pending_key("1.2.3.4"), "1.2.3.4");
    assert_ne!(pending_key("1.2.3.4"), pending_key("1.2.3.5"));
    // Anything else, by a digest of fixed size.
    assert_eq!(pending_key(&"x".repeat(5000)).len(), pending_key("").len());
}

#[test]
fn par_field_caps() {
    let with = |k: &str, v: String| {
        let mut pairs: Vec<(String, Json)> = [
            ("client_id", "http://localhost"),
            ("state", "s"),
            ("code_challenge", &"c".repeat(43)),
            ("scope", "atproto"),
        ]
        .iter()
        .map(|(k, v)| (k.to_string(), json!(v)))
        .collect();
        pairs.retain(|(n, _)| n != k);
        pairs.push((k.to_string(), json!(v)));
        too_large(&Params(pairs))
    };
    let cases: &[(&str, usize, usize)] = &[
        ("client_id", 18470, 18471),
        ("state", 1024, 1025),
        ("redirect_uri", 2048, 2049),
        ("login_hint", 2048, 2049),
        ("scope", 4096, 4097),
    ];
    for (k, taken, refused) in cases {
        assert_eq!(with(k, "a".repeat(*taken)), None, "{k}");
        assert!(with(k, "a".repeat(*refused)).is_some(), "{k}");
    }
    assert_eq!(with("code_challenge", "c".repeat(43)), None);
    assert!(with("code_challenge", "c".repeat(42)).is_some());
    assert!(with("code_challenge", "c".repeat(44)).is_some());
    assert_eq!(with("ui_locales", vec!["en"; 16].join(" ")), None);
    assert!(with("ui_locales", vec!["en"; 17].join(" ")).is_some());
}

#[tokio::test]
async fn par_refuses_what_it_would_not_keep() {
    let (dir, srv, plc) = setup("oauth-par-caps").await;
    let mut app = App::new(&srv, "atproto");
    let mut browser = Browser::new(&srv);
    let refused = |g: &Got| (g.status, g.error());
    // Step 17: what is larger than the server keeps.
    let too_big = (400, "invalid_request".to_string());
    let long_scope = vec!["atproto"; 600].join(" ");
    let many = vec!["en"; 17].join(" ");
    let long_state = "s".repeat(1025);
    let challenge = "c".repeat(44);
    for extra in [
        [("state", Some(long_state.as_str()))],
        [("code_challenge", Some(&challenge))],
        [("scope", Some(&long_scope))],
        [("ui_locales", Some(&many))],
    ] {
        let (g, _) = app.par(&extra).await;
        assert_eq!(refused(&g), too_big, "{extra:?}");
        assert!(
            g.json()["error_description"]
                .as_str()
                .unwrap()
                .contains("too")
                || g.json()["error_description"]
                    .as_str()
                    .unwrap()
                    .contains("43"),
            "{}",
            g.body
        );
    }
    assert_eq!(
        app.par(&[("state", Some(&"s".repeat(1024)))])
            .await
            .0
            .status,
        201
    );
    // Step 18: pending requests from the client address, and from all.
    srv.svc.oauth.cap_pending(2, 100);
    let (_, a) = app.par(&[]).await;
    assert_eq!(srv.svc.oauth.pending(), 2);
    let (g, c) = app.par(&[]).await;
    assert_eq!(refused(&g), (429, "invalid_request".to_string()));
    assert!(
        g.json()["error_description"]
            .as_str()
            .unwrap()
            .contains("address")
    );
    // Rejected, a request is pending no longer; the refused one's state was not spent.
    browser.page(&app.client_id, &a.request_uri).await;
    assert_eq!(
        browser
            .api(&app.client_id, &a.request_uri, "reject", json!({}), None)
            .await
            .status,
        200
    );
    assert_eq!(srv.svc.oauth.pending(), 1);
    assert_eq!(app.par(&[("state", Some(&c.state))]).await.0.status, 201);
    assert_eq!(app.par(&[]).await.0.status, 429);
    // Past their time, they are pending no longer.
    srv.skew(REQUEST_LIFE);
    assert_eq!(app.par(&[]).await.0.status, 201);
    assert_eq!(srv.svc.oauth.pending(), 1);
    // Approved, neither; nor once its code is exchanged.
    let (pushed, code) = approved(&mut app, &mut browser, "alice").await;
    assert_eq!(srv.svc.oauth.pending(), 1);
    assert_eq!(app.exchange(&code, &pushed).await.status, 200);
    assert_eq!(srv.svc.oauth.pending(), 1);
    // From all addresses together.
    srv.svc.oauth.cap_pending(100, 1);
    let g = app.par(&[]).await.0;
    assert_eq!(
        (g.status, g.json()["error_description"].clone()),
        (429, json!("Too many pending authorization requests"))
    );
    // A restart counts them again from what it replays, as of its clock.
    let before = srv.svc.oauth.snapshot().pending.of;
    drop(app);
    drop(browser);
    drop(srv);
    let srv = serve(open(&dir, &plc)).await;
    srv.skew(REQUEST_LIFE);
    let mut app = App::new(&srv, "atproto");
    assert_eq!(app.par(&[]).await.0.status, 201);
    let after = srv.svc.oauth.snapshot().pending.of;
    assert!(before.keys().all(|id| after.contains_key(id)));
    assert_eq!((before.len(), after.len()), (1, 2));
    let _ = std::fs::remove_dir_all(&dir);
}

/// POST `body` to `path` as it comes, in chunks, with no `Content-Length`: the status answered.
async fn chunked(srv: &Server, path: &str, headers: &[(&str, String)], body: &[u8]) -> u16 {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    let addr = srv.base.strip_prefix("http://").unwrap();
    let mut s = tokio::net::TcpStream::connect(addr).await.unwrap();
    let mut req = format!(
        "POST {path} HTTP/1.1\r\nhost: {addr}\r\ntransfer-encoding: chunked\r\nconnection: close\r\n"
    );
    for (k, v) in headers {
        req.push_str(&format!("{k}: {v}\r\n"));
    }
    req.push_str("\r\n");
    let _ = s.write_all(req.as_bytes()).await;
    for c in body.chunks(8192) {
        let _ = s.write_all(format!("{:x}\r\n", c.len()).as_bytes()).await;
        let _ = s.write_all(c).await;
        let _ = s.write_all(b"\r\n").await;
    }
    let _ = s.write_all(b"0\r\n\r\n").await;
    let mut out = Vec::new();
    let _ = s.read_to_end(&mut out).await;
    String::from_utf8_lossy(&out)
        .split(' ')
        .nth(1)
        .and_then(|s| s.parse().ok())
        .unwrap_or(0)
}

#[tokio::test]
async fn bodies_of_at_most_100_kib() {
    let (dir, srv, _) = setup("oauth-body-cap").await;
    let mut app = App::new(&srv, "atproto");
    app.fresh_nonce().await;
    // A good request, padded to `len` bytes with a parameter PAR ignores.
    let padded = |app: &App, len: usize| {
        let params = app.par_params(
            &b64(rand::random::<[u8; 32]>()),
            &hex::encode(rand::random::<[u8; 8]>()),
            &[],
        );
        let pairs: Vec<(&str, &str)> = params
            .iter()
            .map(|(k, v)| (k.as_str(), v.as_str()))
            .collect();
        let body = format!("{}&pad=", form(&pairs));
        format!("{body}{}", "a".repeat(len - body.len()))
    };
    let body = padded(&app, BODY_MAX);
    assert_eq!(body.len(), 102400);
    let proof = app.proof("POST", "/oauth/par", None);
    let g = app.send("/oauth/par", &body, &[proof]).await;
    assert_eq!(g.status, 201, "{}", g.body);
    let proof = app.proof("POST", "/oauth/par", None);
    let g = app
        .send("/oauth/par", &padded(&app, BODY_MAX + 1), &[proof])
        .await;
    assert_eq!((g.status, g.error()), (413, "invalid_request".into()));
    // As it comes, with no Content-Length, alike.
    let headers = |app: &App| {
        vec![
            (
                "content-type",
                "application/x-www-form-urlencoded".to_string(),
            ),
            ("dpop", app.proof("POST", "/oauth/par", None)),
        ]
    };
    assert_eq!(
        chunked(
            &srv,
            "/oauth/par",
            &headers(&app),
            padded(&app, BODY_MAX).as_bytes()
        )
        .await,
        201
    );
    assert_eq!(
        chunked(
            &srv,
            "/oauth/par",
            &headers(&app),
            padded(&app, BODY_MAX + 1).as_bytes()
        )
        .await,
        413
    );
    // The API's body likewise, answered as its other refusals.
    let mut browser = Browser::new(&srv);
    let (_, pushed) = app.par(&[]).await;
    browser.page(&app.client_id, &pushed.request_uri).await;
    let did = "x".repeat(BODY_MAX);
    let g = got(browser.api_request(
        &app.client_id,
        &pushed.request_uri,
        "consent",
        &json!({ "did": did }),
        &[],
    ))
    .await;
    assert_eq!(
        (g.status, g.error(), g.header("cache-control").as_deref()),
        (413, "invalid_request".into(), Some("no-store"))
    );
    assert!(g.json()["error_description"].is_string());
    let g = got(browser.api_request(
        &app.client_id,
        &pushed.request_uri,
        "consent",
        &json!({ "did": &did[..BODY_MAX - 12] }),
        &[],
    ))
    .await;
    assert_eq!(
        (g.status, g.error()),
        (400, "invalid_request".into()),
        "{}",
        g.body
    );
    let _ = std::fs::remove_dir_all(&dir);
}

/// No `Content-Encoding` is decoded: a body with one but `identity` is
/// `415 invalid_request` at PAR, the token endpoint and revocation; with
/// `identity`, it is read as any other.
#[tokio::test]
async fn encoded_bodies_are_refused() {
    let (dir, srv, _) = setup("oauth-encoded").await;
    let mut app = App::new(&srv, "atproto");
    app.fresh_nonce().await;
    let params = app.par_params(
        &b64(rand::random::<[u8; 32]>()),
        &hex::encode(rand::random::<[u8; 8]>()),
        &[],
    );
    let pairs: Vec<(&str, &str)> = params
        .iter()
        .map(|(k, v)| (k.as_str(), v.as_str()))
        .collect();
    let body = form(&pairs);
    let post = |app: &App, path: &str, encoding: &str| {
        let proof = app.proof("POST", path, None);
        srv.request("POST", path)
            .header("content-type", "application/x-www-form-urlencoded")
            .header("content-encoding", encoding)
            .header("dpop", proof)
            .body(body.clone())
    };
    for path in ["/oauth/par", "/oauth/token", "/oauth/revoke"] {
        for encoding in ["gzip", "GZIP", "identity, gzip", "foo"] {
            let g = got(post(&app, path, encoding)).await;
            assert_eq!(
                (g.status, g.error()),
                (415, "invalid_request".into()),
                "{path} {encoding}"
            );
        }
    }
    let g = got(post(&app, "/oauth/par", "identity")).await;
    assert_eq!(g.status, 201, "{}", g.body);
    let _ = std::fs::remove_dir_all(&dir);
}

#[tokio::test]
async fn states_are_kept_as_digests() {
    let (dir, srv, _) = setup("oauth-state-digest").await;
    let mut app = App::new(&srv, "atproto");
    let state = "s".repeat(1024);
    assert_eq!(app.par(&[("state", Some(&state))]).await.0.status, 201);
    // Kept as the SHA-256 of the client_id and state, in one namespace: each entry of one size.
    let digest = hex::encode(Sha256::digest(
        state_value(&app.client_id, &state).as_bytes(),
    ));
    let held = srv.svc.replay.snapshot(srv.now());
    assert!(held.contains_key(&(STATE_NS.to_string(), digest)));
    assert!(
        held.keys()
            .all(|(ns, _)| ["dpop", "pkce", STATE_NS].contains(&ns.as_str())),
        "{held:?}"
    );
    let log =
        String::from_utf8_lossy(&std::fs::read(dir.join(crate::log::ACCOUNTS_LOG_FILE)).unwrap())
            .into_owned();
    assert!(log.contains(r#""ns":"state","#) && !log.contains(r#""ns":"state "#));
    // A state an older server kept, in the client's namespace, is still refused.
    let now = srv.now();
    let older = json!({ "t": "spent", "ns": format!("state {}", app.client_id), "v": hex::encode(Sha256::digest(b"older")), "until": now + 1000 });
    srv.svc.replay.replay(&older, now).unwrap();
    assert_eq!(
        app.par(&[("state", Some("older"))]).await.0.error(),
        "invalid_request"
    );
    assert_eq!(app.par(&[("state", Some("newer"))]).await.0.status, 201);
    let _ = std::fs::remove_dir_all(&dir);
}

#[tokio::test]
async fn below_the_free_space_floor() {
    let plc = plc().await;
    let dir = scratch("oauth-free-space");
    let srv = serve(crate::testing::open_with(&dir, &plc, |c| {
        c.min_free = 1 << 20
    }))
    .await;
    create(&srv.svc, "alice").await;
    let did = srv.svc.account("alice.test").unwrap().did.clone();
    let mut app = App::new(&srv, "atproto");
    let mut browser = Browser::new(&srv);
    // With room: a session, a code, a request loaded on a device the account is signed in on, and one pushed.
    let t = sign_in(&mut app, &mut browser, "alice", None).await.json();
    let (approved_req, code) = approved(&mut app, &mut browser, "alice").await;
    let (_, loaded) = app.par(&[]).await;
    assert_eq!(
        browser
            .page(&app.client_id, &loaded.request_uri)
            .await
            .status,
        200
    );
    let (_, pushed) = app.par(&[]).await;
    srv.svc.limits.disk.set_free(Some(1000));
    let log_len = srv.svc.log.len();
    let full = (507, "temporarily_unavailable".to_string());
    let refused = |g: &Got| (g.status, g.error());
    assert_eq!(refused(&app.par(&[]).await.0), full);
    let page = browser.page(&app.client_id, &pushed.request_uri).await;
    assert_eq!(
        (refused(&page), page.page("__errorData").is_some()),
        (full.clone(), true)
    );
    for (endpoint, body) in [("consent", json!({ "did": did })), ("reject", json!({}))] {
        let g = browser
            .api(&app.client_id, &loaded.request_uri, endpoint, body, None)
            .await;
        assert_eq!(refused(&g), full, "{endpoint}");
        assert!(g.json()["error_description"].is_string());
    }
    let (access, refresh) = (text(&t, "access_token"), text(&t, "refresh_token"));
    assert_eq!(refused(&app.exchange(&code, &approved_req).await), full);
    assert_eq!(refused(&app.refresh(&refresh).await), full);
    assert_eq!(refused(&app.revoke(&access).await), full);
    // What keeps nothing is answered: a revocation of no token, a read with an OAuth token.
    assert_eq!(app.revoke("x").await.status, 200);
    let path = "/xrpc/com.atproto.server.getSession";
    let proof = app.proof("GET", path, Some(&access));
    assert_eq!(
        app.get_session_with(&access, std::slice::from_ref(&proof))
            .await
            .status,
        200
    );
    // Its proof is held in memory alone.
    assert_eq!(
        app.get_session_with(&access, &[proof]).await.error(),
        "invalid_dpop_proof"
    );
    assert_eq!(srv.svc.log.len(), log_len, "nothing was written");
    // With room again, it all goes on from where it was: nothing was spent.
    srv.svc.limits.disk.set_free(None);
    assert_eq!(app.exchange(&code, &approved_req).await.status, 200);
    assert_eq!(app.refresh(&refresh).await.status, 200);
    assert_eq!(
        browser
            .api(
                &app.client_id,
                &loaded.request_uri,
                "consent",
                json!({ "did": did }),
                None
            )
            .await
            .status,
        200
    );
    assert_eq!(
        browser
            .page(&app.client_id, &pushed.request_uri)
            .await
            .status,
        200
    );
    assert_eq!(app.par(&[]).await.0.status, 201);
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn spent_proofs_held_in_memory() {
    // At most so many, the oldest forgotten first.
    let mut s = dpop::Spent::new(3);
    assert!(s.spend("a", 0, 200) && s.spend("b", 1, 201) && s.spend("c", 2, 202));
    assert!(!s.spend("a", 3, 203));
    assert!(s.spend("d", 3, 203));
    assert_eq!(s.len(), 3);
    assert!(s.spend("a", 4, 204), "the oldest was forgotten");
    assert!(!s.spend("c", 5, 205) && !s.spend("d", 5, 205));
    assert!(s.spend("b", 5, 205));
    // Each until its time.
    let mut s = dpop::Spent::new(10);
    assert!(s.spend("x", 0, 200));
    assert!(!s.spend("x", 199, 399));
    assert!(s.spend("x", 200, 400));
    assert_eq!(s.len(), 1);
    // The server's holds 1000000.
    assert_eq!(dpop::MEMORY_MAX, 1_000_000);
    let mut s = dpop::Spent::default();
    for i in 0..=dpop::MEMORY_MAX {
        assert!(s.spend(&i.to_string(), 0, 200));
    }
    assert_eq!(s.len(), dpop::MEMORY_MAX);
    assert!(!s.spend("1", 0, 200));
    assert!(s.spend("0", 0, 200), "the first was forgotten");
}

#[tokio::test]
async fn refused_requests_spend_their_proofs_in_memory_alone() {
    let plc = plc().await;
    let dir = scratch("oauth-proofs-in-memory");
    let srv = serve(open(&dir, &plc)).await;
    let mut app = App::new(&srv, "atproto");
    app.fresh_nonce().await;
    let log_len = srv.svc.log.len();
    // A refresh token that is not good, a revocation of none, a PAR refused at step 17.
    let token = form(&[
        ("client_id", &app.client_id),
        ("grant_type", "refresh_token"),
        ("refresh_token", "bogus"),
    ]);
    let revoke = form(&[("client_id", &app.client_id), ("token", "bogus")]);
    let params = app.par_params(&b64(rand::random::<[u8; 32]>()), &"s".repeat(1025), &[]);
    let par = form(
        &params
            .iter()
            .map(|(k, v)| (k.as_str(), v.as_str()))
            .collect::<Vec<_>>(),
    );
    let calls = [
        ("/oauth/token", token, "invalid_grant", 400),
        ("/oauth/revoke", revoke, "", 200),
        ("/oauth/par", par, "invalid_request", 400),
    ];
    let proofs: Vec<String> = calls
        .iter()
        .map(|(path, ..)| app.proof("POST", path, None))
        .collect();
    for ((path, body, error, status), proof) in calls.iter().zip(&proofs) {
        let g = app.send(path, body, std::slice::from_ref(proof)).await;
        assert_eq!(
            (g.status, g.error()),
            (*status, error.to_string()),
            "{path}"
        );
        // Spent at once: sent again, refused as replayed.
        assert_eq!(
            app.send(path, body, std::slice::from_ref(proof))
                .await
                .error(),
            "invalid_dpop_proof",
            "{path}"
        );
    }
    assert_eq!(
        srv.svc.log.len(),
        log_len,
        "a stranger's proofs write nothing"
    );
    // Not across a restart: there, each is a proof never seen, and its request is refused as before.
    let (key, client_id, nonce) = (
        std::mem::replace(&mut app.key, Key::new()),
        app.client_id.clone(),
        app.nonce.clone(),
    );
    drop(app);
    drop(srv);
    let srv = serve(open(&dir, &plc)).await;
    let mut app = App::new(&srv, "atproto");
    (app.key, app.client_id, app.nonce) = (key, client_id, nonce);
    for ((path, body, error, status), proof) in calls.iter().zip(&proofs) {
        let g = app.send(path, body, std::slice::from_ref(proof)).await;
        assert_eq!(
            (g.status, g.error()),
            (*status, error.to_string()),
            "{path}"
        );
    }
    let _ = std::fs::remove_dir_all(&dir);
}

/// The admin's `updateSubjectStatus` of account `did`, with `body`'s `takedown` or `deactivated`.
pub(crate) async fn admin_status(s: &Shared, did: &str, mut body: Json) -> Result<Json, String> {
    let admin = format!(
        "Basic {}",
        base64::engine::general_purpose::STANDARD
            .encode(format!("admin:{}", crate::testing::ADMIN_PASSWORD))
    );
    body["subject"] = json!({ "$type": "com.atproto.admin.defs#repoRef", "did": did });
    crate::testing::call_raw(
        s,
        "com.atproto.admin.updateSubjectStatus",
        crate::sessions::Bearer::of(Some(&admin)),
        &[],
        &body.to_string(),
    )
    .await
}

/// A takedown, applied or lifted, and a deactivation, every way, end the
/// requests approved for the account and not yet exchanged: their codes are
/// refused after the account is back too, and after a restart; and a code
/// whose account is down when it is exchanged is refused and spent
/// (`spec/LIFECYCLE.md`, "OAuth sessions"; `spec/OAUTH.md`, token step 6).
#[tokio::test]
async fn changes_of_an_account_end_its_approved_requests() {
    use crate::testing::call;
    let plc = plc().await;
    let dir = scratch("oauth-changes-end-requests");
    let srv = serve(open(&dir, &plc)).await;
    let (did, token) = create(&srv.svc, "alice").await;
    let mut app = App::new(&srv, "atproto account:status?action=manage");
    let mut browser = Browser::new(&srv);
    let grant = (400, "invalid_grant".to_string());
    let refused = |g: &Got| (g.status, g.error());
    let activate = async || {
        call(
            &srv.svc,
            "com.atproto.server.activateAccount",
            Some(&token),
            Json::Null,
        )
        .await
        .unwrap()
    };
    let mut ended: Vec<(&str, Pushed, String)> = Vec::new();
    // By its password session.
    let (pushed, code) = approved(&mut app, &mut browser, "alice").await;
    call(
        &srv.svc,
        "com.atproto.server.deactivateAccount",
        Some(&token),
        json!({}),
    )
    .await
    .unwrap();
    activate().await;
    ended.push(("password session", pushed, code));
    // By an OAuth token: its sessions end, and the other approved request with them.
    let (p, c) = approved(&mut app, &mut browser, "alice").await;
    let t = app.exchange(&c, &p).await.json();
    let (pushed, code) = approved(&mut app, &mut browser, "alice").await;
    assert_eq!(
        app.post(
            "com.atproto.server.deactivateAccount",
            &text(&t, "access_token"),
            json!({})
        )
        .await
        .status,
        200
    );
    activate().await;
    ended.push(("OAuth token", pushed, code));
    // By the admin.
    let (pushed, code) = approved(&mut app, &mut browser, "alice").await;
    admin_status(
        &srv.svc,
        &did,
        json!({ "deactivated": { "applied": true } }),
    )
    .await
    .unwrap();
    admin_status(
        &srv.svc,
        &did,
        json!({ "deactivated": { "applied": false } }),
    )
    .await
    .unwrap();
    ended.push(("the admin", pushed, code));
    // A takedown, then lifted; and a lifting of none.
    let (pushed, code) = approved(&mut app, &mut browser, "alice").await;
    admin_status(&srv.svc, &did, json!({ "takedown": { "applied": true } }))
        .await
        .unwrap();
    admin_status(&srv.svc, &did, json!({ "takedown": { "applied": false } }))
        .await
        .unwrap();
    ended.push(("a takedown", pushed, code));
    let (pushed, code) = approved(&mut app, &mut browser, "alice").await;
    admin_status(&srv.svc, &did, json!({ "takedown": { "applied": false } }))
        .await
        .unwrap();
    ended.push(("a lifting", pushed, code));
    let st = srv.svc.oauth.snapshot();
    for (why, _, code) in &ended {
        assert!(!st.codes.contains_key(code), "{why}");
    }
    // One approved with no change is kept.
    let (kept, kept_code) = approved(&mut app, &mut browser, "alice").await;
    // A code whose account is down at the exchange is refused, and spent.
    let account = srv.svc.account(&did).unwrap();
    for flip in [
        |s: &mut crate::lifecycle::State| s.deactivated = !s.deactivated,
        |s: &mut crate::lifecycle::State| s.takedown = s.takedown.is_none().then(|| "t".into()),
    ] {
        let (p, c) = approved(&mut app, &mut browser, "alice").await;
        flip(&mut crate::write(&account.state));
        assert_eq!(refused(&app.exchange(&c, &p).await), grant);
        flip(&mut crate::write(&account.state));
        assert_eq!(refused(&app.exchange(&c, &p).await), grant, "spent");
    }
    // Kept so across a restart.
    let (key, client_id, nonce) = (
        std::mem::replace(&mut app.key, Key::new()),
        app.client_id.clone(),
        app.nonce.clone(),
    );
    drop(app);
    drop(browser);
    drop(srv);
    let srv = serve(open(&dir, &plc)).await;
    let mut app = App::new(&srv, "atproto account:status?action=manage");
    (app.key, app.client_id, app.nonce) = (key, client_id, nonce);
    for (why, pushed, code) in &ended {
        assert_eq!(refused(&app.exchange(code, pushed).await), grant, "{why}");
    }
    assert_eq!(app.exchange(&kept_code, &kept).await.status, 200);
    let _ = std::fs::remove_dir_all(&dir);
}

/// `resetPassword` ends every OAuth session of the account, the requests
/// approved for it, and its sign-ins on every device, in its frame: so after
/// a restart too (`spec/EMAIL.md`).
#[tokio::test]
async fn a_password_reset_ends_what_oauth_kept_of_the_account() {
    use crate::email::testing::{last_token, open_with_sink};
    use crate::testing::call;
    let plc = plc().await;
    let (dir, sink) = (scratch("oauth-reset"), scratch("oauth-reset-mail"));
    let srv = serve(open_with_sink(&dir, &plc, &sink)).await;
    create(&srv.svc, "alice").await;
    create(&srv.svc, "bob").await;
    let mut app = App::new(&srv, "atproto");
    let (mut phone, mut laptop, mut bobs) =
        (Browser::new(&srv), Browser::new(&srv), Browser::new(&srv));
    let t1 = sign_in(&mut app, &mut phone, "alice", None).await.json();
    let t2 = sign_in(&mut app, &mut laptop, "alice", None).await.json();
    let bob = sign_in(&mut app, &mut bobs, "bob", None).await.json();
    let (pushed, code) = approved(&mut app, &mut phone, "alice").await;
    call(
        &srv.svc,
        "com.atproto.server.requestPasswordReset",
        None,
        json!({ "email": "alice@mail.com" }),
    )
    .await
    .unwrap();
    let log_len = srv.svc.log.len();
    call(
        &srv.svc,
        "com.atproto.server.resetPassword",
        None,
        json!({ "token": last_token(&sink), "password": "new-pw" }),
    )
    .await
    .unwrap();
    let frames = pds_store::scan(
        &std::fs::read(dir.join(crate::log::ACCOUNTS_LOG_FILE)).unwrap()[log_len as usize..],
    )
    .unwrap()
    .0;
    assert_eq!(frames.len(), 1, "one frame");
    let kinds: Vec<&str> = frames[0].iter().filter_map(|e| e["t"].as_str()).collect();
    assert!(
        [
            "password",
            "oauthEndRequest",
            "oauthEndSession",
            "oauthSignOut"
        ]
        .iter()
        .all(|k| kinds.contains(k)),
        "{kinds:?}"
    );
    let after = srv.svc.oauth.snapshot();
    let (key, client_id, nonce) = (
        std::mem::replace(&mut app.key, Key::new()),
        app.client_id.clone(),
        app.nonce.clone(),
    );
    let cookies = [
        phone.cookies.clone(),
        laptop.cookies.clone(),
        bobs.cookies.clone(),
    ];
    drop(app);
    drop((phone, laptop, bobs));
    drop(srv);
    let srv = serve(open_with_sink(&dir, &plc, &sink)).await;
    assert_eq!(srv.svc.oauth.snapshot(), after);
    let mut app = App::new(&srv, "atproto");
    (app.key, app.client_id, app.nonce) = (key, client_id, nonce);
    for t in [&t1, &t2] {
        assert_eq!(
            app.get_session(&text(t, "access_token")).await.error(),
            "invalid_token"
        );
        assert_eq!(
            app.refresh(&text(t, "refresh_token")).await.error(),
            "invalid_grant"
        );
    }
    assert_eq!(app.exchange(&code, &pushed).await.error(), "invalid_grant");
    // Bob's are as they were.
    assert_eq!(
        app.get_session(&text(&bob, "access_token")).await.status,
        200
    );
    // Neither of her devices lists her; bob's lists him.
    for (cookies, listed) in cookies.into_iter().zip([0, 0, 1]) {
        let mut b = Browser::new(&srv);
        b.cookies = cookies;
        let (_, p) = app.par(&[]).await;
        let page = b.page(&app.client_id, &p.request_uri).await;
        assert_eq!(
            page.page("__sessions").unwrap().as_array().unwrap().len(),
            listed,
            "{}",
            page.body
        );
    }
    let _ = std::fs::remove_dir_all(&dir);
    let _ = std::fs::remove_dir_all(&sink);
}

// ---- The account's own sessions and devices (`account`) ----------------------

/// A call of one of the account's OAuth routes, with `Authorization: auth`
/// and a JSON body, if given.
async fn own(
    srv: &Server,
    method: &str,
    route: &str,
    auth: Option<&str>,
    body: Option<Json>,
) -> Got {
    let mut r = srv.request(method, &format!("/xrpc/{route}"));
    if let Some(a) = auth {
        r = r.header("authorization", a);
    }
    if let Some(b) = body {
        r = r
            .header("content-type", "application/json")
            .body(b.to_string());
    }
    got(r).await
}

/// What a list route answers with the account's password session `auth`.
async fn own_list(srv: &Server, route: &str, auth: &str, key: &str) -> Vec<Json> {
    let g = own(srv, "GET", route, Some(auth), None).await;
    assert_eq!(g.status, 200, "{}", g.body);
    g.json()[key].as_array().unwrap().clone()
}

/// A session's and a device's public id is none of its tokens, its code, its
/// own id or its cookies, and is taken as none of them; it names the same
/// session or device each time it is listed.
#[tokio::test]
async fn the_accounts_ids_are_no_tokens() {
    let (dir, srv, _) = setup("oauth-account-ids").await;
    let password = format!(
        "Bearer {}",
        crate::testing::session(&srv.svc, "alice").await
    );
    let mut app = App::new(&srv, "atproto transition:generic");
    let mut browser = Browser::new(&srv);
    sign_in(&mut app, &mut browser, "alice", None).await;
    let first = srv
        .svc
        .oauth
        .snapshot()
        .sessions
        .into_keys()
        .next()
        .unwrap();
    let first_id = text(
        &own_list(&srv, "_oauthSessions", &password, "sessions").await[0],
        "id",
    );
    assert_eq!(app.revoke(&first_id).await.status, 200);
    let (pushed, code) = approved(&mut app, &mut browser, "alice").await;
    let t = app.exchange(&code, &pushed).await.json();
    let r = app.refresh(&text(&t, "refresh_token")).await.json();
    let st = srv.svc.oauth.snapshot();
    // Revoked by its id at /oauth/revoke, the first session is still there.
    assert!(st.sessions.contains_key(&first));
    let (sid, _) = srv
        .svc
        .oauth
        .token_of("refresh", &text(&r, "refresh_token"))
        .unwrap();
    let s = &st.sessions[&sid];
    let listed = own(&srv, "GET", "_oauthSessions", Some(&password), None).await;
    assert_eq!(
        listed.header("content-type").as_deref(),
        Some("application/json; charset=utf-8")
    );
    let sessions = listed.json()["sessions"].as_array().unwrap().clone();
    assert_eq!(sessions.len(), 2);
    let id = account::public_id(&srv.svc, account::SESSION_ID, &sid);
    let lower_hex = |id: &str| {
        id.len() == 32
            && id
                .bytes()
                .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
    };
    assert!(lower_hex(&id), "{id}");
    let at = |secs: u64| pds_repo::data::datetime_string(secs as i64 * 1000);
    let this = sessions.iter().find(|s| s["id"] == json!(id)).unwrap();
    // One never refreshed was last answered when it started.
    let other = sessions.iter().find(|s| s["id"] != json!(id)).unwrap();
    assert_eq!(other["updatedAt"], other["createdAt"]);
    assert!(text(other, "createdAt").ends_with(".000Z"));
    assert_eq!(
        this,
        &json!({
            "id": id, "clientId": app.client_id, "issuer": "atproto", "scope": "atproto transition:generic",
            "createdAt": at(s.started), "updatedAt": at(s.refreshed), "expiresAt": at(s.started + SESSION_LIFE),
        })
    );
    // The same each time.
    assert_eq!(
        own_list(&srv, "_oauthSessions", &password, "sessions").await,
        sessions
    );
    let (access, refresh) = (text(&r, "access_token"), text(&r, "refresh_token"));
    for token in [&access, &refresh, &text(&t, "refresh_token"), &code, &sid] {
        assert_ne!(&id, token);
    }
    // Taken as none of them.
    let bearer = got(srv
        .request("GET", "/xrpc/com.atproto.server.getSession")
        .header("authorization", format!("Bearer {id}")))
    .await;
    assert_eq!(bearer.status, 400, "{}", bearer.body);
    assert_eq!(app.get_session(&id).await.error(), "invalid_token");
    assert_eq!(app.refresh(&id).await.error(), "invalid_grant");
    assert_eq!(app.revoke(&id).await.status, 200);
    assert_eq!(app.get_session(&access).await.status, 200);
    assert_eq!(app.refresh(&refresh).await.status, 200);
    // A device's id is none of its cookies, nor its own id, and as its cookie
    // is a new device, on which no account is signed in.
    let devices = own_list(&srv, "_oauthDevices", &password, "devices").await;
    assert_eq!(devices.len(), 1);
    let device_id = text(&devices[0], "id");
    let device = st.devices.keys().next().unwrap();
    assert_eq!(
        device_id,
        account::public_id(&srv.svc, account::DEVICE_ID, device)
    );
    assert_ne!(&device_id, device);
    assert!(lower_hex(&device_id), "{device_id}");
    for (_, v) in &browser.cookies {
        assert_ne!(&device_id, v);
    }
    let mut forged = Browser::new(&srv);
    forged.cookies = browser
        .cookies
        .iter()
        .map(|(k, _)| (k.clone(), device_id.clone()))
        .collect();
    let (_, p) = app.par(&[]).await;
    let page = forged.page(&app.client_id, &p.request_uri).await;
    assert_eq!(
        page.page("__sessions").unwrap().as_array().unwrap().len(),
        0,
        "{}",
        page.body
    );
    assert_eq!(
        own_list(&srv, "_oauthDevices", &password, "devices").await,
        devices
    );
    let _ = std::fs::remove_dir_all(&dir);
}

/// `_oauthRevokeSession` takes the account's password session alone, ends
/// the session of the id given, as `/oauth/revoke` would, and leaves the
/// account's other sessions, and another account's, as they were, after a
/// restart too.
#[tokio::test]
async fn the_account_revokes_a_session() {
    let (dir, srv, plc) = setup("oauth-account-revoke").await;
    create(&srv.svc, "bob").await;
    let alice = format!(
        "Bearer {}",
        crate::testing::session(&srv.svc, "alice").await
    );
    let bob = format!("Bearer {}", crate::testing::session(&srv.svc, "bob").await);
    let mut app = App::new(&srv, "atproto");
    let (mut browser, mut bobs) = (Browser::new(&srv), Browser::new(&srv));
    let t1 = sign_in(&mut app, &mut browser, "alice", None).await.json();
    let t2 = sign_in(&mut app, &mut browser, "alice", None).await.json();
    let r2 = app.refresh(&text(&t2, "refresh_token")).await.json();
    let tb = sign_in(&mut app, &mut bobs, "bob", None).await.json();
    let refused = |g: Got| (g.status, g.error());
    let body = || Some(json!({ "id": "x" }));
    // Its auth, then its method, then its body.
    let route = "_oauthRevokeSession";
    assert_eq!(
        refused(own(&srv, "POST", route, None, body()).await),
        (401, "AuthMissing".into())
    );
    for auth in [
        "Basic YWRtaW46YWRtaW4=",
        "Bearer x",
        &format!("Bearer {}", text(&t1, "access_token")),
    ] {
        assert_eq!(
            refused(own(&srv, "POST", route, Some(auth), body()).await),
            (400, "InvalidToken".into()),
            "{auth}"
        );
    }
    let oauth = app
        .post(route, &text(&t1, "access_token"), json!({ "id": "x" }))
        .await;
    assert_eq!(refused(oauth), (403, "Forbidden".into()));
    assert_eq!(
        refused(own(&srv, "GET", route, Some(&alice), body()).await),
        (400, "InvalidRequest".into())
    );
    for bad in [
        None,
        Some(json!([])),
        Some(json!({})),
        Some(json!({ "id": 1 })),
    ] {
        assert_eq!(
            refused(own(&srv, "POST", route, Some(&alice), bad.clone()).await),
            (400, "InvalidRequest".into()),
            "{bad:?}"
        );
    }
    let not_json = got(srv
        .request("POST", &format!("/xrpc/{route}"))
        .header("authorization", &alice)
        .header("content-type", "text/plain")
        .body(r#"{"id":"x"}"#))
    .await;
    assert_eq!(refused(not_json), (400, "InvalidRequest".into()));
    // Each lists its own.
    assert_eq!(
        own_list(&srv, "_oauthSessions", &alice, "sessions")
            .await
            .len(),
        2
    );
    let bobs_id = text(
        &own_list(&srv, "_oauthSessions", &bob, "sessions").await[0],
        "id",
    );
    // Another account's id, and one no session has, end nothing.
    for id in [bobs_id.as_str(), "x"] {
        let g = own(&srv, "POST", route, Some(&alice), Some(json!({ "id": id }))).await;
        assert_eq!((g.status, g.json()), (200, json!({})));
    }
    assert_eq!(
        app.get_session(&text(&tb, "access_token")).await.status,
        200
    );
    let (sid, _) = srv
        .svc
        .oauth
        .token_of("refresh", &text(&r2, "refresh_token"))
        .unwrap();
    let id = account::public_id(&srv.svc, account::SESSION_ID, &sid);
    let log_len = srv.svc.log.len();
    let g = own(
        &srv,
        "POST",
        route,
        Some(&alice),
        Some(json!({ "id": id, "other": 1 })),
    )
    .await;
    assert_eq!((g.status, g.json()), (200, json!({})));
    let frames = pds_store::scan(
        &std::fs::read(dir.join(crate::log::ACCOUNTS_LOG_FILE)).unwrap()[log_len as usize..],
    )
    .unwrap()
    .0;
    assert_eq!(
        frames,
        [vec![json!({ "t": "oauthEndSession", "sid": sid })]]
    );
    assert_eq!(
        app.get_session(&text(&r2, "access_token")).await.error(),
        "invalid_token"
    );
    for refresh in [&r2, &t2] {
        assert_eq!(
            app.refresh(&text(refresh, "refresh_token")).await.error(),
            "invalid_grant"
        );
    }
    assert_eq!(
        app.get_session(&text(&t1, "access_token")).await.status,
        200
    );
    let left = own_list(&srv, "_oauthSessions", &alice, "sessions").await;
    assert_eq!(left.len(), 1);
    assert_ne!(left[0]["id"], json!(id));
    let after = srv.svc.oauth.snapshot();
    assert!(!after.sessions.contains_key(&sid));
    drop((app, browser, bobs));
    drop(srv);
    let srv = serve(open(&dir, &plc)).await;
    assert_eq!(srv.svc.oauth.snapshot(), after);
    let _ = std::fs::remove_dir_all(&dir);
}

/// A remembered sign-in is kept with its `User-Agent`, its first 256
/// characters, and its client address; `_oauthRevokeDevice` signs the
/// account out of that device alone, leaving the other accounts signed in
/// on it, and the sessions made through it; after a restart too.
#[tokio::test]
async fn the_account_signs_out_of_a_device() {
    let (dir, srv, plc) = setup("oauth-account-devices").await;
    create(&srv.svc, "bob").await;
    let alice = format!(
        "Bearer {}",
        crate::testing::session(&srv.svc, "alice").await
    );
    let bob = format!("Bearer {}", crate::testing::session(&srv.svc, "bob").await);
    let alice_did = srv.svc.account("alice.test").unwrap().did.clone();
    let bob_did = srv.svc.account("bob.test").unwrap().did.clone();
    let mut app = App::new(&srv, "atproto");
    let mut browser = Browser::new(&srv);
    let ta = sign_in(&mut app, &mut browser, "alice", None).await.json();
    sign_in(&mut app, &mut browser, "bob", None).await;
    // Alice signs in on it again, with a User-Agent of its own.
    let agent = format!("TestBrowser/1.0 {}", "é".repeat(300));
    let (_, pushed) = app.par(&[]).await;
    browser.page(&app.client_id, &pushed.request_uri).await;
    let signing = json!({ "locale": "en", "identifier": "alice.test", "password": "alice-pw", "remember": true });
    let g = got(browser.api_request(
        &app.client_id,
        &pushed.request_uri,
        "sign-in",
        &signing,
        &[("user-agent", &agent)],
    ))
    .await;
    assert_eq!(g.status, 200, "{}", g.body);
    browser.keep_cookies(&g);
    // A sign-in on another, not remembered, is no device of hers.
    approved(&mut app, &mut Browser::new(&srv), "alice").await;
    let devices = own_list(&srv, "_oauthDevices", &alice, "devices").await;
    assert_eq!(devices.len(), 1, "{devices:?}");
    let d = &devices[0];
    let id = text(d, "id");
    assert_eq!(
        text(d, "userAgent"),
        agent.chars().take(256).collect::<String>()
    );
    // This server knows no client address (`limits::serve` gives it one): it is left out.
    assert_eq!(d.get("ipAddress"), None);
    assert_eq!(d["loginRequired"], json!(false));
    let st = srv.svc.oauth.snapshot();
    let device = st
        .devices
        .keys()
        .find(|k| account::public_id(&srv.svc, account::DEVICE_ID, k) == id)
        .unwrap();
    let at = st
        .signed_in(device)
        .iter()
        .find(|(d, _)| *d == alice_did)
        .unwrap()
        .1;
    assert_eq!(
        text(d, "signedInAt"),
        pds_repo::data::datetime_string(at as i64 * 1000)
    );
    // Bob's sign-in there sent no User-Agent: it is left out too.
    let bobs = own_list(&srv, "_oauthDevices", &bob, "devices").await;
    assert_eq!(
        bobs,
        [json!({ "id": id, "signedInAt": bobs[0]["signedInAt"], "loginRequired": false })]
    );
    // Signed out of it, as `sign-out` there would.
    let route = "_oauthRevokeDevice";
    let g = own(&srv, "POST", route, Some(&bob), Some(json!({ "id": "x" }))).await;
    assert_eq!((g.status, g.json()), (200, json!({})));
    let log_len = srv.svc.log.len();
    let g = own(&srv, "POST", route, Some(&alice), Some(json!({ "id": id }))).await;
    assert_eq!((g.status, g.json()), (200, json!({})));
    let frames = pds_store::scan(
        &std::fs::read(dir.join(crate::log::ACCOUNTS_LOG_FILE)).unwrap()[log_len as usize..],
    )
    .unwrap()
    .0;
    assert_eq!(
        frames,
        [vec![
            json!({ "t": "oauthSignOut", "device": device, "did": alice_did })
        ]]
    );
    assert!(
        own_list(&srv, "_oauthDevices", &alice, "devices")
            .await
            .is_empty()
    );
    assert_eq!(
        own_list(&srv, "_oauthDevices", &bob, "devices").await.len(),
        1
    );
    let (_, p) = app.par(&[]).await;
    let page = browser.page(&app.client_id, &p.request_uri).await;
    let listed: Vec<Json> = page
        .page("__sessions")
        .unwrap()
        .as_array()
        .unwrap()
        .iter()
        .map(|s| s["account"]["did"].clone())
        .collect();
    assert_eq!(listed, [json!(bob_did)], "{}", page.body);
    assert_eq!(
        app.get_session(&text(&ta, "access_token")).await.status,
        200
    );
    let after = srv.svc.oauth.snapshot();
    drop((app, browser));
    drop(srv);
    let srv = serve(open(&dir, &plc)).await;
    assert_eq!(srv.svc.oauth.snapshot(), after);
    assert_eq!(own_list(&srv, "_oauthDevices", &bob, "devices").await, bobs);
    // A week on, a sign-in there is needed again.
    srv.skew(LOGIN_LIFE + 1);
    let late = format!("Bearer {}", crate::testing::session(&srv.svc, "bob").await);
    assert_eq!(
        own_list(&srv, "_oauthDevices", &late, "devices").await[0]["loginRequired"],
        json!(true)
    );
    let _ = std::fs::remove_dir_all(&dir);
}

/// A sign-in kept before its `User-Agent` and client address were replays,
/// with neither; a later one keeps those it has, and a sign-out, the
/// device's end or the account's deletion forgets them.
#[test]
fn sign_ins_kept_before_their_whence_replay() {
    let mut st = State::default();
    let any = |_: &str| true;
    let (a, b) = ("did:plc:a", "did:plc:b");
    let sign_in = |did: &str, at: u64, whence: &Whence| {
        let mut e = json!({ "t": "oauthSignIn", "device": "d", "did": did, "at": at });
        whence.fill(&mut e);
        e
    };
    let old = json!({ "t": "oauthSignIn", "device": "d", "did": a, "at": 1 });
    st.apply(&old, &any).unwrap();
    assert_eq!(st.signed_in("d"), [(a.to_string(), 1)]);
    assert!(st.whence.is_empty());
    let from = Whence {
        user_agent: Some("UA".into()),
        address: Some("203.0.113.7".into()),
    };
    st.apply(&sign_in(b, 2, &from), &any).unwrap();
    assert_eq!(st.whence[&("d".to_string(), b.to_string())], from);
    // Signed in again with none, it keeps none.
    st.apply(&sign_in(b, 3, &Whence::default()), &any).unwrap();
    assert!(st.whence.is_empty());
    st.apply(&sign_in(a, 4, &from), &any).unwrap();
    st.apply(&sign_in(b, 4, &from), &any).unwrap();
    st.apply(
        &json!({ "t": "oauthSignOut", "device": "d", "did": b }),
        &any,
    )
    .unwrap();
    assert_eq!(st.whence.len(), 1);
    st.forget_account(a);
    assert!(st.whence.is_empty());
    st.apply(&sign_in(a, 5, &from), &any).unwrap();
    st.apply(&json!({ "t": "oauthDeviceEnd", "device": "d" }), &any)
        .unwrap();
    assert!(st.whence.is_empty() && st.devices.is_empty());
    let headers = HeaderMap::from_iter([(header::USER_AGENT, HeaderValue::from_static("x"))]);
    assert_eq!(
        Whence::of(&headers, ""),
        Whence {
            user_agent: Some("x".into()),
            address: None
        }
    );
    assert_eq!(
        Whence::of(&HeaderMap::new(), "203.0.113.7"),
        Whence {
            user_agent: None,
            address: Some("203.0.113.7".into())
        }
    );
}

/// A revocation's body of more than 153600 bytes is `413
/// PayloadTooLargeError`, after its HTTP method and before its type, sent
/// whole or chunked; one of exactly 153600 is taken.
#[tokio::test]
async fn revocation_bodies_of_at_most_150_kib() {
    let (dir, srv, _) = setup("oauth-account-bodies").await;
    let alice = format!(
        "Bearer {}",
        crate::testing::session(&srv.svc, "alice").await
    );
    let max = crate::limits::MAX_BODY;
    assert_eq!(max, 153600);
    let padded = |n: usize| {
        let (head, tail) = (r#"{"id":"x","pad":""#, r#""}"#);
        format!("{head}{}{tail}", "a".repeat(n - head.len() - tail.len()))
    };
    for route in ["_oauthRevokeSession", "_oauthRevokeDevice"] {
        let path = format!("/xrpc/{route}");
        let send = |method: &str, body: String, ty: &str| {
            srv.request(method, &path)
                .header("authorization", &alice)
                .header("content-type", ty)
                .body(body)
        };
        let refused = |g: Got| (g.status, g.error());
        assert_eq!(
            refused(got(send("POST", padded(max), "application/json")).await),
            (200, String::new())
        );
        assert_eq!(
            refused(got(send("POST", padded(max + 1), "text/plain")).await),
            (413, "PayloadTooLargeError".into())
        );
        assert_eq!(
            refused(got(send("GET", padded(max + 1), "application/json")).await),
            (400, "InvalidRequest".into())
        );
        let headers = [
            ("authorization", alice.clone()),
            ("content-type", "application/json".to_string()),
        ];
        assert_eq!(
            chunked(&srv, &path, &headers, padded(max).as_bytes()).await,
            200
        );
        assert_eq!(
            chunked(&srv, &path, &headers, padded(max + 1).as_bytes()).await,
            413
        );
    }
    let _ = std::fs::remove_dir_all(&dir);
}