chadtmiller.com/group-host
atmosphere group host
0
0
The host answers XRPC through atproto-server, on the shared crates' new releases
crates/atgrp/src/lib.rs+3−6
| @@ -318,12 +318,9 @@ impl Client { | ||
bytes: Vec<u8>, | ||
kind: &str, | ||
) -> Result<Value> { | ||
let token = self.token(&host.did, lxm).await?; | ||
let url = format!("{}/xrpc/{lxm}", host.url); | ||
let asked = self.http.post(url).bearer_auth(token).query(params); | ||
let sent = asked.header("content-type", kind).body(bytes).send().await; | ||
let res = sent.context(format!("reaching {}", host.url))?; | ||
answer(res, lxm).await | ||
let (at, auth) = self.at(host, lxm).await?; | ||
let answer = at.procedure_bytes(lxm, params, bytes, kind, Some(&auth)); | ||
said(lxm, &host.url, answer.await) | ||
} | ||
| ||
/// Invites `invitee` to `group`, as the group: with a group token for | ||
crates/group-host/src/account_move.rs+41−55
| @@ -32,13 +32,14 @@ use crate::migration::creds; | ||
use crate::rbac::INTERNAL; | ||
use crate::store::Store; | ||
use crate::time::now_millis; | ||
use crate::xrpc::XrpcError; | ||
use crate::xrpc::internal; | ||
use anyhow::Result; | ||
use atproto::did; | ||
use atproto::space::SPACE_URI_PREFIX; | ||
use atproto_client::oauth::{self as login, Session, SessionStore, StoreError}; | ||
use atproto_client::service_auth; | ||
use atproto_client::xrpc::{self, Auth, Xrpc}; | ||
use atproto_server::Error; | ||
use axum::Json; | ||
use axum::extract::{Query, RawQuery, State}; | ||
use axum::http::{HeaderMap, StatusCode, header}; | ||
| @@ -48,13 +49,14 @@ use serde_json::{Value, json}; | ||
use std::collections::HashMap; | ||
use std::sync::Arc; | ||
| ||
type Answer = Result<Json<Value>, XrpcError>; | ||
type Answer = Result<Json<Value>, Error>; | ||
| ||
/// How long the host keeps an account's session for a move not finished. | ||
const KEPT_FOR: i64 = 24 * 60 * 60_000; | ||
| ||
/// The sessions of accounts being moved here, in the database, by the | ||
/// account: the store of the console's client for moves. | ||
/// The sessions of accounts being moved here, in the database, kept by the | ||
/// account's DID as the session id, one session per account: the store of | ||
/// the console's client for moves. | ||
pub(crate) struct Moves(pub Store); | ||
| ||
impl SessionStore for Moves { | ||
| @@ -64,8 +66,8 @@ impl SessionStore for Moves { | ||
| ||
/// A session kept only while its account's move is: one whose move | ||
/// was finished, cancelled or swept meanwhile has ended. | ||
fn put(&self, session: &Session) -> Result<(), StoreError> { | ||
match self.0.keep_oauth_session(session).map_err(unstored)? { | ||
fn put(&self, did: &str, session: &Session) -> Result<(), StoreError> { | ||
match self.0.keep_oauth_session(did, session).map_err(unstored)? { | ||
true => Ok(()), | ||
false => Err(StoreError::Ended), | ||
} | ||
| @@ -129,12 +131,12 @@ impl Store { | ||
Ok(found.map(|s| serde_json::from_str(&s)).transpose()?) | ||
} | ||
| ||
/// Keeps `session`, in place of any for its account, while the account | ||
/// is being moved: whether it is. | ||
pub fn keep_oauth_session(&self, session: &Session) -> Result<bool> { | ||
/// Keeps `session` for the account `did`, in place of any before, | ||
/// while the account is being moved: whether it is. | ||
pub fn keep_oauth_session(&self, did: &str, session: &Session) -> Result<bool> { | ||
let kept = serde_json::to_string(session)?; | ||
let conn = self.conn(); | ||
Ok(conn.execute(KEEP_SESSION, params![session.did, kept])? == 1) | ||
Ok(conn.execute(KEEP_SESSION, params![did, kept])? == 1) | ||
} | ||
| ||
/// Forgets the session kept for `did`. | ||
| @@ -158,24 +160,24 @@ fn escaped(text: &str) -> String { | ||
} | ||
| ||
/// The account's server, failing or saying no. | ||
fn upstream(why: impl std::fmt::Display) -> XrpcError { | ||
XrpcError::new( | ||
fn upstream(why: impl std::fmt::Display) -> Error { | ||
Error::new( | ||
StatusCode::BAD_GATEWAY, | ||
"UpstreamFailure", | ||
format!("the account's server: {why}"), | ||
) | ||
} | ||
| ||
fn none_here() -> XrpcError { | ||
XrpcError::new( | ||
fn none_here() -> Error { | ||
Error::new( | ||
StatusCode::BAD_REQUEST, | ||
"NotFound", | ||
"no account is signed in for you to move: sign in to it first", | ||
) | ||
} | ||
| ||
fn sign_in_again() -> XrpcError { | ||
XrpcError::new( | ||
fn sign_in_again() -> Error { | ||
Error::new( | ||
StatusCode::BAD_REQUEST, | ||
"SignInAgain", | ||
"the account's sign-in has lapsed: sign in to it again", | ||
| @@ -218,7 +220,7 @@ impl Host { | ||
} | ||
| ||
/// `did`'s session, refreshed if it is about to lapse, or `now_anyway`. | ||
async fn moving_session(&self, did: &str, now_anyway: bool) -> Result<Session, XrpcError> { | ||
async fn moving_session(&self, did: &str, now_anyway: bool) -> Result<Session, Error> { | ||
let session = match now_anyway { | ||
true => self.console.refresh(did).await.map(|r| r.session), | ||
false => self.console.session(did).await, | ||
| @@ -240,7 +242,7 @@ impl Host { | ||
did: &str, | ||
renew: bool, | ||
at_most: usize, | ||
) -> Result<(Xrpc, Auth), XrpcError> { | ||
) -> Result<(Xrpc, Auth), Error> { | ||
let session = self.moving_session(did, renew).await?; | ||
let auth = self.console.auth(&session).map_err(upstream)?; | ||
Ok((self.console.pds(&session).at_most(at_most), auth)) | ||
| @@ -254,7 +256,7 @@ impl Host { | ||
&self, | ||
(did, nsid, at_most): (&str, &str, usize), | ||
call: impl Fn(Xrpc, Auth) -> F, | ||
) -> Result<T, XrpcError> | ||
) -> Result<T, Error> | ||
where | ||
F: Future<Output = Result<T, xrpc::Error>>, | ||
{ | ||
| @@ -278,7 +280,7 @@ impl Host { | ||
nsid: &str, | ||
query: &[(&str, &str)], | ||
body: Option<&Value>, | ||
) -> Result<Value, XrpcError> { | ||
) -> Result<Value, Error> { | ||
let input = body.filter(|b| !b.is_null()); | ||
let call = |pds: Xrpc, auth: Auth| async move { | ||
match body { | ||
| @@ -296,7 +298,7 @@ impl Host { | ||
did: &str, | ||
nsid: &str, | ||
query: &[(&str, &str)], | ||
) -> Result<Option<(Vec<u8>, String)>, XrpcError> { | ||
) -> Result<Option<(Vec<u8>, String)>, Error> { | ||
let call = |pds: Xrpc, auth: Auth| async move { | ||
let read = pds.query_raw(nsid, query, Some(&auth)).await; | ||
let errored = read.as_ref().err().and_then(xrpc::Error::xrpc); | ||
| @@ -316,7 +318,7 @@ impl Host { | ||
/// The account's spaces, each brought here as its server serves them: | ||
/// a space it governs first, then its files there, then its repo, | ||
/// which holds them. How many spaces, records and files. | ||
async fn bring_spaces(&self, m: &Session) -> Result<(usize, usize, usize), XrpcError> { | ||
async fn bring_spaces(&self, m: &Session) -> Result<(usize, usize, usize), Error> { | ||
let did = m.did.as_str(); | ||
let mut spaces = Vec::new(); | ||
// Only a server that says it holds spaces has any to bring: most do | ||
| @@ -392,8 +394,8 @@ pub async fn login( | ||
State(host): State<Arc<Host>>, | ||
headers: HeaderMap, | ||
Query(q): Query<HashMap<String, String>>, | ||
) -> Result<Response, XrpcError> { | ||
let me = host.console_caller(&headers).map_err(XrpcError::internal)?; | ||
) -> Result<Response, Error> { | ||
let me = host.console_caller(&headers).map_err(internal)?; | ||
let Some(me) = me else { | ||
let why = "Signing in failed: sign in to the console first"; | ||
return Ok((StatusCode::UNAUTHORIZED, why).into_response()); | ||
| @@ -409,7 +411,7 @@ pub async fn callback( | ||
State(host): State<Arc<Host>>, | ||
headers: HeaderMap, | ||
RawQuery(query): RawQuery, | ||
) -> Result<Response, XrpcError> { | ||
) -> Result<Response, Error> { | ||
let query = query.unwrap_or_default(); | ||
let (session, started) = match come_back(&host, &headers, &query, true).await? { | ||
Ok(back) => back, | ||
| @@ -420,41 +422,31 @@ pub async fn callback( | ||
// back, as is the account they were moving before, if another. | ||
let mover = started.mover.unwrap_or_default(); | ||
let before = host.store.keep_move(&mover, &session.did, now_millis()); | ||
if let Some(before) = before.map_err(XrpcError::internal)? { | ||
if let Some(before) = before.map_err(internal)? { | ||
host.give_back(&before).await; | ||
} | ||
let kept = host.console.keep(&session).await; | ||
kept.map_err(XrpcError::internal)?; | ||
let kept = host.console.replace(&session.did, &session).await; | ||
kept.map_err(internal)?; | ||
tracing::info!(did = session.did, mover, "signed in to an account to move"); | ||
let done = [(header::SET_COOKIE, done(&host))]; | ||
Ok((done, Redirect::to(&started.back)).into_response()) | ||
} | ||
| ||
/// The session of the account `me` signed in to move. | ||
fn moving(host: &Host, me: &str) -> Result<Session, XrpcError> { | ||
let found = host | ||
.store | ||
.move_of(me, now_millis()) | ||
.map_err(XrpcError::internal)?; | ||
fn moving(host: &Host, me: &str) -> Result<Session, Error> { | ||
let found = host.store.move_of(me, now_millis()).map_err(internal)?; | ||
found.ok_or_else(none_here) | ||
} | ||
| ||
/// The account signed in for the caller to move, if any. | ||
pub async fn get_account_move(State(host): State<Arc<Host>>, headers: HeaderMap) -> Answer { | ||
let me = signed_in(&host, &headers, &format!("{INTERNAL}.getAccountMove")).await?; | ||
let Some(m) = host | ||
.store | ||
.move_of(&me, now_millis()) | ||
.map_err(XrpcError::internal)? | ||
else { | ||
let Some(m) = host.store.move_of(&me, now_millis()).map_err(internal)? else { | ||
return Ok(Json(json!({}))); | ||
}; | ||
let doc = host.identity.document_now(&m.did).await.ok(); | ||
let handle = doc.as_ref().and_then(did::handle); | ||
let pending = host | ||
.store | ||
.pending_import(&m.did) | ||
.map_err(XrpcError::internal)?; | ||
let handle = doc.as_deref().and_then(did::handle); | ||
let pending = host.store.pending_import(&m.did).map_err(internal)?; | ||
let started = pending.is_some_and(|p| p.founder == me); | ||
let mut out = json!({"did": m.did, "pds": m.pds, "started": started}); | ||
if let Some(handle) = handle { | ||
| @@ -501,18 +493,15 @@ pub async fn finish_account_move( | ||
let me = signed_in(&host, &headers, &format!("{INTERNAL}.finishAccountMove")).await?; | ||
let m = moving(&host, &me)?; | ||
let code = body["code"].as_str().map(str::trim).unwrap_or_default(); | ||
let pending = host | ||
.store | ||
.pending_import(&m.did) | ||
.map_err(XrpcError::internal)?; | ||
let pending = host.store.pending_import(&m.did).map_err(internal)?; | ||
if !pending.is_some_and(|p| p.founder == me) { | ||
return Err(XrpcError::new( | ||
return Err(Error::new( | ||
StatusCode::BAD_REQUEST, | ||
"NotStarted", | ||
"start the move first", | ||
)); | ||
} | ||
let account = host.store.account(&m.did).map_err(XrpcError::internal)?; | ||
let account = host.store.account(&m.did).map_err(internal)?; | ||
let mut asked = creds(&host, &account.expect("a move's account")); | ||
asked["token"] = json!(code); | ||
let sign = "com.atproto.identity.signPlcOperation"; | ||
| @@ -520,7 +509,7 @@ pub async fn finish_account_move( | ||
let done = host | ||
.complete_import_as(&me, &m.did, &signed["operation"]) | ||
.await?; | ||
host.store.forget_move(&me).map_err(XrpcError::internal)?; | ||
host.store.forget_move(&me).map_err(internal)?; | ||
host.give_back(&m.did).await; | ||
Ok(Json(done)) | ||
} | ||
| @@ -530,14 +519,11 @@ pub async fn finish_account_move( | ||
pub async fn cancel_account_move(State(host): State<Arc<Host>>, headers: HeaderMap) -> Answer { | ||
let me = signed_in(&host, &headers, &format!("{INTERNAL}.cancelAccountMove")).await?; | ||
let m = moving(&host, &me)?; | ||
let pending = host | ||
.store | ||
.pending_import(&m.did) | ||
.map_err(XrpcError::internal)?; | ||
let pending = host.store.pending_import(&m.did).map_err(internal)?; | ||
if pending.is_some_and(|p| p.founder == me) { | ||
host.forget(&m.did); | ||
} | ||
host.store.forget_move(&me).map_err(XrpcError::internal)?; | ||
host.store.forget_move(&me).map_err(internal)?; | ||
host.give_back(&m.did).await; | ||
Ok(Json(json!({}))) | ||
} | ||
crates/group-host/src/actor_search.rs+2−2
| @@ -11,8 +11,8 @@ | ||
| ||
use crate::Host; | ||
use crate::api::Params; | ||
use crate::xrpc::XrpcError; | ||
use atproto::did; | ||
use atproto_server::Error; | ||
use axum::Json; | ||
use axum::extract::{Query, State}; | ||
use serde_json::{Value, json}; | ||
| @@ -128,7 +128,7 @@ impl Host { | ||
pub async fn search_actors( | ||
State(host): State<Arc<Host>>, | ||
Query(p): Query<Params>, | ||
) -> Result<Json<Value>, XrpcError> { | ||
) -> Result<Json<Value>, Error> { | ||
let q = p | ||
.get("q") | ||
.map_or("", |q| q.trim().trim_start_matches('@')) | ||
crates/group-host/src/actors.rs+13−15
| @@ -7,8 +7,9 @@ use crate::group::{members_space, meta_space}; | ||
use crate::group_api::{caller, group_of, signed_in}; | ||
use crate::rbac::{INTERNAL, NS}; | ||
use crate::store::Store; | ||
use crate::xrpc::XrpcError; | ||
use crate::xrpc::internal; | ||
use atproto::did; | ||
use atproto_server::Error; | ||
use axum::Json; | ||
use axum::extract::{Query, State}; | ||
use axum::http::{HeaderMap, StatusCode}; | ||
| @@ -16,7 +17,7 @@ use serde_json::{Value, json}; | ||
use std::collections::{BTreeSet, HashMap}; | ||
use std::sync::Arc; | ||
| ||
type Answer = Result<Json<Value>, XrpcError>; | ||
type Answer = Result<Json<Value>, Error>; | ||
| ||
/// Who is asking, by the console's cookie or service auth, and the other | ||
/// accounts the browser is signed in to: nothing, for no one. | ||
| @@ -27,12 +28,12 @@ pub async fn get_viewer(State(host): State<Arc<Host>>, headers: HeaderMap) -> An | ||
}; | ||
let mut actor = json!({"did": me, "canCreateGroup": host.may_found(&me)}); | ||
let doc = host.identity.document_now(&me).await.ok(); | ||
if let Some(handle) = doc.as_ref().and_then(did::handle) { | ||
if let Some(handle) = doc.as_deref().and_then(did::handle) { | ||
actor["handle"] = json!(handle); | ||
} | ||
let mut answer = json!({ "actor": actor, "signUpAt": signup }); | ||
let others = host.console_others(&headers, Some(&me)); | ||
let others = others.map_err(XrpcError::internal)?; | ||
let others = others.map_err(internal)?; | ||
if !others.is_empty() { | ||
let views = futures::future::join_all(others.iter().map(|(d, _)| host.actor_view(d))); | ||
answer["accounts"] = json!(views.await); | ||
| @@ -45,7 +46,7 @@ impl Host { | ||
/// document names, if it can be read. | ||
pub(crate) async fn actor_view(&self, did: &str) -> Value { | ||
let doc = self.identity.document_now(did).await.ok(); | ||
match doc.as_ref().and_then(did::handle) { | ||
match doc.as_deref().and_then(did::handle) { | ||
Some(handle) => json!({"did": did, "handle": handle}), | ||
None => json!({"did": did}), | ||
} | ||
| @@ -66,14 +67,14 @@ impl Host { | ||
/// name and picture as they may read them, and how many are in it. | ||
fn group_view_basic(&self, group: &str, viewer: &str) -> Answer { | ||
let handle = group_of(self, group)?; | ||
let address = self.store.address(group).map_err(XrpcError::internal)?; | ||
let address = self.store.address(group).map_err(internal)?; | ||
let address = address.expect("a group has an address"); | ||
let mut view = json!({"did": group, "handle": handle, "address": address}); | ||
let roles = self.roles(group, viewer).map_err(XrpcError::internal)?; | ||
let roles = self.roles(group, viewer).map_err(internal)?; | ||
let meta = meta_space(group); | ||
if self.reads_space(&meta, &roles)? { | ||
let profile = self.group_record(group, &meta, &format!("{NS}.about"), "self"); | ||
let profile = profile.map_err(XrpcError::internal)?.unwrap_or_default(); | ||
let profile = profile.map_err(internal)?.unwrap_or_default(); | ||
if let Some(name) = profile.get("displayName") { | ||
view["displayName"] = name.clone(); | ||
} | ||
| @@ -82,7 +83,7 @@ impl Host { | ||
} | ||
} | ||
let members = self.group_records(group, &members_space(group), &format!("{NS}.membership")); | ||
view["memberCount"] = json!(members.map_err(XrpcError::internal)?.len()); | ||
view["memberCount"] = json!(members.map_err(internal)?.len()); | ||
Ok(Json(view)) | ||
} | ||
} | ||
| @@ -109,12 +110,9 @@ pub async fn get_actor( | ||
let actor = param(&p, "actor")?; | ||
let shown = actor == me | ||
|| !host.groups_of(actor)?.is_empty() | ||
|| host | ||
.store | ||
.asking_anywhere(actor) | ||
.map_err(XrpcError::internal)?; | ||
|| host.store.asking_anywhere(actor).map_err(internal)?; | ||
if !shown { | ||
return Err(XrpcError::new( | ||
return Err(Error::new( | ||
StatusCode::BAD_REQUEST, | ||
"ActorNotFound", | ||
format!("no one here by {actor}"), | ||
| @@ -141,7 +139,7 @@ pub async fn get_actor_groups( | ||
true => Some(asked.clone()), | ||
false => host.identity.resolve_handle(&asked).await.ok(), | ||
}; | ||
let not_found = || XrpcError::new(StatusCode::BAD_REQUEST, "ActorNotFound", "no such actor"); | ||
let not_found = || Error::new(StatusCode::BAD_REQUEST, "ActorNotFound", "no such actor"); | ||
let actor = actor.ok_or_else(not_found)?; | ||
let limit = page(&p, 50, 100)? as usize; | ||
let after = p.get("cursor").map(String::as_str).unwrap_or_default(); | ||
crates/group-host/src/admin.rs+6−5
| @@ -8,7 +8,8 @@ use crate::group_api::signed_in; | ||
use crate::logs::Asked; | ||
use crate::rbac::INTERNAL; | ||
use crate::space_api::forbidden; | ||
use crate::xrpc::XrpcError; | ||
use crate::xrpc::internal; | ||
use atproto_server::Error; | ||
use axum::Json; | ||
use axum::extract::{Query, State}; | ||
use axum::http::HeaderMap; | ||
| @@ -17,7 +18,7 @@ use serde_json::{Value, json}; | ||
use std::sync::Arc; | ||
use std::time::{Duration, Instant}; | ||
| ||
type Answer = Result<Json<Value>, XrpcError>; | ||
type Answer = Result<Json<Value>, Error>; | ||
| ||
/// How often the lines logged and the counts are written. | ||
pub const FLUSH: Duration = Duration::from_secs(1); | ||
| @@ -26,7 +27,7 @@ pub const FLUSH: Duration = Duration::from_secs(1); | ||
const PRUNE: Duration = Duration::from_secs(60); | ||
| ||
/// The caller of `lxm`, who must be one of the host's operators. | ||
async fn operator(host: &Host, headers: &HeaderMap, lxm: &str) -> Result<String, XrpcError> { | ||
async fn operator(host: &Host, headers: &HeaderMap, lxm: &str) -> Result<String, Error> { | ||
let who = signed_in(host, headers, lxm).await?; | ||
if !host.config.host_admins.contains(&who) { | ||
return Err(forbidden("only this host's operators may read this")); | ||
| @@ -45,7 +46,7 @@ pub async fn get_logs( | ||
tracing::info!(did, asked = asked.said(), "logs read"); | ||
// What was logged up to now, this read's own line with it. | ||
let read = host.logs.flush().and_then(|()| host.logs.read(&asked)); | ||
let lines = read.map_err(XrpcError::internal)?; | ||
let lines = read.map_err(internal)?; | ||
let lines: Vec<Value> = lines | ||
.into_iter() | ||
.map(|line| json!({"line": line})) | ||
| @@ -70,7 +71,7 @@ pub async fn get_stats( | ||
let days = asked.days.unwrap_or(7); | ||
let now = crate::time::now_millis(); | ||
let report = counted.and_then(|()| host.stats.report(&host.store, days, now)); | ||
Ok(Json(report.map_err(XrpcError::internal)?)) | ||
Ok(Json(report.map_err(internal)?)) | ||
} | ||
| ||
/// Writes the lines logged and the counts every `every`, and lets go of | ||
crates/group-host/src/api.rs+34−40
| @@ -3,8 +3,9 @@ | ||
| ||
use crate::Host; | ||
use crate::store::Record; | ||
use crate::xrpc::XrpcError; | ||
use crate::xrpc::internal; | ||
use atproto::drisl; | ||
use atproto_server::Error; | ||
use axum::Json; | ||
use axum::extract::{Query, State}; | ||
use axum::http::{HeaderMap, StatusCode, header}; | ||
| @@ -25,16 +26,16 @@ pub(crate) fn too_much(max: usize) -> String { | ||
use std::sync::Arc; | ||
| ||
pub(crate) type Params = HashMap<String, String>; | ||
type Answer = Result<Json<Value>, XrpcError>; | ||
type Answer = Result<Json<Value>, Error>; | ||
| ||
pub(crate) fn invalid(message: impl Into<String>) -> XrpcError { | ||
XrpcError::new(StatusCode::BAD_REQUEST, "InvalidRequest", message) | ||
pub(crate) fn invalid(message: impl Into<String>) -> Error { | ||
Error::new(StatusCode::BAD_REQUEST, "InvalidRequest", message) | ||
} | ||
| ||
/// A cursor this host never gave, as a list whose lexicon names | ||
/// `InvalidCursor` refuses it. | ||
pub(crate) fn invalid_cursor() -> XrpcError { | ||
XrpcError::new( | ||
pub(crate) fn invalid_cursor() -> Error { | ||
Error::new( | ||
StatusCode::BAD_REQUEST, | ||
"InvalidCursor", | ||
"a cursor this host gave", | ||
| @@ -52,7 +53,7 @@ pub(crate) fn paged(mut body: Value, cursor: Option<String>) -> Value { | ||
} | ||
| ||
/// The parameter `name`, which the method needs. | ||
pub(crate) fn param<'a>(params: &'a Params, name: &str) -> Result<&'a str, XrpcError> { | ||
pub(crate) fn param<'a>(params: &'a Params, name: &str) -> Result<&'a str, Error> { | ||
params | ||
.get(name) | ||
.map(String::as_str) | ||
| @@ -60,12 +61,12 @@ pub(crate) fn param<'a>(params: &'a Params, name: &str) -> Result<&'a str, XrpcE | ||
} | ||
| ||
/// The page size `limit` asks for: 1 to 100, 50 unless it says. | ||
fn limit(params: &Params) -> Result<u32, XrpcError> { | ||
fn limit(params: &Params) -> Result<u32, Error> { | ||
page(params, 50, 100) | ||
} | ||
| ||
/// The page size `limit` asks for: 1 to `max`, `default` unless it says. | ||
pub(crate) fn page(params: &Params, default: u32, max: u32) -> Result<u32, XrpcError> { | ||
pub(crate) fn page(params: &Params, default: u32, max: u32) -> Result<u32, Error> { | ||
match params.get("limit") { | ||
None => Ok(default), | ||
Some(l) => l | ||
| @@ -76,8 +77,8 @@ pub(crate) fn page(params: &Params, default: u32, max: u32) -> Result<u32, XrpcE | ||
} | ||
} | ||
| ||
fn repo_not_found(repo: &str) -> XrpcError { | ||
XrpcError::new( | ||
fn repo_not_found(repo: &str) -> Error { | ||
Error::new( | ||
StatusCode::BAD_REQUEST, | ||
"RepoNotFound", | ||
format!("no repo {repo} here"), | ||
| @@ -86,8 +87,8 @@ fn repo_not_found(repo: &str) -> XrpcError { | ||
| ||
/// The DID of the account `repo` names, by DID or handle. | ||
/// Refused for an account switched off. | ||
fn did_of(host: &Host, repo: &str) -> Result<String, XrpcError> { | ||
let account = host.store.account(repo).map_err(XrpcError::internal)?; | ||
fn did_of(host: &Host, repo: &str) -> Result<String, Error> { | ||
let account = host.store.account(repo).map_err(internal)?; | ||
let did = account.map(|a| a.did).ok_or_else(|| repo_not_found(repo))?; | ||
host.active(&did)?; | ||
Ok(did) | ||
| @@ -137,17 +138,10 @@ pub async fn describe_server(State(host): State<Arc<Host>>) -> Json<Value> { | ||
| ||
pub async fn describe_repo(State(host): State<Arc<Host>>, Query(p): Query<Params>) -> Answer { | ||
let repo = param(&p, "repo")?; | ||
let account = host.store.account(repo).map_err(XrpcError::internal)?; | ||
let account = host.store.account(repo).map_err(internal)?; | ||
let account = account.ok_or_else(|| repo_not_found(repo))?; | ||
let doc = host | ||
.plc | ||
.document(&account.did) | ||
.await | ||
.map_err(XrpcError::internal)?; | ||
let collections = host | ||
.store | ||
.collections(&account.did) | ||
.map_err(XrpcError::internal)?; | ||
let doc = host.plc.document(&account.did).await.map_err(internal)?; | ||
let collections = host.store.collections(&account.did).map_err(internal)?; | ||
Ok(Json(json!({ | ||
"handle": account.handle, | ||
"did": account.did, | ||
| @@ -163,11 +157,11 @@ pub async fn get_record(State(host): State<Arc<Host>>, Query(p): Query<Params>) | ||
let found = host | ||
.store | ||
.record(&did, collection, rkey) | ||
.map_err(XrpcError::internal)?; | ||
.map_err(internal)?; | ||
// A `cid` asks for that version, which is only ever the one here. | ||
let found = found.filter(|r| p.get("cid").is_none_or(|c| *c == r.cid.to_string())); | ||
let not_found = || { | ||
XrpcError::new( | ||
Error::new( | ||
StatusCode::BAD_REQUEST, | ||
"RecordNotFound", | ||
format!("no record {collection}/{rkey}"), | ||
| @@ -184,7 +178,7 @@ pub async fn list_records(State(host): State<Arc<Host>>, Query(p): Query<Params> | ||
let records = host | ||
.store | ||
.list(&did, collection, cursor, limit, reverse) | ||
.map_err(XrpcError::internal)?; | ||
.map_err(internal)?; | ||
// A full page may have more after it. | ||
let cursor = records | ||
.last() | ||
| @@ -197,9 +191,9 @@ pub async fn list_records(State(host): State<Arc<Host>>, Query(p): Query<Params> | ||
pub async fn get_repo( | ||
State(host): State<Arc<Host>>, | ||
Query(p): Query<Params>, | ||
) -> Result<Response, XrpcError> { | ||
) -> Result<Response, Error> { | ||
let did = &did_of(&host, param(&p, "did")?)?; | ||
let car = host.export(did).map_err(XrpcError::internal)?; | ||
let car = host.export(did).map_err(internal)?; | ||
Ok(([(header::CONTENT_TYPE, "application/vnd.ipld.car")], car).into_response()) | ||
} | ||
| ||
| @@ -208,17 +202,17 @@ pub async fn get_repo( | ||
pub async fn get_sync_record( | ||
State(host): State<Arc<Host>>, | ||
Query(p): Query<Params>, | ||
) -> Result<Response, XrpcError> { | ||
) -> Result<Response, Error> { | ||
let did = &did_of(&host, param(&p, "did")?)?; | ||
let (collection, rkey) = (param(&p, "collection")?, param(&p, "rkey")?); | ||
let car = host.record_proof(did, collection, rkey); | ||
let car = car.map_err(XrpcError::internal)?; | ||
let car = car.map_err(internal)?; | ||
Ok(([(header::CONTENT_TYPE, "application/vnd.ipld.car")], car).into_response()) | ||
} | ||
| ||
pub async fn get_latest_commit(State(host): State<Arc<Host>>, Query(p): Query<Params>) -> Answer { | ||
let did = &did_of(&host, param(&p, "did")?)?; | ||
let head = host.store.head(did).map_err(XrpcError::internal)?; | ||
let head = host.store.head(did).map_err(internal)?; | ||
let head = head.expect("an account has a repo"); | ||
Ok(Json(json!({"cid": head.cid.to_string(), "rev": head.rev}))) | ||
} | ||
| @@ -226,7 +220,7 @@ pub async fn get_latest_commit(State(host): State<Arc<Host>>, Query(p): Query<Pa | ||
/// The page size of the sync methods that list a host's repos or a repo's | ||
/// blobs, as atproto's lexicons have it: 1 to 1000, 500 unless asked; a | ||
/// relay crawling the host asks for 1000. | ||
fn sync_limit(params: &Params) -> Result<u32, XrpcError> { | ||
fn sync_limit(params: &Params) -> Result<u32, Error> { | ||
page(params, 500, 1000) | ||
} | ||
| ||
| @@ -235,7 +229,7 @@ pub async fn list_repos(State(host): State<Arc<Host>>, Query(p): Query<Params>) | ||
let repos = host | ||
.store | ||
.accounts(p.get("cursor").map(String::as_str), limit) | ||
.map_err(XrpcError::internal)?; | ||
.map_err(internal)?; | ||
let cursor = repos | ||
.last() | ||
.filter(|_| repos.len() == limit as usize) | ||
| @@ -263,7 +257,7 @@ pub async fn resolve_handle( | ||
headers: HeaderMap, | ||
) -> Answer { | ||
let handle = param(&p, "handle")?.to_ascii_lowercase(); | ||
let account = host.store.account(&handle).map_err(XrpcError::internal)?; | ||
let account = host.store.account(&handle).map_err(internal)?; | ||
let mut did = account.filter(|a| a.handle == handle).map(|a| a.did); | ||
// Anyone else's, as a PDS resolves them, for someone signed in: the | ||
// host asks the handle's own server, which no stranger sends it to. | ||
| @@ -276,7 +270,7 @@ pub async fn resolve_handle( | ||
did = host.identity.resolve_handle(&handle).await.ok(); | ||
} | ||
let not_found = || { | ||
XrpcError::new( | ||
Error::new( | ||
StatusCode::BAD_REQUEST, | ||
"HandleNotFound", | ||
format!("no account {handle} we can find"), | ||
| @@ -291,17 +285,17 @@ pub async fn resolve_handle( | ||
pub async fn get_blob( | ||
State(host): State<Arc<Host>>, | ||
Query(p): Query<Params>, | ||
) -> Result<Response, XrpcError> { | ||
) -> Result<Response, Error> { | ||
let did = did_of(&host, param(&p, "did")?)?; | ||
let cid = param(&p, "cid")?; | ||
let cid = atproto::Cid::parse(cid).map_err(|e| invalid(format!("cid: {e}")))?; | ||
let public = host.store.held_publicly(&did, &cid); | ||
let found = match public.map_err(XrpcError::internal)? { | ||
true => host.read_blob(&did, &cid).map_err(XrpcError::internal)?, | ||
let found = match public.map_err(internal)? { | ||
true => host.read_blob(&did, &cid).map_err(internal)?, | ||
false => None, | ||
}; | ||
let not_found = || { | ||
XrpcError::new( | ||
Error::new( | ||
StatusCode::BAD_REQUEST, | ||
"BlobNotFound", | ||
format!("no blob {cid} here"), | ||
| @@ -329,7 +323,7 @@ pub async fn list_blobs(State(host): State<Arc<Host>>, Query(p): Query<Params>) | ||
let cids = host | ||
.store | ||
.list_blobs(&did, since, cursor, limit) | ||
.map_err(XrpcError::internal)?; | ||
.map_err(internal)?; | ||
let cursor = cids | ||
.last() | ||
.filter(|_| cids.len() == limit as usize) | ||
crates/group-host/src/app_passwords.rs+40−63
| @@ -23,8 +23,9 @@ use crate::oauth_store::{AppPassword, Grant, Tokens, app_password_client}; | ||
use crate::rbac::{INTERNAL, repo_collections_for}; | ||
use crate::scopes::Permissions; | ||
use crate::time::{iso, now_millis}; | ||
use crate::xrpc::XrpcError; | ||
use crate::xrpc::internal; | ||
use atproto::jose; | ||
use atproto_server::Error; | ||
use axum::extract::{Query, State}; | ||
use axum::http::{HeaderMap, StatusCode, header}; | ||
use axum::{Extension, Json}; | ||
| @@ -40,14 +41,14 @@ const SESSION_TTL: i64 = 90 * 86_400_000; | ||
/// What a session is, as `listGroupTokens` names it. | ||
pub const SOURCE: &str = "appPassword"; | ||
| ||
type Answer = Result<Json<Value>, XrpcError>; | ||
type Answer = Result<Json<Value>, Error>; | ||
| ||
fn forbidden(message: impl Into<String>) -> XrpcError { | ||
XrpcError::new(StatusCode::FORBIDDEN, "Forbidden", message) | ||
fn forbidden(message: impl Into<String>) -> Error { | ||
Error::new(StatusCode::FORBIDDEN, "Forbidden", message) | ||
} | ||
| ||
fn refused(error: &'static str, message: &str) -> XrpcError { | ||
XrpcError::new(StatusCode::UNAUTHORIZED, error, message) | ||
fn refused(error: &'static str, message: &str) -> Error { | ||
Error::new(StatusCode::UNAUTHORIZED, error, message) | ||
} | ||
| ||
/// `xxxx-xxxx-xxxx-xxxx` from a-z and 2-7, as a PDS hands one out: 80 | ||
| @@ -80,22 +81,22 @@ fn scope_of(p: &AppPassword) -> &'static str { | ||
impl Host { | ||
/// Whether `member` may make app passwords for `group`: they may do | ||
/// anything as it, every repo collection. | ||
pub fn may_issue(&self, group: &str, member: &str) -> Result<bool, XrpcError> { | ||
let roles = self.roles(group, member).map_err(XrpcError::internal)?; | ||
let granted = self.role_grants(group).map_err(XrpcError::internal)?; | ||
pub fn may_issue(&self, group: &str, member: &str) -> Result<bool, Error> { | ||
let roles = self.roles(group, member).map_err(internal)?; | ||
let granted = self.role_grants(group).map_err(internal)?; | ||
Ok(repo_collections_for(&granted, &roles).contains("*")) | ||
} | ||
| ||
/// Whether a session's app password still stands: there, and its | ||
/// maker still able to make it. One whose maker could not now is | ||
/// forgotten, with every session signed in with one of theirs. | ||
fn stands(&self, grant: &Grant) -> Result<bool, XrpcError> { | ||
fn stands(&self, grant: &Grant) -> Result<bool, Error> { | ||
let name = grant | ||
.client_id | ||
.strip_prefix("app-password:") | ||
.unwrap_or_default(); | ||
let found = self.store.app_password(&grant.group, Some(name), None); | ||
let found = found.map_err(XrpcError::internal)?; | ||
let found = found.map_err(internal)?; | ||
if found.is_some_and(|p| p.member == grant.member) | ||
&& self.may_issue(&grant.group, &grant.member)? | ||
{ | ||
| @@ -107,20 +108,20 @@ impl Host { | ||
| ||
/// Forgets `member`'s app passwords for `group`, and every session | ||
/// signed in with one of them. | ||
fn forget_app_passwords(&self, group: &str, member: &str) -> Result<(), XrpcError> { | ||
fn forget_app_passwords(&self, group: &str, member: &str) -> Result<(), Error> { | ||
let dropped = self.store.drop_members_app_passwords(group, member); | ||
dropped.map_err(XrpcError::internal)?; | ||
dropped.map_err(internal)?; | ||
let ended = self.store.revoke_member_sessions(group, member); | ||
ended.map_err(XrpcError::internal)?; | ||
ended.map_err(internal)?; | ||
Ok(()) | ||
} | ||
| ||
/// The group's app passwords whose makers could still make them; the | ||
/// rest are forgotten, so none comes back with its maker's roles. | ||
fn app_passwords(&self, group: &str) -> Result<Vec<AppPassword>, XrpcError> { | ||
fn app_passwords(&self, group: &str) -> Result<Vec<AppPassword>, Error> { | ||
let held = self.store.app_passwords(group); | ||
let mut kept = Vec::new(); | ||
for p in held.map_err(XrpcError::internal)? { | ||
for p in held.map_err(internal)? { | ||
match self.may_issue(group, &p.member)? { | ||
true => kept.push(p), | ||
false => self.forget_app_passwords(group, &p.member)?, | ||
| @@ -185,34 +186,28 @@ impl Host { | ||
/// password last. | ||
pub(crate) fn session(&self, token: &str, now: i64) -> Result<Acting, Refusal> { | ||
let found = self.store.grant_by_access(&jose::sha256(token), now); | ||
let grant = found | ||
.map_err(XrpcError::internal)? | ||
.filter(|g| g.source == SOURCE); | ||
let grant = found.map_err(internal)?.filter(|g| g.source == SOURCE); | ||
let Some(grant) = grant else { | ||
// One that lapsed is a 400 saying so, as a PDS answers: what an | ||
// app takes as its sign to refresh. | ||
let any = self.store.grant_by_access(&jose::sha256(token), i64::MIN); | ||
let lapsed = any | ||
.map_err(XrpcError::internal)? | ||
.is_some_and(|g| g.source == SOURCE); | ||
let lapsed = any.map_err(internal)?.is_some_and(|g| g.source == SOURCE); | ||
if lapsed { | ||
let said = "the token has expired"; | ||
return Err(XrpcError::new(StatusCode::BAD_REQUEST, "ExpiredToken", said).into()); | ||
return Err(Error::new(StatusCode::BAD_REQUEST, "ExpiredToken", said).into()); | ||
} | ||
return Err(refused("InvalidToken", "the token is invalid").into()); | ||
}; | ||
if !self.stands(&grant)? { | ||
return Err(refused("InvalidToken", "the token is invalid").into()); | ||
} | ||
self.store | ||
.touch(&grant.id, now) | ||
.map_err(XrpcError::internal)?; | ||
self.store.touch(&grant.id, now).map_err(internal)?; | ||
let permissions = Permissions::new(&grant.scope, &grant.group); | ||
Ok(Acting { grant, permissions }) | ||
} | ||
| ||
/// The session a request's bearer refresh token names, while it lasts. | ||
fn refreshing(&self, headers: &HeaderMap) -> Result<(Grant, String), XrpcError> { | ||
fn refreshing(&self, headers: &HeaderMap) -> Result<(Grant, String), Error> { | ||
let authorization = headers | ||
.get(header::AUTHORIZATION) | ||
.and_then(|v| v.to_str().ok()); | ||
| @@ -220,9 +215,7 @@ impl Host { | ||
let token = token.ok_or_else(|| refused("AuthMissing", "a refresh token is required"))?; | ||
let hash = jose::sha256(token); | ||
let found = self.store.grant_to_refresh(&hash, now_millis()); | ||
let grant = found | ||
.map_err(XrpcError::internal)? | ||
.filter(|g| g.source == SOURCE); | ||
let grant = found.map_err(internal)?.filter(|g| g.source == SOURCE); | ||
let grant = grant.ok_or_else(|| refused("InvalidToken", "the token is invalid"))?; | ||
Ok((grant, hash)) | ||
} | ||
| @@ -245,10 +238,7 @@ pub async fn create_session( | ||
let identifier = identifier.trim().trim_start_matches('@').to_lowercase(); | ||
let from = client.map_or_else(String::new, |Extension(Client(ip))| key(ip)); | ||
host.spend(&SESSIONS, &format!("{identifier} {from}"), 1)?; | ||
let account = host | ||
.store | ||
.account(&identifier) | ||
.map_err(XrpcError::internal)?; | ||
let account = host.store.account(&identifier).map_err(internal)?; | ||
let group = account | ||
.map(|a| a.did) | ||
.filter(|d| group_of(&host, d).is_ok()) | ||
| @@ -256,7 +246,7 @@ pub async fn create_session( | ||
let found = host | ||
.store | ||
.app_password(&group, None, Some(&hash_of(password))); | ||
let p = found.map_err(XrpcError::internal)?.ok_or_else(no)?; | ||
let p = found.map_err(internal)?.ok_or_else(no)?; | ||
if !host.may_issue(&group, &p.member)? { | ||
host.forget_app_passwords(&group, &p.member)?; | ||
return Err(no()); | ||
| @@ -283,12 +273,10 @@ pub async fn create_session( | ||
refresh_hash: &jose::sha256(&refresh), | ||
expires_at: grant.expires_at, | ||
}; | ||
host.store | ||
.issue(&grant, &tokens) | ||
.map_err(XrpcError::internal)?; | ||
host.store.issue(&grant, &tokens).map_err(internal)?; | ||
let signed_in = format!("signed in with the app password \"{}\"", p.name); | ||
host.record(&group, &p.member, Some(&grant.client_id), &signed_in) | ||
.map_err(XrpcError::internal)?; | ||
.map_err(internal)?; | ||
host.session_view(&group, &access, &refresh).await | ||
} | ||
| ||
| @@ -307,10 +295,7 @@ pub async fn refresh_session(State(host): State<Arc<Host>>, headers: HeaderMap) | ||
refresh_hash: &jose::sha256(&refresh), | ||
expires_at: now + SESSION_TTL, | ||
}; | ||
let rotated = host | ||
.store | ||
.rotate(&old, &tokens, now) | ||
.map_err(XrpcError::internal)?; | ||
let rotated = host.store.rotate(&old, &tokens, now).map_err(internal)?; | ||
// Refreshed at once by another request, which took it. | ||
let fresh = rotated | ||
.then_some(()) | ||
| @@ -322,11 +307,9 @@ pub async fn refresh_session(State(host): State<Arc<Host>>, headers: HeaderMap) | ||
/// Signs a session out. | ||
pub async fn delete_session(State(host): State<Arc<Host>>, headers: HeaderMap) -> Answer { | ||
let (grant, _) = host.refreshing(&headers)?; | ||
host.store | ||
.end_grant(&grant.id) | ||
.map_err(XrpcError::internal)?; | ||
host.store.end_grant(&grant.id).map_err(internal)?; | ||
let bought = host.end_grant_reads(&grant.group).await; | ||
bought.map_err(XrpcError::internal)?; | ||
bought.map_err(internal)?; | ||
Ok(Json(json!({}))) | ||
} | ||
| ||
| @@ -347,7 +330,7 @@ pub async fn create_app_password( | ||
} | ||
let name = body["name"].as_str().unwrap_or_default().trim(); | ||
if name.is_empty() || name.chars().count() > 64 { | ||
return Err(XrpcError::new( | ||
return Err(Error::new( | ||
StatusCode::BAD_REQUEST, | ||
"InvalidName", | ||
"a name of 1 to 64 characters", | ||
| @@ -356,7 +339,7 @@ pub async fn create_app_password( | ||
let held = host.app_passwords(group)?; | ||
if held.len() >= APP_PASSWORDS_AT_MOST { | ||
let said = format!("a group holds {APP_PASSWORDS_AT_MOST} app passwords at most"); | ||
return Err(XrpcError::new( | ||
return Err(Error::new( | ||
StatusCode::BAD_REQUEST, | ||
"TooManyAppPasswords", | ||
said, | ||
| @@ -372,17 +355,12 @@ pub async fn create_app_password( | ||
let kept = host | ||
.store | ||
.make_app_password(group, &made, &hash_of(&password)); | ||
if !kept.map_err(XrpcError::internal)? { | ||
if !kept.map_err(internal)? { | ||
let said = "the group has an app password by that name"; | ||
return Err(XrpcError::new( | ||
StatusCode::BAD_REQUEST, | ||
"DuplicateName", | ||
said, | ||
)); | ||
return Err(Error::new(StatusCode::BAD_REQUEST, "DuplicateName", said)); | ||
} | ||
let action = format!("made the app password \"{name}\""); | ||
host.record(group, &me, None, &action) | ||
.map_err(XrpcError::internal)?; | ||
host.record(group, &me, None, &action).map_err(internal)?; | ||
Ok(Json(json!({ | ||
"name": made.name, | ||
"password": password, | ||
| @@ -408,7 +386,7 @@ pub async fn list_app_passwords( | ||
let sessions = host | ||
.store | ||
.grants_of(group, now_millis()) | ||
.map_err(XrpcError::internal)?; | ||
.map_err(internal)?; | ||
let held = host.app_passwords(group)?; | ||
let held: Vec<_> = held | ||
.into_iter() | ||
| @@ -457,9 +435,9 @@ pub async fn revoke_app_password( | ||
let found = host | ||
.store | ||
.app_password(group, Some(name), None) | ||
.map_err(XrpcError::internal)?; | ||
.map_err(internal)?; | ||
let p = found.ok_or_else(|| { | ||
XrpcError::new( | ||
Error::new( | ||
StatusCode::BAD_REQUEST, | ||
"NotFound", | ||
"no app password by that name", | ||
| @@ -470,9 +448,8 @@ pub async fn revoke_app_password( | ||
} | ||
host.store | ||
.drop_app_password(group, name) | ||
.map_err(XrpcError::internal)?; | ||
.map_err(internal)?; | ||
let action = format!("revoked the app password \"{name}\""); | ||
host.record(group, &me, None, &action) | ||
.map_err(XrpcError::internal)?; | ||
host.record(group, &me, None, &action).map_err(internal)?; | ||
Ok(Json(json!({}))) | ||
} | ||
crates/group-host/src/authority.rs+30−32
| @@ -25,15 +25,16 @@ use crate::space::NOTIFY_REPO_UPDATE; | ||
use crate::space_api::NOTIFY_REVOKED; | ||
use crate::store::{Notice, Registration, Space, Store, SyncerNotice, SyncerUpdate}; | ||
use crate::time::now_millis; | ||
use crate::xrpc::XrpcError; | ||
use crate::xrpc::internal; | ||
use anyhow::{Context, Result}; | ||
use atproto::service_auth::{self, Claims}; | ||
use atproto::service_auth::{self, Claims, LIFETIME}; | ||
use atproto::space::SpaceRef; | ||
use atproto::space_auth::{self, space_host_aud}; | ||
use atproto::{Value, jose, syntax}; | ||
use atproto_client::guard::Guarded; | ||
use atproto_client::identity; | ||
use atproto_client::sender::SendError; | ||
use atproto_server::Error; | ||
use axum::http::StatusCode; | ||
use futures::future::{OptionFuture, join_all}; | ||
use futures::{StreamExt, stream}; | ||
| @@ -315,19 +316,6 @@ impl Syncers { | ||
} | ||
| ||
impl Host { | ||
/// Service auth from `iss` to `aud` for `lxm`, for a minute. | ||
pub(crate) fn claims(&self, iss: &str, aud: &str, lxm: &str) -> Claims { | ||
let now = now() as u64; | ||
Claims { | ||
iss: iss.into(), | ||
aud: aud.into(), | ||
exp: now + 60, | ||
iat: Some(now), | ||
lxm: Some(lxm.into()), | ||
jti: Some(self.clock.next()), | ||
} | ||
} | ||
| ||
/// Makes a space of `authority`'s, a group here, of `kind` at `skey`, | ||
/// under `policy`. Its URI. | ||
pub fn create_space( | ||
| @@ -336,19 +324,19 @@ impl Host { | ||
kind: &str, | ||
skey: &str, | ||
policy: &Json, | ||
) -> Result<String, XrpcError> { | ||
) -> Result<String, Error> { | ||
let uri = crate::group::space_uri(authority, kind, skey); | ||
SpaceRef::parse(&uri).map_err(|e| invalid(e.to_string()))?; | ||
let account = self.store.account(authority).map_err(XrpcError::internal)?; | ||
let account = self.store.account(authority).map_err(internal)?; | ||
if !account.is_some_and(|a| a.did == authority) { | ||
return Err(invalid(format!("{authority} is no group here"))); | ||
} | ||
let made = self | ||
.store | ||
.create_space(&uri, authority, policy, now()) | ||
.map_err(XrpcError::internal)?; | ||
.map_err(internal)?; | ||
if !made { | ||
return Err(XrpcError::new( | ||
return Err(Error::new( | ||
StatusCode::BAD_REQUEST, | ||
"SpaceAlreadyExists", | ||
format!("{uri} exists"), | ||
| @@ -367,28 +355,26 @@ impl Host { | ||
} | ||
| ||
/// The space at `uri`, if its authority is a group here. | ||
pub fn hosted_space(&self, uri: &str) -> Result<Space, XrpcError> { | ||
let space = self.store.space(uri).map_err(XrpcError::internal)?; | ||
space.ok_or_else(|| { | ||
XrpcError::new(StatusCode::BAD_REQUEST, "SpaceNotFound", "space not found") | ||
}) | ||
pub fn hosted_space(&self, uri: &str) -> Result<Space, Error> { | ||
let space = self.store.space(uri).map_err(internal)?; | ||
space.ok_or_else(|| Error::new(StatusCode::BAD_REQUEST, "SpaceNotFound", "space not found")) | ||
} | ||
| ||
/// Lets `did` read `space`, write it, or both: what it was let do | ||
/// before is replaced. | ||
pub fn grant(&self, space: &str, did: &str, read: bool, write: bool) -> Result<(), XrpcError> { | ||
pub fn grant(&self, space: &str, did: &str, read: bool, write: bool) -> Result<(), Error> { | ||
self.hosted_space(space)?; | ||
if !syntax::is_did(did) { | ||
return Err(invalid(format!("{did} is no DID"))); | ||
} | ||
let granted = self.store.grant(space, did, read, write); | ||
granted.map_err(XrpcError::internal) | ||
granted.map_err(internal) | ||
} | ||
| ||
/// Takes back whatever `did` was let do in `space`. | ||
pub fn ungrant(&self, space: &str, did: &str) -> Result<(), XrpcError> { | ||
pub fn ungrant(&self, space: &str, did: &str) -> Result<(), Error> { | ||
self.hosted_space(space)?; | ||
self.store.ungrant(space, did).map_err(XrpcError::internal) | ||
self.store.ungrant(space, did).map_err(internal) | ||
} | ||
| ||
/// Whether `user` may do `access` in `space` (at `uri`): with no user, | ||
| @@ -506,7 +492,7 @@ impl Host { | ||
&self, | ||
space: &str, | ||
to: &Registration, | ||
) -> Result<(), XrpcError> { | ||
) -> Result<(), Error> { | ||
let challenge = jose::random(16); | ||
let url = format!( | ||
"{}/xrpc/{CONFIRM_REGISTRATION}", | ||
| @@ -526,7 +512,7 @@ impl Host { | ||
return Ok(()); | ||
} | ||
tracing::warn!(space, endpoint = to.endpoint, "registration not confirmed"); | ||
Err(XrpcError::new( | ||
Err(Error::new( | ||
StatusCode::BAD_REQUEST, | ||
"RegistrationNotConfirmed", | ||
"the notify endpoint did not confirm the registration", | ||
| @@ -661,7 +647,13 @@ impl Host { | ||
jtis: &[String], | ||
) -> Result<()> { | ||
let doc = self.identity.document_now(writer).await?; | ||
let claims = self.claims(authority, writer, NOTIFY_REVOKED); | ||
let claims = Claims::new( | ||
authority, | ||
writer, | ||
Some(NOTIFY_REVOKED), | ||
now() as u64, | ||
LIFETIME, | ||
); | ||
let pds = identity::pds(writer, &doc, self.guarded.guard())?; | ||
let asked = self.guarded.post(&format!("{pds}/xrpc/{NOTIFY_REVOKED}"))?; | ||
let res = asked | ||
| @@ -718,7 +710,13 @@ impl Host { | ||
let aud = space_host_aud(&space.authority); | ||
let token = service_auth::sign( | ||
&account.signing, | ||
&self.claims(&account.did, &aud, NOTIFY_REPO_UPDATE), | ||
&Claims::new( | ||
&account.did, | ||
&aud, | ||
Some(NOTIFY_REPO_UPDATE), | ||
now() as u64, | ||
LIFETIME, | ||
), | ||
); | ||
let body = json!({ | ||
"space": notice.space, | ||
crates/group-host/src/authority_api.rs+32−38
| @@ -9,11 +9,12 @@ use crate::authority::{Access, repo_removed, repo_write}; | ||
use crate::space::NOTIFY_REPO_UPDATE; | ||
use crate::space_api::{credential, forbidden, now, refused, service_caller}; | ||
use crate::store::{Registration, Space}; | ||
use crate::xrpc::XrpcError; | ||
use crate::xrpc::internal; | ||
use atproto::space::SpaceRef; | ||
use atproto::space_auth::{self, Kind, Make, space_host_aud}; | ||
use atproto::{PublicKey, Value as Drisl, syntax, tid}; | ||
use atproto_client::service_auth; | ||
use atproto_server::Error; | ||
use axum::Json; | ||
use axum::extract::{Query, State}; | ||
use axum::http::{HeaderMap, StatusCode}; | ||
| @@ -26,22 +27,22 @@ const FUTURE_REV: u64 = 5 * 60; | ||
/// The longest token a syncer registers with, in bytes. | ||
const TOKEN_AT_MOST: usize = 512; | ||
| ||
type Answer = Result<Json<Value>, XrpcError>; | ||
type Answer = Result<Json<Value>, Error>; | ||
| ||
fn bad(error: &'static str, message: impl Into<String>) -> XrpcError { | ||
XrpcError::new(StatusCode::BAD_REQUEST, error, message) | ||
fn bad(error: &'static str, message: impl Into<String>) -> Error { | ||
Error::new(StatusCode::BAD_REQUEST, error, message) | ||
} | ||
| ||
fn not_found() -> XrpcError { | ||
fn not_found() -> Error { | ||
bad("SpaceNotFound", "space not found") | ||
} | ||
| ||
/// The space `uri` names, written as a space is. | ||
fn space_ref(uri: &str) -> Result<SpaceRef, XrpcError> { | ||
fn space_ref(uri: &str) -> Result<SpaceRef, Error> { | ||
SpaceRef::parse(uri).map_err(|e| invalid(e.to_string())) | ||
} | ||
| ||
fn text<'a>(body: &'a Value, name: &str) -> Result<&'a str, XrpcError> { | ||
fn text<'a>(body: &'a Value, name: &str) -> Result<&'a str, Error> { | ||
body[name] | ||
.as_str() | ||
.ok_or_else(|| invalid(format!("{name} is required"))) | ||
| @@ -50,7 +51,7 @@ fn text<'a>(body: &'a Value, name: &str) -> Result<&'a str, XrpcError> { | ||
/// The endpoint and token a body's `notify` registers, if it has one: an | ||
/// https URL (or http, while this host is on http itself, as a network of | ||
/// test servers is), and a token of at most 512 bytes. | ||
fn notify_of(host: &Host, body: &Value) -> Result<Option<Registration>, XrpcError> { | ||
fn notify_of(host: &Host, body: &Value) -> Result<Option<Registration>, Error> { | ||
let notify = &body["notify"]; | ||
if notify.is_null() { | ||
return Ok(None); | ||
| @@ -88,22 +89,19 @@ pub async fn authorize_space_sync( | ||
return Err(invalid("credentialKey is a P-256 did:key")); | ||
} | ||
let notify = notify_of(&host, &body)?; | ||
let authority = host | ||
.store | ||
.account(&space.authority) | ||
.map_err(XrpcError::internal)?; | ||
let authority = host.store.account(&space.authority).map_err(internal)?; | ||
let authority = authority | ||
.filter(|a| a.did == space.authority) | ||
.ok_or_else(not_found)?; | ||
let off = host.store.deactivation(&authority.did); | ||
if off.map_err(XrpcError::internal)?.is_some() { | ||
if off.map_err(internal)?.is_some() { | ||
return Err(bad( | ||
"RepoDeactivated", | ||
"the space's authority is switched off", | ||
)); | ||
} | ||
// Whoever asks: a syncer that missed the deletion learns of it here. | ||
let deleted = host.store.space_deleted(uri).map_err(XrpcError::internal)?; | ||
let deleted = host.store.space_deleted(uri).map_err(internal)?; | ||
if deleted { | ||
return Err(bad("SpaceDeleted", "the space was deleted")); | ||
} | ||
| @@ -114,7 +112,7 @@ pub async fn authorize_space_sync( | ||
// `clientAttestation` is taken and neither checked nor used: no space | ||
// here admits by the app asking. | ||
let user = delegation.as_ref().map(|d| d.iss.as_str()); | ||
let hosted = host.store.space(uri).map_err(XrpcError::internal)?; | ||
let hosted = host.store.space(uri).map_err(internal)?; | ||
let hosted = hosted.ok_or_else(not_found)?; | ||
// A delegation a group's grant was given here buys only while the | ||
// grant lasts and its member reads the space. | ||
| @@ -122,25 +120,25 @@ pub async fn authorize_space_sync( | ||
Some(d) => host.store.delegation_grant(&d.jti), | ||
None => Ok(None), | ||
}; | ||
let grant = grant.map_err(XrpcError::internal)?; | ||
let grant = grant.map_err(internal)?; | ||
let may = host.may(uri, &hosted, user, Access::Read); | ||
let mut may = may.map_err(XrpcError::internal)?; | ||
let mut may = may.map_err(internal)?; | ||
if let Some(id) = grant.as_deref().filter(|_| may) { | ||
let reads = host.grant_reads(id, uri, &hosted); | ||
may = reads.map_err(XrpcError::internal)?; | ||
may = reads.map_err(internal)?; | ||
} | ||
if !may { | ||
// A syncer that lost the space is told of it no more. | ||
if let Some(to) = ¬ify { | ||
let gone = host.store.unregister(uri, to); | ||
gone.map_err(XrpcError::internal)?; | ||
gone.map_err(internal)?; | ||
} | ||
return Err(not_found()); | ||
} | ||
// Spent once it buys a credential: one token, one credential. | ||
if let Some(d) = &delegation { | ||
let spent = host.store.spend(&d.iss, &d.jti, d.exp as i64, now() as i64); | ||
if !spent.map_err(XrpcError::internal)? { | ||
if !spent.map_err(internal)? { | ||
return Err(bad( | ||
"InvalidDelegationToken", | ||
"the delegation token was used already", | ||
| @@ -150,7 +148,7 @@ pub async fn authorize_space_sync( | ||
// An endpoint registered already, lapsed or not, confirmed it then. | ||
if let Some(to) = ¬ify { | ||
let registered = host.store.registration(uri, to); | ||
if registered.map_err(XrpcError::internal)?.is_none() { | ||
if registered.map_err(internal)?.is_none() { | ||
host.confirm_registration(uri, to).await?; | ||
} | ||
} | ||
| @@ -160,29 +158,29 @@ pub async fn authorize_space_sync( | ||
key_id: Some(key), | ||
..Make::default() | ||
}; | ||
let credential = space_auth::create(Kind::Credential, &make, &authority.signing, now()) | ||
.map_err(XrpcError::internal)?; | ||
let credential = | ||
space_auth::create(Kind::Credential, &make, &authority.signing, now()).map_err(internal)?; | ||
let (_, issued) = space_auth::parse(Kind::Credential, &credential).map_err(refused)?; | ||
// Kept, so a member who loses the space has theirs revoked. | ||
if let Some(user) = user { | ||
host.store | ||
.issued(uri, user, &issued.jti, issued.exp as i64, now() as i64) | ||
.map_err(XrpcError::internal)?; | ||
.map_err(internal)?; | ||
} | ||
if let Some(id) = &grant { | ||
let kept = host.store.bought(uri, &issued.jti, id); | ||
kept.map_err(XrpcError::internal)?; | ||
kept.map_err(internal)?; | ||
} | ||
// Renewed with each credential, so a syncer that keeps authorizing | ||
// stays registered. | ||
if let Some(to) = ¬ify { | ||
let kept = host.store.register(uri, to, issued.exp as i64); | ||
kept.map_err(XrpcError::internal)?; | ||
kept.map_err(internal)?; | ||
let bound = host.store.bind_registration(uri, to, grant.as_deref()); | ||
bound.map_err(XrpcError::internal)?; | ||
bound.map_err(internal)?; | ||
} | ||
// Read once registered, so that any change after it is told. | ||
let space_rev = host.store.space_rev(uri).map_err(XrpcError::internal)?; | ||
let space_rev = host.store.space_rev(uri).map_err(internal)?; | ||
let mut answer = json!({ "credential": credential }); | ||
if let Some(rev) = space_rev { | ||
answer["spaceRev"] = json!(rev); | ||
| @@ -192,11 +190,7 @@ pub async fn authorize_space_sync( | ||
| ||
/// What a delegation token says, once it is signed by the user it names, | ||
/// for this space's authority and this space. | ||
async fn delegated( | ||
host: &Host, | ||
token: &str, | ||
space: &SpaceRef, | ||
) -> Result<space_auth::Token, XrpcError> { | ||
async fn delegated(host: &Host, token: &str, space: &SpaceRef) -> Result<space_auth::Token, Error> { | ||
let refused = |m: String| bad("InvalidDelegationToken", m); | ||
let checked = service_auth::verify_delegation(&host.identity, token, now()).await; | ||
let checked = checked.map_err(|e| refused(e.to_string()))?; | ||
| @@ -236,24 +230,24 @@ pub async fn notify_repo_update( | ||
if caller.account() != repo { | ||
return Err(forbidden("notifyRepoUpdate's issuer is not the repo")); | ||
} | ||
let hosted = host.store.space(uri).map_err(XrpcError::internal)?; | ||
let hosted = host.store.space(uri).map_err(internal)?; | ||
let hosted = hosted.ok_or_else(not_found)?; | ||
let ahead = tid::micros(rev).unwrap_or_default() / 1_000_000; | ||
if ahead > now() + FUTURE_REV { | ||
return Err(bad("FutureRev", "repoRev is in the future")); | ||
} | ||
let may = host.may(uri, &hosted, Some(repo), Access::Write); | ||
if !may.map_err(XrpcError::internal)? { | ||
if !may.map_err(internal)? { | ||
return Err(forbidden("the repo may not write in this space")); | ||
} | ||
let kept = host.record_writer(uri, repo, rev, &data); | ||
kept.map_err(XrpcError::internal)?; | ||
kept.map_err(internal)?; | ||
Ok(Json(json!({}))) | ||
} | ||
| ||
/// The space a credential to it names, if its authority is here: the | ||
/// credential for the authority, not a repo. | ||
async fn as_authority(host: &Host, headers: &HeaderMap, uri: &str) -> Result<Space, XrpcError> { | ||
async fn as_authority(host: &Host, headers: &HeaderMap, uri: &str) -> Result<Space, Error> { | ||
let space = space_ref(uri)?; | ||
credential(host, headers, uri, &space.authority).await?; | ||
host.hosted_space(uri) | ||
| @@ -274,7 +268,7 @@ pub async fn list_writers( | ||
let changes = host | ||
.store | ||
.writer_log(uri, cursor, limit) | ||
.map_err(XrpcError::internal)?; | ||
.map_err(internal)?; | ||
let repos: Vec<Value> = changes | ||
.iter() | ||
.map(|c| { | ||