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

A space's authority may be a did:web, its key kept a few minutes

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:host/did-resolver
crates/group-host/src/config.rs+8−0
@@ -21,6 +21,9 @@ pub struct Config {
pub data_dir: PathBuf,
/// The PLC directory groups' identities are published to, `PLC_URL`.
pub plc_url: String,
/// How a `did:web`'s document is read, `DID_WEB_SCHEME`: `https`, or
/// `http` for a network of test servers.
pub did_web_scheme: String,
/// The relays told of this host's news, `PDS_CRAWLERS`, comma-separated.
pub crawlers: Vec<String>,
/// The most bytes one blob may be, `BLOB_UPLOAD_LIMIT`.
@@ -54,6 +57,10 @@ impl Config {
}
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());
let did_web_scheme = var("DID_WEB_SCHEME").unwrap_or_else(|| "https".into());
if !["https", "http"].contains(&did_web_scheme.as_str()) {
bail!("DID_WEB_SCHEME is https or http, not {did_web_scheme}");
}
let crawlers = var("PDS_CRAWLERS").unwrap_or_default();
let crawlers = crawlers
.split(',')
@@ -73,6 +80,7 @@ impl Config {
handle_domain,
data_dir,
plc_url,
did_web_scheme,
crawlers,
blob_upload_limit,
})
crates/group-host/src/identity.rsnew+133−0
@@ -0,0 +1,133 @@
//! Other accounts' DID documents, as the host reads them to check what
//! they sign and to find their servers: a `did:plc`'s from the PLC
//! directory, a `did:web`'s from its host, each kept a few minutes.
use anyhow::{Context, Result, bail};
use atproto::{PublicKey, did};
use serde_json::Value;
use std::collections::HashMap;
use std::sync::Mutex;
use std::time::{Duration, Instant};
/// How long a document read is taken as it stands.
pub const KEPT_FOR: Duration = Duration::from_secs(300);
/// The most bytes a document may be: a request names the host it is read
/// from, so what that host sends is a caller's to choose.
pub const DOCUMENT_AT_MOST: usize = 256 * 1024;
/// A response's body, refused once it is past [`DOCUMENT_AT_MOST`].
async fn body(mut res: reqwest::Response) -> Result<Vec<u8>> {
let mut bytes = Vec::new();
while let Some(chunk) = res.chunk().await? {
bytes.extend_from_slice(&chunk);
if bytes.len() > DOCUMENT_AT_MOST {
bail!("a DID document past {DOCUMENT_AT_MOST} bytes");
}
}
Ok(bytes)
}
/// The most documents kept at once: a request names whose document is
/// read, so how many is a caller's to choose.
pub const KEPT_AT_MOST: usize = 10_000;
pub struct Resolver {
plc_url: String,
did_web_scheme: String,
http: reqwest::Client,
kept: Mutex<HashMap<String, (Instant, Value)>>,
kept_for: Duration,
kept_at_most: usize,
}
impl Resolver {
pub fn new(plc_url: &str, did_web_scheme: &str) -> Resolver {
Resolver::keeping(plc_url, did_web_scheme, KEPT_FOR, KEPT_AT_MOST)
}
/// A resolver keeping documents `kept_for`, at most `kept_at_most` of
/// them at once.
pub fn keeping(
plc_url: &str,
did_web_scheme: &str,
kept_for: Duration,
kept_at_most: usize,
) -> Resolver {
Resolver {
kept_for,
kept_at_most,
plc_url: plc_url.trim_end_matches('/').to_string(),
did_web_scheme: did_web_scheme.to_string(),
http: crate::client(),
kept: Mutex::default(),
}
}
/// Where `did`'s document is read.
fn url(&self, did: &str) -> Result<String> {
if let Some(host) = did.strip_prefix("did:web:") {
// A did:web of a host alone: one with a path names no host here.
if host.is_empty() || host.contains(':') {
bail!("{did} is not a did:web of a host");
}
let host = host.replace("%3A", ":");
Ok(format!(
"{}://{host}/.well-known/did.json",
self.did_web_scheme
))
} else if did.starts_with("did:plc:") {
Ok(format!("{}/{did}", self.plc_url))
} else {
bail!("{did}: not a did:plc or a did:web");
}
}
/// `did`'s document, read now, and kept.
pub async fn document(&self, did: &str) -> Result<Value> {
let res = self.http.get(self.url(did)?).send().await?;
let res = res.error_for_status().context(format!("resolving {did}"))?;
let doc: Value = serde_json::from_slice(&body(res).await?)?;
if doc.get("id").and_then(Value::as_str) != Some(did) {
bail!("{did}'s document is another's");
}
let mut kept = self.kept.lock().expect("not poisoned");
// Full, the lapsed go; still full, all of them.
if kept.len() >= self.kept_at_most {
kept.retain(|_, (at, _)| at.elapsed() < self.kept_for);
}
if kept.len() >= self.kept_at_most {
kept.clear();
}
kept.insert(did.into(), (Instant::now(), doc.clone()));
Ok(doc)
}
/// `did`'s document as it was read in the last few minutes, if it
/// was. What it names may have changed since: a key that turns a
/// signature away is worth reading again with [`Resolver::document`].
pub fn kept(&self, did: &str) -> Option<Value> {
let kept = self.kept.lock().expect("not poisoned");
let (at, doc) = kept.get(did)?;
(at.elapsed() < self.kept_for).then(|| doc.clone())
}
/// What `check` makes of `did`'s signing key: with the key kept, and
/// if that one turns it away, the key read again; with no key kept, the
/// key read now. `None` if no key is to be had.
pub async fn with_key<T, E>(
&self,
did: &str,
check: impl Fn(&PublicKey) -> Result<T, E>,
) -> Option<Result<T, E>> {
let key_in = |doc: &Value| did::signing_key(doc).ok();
if let Some(key) = self.kept(did).as_ref().and_then(key_in) {
let checked = check(&key);
if checked.is_ok() {
return Some(checked);
}
}
let doc = self.document(did).await.ok()?;
Some(check(&key_in(&doc)?))
}
}
crates/group-host/src/lib.rs+5−0
@@ -7,6 +7,7 @@ pub mod api;
pub mod blobs;
pub mod config;
pub mod firehose;
pub mod identity;
pub mod plc;
pub mod repo;
pub mod secrets;
@@ -31,6 +32,8 @@ pub struct Host {
pub store: store::Store,
pub secrets: secrets::Secrets,
pub plc: plc::Directory,
/// Other accounts' documents.
pub identity: identity::Resolver,
/// 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.
@@ -49,6 +52,7 @@ impl Host {
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);
let identity = identity::Resolver::new(&config.plc_url, &config.did_web_scheme);
// 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 {
@@ -56,6 +60,7 @@ impl Host {
store,
secrets,
plc,
identity,
clock,
writing: Default::default(),
events: tokio::sync::broadcast::channel(16).0,
crates/group-host/src/space.rs+5−1
@@ -119,7 +119,11 @@ impl Host {
space: &SpaceRef,
commit: &Commit,
) -> Result<()> {
let doc = self.plc.document(&space.authority).await?;
let doc = self.identity.kept(&space.authority);
let doc = match doc {
Some(doc) => doc,
None => self.identity.document(&space.authority).await?,
};
let pds = did::pds(&doc).context("the authority's document names no PDS")?;
let now = now_millis() as u64 / 1000;
let claims = Claims {
crates/group-host/src/space_api.rs+12−15
@@ -14,7 +14,7 @@ use atproto::space::{
record_mac, star,
};
use atproto::space_auth::{self, CLOCK_SKEW, CREDENTIAL_MAX_AGE, Expect, Kind, TokenError};
use atproto::{Cid, did, drisl};
use atproto::{Cid, drisl};
use axum::Json;
use axum::extract::{Query, State};
use axum::http::{HeaderMap, HeaderName, StatusCode, header};
@@ -40,12 +40,6 @@ fn now() -> u64 {
now_millis() as u64 / 1000
}
/// The signing key of the account `did`, from its document.
async fn key_of(host: &Host, did: &str) -> Option<atproto::PublicKey> {
let doc = host.plc.document(did).await.ok()?;
did::signing_key(&doc).ok()
}
/// What a read in a space asks of: the account whose repo it is, and the
/// space, once the caller's credential lets them read it.
struct Asked {
@@ -78,14 +72,16 @@ async fn credential(
"space credential issuer is not the space authority",
));
}
let key = key_of(host, &token.iss).await;
let key =
key.ok_or_else(|| unauthorized("BadJwtIss", format!("no signing key for {}", token.iss)))?;
let expect = Expect {
aud: None,
sub: Some(space),
};
space_auth::verify(Kind::Credential, jwt, &key, &expect, now()).map_err(refused)?;
let check =
|key: &atproto::PublicKey| space_auth::verify(Kind::Credential, jwt, key, &expect, now());
let checked = host.identity.with_key(&token.iss, check).await;
let checked = checked
.ok_or_else(|| unauthorized("BadJwtIss", format!("no signing key for {}", token.iss)))?;
checked.map_err(refused)?;
if text("atproto-space-audience") != Some(repo) {
return Err(XrpcError::new(
StatusCode::BAD_REQUEST,
@@ -434,10 +430,11 @@ async fn service_caller(host: &Host, headers: &HeaderMap, lxm: &str) -> Result<C
let token = bearer.ok_or_else(|| unauthorized("AuthMissing", "service auth is required"))?;
let bad = |e: service_auth::AuthError| unauthorized("BadJwt", e.0);
let (_, claims) = service_auth::parts(token).map_err(bad)?;
let key = key_of(host, claims.account()).await;
let key =
key.ok_or_else(|| unauthorized("BadJwtIss", format!("no signing key for {}", claims.iss)))?;
let claims = service_auth::verify(token, &key, now()).map_err(bad)?;
let check = |key: &atproto::PublicKey| service_auth::verify(token, key, now());
let checked = host.identity.with_key(claims.account(), check).await;
let checked = checked
.ok_or_else(|| unauthorized("BadJwtIss", format!("no signing key for {}", claims.iss)))?;
let claims = checked.map_err(bad)?;
if claims.lxm.as_deref() != Some(lxm) {
return Err(unauthorized(
"BadJwtLexiconMethod",
crates/group-host/tests/config.rs+11−1
@@ -19,6 +19,7 @@ fn defaults_serve_localhost() {
assert_eq!(c.service_did, "did:web:localhost%3A2600");
assert_eq!(c.handle_domain, ".test");
assert_eq!(c.data_dir, std::path::PathBuf::from("data"));
assert_eq!(c.did_web_scheme, "https");
}
#[test]
@@ -35,8 +36,13 @@ fn the_environment_names_the_host() {
assert_eq!(c.service_did, "did:web:groups.example.com");
assert_eq!(c.handle_domain, ".groups.example.com");
let c = config(&[("SERVICE_DID", "did:web:other.example")]).unwrap();
let c = config(&[
("SERVICE_DID", "did:web:other.example"),
("DID_WEB_SCHEME", "http"),
])
.unwrap();
assert_eq!(c.service_did, "did:web:other.example");
assert_eq!(c.did_web_scheme, "http");
}
#[test]
@@ -55,6 +61,10 @@ fn refuses_what_does_not_read() {
err(&[("BLOB_UPLOAD_LIMIT", "lots")]),
"BLOB_UPLOAD_LIMIT is no number of bytes: lots"
);
assert_eq!(
err(&[("DID_WEB_SCHEME", "ftp")]),
"DID_WEB_SCHEME is https or http, not ftp"
);
assert_eq!(
err(&[("HANDLE_DOMAIN", "example.com")]),
"HANDLE_DOMAIN starts with a dot: .example.com"
crates/group-host/tests/identity.rsnew+123−0
@@ -0,0 +1,123 @@
//! Other accounts' DID documents, as the host reads them.
mod common;
use axum::Router;
use axum::routing::get;
use common::serve;
use group_host::identity::Resolver;
use serde_json::{Value, json};
use std::time::Duration;
/// A server whose did:web document is `doc`, and its DID.
async fn web(doc: Value) -> String {
let router = Router::new().route(
"/.well-known/did.json",
get(move || {
let doc = doc.clone();
async move { axum::Json(doc) }
}),
);
let url = serve(router).await;
format!(
"did:web:{}",
url.strip_prefix("http://").unwrap().replace(':', "%3A")
)
}
#[tokio::test]
async fn reads_what_it_can_and_refuses_the_rest() {
let r = Resolver::new("http://127.0.0.1:9", "http");
let err = |e: anyhow::Error| format!("{e:#}");
for (did, why) in [
("did:key:zQ3sh", "did:key:zQ3sh: not a did:plc or a did:web"),
("did:web:", "did:web: is not a did:web of a host"),
(
"did:web:example.com:users:alice",
"did:web:example.com:users:alice is not a did:web of a host",
),
] {
assert_eq!(err(r.document(did).await.unwrap_err()), why);
}
// A document of another DID is not this one's.
let other = web(json!({"id": "did:web:elsewhere"})).await;
assert_eq!(
err(r.document(&other).await.unwrap_err()),
format!("{other}'s document is another's")
);
assert_eq!(r.kept(&other), None);
// Nor is one past the size a document may be.
let padding = "x".repeat(group_host::identity::DOCUMENT_AT_MOST);
let large = web(json!({"id": "did:web:large", "padding": padding})).await;
assert_eq!(
err(r.document(&large).await.unwrap_err()),
format!(
"a DID document past {} bytes",
group_host::identity::DOCUMENT_AT_MOST
)
);
// Nor one that is no object.
let text = web(json!("not a document")).await;
assert_eq!(
err(r.document(&text).await.unwrap_err()),
format!("{text}'s document is another's")
);
}
#[tokio::test]
async fn gives_no_key_where_a_document_names_none() {
let r = Resolver::new("http://127.0.0.1:9", "http");
let web = webs(1).await.remove(0);
let check = |_: &atproto::PublicKey| Ok::<(), ()>(());
assert_eq!(r.with_key(&web, check).await, None);
// Kept now, and still keyless when read again.
assert!(r.kept(&web).is_some());
assert_eq!(r.with_key(&web, check).await, None);
// A directory that does not answer gives no document.
assert!(r.with_key("did:plc:nowhere", check).await.is_none());
}
/// A server of `n` did:web documents, each its own DID's, by port.
async fn webs(n: usize) -> Vec<String> {
let mut dids = Vec::new();
for _ in 0..n {
let did = std::sync::Arc::new(std::sync::Mutex::new(String::new()));
let served = did.clone();
let router = Router::new().route(
"/.well-known/did.json",
get(move || {
let id = served.lock().unwrap().clone();
async move { axum::Json(json!({"id": id})) }
}),
);
let url = serve(router).await;
let web = format!(
"did:web:{}",
url.strip_prefix("http://").unwrap().replace(':', "%3A")
);
*did.lock().unwrap() = web.clone();
dids.push(web);
}
dids
}
#[tokio::test]
async fn keeps_so_many_documents_and_no_more() {
let dids = webs(3).await;
// Full, it lets go of those lapsed first.
let lapsing = Resolver::keeping("http://127.0.0.1:9", "http", Duration::ZERO, 2);
for did in &dids {
lapsing.document(did).await.unwrap();
}
assert_eq!(lapsing.kept(&dids[2]), None);
// And with none lapsed, of all of them.
let keeping = Resolver::keeping("http://127.0.0.1:9", "http", Duration::from_secs(60), 2);
for did in &dids {
keeping.document(did).await.unwrap();
}
assert_eq!(keeping.kept(&dids[0]), None);
assert_eq!(keeping.kept(&dids[1]), None);
assert!(keeping.kept(&dids[2]).is_some());
}
crates/group-host/tests/spaces.rs+144−1
@@ -72,6 +72,11 @@ struct Authority {
did: String,
key: Keypair,
told: Arc<Told>,
/// Its rotation key, its PDS, and its last operation, to change its
/// document with.
rotation: Keypair,
pds: String,
last: Option<Cid>,
}
async fn authority(h: &Running, refuse: bool, pds: bool) -> Authority {
@@ -104,7 +109,37 @@ async fn authority(h: &Running, refuse: bool, pds: bool) -> Authority {
.await
.unwrap();
assert!(res.status().is_success());
Authority { did, key, told }
Authority {
did,
key,
told,
rotation,
pds: url,
last: Some(genesis.cid()),
}
}
impl Authority {
/// Signs with a new key from now on, its document saying so.
async fn rotate(&mut self, h: &Running) {
self.key = Keypair::generate(Curve::K256);
let op = Op::atproto(
&self.key.public().did_key(),
&[self.rotation.public().did_key()],
"authority.test",
&self.pds,
);
let signed = op.sign(self.last, &self.rotation);
let res = h
.http
.post(format!("{}/{}", plc_url(h), self.did))
.json(&signed.to_json())
.send()
.await
.unwrap();
assert!(res.status().is_success());
self.last = Some(signed.cid());
}
}
fn plc_url(h: &Running) -> String {
@@ -837,6 +872,9 @@ async fn reads_only_with_a_credential_the_authority_issued() {
did: f.authority.did.clone(),
key: Keypair::generate(Curve::K256),
told: Default::default(),
rotation: Keypair::generate(Curve::K256),
pds: String::new(),
last: None,
};
let expired = space_auth::create(
Kind::Credential,
@@ -1207,3 +1245,108 @@ fn a_space_write_builds_on_the_revision_it_read() {
);
assert_eq!(store.space_head("did:plc:a", "s").unwrap(), Some(head));
}
/// What `getLatestCommit` answers the fixture's syncer.
async fn latest(f: &Fixture) -> u16 {
let (headers, _) = signed(&f.syncer, &f.group, &f.kem, COMMIT_MAC);
read(
&f.h,
"com.atproto.space.getLatestCommit",
&f.query(""),
&headers,
)
.await
.status
}
#[tokio::test]
async fn reads_with_a_credential_signed_by_an_authoritys_new_key() {
let mut f = fixture().await;
f.h.host
.space_write(&f.group, &f.space, &[create(RULE, "a", rule("A"))])
.await
.unwrap();
// The host keeps the authority's key it read.
assert_eq!(latest(&f).await, 200);
// The authority moves to a new key: a credential it signs with that
// one is checked against its document read again.
f.authority.rotate(&f.h).await;
f.syncer = syncer(&f.authority, &f.space);
assert_eq!(latest(&f).await, 200);
}
/// A did:web authority's server: its document, and its PDS hearing of
/// writes.
async fn web_authority(told: Arc<Told>) -> (String, Keypair) {
let doc = Arc::new(Mutex::new(Json::Null));
let served = doc.clone();
let router = Router::new()
.route("/xrpc/com.atproto.space.notifyWrite", post(notify_write))
.with_state(told)
.route(
"/.well-known/did.json",
axum::routing::get(move || {
let doc = served.lock().unwrap().clone();
async move { axum::Json(doc) }
}),
);
let url = serve(router).await;
let did = format!(
"did:web:{}",
url.strip_prefix("http://").unwrap().replace(':', "%3A")
);
let key = Keypair::generate(Curve::K256);
*doc.lock().unwrap() = atproto::did::service_document(
&did,
&key.public(),
&[("#atproto_pds", "AtprotoPersonalDataServer", url.as_str())],
);
(did, key)
}
#[tokio::test]
async fn a_space_of_a_did_web_authority() {
let h = start(&[("DID_WEB_SCHEME", "http")], false).await;
let group = h.host.create_account(RIDERS).await.unwrap();
let kem = h
.host
.store
.account(&group)
.unwrap()
.unwrap()
.kem
.public()
.did_key();
let told = Arc::new(Told::default());
let (did, key) = web_authority(told.clone()).await;
let authority = Authority {
did,
key,
told,
rotation: Keypair::generate(Curve::K256),
pds: String::new(),
last: None,
};
let space = format!("at://{}/space/fyi.opensocial.content/self", authority.did);
let commit = h
.host
.space_write(&group, &space, &[create(RULE, "a", rule("A"))])
.await
.unwrap();
// Told, at the PDS its document names.
assert_eq!(
authority.told.writes.lock().unwrap()[0].1["repoRev"],
commit.rev
);
// And its credential reads.
let syncer = syncer(&authority, &space);
let (headers, secret) = signed(&syncer, &group, &kem, COMMIT_MAC);
// A did:web's `%3A` is sent as it is, escaped.
let query = format!("space={}&repo={group}", space.replace('%', "%25"));
let got = read(&h, "com.atproto.space.getLatestCommit", &query, &headers).await;
assert_eq!(got.status, 200, "{}", String::from_utf8_lossy(&got.body));
assert_eq!(
got.mac(),
Some(mac_header(COMMIT_MAC, &commit.mac(&secret)).as_str())
);
}
docs/design/README.md+3−3
@@ -72,9 +72,9 @@ says otherwise.
then the repos the host keeps in spaces, each group with its
`#atproto_kem` key, read with an authority's credential and each write
told to the authority (`space.rs`, `space_api.rs`; done, see
[spaces](spaces.md)); next, one resolver for `did:plc` and `did:web`
with a short cache of keys, so a space's authority may be either; then
being the authority for its groups' spaces, with a queue that tries a
[spaces](spaces.md)), others' DID documents read for a `did:plc` or a
`did:web` and kept a few minutes (`identity.rs`; done), then being the
authority for its groups' spaces, with a queue that tries a
`notifyWrite` again for a day, as the reference PDS does.
Then the
groups: `createGroup`, `getGroup`, `listGroups`,
docs/design/spaces.md+22−2
@@ -39,8 +39,28 @@ authority keeps it, and tells the services syncing the space.
The write stands whether the authority heard or not: it learns of the
next write instead. The host waits on it ten seconds at most, as it
waits on any server it asks. Trying again, as the reference PDS does for a day,
is still to come. An authority is found on the PLC directory, so for
now it is a `did:plc`.
is still to come. An authority may be a `did:plc` or a `did:web`.
## Others' identities
The host reads other accounts' DID documents (a space's authority, an
authority revoking a credential) from the PLC directory for a
`did:plc`, and from `/.well-known/did.json` at its host for a `did:web`
(`DID_WEB_SCHEME`, `https` unless it is a network of test servers). A
document must be the DID's own, its `id` that DID. Each is kept five
minutes, so the same authority's credentials are checked without a
lookup each; a signature the kept key turns away is checked again with
the document read afresh, so a key the authority moved to counts at
once. A key it moved away from counts for those minutes still.
Whose document is read is a caller's to say: the issuer of a credential
or a service token is read before it is checked. So any caller can have
the host GET `/.well-known/did.json` from a host of their choosing, as
any server resolving a `did:web` can be made to. The host reads at most
256 KiB of it, keeps at most 10,000 documents, and does not refuse
private or loopback addresses: a host whose network reaches services
that answer `/.well-known/did.json` to anyone inside it should keep its
outgoing requests from reaching them.
## Reading
docs/reference/config.md+1−0