~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
1159 lines · 37.5 KB Raw History
//! The permission engine against the examples of `spec/OAUTH-SCOPES.md` and
//! `atproto/permission.md`, and each family of methods with an OAuth
//! session's token: the right scope passes, a narrower one is refused naming
//! the scope it lacks.

use super::*;
use crate::oauth::tests::{App, Browser, Got, Server, got, serve, sign_in, text};
use crate::testing::{create, open, plc, scratch};
use serde_json::json;

fn scope(s: &str) -> Scope {
    Scope::of(&s.split(' ').map(str::to_string).collect::<Vec<_>>())
}

fn repo(collection: &str, action: Action) -> Need<'_> {
    Need::Repo { collection, action }
}

const ALL: [Action; 3] = [Action::Create, Action::Update, Action::Delete];

#[test]
fn repo_permissions() {
    // permission.md: full permission on one record type, actions implicit or explicit.
    for s in [
        "atproto repo:app.example.profile",
        "atproto repo:app.example.profile?action=create&action=update&action=delete",
    ] {
        let sc = scope(s);
        for a in ALL {
            assert!(sc.allows(&repo("app.example.profile", a)), "{s} {a:?}");
            assert!(!sc.allows(&repo("app.example.post", a)), "{s} {a:?}");
        }
    }
    // Several record types.
    let sc = scope("atproto repo?collection=app.example.profile&collection=app.example.post");
    for a in ALL {
        assert!(
            sc.allows(&repo("app.example.profile", a))
                && sc.allows(&repo("app.example.post", a))
                && !sc.allows(&repo("app.example.like", a))
        );
    }
    // All record types; delete only.
    let sc = scope("atproto repo:*");
    assert!(ALL.iter().all(|a| sc.allows(&repo("any.thing.at", *a))));
    let sc = scope("atproto repo:*?action=delete");
    assert!(
        sc.allows(&repo("a.b.c", Action::Delete))
            && !sc.allows(&repo("a.b.c", Action::Create))
            && !sc.allows(&repo("a.b.c", Action::Update))
    );
    // OAUTH.md's: create only.
    let sc = scope("atproto repo:com.example.foo?action=create");
    assert!(
        sc.allows(&repo("com.example.foo", Action::Create))
            && !sc.allows(&repo("com.example.foo", Action::Update))
    );
    // Compared as written, case and all.
    assert!(
        !scope("atproto repo:com.example.note").allows(&repo("com.Example.note", Action::Create))
    );
    // atproto alone allows no write.
    assert!(!scope("atproto").allows(&repo("a.b.c", Action::Create)));
}

#[test]
fn blob_permissions() {
    let image = scope("atproto blob:image/*");
    assert!(image.allows(&Need::Blob("image/png")) && image.allows(&Need::Blob("image/svg+xml")));
    for m in [
        "IMAGE/PNG",
        "Image/png",
        "video/mp4",
        "imagex/png",
        "image",
        "image/",
        "*/*",
        "image/*",
        "a/b/c",
        "image/png ",
    ] {
        assert!(!image.allows(&Need::Blob(m)), "{m}");
    }
    // permission.md: any type; video or html.
    let any = scope("atproto blob:*/*");
    assert!(
        any.allows(&Need::Blob("text/plain")) && any.allows(&Need::Blob("application/x-thing"))
    );
    // No blob permission allows a media type that is not a type and a subtype.
    for m in [
        "*/*",
        "image/*",
        "a/b/c",
        "text/plain ",
        "png",
        "",
        "/png",
        "text/",
    ] {
        assert!(!any.allows(&Need::Blob(m)), "{m}");
    }
    let some = scope("atproto blob?accept=video/*&accept=text/html");
    assert!(some.allows(&Need::Blob("video/mp4")) && some.allows(&Need::Blob("text/html")));
    assert!(!some.allows(&Need::Blob("text/plain")) && !some.allows(&Need::Blob("image/png")));
    let exact = scope("atproto blob:image/png");
    assert!(exact.allows(&Need::Blob("image/png")) && !exact.allows(&Need::Blob("image/jpeg")));
    // transition:generic allows any, `*/*` and `a/b/c` too.
    let generic = scope("atproto transition:generic");
    for m in ["image/png", "*/*", "a/b/c", "TEXT/Plain", "png"] {
        assert!(generic.allows(&Need::Blob(m)), "{m}");
    }
    assert!(!scope("atproto").allows(&Need::Blob("image/png")));
}

