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

Spaces, repos and notices are read and sent through atproto-client

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:deps/shared-atproto-spaces
.changeset/shared-atproto-spaces.mdnew+7−0
@@ -0,0 +1,7 @@
---
default: patch
---
# Spaces, repos and syncers reached through atproto-client
The host reads its groups' spaces at their writers' PDSes, copies an account's or a group's repo and files when it moves here, and tells syncers, PDSes and relays what changed, through the shared `atproto-client` crate's space, sync and XRPC clients. A repo is asked for as STAR-lite, zstd'd, where its host serves one, and a CAR otherwise. A syncer confirming its registration must answer with a success, and a failure to read another server now names the method and the error it answered (`getRepo: RepoNotFound (404): …`).
crates/group-host/src/account_move.rs+3−7
@@ -37,8 +37,8 @@ use anyhow::Result;
use atproto::did;
use atproto::space::SPACE_URI_PREFIX;
use atproto_client::oauth::{self as login, Session, SessionStore, StoreError};
use atproto_client::service_auth;
use atproto_client::xrpc::{self, Auth, Xrpc};
use atproto_client::{service_auth, space};
use atproto_server::Error;
use axum::Json;
use axum::extract::{Query, RawQuery, State};
@@ -323,12 +323,8 @@ impl Host {
let mut spaces = Vec::new();
// Only a server that says it holds spaces has any to bring: most do
// not yet, and answer for a method they lack in no one way.
let url = format!("{}/xrpc/com.atproto.server.describeServer", m.pds);
let described = self
.public_json(&url, "its server")
.await
.map_err(upstream)?;
let holds = described["spacesAlpha"] == true;
let pds = Xrpc::new(self.guarded.clone(), &m.pds).at_most(ANSWER_AT_MOST);
let holds = space::spaces_alpha(&pds).await.map_err(upstream)?;
let mut cursor = holds.then_some(String::new());
while let Some(after) = cursor.take() {
let mut page = vec![("limit", "100")];
crates/group-host/src/api.rs+1−6
@@ -12,6 +12,7 @@ use axum::http::{HeaderMap, StatusCode, header};
use axum::response::{IntoResponse, Response};
use serde_json::{Value, json};
use std::collections::HashMap;
use std::sync::Arc;
/// The most a JSON answer from another server is read to.
pub const ANSWER_AT_MOST: usize = 16 * 1024 * 1024;
@@ -19,12 +20,6 @@ pub const ANSWER_AT_MOST: usize = 16 * 1024 * 1024;
/// 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>;
type Answer = Result<Json<Value>, Error>;
crates/group-host/src/apps.rs+1−1
@@ -13,8 +13,8 @@
use crate::Host;
use crate::api::Params;
use crate::index_api::capped;
use crate::time::now_millis;
use crate::xrpc::capped;
use axum::body::Bytes;
use axum::extract::{Query, State};
use axum::http::{StatusCode, header};
crates/group-host/src/authority.rs+33−44
@@ -18,7 +18,7 @@
//! or a day has passed, as pds.js's `outbox.js` does.
use crate::Host;
use crate::index_api::capped;
use crate::api::ANSWER_AT_MOST;
use crate::rbac::Policy;
use crate::repo::invalid;
use crate::space::NOTIFY_REPO_UPDATE;
@@ -33,11 +33,13 @@ use atproto::space_auth::{self, space_host_aud};
use atproto::{Value, jose, syntax};
use atproto_client::guard::Guarded;
use atproto_client::identity;
use atproto_client::sender::SendError;
use atproto_client::xrpc::{Auth, Xrpc};
use atproto_server::Error;
use axum::body::Bytes;
use axum::http::StatusCode;
use futures::future::{OptionFuture, join_all};
use futures::future::join_all;
use futures::{StreamExt, stream};
use serde::de::IgnoredAny;
use serde_json::{Value as Json, json};
/// What a user would do in a space.
@@ -148,10 +150,15 @@ fn syncer_update(update: &SyncerUpdate) -> Json {
}
}
/// What a request's answer says of delivering it.
fn delivery(sent: Result<reqwest::Response, SendError>) -> Delivery {
match sent.map(|r| r.status()) {
Ok(s) if s.is_success() => Delivery::Delivered,
/// `body` posted as JSON to the procedure `nsid` of the host `at` calls,
/// with `auth` if any: what its answer says of delivering it. A host
/// refused, not reached, or answering past what is read is as one that
/// may answer later.
async fn deliver_to(at: &Xrpc, nsid: &str, body: &Json, auth: Option<&Auth>) -> Delivery {
let input = (Bytes::from(body.to_string()), "application/json");
let sent = at.procedure_reply(nsid, &[], Some(input), auth).await;
match sent.map(|r| r.status) {
Ok(200..=299) => Delivery::Delivered,
Ok(s) if retryable(s) => Delivery::Retry,
Ok(_) => Delivery::Failed,
Err(_) => Delivery::Retry,
@@ -171,16 +178,10 @@ struct Syncers {
impl Syncers {
/// Tells the syncer at `to` of `update` to `space`, once.
async fn send(&self, space: &str, to: &Registration, update: &Json) -> Delivery {
let url = format!(
"{}/xrpc/{NOTIFY_SPACE_UPDATE}",
to.endpoint.trim_end_matches('/')
);
// The syncer chose the endpoint: it is fetched as one not trusted.
// A refused endpoint is as one that did not answer.
// The syncer chose the endpoint: it is asked as one not trusted.
let at = Xrpc::new(self.guarded.clone(), &to.endpoint).at_most(ANSWER_AT_MOST);
let body = json!({"space": space, "token": to.token, "update": update});
let asked = self.guarded.post(&url).ok().map(|a| a.json(&body).send());
let sent = OptionFuture::from(asked).await;
sent.map_or(Delivery::Retry, delivery)
deliver_to(&at, NOTIFY_SPACE_UPDATE, &body, None).await
}
/// Tells each syncer registered for `space` of `update`, a change to
@@ -494,21 +495,13 @@ impl Host {
to: &Registration,
) -> Result<(), Error> {
let challenge = jose::random(16);
let url = format!(
"{}/xrpc/{CONFIRM_REGISTRATION}",
to.endpoint.trim_end_matches('/')
);
let body = json!({"space": space, "token": to.token, "challenge": challenge});
let echoed = async {
// The syncer chose the endpoint: it is fetched as one not
// trusted.
let asked = self.guarded.post(&url).ok()?;
let res = asked.json(&body).send().await.ok()?;
let bytes = capped(res, CONFIRMATION_AT_MOST).await?;
let said: Json = serde_json::from_slice(&bytes).ok()?;
said["challenge"].as_str().map(String::from)
};
if echoed.await.as_deref() == Some(challenge.as_str()) {
// The syncer chose the endpoint: it is asked as one not trusted.
let at = Xrpc::new(self.guarded.clone(), &to.endpoint).at_most(CONFIRMATION_AT_MOST);
let said = at.procedure::<Json>(CONFIRM_REGISTRATION, Some(&body), None);
let said = said.await.unwrap_or_default();
let echoed = said["challenge"].as_str();
if echoed == Some(challenge.as_str()) {
return Ok(());
}
tracing::warn!(space, endpoint = to.endpoint, "registration not confirmed");
@@ -655,13 +648,11 @@ impl Host {
LIFETIME,
);
let pds = identity::pds(writer, &doc, self.guarded.guard())?;
let asked = self.guarded.post(&format!("{pds}/xrpc/{NOTIFY_REVOKED}"))?;
let res = asked
.bearer_auth(service_auth::sign(signing, &claims))
.json(&json!({ "space": space, "credentials": jtis }))
.send()
.await?;
res.error_for_status()?;
let at = Xrpc::new(self.guarded.clone(), &pds).at_most(ANSWER_AT_MOST);
let auth = Auth::bearer(&service_auth::sign(signing, &claims));
let body = json!({ "space": space, "credentials": jtis });
let told = at.procedure::<IgnoredAny>(NOTIFY_REVOKED, Some(&body), Some(&auth));
told.await?;
Ok(())
}
@@ -702,11 +693,10 @@ impl Host {
};
// An authority not found, or naming no PDS yet, or none to be
// asked, may be found later.
let pds = self.identity.pds(&space.authority).await;
let url = pds.map(|pds| format!("{pds}/xrpc/{NOTIFY_REPO_UPDATE}"));
let Some(asked) = url.ok().and_then(|url| self.guarded.post(&url).ok()) else {
let Ok(pds) = self.identity.pds(&space.authority).await else {
return Delivery::Retry;
};
let at = Xrpc::new(self.guarded.clone(), &pds).at_most(ANSWER_AT_MOST);
let aud = space_host_aud(&space.authority);
let token = service_auth::sign(
&account.signing,
@@ -724,8 +714,7 @@ impl Host {
"repoRev": notice.rev,
"data": Value::Bytes(notice.data.clone()).to_json(),
});
let sent = asked.bearer_auth(token).json(&body).send().await;
delivery(sent)
deliver_to(&at, NOTIFY_REPO_UPDATE, &body, Some(&Auth::bearer(&token))).await
}
/// Tries `notice`, and keeps what came of it: owed no more, or owed
@@ -765,6 +754,6 @@ impl Host {
}
/// Whether a refusal says the same request may land later.
fn retryable(status: StatusCode) -> bool {
matches!(status.as_u16(), 408 | 425 | 429) || status.is_server_error()
fn retryable(status: u16) -> bool {
matches!(status, 408 | 425 | 429 | 500..=599)
}
crates/group-host/src/firehose.rs+8−3
@@ -5,14 +5,17 @@
//! And the relays, asked to read it.
use crate::Host;
use crate::api::ANSWER_AT_MOST;
use crate::store::Sequenced;
use atproto::stream::Frame;
use atproto::{Value, drisl};
use atproto_client::xrpc::Xrpc;
use atproto_server::Error;
use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
use axum::extract::{Query, State};
use axum::http::StatusCode;
use axum::response::Response;
use serde::de::IgnoredAny;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
@@ -23,6 +26,8 @@ const PAGE: u32 = 500;
/// How long between asking the relays to read the firehose.
pub const CRAWL_EVERY: Duration = Duration::from_secs(20 * 60);
const REQUEST_CRAWL: &str = "com.atproto.sync.requestCrawl";
/// Asks each relay `PDS_CRAWLERS` names to read the firehose
/// (`requestCrawl`), now and then every `every`, whether or not anything
/// was written. A relay that starts reading a host takes only the events
@@ -35,9 +40,9 @@ pub async fn crawling(host: Arc<Host>, every: Duration) {
let body = serde_json::json!({ "hostname": hostname.unwrap_or_default() });
loop {
for crawler in &host.config.crawlers {
let url = format!("{crawler}/xrpc/com.atproto.sync.requestCrawl");
let asked = host.http.post(url).json(&body).send().await;
match asked.and_then(|r| r.error_for_status()) {
let relay = Xrpc::new(host.http.clone(), crawler).at_most(ANSWER_AT_MOST);
let asked = relay.procedure::<IgnoredAny>(REQUEST_CRAWL, Some(&body), None);
match asked.await {
Ok(_) => tracing::info!(crawler, "asked the relay to crawl"),
Err(e) => tracing::warn!(crawler, error = %e, "requestCrawl failed"),
}
crates/group-host/src/import.rs+36−65
@@ -24,11 +24,10 @@
//! while the move is pending.
use crate::Host;
use crate::api::{ANSWER_AT_MOST, Params, REPO_AT_MOST, invalid, param, too_much};
use crate::api::{ANSWER_AT_MOST, Params, REPO_AT_MOST, invalid, param};
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::INTERNAL;
use crate::repo::{Asked, Write};
@@ -40,10 +39,12 @@ use atproto::plc::Signed;
use atproto::service_auth;
use atproto::{Cid, PublicKey, did};
use atproto_client::service_auth::{Error as Unverified, verify_with};
use atproto_client::sync;
use atproto_client::xrpc::Xrpc;
use atproto_server::Error;
use axum::Json;
use axum::extract::{Query, State};
use axum::http::{HeaderMap, StatusCode, header};
use axum::http::{HeaderMap, StatusCode};
use futures::StreamExt;
use rusqlite::{OptionalExtension, params};
use serde_json::{Value, json};
@@ -54,6 +55,8 @@ type Answer = Result<Json<Value>, Error>;
/// The method an account's token for moving here is for.
const CREATE_ACCOUNT: &str = "com.atproto.server.createAccount";
/// What an account's server says of itself.
const DESCRIBE_SERVER: &str = "com.atproto.server.describeServer";
/// The longest name and description a group's profile holds, in
/// characters: no more graphemes than its lexicon lets it have, and so no
/// more bytes.
@@ -229,10 +232,11 @@ impl Host {
if handle == "handle.invalid" || under(handle, &self.config.handle_domain) {
return false;
}
let url = format!("{pds}/xrpc/com.atproto.server.describeServer");
// A server that cannot say which domains it gives out may give out
// this one: the handle is not kept on a guess.
let Ok(described) = self.public_json(&url, "its server").await else {
let at = Xrpc::new(self.guarded.clone(), pds).at_most(ANSWER_AT_MOST);
let described = at.query::<Value>(DESCRIBE_SERVER, &[], None).await;
let Ok(described) = described else {
return false;
};
let domains = described["availableUserDomains"].as_array();
@@ -243,66 +247,31 @@ impl Host {
self.names(handle, did).await
}
/// GETs `url` of the account's server, with `query`.
async fn ask_server(
&self,
url: &str,
query: &[(&str, &str)],
) -> Result<reqwest::Response, Error> {
let asked = self.guarded.get(url).map_err(upstream)?;
let res = asked.query(query).send().await.map_err(upstream)?;
if !res.status().is_success() {
return Err(upstream(format!("{url} answered {}", res.status())));
}
Ok(res)
}
/// Every file `did` holds at `pds`, copied four at a time: how many
/// came. One that does not, or is not what it says, is left out, as a
/// file deleted there is.
async fn copy_blobs(&self, did: &str, pds: &str) -> Result<usize, Error> {
let list = format!("{pds}/xrpc/com.atproto.sync.listBlobs");
let mut cids: Vec<String> = Vec::new();
let mut cursor: Option<String> = None;
loop {
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 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);
cids.extend(listed.iter().filter_map(|c| c.as_str().map(String::from)));
if cursor.is_none() {
break;
}
}
let get = format!("{pds}/xrpc/com.atproto.sync.getBlob");
/// Every file `did` holds at `at`, its server, copied four at a time:
/// how many came. One that does not, or is not what it says, is left
/// out, as a file deleted there is.
async fn copy_blobs(&self, did: &str, at: &Xrpc) -> Result<usize, Error> {
let listing = sync::list_blobs(at, did).all().await;
let cids = listing.map_err(|e| upstream(format!("listBlobs: {e}")))?;
let most = self.config.blob_upload_limit as usize;
let at = at.clone().at_most(most);
let copies: Vec<_> = cids
.iter()
.map(|cid| self.copy_blob(did, &get, cid))
.map(|cid| self.copy_blob(did, &at, cid))
.collect();
let copies = futures::stream::iter(copies).buffer_unordered(4);
let came: Vec<bool> = copies.collect().await;
Ok(came.into_iter().filter(|c| *c).count())
}
/// The file `cid` of `did`'s, from `url`, kept: whether it came, as
/// The file `cid` of `did`'s, from `at`, kept: whether it came, as
/// what it says it is.
async fn copy_blob(&self, did: &str, url: &str, cid: &str) -> bool {
async fn copy_blob(&self, did: &str, at: &Xrpc, cid: &str) -> bool {
let came = async {
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 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")));
}
self.upload_blob(did, &bytes, &mime.unwrap_or_default())
let cid = Cid::parse(cid).map_err(upstream)?;
let blob = sync::get_blob(at, did, &cid).await.map_err(upstream)?;
let mime = blob.mime_type.unwrap_or_default();
self.upload_blob(did, &blob.bytes, &mime)
};
let came = came.await;
if let Err(e) = &came {
@@ -316,17 +285,19 @@ impl Host {
/// files, and its profile. A record this host would not keep (one not
/// of its collection's type) is left out.
async fn copy(&self, did: &str, plan: &Plan) -> Result<(usize, usize, Value), Error> {
let at = Xrpc::new(self.guarded.clone(), &plan.pds).at_most(ANSWER_AT_MOST);
// Its files first: its records hold them.
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 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",
"its repo is not the account's, signed and whole",
));
let blobs = self.copy_blobs(did, &at).await?;
let at = at.at_most(REPO_AT_MOST);
let writes = match repo_writes(&at, did, &plan.key).await {
Ok(writes) => writes,
Err(sync::Error::Invalid(_)) => {
return Err(refused(
"InvalidRepo",
"its repo is not the account's, signed and whole",
));
}
Err(e) => return Err(upstream(format!("getRepo: {e}"))),
};
let total = writes.len();
let writes: Vec<Write> = writes.into_iter().filter(keeps).collect();
crates/group-host/src/index.rs+83−203
@@ -6,133 +6,52 @@
//! writer's revision and digest as their host last said. When a writer's
//! digest is not the one the index came to, the index reads their repo:
//! from the store, for a writer here; otherwise from their PDS, as any
//! syncer reads a space, with a credential the group issues itself and a
//! secret agreed against the writer's `#atproto_kem` key for each request.
//! It reads on from its oplog when it has read the repo before, moving
//! the set hash by each write, and checks it against the commit their
//! host vouches for; or reads it whole, as a STAR archive, and checks it
//! the same way. A record that is not a DRISL map is left out.
//! syncer reads a space (`atproto_client::space`), with a credential the
//! group issues itself and a secret agreed against the writer's
//! `#atproto_kem` key for each request. It reads on from its oplog when it
//! has read the repo before, moving the set hash by each write, and checks
//! it against the commit their host vouches for; or reads it whole, as a
//! STAR archive, and checks it the same way. A record that is not a DRISL
//! map is left out.
use crate::Host;
use crate::authority::Access;
use crate::store::SpaceHead;
use crate::time::now_millis;
use anyhow::{Context, Result, bail, ensure};
use atproto::space::{
COMMIT_MAC, Commit, LtHash, accept_signature, check_commit_mac, element, encapsulate,
read_repo_star,
};
use atproto::space_auth::{self, Kind, Make, sign_request};
use atproto::{Cid, Curve, Keypair, Value, did, drisl};
use atproto_client::guard::Guarded;
use anyhow::{Context, Result, ensure};
use atproto::space::LtHash;
use atproto::space_auth::{self, Kind, Make};
use atproto::{Cid, Curve, Keypair, PublicKey, Value, did, drisl};
use atproto_client::identity;
use atproto_client::space::{self, Credential};
use atproto_client::xrpc::Xrpc;
use serde_json::Value as Json;
use std::collections::{BTreeMap, HashSet};
use std::collections::BTreeMap;
/// The most bytes a repo, or a page of its oplog, is read for.
pub const REPO_AT_MOST: usize = 64 * 1024 * 1024;
/// How many writes a page of an oplog is asked for.
const PAGE: &str = "500";
/// What the index learned of a repo: by path, each record's CID and
/// DRISL, or none for one taken out.
type Changes = BTreeMap<String, Option<(Cid, Vec<u8>)>>;
/// A writer's repo in a space, at their PDS, and how to ask for it.
/// A writer's repo in a space, at their PDS, and what lets the index read
/// it.
struct Remote {
space: String,
did: String,
pds: String,
/// For asking `pds`, a host others' data names.
client: Guarded,
kem: String,
/// `Atproto-Space-Credential <jwt>`, the group's to its own space.
authorization: String,
/// The key the credential is bound to.
key: Keypair,
}
/// An answer to a request that asked for a MAC: the key share asked with,
/// the secret agreed with it, and the answer's headers and body.
struct Vouched {
share: String,
secret: [u8; 32],
headers: reqwest::header::HeaderMap,
body: Vec<u8>,
}
impl Vouched {
/// An answer's header by its name in lower case.
fn header(&self, name: &str) -> Option<&str> {
self.headers.get(name).and_then(|v| v.to_str().ok())
}
}
impl Remote {
async fn ask(&self, method: &str, params: &[(&str, &str)]) -> Result<Vouched> {
let (share, secret) = encapsulate(&self.kem)?;
let url = format!("{}/xrpc/com.atproto.space.{method}", self.pds);
let mut req = self
.client
.get(&url)?
.query(&[("space", self.space.as_str()), ("repo", self.did.as_str())])
.query(params)
.header("accept-signature", accept_signature(COMMIT_MAC, &share));
for (k, v) in sign_request(&self.key, &self.authorization, &self.did)? {
req = req.header(k, v);
}
let res = req.send().await?.error_for_status()?;
let headers = res.headers().clone();
let body = crate::index_api::capped(res, REPO_AT_MOST).await;
let body = body.context("an answer past the most a repo is read for")?;
Ok(Vouched {
share,
secret,
headers,
body,
})
}
/// The commit `answer`'s MAC vouches for, if it is this repo's.
fn vouched(&self, answer: &Vouched) -> Result<Commit> {
let commit = check_commit_mac(|n| answer.header(n), &answer.share, &answer.secret)?;
let ours = commit.repo == self.did && commit.space == self.space;
ensure!(ours, "a commit of another repo");
Ok(commit)
}
}
/// A commit as `listRepoOps` and `getLatestCommit` write it in JSON.
fn commit_of(json: &Json) -> Result<Commit> {
let data = Value::from_json(&json["data"]);
let Ok(Value::Bytes(data)) = data else {
bail!("a commit with no data");
};
let text = |k: &str| {
json[k]
.as_str()
.map(String::from)
.context("a commit missing a field")
};
ensure!(json["ver"] == 1, "a commit of another version");
Ok(Commit {
repo: text("repo")?,
space: text("space")?,
rev: text("rev")?,
data: data
.as_slice()
.try_into()
.context("a commit's data is 32 bytes")?,
})
/// Their PDS, a host others' data names, read up to [`REPO_AT_MOST`].
at: Xrpc,
kem: PublicKey,
/// The group's to its own space.
credential: Credential,
}
/// A record's DRISL, if it is a map.
fn record_bytes(value: &Json) -> Option<Vec<u8>> {
match Value::from_json(value) {
Ok(v @ Value::Map(_)) => Some(drisl::encode(&v)),
_ => None,
}
let record = Value::from_json(value).ok();
let record = record.filter(|v| matches!(v, Value::Map(_)))?;
Some(drisl::encode(&record))
}
impl Host {
@@ -218,13 +137,10 @@ impl Host {
self.read_whole(&remote).await
}
/// `did`'s repo in `space`, at their PDS, with a credential to it the
/// group `authority` issues itself.
async fn remote(&self, space: &str, authority: &str, did: &str) -> Result<Remote> {
let doc = self.identity.document_now(did).await?;
let pds = identity::pds(did, &doc, self.guarded.guard())?;
let client = self.guarded.clone();
let kem = did::kem_key(&doc).context("a writer with no #atproto_kem key")?;
/// A credential to `space` that the group `authority` issues itself,
/// bound to a key made for it alone: what the host reads its groups'
/// spaces at their writers' PDSes with, as any syncer would.
pub(crate) fn own_credential(&self, authority: &str, space: &str) -> Result<Credential> {
let key = Keypair::generate(Curve::P256);
let signing = self
.store
@@ -239,85 +155,58 @@ impl Host {
..Make::default()
};
let now = now_millis() as u64 / 1000;
let credential = space_auth::create(Kind::Credential, &make, &signing, now);
let credential = credential?;
let jwt = space_auth::create(Kind::Credential, &make, &signing, now)?;
Ok(Credential::new(&jwt, key)?)
}
/// `did`'s repo in `space`, at their PDS, with a credential to it the
/// group `authority` issues itself.
async fn remote(&self, space: &str, authority: &str, did: &str) -> Result<Remote> {
let doc = self.identity.document_now(did).await?;
let pds = identity::pds(did, &doc, self.guarded.guard())?;
let kem = did::kem_key(&doc).context("a writer with no #atproto_kem key")?;
Ok(Remote {
space: space.into(),
did: did.into(),
pds,
client,
kem: kem.did_key(),
authorization: format!("Atproto-Space-Credential {credential}"),
key,
at: Xrpc::new(self.guarded.clone(), &pds).at_most(REPO_AT_MOST),
kem,
credential: self.own_credential(authority, space)?,
})
}
/// Reads on from `from`: each page of the writes since, the set hash
/// moved by each, checked against the commit they come to.
async fn read_on(&self, remote: &Remote, from: &SpaceHead) -> Result<()> {
let mut hash = LtHash::from_state(&from.state)?;
let mut last: BTreeMap<String, Json> = BTreeMap::new();
let mut cursor: Option<String> = None;
let mut seen = HashSet::new();
let (page, answer) = loop {
let mut params = vec![("since", from.rev.as_str()), ("limit", PAGE)];
if let Some(c) = &cursor {
params.push(("cursor", c));
}
let answer = remote.ask("listRepoOps", &params).await?;
let page: Json = serde_json::from_slice(&answer.body)?;
for op in page["ops"].as_array().context("a page with no ops")? {
let (collection, rkey) = (
op["collection"]
.as_str()
.context("an op with no collection")?,
op["rkey"].as_str().context("an op with no rkey")?,
);
let cid_of = |k: &str| op[k].as_str().map(Cid::parse).transpose();
if let Some(prev) = cid_of("prev")? {
hash.remove(&element(collection, rkey, &prev));
}
if let Some(cid) = cid_of("cid")? {
hash.add(&element(collection, rkey, &cid));
}
last.insert(format!("{collection}/{rkey}"), op.clone());
}
cursor = page["cursor"].as_str().map(String::from);
// A server that answers a page it gave would be read forever.
ensure!(seen.insert(cursor.clone()), "the oplog repeats a page");
if cursor.is_none() {
break (page, answer);
}
};
// Every page carries the repo's head; the last one's is where the
// oplog leads.
let commit = remote.vouched(&answer)?;
let written = commit_of(&page["commit"]).context("the oplog's head with no commit")?;
ensure!(written == commit, "a commit not the one vouched for");
ensure!(
hash.digest() == commit.data,
"the oplog does not come to its commit"
let hash = LtHash::from_state(&from.state)?;
let writer = (remote.did.as_str(), &remote.kem);
let since = (Some(from.rev.as_str()), None);
let read = space::list_repo_ops(
&remote.at,
&remote.credential,
writer,
since,
hash,
usize::MAX,
);
let oplog = read.await?;
let (changed, unreadable) = oplog.changes(|_| true)?;
// A record that is not what its write made was written again
// since: the repo is read whole instead.
ensure!(unreadable.is_empty(), "a record not of its CID");
let mut changes = Changes::new();
for (path, op) in last {
let put = match op["cid"].as_str() {
for change in changed {
let put = match change.value {
None => None,
Some(cid) => {
// Its value as it is now: one written again since is
// another, and the repo is read whole instead.
let bytes = record_bytes(&op["value"]).context("a write with no record")?;
ensure!(
Cid::of_cbor(&bytes).to_string() == cid,
"a record not of its CID"
);
Some(value) => {
let bytes = record_bytes(&value).context("a write that is no record")?;
Some((Cid::of_cbor(&bytes), bytes))
}
};
changes.insert(path, put);
changes.insert(format!("{}/{}", change.collection, change.rkey), put);
}
let head = SpaceHead {
rev: commit.rev,
state: hash.state(),
rev: oplog.commit.rev,
state: oplog.hash.state(),
};
self.store.index(
&remote.space,
@@ -332,38 +221,29 @@ impl Host {
/// Reads the repo whole, from its STAR archive, checked against the
/// commit it opens with.
async fn read_whole(&self, remote: &Remote) -> Result<()> {
let answer = remote.ask("getRepo", &[]).await?;
let (commit, records) = read_repo_star(
&answer.body,
&remote.space,
&remote.did,
&answer.share,
&answer.secret,
|n| answer.header(n),
)?;
let mut hash = LtHash::default();
let mut changes = Changes::new();
for (path, bytes) in records {
let (collection, rkey) = path.split_once('/').expect("a record's path");
let cid = Cid::of_cbor(&bytes);
hash.add(&element(collection, rkey, &cid));
// Hashed as it is, kept only if it is a record.
match drisl::decode(&bytes) {
Ok(Value::Map(_)) => {
changes.insert(path, Some((cid, bytes)));
}
_ => tracing::warn!(
space = remote.space,
repo = remote.did,
path,
"a record that is not a DRISL map, left out"
),
}
let writer = (remote.did.as_str(), &remote.kem);
let repo = space::get_repo(&remote.at, &remote.credential, writer).await?;
// Hashed as it is, kept only if it is a record.
for left in &repo.unreadable {
tracing::warn!(
space = remote.space,
repo = remote.did,
path = format!("{}/{}", left.collection, left.rkey),
"a record that is not a DRISL map, left out"
);
}
let changes = repo
.records
.iter()
.map(|r| {
let bytes = record_bytes(&r.value).expect("a record read whole is a map");
(format!("{}/{}", r.collection, r.rkey), Some((r.cid, bytes)))
})
.collect();
// The archive's records came to its commit as it was read.
let head = SpaceHead {
rev: commit.rev,
state: hash.state(),
rev: repo.commit.rev,
state: repo.hash.state(),
};
self.store.index(
&remote.space,
crates/group-host/src/index_api.rs+8−42
@@ -13,9 +13,10 @@ use crate::store::Indexed;
use crate::time::iso;
use crate::xrpc::internal;
use atproto::space::SpaceRef;
use atproto::space_auth::{self, Kind, Make, sign_request};
use atproto::{Cid, Curve, Keypair, drisl};
use atproto::{Cid, drisl};
use atproto_client::identity;
use atproto_client::space;
use atproto_client::xrpc::Xrpc;
use atproto_server::Error;
use axum::Json;
use axum::extract::{Query, State};
@@ -236,46 +237,11 @@ impl Host {
}
let doc = self.identity.document_now(repo).await.ok()?;
let pds = identity::pds(repo, &doc, self.guarded.guard()).ok()?;
let asked = self
.guarded
.get(&format!("{pds}/xrpc/com.atproto.space.getBlob"));
let asked = asked.ok()?;
let key = Keypair::generate(Curve::P256);
let signing = self.store.account(group).ok()??.signing;
let kid = key.public().did_key();
let make = Make {
iss: group,
sub: space,
key_id: Some(&kid),
..Make::default()
};
let now = crate::time::now_millis() as u64 / 1000;
let credential = space_auth::create(Kind::Credential, &make, &signing, now).ok()?;
let authorization = format!("Atproto-Space-Credential {credential}");
let mut req = asked.query(&[("space", space), ("repo", repo), ("cid", &cid.to_string())]);
for (k, v) in sign_request(&key, &authorization, repo).ok()? {
req = req.header(k, v);
}
let res = req.send().await.ok()?.error_for_status().ok()?;
let mime = res
.headers()
.get(header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok());
let mime = mime.unwrap_or("application/octet-stream").to_string();
let bytes = capped(res, FILE_AT_MOST).await?;
let at = Xrpc::new(self.guarded.clone(), &pds).at_most(FILE_AT_MOST);
let credential = self.own_credential(group, space).ok()?;
// What the writer sent must be the file asked for.
(Cid::of_raw(&bytes) == *cid).then_some((mime, bytes))
}
}
/// A response's bytes, if they are no more than `max`.
pub(crate) async fn capped(mut res: reqwest::Response, max: usize) -> Option<Vec<u8>> {
let mut bytes = Vec::new();
while let Some(chunk) = res.chunk().await.ok()? {
bytes.extend_from_slice(&chunk);
if bytes.len() > max {
return None;
}
let blob = space::get_blob(&at, &credential, repo, cid).await.ok()?;
let mime = blob.mime_type.unwrap_or("application/octet-stream".into());
Some((mime, blob.bytes.to_vec()))
}
Some(bytes)
}
crates/group-host/src/migration.rs+52−72
@@ -28,25 +28,28 @@
//! `com.atproto.memberspace.member` policy state; and its writers.
use crate::Host;
use crate::api::{ANSWER_AT_MOST, Params, REPO_AT_MOST, invalid, param, too_much};
use crate::api::{ANSWER_AT_MOST, Params, REPO_AT_MOST, invalid, param};
use crate::group::did_rkey;
use crate::group_api::signed_in;
use crate::import_space::MEMBER;
use crate::index_api::capped;
use crate::rbac::INTERNAL;
use crate::repo::{Asked, Write};
use crate::store::{Account, Space, Store};
use crate::time::now_millis;
use crate::xrpc::internal;
use anyhow::Result;
use atproto::mst::{Blocks, Tree};
use atproto::service_auth::{self, Claims};
use atproto::space::{
LtHash, SPACE_META, SPACE_META_VERSION, SpaceRef, element, read_space_meta, read_star, star,
write_star,
};
use atproto::{Cid, Curve, Keypair, car, did, drisl, jose, mst::Tree};
use atproto::{Cid, Curve, Keypair, PublicKey, did, drisl, jose};
use atproto_client::sync;
use atproto_client::xrpc::Xrpc;
use atproto_server::Error;
use axum::Json;
use axum::body::Bytes;
use axum::extract::{Query, State};
use axum::http::{HeaderMap, StatusCode, header};
use axum::response::{IntoResponse, Response};
@@ -61,18 +64,13 @@ type Answer = Result<Json<Value>, Error>;
const EXPORT_FOR: i64 = 60 * 60_000;
/// The method the group's service token is for.
pub const RECEIVE: &str = "org.atgrp.internal.migrateReceive";
/// The method the group's export is pulled with.
const EXPORT: &str = "org.atgrp.internal.migrateExport";
fn refused(error: &'static str, message: impl Into<String>) -> Error {
Error::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, Error> {
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) -> Error {
Error::new(
StatusCode::BAD_GATEWAY,
@@ -326,23 +324,20 @@ pub(crate) fn create(path: &str, value: &[u8]) -> Option<Write> {
})
}
/// The records of a repo's CAR, once its commit is `group`'s, at a TID,
/// signed by `key` (`atproto::Commit::verified`), and its tree and records
/// are whole.
pub(crate) fn repo_writes(
bytes: &[u8],
group: &str,
key: &atproto::PublicKey,
) -> Option<Vec<Write>> {
let repo = car::read(bytes).ok()?;
let root = repo.roots.first()?;
let commit = atproto::Commit::verified(repo.blocks.get(root)?, group, key).ok()?;
let tree = Tree::read(commit.data, &repo.blocks).ok()?;
let leaves = tree.leaves();
leaves
.into_iter()
.map(|(path, cid)| create(path, repo.blocks.get(&cid)?))
.collect()
/// The records of `did`'s repo, as the host `at` calls answers
/// `getRepo` (`atproto_client::sync`), once its commit is `did`'s, signed
/// by `key`, and its tree and records are whole: one that is not is
/// `sync::Error::Invalid`.
pub(crate) async fn repo_writes(
at: &Xrpc,
did: &str,
key: &PublicKey,
) -> Result<Vec<Write>, sync::Error> {
let export = sync::get_repo(at, did, key, Blocks::new()).await?;
let (_, records) = export.records().await?;
let writes = records.iter().map(|(path, value)| create(path, value));
let not_drisl = sync::Error::Invalid("a record that is not DRISL".into());
writes.collect::<Option<_>>().ok_or(not_drisl)
}
/// The records of `group`'s repo in `space`, from its STAR archive, once
@@ -385,33 +380,21 @@ pub fn handle_here(handle: &str, address: Option<&str>, domain: &str) -> (String
}
impl Host {
/// GETs `part` of the group's export from its host at `pds`.
/// `part` of the group's export from its host at `pds`, read up to
/// `at_most` bytes: an answer other than a success is the host's to
/// say, not read as one.
async fn pull(
&self,
pds: &str,
group: &str,
token: &str,
(pds, group, token): (&str, &str, &str),
extra: &[(&str, &str)],
) -> Result<reqwest::Response, Error> {
let url = format!("{pds}/xrpc/org.atgrp.internal.migrateExport");
at_most: usize,
) -> Result<Bytes, Error> {
let mut query = vec![("group", group), ("token", token)];
query.extend_from_slice(extra);
self.ask_source(&url, &query).await
}
/// GETs `url` of the group's host, with `query`: an answer other than
/// a success is the host's to say, not read as one.
async fn ask_source(
&self,
url: &str,
query: &[(&str, &str)],
) -> Result<reqwest::Response, Error> {
let asked = self.guarded.get(url).map_err(source)?;
let res = asked.query(query).send().await.map_err(source)?;
if !res.status().is_success() {
return Err(source(format!("{url} answered {}", res.status())));
}
Ok(res)
let at = Xrpc::new(self.guarded.clone(), pds).at_most(at_most);
let read = at.query_raw(EXPORT, &query, None).await;
read.map(|(_, body)| body)
.map_err(|e| source(format!("{EXPORT}: {e}")))
}
}
@@ -536,12 +519,15 @@ pub async fn migrate_receive(
};
// Its public repo, checked against the group's key.
let url = format!("{pds}/xrpc/com.atproto.sync.getRepo");
let res = host.ask_source(&url, &[("did", group)]).await?;
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"))?;
let at = Xrpc::new(host.guarded.clone(), &pds).at_most(REPO_AT_MOST);
let writes = match repo_writes(&at, group, &key).await {
Ok(writes) => writes,
Err(sync::Error::Invalid(why)) => {
let why = format!("a repo that is not the group's, signed and whole: {why}");
return Err(source(why));
}
Err(e) => return Err(source(format!("getRepo: {e}"))),
};
let account = take_in(&host, group, &handle, &here).await?;
let received = receive(&host, group, &me, &pds, token, snapshot, writes).await;
@@ -582,17 +568,17 @@ async fn receive(
};
// Its files first: its records hold them.
let res = host.pull(pds, group, token, &[("part", "blobs")]).await?;
let listed: Value = json_at_most(res).await?;
let from = (pds, group, token);
let listed = host
.pull(from, &[("part", "blobs")], ANSWER_AT_MOST)
.await?;
let listed: Value = serde_json::from_slice(&listed).map_err(source)?;
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 most = host.config.blob_upload_limit as usize;
let read = capped(res, most).await;
let bytes = read.ok_or(source(too_much(most)))?;
let asked = [("part", "blob"), ("cid", cid)];
let bytes = host.pull(from, &asked, most).await?;
if Cid::of_raw(&bytes).to_string() != cid {
return Err(source(format!("the file {cid} is not what it says")));
}
@@ -615,18 +601,12 @@ async fn receive(
if space.authority != group {
return Err(invalid(format!("{uri} is not one of the group's spaces")));
}
let res = host
.pull(pds, group, token, &[("part", "meta"), ("space", uri)])
.await?;
let read = capped(res, REPO_AT_MOST).await;
let bytes = read.ok_or(source(too_much(REPO_AT_MOST)))?;
let meta = [("part", "meta"), ("space", uri.as_str())];
let bytes = host.pull(from, &meta, REPO_AT_MOST).await?;
let meta = read_space_meta(&bytes).map_err(source)?;
host.keep_space_meta(group, meta)?;
let res = host
.pull(pds, group, token, &[("part", "repo"), ("space", uri)])
.await?;
let read = capped(res, REPO_AT_MOST).await;
let bytes = read.ok_or(source(too_much(REPO_AT_MOST)))?;
let repo = [("part", "repo"), ("space", uri.as_str())];
let bytes = host.pull(from, &repo, REPO_AT_MOST).await?;
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/src/oauth_clients.rs+1−1
crates/group-host/src/proxy.rs+1−1
crates/group-host/src/xrpc.rs+15−1
crates/group-host/tests/migration.rs+1−4