1#![cfg_attr(
13 all(feature = "encrypted-account-admission", not(test)),
14 allow(dead_code, unused_imports)
15)]
16
17use anyhow::{anyhow, Context, Result};
18use async_trait::async_trait;
19use capnp::message::{Builder, ReaderOptions};
20use ed25519_dalek::VerifyingKey;
21use parking_lot::Mutex;
22use std::io::Cursor;
23use std::path::Path;
24
25use super::user_store::{
26 matches_filter, pubkey_fingerprint, AccountKeyCustody, DeviceRecord, DeviceStore,
27 ExternalIdentityBinding, HostedAccountProvisionError, HostedAccountProvisioning, KeyAlgorithm,
28 PubkeyEntry, UserFilter, UserProfile, UserProfilePatch, UserStore,
29};
30
31const USER_PREFIX: &[u8] = b"user:";
32const PUBKEY_PREFIX: &[u8] = b"pubkey:";
33const ACCOUNT_AUTH_PREFIX: &[u8] = b"account-auth:";
34
35fn user_key(username: &str) -> Vec<u8> {
36 let mut key = USER_PREFIX.to_vec();
37 key.extend_from_slice(username.as_bytes());
38 key
39}
40
41fn pubkey_key(fingerprint: &str) -> Vec<u8> {
42 let mut key = PUBKEY_PREFIX.to_vec();
43 key.extend_from_slice(fingerprint.as_bytes());
44 key
45}
46
47fn account_auth_key(username: &str) -> Vec<u8> {
48 let mut key = ACCOUNT_AUTH_PREFIX.to_vec();
49 key.extend_from_slice(username.as_bytes());
50 key
51}
52
53fn strip_user_prefix(key: &[u8]) -> Option<&str> {
54 key.strip_prefix(USER_PREFIX)
55 .and_then(|s| std::str::from_utf8(s).ok())
56}
57
58fn text_or_none(reader: capnp::Result<capnp::text::Reader<'_>>) -> Option<String> {
60 reader
61 .ok()
62 .filter(|t| !t.is_empty())
63 .and_then(|t| t.to_string().ok())
64}
65
66#[derive(Debug, Clone)]
68struct StoredPubkey {
69 fingerprint: String,
70 pubkey_base64: String,
71 label: Option<String>,
72 created_at: i64,
73 last_used_at: i64, algorithm: KeyAlgorithm,
76 pq_pubkey: Option<Vec<u8>>,
79}
80
81#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
86struct StoredAccountAuth {
87 #[serde(default, skip_serializing_if = "Option::is_none")]
88 key_custody: Option<AccountKeyCustody>,
89 #[serde(default, skip_serializing_if = "Vec::is_empty")]
90 external_identities: Vec<ExternalIdentityBinding>,
91}
92
93pub struct RocksDbUserStore {
94 db: rocksdb::DB,
95 provisioning_lock: Mutex<()>,
99}
100
101impl RocksDbUserStore {
102 pub(crate) fn open_admitted(
104 credentials_dir: &Path,
105 _permit: &super::production_user_store::ProductionStorePermit,
106 ) -> Result<Self> {
107 Self::open_inner(credentials_dir)
108 }
109
110 #[cfg(test)]
111 pub(crate) fn open(credentials_dir: &Path) -> Result<Self> {
112 Self::open_inner(credentials_dir)
113 }
114
115 fn open_inner(credentials_dir: &Path) -> Result<Self> {
116 let db_path = credentials_dir.join("users.db");
117 std::fs::create_dir_all(&db_path)?;
118
119 let mut opts = rocksdb::Options::default();
120 opts.create_if_missing(true);
121
122 let db = rocksdb::DB::open(&opts, &db_path)
123 .with_context(|| format!("Failed to open RocksDB at {:?}", db_path))?;
124
125 Ok(Self {
126 db,
127 provisioning_lock: Mutex::new(()),
128 })
129 }
130
131 #[cfg(test)]
136 #[allow(dead_code)]
137 pub(crate) fn open_readonly(credentials_dir: &Path) -> Result<Self> {
138 let db_path = credentials_dir.join("users.db");
139
140 let mut opts = rocksdb::Options::default();
141 opts.create_if_missing(false);
142
143 let db = rocksdb::DB::open_for_read_only(&opts, &db_path, false)
144 .with_context(|| format!("Failed to open RocksDB (read-only) at {:?}", db_path))?;
145
146 Ok(Self {
147 db,
148 provisioning_lock: Mutex::new(()),
149 })
150 }
151
152 pub fn is_writable(&self) -> bool {
157 true
158 }
159
160 const FLAG_EMAIL_VERIFIED: u8 = 0x01;
162 const FLAG_ACTIVE: u8 = 0x02;
163
164 fn serialize_profile(
167 sub: &str,
168 profile: &UserProfile,
169 pubkeys: &[StoredPubkey],
170 ) -> Result<Vec<u8>> {
171 let mut flags: u8 = 0;
172 if profile.email_verified.is_some() {
173 flags |= Self::FLAG_EMAIL_VERIFIED;
174 }
175 if profile.active.is_some() {
176 flags |= Self::FLAG_ACTIVE;
177 }
178
179 let mut message = Builder::new_default();
180 {
181 let mut ui = message.init_root::<hyprstream_rpc_std::oauth_capnp::user_info::Builder>();
182 ui.set_sub(sub);
183 if let Some(ref name) = profile.name {
184 ui.set_name(name);
185 }
186 if let Some(ref email) = profile.email {
187 ui.set_email(email);
188 }
189 ui.set_email_verified(profile.email_verified.unwrap_or(false));
190 ui.set_active(profile.active.unwrap_or(false));
191 if let Some(ref eid) = profile.external_id {
192 ui.set_external_id(eid);
193 }
194 if let Some(ref did) = profile.atproto_did {
195 ui.set_atproto_did(did);
196 }
197 let mut pk_list = ui.init_pubkeys(pubkeys.len() as u32);
199 for (i, pk) in pubkeys.iter().enumerate() {
200 let mut entry = pk_list.reborrow().get(i as u32);
201 entry.set_fingerprint(&pk.fingerprint);
202 entry.set_pubkey_base64(&pk.pubkey_base64);
203 if let Some(ref label) = pk.label {
204 entry.set_label(label);
205 }
206 entry.set_created_at(pk.created_at);
207 entry.set_last_used_at(pk.last_used_at);
208 entry.set_algorithm(pk.algorithm.as_str());
209 match (pk.algorithm.is_hybrid(), &pk.pq_pubkey) {
212 (true, Some(vk)) => entry.set_pq_pubkey(vk),
213 (false, None) => {}
214 (true, None) => anyhow::bail!(
215 "hybrid pubkey {} has no ML-DSA-65 key material (refusing to persist)",
216 pk.fingerprint
217 ),
218 (false, Some(_)) => anyhow::bail!(
219 "classical pubkey {} carries ML-DSA-65 key material (refusing to persist)",
220 pk.fingerprint
221 ),
222 }
223 }
224 }
225 let mut bytes = vec![flags];
226 capnp::serialize::write_message(&mut bytes, &message)?;
227 Ok(bytes)
228 }
229
230 fn deserialize_profile(bytes: &[u8]) -> Result<(String, UserProfile, Vec<StoredPubkey>)> {
232 if bytes.is_empty() {
233 anyhow::bail!("empty profile data");
234 }
235 let flags = bytes[0];
236 let cursor = Cursor::new(&bytes[1..]);
237 let reader = capnp::serialize::read_message(cursor, ReaderOptions::new())?;
238 let ui = reader.get_root::<hyprstream_rpc_std::oauth_capnp::user_info::Reader>()?;
239
240 let sub = ui.get_sub()?.to_string()?;
241 let profile = UserProfile {
242 sub: Some(sub.clone()),
243 name: text_or_none(ui.get_name()),
244 email: text_or_none(ui.get_email()),
245 email_verified: if flags & Self::FLAG_EMAIL_VERIFIED != 0 {
246 Some(ui.get_email_verified())
247 } else {
248 None
249 },
250 active: if flags & Self::FLAG_ACTIVE != 0 {
251 Some(ui.get_active())
252 } else {
253 None
254 },
255 external_id: text_or_none(ui.get_external_id()),
256 atproto_did: text_or_none(ui.get_atproto_did()),
257 key_custody: None,
258 external_identities: Vec::new(),
259 };
260
261 let mut pubkeys = Vec::new();
263 if ui.has_pubkeys() {
264 for pk in ui.get_pubkeys()? {
265 let fingerprint = pk.get_fingerprint()?.to_string()?;
266 let algorithm = match text_or_none(pk.get_algorithm()) {
271 Some(s) => KeyAlgorithm::parse(&s)?,
272 None => KeyAlgorithm::default(),
273 };
274 let pq_pubkey = match pk.get_pq_pubkey() {
278 Ok(bytes) if !bytes.is_empty() => Some(bytes.to_vec()),
279 _ => None,
280 };
281 match (algorithm.is_hybrid(), &pq_pubkey) {
282 (true, Some(_)) | (false, None) => {}
283 (true, None) => anyhow::bail!(
284 "hybrid pubkey record {fingerprint} is missing its ML-DSA-65 \
285 key material (refusing to read — fail closed)"
286 ),
287 (false, Some(_)) => anyhow::bail!(
288 "classical pubkey record {fingerprint} carries unexpected \
289 ML-DSA-65 key material (refusing to read)"
290 ),
291 }
292 pubkeys.push(StoredPubkey {
293 fingerprint,
294 pubkey_base64: pk.get_pubkey_base64()?.to_string()?,
295 label: text_or_none(pk.get_label()),
296 created_at: pk.get_created_at(),
297 last_used_at: pk.get_last_used_at(),
298 algorithm,
299 pq_pubkey,
300 });
301 }
302 }
303
304 Ok((sub, profile, pubkeys))
305 }
306
307 fn get_raw(&self, username: &str) -> Result<Option<(String, UserProfile, Vec<StoredPubkey>)>> {
308 let key = user_key(username);
309 match self.db.get(&key)? {
310 Some(bytes) => {
311 let (sub, mut profile, pubkeys) = Self::deserialize_profile(&bytes)
312 .with_context(|| format!("Failed to deserialize profile for '{}'", username))?;
313 if let Some(metadata) = self.db.get(account_auth_key(username))? {
314 let stored: StoredAccountAuth = serde_json::from_slice(&metadata)
315 .with_context(|| {
316 format!(
317 "Failed to deserialize hosted-account auth metadata for '{}'",
318 username
319 )
320 })?;
321 profile.key_custody = stored.key_custody;
322 profile.external_identities = stored.external_identities;
323 }
324 Ok(Some((sub, profile, pubkeys)))
325 }
326 None => Ok(None),
327 }
328 }
329
330 fn put_user(
332 &self,
333 username: &str,
334 sub: &str,
335 profile: &UserProfile,
336 pubkeys: &[StoredPubkey],
337 ) -> Result<()> {
338 let bytes = Self::serialize_profile(sub, profile, pubkeys)?;
339 let key = user_key(username);
340 let metadata = serde_json::to_vec(&StoredAccountAuth {
341 key_custody: profile.key_custody,
342 external_identities: profile.external_identities.clone(),
343 })?;
344 let mut batch = rocksdb::WriteBatch::default();
345 batch.put(key, bytes);
346 batch.put(account_auth_key(username), metadata);
347 self.db.write(batch)?;
348 Ok(())
349 }
350
351 fn put_pubkey_index(&self, fingerprint: &str, username: &str) -> Result<()> {
353 let key = pubkey_key(fingerprint);
354 self.db.put(&key, username.as_bytes())?;
355 Ok(())
356 }
357
358 fn delete_pubkey_index(&self, fingerprint: &str) -> Result<()> {
360 let key = pubkey_key(fingerprint);
361 self.db.delete(&key)?;
362 Ok(())
363 }
364
365 fn get_pubkey_index(&self, fingerprint: &str) -> Result<Option<String>> {
367 let key = pubkey_key(fingerprint);
368 match self.db.get(&key)? {
369 Some(bytes) => Ok(Some(String::from_utf8(bytes.clone())?)),
370 None => Ok(None),
371 }
372 }
373}
374
375#[cfg(not(test))]
376impl super::user_store::private::Sealed for RocksDbUserStore {}
377
378#[async_trait]
379#[cfg(any(not(feature = "encrypted-account-admission"), test))]
380impl UserStore for RocksDbUserStore {
381 async fn get_profile(&self, username: &str) -> Result<Option<UserProfile>> {
382 Ok(self.get_raw(username)?.map(|(_, p, _)| p))
383 }
384
385 async fn register(&self, username: &str) -> Result<String> {
386 let colon_count = username.matches(':').count();
390 if colon_count > 1 || username.starts_with(':') || username.ends_with(':') {
391 anyhow::bail!(
392 "Username '{}' must not contain more than one ':', and must not start or end with ':'",
393 username
394 );
395 }
396 let _guard = self.provisioning_lock.lock();
397 if self.get_raw(username)?.is_some() {
398 tracing::warn!(
399 "Overwriting existing entry for user '{}' in credential store",
400 username
401 );
402 }
403 let sub = uuid::Uuid::new_v4().to_string();
404 let profile = UserProfile::default();
405 self.put_user(username, &sub, &profile, &[])?;
406 Ok(sub)
407 }
408
409 async fn provision_hosted_account(
410 &self,
411 username: &str,
412 atproto_did: &str,
413 pubkey: VerifyingKey,
414 custody: AccountKeyCustody,
415 ) -> std::result::Result<HostedAccountProvisioning, HostedAccountProvisionError> {
416 use base64::engine::general_purpose::URL_SAFE_NO_PAD;
417 use base64::Engine;
418
419 let _guard = self.provisioning_lock.lock();
420 let fingerprint = pubkey_fingerprint(&pubkey);
421 let usable_binding = |owner: &str,
422 raw: &(String, UserProfile, Vec<StoredPubkey>),
423 required_fingerprint: Option<&str>|
424 -> std::result::Result<bool, HostedAccountProvisionError> {
425 let (sub, profile, keys) = raw;
426 if sub.is_empty()
427 || profile.sub.as_deref() != Some(sub)
428 || profile.active != Some(true)
429 || !profile
430 .atproto_did
431 .as_deref()
432 .is_some_and(|did| did.starts_with("did:web:"))
433 || profile.key_custody.is_none()
434 || keys.is_empty()
435 {
436 return Ok(false);
437 }
438 for key in keys {
439 if required_fingerprint.is_some_and(|required| key.fingerprint != required) {
440 continue;
441 }
442 let valid_key = URL_SAFE_NO_PAD
443 .decode(&key.pubkey_base64)
444 .ok()
445 .and_then(|bytes| <[u8; 32]>::try_from(bytes).ok())
446 .and_then(|bytes| VerifyingKey::from_bytes(&bytes).ok())
447 .is_some_and(|key_bytes| pubkey_fingerprint(&key_bytes) == key.fingerprint);
448 if !valid_key {
449 continue;
450 }
451 if self
452 .get_pubkey_index(&key.fingerprint)
453 .map_err(HostedAccountProvisionError::Backend)?
454 .as_deref()
455 == Some(owner)
456 {
457 return Ok(true);
458 }
459 }
460 Ok(false)
461 };
462
463 if let Some(raw) = self
464 .get_raw(username)
465 .map_err(HostedAccountProvisionError::Backend)?
466 {
467 let (_, profile, keys) = &raw;
468 let exact_key = keys.iter().any(|key| {
469 key.fingerprint == fingerprint
470 && key.algorithm == KeyAlgorithm::Ed25519
471 && key.pq_pubkey.is_none()
472 && URL_SAFE_NO_PAD
473 .decode(&key.pubkey_base64)
474 .is_ok_and(|bytes| bytes.as_slice() == pubkey.as_bytes())
475 });
476 let exact = profile.sub.as_deref() == Some(raw.0.as_str())
477 && profile.active.is_some()
478 && profile.atproto_did.as_deref() == Some(atproto_did)
479 && profile.key_custody == Some(custody)
480 && profile.external_identities.is_empty()
481 && exact_key
482 && self
483 .get_pubkey_index(&fingerprint)
484 .map_err(HostedAccountProvisionError::Backend)?
485 .as_deref()
486 == Some(username);
487 if exact {
488 return Ok(HostedAccountProvisioning {
489 sub: raw.0,
490 fingerprint,
491 resumed: true,
492 });
493 }
494 if usable_binding(username, &raw, None)? {
495 return Err(HostedAccountProvisionError::AccountAlreadyExists);
496 }
497 return Err(HostedAccountProvisionError::Backend(anyhow!(
498 "existing hosted-account username has no usable credential binding"
499 )));
500 }
501
502 if let Some(owner) = self
503 .get_pubkey_index(&fingerprint)
504 .map_err(HostedAccountProvisionError::Backend)?
505 {
506 let owner_raw = self
507 .get_raw(&owner)
508 .map_err(HostedAccountProvisionError::Backend)?
509 .ok_or_else(|| {
510 HostedAccountProvisionError::Backend(anyhow!(
511 "hosted-account key owner profile is missing"
512 ))
513 })?;
514 if usable_binding(&owner, &owner_raw, Some(&fingerprint))? {
515 return Err(HostedAccountProvisionError::KeyAlreadyBound);
516 }
517 return Err(HostedAccountProvisionError::Backend(anyhow!(
518 "existing hosted-account key owner has no usable credential binding"
519 )));
520 }
521
522 let sub = uuid::Uuid::new_v4().to_string();
523 let profile = UserProfile {
524 sub: Some(sub.clone()),
525 active: Some(false),
528 atproto_did: Some(atproto_did.to_owned()),
529 key_custody: Some(custody),
530 external_identities: Vec::new(),
531 ..Default::default()
532 };
533 let stored_key = StoredPubkey {
534 fingerprint: fingerprint.clone(),
535 pubkey_base64: URL_SAFE_NO_PAD.encode(pubkey.as_bytes()),
536 label: Some("aegis-vault".to_owned()),
537 created_at: chrono::Utc::now().timestamp(),
538 last_used_at: 0,
539 algorithm: KeyAlgorithm::Ed25519,
540 pq_pubkey: None,
541 };
542 let profile_bytes = Self::serialize_profile(&sub, &profile, &[stored_key])
543 .map_err(HostedAccountProvisionError::Backend)?;
544 let metadata_bytes = serde_json::to_vec(&StoredAccountAuth {
545 key_custody: profile.key_custody,
546 external_identities: profile.external_identities.clone(),
547 })
548 .map_err(|error| HostedAccountProvisionError::Backend(error.into()))?;
549 let mut batch = rocksdb::WriteBatch::default();
550 batch.put(user_key(username), profile_bytes);
551 batch.put(account_auth_key(username), metadata_bytes);
552 batch.put(pubkey_key(&fingerprint), username.as_bytes());
553 self.db
554 .write(batch)
555 .map_err(|error| HostedAccountProvisionError::Backend(error.into()))?;
556
557 Ok(HostedAccountProvisioning {
558 sub,
559 fingerprint,
560 resumed: false,
561 })
562 }
563
564 async fn activate_hosted_account(
565 &self,
566 username: &str,
567 atproto_did: &str,
568 fingerprint: &str,
569 custody: AccountKeyCustody,
570 ) -> std::result::Result<(), HostedAccountProvisionError> {
571 let _guard = self.provisioning_lock.lock();
572 let (sub, mut profile, pubkeys) = self
573 .get_raw(username)
574 .map_err(HostedAccountProvisionError::Backend)?
575 .ok_or_else(|| {
576 HostedAccountProvisionError::Backend(anyhow!(
577 "staged hosted-account profile is missing"
578 ))
579 })?;
580 use base64::engine::general_purpose::URL_SAFE_NO_PAD;
581 use base64::Engine;
582 let key_matches = pubkeys.iter().any(|key| {
583 key.fingerprint == fingerprint
584 && URL_SAFE_NO_PAD
585 .decode(&key.pubkey_base64)
586 .ok()
587 .and_then(|bytes| <[u8; 32]>::try_from(bytes).ok())
588 .and_then(|bytes| VerifyingKey::from_bytes(&bytes).ok())
589 .is_some_and(|key_bytes| pubkey_fingerprint(&key_bytes) == fingerprint)
590 });
591 let reverse_matches = self
592 .get_pubkey_index(fingerprint)
593 .map_err(HostedAccountProvisionError::Backend)?
594 .as_deref()
595 == Some(username);
596 if profile.sub.as_deref() != Some(sub.as_str())
597 || profile.atproto_did.as_deref() != Some(atproto_did)
598 || profile.key_custody != Some(custody)
599 || !key_matches
600 || !reverse_matches
601 {
602 return Err(HostedAccountProvisionError::Backend(anyhow!(
603 "staged hosted-account binding changed before activation"
604 )));
605 }
606 if profile.active == Some(true) {
607 return Ok(());
608 }
609 if profile.active != Some(false) {
610 return Err(HostedAccountProvisionError::Backend(anyhow!(
611 "staged hosted-account binding has an invalid activation state"
612 )));
613 }
614 profile.active = Some(true);
615 let profile_bytes = Self::serialize_profile(&sub, &profile, &pubkeys)
616 .map_err(HostedAccountProvisionError::Backend)?;
617 self.db
618 .put(user_key(username), profile_bytes)
619 .map_err(|error| HostedAccountProvisionError::Backend(error.into()))
620 }
621
622 async fn set_profile(&self, username: &str, update: UserProfilePatch) -> Result<()> {
623 let (mut sub, mut profile, pubkeys) = self
624 .get_raw(username)
625 .with_context(|| format!("User '{}' not found", username))?
626 .ok_or_else(|| anyhow!("User '{}' not found", username))?;
627
628 if let Some(Some(s)) = update.sub {
629 sub = s;
630 }
631 if let Some(value) = update.name {
632 profile.name = value;
633 }
634 if let Some(value) = update.email {
635 profile.email = value;
636 }
637 if let Some(value) = update.email_verified {
638 profile.email_verified = value;
639 }
640 if let Some(value) = update.active {
641 profile.active = value;
642 }
643 if let Some(value) = update.external_id {
644 profile.external_id = value;
645 }
646 if let Some(value) = update.atproto_did {
647 profile.atproto_did = value;
648 }
649 if let Some(value) = update.key_custody {
650 profile.key_custody = value;
651 }
652 if let Some(value) = update.external_identities {
653 profile.external_identities = value;
654 }
655
656 self.put_user(username, &sub, &profile, &pubkeys)?;
657 Ok(())
658 }
659
660 async fn remove(&self, username: &str) -> Result<bool> {
661 let key = user_key(username);
662 match self.get_raw(username)? {
663 Some((_, _, pubkeys)) => {
664 for pk in &pubkeys {
666 self.delete_pubkey_index(&pk.fingerprint)?;
667 }
668 let mut batch = rocksdb::WriteBatch::default();
669 batch.delete(&key);
670 batch.delete(account_auth_key(username));
671 self.db.write(batch)?;
672 Ok(true)
673 }
674 None => Ok(false),
675 }
676 }
677
678 async fn list_users(&self) -> Result<Vec<String>> {
679 let mut users = Vec::new();
680 let iter = self.db.prefix_iterator(USER_PREFIX);
681 for item in iter {
682 let (key, _) = item?;
683 if let Some(username) = strip_user_prefix(&key) {
684 users.push(username.to_owned());
685 }
686 }
687 Ok(users)
688 }
689
690 async fn search(&self, filter: &UserFilter) -> Result<Vec<(String, UserProfile)>> {
691 let mut results: Vec<(String, UserProfile)> = Vec::new();
692 let iter = self.db.prefix_iterator(USER_PREFIX);
693
694 for item in iter {
695 let (key, value) = match item {
696 Ok(kv) => kv,
697 Err(_) => continue,
698 };
699 let username = match strip_user_prefix(&key) {
700 Some(u) => u.to_owned(),
701 None => continue,
702 };
703
704 let (_sub, profile, _pubkeys) = match Self::deserialize_profile(&value) {
705 Ok(p) => p,
706 Err(_) => continue,
707 };
708
709 if filter.active_only == Some(true) && profile.active == Some(false) {
710 continue;
711 }
712
713 if let Some(ref expr) = filter.filter {
714 if !matches_filter(
715 expr,
716 &username,
717 &profile.sub,
718 &profile.external_id,
719 profile.active,
720 ) {
721 continue;
722 }
723 }
724
725 results.push((username, profile));
726 }
727
728 if let Some(ref sort_by) = filter.sort_by {
729 let descending = filter.sort_order.as_deref() == Some("descending");
730 results.sort_by(|a, b| {
731 let cmp = match sort_by.as_str() {
732 "userName" => a.0.cmp(&b.0),
733 "id" | "sub" => a.1.sub.cmp(&b.1.sub),
734 "active" => a.1.active.cmp(&b.1.active),
735 "displayName" | "name" => a.1.name.cmp(&b.1.name),
736 "externalId" => a.1.external_id.cmp(&b.1.external_id),
737 _ => std::cmp::Ordering::Equal,
738 };
739 if descending {
740 cmp.reverse()
741 } else {
742 cmp
743 }
744 });
745 }
746
747 let start = filter.start_index.unwrap_or(1).saturating_sub(1);
748 let count = filter.count.unwrap_or(100);
749
750 Ok(results.into_iter().skip(start).take(count).collect())
751 }
752
753 async fn set_active(&self, username: &str, active: bool) -> Result<()> {
754 let (sub, mut profile, pubkeys) = self
755 .get_raw(username)
756 .with_context(|| format!("User '{}' not found", username))?
757 .ok_or_else(|| anyhow!("User '{}' not found", username))?;
758 profile.active = Some(active);
759 self.put_user(username, &sub, &profile, &pubkeys)?;
760 Ok(())
761 }
762
763 async fn list_pubkeys(&self, username: &str) -> Result<Vec<PubkeyEntry>> {
766 use base64::engine::general_purpose::URL_SAFE_NO_PAD;
767 use base64::Engine;
768
769 let (_, _, stored) = self
770 .get_raw(username)?
771 .ok_or_else(|| anyhow!("User '{}' not found", username))?;
772
773 let mut entries = Vec::with_capacity(stored.len());
774 for sp in stored {
775 let pubkey_bytes = URL_SAFE_NO_PAD
776 .decode(&sp.pubkey_base64)
777 .with_context(|| format!("Invalid base64 for pubkey {}", sp.fingerprint))?;
778 let pubkey_arr: [u8; 32] = pubkey_bytes
779 .try_into()
780 .map_err(|_| anyhow!("Pubkey {} is not 32 bytes", sp.fingerprint))?;
781 let pubkey = VerifyingKey::from_bytes(&pubkey_arr)?;
782
783 entries.push(PubkeyEntry {
784 fingerprint: sp.fingerprint,
785 pubkey,
786 label: sp.label,
787 created_at: sp.created_at,
788 last_used_at: if sp.last_used_at == 0 {
789 None
790 } else {
791 Some(sp.last_used_at)
792 },
793 algorithm: sp.algorithm,
794 pq_pubkey: sp.pq_pubkey,
795 });
796 }
797 Ok(entries)
798 }
799
800 async fn add_pubkey(
801 &self,
802 username: &str,
803 pubkey: VerifyingKey,
804 label: Option<String>,
805 ) -> Result<String> {
806 use base64::engine::general_purpose::URL_SAFE_NO_PAD;
807 use base64::Engine;
808
809 let _guard = self.provisioning_lock.lock();
810 let (sub, profile, mut pubkeys) = self
811 .get_raw(username)?
812 .ok_or_else(|| anyhow!("User '{}' not found", username))?;
813
814 let fingerprint = pubkey_fingerprint(&pubkey);
815
816 if pubkeys.iter().any(|pk| pk.fingerprint == fingerprint) {
818 anyhow::bail!(
819 "Pubkey with fingerprint {} already exists for user '{}'",
820 fingerprint,
821 username
822 );
823 }
824
825 if let Some(existing_user) = self.get_pubkey_index(&fingerprint)? {
827 if existing_user != username {
828 anyhow::bail!("Pubkey already associated with user '{}'", existing_user);
829 }
830 }
831
832 let now = chrono::Utc::now().timestamp();
833 pubkeys.push(StoredPubkey {
834 fingerprint: fingerprint.clone(),
835 pubkey_base64: URL_SAFE_NO_PAD.encode(pubkey.as_bytes()),
836 label,
837 created_at: now,
838 last_used_at: 0,
839 algorithm: KeyAlgorithm::Ed25519,
841 pq_pubkey: None,
842 });
843
844 self.put_user(username, &sub, &profile, &pubkeys)?;
845 self.put_pubkey_index(&fingerprint, username)?;
846
847 Ok(fingerprint)
848 }
849
850 async fn add_pubkey_hybrid(
851 &self,
852 username: &str,
853 pubkey: VerifyingKey,
854 ml_dsa_vk: Vec<u8>,
855 label: Option<String>,
856 ) -> Result<String> {
857 use base64::engine::general_purpose::URL_SAFE_NO_PAD;
858 use base64::Engine;
859
860 let _guard = self.provisioning_lock.lock();
861 if ml_dsa_vk.is_empty() {
862 anyhow::bail!("add_pubkey_hybrid: empty ML-DSA-65 verifying key");
863 }
864
865 let (sub, profile, mut pubkeys) = self
866 .get_raw(username)?
867 .ok_or_else(|| anyhow!("User '{}' not found", username))?;
868
869 let fingerprint = pubkey_fingerprint(&pubkey);
871
872 if let Some(existing_user) = self.get_pubkey_index(&fingerprint)? {
874 if existing_user != username {
875 anyhow::bail!("Pubkey already associated with user '{}'", existing_user);
876 }
877 }
878
879 let pubkey_base64 = URL_SAFE_NO_PAD.encode(pubkey.as_bytes());
880 if let Some(existing) = pubkeys.iter_mut().find(|pk| pk.fingerprint == fingerprint) {
881 existing.algorithm = KeyAlgorithm::HybridEd25519MlDsa65;
886 existing.pq_pubkey = Some(ml_dsa_vk);
887 if label.is_some() {
888 existing.label = label;
889 }
890 } else {
891 let now = chrono::Utc::now().timestamp();
892 pubkeys.push(StoredPubkey {
893 fingerprint: fingerprint.clone(),
894 pubkey_base64,
895 label,
896 created_at: now,
897 last_used_at: 0,
898 algorithm: KeyAlgorithm::HybridEd25519MlDsa65,
899 pq_pubkey: Some(ml_dsa_vk),
900 });
901 }
902
903 self.put_user(username, &sub, &profile, &pubkeys)?;
904 self.put_pubkey_index(&fingerprint, username)?;
905
906 Ok(fingerprint)
907 }
908
909 async fn remove_pubkey(&self, username: &str, fingerprint: &str) -> Result<bool> {
910 let (sub, profile, mut pubkeys) = self
911 .get_raw(username)?
912 .ok_or_else(|| anyhow!("User '{}' not found", username))?;
913
914 let original_len = pubkeys.len();
915 pubkeys.retain(|pk| pk.fingerprint != fingerprint);
916
917 if pubkeys.len() == original_len {
918 return Ok(false);
919 }
920
921 self.put_user(username, &sub, &profile, &pubkeys)?;
922 self.delete_pubkey_index(fingerprint)?;
923
924 Ok(true)
925 }
926
927 async fn get_pubkey_user(&self, fingerprint: &str) -> Result<Option<String>> {
928 self.get_pubkey_index(fingerprint)
929 }
930
931 async fn touch_pubkey(&self, username: &str, fingerprint: &str) -> Result<()> {
932 let (sub, profile, mut pubkeys) = self
933 .get_raw(username)?
934 .ok_or_else(|| anyhow!("User '{}' not found", username))?;
935
936 let now = chrono::Utc::now().timestamp();
937 let mut found = false;
938 for pk in &mut pubkeys {
939 if pk.fingerprint == fingerprint {
940 pk.last_used_at = now;
941 found = true;
942 break;
943 }
944 }
945
946 if !found {
947 anyhow::bail!("Pubkey {} not found for user '{}'", fingerprint, username);
948 }
949
950 self.put_user(username, &sub, &profile, &pubkeys)?;
951 Ok(())
952 }
953}
954
955const DEVICE_PREFIX: &[u8] = b"device:";
960
961fn device_key(fingerprint: &str) -> Vec<u8> {
962 let mut key = DEVICE_PREFIX.to_vec();
963 key.extend_from_slice(fingerprint.as_bytes());
964 key
965}
966
967#[async_trait]
968impl DeviceStore for RocksDbUserStore {
969 async fn enroll_device(&self, record: DeviceRecord) -> anyhow::Result<()> {
970 let key = device_key(&record.fingerprint);
971 let existing: Option<DeviceRecord> = self
973 .db
974 .get(&key)?
975 .and_then(|v| serde_json::from_slice(&v).ok());
976 let to_store = if let Some(existing) = existing {
977 DeviceRecord {
978 user_sub: existing.user_sub.or(record.user_sub),
979 label: existing.label.or(record.label),
980 enrolled_at: record.enrolled_at,
981 ..existing
982 }
983 } else {
984 record
985 };
986 let bytes = serde_json::to_vec(&to_store)?;
987 self.db.put(&key, &bytes)?;
988 Ok(())
989 }
990
991 async fn link_device_user(&self, fingerprint: &str, user_sub: &str) -> anyhow::Result<()> {
992 let key = device_key(fingerprint);
993 let Some(bytes) = self.db.get(&key)? else {
994 anyhow::bail!("device {} not found", fingerprint);
995 };
996 let mut record: DeviceRecord = serde_json::from_slice(&bytes)?;
997 record.user_sub = Some(user_sub.to_owned());
998 self.db.put(&key, serde_json::to_vec(&record)?)?;
999 Ok(())
1000 }
1001
1002 async fn get_device(&self, fingerprint: &str) -> anyhow::Result<Option<DeviceRecord>> {
1003 let key = device_key(fingerprint);
1004 Ok(self
1005 .db
1006 .get(&key)?
1007 .and_then(|v| serde_json::from_slice(&v).ok()))
1008 }
1009
1010 async fn touch_device(&self, fingerprint: &str) -> anyhow::Result<()> {
1011 let key = device_key(fingerprint);
1012 let Some(bytes) = self.db.get(&key)? else {
1013 return Ok(());
1014 };
1015 let mut record: DeviceRecord = serde_json::from_slice(&bytes)?;
1016 record.last_seen_at = Some(chrono::Utc::now().timestamp());
1017 self.db.put(&key, serde_json::to_vec(&record)?)?;
1018 Ok(())
1019 }
1020
1021 async fn revoke_device(&self, fingerprint: &str) -> anyhow::Result<bool> {
1022 let key = device_key(fingerprint);
1023 let exists = self.db.get(&key)?.is_some();
1024 if exists {
1025 self.db.delete(&key)?;
1026 }
1027 Ok(exists)
1028 }
1029}
1030
1031#[cfg(test)]
1032#[allow(clippy::unwrap_used, clippy::expect_used)]
1033mod tests {
1034 use super::*;
1035 use ed25519_dalek::SigningKey;
1036 use tempfile::TempDir;
1037
1038 fn make_store(dir: &Path) -> RocksDbUserStore {
1039 RocksDbUserStore::open(dir).expect("Failed to open RocksDB store")
1040 }
1041
1042 #[tokio::test]
1043 async fn test_register_and_get_profile() -> Result<()> {
1044 let dir = TempDir::new()?;
1045 let store = make_store(dir.path());
1046 let sub = store.register("alice").await?;
1047 assert!(!sub.is_empty(), "sub should be returned on register");
1048 let profile = store
1049 .get_profile("alice")
1050 .await?
1051 .ok_or_else(|| anyhow!("alice not found"))?;
1052 assert_eq!(profile.sub.as_deref(), Some(sub.as_str()));
1053 Ok(())
1054 }
1055
1056 #[tokio::test]
1057 async fn test_remove_user() -> Result<()> {
1058 let dir = TempDir::new()?;
1059 let store = make_store(dir.path());
1060 store.register("bob").await?;
1061 assert!(store.remove("bob").await?);
1062 assert!(store.get_profile("bob").await?.is_none());
1063 Ok(())
1064 }
1065
1066 #[tokio::test]
1067 async fn test_list_users() -> Result<()> {
1068 let dir = TempDir::new()?;
1069 let store = make_store(dir.path());
1070 store.register("alice").await?;
1071 store.register("bob").await?;
1072 let mut users = store.list_users().await?;
1073 users.sort();
1074 assert_eq!(users, vec!["alice", "bob"]);
1075 Ok(())
1076 }
1077
1078 #[tokio::test]
1079 async fn test_register_allows_namespaced_oidc_subject() -> Result<()> {
1080 let dir = TempDir::new()?;
1081 let store = make_store(dir.path());
1082 store.register("google:abc123").await?;
1084 let profile = store.get_profile("google:abc123").await?;
1085 assert!(profile.is_some());
1086 Ok(())
1087 }
1088
1089 #[tokio::test]
1090 async fn test_register_rejects_multiple_colons() -> Result<()> {
1091 let dir = TempDir::new()?;
1092 let store = make_store(dir.path());
1093 let result = store.register("a:b:c").await;
1094 assert!(result.is_err());
1095 assert!(result
1096 .unwrap_err()
1097 .to_string()
1098 .contains("must not contain more than one"));
1099 Ok(())
1100 }
1101
1102 #[tokio::test]
1103 async fn test_register_rejects_leading_trailing_colon() -> Result<()> {
1104 let dir = TempDir::new()?;
1105 let store = make_store(dir.path());
1106 assert!(store.register(":bad").await.is_err());
1107 assert!(store.register("bad:").await.is_err());
1108 Ok(())
1109 }
1110
1111 #[tokio::test]
1112 async fn test_search_filter_eq() -> Result<()> {
1113 let dir = TempDir::new()?;
1114 let store = make_store(dir.path());
1115 store.register("alice").await?;
1116 store.register("bob").await?;
1117
1118 let results = store
1119 .search(&UserFilter {
1120 filter: Some(r#"userName eq "alice""#.to_owned()),
1121 ..Default::default()
1122 })
1123 .await?;
1124 assert_eq!(results.len(), 1);
1125 assert_eq!(results[0].0, "alice");
1126 Ok(())
1127 }
1128
1129 #[tokio::test]
1130 async fn test_search_filter_pr() -> Result<()> {
1131 let dir = TempDir::new()?;
1132 let store = make_store(dir.path());
1133 store.register("alice").await?;
1134
1135 let results = store
1136 .search(&UserFilter {
1137 filter: Some("userName pr".to_owned()),
1138 ..Default::default()
1139 })
1140 .await?;
1141 assert_eq!(results.len(), 1);
1142
1143 let results = store
1144 .search(&UserFilter {
1145 filter: Some("active pr".to_owned()),
1146 ..Default::default()
1147 })
1148 .await?;
1149 assert!(
1150 results.is_empty(),
1151 "active is None by default, pr should not match"
1152 );
1153 Ok(())
1154 }
1155
1156 #[tokio::test]
1157 async fn test_search_pagination() -> Result<()> {
1158 let dir = TempDir::new()?;
1159 let store = make_store(dir.path());
1160 for name in &["alice", "bob", "carol"] {
1161 store.register(name).await?;
1162 }
1163
1164 let results = store
1165 .search(&UserFilter {
1166 start_index: Some(1),
1167 count: Some(2),
1168 ..Default::default()
1169 })
1170 .await?;
1171 assert_eq!(results.len(), 2);
1172
1173 let results = store
1174 .search(&UserFilter {
1175 start_index: Some(3),
1176 count: Some(2),
1177 ..Default::default()
1178 })
1179 .await?;
1180 assert_eq!(results.len(), 1);
1181 Ok(())
1182 }
1183
1184 #[tokio::test]
1185 async fn test_search_sorting() -> Result<()> {
1186 let dir = TempDir::new()?;
1187 let store = make_store(dir.path());
1188 store.register("carol").await?;
1189 store.register("alice").await?;
1190 store.register("bob").await?;
1191
1192 let results = store
1193 .search(&UserFilter {
1194 sort_by: Some("userName".to_owned()),
1195 sort_order: Some("ascending".to_owned()),
1196 ..Default::default()
1197 })
1198 .await?;
1199 assert_eq!(results[0].0, "alice");
1200 assert_eq!(results[1].0, "bob");
1201 assert_eq!(results[2].0, "carol");
1202
1203 let results = store
1204 .search(&UserFilter {
1205 sort_by: Some("userName".to_owned()),
1206 sort_order: Some("descending".to_owned()),
1207 ..Default::default()
1208 })
1209 .await?;
1210 assert_eq!(results[0].0, "carol");
1211 assert_eq!(results[1].0, "bob");
1212 assert_eq!(results[2].0, "alice");
1213 Ok(())
1214 }
1215
1216 #[tokio::test]
1217 async fn test_set_active() -> Result<()> {
1218 let dir = TempDir::new()?;
1219 let store = make_store(dir.path());
1220 store.register("alice").await?;
1221
1222 let profile = store.get_profile("alice").await?.unwrap();
1223 assert!(profile.active.is_none());
1224
1225 store.set_active("alice", false).await?;
1226 let profile = store.get_profile("alice").await?.unwrap();
1227 assert_eq!(profile.active, Some(false));
1228
1229 let results = store
1230 .search(&UserFilter {
1231 active_only: Some(true),
1232 ..Default::default()
1233 })
1234 .await?;
1235 assert!(results.is_empty());
1236
1237 store.set_active("alice", true).await?;
1238 let profile = store.get_profile("alice").await?.unwrap();
1239 assert_eq!(profile.active, Some(true));
1240 Ok(())
1241 }
1242
1243 #[tokio::test]
1244 async fn test_new_fields_roundtrip() -> Result<()> {
1245 let dir = TempDir::new()?;
1246 {
1247 let store = make_store(dir.path());
1248 store.register("alice").await?;
1249 store
1250 .set_profile(
1251 "alice",
1252 UserProfile {
1253 sub: None,
1254 name: Some("Alice Smith".to_owned()),
1255 email: Some("alice@example.com".to_owned()),
1256 email_verified: Some(true),
1257 active: Some(true),
1258 external_id: Some("ext-123".to_owned()),
1259 atproto_did: Some("did:plc:abcdefghijklmnqrstuvwx2p".to_owned()),
1260 key_custody: Some(AccountKeyCustody::SelfCustody),
1261 external_identities: vec![ExternalIdentityBinding {
1262 issuer: "https://issuer.example".to_owned(),
1263 subject: "alice-123".to_owned(),
1264 }],
1265 }
1266 .into(),
1267 )
1268 .await?;
1269 }
1270 let store2 = RocksDbUserStore::open(dir.path())?;
1272 let profile = store2.get_profile("alice").await?.unwrap();
1273 assert_eq!(profile.name.as_deref(), Some("Alice Smith"));
1274 assert_eq!(profile.external_id.as_deref(), Some("ext-123"));
1275 assert_eq!(profile.active, Some(true));
1276 assert_eq!(profile.email_verified, Some(true));
1277 assert_eq!(
1278 profile.atproto_did.as_deref(),
1279 Some("did:plc:abcdefghijklmnqrstuvwx2p")
1280 );
1281 assert_eq!(profile.key_custody, Some(AccountKeyCustody::SelfCustody));
1282 assert_eq!(
1283 profile.external_identities,
1284 vec![ExternalIdentityBinding {
1285 issuer: "https://issuer.example".to_owned(),
1286 subject: "alice-123".to_owned(),
1287 }]
1288 );
1289 Ok(())
1290 }
1291
1292 #[tokio::test]
1293 async fn hosted_account_provisioning_is_atomic_and_preserves_future_idp_seam() -> Result<()> {
1294 let dir = TempDir::new()?;
1295 let store = make_store(dir.path());
1296 let alice_key = ed25519_dalek::SigningKey::from_bytes(&[0x71; 32]).verifying_key();
1297 let provisioned = store
1298 .provision_hosted_account(
1299 "alice",
1300 "did:web:alice.accounts.example.test",
1301 alice_key,
1302 AccountKeyCustody::SelfCustody,
1303 )
1304 .await?;
1305 assert_eq!(provisioned.fingerprint, pubkey_fingerprint(&alice_key));
1306 assert!(!provisioned.resumed);
1307 let profile = store.get_profile("alice").await?.unwrap();
1308 assert_eq!(
1309 profile.atproto_did.as_deref(),
1310 Some("did:web:alice.accounts.example.test")
1311 );
1312 assert_eq!(profile.key_custody, Some(AccountKeyCustody::SelfCustody));
1313 assert_eq!(profile.active, Some(false));
1314 assert!(profile.external_identities.is_empty());
1315 assert_eq!(
1316 store.get_pubkey_user(&provisioned.fingerprint).await?,
1317 Some("alice".to_owned())
1318 );
1319 let resumed = store
1320 .provision_hosted_account(
1321 "alice",
1322 "did:web:alice.accounts.example.test",
1323 alice_key,
1324 AccountKeyCustody::SelfCustody,
1325 )
1326 .await?;
1327 assert!(resumed.resumed);
1328 assert_eq!(resumed.sub, provisioned.sub);
1329 store
1330 .activate_hosted_account(
1331 "alice",
1332 "did:web:alice.accounts.example.test",
1333 &provisioned.fingerprint,
1334 AccountKeyCustody::SelfCustody,
1335 )
1336 .await?;
1337 assert_eq!(
1338 store.get_profile("alice").await?.unwrap().active,
1339 Some(true)
1340 );
1341 assert!(matches!(
1342 store
1343 .provision_hosted_account(
1344 "alice",
1345 "did:web:alice.accounts.example.test",
1346 ed25519_dalek::SigningKey::from_bytes(&[0x72; 32]).verifying_key(),
1347 AccountKeyCustody::SelfCustody,
1348 )
1349 .await,
1350 Err(HostedAccountProvisionError::AccountAlreadyExists)
1351 ));
1352 assert!(matches!(
1353 store
1354 .provision_hosted_account(
1355 "bob",
1356 "did:web:bob.accounts.example.test",
1357 alice_key,
1358 AccountKeyCustody::SelfCustody,
1359 )
1360 .await,
1361 Err(HostedAccountProvisionError::KeyAlreadyBound)
1362 ));
1363
1364 store
1365 .set_profile(
1366 "alice",
1367 UserProfilePatch {
1368 external_identities: Some(vec![ExternalIdentityBinding {
1369 issuer: "https://issuer.example".to_owned(),
1370 subject: "external-alice".to_owned(),
1371 }]),
1372 ..Default::default()
1373 },
1374 )
1375 .await?;
1376 assert_eq!(
1377 store
1378 .get_external_identity_user("https://issuer.example", "external-alice")
1379 .await?,
1380 Some("alice".to_owned())
1381 );
1382 assert_eq!(
1383 store.list_external_identities("alice").await?,
1384 vec![ExternalIdentityBinding {
1385 issuer: "https://issuer.example".to_owned(),
1386 subject: "external-alice".to_owned(),
1387 }]
1388 );
1389 Ok(())
1390 }
1391
1392 #[tokio::test]
1393 async fn corrupt_exact_key_index_never_returns_trusted_key_conflict() -> Result<()> {
1394 use base64::engine::general_purpose::URL_SAFE_NO_PAD;
1395 use base64::Engine;
1396
1397 let dir = TempDir::new()?;
1398 let store = make_store(dir.path());
1399 let alice_key = SigningKey::from_bytes(&[0x74; 32]).verifying_key();
1400 let alice = store
1401 .provision_hosted_account(
1402 "alice",
1403 "did:web:alice.accounts.example.test",
1404 alice_key,
1405 AccountKeyCustody::SelfCustody,
1406 )
1407 .await?;
1408 store
1409 .activate_hosted_account(
1410 "alice",
1411 "did:web:alice.accounts.example.test",
1412 &alice.fingerprint,
1413 AccountKeyCustody::SelfCustody,
1414 )
1415 .await?;
1416
1417 let conflicting_key = SigningKey::from_bytes(&[0x75; 32]).verifying_key();
1418 let conflicting_fingerprint = pubkey_fingerprint(&conflicting_key);
1419 store
1420 .db
1421 .put(pubkey_key(&conflicting_fingerprint), b"alice")?;
1422
1423 let attempt = || {
1424 store.provision_hosted_account(
1425 "bob",
1426 "did:web:bob.accounts.example.test",
1427 conflicting_key,
1428 AccountKeyCustody::SelfCustody,
1429 )
1430 };
1431 assert!(matches!(
1432 attempt().await,
1433 Err(HostedAccountProvisionError::Backend(_))
1434 ));
1435
1436 let (sub, profile, mut keys) = store.get_raw("alice")?.unwrap();
1437 keys.push(StoredPubkey {
1438 fingerprint: conflicting_fingerprint,
1439 pubkey_base64: URL_SAFE_NO_PAD.encode(alice_key.as_bytes()),
1443 label: Some("corrupt-mismatch".to_owned()),
1444 created_at: chrono::Utc::now().timestamp(),
1445 last_used_at: 0,
1446 algorithm: KeyAlgorithm::Ed25519,
1447 pq_pubkey: None,
1448 });
1449 store.put_user("alice", &sub, &profile, &keys)?;
1450 assert!(matches!(
1451 attempt().await,
1452 Err(HostedAccountProvisionError::Backend(_))
1453 ));
1454
1455 keys.last_mut().unwrap().pubkey_base64 = "not-base64".to_owned();
1456 store.put_user("alice", &sub, &profile, &keys)?;
1457 assert!(matches!(
1458 attempt().await,
1459 Err(HostedAccountProvisionError::Backend(_))
1460 ));
1461 Ok(())
1462 }
1463
1464 #[tokio::test]
1465 async fn concurrent_same_key_different_handles_never_reserves_two_accounts() -> Result<()> {
1466 let dir = TempDir::new()?;
1467 let store = std::sync::Arc::new(make_store(dir.path()));
1468 let key = ed25519_dalek::SigningKey::from_bytes(&[0x73; 32]).verifying_key();
1469 let barrier = std::sync::Arc::new(tokio::sync::Barrier::new(3));
1470
1471 let attempt = |handle: &'static str| {
1472 let store = store.clone();
1473 let barrier = barrier.clone();
1474 tokio::spawn(async move {
1475 barrier.wait().await;
1476 store
1477 .provision_hosted_account(
1478 handle,
1479 &format!("did:web:{handle}.accounts.example.test"),
1480 key,
1481 AccountKeyCustody::SelfCustody,
1482 )
1483 .await
1484 .map(|provisioned| (handle, provisioned))
1485 })
1486 };
1487 let alice = attempt("alice");
1488 let bob = attempt("bob");
1489 barrier.wait().await;
1490 let results = [alice.await?, bob.await?];
1491 let winner = results
1492 .iter()
1493 .find_map(|result| result.as_ref().ok())
1494 .expect("one transaction must win");
1495 assert_eq!(
1496 results.iter().filter(|result| result.is_ok()).count(),
1497 1,
1498 "the same vault key must never stage two handles"
1499 );
1500 assert!(results
1501 .iter()
1502 .any(|result| matches!(result, Err(HostedAccountProvisionError::Backend(_)))));
1503 let loser = if winner.0 == "alice" { "bob" } else { "alice" };
1504 assert!(store.get_profile(winner.0).await?.is_some());
1505 assert!(store.get_profile(loser).await?.is_none());
1506
1507 store
1508 .activate_hosted_account(
1509 winner.0,
1510 &format!("did:web:{}.accounts.example.test", winner.0),
1511 &winner.1.fingerprint,
1512 AccountKeyCustody::SelfCustody,
1513 )
1514 .await?;
1515 assert!(matches!(
1516 store
1517 .provision_hosted_account(
1518 loser,
1519 &format!("did:web:{loser}.accounts.example.test"),
1520 key,
1521 AccountKeyCustody::SelfCustody,
1522 )
1523 .await,
1524 Err(HostedAccountProvisionError::KeyAlreadyBound)
1525 ));
1526 Ok(())
1527 }
1528
1529 #[tokio::test]
1530 async fn test_atproto_did_can_be_explicitly_cleared() -> Result<()> {
1531 let dir = TempDir::new()?;
1532 let store = std::sync::Arc::new(make_store(dir.path()));
1533 store.register("alice").await?;
1534 store
1535 .set_profile(
1536 "alice",
1537 UserProfilePatch {
1538 atproto_did: Some(Some("did:plc:abcdefghijklmnqrstuvwx2p".to_owned())),
1539 ..Default::default()
1540 },
1541 )
1542 .await?;
1543
1544 let service = crate::services::oauth::user_service::UserService::new(
1545 crate::auth::ProductionUserStore::for_test(store.clone()),
1546 );
1547 service
1548 .update(
1549 "alice",
1550 crate::services::oauth::user_service::UserUpdate {
1551 atproto_did: Some(None),
1552 ..Default::default()
1553 },
1554 )
1555 .await?;
1556
1557 let profile = store.get_profile("alice").await?.unwrap();
1558 assert_eq!(profile.atproto_did, None);
1559 Ok(())
1560 }
1561
1562 #[tokio::test]
1563 async fn test_persistence_across_reopens() -> Result<()> {
1564 let dir = TempDir::new()?;
1565 {
1566 let store = make_store(dir.path());
1567 store.register("alice").await?;
1568 store.register("bob").await?;
1569 }
1570 let store2 = RocksDbUserStore::open(dir.path())?;
1571 let mut users = store2.list_users().await?;
1572 users.sort();
1573 assert_eq!(users, vec!["alice", "bob"]);
1574
1575 let profile = store2.get_profile("alice").await?.unwrap();
1576 assert!(profile.sub.is_some());
1577 Ok(())
1578 }
1579
1580 #[tokio::test]
1583 async fn test_add_and_list_pubkeys() -> Result<()> {
1584 let dir = TempDir::new()?;
1585 let store = make_store(dir.path());
1586 store.register("alice").await?;
1587
1588 let signing_key = SigningKey::generate(&mut rand::thread_rng());
1589 let pubkey = signing_key.verifying_key();
1590
1591 let fingerprint = store
1592 .add_pubkey("alice", pubkey, Some("laptop".to_owned()))
1593 .await?;
1594 assert!(!fingerprint.is_empty());
1595
1596 let keys = store.list_pubkeys("alice").await?;
1597 assert_eq!(keys.len(), 1);
1598 assert_eq!(keys[0].fingerprint, fingerprint);
1599 assert_eq!(keys[0].label.as_deref(), Some("laptop"));
1600 assert_eq!(keys[0].pubkey.as_bytes(), pubkey.as_bytes());
1601 assert!(keys[0].last_used_at.is_none());
1602 assert_eq!(keys[0].algorithm, KeyAlgorithm::Ed25519);
1604 Ok(())
1605 }
1606
1607 #[tokio::test]
1611 async fn test_pubkey_algorithm_tag_persists_across_reopen() -> Result<()> {
1612 let dir = TempDir::new()?;
1613 {
1614 let store = make_store(dir.path());
1615 store.register("alice").await?;
1616 let pubkey = SigningKey::generate(&mut rand::thread_rng()).verifying_key();
1617 store.add_pubkey("alice", pubkey, None).await?;
1618 }
1621
1622 let store2 = RocksDbUserStore::open(dir.path())?;
1624 let keys = store2.list_pubkeys("alice").await?;
1625 assert_eq!(keys.len(), 1);
1626 assert_eq!(keys[0].algorithm, KeyAlgorithm::Ed25519);
1627 assert_eq!(keys[0].algorithm.as_str(), "ed25519");
1628 Ok(())
1629 }
1630
1631 #[tokio::test]
1632 async fn test_multiple_pubkeys_per_user() -> Result<()> {
1633 let dir = TempDir::new()?;
1634 let store = make_store(dir.path());
1635 store.register("alice").await?;
1636
1637 let key1 = SigningKey::generate(&mut rand::thread_rng()).verifying_key();
1638 let key2 = SigningKey::generate(&mut rand::thread_rng()).verifying_key();
1639
1640 let fp1 = store
1641 .add_pubkey("alice", key1, Some("laptop".to_owned()))
1642 .await?;
1643 let fp2 = store
1644 .add_pubkey("alice", key2, Some("phone".to_owned()))
1645 .await?;
1646
1647 let keys = store.list_pubkeys("alice").await?;
1648 assert_eq!(keys.len(), 2);
1649
1650 let fingerprints: Vec<_> = keys.iter().map(|k| k.fingerprint.as_str()).collect();
1651 assert!(fingerprints.contains(&fp1.as_str()));
1652 assert!(fingerprints.contains(&fp2.as_str()));
1653 Ok(())
1654 }
1655
1656 #[tokio::test]
1657 async fn test_remove_pubkey() -> Result<()> {
1658 let dir = TempDir::new()?;
1659 let store = make_store(dir.path());
1660 store.register("alice").await?;
1661
1662 let key = SigningKey::generate(&mut rand::thread_rng()).verifying_key();
1663 let fingerprint = store.add_pubkey("alice", key, None).await?;
1664
1665 assert!(store.remove_pubkey("alice", &fingerprint).await?);
1666 assert!(!store.remove_pubkey("alice", &fingerprint).await?); let keys = store.list_pubkeys("alice").await?;
1669 assert!(keys.is_empty());
1670 Ok(())
1671 }
1672
1673 #[tokio::test]
1674 async fn test_get_pubkey_user_reverse_lookup() -> Result<()> {
1675 let dir = TempDir::new()?;
1676 let store = make_store(dir.path());
1677 store.register("alice").await?;
1678 store.register("bob").await?;
1679
1680 let alice_key = SigningKey::generate(&mut rand::thread_rng()).verifying_key();
1681 let bob_key = SigningKey::generate(&mut rand::thread_rng()).verifying_key();
1682
1683 let alice_fp = store.add_pubkey("alice", alice_key, None).await?;
1684 let bob_fp = store.add_pubkey("bob", bob_key, None).await?;
1685
1686 assert_eq!(
1687 store.get_pubkey_user(&alice_fp).await?,
1688 Some("alice".to_owned())
1689 );
1690 assert_eq!(
1691 store.get_pubkey_user(&bob_fp).await?,
1692 Some("bob".to_owned())
1693 );
1694 assert_eq!(store.get_pubkey_user("nonexistent").await?, None);
1695 Ok(())
1696 }
1697
1698 #[tokio::test]
1699 async fn test_touch_pubkey() -> Result<()> {
1700 let dir = TempDir::new()?;
1701 let store = make_store(dir.path());
1702 store.register("alice").await?;
1703
1704 let key = SigningKey::generate(&mut rand::thread_rng()).verifying_key();
1705 let fingerprint = store.add_pubkey("alice", key, None).await?;
1706
1707 let keys = store.list_pubkeys("alice").await?;
1709 assert!(keys[0].last_used_at.is_none());
1710
1711 store.touch_pubkey("alice", &fingerprint).await?;
1713 let keys = store.list_pubkeys("alice").await?;
1714 assert!(keys[0].last_used_at.is_some());
1715 Ok(())
1716 }
1717
1718 #[tokio::test]
1719 async fn test_remove_user_cleans_pubkey_indexes() -> Result<()> {
1720 let dir = TempDir::new()?;
1721 let store = make_store(dir.path());
1722 store.register("alice").await?;
1723
1724 let key = SigningKey::generate(&mut rand::thread_rng()).verifying_key();
1725 let fingerprint = store.add_pubkey("alice", key, None).await?;
1726
1727 assert_eq!(
1729 store.get_pubkey_user(&fingerprint).await?,
1730 Some("alice".to_owned())
1731 );
1732
1733 store.remove("alice").await?;
1735
1736 assert_eq!(store.get_pubkey_user(&fingerprint).await?, None);
1738 Ok(())
1739 }
1740
1741 #[tokio::test]
1742 async fn test_duplicate_pubkey_rejected() -> Result<()> {
1743 let dir = TempDir::new()?;
1744 let store = make_store(dir.path());
1745 store.register("alice").await?;
1746
1747 let key = SigningKey::generate(&mut rand::thread_rng()).verifying_key();
1748 store
1749 .add_pubkey("alice", key, Some("first".to_owned()))
1750 .await?;
1751
1752 let result = store
1754 .add_pubkey("alice", key, Some("second".to_owned()))
1755 .await;
1756 assert!(result.is_err());
1757 assert!(result.unwrap_err().to_string().contains("already exists"));
1758 Ok(())
1759 }
1760
1761 #[tokio::test]
1762 async fn test_pubkey_cross_user_rejected() -> Result<()> {
1763 let dir = TempDir::new()?;
1764 let store = make_store(dir.path());
1765 store.register("alice").await?;
1766 store.register("bob").await?;
1767
1768 let key = SigningKey::generate(&mut rand::thread_rng()).verifying_key();
1769 store.add_pubkey("alice", key, None).await?;
1770
1771 let result = store.add_pubkey("bob", key, None).await;
1773 assert!(result.is_err());
1774 assert!(result
1775 .unwrap_err()
1776 .to_string()
1777 .contains("already associated"));
1778 Ok(())
1779 }
1780
1781 #[tokio::test]
1782 async fn test_pubkeys_persist_across_reopens() -> Result<()> {
1783 let dir = TempDir::new()?;
1784 let key = SigningKey::generate(&mut rand::thread_rng()).verifying_key();
1785 let fingerprint;
1786 {
1787 let store = make_store(dir.path());
1788 store.register("alice").await?;
1789 fingerprint = store
1790 .add_pubkey("alice", key, Some("laptop".to_owned()))
1791 .await?;
1792 }
1793
1794 let store2 = RocksDbUserStore::open(dir.path())?;
1796 let keys = store2.list_pubkeys("alice").await?;
1797 assert_eq!(keys.len(), 1);
1798 assert_eq!(keys[0].fingerprint, fingerprint);
1799 assert_eq!(keys[0].label.as_deref(), Some("laptop"));
1800
1801 assert_eq!(
1803 store2.get_pubkey_user(&fingerprint).await?,
1804 Some("alice".to_owned())
1805 );
1806 Ok(())
1807 }
1808
1809 #[tokio::test]
1810 async fn test_hybrid_pubkey_round_trips_pq_material_across_reopen() -> Result<()> {
1811 let dir = TempDir::new()?;
1812 let key = SigningKey::generate(&mut rand::thread_rng()).verifying_key();
1813 let pq_vk = vec![0xABu8; 1952];
1815 let fingerprint;
1816 {
1817 let store = make_store(dir.path());
1818 store.register("alice").await?;
1819 fingerprint = store
1820 .add_pubkey_hybrid("alice", key, pq_vk.clone(), Some("laptop".to_owned()))
1821 .await?;
1822 }
1823
1824 let store2 = RocksDbUserStore::open(dir.path())?;
1826 let keys = store2.list_pubkeys("alice").await?;
1827 assert_eq!(keys.len(), 1);
1828 assert_eq!(keys[0].fingerprint, fingerprint);
1829 assert_eq!(keys[0].algorithm, KeyAlgorithm::HybridEd25519MlDsa65);
1830 assert_eq!(keys[0].pq_pubkey.as_ref(), Some(&pq_vk));
1831 Ok(())
1832 }
1833
1834 #[tokio::test]
1835 async fn test_hybrid_upgrade_in_place_preserves_fingerprint() -> Result<()> {
1836 let dir = TempDir::new()?;
1837 let key = SigningKey::generate(&mut rand::thread_rng()).verifying_key();
1838 let store = make_store(dir.path());
1839 store.register("alice").await?;
1840
1841 let fp1 = store.add_pubkey("alice", key, None).await?;
1843 let fp2 = store
1844 .add_pubkey_hybrid("alice", key, vec![0x11u8; 1952], None)
1845 .await?;
1846 assert_eq!(
1847 fp1, fp2,
1848 "hybrid upgrade keeps the Ed25519 anchor fingerprint"
1849 );
1850
1851 let keys = store.list_pubkeys("alice").await?;
1852 assert_eq!(keys.len(), 1, "in-place upgrade, not a second key");
1853 assert_eq!(keys[0].algorithm, KeyAlgorithm::HybridEd25519MlDsa65);
1854 assert!(keys[0].pq_pubkey.is_some());
1855 Ok(())
1856 }
1857
1858 #[test]
1859 fn test_serialize_rejects_invariant_violations() {
1860 let bad_hybrid = StoredPubkey {
1862 fingerprint: "SHA256:x".to_owned(),
1863 pubkey_base64: "AAAA".to_owned(),
1864 label: None,
1865 created_at: 0,
1866 last_used_at: 0,
1867 algorithm: KeyAlgorithm::HybridEd25519MlDsa65,
1868 pq_pubkey: None,
1869 };
1870 let profile = UserProfile::default();
1871 assert!(
1872 RocksDbUserStore::serialize_profile("sub", &profile, &[bad_hybrid]).is_err(),
1873 "hybrid record with no PQ key must fail to serialize"
1874 );
1875
1876 let bad_classical = StoredPubkey {
1878 fingerprint: "SHA256:y".to_owned(),
1879 pubkey_base64: "AAAA".to_owned(),
1880 label: None,
1881 created_at: 0,
1882 last_used_at: 0,
1883 algorithm: KeyAlgorithm::Ed25519,
1884 pq_pubkey: Some(vec![1, 2, 3]),
1885 };
1886 assert!(
1887 RocksDbUserStore::serialize_profile("sub", &profile, &[bad_classical]).is_err(),
1888 "classical record carrying PQ key material must fail to serialize"
1889 );
1890 }
1891
1892 #[test]
1893 fn test_deserialize_rejects_unknown_algorithm_tag() {
1894 let mut message = Builder::new_default();
1898 {
1899 let mut ui = message.init_root::<hyprstream_rpc_std::oauth_capnp::user_info::Builder>();
1900 ui.set_sub("sub");
1901 let mut pk_list = ui.init_pubkeys(1);
1902 let mut e = pk_list.reborrow().get(0);
1903 e.set_fingerprint("SHA256:z");
1904 e.set_pubkey_base64("AAAA");
1905 e.set_created_at(0);
1906 e.set_last_used_at(0);
1907 e.set_algorithm("ml-dsa-99-future");
1908 }
1909 let mut bytes = vec![0u8]; capnp::serialize::write_message(&mut bytes, &message).unwrap();
1911
1912 let err = RocksDbUserStore::deserialize_profile(&bytes)
1913 .expect_err("unknown algorithm tag must fail the read");
1914 assert!(
1915 err.to_string()
1916 .to_lowercase()
1917 .contains("unknown key algorithm"),
1918 "error must name the unknown tag: {err}"
1919 );
1920 }
1921}