//! Space access policy and OAuth scope matching; JWT verification is in auth. use super::{SpaceService, domain::Space, space_not_found}; use crate::{ domain::oauth::AuthenticatedToken, error::{Error, Result}, syntax::{self, SpaceRef}, }; use serde_json::Value; impl SpaceService { pub(super) fn require_active_account(&self, did: &str) -> Result<()> { let (_account, status) = self .database .hosted_account_by_identifier(did)? .ok_or_else(|| Error::xrpc("RepoNotFound", "repository is not hosted by this PDS"))?; status.require_repo_active() } pub(crate) fn authorize_delegation( &self, auth: &AuthenticatedToken, space: &str, ) -> Result<()> { if auth.account.did != self.hosted_did { return Err(Error::Authorization( "OAuth account is not hosted by this PDS".to_owned(), )); } let space_ref = space.parse::()?; require_scope(auth, &space_ref, Capability::Read) } pub(crate) fn authorize_credential( &self, space: &str, user_did: &str, client_id: Option<&str>, ) -> Result> { self.require_active_account(&self.hosted_did)?; let space_ref = space.parse::()?; if space_ref.authority != self.hosted_did { return Err(Error::xrpc( "SpaceNotFound", "this PDS is not the space host", )); } match self.database.space_is_deleted(space)? { Some(true) => return Err(Error::xrpc("SpaceDeleted", "space has been deleted")), None => return Err(Error::xrpc("SpaceNotFound", "space does not exist")), Some(false) => {} } let local = self.database.space(space)?; if union_type(&local.app_access) == Some("com.atproto.simplespace.defs#allowList") { let allowed = local.app_access["allowed"] .as_array() .expect("validated allowList policy"); if !client_id.is_some_and(|client| { allowed .iter() .any(|allowed| allowed.as_str() == Some(client)) }) { return Err(Error::xrpc( "AppNotAuthorized", "application is not authorized for this space", )); } } if user_did == local.authority || self.user_can_read(&local, user_did)? { return Ok(None); } match union_type(&local.policy) { Some("com.atproto.simplespace.defs#managingAppPolicy") => local.policy["managingApp"] .as_str() .map(ToOwned::to_owned) .map(Some) .ok_or_else(|| Error::xrpc("UserNotAuthorized", "managing app is not configured")), _ => Err(Error::xrpc( "UserNotAuthorized", "user is not authorized for this space", )), } } pub(super) fn authorize_write( &self, auth: &AuthenticatedToken, space: &str, repo: &str, collection: &str, action: &'static str, ) -> Result { if repo != auth.account.did { return Err(Error::Authorization( "a permissioned write must target the authenticated account DID".to_owned(), )); } self.require_active_account(repo)?; syntax::collection(collection)?; let space_ref = space.parse::()?; require_scope(auth, &space_ref, Capability::Record(action, collection))?; if space_ref.authority == self.hosted_did { let local = self.database.space(space).map_err(space_not_found)?; if !self.user_can_read(&local, &auth.account.did)? { return Err(Error::Authorization( "the account is not a member of this space".to_owned(), )); } } Ok(space_ref) } pub(super) fn authorize_read( &self, auth: &ReadAuthorization, space: &str, repo: &str, ) -> Result { let space_ref = space.parse::()?; match auth { ReadAuthorization::OAuth(auth) => { if repo != auth.account.did { return Err(Error::Authorization( "an OAuth credential can only read its account's own permissioned repo" .to_owned(), )); } require_scope(auth, &space_ref, Capability::ReadSelf)?; if space_ref.authority == self.hosted_did { let local = self.database.space(space).map_err(space_not_found)?; if !self.user_can_read(&local, &auth.account.did)? { return Err(Error::Authorization( "the account is not a member of this space".to_owned(), )); } } } ReadAuthorization::Credential(credential_space) => { if credential_space != space { return Err(Error::Authorization( "space credential does not cover the requested space".to_owned(), )); } } } self.require_active_account(repo)?; Ok(space_ref) } pub(super) fn require_owner(&self, auth: &AuthenticatedToken, space: &SpaceRef) -> Result<()> { if space.authority != auth.account.did || space.authority != self.hosted_did { return Err(Error::Authorization( "the authenticated account is not the space owner".to_owned(), )); } Ok(()) } pub(super) fn assert_local_credential_space( &self, credential_space: &str, space: &str, ) -> Result<()> { if credential_space != space { return Err(Error::Authorization( "space credential does not cover the requested space".to_owned(), )); } let space_ref = space.parse::()?; if space_ref.authority != self.hosted_did { return Err(Error::xrpc( "SpaceNotFound", "this PDS is not the space host", )); } self.database.space(space).map_err(space_not_found)?; Ok(()) } pub(super) fn user_can_read(&self, space: &Space, did: &str) -> Result { match union_type(&space.policy) { Some("com.atproto.simplespace.defs#publicPolicy") => Ok(true), Some("com.atproto.simplespace.defs#memberListPolicy") => { self.database.is_space_member(&space.uri, did) } // A managing-app callback is intentionally not guessed. Until a // configured verifier exists, only the owner is admitted. Some("com.atproto.simplespace.defs#managingAppPolicy") => Ok(space.authority == did), _ => Ok(false), } } } pub(crate) enum ReadAuthorization { OAuth(AuthenticatedToken), Credential(String), } #[derive(Clone, Copy)] pub(super) enum Capability<'a> { Read, ReadSelf, Record(&'static str, &'a str), Manage(&'static str), } pub(super) fn require_scope( auth: &AuthenticatedToken, target: &SpaceRef, capability: Capability<'_>, ) -> Result<()> { if auth.scope.split_ascii_whitespace().any(|scope| { parse_space_scope(scope).is_some_and(|grant| { grant.matches(&auth.account.did, target) && grant.permits(capability) }) }) { return Ok(()); } Err(Error::Authorization(format!( "OAuth token has no covering `space:` grant for {target}" ))) } struct SpaceGrant { space_type: String, authority: String, skey: String, collections: Vec, actions: Vec, manage: Vec, } impl SpaceGrant { fn matches(&self, actor: &str, target: &SpaceRef) -> bool { (self.space_type == "*" || self.space_type == target.space_type) && (self.authority == "*" || self.authority == target.authority || (self.authority == "self" && target.authority == actor)) && (self.skey == "*" || self.skey == target.skey) } fn permits(&self, capability: Capability<'_>) -> bool { match capability { Capability::Read => self.actions.iter().any(|value| value == "read"), Capability::ReadSelf => { self.actions.is_empty() || self.actions.iter().any(|value| value == "read") || self.actions.iter().any(|value| value == "read_self") } Capability::Record(action, collection) => { let action_allowed = self.actions.is_empty() || self.actions.iter().any(|value| value == action); let collection_allowed = self .collections .iter() .any(|value| value == "*" || value == collection); action_allowed && collection_allowed } Capability::Manage(action) => self.manage.iter().any(|value| value == action), } } } fn parse_space_scope(value: &str) -> Option { let value = value.strip_prefix("space:")?; let (space_type, query) = value.split_once('?').unwrap_or((value, "")); if space_type != "*" && syntax::collection(space_type).is_err() { return None; } let mut grant = SpaceGrant { space_type: space_type.to_owned(), authority: "self".to_owned(), skey: "*".to_owned(), collections: Vec::new(), actions: Vec::new(), manage: Vec::new(), }; for (name, value) in url::form_urlencoded::parse(query.as_bytes()) { match name.as_ref() { "authority" => grant.authority = value.into_owned(), "skey" => grant.skey = value.into_owned(), "collection" => grant.collections.push(value.into_owned()), "action" => grant.actions.push(value.into_owned()), "manage" => grant.manage.push(value.into_owned()), _ => return None, } } Some(grant) } pub(super) fn validate_policy(value: &Value) -> Result<()> { match union_type(value) { Some( "com.atproto.simplespace.defs#publicPolicy" | "com.atproto.simplespace.defs#memberListPolicy", ) => Ok(()), Some("com.atproto.simplespace.defs#managingAppPolicy") if value["managingApp"].as_str().is_some() => { Ok(()) } _ => Err(Error::InvalidRequest( "unsupported simplespace policy".to_owned(), )), } } pub(super) fn validate_app_access(value: &Value) -> Result<()> { match union_type(value) { Some("com.atproto.simplespace.defs#open") => Ok(()), Some("com.atproto.simplespace.defs#allowList") if value["allowed"] .as_array() .is_some_and(|values| values.iter().all(Value::is_string)) => { Ok(()) } _ => Err(Error::InvalidRequest( "unsupported simplespace appAccess policy".to_owned(), )), } } pub(super) fn union_type(value: &Value) -> Option<&str> { value.as_object()?.get("$type")?.as_str() }