chadtmiller.com/group-host
atmosphere group host
0
0
host: groups' accounts and repos, as signed commits a PDS serves
crates/group-host/src/api.rsnew+211−0
| @@ -0,0 +1,211 @@ | ||
//! The `com.atproto.*` methods a PDS answers for its accounts' repos, and | ||
//! the well-known documents that name the host and its groups. | ||
| ||
use crate::Host; | ||
use crate::store::Record; | ||
use crate::xrpc::XrpcError; | ||
use atproto::drisl; | ||
use axum::Json; | ||
use axum::extract::{Query, State}; | ||
use axum::http::{HeaderMap, StatusCode, header}; | ||
use axum::response::{IntoResponse, Response}; | ||
use serde_json::{Value, json}; | ||
use std::collections::HashMap; | ||
use std::sync::Arc; | ||
| ||
type Params = Query<HashMap<String, String>>; | ||
type Answer = Result<Json<Value>, XrpcError>; | ||
| ||
fn invalid(message: impl Into<String>) -> XrpcError { | ||
XrpcError::new(StatusCode::BAD_REQUEST, "InvalidRequest", message) | ||
} | ||
| ||
/// The parameter `name`, which the method needs. | ||
fn param<'a>(params: &'a HashMap<String, String>, name: &str) -> Result<&'a str, XrpcError> { | ||
params | ||
.get(name) | ||
.map(String::as_str) | ||
.ok_or_else(|| invalid(format!("{name} is required"))) | ||
} | ||
| ||
/// The page size `limit` asks for: 1 to 100, 50 unless it says. | ||
fn limit(params: &HashMap<String, String>) -> Result<u32, XrpcError> { | ||
match params.get("limit") { | ||
None => Ok(50), | ||
Some(l) => l | ||
.parse() | ||
.ok() | ||
.filter(|n| (1..=100).contains(n)) | ||
.ok_or_else(|| invalid("limit is 1 to 100")), | ||
} | ||
} | ||
| ||
fn repo_not_found(repo: &str) -> XrpcError { | ||
XrpcError::new( | ||
StatusCode::BAD_REQUEST, | ||
"RepoNotFound", | ||
format!("no repo {repo} here"), | ||
) | ||
} | ||
| ||
/// The DID of the account `repo` names, by DID or handle. | ||
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)) | ||
} | ||
| ||
fn view(did: &str, r: &Record) -> Value { | ||
let value = drisl::decode(&r.value) | ||
.expect("a record the host wrote") | ||
.to_json(); | ||
json!({"uri": format!("at://{did}/{}/{}", r.collection, r.rkey), "cid": r.cid.to_string(), "value": value}) | ||
} | ||
| ||
pub async fn describe_repo(State(host): State<Arc<Host>>, Query(p): Params) -> Answer { | ||
let repo = param(&p, "repo")?; | ||
let account = host.store.account(repo).map_err(XrpcError::internal)?; | ||
let account = account.ok_or_else(|| repo_not_found(repo))?; | ||
let doc = host | ||
.plc | ||
.document(&account.did) | ||
.await | ||
.map_err(XrpcError::internal)?; | ||
let collections = host | ||
.store | ||
.collections(&account.did) | ||
.map_err(XrpcError::internal)?; | ||
Ok(Json(json!({ | ||
"handle": account.handle, | ||
"did": account.did, | ||
"didDoc": doc, | ||
"collections": collections, | ||
"handleIsCorrect": true, | ||
}))) | ||
} | ||
| ||
pub async fn get_record(State(host): State<Arc<Host>>, Query(p): Params) -> Answer { | ||
let did = did_of(&host, param(&p, "repo")?)?; | ||
let (collection, rkey) = (param(&p, "collection")?, param(&p, "rkey")?); | ||
let found = host | ||
.store | ||
.record(&did, collection, rkey) | ||
.map_err(XrpcError::internal)?; | ||
// A `cid` asks for that version, which is only ever the one here. | ||
let found = found.filter(|r| p.get("cid").is_none_or(|c| *c == r.cid.to_string())); | ||
let not_found = || { | ||
XrpcError::new( | ||
StatusCode::BAD_REQUEST, | ||
"RecordNotFound", | ||
format!("no record {collection}/{rkey}"), | ||
) | ||
}; | ||
Ok(Json(view(&did, &found.ok_or_else(not_found)?))) | ||
} | ||
| ||
pub async fn list_records(State(host): State<Arc<Host>>, Query(p): Params) -> Answer { | ||
let did = did_of(&host, param(&p, "repo")?)?; | ||
let (collection, limit) = (param(&p, "collection")?, limit(&p)?); | ||
let reverse = p.get("reverse").is_some_and(|r| r == "true"); | ||
let cursor = p.get("cursor").map(String::as_str); | ||
let records = host | ||
.store | ||
.list(&did, collection, cursor, limit, reverse) | ||
.map_err(XrpcError::internal)?; | ||
// A full page may have more after it. | ||
let cursor = records | ||
.last() | ||
.filter(|_| records.len() == limit as usize) | ||
.map(|r| r.rkey.clone()); | ||
let records: Vec<Value> = records.iter().map(|r| view(&did, r)).collect(); | ||
Ok(Json(json!({"records": records, "cursor": cursor}))) | ||
} | ||
| ||
pub async fn get_repo( | ||
State(host): State<Arc<Host>>, | ||
Query(p): Params, | ||
) -> Result<Response, XrpcError> { | ||
let did = 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): Params) -> Answer { | ||
let did = param(&p, "did")?; | ||
let head = host.store.head(did).map_err(XrpcError::internal)?; | ||
let head = head.ok_or_else(|| repo_not_found(did))?; | ||
Ok(Json(json!({"cid": head.cid.to_string(), "rev": head.rev}))) | ||
} | ||
| ||
pub async fn list_repos(State(host): State<Arc<Host>>, Query(p): Params) -> Answer { | ||
let limit = limit(&p)?; | ||
let repos = host | ||
.store | ||
.accounts(p.get("cursor").map(String::as_str), limit) | ||
.map_err(XrpcError::internal)?; | ||
let cursor = repos | ||
.last() | ||
.filter(|_| repos.len() == limit as usize) | ||
.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})) | ||
.collect(); | ||
Ok(Json(json!({"repos": repos, "cursor": cursor}))) | ||
} | ||
| ||
pub async fn resolve_handle(State(host): State<Arc<Host>>, Query(p): Params) -> Answer { | ||
let handle = param(&p, "handle")?.to_ascii_lowercase(); | ||
let account = host.store.account(&handle).map_err(XrpcError::internal)?; | ||
let account = account.filter(|a| a.handle == handle); | ||
let not_found = || { | ||
XrpcError::new( | ||
StatusCode::BAD_REQUEST, | ||
"HandleNotFound", | ||
format!("no account {handle} here"), | ||
) | ||
}; | ||
Ok(Json(json!({"did": account.ok_or_else(not_found)?.did}))) | ||
} | ||
| ||
/// The host's own DID document, when its DID is a `did:web` of its address. | ||
pub async fn did_json(State(host): State<Arc<Host>>) -> Result<Json<Value>, StatusCode> { | ||
let did = &host.config.service_did; | ||
if !did.starts_with("did:web:") { | ||
return Err(StatusCode::NOT_FOUND); | ||
} | ||
let services = [( | ||
"#atproto_pds", | ||
"AtprotoPersonalDataServer", | ||
host.config.public_url.as_str(), | ||
)]; | ||
Ok(Json(atproto::did::service_document( | ||
did, | ||
&host.secrets.signing.public(), | ||
&services, | ||
))) | ||
} | ||
| ||
/// A group's handle, as its own address answers it: the DID its account is. | ||
pub async fn atproto_did( | ||
State(host): State<Arc<Host>>, | ||
headers: HeaderMap, | ||
) -> Result<String, StatusCode> { | ||
let asked = headers | ||
.get(header::HOST) | ||
.and_then(|h| h.to_str().ok()) | ||
.unwrap_or_default(); | ||
let handle = asked | ||
.split(':') | ||
.next() | ||
.unwrap_or_default() | ||
.to_ascii_lowercase(); | ||
let account = host | ||
.store | ||
.account(&handle) | ||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; | ||
account | ||
.filter(|a| a.handle == handle) | ||
.map(|a| a.did) | ||
.ok_or(StatusCode::NOT_FOUND) | ||
} | ||
crates/group-host/src/config.rs+4−0
| @@ -19,6 +19,8 @@ pub struct Config { | ||
pub handle_domain: String, | ||
/// The database, blobs and keys, `DATA_DIR`. | ||
pub data_dir: PathBuf, | ||
/// The PLC directory groups' identities are published to, `PLC_URL`. | ||
pub plc_url: String, | ||
} | ||
| ||
impl Config { | ||
| @@ -47,12 +49,14 @@ impl Config { | ||
bail!("HANDLE_DOMAIN starts with a dot: .{handle_domain}"); | ||
} | ||
let data_dir = var("DATA_DIR").unwrap_or_else(|| "data".into()).into(); | ||
let plc_url = var("PLC_URL").unwrap_or_else(|| "https://plc.directory".into()); | ||
Ok(Config { | ||
port, | ||
public_url, | ||
service_did, | ||
handle_domain, | ||
data_dir, | ||
plc_url, | ||
}) | ||
} | ||
| ||
crates/group-host/src/lib.rs+51−1
| @@ -3,7 +3,12 @@ | ||
//! `fyi.opensocial.*` methods that run a group. `docs/design/README.md` | ||
//! says how it is built and what is still to come. | ||
| ||
pub mod api; | ||
pub mod config; | ||
pub mod plc; | ||
pub mod repo; | ||
pub mod secrets; | ||
pub mod store; | ||
pub mod xrpc; | ||
| ||
use axum::extract::Path; | ||
| @@ -18,12 +23,57 @@ use xrpc::XrpcError; | ||
/// What every request is answered with. | ||
pub struct Host { | ||
pub config: Config, | ||
pub store: store::Store, | ||
pub secrets: secrets::Secrets, | ||
pub plc: plc::Directory, | ||
/// Each commit's revision, later than the last. | ||
pub clock: atproto::tid::TidClock, | ||
/// Held while a commit is made, so each builds on the one before. | ||
writing: std::sync::Mutex<()>, | ||
} | ||
| ||
impl Host { | ||
/// The host `config` describes, its data directory made if need be. | ||
pub fn open(config: Config) -> anyhow::Result<Host> { | ||
std::fs::create_dir_all(&config.data_dir)?; | ||
let store = store::Store::open(&config.data_dir.join("host.sqlite"))?; | ||
let secrets = secrets::Secrets::load(&config.data_dir)?; | ||
let plc = plc::Directory::new(&config.plc_url); | ||
// A clock id of its own, so two hosts' revisions never collide. | ||
let clock = atproto::tid::TidClock::new(u64::from(secrets.signing.public().to_sec1()[1])); | ||
Ok(Host { | ||
config, | ||
store, | ||
secrets, | ||
plc, | ||
clock, | ||
writing: Default::default(), | ||
}) | ||
} | ||
} | ||
| ||
/// The host's routes. | ||
pub fn router(host: Arc<Host>) -> Router { | ||
Router::new() | ||
.route("/xrpc/_health", get(health)) | ||
.route( | ||
"/xrpc/com.atproto.repo.describeRepo", | ||
get(api::describe_repo), | ||
) | ||
.route("/xrpc/com.atproto.repo.getRecord", get(api::get_record)) | ||
.route("/xrpc/com.atproto.repo.listRecords", get(api::list_records)) | ||
.route("/xrpc/com.atproto.sync.getRepo", get(api::get_repo)) | ||
.route( | ||
"/xrpc/com.atproto.sync.getLatestCommit", | ||
get(api::get_latest_commit), | ||
) | ||
.route("/xrpc/com.atproto.sync.listRepos", get(api::list_repos)) | ||
.route( | ||
"/xrpc/com.atproto.identity.resolveHandle", | ||
get(api::resolve_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)) | ||
.with_state(host) | ||
} | ||
| @@ -44,7 +94,7 @@ pub async fn serve(config: Config) -> anyhow::Result<()> { | ||
let listener = TcpListener::bind(("0.0.0.0", config.port)).await?; | ||
println!("listening on {}", listener.local_addr()?); | ||
tracing::info!(public_url = %config.public_url, did = %config.service_did, "serving"); | ||
let app = router(Arc::new(Host { config })); | ||
let app = router(Arc::new(Host::open(config)?)); | ||
axum::serve(listener, app) | ||
.with_graceful_shutdown(stopped()) | ||
.await?; | ||
crates/group-host/src/plc.rsnew+45−0
| @@ -0,0 +1,45 @@ | ||
//! The PLC directory, `PLC_URL`: where the host publishes its groups' | ||
//! identity operations, and reads their documents back. | ||
| ||
use anyhow::{Context, Result, bail}; | ||
use atproto::plc::Signed; | ||
use serde_json::Value; | ||
| ||
pub struct Directory { | ||
url: String, | ||
http: reqwest::Client, | ||
} | ||
| ||
impl Directory { | ||
pub fn new(url: &str) -> Directory { | ||
Directory { | ||
url: url.trim_end_matches('/').to_string(), | ||
http: reqwest::Client::new(), | ||
} | ||
} | ||
| ||
/// Publishes `op` as `did`'s next operation. | ||
pub async fn publish(&self, did: &str, op: &Signed) -> Result<()> { | ||
let res = self | ||
.http | ||
.post(format!("{}/{did}", self.url)) | ||
.json(&op.to_json()) | ||
.send() | ||
.await?; | ||
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}"); | ||
} | ||
Ok(()) | ||
} | ||
| ||
/// `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?; | ||
let res = res | ||
.error_for_status() | ||
.context(format!("no document for {did}"))?; | ||
Ok(res.json().await?) | ||
} | ||
} | ||
crates/group-host/src/repo.rsnew+252−0
| @@ -0,0 +1,252 @@ | ||
//! Groups' accounts and repos: making an account with its `did:plc`, and | ||
//! changing its records a signed commit at a time. | ||
| ||
use crate::Host; | ||
use crate::store::{Account, Change, Head}; | ||
use crate::xrpc::XrpcError; | ||
use anyhow::{Result, ensure}; | ||
use atproto::mst::{Entry, Node, Tree}; | ||
use atproto::plc::Op; | ||
use atproto::{Cid, Commit, Curve, Keypair, Value, car, drisl, syntax}; | ||
use axum::http::StatusCode; | ||
use std::collections::BTreeMap; | ||
| ||
/// A change to one record. | ||
#[derive(Debug, Clone, PartialEq)] | ||
pub enum Write { | ||
/// A record at a path where there is none. | ||
Create { | ||
collection: String, | ||
rkey: String, | ||
value: serde_json::Value, | ||
}, | ||
/// A record put where there is one. | ||
Update { | ||
collection: String, | ||
rkey: String, | ||
value: serde_json::Value, | ||
}, | ||
Delete { | ||
collection: String, | ||
rkey: String, | ||
}, | ||
} | ||
| ||
/// A commit made: its CID and revision. | ||
#[derive(Debug, Clone, PartialEq)] | ||
pub struct Committed { | ||
pub cid: Cid, | ||
pub rev: String, | ||
} | ||
| ||
fn invalid(message: impl Into<String>) -> XrpcError { | ||
XrpcError::new(StatusCode::BAD_REQUEST, "InvalidRequest", message) | ||
} | ||
| ||
fn now() -> i64 { | ||
let since = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH); | ||
since.expect("after 1970").as_secs() as i64 | ||
} | ||
| ||
impl Host { | ||
/// Makes an account at `handle`, one label under the host's handle | ||
/// domain: its keys, its `did:plc` published to the directory with | ||
/// the host's rotation key, and an empty repo. Its DID. | ||
pub async fn create_account(&self, handle: &str) -> Result<String, XrpcError> { | ||
// A handle names one account whatever its case: kept in lower case. | ||
let handle = handle.to_ascii_lowercase(); | ||
let handle = handle.as_str(); | ||
let domain = &self.config.handle_domain; | ||
let label = handle.strip_suffix(domain.as_str()).unwrap_or_default(); | ||
if label.is_empty() || label.contains('.') || !syntax::is_handle(handle) { | ||
return Err(XrpcError::new( | ||
StatusCode::BAD_REQUEST, | ||
"InvalidHandle", | ||
format!("a group's handle is one label under {domain}"), | ||
)); | ||
} | ||
let taken = || { | ||
XrpcError::new( | ||
StatusCode::BAD_REQUEST, | ||
"HandleNotAvailable", | ||
format!("{handle} is taken"), | ||
) | ||
}; | ||
if self | ||
.store | ||
.account(handle) | ||
.map_err(XrpcError::internal)? | ||
.is_some() | ||
{ | ||
return Err(taken()); | ||
} | ||
let signing = Keypair::generate(Curve::K256); | ||
let rotation = [self.secrets.rotation.public().did_key()]; | ||
let op = Op::atproto( | ||
&signing.public().did_key(), | ||
&rotation, | ||
handle, | ||
&self.config.public_url, | ||
); | ||
let genesis = op.sign(None, &self.secrets.rotation); | ||
let did = genesis.did(); | ||
let failed = |e: anyhow::Error| { | ||
XrpcError::new( | ||
StatusCode::BAD_GATEWAY, | ||
"AccountCreationFailed", | ||
format!("{e:#}"), | ||
) | ||
}; | ||
// Published before the account is kept: if keeping it fails, or | ||
// another took the handle meanwhile, the DID stays in the directory | ||
// with no account here behind it. | ||
self.plc.publish(&did, &genesis).await.map_err(failed)?; | ||
let account = Account { | ||
did: did.clone(), | ||
handle: handle.to_string(), | ||
signing, | ||
}; | ||
let head = self.sign(&account, &Tree::build(&BTreeMap::new())); | ||
// The handle checked above can still be taken as this was made: | ||
// the database's unique handle is what holds. | ||
let kept = self | ||
.store | ||
.create_account(&account, &head, now()) | ||
.map_err(XrpcError::internal)?; | ||
kept.then_some(did).ok_or_else(taken) | ||
} | ||
| ||
/// `account`'s commit of `tree`, at the next revision. | ||
fn sign(&self, account: &Account, tree: &Tree) -> Head { | ||
let commit = Commit::sign( | ||
&account.did, | ||
tree.root(), | ||
&self.clock.next(), | ||
&account.signing, | ||
); | ||
Head { | ||
cid: commit.cid(), | ||
rev: commit.rev.clone(), | ||
block: commit.to_bytes(), | ||
} | ||
} | ||
| ||
/// Makes `writes` to `did`'s repo, as one commit. | ||
pub fn write(&self, did: &str, writes: &[Write]) -> Result<Committed, XrpcError> { | ||
let _one_at_a_time = self.writing.lock().expect("not poisoned"); | ||
let account = self.store.account(did).map_err(XrpcError::internal)?; | ||
let account = account.ok_or_else(|| { | ||
XrpcError::new( | ||
StatusCode::BAD_REQUEST, | ||
"RepoNotFound", | ||
format!("no repo {did} here"), | ||
) | ||
})?; | ||
let head = self | ||
.store | ||
.head(&account.did) | ||
.map_err(XrpcError::internal)? | ||
.expect("an account has a repo"); | ||
let mut paths = self | ||
.store | ||
.paths(&account.did) | ||
.map_err(XrpcError::internal)?; | ||
let mut changes: Vec<Change> = Vec::new(); | ||
for write in writes { | ||
let (collection, rkey, value, exists) = match write { | ||
Write::Create { | ||
collection, | ||
rkey, | ||
value, | ||
} => (collection, rkey, Some(value), false), | ||
Write::Update { | ||
collection, | ||
rkey, | ||
value, | ||
} => (collection, rkey, Some(value), true), | ||
Write::Delete { collection, rkey } => (collection, rkey, None, true), | ||
}; | ||
if !syntax::is_nsid(collection) || !syntax::is_record_key(rkey) { | ||
return Err(invalid(format!( | ||
"{collection}/{rkey} is not a record's path" | ||
))); | ||
} | ||
let path = format!("{collection}/{rkey}"); | ||
if paths.contains_key(&path) != exists { | ||
let what = if exists { | ||
"no record at" | ||
} else { | ||
"a record already at" | ||
}; | ||
return Err(invalid(format!("there is {what} {path}"))); | ||
} | ||
let put = value.map(|v| record(collection, v)).transpose()?; | ||
match &put { | ||
Some((cid, _)) => paths.insert(path, *cid), | ||
None => paths.remove(&path), | ||
}; | ||
changes.push((collection.clone(), rkey.clone(), put)); | ||
} | ||
let new = self.sign(&account, &Tree::build(&paths)); | ||
let moved = self.store.commit(&account.did, &head.cid, &new, &changes); | ||
moved | ||
.and_then(|moved| { | ||
ensure!(moved, "{did}'s repo moved under a write"); | ||
Ok(()) | ||
}) | ||
.map_err(XrpcError::internal)?; | ||
Ok(Committed { | ||
cid: new.cid, | ||
rev: new.rev, | ||
}) | ||
} | ||
| ||
/// `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); | ||
}; | ||
let records: BTreeMap<Cid, Vec<u8>> = self | ||
.store | ||
.records(did)? | ||
.into_iter() | ||
.map(|r| (r.cid, r.value)) | ||
.collect(); | ||
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)), | ||
))) | ||
} | ||
} | ||
| ||
fn walk<'a>( | ||
node: &'a Node, | ||
records: &'a BTreeMap<Cid, Vec<u8>>, | ||
blocks: &mut Vec<(Cid, &'a [u8])>, | ||
) { | ||
blocks.push((node.cid(), node.bytes())); | ||
for entry in node.entries() { | ||
match entry { | ||
Entry::Tree(n) => walk(n, records, blocks), | ||
Entry::Leaf { value, .. } => blocks.push((*value, &records[value])), | ||
} | ||
} | ||
} | ||
| ||
/// A record's JSON as kept: its CID and DRISL. It must be a record by the | ||
/// data model, of its collection's `$type`. | ||
fn record(collection: &str, value: &serde_json::Value) -> Result<(Cid, Vec<u8>), XrpcError> { | ||
drisl::check_record(value).map_err(|e| invalid(e.to_string()))?; | ||
if value.get("$type").and_then(serde_json::Value::as_str) != Some(collection) { | ||
return Err(invalid(format!( | ||
"a record in {collection} has $type {collection}" | ||
))); | ||
} | ||
let bytes = drisl::encode(&Value::from_json(value).expect("checked as a record")); | ||
Ok((Cid::of_cbor(&bytes), bytes)) | ||
} | ||
crates/group-host/src/secrets.rsnew+76−0
| @@ -0,0 +1,76 @@ | ||
//! The host's own keys, kept in `host-secrets.json` in its data directory, | ||
//! made on its first start: the rotation key it signs its groups' PLC | ||
//! operations with, and the key its own `did:web` signs with. | ||
| ||
use anyhow::{Context, Result}; | ||
use atproto::{Curve, Keypair}; | ||
use serde_json::{Value, json}; | ||
use std::path::Path; | ||
| ||
pub struct Secrets { | ||
/// Signs every PLC operation of the groups here, first of their | ||
/// rotation keys. | ||
pub rotation: Keypair, | ||
/// The host's own signing key, in its `did:web` document. | ||
pub signing: Keypair, | ||
} | ||
| ||
fn hex(bytes: &[u8]) -> String { | ||
bytes.iter().map(|b| format!("{b:02x}")).collect() | ||
} | ||
| ||
fn unhex(text: &str) -> Option<Vec<u8>> { | ||
let bytes = text.as_bytes(); | ||
if !bytes.len().is_multiple_of(2) { | ||
return None; | ||
} | ||
bytes | ||
.chunks(2) | ||
.map(|pair| u8::from_str_radix(std::str::from_utf8(pair).ok()?, 16).ok()) | ||
.collect() | ||
} | ||
| ||
impl Secrets { | ||
/// The secrets in `dir`, made there first if there are none, the file | ||
/// readable by the host's user alone. | ||
pub fn load(dir: &Path) -> Result<Secrets> { | ||
let file = dir.join("host-secrets.json"); | ||
if file.exists() { | ||
let text = std::fs::read_to_string(&file)?; | ||
let json: Value = | ||
serde_json::from_str(&text).context("host-secrets.json is not JSON")?; | ||
let key = |name: &str| { | ||
let secret = json[name].as_str().and_then(unhex); | ||
let secret = secret.with_context(|| format!("host-secrets.json has no {name}"))?; | ||
Ok::<_, anyhow::Error>(Keypair::from_bytes(Curve::K256, &secret)?) | ||
}; | ||
return Ok(Secrets { | ||
rotation: key("rotationKey")?, | ||
signing: key("signingKey")?, | ||
}); | ||
} | ||
let secrets = Secrets { | ||
rotation: Keypair::generate(Curve::K256), | ||
signing: Keypair::generate(Curve::K256), | ||
}; | ||
std::fs::create_dir_all(dir)?; | ||
let json = json!({ | ||
"rotationKey": hex(&secrets.rotation.to_bytes()), | ||
"signingKey": hex(&secrets.signing.to_bytes()), | ||
}); | ||
write_private(&file, &serde_json::to_string_pretty(&json)?)?; | ||
Ok(secrets) | ||
} | ||
} | ||
| ||
fn write_private(file: &Path, text: &str) -> Result<()> { | ||
use std::io::Write; | ||
use std::os::unix::fs::OpenOptionsExt; | ||
let mut f = std::fs::OpenOptions::new() | ||
.write(true) | ||
.create_new(true) | ||
.mode(0o600) | ||
.open(file)?; | ||
f.write_all(text.as_bytes())?; | ||
Ok(()) | ||
} | ||
crates/group-host/src/store.rsnew+305−0
| @@ -0,0 +1,305 @@ | ||
//! The host's database: one SQLite file holding every group's account, its | ||
//! repo's current commit, and its records. The tree a commit names is | ||
//! not kept: it is built again from the records, as a group's repo is | ||
//! small (`atproto::mst`). | ||
| ||
use anyhow::{Context, Result}; | ||
use atproto::{Cid, Curve, Keypair}; | ||
use rusqlite::{Connection, OptionalExtension, params}; | ||
use std::collections::BTreeMap; | ||
use std::path::Path; | ||
use std::sync::{Mutex, MutexGuard}; | ||
| ||
/// Each version of the schema, applied in order to a database below it. | ||
const MIGRATIONS: &[&str] = &[" | ||
CREATE TABLE account ( | ||
did TEXT PRIMARY KEY, | ||
handle TEXT NOT NULL UNIQUE, | ||
signing_key BLOB NOT NULL, | ||
created_at INTEGER NOT NULL | ||
); | ||
CREATE TABLE repo ( | ||
did TEXT PRIMARY KEY REFERENCES account (did), | ||
cid TEXT NOT NULL, | ||
rev TEXT NOT NULL, | ||
commit_block BLOB NOT NULL | ||
); | ||
CREATE TABLE record ( | ||
did TEXT NOT NULL REFERENCES account (did), | ||
collection TEXT NOT NULL, | ||
rkey TEXT NOT NULL, | ||
cid TEXT NOT NULL, | ||
value BLOB NOT NULL, | ||
rev TEXT NOT NULL, | ||
PRIMARY KEY (did, collection, rkey) | ||
); | ||
"]; | ||
| ||
const NEW_ACCOUNT: &str = "INSERT INTO account (did, handle, signing_key, created_at) VALUES (?1, ?2, ?3, ?4) ON CONFLICT (handle) DO NOTHING"; | ||
const PUT_RECORD: &str = "INSERT INTO record (did, collection, rkey, cid, value, rev) VALUES (?1, ?2, ?3, ?4, ?5, ?6) ON CONFLICT (did, collection, rkey) DO UPDATE SET cid = ?4, value = ?5, rev = ?6"; | ||
const LIST_UP: &str = "SELECT collection, rkey, cid, value FROM record WHERE did = ?1 AND collection = ?2 AND rkey > ?3 ORDER BY rkey LIMIT ?4"; | ||
const LIST_DOWN: &str = "SELECT collection, rkey, cid, value FROM record WHERE did = ?1 AND collection = ?2 AND rkey < ?3 ORDER BY rkey DESC LIMIT ?4"; | ||
const ACCOUNTS: &str = | ||
"SELECT did, cid, rev, commit_block FROM repo WHERE did > ?1 ORDER BY did LIMIT ?2"; | ||
const COLLECTIONS: &str = | ||
"SELECT DISTINCT collection FROM record WHERE did = ?1 ORDER BY collection"; | ||
| ||
pub struct Store { | ||
conn: Mutex<Connection>, | ||
} | ||
| ||
/// An account the host keeps. | ||
pub struct Account { | ||
pub did: String, | ||
pub handle: String, | ||
/// Signs its repo's commits. | ||
pub signing: Keypair, | ||
} | ||
| ||
/// A repo's current commit. | ||
#[derive(Debug, Clone, PartialEq)] | ||
pub struct Head { | ||
pub cid: Cid, | ||
pub rev: String, | ||
/// The signed commit's block. | ||
pub block: Vec<u8>, | ||
} | ||
| ||
/// A record as kept: where, its CID and its DRISL. | ||
#[derive(Debug, Clone, PartialEq)] | ||
pub struct Record { | ||
pub collection: String, | ||
pub rkey: String, | ||
pub cid: Cid, | ||
pub value: Vec<u8>, | ||
} | ||
| ||
/// What a commit changes: a record put, or taken out (`None`). | ||
pub type Change = (String, String, Option<(Cid, Vec<u8>)>); | ||
| ||
/// A CID the host wrote: one that does not read is a database broken. | ||
fn cid(text: String) -> Cid { | ||
Cid::parse(&text).expect("a CID the host wrote") | ||
} | ||
| ||
fn record(row: &rusqlite::Row) -> rusqlite::Result<Record> { | ||
Ok(Record { | ||
collection: row.get(0)?, | ||
rkey: row.get(1)?, | ||
cid: cid(row.get(2)?), | ||
value: row.get(3)?, | ||
}) | ||
} | ||
| ||
impl Store { | ||
/// The database at `path`, made or brought up to date. `:memory:` for | ||
/// one that lasts as long as the process. | ||
pub fn open(path: &Path) -> Result<Store> { | ||
let opening = format!("opening {}", path.display()); | ||
let mut conn = Connection::open(path).context(opening)?; | ||
conn.pragma_update(None, "journal_mode", "wal")?; | ||
conn.pragma_update(None, "foreign_keys", true)?; | ||
let version: i64 = conn.pragma_query_value(None, "user_version", |r| r.get(0))?; | ||
let tx = conn.transaction()?; | ||
for (i, migration) in (0..).zip(MIGRATIONS).skip(version as usize) { | ||
tx.execute_batch(migration)?; | ||
tx.pragma_update(None, "user_version", i + 1_i64)?; | ||
} | ||
tx.commit()?; | ||
Ok(Store { | ||
conn: Mutex::new(conn), | ||
}) | ||
} | ||
| ||
fn conn(&self) -> MutexGuard<'_, Connection> { | ||
self.conn.lock().expect("not poisoned") | ||
} | ||
| ||
/// Keeps a new account, with its first commit. `false` if its handle | ||
/// is taken. | ||
pub fn create_account(&self, account: &Account, head: &Head, now: i64) -> Result<bool> { | ||
let mut conn = self.conn(); | ||
let tx = conn.transaction()?; | ||
let added = tx.execute( | ||
NEW_ACCOUNT, | ||
params![ | ||
account.did, | ||
account.handle, | ||
account.signing.to_bytes().to_vec(), | ||
now | ||
], | ||
); | ||
if added? == 0 { | ||
return Ok(false); | ||
} | ||
let kept = tx.execute( | ||
"INSERT INTO repo (did, cid, rev, commit_block) VALUES (?1, ?2, ?3, ?4)", | ||
params![account.did, head.cid.to_string(), head.rev, head.block], | ||
); | ||
kept?; | ||
tx.commit()?; | ||
Ok(true) | ||
} | ||
| ||
/// The account `did` or `handle` names. | ||
pub fn account(&self, did_or_handle: &str) -> Result<Option<Account>> { | ||
let found = self | ||
.conn() | ||
.query_row( | ||
"SELECT did, handle, signing_key FROM account WHERE did = ?1 OR handle = lower(?1)", | ||
[did_or_handle], | ||
|r| { | ||
Ok(( | ||
r.get::<_, String>(0)?, | ||
r.get::<_, String>(1)?, | ||
r.get::<_, Vec<u8>>(2)?, | ||
)) | ||
}, | ||
) | ||
.optional()?; | ||
found | ||
.map(|(did, handle, key)| { | ||
Ok(Account { | ||
did, | ||
handle, | ||
signing: Keypair::from_bytes(Curve::K256, &key)?, | ||
}) | ||
}) | ||
.transpose() | ||
} | ||
| ||
/// Accounts in DID order after `cursor`, at most `limit`, with their heads. | ||
pub fn accounts(&self, cursor: Option<&str>, limit: u32) -> Result<Vec<(String, Head)>> { | ||
let conn = self.conn(); | ||
let mut q = conn.prepare(ACCOUNTS)?; | ||
let rows = q.query_map(params![cursor.unwrap_or(""), limit], |r| { | ||
Ok(( | ||
r.get(0)?, | ||
Head { | ||
cid: cid(r.get(1)?), | ||
rev: r.get(2)?, | ||
block: r.get(3)?, | ||
}, | ||
)) | ||
}); | ||
let rows = rows?; | ||
Ok(rows.collect::<rusqlite::Result<_>>()?) | ||
} | ||
| ||
/// `did`'s current commit. | ||
pub fn head(&self, did: &str) -> Result<Option<Head>> { | ||
let head = self | ||
.conn() | ||
.query_row( | ||
"SELECT cid, rev, commit_block FROM repo WHERE did = ?1", | ||
[did], | ||
|r| { | ||
Ok(Head { | ||
cid: cid(r.get(0)?), | ||
rev: r.get(1)?, | ||
block: r.get(2)?, | ||
}) | ||
}, | ||
) | ||
.optional()?; | ||
Ok(head) | ||
} | ||
| ||
/// Every record of `did`'s, by path (`collection/rkey`), with its CID. | ||
pub fn paths(&self, did: &str) -> Result<BTreeMap<String, Cid>> { | ||
let conn = self.conn(); | ||
let mut q = conn.prepare("SELECT collection, rkey, cid FROM record WHERE did = ?1")?; | ||
let rows = q.query_map([did], |r| { | ||
Ok(( | ||
format!("{}/{}", r.get::<_, String>(0)?, r.get::<_, String>(1)?), | ||
cid(r.get(2)?), | ||
)) | ||
}); | ||
let rows = rows?; | ||
Ok(rows.collect::<rusqlite::Result<_>>()?) | ||
} | ||
| ||
/// Every record of `did`'s. | ||
pub fn records(&self, did: &str) -> Result<Vec<Record>> { | ||
let conn = self.conn(); | ||
let mut q = | ||
conn.prepare("SELECT collection, rkey, cid, value FROM record WHERE did = ?1")?; | ||
let rows = q.query_map([did], record)?; | ||
Ok(rows.collect::<rusqlite::Result<_>>()?) | ||
} | ||
| ||
/// `did`'s record at `collection/rkey`. | ||
pub fn record(&self, did: &str, collection: &str, rkey: &str) -> Result<Option<Record>> { | ||
let found = self | ||
.conn() | ||
.query_row( | ||
"SELECT collection, rkey, cid, value FROM record WHERE did = ?1 AND collection = ?2 AND rkey = ?3", | ||
[did, collection, rkey], | ||
record, | ||
) | ||
.optional()?; | ||
Ok(found) | ||
} | ||
| ||
/// `did`'s records in `collection`, past `cursor` (an rkey), at most | ||
/// `limit`: newest key first, or oldest with `reverse`. | ||
pub fn list( | ||
&self, | ||
did: &str, | ||
collection: &str, | ||
cursor: Option<&str>, | ||
limit: u32, | ||
reverse: bool, | ||
) -> Result<Vec<Record>> { | ||
let conn = self.conn(); | ||
let sql = if reverse { LIST_UP } else { LIST_DOWN }; | ||
// No rkey sorts before "" or after "\u{7f}": its characters are ASCII. | ||
let from = cursor.unwrap_or(if reverse { "" } else { "\u{7f}" }); | ||
let mut q = conn.prepare(sql)?; | ||
let rows = q.query_map(params![did, collection, from, limit], record)?; | ||
Ok(rows.collect::<rusqlite::Result<_>>()?) | ||
} | ||
| ||
/// The collections `did` holds records in. | ||
pub fn collections(&self, did: &str) -> Result<Vec<String>> { | ||
let conn = self.conn(); | ||
let mut q = conn.prepare(COLLECTIONS)?; | ||
let rows = q.query_map([did], |r| r.get(0))?; | ||
Ok(rows.collect::<rusqlite::Result<_>>()?) | ||
} | ||
| ||
/// Moves `did`'s repo from `prev` to `head`, with `changes`, unless | ||
/// another commit moved it first: `false` then, and nothing changes. | ||
pub fn commit(&self, did: &str, prev: &Cid, head: &Head, changes: &[Change]) -> Result<bool> { | ||
let mut conn = self.conn(); | ||
let tx = conn.transaction()?; | ||
let moved = tx.execute( | ||
"UPDATE repo SET cid = ?1, rev = ?2, commit_block = ?3 WHERE did = ?4 AND cid = ?5", | ||
params![ | ||
head.cid.to_string(), | ||
head.rev, | ||
head.block, | ||
did, | ||
prev.to_string() | ||
], | ||
); | ||
if moved? == 0 { | ||
return Ok(false); | ||
} | ||
for (collection, rkey, put) in changes { | ||
let done = match put { | ||
Some((cid, value)) => tx.execute( | ||
PUT_RECORD, | ||
params![did, collection, rkey, cid.to_string(), value, head.rev], | ||
), | ||
None => tx.execute( | ||
"DELETE FROM record WHERE did = ?1 AND collection = ?2 AND rkey = ?3", | ||
params![did, collection, rkey], | ||
), | ||
}; | ||
done?; | ||
} | ||
tx.commit()?; | ||
Ok(true) | ||
} | ||
} | ||
crates/group-host/src/xrpc.rs+10−0
| @@ -23,6 +23,16 @@ impl XrpcError { | ||
} | ||
} | ||
| ||
/// What went wrong inside the host, said as it is: the database, or | ||
/// a server it asked. | ||
pub fn internal(err: impl std::fmt::Display) -> Self { | ||
XrpcError::new( | ||
StatusCode::INTERNAL_SERVER_ERROR, | ||
"InternalServerError", | ||
err.to_string(), | ||
) | ||
} | ||
| ||
/// A call this host has no method for. | ||
pub fn not_implemented(nsid: &str) -> Self { | ||
XrpcError::new( | ||
crates/group-host/tests/common/mod.rsnew+145−0
| @@ -0,0 +1,145 @@ | ||
//! A host to test against, on a free port over a data directory of its | ||
//! own, and the PLC directory it publishes to, faked in this process. | ||
| ||
#![allow(dead_code)] | ||
| ||
use atproto::plc::Signed; | ||
use axum::extract::{Path, State}; | ||
use axum::http::StatusCode; | ||
use axum::routing::get; | ||
use axum::{Json, Router}; | ||
use group_host::Host; | ||
use group_host::config::Config; | ||
use serde_json::{Value, json}; | ||
use std::collections::HashMap; | ||
use std::sync::{Arc, Mutex}; | ||
| ||
/// A PLC directory: each DID's operations, each checked as the real one | ||
/// checks them, and its document as it serves one. `refuse` turns every | ||
/// operation away. | ||
#[derive(Default)] | ||
pub struct Plc { | ||
pub ops: Mutex<HashMap<String, Vec<Signed>>>, | ||
pub refuse: bool, | ||
} | ||
| ||
async fn publish( | ||
State(plc): State<Arc<Plc>>, | ||
Path(did): Path<String>, | ||
Json(op): Json<Value>, | ||
) -> StatusCode { | ||
let Ok(op) = Signed::from_json(&op) else { | ||
return StatusCode::BAD_REQUEST; | ||
}; | ||
let mut ops = plc.ops.lock().unwrap(); | ||
let log = ops.entry(did.clone()).or_default(); | ||
let signed = match (log.last(), &op) { | ||
( | ||
None, | ||
Signed::Update { | ||
op: o, prev: None, .. | ||
}, | ||
) => op.did() == did && op.signed_by(&o.rotation_keys).is_some(), | ||
(Some(last @ Signed::Update { op: o, .. }), _) => { | ||
op.prev() == Some(last.cid()) && op.signed_by(&o.rotation_keys).is_some() | ||
} | ||
_ => false, | ||
}; | ||
if plc.refuse || !signed { | ||
return StatusCode::BAD_REQUEST; | ||
} | ||
log.push(op); | ||
StatusCode::OK | ||
} | ||
| ||
async fn document( | ||
State(plc): State<Arc<Plc>>, | ||
Path(did): Path<String>, | ||
) -> Result<Json<Value>, StatusCode> { | ||
let ops = plc.ops.lock().unwrap(); | ||
let Some(Signed::Update { op, .. }) = ops.get(&did).and_then(|l| l.last()) else { | ||
return Err(StatusCode::NOT_FOUND); | ||
}; | ||
let key = op.verification_methods["atproto"] | ||
.strip_prefix("did:key:") | ||
.unwrap(); | ||
Ok(Json(json!({ | ||
"@context": ["https://www.w3.org/ns/did/v1", "https://w3id.org/security/multikey/v1"], | ||
"id": did, | ||
"alsoKnownAs": op.also_known_as, | ||
"verificationMethod": [{"id": format!("{did}#atproto"), "type": "Multikey", "controller": did, "publicKeyMultibase": key}], | ||
"service": [{"id": "#atproto_pds", "type": "AtprotoPersonalDataServer", "serviceEndpoint": op.services["atproto_pds"].endpoint}], | ||
}))) | ||
} | ||
| ||
/// Serves `router` on a free port, answering its address. | ||
async fn serve(router: Router) -> String { | ||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); | ||
let addr = listener.local_addr().unwrap(); | ||
tokio::spawn(async move { axum::serve(listener, router).await.unwrap() }); | ||
format!("http://{addr}") | ||
} | ||
| ||
pub async fn start_plc(refuse: bool) -> (Arc<Plc>, String) { | ||
let plc = Arc::new(Plc { | ||
refuse, | ||
..Plc::default() | ||
}); | ||
let router = Router::new() | ||
.route("/{did}", get(document).post(publish)) | ||
.with_state(plc.clone()); | ||
(plc, serve(router).await) | ||
} | ||
| ||
/// A running host and what it stands on. | ||
pub struct Running { | ||
pub host: Arc<Host>, | ||
pub url: String, | ||
pub plc: Arc<Plc>, | ||
pub http: reqwest::Client, | ||
pub data: tempfile::TempDir, | ||
} | ||
| ||
impl Running { | ||
/// What `GET /xrpc/<nsid>?<query>` answers: its status and JSON. | ||
pub async fn get(&self, nsid: &str, query: &str) -> (u16, Value) { | ||
let res = self | ||
.http | ||
.get(format!("{}/xrpc/{nsid}?{query}", self.url)) | ||
.send() | ||
.await | ||
.unwrap(); | ||
( | ||
res.status().as_u16(), | ||
res.json().await.unwrap_or(Value::Null), | ||
) | ||
} | ||
} | ||
| ||
/// A host whose groups' handles are under `.groups.test`, with `vars` | ||
/// besides, publishing to a fake PLC directory. | ||
pub async fn start(vars: &[(&str, &str)], refuse: bool) -> Running { | ||
let (plc, plc_url) = start_plc(refuse).await; | ||
let data = tempfile::tempdir().unwrap(); | ||
let dir = data.path().to_str().unwrap().to_string(); | ||
let mut env: HashMap<String, String> = [ | ||
("DATA_DIR", dir.as_str()), | ||
("PLC_URL", plc_url.as_str()), | ||
("HANDLE_DOMAIN", ".groups.test"), | ||
("PUBLIC_URL", "https://host.test"), | ||
] | ||
.into_iter() | ||
.map(|(k, v)| (k.to_string(), v.to_string())) | ||
.collect(); | ||
env.extend(vars.iter().map(|(k, v)| (k.to_string(), v.to_string()))); | ||
let config = Config::from(|k| env.get(k).cloned()).unwrap(); | ||
let host = Arc::new(Host::open(config).unwrap()); | ||
let url = serve(group_host::router(host.clone())).await; | ||
Running { | ||
host, | ||
url, | ||
plc, | ||
http: reqwest::Client::new(), | ||
data, | ||
} | ||
} | ||
crates/group-host/tests/repos.rsnew+515−0
515 lines changed: not loaded until asked for.
crates/group-host/tests/serve.rs+4−2
| @@ -16,9 +16,10 @@ impl Running { | ||
} | ||
} | ||
| ||
fn start() -> Running { | ||
fn start(data: &std::path::Path) -> Running { | ||
let mut child = Command::new(env!("CARGO_BIN_EXE_group-host")) | ||
.env("PORT", "0") | ||
.env("DATA_DIR", data) | ||
.env("RUST_LOG", "off") | ||
.stdout(Stdio::piped()) | ||
.spawn() | ||
| @@ -34,7 +35,8 @@ fn start() -> Running { | ||
| ||
#[tokio::test] | ||
async fn answers_health_and_refuses_unknown_methods() { | ||
let host = start(); | ||
let data = tempfile::tempdir().unwrap(); | ||
let host = start(data.path()); | ||
let http = reqwest::Client::new(); | ||
| ||
let health: serde_json::Value = http | ||