1use anyhow::{anyhow, bail, ensure, Context, Result};
54use async_trait::async_trait;
55use serde_json::Value;
56use sha2::{Digest, Sha256};
57use url::Url;
58
59use crate::did_web::{parse_did_document_no_duplicates, DidDocFetcher};
60
61const MAX_DID_DOC_BYTES: usize = 1024 * 1024;
65
66const MAX_PLC_AUDIT_BYTES: usize = 8 * 1024 * 1024;
68
69const MAX_PLC_OPERATION_BYTES: usize = 7_500;
71
72const MAX_CACHE_ENTRIES: usize = 256;
75
76struct CachedDoc {
77 doc: Value,
78 fetched_at: std::time::Instant,
79}
80
81async fn read_capped(resp: reqwest::Response, max: usize) -> Result<Vec<u8>> {
83 use futures::StreamExt;
84
85 if let Some(len) = resp.content_length() {
86 if len > max as u64 {
87 bail!("DID document exceeds {max}-byte cap (Content-Length {len})");
88 }
89 }
90
91 let mut body = Vec::new();
92 let mut stream = resp.bytes_stream();
93 while let Some(chunk) = stream.next().await {
94 let chunk = chunk?;
95 if body.len() + chunk.len() > max {
96 bail!("DID document exceeds {max}-byte cap");
97 }
98 body.extend_from_slice(&chunk);
99 }
100 Ok(body)
101}
102
103fn evict_for_insert(
106 cache: &mut std::collections::HashMap<String, CachedDoc>,
107 ttl: std::time::Duration,
108) {
109 cache.retain(|_, entry| entry.fetched_at.elapsed() < ttl);
110 while cache.len() >= MAX_CACHE_ENTRIES {
111 let Some(oldest) = cache
112 .iter()
113 .min_by_key(|(_, entry)| entry.fetched_at)
114 .map(|(url, _)| url.clone())
115 else {
116 break;
117 };
118 cache.remove(&oldest);
119 }
120}
121
122pub const DID_PLC_PREFIX: &str = "did:plc:";
126
127const PLC_MSI_LEN: usize = 24;
130
131pub fn is_did_plc(did: &str) -> bool {
133 did.starts_with(DID_PLC_PREFIX)
134}
135
136fn plc_msi(did: &str) -> Result<&str> {
145 let did = did.split(['#', '?']).next().unwrap_or(did);
146 let msi = did
147 .strip_prefix(DID_PLC_PREFIX)
148 .ok_or_else(|| anyhow!("not a did:plc identifier: {did}"))?;
149 if msi.len() != PLC_MSI_LEN {
150 bail!(
151 "did:plc method-specific identifier must be {PLC_MSI_LEN} characters (got {}): {did}",
152 msi.len()
153 );
154 }
155 if !msi.bytes().all(|b| matches!(b, b'a'..=b'z' | b'2'..=b'7')) {
156 bail!("did:plc method-specific identifier is not lowercase base32 (`a-z2-7`): {did}");
157 }
158 Ok(msi)
159}
160
161#[derive(Clone, Debug)]
174pub struct PlcResolverConfig {
175 base_url: Url,
176 ttl: std::time::Duration,
177}
178
179impl PlcResolverConfig {
180 pub fn new(base_url: Url, ttl: std::time::Duration) -> Result<Self> {
182 validate_plc_base_url(&base_url)?;
183 Ok(Self { base_url, ttl })
184 }
185
186 pub fn base_url(&self) -> &Url {
188 &self.base_url
189 }
190
191 pub fn ttl(&self) -> std::time::Duration {
193 self.ttl
194 }
195}
196
197fn validate_plc_base_url(base_url: &Url) -> Result<()> {
199 if base_url.scheme() != "https" {
200 bail!("PLC directory base URL must use https:// (got {base_url})");
201 }
202 if base_url.host().is_none() {
203 bail!("PLC directory base URL must include a host: {base_url}");
204 }
205 if !base_url.username().is_empty() || base_url.password().is_some() {
206 bail!("PLC directory base URL must not carry credentials: {base_url}");
207 }
208 if base_url.query().is_some() || base_url.fragment().is_some() {
209 bail!("PLC directory base URL must not carry a query or fragment: {base_url}");
210 }
211 Ok(())
212}
213
214pub fn did_plc_url(did: &str, base_url: &Url) -> Result<String> {
227 validate_plc_base_url(base_url)?;
228 plc_msi(did)?;
229 let did = did.split(['#', '?']).next().unwrap_or(did);
230
231 let mut url = base_url.clone();
241 let trimmed = url.path().trim_end_matches('/');
242 url.set_path(&format!("{trimmed}/{did}"));
243
244 if url.origin() != base_url.origin() {
248 bail!("derived did:plc URL {url} escaped the configured origin {base_url} (fail-closed)");
249 }
250 Ok(url.into())
251}
252
253pub fn validate_plc_document(did: &str, doc: &Value) -> Result<()> {
271 let asked = did.split(['#', '?']).next().unwrap_or(did);
272 let object = doc.as_object().ok_or_else(|| {
273 anyhow!("did:plc document for {asked} is not a JSON object (fail-closed)")
274 })?;
275 let id = object
276 .get("id")
277 .and_then(Value::as_str)
278 .ok_or_else(|| anyhow!("did:plc document for {asked} has no string `id` (fail-closed)"))?;
279 if id != asked {
280 bail!(
281 "did:plc document id mismatch: asked {asked}, document claims {id} — substitution oracle (fail-closed)"
282 );
283 }
284
285 if let Some(also_known_as) = object.get("alsoKnownAs") {
286 validate_string_collection(asked, "alsoKnownAs", also_known_as)?;
287 }
288 if let Some(verification_methods) = object.get("verificationMethod") {
289 validate_verification_methods(asked, verification_methods)?;
290 }
291 if let Some(services) = object.get("service") {
292 validate_services(asked, services)?;
293 }
294 Ok(())
295}
296
297fn validate_string_collection(did: &str, member: &str, value: &Value) -> Result<()> {
298 let values = value.as_array().ok_or_else(|| {
299 anyhow!("did:plc document for {did} has non-array `{member}` (fail-closed)")
300 })?;
301 let mut seen = std::collections::HashSet::new();
302 for value in values {
303 let value = value
304 .as_str()
305 .filter(|value| !value.is_empty())
306 .ok_or_else(|| {
307 anyhow!("did:plc document for {did} has invalid `{member}` member (fail-closed)")
308 })?;
309 if !is_absolute_uri(value) {
313 bail!("did:plc document for {did} has `{member}` member that is not a valid URI: `{value}` (fail-closed)");
314 }
315 if !seen.insert(value) {
316 bail!("did:plc document for {did} has duplicate `{member}` member `{value}` (fail-closed)");
317 }
318 }
319 Ok(())
320}
321
322fn is_did(s: &str) -> bool {
338 let Some(rest) = s.strip_prefix("did:") else {
339 return false;
340 };
341 let Some((method, msi)) = rest.split_once(':') else {
342 return false;
343 };
344 !method.is_empty()
345 && method
346 .bytes()
347 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
348 && !msi.is_empty()
349 && msi
350 .bytes()
351 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_' | b':' | b'%'))
352}
353
354fn is_did_url(s: &str) -> bool {
359 let Some(rest) = s.strip_prefix("did:") else {
360 return false;
361 };
362 let authority = rest.split(['/', '?', '#']).next().unwrap_or(rest);
363 let Some((method, msi)) = authority.split_once(':') else {
364 return false;
365 };
366 !method.is_empty()
367 && method
368 .bytes()
369 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
370 && !msi.is_empty()
371 && msi
372 .bytes()
373 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_' | b':' | b'%'))
374}
375
376fn is_absolute_uri(s: &str) -> bool {
381 let Some(colon) = s.find(':') else {
382 return false;
383 };
384 let first_separator = s.find(['/', '?', '#']).unwrap_or(usize::MAX);
385 if colon >= first_separator {
386 return false;
387 }
388 let scheme = &s[..colon];
389 !scheme.is_empty()
390 && scheme
391 .bytes()
392 .next()
393 .is_some_and(|b| b.is_ascii_alphabetic())
394 && scheme
395 .bytes()
396 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.'))
397}
398
399fn resolve_did_url(subject: &str, reference: &str) -> Result<String> {
402 if is_absolute_uri(reference) {
403 return Ok(reference.to_owned());
404 }
405 if reference.is_empty() {
406 bail!("empty DID-URL reference");
407 }
408 let base = subject.split(['#', '?']).next().unwrap_or(subject);
409 if reference.starts_with('#') || reference.starts_with('?') || reference.starts_with('/') {
410 Ok(format!("{base}{reference}"))
411 } else {
412 Ok(format!("{base}/{reference}"))
414 }
415}
416
417fn canonical_member_id(did: &str, id: &str, member: &str) -> Result<String> {
421 if is_absolute_uri(id) {
422 if !is_did_url(id) {
423 bail!("did:plc document for {did} has `{member}` with non-DID-URL id `{id}` (fail-closed)");
424 }
425 Ok(id.to_owned())
426 } else {
427 resolve_did_url(did, id)
428 }
429}
430
431const KNOWN_MATERIAL_FIELDS: &[&str] = &[
438 "publicKeyJwk",
439 "publicKeyMultibase",
440 "publicKeyBase58",
441 "publicKeyHex",
442 "publicKeyPem",
443 "publicKeyPgp",
444];
445
446fn read_multicodec(bytes: &[u8]) -> Option<(u64, &[u8])> {
449 let mut value = 0u64;
450 let mut shift = 0u32;
451 for (i, &b) in bytes.iter().enumerate() {
452 value |= ((b & 0x7f) as u64) << shift;
453 if b & 0x80 == 0 {
454 return Some((value, &bytes[i + 1..]));
455 }
456 shift = shift.checked_add(7)?;
457 if shift >= 64 {
458 return None;
459 }
460 }
461 None
462}
463
464mod multicodec {
466 pub const ED25519_PUB: u64 = 0xed;
468 pub const SECP256K1_PUB: u64 = 0xe7;
470 pub const P256_PUB: u64 = 0x1200;
472 pub const ML_DSA_65_PUB: u64 = 0x1211;
474}
475
476const ML_DSA_65_PUB_KEY_LEN: usize = 1952;
478
479const MIN_UNKNOWN_MULTIKEY_PAYLOAD: usize = 16;
485
486fn is_valid_multikey(s: &str) -> bool {
492 let Some(body) = s.strip_prefix('z') else {
493 return false;
494 };
495 let Ok(decoded) = bs58::decode(body).into_vec() else {
496 return false;
497 };
498 let Some((codec, payload)) = read_multicodec(&decoded) else {
499 return false;
500 };
501 match codec {
502 multicodec::ED25519_PUB => payload.len() == 32,
503 multicodec::SECP256K1_PUB | multicodec::P256_PUB => payload.len() == 33,
504 multicodec::ML_DSA_65_PUB => payload.len() == ML_DSA_65_PUB_KEY_LEN,
505 _ => payload.len() >= MIN_UNKNOWN_MULTIKEY_PAYLOAD,
506 }
507}
508
509fn is_valid_jwk(jwk: &serde_json::Map<String, Value>) -> bool {
513 let Some(kty) = jwk.get("kty").and_then(Value::as_str) else {
514 return false;
515 };
516 let has_str = |k: &str| {
517 jwk.get(k)
518 .and_then(Value::as_str)
519 .is_some_and(|v| !v.is_empty())
520 };
521 match kty {
522 "EC" | "OKP" => has_str("crv") && has_str("x"),
523 "RSA" => has_str("n") && has_str("e"),
524 "oct" => has_str("k"),
525 _ => false,
526 }
527}
528
529fn required_nonempty_string<'a>(
530 did: &str,
531 member: &str,
532 object: &'a serde_json::Map<String, Value>,
533 field: &str,
534) -> Result<&'a str> {
535 object
536 .get(field)
537 .and_then(Value::as_str)
538 .filter(|value| !value.is_empty())
539 .ok_or_else(|| {
540 anyhow!(
541 "did:plc document for {did} has `{member}` member without non-empty string `{field}` (fail-closed)"
542 )
543 })
544}
545
546fn validate_verification_material(
550 did: &str,
551 id: &str,
552 method: &serde_json::Map<String, Value>,
553 field: &str,
554) -> Result<()> {
555 match field {
556 "publicKeyMultibase" => {
557 let v = method
558 .get(field)
559 .and_then(Value::as_str)
560 .filter(|s| !s.is_empty());
561 if !v.is_some_and(is_valid_multikey) {
562 bail!("did:plc document for {did} has malformed Multikey `publicKeyMultibase` in `{id}` (fail-closed)");
563 }
564 }
565 "publicKeyJwk" => {
566 let Some(v) = method.get(field).and_then(Value::as_object) else {
567 bail!("did:plc document for {did} has non-object `publicKeyJwk` in `{id}` (fail-closed)");
568 };
569 if !is_valid_jwk(v) {
570 bail!("did:plc document for {did} has malformed `publicKeyJwk` in `{id}` (fail-closed)");
571 }
572 }
573 "publicKeyBase58" | "publicKeyHex" | "publicKeyPem" | "publicKeyPgp" => {
574 if method
575 .get(field)
576 .and_then(Value::as_str)
577 .is_some_and(|v| !v.is_empty())
578 {
579 return Ok(());
580 }
581 bail!("did:plc document for {did} has empty `{field}` in `{id}` (fail-closed)");
582 }
583 _ => {}
584 }
585 Ok(())
586}
587
588fn validate_verification_methods(did: &str, value: &Value) -> Result<()> {
589 let methods = value.as_array().ok_or_else(|| {
590 anyhow!("did:plc document for {did} has non-array `verificationMethod` (fail-closed)")
591 })?;
592 let mut ids: std::collections::HashSet<String> = std::collections::HashSet::new();
593 for value in methods {
594 let method = value.as_object().ok_or_else(|| {
595 anyhow!("did:plc document for {did} has non-object `verificationMethod` member (fail-closed)")
596 })?;
597 let id = required_nonempty_string(did, "verificationMethod", method, "id")?;
598 required_nonempty_string(did, "verificationMethod", method, "type")?;
599 let controller = required_nonempty_string(did, "verificationMethod", method, "controller")?;
600 if !is_did(controller) {
601 bail!("did:plc document for {did} has `verificationMethod` `{id}` with non-DID controller `{controller}` (fail-closed)");
602 }
603
604 let present: Vec<&str> = KNOWN_MATERIAL_FIELDS
609 .iter()
610 .copied()
611 .filter(|f| method.contains_key(*f))
612 .collect();
613 if present.len() > 1 {
614 bail!("did:plc document for {did} has `verificationMethod` `{id}` with multiple verification-material properties (fail-closed)");
615 }
616 let Some(field) = present.into_iter().next() else {
617 bail!("did:plc document for {did} has `verificationMethod` `{id}` without a recognized verification-material property (fail-closed)");
618 };
619 validate_verification_material(did, id, method, field)?;
620
621 let canonical = canonical_member_id(did, id, "verificationMethod")?;
625 if !ids.insert(canonical) {
626 bail!("did:plc document for {did} has duplicate `verificationMethod` id `{id}` (fail-closed)");
627 }
628 }
629 Ok(())
630}
631
632fn is_valid_service_endpoint(value: &Value) -> bool {
633 match value {
634 Value::String(value) => !value.is_empty() && is_absolute_uri(value),
636 Value::Object(value) => !value.is_empty(),
637 Value::Array(values) => !values.is_empty() && values.iter().all(is_valid_service_endpoint),
638 _ => false,
639 }
640}
641
642fn validate_services(did: &str, value: &Value) -> Result<()> {
643 let services = value.as_array().ok_or_else(|| {
644 anyhow!("did:plc document for {did} has non-array `service` (fail-closed)")
645 })?;
646 let mut ids: std::collections::HashSet<String> = std::collections::HashSet::new();
647 for value in services {
648 let service = value.as_object().ok_or_else(|| {
649 anyhow!("did:plc document for {did} has non-object `service` member (fail-closed)")
650 })?;
651 let id = required_nonempty_string(did, "service", service, "id")?;
652 required_nonempty_string(did, "service", service, "type")?;
653 if !service
654 .get("serviceEndpoint")
655 .is_some_and(is_valid_service_endpoint)
656 {
657 bail!("did:plc document for {did} has `service` member without valid `serviceEndpoint` (fail-closed)");
658 }
659 let canonical = canonical_member_id(did, id, "service")?;
660 if !ids.insert(canonical) {
661 bail!("did:plc document for {did} has duplicate `service` id `{id}` (fail-closed)");
662 }
663 }
664 Ok(())
665}
666
667fn did_plc_audit_url(did: &str, base_url: &Url) -> Result<String> {
671 Ok(format!("{}/log/audit", did_plc_url(did, base_url)?))
672}
673
674fn plc_dag_cbor(value: &Value) -> Result<Vec<u8>> {
677 fn write_uint(out: &mut Vec<u8>, major: u8, value: u64) {
678 let prefix = major << 5;
679 if value < 24 {
680 out.push(prefix | value as u8);
681 } else if value <= u8::MAX as u64 {
682 out.extend_from_slice(&[prefix | 24, value as u8]);
683 } else if value <= u16::MAX as u64 {
684 out.push(prefix | 25);
685 out.extend_from_slice(&(value as u16).to_be_bytes());
686 } else if value <= u32::MAX as u64 {
687 out.push(prefix | 26);
688 out.extend_from_slice(&(value as u32).to_be_bytes());
689 } else {
690 out.push(prefix | 27);
691 out.extend_from_slice(&value.to_be_bytes());
692 }
693 }
694
695 fn encode(value: &Value, out: &mut Vec<u8>, depth: usize) -> Result<()> {
696 ensure!(depth <= 128, "PLC operation exceeds DAG-CBOR nesting limit");
697 match value {
698 Value::Null => out.push(0xf6),
699 Value::Bool(false) => out.push(0xf4),
700 Value::Bool(true) => out.push(0xf5),
701 Value::String(text) => {
702 write_uint(out, 3, text.len() as u64);
703 out.extend_from_slice(text.as_bytes());
704 }
705 Value::Array(values) => {
706 write_uint(out, 4, values.len() as u64);
707 for value in values {
708 encode(value, out, depth + 1)?;
709 }
710 }
711 Value::Object(object) => {
712 let mut entries: Vec<_> = object.iter().collect();
713 entries.sort_unstable_by(|(left, _), (right, _)| {
716 left.len()
717 .cmp(&right.len())
718 .then_with(|| left.as_bytes().cmp(right.as_bytes()))
719 });
720 write_uint(out, 5, entries.len() as u64);
721 for (key, value) in entries {
722 write_uint(out, 3, key.len() as u64);
723 out.extend_from_slice(key.as_bytes());
724 encode(value, out, depth + 1)?;
725 }
726 }
727 Value::Number(_) => bail!("PLC operations cannot contain JSON numbers"),
728 }
729 Ok(())
730 }
731
732 let mut encoded = Vec::new();
733 encode(value, &mut encoded, 0)?;
734 ensure!(
735 encoded.len() <= MAX_PLC_OPERATION_BYTES,
736 "PLC operation exceeds {MAX_PLC_OPERATION_BYTES}-byte DAG-CBOR limit"
737 );
738 Ok(encoded)
739}
740
741fn operation_cid(operation: &Value) -> Result<String> {
742 let digest = Sha256::digest(plc_dag_cbor(operation)?);
743 let mut bytes = Vec::with_capacity(36);
744 bytes.extend_from_slice(&[0x01, 0x71, 0x12, 0x20]);
746 bytes.extend_from_slice(&digest);
747 Ok(format!(
748 "b{}",
749 data_encoding::BASE32_NOPAD
750 .encode(&bytes)
751 .to_ascii_lowercase()
752 ))
753}
754
755fn did_from_genesis(operation: &Value) -> Result<String> {
756 let digest = Sha256::digest(plc_dag_cbor(operation)?);
757 let encoded = data_encoding::BASE32_NOPAD
758 .encode(&digest)
759 .to_ascii_lowercase();
760 Ok(format!("did:plc:{}", &encoded[..PLC_MSI_LEN]))
761}
762
763fn operation_prev(operation: &Value) -> Result<Option<&str>> {
764 let object = operation
765 .as_object()
766 .ok_or_else(|| anyhow!("PLC audit operation is not an object"))?;
767 match object.get("prev") {
768 Some(Value::Null) => Ok(None),
769 Some(Value::String(prev)) if !prev.is_empty() => Ok(Some(prev)),
770 Some(_) => bail!("PLC operation has invalid `prev`"),
771 None => bail!("PLC operation omits required `prev`"),
772 }
773}
774
775fn operation_rotation_keys(operation: &Value) -> Result<Vec<&str>> {
776 let object = operation
777 .as_object()
778 .ok_or_else(|| anyhow!("PLC audit operation is not an object"))?;
779 match object.get("type").and_then(Value::as_str) {
780 Some("plc_operation") => {
781 let keys = object
782 .get("rotationKeys")
783 .and_then(Value::as_array)
784 .ok_or_else(|| anyhow!("PLC operation omits `rotationKeys`"))?;
785 ensure!(
786 (1..=5).contains(&keys.len()),
787 "PLC operation must carry 1..=5 rotation keys"
788 );
789 let mut seen = std::collections::HashSet::new();
790 keys.iter()
791 .map(|key| {
792 let key = key
793 .as_str()
794 .filter(|key| !key.is_empty())
795 .ok_or_else(|| anyhow!("PLC operation has invalid rotation key"))?;
796 ensure!(seen.insert(key), "PLC operation has duplicate rotation key");
797 Ok(key)
798 })
799 .collect()
800 }
801 Some("create") => {
802 let key = object
803 .get("recoveryKey")
804 .and_then(Value::as_str)
805 .filter(|key| !key.is_empty())
806 .ok_or_else(|| anyhow!("legacy PLC create operation omits `recoveryKey`"))?;
807 Ok(vec![key])
808 }
809 Some("plc_tombstone") => bail!("a PLC tombstone carries no successor rotation keys"),
810 Some(other) => bail!("unsupported PLC operation type `{other}`"),
811 None => bail!("PLC operation omits string `type`"),
812 }
813}
814
815fn verify_operation_signature(operation: &Value, rotation_keys: &[&str]) -> Result<()> {
816 use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
817 use k256::ecdsa::signature::Verifier as _;
818
819 let object = operation
820 .as_object()
821 .ok_or_else(|| anyhow!("PLC audit operation is not an object"))?;
822 let signature_text = object
823 .get("sig")
824 .and_then(Value::as_str)
825 .ok_or_else(|| anyhow!("PLC operation omits string `sig`"))?;
826 let signature_bytes = URL_SAFE_NO_PAD
827 .decode(signature_text)
828 .context("PLC operation signature is not canonical base64url")?;
829 ensure!(
830 signature_bytes.len() == 64 && URL_SAFE_NO_PAD.encode(&signature_bytes) == signature_text,
831 "PLC operation signature is not canonical 64-byte base64url"
832 );
833
834 let mut unsigned = operation.clone();
835 let unsigned_object = unsigned
836 .as_object_mut()
837 .ok_or_else(|| anyhow!("PLC audit operation is not an object"))?;
838 unsigned_object.remove("sig");
839 let message = plc_dag_cbor(&unsigned)?;
840
841 for did_key in rotation_keys {
842 let Some(multibase) = did_key.strip_prefix("did:key:z") else {
843 continue;
844 };
845 let Ok(decoded) = bs58::decode(multibase).into_vec() else {
846 continue;
847 };
848 let Some((codec, key_bytes)) = read_multicodec(&decoded) else {
849 continue;
850 };
851 let verified = match codec {
852 multicodec::SECP256K1_PUB => {
853 if !decoded.starts_with(&[0xe7, 0x01]) {
854 continue;
855 }
856 let Ok(key) = k256::ecdsa::VerifyingKey::from_sec1_bytes(key_bytes) else {
857 continue;
858 };
859 let Ok(signature) = k256::ecdsa::Signature::from_slice(&signature_bytes) else {
860 continue;
861 };
862 if signature.normalize_s().is_some() {
863 continue;
864 }
865 key.verify(&message, &signature).is_ok()
866 }
867 multicodec::P256_PUB => {
868 if !decoded.starts_with(&[0x80, 0x24]) {
869 continue;
870 }
871 let Ok(key) = p256::ecdsa::VerifyingKey::from_sec1_bytes(key_bytes) else {
872 continue;
873 };
874 let Ok(signature) = p256::ecdsa::Signature::from_slice(&signature_bytes) else {
875 continue;
876 };
877 if signature.normalize_s().is_some() {
878 continue;
879 }
880 key.verify(&message, &signature).is_ok()
881 }
882 _ => false,
883 };
884 if verified {
885 return Ok(());
886 }
887 }
888 bail!("PLC operation signature did not verify under any authorized rotation key")
889}
890
891fn document_from_operation(did: &str, operation: &Value) -> Result<Value> {
892 let object = operation
893 .as_object()
894 .ok_or_else(|| anyhow!("PLC audit head operation is not an object"))?;
895 let op_type = object
896 .get("type")
897 .and_then(Value::as_str)
898 .ok_or_else(|| anyhow!("PLC audit head omits string `type`"))?;
899 if op_type == "plc_tombstone" {
900 bail!("did:plc identity {did} is deactivated");
901 }
902
903 let (verification_methods, also_known_as, services) = if op_type == "create" {
904 let signing_key = object
905 .get("signingKey")
906 .and_then(Value::as_str)
907 .ok_or_else(|| anyhow!("legacy PLC create omits `signingKey`"))?;
908 let handle = object
909 .get("handle")
910 .and_then(Value::as_str)
911 .ok_or_else(|| anyhow!("legacy PLC create omits `handle`"))?;
912 let service = object
913 .get("service")
914 .and_then(Value::as_str)
915 .ok_or_else(|| anyhow!("legacy PLC create omits `service`"))?;
916 (
917 serde_json::json!({ "atproto": signing_key }),
918 serde_json::json!([format!("at://{handle}")]),
919 serde_json::json!({
920 "atproto_pds": {
921 "type": "AtprotoPersonalDataServer",
922 "endpoint": service
923 }
924 }),
925 )
926 } else if op_type == "plc_operation" {
927 (
928 object
929 .get("verificationMethods")
930 .cloned()
931 .ok_or_else(|| anyhow!("PLC operation omits `verificationMethods`"))?,
932 object
933 .get("alsoKnownAs")
934 .cloned()
935 .ok_or_else(|| anyhow!("PLC operation omits `alsoKnownAs`"))?,
936 object
937 .get("services")
938 .cloned()
939 .ok_or_else(|| anyhow!("PLC operation omits `services`"))?,
940 )
941 } else {
942 bail!("unsupported PLC audit head operation type `{op_type}`");
943 };
944
945 let methods = verification_methods
946 .as_object()
947 .ok_or_else(|| anyhow!("PLC `verificationMethods` is not an object"))?
948 .iter()
949 .map(|(name, key)| {
950 ensure!(
951 !name.is_empty() && !name.starts_with('#'),
952 "invalid PLC verification-method name"
953 );
954 let multibase = key
955 .as_str()
956 .and_then(|key| key.strip_prefix("did:key:"))
957 .ok_or_else(|| anyhow!("PLC verification method `{name}` is not a did:key"))?;
958 Ok(serde_json::json!({
959 "id": format!("{did}#{name}"),
960 "type": "Multikey",
961 "controller": did,
962 "publicKeyMultibase": multibase,
963 }))
964 })
965 .collect::<Result<Vec<_>>>()?;
966
967 let rendered_services = services
968 .as_object()
969 .ok_or_else(|| anyhow!("PLC `services` is not an object"))?
970 .iter()
971 .map(|(name, service)| {
972 ensure!(
973 !name.is_empty() && !name.starts_with('#'),
974 "invalid PLC service name"
975 );
976 let service = service
977 .as_object()
978 .ok_or_else(|| anyhow!("PLC service `{name}` is not an object"))?;
979 let service_type = service
980 .get("type")
981 .and_then(Value::as_str)
982 .ok_or_else(|| anyhow!("PLC service `{name}` omits string `type`"))?;
983 let endpoint = service
984 .get("endpoint")
985 .and_then(Value::as_str)
986 .ok_or_else(|| anyhow!("PLC service `{name}` omits string `endpoint`"))?;
987 Ok(serde_json::json!({
988 "id": format!("#{name}"),
989 "type": service_type,
990 "serviceEndpoint": endpoint,
991 }))
992 })
993 .collect::<Result<Vec<_>>>()?;
994
995 Ok(serde_json::json!({
996 "id": did,
997 "alsoKnownAs": also_known_as,
998 "verificationMethod": methods,
999 "service": rendered_services,
1000 }))
1001}
1002
1003fn normalized_document_members(
1004 did: &str,
1005 member: &str,
1006 value: Option<&Value>,
1007) -> Result<std::collections::BTreeMap<String, Value>> {
1008 let values = value
1009 .and_then(Value::as_array)
1010 .ok_or_else(|| anyhow!("did:plc document omits array `{member}`"))?;
1011 values
1012 .iter()
1013 .map(|value| {
1014 let mut object = value
1015 .as_object()
1016 .cloned()
1017 .ok_or_else(|| anyhow!("did:plc document has non-object `{member}` entry"))?;
1018 let id = object
1019 .remove("id")
1020 .and_then(|id| id.as_str().map(str::to_owned))
1021 .ok_or_else(|| anyhow!("did:plc document `{member}` entry omits string `id`"))?;
1022 Ok((
1023 canonical_member_id(did, &id, member)?,
1024 Value::Object(object),
1025 ))
1026 })
1027 .collect()
1028}
1029
1030pub fn verify_plc_audit(did: &str, audit: &Value, current_document: &Value) -> Result<()> {
1033 plc_msi(did)?;
1034 validate_plc_document(did, current_document)?;
1035 let entries = audit
1036 .as_array()
1037 .filter(|entries| !entries.is_empty())
1038 .ok_or_else(|| anyhow!("PLC audit log for {did} is empty or not an array"))?;
1039 let mut cid_to_index: std::collections::HashMap<String, usize> =
1040 std::collections::HashMap::new();
1041 let mut active = Vec::new();
1042 let mut genesis_count = 0usize;
1043
1044 for (index, entry) in entries.iter().enumerate() {
1045 let entry = entry
1046 .as_object()
1047 .ok_or_else(|| anyhow!("PLC audit entry {index} is not an object"))?;
1048 ensure!(
1049 entry.get("did").and_then(Value::as_str) == Some(did),
1050 "PLC audit entry {index} is for a different DID"
1051 );
1052 let operation = entry
1053 .get("operation")
1054 .ok_or_else(|| anyhow!("PLC audit entry {index} omits `operation`"))?;
1055 if operation.get("type").and_then(Value::as_str) != Some("plc_tombstone") {
1056 operation_rotation_keys(operation)?;
1059 }
1060 let cid = entry
1061 .get("cid")
1062 .and_then(Value::as_str)
1063 .ok_or_else(|| anyhow!("PLC audit entry {index} omits string `cid`"))?;
1064 ensure!(
1065 operation_cid(operation)? == cid,
1066 "PLC audit entry {index} CID does not match its signed operation"
1067 );
1068
1069 let prev = operation_prev(operation)?;
1070 let authorized_keys = if let Some(prev) = prev {
1071 let parent_index = *cid_to_index.get(prev).ok_or_else(|| {
1072 anyhow!("PLC operation `{cid}` references unknown or future prev `{prev}`")
1073 })?;
1074 let parent = entries[parent_index]
1075 .get("operation")
1076 .ok_or_else(|| anyhow!("PLC parent entry omits operation"))?;
1077 operation_rotation_keys(parent)?
1078 } else {
1079 genesis_count += 1;
1080 ensure!(
1081 did_from_genesis(operation)? == did,
1082 "PLC genesis operation does not bind to {did}"
1083 );
1084 operation_rotation_keys(operation)?
1085 };
1086 verify_operation_signature(operation, &authorized_keys).with_context(|| {
1087 format!("PLC audit entry {index} (`{cid}`) signature verification failed")
1088 })?;
1089 ensure!(
1090 cid_to_index.insert(cid.to_owned(), index).is_none(),
1091 "PLC audit contains duplicate operation CID `{cid}`"
1092 );
1093
1094 let nullified = entry
1095 .get("nullified")
1096 .and_then(Value::as_bool)
1097 .ok_or_else(|| anyhow!("PLC audit entry {index} omits boolean `nullified`"))?;
1098 if !nullified {
1099 active.push((cid, operation));
1100 }
1101 }
1102
1103 ensure!(
1104 genesis_count == 1,
1105 "PLC audit must contain exactly one genesis operation"
1106 );
1107 ensure!(
1108 !active.is_empty(),
1109 "PLC audit has no active operation chain"
1110 );
1111 ensure!(
1112 operation_prev(active[0].1)?.is_none(),
1113 "PLC active chain does not start at genesis"
1114 );
1115 for pair in active.windows(2) {
1116 ensure!(
1117 operation_prev(pair[1].1)? == Some(pair[0].0),
1118 "PLC active operation chain has a broken `prev` link"
1119 );
1120 }
1121
1122 let active_head = active
1123 .last()
1124 .ok_or_else(|| anyhow!("PLC audit has no active operation chain"))?;
1125 let verified_document = document_from_operation(did, active_head.1)?;
1126 ensure!(
1127 current_document.get("id") == verified_document.get("id"),
1128 "PLC current document `id` does not match the verified audit-log head"
1129 );
1130 ensure!(
1131 current_document.get("alsoKnownAs") == verified_document.get("alsoKnownAs"),
1132 "PLC current document `alsoKnownAs` does not match the verified audit-log head"
1133 );
1134 for member in ["verificationMethod", "service"] {
1135 ensure!(
1136 normalized_document_members(did, member, current_document.get(member))?
1137 == normalized_document_members(did, member, verified_document.get(member))?,
1138 "PLC current document `{member}` does not match the verified audit-log head"
1139 );
1140 }
1141 Ok(())
1142}
1143
1144#[async_trait]
1151pub trait PlcAuditFetcher: DidDocFetcher {
1152 async fn fetch_audit(&self, url: &str) -> Result<Value>;
1153}
1154
1155pub struct DidPlcResolver<F: PlcAuditFetcher> {
1165 fetcher: F,
1166 config: PlcResolverConfig,
1167}
1168
1169impl<F: PlcAuditFetcher> DidPlcResolver<F> {
1170 pub fn with_fetcher(fetcher: F, config: PlcResolverConfig) -> Self {
1175 Self { fetcher, config }
1176 }
1177
1178 pub fn config(&self) -> &PlcResolverConfig {
1180 &self.config
1181 }
1182
1183 pub async fn resolve_document(&self, did: &str) -> Result<Value> {
1190 let url = did_plc_url(did, self.config.base_url())?;
1191 let doc = self.fetcher.fetch(&url).await?;
1192 validate_plc_document(did, &doc)?;
1193 let audit_url = did_plc_audit_url(did, self.config.base_url())?;
1194 let audit = self.fetcher.fetch_audit(&audit_url).await?;
1195 verify_plc_audit(did, &audit, &doc)?;
1196 Ok(doc)
1197 }
1198}
1199
1200impl DidPlcResolver<HttpPlcFetcher> {
1201 pub fn new(config: PlcResolverConfig) -> Result<Self> {
1206 let fetcher = HttpPlcFetcher::new(&config)?;
1207 Ok(Self { fetcher, config })
1208 }
1209}
1210
1211pub struct HttpPlcFetcher {
1230 http: reqwest::Client,
1231 cache: parking_lot::Mutex<std::collections::HashMap<String, CachedDoc>>,
1232 ttl: std::time::Duration,
1233 allowed_origins: Vec<url::Origin>,
1234}
1235
1236impl HttpPlcFetcher {
1237 fn new(config: &PlcResolverConfig) -> Result<Self> {
1243 let http = reqwest::Client::builder()
1244 .redirect(reqwest::redirect::Policy::none())
1248 .connect_timeout(std::time::Duration::from_secs(10))
1250 .timeout(std::time::Duration::from_secs(10))
1251 .build()
1252 .map_err(|e| anyhow!("failed to build did:plc HTTPS client: {e}"))?;
1253 Ok(Self {
1254 http,
1255 cache: parking_lot::Mutex::new(std::collections::HashMap::new()),
1256 ttl: config.ttl(),
1257 allowed_origins: vec![config.base_url().origin()],
1260 })
1261 }
1262
1263 pub fn allowed_origins(&self) -> &[url::Origin] {
1266 &self.allowed_origins
1267 }
1268
1269 fn validate_fetch_url(&self, url: &str) -> Result<Url> {
1270 let parsed = Url::parse(url)
1271 .map_err(|e| anyhow!("did:plc directory URL does not parse ({url}): {e}"))?;
1272 if parsed.scheme() != "https" {
1273 bail!("did:plc directory URL must use https:// (got {url})");
1274 }
1275 if !self.allowed_origins.contains(&parsed.origin()) {
1276 bail!(
1277 "did:plc fetch refused: origin of {url} is not in the egress allowlist (fail-closed)"
1278 );
1279 }
1280 Ok(parsed)
1281 }
1282
1283 async fn fetch_json(&self, url: &str, max_bytes: usize) -> Result<Value> {
1284 {
1285 let cache = self.cache.lock();
1286 if let Some(entry) = cache.get(url) {
1287 if entry.fetched_at.elapsed() < self.ttl {
1288 return Ok(entry.doc.clone());
1289 }
1290 }
1291 }
1292
1293 let resp = self.http.get(url).send().await?;
1294 if !resp.status().is_success() {
1295 bail!(
1296 "did:plc directory returned non-success status {} for {url}",
1297 resp.status()
1298 );
1299 }
1300 let body = read_capped(resp, max_bytes).await?;
1301 let value = parse_did_document_no_duplicates(&body, url)?;
1302
1303 {
1304 let mut cache = self.cache.lock();
1305 evict_for_insert(&mut cache, self.ttl);
1306 cache.insert(
1307 url.to_owned(),
1308 CachedDoc {
1309 doc: value.clone(),
1310 fetched_at: std::time::Instant::now(),
1311 },
1312 );
1313 }
1314 Ok(value)
1315 }
1316}
1317
1318#[async_trait]
1319impl DidDocFetcher for HttpPlcFetcher {
1320 async fn fetch(&self, url: &str) -> Result<Value> {
1321 let parsed = self.validate_fetch_url(url)?;
1322 let asked = parsed
1323 .path_segments()
1324 .and_then(|mut segments| segments.next_back())
1325 .ok_or_else(|| anyhow!("did:plc document URL has no DID path segment: {url}"))?;
1326 plc_msi(asked)?;
1327 let doc = self.fetch_json(url, MAX_DID_DOC_BYTES).await?;
1328 validate_plc_document(asked, &doc)?;
1329 Ok(doc)
1330 }
1331}
1332
1333#[async_trait]
1334impl PlcAuditFetcher for HttpPlcFetcher {
1335 async fn fetch_audit(&self, url: &str) -> Result<Value> {
1336 let parsed = self.validate_fetch_url(url)?;
1337 let segments: Vec<_> = parsed
1338 .path_segments()
1339 .ok_or_else(|| anyhow!("did:plc audit URL has no path segments: {url}"))?
1340 .collect();
1341 ensure!(
1342 segments.len() >= 3
1343 && segments[segments.len() - 2] == "log"
1344 && segments[segments.len() - 1] == "audit",
1345 "did:plc audit URL must end in /log/audit"
1346 );
1347 plc_msi(segments[segments.len() - 3])?;
1348 self.fetch_json(url, MAX_PLC_AUDIT_BYTES).await
1349 }
1350}
1351
1352#[cfg(test)]
1353#[allow(clippy::unwrap_used, clippy::expect_used)]
1354mod tests {
1355 use super::*;
1356 use serde_json::json;
1357
1358 const DID: &str = "did:plc:ewvi7nxzyoun6zhxrhs64oiz";
1360
1361 fn configured_base() -> Url {
1362 Url::parse("https://plc.example").unwrap()
1363 }
1364
1365 #[test]
1368 fn is_did_plc_prefix_check() {
1369 assert!(is_did_plc(DID));
1370 assert!(!is_did_plc("did:web:example.com"));
1371 assert!(!is_did_plc("did:plc")); }
1373
1374 #[test]
1375 fn msi_accepts_conformant_did() {
1376 assert_eq!(plc_msi(DID).unwrap(), "ewvi7nxzyoun6zhxrhs64oiz");
1377 assert_eq!(
1379 plc_msi(&format!("{DID}#atproto")).unwrap(),
1380 "ewvi7nxzyoun6zhxrhs64oiz"
1381 );
1382 }
1383
1384 #[test]
1385 fn msi_rejects_non_plc_and_malformed() {
1386 assert!(plc_msi("did:web:example.com").is_err());
1387 assert!(plc_msi("did:plc:").is_err());
1388 assert!(plc_msi("did:plc:abc").is_err());
1390 assert!(plc_msi("did:plc:ewvi7nxzyoun6zhxrhs64oizextra").is_err());
1391 assert!(plc_msi("did:plc:EWVI7NXZYOUN6ZHXRHS64OIZ").is_err());
1393 assert!(plc_msi("did:plc:0wvi7nxzyoun6zhxrhs64oiz").is_err());
1395 assert!(plc_msi("did:plc:1wvi7nxzyoun6zhxrhs64oiz").is_err());
1396 assert!(plc_msi("did:plc:8wvi7nxzyoun6zhxrhs64oiz").is_err());
1397 assert!(plc_msi("did:plc:9wvi7nxzyoun6zhxrhs64oiz").is_err());
1398 assert!(plc_msi("did:plc:ewvi7nxzyoun6zhxrhs64oi/").is_err());
1400 assert!(plc_msi("did:plc:ewvi7nxzyoun6zhxrhs64oi%").is_err());
1401 }
1402
1403 #[test]
1406 fn config_accepts_https_base() {
1407 let cfg =
1408 PlcResolverConfig::new(configured_base(), std::time::Duration::from_secs(60)).unwrap();
1409 assert_eq!(cfg.base_url().as_str(), "https://plc.example/");
1410 assert_eq!(cfg.ttl(), std::time::Duration::from_secs(60));
1411 }
1412
1413 #[test]
1414 fn config_rejects_http_credentials_query_fragment() {
1415 assert!(PlcResolverConfig::new(
1416 Url::parse("http://plc.invalid").unwrap(),
1417 std::time::Duration::from_secs(60)
1418 )
1419 .is_err());
1420 assert!(PlcResolverConfig::new(
1421 Url::parse("https://user:pass@plc.invalid").unwrap(),
1422 std::time::Duration::from_secs(60)
1423 )
1424 .is_err());
1425 assert!(PlcResolverConfig::new(
1426 Url::parse("https://plc.invalid/?token=x").unwrap(),
1427 std::time::Duration::from_secs(60)
1428 )
1429 .is_err());
1430 assert!(PlcResolverConfig::new(
1431 Url::parse("https://plc.invalid/#frag").unwrap(),
1432 std::time::Duration::from_secs(60)
1433 )
1434 .is_err());
1435 }
1436
1437 #[test]
1439 fn url_derivation_configured_base() {
1440 assert_eq!(
1441 did_plc_url(DID, &configured_base()).unwrap(),
1442 format!("https://plc.example/{DID}")
1443 );
1444 }
1445
1446 #[test]
1447 fn url_derivation_custom_base_with_path() {
1448 let base = Url::parse("https://plc.example/mirror").unwrap();
1451 assert_eq!(
1452 did_plc_url(DID, &base).unwrap(),
1453 "https://plc.example/mirror/did:plc:ewvi7nxzyoun6zhxrhs64oiz"
1454 );
1455 let base = Url::parse("https://plc.example/mirror/").unwrap();
1457 assert_eq!(
1458 did_plc_url(DID, &base).unwrap(),
1459 "https://plc.example/mirror/did:plc:ewvi7nxzyoun6zhxrhs64oiz"
1460 );
1461 let base = Url::parse("https://localhost:8443").unwrap();
1463 assert_eq!(
1464 did_plc_url(DID, &base).unwrap(),
1465 "https://localhost:8443/did:plc:ewvi7nxzyoun6zhxrhs64oiz"
1466 );
1467 }
1468
1469 #[test]
1470 fn url_derivation_rejects_malformed_did() {
1471 assert!(did_plc_url("did:web:example.com", &configured_base()).is_err());
1472 assert!(did_plc_url("did:plc:tooshort", &configured_base()).is_err());
1473 }
1474
1475 #[test]
1478 fn validate_accepts_matching_subject() {
1479 let doc = json!({ "id": DID, "verificationMethod": [] });
1480 assert!(validate_plc_document(DID, &doc).is_ok());
1481 assert!(validate_plc_document(&format!("{DID}#atproto"), &doc).is_ok());
1483 }
1484
1485 #[test]
1486 fn validate_rejects_substituted_subject() {
1487 let doc = json!({ "id": "did:plc:zxcvbnmasdfghjklqwertyu", "verificationMethod": [] });
1490 let err = validate_plc_document(DID, &doc).unwrap_err();
1491 assert!(err.to_string().contains("mismatch"), "{err}");
1492 }
1493
1494 #[test]
1495 fn validate_rejects_missing_or_nonstring_id() {
1496 assert!(validate_plc_document(DID, &json!({ "verificationMethod": [] })).is_err());
1497 assert!(validate_plc_document(DID, &json!({ "id": 42 })).is_err());
1498 assert!(validate_plc_document(DID, &json!(["not", "an", "object"])).is_err());
1500 }
1501
1502 #[test]
1503 fn validate_rejects_malformed_collection_members() {
1504 assert!(validate_plc_document(DID, &json!({ "id": DID, "service": {} })).is_err());
1505 assert!(
1506 validate_plc_document(DID, &json!({ "id": DID, "verificationMethod": {} })).is_err()
1507 );
1508 }
1509
1510 #[test]
1511 fn validate_rejects_malformed_or_ambiguous_collection_members() {
1512 assert!(validate_plc_document(DID, &json!({ "id": DID, "alsoKnownAs": [null] })).is_err());
1513 assert!(validate_plc_document(
1514 DID,
1515 &json!({
1516 "id": DID,
1517 "verificationMethod": [{ "id": "#key", "type": "Multikey" }]
1518 })
1519 )
1520 .is_err());
1521 assert!(validate_plc_document(
1522 DID,
1523 &json!({
1524 "id": DID,
1525 "verificationMethod": [
1526 {
1527 "id": "#key",
1528 "type": "Multikey",
1529 "controller": DID,
1530 "publicKeyMultibase": "zKey"
1531 },
1532 {
1533 "id": "#key",
1534 "type": "Multikey",
1535 "controller": DID,
1536 "publicKeyMultibase": "zOtherKey"
1537 }
1538 ]
1539 })
1540 )
1541 .is_err());
1542 assert!(validate_plc_document(
1543 DID,
1544 &json!({
1545 "id": DID,
1546 "service": [{ "id": "#pds", "type": "AtprotoPersonalDataServer" }]
1547 })
1548 )
1549 .is_err());
1550 assert!(validate_plc_document(
1551 DID,
1552 &json!({
1553 "id": DID,
1554 "service": [
1555 { "id": "#pds", "type": "AtprotoPersonalDataServer", "serviceEndpoint": "https://pds.example" },
1556 { "id": "#pds", "type": "AtprotoPersonalDataServer", "serviceEndpoint": "https://other.example" }
1557 ]
1558 })
1559 )
1560 .is_err());
1561 }
1562
1563 #[test]
1564 fn parser_rejects_ambiguous_duplicate_keys() {
1565 let duplicate_id = format!(r#"{{"id":"{DID}","id":"did:plc:zxcvbnmasdfghjklqwertyu"}}"#);
1566 assert!(parse_did_document_no_duplicates(
1567 duplicate_id.as_bytes(),
1568 "https://plc.example/doc"
1569 )
1570 .is_err());
1571 assert!(parse_did_document_no_duplicates(
1572 br#"{"id":"did:plc:ewvi7nxzyoun6zhxrhs64oiz","service":[{"type":"a","type":"b"}] }"#,
1573 "https://plc.example/doc"
1574 )
1575 .is_err());
1576 }
1577
1578 #[test]
1579 fn captured_audit_verifies_cids_genesis_and_signature_chain() {
1580 verify_plc_audit(DID, &captured_audit(), &captured_document()).unwrap();
1581 }
1582
1583 #[test]
1584 fn audit_rejects_signature_tamper_even_with_recomputed_cid() {
1585 let mut audit = captured_audit();
1586 let entries = audit.as_array_mut().unwrap();
1587 let last = entries.last_mut().unwrap();
1588 let operation = last.get_mut("operation").unwrap();
1589 operation["sig"] =
1590 Value::String("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".into());
1591 last["cid"] = Value::String(operation_cid(operation).unwrap());
1592
1593 let err = verify_plc_audit(DID, &audit, &captured_document()).unwrap_err();
1594 assert!(err.to_string().contains("signature"), "{err:#}");
1595 }
1596
1597 #[test]
1598 fn audit_rejects_unsigned_current_document_substitution() {
1599 let mut substituted = captured_document();
1600 substituted["verificationMethod"][0]["publicKeyMultibase"] =
1601 Value::String("zQ3shXjHeiBuRCKmM36cuYnm7YEMzhGnCmCyW92sRJ9pribSF".into());
1602 let err = verify_plc_audit(DID, &captured_audit(), &substituted).unwrap_err();
1603 assert!(err.to_string().contains("verified audit-log head"), "{err}");
1604 }
1605
1606 #[test]
1607 fn audit_head_comparison_canonicalizes_relative_member_ids() {
1608 let mut document = captured_document();
1609 document["verificationMethod"][0]["id"] = Value::String("#atproto".into());
1610 verify_plc_audit(DID, &captured_audit(), &document).unwrap();
1611 }
1612
1613 #[test]
1624 fn validate_rejects_malformed_verification_material() {
1625 assert!(validate_plc_document(
1627 DID,
1628 &json!({
1629 "id": DID,
1630 "verificationMethod": [{
1631 "id": "#bad-multikey", "type": "Multikey", "controller": DID,
1632 "publicKeyMultibase": "zKey"
1633 }]
1634 })
1635 )
1636 .is_err());
1637 assert!(validate_plc_document(
1639 DID,
1640 &json!({
1641 "id": DID,
1642 "verificationMethod": [{
1643 "id": "#bad-multikey2", "type": "Multikey", "controller": DID,
1644 "publicKeyMultibase": "not-multibase"
1645 }]
1646 })
1647 )
1648 .is_err());
1649 assert!(validate_plc_document(
1651 DID,
1652 &json!({
1653 "id": DID,
1654 "verificationMethod": [{
1655 "id": "#bad-jwk", "type": "JsonWebKey", "controller": DID,
1656 "publicKeyJwk": { "garbage": true }
1657 }]
1658 })
1659 )
1660 .is_err());
1661 assert!(validate_plc_document(
1663 DID,
1664 &json!({
1665 "id": DID,
1666 "verificationMethod": [{
1667 "id": "#bad-jwk2", "type": "JsonWebKey", "controller": DID,
1668 "publicKeyJwk": { "kty": "NotARealKty" }
1669 }]
1670 })
1671 )
1672 .is_err());
1673 assert!(validate_plc_document(
1676 DID,
1677 &json!({
1678 "id": DID,
1679 "verificationMethod": [{
1680 "id": "#no-material", "type": "Multikey", "controller": DID
1681 }]
1682 })
1683 )
1684 .is_err());
1685 }
1686
1687 #[test]
1691 fn validate_preserves_unknown_algorithm_with_valid_material() {
1692 let unknown_key = {
1695 let payload = [0x0bu8, 0xad, 0x01]; let mut bytes = vec![0xfd, 0x01]; bytes.extend_from_slice(&payload);
1698 bytes.extend_from_slice(&[0u8; 30]); format!("z{}", bs58::encode(&bytes).into_string())
1700 };
1701 let doc = json!({
1702 "id": DID,
1703 "verificationMethod": [{
1704 "id": "#unknown", "type": "UnknownVerificationMethod2026",
1705 "controller": DID, "publicKeyMultibase": unknown_key
1706 }]
1707 });
1708 assert!(validate_plc_document(DID, &doc).is_ok());
1709 }
1710
1711 #[test]
1714 fn validate_rejects_multiple_material_properties() {
1715 let mk = "zQ3shunBKsXixLxKtC5qeSG9E4J5RkGN57im31pcTzbNQnm5w";
1717 assert!(validate_plc_document(
1718 DID,
1719 &json!({
1720 "id": DID,
1721 "verificationMethod": [{
1722 "id": "#both", "type": "Multikey", "controller": DID,
1723 "publicKeyMultibase": mk,
1724 "publicKeyJwk": { "kty": "OKP", "crv": "Ed25519", "x": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlnw_vyHashME" }
1725 }]
1726 })
1727 )
1728 .is_err());
1729 }
1730
1731 #[test]
1735 fn validate_rejects_semantically_duplicate_ids() {
1736 let mk = "zQ3shunBKsXixLxKtC5qeSG9E4J5RkGN57im31pcTzbNQnm5w";
1737 assert!(validate_plc_document(
1738 DID,
1739 &json!({
1740 "id": DID,
1741 "verificationMethod": [
1742 { "id": "#key", "type": "Multikey", "controller": DID, "publicKeyMultibase": mk },
1743 { "id": format!("{DID}#key"), "type": "Multikey", "controller": DID, "publicKeyMultibase": mk }
1744 ]
1745 })
1746 )
1747 .is_err());
1748 }
1749
1750 #[test]
1754 fn validate_rejects_non_did_or_non_uri_fields() {
1755 assert!(
1757 validate_plc_document(DID, &json!({ "id": DID, "alsoKnownAs": ["not-a-uri"] }))
1758 .is_err()
1759 );
1760 assert!(validate_plc_document(
1762 DID,
1763 &json!({
1764 "id": DID,
1765 "verificationMethod": [{
1766 "id": "#k", "type": "Multikey", "controller": "not-a-did",
1767 "publicKeyMultibase": "zQ3shunBKsXixLxKtC5qeSG9E4J5RkGN57im31pcTzbNQnm5w"
1768 }]
1769 })
1770 )
1771 .is_err());
1772 assert!(validate_plc_document(
1774 DID,
1775 &json!({
1776 "id": DID,
1777 "verificationMethod": [{
1778 "id": "https://evil.example/key", "type": "Multikey", "controller": DID,
1779 "publicKeyMultibase": "zQ3shunBKsXixLxKtC5qeSG9E4J5RkGN57im31pcTzbNQnm5w"
1780 }]
1781 })
1782 )
1783 .is_err());
1784 assert!(validate_plc_document(
1786 DID,
1787 &json!({
1788 "id": DID,
1789 "service": [{ "id": "#pds", "type": "T", "serviceEndpoint": "no-scheme-here" }]
1790 })
1791 )
1792 .is_err());
1793 }
1794
1795 struct FixtureFetcher {
1798 doc: Value,
1799 audit: Value,
1800 }
1801
1802 #[async_trait]
1803 impl DidDocFetcher for FixtureFetcher {
1804 async fn fetch(&self, url: &str) -> Result<Value> {
1805 assert_eq!(url, "https://plc.example/did:plc:ewvi7nxzyoun6zhxrhs64oiz");
1806 Ok(self.doc.clone())
1807 }
1808 }
1809
1810 #[async_trait]
1811 impl PlcAuditFetcher for FixtureFetcher {
1812 async fn fetch_audit(&self, url: &str) -> Result<Value> {
1813 assert_eq!(
1814 url,
1815 "https://plc.example/did:plc:ewvi7nxzyoun6zhxrhs64oiz/log/audit"
1816 );
1817 Ok(self.audit.clone())
1818 }
1819 }
1820
1821 struct NeverFetcher;
1824
1825 #[async_trait]
1826 impl DidDocFetcher for NeverFetcher {
1827 async fn fetch(&self, url: &str) -> Result<Value> {
1828 panic!("resolver must not fetch for a malformed DID (called with {url})");
1829 }
1830 }
1831
1832 #[async_trait]
1833 impl PlcAuditFetcher for NeverFetcher {
1834 async fn fetch_audit(&self, url: &str) -> Result<Value> {
1835 panic!("resolver must not fetch audit for a malformed DID (called with {url})");
1836 }
1837 }
1838
1839 fn captured_document() -> Value {
1840 parse_did_document_no_duplicates(
1841 include_bytes!("fixtures/plc_directory_ewvi7nxzyoun6zhxrhs64oiz.json"),
1842 "captured PLC document",
1843 )
1844 .unwrap()
1845 }
1846
1847 fn captured_audit() -> Value {
1848 parse_did_document_no_duplicates(
1849 include_bytes!("fixtures/plc_directory_ewvi7nxzyoun6zhxrhs64oiz_audit.json"),
1850 "captured PLC audit",
1851 )
1852 .unwrap()
1853 }
1854
1855 fn fixture_resolver(doc: Value) -> DidPlcResolver<FixtureFetcher> {
1856 DidPlcResolver::with_fetcher(
1857 FixtureFetcher {
1858 doc,
1859 audit: captured_audit(),
1860 },
1861 PlcResolverConfig::new(configured_base(), std::time::Duration::from_secs(60)).unwrap(),
1862 )
1863 }
1864
1865 #[tokio::test]
1866 async fn resolve_document_returns_signature_chain_verified_doc() {
1867 let doc = captured_document();
1868 let resolver = fixture_resolver(doc.clone());
1869 let got = resolver.resolve_document(DID).await.unwrap();
1870 assert_eq!(got, doc);
1871 }
1872
1873 #[tokio::test]
1874 async fn resolve_document_accepts_captured_reference_directory_document() {
1875 let doc = parse_did_document_no_duplicates(
1879 include_bytes!("fixtures/plc_directory_ewvi7nxzyoun6zhxrhs64oiz.json"),
1880 "https://plc.directory/did:plc:ewvi7nxzyoun6zhxrhs64oiz",
1881 )
1882 .unwrap();
1883 let resolver = fixture_resolver(doc.clone());
1884 assert_eq!(resolver.resolve_document(DID).await.unwrap(), doc);
1885 }
1886
1887 #[tokio::test]
1888 async fn resolve_document_rejects_id_mismatch() {
1889 let doc = json!({ "id": "did:plc:zxcvbnmasdfghjklqwertyu" });
1890 let resolver = fixture_resolver(doc);
1891 let err = resolver.resolve_document(DID).await.unwrap_err();
1892 assert!(err.to_string().contains("mismatch"), "{err}");
1893 }
1894
1895 #[tokio::test]
1896 async fn resolve_document_rejects_missing_id() {
1897 let resolver = fixture_resolver(json!({ "verificationMethod": [] }));
1898 assert!(resolver.resolve_document(DID).await.is_err());
1899 }
1900
1901 #[tokio::test]
1902 async fn resolve_document_fetch_failure_fails_closed() {
1903 struct FailingFetcher;
1904 #[async_trait]
1905 impl DidDocFetcher for FailingFetcher {
1906 async fn fetch(&self, url: &str) -> Result<Value> {
1907 bail!("simulated directory failure for {url}");
1908 }
1909 }
1910 #[async_trait]
1911 impl PlcAuditFetcher for FailingFetcher {
1912 async fn fetch_audit(&self, url: &str) -> Result<Value> {
1913 bail!("simulated directory failure for {url}");
1914 }
1915 }
1916 let resolver = DidPlcResolver::with_fetcher(
1917 FailingFetcher,
1918 PlcResolverConfig::new(configured_base(), std::time::Duration::from_secs(60)).unwrap(),
1919 );
1920 assert!(resolver.resolve_document(DID).await.is_err());
1921 }
1922
1923 #[tokio::test]
1924 async fn resolve_document_malformed_did_never_fetches() {
1925 let resolver = DidPlcResolver::with_fetcher(
1926 NeverFetcher,
1927 PlcResolverConfig::new(configured_base(), std::time::Duration::from_secs(60)).unwrap(),
1928 );
1929 assert!(resolver.resolve_document("did:plc:tooshort").await.is_err());
1930 assert!(resolver
1931 .resolve_document("did:web:example.com")
1932 .await
1933 .is_err());
1934 }
1935
1936 #[test]
1939 fn fetcher_allowlist_is_configured_origin() {
1940 let cfg = PlcResolverConfig::new(
1941 Url::parse("https://plc.example/mirror").unwrap(),
1942 std::time::Duration::from_secs(60),
1943 )
1944 .unwrap();
1945 let f = HttpPlcFetcher::new(&cfg).unwrap();
1946 assert_eq!(
1947 f.allowed_origins(),
1948 &[Url::parse("https://plc.example").unwrap().origin()]
1949 );
1950 }
1951
1952 #[test]
1953 fn native_resolver_uses_its_single_cache_configuration() {
1954 let config =
1955 PlcResolverConfig::new(configured_base(), std::time::Duration::from_secs(37)).unwrap();
1956 let resolver = DidPlcResolver::new(config).unwrap();
1957 assert_eq!(resolver.fetcher.ttl, resolver.config.ttl());
1958 assert_eq!(
1959 resolver.fetcher.allowed_origins,
1960 vec![resolver.config.base_url().origin()]
1961 );
1962 }
1963
1964 #[tokio::test]
1965 async fn fetcher_rejects_non_https() {
1966 let config =
1967 PlcResolverConfig::new(configured_base(), std::time::Duration::from_secs(60)).unwrap();
1968 let f = HttpPlcFetcher::new(&config).unwrap();
1969 let err = f
1970 .fetch("http://plc.example/ewvi7nxzyoun6zhxrhs64oiz")
1971 .await
1972 .unwrap_err();
1973 assert!(err.to_string().contains("https"), "{err}");
1974 }
1975
1976 #[tokio::test]
1977 async fn fetcher_rejects_origin_outside_allowlist() {
1978 let config =
1979 PlcResolverConfig::new(configured_base(), std::time::Duration::from_secs(60)).unwrap();
1980 let f = HttpPlcFetcher::new(&config).unwrap();
1981 let err = f
1984 .fetch("https://evil.example/ewvi7nxzyoun6zhxrhs64oiz")
1985 .await
1986 .unwrap_err();
1987 assert!(err.to_string().contains("egress allowlist"), "{err}");
1988 let err = f
1990 .fetch("https://plc.example:4443/ewvi7nxzyoun6zhxrhs64oiz")
1991 .await
1992 .unwrap_err();
1993 assert!(err.to_string().contains("egress allowlist"), "{err}");
1994 }
1995
1996 #[tokio::test]
1997 async fn fetcher_rejects_unparseable_url() {
1998 let config =
1999 PlcResolverConfig::new(configured_base(), std::time::Duration::from_secs(60)).unwrap();
2000 let f = HttpPlcFetcher::new(&config).unwrap();
2001 assert!(f.fetch("not a url").await.is_err());
2002 }
2003}