Skip to main content

hyprstream_core/services/oauth/
user_service.rs

1//! Shared user CRUD logic for SCIM HTTP and ZMQ RPC transports.
2//!
3//! Both transports call into `UserService` — no duplicated CRUD logic.
4
5use std::sync::Arc;
6
7use anyhow::{anyhow, Result};
8use base64::{engine::general_purpose::STANDARD, Engine};
9use ed25519_dalek::VerifyingKey;
10
11use crate::auth::{
12    decode_pubkey_base64, ProductionUserStore, PubkeyEntry, UserFilter, UserProfilePatch, UserStore,
13};
14
15/// Shared user information type (SCIM-informed).
16#[derive(Debug, Clone)]
17pub struct UserInfo {
18    pub username: String,
19    pub sub: String,
20    pub pubkey_base64: String,
21    pub name: Option<String>,
22    pub email: Option<String>,
23    pub email_verified: bool,
24    pub active: bool,
25    pub external_id: Option<String>,
26    pub atproto_did: Option<String>,
27    pub pubkeys: Vec<PubkeyInfo>,
28}
29
30/// Pubkey info for API responses.
31#[derive(Debug, Clone)]
32pub struct PubkeyInfo {
33    pub fingerprint: String,
34    pub pubkey_base64: String,
35    pub label: Option<String>,
36    pub created_at: i64,
37    pub last_used_at: Option<i64>,
38    pub algorithm: crate::auth::KeyAlgorithm,
39    /// Bound ML-DSA-65 verifying key bytes for a hybrid record (#439); `None`
40    /// for classical Ed25519.
41    pub pq_pubkey: Option<Vec<u8>>,
42}
43
44impl From<&PubkeyEntry> for PubkeyInfo {
45    fn from(entry: &PubkeyEntry) -> Self {
46        Self {
47            fingerprint: entry.fingerprint.clone(),
48            pubkey_base64: STANDARD.encode(entry.pubkey.as_bytes()),
49            label: entry.label.clone(),
50            created_at: entry.created_at,
51            last_used_at: entry.last_used_at,
52            algorithm: entry.algorithm,
53            pq_pubkey: entry.pq_pubkey.clone(),
54        }
55    }
56}
57
58/// Paginated user list result.
59#[derive(Debug, Clone)]
60pub struct UserList {
61    pub users: Vec<UserInfo>,
62    pub total_results: usize,
63}
64
65/// Fields to update on a user.
66#[derive(Debug, Clone, Default)]
67pub struct UserUpdate {
68    pub name: Option<Option<String>>,
69    pub email: Option<Option<String>>,
70    pub email_verified: Option<bool>,
71    pub external_id: Option<Option<String>>,
72    /// The account's mapped atproto DID (#1113 r5 / #1124 seam).
73    pub atproto_did: Option<Option<String>>,
74}
75
76/// Shared user CRUD service used by both SCIM HTTP and ZMQ RPC transports.
77pub struct UserService {
78    store: ProductionUserStore,
79}
80
81impl UserService {
82    pub(crate) fn new(store: ProductionUserStore) -> Self {
83        Self { store }
84    }
85
86    /// Register a new user. If `pubkey_base64` is non-empty, adds it as the first key.
87    pub async fn register(&self, username: &str, pubkey_base64: &str) -> Result<UserInfo> {
88        self.store.register(username).await?;
89
90        if !pubkey_base64.is_empty() {
91            let pubkey = decode_pubkey_base64(pubkey_base64)?;
92            self.store.add_pubkey(username, pubkey, None).await?;
93        }
94
95        self.get(username)
96            .await?
97            .ok_or_else(|| anyhow!("User '{}' not found after registration", username))
98    }
99
100    /// Get a user by username.
101    pub async fn get(&self, username: &str) -> Result<Option<UserInfo>> {
102        let profile = self.store.get_profile(username).await?;
103
104        match profile {
105            Some(profile) => {
106                let pubkeys = self.store.list_pubkeys(username).await?;
107                let sub = profile
108                    .sub
109                    .ok_or_else(|| anyhow!("User '{username}' has no stable subject"))?;
110                // For backward compat, use first pubkey as the primary
111                let primary_pubkey = pubkeys
112                    .first()
113                    .map(|pk| STANDARD.encode(pk.pubkey.as_bytes()))
114                    .unwrap_or_default();
115
116                Ok(Some(UserInfo {
117                    username: username.to_owned(),
118                    sub,
119                    pubkey_base64: primary_pubkey,
120                    name: profile.name,
121                    email: profile.email,
122                    email_verified: profile.email_verified.unwrap_or(false),
123                    active: profile.active.unwrap_or(true),
124                    external_id: profile.external_id,
125                    atproto_did: profile.atproto_did,
126                    pubkeys: pubkeys.iter().map(PubkeyInfo::from).collect(),
127                }))
128            }
129            None => Ok(None),
130        }
131    }
132
133    /// List/search users with SCIM-aligned filtering, sorting, and pagination.
134    pub async fn list(&self, filter: &UserFilter) -> Result<UserList> {
135        let results = self.store.search(filter).await?;
136
137        // Total count is before pagination (we need a separate count without pagination).
138        // For simplicity, search() already applies pagination, so we re-run without
139        // pagination to get total. This is fine for in-memory stores with small user counts.
140        let total_filter = UserFilter {
141            count: None,
142            start_index: None,
143            ..filter.clone()
144        };
145        let total_results = self.store.search(&total_filter).await?.len();
146
147        let users = results
148            .into_iter()
149            .map(|(username, profile)| -> Result<UserInfo> {
150                let sub = profile
151                    .sub
152                    .ok_or_else(|| anyhow!("User '{username}' has no stable subject"))?;
153                Ok(UserInfo {
154                    username,
155                    sub,
156                    pubkey_base64: String::new(), // Omitted in list for size; use get() for full info
157                    name: profile.name,
158                    email: profile.email,
159                    email_verified: profile.email_verified.unwrap_or(false),
160                    active: profile.active.unwrap_or(true),
161                    external_id: profile.external_id,
162                    atproto_did: profile.atproto_did,
163                    pubkeys: vec![], // Omitted in list
164                })
165            })
166            .collect::<Result<Vec<_>>>()?;
167
168        Ok(UserList {
169            users,
170            total_results,
171        })
172    }
173
174    /// Update a user's profile fields.
175    pub async fn update(&self, username: &str, update: UserUpdate) -> Result<UserInfo> {
176        self.store
177            .get_profile(username)
178            .await?
179            .ok_or_else(|| anyhow!("User '{}' not found", username))?;
180
181        let patch = UserProfilePatch {
182            name: update.name,
183            email: update.email,
184            email_verified: update.email_verified.map(Some),
185            external_id: update.external_id,
186            atproto_did: update.atproto_did,
187            ..Default::default()
188        };
189        self.store.set_profile(username, patch).await?;
190
191        self.get(username)
192            .await?
193            .ok_or_else(|| anyhow!("User '{}' not found after update", username))
194    }
195
196    /// Suspend a user (set active = false).
197    pub async fn suspend(&self, username: &str) -> Result<()> {
198        self.store.set_active(username, false).await
199    }
200
201    /// Resume a suspended user (set active = true).
202    pub async fn resume(&self, username: &str) -> Result<()> {
203        self.store.set_active(username, true).await
204    }
205
206    /// Permanently remove a user.
207    pub async fn remove(&self, username: &str) -> Result<bool> {
208        self.store.remove(username).await
209    }
210
211    /// Add a public key to a user. Returns the new PubkeyInfo.
212    pub async fn add_pubkey(
213        &self,
214        username: &str,
215        pubkey: VerifyingKey,
216        label: Option<String>,
217    ) -> Result<PubkeyInfo> {
218        let fingerprint = self.store.add_pubkey(username, pubkey, label).await?;
219        let entries = self.store.list_pubkeys(username).await?;
220        entries
221            .iter()
222            .find(|e| e.fingerprint == fingerprint)
223            .map(PubkeyInfo::from)
224            .ok_or_else(|| anyhow!("pubkey not found after insert"))
225    }
226
227    /// Remove a public key by fingerprint. Returns true if removed.
228    pub async fn remove_pubkey(&self, username: &str, fingerprint: &str) -> Result<bool> {
229        self.store.remove_pubkey(username, fingerprint).await
230    }
231
232    /// List all public keys for a user.
233    pub async fn list_pubkeys(&self, username: &str) -> Result<Vec<PubkeyInfo>> {
234        let entries = self.store.list_pubkeys(username).await?;
235        Ok(entries.iter().map(PubkeyInfo::from).collect())
236    }
237
238    /// Get the underlying store for direct access (e.g., by OAuth handlers).
239    pub(crate) fn store(&self) -> Arc<dyn UserStore> {
240        self.store.clone_inner()
241    }
242}