Something went wrong. Try again.
Chris’s PDS implementation
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329//! Bounded AT Protocol identity resolution over deployment-controlled DNS.
pub(crate) mod http;
use std::{ collections::HashSet, sync::{ Arc, Mutex, atomic::{AtomicBool, Ordering}, },};
use atrium_api::{ did_doc::DidDocument, types::string::{Did, Handle},};use atrium_common::resolver::Resolver as _;use atrium_identity::{ did::{CommonDidResolver, CommonDidResolverConfig, DEFAULT_PLC_DIRECTORY_URL}, handle::{WellKnownHandleResolver, WellKnownHandleResolverConfig},};use atrium_xrpc::{HttpClient, http::Request};use hickory_resolver::{TokioResolver, proto::rr::RData};use percent_encoding::percent_decode_str;use url::Url;
use self::http::{OutboundHttp, dns_resolver, validate_https_url};
use crate::{ config::DeploymentMode, domain::identity::document_claims_handle, error::{Error, ErrorContext as _, Result},};
/// Network identity resolver plus the canonical identity hosted by this PDS.pub(crate) struct IdentityService { local_document: DidDocument, local_handle: Handle, local_did: Did, mode: DeploymentMode, local_handle_verified: AtomicBool, network: Mutex<Option<Arc<dyn IdentityNetwork>>>,}
struct NetworkIdentity { dns: TokioResolver, did: CommonDidResolver<OutboundHttp>, https_handle: WellKnownHandleResolver<OutboundHttp>, http: Arc<OutboundHttp>,}
#[async_trait::async_trait]trait IdentityNetwork: Send + Sync { async fn resolve_dns_handle(&self, handle: &Handle) -> Result<Option<Did>>; async fn resolve_https_handle(&self, handle: &Handle) -> Result<Did>; async fn resolve_did(&self, did: &Did) -> Result<DidDocument>;}
impl IdentityService { pub(crate) fn local_document(&self) -> &DidDocument { &self.local_document }
pub(crate) fn outbound_http(&self) -> Result<OutboundHttp> { OutboundHttp::new(None, self.mode) }
pub(crate) fn new(local_document: DidDocument, mode: DeploymentMode) -> Result<Self> { let local_did = local_document .id .parse::<Did>() .context(Error::Configuration, "invalid local DID")?; let local_handle = local_document .also_known_as .as_ref() .and_then(|aliases| aliases.iter().find_map(|alias| alias.strip_prefix("at://"))) .ok_or_else(|| Error::Configuration("local DID document has no handle".to_owned()))? .parse::<Handle>() .context(Error::Configuration, "invalid local handle")?; let network: Option<Arc<dyn IdentityNetwork>> = (mode == DeploymentMode::Production) .then(NetworkIdentity::new) .transpose()? .map(|network| Arc::new(network) as Arc<dyn IdentityNetwork>); Ok(Self { local_document, local_handle, local_did, mode, local_handle_verified: AtomicBool::new(mode == DeploymentMode::Local), network: Mutex::new(network), }) }
/// Resolve a handle using the preferred DNS TXT method, then HTTPS well-known. pub(crate) async fn resolve_handle(&self, handle: &Handle) -> Result<Did> { if self.mode == DeploymentMode::Local && handle == &self.local_handle { return Ok(self.local_did.clone()); } let network = self.network()?; match network.resolve_dns_handle(handle).await { Ok(Some(did)) => return Ok(did), Ok(None) => {} Err(Error::Upstream(error)) => { tracing::warn!(handle = handle.as_str(), %error, "DNS handle resolution failed; trying HTTPS"); } Err(error) => return Err(error), } network.resolve_https_handle(handle).await }
/// Resolve and validate a supported DID document. pub(crate) async fn resolve_did(&self, did: &Did) -> Result<DidDocument> { if did == &self.local_did { return Ok(self.local_document.clone()); } let network = self.network()?; let document = network.resolve_did(did).await?; if document.id != did.as_str() { return Err(Error::Upstream( "resolved DID document id does not match the requested DID".to_owned(), )); } Ok(document) }
/// Resolve both directions and require the DID document to claim the handle. pub(crate) async fn verify_handle(&self, handle: &Handle) -> Result<Did> { let did = self.resolve_handle(handle).await?; let document = self.resolve_did(&did).await?; if !document_claims_handle(&document, handle.as_str()) { return Err(handle_not_found( "resolved DID document does not link back to the handle", )); } Ok(did) }
/// Verify the configured public handle before production begins serving. pub(crate) async fn verify_local_handle(&self) -> Result<()> { if self.revalidate_local_handle().await? { return Ok(()); } Err(Error::Configuration(format!( "configured handle {} does not resolve bidirectionally to {}", self.local_handle.as_str(), self.local_did.as_str() ))) }
/// Recheck the configured handle, preserving the prior result on a transient /// resolver failure and returning a confirmed valid/invalid result. pub(crate) async fn revalidate_local_handle(&self) -> Result<bool> { let valid = match self.verify_handle(&self.local_handle).await { Ok(did) => did == self.local_did, Err(Error::Xrpc { name: "HandleNotFound", .. }) => false, Err(error) => return Err(error), }; self.local_handle_verified.store(valid, Ordering::Release); Ok(valid) }
pub(crate) fn local_handle_verified(&self) -> bool { self.local_handle_verified.load(Ordering::Acquire) }
fn network(&self) -> Result<Arc<dyn IdentityNetwork>> { let mut network = self .network .lock() .map_err(|_| Error::Internal("identity resolver lock is poisoned".to_owned()))?; if let Some(network) = network.as_ref() { return Ok(network.clone()); } let initialized: Arc<dyn IdentityNetwork> = Arc::new(NetworkIdentity::new().context( Error::Upstream, "network identity resolver initialization failed", )?); *network = Some(initialized.clone()); Ok(initialized) }}
impl NetworkIdentity { fn new() -> Result<Self> { let dns = dns_resolver()?; let http = Arc::new(OutboundHttp::new( Some(dns.clone()), DeploymentMode::Production, )?); Ok(Self { dns, did: CommonDidResolver::new(CommonDidResolverConfig { plc_directory_url: DEFAULT_PLC_DIRECTORY_URL.to_owned(), http_client: http.clone(), }), https_handle: WellKnownHandleResolver::new(WellKnownHandleResolverConfig { http_client: http.clone(), }), http, }) }}
#[async_trait::async_trait]impl IdentityNetwork for NetworkIdentity { async fn resolve_dns_handle(&self, handle: &Handle) -> Result<Option<Did>> { let query = format!("_atproto.{}.", handle.as_str()); let lookup = self .dns .txt_lookup(query) .await .context(Error::Upstream, "DNS TXT lookup failed")?; let records = lookup.answers().iter().filter_map(|answer| { let RData::TXT(txt) = &answer.data else { return None; }; Some(txt.txt_data.concat()) }); select_dns_handle(records) }
async fn resolve_https_handle(&self, handle: &Handle) -> Result<Did> { self.https_handle.resolve(handle).await.map_err(|error| { if matches!( &error, atrium_identity::Error::NotFound | atrium_identity::Error::HttpStatus(atrium_xrpc::http::StatusCode::NOT_FOUND) ) { handle_not_found("handle does not resolve through DNS or HTTPS") } else { Error::Upstream(format!("HTTPS handle resolution failed: {error}")) } }) }
async fn resolve_did(&self, did: &Did) -> Result<DidDocument> { if !did.as_str().starts_with("did:web:") { return self .did .resolve(did) .await .context(Error::Upstream, "DID resolution failed"); } let url = did_web_url(did)?; let request = Request::builder() .header( atrium_xrpc::http::header::ACCEPT, "application/did+ld+json,application/json", ) .uri(url.as_str()) .body(Vec::new()) .context(Error::Internal, "DID request")?; let response = self .http .send_http(request) .await .context(Error::Upstream, "DID resolution failed")?; if !response.status().is_success() { return Err(Error::Upstream(format!( "DID resolution returned {}", response.status() ))); } serde_json::from_slice(response.body()).context(Error::Upstream, "invalid DID document") }}
fn did_web_url(did: &Did) -> Result<Url> { let method_id = did .as_str() .strip_prefix("did:web:") .ok_or_else(|| Error::Upstream("DID is not did:web".to_owned()))?; let segments = method_id .split(':') .map(|segment| { percent_decode_str(segment) .decode_utf8() .map_err(|_| Error::Upstream("invalid percent encoding in did:web".to_owned())) }) .collect::<Result<Vec<_>>>()?; let (host, path) = (&segments[0], &segments[1..]); if segments .iter() .any(|segment| segment.is_empty() || segment.contains(['/', '?', '#'])) { return Err(Error::Upstream( "did:web contains an invalid path segment".to_owned(), )); } let suffix = if path.is_empty() { "/.well-known/did.json".to_owned() } else { format!("/{}/did.json", path.join("/")) }; let url = Url::parse(&format!("https://{host}{suffix}")) .context(Error::Upstream, "invalid did:web URL")?; validate_https_url(&url).map_err(|error| Error::Upstream(error.to_owned()))?; Ok(url)}
fn select_dns_handle(records: impl IntoIterator<Item = Vec<u8>>) -> Result<Option<Did>> { let dids: HashSet<Did> = records .into_iter() .filter_map(|record| { std::str::from_utf8(&record) .ok()? .strip_prefix("did=")? .parse() .ok() }) .collect(); if dids.len() > 1 { return Err(handle_not_found( "DNS publishes conflicting valid DID records for the handle", )); } Ok(dids.into_iter().next())}
fn handle_not_found(message: &str) -> Error { Error::xrpc("HandleNotFound", message)}
#[cfg(test)]mod tests;