Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/colibri-social/appview. The AppView (backend server) for Colibri api.colibri.social
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369//! Shared scaffolding for authenticated XRPC handlers.//!//! Every authenticated community endpoint repeats the same prelude — parse//! the community AT-URI, verify the service-auth JWT, load the caller's//! authz state for the community, optionally check a permission — and the//! same error shapes for each of those failure modes. This module holds://!//! - `CallerContext`: what an authenticated handler typically needs.//! - `with_community_authz`: the combinator that runs the prelude and hands//! `CallerContext` + `DatabaseConnection` to a body closure.//! - `with_authenticated`: the simpler variant for handlers that need//! service auth but no community context (notification endpoints, etc.).//! - Reusable dependency types (`VerifyAuthFn`, `LoadAuthzFn`) and the//! production-side boxed implementations (`verify_auth_boxed`,//! `load_authz_boxed`), so each handler stops redefining its own copy.//! - Error-response constructors (`auth_error`, `invalid_community_uri`,//! `forbidden`) used both by the combinator and by handlers that need to//! emit the same shapes from their own bodies.
use std::future::Future;
use futures::future::BoxFuture;use sea_orm::{DatabaseConnection, DbErr};
use crate::lib::at_uri::AtUri;use crate::lib::community_authz::{self, ActorAuthz};use crate::lib::permissions::Permission;use crate::lib::responses::{ErrorCode, ErrorResponse};use crate::lib::service_auth::{self, ServiceAuthError};
// ---- Reusable dependency types ------------------------------------------
pub type VerifyAuthFn = dyn Fn(String, String) -> BoxFuture<'static, Result<String, ServiceAuthError>> + Send + Sync;pub type LoadAuthzFn = dyn Fn(DatabaseConnection, String, String) -> BoxFuture<'static, Result<ActorAuthz, DbErr>> + Send + Sync;
pub fn verify_auth_boxed( auth: String, lxm: String,) -> BoxFuture<'static, Result<String, ServiceAuthError>> { Box::pin(async move { service_auth::verify_service_auth(&auth, &lxm).await })}
pub fn load_authz_boxed( db: DatabaseConnection, community_uri: String, did: String,) -> BoxFuture<'static, Result<ActorAuthz, DbErr>> { Box::pin(async move { community_authz::load_actor_authz(&db, &community_uri, &did).await })}
// ---- Error-response constructors ----------------------------------------
pub fn auth_error(err: ServiceAuthError) -> ErrorResponse { ErrorCode::AuthRequired.with(err.to_string())}
pub fn invalid_community_uri() -> ErrorResponse { ErrorCode::InvalidRequest.with("Invalid community AT-URI.")}
pub fn forbidden(permission: Permission) -> ErrorResponse { ErrorCode::Forbidden.with(format!("Missing permission: {permission}"))}
// ---- Caller context -----------------------------------------------------
/// Aggregated state every authenticated community handler needs once the/// prelude has run.#[derive(Debug)]pub struct CallerContext { pub caller_did: String, pub community: AtUri, /// The original AT-URI string as supplied to the combinator. Retained so /// handlers that need to re-issue authz lookups for a different DID can /// reuse the same `LoadAuthzFn` without rebuilding the URI from the /// parsed parts. pub community_uri: String, pub authz: ActorAuthz,}
// ---- Combinators --------------------------------------------------------
/// Authenticated community handler combinator.////// Runs the prelude every community-scoped endpoint shares:////// 1. Parse `community_uri` to an [`AtUri`] (→ `InvalidRequest` on failure)./// 2. Verify `auth` for `lxm` to a caller DID (→ `AuthRequired`)./// 3. Load the caller's [`ActorAuthz`] for the community./// 4. If `permission` is `Some`, refuse with `Forbidden` unless the caller/// holds it (no channel scope — use [`with_community_authz_scoped`] for/// endpoints that act on a specific channel, so per-channel permission/// overrides apply).////// On success, invokes `body` with [`CallerContext`] and the same/// `DatabaseConnection` so the body can issue further queries.#[allow(clippy::too_many_arguments)]pub async fn with_community_authz<F, Fut, T>( auth: String, lxm: &'static str, community_uri: String, permission: Option<Permission>, db: DatabaseConnection, verify_auth_fn: &VerifyAuthFn, load_authz_fn: &LoadAuthzFn, body: F,) -> Result<T, ErrorResponse>where F: FnOnce(CallerContext, DatabaseConnection) -> Fut, Fut: Future<Output = Result<T, ErrorResponse>>,{ with_community_authz_scoped( auth, lxm, community_uri, permission, None, db, verify_auth_fn, load_authz_fn, body, ) .await}
/// Same as [`with_community_authz`], but `channel_rkey` (when given) scopes/// the permission check so a role's per-channel `allow`/`deny` overrides for/// that channel are consulted, not just its base permission list. Use this/// for any endpoint that acts on a specific, already-known channel.#[allow(clippy::too_many_arguments)]pub async fn with_community_authz_scoped<F, Fut, T>( auth: String, lxm: &'static str, community_uri: String, permission: Option<Permission>, channel_rkey: Option<&str>, db: DatabaseConnection, verify_auth_fn: &VerifyAuthFn, load_authz_fn: &LoadAuthzFn, body: F,) -> Result<T, ErrorResponse>where F: FnOnce(CallerContext, DatabaseConnection) -> Fut, Fut: Future<Output = Result<T, ErrorResponse>>,{ let community = AtUri::parse(&community_uri).ok_or_else(invalid_community_uri)?; let caller_did = verify_auth_fn(auth, lxm.to_string()) .await .map_err(auth_error)?; let authz = load_authz_fn(db.clone(), community_uri.clone(), caller_did.clone()).await?;
if let Some(perm) = permission && !authz.has(perm, channel_rkey) { return Err(forbidden(perm)); }
body( CallerContext { caller_did, community, community_uri, authz, }, db, ) .await}
/// Authenticated-only handler combinator (no community context).////// Verifies the service-auth JWT and hands `caller_did` + `db` to the body./// Use this for endpoints that only need to know who's calling — notification/// endpoints, anything keyed by the caller's own DID.pub async fn with_authenticated<F, Fut, T>( auth: String, lxm: &'static str, db: DatabaseConnection, verify_auth_fn: &VerifyAuthFn, body: F,) -> Result<T, ErrorResponse>where F: FnOnce(String, DatabaseConnection) -> Fut, Fut: Future<Output = Result<T, ErrorResponse>>,{ let caller_did = verify_auth_fn(auth, lxm.to_string()) .await .map_err(auth_error)?; body(caller_did, db).await}
#[cfg(test)]mod tests { use super::*; use crate::lib::permissions::Permission; use crate::lib::test_fixtures::{empty_authz, mock_db, owner_authz}; use rocket::tokio;
#[tokio::test] async fn with_community_authz_runs_body_when_owner_and_no_permission_required() { let db = mock_db(); let result: Result<&'static str, ErrorResponse> = with_community_authz( String::from("token"), "social.colibri.test", String::from("at://did:plc:owner/social.colibri.community/c1"), None, db, &|_, _| Box::pin(async { Ok(String::from("did:plc:owner")) }), &|_, _, _| Box::pin(async { Ok(owner_authz()) }), |ctx, _db| async move { assert_eq!(ctx.caller_did, "did:plc:owner"); assert_eq!(ctx.community.authority, "did:plc:owner"); assert!(ctx.authz.is_owner); Ok("ran") }, ) .await; assert_eq!(result.unwrap(), "ran"); }
#[tokio::test] async fn with_community_authz_rejects_invalid_uri_without_calling_anything() { let db = mock_db(); let result: Result<(), ErrorResponse> = with_community_authz( String::from("token"), "social.colibri.test", String::from("not-a-uri"), None, db, &|_, _| Box::pin(async { panic!("should not authenticate") }), &|_, _, _| Box::pin(async { panic!("should not load authz") }), |_, _| async { panic!("should not run body") }, ) .await; assert_eq!( result.err().unwrap().body.into_inner().error, "InvalidRequest" ); }
#[tokio::test] async fn with_community_authz_rejects_when_permission_missing() { let db = mock_db(); let result: Result<(), ErrorResponse> = with_community_authz( String::from("token"), "social.colibri.test", String::from("at://did:plc:owner/social.colibri.community/c1"), Some(Permission::MemberBan), db, &|_, _| Box::pin(async { Ok(String::from("did:plc:rando")) }), &|_, _, _| Box::pin(async { Ok(empty_authz()) }), |_, _| async { panic!("should not run body when permission missing") }, ) .await; assert_eq!(result.err().unwrap().body.into_inner().error, "Forbidden"); }
#[tokio::test] async fn with_community_authz_surfaces_auth_error() { let db = mock_db(); let result: Result<(), ErrorResponse> = with_community_authz( String::from("token"), "social.colibri.test", String::from("at://did:plc:owner/social.colibri.community/c1"), None, db, &|_, _| Box::pin(async { Err(ServiceAuthError::InvalidSignature) }), &|_, _, _| Box::pin(async { panic!("should not load authz") }), |_, _| async { panic!("should not run body") }, ) .await; assert_eq!( result.err().unwrap().body.into_inner().error, "AuthRequired" ); }
#[tokio::test] async fn with_community_authz_scoped_consults_channel_override_deny() { use crate::lib::test_fixtures::{member, role_with_override};
let db = mock_db(); let authz = ActorAuthz { is_owner: false, member: Some(member("did:plc:mod", vec!["mod"])), roles: vec![role_with_override( "Moderator", 10, vec![Permission::MessageDelete], "chan-a", vec![], vec![Permission::MessageDelete], )], };
let result: Result<(), ErrorResponse> = with_community_authz_scoped( String::from("token"), "social.colibri.test", String::from("at://did:plc:owner/social.colibri.community/c1"), Some(Permission::MessageDelete), Some("chan-a"), db, &|_, _| Box::pin(async { Ok(String::from("did:plc:mod")) }), &move |_, _, _| { let authz = authz.clone(); Box::pin(async move { Ok(authz) }) }, |_, _| async { panic!("should not run body: channel override denies this") }, ) .await;
assert_eq!(result.err().unwrap().body.into_inner().error, "Forbidden"); }
#[tokio::test] async fn with_community_authz_scoped_allows_outside_the_overridden_channel() { use crate::lib::test_fixtures::{member, role_with_override};
let db = mock_db(); let authz = ActorAuthz { is_owner: false, member: Some(member("did:plc:mod", vec!["mod"])), roles: vec![role_with_override( "Moderator", 10, vec![Permission::MessageDelete], "chan-a", vec![], vec![Permission::MessageDelete], )], };
let result: Result<&'static str, ErrorResponse> = with_community_authz_scoped( String::from("token"), "social.colibri.test", String::from("at://did:plc:owner/social.colibri.community/c1"), Some(Permission::MessageDelete), Some("chan-b"), db, &|_, _| Box::pin(async { Ok(String::from("did:plc:mod")) }), &move |_, _, _| { let authz = authz.clone(); Box::pin(async move { Ok(authz) }) }, |_, _| async { Ok("ran") }, ) .await;
assert_eq!(result.unwrap(), "ran"); }
#[tokio::test] async fn with_authenticated_passes_caller_did_to_body() { let db = mock_db(); let result: Result<String, ErrorResponse> = with_authenticated( String::from("token"), "social.colibri.test", db, &|_, _| Box::pin(async { Ok(String::from("did:plc:me")) }), |caller, _| async move { Ok(caller) }, ) .await; assert_eq!(result.unwrap(), "did:plc:me"); }}