#[test]
fn identity_account_and_rpc_permissions() {
    let handle = Need::Identity("handle");
    for s in [
        "atproto identity:handle",
        "atproto identity:*",
        "atproto identity:*?",
        "atproto identity?attr=handle",
    ] {
        assert!(scope(s).allows(&handle), "{s}");
    }
    for s in [
        "atproto",
        "atproto transition:generic",
        "atproto transition:generic transition:email transition:chat.bsky",
        "atproto account:email?action=manage",
    ] {
        assert!(!scope(s).allows(&handle), "{s}");
    }
    let (read, manage) = (
        Need::Account {
            attr: "email",
            manage: false,
        },
        Need::Account {
            attr: "email",
            manage: true,
        },
    );
    for s in [
        "atproto account:email",
        "atproto account?attr=email",
        "atproto account:email?action=read",
        "atproto transition:email",
    ] {
        assert!(scope(s).allows(&read) && !scope(s).allows(&manage), "{s}");
    }
    let sc = scope("atproto account:email?action=manage");
    assert!(sc.allows(&read) && sc.allows(&manage));
    for s in [
        "atproto",
        "atproto transition:generic",
        "atproto account:repo?action=manage",
        "atproto identity:*",
    ] {
        assert!(!scope(s).allows(&read), "{s}");
    }
    // permission.md: importing a repository.
    let sc = scope("atproto account:repo?action=manage");
    assert!(
        sc.allows(&Need::Account {
            attr: "repo",
            manage: true
        }) && !sc.allows(&Need::Account {
            attr: "status",
            manage: false
        })
    );
    // permission.md: reports to any service; any method of one service.
    let report = Need::Rpc {
        lxm: "app.example.moderation.createReport",
        aud: "did:web:mod.example.com#atproto_labeler",
    };
    let sc = scope("atproto rpc:app.example.moderation.createReport?aud=*");
    assert!(
        sc.allows(&report)
            && !sc.allows(&Need::Rpc {
                lxm: "app.example.feed.getTimeline",
                aud: "did:web:api.example.com#svc_appview"
            })
    );
    let sc = scope("atproto rpc?lxm=*&aud=did:web:api.example.com%23svc_appview");
    assert!(sc.allows(&Need::Rpc {
        lxm: "app.example.feed.getTimeline",
        aud: "did:web:api.example.com#svc_appview"
    }));
    assert!(!sc.allows(&Need::Rpc {
        lxm: "app.example.feed.getTimeline",
        aud: "did:web:api.example.com#svc_chat"
    }));
    assert!(!sc.allows(&report));
    // atproto/oauth.md: transition:generic calls any method but chat.bsky's, `*` too; transition:chat.bsky
    // alone calls chat.bsky's, to any service, and nothing else.
    let chat = Need::Rpc {
        lxm: "chat.bsky.convo.getLog",
        aud: "did:web:api.bsky.chat#bsky_chat",
    };
    let chat_elsewhere = Need::Rpc {
        lxm: "chat.bsky.convo.sendMessage",
        aud: "did:web:api.bsky.app#bsky_appview",
    };
    let any = Need::Rpc {
        lxm: "*",
        aud: "did:web:api.bsky.app#bsky_appview",
    };
    assert!(
        scope("atproto transition:generic").allows(&report)
            && !scope("atproto transition:generic").allows(&chat)
    );
    assert!(
        scope("atproto transition:generic").allows(&any)
            && !scope("atproto transition:chat.bsky").allows(&any)
    );
    assert!(
        scope("atproto transition:generic transition:chat.bsky").allows(&chat)
            && scope("atproto transition:chat.bsky").allows(&chat)
    );
    assert!(
        scope("atproto transition:chat.bsky").allows(&chat_elsewhere)
            && !scope("atproto transition:chat.bsky").allows(&report)
    );
    // The prefix in any case: a service may read a method's name so.
    for lxm in ["Chat.Bsky.convo.sendMessage", "CHAT.BSKY.convo.getLog"] {
        let need = Need::Rpc {
            lxm,
            aud: "did:web:api.bsky.chat#bsky_chat",
        };
        assert!(!scope("atproto transition:generic").allows(&need), "{lxm}");
        assert!(scope("atproto transition:chat.bsky").allows(&need), "{lxm}");
    }
    // transition:generic allows nothing of identity or account.
    let generic = scope("atproto transition:generic");
    assert!(
        !generic.allows(&read)
            && !generic.allows(&Need::Account {
                attr: "repo",
                manage: true
            })
    );
    // A permission set is not served: it allows nothing.
    let set = scope("atproto include:app.example.authFull?aud=did:web:api.example.com%23svc_chat");
    assert!(!set.allows(&repo("app.example.profile", Action::Create)) && !set.allows(&report));
}

