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

did:web accounts move in, with their owners' documents

Merged chadtmiller.com asked to merge into main from chadtmiller.com/monolith:moves/did-web
crates/pds-server/src/migration/tests.rs+330−1
@@ -820,7 +820,7 @@ async fn moving_signs_and_submits() {
let body = pds_repo::data::to_json(&decode(&frame[n..]).unwrap());
assert!(body.get("handle").is_none(), "{body}");
// The document it made is served at once; the account may be activated.
let doc = crate::identity::did_doc(&m.new, &m.did).await;
let doc = crate::identity::did_doc(&m.new, &m.did).await.ok().unwrap();
assert_eq!(
doc["service"][0]["serviceEndpoint"],
json!("http://new.test")
@@ -1007,6 +1007,335 @@ async fn imports_need_free_space() {
assert_eq!(import(&m.new, &token, &car).await, Ok(Json::Null));
}
// ---- A did:web account --------------------------------------------------------
const CHECK: &str = "com.atproto.server.checkAccountStatus";
const DESCRIBE: &str = "com.atproto.repo.describeRepo";
const UPDATE_HANDLE: &str = "com.atproto.identity.updateHandle";
const RESOLVE: &str = "com.atproto.identity.resolveHandle";
/// A `did:web` of the test's own, `did:web:localhost%3A<port>`: its host
/// serves `doc` at `/.well-known/did.json`, `404` while it is `None`.
struct WebDid {
did: String,
key: SigningKey,
doc: Arc<std::sync::Mutex<Option<Json>>>,
}
impl WebDid {
async fn start() -> WebDid {
use axum::response::IntoResponse;
let doc: Arc<std::sync::Mutex<Option<Json>>> = Arc::default();
let served = doc.clone();
let app = axum::Router::new().route(
"/.well-known/did.json",
axum::routing::get(move || {
let d = served.lock().unwrap().clone();
async move {
match d {
Some(d) => axum::Json(d).into_response(),
None => axum::http::StatusCode::NOT_FOUND.into_response(),
}
}
}),
);
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0))
.await
.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
WebDid {
did: format!("did:web:localhost%3A{port}"),
key: SigningKey::from_slice(&[11u8; 32]).unwrap(),
doc,
}
}
/// Serve a document naming `handle`, the signing key `signing` (a
/// `did:key`) and the endpoint `pds`, as `atproto/did.md` lays one out.
fn serve(&self, handle: &str, signing: &str, pds: &str) {
let did = &self.did;
*self.doc.lock().unwrap() = Some(json!({
"@context": ["https://www.w3.org/ns/did/v1", "https://w3id.org/security/multikey/v1"],
"id": did,
"alsoKnownAs": [format!("at://{handle}")],
"verificationMethod": [{ "id": format!("{did}#atproto"), "type": "Multikey", "controller": did, "publicKeyMultibase": signing.trim_start_matches("did:key:") }],
"service": [{ "id": "#atproto_pds", "type": "AtprotoPersonalDataServer", "serviceEndpoint": pds }],
}));
}
fn served(&self) -> Option<Json> {
self.doc.lock().unwrap().clone()
}
fn set(&self, doc: Option<Json>) {
*self.doc.lock().unwrap() = doc;
}
}
/// A service token of `iss` for `createAccount` on `did:web:new.test`, signed with `key`.
fn web_token(iss: &str, key: &SigningKey) -> String {
let claims = json!({ "iss": iss, "aud": "did:web:new.test", "exp": now() + 60, "lxm": CREATE });
format!(
"Bearer {}",
jwt(key, json!({ "alg": "ES256K", "typ": "JWT" }), claims)
)
}
/// The server a `did:web` moves to: `did:web:new.test` at `http://new.test`,
/// mailing to `sink`.
fn web_server(dir: &std::path::Path, plc: &str, sink: &std::path::Path) -> Shared {
let sink = sink.to_path_buf();
open_with(dir, plc, move |c| {
c.hostname = "new.test".into();
c.public_url = "http://new.test".into();
c.mailer = crate::email::Mailer::sink(&sink);
})
}
/// A DID neither a `did:plc` nor a `did:web` as `atproto/did.md` allows one.
#[test]
fn atproto_did_webs() {
for ok in [
"did:web:example.com",
"did:web:localhost%3A2583",
"did:web:Localhost%3a2583",
] {
assert!(crate::outbound::atproto_did_web(ok), "{ok}");
}
for bad in [
"did:web:example.com%3A8443",
"did:web:example.com:path",
"did:web:",
"did:web:a..b",
"did:plc:aaaaaaaaaaaaaaaaaaaaaaaa",
] {
assert!(!crate::outbound::atproto_did_web(bad), "{bad}");
}
}
/// What a `did:web` document names, as `atproto/did.md` takes it: the first
/// `#atproto` method's key, and the first `#atproto_pds` service of its type.
#[test]
fn did_web_documents_name() {
let key = SigningKey::from_slice(&[11u8; 32]).unwrap();
let other = SigningKey::from_slice(&[12u8; 32]).unwrap();
let mk = |k: &SigningKey| {
crate::plc::did_key(k.verifying_key())
.trim_start_matches("did:key:")
.to_string()
};
let doc = json!({
"id": "did:web:x.test",
"verificationMethod": [
{ "id": "did:web:x.test#other", "type": "Multikey", "publicKeyMultibase": mk(&other) },
{ "id": "did:web:x.test#atproto", "type": "Multikey", "publicKeyMultibase": mk(&key) },
{ "id": "#atproto", "type": "Multikey", "publicKeyMultibase": mk(&other) },
],
"service": [
{ "id": "#atproto_pds", "type": "Other", "serviceEndpoint": "https://a.test" },
{ "id": "did:web:x.test#atproto_pds", "type": "AtprotoPersonalDataServer", "serviceEndpoint": "https://b.test" },
{ "id": "#atproto_pds", "type": "AtprotoPersonalDataServer", "serviceEndpoint": "https://c.test" },
],
});
assert_eq!(
crate::identity::web_signing_key(&doc),
Some(Key::K256(*key.verifying_key()))
);
assert_eq!(crate::identity::web_endpoint(&doc), Some("https://b.test"));
assert_eq!(crate::identity::web_signing_key(&json!({})), None);
assert_eq!(
crate::identity::web_endpoint(&json!({ "service": [] })),
None
);
}
/// A `did:web` account moves in: made by its owner's own service token,
/// its document read from its host, with the errors `spec/MIGRATION.md`
/// gives; activated once its document names this server, by endpoint and
/// key alone; no PLC method applies; and its handle changes only to the one
/// its document names, read again each time.
#[tokio::test]
async fn a_did_web_moves_in() {
let plc = Plc::start().await;
let (dir, sink) = (scratch("migration-web"), scratch("migration-web-mail"));
std::fs::create_dir_all(&sink).unwrap();
let s = web_server(&dir, &plc.url, &sink);
let w = WebDid::start().await;
let own = crate::plc::did_key(w.key.verifying_key());
w.serve("carlos.test", &own, "https://old.example.com");
let body = |did: &str| json!({ "did": did, "handle": "carlos.test", "email": "carlos@mail.com", "password": "carlos-pw" });
let create = |did: &str, auth: Option<String>| {
let (s, b) = (s.clone(), body(did));
async move {
send(
&s,
CREATE,
auth.as_deref(),
Some("application/json"),
&[],
b.to_string().as_bytes(),
)
.await
}
};
let auth_required = Err((401, "AuthenticationRequired".to_string()));
let internal = Err((500, "InternalServerError".to_string()));
let refused = Err((400, "InvalidRequest".to_string()));
// Refused: no token; a key its document does not name; its document not
// found; one of another DID; a host that does not answer.
assert_eq!(create(&w.did, None).await, auth_required);
let other = SigningKey::from_slice(&[3u8; 32]).unwrap();
assert_eq!(
create(&w.did, Some(web_token(&w.did, &other))).await,
Err((401, "BadJwtSignature".into()))
);
let served = w.served().unwrap();
w.set(None);
assert_eq!(
create(&w.did, Some(web_token(&w.did, &w.key))).await,
auth_required
);
let mut not_its = served.clone();
not_its["id"] = json!("did:web:other.test");
w.set(Some(not_its));
assert_eq!(
create(&w.did, Some(web_token(&w.did, &w.key))).await,
internal
);
let closed = std::net::TcpListener::bind("127.0.0.1:0")
.unwrap()
.local_addr()
.unwrap()
.port();
let silent = format!("did:web:localhost%3A{closed}");
assert_eq!(
create(&silent, Some(web_token(&silent, &w.key))).await,
internal
);
w.set(Some(served.clone()));
// Made, deactivated, its didDoc the document served; nothing on the firehose.
let made = create(&w.did, Some(web_token(&w.did, &w.key)))
.await
.unwrap();
assert_eq!(made["did"], json!(w.did));
assert_eq!(made["didDoc"], served);
assert!(s.events.seqs_of(&w.did).is_empty());
let token = made["accessJwt"].as_str().unwrap().to_string();
let bearer = format!("Bearer {token}");
let status =
|| async { post(&s, CHECK, Some(&token), Json::Null).await.unwrap()["validDid"].clone() };
let activate = || send(&s, ACTIVATE, Some(&bearer), None, &[], b"");
let describe = || {
let p = [("repo".to_string(), w.did.clone())];
let s = s.clone();
async move { send(&s, DESCRIBE, None, None, &p, b"").await }
};
assert_eq!(status().await, json!(false));
assert_eq!(activate().await, refused);
// No PLC method applies, and nothing goes to the directory.
let creds = post(&s, CREDENTIALS, Some(&token), Json::Null)
.await
.unwrap();
assert_eq!(
send(&s, REQUEST, Some(&bearer), None, &[], b"").await,
Ok(Json::Null)
);
let mailed = crate::email::testing::last_token(&sink);
assert_eq!(
post(&s, SIGN, Some(&token), json!({ "token": mailed })).await,
refused
);
let mut op = creds.clone();
op["type"] = json!("plc_operation");
op["prev"] = Json::Null;
op["sig"] = json!("c2ln");
assert_eq!(
post(&s, SUBMIT, Some(&token), json!({ "operation": op })).await,
refused
);
assert!(plc.log(&w.did).is_empty());
// Its document pointed here, with the recommended key: activated.
let signing = creds["verificationMethods"]["atproto"].as_str().unwrap();
w.serve("carlos.test", signing, "http://new.test");
assert_eq!(status().await, json!(true));
// Not with a key other than the account's.
w.serve("carlos.test", &own, "http://new.test");
assert_eq!(status().await, json!(false));
w.serve("carlos.test", signing, "http://new.test");
assert_eq!(activate().await, Ok(Json::Null));
let got = describe().await.unwrap();
assert_eq!(
(&got["didDoc"], &got["handleIsCorrect"]),
(&w.served().unwrap(), &json!(true))
);
// Its handle: refused while its document names another, with no event;
// then, once it does, given, with its `#identity`.
let events = s.events.seqs_of(&w.did).len();
let update = |h: &str| post(&s, UPDATE_HANDLE, Some(&token), json!({ "handle": h }));
assert_eq!(update("carlosx.test").await, refused);
assert_eq!(s.account(&w.did).unwrap().handle(), "carlos.test");
assert_eq!(s.events.seqs_of(&w.did).len(), events);
w.serve("carlosx.test", signing, "http://new.test");
assert_eq!(update("CarlosX.test").await, Ok(Json::Null));
assert_eq!(s.account(&w.did).unwrap().handle(), "carlosx.test");
assert_eq!(s.events.seqs_of(&w.did).len(), events + 1);
assert_eq!(
send(
&s,
RESOLVE,
None,
None,
&[("handle".to_string(), "carlosx.test".to_string())],
b""
)
.await,
Ok(json!({ "did": w.did }))
);
assert!(plc.log(&w.did).is_empty());
// The handle it had is free again.
assert!(s.account("carlos.test").is_none());
// Its document gone: describeRepo `400`, validDid `false`, an activation
// `400`, and a handle change `500`, which changes nothing.
let named = w.served();
w.set(None);
assert_eq!(describe().await, refused);
assert_eq!(status().await, json!(false));
assert_eq!(activate().await, refused);
assert_eq!(update("carlosx.test").await, internal);
assert_eq!(s.events.seqs_of(&w.did).len(), events + 1);
// No document of it: an activation is `500`.
let mut not_its = named.clone().unwrap();
not_its["id"] = json!("did:web:other.test");
w.set(Some(not_its));
assert_eq!(activate().await, internal);
w.set(named);
// A restart keeps the handle, and settles nothing with the directory.
drop(s);
let s = web_server(&dir, &plc.url, &sink);
assert_eq!(s.account(&w.did).unwrap().handle(), "carlosx.test");
assert_eq!(
post(
&s,
UPDATE_HANDLE,
Some(&token),
json!({ "handle": "carlosx.test" })
)
.await,
Ok(Json::Null)
);
for d in [dir, sink] {
let _ = std::fs::remove_dir_all(d);
}
}
/// The DIDs `listRepos` lists.
async fn repos(s: &Shared) -> Vec<String> {
let listed = post(s, "com.atproto.sync.listRepos", None, Json::Null)
crates/pds-server/src/space_credentials/jwt.rs+5−0
@@ -153,6 +153,11 @@ impl Key {
.as_array()?
.iter()
.find(|m| m["id"] == short.as_str() || m["id"] == full.as_str())?;
Key::of_method(method)
}
/// The key of a verification method, as a `Multikey` or in the legacy form.
pub fn of_method(method: &Json) -> Option<Key> {
let (typ, multibase) = (
method["type"].as_str()?,
method["publicKeyMultibase"].as_str()?,
crates/pds-server/src/identity.rs+124−25
@@ -10,7 +10,9 @@
//! are made one at a time, each holding its account's `Slot` while it talks
//! to the directory; one left unsettled, by a restart or a directory that
//! could not be reached, waits in the slot, and is settled in the background
//! or by the account's next change.
//! or by the account's next change. A `did:web` account's change posts
//! nothing: its document, read again, must name the handle already, and the
//! change lands at once (`spec/MIGRATION.md`, "A `did:web` account").
use crate::log;
use crate::ops::Level;
@@ -118,8 +120,8 @@ fn held_doc(text: &str) -> Json {
serde_json::from_str(text).unwrap_or(Json::Null)
}
/// An account's DID document, as the directory last served it, if it was
/// fetched within `PDS_DID_CACHE_SECS`.
/// An account's DID document, as the directory or its host last served
/// it, if it was fetched within `PDS_DID_CACHE_SECS`.
fn kept_doc(s: &Service, a: &Account) -> Option<Json> {
let (doc, at) = &*read(&a.did_doc);
at.filter(|t| s.limits.clock.now() < t.saturating_add(s.config.did_cache))
@@ -129,26 +131,37 @@ fn kept_doc(s: &Service, a: &Account) -> Option<Json> {
/// The DID document of an account's DID: the one kept, if it was fetched
/// within `PDS_DID_CACHE_SECS`, or else the one the directory serves now,
/// fetched once at a time; the one it last served, should it not answer.
pub(crate) async fn did_doc(s: &Service, did: &str) -> Json {
/// A `did:web`'s is its host's, and an error, as `proxy::read_did` gives
/// it, when it cannot be read (`spec/MIGRATION.md`, "A `did:web` account").
pub(crate) async fn did_doc(s: &Service, did: &str) -> Result<Json, XrpcError> {
let Some(a) = s.account(did) else {
return Json::Null;
return Ok(Json::Null);
};
if let Some(doc) = kept_doc(s, &a) {
return doc;
return Ok(doc);
}
let _fetching = a.fetching.lock().await;
// Another call may have fetched it meanwhile.
if let Some(doc) = kept_doc(s, &a) {
return doc;
return Ok(doc);
}
fetch_doc(s, &a).await
}
/// Fetch an account's DID document from the directory, and keep it; with the
/// account's fetch held.
async fn fetch_doc(s: &Service, a: &Account) -> Json {
/// Whether a DID is a `did:web`, whose document its owner serves at its
/// host rather than the directory (`spec/MIGRATION.md`, "A `did:web` account").
pub(crate) fn is_web(did: &str) -> bool {
did.starts_with("did:web:")
}
/// Fetch an account's DID document from the directory, or its host for a
/// `did:web`, and keep it; with the account's fetch held.
async fn fetch_doc(s: &Service, a: &Account) -> Result<Json, XrpcError> {
if is_web(&a.did) {
return fetch_web_doc(s, a).await;
}
let url = format!("{}/{}", s.config.plc_url.trim_end_matches('/'), a.did);
match plc::document(&s.http, &url).await {
Ok(match plc::document(&s.http, &url).await {
Ok(Some(doc)) => {
*write(&a.did_doc) = (doc.to_string().into(), Some(s.limits.clock.now()));
doc
@@ -166,7 +179,31 @@ async fn fetch_doc(s: &Service, a: &Account) -> Json {
crate::ops::failed_for(Level::Warn, "reading a DID document failed", &a.did, why);
held_doc(&read(&a.did_doc).0)
}
}
})
}
/// A `did:web` account's document as its host serves it now, kept once
/// read; with the account's fetch held. `400 InvalidRequest` for a host
/// that answers anything but `2xx`, `500` for one that does not answer or
/// answers what is no document of the DID (`proxy::read_did`).
async fn fetch_web_doc(s: &Service, a: &Account) -> Result<Json, XrpcError> {
let doc = crate::proxy::read_did(s, &a.did).await.inspect_err(|e| {
crate::ops::failed_for(
Level::Warn,
"reading a did:web document failed",
&a.did,
e.name,
);
})?;
*write(&a.did_doc) = (doc.to_string().into(), Some(s.limits.clock.now()));
Ok(doc)
}
/// A `did:web` account's document read again from its host, past anything
/// kept, as `fetch_web_doc` reads it.
pub(crate) async fn web_doc_now(s: &Service, a: &Account) -> Result<Json, XrpcError> {
let _fetching = a.fetching.lock().await;
fetch_web_doc(s, a).await
}
/// After an operation the server posted for the account: its document,
@@ -174,7 +211,7 @@ async fn fetch_doc(s: &Service, a: &Account) -> Json {
async fn refetch_doc(s: &Service, a: &Account) {
let _fetching = a.fetching.lock().await;
write(&a.did_doc).1 = None;
fetch_doc(s, a).await;
let _ = fetch_doc(s, a).await;
}
/// Whether a DID document's first `at://` name is `at://<handle>`.
@@ -187,6 +224,43 @@ pub(crate) fn names_handle(doc: &Json, handle: &str) -> bool {
first.and_then(|u| u.strip_prefix("at://")) == Some(handle)
}
/// The signing key a `did:web` document names, as `atproto/did.md` takes
/// it: of its first `verificationMethod` whose `id` ends `#atproto`.
pub(crate) fn web_signing_key(doc: &Json) -> Option<crate::space_credentials::jwt::Key> {
let method = doc["verificationMethod"]
.as_array()?
.iter()
.find(|m| m["id"].as_str().is_some_and(|id| id.ends_with("#atproto")))?;
crate::space_credentials::jwt::Key::of_method(method)
}
/// The endpoint a `did:web` document names, as `atproto/did.md` takes it:
/// the `serviceEndpoint` of its first `service` whose `id` ends
/// `#atproto_pds` and whose `type` is `AtprotoPersonalDataServer`.
pub(crate) fn web_endpoint(doc: &Json) -> Option<&str> {
doc["service"].as_array()?.iter().find(|s| {
s["id"]
.as_str()
.is_some_and(|id| id.ends_with("#atproto_pds"))
&& s["type"] == "AtprotoPersonalDataServer"
})?["serviceEndpoint"]
.as_str()
}
/// Whether a `did:web` document names this server: its endpoint is
/// `PDS_PUBLIC_URL` and, if the account has one still, its signing key
/// the account's. No rotation key nor handle is asked of it.
pub(crate) fn web_names_server(
s: &Service,
doc: &Json,
signing: Option<&k256::ecdsa::VerifyingKey>,
) -> bool {
web_endpoint(doc) == Some(s.config.public_url.as_str())
&& signing.is_none_or(|k| {
web_signing_key(doc) == Some(crate::space_credentials::jwt::Key::K256(*k))
})
}
/// `GET /.well-known/atproto-did`: the DID of the account whose handle the
/// `Host` header names, less any `:port`, as given.
pub(crate) async fn well_known(AxState(s): AxState<Shared>, headers: HeaderMap) -> Response {
@@ -287,11 +361,13 @@ async fn settle_later(s: Weak<Service>, did: String) {
/// Settle an account's unsettled change, if it has one, by whether the
/// directory's log holds its operation; an error if the directory cannot say.
/// A `did:web`'s change posted nothing, and its document named the handle
/// when it was recorded: it landed.
async fn settle(s: &Service, a: &Account, change: &mut Option<Pending>) -> Result<(), String> {
let Some(p) = change.as_ref() else {
return Ok(());
};
let landed = plc::holds(&s.http, &s.config.plc_url, &a.did, &p.cid).await?;
let landed = is_web(&a.did) || plc::holds(&s.http, &s.config.plc_url, &a.did, &p.cid).await?;
if !finish(s, a, change, landed).await {
return Err("its settling could not be logged".into());
}
@@ -436,22 +512,40 @@ async fn update_handle(s: Shared, did: String, b: Map<String, Json>) -> Result<R
}
}
};
let last = match plc::last_operation(&s.http, &s.config.plc_url, &did).await {
Ok(op) => op,
Err(Upstream::Refused(why)) => return invalid(why),
Err(Upstream::Unreachable { why, .. }) => {
crate::ops::failed_for(Level::Warn, "updateHandle failed", &did, why);
return upstream();
// A `did:plc`'s handle goes to the directory in an operation; a
// `did:web`'s document, read again now, must name it already.
let (op, cid) = if is_web(&did) {
let doc = match web_doc_now(&s, &a).await {
Ok(doc) => doc,
Err(_) => return internal(),
};
if !names_handle(&doc, &handle) {
return invalid("DID document does not name the handle");
}
};
let (op, cid) =
match plc::update(&s.config, &last, &handle).and_then(|op| Ok((plc::cid(&op)?, op))) {
Ok((cid, op)) => (op, cid),
match plc::cid(&json!({ "did": did, "handle": handle })) {
Ok(cid) => (None, cid),
Err(why) => {
crate::ops::failed_for(Level::Error, "updateHandle failed", &did, why);
return internal();
}
}
} else {
let last = match plc::last_operation(&s.http, &s.config.plc_url, &did).await {
Ok(op) => op,
Err(Upstream::Refused(why)) => return invalid(why),
Err(Upstream::Unreachable { why, .. }) => {
crate::ops::failed_for(Level::Warn, "updateHandle failed", &did, why);
return upstream();
}
};
match plc::update(&s.config, &last, &handle).and_then(|op| Ok((plc::cid(&op)?, op))) {
Ok((cid, op)) => (Some(op), cid),
Err(why) => {
crate::ops::failed_for(Level::Error, "updateHandle failed", &did, why);
return internal();
}
}
};
// Recorded, and on disk, before the operation goes: from here the change
// holds the handle until it is settled. A start looks for it in the
// account's log, once marked (`cache`).
@@ -490,7 +584,12 @@ async fn update_handle(s: Shared, did: String, b: Map<String, Json>) -> Result<R
tokio::spawn(settle_later(Arc::downgrade(&s), did));
return internal();
}
let (landed, refused) = match plc::post(&s.http, &s.config.plc_url, &did, &op).await {
let posted = match &op {
// A `did:web`'s: nothing is posted, and it lands at once.
None => Ok(()),
Some(op) => plc::post(&s.http, &s.config.plc_url, &did, op).await,
};
let (landed, refused) = match posted {
Ok(()) => (true, None),
Err(Upstream::Refused(why)) => (false, Some(invalid(why))),
Err(Upstream::Unreachable { why, sent }) => {
crates/pds-server/src/lifecycle.rs+21−5
@@ -757,12 +757,20 @@ fn names_server(s: &Service, data: &Json, signing: Option<&str>) -> bool {
}
/// Whether the PLC directory's current data for the account's DID names
/// this server: its PDS, its signing key, and the server's rotation key.
/// this server: its PDS, its signing key, and the server's rotation key. A
/// `did:web`'s document is read from its host instead, its errors as
/// `identity::web_doc_now` gives them, and names this server by its
/// endpoint and signing key alone (`spec/MIGRATION.md`, "A `did:web` account").
async fn valid_did(s: &Service, a: &Account) -> Result<bool, XrpcError> {
let signing = *read(&a.store).repo.verifying_key();
if crate::identity::is_web(&a.did) {
let doc = crate::identity::web_doc_now(s, a).await?;
return Ok(crate::identity::web_names_server(s, &doc, Some(&signing)));
}
let Some(data) = did_data(s, &a.did).await? else {
return Ok(false);
};
let signing = crate::plc::did_key(read(&a.store).repo.verifying_key());
let signing = crate::plc::did_key(&signing);
Ok(names_server(s, &data, Some(&signing)))
}
@@ -787,10 +795,18 @@ async fn activate(s: &Shared, a: &Account) -> Result<(), XrpcError> {
/// account's, but there is no signing key to find in it, and one that
/// otherwise names this server is `500`, as the reference answers it.
async fn activate_gone(s: &Service, did: &str) -> Result<(), XrpcError> {
match did_data(s, did).await? {
Some(data) if names_server(s, &data, None) => internal(),
_ => not_this_server(),
let names = if crate::identity::is_web(did) {
let doc = crate::proxy::read_did(s, did).await?;
crate::identity::web_names_server(s, &doc, None)
} else {
did_data(s, did)
.await?
.is_some_and(|data| names_server(s, &data, None))
};
if names {
return internal();
}
not_this_server()
}
/// The token's account, which the gate found.
crates/pds-server/src/migration.rs+27−8
@@ -167,11 +167,17 @@ pub(crate) async fn service_caller(
_ => "atproto",
};
let key = |doc: &Json| Key::of_document_named(doc, did, id);
let Some(k) = crate::proxy::resolve_did(s, did)
.await
.ok()
.and_then(|d| key(&d))
else {
// Read as an account's is, held for `PDS_DID_CACHE_SECS`: one that cannot
// be read, or names no key, is `401`; but a `did:web` whose host does not
// answer, or answers what is no document of it, `500`.
let life = std::time::Duration::from_secs(s.config.did_cache);
let web = crate::identity::is_web(did) && crate::outbound::did_web_url(did, false).is_some();
let found = |doc: Result<std::sync::Arc<Json>, XrpcError>| match doc {
Ok(d) => Ok(key(&d)),
Err(e) if web && e.status == 500 => Err(e),
Err(_) => Ok(None),
};
let Some(k) = found(crate::proxy::resolve_did_within(s, did, life).await)? else {
return auth_required();
};
let signed = format!("{h}.{p}");
@@ -179,7 +185,7 @@ pub(crate) async fn service_caller(
if !k.verifies(alg, signed.as_bytes(), &signature, true) {
// A key rotated a moment ago: the document as the directory serves it now.
crate::proxy::forget_did(s, did);
let fresh = crate::proxy::resolve_did(s, did)
let fresh = crate::proxy::resolve_did_within(s, did, life)
.await
.ok()
.and_then(|d| key(&d));
@@ -497,6 +503,10 @@ async fn submit_plc_operation(
if op["alsoKnownAs"][0] != json!(format!("at://{}", a.handle())) {
return invalid("Incorrect handle in alsoKnownAs");
}
// A `did:web` is no directory's: its owner changes its document instead.
if crate::identity::is_web(&a.did) {
return invalid("A did:web has no PLC operations");
}
match crate::plc::post(
&s.http,
&s.config.plc_url,
@@ -526,7 +536,7 @@ async fn submit_plc_operation(
let _fetching = a.fetching.lock().await;
write(&a.did_doc).1 = None;
}
crate::identity::did_doc(&s, &a.did).await;
let _ = crate::identity::did_doc(&s, &a.did).await;
crate::lifecycle::tell(&s, &a, |seq, time| events::did_event(&a.did, seq, time)).await?;
Ok(Resp::Nothing)
}
@@ -554,7 +564,16 @@ async fn sign_plc_operation(s: Shared, t: Token, b: Map<String, Json>) -> Result
return invalid_token();
};
email::lock(&a.mail).check(Purpose::PlcOperation, token, s.sessions.now())?;
let last = match crate::plc::last_operation(&s.http, &s.config.plc_url, &a.did).await {
// The directory knows no `did:web`.
let last = if crate::identity::is_web(&a.did) {
Err(crate::plc::Upstream::Refused(format!(
"the directory has no operation for {}",
a.did
)))
} else {
crate::plc::last_operation(&s.http, &s.config.plc_url, &a.did).await
};
let last = match last {
Ok(op) => op,
Err(crate::plc::Upstream::Refused(why)) => return invalid(why),
Err(crate::plc::Upstream::Unreachable { why, .. }) => {
crates/pds-server/src/outbound.rs+11−0
@@ -199,6 +199,17 @@ pub(crate) fn did_web_url(did: &str, protect: bool) -> Option<url::Url> {
url::Url::parse(&format!("{scheme}://{host}{port}/.well-known/did.json")).ok()
}
/// Whether `did` is a `did:web` as `atproto/did.md` allows one: a host
/// name, no path, and a port only on `localhost`. The port is read from the
/// identifier, as a URL drops a port that is its scheme's default.
pub(crate) fn atproto_did_web(did: &str) -> bool {
let id = did
.strip_prefix("did:web:")
.unwrap_or_default()
.to_ascii_lowercase();
did_web_url(did, false).is_some() && (!id.contains("%3a") || id.starts_with("localhost%3a"))
}
/// A service's endpoint, as the spaces send to one (`spec/SPACES-SYNC.md`,
/// "Environment"): its `serviceEndpoint` when that is a string starting
/// with `http://` or `https://` that parses as a URL and has no user name
crates/pds-server/src/proxy.rs+33−23
@@ -432,20 +432,45 @@ pub(crate) async fn target(svc: &Service, header: Option<&str>) -> Result<Target
}
/// A service's DID document, read from the PLC directory or its `did:web`
/// host, and checked to be the DID's: `400 InvalidRequest` for one that
/// resolves to nothing, `500 InternalServerError` for one that cannot be
/// read or is not a document of the DID. A `did:web` document is read
/// through the guard (`outbound::Outbound::did_web`): an answer other than
/// `2xx` or `3xx` is `400`; a redirect, one longer than its limit, or none
/// at all, `500`.
/// host, and checked to be the DID's, kept for `DOC_LIFE` (`read_did`).
pub(crate) async fn resolve_did(svc: &Service, did: &str) -> Result<Arc<Json>, XrpcError> {
resolve_did_within(svc, did, DOC_LIFE).await
}
/// A DID's document as `resolve_did` reads it, but kept only for `life`:
/// one read longer ago than that is read again.
pub(crate) async fn resolve_did_within(
svc: &Service,
did: &str,
life: Duration,
) -> Result<Arc<Json>, XrpcError> {
let kept = read(&svc.did_docs.0)
.get(did)
.filter(|(at, _)| at.elapsed() < DOC_LIFE)
.filter(|(at, _)| at.elapsed() < life)
.map(|(_, d)| d.clone());
if let Some(doc) = kept {
return Ok(doc);
}
let doc = Arc::new(read_did(svc, did).await?);
let mut docs = write(&svc.did_docs.0);
if docs.len() >= DOCS_KEPT {
docs.retain(|_, (at, _)| at.elapsed() < DOC_LIFE);
if docs.len() >= DOCS_KEPT {
docs.clear();
}
}
docs.insert(did.to_string(), (Instant::now(), doc.clone()));
Ok(doc)
}
/// A DID's document, read now from the PLC directory or its `did:web`
/// host, and checked to be the DID's: `400 InvalidRequest` for one that
/// resolves to nothing, `500 InternalServerError` for one that cannot be
/// read or is not a document of the DID. A `did:web` document is read
/// through the guard (`outbound::Outbound::did_web`): an answer other than
/// `2xx` or `3xx` is `400`; a redirect, one longer than its limit, or none
/// at all, `500`.
pub(crate) async fn read_did(svc: &Service, did: &str) -> Result<Json, XrpcError> {
let doc: Json = if did.starts_with("did:plc:") && valid_did(did) {
match crate::plc::document(
&svc.http,
@@ -477,15 +502,6 @@ pub(crate) async fn resolve_did(svc: &Service, did: &str) -> Result<Arc<Json>, X
if !is_document(&doc, did) {
return internal();
}
let doc = Arc::new(doc);
let mut docs = write(&svc.did_docs.0);
if docs.len() >= DOCS_KEPT {
docs.retain(|_, (at, _)| at.elapsed() < DOC_LIFE);
if docs.len() >= DOCS_KEPT {
docs.clear();
}
}
docs.insert(did.to_string(), (Instant::now(), doc.clone()));
Ok(doc)
}
@@ -612,13 +628,7 @@ fn valid_audience(aud: &str) -> bool {
.bytes()
.all(|c| c.is_ascii_lowercase() || (b'2'..=b'7').contains(&c));
}
// A port follows `%3A`: read from the identifier, as a URL drops a port that is its scheme's default.
let id = did
.strip_prefix("did:web:")
.unwrap_or_default()
.to_ascii_lowercase();
crate::outbound::did_web_url(did, false).is_some()
&& (!id.contains("%3a") || id.starts_with("localhost%3a"))
crate::outbound::atproto_did_web(did)
}
fn get_service_auth(
crates/pds-server/src/repo.rs+5−2
@@ -123,7 +123,8 @@ fn list_records(
}
/// The repository, and its account's DID document as the directory serves
/// it now (`spec/IDENTITY.md`).
/// it now, or a `did:web`'s host: one that cannot be read is `400
/// InvalidRequest` (`spec/IDENTITY.md`).
async fn describe_repo(s: Shared, p: Map<String, Json>) -> Result<Resp, XrpcError> {
let repo = required(&p, "repo")?;
let missing = || XrpcError {
@@ -139,7 +140,9 @@ async fn describe_repo(s: Shared, p: Map<String, Json>) -> Result<Resp, XrpcErro
a.did.clone(),
))
})?;
let doc = crate::identity::did_doc(&s, &did).await;
let Ok(doc) = crate::identity::did_doc(&s, &did).await else {
return invalid(format!("Could not resolve DID {did}"));
};
out["handleIsCorrect"] = json!(crate::identity::names_handle(
&doc,
out["handle"].as_str().unwrap_or_default()
crates/pds-server/src/server.rs+22−3
@@ -387,8 +387,11 @@ async fn create_account(
"Missing auth to create account with did",
);
}
if !did.starts_with("did:plc:") {
return invalid("Only did:plc accounts may move here");
let web = crate::identity::is_web(did)
&& pds_repo::data::valid_did(did)
&& crate::outbound::atproto_did_web(did);
if !did.starts_with("did:plc:") && !web {
return invalid("Only did:plc and did:web accounts may move here");
}
if d.by_did.contains_key(did) || d.claimed_dids.contains(did) {
return err(400, "AlreadyExists", "Repo already exists");
@@ -427,7 +430,23 @@ async fn create_account(
let kem = pds_space::KemKey::generate();
let (did, did_doc) = match &moving {
// Its DID is its own already: no operation goes to the directory, and
// its document is the one the directory serves for it now.
// its document is the one the directory, or a `did:web`'s host, serves
// for it now; a `did:web`'s as the service token's check read it.
Some(did) if crate::identity::is_web(did) => {
let life = std::time::Duration::from_secs(s.config.did_cache);
match crate::proxy::resolve_did_within(&s, did, life).await {
Ok(doc) => (did.clone(), Json::clone(&doc)),
Err(e) => {
crate::ops::failed_for(
crate::ops::Level::Warn,
"createAccount failed",
did,
e.message,
);
return internal();
}
}
}
Some(did) => {
let url = format!("{}/{did}", s.config.plc_url.trim_end_matches('/'));
match crate::plc::document(&s.http, &url).await {
harness/checks/moves.mjs+165−3
@@ -1,16 +1,17 @@
// Accounts moving between servers (spec/MIGRATION.md): to each side from a
// third PDS, the reference on the same PLC directory, and from each side to
// it; and the methods of a move by account state. A run of its own,
// `--moves`: its steps are a move in, a move out and the states, in
// `--moves`: its steps are a move in, a move out, the states and a did:web account, in
// turn, the same requests to both sides, compared, with both firehoses held
// to what each move puts on them.
import http from 'node:http'
import { isDeepStrictEqual } from 'node:util'
import { TestPds } from '@atproto/dev-env'
import { createServiceJwt } from '@atproto/xrpc-server'
import { Secp256k1Keypair, verifySignature } from '@atproto/crypto'
import { cborDecode, cborEncode, cidForCbor } from '@atproto/common'
import { readCarWithRoot, verifyRepoCar } from '@atproto/repo'
import { MemoryBlockstore, Repo, WriteOpAction, blocksToCarFile, readCarWithRoot, verifyRepoCar } from '@atproto/repo'
import { MOVES_STEPS } from '../lib/args.mjs'
import { ADMIN_PASSWORD, MAX_REPO_IMPORT } from '../lib/env.mjs'
import { checkMail } from '../lib/mail.mjs'
@@ -553,6 +554,167 @@ async function verifyAgainstDoc(side, did, what) {
}
}
// ---- A did:web account --------------------------------------------------
/// A `did:web` the harness is the owner of, one for each side: a host of
/// its own on this machine, `localhost:<port>`, serving the document
/// `serve` last gave it, or `404` after `unserve`. Answers `{did, key,
/// serve, unserve, doc}`.
async function webDid(front, side) {
let doc = null
const web = http.createServer((req, res) => {
if (req.url !== '/.well-known/did.json' || !doc) return res.writeHead(404, { 'content-type': 'text/plain' }).end('not found')
res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(doc))
})
await new Promise((ok) => web.listen(0, '127.0.0.1', ok))
web.unref()
const did = `did:web:localhost%3A${web.address().port}`
const key = await Secp256k1Keypair.create({ exportable: true })
name(side, did, `<web:${front}>`)
const w = {
did,
key,
get doc() {
return doc
},
/// Serve a document naming `handle`, the signing key `signing` and
/// the endpoint `pds`, as atproto/did.md lays one out.
async serve({ handle, signing, pds }) {
doc = {
'@context': ['https://www.w3.org/ns/did/v1', 'https://w3id.org/security/multikey/v1'],
id: did,
alsoKnownAs: [`at://${handle}`],
verificationMethod: [{ id: `${did}#atproto`, type: 'Multikey', controller: did, publicKeyMultibase: signing.replace(/^did:key:/, '') }],
service: [{ id: '#atproto_pds', type: 'AtprotoPersonalDataServer', serviceEndpoint: pds }],
}
// The reference keeps the documents it resolved: have it read this one.
if (side === ref) await net.pds.ctx.idResolver.did.resolve(did, true).catch(() => {})
},
async unserve() {
doc = null
if (side === ref) await net.pds.ctx.idResolver.did.resolve(did, true).catch(() => {})
},
}
return w
}
/// A repository of `did`, with `records`, signed with `key`, as a CAR file:
/// the account's own, which it brings to a server for the first time.
async function ownRepo(did, key, records) {
const storage = new MemoryBlockstore()
const writes = records.map((r) => ({ action: WriteOpAction.Create, collection: C, rkey: r.rkey, record: r.value }))
const repo = await Repo.create(storage, did, key, writes)
return blocksToCarFile(repo.cid, storage.blocks)
}
/// A `did:web` account made on each side by its owner, the harness, with a
/// service token it signs itself, then moved in whole: its repository
/// imported, its document pointed at the side, activated, written to, its
/// handle changed (spec/MIGRATION.md, "A `did:web` account").
async function webAccount() {
const front = `web${run.step}`
const data = content()
const w = { reference: await webDid(front, ref), server: await webDid(front, cand) }
for (const side of sides()) await w[side.name].serve({ handle: `${front}.test`, signing: w[side.name].key.did(), pds: 'https://old.example.com' })
const did = { reference: w.reference.did, server: w.server.did }
const token = (side, claims = {}, keypair) => createServiceJwt({ iss: did[side.name], aud: sideDid, lxm: `${S}createAccount`, keypair: keypair ?? w[side.name].key, ...claims })
const body = (side) => ({ did: did[side.name], handle: `${front}.test`, email: `${front}@web.example.com`, password: 'web-pass' })
// Refused, then made.
if (chance(0.5)) await same('createAccount of a did:web: no token', `${S}createAccount`, (side) => ({ body: body(side) }))
if (chance(0.5)) {
const other = await Secp256k1Keypair.create()
const req = {}
for (const side of sides()) req[side.name] = { auth: bearer(await token(side, {}, other)), body: body(side) }
await same('createAccount of a did:web: a key not its document\'s', `${S}createAccount`, (side) => req[side.name])
}
if (chance(0.5)) {
for (const side of sides()) await w[side.name].unserve()
const req = {}
for (const side of sides()) req[side.name] = { auth: bearer(await token(side)), body: body(side) }
await same('createAccount of a did:web: its document not found', `${S}createAccount`, (side) => req[side.name])
for (const side of sides()) await w[side.name].serve({ handle: `${front}.test`, signing: w[side.name].key.did(), pds: 'https://old.example.com' })
}
const req = {}
for (const side of sides()) req[side.name] = { auth: bearer(await token(side)), body: body(side) }
const tok = {}
const [a, b] = await same('createAccount of a did:web', `${S}createAccount`, (side) => req[side.name], (side, res) => {
tok[side.name] = res.body?.accessJwt
})
for (const [side, res] of [[ref, a], [cand, b]]) if (res.status === 200 && !isDeepStrictEqual(res.body.didDoc, w[side.name].doc)) await fail(side, 'createAccount of a did:web: didDoc', { did: '<web>' }, w[side.name].doc, res.body.didDoc)
if (a.status !== 200) return
const own = (side) => bearer(tok[side.name])
await checkEvents('createAccount of a did:web', did, [])
await same('getSession of a did:web moving in', `${S}getSession`, (side) => ({ auth: own(side) }))
await same('checkAccountStatus of a did:web moving in', `${S}checkAccountStatus`, (side) => ({ auth: own(side) }))
await same('describeRepo of a did:web moving in', `${R}describeRepo`, (side) => ({ params: { repo: did[side.name] } }))
// Its own repository, signed by its owner.
const car = {}
for (const side of sides()) car[side.name] = await ownRepo(did[side.name], w[side.name].key, data.records)
await same('importRepo of a did:web\'s own repository', `${R}importRepo`, (side) => ({ auth: own(side), body: car[side.name] }))
await same('checkAccountStatus after importRepo of a did:web', `${S}checkAccountStatus`, (side) => ({ auth: own(side) }))
await checkEvents('importRepo of a did:web', did, [])
// No PLC method applies.
await same('getRecommendedDidCredentials of a did:web', `${I}getRecommendedDidCredentials`, (side) => ({ auth: own(side) }))
const creds = {}
for (const side of sides()) creds[side.name] = (await send(side, `${I}getRecommendedDidCredentials`, { auth: own(side) })).body
await same('requestPlcOperationSignature of a did:web', `${I}requestPlcOperationSignature`, (side) => ({ auth: own(side), method: 'POST' }))
const mailed = await mailedTokens('requestPlcOperationSignature of a did:web', { did: '<web>' })
await same('signPlcOperation of a did:web', `${I}signPlcOperation`, (side) => ({ auth: own(side), body: { token: mailed[side.name] } }))
if (ownRules()) {
const op = { type: 'plc_operation', ...creds.server, prev: null, sig: 'c2ln' }
const res = await send(cand, `${I}submitPlcOperation`, { auth: own(cand), body: { operation: op } })
count('moves: submitPlcOperation of a did:web', res.status < 400)
if (res.status !== 400 || res.body?.error !== 'InvalidRequest') await fail(cand, 'submitPlcOperation of a did:web (spec/MIGRATION.md, "Where the reference departs")', { did: '<web>' }, { status: 400, error: 'InvalidRequest' }, { status: res.status, error: res.body?.error })
}
// Its document pointed here, by its owner; then activated.
await same('activateAccount of a did:web whose document names its old server', `${S}activateAccount`, (side) => ({ auth: own(side), method: 'POST' }))
for (const side of sides()) await w[side.name].serve({ handle: `${front}.test`, signing: creds[side.name].verificationMethods.atproto, pds: side.publicUrl })
await same('checkAccountStatus of a did:web pointed here', `${S}checkAccountStatus`, (side) => ({ auth: own(side) }))
await same('activateAccount of a did:web', `${S}activateAccount`, (side) => ({ auth: own(side), method: 'POST' }))
await checkEvents('activateAccount of a did:web', did, [{ t: '#account', active: true }, { t: '#identity', handle: `${front}.test` }, { t: '#sync' }])
await same('describeRepo of a did:web moved in', `${R}describeRepo`, (side) => ({ params: { repo: did[side.name] } }))
await same('a write of a did:web moved in', `${R}createRecord`, (side) => ({ auth: own(side), body: { repo: did[side.name], collection: C, rkey: 'after', record: { $type: C, text: 'after the move' } } }))
await checkEvents('a write of a did:web', did, [{ t: '#commit' }])
for (const side of sides()) await verifyAgainstKey(side, did[side.name], creds[side.name].verificationMethods.atproto, 'getRepo of a did:web moved in')
// Its handle, changed in its document first.
const next = `${front}x.test`
await same('updateHandle of a did:web to a handle its document does not name', `${I}updateHandle`, (side) => ({ auth: own(side), body: { handle: next } }))
await checkEvents('updateHandle of a did:web refused', did, [])
for (const side of sides()) await w[side.name].serve({ handle: next, signing: creds[side.name].verificationMethods.atproto, pds: side.publicUrl })
await same('updateHandle of a did:web', `${I}updateHandle`, (side) => ({ auth: own(side), body: { handle: next } }))
await checkEvents('updateHandle of a did:web', did, [{ t: '#identity', handle: next }])
await same('describeRepo of a did:web by its new handle', `${R}describeRepo`, (side) => ({ params: { repo: next } }))
await same('resolveHandle of a did:web\'s handle', `${I}resolveHandle`, (side) => ({ params: { handle: next } }))
for (const side of sides()) {
const log = await plcLog(did[side.name])
if (log.status === 200) await fail(side, 'the PLC directory after a did:web\'s moves', { did: '<web>' }, 'no operations: a did:web is no directory\'s', log.body)
}
// Its document gone.
if (chance(0.5)) {
for (const side of sides()) await w[side.name].unserve()
await same('describeRepo of a did:web whose document is gone', `${R}describeRepo`, (side) => ({ params: { repo: did[side.name] } }))
await same('checkAccountStatus of a did:web whose document is gone', `${S}checkAccountStatus`, (side) => ({ auth: own(side) }))
await same('activateAccount of a did:web whose document is gone', `${S}activateAccount`, (side) => ({ auth: own(side), method: 'POST' }))
}
}
/// A side's whole repository must verify against `key`.
async function verifyAgainstKey(side, did, key, what) {
const res = await send(side, `${Y}getRepo`, { params: { did } })
try {
if (!res.bytes) throw new Error(`getRepo answered ${res.status} ${JSON.stringify(res.body)}`)
await verifyRepoCar(res.bytes, did, key)
} catch (err) {
await fail(side, what, { did: '<web>' }, `a repository verified against ${key}`, String(err.message ?? err))
}
}
/// listMissingBlobs, held to the records that reference each blob, then
/// each blob uploaded, in a random order.
async function missingBlobs(o, tok, data, appPw) {
@@ -848,7 +1010,7 @@ export async function movesRun() {
squatter = await makeOnBoth('createAccount of an account in the way', { handle: 'squat.test', email: 'squat@here.example.com', password: 'squat-pass' })
squatter.email = 'squat@here.example.com'
passwordless = await makeOnBoth('createAccount without a password', { handle: 'nopass.test', email: 'nopass@here.example.com' })
const kinds = [moveIn, moveOut, states]
const kinds = [moveIn, moveOut, states, webAccount]
for (run.step = 1; run.step <= MOVES_STEPS; run.step++) {
const step = kinds[(run.step - 1) % kinds.length]
process.stderr.write(`\rmove step ${run.step}/${MOVES_STEPS}: ${step.name} `)
harness/checks/operations.mjs+11−6
harness/lib/args.mjs+2−2
harness/lib/processes.mjs+15−4
spec/ACCOUNTS.md+5−4
spec/IDENTITY.md+12−7
spec/LIFECYCLE.md+4−1
spec/LIMITS.md+1−1
spec/MIGRATION.md+94−14
spec/OPERATIONS.md+4−3
README.md+2−2