~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
1119 lines · 41.5 KB Raw History
//! Who a space's policy authorizes (`spec/SPACES-POLICIES.md`, "Who is
//! authorized"), as the other parts of spaces ask it: whether a space is
//! live (`Lifecycle`), whether its authority issues a credential and
//! whether the app may have it (`Perimeter`), and whether it tracks an
//! account's writes (`Service::authorize_write`). Under a managedspace each
//! decision for an account other than the authority asks the managing app
//! afresh, with `com.atproto.managedspace.checkAccess`; one it fails to
//! decide is `Undecided`.

use crate::space_authority::{Policy, Space};
use crate::{Service, XrpcError, err, outbound, read};
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use pds_space::SpaceRef;
use serde_json::{Value as Json, json};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

/// Whether a space is live: from `createSpace` or `importSpaceMeta` until
/// `deleteSpace`; deleted after that, until created or imported again; and
/// otherwise, as is every space whose authority is no account here, unknown.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum SpaceState {
    Unknown,
    Live,
    Deleted,
}

pub(crate) trait Lifecycle {
    fn space_state(&self, space: &SpaceRef) -> SpaceState;
}

/// A managing app's failure to decide (`spec/SPACES-POLICIES.md`, "Asking a
/// managing app: checkAccess", "No answer"): neither a refusal nor an
/// authorization.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Undecided;

impl Undecided {
    /// What the method that asked answers: `502 UpstreamFailure`.
    pub(crate) fn answer<T>(self) -> Result<T, XrpcError> {
        err(
            502,
            "UpstreamFailure",
            "The space's managing app did not decide",
        )
    }
}

pub(crate) trait Perimeter {
    /// The read column of "Who is authorized", for a live space: yes, no,
    /// or a managing app's failure to decide. With no `repo` (no delegation
    /// token), yes for a memberspace with `publicRead`, as the managing app
    /// answers for a managedspace, and no otherwise. `client_id`, the
    /// attested client, is passed to a managing app and decides nothing
    /// else here.
    fn authorize_read(
        &self,
        space: &SpaceRef,
        repo: Option<&str>,
        client_id: Option<&str>,
    ) -> impl Future<Output = Result<bool, Undecided>> + Send;
    /// The `allowedApps` gate, asked once `authorize_read` is yes: false
    /// only for a memberspace with `allowedApps` and no `client_id`, or one
    /// not listed.
    fn authorize_app(&self, space: &SpaceRef, client_id: Option<&str>) -> bool;
}

impl Lifecycle for Service {
    fn space_state(&self, space: &SpaceRef) -> SpaceState {
        match self.account(&space.authority) {
            Some(a) => read(&a.store).authority.state(&space.uri()),
            None => SpaceState::Unknown,
        }
    }
}

impl Perimeter for Service {
    async fn authorize_read(
        &self,
        space: &SpaceRef,
        repo: Option<&str>,
        client_id: Option<&str>,
    ) -> Result<bool, Undecided> {
        self.authorize(space, repo, Access::Read, client_id).await
    }

    fn authorize_app(&self, space: &SpaceRef, client_id: Option<&str>) -> bool {
        let Some(a) = self.account(&space.authority) else {
            return true;
        };
        let st = read(&a.store);
        match st.authority.live(&space.uri()).map(|s| &s.policy) {
            Some(Policy::Member {
                allowed_apps: Some(apps),
                ..
            }) => client_id.is_some_and(|c| apps.iter().any(|a| a == c)),
            _ => true,
        }
    }
}

impl Service {
    /// The write column of "Who is authorized", for a live space: whether
    /// the authority tracks `repo`'s writes, or a managing app's failure to
    /// decide. A managing app is asked without a client.
    pub(crate) async fn authorize_write(
        &self,
        space: &SpaceRef,
        repo: &str,
    ) -> Result<bool, Undecided> {
        self.authorize(space, Some(repo), Access::Write, None).await
    }

    async fn authorize(
        &self,
        space: &SpaceRef,
        repo: Option<&str>,
        access: Access,
        client_id: Option<&str>,
    ) -> Result<bool, Undecided> {
        // The decision is made on the space as it is now, with no lock held after.
        let decision = {
            let Some(a) = self.account(&space.authority) else {
                return Ok(false);
            };
            let st = read(&a.store);
            match st.authority.live(&space.uri()) {
                Some(s) => decide(&space.authority, s, repo, access),
                None => return Ok(false),
            }
        };
        match decision {
            Decision::Granted => Ok(true),
            Decision::Refused => Ok(false),
            Decision::Ask(app) => {
                let client_id = client_id.filter(|_| access == Access::Read);
                let answer = ask(self, space, &app, repo, client_id)
                    .await
                    .ok_or(Undecided)?;
                Ok(match access {
                    Access::Read => answer.read,
                    Access::Write => answer.write,
                })
            }
        }
    }
}

/// What an account is authorized to do.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Access {
    Read,
    Write,
}

/// A policy's answer for an account, before any managing app is asked.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Decision {
    Granted,
    Refused,
    /// Ask this managing app (`managingApp` as stored).
    Ask(String),
}