#[test]
fn refusals_name_the_missing_scope() {
    let refused = |need: Need| match scope("atproto").may(&need) {
        Err(e) => (e.status, e.name, e.message),
        Ok(()) => panic!("{need:?} allowed"),
    };
    let names = |need: Need, s: &str| {
        assert_eq!(
            refused(need),
            (
                403,
                "ScopeMissingError",
                format!("Missing required scope \"{s}\"")
            )
        )
    };
    names(
        repo("com.example.note", Action::Create),
        "repo:com.example.note?action=create",
    );
    names(repo("a.b.c", Action::Update), "repo:a.b.c?action=update");
    names(repo("a.b.c", Action::Delete), "repo:a.b.c?action=delete");
    names(Need::Identity("handle"), "identity:handle");
    names(Need::Blob("IMAGE/PNG"), "blob:image/png");
    names(Need::Blob("text/plain "), "blob:text/plain%20");
    names(Need::Blob("image/svg+xml"), "blob:image/svg+xml");
    names(Need::Blob("*/*"), "blob:*/*");
    names(Need::Blob("a/b,c@d:e%f"), "blob:a/b,c@d:e%f");
    names(Need::Blob("x/é\"#"), "blob:x/%C3%A9%22%23");
    names(
        Need::Rpc {
            lxm: "chat.bsky.convo.listConvos",
            aud: "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa#a b",
        },
        "rpc:chat.bsky.convo.listConvos?aud=did:plc:aaaaaaaaaaaaaaaaaaaaaaaa%23a+b",
    );
    names(
        Need::Account {
            attr: "email",
            manage: false,
        },
        "account:email?action=read",
    );
    names(
        Need::Rpc {
            lxm: "a.b.c",
            aud: "did:web:x.com#svc",
        },
        "rpc:a.b.c?aud=did:web:x.com%23svc",
    );
    // A password session is allowed every need.
    assert!(
        may(
            Bearer::Token("a password session's"),
            &Need::Identity("handle")
        )
        .is_ok()
    );
}

#[test]
fn applywrites_needs_in_order() {
    let input = json!({ "repo": "x", "writes": [
        { "$type": "com.atproto.repo.applyWrites#delete", "collection": "d.d.d", "rkey": "1" },
        { "$type": "com.atproto.repo.applyWrites#update", "collection": "b.b.b", "rkey": "1", "value": {} },
        { "$type": "com.atproto.repo.applyWrites#create", "collection": "c.c.c", "value": {} },
        { "$type": "com.atproto.repo.applyWrites#create", "collection": "a.a.a", "value": {} },
        { "$type": "com.atproto.repo.applyWrites#create", "collection": "c.c.c", "value": {} },
        { "$type": "com.atproto.repo.applyWrites#update", "collection": "c.c.c", "rkey": "2", "value": {} },
    ]});
    let needs = record_needs("com.atproto.repo.applyWrites", input.as_object().unwrap());
    assert_eq!(
        needs,
        [
            repo("c.c.c", Action::Create),
            repo("a.a.a", Action::Create),
            repo("b.b.b", Action::Update),
            repo("c.c.c", Action::Update),
            repo("d.d.d", Action::Delete)
        ]
    );
    let put = json!({ "repo": "x", "collection": "a.b.c", "rkey": "k", "record": {} });
    assert_eq!(
        record_needs("com.atproto.repo.putRecord", put.as_object().unwrap()),
        [repo("a.b.c", Action::Create), repo("a.b.c", Action::Update)]
    );
}

/// Every method served is in `METHODS`, and nothing else is.
#[test]
fn the_table_names_every_method() {
    let served: Vec<&str> = pds_lexicon::methods()
        .iter()
        .map(|m| m.nsid.as_str())
        .filter(|n| crate::handler(n).is_some() || *n == "com.atproto.repo.uploadBlob")
        .collect();
    for n in &served {
        assert!(METHODS.iter().any(|(m, _)| m == n), "{n} is not in METHODS");
    }
    for (m, _) in METHODS {
        assert!(served.contains(m), "{m} is not served");
    }
}

// ---- Each family of methods, over a socket, with an OAuth session ------------

/// The server with `alice.test`, and `bob.test` beside her.
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;
    let (alice, _) = create(&srv.svc, "alice").await;
    create(&srv.svc, "bob").await;
    (dir, srv, alice)
}

/// A client app with an OAuth session of alice's, of `scope`.
struct Client<'s> {
    srv: &'s Server,
    app: App<'s>,
    access: String,
}

