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

The host resolves identities and asks others' hosts with atproto-client

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:client/0.1
.changeset/atproto-client.mdnew+9−0
@@ -0,0 +1,9 @@
---
default: minor
---
# Identities, guarded requests and service tokens by atproto-client
The host resolves identities, asks the hosts others' data names, and checks a space's delegation tokens and a group's token for moving here with the `atproto-client` crate. Its requests to such hosts now share one pool of connections rather than a client each. Whose a handle is, it keeps five minutes as it keeps DID documents, but asks again to check a group's own domain or an account moving here. `HANDLE_RESOLVERS` names a handle's own `/.well-known/atproto-did` as `well-known`, asked over the scheme `DID_WEB_SCHEME` says, where it was `well-known:<scheme>`: the host refuses to start with the old form. With `DID_WEB_SCHEME=http`, as on a test network, a handle may be any name, as `127.0.0.1:2584`. `atgrp` calls hosts and its own PDS through the same crate.
Each call the host makes to resolve an identity or check a token is logged as a `call` line, attempt by attempt, in the trace of the request it is made for, and sends a `traceparent` naming that trace; a refusal it is answered with is logged as `refused`.
crates/atgrp/src/lib.rs+70−66
@@ -15,6 +15,8 @@ use anyhow::{Context, Result, anyhow, bail};
use atproto::keys::{Curve, Keypair};
use atproto::space::{SPACE_URI_PREFIX, SpaceRecordUri, SpaceRef};
use atproto::{did, dpop};
use atproto_client::service_auth;
use atproto_client::xrpc::{self, Auth, Xrpc};
use group_host_mcp::{Plan, Tool};
use serde_json::{Value, json};
use std::collections::HashMap;
@@ -193,8 +195,9 @@ pub struct Host {
/// A person signed in at their PDS.
pub struct Client {
http: reqwest::Client,
pds: String,
access: String,
/// Their PDS, asked as them.
pds: Xrpc,
auth: Auth,
/// Who they are.
pub did: String,
}
@@ -211,74 +214,80 @@ async fn answer(res: reqwest::Response, what: &str) -> Result<Value> {
Ok(body)
}
/// Why `what` failed, said as [`answer`] says it: the server's refusal,
/// its status, error and message; or that `at` could not be reached.
fn failed(what: &str, at: &str, e: xrpc::Error) -> anyhow::Error {
let Some(refused) = e.xrpc() else {
return anyhow::Error::new(e).context(format!("reaching {at}"));
};
let status = reqwest::StatusCode::from_u16(refused.status).map(|s| s.to_string());
let (error, message) = (&refused.error, &refused.message);
anyhow!("{what}: {} {error} {message}", status.unwrap_or_default())
}
/// What `at` answered `what` with, or why it failed ([`failed`]).
fn said<T>(what: &str, at: &str, said: Result<T, xrpc::Error>) -> Result<T> {
said.map_err(|e| failed(what, at, e))
}
impl Client {
/// Signs `handle` in at `pds` with `password`.
pub async fn sign_in(pds: &str, handle: &str, password: &str) -> Result<Client> {
let http = reqwest::Client::new();
let sent = http
.post(format!("{pds}/xrpc/com.atproto.server.createSession"))
.json(&json!({"identifier": handle, "password": password}))
.send()
.await;
let res = sent.with_context(|| format!("reaching {pds}"))?;
let session = answer(res, &format!("signing in as {handle}")).await?;
let at = Xrpc::new(http.clone(), pds);
let body = json!({"identifier": handle, "password": password});
let signed = at.procedure("com.atproto.server.createSession", Some(&body), None);
let signed: Result<Value, _> = signed.await;
let session = said(&format!("signing in as {handle}"), pds, signed)?;
let field = |k: &str| text(&session[k]).to_string();
Ok(Client {
http,
pds: pds.into(),
access: field("accessJwt"),
pds: at,
auth: Auth::bearer(text(&session["accessJwt"])),
did: field("did"),
})
}
/// A service token from the person's PDS, for `aud`'s `lxm`.
async fn token(&self, aud: &str, lxm: &str) -> Result<String> {
let url = format!("{}/xrpc/com.atproto.server.getServiceAuth", self.pds);
let asked = self.http.get(url).query(&[("aud", aud), ("lxm", lxm)]);
let res = asked.bearer_auth(&self.access).send().await?;
let said = answer(res, &format!("a token for {lxm}")).await?;
Ok(text(&said["token"]).to_string())
let token = service_auth::token(&self.pds, &self.auth, aud, Some(lxm), None).await;
said(&format!("a token for {lxm}"), self.pds.base(), token)
}
/// `host` called as the person, with a service token for `lxm`.
async fn at(&self, host: &Host, lxm: &str) -> Result<(Xrpc, Auth)> {
let token = self.token(&host.did, lxm).await?;
Ok((
Xrpc::new(self.http.clone(), &host.url),
Auth::bearer(&token),
))
}
/// `host`'s procedure `lxm`, with `body`.
pub async fn call(&self, host: &Host, lxm: &str, body: &Value) -> Result<Value> {
let token = self.token(&host.did, lxm).await?;
let url = format!("{}/xrpc/{lxm}", host.url);
let sent = self.http.post(url).bearer_auth(token).json(body).send();
let res = sent
.await
.with_context(|| format!("reaching {}", host.url))?;
answer(res, lxm).await
let (at, auth) = self.at(host, lxm).await?;
let answer = at.procedure(lxm, Some(body), Some(&auth)).await;
said(lxm, &host.url, answer)
}
/// `host`'s query `lxm`, with `params`.
pub async fn query(&self, host: &Host, lxm: &str, params: &[(&str, &str)]) -> Result<Value> {
let token = self.token(&host.did, lxm).await?;
let url = format!("{}/xrpc/{lxm}", host.url);
let sent = self.http.get(url).bearer_auth(token).query(params).send();
let res = sent
.await
.with_context(|| format!("reaching {}", host.url))?;
answer(res, lxm).await
let (at, auth) = self.at(host, lxm).await?;
let answer = at.query(lxm, params, Some(&auth)).await;
said(lxm, &host.url, answer)
}
/// `nsid` of the person's own PDS, as them: a query with `params`, or
/// with `body`, a procedure (one that takes none with a null body).
async fn own(
&self,
nsid: &str,
params: &[(&str, &str)],
body: Option<&Value>,
) -> Result<Value> {
let url = format!("{}/xrpc/{nsid}", self.pds);
let asked = match body {
Some(Value::Null) => self.http.post(url),
Some(body) => self.http.post(url).json(body),
None => self.http.get(url),
};
let sent = asked.query(params).bearer_auth(&self.access).send().await;
let res = sent.context(format!("reaching {}", self.pds))?;
answer(res, nsid).await
/// The query `nsid` of the person's own PDS, as them, with `params`.
async fn own_query(&self, nsid: &str, params: &[(&str, &str)]) -> Result<Value> {
let answer = self.pds.query(nsid, params, Some(&self.auth)).await;
said(nsid, self.pds.base(), answer)
}
/// The procedure `nsid` of the person's own PDS, as them, with `body`,
/// or none for one that takes none.
async fn own_call(&self, nsid: &str, body: Option<&Value>) -> Result<Value> {
let answer = self.pds.procedure(nsid, body, Some(&self.auth)).await;
said(nsid, self.pds.base(), answer)
}
/// The bytes `nsid` of the person's own PDS answers with `params`, and
@@ -288,21 +297,16 @@ impl Client {
nsid: &str,
params: &[(&str, &str)],
) -> Result<Option<(Vec<u8>, String)>> {
let url = format!("{}/xrpc/{nsid}", self.pds);
let asked = self.http.get(url).query(params).bearer_auth(&self.access);
let res = asked.send().await;
let res = res.context(format!("reaching {}", self.pds))?;
let kind = res
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok());
let read = self.pds.query_raw(nsid, params, Some(&self.auth)).await;
let errored = read.as_ref().err().and_then(xrpc::Error::xrpc);
let none = errored.is_some_and(|r| r.error == "RepoNotFound");
let (headers, bytes) = match none {
true => return Ok(None),
false => said(nsid, self.pds.base(), read)?,
};
let kind = headers.get("content-type").and_then(|v| v.to_str().ok());
let kind = kind.unwrap_or("application/octet-stream").to_string();
if !res.status().is_success() {
let said = answer(res, nsid).await.expect_err("a refusal");
let none = format!("{said}").contains("RepoNotFound");
return none.then_some(None).ok_or(said);
}
Ok(Some((res.bytes().await?.to_vec(), kind)))
Ok(Some((bytes.to_vec(), kind)))
}
/// `host`'s procedure `lxm` with `params`, taking `bytes` of `kind`.
@@ -1161,7 +1165,7 @@ async fn start_import(
let mut spaces = Vec::new();
// Only a server that says it holds spaces has any to bring.
let described = theirs
.own("com.atproto.server.describeServer", &[], None)
.own_query("com.atproto.server.describeServer", &[])
.await?;
let holds = described["spacesAlpha"] == true;
let mut cursor = holds.then_some(String::new());
@@ -1169,7 +1173,7 @@ async fn start_import(
let mut page = vec![("limit", "100")];
page.extend((!after.is_empty()).then_some(("cursor", after.as_str())));
let listed = theirs
.own("com.atproto.space.listSpaces", &page, None)
.own_query("com.atproto.space.listSpaces", &page)
.await?;
let uris = listed["spaces"].as_array().into_iter().flatten();
spaces.extend(uris.map(|s| text(&s["space"]).to_string()));
@@ -1193,7 +1197,7 @@ async fn start_import(
let mut page = at.to_vec();
page.extend((!after.is_empty()).then_some(("cursor", after.as_str())));
let listed = theirs
.own("com.atproto.space.listBlobs", &page, None)
.own_query("com.atproto.space.listBlobs", &page)
.await?;
for cid in listed["cids"].as_array().into_iter().flatten() {
let at = [at[0], at[1], ("cid", text(cid))];
@@ -1217,7 +1221,7 @@ async fn start_import(
spaces.len()
);
let ask = "com.atproto.identity.requestPlcOperationSignature";
theirs.own(ask, &[], Some(&Value::Null)).await?;
theirs.own_call(ask, None).await?;
out += &format!(
"its server has emailed a code to move its identity; finish with\n atgrp account import {account} --code <code>\n"
);
@@ -1238,7 +1242,7 @@ async fn finish_import(
let mut asked = creds.clone();
asked.insert("token".into(), json!(code.trim()));
let sign = "com.atproto.identity.signPlcOperation";
let signed = theirs.own(sign, &[], Some(&Value::Object(asked))).await?;
let signed = theirs.own_call(sign, Some(&Value::Object(asked))).await?;
let body = json!({ "did": did, "operation": signed["operation"] });
let done = me.call(host, &internal("completeImport"), &body).await?;
Ok(format!(
crates/atgrp/Cargo.toml+1−0
@@ -13,6 +13,7 @@ workspace = true
[dependencies]
anyhow.workspace = true
atproto.workspace = true
atproto-client.workspace = true
group-host-mcp.workspace = true
reqwest.workspace = true
serde_json.workspace = true
crates/group-host/src/account_move.rs+7−3
@@ -266,7 +266,7 @@ impl Host {
body: Option<&Value>,
) -> Result<reqwest::Response, XrpcError> {
let url = format!("{}/xrpc/{nsid}", m.pds);
let (pinned, at) = self.pinned(&url).await.map_err(upstream)?;
self.guarded.guard().may_ask(&url).map_err(upstream)?;
if m.expires_at - EARLY <= now_millis() {
self.renew(mover, m).await?;
}
@@ -283,7 +283,11 @@ impl Host {
let mut claims = dpop::Claims::new(method.as_str(), &url, now).token(&m.access);
claims.nonce = nonce.clone();
let proof = dpop::sign(&key, &claims);
let mut req = pinned.request(method.clone(), at.clone()).query(query);
let req = self
.guarded
.request(method.clone(), &url)
.map_err(upstream)?;
let mut req = req.query(query);
req = req.header("authorization", format!("DPoP {}", m.access));
req = req.header("dpop", proof);
// A procedure that takes no body is sent none.
@@ -480,7 +484,7 @@ pub async fn get_account_move(State(host): State<Arc<Host>>, headers: HeaderMap)
else {
return Ok(Json(json!({})));
};
let doc = host.identity.document(&m.did).await.ok();
let doc = host.identity.document_now(&m.did).await.ok();
let handle = doc.as_ref().and_then(did::handle);
let pending = host
.store
crates/group-host/src/actors.rs+3−7
@@ -26,7 +26,7 @@ pub async fn get_viewer(State(host): State<Arc<Host>>, headers: HeaderMap) -> An
return Ok(Json(json!({ "signUpAt": signup })));
};
let mut actor = json!({"did": me, "canCreateGroup": host.may_found(&me)});
let doc = host.identity.document(&me).await.ok();
let doc = host.identity.document_now(&me).await.ok();
if let Some(handle) = doc.as_ref().and_then(did::handle) {
actor["handle"] = json!(handle);
}
@@ -44,7 +44,7 @@ impl Host {
/// A person as a list names them: their DID, and the handle their DID
/// document names, if it can be read.
pub(crate) async fn actor_view(&self, did: &str) -> Value {
let doc = self.identity.document(did).await.ok();
let doc = self.identity.document_now(did).await.ok();
match doc.as_ref().and_then(did::handle) {
Some(handle) => json!({"did": did, "handle": handle}),
None => json!({"did": did}),
@@ -139,11 +139,7 @@ pub async fn get_actor_groups(
let asked = param(&p, "actor")?.trim_start_matches('@').to_lowercase();
let actor = match asked.starts_with("did:") {
true => Some(asked.clone()),
false => {
host.identity
.resolve_handle(&asked, &host.config.handle_resolvers)
.await
}
false => host.identity.resolve_handle(&asked).await.ok(),
};
let not_found = || XrpcError::new(StatusCode::BAD_REQUEST, "ActorNotFound", "no such actor");
let actor = actor.ok_or_else(not_found)?;
crates/group-host/src/api.rs+1−4
@@ -256,10 +256,7 @@ pub async fn resolve_handle(
.await?
.is_some()
{
did = host
.identity
.resolve_handle(&handle, &host.config.handle_resolvers)
.await;
did = host.identity.resolve_handle(&handle).await.ok();
}
let not_found = || {
XrpcError::new(
crates/group-host/src/apps.rs+2−2
@@ -141,8 +141,8 @@ impl Host {
async fn read_logo(&self, id: &str, now: i64) -> Option<Logo> {
let view = self.client_view(id, now).await?;
let (pinned, at) = self.pinned(view["logo"].as_str()?).await.ok()?;
let res = pinned.get(at).send().await.ok()?;
let asked = self.guarded.get(view["logo"].as_str()?).ok()?;
let res = asked.send().await.ok()?;
let res = res.error_for_status().ok()?;
let bytes = capped(res, LOGO_AT_MOST).await?;
let kind = image_kind(&bytes)?;
crates/group-host/src/authority.rs+22−24
@@ -18,7 +18,6 @@
//! or a day has passed, as pds.js's `outbox.js` does.
use crate::Host;
use crate::guard::pinned_client;
use crate::index_api::capped;
use crate::rbac::Policy;
use crate::repo::invalid;
@@ -32,8 +31,10 @@ use atproto::service_auth::{self, Claims};
use atproto::space::SpaceRef;
use atproto::space_auth::{self, space_host_aud};
use atproto::{Value, jose, syntax};
use atproto_client::guard::Guarded;
use atproto_client::identity;
use axum::http::StatusCode;
use futures::future::join_all;
use futures::future::{OptionFuture, join_all};
use futures::{StreamExt, stream};
use serde_json::{Value as Json, json};
@@ -160,8 +161,9 @@ fn delivery(sent: reqwest::Result<reqwest::Response>) -> Delivery {
#[derive(Clone)]
struct Syncers {
store: Store,
/// Whether the host is on http, and so may call endpoints on http.
http_here: bool,
/// For the endpoints syncers chose, held as the host holds any host
/// others' data names.
guarded: Guarded,
}
impl Syncers {
@@ -172,11 +174,11 @@ impl Syncers {
to.endpoint.trim_end_matches('/')
);
// The syncer chose the endpoint: it is fetched as one not trusted.
let Ok((client, at)) = pinned_client(&url, self.http_here).await else {
return Delivery::Retry;
};
// A refused endpoint is as one that did not answer.
let body = json!({"space": space, "token": to.token, "update": update});
delivery(client.post(at).json(&body).send().await)
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)
}
/// Tells each syncer registered for `space` of `update`, a change to
@@ -423,7 +425,7 @@ impl Host {
fn syncers(&self) -> Syncers {
Syncers {
store: self.store.clone(),
http_here: self.config.public_url.starts_with("http://"),
guarded: self.guarded.clone(),
}
}
@@ -513,8 +515,8 @@ impl Host {
let echoed = async {
// The syncer chose the endpoint: it is fetched as one not
// trusted.
let (client, at) = self.pinned(&url).await.ok()?;
let res = client.post(at).json(&body).send().await.ok()?;
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)
@@ -657,12 +659,11 @@ impl Host {
space: &str,
jtis: &[String],
) -> Result<()> {
let doc = self.identity.document(writer).await?;
let doc = self.identity.document_now(writer).await?;
let claims = self.claims(authority, writer, NOTIFY_REVOKED);
let pds = self.at_pds(&doc, NOTIFY_REVOKED).await;
let (client, at) = pds.map_err(anyhow::Error::msg)?;
let res = client
.post(at)
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()
@@ -706,14 +707,11 @@ impl Host {
let Ok(Some(account)) = self.store.account(&notice.repo) else {
return Delivery::Failed;
};
let doc = match self.identity.kept(&space.authority) {
Some(doc) => Ok(doc),
None => self.identity.document(&space.authority).await,
};
// An authority not found, or naming no PDS yet, or none to be
// asked ([`crate::guard`]), may be found later.
let doc = doc.unwrap_or_default();
let Ok((client, at)) = self.at_pds(&doc, NOTIFY_REPO_UPDATE).await else {
// 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 {
return Delivery::Retry;
};
let aud = space_host_aud(&space.authority);
@@ -727,7 +725,7 @@ impl Host {
"repoRev": notice.rev,
"data": Value::Bytes(notice.data.clone()).to_json(),
});
let sent = client.post(at).bearer_auth(token).json(&body).send().await;
let sent = asked.bearer_auth(token).json(&body).send().await;
delivery(sent)
}
crates/group-host/src/authority_api.rs+8−12
@@ -11,8 +11,9 @@ use crate::space_api::{credential, forbidden, now, refused, service_caller};
use crate::store::{Registration, Space};
use crate::xrpc::XrpcError;
use atproto::space::SpaceRef;
use atproto::space_auth::{self, Expect, Kind, Make, space_host_aud};
use atproto::space_auth::{self, Kind, Make, space_host_aud};
use atproto::{PublicKey, Value as Drisl, syntax, tid};
use atproto_client::service_auth;
use axum::Json;
use axum::extract::{Query, State};
use axum::http::{HeaderMap, StatusCode};
@@ -197,17 +198,12 @@ async fn delegated(
space: &SpaceRef,
) -> Result<space_auth::Token, XrpcError> {
let refused = |m: String| bad("InvalidDelegationToken", m);
let (_, claims) = space_auth::parse(Kind::Delegation, token).map_err(|e| refused(e.message))?;
let aud = space_host_aud(&space.authority);
let uri = space.to_string();
let expect = Expect {
aud: Some(&aud),
sub: Some(&uri),
};
let check = |key: &PublicKey| space_auth::verify(Kind::Delegation, token, key, &expect, now());
let checked = host.identity.with_key(&claims.iss, check).await;
let checked = checked.ok_or_else(|| refused(format!("no signing key for {}", claims.iss)))?;
checked.map_err(|e| refused(e.message))
let checked = service_auth::verify_delegation(&host.identity, token, now()).await;
let checked = checked.map_err(|e| refused(e.to_string()))?;
if checked.sub != space.to_string() {
return Err(refused(format!("a token for {}, not {space}", checked.sub)));
}
Ok(checked)
}
/// A repo host says a repo of one of its accounts was written in a space
crates/group-host/src/config.rs+15−7
@@ -7,6 +7,9 @@ use atproto::did;
use std::collections::BTreeMap;
use std::path::PathBuf;
/// In `HANDLE_RESOLVERS`, a handle's own `/.well-known/atproto-did`.
pub const WELL_KNOWN: &str = "well-known";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Config {
/// The port it listens on, `PORT`; 0 for any free one.
@@ -31,9 +34,10 @@ pub struct Config {
/// network of test servers: `grain.social=127.0.0.1:2584`.
pub did_web_hosts: BTreeMap<String, String>,
/// How a handle is resolved, `HANDLE_RESOLVERS`, comma-separated, each
/// tried in turn: `well-known:<scheme>` for the handle's own
/// `/.well-known/atproto-did`, or a service answering
/// `com.atproto.identity.resolveHandle`, which reads its DNS record.
/// tried in turn: [`WELL_KNOWN`] for the handle's own
/// `/.well-known/atproto-did` (on http where `DID_WEB_SCHEME` is), or
/// a service answering `com.atproto.identity.resolveHandle`, which
/// reads its DNS record.
pub handle_resolvers: Vec<String>,
/// Where the host reads a DNS TXT record, `DNS_OVER_HTTPS`: a
/// DNS-over-HTTPS service answering JSON (`application/dns-json`),
@@ -149,10 +153,14 @@ impl Config {
let group_founders = list("GROUP_FOUNDERS");
let mut handle_resolvers = urls("HANDLE_RESOLVERS");
if handle_resolvers.is_empty() {
handle_resolvers = vec![
"well-known:https".into(),
"https://public.api.bsky.app".into(),
];
handle_resolvers = vec![WELL_KNOWN.into(), "https://public.api.bsky.app".into()];
}
let service = |r: &String| r.starts_with("https://") || r.starts_with("http://");
if let Some(r) = handle_resolvers
.iter()
.find(|r| *r != WELL_KNOWN && !service(r))
{
bail!("HANDLE_RESOLVERS is {WELL_KNOWN} or a service's URL, not {r}");
}
let crawlers = urls("PDS_CRAWLERS");
let dns_over_https = var("DNS_OVER_HTTPS").unwrap_or_else(|| DNS_OVER_HTTPS.into());
crates/group-host/src/console_login.rs+4−13
crates/group-host/src/group_domain.rs+8−12
crates/group-host/src/group_handle.rs+3−2
crates/group-host/src/guard.rsdeleted+0−93
crates/group-host/src/identity.rsdeleted+0−221
crates/group-host/src/import.rs+4−4
crates/group-host/src/index.rs+9−6
crates/group-host/src/index_api.rs+8−6
crates/group-host/src/lib.rs+41−7
crates/group-host/src/migration.rs+12−13
crates/group-host/src/oauth_clients.rs+7−4
crates/group-host/src/observe.rs+61−6
crates/group-host/src/permission_sets.rs+1−1
crates/group-host/src/proxy.rs+3−4
crates/group-host/tests/addresses.rsnew+41−0
crates/group-host/tests/authority.rs+5−0
crates/group-host/tests/config.rs+5−1
crates/group-host/tests/console_login.rs+2−1
crates/group-host/tests/group_handle.rs+1−1
crates/group-host/tests/identity.rsdeleted+0−347
crates/group-host/tests/oauth_clients.rs+7−14
crates/group-host/tests/proxy.rs+1−1
crates/group-host/Cargo.toml+1−0
docs/reference/api.md+9−0
docs/reference/config.md+2−2
Cargo.lock+382−5
Cargo.toml+2−1