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

The host moves to a new address, its groups keeping their DIDs

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:host/move-host
crates/group-host/src/lib.rs+25−0
@@ -30,6 +30,7 @@ pub mod index_api;
pub mod lifecycle;
pub mod migration;
pub mod moderation;
pub mod move_host;
pub mod oauth;
pub mod oauth_clients;
pub mod oauth_dpop;
@@ -538,6 +539,30 @@ async fn not_implemented(Path(nsid): Path<String>) -> XrpcError {
XrpcError::not_implemented(&nsid)
}
/// What `group-host` prints for a command it does not know.
pub const USAGE: &str = "usage: group-host serve, as the environment says
group-host move-host --from <old address> [--dry-run]
repoint each account's DID document at the
address the environment names now";
/// What `group-host` does with `args` (without its own name): serves,
/// or moves the host, printing what it did.
pub async fn run(args: &[String], config: Config) -> anyhow::Result<()> {
let args: Vec<&str> = args.iter().map(String::as_str).collect();
match args.as_slice() {
[] => serve(config).await,
["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? {
println!("{line}");
}
Ok(())
}
_ => anyhow::bail!("{USAGE}"),
}
}
/// Serves `config` until the process is told to stop (SIGTERM, or ctrl-c),
/// saying where once it listens: `listening on <address>`. Requests under
/// way when it is told are answered first.
crates/group-host/src/main.rs+2−1
@@ -8,5 +8,6 @@ async fn main() -> anyhow::Result<()> {
tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()),
)
.init();
group_host::serve(group_host::config::Config::from_env()?).await
let args: Vec<String> = std::env::args().skip(1).collect();
group_host::run(&args, group_host::config::Config::from_env()?).await
}
crates/group-host/src/move_host.rsnew+130−0
@@ -0,0 +1,130 @@
//! The host moved to a new address: the URL it answers at, and its
//! did:web. The groups keep their DIDs; what names the host changes: each
//! account's DID document, every service at the old address pointed at
//! the new one, signed with the host's rotation key, and the relays told
//! who each account is now.
//!
//! `group-host move-host --from <old address> [--dry-run]`, once, with the
//! host stopped and its environment naming the new address (`PUBLIC_URL`,
//! `SERVICE_DID`). Run again, it finds nothing left to repoint, and tells
//! the relays again of each account at the new address.
//!
//! As the prototype's `scripts/move-host.ts`. This host keeps no managing
//! app on its spaces and no PDS per group, so only the documents change.
use crate::Host;
use crate::repo::identity;
use crate::store::Store;
use anyhow::{Result, bail};
use atproto::plc::Signed;
/// What became of an account's DID document.
#[derive(Debug, Clone, PartialEq)]
pub enum Moved {
/// Its services named here: those that were at the old address.
Repointed(Vec<String>),
/// Already at the new address, or never at the old.
Current,
/// Its DID is ended.
Ended,
/// This host holds no rotation key to it any more.
NotOurs,
}
impl Store {
/// Keeps `events` of `did`'s, for the relays, with nothing else.
pub fn tell(&self, did: &str, events: &[crate::store::Event]) -> Result<()> {
let mut conn = self.conn();
let tx = conn.transaction()?;
crate::store::sequence(&tx, did, events)?;
tx.commit()?;
Ok(())
}
}
impl Host {
/// `did`'s document, every service at `from` pointed at this host's
/// address, unless `dry_run`.
async fn repoint(&self, did: &str, handle: &str, from: &str, dry_run: bool) -> Result<Moved> {
let to = self.config.public_url.trim_end_matches('/');
let last = self.plc.last_op(did).await?;
let Signed::Update { op, .. } = &last else {
return Ok(Moved::Ended);
};
let at = |endpoint: &str, here: &str| endpoint.trim_end_matches('/') == here;
let stale: Vec<String> = op
.services
.iter()
.filter(|(_, s)| at(&s.endpoint, from))
.map(|(id, _)| id.clone())
.collect();
if stale.is_empty() {
let here = op.services.values().any(|s| at(&s.endpoint, to));
if here && !dry_run {
self.store.tell(did, &[identity(did, handle)])?;
}
return Ok(Moved::Current);
}
let ours = self.secrets.rotation.public().did_key();
if !op.rotation_keys.contains(&ours) {
return Ok(Moved::NotOurs);
}
if !dry_run {
let mut next = op.clone();
for id in &stale {
let service = next.services.get_mut(id).expect("a service it has");
service.endpoint = to.to_string();
}
let signed = next.sign(Some(last.cid()), &self.secrets.rotation);
self.plc.publish(did, &signed).await?;
self.store.tell(did, &[identity(did, handle)])?;
}
Ok(Moved::Repointed(stale))
}
}
/// 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>> {
let from = from.trim_end_matches('/');
let to = host.config.public_url.trim_end_matches('/');
if from == to {
bail!("the environment still names {from}: set PUBLIC_URL to the new address first");
}
let mut said = vec![format!(
"{from} → {to} ({}){}",
host.config.service_did,
if dry_run {
": a dry run, nothing is written"
} else {
""
}
)];
let (mut cursor, mut seen, mut moved) = (None::<String>, 0, 0);
loop {
let page = host.store.accounts(cursor.as_deref(), 100)?;
let Some((last, _)) = page.last() else {
break;
};
cursor = Some(last.clone());
for (did, _) in &page {
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? {
Moved::Repointed(ids) => {
moved += 1;
said.push(format!("{name}: {} → {to}", ids.join(", ")));
}
Moved::Current => {}
Moved::Ended => said.push(format!("{name}: its DID is ended, skipped")),
Moved::NotOurs => said.push(format!(
"{name}: this host holds no rotation key to it, skipped"
)),
}
}
}
let done = if dry_run { "to repoint" } else { "repointed" };
said.push(format!("{moved} of {seen} DID documents {done}"));
Ok(said)
}
crates/group-host/src/store.rs+1−1
@@ -552,7 +552,7 @@ fn linked(tx: &rusqlite::Transaction, did: &str, collection: &str, rkey: &str) -
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
fn sequence(tx: &rusqlite::Transaction, did: &str, events: &[Event]) -> Result<()> {
pub(crate) fn sequence(tx: &rusqlite::Transaction, did: &str, events: &[Event]) -> Result<()> {
for e in events {
let added = tx.execute(SEQUENCE, params![did, e.kind, e.body]);
added?;
crates/group-host/tests/move_host.rsnew+121−0
@@ -0,0 +1,121 @@
//! The host moved to a new address: each account's DID document pointed
//! there, and nothing it may not change.
mod common;
use atproto::plc::{Signed, tombstone};
use atproto::{Curve, Keypair};
use common::groups::*;
use common::spaces::*;
use common::{Running, start};
use group_host::Host;
use group_host::config::Config;
use group_host::move_host::move_host;
use serde_json::json;
use std::collections::HashMap;
/// The host `h` is, opened again as its environment names `url`.
fn at(h: &Running, url: &str) -> Host {
let env: HashMap<&str, String> = HashMap::from([
("DATA_DIR", h.data.path().to_str().unwrap().to_string()),
("PLC_URL", h.host.config.plc_url.clone()),
("HANDLE_DOMAIN", ".groups.test".to_string()),
("PUBLIC_URL", url.to_string()),
]);
Host::open(Config::from(|k| env.get(k).cloned()).unwrap()).unwrap()
}
async fn pds(h: &Running, did: &str) -> String {
let Signed::Update { op, .. } = h.host.plc.last_op(did).await.unwrap() else {
panic!("ended")
};
op.services["atproto_pds"].endpoint.clone()
}
async fn group(h: &Running, handle: &str) -> String {
let [alice, ..] = people(h).await;
start_group(
h,
&alice,
json!({"handle": handle, "displayName": "A group"}),
)
.await
}
#[tokio::test]
async fn points_each_accounts_document_at_the_new_address() {
let h = start(&[], false).await;
let riders = group(&h, RIDERS).await;
let moved = at(&h, "https://new.test");
// A dry run says what it would do, and does nothing.
let said = move_host(&moved, "https://host.test/", true).await.unwrap();
assert!(said[0].contains("a dry run"), "{said:?}");
assert_eq!(said.last().unwrap(), "1 of 1 DID documents to repoint");
assert_eq!(pds(&h, &riders).await, "https://host.test");
let said = move_host(&moved, "https://host.test", false).await.unwrap();
assert_eq!(
said[1..],
[
format!("{RIDERS}: atproto_pds → https://new.test"),
"1 of 1 DID documents repointed".to_string()
]
);
assert_eq!(pds(&h, &riders).await, "https://new.test");
// Again, nothing is left to repoint.
let said = move_host(&moved, "https://host.test", false).await.unwrap();
assert_eq!(said.last().unwrap(), "0 of 1 DID documents repointed");
let said = move_host(&moved, "https://host.test", true).await.unwrap();
assert_eq!(said.last().unwrap(), "0 of 1 DID documents to repoint");
}
#[tokio::test]
async fn skips_an_ended_did_and_one_a_steward_took() {
let h = start(&[], false).await;
let ended = group(&h, "ended.groups.test").await;
let last = h.host.plc.last_op(&ended).await.unwrap();
h.host
.plc
.publish(&ended, &tombstone(last.cid(), &h.host.secrets.rotation))
.await
.unwrap();
let taken = group(&h, "taken.groups.test").await;
let steward = Keypair::generate(Curve::K256);
let Signed::Update { op, .. } = h.host.plc.last_op(&taken).await.unwrap() else {
panic!()
};
let last = h.host.plc.last_op(&taken).await.unwrap();
let mut next = op.clone();
next.rotation_keys = vec![steward.public().did_key()];
h.host
.plc
.publish(
&taken,
&next.sign(Some(last.cid()), &h.host.secrets.rotation),
)
.await
.unwrap();
let said = move_host(&at(&h, "https://new.test"), "https://host.test", false)
.await
.unwrap();
assert!(
said.contains(&"ended.groups.test: its DID is ended, skipped".to_string()),
"{said:?}"
);
assert!(said.contains(
&"taken.groups.test: this host holds no rotation key to it, skipped".to_string()
));
assert_eq!(said.last().unwrap(), "0 of 2 DID documents repointed");
}
#[tokio::test]
async fn refuses_to_move_to_where_it_is() {
let h = start(&[], false).await;
let said = move_host(&h.host, "https://host.test/", false).await;
assert!(
said.unwrap_err()
.to_string()
.contains("still names https://host.test")
);
}
crates/group-host/tests/serve.rs+27−0
@@ -71,3 +71,30 @@ fn refuses_a_bad_environment() {
assert!(!out.status.success());
assert!(String::from_utf8_lossy(&out.stderr).contains("PORT is no port: eighty"));
}
#[test]
fn moves_the_host_from_an_old_address() {
let data = tempfile::tempdir().unwrap();
let run = |args: &[&str]| {
Command::new(env!("CARGO_BIN_EXE_group-host"))
.args(args)
.env("DATA_DIR", data.path())
.env("PUBLIC_URL", "https://new.test")
.env("RUST_LOG", "off")
.output()
.unwrap()
};
let out = run(&["move-host", "--from", "https://old.test", "--dry-run"]);
assert!(out.status.success());
let said = String::from_utf8_lossy(&out.stdout);
assert!(said.contains("0 of 0 DID documents to repoint"), "{said}");
for wrong in [
&["move-host"][..],
&["move-host", "--from", "x", "--wet"],
&["nonsense"],
] {
let out = run(wrong);
assert!(!out.status.success());
assert!(String::from_utf8_lossy(&out.stderr).contains("usage: group-host"));
}
}
docs/design/moving.md+23−0
@@ -105,3 +105,26 @@ DID names this host, the network reads the account here.
and its repos in others' in the space alpha's archives, is not here
yet: it waits for the alpha to publish its meta archive, which the
version the prototype builds against does not have.
# Moving the host
The host itself moves to a new address, the URL it answers at and its
did:web, and its groups keep their DIDs (`move_host.rs`). With the host
stopped and its environment naming the new address (`PUBLIC_URL`,
`SERVICE_DID`), `group-host move-host --from <old address>` points every
service each account's DID document names at the old address at the new
one, signed with the host's rotation key, and tells the relays who each
account is. It skips, and says so, an account whose DID is ended and one
this host holds no rotation key to any more (a steward took it).
`--dry-run` says what it would do.
Run again, it finds nothing left to repoint, and tells the relays again
of each account at the new address: a relay that starts reading the host
after the first run hears of them so.
## From the prototype
- This host keeps no managing app on its spaces and no PDS per group, so
only the DID documents change.
- Sessions, app passwords' among them, are found by their hash, not
their audience, so they go on working at the new address.
docs/design/README.md+3−2
@@ -124,8 +124,9 @@ says otherwise.
[recovery](recovery.md)); moving a group to another host
(`migration.rs`; done, see [moving](moving.md)); an account on
another server becoming a group (`import.rs`; done, but for its
spaces, see [moving](moving.md#an-account-becoming-a-group)); then
moving the host itself:
spaces, see [moving](moving.md#an-account-becoming-a-group)); and
moving the host itself (`move_host.rs`; done, see
[moving](moving.md#moving-the-host)):
`methods/{moderation,recovery,importAccount,migration}.ts`,
`hostLabels.ts`, `scripts/move-host.ts`.
9. **MCP and the command.** The MCP tools over what steps 4 to 8 brought,
docs/reference/cli.md+10−1
@@ -1,4 +1,13 @@
# The command and the recipes
# The commands and the recipes
## `group-host`
| Command | What it does |
| --- | --- |
| none | serves, as the environment says ([config](config.md)) |
| `move-host --from <old address> [--dry-run]` | points each account's DID document at the address the environment names now ([moving the host](../design/moving.md#moving-the-host)) |
Anything else fails with its usage.
## `opensocial`