/// What the space's policy and member list say of `repo` (None: no
/// delegation token) for `access`. Its authority is authorized under every
/// policy. A member's write is as its entry says; an account not listed
/// writes only under `publicWrite`. A managedspace asks its app of every
/// other, with no `repo` too.
pub(crate) fn decide(
    authority: &str,
    space: &Space,
    repo: Option<&str>,
    access: Access,
) -> Decision {
    let yes = |b: bool| {
        if b {
            Decision::Granted
        } else {
            Decision::Refused
        }
    };
    if repo == Some(authority) {
        return Decision::Granted;
    }
    match &space.policy {
        Policy::Personal => Decision::Refused,
        Policy::Member {
            public_read,
            public_write,
            ..
        } => {
            let member = repo.and_then(|u| space.members.get(u));
            match access {
                Access::Read => yes(*public_read || member.is_some_and(|m| m.read)),
                Access::Write => yes(member.map_or(*public_write, |m| m.write)),
            }
        }
        Policy::Managed { managing_app, .. } => Decision::Ask(managing_app.clone()),
    }
}

/// The method a managing app is asked with.
pub(crate) const CHECK_ACCESS: &str = "com.atproto.managedspace.checkAccess";

/// How long a managing app's answer is waited for, and a slot to ask it in;
/// and how many may be asked at once, across every space.
#[cfg(not(test))]
const WAIT: Duration = crate::outbound::WAIT;
#[cfg(test)]
const WAIT: Duration = Duration::from_millis(1500);
#[cfg(not(test))]
const IN_FLIGHT: usize = 64;
#[cfg(test)]
const IN_FLIGHT: usize = 4;

/// The managing apps being asked: at most `IN_FLIGHT` at once; an ask that
/// gets no slot within its time is undecided.
pub(crate) struct Asking {
    slots: tokio::sync::Semaphore,
}

impl Default for Asking {
    fn default() -> Asking {
        Asking {
            slots: tokio::sync::Semaphore::new(IN_FLIGHT),
        }
    }
}

/// A managing app's answer: both its decisions.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Answer {
    read: bool,
    write: bool,
}

/// Ask `app` about `repo` (None: a read with no delegation token) in
/// `space` (`spec/SPACES-POLICIES.md`, "Asking a managing app:
/// checkAccess"). Its answer when it answers `2xx` with `Content-Type`
/// `application/json` and a JSON object whose `read` and `write` are both
/// booleans; None, undecided, for anything else: a DID that does not
/// resolve, no such service or no endpoint (one with a user name or
/// password is asked nothing), a request the guard does not send, one that
/// fails or takes more than `WAIT`, a redirect, another status or type, or
/// a body that is not such JSON or is longer than `JSON_DOC_MAX`.
async fn ask(
    svc: &Service,
    space: &SpaceRef,
    app: &str,
    repo: Option<&str>,
    client_id: Option<&str>,
) -> Option<Answer> {
    let _slot = tokio::time::timeout(WAIT, svc.space_authority.asking.slots.acquire())
        .await
        .ok()?
        .ok()?;
    let origin = outbound::origin(&endpoint(svc, app).await?)?;
    let url = origin.join(&format!("/xrpc/{CHECK_ACCESS}")).ok()?;
    let jwt = service_auth(svc, &space.authority, app, CHECK_ACCESS)?;
    let mut query = vec![("space", space.uri())];
    if let Some(r) = repo {
        query.push(("repo", r.to_string()));
    }
    if let Some(c) = client_id {
        query.push(("clientId", c.to_string()));
    }
    let request = svc
        .outbound
        .client()
        .get(url)
        .query(&query)
        .bearer_auth(jwt);
    let got = svc
        .outbound
        .fetch_limited(
            crate::ops::Target::Service,
            request,
            outbound::JSON_DOC_MAX,
            WAIT,
        )
        .await
        .ok()?;
    let json = got
        .headers
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .is_some_and(|t| {
            t.split(';')
                .next()
                .unwrap_or_default()
                .trim()
                .eq_ignore_ascii_case("application/json")
        });
    if !(200..300).contains(&got.status) || !json {
        return None;
    }
    let body: Json = serde_json::from_slice(&got.body).ok()?;
    match (body.get("read"), body.get("write")) {
        (Some(Json::Bool(read)), Some(Json::Bool(write))) if body.is_object() => Some(Answer {
            read: *read,
            write: *write,
        }),
        _ => None,
    }
}

/// The `serviceEndpoint` of a service identifier, a DID and an optional
/// `#fragment`, as a managing app's is resolved: its document's service of
/// that `id` (`#<fragment>` or the DID and `#<fragment>`), or with none, its
/// `#atproto_pds`. None if the DID's document cannot be read or names no
/// such service; what it names may be no endpoint (`outbound::origin`).
pub(crate) async fn endpoint(svc: &Service, ident: &str) -> Option<Json> {
    let did = ident.split_once('#').map_or(ident, |(did, _)| did);
    service_endpoint(&document(svc, did).await?, ident).cloned()
}

