chadtmiller.com/group-host
atmosphere group host
0
0
A group takes a handle on a domain of its own, and its address back
crates/group-host/src/config.rs+13−0
| @@ -24,6 +24,11 @@ pub struct Config { | ||
/// How a `did:web`'s document is read, `DID_WEB_SCHEME`: `https`, or | ||
/// `http` for a network of test servers. | ||
pub did_web_scheme: String, | ||
/// How a handle is resolved, `HANDLE_RESOLVERS`, comma-separated, each | ||
/// tried in turn: `well-known:<scheme>` for the handle's own | ||
/// `/.well-known/atproto-did`, or a service answering | ||
/// `com.atproto.identity.resolveHandle`, which reads its DNS record. | ||
pub handle_resolvers: Vec<String>, | ||
/// Who this host starts groups for, `GROUP_FOUNDERS`, comma-separated | ||
/// DIDs: anyone when it names none. | ||
pub group_founders: Vec<String>, | ||
| @@ -73,6 +78,13 @@ impl Config { | ||
.collect() | ||
}; | ||
let group_founders = list("GROUP_FOUNDERS"); | ||
let mut handle_resolvers = list("HANDLE_RESOLVERS"); | ||
if handle_resolvers.is_empty() { | ||
handle_resolvers = vec![ | ||
"well-known:https".into(), | ||
"https://public.api.bsky.app".into(), | ||
]; | ||
} | ||
let crawlers = list("PDS_CRAWLERS"); | ||
let blob_upload_limit = match var("BLOB_UPLOAD_LIMIT") { | ||
Some(l) => l | ||
| @@ -88,6 +100,7 @@ impl Config { | ||
data_dir, | ||
plc_url, | ||
did_web_scheme, | ||
handle_resolvers, | ||
group_founders, | ||
crawlers, | ||
blob_upload_limit, | ||
crates/group-host/src/group_api.rs+8−7
| @@ -153,14 +153,15 @@ fn rules(host: &Host, group: &str) -> Result<Vec<Value>, XrpcError> { | ||
.collect()) | ||
} | ||
| ||
fn base(did: &str, handle: &str) -> Value { | ||
json!({ | ||
fn base(host: &Host, did: &str, handle: &str) -> Result<Value, XrpcError> { | ||
let address = host.store.address(did).map_err(XrpcError::internal)?; | ||
Ok(json!({ | ||
"did": did, | ||
"handle": handle, | ||
"address": handle, | ||
"address": address, | ||
"meta": meta_space(did), | ||
"members": members_space(did), | ||
}) | ||
})) | ||
} | ||
| ||
fn merge(into: &mut Value, from: Value) { | ||
| @@ -190,7 +191,7 @@ pub async fn get_group( | ||
// 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); | ||
let mut view = base(&host, group, &handle)?; | ||
view["deactivated"] = json!(true); | ||
return Ok(Json(json!({ "group": view }))); | ||
} | ||
| @@ -214,7 +215,7 @@ pub async fn get_group( | ||
let granted = grants(&permissions); | ||
let actions = actions_for(&granted, &roles); | ||
| ||
let mut view = base(group, &handle); | ||
let mut view = base(&host, group, &handle)?; | ||
if reads_meta { | ||
if let Some(profile) = record(&meta, "profile", "self")? { | ||
merge(&mut view, profile_view(&profile)); | ||
| @@ -321,7 +322,7 @@ pub async fn list_groups(State(host): State<Arc<Host>>) -> Answer { | ||
let Ok(handle) = group_of(&host, did) else { | ||
continue; | ||
}; | ||
let mut view = base(did, &handle); | ||
let mut view = base(&host, did, &handle)?; | ||
if host.deactivation(did)?.is_some() { | ||
view["deactivated"] = json!(true); | ||
groups.push(view); | ||
crates/group-host/src/group_handle.rsnew+162−0
| @@ -0,0 +1,162 @@ | ||
//! A group's handle on a domain of its own. | ||
//! | ||
//! A group starts with a handle under `HANDLE_DOMAIN`, which is also its | ||
//! address, where its site is served. It may take a handle on a domain of | ||
//! its own instead, once the domain names it (by its `_atproto` DNS record | ||
//! or its `/.well-known/atproto-did`, as any handle is resolved): the | ||
//! handle is then its name everywhere, and goes with it to another host. | ||
//! The address stays. Under the host's domain a group may take only its | ||
//! own address back, so no group takes another's. | ||
//! | ||
//! As the prototype's `methods/handle.ts`. | ||
| ||
use crate::Host; | ||
use crate::api::{Params, invalid, param}; | ||
use crate::group_api::{group_of, signed_in}; | ||
use crate::group_config::forbidden; | ||
use crate::rbac::NS; | ||
use crate::repo::event; | ||
use crate::time::{iso, now_millis}; | ||
use crate::xrpc::XrpcError; | ||
use atproto::plc::Signed; | ||
use atproto::{Value as Drisl, syntax}; | ||
use axum::Json; | ||
use axum::extract::{Query, 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: impl Into<String>) -> XrpcError { | ||
XrpcError::new(StatusCode::BAD_REQUEST, error, message) | ||
} | ||
| ||
/// The group a caller of `lxm` may configure, and its address. | ||
async fn configurable( | ||
host: &Host, | ||
headers: &HeaderMap, | ||
group: &str, | ||
lxm: &str, | ||
) -> Result<String, XrpcError> { | ||
let me = signed_in(host, headers, &format!("{NS}.{lxm}")).await?; | ||
group_of(host, group)?; | ||
if !host.may_configure(group, &me)? { | ||
return Err(forbidden()); | ||
} | ||
let address = host.store.address(group).map_err(XrpcError::internal)?; | ||
Ok(address.expect("a group has an address")) | ||
} | ||
| ||
/// The handle a group could take, as the host reads it: refused when it | ||
/// never could. | ||
fn wanted(host: &Host, group: &str, address: &str, asked: &str) -> Result<String, XrpcError> { | ||
let handle = asked.trim().trim_start_matches('@').to_ascii_lowercase(); | ||
if !syntax::is_handle(&handle) { | ||
return Err(bad("InvalidHandle", format!("{handle} is no handle"))); | ||
} | ||
let domain = host.config.handle_domain.trim_start_matches('.'); | ||
let under = handle == domain || handle.ends_with(&host.config.handle_domain); | ||
if under && handle != address { | ||
return Err(bad( | ||
"UnsupportedDomain", | ||
format!("under {domain}, a group may have only its own address, {address}"), | ||
)); | ||
} | ||
let holder = host.store.account(&handle).map_err(XrpcError::internal)?; | ||
if holder.is_some_and(|a| a.did != group && a.handle == handle) { | ||
return Err(bad( | ||
"HandleNotAvailable", | ||
"another account here has that handle", | ||
)); | ||
} | ||
Ok(handle) | ||
} | ||
| ||
/// The DID `handle` names now: the group, for its own address. | ||
async fn named(host: &Host, group: &str, address: &str, handle: &str) -> Option<String> { | ||
if handle == address { | ||
return Some(group.to_string()); | ||
} | ||
let resolvers = &host.config.handle_resolvers; | ||
host.identity.resolve_handle(handle, resolvers).await | ||
} | ||
| ||
/// Whether a domain is ready to be the group's handle. Changes nothing. | ||
pub async fn check_group_handle( | ||
State(host): State<Arc<Host>>, | ||
Query(p): Query<Params>, | ||
headers: HeaderMap, | ||
) -> Answer { | ||
let group = param(&p, "group")?; | ||
let address = configurable(&host, &headers, group, "checkGroupHandle").await?; | ||
let handle = wanted(&host, group, &address, param(&p, "handle")?)?; | ||
let did = named(&host, group, &address, &handle).await; | ||
let mut out = json!({"handle": handle, "ready": did.as_deref() == Some(group)}); | ||
if let Some(did) = did { | ||
out["did"] = json!(did); | ||
} | ||
Ok(Json(out)) | ||
} | ||
| ||
/// Gives the group a handle on a domain that names it, or its own address | ||
/// back: its `did:plc` first, then the host, then the relays. | ||
pub async fn update_group_handle( | ||
State(host): State<Arc<Host>>, | ||
headers: HeaderMap, | ||
Json(body): Json<Value>, | ||
) -> Answer { | ||
let group = body["group"] | ||
.as_str() | ||
.ok_or_else(|| invalid("group is required"))?; | ||
let asked = body["handle"] | ||
.as_str() | ||
.ok_or_else(|| invalid("handle is required"))?; | ||
let address = configurable(&host, &headers, group, "updateGroupHandle").await?; | ||
let handle = wanted(&host, group, &address, asked)?; | ||
let current = host.store.account(group).map_err(XrpcError::internal)?; | ||
if current.is_some_and(|a| a.handle == handle) { | ||
return Ok(Json(json!({ "handle": handle }))); | ||
} | ||
if named(&host, group, &address, &handle).await.as_deref() != Some(group) { | ||
return Err(bad( | ||
"NotPointing", | ||
format!( | ||
"{handle} does not name this group yet: its _atproto record should say did={group}" | ||
), | ||
)); | ||
} | ||
// The directory first: until it names the handle, nobody takes it for | ||
// the group's. | ||
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")); | ||
}; | ||
let ours = host.secrets.rotation.public().did_key(); | ||
if !op.rotation_keys.contains(&ours) { | ||
return Err(bad( | ||
"NotController", | ||
"this host no longer holds a rotation key for the group", | ||
)); | ||
} | ||
let mut next = op.clone(); | ||
next.also_known_as = vec![format!("at://{handle}")]; | ||
let signed = next.sign(Some(last.cid()), &host.secrets.rotation); | ||
host.plc | ||
.publish(group, &signed) | ||
.await | ||
.map_err(XrpcError::internal)?; | ||
let identity = event( | ||
"#identity", | ||
[ | ||
("did", Drisl::String(group.into())), | ||
("handle", Drisl::String(handle.clone())), | ||
("time", Drisl::String(iso(now_millis()))), | ||
], | ||
); | ||
// Taken here meanwhile, the database's unique handle refuses it. | ||
let set = host.store.set_handle(group, &handle, &[identity]); | ||
set.map_err(XrpcError::internal)?; | ||
host.announce(); | ||
Ok(Json(json!({ "handle": handle }))) | ||
} | ||
crates/group-host/src/group_lifecycle.rs+17−15
| @@ -59,18 +59,18 @@ pub async fn deactivate_group( | ||
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!({}))) | ||
// Off already, or off by another meanwhile: the store says. | ||
let done = host.deactivate_account(&group, &me, &stewards); | ||
match done.map_err(XrpcError::internal)? { | ||
true => Ok(Json(json!({}))), | ||
false => Err(bad( | ||
"AlreadyDeactivated", | ||
"the group is switched off already", | ||
)), | ||
} | ||
} | ||
| ||
/// Switches a group back on, for one who could switch it off. | ||
| @@ -80,17 +80,19 @@ pub async fn activate_group( | ||
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!({}))) | ||
// On already, or on by another meanwhile: the store says. | ||
match host.activate_account(&group).map_err(XrpcError::internal)? { | ||
true => Ok(Json(json!({}))), | ||
false => Err(bad("NotDeactivated", "the group is not switched off")), | ||
} | ||
} | ||
| ||
/// 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. | ||
/// ended. They are told first, while the group has a key to sign with: | ||
/// best effort, so a delete that then fails has told them of one that | ||
/// did not happen, and they find it again when they next read. What members wrote in its spaces is theirs, at their own PDSes. | ||
pub async fn delete_group( | ||
State(host): State<Arc<Host>>, | ||
headers: HeaderMap, | ||
crates/group-host/src/identity.rs+38−0
| @@ -32,6 +32,10 @@ async fn body(mut res: reqwest::Response) -> Result<Vec<u8>> { | ||
/// read, so how many is a caller's to choose. | ||
pub const KEPT_AT_MOST: usize = 10_000; | ||
| ||
/// How long a lookup at a host a name alone points to may take: a | ||
/// handle's `/.well-known/atproto-did` may be anyone's, and never answer. | ||
pub const LOOKUP: Duration = Duration::from_secs(3); | ||
| ||
pub struct Resolver { | ||
plc_url: String, | ||
did_web_scheme: String, | ||
| @@ -103,6 +107,30 @@ impl Resolver { | ||
Ok(doc) | ||
} | ||
| ||
/// The DID `handle` names, asked of each of `resolvers` in turn | ||
/// (`HANDLE_RESOLVERS`): none if none of them says. | ||
pub async fn resolve_handle(&self, handle: &str, resolvers: &[String]) -> Option<String> { | ||
for resolver in resolvers { | ||
let named = match resolver.strip_prefix("well-known:") { | ||
Some(scheme) => { | ||
let url = format!("{scheme}://{handle}/.well-known/atproto-did"); | ||
text(self.http.get(url).timeout(LOOKUP).send().await).await | ||
} | ||
None => { | ||
let url = format!("{resolver}/xrpc/com.atproto.identity.resolveHandle"); | ||
let asked = self.http.get(url).query(&[("handle", handle)]); | ||
let body = json(asked.send().await).await; | ||
body.and_then(|b| b["did"].as_str().map(String::from)) | ||
} | ||
}; | ||
let named = named.map(|d| d.trim().to_string()); | ||
if let Some(did) = named.filter(|d| d.starts_with("did:")) { | ||
return Some(did); | ||
} | ||
} | ||
None | ||
} | ||
| ||
/// `did`'s document as it was read in the last few minutes, if it | ||
/// was. What it names may have changed since: a key that turns a | ||
/// signature away is worth reading again with [`Resolver::document`]. | ||
| @@ -131,3 +159,13 @@ impl Resolver { | ||
Some(check(&key_in(&doc)?)) | ||
} | ||
} | ||
| ||
/// A response's text, if it answered with one. | ||
async fn text(res: reqwest::Result<reqwest::Response>) -> Option<String> { | ||
res.ok()?.error_for_status().ok()?.text().await.ok() | ||
} | ||
| ||
/// A response's JSON, if it answered with some. | ||
async fn json(res: reqwest::Result<reqwest::Response>) -> Option<Value> { | ||
res.ok()?.error_for_status().ok()?.json().await.ok() | ||
} | ||
crates/group-host/src/lib.rs+9−0
| @@ -12,6 +12,7 @@ pub mod firehose; | ||
pub mod group; | ||
pub mod group_api; | ||
pub mod group_config; | ||
pub mod group_handle; | ||
pub mod group_lifecycle; | ||
pub mod identity; | ||
pub mod lifecycle; | ||
| @@ -194,6 +195,14 @@ pub fn router(host: Arc<Host>) -> Router { | ||
"/xrpc/fyi.opensocial.deleteGroup", | ||
post(group_lifecycle::delete_group), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.checkGroupHandle", | ||
get(group_handle::check_group_handle), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.updateGroupHandle", | ||
post(group_handle::update_group_handle), | ||
) | ||
.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/store.rs+39−0
| @@ -161,6 +161,12 @@ const MIGRATIONS: &[&str] = &[ | ||
by TEXT NOT NULL, | ||
stewards TEXT NOT NULL | ||
); | ||
", | ||
" | ||
CREATE TABLE address ( | ||
did TEXT PRIMARY KEY REFERENCES account (did), | ||
address TEXT NOT NULL UNIQUE | ||
); | ||
", | ||
]; | ||
| ||
| @@ -241,6 +247,7 @@ const ACTIVATE: &str = "DELETE FROM deactivation WHERE did = ?1"; | ||
/// What goes with an account, in an order its references allow. | ||
const FORGET_ACCOUNT: &[&str] = &[ | ||
"DELETE FROM deactivation WHERE did = ?1", | ||
"DELETE FROM address WHERE did = ?1", | ||
"DELETE FROM outbox WHERE repo = ?1", | ||
"DELETE FROM space_recipient WHERE space IN (SELECT uri FROM space WHERE authority = ?1)", | ||
"DELETE FROM space_writer WHERE space IN (SELECT uri FROM space WHERE authority = ?1)", | ||
| @@ -489,6 +496,13 @@ impl Store { | ||
params![account.did, head.cid.to_string(), head.rev, head.block], | ||
); | ||
kept?; | ||
// Its first handle is its address, which stays when it takes | ||
// another. | ||
let addressed = tx.execute( | ||
"INSERT INTO address (did, address) VALUES (?1, ?2)", | ||
params![account.did, account.handle], | ||
); | ||
addressed?; | ||
sequence(&tx, &account.did, events)?; | ||
tx.commit()?; | ||
Ok(true) | ||
| @@ -1161,6 +1175,31 @@ impl Store { | ||
Ok(rows.collect::<rusqlite::Result<_>>()?) | ||
} | ||
| ||
/// `did`'s address: the handle it was made at, under the host's | ||
/// domain. | ||
pub fn address(&self, did: &str) -> Result<Option<String>> { | ||
let conn = self.conn(); | ||
let found = conn.query_row("SELECT address FROM address WHERE did = ?1", [did], |r| { | ||
r.get(0) | ||
}); | ||
Ok(found.optional()?) | ||
} | ||
| ||
/// Gives `did` the handle `handle`, with `events`; refused if another | ||
/// account has it. | ||
pub fn set_handle(&self, did: &str, handle: &str, events: &[Event]) -> Result<()> { | ||
let mut conn = self.conn(); | ||
let tx = conn.transaction()?; | ||
let set = tx.execute( | ||
"UPDATE account SET handle = ?1 WHERE did = ?2", | ||
[handle, did], | ||
); | ||
set?; | ||
sequence(&tx, did, events)?; | ||
tx.commit()?; | ||
Ok(()) | ||
} | ||
| ||
/// Switches `did` off, by `by` at `at`, `stewards` the ones who may | ||
/// switch it back on, with `events`: `false` if it is off already. | ||
pub fn deactivate( | ||
crates/group-host/tests/config.rs+6−0
| @@ -21,6 +21,10 @@ fn defaults_serve_localhost() { | ||
assert_eq!(c.data_dir, std::path::PathBuf::from("data")); | ||
assert_eq!(c.did_web_scheme, "https"); | ||
assert!(c.group_founders.is_empty()); | ||
assert_eq!( | ||
c.handle_resolvers, | ||
["well-known:https", "https://public.api.bsky.app"] | ||
); | ||
} | ||
| ||
#[test] | ||
| @@ -41,8 +45,10 @@ fn the_environment_names_the_host() { | ||
("SERVICE_DID", "did:web:other.example"), | ||
("DID_WEB_SCHEME", "http"), | ||
("GROUP_FOUNDERS", "did:plc:a, did:plc:b,"), | ||
("HANDLE_RESOLVERS", "https://resolver.example"), | ||
]) | ||
.unwrap(); | ||
assert_eq!(c.handle_resolvers, ["https://resolver.example"]); | ||
assert_eq!(c.group_founders, ["did:plc:a", "did:plc:b"]); | ||
assert_eq!(c.service_did, "did:web:other.example"); | ||
assert_eq!(c.did_web_scheme, "http"); | ||
crates/group-host/tests/group_config.rs+5−0
| @@ -341,6 +341,11 @@ async fn an_admin_keeps_the_rules() { | ||
"putRule", | ||
json!({"group": did, "title": "Odd", "order": -1}), | ||
), | ||
// A key no record could have. | ||
( | ||
"putRule", | ||
json!({"group": did, "rkey": "a/b", "title": "Odd"}), | ||
), | ||
("putRule", json!({"title": "Odd"})), | ||
("deleteRule", json!({"group": did})), | ||
("deleteRule", json!({"rkey": "x"})), | ||
crates/group-host/tests/group_handle.rsnew+273−0
| @@ -0,0 +1,273 @@ | ||
//! A group's handle on a domain of its own, and its own address back. | ||
| ||
mod common; | ||
| ||
use atproto::plc::Signed; | ||
use axum::Router; | ||
use axum::extract::{Query, State}; | ||
use axum::routing::get as route_get; | ||
use common::groups::*; | ||
use common::spaces::*; | ||
use common::{Running, serve, start}; | ||
use serde_json::{Value as Json, json}; | ||
use std::collections::HashMap; | ||
use std::sync::{Arc, Mutex}; | ||
| ||
const NS: &str = "fyi.opensocial"; | ||
| ||
/// A service resolving handles from what it is told, as one reading DNS. | ||
#[derive(Default)] | ||
struct Names(Mutex<HashMap<String, String>>); | ||
| ||
async fn resolve( | ||
State(names): State<Arc<Names>>, | ||
Query(q): Query<HashMap<String, String>>, | ||
) -> axum::response::Response { | ||
use axum::response::IntoResponse; | ||
let named = names.0.lock().unwrap().get(&q["handle"]).cloned(); | ||
match named { | ||
Some(did) => axum::Json(json!({"did": did})).into_response(), | ||
None => axum::http::StatusCode::BAD_REQUEST.into_response(), | ||
} | ||
} | ||
| ||
/// A host resolving handles by `/.well-known` (which finds nothing under | ||
/// `.test`) and then the service `names` is, and a group Alice started. | ||
async fn here() -> (Running, Arc<Names>, String, [Authority; 3]) { | ||
let names = Arc::new(Names::default()); | ||
let router = Router::new() | ||
.route( | ||
"/xrpc/com.atproto.identity.resolveHandle", | ||
route_get(resolve), | ||
) | ||
.with_state(names.clone()); | ||
let service = serve(router).await; | ||
let resolvers = format!("well-known:http,{service}"); | ||
let h = start(&[("HANDLE_RESOLVERS", resolvers.as_str())], false).await; | ||
let [alice, bob, carol] = people(&h).await; | ||
let did = start_group( | ||
&h, | ||
&alice, | ||
json!({"handle": RIDERS, "displayName": "Riders"}), | ||
) | ||
.await; | ||
(h, names, did, [alice, bob, carol]) | ||
} | ||
| ||
async fn check(h: &Running, who: &Authority, did: &str, handle: &str) -> (u16, Json) { | ||
let lxm = format!("{NS}.checkGroupHandle"); | ||
get( | ||
h, | ||
&lxm, | ||
&format!("group={did}&handle={handle}"), | ||
&[auth(h, who, &lxm)], | ||
) | ||
.await | ||
} | ||
| ||
async fn update(h: &Running, who: &Authority, did: &str, handle: &str) -> (u16, Json) { | ||
let lxm = format!("{NS}.updateGroupHandle"); | ||
post( | ||
h, | ||
&lxm, | ||
&json!({"group": did, "handle": handle}), | ||
&[auth(h, who, &lxm)], | ||
) | ||
.await | ||
} | ||
| ||
fn error(said: &(u16, Json)) -> (u16, &str) { | ||
(said.0, said.1["error"].as_str().unwrap_or_default()) | ||
} | ||
| ||
#[tokio::test] | ||
async fn checks_a_domain_before_it_is_taken() { | ||
let (h, names, did, [alice, _, _]) = here().await; | ||
names | ||
.0 | ||
.lock() | ||
.unwrap() | ||
.insert("riders.test".into(), did.clone()); | ||
names | ||
.0 | ||
.lock() | ||
.unwrap() | ||
.insert("other.test".into(), "did:plc:other".into()); | ||
assert_eq!( | ||
check(&h, &alice, &did, "@Riders.TEST").await, | ||
( | ||
200, | ||
json!({"handle": "riders.test", "ready": true, "did": did}) | ||
) | ||
); | ||
assert_eq!( | ||
check(&h, &alice, &did, "other.test").await, | ||
( | ||
200, | ||
json!({"handle": "other.test", "ready": false, "did": "did:plc:other"}) | ||
) | ||
); | ||
assert_eq!( | ||
check(&h, &alice, &did, "nobody.test").await, | ||
(200, json!({"handle": "nobody.test", "ready": false})) | ||
); | ||
// Its own address is always its own. | ||
assert_eq!(check(&h, &alice, &did, RIDERS).await.1["ready"], true); | ||
} | ||
| ||
#[tokio::test] | ||
async fn takes_a_domain_that_names_it_and_its_address_back() { | ||
let (h, names, did, [alice, _, _]) = here().await; | ||
names | ||
.0 | ||
.lock() | ||
.unwrap() | ||
.insert("riders.test".into(), did.clone()); | ||
assert_eq!( | ||
update(&h, &alice, &did, "riders.test").await, | ||
(200, json!({"handle": "riders.test"})) | ||
); | ||
// The directory names it, then the host, then the relays hear. | ||
let ops = h.plc.ops.lock().unwrap()[&did].clone(); | ||
let Some(Signed::Update { op, .. }) = ops.last() else { | ||
panic!("an update"); | ||
}; | ||
assert_eq!(op.also_known_as, ["at://riders.test"]); | ||
assert_eq!( | ||
h.host.store.account(&did).unwrap().unwrap().handle, | ||
"riders.test" | ||
); | ||
let events = h.host.store.events_after(0, 1000).unwrap(); | ||
let last = atproto::drisl::decode(&events.last().unwrap().body) | ||
.unwrap() | ||
.to_json(); | ||
assert_eq!( | ||
(events.last().unwrap().kind.as_str(), last["handle"].clone()), | ||
("#identity", json!("riders.test")) | ||
); | ||
// Its site stays at its address. | ||
let (_, shown) = get(&h, &format!("{NS}.getGroup"), &format!("group={did}"), &[]).await; | ||
assert_eq!( | ||
( | ||
shown["group"]["handle"].clone(), | ||
shown["group"]["address"].clone() | ||
), | ||
(json!("riders.test"), json!(RIDERS)) | ||
); | ||
| ||
// Asked again, nothing changes. | ||
let before = h.plc.ops.lock().unwrap()[&did].len(); | ||
assert_eq!(update(&h, &alice, &did, "riders.test").await.0, 200); | ||
assert_eq!(h.plc.ops.lock().unwrap()[&did].len(), before); | ||
// And back to its address. | ||
assert_eq!( | ||
update(&h, &alice, &did, RIDERS).await, | ||
(200, json!({"handle": RIDERS})) | ||
); | ||
assert_eq!(h.host.store.account(&did).unwrap().unwrap().handle, RIDERS); | ||
} | ||
| ||
#[tokio::test] | ||
async fn refuses_a_handle_it_cannot_take() { | ||
let (h, names, did, [alice, bob, _]) = here().await; | ||
names | ||
.0 | ||
.lock() | ||
.unwrap() | ||
.insert("other.test".into(), "did:plc:other".into()); | ||
// Another group here takes a domain first. | ||
let theirs = start_group( | ||
&h, | ||
&bob, | ||
json!({"handle": "hikers.groups.test", "displayName": "Hikers"}), | ||
) | ||
.await; | ||
names | ||
.0 | ||
.lock() | ||
.unwrap() | ||
.insert("taken.test".into(), theirs.clone()); | ||
assert_eq!(update(&h, &bob, &theirs, "taken.test").await.0, 200); | ||
| ||
for (handle, refused) in [ | ||
("not a handle", (400, "InvalidHandle")), | ||
// Under the host's domain, only its own address. | ||
("hikers.groups.test", (400, "UnsupportedDomain")), | ||
("groups.test", (400, "UnsupportedDomain")), | ||
("taken.test", (400, "HandleNotAvailable")), | ||
] { | ||
assert_eq!( | ||
error(&check(&h, &alice, &did, handle).await), | ||
refused, | ||
"{handle}" | ||
); | ||
assert_eq!( | ||
error(&update(&h, &alice, &did, handle).await), | ||
refused, | ||
"{handle}" | ||
); | ||
} | ||
assert_eq!( | ||
error(&update(&h, &alice, &did, "other.test").await), | ||
(400, "NotPointing") | ||
); | ||
assert_eq!( | ||
error(&update(&h, &alice, &did, "nobody.test").await), | ||
(400, "NotPointing") | ||
); | ||
// Only one who may configure it. | ||
assert_eq!( | ||
error(&check(&h, &bob, &did, "riders.test").await), | ||
(403, "Forbidden") | ||
); | ||
assert_eq!( | ||
error(&update(&h, &bob, &did, "riders.test").await), | ||
(403, "Forbidden") | ||
); | ||
let lxm = format!("{NS}.updateGroupHandle"); | ||
for body in [json!({"handle": "riders.test"}), json!({"group": did})] { | ||
let said = post(&h, &lxm, &body, &[auth(&h, &alice, &lxm)]).await; | ||
assert_eq!(error(&said), (400, "InvalidRequest")); | ||
} | ||
assert_eq!( | ||
error(&check(&h, &alice, "did:plc:nobody", "riders.test").await), | ||
(400, "GroupNotFound") | ||
); | ||
| ||
// Once the host holds no rotation key for it, it changes nothing. | ||
names | ||
.0 | ||
.lock() | ||
.unwrap() | ||
.insert("riders.test".into(), did.clone()); | ||
let elsewhere = atproto::Keypair::generate(atproto::Curve::K256); | ||
{ | ||
let mut ops = h.plc.ops.lock().unwrap(); | ||
let log = ops.get_mut(&did).unwrap(); | ||
let last = log.last().cloned().unwrap(); | ||
let Signed::Update { op, .. } = &last else { | ||
panic!("an update"); | ||
}; | ||
let mut moved = op.clone(); | ||
moved.rotation_keys = vec![elsewhere.public().did_key()]; | ||
log.push(moved.sign(Some(last.cid()), &h.host.secrets.rotation)); | ||
} | ||
assert_eq!( | ||
error(&update(&h, &alice, &did, "riders.test").await), | ||
(400, "NotController") | ||
); | ||
// Nor once its DID is ended. | ||
{ | ||
let mut ops = h.plc.ops.lock().unwrap(); | ||
let log = ops.get_mut(&did).unwrap(); | ||
let last = log.last().unwrap().cid(); | ||
log.push(atproto::plc::tombstone(last, &elsewhere)); | ||
} | ||
assert_eq!( | ||
error(&update(&h, &alice, &did, "riders.test").await), | ||
(400, "NotController") | ||
); | ||
// Nor when the directory cannot say. | ||
h.plc.ops.lock().unwrap().remove(&did); | ||
assert_eq!(update(&h, &alice, &did, "riders.test").await.0, 500); | ||
} | ||