chadtmiller.com/group-host
atmosphere group host
0
0
Refusals are answered as the caller's, and failures as the host's
crates/group-host/src/assistants.rs+4−1
| @@ -751,7 +751,10 @@ pub async fn mcp( | ||
let Some(who) = found.map_err(XrpcError::internal)? else { | ||
return Ok(challenge(&host, Some("invalid_token"))); | ||
}; | ||
let message: Value = serde_json::from_slice(&body).unwrap_or_default(); | ||
let Ok(message) = serde_json::from_slice::<Value>(&body) else { | ||
let said = Json(group_host_mcp::not_json()); | ||
return Ok((StatusCode::BAD_REQUEST, said).into_response()); | ||
}; | ||
let call = |tool: Tool, args: Value| async move { host.call_as(&who, tool, args).await }; | ||
Ok(match group_host_mcp::answer(&message, &TOOLS, call).await { | ||
Some(answer) => Json(answer).into_response(), | ||
crates/group-host/src/authority_api.rs+5−1
| @@ -188,7 +188,11 @@ pub async fn list_repos( | ||
.store | ||
.writers(uri, cursor, limit) | ||
.map_err(XrpcError::internal)?; | ||
let cursor = writers.last().map(|w| w.space_rev.clone()); | ||
// A short page is the last: no cursor to ask for an empty one after it. | ||
let cursor = writers | ||
.last() | ||
.filter(|_| writers.len() == limit as usize) | ||
.map(|w| w.space_rev.clone()); | ||
let repos: Vec<Value> = writers | ||
.iter() | ||
.map(|w| { | ||
crates/group-host/src/group_handle.rs+3−1
| @@ -125,6 +125,7 @@ pub async fn update_group_handle( | ||
} | ||
// The directory first: until it names the handle, nobody takes it for | ||
// the group's. | ||
let turn = host.plc.turn().await; | ||
let last = host.plc.last_op(group).await.map_err(XrpcError::internal)?; | ||
let Signed::Update { op, .. } = &last else { | ||
return Err(bad("NotController", "the group's DID is ended")); | ||
| @@ -142,7 +143,8 @@ pub async fn update_group_handle( | ||
host.plc | ||
.publish(group, &signed) | ||
.await | ||
.map_err(XrpcError::internal)?; | ||
.map_err(crate::plc::not_published)?; | ||
drop(turn); | ||
// Taken here meanwhile, the database's unique handle refuses it. | ||
let set = host | ||
.store | ||
crates/group-host/src/import.rs+5−2
| @@ -225,8 +225,11 @@ impl Host { | ||
return false; | ||
} | ||
let url = format!("{pds}/xrpc/com.atproto.server.describeServer"); | ||
let described = self.public_json(&url, "its server").await; | ||
let described = described.unwrap_or_default(); | ||
// A server that cannot say which domains it gives out may give out | ||
// this one: the handle is not kept on a guess. | ||
let Ok(described) = self.public_json(&url, "its server").await else { | ||
return false; | ||
}; | ||
let domains = described["availableUserDomains"].as_array(); | ||
let theirs = domains.into_iter().flatten().filter_map(Value::as_str); | ||
if theirs.into_iter().any(|d| under(handle, d)) { | ||
crates/group-host/src/lib.rs+8−1
| @@ -605,9 +605,16 @@ pub async fn run(args: &[String], config: Config) -> anyhow::Result<()> { | ||
["move-host", "--from", from, rest @ ..] if rest.iter().all(|a| *a == "--dry-run") => { | ||
let host = Host::open(config)?; | ||
let dry_run = !rest.is_empty(); | ||
for line in move_host::move_host(&host, from, dry_run).await? { | ||
let report = move_host::move_host(&host, from, dry_run).await?; | ||
for line in &report.said { | ||
println!("{line}"); | ||
} | ||
if report.failed > 0 { | ||
anyhow::bail!( | ||
"{} DID documents not repointed: run it again once the directory answers for them", | ||
report.failed | ||
); | ||
} | ||
Ok(()) | ||
} | ||
_ => anyhow::bail!("{USAGE}"), | ||
crates/group-host/src/migration.rs+18−14
| @@ -371,12 +371,22 @@ impl Host { | ||
extra: &[(&str, &str)], | ||
) -> Result<reqwest::Response, XrpcError> { | ||
let url = format!("{pds}/xrpc/fyi.opensocial.migrateExport"); | ||
let (pinned, at) = self.pinned(&url).await.map_err(source)?; | ||
let mut query = vec![("group", group), ("token", token)]; | ||
query.extend_from_slice(extra); | ||
let res = pinned.get(at).query(&query).send().await.map_err(source)?; | ||
self.ask_source(&url, &query).await | ||
} | ||
| ||
/// GETs `url` of the group's host, with `query`: an answer other than | ||
/// a success is the host's to say, not read as one. | ||
async fn ask_source( | ||
&self, | ||
url: &str, | ||
query: &[(&str, &str)], | ||
) -> Result<reqwest::Response, XrpcError> { | ||
let (pinned, at) = self.pinned(url).await.map_err(source)?; | ||
let res = pinned.get(at).query(query).send().await.map_err(source)?; | ||
if !res.status().is_success() { | ||
return Err(source(format!("answered {}", res.status()))); | ||
return Err(source(format!("{url} answered {}", res.status()))); | ||
} | ||
Ok(res) | ||
} | ||
| @@ -511,16 +521,8 @@ pub async fn migrate_receive( | ||
}; | ||
| ||
// Its public repo, checked against the group's key. | ||
let (pinned, at) = host | ||
.pinned(&format!("{pds}/xrpc/com.atproto.sync.getRepo")) | ||
.await | ||
.map_err(source)?; | ||
let res = pinned | ||
.get(at) | ||
.query(&[("did", group)]) | ||
.send() | ||
.await | ||
.map_err(source)?; | ||
let url = format!("{pds}/xrpc/com.atproto.sync.getRepo"); | ||
let res = host.ask_source(&url, &[("did", group)]).await?; | ||
let read = capped(res, REPO_AT_MOST).await; | ||
let bytes = read.ok_or(source(too_much(REPO_AT_MOST)))?; | ||
let writes = repo_writes(&bytes, group, &key); | ||
| @@ -665,6 +667,7 @@ pub async fn migrate_complete( | ||
if theirs.is_empty() { | ||
return Err(invalid("recommendedCreds names no rotation key")); | ||
} | ||
let turn = host.plc.turn().await; | ||
let last = host | ||
.plc | ||
.last_op(&group) | ||
| @@ -712,7 +715,8 @@ pub async fn migrate_complete( | ||
host.plc | ||
.publish(&group, &signed) | ||
.await | ||
.map_err(XrpcError::internal)?; | ||
.map_err(crate::plc::not_published)?; | ||
drop(turn); | ||
let off = host.store.deactivate(&group, now_millis(), &me, &[], &[]); | ||
off.map_err(XrpcError::internal)?; | ||
// Handed over, there is nothing more to pull. | ||
crates/group-host/src/moderation.rs+6−6
| @@ -85,7 +85,7 @@ fn event_row(row: &Row) -> rusqlite::Result<Event> { | ||
impl Store { | ||
/// Keeps `event` on `subject` in `group`'s queue, opening the subject | ||
/// if it is new; a report reopens one resolved, as someone asks again. | ||
pub fn moderate(&self, group: &str, subject: &str, event: &Event) -> Result<()> { | ||
pub fn moderate(&self, group: &str, subject: &str, event: &Event) -> Result<i64> { | ||
let mut conn = self.conn(); | ||
let tx = conn.transaction()?; | ||
let at = event.created_at; | ||
| @@ -101,8 +101,9 @@ impl Store { | ||
"INSERT INTO mod_event (grp, subject, kind, actor, reason_type, reason, val, note, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", | ||
params![group, subject, e.kind, e.actor, e.reason_type, e.reason, e.val, e.note, at], | ||
)?; | ||
let seq = tx.last_insert_rowid(); | ||
tx.commit()?; | ||
Ok(()) | ||
Ok(seq) | ||
} | ||
| ||
/// Sets `subject`'s status in `group`'s queue: `false` if it has none. | ||
| @@ -499,11 +500,10 @@ pub async fn create_report( | ||
created_at: now, | ||
..Event::default() | ||
}; | ||
host.store | ||
.moderate(&group, uri, &event) | ||
.map_err(XrpcError::internal)?; | ||
let id = host.store.moderate(&group, uri, &event); | ||
let id = id.map_err(XrpcError::internal)?; | ||
let mut out = json!({ | ||
"id": now, | ||
"id": id, | ||
"reasonType": reason_type, | ||
"subject": body["subject"], | ||
"reportedBy": me, | ||
crates/group-host/src/move_host.rs+27−5
| @@ -29,6 +29,22 @@ pub enum Moved { | ||
Ended, | ||
/// This host holds no rotation key to it any more. | ||
NotOurs, | ||
/// Not repointed, and why: the directory did not answer for it, or | ||
/// refused the change. | ||
Failed(String), | ||
} | ||
| ||
/// What a move did, a line each, and how many accounts it could not | ||
/// repoint. | ||
#[derive(Debug)] | ||
pub struct Report { | ||
pub said: Vec<String>, | ||
pub failed: usize, | ||
} | ||
| ||
/// An account the move could not repoint, and why. | ||
fn failed(e: anyhow::Error) -> Moved { | ||
Moved::Failed(format!("{e:#}")) | ||
} | ||
| ||
impl Store { | ||
| @@ -84,8 +100,9 @@ impl Host { | ||
} | ||
| ||
/// Moves `host`, whose environment names its new address, from `from`: | ||
/// what it did, a line each. | ||
pub async fn move_host(host: &Host, from: &str, dry_run: bool) -> Result<Vec<String>> { | ||
/// what it did. An account it cannot repoint is said so, and the rest | ||
/// moved still. | ||
pub async fn move_host(host: &Host, from: &str, dry_run: bool) -> Result<Report> { | ||
let from = from.trim_end_matches('/'); | ||
let to = host.config.public_url.trim_end_matches('/'); | ||
if from == to { | ||
| @@ -100,7 +117,7 @@ pub async fn move_host(host: &Host, from: &str, dry_run: bool) -> Result<Vec<Str | ||
"" | ||
} | ||
)]; | ||
let (mut cursor, mut seen, mut moved) = (None::<String>, 0, 0); | ||
let (mut cursor, mut seen, mut moved, mut not) = (None::<String>, 0, 0, 0); | ||
loop { | ||
let page = host.store.accounts(cursor.as_deref(), 100)?; | ||
let Some((last, _)) = page.last() else { | ||
| @@ -111,7 +128,8 @@ pub async fn move_host(host: &Host, from: &str, dry_run: bool) -> Result<Vec<Str | ||
seen += 1; | ||
let account = host.store.account(did)?.expect("an account listed"); | ||
let name = &account.handle; | ||
match host.repoint(did, name, from, dry_run).await? { | ||
let repointed = host.repoint(did, name, from, dry_run).await; | ||
match repointed.unwrap_or_else(failed) { | ||
Moved::Repointed(ids) => { | ||
moved += 1; | ||
said.push(format!("{name}: {} → {to}", ids.join(", "))); | ||
| @@ -121,10 +139,14 @@ pub async fn move_host(host: &Host, from: &str, dry_run: bool) -> Result<Vec<Str | ||
Moved::NotOurs => said.push(format!( | ||
"{name}: this host holds no rotation key to it, skipped" | ||
)), | ||
Moved::Failed(why) => { | ||
not += 1; | ||
said.push(format!("{name}: not repointed: {why}")); | ||
} | ||
} | ||
} | ||
} | ||
let done = if dry_run { "to repoint" } else { "repointed" }; | ||
said.push(format!("{moved} of {seen} DID documents {done}")); | ||
Ok(said) | ||
Ok(Report { said, failed: not }) | ||
} | ||
crates/group-host/src/plc.rs+45−2
| @@ -1,13 +1,48 @@ | ||
//! The PLC directory, `PLC_URL`: where the host publishes its groups' | ||
//! identity operations, and reads their documents back. | ||
| ||
use anyhow::{Context, Result, bail}; | ||
use crate::xrpc::XrpcError; | ||
use anyhow::{Context, Result}; | ||
use atproto::plc::Signed; | ||
use axum::http::StatusCode; | ||
use serde_json::Value; | ||
| ||
pub struct Directory { | ||
url: String, | ||
http: reqwest::Client, | ||
/// Held from reading a DID's last operation to publishing the next, | ||
/// so two changes at once never both build on the same one. | ||
turn: tokio::sync::Mutex<()>, | ||
} | ||
| ||
/// An operation the directory answered with an error, and what it said. | ||
#[derive(Debug)] | ||
pub struct Refused { | ||
pub status: StatusCode, | ||
pub said: String, | ||
} | ||
| ||
impl std::fmt::Display for Refused { | ||
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { | ||
let Refused { status, said } = self; | ||
write!(f, "the PLC directory refused it ({status}): {said}") | ||
} | ||
} | ||
| ||
impl std::error::Error for Refused {} | ||
| ||
/// An operation not published, as its caller is told. One the directory | ||
/// turned away (a 4xx: a key it does not take, too many keys, another | ||
/// change made first) is the caller's to change or send again, | ||
/// `InvalidOperation`; a directory that failed, or never answered, is the | ||
/// host's trouble. | ||
pub fn not_published(e: anyhow::Error) -> XrpcError { | ||
match e.downcast_ref::<Refused>() { | ||
Some(r) if r.status.is_client_error() => { | ||
XrpcError::new(StatusCode::BAD_REQUEST, "InvalidOperation", r.to_string()) | ||
} | ||
_ => XrpcError::internal(format!("{e:#}")), | ||
} | ||
} | ||
| ||
impl Directory { | ||
| @@ -15,9 +50,16 @@ impl Directory { | ||
Directory { | ||
url: url.trim_end_matches('/').to_string(), | ||
http: crate::client(), | ||
turn: Default::default(), | ||
} | ||
} | ||
| ||
/// The turn to change a DID's document: held from reading its last | ||
/// operation until the next is published. | ||
pub async fn turn(&self) -> tokio::sync::MutexGuard<'_, ()> { | ||
self.turn.lock().await | ||
} | ||
| ||
/// Publishes `op` as `did`'s next operation. | ||
pub async fn publish(&self, did: &str, op: &Signed) -> Result<()> { | ||
let res = self | ||
| @@ -29,7 +71,8 @@ impl Directory { | ||
let status = res.status(); | ||
if !status.is_success() { | ||
let said = res.text().await.unwrap_or_default(); | ||
bail!("the PLC directory refused {did}'s operation ({status}): {said}"); | ||
let refused = Err(Refused { status, said }); | ||
return refused.context(format!("{did}'s operation")); | ||
} | ||
Ok(()) | ||
} | ||
crates/group-host/src/recovery.rs+20−9
| @@ -130,6 +130,19 @@ impl Host { | ||
}) | ||
} | ||
| ||
/// The group's rotation keys, for a change to them: refused once the | ||
/// host holds none, whatever the change. | ||
async fn keys_to_change(&self, group: &str) -> Result<Keys, XrpcError> { | ||
let keys = self.rotation_keys(group).await?; | ||
if !keys.host_holds() { | ||
return Err(refused( | ||
"NotController", | ||
"this host no longer holds a rotation key for the group, so it cannot change them", | ||
)); | ||
} | ||
Ok(keys) | ||
} | ||
| ||
/// Writes the group's rotation keys: its stewards', in order, and | ||
/// this host's last, signed by this host's. | ||
async fn set_rotation_keys( | ||
| @@ -138,12 +151,6 @@ impl Host { | ||
keys: &Keys, | ||
stewards: Vec<String>, | ||
) -> Result<(), XrpcError> { | ||
if !keys.host_holds() { | ||
return Err(refused( | ||
"NotController", | ||
"this host no longer holds a rotation key for the group, so it cannot change them", | ||
)); | ||
} | ||
let mut next = keys.op.clone(); | ||
next.rotation_keys = stewards; | ||
next.rotation_keys.push(keys.ours.clone()); | ||
| @@ -151,7 +158,7 @@ impl Host { | ||
self.plc | ||
.publish(group, &signed) | ||
.await | ||
.map_err(XrpcError::internal) | ||
.map_err(crate::plc::not_published) | ||
} | ||
} | ||
| ||
| @@ -205,7 +212,8 @@ pub async fn add_recovery_key( | ||
"not a did:key the directory takes (secp256k1 or P-256)", | ||
)); | ||
} | ||
let keys = host.rotation_keys(&group).await?; | ||
let turn = host.plc.turn().await; | ||
let keys = host.keys_to_change(&group).await?; | ||
if keys.op.rotation_keys.iter().any(|k| k == key) { | ||
return Err(refused( | ||
"AlreadyAdded", | ||
| @@ -221,6 +229,7 @@ pub async fn add_recovery_key( | ||
let mut stewards = keys.stewards.clone(); | ||
stewards.push(key.into()); | ||
host.set_rotation_keys(&group, &keys, stewards).await?; | ||
drop(turn); | ||
let noted = host | ||
.store | ||
.note_recovery_key(&group, key, Some(&me), now_millis()); | ||
| @@ -240,7 +249,8 @@ pub async fn remove_recovery_key( | ||
.configuring(&headers, "removeRecoveryKey", body["group"].as_str()) | ||
.await?; | ||
let key = body["key"].as_str().unwrap_or_default(); | ||
let keys = host.rotation_keys(&group).await?; | ||
let turn = host.plc.turn().await; | ||
let keys = host.keys_to_change(&group).await?; | ||
if key == keys.ours { | ||
return Err(refused( | ||
"HostKey", | ||
| @@ -260,6 +270,7 @@ pub async fn remove_recovery_key( | ||
.cloned() | ||
.collect(); | ||
host.set_rotation_keys(&group, &keys, stewards).await?; | ||
drop(turn); | ||
let noted = host | ||
.store | ||
.note_recovery_key(&group, key, None, now_millis()); | ||