/// The `serviceEndpoint` a DID document names for a service identifier, a
/// DID and an optional `#fragment`: of the service of that `id`
/// (`#<fragment>` or the DID and `#<fragment>`), or with none, its
/// `#atproto_pds`.
pub(crate) fn service_endpoint<'a>(doc: &'a Json, ident: &str) -> Option<&'a Json> {
    let (did, fragment) = ident.split_once('#').unwrap_or((ident, "atproto_pds"));
    let (short, full) = (format!("#{fragment}"), format!("{did}#{fragment}"));
    let service = doc["service"]
        .as_array()?
        .iter()
        .find(|s| s["id"].as_str().is_some_and(|id| id == short || id == full))?;
    service.get("serviceEndpoint")
}

/// A DID's document (`spec/SPACES-CREDENTIALS.md`, "Issuers' keys"): a
/// `did:plc`'s from the directory the server uses; a `did:web`'s from its
/// host, through the guard (`Outbound::did_web`), answered `2xx`. None for
/// one that cannot be read so, or for another method.
pub(crate) async fn document(svc: &Service, did: &str) -> Option<Json> {
    if did.starts_with("did:plc:") {
        let url = format!("{}/{did}", svc.config.plc_url.trim_end_matches('/'));
        return match crate::plc::document(&svc.http, &url).await {
            Ok(doc) => doc,
            Err(why) => {
                crate::ops::failed_for(
                    crate::ops::Level::Warn,
                    "reading a DID document failed",
                    did,
                    why,
                );
                None
            }
        };
    }
    if !did.starts_with("did:web:") {
        return None;
    }
    let got = svc
        .outbound
        .did_web(did)
        .await
        .ok()
        .filter(|got| (200..300).contains(&got.status))?;
    serde_json::from_slice(&got.body).ok()
}

