Skip to main content

hyprstream_core/services/oauth/
atproto_session.rs

1//! Native authority adapter for the protected ATProto `getSession` route.
2//!
3//! The resolver is deliberately narrower than a generic DID resolver. It only
4//! answers for a host-form DID whose account label is covered by the configured
5//! account zone, and it requires both durable account-record authority and the
6//! credential profile's exact DID binding. There is no directory enumeration or
7//! request-supplied tenant input on this path.
8
9use std::sync::Arc;
10
11use anyhow::{anyhow, Result};
12use async_trait::async_trait;
13
14use crate::account::AccountZone;
15use crate::auth::UserStore;
16use crate::services::oauth::xrpc::{AtprotoSessionInfo, AtprotoSessionResolver};
17use hyprstream_pds_service::{AccountRecordStore, OAUTH_ACCOUNT_RESOLVER_SUBJECT};
18use hyprstream_rpc::Subject;
19
20/// Production native authority for the standard protected `getSession` seam.
21///
22/// `user_store` is the admitted credential/profile backend. `account_store`
23/// proves that the same DID has a durable, authority-owned hosted account
24/// record. The zone is deployment configuration and is never inferred from a
25/// request or profile field.
26pub(crate) struct NativeAtprotoSessionResolver {
27    user_store: Arc<dyn UserStore>,
28    account_store: Arc<AccountRecordStore>,
29    zone: AccountZone,
30}
31
32impl NativeAtprotoSessionResolver {
33    pub(crate) fn new(
34        user_store: Arc<dyn UserStore>,
35        account_store: Arc<AccountRecordStore>,
36        zone: AccountZone,
37    ) -> Self {
38        Self {
39            user_store,
40            account_store,
41            zone,
42        }
43    }
44
45    /// Extract the one account label represented by a configured-zone did:web.
46    ///
47    /// ATProto host-form DIDs use the DNS host directly for a single-label
48    /// account zone. Reject ports, paths, percent escapes, extra labels and
49    /// case changes instead of normalizing an ambiguous identity.
50    fn label_for_did(&self, did: &str) -> Result<Option<String>> {
51        hosted_label_for_did(&self.zone, did)
52    }
53}
54
55pub(crate) fn hosted_label_for_did(zone: &AccountZone, did: &str) -> Result<Option<String>> {
56    let Some(host) = did.strip_prefix("did:web:") else {
57        return Ok(None);
58    };
59    if host.is_empty()
60        || host != host.to_ascii_lowercase()
61        || host.contains([':', '/', '%'])
62        || !host.is_ascii()
63    {
64        return Err(anyhow!("invalid host-form hosted account DID"));
65    }
66    let suffix = format!(".{}", zone.apex());
67    let Some(label) = host.strip_suffix(&suffix) else {
68        return Ok(None);
69    };
70    if label.is_empty() || label.contains('.') || zone.host_for_label(label)? != host {
71        return Err(anyhow!(
72            "hosted account DID is outside the configured account zone"
73        ));
74    }
75    Ok(Some(label.to_owned()))
76}
77
78#[async_trait]
79impl AtprotoSessionResolver for NativeAtprotoSessionResolver {
80    async fn resolve_session(&self, did: &str) -> Result<Option<AtprotoSessionInfo>> {
81        let Some(label) = self.label_for_did(did)? else {
82            // did:plc and foreign did:web identities are federated identities
83            // for this PDS and must not be answered from local profile data.
84            return Ok(None);
85        };
86
87        let Some(profile) = self.user_store.get_profile(&label).await? else {
88            return Ok(None);
89        };
90        if profile.atproto_did.as_deref() != Some(did) {
91            return Ok(None);
92        }
93
94        let authority = Subject::new(OAUTH_ACCOUNT_RESOLVER_SUBJECT);
95        if self
96            .account_store
97            .resolve_tenant_for_hosted_did(&authority, did)
98            .await?
99            .is_none()
100        {
101            return Ok(None);
102        }
103
104        let active = profile.active.unwrap_or(true);
105        Ok(Some(AtprotoSessionInfo {
106            handle: self.zone.host_for_label(&label)?,
107            did_doc: None,
108            email: profile.email,
109            email_confirmed: profile.email_verified,
110            email_auth_factor: None,
111            active,
112            status: (!active).then(|| "deactivated".to_owned()),
113        }))
114    }
115}
116
117#[cfg(test)]
118mod tests {
119    use super::*;
120
121    #[test]
122    fn only_exact_single_label_zone_hosts_are_accepted() -> Result<()> {
123        let zone = AccountZone::new("accounts.example.test")?;
124        assert_eq!(
125            hosted_label_for_did(&zone, "did:web:alice.accounts.example.test")?,
126            Some("alice".to_owned())
127        );
128        assert!(hosted_label_for_did(&zone, "did:web:a.b.accounts.example.test").is_err());
129        assert!(hosted_label_for_did(&zone, "did:web:alice.accounts.example.test:8443").is_err());
130        assert!(hosted_label_for_did(&zone, "did:web:Alice.accounts.example.test").is_err());
131        assert_eq!(
132            hosted_label_for_did(&zone, "did:web:other.example.test")?,
133            None
134        );
135        assert_eq!(hosted_label_for_did(&zone, "did:plc:abc")?, None);
136        Ok(())
137    }
138}