A better Rust ATProto crate
1//! Identity resolution utilities: DID and handle resolution, DID document fetch, 2//! and helpers for PDS endpoint discovery. See `identity::resolver` for details. 3//! Identity resolution: handle → DID and DID → document, with smart fallbacks. 4//! 5//! Fallback order (default): 6//! - Handle → DID: DNS TXT (if `dns` feature) → HTTPS well-known → PDS XRPC 7//! `resolveHandle` (when `pds_fallback` is configured) → public API fallback → Slingshot `resolveHandle` (if configured). 8//! - DID → Doc: did:web well-known → PLC/Slingshot HTTP → PDS XRPC `resolveDid` (when configured), 9//! then Slingshot mini‑doc (partial) if configured. 10//! 11//! Parsing returns a `DidDocResponse` so callers can borrow from the response buffer 12//! and optionally validate the document `id` against the requested DID. 13 14// use crate::CowStr; // not currently needed directly here 15pub mod resolver; 16 17use crate::resolver::{ 18 DidDocResponse, DidStep, HandleStep, IdentityError, IdentityResolver, MiniDoc, PlcSource, 19 ResolverOptions, 20}; 21use bytes::Bytes; 22use jacquard_api::com_atproto::identity::resolve_did; 23use jacquard_api::com_atproto::identity::resolve_handle::ResolveHandle; 24use jacquard_common::error::TransportError; 25use jacquard_common::http_client::HttpClient; 26use jacquard_common::types::did::Did; 27use jacquard_common::types::did_doc::DidDocument; 28use jacquard_common::types::ident::AtIdentifier; 29use jacquard_common::types::xrpc::XrpcExt; 30use jacquard_common::{IntoStatic, types::string::Handle}; 31use percent_encoding::percent_decode_str; 32use reqwest::StatusCode; 33use url::{ParseError, Url}; 34 35#[cfg(feature = "dns")] 36use hickory_resolver::{TokioAsyncResolver, config::ResolverConfig}; 37 38/// Default resolver implementation with configurable fallback order. 39pub struct JacquardResolver { 40 http: reqwest::Client, 41 opts: ResolverOptions, 42 #[cfg(feature = "dns")] 43 dns: Option<TokioAsyncResolver>, 44} 45 46impl JacquardResolver { 47 /// Create a new instance of the default resolver with all options (except DNS) up front 48 pub fn new(http: reqwest::Client, opts: ResolverOptions) -> Self { 49 Self { 50 http, 51 opts, 52 #[cfg(feature = "dns")] 53 dns: None, 54 } 55 } 56 57 #[cfg(feature = "dns")] 58 /// Create a new instance of the default resolver with all options, plus default DNS, up front 59 pub fn new_dns(http: reqwest::Client, opts: ResolverOptions) -> Self { 60 Self { 61 http, 62 opts, 63 dns: Some(TokioAsyncResolver::tokio( 64 ResolverConfig::default(), 65 Default::default(), 66 )), 67 } 68 } 69 70 #[cfg(feature = "dns")] 71 /// Add default DNS resolution to the resolver 72 pub fn with_system_dns(mut self) -> Self { 73 self.dns = Some(TokioAsyncResolver::tokio( 74 ResolverConfig::default(), 75 Default::default(), 76 )); 77 self 78 } 79 80 /// Set PLC source (PLC directory or Slingshot) 81 pub fn with_plc_source(mut self, source: PlcSource) -> Self { 82 self.opts.plc_source = source; 83 self 84 } 85 86 /// Enable/disable public unauthenticated fallback for resolveHandle 87 pub fn with_public_fallback_for_handle(mut self, enable: bool) -> Self { 88 self.opts.public_fallback_for_handle = enable; 89 self 90 } 91 92 /// Enable/disable doc id validation 93 pub fn with_validate_doc_id(mut self, enable: bool) -> Self { 94 self.opts.validate_doc_id = enable; 95 self 96 } 97 98 /// Construct the well-known HTTPS URL for a `did:web` DID. 99 /// 100 /// - `did:web:example.com` → `https://example.com/.well-known/did.json` 101 /// - `did:web:example.com:user:alice` → `https://example.com/user/alice/did.json` 102 fn did_web_url(&self, did: &Did<'_>) -> Result<Url, IdentityError> { 103 // did:web:example.com[:path:segments] 104 let s = did.as_str(); 105 let rest = s 106 .strip_prefix("did:web:") 107 .ok_or_else(|| IdentityError::UnsupportedDidMethod(s.to_string()))?; 108 let mut parts = rest.split(':'); 109 let host = parts 110 .next() 111 .ok_or_else(|| IdentityError::UnsupportedDidMethod(s.to_string()))?; 112 let mut url = Url::parse(&format!("https://{host}/")).map_err(IdentityError::Url)?; 113 let path: Vec<&str> = parts.collect(); 114 if path.is_empty() { 115 url.set_path(".well-known/did.json"); 116 } else { 117 // Append path segments and did.json 118 let mut segments = url 119 .path_segments_mut() 120 .map_err(|_| IdentityError::Url(ParseError::SetHostOnCannotBeABaseUrl))?; 121 for seg in path { 122 // Minimally percent-decode each segment per spec guidance 123 let decoded = percent_decode_str(seg).decode_utf8_lossy(); 124 segments.push(&decoded); 125 } 126 segments.push("did.json"); 127 // drop segments 128 } 129 Ok(url) 130 } 131 132 #[cfg(test)] 133 fn test_did_web_url_raw(&self, s: &str) -> String { 134 let did = Did::new(s).unwrap(); 135 self.did_web_url(&did).unwrap().to_string() 136 } 137 138 async fn get_json_bytes(&self, url: Url) -> Result<(Bytes, StatusCode), IdentityError> { 139 let resp = self 140 .http 141 .get(url) 142 .send() 143 .await 144 .map_err(TransportError::from)?; 145 let status = resp.status(); 146 let buf = resp.bytes().await.map_err(TransportError::from)?; 147 Ok((buf, status)) 148 } 149 150 async fn get_text(&self, url: Url) -> Result<String, IdentityError> { 151 let resp = self 152 .http 153 .get(url) 154 .send() 155 .await 156 .map_err(TransportError::from)?; 157 if resp.status() == StatusCode::OK { 158 Ok(resp.text().await.map_err(TransportError::from)?) 159 } else { 160 Err(IdentityError::Http( 161 resp.error_for_status().unwrap_err().into(), 162 )) 163 } 164 } 165 166 #[cfg(feature = "dns")] 167 async fn dns_txt(&self, name: &str) -> Result<Vec<String>, IdentityError> { 168 let Some(dns) = &self.dns else { 169 return Ok(vec![]); 170 }; 171 let fqdn = format!("_atproto.{name}."); 172 let response = dns.txt_lookup(fqdn).await?; 173 let mut out = Vec::new(); 174 for txt in response.iter() { 175 for data in txt.txt_data().iter() { 176 out.push(String::from_utf8_lossy(data).to_string()); 177 } 178 } 179 Ok(out) 180 } 181 182 fn parse_atproto_did_body(body: &str) -> Result<Did<'static>, IdentityError> { 183 let line = body 184 .lines() 185 .find(|l| !l.trim().is_empty()) 186 .ok_or(IdentityError::InvalidWellKnown)?; 187 let did = Did::new(line.trim()).map_err(|_| IdentityError::InvalidWellKnown)?; 188 Ok(did.into_static()) 189 } 190} 191 192impl JacquardResolver { 193 /// Resolve handle to DID via a PDS XRPC call (stateless, unauth by default) 194 pub async fn resolve_handle_via_pds( 195 &self, 196 handle: &Handle<'_>, 197 ) -> Result<Did<'static>, IdentityError> { 198 let pds = match &self.opts.pds_fallback { 199 Some(u) => u.clone(), 200 None => return Err(IdentityError::InvalidWellKnown), 201 }; 202 let req = ResolveHandle::new().handle((*handle).clone()).build(); 203 let resp = self 204 .http 205 .xrpc(pds) 206 .send(&req) 207 .await 208 .map_err(|e| IdentityError::Xrpc(e.to_string()))?; 209 let out = resp 210 .into_output() 211 .map_err(|e| IdentityError::Xrpc(e.to_string()))?; 212 Did::new_owned(out.did.as_str()) 213 .map(|d| d.into_static()) 214 .map_err(|_| IdentityError::InvalidWellKnown) 215 } 216 217 /// Fetch DID document via PDS resolveDid (returns owned DidDocument) 218 pub async fn fetch_did_doc_via_pds_owned( 219 &self, 220 did: &Did<'_>, 221 ) -> Result<DidDocument<'static>, IdentityError> { 222 let pds = match &self.opts.pds_fallback { 223 Some(u) => u.clone(), 224 None => return Err(IdentityError::InvalidWellKnown), 225 }; 226 let req = resolve_did::ResolveDid::new().did(did.clone()).build(); 227 let resp = self 228 .http 229 .xrpc(pds) 230 .send(&req) 231 .await 232 .map_err(|e| IdentityError::Xrpc(e.to_string()))?; 233 let out = resp 234 .into_output() 235 .map_err(|e| IdentityError::Xrpc(e.to_string()))?; 236 let doc_json = serde_json::to_value(&out.did_doc)?; 237 let s = serde_json::to_string(&doc_json)?; 238 let doc_borrowed: DidDocument<'_> = serde_json::from_str(&s)?; 239 Ok(doc_borrowed.into_static()) 240 } 241 242 /// Fetch a minimal DID document via a Slingshot mini-doc endpoint, if your PlcSource uses Slingshot. 243 /// Returns the raw response wrapper for borrowed parsing and validation. 244 pub async fn fetch_mini_doc_via_slingshot( 245 &self, 246 did: &Did<'_>, 247 ) -> Result<DidDocResponse, IdentityError> { 248 let base = match &self.opts.plc_source { 249 PlcSource::Slingshot { base } => base.clone(), 250 _ => { 251 return Err(IdentityError::UnsupportedDidMethod( 252 "mini-doc requires Slingshot source".into(), 253 )); 254 } 255 }; 256 let mut url = base; 257 url.set_path("/xrpc/com.bad-example.identity.resolveMiniDoc"); 258 if let Ok(qs) = 259 serde_html_form::to_string(&resolve_did::ResolveDid::new().did(did.clone()).build()) 260 { 261 url.set_query(Some(&qs)); 262 } 263 let (buf, status) = self.get_json_bytes(url).await?; 264 Ok(DidDocResponse { 265 buffer: buf, 266 status, 267 requested: Some(did.clone().into_static()), 268 }) 269 } 270} 271 272#[async_trait::async_trait] 273impl IdentityResolver for JacquardResolver { 274 fn options(&self) -> &ResolverOptions { 275 &self.opts 276 } 277 async fn resolve_handle(&self, handle: &Handle<'_>) -> Result<Did<'static>, IdentityError> { 278 let host = handle.as_str(); 279 for step in &self.opts.handle_order { 280 match step { 281 HandleStep::DnsTxt => { 282 #[cfg(feature = "dns")] 283 { 284 if let Ok(txts) = self.dns_txt(host).await { 285 for txt in txts { 286 if let Some(did_str) = txt.strip_prefix("did=") { 287 if let Ok(did) = Did::new(did_str) { 288 return Ok(did.into_static()); 289 } 290 } 291 } 292 } 293 } 294 } 295 HandleStep::HttpsWellKnown => { 296 let url = Url::parse(&format!("https://{host}/.well-known/atproto-did"))?; 297 if let Ok(text) = self.get_text(url).await { 298 if let Ok(did) = Self::parse_atproto_did_body(&text) { 299 return Ok(did); 300 } 301 } 302 } 303 HandleStep::PdsResolveHandle => { 304 // Prefer PDS XRPC via stateless client 305 if let Ok(did) = self.resolve_handle_via_pds(handle).await { 306 return Ok(did); 307 } 308 // Public unauth fallback 309 if self.opts.public_fallback_for_handle { 310 if let Ok(mut url) = Url::parse("https://public.api.bsky.app") { 311 url.set_path("/xrpc/com.atproto.identity.resolveHandle"); 312 if let Ok(qs) = serde_html_form::to_string( 313 &ResolveHandle::new().handle((*handle).clone()).build(), 314 ) { 315 url.set_query(Some(&qs)); 316 } else { 317 continue; 318 } 319 if let Ok((buf, status)) = self.get_json_bytes(url).await { 320 if status.is_success() { 321 if let Ok(val) = 322 serde_json::from_slice::<serde_json::Value>(&buf) 323 { 324 if let Some(did_str) = 325 val.get("did").and_then(|v| v.as_str()) 326 { 327 if let Ok(did) = Did::new_owned(did_str) { 328 return Ok(did.into_static()); 329 } 330 } 331 } 332 } 333 } 334 } 335 } 336 // Non-auth path: if PlcSource is Slingshot, use its resolveHandle endpoint. 337 if let PlcSource::Slingshot { base } = &self.opts.plc_source { 338 let mut url = base.clone(); 339 url.set_path("/xrpc/com.atproto.identity.resolveHandle"); 340 if let Ok(qs) = serde_html_form::to_string( 341 &ResolveHandle::new().handle((*handle).clone()).build(), 342 ) { 343 url.set_query(Some(&qs)); 344 } else { 345 continue; 346 } 347 if let Ok((buf, status)) = self.get_json_bytes(url).await { 348 if status.is_success() { 349 if let Ok(val) = serde_json::from_slice::<serde_json::Value>(&buf) { 350 if let Some(did_str) = val.get("did").and_then(|v| v.as_str()) { 351 if let Ok(did) = Did::new_owned(did_str) { 352 return Ok(did.into_static()); 353 } 354 } 355 } 356 } 357 } 358 } 359 } 360 } 361 } 362 Err(IdentityError::InvalidWellKnown) 363 } 364 365 async fn resolve_did_doc(&self, did: &Did<'_>) -> Result<DidDocResponse, IdentityError> { 366 let s = did.as_str(); 367 for step in &self.opts.did_order { 368 match step { 369 DidStep::DidWebHttps if s.starts_with("did:web:") => { 370 let url = self.did_web_url(did)?; 371 if let Ok((buf, status)) = self.get_json_bytes(url).await { 372 return Ok(DidDocResponse { 373 buffer: buf, 374 status, 375 requested: Some(did.clone().into_static()), 376 }); 377 } 378 } 379 DidStep::PlcHttp if s.starts_with("did:plc:") => { 380 let url = match &self.opts.plc_source { 381 PlcSource::PlcDirectory { base } => base.join(did.as_str())?, 382 PlcSource::Slingshot { base } => base.join(did.as_str())?, 383 }; 384 if let Ok((buf, status)) = self.get_json_bytes(url).await { 385 return Ok(DidDocResponse { 386 buffer: buf, 387 status, 388 requested: Some(did.clone().into_static()), 389 }); 390 } 391 } 392 DidStep::PdsResolveDid => { 393 // Try PDS XRPC for full DID doc 394 if let Ok(doc) = self.fetch_did_doc_via_pds_owned(did).await { 395 let buf = serde_json::to_vec(&doc).unwrap_or_default(); 396 return Ok(DidDocResponse { 397 buffer: Bytes::from(buf), 398 status: StatusCode::OK, 399 requested: Some(did.clone().into_static()), 400 }); 401 } 402 // Fallback: if Slingshot configured, return mini-doc response (partial doc) 403 if let PlcSource::Slingshot { base } = &self.opts.plc_source { 404 let url = self.slingshot_mini_doc_url(base, did.as_str())?; 405 let (buf, status) = self.get_json_bytes(url).await?; 406 return Ok(DidDocResponse { 407 buffer: buf, 408 status, 409 requested: Some(did.clone().into_static()), 410 }); 411 } 412 } 413 _ => {} 414 } 415 } 416 Err(IdentityError::UnsupportedDidMethod(s.to_string())) 417 } 418} 419 420impl HttpClient for JacquardResolver { 421 async fn send_http( 422 &self, 423 request: http::Request<Vec<u8>>, 424 ) -> core::result::Result<http::Response<Vec<u8>>, Self::Error> { 425 self.http.send_http(request).await 426 } 427 428 type Error = reqwest::Error; 429} 430 431/// Warnings produced during identity checks that are not fatal 432#[derive(Debug, Clone, PartialEq, Eq)] 433pub enum IdentityWarning { 434 /// The DID doc did not contain the expected handle alias under alsoKnownAs 435 HandleAliasMismatch { 436 #[allow(missing_docs)] 437 expected: Handle<'static>, 438 }, 439} 440 441impl JacquardResolver { 442 /// Resolve a handle to its DID, fetch the DID document, and return doc plus any warnings. 443 /// This applies the default equality check on the document id (error with doc if mismatch). 444 pub async fn resolve_handle_and_doc( 445 &self, 446 handle: &Handle<'_>, 447 ) -> Result<(Did<'static>, DidDocResponse, Vec<IdentityWarning>), IdentityError> { 448 let did = self.resolve_handle(handle).await?; 449 let resp = self.resolve_did_doc(&did).await?; 450 let resp_for_parse = resp.clone(); 451 let doc_borrowed = resp_for_parse.parse()?; 452 if self.opts.validate_doc_id && doc_borrowed.id.as_str() != did.as_str() { 453 return Err(IdentityError::DocIdMismatch { 454 expected: did.clone().into_static(), 455 doc: doc_borrowed.clone().into_static(), 456 }); 457 } 458 let mut warnings = Vec::new(); 459 // Check handle alias presence (soft warning) 460 let expected_alias = format!("at://{}", handle.as_str()); 461 let has_alias = doc_borrowed 462 .also_known_as 463 .as_ref() 464 .map(|v| v.iter().any(|s| s.as_ref() == expected_alias)) 465 .unwrap_or(false); 466 if !has_alias { 467 warnings.push(IdentityWarning::HandleAliasMismatch { 468 expected: handle.clone().into_static(), 469 }); 470 } 471 Ok((did, resp, warnings)) 472 } 473 474 /// Build Slingshot mini-doc URL for an identifier (handle or DID) 475 fn slingshot_mini_doc_url(&self, base: &Url, identifier: &str) -> Result<Url, IdentityError> { 476 let mut url = base.clone(); 477 url.set_path("/xrpc/com.bad-example.identity.resolveMiniDoc"); 478 url.set_query(Some(&format!( 479 "identifier={}", 480 urlencoding::Encoded::new(identifier) 481 ))); 482 Ok(url) 483 } 484 485 /// Fetch a minimal DID document via Slingshot's mini-doc endpoint using a generic at-identifier 486 pub async fn fetch_mini_doc_via_slingshot_identifier( 487 &self, 488 identifier: &AtIdentifier<'_>, 489 ) -> Result<MiniDocResponse, IdentityError> { 490 let base = match &self.opts.plc_source { 491 PlcSource::Slingshot { base } => base.clone(), 492 _ => { 493 return Err(IdentityError::UnsupportedDidMethod( 494 "mini-doc requires Slingshot source".into(), 495 )); 496 } 497 }; 498 let url = self.slingshot_mini_doc_url(&base, identifier.as_str())?; 499 let (buf, status) = self.get_json_bytes(url).await?; 500 Ok(MiniDocResponse { 501 buffer: buf, 502 status, 503 }) 504 } 505} 506 507/// Slingshot mini-doc JSON response wrapper 508#[derive(Clone)] 509pub struct MiniDocResponse { 510 buffer: Bytes, 511 status: StatusCode, 512} 513 514impl MiniDocResponse { 515 /// Parse borrowed MiniDoc 516 pub fn parse<'b>(&'b self) -> Result<MiniDoc<'b>, IdentityError> { 517 if self.status.is_success() { 518 serde_json::from_slice::<MiniDoc<'b>>(&self.buffer).map_err(IdentityError::from) 519 } else { 520 Err(IdentityError::HttpStatus(self.status)) 521 } 522 } 523} 524 525/// Resolver specialized for unauthenticated/public flows using reqwest and stateless XRPC 526pub type PublicResolver = JacquardResolver; 527 528impl Default for PublicResolver { 529 /// Build a resolver with: 530 /// - reqwest HTTP client 531 /// - Public fallbacks enabled for handle resolution 532 /// - default options (DNS enabled if compiled, public fallback for handles enabled) 533 /// 534 /// Example 535 /// ```ignore 536 /// use jacquard::identity::resolver::PublicResolver; 537 /// let resolver = PublicResolver::default(); 538 /// ``` 539 fn default() -> Self { 540 let http = reqwest::Client::new(); 541 let opts = ResolverOptions::default(); 542 let resolver = JacquardResolver::new(http, opts); 543 #[cfg(feature = "dns")] 544 let resolver = resolver.with_system_dns(); 545 resolver 546 } 547} 548 549/// Build a resolver configured to use Slingshot (`https://slingshot.microcosm.blue`) for PLC and 550/// mini-doc fallbacks, unauthenticated by default. 551pub fn slingshot_resolver_default() -> PublicResolver { 552 let http = reqwest::Client::new(); 553 let mut opts = ResolverOptions::default(); 554 opts.plc_source = PlcSource::slingshot_default(); 555 let resolver = JacquardResolver::new(http, opts); 556 #[cfg(feature = "dns")] 557 let resolver = resolver.with_system_dns(); 558 resolver 559} 560 561#[cfg(test)] 562mod tests { 563 use super::*; 564 565 #[test] 566 fn did_web_urls() { 567 let r = JacquardResolver::new(reqwest::Client::new(), ResolverOptions::default()); 568 assert_eq!( 569 r.test_did_web_url_raw("did:web:example.com"), 570 "https://example.com/.well-known/did.json" 571 ); 572 assert_eq!( 573 r.test_did_web_url_raw("did:web:example.com:user:alice"), 574 "https://example.com/user/alice/did.json" 575 ); 576 } 577 578 #[test] 579 fn slingshot_mini_doc_url_build() { 580 let r = JacquardResolver::new(reqwest::Client::new(), ResolverOptions::default()); 581 let base = Url::parse("https://slingshot.microcosm.blue").unwrap(); 582 let url = r.slingshot_mini_doc_url(&base, "bad-example.com").unwrap(); 583 assert_eq!( 584 url.as_str(), 585 "https://slingshot.microcosm.blue/xrpc/com.bad-example.identity.resolveMiniDoc?identifier=bad-example.com" 586 ); 587 } 588 589 #[test] 590 fn slingshot_mini_doc_parse_success() { 591 let buf = Bytes::from_static( 592 br#"{ 593 "did": "did:plc:hdhoaan3xa3jiuq4fg4mefid", 594 "handle": "bad-example.com", 595 "pds": "https://porcini.us-east.host.bsky.network", 596 "signing_key": "zQ3shpq1g134o7HGDb86CtQFxnHqzx5pZWknrVX2Waum3fF6j" 597}"#, 598 ); 599 let resp = MiniDocResponse { 600 buffer: buf, 601 status: StatusCode::OK, 602 }; 603 let doc = resp.parse().expect("parse mini-doc"); 604 assert_eq!(doc.did.as_str(), "did:plc:hdhoaan3xa3jiuq4fg4mefid"); 605 assert_eq!(doc.handle.as_str(), "bad-example.com"); 606 assert_eq!( 607 doc.pds.as_ref(), 608 "https://porcini.us-east.host.bsky.network" 609 ); 610 assert!(doc.signing_key.as_ref().starts_with('z')); 611 } 612 613 #[test] 614 fn slingshot_mini_doc_parse_error_status() { 615 let buf = Bytes::from_static( 616 br#"{ 617 "error": "RecordNotFound", 618 "message": "This record was deleted" 619}"#, 620 ); 621 let resp = MiniDocResponse { 622 buffer: buf, 623 status: StatusCode::BAD_REQUEST, 624 }; 625 match resp.parse() { 626 Err(IdentityError::HttpStatus(s)) => assert_eq!(s, StatusCode::BAD_REQUEST), 627 other => panic!("unexpected: {:?}", other), 628 } 629 } 630}