/// Service auth (`atproto/xrpc.md`) from an account here, `iss`, for method
/// `lxm`: an ES256K JWT whose body is exactly `iss`, `aud`, `lxm`, `iat`,
/// `exp` a minute on and a fresh `jti`, signed with `iss`'s `#atproto` key.
pub(crate) fn service_auth(svc: &Service, iss: &str, aud: &str, lxm: &str) -> Option<String> {
    let a = svc.account(iss)?;
    let iat = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();
    let jti = hex::encode(rand::random::<[u8; 16]>());
    let header = URL_SAFE_NO_PAD.encode(json!({ "typ": "JWT", "alg": "ES256K" }).to_string());
    let body = URL_SAFE_NO_PAD.encode(
        json!({ "iss": iss, "aud": aud, "lxm": lxm, "iat": iat, "exp": iat + 60, "jti": jti })
            .to_string(),
    );
    let signed = format!("{header}.{body}");
    let sig = read(&a.store).repo.sign(signed.as_bytes());
    Some(format!("{signed}.{}", URL_SAFE_NO_PAD.encode(sig)))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Shared;
    use crate::space_authority::{Access as Member, MANAGED, MEMBER, PERSONAL};
    use crate::testing::*;
    use axum::Router;
    use axum::extract::{Path, Query, State};
    use axum::http::{HeaderMap, StatusCode, header};
    use axum::response::{IntoResponse, Response};
    use axum::routing::get;
    use std::collections::{BTreeMap, HashMap};
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::{Arc, Mutex};

    fn space(policy: Policy, members: &[(&str, bool, bool)]) -> Space {
        let members = members
            .iter()
            .map(|(d, read, write)| {
                (
                    d.to_string(),
                    Member {
                        read: *read,
                        write: *write,
                    },
                )
            })
            .collect();
        Space {
            policy,
            members,
            writers: BTreeMap::new(),
        }
    }

    fn member(public_read: bool, public_write: bool) -> Policy {
        Policy::Member {
            public_read,
            public_write,
            publish_policy: false,
            publish_members: false,
            allowed_apps: None,
        }
    }

    /// Each policy's read and write columns, the authority under each, and
    /// no account: under `publicWrite` a member's write is as its entry says.
    #[test]
    fn policy_decisions() {
        use Access::{Read, Write};
        use Decision::{Granted, Refused};
        let auth = "did:plc:authority";
        let personal = space(Policy::Personal, &[("did:plc:m", true, true)]);
        for access in [Read, Write] {
            assert_eq!(decide(auth, &personal, Some(auth), access), Granted);
            assert_eq!(decide(auth, &personal, Some("did:plc:m"), access), Refused);
            assert_eq!(decide(auth, &personal, None, access), Refused);
        }
        let members = [
            ("did:plc:r", true, false),
            ("did:plc:w", false, true),
            ("did:plc:none", false, false),
        ];
        let closed = space(member(false, false), &members);
        let want = [
            (Some(auth), Granted, Granted),
            (Some("did:plc:r"), Granted, Refused),
            (Some("did:plc:w"), Refused, Granted),
            (Some("did:plc:none"), Refused, Refused),
            (Some("did:plc:x"), Refused, Refused),
            (None, Refused, Refused),
        ];
        for (repo, read, write) in want {
            assert_eq!(
                (
                    decide(auth, &closed, repo, Read),
                    decide(auth, &closed, repo, Write)
                ),
                (read, write),
                "{repo:?}"
            );
        }
        let open = space(member(true, true), &members);
        let want = [
            (Some(auth), Granted),
            (Some("did:plc:x"), Granted),
            (Some("did:plc:w"), Granted),
            (Some("did:plc:r"), Refused),
            (Some("did:plc:none"), Refused),
        ];
        for (repo, write) in want {
            assert_eq!(
                (
                    decide(auth, &open, repo, Read),
                    decide(auth, &open, repo, Write)
                ),
                (Granted, write),
                "{repo:?}"
            );
        }
        // No account: only publicRead authorizes a read.
        assert_eq!(decide(auth, &open, None, Read), Granted);
        let managed = space(
            Policy::Managed {
                managing_app: "did:plc:app#forum".into(),
                publish_policy: false,
            },
            &[],
        );
        for access in [Read, Write] {
            assert_eq!(decide(auth, &managed, Some(auth), access), Granted);
            for repo in [Some("did:plc:u"), None] {
                assert_eq!(
                    decide(auth, &managed, repo, access),
                    Decision::Ask("did:plc:app#forum".into())
                );
            }
        }
    }

    type Docs = Arc<Mutex<HashMap<String, Json>>>;

    /// A directory that takes any account's genesis and serves its document,
    /// and serves documents a test puts in it.
    async fn directory() -> (String, Docs) {
        async fn post(
            State(docs): State<Docs>,
            Path(did): Path<String>,
            body: axum::body::Bytes,
        ) -> StatusCode {
            let op: Json = serde_json::from_slice(&body).unwrap();
            docs.lock()
                .unwrap()
                .insert(did.clone(), did_document(&did, &op));
            StatusCode::OK
        }
        async fn doc(State(docs): State<Docs>, Path(did): Path<String>) -> Response {
            match docs.lock().unwrap().get(&did) {
                Some(d) => {
                    ([(header::CONTENT_TYPE, "application/json")], d.to_string()).into_response()
                }
                None => StatusCode::NOT_FOUND.into_response(),
            }
        }
        let docs = Docs::default();
        let app = Router::new()
            .route("/{did}", get(doc).post(post))
            .with_state(docs.clone());
        (serve(app).await, docs)
    }

    async fn serve(app: Router) -> String {
        let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0))
            .await
            .unwrap();
        let url = format!("http://{}", listener.local_addr().unwrap());
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        url
    }

    /// What a managing app answers about a repo: its status, body,
    /// `Content-Type` (none if empty), and delay in ms.
    type Reply = (u16, String, String, u64);

    /// A managing app: it answers each repo (`""` for a call with none)
    /// from its table, and keeps each call's parameters and
    /// `Authorization`, and the most calls it had at once.
    #[derive(Default)]
    struct App {
        answers: Mutex<HashMap<String, Reply>>,
        calls: Mutex<Vec<(BTreeMap<String, String>, String)>>,
        now: AtomicUsize,
        most: AtomicUsize,
    }

    async fn app() -> (String, Arc<App>) {
        async fn check(
            State(app): State<Arc<App>>,
            Query(q): Query<BTreeMap<String, String>>,
            headers: HeaderMap,
        ) -> Response {
            let auth = headers
                .get(header::AUTHORIZATION)
                .map(|v| v.to_str().unwrap().to_string())
                .unwrap_or_default();
            let (status, body, ctype, delay) = app
                .answers
                .lock()
                .unwrap()
                .get(q.get("repo").map_or("", String::as_str))
                .cloned()
                .unwrap_or((404, String::new(), String::new(), 0));
            app.calls.lock().unwrap().push((q, auth));
            // Counted out when the call ends, answered or dropped as its asker gave up.
            struct InFlight(Arc<App>);
            impl Drop for InFlight {
                fn drop(&mut self) {
                    self.0.now.fetch_sub(1, Ordering::SeqCst);
                }
            }
            let now = app.now.fetch_add(1, Ordering::SeqCst) + 1;
            app.most.fetch_max(now, Ordering::SeqCst);
            let _in_flight = InFlight(app.clone());
            tokio::time::sleep(std::time::Duration::from_millis(delay)).await;
            let mut res = Response::new(axum::body::Body::from(body.clone()));
            *res.status_mut() = StatusCode::from_u16(status).unwrap();
            if !ctype.is_empty() {
                res.headers_mut()
                    .insert(header::CONTENT_TYPE, ctype.parse().unwrap());
            }
            // A redirect goes where its body says.
            if (300..400).contains(&status) {
                res.headers_mut()
                    .insert(header::LOCATION, body.parse().unwrap());
            }
            res
        }
        let state = Arc::new(App::default());
        let router = Router::new()
            .route(&format!("/xrpc/{CHECK_ACCESS}"), get(check))
            .with_state(state.clone());
        (serve(router).await, state)
    }

    impl App {
        /// Answer `repo` with JSON.
        fn answer(&self, repo: &str, status: u16, body: &str, delay: u64) {
            self.answer_as(repo, status, body, "application/json", delay);
        }

        fn answer_as(&self, repo: &str, status: u16, body: &str, ctype: &str, delay: u64) {
            self.answers
                .lock()
                .unwrap()
                .insert(repo.into(), (status, body.into(), ctype.into(), delay));
        }

        fn calls(&self) -> Vec<(BTreeMap<String, String>, String)> {
            std::mem::take(&mut self.calls.lock().unwrap())
        }
    }

    async fn create_space(s: &Shared, token: &str, skey: &str, policy: Json) -> SpaceRef {
        let body = json!({ "spaceType": "com.example.forum", "skey": skey, "policy": policy });
        SpaceRef::parse(
            call(s, "com.atproto.space.createSpace", Some(token), body)
                .await
                .unwrap()["space"]
                .as_str()
                .unwrap(),
        )
        .unwrap()
    }

    const YES: Result<bool, Undecided> = Ok(true);
    const NO: Result<bool, Undecided> = Ok(false);

    /// A memberspace and a personalspace, as `Perimeter` and `authorize_write`
    /// answer them, each as the space is when asked; spaces not live are refused.
    #[tokio::test]
    async fn member_and_personal_spaces() {
        let plc = plc().await;
        let dir = scratch("authz-member");
        let s = open(&dir, &plc);
        let (alice, ta) = create(&s, "alice").await;
        let (bob, _) = create(&s, "bob").await;
        let ms = create_space(&s, &ta, "m", json!({ "$type": MEMBER })).await;
        let put = |did: &str, read: bool, write: bool| json!({ "space": ms.uri(), "members": [{ "did": did, "read": read, "write": write }] });
        let both = |repo: &str| {
            let (s, ms, repo) = (s.clone(), ms.clone(), repo.to_string());
            async move {
                (
                    s.authorize_read(&ms, Some(&repo), None).await,
                    s.authorize_write(&ms, &repo).await,
                )
            }
        };
        assert_eq!(both(&alice).await, (YES, YES));
        assert_eq!(both(&bob).await, (NO, NO));
        call(
            &s,
            "com.atproto.memberspace.putMembers",
            Some(&ta),
            put(&bob, true, false),
        )
        .await
        .unwrap();
        assert_eq!(both(&bob).await, (YES, NO));
        call(
            &s,
            "com.atproto.memberspace.putMembers",
            Some(&ta),
            put(&bob, false, true),
        )
        .await
        .unwrap();
        assert_eq!(both(&bob).await, (NO, YES));
        assert_eq!(s.authorize_read(&ms, None, None).await, NO);
        // Every app, until allowedApps names some; then only those, the authority's too.
        assert!(s.authorize_app(&ms, None));
        let update = |policy: Json| json!({ "space": ms.uri(), "policy": policy });
        let policy = json!({ "$type": MEMBER, "publicRead": true, "allowedApps": ["https://app.example/client"] });
        call(
            &s,
            "com.atproto.space.updateSpace",
            Some(&ta),
            update(policy),
        )
        .await
        .unwrap();
        assert_eq!(s.authorize_read(&ms, None, None).await, YES);
        assert_eq!(
            s.authorize_read(&ms, Some("did:plc:anyone"), None).await,
            YES
        );
        assert!(
            !s.authorize_app(&ms, None)
                && !s.authorize_app(&ms, Some("https://other.example/client"))
        );
        assert!(s.authorize_app(&ms, Some("https://app.example/client")));
        call(
            &s,
            "com.atproto.space.updateSpace",
            Some(&ta),
            update(json!({ "$type": MEMBER, "allowedApps": [] })),
        )
        .await
        .unwrap();
        assert!(!s.authorize_app(&ms, Some("https://app.example/client")));
        assert_eq!(s.authorize_read(&ms, Some(&alice), None).await, YES);
        assert_eq!(s.authorize_read(&ms, None, None).await, NO);
        // Under publicWrite, an account not listed writes; a member as its entry says.
        call(
            &s,
            "com.atproto.space.updateSpace",
            Some(&ta),
            update(json!({ "$type": MEMBER, "publicWrite": true })),
        )
        .await
        .unwrap();
        assert_eq!(s.authorize_write(&ms, "did:plc:anyone").await, YES);
        assert!(s.authorize_app(&ms, None));
        assert_eq!(s.authorize_write(&ms, &bob).await, YES);
        call(
            &s,
            "com.atproto.memberspace.putMembers",
            Some(&ta),
            put(&bob, true, false),
        )
        .await
        .unwrap();
        assert_eq!(s.authorize_write(&ms, &bob).await, NO);
        call(
            &s,
            "com.atproto.memberspace.removeMembers",
            Some(&ta),
            json!({ "space": ms.uri(), "dids": [bob] }),
        )
        .await
        .unwrap();
        assert_eq!(s.authorize_write(&ms, &bob).await, YES);
        // A personalspace: the authority alone; every app.
        let ps = create_space(&s, &ta, "p", json!({ "$type": PERSONAL })).await;
        assert_eq!(
            (
                s.authorize_read(&ps, Some(&alice), None).await,
                s.authorize_write(&ps, &alice).await
            ),
            (YES, YES)
        );
        assert!(s.authorize_app(&ps, None));
        assert_eq!(
            (
                s.authorize_read(&ps, Some(&bob), None).await,
                s.authorize_write(&ps, &bob).await,
                s.authorize_read(&ps, None, None).await
            ),
            (NO, NO, NO)
        );
        // Live, deleted, unknown.
        assert_eq!(s.space_state(&ps), SpaceState::Live);
        call(
            &s,
            "com.atproto.space.deleteSpace",
            Some(&ta),
            json!({ "space": ps.uri() }),
        )
        .await
        .unwrap();
        assert_eq!(s.space_state(&ps), SpaceState::Deleted);
        assert_eq!(
            (
                s.authorize_read(&ps, Some(&alice), None).await,
                s.authorize_write(&ps, &alice).await
            ),
            (NO, NO)
        );
        let elsewhere =
            SpaceRef::parse("at://did:plc:elsewhere/space/com.example.forum/m").unwrap();
        let never = SpaceRef {
            skey: "never".into(),
            ..ms.clone()
        };
        for sr in [&elsewhere, &never] {
            assert_eq!(s.space_state(sr), SpaceState::Unknown);
            assert_eq!(
                (
                    s.authorize_read(sr, Some(&alice), None).await,
                    s.authorize_write(sr, &alice).await
                ),
                (NO, NO)
            );
        }
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// `checkAccess` as a managing app sees it: asked afresh for each
    /// decision, with exactly the parameters and service auth the spec
    /// gives; its `read` or `write` taken from a `2xx` JSON object with
    /// both booleans, and anything else undecided.
    #[tokio::test]
    async fn managing_apps_are_asked() {
        let (plc, docs) = directory().await;
        let (url, app) = app().await;
        let dir = scratch("authz-managed");
        let s = open(&dir, &plc);
        let (alice, ta) = create(&s, "alice").await;
        let key = *crate::read(&s.account(&alice).unwrap().store)
            .repo
            .verifying_key();
        let app_did = "did:plc:managingappmanagingappaa";
        docs.lock().unwrap().insert(
            app_did.into(),
            json!({ "id": app_did, "service": [
                { "id": "#forum", "type": "ManagingApp", "serviceEndpoint": url },
                { "id": format!("{app_did}#other"), "type": "ManagingApp", "serviceEndpoint": format!("{url}/") },
            ] }),
        );
        let managed = |app: &str| json!({ "$type": MANAGED, "managingApp": app });
        let forum = create_space(&s, &ta, "forum", managed(&format!("{app_did}#forum"))).await;
        let (u, v) = ("did:plc:user", "did:web:user.example");
        app.answer(u, 200, r#"{"read":true,"write":false}"#, 0);
        app.answer(v, 200, r#"{"read":false,"write":true}"#, 0);
        let client = "https://client.example/meta.json";

        assert_eq!(s.authorize_read(&forum, Some(u), Some(client)).await, YES);
        let [(q, auth)] = &app.calls()[..] else {
            panic!("one call")
        };
        let want = |repo: Option<&str>, client: Option<&str>| {
            let mut q = BTreeMap::from([("space".to_string(), forum.uri())]);
            if let Some(r) = repo {
                q.insert("repo".into(), r.into());
            }
            if let Some(c) = client {
                q.insert("clientId".into(), c.into());
            }
            q
        };
        assert_eq!(q, &want(Some(u), Some(client)));
        // Its service auth: an ES256K JWT, exactly these claims, signed with the authority's key.
        let jwt = auth.strip_prefix("Bearer ").unwrap();
        let parts: Vec<&str> = jwt.split('.').collect();
        let part = |i: usize| -> Json {
            serde_json::from_slice(&URL_SAFE_NO_PAD.decode(parts[i]).unwrap()).unwrap()
        };
        assert_eq!(part(0), json!({ "typ": "JWT", "alg": "ES256K" }));
        let claims = part(1);
        assert_eq!(
            claims.as_object().unwrap().keys().collect::<Vec<_>>(),
            ["aud", "exp", "iat", "iss", "jti", "lxm"]
        );
        assert_eq!(
            (&claims["iss"], &claims["aud"], &claims["lxm"]),
            (
                &json!(alice),
                &json!(format!("{app_did}#forum")),
                &json!(CHECK_ACCESS)
            )
        );
        assert_eq!(
            claims["exp"].as_u64().unwrap(),
            claims["iat"].as_u64().unwrap() + 60
        );
        assert!(!claims["jti"].as_str().unwrap().is_empty());
        use k256::ecdsa::signature::hazmat::PrehashVerifier;
        use sha2::Digest;
        let sig =
            k256::ecdsa::Signature::from_slice(&URL_SAFE_NO_PAD.decode(parts[2]).unwrap()).unwrap();
        key.verify_prehash(
            &sha2::Sha256::digest(format!("{}.{}", parts[0], parts[1])),
            &sig,
        )
        .unwrap();
        // Each decision asks afresh, each with a fresh jti, and takes its own
        // field; a write, and a read with no attestation, carry no clientId.
        assert_eq!(s.authorize_read(&forum, Some(u), None).await, YES);
        assert_eq!(s.authorize_write(&forum, u).await, NO);
        let calls = app.calls();
        assert_eq!(
            calls.iter().map(|c| c.0.clone()).collect::<Vec<_>>(),
            [want(Some(u), None), want(Some(u), None)]
        );
        assert_ne!(calls[0].1, calls[1].1);
        assert_eq!(s.authorize_read(&forum, Some(v), None).await, NO);
        assert_eq!(s.authorize_write(&forum, v).await, YES);
        // The authority asks nothing.
        app.calls();
        assert_eq!(s.authorize_read(&forum, Some(&alice), None).await, YES);
        assert_eq!(s.authorize_write(&forum, &alice).await, YES);
        assert!(s.authorize_app(&forum, None));
        assert_eq!(app.calls().len(), 0);
        // A read with no delegation token asks with no repo.
        app.answer("", 200, r#"{"read":true,"write":false}"#, 0);
        assert_eq!(s.authorize_read(&forum, None, Some(client)).await, YES);
        app.answer("", 200, r#"{"read":false,"write":true}"#, 0);
        assert_eq!(s.authorize_read(&forum, None, None).await, NO);
        assert_eq!(
            app.calls().into_iter().map(|c| c.0).collect::<Vec<_>>(),
            [want(None, Some(client)), want(None, None)]
        );
        // Taken: any 2xx, other fields, a JSON media type in any case, with parameters.
        for (i, (status, body, ctype)) in [
            (201, r#"{"read":true,"write":false}"#, "application/json"),
            (
                200,
                r#"{"read":true,"write":false,"other":1}"#,
                "application/json",
            ),
            (
                200,
                r#"{"write":false,"read":true}"#,
                "application/json; charset=utf-8",
            ),
            (200, r#"{"read":true,"write":false}"#, "Application/JSON"),
        ]
        .into_iter()
        .enumerate()
        {
            let repo = format!("did:plc:taken{i}");
            app.answer_as(&repo, status, body, ctype, 0);
            assert_eq!(
                s.authorize_read(&forum, Some(&repo), None).await,
                YES,
                "{status} {body} {ctype}"
            );
        }
        assert_eq!(app.calls().len(), 4);
        // Anything else is undecided, for a read and a write alike.
        let json = "application/json";
        for (i, (status, body, ctype, delay)) in [
            (200, r#"{"read":"true","write":false}"#, json, 0),
            (200, r#"{"read":1,"write":true}"#, json, 0),
            (200, r#"{"read":null,"write":true}"#, json, 0),
            (200, r#"{"read":true}"#, json, 0),
            (200, r#"{"authorized":true}"#, json, 0),
            (200, r#"{}"#, json, 0),
            (200, "not json", json, 0),
            (200, "[true]", json, 0),
            (200, r#"{"read":true,"write":true}"#, "text/plain", 0),
            (200, r#"{"read":true,"write":true}"#, "", 0),
            (204, "", json, 0),
            (401, r#"{"read":true,"write":true}"#, json, 0),
            (500, r#"{"read":true,"write":true}"#, json, 0),
            (200, r#"{"read":true,"write":true}"#, json, 2500),
        ]
        .into_iter()
        .enumerate()
        {
            let repo = format!("did:plc:undecided{i}");
            app.answer_as(&repo, status, body, ctype, delay);
            let what = format!("{status} {body} {ctype:?} after {delay}ms");
            assert_eq!(
                s.authorize_read(&forum, Some(&repo), None).await,
                Err(Undecided),
                "{what}"
            );
            if delay == 0 {
                assert_eq!(
                    s.authorize_write(&forum, &repo).await,
                    Err(Undecided),
                    "{what}"
                );
            }
        }
        assert_eq!(app.calls().len(), 27);
        // The service by its full id, and an endpoint with a trailing slash.
        let other = create_space(&s, &ta, "other", managed(&format!("{app_did}#other"))).await;
        assert_eq!(s.authorize_read(&other, Some(u), None).await, YES);
        assert_eq!(app.calls().len(), 1);
        // A fragment the document lacks, and a DID that does not resolve:
        // undecided, with no call.
        for (key, managing) in [
            ("missing", format!("{app_did}#missing")),
            ("nobody", "did:plc:nobodynobodynobodynobody#forum".into()),
        ] {
            let sr = create_space(&s, &ta, key, managed(&managing)).await;
            assert_eq!(
                (
                    s.authorize_read(&sr, Some(u), None).await,
                    s.authorize_write(&sr, u).await
                ),
                (Err(Undecided), Err(Undecided)),
                "{managing}"
            );
        }
        assert_eq!(app.calls().len(), 0);
        // At most IN_FLIGHT asks at once; the rest wait for a slot. (The
        // app is still answering the ask that took too long: wait it out.)
        while app.now.load(Ordering::SeqCst) > 0 {
            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
        }
        app.most.store(0, Ordering::SeqCst);
        app.answer(u, 200, r#"{"read":true,"write":true}"#, 100);
        let asks: Vec<_> = (0..3 * IN_FLIGHT)
            .map(|_| s.authorize_read(&forum, Some(u), None))
            .collect();
        assert!(futures_all(asks).await.into_iter().all(|ok| ok == YES));
        assert_eq!(app.most.load(Ordering::SeqCst), IN_FLIGHT);
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Where a managing app is asked (`spec/SPACES-POLICIES.md`, "Asking a
    /// managing app: checkAccess"): at its endpoint's origin, with the
    /// parameters alone; nothing to an endpoint with a user name or
    /// password, or to what is no endpoint; a redirect not followed; an
    /// answer longer than `JSON_DOC_MAX` bytes: each undecided.
    #[tokio::test]
    async fn managing_apps_are_asked_at_their_origin() {
        let (plc, docs) = directory().await;
        let (url, app) = app().await;
        let dir = scratch("authz-origin");
        let s = open(&dir, &plc);
        let (_, ta) = create(&s, "alice").await;
        let app_did = "did:plc:managingappmanagingappbb";
        let host = url.strip_prefix("http://").unwrap();
        let ends = [
            ("path", json!(format!("{url}/base/more?x=1#f"))),
            ("query", json!(format!("{url}/base?"))),
            ("userpass", json!(format!("http://u:p@{host}"))),
            ("user", json!(format!("http://u@{host}"))),
            ("ftp", json!(format!("ftp://{host}"))),
            ("bare", json!(host)),
            ("object", json!({ "uri": url })),
        ];
        let services: Vec<Json> = ends.iter().map(|(id, e)| json!({ "id": format!("#{id}"), "type": "ManagingApp", "serviceEndpoint": e })).collect();
        docs.lock().unwrap().insert(
            app_did.into(),
            json!({ "id": app_did, "service": services }),
        );
        let managed = |fragment: &str| json!({ "$type": MANAGED, "managingApp": format!("{app_did}#{fragment}") });
        let u = "did:plc:user";
        app.answer(u, 200, r#"{"read":true,"write":true}"#, 0);
        for fragment in ["path", "query"] {
            let sr = create_space(&s, &ta, fragment, managed(fragment)).await;
            assert_eq!(
                s.authorize_read(&sr, Some(u), None).await,
                YES,
                "{fragment}"
            );
            let want = BTreeMap::from([("space".to_string(), sr.uri()), ("repo".into(), u.into())]);
            assert_eq!(
                app.calls().into_iter().map(|c| c.0).collect::<Vec<_>>(),
                [want],
                "{fragment}"
            );
        }
        for fragment in ["userpass", "user", "ftp", "bare", "object"] {
            let sr = create_space(&s, &ta, fragment, managed(fragment)).await;
            assert_eq!(
                (
                    s.authorize_read(&sr, Some(u), None).await,
                    s.authorize_write(&sr, u).await
                ),
                (Err(Undecided), Err(Undecided)),
                "{fragment}"
            );
        }
        assert_eq!(app.calls().len(), 0);
        // A redirect to where the repo is authorized is not followed.
        let forum = create_space(&s, &ta, "forum", managed("path")).await;
        app.answer(
            "did:plc:moved",
            302,
            &format!("/xrpc/{CHECK_ACCESS}?repo={u}"),
            0,
        );
        assert_eq!(
            s.authorize_read(&forum, Some("did:plc:moved"), None).await,
            Err(Undecided)
        );
        assert_eq!(app.calls().len(), 1);
        // An answer is read up to JSON_DOC_MAX bytes; one longer is undecided.
        let of = |n: usize| {
            let head = r#"{"read":true,"write":true,"p":""#;
            format!("{head}{}\"}}", "x".repeat(n - head.len() - 2))
        };
        assert_eq!(of(outbound::JSON_DOC_MAX).len(), outbound::JSON_DOC_MAX);
        app.answer("did:plc:edge", 200, &of(outbound::JSON_DOC_MAX), 0);
        app.answer("did:plc:over", 200, &of(outbound::JSON_DOC_MAX + 1), 0);
        assert_eq!(
            s.authorize_read(&forum, Some("did:plc:edge"), None).await,
            YES
        );
        assert_eq!(
            s.authorize_read(&forum, Some("did:plc:over"), None).await,
            Err(Undecided)
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Run futures side by side, answering their outputs in order.
    async fn futures_all<T: Clone, F: Future<Output = T>>(fs: Vec<F>) -> Vec<T> {
        let mut set = Vec::new();
        for f in fs {
            set.push(Box::pin(f));
        }
        let mut out: Vec<Option<T>> = vec![None; set.len()];
        std::future::poll_fn(|cx| {
            for (i, f) in set.iter_mut().enumerate() {
                if out[i].is_none()
                    && let std::task::Poll::Ready(v) = f.as_mut().poll(cx)
                {
                    out[i] = Some(v);
                }
            }
            if out.iter().all(Option::is_some) {
                std::task::Poll::Ready(())
            } else {
                std::task::Poll::Pending
            }
        })
        .await;
        out.into_iter().map(Option::unwrap).collect()
    }
}