~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0

Groups are switched off, back on, and deleted

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:host/group-lifecycle
crates/group-host/src/api.rs+16−6
@@ -54,9 +54,12 @@ 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)?;
account.map(|a| a.did).ok_or_else(|| repo_not_found(repo))
let did = account.map(|a| a.did).ok_or_else(|| repo_not_found(repo))?;
host.active(&did)?;
Ok(did)
}
fn view(did: &str, r: &Record) -> Value {
@@ -129,16 +132,15 @@ pub async fn get_repo(
State(host): State<Arc<Host>>,
Query(p): Query<Params>,
) -> Result<Response, XrpcError> {
let did = param(&p, "did")?;
let did = &did_of(&host, param(&p, "did")?)?;
let car = host.export(did).map_err(XrpcError::internal)?;
let car = car.ok_or_else(|| repo_not_found(did))?;
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 = param(&p, "did")?;
let did = &did_of(&host, param(&p, "did")?)?;
let head = host.store.head(did).map_err(XrpcError::internal)?;
let head = head.ok_or_else(|| repo_not_found(did))?;
let head = head.expect("an account has a repo");
Ok(Json(json!({"cid": head.cid.to_string(), "rev": head.rev})))
}
@@ -154,7 +156,15 @@ pub async fn list_repos(State(host): State<Arc<Host>>, Query(p): Query<Params>)
.map(|(did, _)| did.clone());
let repos: Vec<Value> = repos
.iter()
.map(|(did, head)| json!({"did": did, "head": head.cid.to_string(), "rev": head.rev, "active": true}))
.map(|(did, head)| {
let mut repo =
json!({"did": did, "head": head.cid.to_string(), "rev": head.rev, "active": true});
if host.deactivation(did).ok().flatten().is_some() {
repo["active"] = json!(false);
repo["status"] = json!("deactivated");
}
repo
})
.collect();
Ok(Json(json!({"repos": repos, "cursor": cursor})))
}
crates/group-host/src/authority.rs+36−0
@@ -33,6 +33,9 @@ pub enum Access {
Write,
}
/// The method an authority tells a syncer a space is gone with.
pub const NOTIFY_SPACE_DELETED: &str = "com.atproto.space.notifySpaceDeleted";
/// How long a write's word is tried before it is given up, in seconds.
pub const DELIVER_FOR: i64 = 24 * 60 * 60;
/// The wait before the first retry, doubling each after, up to an hour.
@@ -138,6 +141,10 @@ impl Host {
user: Option<&str>,
access_kind: Access,
) -> Result<bool> {
// Nothing reads or writes in the spaces of an authority switched off.
if self.store.deactivation(&space.authority)?.is_some() {
return Ok(false);
}
let Some(user) = user else {
return Ok(access_kind == Access::Read && space.public_read);
};
@@ -219,6 +226,35 @@ impl Host {
Ok(())
}
/// Tells the services syncing each of `authority`'s spaces that it is
/// gone, as the authority, before its key is: best effort, as a syncer
/// that misses it learns so when its credential is refused.
pub fn tell_spaces_deleted(&self, authority: &str) -> Result<()> {
let signing = self
.store
.account(authority)?
.context("the authority is here")?
.signing;
for space in self.store.spaces_of(authority)? {
for (service, endpoint) in self.store.recipients(&space, now())? {
let claims = self.claims(authority, &service, NOTIFY_SPACE_DELETED);
let send = self
.http
.post(format!("{endpoint}/xrpc/{NOTIFY_SPACE_DELETED}"))
.bearer_auth(service_auth::sign(&signing, &claims))
.json(&json!({ "space": space }))
.send();
tokio::spawn(async move {
let said = send.await.and_then(|r| r.error_for_status());
if let Err(e) = said {
tracing::warn!(service, error = %e, "notifySpaceDeleted failed");
}
});
}
}
Ok(())
}
/// Tries `notice` now: tells its space's authority, at its PDS, as the
/// repo.
pub async fn deliver(&self, notice: &Notice) -> Delivery {
crates/group-host/src/group.rs+20−2
@@ -138,6 +138,24 @@ impl Host {
e
}
})?;
// A group half made is no group: its account goes, so its handle
// is free again.
let made = self.set_up(&did, new, join, &readers, &stewards).await;
if made.is_err() {
let _ = self.delete_account(&did).await;
}
made
}
async fn set_up(
&self,
did: &str,
new: &NewGroup,
join: &str,
readers: &[String],
stewards: &[String],
) -> Result<Made, XrpcError> {
let did = did.to_string();
let meta = self.create_space(&did, &format!("{NS}.meta"), "self", false)?;
let members = self.create_space(&did, &format!("{NS}.members"), "self", false)?;
let at = iso(now_millis());
@@ -160,7 +178,7 @@ impl Host {
"self",
json!({
"$type": c("access"),
"readableBy": audience(&readers),
"readableBy": audience(readers),
"credentialScopes": [{"role": "admin", "scopes": [{"collection": c("profile")}, {"collection": c("rule")}]}],
"createdAt": at,
}),
@@ -199,7 +217,7 @@ impl Host {
json!({"$type": c("space"), "space": space, "createdAt": at}),
));
}
for steward in &stewards {
for steward in stewards {
members_writes.push(put(
&c("membership"),
&did_rkey(steward),
crates/group-host/src/group_api.rs+12−0
@@ -187,6 +187,13 @@ pub async fn get_group(
let group = param(&p, "group")?;
let handle = group_of(&host, group)?;
let me = caller(&host, &headers, &format!("{NS}.getGroup")).await?;
// Switched off: nothing in it is read, by members either. Still
// answered, so a steward can find the switch.
if host.deactivation(group)?.is_some() {
let mut view = base(group, &handle);
view["deactivated"] = json!(true);
return Ok(Json(json!({ "group": view })));
}
let record = |space: &str, collection: &str, rkey: &str| {
host.group_record(group, space, &format!("{NS}.{collection}"), rkey)
.map_err(XrpcError::internal)
@@ -315,6 +322,11 @@ pub async fn list_groups(State(host): State<Arc<Host>>) -> Answer {
continue;
};
let mut view = base(did, &handle);
if host.deactivation(did)?.is_some() {
view["deactivated"] = json!(true);
groups.push(view);
continue;
}
let meta = meta_space(did);
let access = host
.group_record(did, &meta, &format!("{NS}.access"), "self")
crates/group-host/src/group_config.rs+29−13
@@ -8,7 +8,7 @@ use crate::Host;
use crate::api::{Params, invalid, param};
use crate::group::{join_policy, members_space, meta_space};
use crate::group_api::{group_of, signed_in};
use crate::rbac::{NS, actions_for, grants};
use crate::rbac::{NS, actions_for, grants, listed};
use crate::repo::Write;
use crate::time::{iso, now_millis};
use crate::xrpc::XrpcError;
@@ -32,7 +32,7 @@ const PLACES: [&str; 4] = [
"community.lexicon.location.hthree",
];
fn forbidden() -> XrpcError {
pub(crate) fn forbidden() -> XrpcError {
XrpcError::new(
StatusCode::FORBIDDEN,
"Forbidden",
@@ -50,22 +50,38 @@ async fn configurer(
) -> Result<String, XrpcError> {
let me = signed_in(host, headers, &format!("{NS}.{lxm}")).await?;
group_of(host, group)?;
let permissions = host
.group_record(
group,
&members_space(group),
&format!("{NS}.permissions"),
"self",
)
.map_err(XrpcError::internal)?;
let roles = host.roles(group, &me).map_err(XrpcError::internal)?;
let granted = grants(&permissions.unwrap_or_default());
if !actions_for(&granted, &roles).contains("group.configure") {
if !host.may_configure(group, &me)? {
return Err(forbidden());
}
Ok(group.to_string())
}
impl Host {
/// Whether `did` holds `group.configure` in `group`, by its records now.
pub fn may_configure(&self, group: &str, did: &str) -> Result<bool, XrpcError> {
Ok(self.configurers(group)?.iter().any(|c| c == did))
}
/// Everyone whose roles in `group` carry `group.configure`.
pub fn configurers(&self, group: &str) -> Result<Vec<String>, XrpcError> {
let members = members_space(group);
let permissions = self
.group_record(group, &members, &format!("{NS}.permissions"), "self")
.map_err(XrpcError::internal)?;
let granted = grants(&permissions.unwrap_or_default());
let memberships = self
.group_records(group, &members, &format!("{NS}.membership"))
.map_err(XrpcError::internal)?;
Ok(memberships
.iter()
.filter(|(_, m)| {
actions_for(&granted, &listed(m, "roles", "role")).contains("group.configure")
})
.filter_map(|(_, m)| m["member"].as_str().map(String::from))
.collect())
}
}
/// Puts the group's record at `collection/rkey` in meta, made or replaced:
/// its URI and CID.
async fn put(host: &Host, group: &str, collection: &str, rkey: &str, value: Value) -> Answer {
crates/group-host/src/group_lifecycle.rsnew+108−0
@@ -0,0 +1,108 @@
//! Switching a group off, back on, and deleting it, as `lifecycle.rs`
//! does to its account.
//!
//! While a group is on, who may do each is who holds `group.configure`;
//! while it is off nothing can read its memberships, so it is who held it
//! when it was switched off, kept then.
//!
//! As the prototype's `methods/lifecycle.ts`.
use crate::Host;
use crate::api::invalid;
use crate::group_api::{group_of, signed_in};
use crate::group_config::forbidden;
use crate::rbac::NS;
use crate::xrpc::XrpcError;
use axum::Json;
use axum::extract::State;
use axum::http::{HeaderMap, StatusCode};
use serde_json::{Value, json};
use std::sync::Arc;
type Answer = Result<Json<Value>, XrpcError>;
fn bad(error: &'static str, message: &str) -> XrpcError {
XrpcError::new(StatusCode::BAD_REQUEST, error, message)
}
/// The group a body names, and who asks for `lxm` on it.
async fn asked(
host: &Host,
headers: &HeaderMap,
body: &Value,
lxm: &str,
) -> Result<(String, String), XrpcError> {
let me = signed_in(host, headers, &format!("{NS}.{lxm}")).await?;
let group = body["group"]
.as_str()
.ok_or_else(|| invalid("group is required"))?;
group_of(host, group)?;
Ok((group.to_string(), me))
}
/// Whether `me` may switch `group` back on or delete it: by its records
/// while it is on, by who held `group.configure` when it went off while
/// it is off.
fn steward(host: &Host, group: &str, me: &str) -> Result<(), XrpcError> {
let may = match host.deactivation(group)? {
Some(off) => off.stewards.iter().any(|s| s == me),
None => host.may_configure(group, me)?,
};
if may { Ok(()) } else { Err(forbidden()) }
}
/// Switches a group off: nothing reads its spaces or writes as it until a
/// steward of now switches it back on.
pub async fn deactivate_group(
State(host): State<Arc<Host>>,
headers: HeaderMap,
Json(body): Json<Value>,
) -> Answer {
let (group, me) = asked(&host, &headers, &body, "deactivateGroup").await?;
if host.deactivation(&group)?.is_some() {
return Err(bad(
"AlreadyDeactivated",
"the group is switched off already",
));
}
steward(&host, &group, &me)?;
// Read before it goes dark: afterwards nothing can read them.
let stewards = host.configurers(&group)?;
host.deactivate_account(&group, &me, &stewards)
.map_err(XrpcError::internal)?;
Ok(Json(json!({})))
}
/// Switches a group back on, for one who could switch it off.
pub async fn activate_group(
State(host): State<Arc<Host>>,
headers: HeaderMap,
Json(body): Json<Value>,
) -> Answer {
let (group, me) = asked(&host, &headers, &body, "activateGroup").await?;
if host.deactivation(&group)?.is_none() {
return Err(bad("NotDeactivated", "the group is not switched off"));
}
steward(&host, &group, &me)?;
host.activate_account(&group).map_err(XrpcError::internal)?;
Ok(Json(json!({})))
}
/// Deletes a group: its account, repos and spaces here, and what the host
/// keeps of them; the services syncing its spaces are told; its DID is
/// ended. What members wrote in its spaces is theirs, at their own PDSes.
pub async fn delete_group(
State(host): State<Arc<Host>>,
headers: HeaderMap,
Json(body): Json<Value>,
) -> Answer {
let (group, me) = asked(&host, &headers, &body, "deleteGroup").await?;
steward(&host, &group, &me)?;
host.tell_spaces_deleted(&group)
.map_err(XrpcError::internal)?;
let tombstoned = host
.delete_account(&group)
.await
.map_err(XrpcError::internal)?;
Ok(Json(json!({ "tombstoned": tombstoned })))
}
crates/group-host/src/lib.rs+14−0
@@ -12,7 +12,9 @@ pub mod firehose;
pub mod group;
pub mod group_api;
pub mod group_config;
pub mod group_lifecycle;
pub mod identity;
pub mod lifecycle;
pub mod plc;
pub mod rbac;
pub mod repo;
@@ -180,6 +182,18 @@ pub fn router(host: Arc<Host>) -> Router {
"/xrpc/fyi.opensocial.deleteRule",
post(group_config::delete_rule),
)
.route(
"/xrpc/fyi.opensocial.deactivateGroup",
post(group_lifecycle::deactivate_group),
)
.route(
"/xrpc/fyi.opensocial.activateGroup",
post(group_lifecycle::activate_group),
)
.route(
"/xrpc/fyi.opensocial.deleteGroup",
post(group_lifecycle::delete_group),
)
.route("/.well-known/did.json", get(api::did_json))
.route("/.well-known/atproto-did", get(api::atproto_did))
.route("/xrpc/{nsid}", get(not_implemented).post(not_implemented))
crates/group-host/src/lifecycle.rsnew+104−0
@@ -0,0 +1,104 @@
//! An account switched off, back on, and deleted, as a PDS does to an
//! account, and the relays told of each.
//!
//! While it is off, nothing reads its repos or its spaces and nothing
//! writes as it; who may switch it back on is kept with it, as nothing
//! can read its memberships to say. Deleted, it is gone from the host, and
//! its DID ended in the directory.
use crate::Host;
use crate::repo::event;
use crate::store::Deactivation;
use crate::time::{iso, now_millis};
use crate::xrpc::XrpcError;
use anyhow::{Context, Result};
use atproto::Value;
use axum::http::StatusCode;
/// The refusal of a repo whose account is switched off.
pub fn deactivated(did: &str) -> XrpcError {
XrpcError::new(
StatusCode::BAD_REQUEST,
"RepoDeactivated",
format!("{did} is deactivated"),
)
}
/// An `#account` event: whether it is active, and if not, why.
fn status(did: &str, status: Option<&str>) -> crate::store::Event {
let at = Value::String(iso(now_millis()));
match status {
None => event(
"#account",
[
("did", Value::String(did.into())),
("active", Value::Bool(true)),
("time", at),
],
),
Some(status) => event(
"#account",
[
("did", Value::String(did.into())),
("active", Value::Bool(false)),
("status", Value::String(status.into())),
("time", at),
],
),
}
}
impl Host {
/// How `did` was switched off, if it is.
pub fn deactivation(&self, did: &str) -> Result<Option<Deactivation>, XrpcError> {
self.store.deactivation(did).map_err(XrpcError::internal)
}
/// Refuses `did` if it is switched off.
pub fn active(&self, did: &str) -> Result<(), XrpcError> {
match self.deactivation(did)? {
Some(_) => Err(deactivated(did)),
None => Ok(()),
}
}
/// Switches `did` off, by `by`, for `stewards` to switch back on:
/// `false` if it was off.
pub fn deactivate_account(&self, did: &str, by: &str, stewards: &[String]) -> Result<bool> {
let events = [status(did, Some("deactivated"))];
let done = self
.store
.deactivate(did, now_millis(), by, stewards, &events)?;
self.announce();
Ok(done)
}
/// Switches `did` back on: `false` if it was on.
pub fn activate_account(&self, did: &str) -> Result<bool> {
let done = self.store.activate(did, &[status(did, None)])?;
self.announce();
Ok(done)
}
/// Deletes `did` from the host whole, and ends its DID in the
/// directory, as only this host holds a key to it. Whether it was
/// ended.
pub async fn delete_account(&self, did: &str) -> Result<bool> {
let blobs = self
.store
.delete_account(did, &[status(did, Some("deleted"))])?;
self.remove_blobs(blobs.iter().map(|cid| (did, cid)));
self.announce();
let ended = self.tombstone(did).await;
if let Err(e) = &ended {
tracing::warn!(did, error = %format!("{e:#}"), "could not end the DID");
}
Ok(ended.is_ok())
}
async fn tombstone(&self, did: &str) -> Result<()> {
let last = self.plc.last_op(did).await?;
let end = atproto::plc::tombstone(last.cid(), &self.secrets.rotation);
self.plc.publish(did, &end).await.context("tombstoning")
}
}
crates/group-host/src/plc.rs+14−0
@@ -34,6 +34,20 @@ impl Directory {
Ok(())
}
/// `did`'s last operation, as the directory has it.
pub async fn last_op(&self, did: &str) -> Result<Signed> {
let res = self
.http
.get(format!("{}/{did}/log/last", self.url))
.send()
.await?;
let res = res
.error_for_status()
.context(format!("no operations for {did}"))?;
let op: Value = res.json().await?;
Ok(Signed::from_json(&op)?)
}
/// `did`'s document, as the directory serves it.
pub async fn document(&self, did: &str) -> Result<Value> {
let res = self.http.get(format!("{}/{did}", self.url)).send().await?;
crates/group-host/src/repo.rs+6−10
@@ -202,6 +202,7 @@ impl Host {
format!("no repo {did} here"),
)
})?;
self.active(&account.did)?;
let head = self
.store
.head(&account.did)
@@ -314,7 +315,7 @@ impl Host {
/// `PDS_CRAWLERS` this host has news: at most every twenty minutes,
/// and the first time after it starts, so a relay that marked it
/// offline comes back.
fn announce(&self) {
pub(crate) fn announce(&self) {
let _ = self.events.send(());
let mut last = self.crawled.lock().expect("not poisoned");
if last.is_some_and(|at| at.elapsed() < CRAWL_EVERY) {
@@ -347,10 +348,8 @@ impl Host {
/// `did`'s whole repo as a CAR file: its commit, then each node of its
/// tree, parents first, with the records it holds in the order it
/// holds them.
pub fn export(&self, did: &str) -> Result<Option<Vec<u8>>> {
let Some(head) = self.store.head(did)? else {
return Ok(None);
};
pub fn export(&self, did: &str) -> Result<Vec<u8>> {
let head = self.store.head(did)?.context("an account has a repo")?;
let records: BTreeMap<Cid, Vec<u8>> = self
.store
.records(did)?
@@ -360,10 +359,7 @@ impl Host {
let tree = Tree::build(&self.store.paths(did)?);
let mut blocks: Vec<(Cid, &[u8])> = vec![(head.cid, &head.block)];
walk(tree.root_node(), &records, &mut blocks);
Ok(Some(car::write(
&[head.cid],
blocks.iter().map(|(c, b)| (c, *b)),
)))
Ok(car::write(&[head.cid], blocks.iter().map(|(c, b)| (c, *b))))
}
}
@@ -371,7 +367,7 @@ impl Host {
const CRAWL_EVERY: std::time::Duration = std::time::Duration::from_secs(20 * 60);
/// An event of `kind` with the fields given.
fn event<const N: usize>(kind: &'static str, fields: [(&str, Value); N]) -> Event {
pub(crate) fn event<const N: usize>(kind: &'static str, fields: [(&str, Value); N]) -> Event {
let map = fields
.into_iter()
.map(|(k, v)| (k.to_string(), v))
crates/group-host/src/space.rs+1−0
crates/group-host/src/space_api.rs+1−0
crates/group-host/src/store.rs+115−0
crates/group-host/tests/common/mod.rs+12−0
crates/group-host/tests/common/spaces.rs+4−0
crates/group-host/tests/lifecycle.rsnew+327−0
docs/design/groups.md+22−0
docs/design/README.md+3−1