impl<'s> Client<'s> {
    async fn new(srv: &'s Server, scope: &str) -> Client<'s> {
        let mut app = App::new(srv, scope);
        let mut browser = Browser::new(srv);
        let t = sign_in(&mut app, &mut browser, "alice", None).await;
        assert_eq!(t.status, 200, "{}", t.body);
        assert_eq!(t.json()["scope"], json!(scope));
        Client {
            srv,
            app,
            access: text(&t.json(), "access_token"),
        }
    }

    /// A proof of a call to `nsid`, with the nonce the app holds, if `nonce`.
    fn proof(&mut self, method: &str, nsid: &str, nonce: bool) -> String {
        let held = if nonce {
            self.app.nonce.clone()
        } else {
            self.app.nonce.take()
        };
        let p = self
            .app
            .proof(method, &format!("/xrpc/{nsid}"), Some(&self.access));
        self.app.nonce = held;
        p
    }

    /// A call as sent: its `Authorization` header and proof, if any.
    #[allow(clippy::too_many_arguments)]
    async fn send(
        &mut self,
        method: &str,
        nsid: &str,
        query: &str,
        content_type: Option<&str>,
        body: Vec<u8>,
        authorization: Option<String>,
        proof: Option<String>,
    ) -> Got {
        let mut r = self
            .srv
            .request(method, &format!("/xrpc/{nsid}{query}"))
            .body(body);
        if let Some(c) = content_type {
            r = r.header("content-type", c);
        }
        if let Some(a) = authorization {
            r = r.header("authorization", a);
        }
        if let Some(p) = proof {
            r = r.header("dpop", p);
        }
        let g = got(r).await;
        if let Some(n) = g.header("dpop-nonce") {
            self.app.nonce = Some(n);
        }
        g
    }

    /// A call with the session's token and a good proof, once more with the nonce if asked for one.
    async fn call(
        &mut self,
        method: &str,
        nsid: &str,
        query: &str,
        content_type: Option<&str>,
        body: Vec<u8>,
    ) -> Got {
        for _ in 0..2 {
            let proof = self.proof(method, nsid, true);
            let g = self
                .send(
                    method,
                    nsid,
                    query,
                    content_type,
                    body.clone(),
                    Some(format!("DPoP {}", self.access)),
                    Some(proof),
                )
                .await;
            if g.error() != "use_dpop_nonce" {
                return g;
            }
        }
        panic!("the server kept asking for a nonce");
    }

    async fn post(&mut self, nsid: &str, body: Json) -> Got {
        self.call(
            "POST",
            nsid,
            "",
            Some("application/json"),
            body.to_string().into_bytes(),
        )
        .await
    }

    async fn get(&mut self, nsid: &str, query: &str) -> Got {
        self.call("GET", nsid, query, None, Vec::new()).await
    }
}

/// An answer's status, `error` and `message`.
fn answer(g: &Got) -> (u16, String, String) {
    (
        g.status,
        g.error(),
        g.json()["message"].as_str().unwrap_or_default().to_string(),
    )
}

/// The refusal of a scope that lacks `s`, with the nonce and no `WWW-Authenticate`.
fn lacks(g: &Got, s: &str) {
    assert_eq!(
        answer(g),
        (
            403,
            "ScopeMissingError".into(),
            format!("Missing required scope \"{s}\"")
        ),
        "{}",
        g.body
    );
    assert!(g.header("dpop-nonce").is_some() && g.header("www-authenticate").is_none());
    assert_eq!(
        g.header("access-control-expose-headers").as_deref(),
        Some("DPoP-Nonce")
    );
}

fn ok(g: &Got) {
    assert_eq!(g.status, 200, "{}", g.body);
    assert!(g.header("dpop-nonce").is_some());
}

const CREATE: &str = "com.atproto.repo.createRecord";
const PUT: &str = "com.atproto.repo.putRecord";
const DELETE: &str = "com.atproto.repo.deleteRecord";
const APPLY: &str = "com.atproto.repo.applyWrites";

#[tokio::test]
async fn record_writes() {
    let (dir, srv, alice) = setup("scopes-records").await;
    let mut c = Client::new(&srv, "atproto repo:a.b.c?action=create").await;
    ok(&c
        .post(
            CREATE,
            json!({ "repo": alice, "collection": "a.b.c", "rkey": "one", "record": {} }),
        )
        .await);
    lacks(
        &c.post(
            CREATE,
            json!({ "repo": alice, "collection": "a.b.d", "record": {} }),
        )
        .await,
        "repo:a.b.d?action=create",
    );
    // putRecord needs create, then update, whether or not the record exists.
    lacks(
        &c.post(
            PUT,
            json!({ "repo": alice, "collection": "a.b.c", "rkey": "one", "record": { "n": 1 } }),
        )
        .await,
        "repo:a.b.c?action=update",
    );
    lacks(
        &c.post(
            PUT,
            json!({ "repo": alice, "collection": "a.b.c", "rkey": "new", "record": {} }),
        )
        .await,
        "repo:a.b.c?action=update",
    );
    lacks(
        &c.post(
            PUT,
            json!({ "repo": alice, "collection": "a.b.d", "rkey": "new", "record": {} }),
        )
        .await,
        "repo:a.b.d?action=create",
    );
    lacks(
        &c.post(
            DELETE,
            json!({ "repo": alice, "collection": "a.b.c", "rkey": "none" }),
        )
        .await,
        "repo:a.b.c?action=delete",
    );
    // applyWrites: its creates' collections, then its updates', then its deletes'.
    let writes = json!([
        { "$type": "com.atproto.repo.applyWrites#delete", "collection": "a.b.c", "rkey": "one" },
        { "$type": "com.atproto.repo.applyWrites#update", "collection": "a.b.c", "rkey": "missing", "value": {} },
        { "$type": "com.atproto.repo.applyWrites#create", "collection": "a.b.c", "value": {} },
        { "$type": "com.atproto.repo.applyWrites#create", "collection": "a.b.f", "value": {} },
    ]);
    lacks(
        &c.post(APPLY, json!({ "repo": alice, "writes": writes }))
            .await,
        "repo:a.b.f?action=create",
    );
    // The refusal comes before anything of the record: an update of one that does not exist.
    let mut c = Client::new(&srv, "atproto repo:*?action=create&action=delete").await;
    lacks(
        &c.post(APPLY, json!({ "repo": alice, "writes": writes }))
            .await,
        "repo:a.b.c?action=update",
    );
    let mut wide = Client::new(&srv, "atproto repo:*").await;
    ok(&wide
        .post(
            PUT,
            json!({ "repo": alice, "collection": "a.b.c", "rkey": "one", "record": { "n": 2 } }),
        )
        .await);
    ok(&wide
        .post(
            DELETE,
            json!({ "repo": alice, "collection": "a.b.c", "rkey": "one" }),
        )
        .await);
    let mut generic = Client::new(&srv, "atproto transition:generic").await;
    ok(&generic.post(APPLY, json!({ "repo": alice, "writes": [{ "$type": "com.atproto.repo.applyWrites#create", "collection": "x.y.z", "value": {} }] })).await);
    // With atproto alone: the input, then the repo, then the scope, before the
    // record's $type, `validate`, a key that exists or a swap.
    let mut bare = Client::new(&srv, "atproto").await;
    let bob = srv.svc.account("bob.test").unwrap().did.clone();
    assert_eq!(
        answer(
            &bare
                .post(
                    CREATE,
                    json!({ "repo": alice, "collection": "a.b.c", "record": 1.5 })
                )
                .await
        )
        .1,
        "InvalidRequest"
    );
    assert_eq!(
        answer(
            &bare
                .post(
                    CREATE,
                    json!({ "repo": bob, "collection": "a.b.c", "record": {} })
                )
                .await
        )
        .1,
        "AuthenticationRequired"
    );
    assert_eq!(
        answer(
            &bare
                .post(
                    CREATE,
                    json!({ "repo": "nobody.test", "collection": "a.b.c", "record": {} })
                )
                .await
        )
        .1,
        "AccountNotFound"
    );
    for body in [
        json!({ "repo": alice, "collection": "a.b.c", "record": { "$type": "x.y.z" } }),
        json!({ "repo": alice, "collection": "a.b.c", "record": {}, "validate": true }),
        json!({ "repo": alice, "collection": "a.b.c", "record": {}, "swapCommit": "bafyreie5737gdxlw5i64vzichcalba3z2v5n6icifvx5xytvske7mr3hpm" }),
    ] {
        lacks(&bare.post(CREATE, body).await, "repo:a.b.c?action=create");
    }
    let _ = std::fs::remove_dir_all(&dir);
}

#[tokio::test]
async fn blob_uploads() {
    let (dir, srv, _) = setup("scopes-blobs").await;
    let mut c = Client::new(&srv, "atproto blob:image/*").await;
    ok(&upload(&mut c, Some("image/png")).await);
    lacks(&upload(&mut c, Some("text/plain")).await, "blob:text/plain");
    lacks(&upload(&mut c, Some("IMAGE/PNG")).await, "blob:image/png");
    lacks(
        &upload(&mut c, Some("text/plain ;q=1")).await,
        "blob:text/plain%20",
    );
    ok(&upload(&mut c, Some("image/svg+xml;charset=utf-8")).await);
    lacks(&upload(&mut c, Some("*/*")).await, "blob:*/*");
    // No Content-Type is refused whatever the scope, with the nonce.
    let g = upload(&mut c, None).await;
    assert_eq!(answer(&g).1, "InvalidRequest");
    assert!(g.header("dpop-nonce").is_some());
    let mut generic = Client::new(&srv, "atproto transition:generic").await;
    for ct in ["*/*", "a/b/c", "TEXT/Plain"] {
        ok(&upload(&mut generic, Some(ct)).await);
    }
    // More than the limit, with a scope that allows it.
    let big = generic
        .call(
            "POST",
            "com.atproto.repo.uploadBlob",
            "",
            Some("image/png"),
            vec![0; crate::blobs::DEFAULT_UPLOAD_LIMIT as usize + 1],
        )
        .await;
    assert_eq!(answer(&big).1, "PayloadTooLarge");
    // Each byte of the header is its Latin-1 character, lowered, then UTF-8.
    for (bytes, s) in [
        (&b"image/p\xC9ng"[..], "blob:image/p%C3%A9ng"),
        (&b"x/\xC3\x89"[..], "blob:x/%C3%A3%C2%89"),
        (&b"\xC9/x"[..], "blob:%C3%A9/x"),
    ] {
        let proof = c.proof("POST", "com.atproto.repo.uploadBlob", true);
        let r = srv
            .request("POST", "/xrpc/com.atproto.repo.uploadBlob")
            .body(b"some bytes".to_vec())
            .header(
                "content-type",
                reqwest::header::HeaderValue::from_bytes(bytes).unwrap(),
            )
            .header("authorization", format!("DPoP {}", c.access))
            .header("dpop", proof);
        let g = got(r).await;
        if let Some(n) = g.header("dpop-nonce") {
            c.app.nonce = Some(n);
        }
        if s.starts_with("blob:image/") {
            ok(&g);
        } else {
            lacks(&g, s);
        }
    }
    let _ = std::fs::remove_dir_all(&dir);
}

/// An upload of a few bytes with this `Content-Type`.
async fn upload(c: &mut Client<'_>, content_type: Option<&str>) -> Got {
    c.call(
        "POST",
        "com.atproto.repo.uploadBlob",
        "",
        content_type,
        b"some bytes".to_vec(),
    )
    .await
}

#[tokio::test]
async fn identity() {
    let (dir, srv, _) = setup("scopes-identity").await;
    const UPDATE: &str = "com.atproto.identity.updateHandle";
    // The scope before the input.
    let mut bare = Client::new(&srv, "atproto transition:generic").await;
    lacks(
        &bare.post(UPDATE, json!({ "handle": "not a handle" })).await,
        "identity:handle",
    );
    ok(&bare
        .get("com.atproto.identity.getRecommendedDidCredentials", "")
        .await);
    for s in ["atproto identity:handle", "atproto identity:*"] {
        let mut c = Client::new(&srv, s).await;
        let g = c.post(UPDATE, json!({ "handle": "not a handle" })).await;
        assert_eq!(answer(&g).1, "InvalidRequest", "{s}");
        assert!(g.header("dpop-nonce").is_some());
    }
    let _ = std::fs::remove_dir_all(&dir);
}

#[tokio::test]
async fn sessions_and_app_passwords() {
    let (dir, srv, alice) = setup("scopes-sessions").await;
    const GET: &str = "com.atproto.server.getSession";
    let without = json!({ "did": alice, "handle": "alice.test", "active": true });
    let with = json!({ "did": alice, "handle": "alice.test", "active": true, "email": "alice@mail.com", "emailConfirmed": false, "emailAuthFactor": false });
    for (s, want) in [
        ("atproto", &without),
        ("atproto transition:generic", &without),
        ("atproto transition:email", &with),
        ("atproto account:email", &with),
        ("atproto account?attr=email", &with),
        ("atproto account:email?action=manage", &with),
    ] {
        let mut c = Client::new(&srv, s).await;
        let g = c.get(GET, "").await;
        ok(&g);
        assert_eq!(&g.json(), want, "{s}");
    }
    // Never the app password methods: after the token, before the input.
    let mut c = Client::new(&srv, "atproto transition:generic transition:email").await;
    for g in [
        c.post("com.atproto.server.createAppPassword", json!({ "name": 5 }))
            .await,
        c.get("com.atproto.server.listAppPasswords", "").await,
        c.post("com.atproto.server.revokeAppPassword", json!({}))
            .await,
    ] {
        assert_eq!(
            (g.status, g.error()),
            (403, "Forbidden".into()),
            "{}",
            g.body
        );
        assert!(g.header("dpop-nonce").is_some() && g.header("www-authenticate").is_none());
    }
    // A refresh token's methods take none: as no token, with no nonce.
    for nsid in [
        "com.atproto.server.refreshSession",
        "com.atproto.server.deleteSession",
    ] {
        let proof = c.proof("POST", nsid, true);
        let auth = Some(format!("DPoP {}", c.access));
        let g = c
            .send("POST", nsid, "", None, Vec::new(), auth, Some(proof))
            .await;
        assert_eq!(
            (g.status, g.error(), g.header("dpop-nonce")),
            (401, "AuthMissing".into(), None),
            "{nsid}"
        );
    }
    let _ = std::fs::remove_dir_all(&dir);
}

#[tokio::test]
async fn reads() {
    let (dir, srv, alice) = setup("scopes-reads").await;
    let mut c = Client::new(&srv, "atproto").await;
    let password = crate::testing::session(&srv.svc, "alice").await;
    let oauth = c.access.clone();
    let did = format!("?did={alice}");
    // The methods that take a token optionally: a good one answers as none does, with the nonce.
    for (nsid, query) in [
        ("com.atproto.sync.getLatestCommit", did.clone()),
        ("com.atproto.sync.getRepo", did.clone()),
        ("com.atproto.sync.listBlobs", did.clone()),
    ] {
        let g = c.get(nsid, &query).await;
        ok(&g);
        // Bearer: a session's token is as none; one the server did not give out, or an OAuth token, is refused.
        for (bearer, want) in [
            (password.as_str(), 200),
            ("forged", 400),
            (oauth.as_str(), 400),
        ] {
            let g = c
                .send(
                    "GET",
                    nsid,
                    &query,
                    None,
                    Vec::new(),
                    Some(format!("Bearer {bearer}")),
                    None,
                )
                .await;
            assert_eq!(
                (g.status, g.header("dpop-nonce")),
                (want, None),
                "{nsid} {bearer}"
            );
        }
    }
    // A query's parameters first: refused as without a token, with no nonce.
    let proof = c.proof("GET", "com.atproto.sync.getRepo", false);
    let auth = Some(format!("DPoP {}", c.access));
    let g = c
        .send(
            "GET",
            "com.atproto.sync.getRepo",
            "?did=not-a-did",
            None,
            Vec::new(),
            auth.clone(),
            Some(proof),
        )
        .await;
    assert_eq!(
        (g.status, g.error(), g.header("dpop-nonce")),
        (400, "InvalidRequest".into(), None)
    );
    let g = c
        .send(
            "GET",
            "com.atproto.sync.getBlob",
            "?did=x",
            None,
            Vec::new(),
            Some("Bearer forged".into()),
            None,
        )
        .await;
    assert_eq!(g.error(), "InvalidRequest");
    // The methods that take none do not read the header.
    for (nsid, query) in [
        ("com.atproto.server.describeServer", String::new()),
        (
            "com.atproto.repo.listRecords",
            format!("?repo={alice}&collection=a.b.c"),
        ),
    ] {
        let g = c
            .send(
                "GET",
                nsid,
                &query,
                None,
                Vec::new(),
                Some("DPoP garbage".into()),
                Some("garbage".into()),
            )
            .await;
        assert_eq!((g.status, g.header("dpop-nonce")), (200, None), "{nsid}");
    }
    // createAccount: whatever the token and proof, before its input.
    let g = c
        .send(
            "POST",
            "com.atproto.server.createAccount",
            "",
            Some("application/json"),
            b"{}".to_vec(),
            auth,
            Some("garbage".into()),
        )
        .await;
    assert_eq!(
        (g.status, g.error(), g.header("dpop-nonce")),
        (401, "AuthenticationRequired".into(), None)
    );
    // A `DPoP` header that is not two words is a header of a bad form, first.
    for (header, status, name) in [
        ("DPoP", 400, "InvalidToken"),
        ("DPoP a b", 400, "InvalidToken"),
        ("dpop abc", 401, "AuthenticationRequired"),
    ] {
        let g = c
            .send(
                "POST",
                "com.atproto.server.createAccount",
                "",
                Some("application/json"),
                b"{}".to_vec(),
                Some(header.into()),
                None,
            )
            .await;
        assert_eq!(
            (g.status, g.error(), g.header("dpop-nonce")),
            (status, name.into(), None),
            "{header}"
        );
    }
    let _ = std::fs::remove_dir_all(&dir);
}

#[tokio::test]
async fn tokens_and_proofs() {
    let (dir, srv, alice) = setup("scopes-proofs").await;
    let mut c = Client::new(&srv, "atproto repo:*").await;
    let auth = Some(format!("DPoP {}", c.access));
    let www = |g: &Got| {
        g.header("www-authenticate").and_then(|w| {
            w.split("error=\"")
                .nth(1)
                .map(|e| e[..e.find('"').unwrap()].to_string())
        })
    };
    // A procedure's token and proof before its input: no collection, and no nonce.
    let proof = c.proof("POST", CREATE, false);
    let g = c
        .send(
            "POST",
            CREATE,
            "",
            Some("application/json"),
            json!({ "repo": alice }).to_string().into_bytes(),
            auth.clone(),
            Some(proof),
        )
        .await;
    assert_eq!(
        (g.status, g.error(), www(&g)),
        (401, "use_dpop_nonce".into(), Some("use_dpop_nonce".into()))
    );
    assert!(g.header("dpop-nonce").is_some());
    assert_eq!(
        g.header("access-control-expose-headers").as_deref(),
        Some("DPoP-Nonce, WWW-Authenticate")
    );
    // Then its input, with the nonce.
    let proof = c.proof("POST", CREATE, true);
    let g = c
        .send(
            "POST",
            CREATE,
            "",
            Some("application/json"),
            json!({ "repo": alice }).to_string().into_bytes(),
            auth.clone(),
            Some(proof.clone()),
        )
        .await;
    assert_eq!(
        (g.status, g.error(), www(&g)),
        (400, "InvalidRequest".into(), None)
    );
    assert!(g.header("dpop-nonce").is_some());
    // A proof spent is spent, whatever its call answered.
    let g = c
        .send(
            "POST",
            CREATE,
            "",
            Some("application/json"),
            b"{}".to_vec(),
            auth.clone(),
            Some(proof),
        )
        .await;
    assert_eq!(
        (g.status, www(&g)),
        (401, Some("invalid_dpop_proof".into()))
    );
    // A proof of another method, none, or of another token.
    let other = c.proof("POST", PUT, true);
    let g = c
        .send(
            "POST",
            CREATE,
            "",
            Some("application/json"),
            b"{}".to_vec(),
            auth.clone(),
            Some(other),
        )
        .await;
    assert_eq!(www(&g), Some("invalid_dpop_proof".into()));
    let g = c
        .send(
            "POST",
            CREATE,
            "",
            Some("application/json"),
            b"{}".to_vec(),
            auth.clone(),
            None,
        )
        .await;
    assert_eq!(www(&g), Some("invalid_dpop_proof".into()));
    let g = c
        .send(
            "POST",
            CREATE,
            "",
            Some("application/json"),
            b"{}".to_vec(),
            Some("DPoP forged".into()),
            None,
        )
        .await;
    assert_eq!(
        (g.status, g.error(), www(&g)),
        (401, "invalid_token".into(), Some("invalid_token".into()))
    );
    let password = crate::testing::session(&srv.svc, "alice").await;
    let g = c
        .send(
            "GET",
            "com.atproto.server.getSession",
            "",
            None,
            Vec::new(),
            Some(format!("DPoP {password}")),
            None,
        )
        .await;
    assert_eq!(www(&g), Some("invalid_token".into()));
    // The scheme: Bearer with the OAuth token, three words, or the HTTP method: no nonce.
    for (method, authorization) in [
        ("POST", format!("Bearer {}", c.access)),
        ("POST", format!("DPoP {} x", c.access)),
        ("GET", format!("DPoP {}", c.access)),
    ] {
        let proof = c.proof(method, CREATE, true);
        let g = c
            .send(
                method,
                CREATE,
                "",
                Some("application/json"),
                b"{}".to_vec(),
                Some(authorization.clone()),
                Some(proof),
            )
            .await;
        assert_eq!(g.status, 400, "{method} {authorization}");
        assert!(
            g.header("dpop-nonce").is_none() && g.header("www-authenticate").is_none(),
            "{method} {authorization}"
        );
    }
    // The scheme in any case; a query in the request is not in htu.
    let proof = c.proof("GET", "com.atproto.sync.getLatestCommit", true);
    let g = c
        .send(
            "GET",
            "com.atproto.sync.getLatestCommit",
            &format!("?did={alice}"),
            None,
            Vec::new(),
            Some(format!("dpop {}", c.access)),
            Some(proof),
        )
        .await;
    ok(&g);
    let _ = std::fs::remove_dir_all(&dir);
}

#[tokio::test]
async fn service_auth() {
    let (dir, srv, _) = setup("scopes-service-auth").await;
    const GET: &str = "com.atproto.server.getServiceAuth";
    let mut c = Client::new(
        &srv,
        "atproto rpc:app.bsky.feed.getPosts?aud=did:web:svc.example.com%23x",
    )
    .await;
    ok(&c
        .get(
            GET,
            "?aud=did:web:svc.example.com%23x&lxm=app.bsky.feed.getPosts",
        )
        .await);
    lacks(
        &c.get(
            GET,
            "?aud=did:web:svc.example.com%23x&lxm=app.bsky.feed.getLikes",
        )
        .await,
        "rpc:app.bsky.feed.getLikes?aud=did:web:svc.example.com%23x",
    );
    lacks(
        &c.get(GET, "?aud=did:web:svc.example.com").await,
        "rpc:*?aud=did:web:svc.example.com",
    );
    // The scope is asked before `aud`'s form.
    lacks(
        &c.get(GET, "?aud=nope&lxm=app.bsky.feed.getPosts").await,
        "rpc:app.bsky.feed.getPosts?aud=nope",
    );
    // Chat is the scope's to allow, not a privileged session's.
    let mut generic = Client::new(&srv, "atproto transition:generic").await;
    ok(&generic.get(GET, "?aud=did:web:svc.example.com").await);
    lacks(
        &generic
            .get(
                GET,
                "?aud=did:web:svc.example.com&lxm=chat.bsky.convo.listConvos",
            )
            .await,
        "rpc:chat.bsky.convo.listConvos?aud=did:web:svc.example.com",
    );
    let mut chat = Client::new(&srv, "atproto transition:generic transition:chat.bsky").await;
    ok(&chat
        .get(
            GET,
            "?aud=did:web:svc.example.com&lxm=chat.bsky.convo.listConvos",
        )
        .await);
    // transition:chat.bsky alone: chat's methods, for any service, and not `*`.
    let mut chat_only = Client::new(&srv, "atproto transition:chat.bsky").await;
    ok(&chat_only
        .get(
            GET,
            "?aud=did:web:svc.example.com%23bsky_appview&lxm=chat.bsky.convo.sendMessage",
        )
        .await);
    lacks(
        &chat_only.get(GET, "?aud=did:web:svc.example.com").await,
        "rpc:*?aud=did:web:svc.example.com",
    );
    let _ = std::fs::remove_dir_all(&dir);
}