feat(pds): DID-Dokument unter /.well-known/did.json ausliefern

Die AppView soll die Access-Tokens der PDS prüfen können, ohne dass
PDS_JWT_SECRET den PDS-Prozess verlässt. Verifiziert wird ES256 mit dem
*öffentlichen* Teil des P-256-Schlüssels — den veröffentlicht die PDS
jetzt als verificationMethod (Multikey) in ihrem DID-Dokument.

Damit fällt auch die hartkodierte Service-DID: describeServer gab stur
did:web:pds.maarcadetweet.local zurück, unabhängig von PDS_PUBLIC_URL.
Beide Endpoints leiten sie jetzt aus einer Quelle ab
(AppConfig::pds_did(), did:web-Regel mit %3A-kodiertem Port). Der `iss`
des Access-Tokens baute die DID zuvor ohne Port-Kodierung zusammen —
also in einer Form, der kein did:web-Resolver folgen könnte.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013HC9HLrUU1LNwkzp8nkDLX
This commit is contained in:
tomdebone
2026-09-09 23:01:16 +02:00
co-authored by Claude Opus 5
parent ec8fe187fe
commit 786a892658
4 changed files with 354 additions and 3 deletions
+7 -1
View File
@@ -39,7 +39,13 @@ pub fn issue_access_jwt(
let now = chrono::Utc::now().timestamp();
let exp = now + 3600;
let claims = JwtClaims {
iss: format!("did:web:{}", cfg.pds_public_url.trim_start_matches("http://").trim_start_matches("https://")),
// Same derivation as `describeServer` and `/.well-known/did.json`
// (`AppConfig::pds_did`), so a verifier can take `iss`, resolve
// the did:web document and arrive at the key this token is
// signed with. The previous inline version dropped the
// percent-encoding of the port, producing an `iss` that no
// did:web resolver could follow.
iss: cfg.pds_did(),
sub: did.to_string(),
aud: "did:web:appview.maarcadetweet.local".into(),
iat: now,
+62 -1
View File
@@ -73,6 +73,7 @@ pub fn router(state: AppState) -> Router {
Router::new()
.route("/", get(root))
.route("/healthz", get(healthz))
.route("/.well-known/did.json", get(did_document))
.route(
"/xrpc/com.atproto.server.describeServer",
get(describe_server),
@@ -163,9 +164,69 @@ async fn healthz() -> Json<serde_json::Value> {
Json(json!({ "ok": true }))
}
/// `GET /.well-known/did.json` — the PDS's own DID document.
///
/// This is how the AppView (and any other relying party) learns the
/// P-256 public key that the access JWTs in
/// `Authorization: Bearer …` are signed with. Without it the AppView
/// could not verify a token at all, and the only alternative would be
/// shipping `PDS_JWT_SECRET` to a second service — a private signing
/// key crossing a service boundary, for a check that needs nothing but
/// the public half.
///
/// Nothing in this response is secret. `publicKeyMultibase` is the
/// uncompressed P-256 point derived from `PDS_JWT_SECRET` by
/// [`jwt_issuer::server_p256_public_multibase`]; the secret itself
/// never leaves this process.
///
/// The document id is [`AppConfig::pds_did`], i.e. it follows
/// `PDS_PUBLIC_URL` — so a `did:web:` resolver that starts from the DID,
/// rebuilds the URL and fetches this path lands back here rather than at
/// some other host's document.
async fn did_document(State(state): State<AppState>) -> Result<Json<serde_json::Value>, (axum::http::StatusCode, Json<serde_json::Value>)> {
let did = state.cfg.pds_did();
let public_multibase = jwt_issuer::server_p256_public_multibase(&state.cfg).map_err(|e| {
// A malformed `PDS_JWT_SECRET` is the one way this fails, and
// it is exactly the failure that also breaks every token this
// server issues — surface it instead of publishing a document
// with a missing key.
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({
"error": "InternalServerError",
"message": format!("server key unavailable: {e}"),
})),
)
})?;
Ok(Json(json!({
"@context": [
"https://www.w3.org/ns/did/v1",
"https://w3id.org/security/multikey/v1",
],
"id": did,
"verificationMethod": [{
// `#atproto` is the fragment AT Proto uses for a repo's
// signing key; we reuse it for the server key so a generic
// did:web consumer finds it in the usual place.
"id": format!("{did}#atproto"),
"type": "Multikey",
"controller": did,
"publicKeyMultibase": public_multibase,
}],
"service": [{
"id": "#atproto_pds",
"type": "AtprotoPersonalDataServer",
"serviceEndpoint": state.cfg.pds_public_url,
}],
})))
}
async fn describe_server(State(state): State<AppState>) -> Json<DescribeServerResp> {
Json(DescribeServerResp {
did: "did:web:pds.maarcadetweet.local".into(),
// Derived from `PDS_PUBLIC_URL`, never hardcoded — see
// `AppConfig::pds_did`. The same value ids the document at
// `/.well-known/did.json`.
did: state.cfg.pds_did(),
available_user_domains: vec![state
.cfg
.pds_handle_dns_zone
+76 -1
View File
@@ -38,11 +38,86 @@ async fn describe_server() {
.json()
.await
.unwrap();
assert!(r["did"].is_string());
// The DID is derived from `PDS_PUBLIC_URL`, not hardcoded — so we
// assert the *shape* (any deployment must produce a did:web) and
// leave the exact value to `at_shared::config`'s unit tests.
let did = r["did"].as_str().expect("describeServer must return a did");
assert!(did.starts_with("did:web:"), "did = {did}");
assert!(r["available_user_domains"].is_array());
assert_eq!(r["invite_code_required"], json!(false));
}
/// `GET /.well-known/did.json` — the document the AppView fetches to
/// learn the key our access tokens are signed with.
///
/// Two properties matter beyond "it returns JSON": the document's `id`
/// must be the same DID `describeServer` advertises (otherwise a client
/// that trusts one and resolves the other ends up at a different
/// identity), and it must carry a usable `publicKeyMultibase`.
#[tokio::test]
async fn did_document_publishes_the_server_key() {
if !wait_for_pds().await {
eprintln!("pds not running, skipping");
return;
}
let c = client().await;
let doc: Value = c
.get(format!("{}/.well-known/did.json", PDS_URL))
.send()
.await
.unwrap()
.json()
.await
.unwrap();
let id = doc["id"].as_str().expect("did document needs an id");
assert!(id.starts_with("did:web:"), "id = {id}");
let described: Value = c
.get(format!("{}/xrpc/com.atproto.server.describeServer", PDS_URL))
.send()
.await
.unwrap()
.json()
.await
.unwrap();
assert_eq!(
described["did"].as_str().unwrap(),
id,
"describeServer and the did document must name the same identity"
);
let vm = &doc["verificationMethod"][0];
assert_eq!(vm["type"], json!("Multikey"));
assert_eq!(vm["controller"], json!(id));
assert_eq!(vm["id"], json!(format!("{id}#atproto")));
let key = vm["publicKeyMultibase"]
.as_str()
.expect("verificationMethod needs publicKeyMultibase");
// base58-btc multibase — the `z` prefix the AppView's decoder wants.
assert!(key.starts_with('z'), "key = {key}");
// And it really is the key our tokens verify against: mint a
// session and check the access JWT against the published key.
let handle = format!("didjson_{}.maarcadetweet.local", uuid::Uuid::new_v4().simple());
let acc: Value = c
.post(format!("{}/xrpc/com.atproto.server.createAccount", PDS_URL))
.json(&json!({"handle": handle, "password": "hunter2hunter2"}))
.send()
.await
.unwrap()
.json()
.await
.unwrap();
let jwt = acc["access_jwt"].as_str().expect("access_jwt");
let claims = at_crypto::jwt::verify_jwt(jwt, key)
.expect("access token must verify against the published key");
assert_eq!(claims.sub, acc["did"].as_str().unwrap());
assert_eq!(claims.scope.as_deref(), Some("com.atproto.access"));
// `iss` is the same did:web the document identifies.
assert_eq!(claims.iss, id);
}
#[tokio::test]
async fn create_account_session_refresh_resolve() {
if !wait_for_pds().await {