chadtmiller.com/group-host
atmosphere group host
0
0
Moving a group here takes only founders and no more than the host keeps
crates/group-host/src/account_move.rs+10−5
| @@ -22,8 +22,10 @@ | ||
//! unfinished copy discarded. | ||
| ||
use crate::Host; | ||
use crate::api::{ANSWER_AT_MOST, REPO_AT_MOST, too_much}; | ||
use crate::console_login::{Pending, sign_in}; | ||
use crate::group_api::signed_in; | ||
use crate::index_api::capped; | ||
use crate::migration::creds; | ||
use crate::rbac::NS; | ||
use crate::store::Store; | ||
| @@ -273,7 +275,8 @@ impl Host { | ||
Method::GET | ||
}; | ||
let key = Keypair::from_bytes(Curve::P256, &m.key).expect("a key the host made"); | ||
let (mut nonce, mut renewed) = (None::<String>, false); | ||
// Each asked for once: a nonce, and a renewed token. | ||
let (mut nonce, mut nonced, mut renewed) = (None::<String>, false, false); | ||
loop { | ||
let mut claims = json!({ | ||
"jti": jose::random(12), | ||
| @@ -302,9 +305,9 @@ impl Host { | ||
let asked = asked.map(String::from); | ||
if res.status() == StatusCode::UNAUTHORIZED | ||
&& challenged(&res, "use_dpop_nonce") | ||
&& nonce.is_none() | ||
&& !nonced | ||
{ | ||
nonce = asked; | ||
(nonce, nonced) = (asked, true); | ||
continue; | ||
} | ||
if res.status() == StatusCode::UNAUTHORIZED | ||
| @@ -330,7 +333,8 @@ impl Host { | ||
) -> Result<Value, XrpcError> { | ||
let res = self.as_moving(mover, m, nsid, query, body).await?; | ||
let status = res.status(); | ||
let said: Value = res.json().await.unwrap_or_default(); | ||
let read = capped(res, ANSWER_AT_MOST).await.unwrap_or_default(); | ||
let said: Value = serde_json::from_slice(&read).unwrap_or_default(); | ||
if !status.is_success() { | ||
let why = said["message"].as_str().or(said["error"].as_str()); | ||
return Err(upstream(format!( | ||
| @@ -357,7 +361,8 @@ impl Host { | ||
.and_then(|v| v.to_str().ok()); | ||
let kind = kind.unwrap_or("application/octet-stream").to_string(); | ||
let status = res.status(); | ||
let bytes = res.bytes().await.map_err(upstream)?; | ||
let read = capped(res, REPO_AT_MOST).await; | ||
let bytes = read.ok_or(upstream(too_much(REPO_AT_MOST)))?; | ||
let said: Value = serde_json::from_slice(&bytes).unwrap_or_default(); | ||
if status.is_success() { | ||
return Ok(Some((bytes.to_vec(), kind))); | ||
crates/group-host/src/api.rs+11−0
| @@ -11,6 +11,17 @@ use axum::http::{HeaderMap, StatusCode, header}; | ||
use axum::response::{IntoResponse, Response}; | ||
use serde_json::{Value, json}; | ||
use std::collections::HashMap; | ||
| ||
/// The most a JSON answer from another server is read to. | ||
pub const ANSWER_AT_MOST: usize = 16 * 1024 * 1024; | ||
/// The most a repo, or a repo in a space, brought from another server is | ||
/// read to. | ||
pub const REPO_AT_MOST: usize = 256 * 1024 * 1024; | ||
| ||
/// Why an answer read up to `max` bytes was not taken. | ||
pub(crate) fn too_much(max: usize) -> String { | ||
format!("an answer of more than {max} bytes, or one cut off") | ||
} | ||
use std::sync::Arc; | ||
| ||
pub(crate) type Params = HashMap<String, String>; | ||
crates/group-host/src/group.rs+14−7
| @@ -135,16 +135,23 @@ impl Host { | ||
founders.is_empty() || founders.iter().any(|f| f == did) | ||
} | ||
| ||
/// Refuses `did` a group here, made, moved or brought, unless the host | ||
/// starts groups for them. | ||
pub(crate) fn founding(&self, did: &str) -> Result<(), XrpcError> { | ||
if self.may_found(did) { | ||
return Ok(()); | ||
} | ||
Err(XrpcError::new( | ||
StatusCode::FORBIDDEN, | ||
"NotAllowed", | ||
"this host is not starting groups for you", | ||
)) | ||
} | ||
| ||
/// Makes a group: its account, its two spaces and what they hold from | ||
/// its first day, and its declaration if anyone may read its meta. | ||
pub async fn create_group(&self, new: &NewGroup) -> Result<Made, XrpcError> { | ||
if !self.may_found(&new.founder) { | ||
return Err(XrpcError::new( | ||
StatusCode::FORBIDDEN, | ||
"NotAllowed", | ||
"this host is not starting groups for you", | ||
)); | ||
} | ||
self.founding(&new.founder)?; | ||
let shape = shape(new)?; | ||
let did = self.create_account(&new.handle).await.map_err(|e| { | ||
if e.error == "HandleNotAvailable" { | ||
crates/group-host/src/import.rs+11−11
| @@ -24,10 +24,11 @@ | ||
//! while the move is pending. | ||
| ||
use crate::Host; | ||
use crate::api::{Params, invalid, param}; | ||
use crate::api::{ANSWER_AT_MOST, Params, REPO_AT_MOST, invalid, param, too_much}; | ||
use crate::group::NewGroup; | ||
use crate::group_api::{for_host, signed_in}; | ||
use crate::import_space::keeps; | ||
use crate::index_api::capped; | ||
use crate::migration::{creds, repo_writes, take_in}; | ||
use crate::rbac::NS; | ||
use crate::repo::{Asked, Write}; | ||
| @@ -259,7 +260,9 @@ impl Host { | ||
let mut query = vec![("did", did), ("limit", "1000")]; | ||
query.extend(cursor.as_deref().map(|c| ("cursor", c))); | ||
let res = self.ask_server(&list, &query).await?; | ||
let page: Value = res.json().await.map_err(upstream)?; | ||
let read = capped(res, ANSWER_AT_MOST).await; | ||
let read = read.ok_or(upstream(too_much(ANSWER_AT_MOST)))?; | ||
let page: Value = serde_json::from_slice(&read).map_err(upstream)?; | ||
let listed = page["cids"].as_array().cloned().unwrap_or_default(); | ||
let next = page["cursor"].as_str().filter(|_| !listed.is_empty()); | ||
cursor = next.map(String::from); | ||
| @@ -285,7 +288,9 @@ impl Host { | ||
let res = self.ask_server(url, &[("did", did), ("cid", cid)]).await?; | ||
let mime = res.headers().get(header::CONTENT_TYPE).cloned(); | ||
let mime = mime.and_then(|m| m.to_str().ok().map(String::from)); | ||
let bytes = res.bytes().await.map_err(upstream)?; | ||
let most = self.config.blob_upload_limit as usize; | ||
let read = capped(res, most).await; | ||
let bytes = read.ok_or(upstream(too_much(most)))?; | ||
if Cid::of_raw(&bytes).to_string() != cid { | ||
return Err(upstream(format!("the file {cid} is not what it says"))); | ||
} | ||
| @@ -307,7 +312,8 @@ impl Host { | ||
let blobs = self.copy_blobs(did, &plan.pds).await?; | ||
let url = format!("{}/xrpc/com.atproto.sync.getRepo", plan.pds); | ||
let res = self.ask_server(&url, &[("did", did)]).await?; | ||
let bytes = res.bytes().await.map_err(upstream)?; | ||
let read = capped(res, REPO_AT_MOST).await; | ||
let bytes = read.ok_or(upstream(too_much(REPO_AT_MOST)))?; | ||
let Some(writes) = repo_writes(&bytes, did, &plan.key) else { | ||
return Err(refused( | ||
"InvalidRepo", | ||
| @@ -419,13 +425,7 @@ impl Host { | ||
jwt: &str, | ||
address: Option<&str>, | ||
) -> Result<Value, XrpcError> { | ||
if !self.may_found(me) { | ||
return Err(XrpcError::new( | ||
StatusCode::FORBIDDEN, | ||
"NotAllowed", | ||
"this host is not starting groups for you", | ||
)); | ||
} | ||
self.founding(me)?; | ||
let did = proof(self, jwt).await?; | ||
if did == me { | ||
return Err(refused( | ||
crates/group-host/src/migration.rs+24−19
| @@ -28,8 +28,9 @@ | ||
//! this host keeps it, not as the space alpha's meta archive. | ||
| ||
use crate::Host; | ||
use crate::api::{Params, invalid, param}; | ||
use crate::api::{ANSWER_AT_MOST, Params, REPO_AT_MOST, invalid, param, too_much}; | ||
use crate::group_api::signed_in; | ||
use crate::index_api::capped; | ||
use crate::rbac::NS; | ||
use crate::repo::{Asked, Write}; | ||
use crate::store::{Account, Store}; | ||
| @@ -59,6 +60,13 @@ fn refused(error: &'static str, message: impl Into<String>) -> XrpcError { | ||
XrpcError::new(StatusCode::BAD_REQUEST, error, message) | ||
} | ||
| ||
/// A JSON answer of the group's host, read up to `ANSWER_AT_MOST`. | ||
async fn json_at_most(res: reqwest::Response) -> Result<Value, XrpcError> { | ||
let read = capped(res, ANSWER_AT_MOST).await; | ||
let bytes = read.ok_or(source(too_much(ANSWER_AT_MOST)))?; | ||
serde_json::from_slice(&bytes).map_err(source) | ||
} | ||
| ||
fn source(why: impl std::fmt::Display) -> XrpcError { | ||
XrpcError::new( | ||
StatusCode::BAD_GATEWAY, | ||
| @@ -455,6 +463,7 @@ pub async fn migrate_receive( | ||
Json(body): Json<Value>, | ||
) -> Answer { | ||
let me = signed_in(&host, &headers, &format!("{NS}.migrateReceive")).await?; | ||
host.founding(&me)?; | ||
let group = body["did"] | ||
.as_str() | ||
.ok_or_else(|| invalid("did is required"))?; | ||
| @@ -512,7 +521,8 @@ pub async fn migrate_receive( | ||
.send() | ||
.await | ||
.map_err(source)?; | ||
let bytes = res.bytes().await.map_err(source)?; | ||
let read = capped(res, REPO_AT_MOST).await; | ||
let bytes = read.ok_or(source(too_much(REPO_AT_MOST)))?; | ||
let writes = repo_writes(&bytes, group, &key); | ||
let writes = writes.ok_or(source("a repo that is not the group's, signed and whole"))?; | ||
| ||
| @@ -555,19 +565,17 @@ async fn receive( | ||
}; | ||
| ||
// Its files first: its records hold them. | ||
let listed: Value = host | ||
.pull(pds, group, token, &[("part", "blobs")]) | ||
.await? | ||
.json() | ||
.await | ||
.map_err(source)?; | ||
let res = host.pull(pds, group, token, &[("part", "blobs")]).await?; | ||
let listed: Value = json_at_most(res).await?; | ||
let blobs = listed["blobs"].as_array().cloned().unwrap_or_default(); | ||
for blob in &blobs { | ||
let cid = blob["cid"].as_str().unwrap_or_default(); | ||
let res = host | ||
.pull(pds, group, token, &[("part", "blob"), ("cid", cid)]) | ||
.await?; | ||
let bytes = res.bytes().await.map_err(source)?; | ||
let most = host.config.blob_upload_limit as usize; | ||
let read = capped(res, most).await; | ||
let bytes = read.ok_or(source(too_much(most)))?; | ||
if Cid::of_raw(&bytes).to_string() != cid { | ||
return Err(source(format!("the file {cid} is not what it says"))); | ||
} | ||
| @@ -590,19 +598,16 @@ async fn receive( | ||
if space.authority != group { | ||
return Err(invalid(format!("{uri} is not one of the group's spaces"))); | ||
} | ||
let meta: Value = host | ||
let res = host | ||
.pull(pds, group, token, &[("part", "meta"), ("space", uri)]) | ||
.await? | ||
.json() | ||
.await | ||
.map_err(source)?; | ||
.await?; | ||
let meta: Value = json_at_most(res).await?; | ||
host.create_space(group, &space.kind, &space.skey, meta["publicRead"] == true)?; | ||
let bytes = host | ||
let res = host | ||
.pull(pds, group, token, &[("part", "repo"), ("space", uri)]) | ||
.await? | ||
.bytes() | ||
.await | ||
.map_err(source)?; | ||
.await?; | ||
let read = capped(res, REPO_AT_MOST).await; | ||
let bytes = read.ok_or(source(too_much(REPO_AT_MOST)))?; | ||
let writes = space_writes(&bytes, group, uri); | ||
let writes = writes.ok_or(source(format!( | ||
"the group's repo in {uri} is not what its commit says" | ||
crates/group-host/tests/account_move.rs+26−7
| @@ -57,6 +57,8 @@ struct Old { | ||
spaces: Mutex<bool>, | ||
undescribed: Mutex<bool>, | ||
no_refresh: Mutex<bool>, | ||
/// Whether it asks for a DPoP nonce without giving one. | ||
nonceless: Mutex<bool>, | ||
} | ||
| ||
impl Old { | ||
| @@ -165,17 +167,20 @@ async fn revoke( | ||
/// given for: a refusal if not, asking for a nonce first, as atproto's | ||
/// servers do, and taking a lapsed token as lapsed once. | ||
fn bound(old: &Old, headers: &HeaderMap, nsid: &str) -> Option<Response> { | ||
let nonceless = *old.nonceless.lock().unwrap(); | ||
let refuse = |error: &str| { | ||
let challenge = format!("DPoP error=\"{error}\""); | ||
let headers = [("www-authenticate", challenge), ("dpop-nonce", "n2".into())]; | ||
Some( | ||
( | ||
StatusCode::UNAUTHORIZED, | ||
headers, | ||
Json(json!({"error": error})), | ||
) | ||
.into_response(), | ||
let mut res = ( | ||
StatusCode::UNAUTHORIZED, | ||
headers, | ||
Json(json!({"error": error})), | ||
) | ||
.into_response(); | ||
if nonceless { | ||
res.headers_mut().remove("dpop-nonce"); | ||
} | ||
Some(res) | ||
}; | ||
let auth = headers["authorization"].to_str().unwrap(); | ||
let access = auth.strip_prefix("DPoP ").unwrap(); | ||
| @@ -746,6 +751,20 @@ async fn stops_rather_than_move_without_what_it_cannot_read_or_renew() { | ||
assert_eq!(error(&said), (400, "SignInAgain")); | ||
} | ||
| ||
#[tokio::test] | ||
async fn asks_once_for_a_nonce_its_server_never_gives() { | ||
let w = world().await; | ||
w.sign_in_to_move().await; | ||
// A server that asks for a nonce and never gives one is asked once | ||
// more, then taken at its word, rather than asked forever. | ||
*w.old.nonceless.lock().unwrap() = true; | ||
let started = w.call("startAccountMove", Some(json!({}))); | ||
let said = tokio::time::timeout(std::time::Duration::from_secs(20), started) | ||
.await | ||
.expect("an answer, not a loop"); | ||
assert_ne!(said.0, 200, "{}", said.1); | ||
} | ||
| ||
#[tokio::test] | ||
async fn gives_back_and_forgets_a_move_kept_a_day() { | ||
let w = world().await; | ||
crates/group-host/tests/migration.rs+31−0
| @@ -720,6 +720,37 @@ async fn takes_in_nothing_it_cannot_check() { | ||
); | ||
} | ||
| ||
#[tokio::test] | ||
async fn takes_in_only_what_it_may_and_no_more_than_it_keeps() { | ||
// A host that starts groups for someone else takes in none of Alice's. | ||
let (_, b, _, _, [alice, ..]) = | ||
two_hosts_with(&[("GROUP_FOUNDERS", "did:plc:someoneelse")]).await; | ||
let key = Keypair::generate(Curve::K256); | ||
let said = from_fake(&b, &alice, Arc::new(Fake::default()), &key).await; | ||
assert_eq!(error(&said), (403, "NotAllowed"), "{}", said.1); | ||
// A file larger than the host keeps stops the move, unread. | ||
let (_, b, _, _, [alice, ..]) = two_hosts_with(&[("BLOB_UPLOAD_LIMIT", "4")]).await; | ||
let fake = Arc::new(Fake::default()); | ||
let big = b"more than four".to_vec(); | ||
fake.said.lock().unwrap().insert( | ||
"blobs".into(), | ||
json!({"blobs": [{"cid": Cid::of_raw(&big).to_string(), "mimeType": "image/png"}]}) | ||
.to_string() | ||
.into_bytes(), | ||
); | ||
fake.said.lock().unwrap().insert("blob".into(), big); | ||
let said = from_fake(&b, &alice, fake, &key).await; | ||
assert_eq!(error(&said), (502, "SourceUnreadable"), "{}", said.1); | ||
assert!( | ||
said.1["message"] | ||
.as_str() | ||
.unwrap() | ||
.contains("more than 4 bytes"), | ||
"{}", | ||
said.1 | ||
); | ||
} | ||
| ||
#[test] | ||
fn takes_a_handle_here() { | ||
use group_host::migration::handle_here; | ||
docs/design/moving.md+6−0
| @@ -84,6 +84,12 @@ Details: | ||
it still resolves to the group. | ||
- If that label or handle is another account's here, the move is refused | ||
`HandleNotAvailable`. | ||
- Only someone this host starts groups for (`GROUP_FOUNDERS`) may bring | ||
a group here, as only they may start one. | ||
- What is pulled is read up to a limit: a file to `BLOB_UPLOAD_LIMIT`, a | ||
repo to 256 MiB, any other answer to 16 MiB. More stops the move. | ||
Bringing an account here reads to the same limits, and leaves out a | ||
file over its limit as it does any file that does not come. | ||
| ||
### Handing over | ||
| ||
docs/reference/config.md+2−2
| @@ -18,8 +18,8 @@ trimmed of spaces and a trailing `/`. | ||
| `PLC_URL` | the PLC directory groups' `did:plc`s are published to | `https://plc.directory` | | ||
| `DID_WEB_SCHEME` | how a `did:web`'s document is read (`https`, or `http` for test servers) | `https` | | ||
| `HANDLE_RESOLVERS` | how a handle is resolved, tried in turn: `well-known:<scheme>` for its own `/.well-known/atproto-did`, or a service answering `com.atproto.identity.resolveHandle` (which reads its DNS record) | `well-known:https,https://public.api.bsky.app` | | ||
| `GROUP_FOUNDERS` | who the host starts groups for, comma-separated DIDs: by `createGroup`, `provisionGroup` or moving an account here | anyone | | ||
| `BLOB_UPLOAD_LIMIT` | the most bytes one blob may be, uploaded or brought with a space; `describeServer` answers it | 52428800 (50 MiB) | | ||
| `GROUP_FOUNDERS` | who the host starts groups for, comma-separated DIDs: by `createGroup`, `provisionGroup`, or moving a group or an account here | anyone | | ||
| `BLOB_UPLOAD_LIMIT` | the most bytes one blob may be, uploaded, or brought with a group, an account or a space; `describeServer` answers it | 52428800 (50 MiB) | | ||
| `CONSOLE_URL` | where the console is: where the host sends a member to approve an app or an assistant (`/authorize`), the console's OAuth client id and callback when people sign in (`/console/…`), and, when `https`, whether the session cookie is `Secure` | `PUBLIC_URL` | | ||
| `PROVISIONING_CLIENTS` | the apps the host makes groups for with `provisionGroup`, comma-separated OAuth client ids; `*` for any | none | | ||
| `PDS_CRAWLERS` | relays told of news with `requestCrawl`, comma-separated: at most every 20 minutes, and the first time after a start | none | | ||