Skip to main content

hyprstream_pds/
hosted_did_document.rs

1//! Canonical DID-document artifact for a hyprstream-hosted account.
2//!
3//! The account document is an immutable input to genesis, not a response
4//! assembled by an HTTP handler. [`HostedAccountMint`](crate::HostedAccountMint)
5//! builds it from the mint's own account DID and generated ES256 key, then
6//! [`SealedHostedDidDocument::cid`] is signed into the genesis `DidOp`.
7//! Serving code must return [`SealedHostedDidDocument::as_bytes`] byte-for-byte.
8
9use std::collections::BTreeSet;
10
11use anyhow::{bail, ensure, Context, Result};
12use p256::ecdsa::VerifyingKey;
13use serde_json::{json, Map, Value};
14
15use crate::cid::Cid;
16use crate::did_op::validate_host_form_did_web;
17use crate::hosted_account::AllocatedAccountName;
18
19/// Media type for the canonical account DID-document bytes.
20pub const DID_DOCUMENT_MEDIA_TYPE: &str = "application/did+json";
21/// Relative path at which B3 serves the canonical document.
22pub const DID_DOCUMENT_PATH: &str = "/.well-known/did.json";
23/// Relative path at which B3 serves the account's operation log.
24pub const DID_OPERATION_LOG_PATH: &str = "/.well-known/did-log.json";
25
26const MAX_DID_DOCUMENT_BYTES: usize = 16 * 1024;
27const P256_MULTICODEC_PREFIX: [u8; 2] = [0x80, 0x24];
28const COMPRESSED_P256_PUBLIC_KEY_LEN: usize = 33;
29const DID_CONTEXT: &str = "https://www.w3.org/ns/did/v1";
30const MULTIKEY_CONTEXT: &str = "https://w3id.org/security/multikey/v1";
31
32/// A validated, byte-stable hosted-account DID document and its raw CID.
33///
34/// Fields are private so a caller cannot change a document after its CID has
35/// been bound into genesis.
36#[derive(Clone, Debug, Eq, PartialEq)]
37pub struct SealedHostedDidDocument {
38    did: String,
39    handle: String,
40    pds_endpoint: String,
41    atproto_key: Vec<u8>,
42    bytes: Vec<u8>,
43    cid: Cid,
44}
45
46impl SealedHostedDidDocument {
47    /// Parse and strictly validate canonical bytes loaded from sealed storage.
48    ///
49    /// The accepted shape is deliberately exact: one `#atproto` P-256
50    /// `Multikey`, one atproto PDS service, one operation-log service, and one
51    /// `at://` alias equal to the immutable account host. Unknown fields,
52    /// alternate aliases, and non-canonical JSON fail closed.
53    pub fn from_canonical_json(bytes: &[u8]) -> Result<Self> {
54        ensure!(
55            bytes.len() <= MAX_DID_DOCUMENT_BYTES,
56            "hosted DID document exceeds {MAX_DID_DOCUMENT_BYTES} bytes"
57        );
58        let value: Value =
59            serde_json::from_slice(bytes).context("hosted DID document is not valid JSON")?;
60        ensure!(
61            canonical_json(&value)? == bytes,
62            "hosted DID document is not canonical JSON"
63        );
64        validate_exact_keys(
65            &value,
66            &[
67                "@context",
68                "alsoKnownAs",
69                "id",
70                "service",
71                "verificationMethod",
72            ],
73            "hosted DID document",
74        )?;
75
76        let did = required_string(&value, "id", "hosted DID document")?.to_owned();
77        validate_host_form_did_web(&did)?;
78        let host = did
79            .strip_prefix("did:web:")
80            .ok_or_else(|| anyhow::anyhow!("hosted DID document id must use did:web"))?;
81
82        let contexts = required_array(&value, "@context", "hosted DID document")?;
83        ensure!(
84            contexts
85                == [
86                    Value::String(DID_CONTEXT.to_owned()),
87                    Value::String(MULTIKEY_CONTEXT.to_owned()),
88                ],
89            "hosted DID document has an unsupported @context"
90        );
91
92        let aliases = required_array(&value, "alsoKnownAs", "hosted DID document")?;
93        let expected_handle = format!("at://{host}");
94        ensure!(
95            aliases == [Value::String(expected_handle.clone())],
96            "hosted DID document must contain exactly the account at:// handle and no other alias"
97        );
98
99        let methods = required_array(&value, "verificationMethod", "hosted DID document")?;
100        ensure!(
101            methods.len() == 1,
102            "hosted DID document must contain exactly one verification method"
103        );
104        let method = methods
105            .first()
106            .ok_or_else(|| anyhow::anyhow!("hosted DID document omits #atproto"))?;
107        validate_exact_keys(
108            method,
109            &["controller", "id", "publicKeyMultibase", "type"],
110            "#atproto verification method",
111        )?;
112        ensure!(
113            required_string(method, "id", "#atproto verification method")?
114                == format!("{did}#atproto"),
115            "hosted DID document verification method must be the account's #atproto fragment"
116        );
117        ensure!(
118            required_string(method, "controller", "#atproto verification method")? == did,
119            "hosted DID document #atproto controller does not match its id"
120        );
121        ensure!(
122            required_string(method, "type", "#atproto verification method")? == "Multikey",
123            "hosted DID document #atproto method must use Multikey"
124        );
125        let atproto_key = decode_p256_multibase(required_string(
126            method,
127            "publicKeyMultibase",
128            "#atproto verification method",
129        )?)?;
130
131        let services = required_array(&value, "service", "hosted DID document")?;
132        ensure!(
133            services.len() == 2,
134            "hosted DID document must contain exactly the PDS and operation-log services"
135        );
136        let pds = services
137            .first()
138            .ok_or_else(|| anyhow::anyhow!("hosted DID document omits its PDS service"))?;
139        validate_service(
140            pds,
141            &format!("{did}#atproto_pds"),
142            "AtprotoPersonalDataServer",
143        )?;
144        let pds_endpoint =
145            required_string(pds, "serviceEndpoint", "atproto PDS service")?.to_owned();
146        validate_https_origin(&pds_endpoint)?;
147
148        let operation_log = services.get(1).ok_or_else(|| {
149            anyhow::anyhow!("hosted DID document omits its operation-log service")
150        })?;
151        validate_service(operation_log, &format!("{did}#did-log"), "DidOperationLog")?;
152        let operation_log_endpoint = required_string(
153            operation_log,
154            "serviceEndpoint",
155            "DID operation-log service",
156        )?;
157        ensure!(
158            operation_log_endpoint == format!("https://{host}{DID_OPERATION_LOG_PATH}"),
159            "hosted DID document operation-log endpoint must be served by its own did:web host"
160        );
161
162        Ok(Self {
163            did,
164            handle: expected_handle,
165            pds_endpoint,
166            atproto_key,
167            cid: Cid::from_raw(bytes),
168            bytes: bytes.to_vec(),
169        })
170    }
171
172    pub(crate) fn seal(
173        name: &AllocatedAccountName,
174        atproto_key: &VerifyingKey,
175        pds_endpoint: &str,
176    ) -> Result<Self> {
177        validate_https_origin(pds_endpoint)?;
178        let did = name.did();
179        validate_host_form_did_web(did)?;
180        let host = did
181            .strip_prefix("did:web:")
182            .ok_or_else(|| anyhow::anyhow!("hosted account DID must use did:web"))?;
183        let handle = format!("at://{host}");
184        let public_key_multibase = encode_p256_multibase(atproto_key);
185
186        let document = json!({
187            "@context": [DID_CONTEXT, MULTIKEY_CONTEXT],
188            "alsoKnownAs": [handle],
189            "id": did,
190            "service": [
191                {
192                    "id": format!("{did}#atproto_pds"),
193                    "serviceEndpoint": pds_endpoint,
194                    "type": "AtprotoPersonalDataServer",
195                },
196                {
197                    "id": format!("{did}#did-log"),
198                    "serviceEndpoint": format!("https://{host}{DID_OPERATION_LOG_PATH}"),
199                    "type": "DidOperationLog",
200                },
201            ],
202            "verificationMethod": [{
203                "controller": did,
204                "id": format!("{did}#atproto"),
205                "publicKeyMultibase": public_key_multibase,
206                "type": "Multikey",
207            }],
208        });
209        let bytes = canonical_json(&document)?;
210        let sealed = Self::from_canonical_json(&bytes)?;
211        ensure!(
212            sealed.atproto_verifying_key()?.to_encoded_point(true)
213                == atproto_key.to_encoded_point(true),
214            "sealed DID document changed the mint's #atproto key"
215        );
216        Ok(sealed)
217    }
218
219    /// Immutable account DID named by this artifact.
220    #[must_use]
221    pub fn did(&self) -> &str {
222        &self.did
223    }
224
225    /// Account handle, always `at://` plus the host-form DID authority.
226    #[must_use]
227    pub fn handle(&self) -> &str {
228        &self.handle
229    }
230
231    /// Origin advertised by the atproto PDS service entry.
232    #[must_use]
233    pub fn pds_endpoint(&self) -> &str {
234        &self.pds_endpoint
235    }
236
237    /// Generated account-specific P-256 key carried by `#atproto`.
238    pub fn atproto_verifying_key(&self) -> Result<VerifyingKey> {
239        VerifyingKey::from_sec1_bytes(&self.atproto_key)
240            .context("sealed DID document contains an invalid #atproto P-256 key")
241    }
242
243    /// Canonical bytes to place in sealed storage and serve byte-for-byte.
244    #[must_use]
245    pub fn as_bytes(&self) -> &[u8] {
246        &self.bytes
247    }
248
249    /// Raw-codec CID over the exact canonical JSON bytes.
250    #[must_use]
251    pub fn cid(&self) -> Cid {
252        self.cid
253    }
254}
255
256fn encode_p256_multibase(key: &VerifyingKey) -> String {
257    let point = key.to_encoded_point(true);
258    let mut payload =
259        Vec::with_capacity(P256_MULTICODEC_PREFIX.len() + COMPRESSED_P256_PUBLIC_KEY_LEN);
260    payload.extend_from_slice(&P256_MULTICODEC_PREFIX);
261    payload.extend_from_slice(point.as_bytes());
262    format!("z{}", bs58::encode(payload).into_string())
263}
264
265fn decode_p256_multibase(encoded: &str) -> Result<Vec<u8>> {
266    let payload = encoded
267        .strip_prefix('z')
268        .ok_or_else(|| anyhow::anyhow!("#atproto publicKeyMultibase must use base58btc"))?;
269    let decoded = bs58::decode(payload)
270        .into_vec()
271        .context("#atproto publicKeyMultibase is not valid base58btc")?;
272    ensure!(
273        decoded.starts_with(&P256_MULTICODEC_PREFIX),
274        "#atproto publicKeyMultibase must use the p256-pub multicodec"
275    );
276    let key = decoded[P256_MULTICODEC_PREFIX.len()..].to_vec();
277    ensure!(
278        key.len() == COMPRESSED_P256_PUBLIC_KEY_LEN,
279        "#atproto P-256 key must be a compressed SEC1 point"
280    );
281    VerifyingKey::from_sec1_bytes(&key).context("#atproto P-256 key is invalid")?;
282    Ok(key)
283}
284
285fn validate_service(value: &Value, id: &str, service_type: &str) -> Result<()> {
286    validate_exact_keys(value, &["id", "serviceEndpoint", "type"], service_type)?;
287    ensure!(
288        required_string(value, "id", service_type)? == id,
289        "{service_type} service id is invalid"
290    );
291    ensure!(
292        required_string(value, "type", service_type)? == service_type,
293        "{service_type} service type is invalid"
294    );
295    Ok(())
296}
297
298fn validate_https_origin(endpoint: &str) -> Result<()> {
299    let parsed = url::Url::parse(endpoint).context("PDS service endpoint is not a valid URL")?;
300    ensure!(
301        parsed.scheme() == "https",
302        "PDS service endpoint must use HTTPS"
303    );
304    ensure!(
305        parsed.host().is_some(),
306        "PDS service endpoint must have a host"
307    );
308    ensure!(
309        parsed.username().is_empty() && parsed.password().is_none(),
310        "PDS service endpoint must not contain credentials"
311    );
312    ensure!(
313        parsed.path() == "/" && parsed.query().is_none() && parsed.fragment().is_none(),
314        "PDS service endpoint must be an origin without path, query, or fragment"
315    );
316    ensure!(
317        endpoint == parsed.origin().ascii_serialization(),
318        "PDS service endpoint must use its canonical origin form"
319    );
320    Ok(())
321}
322
323fn validate_exact_keys(value: &Value, expected: &[&str], what: &str) -> Result<()> {
324    let object = value
325        .as_object()
326        .ok_or_else(|| anyhow::anyhow!("{what} must be a JSON object"))?;
327    let actual = object.keys().map(String::as_str).collect::<BTreeSet<_>>();
328    let expected = expected.iter().copied().collect::<BTreeSet<_>>();
329    ensure!(actual == expected, "{what} has missing or unknown fields");
330    Ok(())
331}
332
333fn required_string<'a>(value: &'a Value, key: &str, what: &str) -> Result<&'a str> {
334    value
335        .get(key)
336        .and_then(Value::as_str)
337        .ok_or_else(|| anyhow::anyhow!("{what} field {key:?} must be a string"))
338}
339
340fn required_array<'a>(value: &'a Value, key: &str, what: &str) -> Result<&'a [Value]> {
341    value
342        .get(key)
343        .and_then(Value::as_array)
344        .map(Vec::as_slice)
345        .ok_or_else(|| anyhow::anyhow!("{what} field {key:?} must be an array"))
346}
347
348/// Serialize the restricted DID-document value as RFC 8785-compatible JSON.
349///
350/// These documents contain only objects, arrays, strings, booleans, and null.
351/// Rejecting numbers avoids silently implementing only part of JCS numeric
352/// normalization if the document profile grows later.
353fn canonical_json(value: &Value) -> Result<Vec<u8>> {
354    let mut output = Vec::new();
355    write_canonical_json(value, &mut output)?;
356    Ok(output)
357}
358
359fn write_canonical_json(value: &Value, output: &mut Vec<u8>) -> Result<()> {
360    match value {
361        Value::Null => output.extend_from_slice(b"null"),
362        Value::Bool(true) => output.extend_from_slice(b"true"),
363        Value::Bool(false) => output.extend_from_slice(b"false"),
364        Value::Number(_) => bail!("hosted DID document canonical JSON does not permit numbers"),
365        Value::String(string) => {
366            serde_json::to_writer(&mut *output, string)
367                .context("failed to serialize hosted DID document string")?;
368        }
369        Value::Array(items) => {
370            output.push(b'[');
371            for (index, item) in items.iter().enumerate() {
372                if index != 0 {
373                    output.push(b',');
374                }
375                write_canonical_json(item, output)?;
376            }
377            output.push(b']');
378        }
379        Value::Object(object) => write_canonical_object(object, output)?,
380    }
381    Ok(())
382}
383
384fn write_canonical_object(object: &Map<String, Value>, output: &mut Vec<u8>) -> Result<()> {
385    output.push(b'{');
386    let mut entries = object.iter().collect::<Vec<_>>();
387    entries.sort_unstable_by_key(|(key, _)| *key);
388    for (index, (key, value)) in entries.into_iter().enumerate() {
389        if index != 0 {
390            output.push(b',');
391        }
392        serde_json::to_writer(&mut *output, key)
393            .context("failed to serialize hosted DID document key")?;
394        output.push(b':');
395        write_canonical_json(value, output)?;
396    }
397    output.push(b'}');
398    Ok(())
399}
400
401#[cfg(test)]
402mod tests {
403    #![allow(clippy::expect_used, clippy::unwrap_used)]
404
405    use p256::ecdsa::SigningKey;
406    use rand::rngs::OsRng;
407    use sha2::{Digest, Sha256};
408
409    use super::*;
410
411    fn artifact() -> SealedHostedDidDocument {
412        let name = AllocatedAccountName::new("alice", "did:web:alice.acct.example.com").unwrap();
413        let key = SigningKey::random(&mut OsRng);
414        SealedHostedDidDocument::seal(&name, key.verifying_key(), "https://pds.example.com")
415            .unwrap()
416    }
417
418    #[test]
419    fn account_document_is_exact_atproto_profile_and_roundtrips() {
420        let artifact = artifact();
421        let document: Value = serde_json::from_slice(artifact.as_bytes()).unwrap();
422        assert_eq!(document["id"], "did:web:alice.acct.example.com");
423        assert_eq!(
424            document["alsoKnownAs"],
425            json!(["at://alice.acct.example.com"])
426        );
427        assert_eq!(document["verificationMethod"].as_array().unwrap().len(), 1);
428        assert_eq!(document["verificationMethod"][0]["type"], "Multikey");
429        assert_eq!(document["service"].as_array().unwrap().len(), 2);
430        assert_eq!(document["service"][0]["type"], "AtprotoPersonalDataServer");
431        assert_eq!(document["service"][1]["type"], "DidOperationLog");
432
433        let parsed = SealedHostedDidDocument::from_canonical_json(artifact.as_bytes()).unwrap();
434        assert_eq!(parsed, artifact);
435        assert_eq!(parsed.cid(), Cid::from_raw(parsed.as_bytes()));
436    }
437
438    #[test]
439    fn canonical_bytes_are_stable() {
440        let name = AllocatedAccountName::new("alice", "did:web:alice.acct.example.com").unwrap();
441        let key = SigningKey::from_slice(&[7; 32]).unwrap();
442        let artifact =
443            SealedHostedDidDocument::seal(&name, key.verifying_key(), "https://pds.example.com")
444                .unwrap();
445        let digest = hex::encode(Sha256::digest(artifact.as_bytes()));
446        assert_eq!(
447            digest,
448            "f619b0958da09951c69b11f935f4077adf35cf7a6d84f003962955941e058ba5"
449        );
450    }
451
452    #[test]
453    fn account_document_rejects_host_capsule_alias_and_noncanonical_bytes() {
454        let artifact = artifact();
455        let mut document: Value = serde_json::from_slice(artifact.as_bytes()).unwrap();
456        document["alsoKnownAs"] = json!(["did:at9p:bafk-host-capsule"]);
457        let tampered = canonical_json(&document).unwrap();
458        let error = SealedHostedDidDocument::from_canonical_json(&tampered).unwrap_err();
459        assert!(error.to_string().contains("at://"), "{error:#}");
460
461        let pretty = serde_json::to_vec_pretty(&document).unwrap();
462        let error = SealedHostedDidDocument::from_canonical_json(&pretty).unwrap_err();
463        assert!(error.to_string().contains("canonical"), "{error:#}");
464    }
465
466    #[test]
467    fn account_document_rejects_wrong_key_shape_and_pds_endpoint() {
468        let artifact = artifact();
469        let mut document: Value = serde_json::from_slice(artifact.as_bytes()).unwrap();
470        document["verificationMethod"][0]["publicKeyMultibase"] = json!("zBadKey");
471        let tampered = canonical_json(&document).unwrap();
472        assert!(SealedHostedDidDocument::from_canonical_json(&tampered).is_err());
473
474        let name = AllocatedAccountName::new("alice", "did:web:alice.acct.example.com").unwrap();
475        let key = SigningKey::random(&mut OsRng);
476        for endpoint in [
477            "http://pds.example.com",
478            "https://pds.example.com/oauth",
479            "https://user@pds.example.com",
480        ] {
481            assert!(
482                SealedHostedDidDocument::seal(&name, key.verifying_key(), endpoint).is_err(),
483                "{endpoint} must be rejected"
484            );
485        }
486    }
487}