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

An account on another server moves here to become a group

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:host/import
crates/group-host/src/group.rs+46−23
@@ -99,6 +99,36 @@ fn audience(roles: &[String]) -> Value {
roles.iter().map(|r| json!({ "role": r })).collect()
}
/// How a new group lets people in, who reads its meta, and who runs it.
struct Shape {
join: &'static str,
readers: Vec<String>,
stewards: Vec<String>,
}
/// What `new` asks of a group's first day, checked.
fn shape(new: &NewGroup) -> Result<Shape, XrpcError> {
let join = join_policy(new.join_policy.as_deref())?;
let readers = new
.meta_readable_by
.clone()
.unwrap_or_else(|| vec!["public".into()]);
let mut stewards = vec![new.founder.clone()];
for s in &new.stewards {
if !atproto::syntax::is_did(s) {
return Err(invalid(format!("steward {s} is no DID")));
}
if !stewards.contains(s) {
stewards.push(s.clone());
}
}
Ok(Shape {
join,
readers,
stewards,
})
}
impl Host {
/// Whether this host starts groups for `did`: anyone, unless
/// `GROUP_FOUNDERS` names who.
@@ -117,20 +147,7 @@ impl Host {
"this host is not starting groups for you",
));
}
let join = join_policy(new.join_policy.as_deref())?;
let readers = new
.meta_readable_by
.clone()
.unwrap_or_else(|| vec!["public".into()]);
let mut stewards = vec![new.founder.clone()];
for s in &new.stewards {
if !atproto::syntax::is_did(s) {
return Err(invalid(format!("steward {s} is no DID")));
}
if !stewards.contains(s) {
stewards.push(s.clone());
}
}
let shape = shape(new)?;
let did = self.create_account(&new.handle).await.map_err(|e| {
if e.error == "HandleNotAvailable" {
XrpcError::new(e.status, "HandleTaken", e.message)
@@ -140,21 +157,27 @@ impl Host {
})?;
// 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;
let made = self.set_up(&did, new, &shape).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> {
/// Makes `did`, an account here already and switched on, the group
/// `new` asks for: its two spaces and what they hold from its first
/// day, and its declaration if anyone may read its meta.
pub async fn make_group(&self, did: &str, new: &NewGroup) -> Result<Made, XrpcError> {
let shape = shape(new)?;
self.set_up(did, new, &shape).await
}
async fn set_up(&self, did: &str, new: &NewGroup, shape: &Shape) -> Result<Made, XrpcError> {
let Shape {
join,
readers,
stewards,
} = shape;
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)?;
crates/group-host/src/group_api.rs+11−7
@@ -18,6 +18,16 @@ use std::sync::Arc;
type Answer = Result<Json<Value>, XrpcError>;
/// Whether a token for `aud` is for this host: its DID, or one of its
/// services, as an OAuth app's rpc scope names it.
pub(crate) fn for_host(host: &Host, aud: &str) -> bool {
let ours = &host.config.service_did;
aud == ours
|| aud
.strip_prefix(ours.as_str())
.is_some_and(|f| f.starts_with('#'))
}
/// Who calls `lxm`: by their service auth for this host, or else the
/// console's session cookie; none without either.
pub(crate) async fn caller(
@@ -30,13 +40,7 @@ pub(crate) async fn caller(
return host.console_caller(headers).map_err(XrpcError::internal);
}
let claims = service_caller(host, headers, lxm).await?;
let ours = &host.config.service_did;
let for_us = claims.aud == *ours
|| claims
.aud
.strip_prefix(ours.as_str())
.is_some_and(|f| f.starts_with('#'));
if !for_us {
if !for_host(host, &claims.aud) {
return Err(unauthorized(
"BadJwtAudience",
format!("a token for {}, not this host", claims.aud),
crates/group-host/src/group_handle.rs+5−12
@@ -15,11 +15,10 @@ 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::repo::identity;
use crate::xrpc::XrpcError;
use atproto::plc::Signed;
use atproto::{Value as Drisl, syntax};
use atproto::syntax;
use axum::Json;
use axum::extract::{Query, State};
use axum::http::{HeaderMap, StatusCode};
@@ -146,16 +145,10 @@ pub async fn update_group_handle(
.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]);
let set = host
.store
.set_handle(group, &handle, &[identity(group, &handle)]);
set.map_err(XrpcError::internal)?;
host.announce();
Ok(Json(json!({ "handle": handle })))
crates/group-host/src/import.rsnew+548−0
548 lines changed: not loaded until asked for.
crates/group-host/src/lib.rs+13−0
@@ -24,6 +24,7 @@ pub mod group_members;
pub mod group_spaces;
pub mod group_tokens;
pub mod identity;
pub mod import;
pub mod index;
pub mod index_api;
pub mod lifecycle;
@@ -415,6 +416,18 @@ pub fn router(host: Arc<Host>) -> Router {
"/xrpc/fyi.opensocial.migrateActivate",
post(migration::migrate_activate),
)
.route(
"/xrpc/fyi.opensocial.checkImport",
get(import::check_import),
)
.route(
"/xrpc/fyi.opensocial.importAccount",
post(import::import_account),
)
.route(
"/xrpc/fyi.opensocial.completeImport",
post(import::complete_import),
)
.route("/oauth/authorize", get(oauth::authorize))
.route(
"/console/client-metadata.json",
crates/group-host/src/lifecycle.rs+9−0
@@ -80,6 +80,15 @@ impl Host {
Ok(done)
}
/// Switches on `did`, arrived from another server as `handle`: the
/// relays told who it is now, and that it is on.
pub fn activate_arrived(&self, did: &str, handle: &str) -> Result<bool> {
let told = [crate::repo::identity(did, handle), status(did, None)];
let done = self.store.activate(did, &told)?;
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.
crates/group-host/src/migration.rs+101−31
@@ -77,6 +77,13 @@ impl Store {
Ok(())
}
/// `group`'s export token, ended.
pub fn end_export(&self, group: &str) -> Result<()> {
let sql = "DELETE FROM migration_export WHERE did = ?1";
self.conn().execute(sql, [group])?;
Ok(())
}
/// Whether `hash` is `group`'s export token, unexpired at `now`.
pub fn may_export(&self, group: &str, hash: &str, now: i64) -> Result<bool> {
let sql =
@@ -292,7 +299,11 @@ fn create(path: &str, value: &[u8]) -> Option<Write> {
/// The records of a repo's CAR, once its commit is `group`'s, signed by
/// `key`, and its tree and records are whole.
fn repo_writes(bytes: &[u8], group: &str, key: &atproto::PublicKey) -> Option<Vec<Write>> {
pub(crate) fn repo_writes(
bytes: &[u8],
group: &str,
key: &atproto::PublicKey,
) -> Option<Vec<Write>> {
let repo = car::read(bytes).ok()?;
let commit = atproto::Commit::from_bytes(repo.blocks.get(repo.roots.first()?)?).ok()?;
(commit.did == group && commit.verify(key)).then_some(())?;
@@ -364,6 +375,79 @@ impl Host {
}
}
/// A new account here for `did`, at `address`, known by `handle`, with
/// keys of its own, as one arriving from another server is until the
/// directory names this host: its records follow it in.
pub(crate) async fn take_in(
host: &Host,
did: &str,
handle: &str,
address: &str,
) -> Result<Account, XrpcError> {
let account = Account {
did: did.into(),
handle: address.into(),
signing: Keypair::generate(Curve::K256),
kem: Keypair::generate(Curve::P256),
};
let empty = host.sign(&account, &Tree::build(&BTreeMap::new()));
let made = host
.store
.create_account(&account, &empty, now_millis(), &[]);
if !made.map_err(XrpcError::internal)? {
return Err(refused(
"HandleNotAvailable",
format!("{address} is taken here"),
));
}
if handle != address {
let named = host.store.set_handle(did, handle, &[]);
if named.is_err() {
host.forget(did);
return Err(refused(
"HandleNotAvailable",
format!("{handle} is taken here"),
));
}
}
Ok(Account {
handle: handle.into(),
..account
})
}
/// What an account's PLC operation should name for it to live here, as
/// com.atproto.identity.getRecommendedDidCredentials answers it.
pub(crate) fn creds(host: &Host, account: &Account) -> Value {
json!({
"rotationKeys": [host.secrets.rotation.public().did_key()],
"alsoKnownAs": [format!("at://{}", account.handle)],
"verificationMethods": {
"atproto": account.signing.public().did_key(),
"atproto_kem": account.kem.public().did_key(),
},
"services": {"atproto_pds": {"type": "AtprotoPersonalDataServer", "endpoint": host.config.public_url}},
})
}
impl Host {
/// Whether `handle` names `did`, as the resolvers this host asks say.
pub(crate) async fn names(&self, handle: &str, did: &str) -> bool {
let resolvers = &self.config.handle_resolvers;
let named = self.identity.resolve_handle(handle, resolvers).await;
named.as_deref() == Some(did)
}
/// An account taken in part way, and its files, gone.
pub(crate) fn forget(&self, did: &str) {
let gone = self.store.delete_account(did, &[]);
let forgotten = gone.is_ok();
tracing::info!(did, forgotten, "an account taken in part way");
let blobs = gone.unwrap_or_default();
self.remove_blobs(blobs.iter().map(|cid| (did, cid)));
}
}
/// Step 2, at the destination: the group taken in, switched off; what
/// the PLC operation should name.
pub async fn migrate_receive(
@@ -409,7 +493,14 @@ pub async fn migrate_receive(
.as_str()
.ok_or_else(|| invalid("snapshot.handle is required"))?;
let domain = &host.config.handle_domain;
let (handle, _) = handle_here(handle, snapshot["address"].as_str(), domain);
let (handle, here) = handle_here(handle, snapshot["address"].as_str(), domain);
// A domain of its own comes along only while it still names the group:
// the snapshot's word for it is not enough.
let handle = if handle == here || host.names(&handle, group).await {
handle
} else {
here.clone()
};
// Its public repo, checked against the group's key.
let (pinned, at) = host
@@ -426,43 +517,19 @@ pub async fn migrate_receive(
let writes = repo_writes(&bytes, group, &key);
let writes = writes.ok_or(source("a repo that is not the group's, signed and whole"))?;
// The account, with keys of its own here, switched off.
let account = Account {
did: group.into(),
handle: handle.clone(),
signing: Keypair::generate(Curve::K256),
kem: Keypair::generate(Curve::P256),
};
let empty = host.sign(&account, &Tree::build(&BTreeMap::new()));
let made = host
.store
.create_account(&account, &empty, now_millis(), &[]);
if !made.map_err(XrpcError::internal)? {
return Err(refused(
"HandleNotAvailable",
format!("{handle} is taken here"),
));
}
let account = take_in(&host, group, &handle, &here).await?;
let received = receive(&host, group, &me, &pds, token, snapshot, writes).await;
let counts = match received {
Ok(counts) => counts,
Err(e) => {
// Nothing half taken in stays.
let gone = host.store.delete_account(group, &[]);
tracing::warn!(group, ?gone, error = ?e, "a group not taken in");
host.forget(group);
tracing::warn!(group, error = ?e, "a group not taken in");
return Err(e);
}
};
tracing::info!(group, from = pds, "a group taken in, switched off");
let creds = json!({
"rotationKeys": [host.secrets.rotation.public().did_key()],
"alsoKnownAs": [format!("at://{handle}")],
"verificationMethods": {
"atproto": account.signing.public().did_key(),
"atproto_kem": account.kem.public().did_key(),
},
"services": {"atproto_pds": {"type": "AtprotoPersonalDataServer", "endpoint": host.config.public_url}},
});
let creds = creds(&host, &account);
Ok(Json(
json!({"recommendedCreds": creds, "records": counts.0, "blobs": counts.1, "spaces": counts.2}),
))
@@ -644,6 +711,8 @@ pub async fn migrate_complete(
.map_err(XrpcError::internal)?;
let off = host.store.deactivate(&group, now_millis(), &me, &[], &[]);
off.map_err(XrpcError::internal)?;
// Handed over, there is nothing more to pull.
host.store.end_export(&group).map_err(XrpcError::internal)?;
host.record(&group, &me, None, &format!("moved the group to {endpoint}"))
.map_err(XrpcError::internal)?;
Ok(Json(json!({ "movedTo": endpoint })))
@@ -673,7 +742,8 @@ pub async fn migrate_activate(
"the directory does not name this host for the group yet",
));
}
host.activate_account(&group).map_err(XrpcError::internal)?;
let on = host.activate_arrived(&group, &account.handle);
on.map_err(XrpcError::internal)?;
let spaces = host.store.spaces_of(&group).map_err(XrpcError::internal)?;
for space in &spaces {
host.reindex(space);
crates/group-host/src/repo.rs+28−15
@@ -88,6 +88,9 @@ pub struct Asked<'a> {
/// Made while the account is switched off, as one received from
/// another host is until the directory names this one.
pub off: bool,
/// Copied whole from another server: a record may hold a file that did
/// not come with it, as one whose file was deleted does.
pub copied: bool,
}
fn invalid_swap(message: impl Into<String>) -> XrpcError {
@@ -234,14 +237,7 @@ impl Host {
let head = self.sign(&account, &tree);
let at = Value::String(iso(now_millis()));
let events = [
event(
"#identity",
[
("did", Value::String(did.clone())),
("handle", Value::String(handle.into())),
("time", at.clone()),
],
),
identity(&did, handle),
event(
"#account",
[
@@ -334,7 +330,8 @@ impl Host {
let mut new_blobs = Vec::new();
let mut blocks = BTreeMap::new();
for write in writes {
let Checked { path, put, blobs } = self.check(&account.did, write, &paths)?;
let Checked { path, put, blobs } =
self.check(&account.did, write, &paths, asked.copied)?;
new_blobs.extend(blobs.iter().copied());
let prev = match &put {
Some((cid, bytes)) => {
@@ -389,12 +386,13 @@ impl Host {
/// `write` to `did`'s records, now at `paths`, checked: its path is a
/// record's, a create's free and an update's or delete's taken, its
/// record one by the data model of its collection's `$type`, and each
/// blob it references uploaded to `did`.
/// blob it references uploaded to `did`, or, `copied`, left out.
pub(crate) fn check(
&self,
did: &str,
write: &Write,
paths: &BTreeMap<String, Cid>,
copied: bool,
) -> Result<Checked, XrpcError> {
let (collection, rkey) = write.path();
let (value, exists) = match write {
@@ -418,11 +416,13 @@ impl Host {
}
let put = value.map(|v| record(collection, v)).transpose()?;
// A record may reference only blobs uploaded to its account.
let blobs = value.map(blob_refs).unwrap_or_default();
for cid in &blobs {
let blob = self.store.blob(did, cid).map_err(XrpcError::internal)?;
if blob.is_none() {
return Err(invalid(format!("blob {cid} was not uploaded to {did}")));
let mut blobs = Vec::new();
for cid in value.map(blob_refs).unwrap_or_default() {
let blob = self.store.blob(did, &cid).map_err(XrpcError::internal)?;
match blob {
Some(_) => blobs.push(cid),
None if copied => {}
None => return Err(invalid(format!("blob {cid} was not uploaded to {did}"))),
}
}
Ok(Checked { path, put, blobs })
@@ -483,6 +483,19 @@ impl Host {
/// How long between telling the relays of news.
const CRAWL_EVERY: std::time::Duration = std::time::Duration::from_secs(20 * 60);
/// An `#identity` event: `did` known as `handle`, for the relays to
/// read its document afresh.
pub(crate) fn identity(did: &str, handle: &str) -> Event {
event(
"#identity",
[
("did", Value::String(did.into())),
("handle", Value::String(handle.into())),
("time", Value::String(iso(now_millis()))),
],
)
}
/// An event of `kind` with the fields given.
pub(crate) fn event<const N: usize>(kind: &'static str, fields: [(&str, Value); N]) -> Event {
let map = fields
crates/group-host/src/space.rs+1−1
@@ -116,7 +116,7 @@ impl Host {
}
let mut changes = Vec::new();
for write in &writes {
let Checked { path, put, blobs } = self.check(&account.did, write, &paths)?;
let Checked { path, put, blobs } = self.check(&account.did, write, &paths, false)?;
let (collection, rkey) = write.path();
let prev = match &put {
Some((cid, _)) => paths.insert(path, *cid),
crates/group-host/src/store.rs+10−0
@@ -334,6 +334,15 @@ pub const MIGRATIONS: &[&str] = &[
token_hash TEXT NOT NULL,
expires_at INTEGER NOT NULL
);
",
"
CREATE TABLE account_import (
did TEXT PRIMARY KEY REFERENCES account (did),
founder TEXT NOT NULL,
display_name TEXT NOT NULL,
description TEXT,
created_at INTEGER NOT NULL
);
",
];
@@ -452,6 +461,7 @@ const DEACTIVATION: &str = "SELECT at, by, stewards FROM deactivation WHERE did
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 account_import WHERE did = ?1",
"DELETE FROM migration_export WHERE did = ?1",
"DELETE FROM recovery_key WHERE grp = ?1",
"DELETE FROM mod_event WHERE grp = ?1",
crates/group-host/src/token_writes.rs+1−1
@@ -343,7 +343,7 @@ async fn put_or_delete(
swap_record,
put: true,
allow: Some(&allow),
off: false,
..Asked::default()
};
// A put of what is there, or a delete of what is not, makes no commit.
let committed = host.write_asked(group, std::slice::from_ref(&write), &asked)?;
crates/group-host/tests/import.rsnew+816−0
816 lines changed: not loaded until asked for.
crates/group-host/tests/migration.rs+107−3
docs/design/moving.md+55−4
docs/design/README.md+4−2