use std::time::Duration; use hickory_resolver::TokioResolver; use hickory_resolver::proto::rr::RecordData; use hickory_resolver::proto::rr::rdata::TXT; use jacquard_common::Bos; use jacquard_common::deps::fluent_uri::Uri; use jacquard_common::deps::smol_str::SmolStr; use jacquard_common::types::did_doc::DidDocument; use jacquard_common::types::string::Did as AtDid; use jacquard_common::xrpc::XrpcClient; use jacquard_common::xrpc::atproto::GetSession; use jacquard_identity::JacquardResolver; use jacquard_identity::resolver::{IdentityResolver, ResolverOptions}; use jacquard_oauth::atproto::{AtprotoClientMetadata, GrantType, atproto_client_metadata}; use jacquard_oauth::authstore::ClientAuthStore; use jacquard_oauth::client::OAuthClient; use jacquard_oauth::keyset::Keyset; use jacquard_oauth::scopes::Scopes; use jacquard_oauth::session::ClientData; use jacquard_oauth::types::{AuthorizeOptions, CallbackParams, OAuthClientMetadata}; use url::Url; use crate::authstore::SqliteAuthStore; use crate::config::ServerConfig; use crate::identity::{Did, Handle, Identity}; use crate::oidc::EmailClaim; use crate::outbound::{self, Policy}; pub trait AtprotoLogin: Send + Sync { fn start( &self, handle: &Handle, state: &str, want_email: bool, ) -> impl Future> + Send; fn finish( &self, handle: &Handle, params: &[(String, String)], want_email: bool, ) -> impl Future> + Send; fn resolve(&self, handle: &Handle) -> impl Future> + Send; } #[derive(Clone, Debug, Eq, PartialEq)] pub struct Login { pub identity: Identity, pub email: Option, } #[derive(Clone, Debug, Eq, PartialEq)] pub struct DocumentSummary { pub lists_handle: bool, pub primary: Option, } impl DocumentSummary { pub fn of + AsRef>(document: &DidDocument, handle: &Handle) -> Self { let mut aliases = document .also_known_as .iter() .flatten() .filter_map(|alias| AsRef::::as_ref(alias).strip_prefix("at://")) .filter_map(|alias| Handle::parse(alias).ok()); let primary = aliases.next(); let lists_handle = primary.as_ref() == Some(handle) || aliases.any(|alias| &alias == handle); Self { lists_handle, primary, } } } trait IdentitySource: Sync { fn did_of(&self, handle: &Handle) -> impl Future> + Send; fn summary_of( &self, did: &Did, handle: &Handle, ) -> impl Future> + Send; } async fn verify_identity( source: &impl IdentitySource, handle: &Handle, authenticated: &str, resolved: Did, ) -> Result { if resolved.as_str() != authenticated { return Err(LoginError::HandleMismatch { handle: handle.clone(), authenticated: authenticated.to_owned(), }); } let document = source .summary_of(&resolved, handle) .await .map_err(|reason| LoginError::HandleResolution { handle: handle.clone(), reason, })?; if !document.lists_handle { return Err(LoginError::HandleNotListed { handle: handle.clone(), did: authenticated.to_owned(), }); } let name = match document.primary { Some(primary) if &primary != handle => { let primary_did = source.did_of(&primary).await.map_err(|error| { LoginError::PrimaryHandleUnverified { primary: primary.clone(), did: authenticated.to_owned(), reason: error.to_string(), } })?; if primary_did != resolved { return Err(LoginError::PrimaryHandleUnverified { primary, did: authenticated.to_owned(), reason: format!("it resolves to {}", primary_did.as_str()), }); } primary } _ => handle.clone(), }; Ok(Identity { did: resolved, handle: name, }) } fn email_claim(address: Option<&str>, confirmed: Option) -> Option { address.map(|address| EmailClaim { address: address.to_owned(), verified: confirmed == Some(true), }) } fn did_from_well_known(status: http::StatusCode, body: &[u8]) -> Result { if !status.is_success() { return Err(format!("well-known returned {status}")); } Did::parse(String::from_utf8_lossy(body).trim()).map_err(|error| error.to_string()) } pub const DNS_TIMEOUT: Duration = Duration::from_secs(5); pub const HTTP_TIMEOUT: Duration = Duration::from_secs(10); pub const UPSTREAM_TIMEOUT: Duration = Duration::from_secs(30); pub const WELL_KNOWN_MAX_BYTES: usize = 1024; #[derive(Debug, thiserror::Error)] pub enum LoginError { #[error("AT Protocol login failed: {0}")] Upstream(String), #[error("cannot build the handle resolver: {0}")] Resolver(String), #[error(transparent)] Outbound(#[from] outbound::OutboundError), #[error("cannot resolve handle {handle}: {reason}")] HandleResolution { handle: Handle, reason: String }, #[error("invalid AT Protocol client metadata: {0}")] Metadata(String), #[error("callback is missing the authorization code")] MissingCode, #[error("authorization server returned an invalid DID: {0}")] InvalidDid(String), #[error("handle {handle} resolves to a different account than {authenticated}")] HandleMismatch { handle: Handle, authenticated: String, }, #[error("the DID document of {did} does not list {handle}")] HandleNotListed { handle: Handle, did: String }, #[error("the primary handle {primary} of {did} does not verify: {reason}")] PrimaryHandleUnverified { primary: Handle, did: String, reason: String, }, } pub fn client_metadata( config: &ServerConfig, ) -> Result, LoginError> { let client_id = parse_uri(config.endpoint("/client-metadata.json"))?; let callback = parse_uri(config.endpoint("/atproto/callback"))?; let mut metadata = AtprotoClientMetadata::new(vec![callback], client_id, Some(atproto_scopes(true)?)) .with_client_name(SmolStr::new(&config.client_name)); metadata.grant_types = vec![GrantType::AuthorizationCode]; metadata.jwks_uri = Some(parse_uri(config.endpoint("/client-jwks.json"))?); Ok(metadata) } pub fn public_client_metadata( metadata: &AtprotoClientMetadata, keyset: &Keyset, ) -> Result { atproto_client_metadata(metadata, &Some(keyset.clone())) .map_err(|error| LoginError::Metadata(error.to_string())) } fn atproto_scopes(want_email: bool) -> Result, LoginError> { let scopes = if want_email { "atproto transition:email" } else { "atproto" }; Scopes::new(SmolStr::new_static(scopes)) .map_err(|error| LoginError::Metadata(error.to_string())) } fn parse_uri(value: String) -> Result, LoginError> { Uri::parse(value).map_err(|(error, _)| LoginError::Metadata(error.to_string())) } pub struct HandleResolver { dns: TokioResolver, http: outbound::Client, } impl HandleResolver { pub fn from_system(http: outbound::Client) -> Result { let mut builder = TokioResolver::builder_tokio() .map_err(|error| LoginError::Resolver(error.to_string()))?; builder.options_mut().timeout = DNS_TIMEOUT; builder.options_mut().attempts = 2; Ok(Self { dns: builder .build() .map_err(|error| LoginError::Resolver(error.to_string()))?, http, }) } pub async fn resolve(&self, handle: &Handle) -> Result { let (did, via) = match self.resolve_txt(handle).await { Some(did) => (did, "dns"), None => (self.resolve_well_known(handle).await?, "well-known"), }; tracing::debug!( handle = handle.as_str(), did = did.as_str(), via, "handle resolved" ); Ok(did) } async fn resolve_txt(&self, handle: &Handle) -> Option { let name = format!("_atproto.{}.", handle.as_str()); let lookup = self.dns.txt_lookup(name).await.ok()?; let records = lookup .answers() .iter() .filter_map(|record| TXT::try_borrow(&record.data)) .flat_map(|txt| &txt.txt_data) .map(|data| String::from_utf8_lossy(data).into_owned()); did_from_txt(records) } async fn resolve_well_known(&self, handle: &Handle) -> Result { let failure = |reason: String| LoginError::HandleResolution { handle: handle.clone(), reason, }; let url = Url::parse(&format!( "https://{}{}", handle.as_str(), outbound::HANDLE_WELL_KNOWN_PATH )) .map_err(|error| failure(error.to_string()))?; let (status, body) = self .http .get(&url) .await .map_err(|error| failure(error.to_string()))?; did_from_well_known(status, &body).map_err(failure) } } pub fn did_from_txt(records: impl IntoIterator) -> Option { records.into_iter().find_map(|record| { record .strip_prefix("did=") .and_then(|did| Did::parse(did.trim()).ok()) }) } pub struct JacquardLogin { client: OAuthClient, SqliteAuthStore>, store: SqliteAuthStore, resolver: HandleResolver, documents: JacquardResolver, } impl JacquardLogin { pub fn new( config: &ServerConfig, store: SqliteAuthStore, keyset: Keyset, ) -> Result { let client_data = ClientData { keyset: Some(keyset), config: client_metadata(config)?, }; let http = outbound::Client::new( Policy::new(config.allow_private_fetch), UPSTREAM_TIMEOUT, outbound::MAX_BODY_BYTES, )?; let documents = http.limited(HTTP_TIMEOUT, outbound::MAX_BODY_BYTES); let well_known = http.limited(HTTP_TIMEOUT, WELL_KNOWN_MAX_BYTES); Ok(Self { client: OAuthClient::new(store.clone(), client_data, http), store, resolver: HandleResolver::from_system(well_known)?, documents: JacquardResolver::new(documents, ResolverOptions::default()), }) } async fn document_summary( &self, did: &Did, handle: &Handle, ) -> Result { let did: AtDid = AtDid::new_owned(did.as_str()).map_err(|error| error.to_string())?; let response = self .documents .resolve_did_doc(&did) .await .map_err(|error| { tracing::debug!(%error, "DID document fetch failed"); "the DID document could not be fetched".to_owned() })?; let document = response .parse() .map_err(|_| "the DID document could not be parsed".to_owned())?; Ok(DocumentSummary::of(&document, handle)) } } impl IdentitySource for JacquardLogin { async fn did_of(&self, handle: &Handle) -> Result { self.resolver.resolve(handle).await } async fn summary_of(&self, did: &Did, handle: &Handle) -> Result { self.document_summary(did, handle).await } } impl AtprotoLogin for JacquardLogin { async fn resolve(&self, handle: &Handle) -> Result { self.resolver.resolve(handle).await } async fn start( &self, handle: &Handle, state: &str, want_email: bool, ) -> Result { let options = AuthorizeOptions:: { redirect_uri: None, scopes: atproto_scopes(want_email)?, prompt: None, state: Some(SmolStr::new(state)), }; let did = self.resolver.resolve(handle).await?; let target = self .client .start_auth(did.as_str(), options) .await .map_err(|error| LoginError::Upstream(error.to_string()))?; tracing::debug!(did = did.as_str(), "authorization request pushed"); Url::parse(&target).map_err(|error| LoginError::Upstream(error.to_string())) } async fn finish( &self, handle: &Handle, params: &[(String, String)], want_email: bool, ) -> Result { let value = |key: &str| { params .iter() .find(|(name, _)| name == key) .map(|(_, value)| SmolStr::new(value)) }; let code = value("code").ok_or(LoginError::MissingCode)?; let session = self .client .callback(CallbackParams { code, state: value("state"), iss: value("iss"), }) .await .map_err(|error| LoginError::Upstream(error.to_string()))?; let (authenticated, session_id) = session.session_info().await; let email = if want_email { let output = match session.send(GetSession).await { Ok(response) => response.into_output().map_err(|error| error.to_string()), Err(error) => Err(error.to_string()), }; match output { Ok(output) => email_claim(output.email.as_deref(), output.email_confirmed), Err(error) => { tracing::debug!(error, "getSession yielded no email"); None } } } else { None }; let resolved = self.resolver.resolve(handle).await; let logout = session.logout().await; tracing::debug!(failure = ?logout.err(), "PDS session closed"); let _ = self .store .delete_session(&authenticated, session_id.as_str()) .await; let identity = verify_identity(self, handle, authenticated.as_ref(), resolved?).await?; Ok(Login { identity, email }) } } #[cfg(test)] mod tests { use std::collections::HashMap; use super::*; const ALICE: &str = "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa"; const MALLORY: &str = "did:plc:mmmmmmmmmmmmmmmmmmmmmmmm"; fn handle(value: &str) -> Handle { Handle::parse(value).expect("handle") } fn did(value: &str) -> Did { Did::parse(value).expect("did") } #[derive(Default)] struct World { handles: HashMap<&'static str, &'static str>, aliases: Option>, } impl IdentitySource for World { async fn did_of(&self, handle: &Handle) -> Result { self.handles .get(handle.as_str()) .map(|value| did(value)) .ok_or_else(|| LoginError::HandleResolution { handle: handle.clone(), reason: "no such handle".to_owned(), }) } async fn summary_of(&self, _: &Did, handle: &Handle) -> Result { let aliases = self.aliases.as_ref().ok_or("the DID document is gone")?; let document: DidDocument = serde_json::from_value(serde_json::json!({ "id": ALICE, "alsoKnownAs": aliases, })) .map_err(|error| error.to_string())?; Ok(DocumentSummary::of(&document, handle)) } } #[tokio::test] async fn an_identity_is_the_authenticated_did_under_its_verified_primary_handle() { let listed = Some(vec!["at://alice.example.com", "at://alias.example.com"]); let cases = [ ( "the primary handle", "alice.example.com", ALICE, vec![("alice.example.com", ALICE)], listed.clone(), Ok("alice.example.com"), ), ( "a secondary handle takes the primary name", "alias.example.com", ALICE, vec![("alice.example.com", ALICE)], listed.clone(), Ok("alice.example.com"), ), ( "aliases that are not handles are skipped", "alice.example.com", ALICE, vec![], Some(vec![ "https://alice.example", "at://not a handle", "at://alice.example.com", ]), Ok("alice.example.com"), ), ( "the handle resolved to another account", "alice.example.com", MALLORY, vec![], listed.clone(), Err("resolves to a different account"), ), ( "the document does not list the handle", "squatter.example.com", ALICE, vec![], listed.clone(), Err("does not list squatter.example.com"), ), ( "the document lists nothing", "alice.example.com", ALICE, vec![], Some(vec![]), Err("does not list alice.example.com"), ), ( "the document cannot be fetched", "alice.example.com", ALICE, vec![], None, Err("the DID document is gone"), ), ( "the primary handle does not resolve", "alias.example.com", ALICE, vec![], listed.clone(), Err("alice.example.com of did:plc:aaaaaaaaaaaaaaaaaaaaaaaa does not verify"), ), ( "the primary handle belongs to someone else", "alias.example.com", ALICE, vec![("alice.example.com", MALLORY)], listed, Err("it resolves to did:plc:mmmmmmmmmmmmmmmmmmmmmmmm"), ), ]; for (name, login, authenticated, handles, aliases, expected) in cases { let world = World { handles: handles.into_iter().collect(), aliases, }; let outcome = verify_identity(&world, &handle(login), authenticated, did(ALICE)).await; match (outcome, expected) { (Ok(identity), Ok(primary)) => { assert_eq!(identity.did, did(ALICE), "{name}"); assert_eq!(identity.handle, handle(primary), "{name}"); } (Err(error), Err(message)) => { assert!(error.to_string().contains(message), "{name}: {error}"); } (outcome, expected) => panic!("{name}: {outcome:?}, expected {expected:?}"), } } } #[test] fn untrusted_pds_and_resolver_answers_are_read_strictly() { let records = [ "v=spf1 -all".to_owned(), "did=not a did".to_owned(), "did=did:web:carol.pds.test".to_owned(), "did=did:plc:aaaaaaaaaaaaaaaaaaaaaaaa".to_owned(), ]; assert_eq!( did_from_txt(records).as_ref().map(Did::as_str), Some("did:web:carol.pds.test") ); assert_eq!(did_from_txt(["did=".to_owned()]), None); assert_eq!(did_from_txt([]), None); let ok = http::StatusCode::OK; assert_eq!( did_from_well_known(ok, b" did:web:carol.pds.test\n"), Ok(did("did:web:carol.pds.test")) ); assert!(did_from_well_known(ok, b"not found").is_err()); assert!(did_from_well_known(ok, &[0xff, 0xfe]).is_err()); assert_eq!( did_from_well_known(http::StatusCode::NOT_FOUND, ALICE.as_bytes()), Err("well-known returned 404 Not Found".to_owned()) ); assert_eq!(email_claim(None, Some(true)), None); for (confirmed, verified) in [(Some(true), true), (Some(false), false), (None, false)] { assert_eq!( email_claim(Some("alice@example.com"), confirmed), Some(EmailClaim { address: "alice@example.com".to_owned(), verified, }), "{confirmed:?}" ); } } }