1use super::{
28 encrypted_columns::{ColumnCipher, EncryptedColumn, ROOT_DEK_BYTES},
29 user_store::matches_filter,
30 AccountKeyCustody, ExternalIdentityBinding, ExternalIdentityResolution,
31 HostedAccountProvisionError, HostedAccountProvisioning, KeyAlgorithm, PubkeyEntry, UserFilter,
32 UserProfile, UserProfilePatch, UserStore,
33};
34use anyhow::{anyhow, bail, ensure, Context, Result};
35use async_trait::async_trait;
36use ed25519_dalek::VerifyingKey;
37use pglite::{PGlite, Row};
38use std::{path::Path, sync::Arc};
39use zeroize::Zeroizing;
40
41pub use super::cipher_glue::USERSTORE_SCHEMA;
44
45const PROFILE_SELECT: &str = r#"
46SELECT u.sub, u.name, u.email, u.email_verified, u.active, u.external_id,
47 u.key_custody, d.atproto_did
48FROM users u
49LEFT JOIN user_did_bindings d ON d.username = u.username
50WHERE u.username = $1
51"#;
52
53const KEY_SELECT: &str = r#"
54SELECT fingerprint, pubkey, label, created_at, last_used_at, algorithm, pq_pubkey
55FROM pubkeys WHERE username = $1 ORDER BY fingerprint
56"#;
57
58#[derive(Clone)]
59pub struct PgliteUserStore {
60 database: Arc<PGlite>,
61 cipher: ColumnCipher,
62}
63
64impl PgliteUserStore {
65 #[cfg(test)]
66 pub(crate) async fn open_for_test(data_dir: impl AsRef<Path>) -> Result<Self> {
67 let database = Arc::new(PGlite::open(data_dir).await?);
68 Self::with_cipher(database, ColumnCipher::test_cipher()).await
69 }
70
71 pub(crate) async fn open_admitted(
76 data_dir: impl AsRef<Path>,
77 _permit: &super::production_user_store::ProductionStorePermit,
78 ) -> Result<Self> {
79 let cipher = ColumnCipher::from_deployment_env()
80 .context("load deployment UserStore encryption configuration")?;
81 let database = Arc::new(PGlite::open(data_dir).await.context("opening PGlite")?);
82 Self::with_cipher(database, cipher).await
83 }
84
85 async fn with_cipher(database: Arc<PGlite>, cipher: ColumnCipher) -> Result<Self> {
88 database
89 .exec(USERSTORE_SCHEMA)
90 .await
91 .context("applying UserStore schema")?;
92 Ok(Self { database, cipher })
93 }
94
95 #[cfg(test)]
96 fn database(&self) -> Arc<PGlite> {
97 Arc::clone(&self.database)
98 }
99
100 async fn create_user_key(
105 &self,
106 tx: &pglite::Transaction<'_>,
107 username: &str,
108 ) -> Result<Zeroizing<[u8; ROOT_DEK_BYTES]>> {
109 let cipher = &self.cipher;
110 let new_key = cipher.create_user_key().await?;
111 tx.query(
112 "INSERT INTO user_encryption_keys(username, wrapped_dek) VALUES($1, $2)",
113 &[&username, &new_key.wrapped],
114 )
115 .await?;
116 Ok(new_key.root)
117 }
118
119 async fn load_user_key(&self, username: &str) -> Result<Zeroizing<[u8; ROOT_DEK_BYTES]>> {
129 let cipher = &self.cipher;
130 let rows = self
131 .database
132 .query(
133 "SELECT wrapped_dek FROM user_encryption_keys WHERE username=$1",
134 &[&username],
135 )
136 .await?;
137 let wrapped: Vec<u8> = rows
138 .first()
139 .context("wrapped UserStore DEK is absent — key material revoked or never provisioned")?
140 .get(0)?;
141 cipher.open_user_key(&wrapped).await
142 }
143
144 async fn load_user_key_tx(
147 &self,
148 tx: &pglite::Transaction<'_>,
149 username: &str,
150 ) -> Result<Zeroizing<[u8; ROOT_DEK_BYTES]>> {
151 let cipher = &self.cipher;
152 let rows = tx
153 .query(
154 "SELECT wrapped_dek FROM user_encryption_keys WHERE username=$1",
155 &[&username],
156 )
157 .await?;
158 let wrapped: Vec<u8> = rows
159 .first()
160 .context("wrapped UserStore DEK is absent — key material revoked or never provisioned")?
161 .get(0)?;
162 cipher.open_user_key(&wrapped).await
163 }
164
165 async fn external_identities(&self, username: &str) -> Result<Vec<ExternalIdentityBinding>> {
166 let rows = self
167 .database
168 .query(
169 "SELECT issuer, issuer_sub FROM oidc_bindings \
170 WHERE username=$1 ORDER BY issuer, issuer_sub",
171 &[&username],
172 )
173 .await?;
174 rows.iter().map(decode_external_identity).collect()
175 }
176
177 fn decode_profile(
182 &self,
183 row: &Row,
184 external_identities: Vec<ExternalIdentityBinding>,
185 username: &str,
186 root: &Zeroizing<[u8; ROOT_DEK_BYTES]>,
187 ) -> Result<UserProfile> {
188 let custody = row
189 .get::<Option<String>>(6)
190 .context("decoding key custody")?
191 .map(|value| AccountKeyCustody::parse(&value))
192 .transpose()?;
193 Ok(UserProfile {
194 sub: Some(row.get(0).context("decoding stable subject")?),
195 name: self.cipher.open_text(
196 root,
197 username,
198 EncryptedColumn::ProfileName,
199 row.get(1).context("decoding name")?,
200 )?,
201 email: self.cipher.open_text(
202 root,
203 username,
204 EncryptedColumn::ProfileEmail,
205 row.get(2).context("decoding email")?,
206 )?,
207 email_verified: row.get(3).context("decoding email verification")?,
208 active: Some(row.get(4).context("decoding active state")?),
209 external_id: self.cipher.open_text(
210 root,
211 username,
212 EncryptedColumn::ProfileExternalId,
213 row.get(5).context("decoding external ID")?,
214 )?,
215 atproto_did: row.get(7).context("decoding ATProto DID")?,
216 key_custody: custody,
217 external_identities,
218 })
219 }
220
221 fn decode_key(
223 &self,
224 row: &Row,
225 username: &str,
226 root: &Zeroizing<[u8; ROOT_DEK_BYTES]>,
227 ) -> Result<PubkeyEntry> {
228 let fingerprint: String = row.get(0).context("decoding fingerprint")?;
229 let raw: Vec<u8> = row.get(1).context("decoding Ed25519 key")?;
230 let decrypted_pk = self.cipher.open_raw(
231 root,
232 username,
233 EncryptedColumn::PublicKey {
234 fingerprint: &fingerprint,
235 },
236 &raw,
237 )?;
238 let raw: [u8; 32] = decrypted_pk
239 .as_slice()
240 .try_into()
241 .map_err(|_| anyhow!("stored Ed25519 key {fingerprint} is not 32 bytes"))?;
242 let pubkey = VerifyingKey::from_bytes(&raw)
243 .with_context(|| format!("decoding Ed25519 key {fingerprint}"))?;
244 ensure!(
245 super::pubkey_fingerprint(&pubkey) == fingerprint,
246 "stored key does not match fingerprint {fingerprint}"
247 );
248 let algorithm_raw: String = row.get(5).context("decoding key algorithm")?;
249 let algorithm = KeyAlgorithm::parse(&algorithm_raw)?;
250 let pq_raw: Option<Vec<u8>> = row.get(6).context("decoding ML-DSA-65 key")?;
251 let pq_pubkey = match (algorithm.is_hybrid(), pq_raw) {
252 (false, None) => None,
253 (true, Some(key_bytes)) => {
254 let mut pt = self.cipher.open_raw(
255 root,
256 username,
257 EncryptedColumn::PqPublicKey {
258 fingerprint: &fingerprint,
259 },
260 &key_bytes,
261 )?;
262 ensure!(
263 pt.len() == 1952,
264 "hybrid key {fingerprint} has invalid ML-DSA-65 material"
265 );
266 Some(std::mem::take(&mut *pt))
267 }
268 (true, None) => bail!("hybrid key {fingerprint} has invalid ML-DSA-65 material"),
269 (false, Some(_)) => bail!("classical key {fingerprint} carries ML-DSA-65 material"),
270 };
271 let label = self.cipher.open_text(
272 root,
273 username,
274 EncryptedColumn::PublicKeyLabel {
275 fingerprint: &fingerprint,
276 },
277 row.get(2).context("decoding key label")?,
278 )?;
279 Ok(PubkeyEntry {
280 fingerprint,
281 pubkey,
282 label,
283 created_at: row.get(3).context("decoding key creation time")?,
284 last_used_at: row.get(4).context("decoding key last-used time")?,
285 algorithm,
286 pq_pubkey,
287 })
288 }
289}
290
291fn decode_external_identity(row: &Row) -> Result<ExternalIdentityBinding> {
292 Ok(ExternalIdentityBinding {
293 issuer: row.get(0).context("decoding external identity issuer")?,
294 subject: row.get(1).context("decoding external identity subject")?,
295 })
296}
297
298fn hosted_backend(error: impl Into<anyhow::Error>) -> HostedAccountProvisionError {
299 HostedAccountProvisionError::Backend(error.into())
300}
301
302#[cfg(not(test))]
303impl super::user_store::private::Sealed for PgliteUserStore {}
304
305#[async_trait]
306impl UserStore for PgliteUserStore {
307 async fn get_profile(&self, username: &str) -> Result<Option<UserProfile>> {
308 let rows = self.database.query(PROFILE_SELECT, &[&username]).await?;
309 ensure!(rows.len() <= 1, "username primary key returned duplicates");
310 let Some(row) = rows.first() else {
311 return Ok(None);
312 };
313 let bindings = self.external_identities(username).await?;
314 let root = self.load_user_key(username).await?;
315 Ok(Some(self.decode_profile(row, bindings, username, &root)?))
316 }
317
318 async fn register(&self, username: &str) -> Result<String> {
319 ensure!(!username.is_empty(), "username must be non-empty");
320 let sub = uuid::Uuid::new_v4().to_string();
321 let tx = self.database.transaction().await?;
322 tx.query(
323 "INSERT INTO users(username, sub, active) VALUES($1, $2, TRUE)",
324 &[&username, &sub],
325 )
326 .await?;
327 self.create_user_key(&tx, username).await?;
328 tx.commit().await?;
329 Ok(sub)
330 }
331
332 async fn resolve_or_bind_external_idp(
333 &self,
334 issuer: &str,
335 subject: &str,
336 username: &str,
337 ) -> Result<ExternalIdentityResolution> {
338 ensure!(
339 !issuer.is_empty() && !subject.is_empty() && !username.is_empty(),
340 "issuer, subject, and username must be non-empty"
341 );
342 let tx = self.database.transaction().await?;
343 let existing = tx
344 .query(
345 "SELECT b.username, u.sub FROM oidc_bindings b \
346 JOIN users u ON u.username=b.username \
347 WHERE b.issuer=$1 AND b.issuer_sub=$2",
348 &[&issuer, &subject],
349 )
350 .await?;
351 ensure!(
352 existing.len() <= 1,
353 "external identity primary key returned duplicates"
354 );
355 if let Some(row) = existing.first() {
356 let resolved_username: String = row.get(0)?;
357 let sub: String = row.get(1)?;
358 ensure!(
359 !resolved_username.is_empty() && !sub.is_empty(),
360 "external identity points at a corrupt local user"
361 );
362 tx.commit().await?;
363 return Ok(ExternalIdentityResolution {
364 username: resolved_username,
365 sub,
366 provisioned: false,
367 });
368 }
369
370 let users = tx
371 .query("SELECT sub FROM users WHERE username=$1", &[&username])
372 .await?;
373 ensure!(users.len() <= 1, "username primary key returned duplicates");
374 ensure!(
375 users.is_empty(),
376 "candidate username already belongs to a local account"
377 );
378 let sub = uuid::Uuid::new_v4().to_string();
379 tx.query(
380 "INSERT INTO users(username, sub, active) VALUES($1, $2, TRUE)",
381 &[&username, &sub],
382 )
383 .await?;
384 self.create_user_key(&tx, username).await?;
385 tx.query(
386 "INSERT INTO oidc_bindings(issuer, issuer_sub, username) VALUES($1, $2, $3)",
387 &[&issuer, &subject, &username],
388 )
389 .await?;
390 tx.commit().await?;
391 Ok(ExternalIdentityResolution {
392 username: username.to_owned(),
393 sub,
394 provisioned: true,
395 })
396 }
397
398 async fn bind_existing_external_idp_to_hosted_account(
399 &self,
400 issuer: &str,
401 subject: &str,
402 username: &str,
403 expected_hosted_did: &str,
404 ) -> Result<ExternalIdentityResolution> {
405 ensure!(
406 !issuer.is_empty()
407 && !subject.is_empty()
408 && !username.is_empty()
409 && !expected_hosted_did.is_empty(),
410 "issuer, subject, username, and hosted DID must be non-empty"
411 );
412
413 let tx = self.database.transaction().await?;
414 let owner_rows = tx
415 .query(
416 "SELECT username, sub, active, key_custody FROM users \
417 WHERE username=$1 FOR UPDATE",
418 &[&username],
419 )
420 .await?;
421 ensure!(
422 owner_rows.len() == 1,
423 "configured hosted account is missing or ambiguous"
424 );
425 let owner_row = &owner_rows[0];
426 let resolved_username: String = owner_row.get(0)?;
427 let sub: String = owner_row.get(1)?;
428 let active: bool = owner_row.get(2)?;
429 let custody: Option<String> = owner_row.get(3)?;
430 let hosted_rows = tx
434 .query(
435 "SELECT d.atproto_did, \
436 EXISTS(SELECT 1 FROM pubkeys p WHERE p.username=d.username \
437 AND p.algorithm='ed25519' AND p.pq_pubkey IS NULL) \
438 FROM user_did_bindings d WHERE d.username=$1",
439 &[&username],
440 )
441 .await?;
442 ensure!(
443 hosted_rows.len() == 1,
444 "hosted account DID binding is missing or ambiguous"
445 );
446 let hosted_did: String = hosted_rows[0].get(0)?;
447 let has_hosted_key: bool = hosted_rows[0].get(1)?;
448 ensure!(
449 resolved_username == username
450 && !sub.is_empty()
451 && active
452 && custody.is_some()
453 && has_hosted_key
454 && hosted_did == expected_hosted_did,
455 "configured user is not the expected active hosted account"
456 );
457
458 let existing = tx
459 .query(
460 "SELECT b.username, u.sub FROM oidc_bindings b \
461 JOIN users u ON u.username=b.username \
462 WHERE b.issuer=$1 AND b.issuer_sub=$2",
463 &[&issuer, &subject],
464 )
465 .await?;
466 ensure!(
467 existing.len() <= 1,
468 "external identity primary key returned duplicates"
469 );
470 if let Some(row) = existing.first() {
471 let bound_username: String = row.get(0)?;
472 let bound_sub: String = row.get(1)?;
473 ensure!(
474 bound_username == username && !bound_sub.is_empty(),
475 "external identity is already bound to a different account"
476 );
477 tx.commit().await?;
478 return Ok(ExternalIdentityResolution {
479 username: bound_username,
480 sub: bound_sub,
481 provisioned: false,
482 });
483 }
484
485 let account_binding = tx
486 .query(
487 "SELECT issuer_sub FROM oidc_bindings WHERE issuer=$1 AND username=$2",
488 &[&issuer, &username],
489 )
490 .await?;
491 ensure!(
492 account_binding.is_empty(),
493 "hosted account already has a different identity from this issuer"
494 );
495
496 tx.query(
497 "INSERT INTO oidc_bindings(issuer, issuer_sub, username) VALUES($1, $2, $3)",
498 &[&issuer, &subject, &username],
499 )
500 .await?;
501 tx.commit().await?;
502 Ok(ExternalIdentityResolution {
503 username: resolved_username,
504 sub,
505 provisioned: false,
506 })
507 }
508
509 async fn provision_hosted_account(
510 &self,
511 username: &str,
512 atproto_did: &str,
513 pubkey: VerifyingKey,
514 custody: AccountKeyCustody,
515 ) -> std::result::Result<HostedAccountProvisioning, HostedAccountProvisionError> {
516 if username.is_empty() || atproto_did.is_empty() {
517 return Err(hosted_backend(anyhow!(
518 "hosted username and DID must be non-empty"
519 )));
520 }
521 let fingerprint = super::pubkey_fingerprint(&pubkey);
522 let tx = self.database.transaction().await.map_err(hosted_backend)?;
523
524 let profiles = tx
527 .query(PROFILE_SELECT, &[&username])
528 .await
529 .map_err(hosted_backend)?;
530 if let Some(profile_row) = profiles.first() {
531 let root = self
533 .load_user_key_tx(&tx, username)
534 .await
535 .map_err(hosted_backend)?;
536 if profiles.len() != 1 {
537 return Err(hosted_backend(anyhow!(
538 "username primary key returned duplicates"
539 )));
540 }
541 let bindings = tx
542 .query(
543 "SELECT issuer, issuer_sub FROM oidc_bindings WHERE username=$1",
544 &[&username],
545 )
546 .await
547 .map_err(hosted_backend)?;
548 let bindings = bindings
549 .iter()
550 .map(decode_external_identity)
551 .collect::<Result<Vec<_>>>()
552 .map_err(hosted_backend)?;
553 let profile = self
554 .decode_profile(profile_row, bindings, username, &root)
555 .map_err(hosted_backend)?;
556 let key_rows = tx
557 .query(KEY_SELECT, &[&username])
558 .await
559 .map_err(hosted_backend)?;
560 let keys = key_rows
561 .iter()
562 .map(|r| self.decode_key(r, username, &root))
563 .collect::<Result<Vec<_>>>()
564 .map_err(hosted_backend)?;
565 let exact_key = keys.iter().any(|key| {
566 key.fingerprint == fingerprint
567 && key.pubkey.as_bytes() == pubkey.as_bytes()
568 && key.algorithm == KeyAlgorithm::Ed25519
569 && key.pq_pubkey.is_none()
570 });
571 let exact = profile.sub.as_deref().is_some_and(|sub| !sub.is_empty())
572 && profile.active.is_some()
573 && profile.atproto_did.as_deref() == Some(atproto_did)
574 && profile.key_custody == Some(custody)
575 && profile.external_identities.is_empty()
576 && exact_key;
577 if exact {
578 let sub = profile
579 .sub
580 .context("checked above")
581 .map_err(hosted_backend)?;
582 tx.commit().await.map_err(hosted_backend)?;
583 return Ok(HostedAccountProvisioning {
584 sub,
585 fingerprint,
586 resumed: true,
587 });
588 }
589 let usable = profile.active == Some(true)
590 && profile.sub.as_deref().is_some_and(|sub| !sub.is_empty())
591 && profile
592 .atproto_did
593 .as_deref()
594 .is_some_and(|did| did.starts_with("did:web:"))
595 && profile.key_custody.is_some()
596 && !keys.is_empty();
597 if usable {
598 tx.commit().await.map_err(hosted_backend)?;
599 return Err(HostedAccountProvisionError::AccountAlreadyExists);
600 }
601 return Err(hosted_backend(anyhow!(
602 "existing hosted-account username has incomplete or inactive state"
603 )));
604 }
605
606 let owner_rows = tx
607 .query(
608 "SELECT username FROM pubkeys WHERE fingerprint=$1",
609 &[&fingerprint],
610 )
611 .await
612 .map_err(hosted_backend)?;
613 if let Some(owner_row) = owner_rows.first() {
614 if owner_rows.len() != 1 {
615 return Err(hosted_backend(anyhow!(
616 "fingerprint primary key returned duplicates"
617 )));
618 }
619 let owner: String = owner_row.get(0).map_err(hosted_backend)?;
620 let owner_root = self
621 .load_user_key_tx(&tx, &owner)
622 .await
623 .map_err(hosted_backend)?;
624 let owner_profiles = tx
625 .query(PROFILE_SELECT, &[&owner])
626 .await
627 .map_err(hosted_backend)?;
628 let owner_keys = tx
629 .query(KEY_SELECT, &[&owner])
630 .await
631 .map_err(hosted_backend)?;
632 let keys = owner_keys
633 .iter()
634 .map(|r| self.decode_key(r, &owner, &owner_root))
635 .collect::<Result<Vec<_>>>()
636 .map_err(hosted_backend)?;
637 let profile = owner_profiles
638 .first()
639 .ok_or_else(|| hosted_backend(anyhow!("key owner profile is missing")))
640 .and_then(|row| {
641 self.decode_profile(row, Vec::new(), &owner, &owner_root)
642 .map_err(hosted_backend)
643 })?;
644 let exact_usable_key = keys.iter().any(|key| key.fingerprint == fingerprint);
645 let usable = profile.active == Some(true)
646 && profile.sub.as_deref().is_some_and(|sub| !sub.is_empty())
647 && profile
648 .atproto_did
649 .as_deref()
650 .is_some_and(|did| did.starts_with("did:web:"))
651 && profile.key_custody.is_some()
652 && exact_usable_key;
653 if usable {
654 tx.commit().await.map_err(hosted_backend)?;
655 return Err(HostedAccountProvisionError::KeyAlreadyBound);
656 }
657 return Err(hosted_backend(anyhow!(
658 "existing hosted-account key owner is incomplete or inactive"
659 )));
660 }
661
662 let sub = uuid::Uuid::new_v4().to_string();
663 let now = chrono::Utc::now().timestamp();
664 tx.query(
667 "INSERT INTO users(username, sub, active, key_custody) \
668 VALUES($1, $2, FALSE, $3)",
669 &[&username, &sub, &custody.as_str()],
670 )
671 .await
672 .map_err(hosted_backend)?;
673 let create_root = self
675 .create_user_key(&tx, username)
676 .await
677 .map_err(hosted_backend)?;
678 let pk_bytes = self
679 .cipher
680 .seal_raw(
681 &create_root,
682 username,
683 EncryptedColumn::PublicKey {
684 fingerprint: &fingerprint,
685 },
686 pubkey.as_bytes(),
687 )
688 .map_err(hosted_backend)?;
689 let label_bytes = self
690 .cipher
691 .seal_text(
692 &create_root,
693 username,
694 EncryptedColumn::PublicKeyLabel {
695 fingerprint: &fingerprint,
696 },
697 Some("aegis-vault".to_owned()),
698 )
699 .map_err(hosted_backend)?;
700 tx.query(
701 "INSERT INTO user_did_bindings(username, atproto_did) VALUES($1, $2)",
702 &[&username, &atproto_did],
703 )
704 .await
705 .map_err(hosted_backend)?;
706 tx.query(
707 "INSERT INTO pubkeys(fingerprint, username, pubkey, label, algorithm, \
708 pq_pubkey, created_at) VALUES($1, $2, $3, $4, 'ed25519', NULL, $5)",
709 &[&fingerprint, &username, &pk_bytes, &label_bytes, &now],
710 )
711 .await
712 .map_err(hosted_backend)?;
713 tx.commit().await.map_err(hosted_backend)?;
714 Ok(HostedAccountProvisioning {
715 sub,
716 fingerprint,
717 resumed: false,
718 })
719 }
720
721 async fn activate_hosted_account(
722 &self,
723 username: &str,
724 atproto_did: &str,
725 fingerprint: &str,
726 custody: AccountKeyCustody,
727 ) -> std::result::Result<(), HostedAccountProvisionError> {
728 let tx = self.database.transaction().await.map_err(hosted_backend)?;
729 let root = self
730 .load_user_key_tx(&tx, username)
731 .await
732 .map_err(hosted_backend)?;
733 let rows = tx
734 .query(PROFILE_SELECT, &[&username])
735 .await
736 .map_err(hosted_backend)?;
737 let profile = rows
738 .first()
739 .ok_or_else(|| hosted_backend(anyhow!("staged hosted account is missing")))
740 .and_then(|row| {
741 self.decode_profile(row, Vec::new(), username, &root)
742 .map_err(hosted_backend)
743 })?;
744 let keys = tx
745 .query(KEY_SELECT, &[&username])
746 .await
747 .map_err(hosted_backend)?;
748 let keys = keys
749 .iter()
750 .map(|r| self.decode_key(r, username, &root))
751 .collect::<Result<Vec<_>>>()
752 .map_err(hosted_backend)?;
753 let exact_key = keys.iter().any(|key| {
754 key.fingerprint == fingerprint
755 && key.algorithm == KeyAlgorithm::Ed25519
756 && key.pq_pubkey.is_none()
757 });
758 if profile.sub.as_deref().is_none_or(str::is_empty)
759 || profile.atproto_did.as_deref() != Some(atproto_did)
760 || profile.key_custody != Some(custody)
761 || !exact_key
762 {
763 return Err(hosted_backend(anyhow!(
764 "staged hosted-account binding changed before activation"
765 )));
766 }
767 match profile.active {
768 Some(true) => {
769 tx.commit().await.map_err(hosted_backend)?;
770 Ok(())
771 }
772 Some(false) => {
773 let updated = tx
774 .query(
775 "UPDATE users SET active=TRUE, updated_at=now() \
776 WHERE username=$1 AND active=FALSE RETURNING username",
777 &[&username],
778 )
779 .await
780 .map_err(hosted_backend)?;
781 if updated.len() != 1 {
782 return Err(hosted_backend(anyhow!(
783 "staged hosted-account activation updated no exact row"
784 )));
785 }
786 tx.commit().await.map_err(hosted_backend)
787 }
788 None => Err(hosted_backend(anyhow!(
789 "staged hosted-account binding has invalid activation state"
790 ))),
791 }
792 }
793
794 async fn set_profile(&self, username: &str, patch: UserProfilePatch) -> Result<()> {
795 ensure!(
796 patch.external_identities.is_none(),
797 "set_profile cannot modify normalized external identity bindings"
798 );
799 let tx = self.database.transaction().await?;
800 let root = self.load_user_key_tx(&tx, username).await?;
801 let rows = tx.query(PROFILE_SELECT, &[&username]).await?;
802 ensure!(rows.len() <= 1, "username primary key returned duplicates");
803 let row = rows.first().context("unknown user")?;
804 let mut profile = self.decode_profile(row, Vec::new(), username, &root)?;
805 if let Some(Some(sub)) = patch.sub {
806 ensure!(!sub.is_empty(), "stable subject must be non-empty");
807 profile.sub = Some(sub);
808 }
809 if let Some(value) = patch.name {
810 profile.name = value;
811 }
812 if let Some(value) = patch.email {
813 profile.email = value;
814 }
815 if let Some(value) = patch.email_verified {
816 profile.email_verified = value;
817 }
818 if let Some(value) = patch.active {
819 profile.active = Some(value.unwrap_or(true));
820 }
821 if let Some(value) = patch.external_id {
822 profile.external_id = value;
823 }
824 let did_update = patch.atproto_did;
825 if let Some(value) = did_update.as_ref() {
826 profile.atproto_did = value.clone();
827 }
828 if let Some(value) = patch.key_custody {
829 profile.key_custody = value;
830 }
831 let sub = profile.sub.context("user has no stable subject")?;
832 let name =
833 self.cipher
834 .seal_text(&root, username, EncryptedColumn::ProfileName, profile.name)?;
835 let email = self.cipher.seal_text(
836 &root,
837 username,
838 EncryptedColumn::ProfileEmail,
839 profile.email,
840 )?;
841 let external_id = self.cipher.seal_text(
842 &root,
843 username,
844 EncryptedColumn::ProfileExternalId,
845 profile.external_id,
846 )?;
847 let custody = profile.key_custody.map(AccountKeyCustody::as_str);
848 tx.query(
849 "UPDATE users SET sub=$2, name=$3, email=$4, email_verified=$5, \
850 active=$6, external_id=$7, key_custody=$8, updated_at=now() \
851 WHERE username=$1 RETURNING username",
852 &[
853 &username,
854 &sub,
855 &name,
856 &email,
857 &profile.email_verified,
858 &profile.active.unwrap_or(true),
859 &external_id,
860 &custody,
861 ],
862 )
863 .await?;
864 if let Some(did) = did_update {
865 tx.query(
866 "DELETE FROM user_did_bindings WHERE username=$1",
867 &[&username],
868 )
869 .await?;
870 if let Some(did) = did {
871 tx.query(
872 "INSERT INTO user_did_bindings(username, atproto_did) VALUES($1, $2)",
873 &[&username, &did],
874 )
875 .await?;
876 }
877 }
878 tx.commit().await?;
879 Ok(())
880 }
881
882 async fn remove(&self, username: &str) -> Result<bool> {
883 let rows = self
884 .database
885 .query(
886 "DELETE FROM users WHERE username=$1 RETURNING username",
887 &[&username],
888 )
889 .await?;
890 Ok(rows.len() == 1)
891 }
892
893 async fn list_users(&self) -> Result<Vec<String>> {
894 self.database
895 .query("SELECT username FROM users ORDER BY username", &[])
896 .await?
897 .iter()
898 .map(|row| row.get(0).map_err(Into::into))
899 .collect()
900 }
901
902 async fn search(&self, filter: &UserFilter) -> Result<Vec<(String, UserProfile)>> {
903 let mut results = Vec::new();
904 for username in self.list_users().await? {
905 let profile = self
906 .get_profile(&username)
907 .await?
908 .context("listed user profile is missing")?;
909 if filter.active_only == Some(true) && profile.active == Some(false) {
910 continue;
911 }
912 if filter.filter.as_ref().is_some_and(|expr| {
913 !matches_filter(
914 expr,
915 &username,
916 &profile.sub,
917 &profile.external_id,
918 profile.active,
919 )
920 }) {
921 continue;
922 }
923 results.push((username, profile));
924 }
925 if let Some(sort_by) = filter.sort_by.as_deref() {
926 let descending = filter.sort_order.as_deref() == Some("descending");
927 results.sort_by(|left, right| {
928 let ordering = match sort_by {
929 "userName" => left.0.cmp(&right.0),
930 "id" | "sub" => left.1.sub.cmp(&right.1.sub),
931 "active" => left.1.active.cmp(&right.1.active),
932 "displayName" | "name" => left.1.name.cmp(&right.1.name),
933 "externalId" => left.1.external_id.cmp(&right.1.external_id),
934 _ => std::cmp::Ordering::Equal,
935 };
936 if descending {
937 ordering.reverse()
938 } else {
939 ordering
940 }
941 });
942 }
943 let start = filter.start_index.unwrap_or(1).saturating_sub(1);
944 let count = filter.count.unwrap_or(100);
945 Ok(results.into_iter().skip(start).take(count).collect())
946 }
947
948 async fn set_active(&self, username: &str, active: bool) -> Result<()> {
949 let rows = self
950 .database
951 .query(
952 "UPDATE users SET active=$2, updated_at=now() \
953 WHERE username=$1 RETURNING username",
954 &[&username, &active],
955 )
956 .await?;
957 ensure!(rows.len() == 1, "unknown user");
958 Ok(())
959 }
960
961 async fn list_pubkeys(&self, username: &str) -> Result<Vec<PubkeyEntry>> {
962 let exists = self
963 .database
964 .query(
965 "SELECT 1::BIGINT FROM users WHERE username=$1",
966 &[&username],
967 )
968 .await?;
969 ensure!(exists.len() == 1, "unknown user");
970 let root = self.load_user_key(username).await?;
971 let rows = self.database.query(KEY_SELECT, &[&username]).await?;
972 rows.iter()
973 .map(|r| self.decode_key(r, username, &root))
974 .collect()
975 }
976
977 async fn add_pubkey(
978 &self,
979 username: &str,
980 pubkey: VerifyingKey,
981 label: Option<String>,
982 ) -> Result<String> {
983 let fingerprint = super::pubkey_fingerprint(&pubkey);
984 let now = chrono::Utc::now().timestamp();
985 let root = self.load_user_key(username).await?;
986 let pk_bytes = self.cipher.seal_raw(
987 &root,
988 username,
989 EncryptedColumn::PublicKey {
990 fingerprint: &fingerprint,
991 },
992 pubkey.as_bytes(),
993 )?;
994 let label_bytes = self.cipher.seal_text(
995 &root,
996 username,
997 EncryptedColumn::PublicKeyLabel {
998 fingerprint: &fingerprint,
999 },
1000 label,
1001 )?;
1002 self.database
1003 .query(
1004 "INSERT INTO pubkeys(fingerprint, username, pubkey, label, algorithm, \
1005 pq_pubkey, created_at) VALUES($1, $2, $3, $4, 'ed25519', NULL, $5)",
1006 &[&fingerprint, &username, &pk_bytes, &label_bytes, &now],
1007 )
1008 .await?;
1009 Ok(fingerprint)
1010 }
1011
1012 async fn add_pubkey_hybrid(
1013 &self,
1014 username: &str,
1015 pubkey: VerifyingKey,
1016 ml_dsa_vk: Vec<u8>,
1017 label: Option<String>,
1018 ) -> Result<String> {
1019 ensure!(
1020 ml_dsa_vk.len() == 1952,
1021 "ML-DSA-65 verifying key must be exactly 1952 bytes"
1022 );
1023 let fingerprint = super::pubkey_fingerprint(&pubkey);
1024 let root = self.load_user_key(username).await?;
1025 let tx = self.database.transaction().await?;
1026 let existing = tx
1027 .query(
1028 "SELECT username, pubkey, algorithm, pq_pubkey FROM pubkeys \
1029 WHERE fingerprint=$1",
1030 &[&fingerprint],
1031 )
1032 .await?;
1033 if let Some(row) = existing.first() {
1034 let owner: String = row.get(0)?;
1035 let stored_key: Vec<u8> = row.get(1)?;
1036 let algorithm: String = row.get(2)?;
1037 let pq: Option<Vec<u8>> = row.get(3)?;
1038 let decrypted_key = self.cipher.open_raw(
1040 &root,
1041 username,
1042 EncryptedColumn::PublicKey {
1043 fingerprint: &fingerprint,
1044 },
1045 &stored_key,
1046 )?;
1047 ensure!(owner == username, "pubkey is already bound to another user");
1048 ensure!(
1049 decrypted_key.as_slice() == pubkey.as_bytes(),
1050 "fingerprint row carries different Ed25519 bytes"
1051 );
1052 ensure!(
1053 algorithm == "ed25519" && pq.is_none(),
1054 "only a classical key can be upgraded to hybrid"
1055 );
1056 let label_bytes = self.cipher.seal_text(
1057 &root,
1058 username,
1059 EncryptedColumn::PublicKeyLabel {
1060 fingerprint: &fingerprint,
1061 },
1062 label,
1063 )?;
1064 let pq_sealed = self.cipher.seal_raw(
1065 &root,
1066 username,
1067 EncryptedColumn::PqPublicKey {
1068 fingerprint: &fingerprint,
1069 },
1070 &ml_dsa_vk,
1071 )?;
1072 tx.query(
1073 "UPDATE pubkeys SET algorithm='ed25519+ml-dsa-65', pq_pubkey=$2, \
1074 label=COALESCE($3, label) WHERE fingerprint=$1 RETURNING fingerprint",
1075 &[&fingerprint, &pq_sealed, &label_bytes],
1076 )
1077 .await?;
1078 } else {
1079 let now = chrono::Utc::now().timestamp();
1080 let pk_bytes = self.cipher.seal_raw(
1081 &root,
1082 username,
1083 EncryptedColumn::PublicKey {
1084 fingerprint: &fingerprint,
1085 },
1086 pubkey.as_bytes(),
1087 )?;
1088 let label_bytes = self.cipher.seal_text(
1089 &root,
1090 username,
1091 EncryptedColumn::PublicKeyLabel {
1092 fingerprint: &fingerprint,
1093 },
1094 label,
1095 )?;
1096 let pq_sealed = self.cipher.seal_raw(
1097 &root,
1098 username,
1099 EncryptedColumn::PqPublicKey {
1100 fingerprint: &fingerprint,
1101 },
1102 &ml_dsa_vk,
1103 )?;
1104 tx.query(
1105 "INSERT INTO pubkeys(fingerprint, username, pubkey, label, algorithm, \
1106 pq_pubkey, created_at) VALUES($1, $2, $3, $4, \
1107 'ed25519+ml-dsa-65', $5, $6)",
1108 &[
1109 &fingerprint,
1110 &username,
1111 &pk_bytes,
1112 &label_bytes,
1113 &pq_sealed,
1114 &now,
1115 ],
1116 )
1117 .await?;
1118 }
1119 tx.commit().await?;
1120 Ok(fingerprint)
1121 }
1122
1123 async fn remove_pubkey(&self, username: &str, fingerprint: &str) -> Result<bool> {
1124 let rows = self
1125 .database
1126 .query(
1127 "DELETE FROM pubkeys WHERE username=$1 AND fingerprint=$2 \
1128 RETURNING fingerprint",
1129 &[&username, &fingerprint],
1130 )
1131 .await?;
1132 Ok(rows.len() == 1)
1133 }
1134
1135 async fn get_pubkey_user(&self, fingerprint: &str) -> Result<Option<String>> {
1136 let rows = self
1137 .database
1138 .query(
1139 "SELECT username FROM pubkeys WHERE fingerprint=$1",
1140 &[&fingerprint],
1141 )
1142 .await?;
1143 ensure!(
1144 rows.len() <= 1,
1145 "fingerprint primary key returned duplicates"
1146 );
1147 rows.first()
1148 .map(|row| row.get(0).map_err(Into::into))
1149 .transpose()
1150 }
1151
1152 async fn touch_pubkey(&self, username: &str, fingerprint: &str) -> Result<()> {
1153 let now = chrono::Utc::now().timestamp();
1154 let rows = self
1155 .database
1156 .query(
1157 "UPDATE pubkeys SET last_used_at=$3 WHERE username=$1 AND fingerprint=$2 \
1158 RETURNING fingerprint",
1159 &[&username, &fingerprint, &now],
1160 )
1161 .await?;
1162 ensure!(rows.len() == 1, "unknown user or fingerprint");
1163 Ok(())
1164 }
1165
1166 async fn list_external_identities(
1167 &self,
1168 username: &str,
1169 ) -> Result<Vec<ExternalIdentityBinding>> {
1170 ensure!(self.get_profile(username).await?.is_some(), "unknown user");
1171 self.external_identities(username).await
1172 }
1173
1174 async fn get_external_identity_user(
1175 &self,
1176 issuer: &str,
1177 subject: &str,
1178 ) -> Result<Option<String>> {
1179 ensure!(
1180 !issuer.is_empty() && !subject.is_empty(),
1181 "external identity issuer and subject must be non-empty"
1182 );
1183 let rows = self
1184 .database
1185 .query(
1186 "SELECT b.username FROM oidc_bindings b \
1187 JOIN users u ON u.username=b.username \
1188 WHERE b.issuer=$1 AND b.issuer_sub=$2",
1189 &[&issuer, &subject],
1190 )
1191 .await?;
1192 ensure!(
1193 rows.len() <= 1,
1194 "external identity primary key returned duplicates"
1195 );
1196 rows.first()
1197 .map(|row| row.get(0).map_err(Into::into))
1198 .transpose()
1199 }
1200}
1201
1202#[cfg(all(test, feature = "pglite"))]
1203#[allow(
1204 clippy::unwrap_used,
1205 clippy::expect_used,
1206 clippy::mem_forget,
1207 deprecated
1208)]
1209pub(crate) mod tests {
1210 use super::*;
1211 use ed25519_dalek::SigningKey;
1212 use rand::rngs::OsRng;
1213
1214 use std::sync::OnceLock;
1215
1216 static SHARED_DB: OnceLock<PgliteUserStore> = OnceLock::new();
1220 static TEST_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
1221
1222 async fn shared() -> &'static PgliteUserStore {
1223 if let Some(s) = SHARED_DB.get() {
1224 return s;
1225 }
1226 let dir = tempfile::tempdir_in(std::env::current_dir().unwrap()).unwrap();
1227 let path = dir.path().to_owned();
1228 std::mem::forget(dir); let database = Arc::new(PGlite::open(&path).await.unwrap());
1230 let s = PgliteUserStore::with_cipher(database, ColumnCipher::test_cipher())
1231 .await
1232 .unwrap();
1233 let _ = SHARED_DB.set(s);
1234 SHARED_DB.get().unwrap()
1235 }
1236
1237 pub(crate) async fn fresh() -> (
1241 tokio::sync::MutexGuard<'static, ()>,
1242 &'static PgliteUserStore,
1243 ) {
1244 let guard = TEST_LOCK.lock().await;
1245 let s = shared().await;
1246 s.database.query("DELETE FROM users", &[]).await.unwrap();
1247 (guard, s)
1248 }
1249
1250 fn make_key() -> VerifyingKey {
1251 SigningKey::generate(&mut OsRng).verifying_key()
1252 }
1253
1254 async fn active_hosted_account(
1255 store: &PgliteUserStore,
1256 username: &str,
1257 did: &str,
1258 ) -> HostedAccountProvisioning {
1259 let key = make_key();
1260 let staged = store
1261 .provision_hosted_account(username, did, key, AccountKeyCustody::SelfCustody)
1262 .await
1263 .unwrap();
1264 store
1265 .activate_hosted_account(
1266 username,
1267 did,
1268 &staged.fingerprint,
1269 AccountKeyCustody::SelfCustody,
1270 )
1271 .await
1272 .unwrap();
1273 staged
1274 }
1275
1276 #[tokio::test]
1279 async fn register_get_profile_round_trip() {
1280 let (_guard, store) = fresh().await;
1281 let sub = store.register("alice").await.unwrap();
1282 let profile = store.get_profile("alice").await.unwrap().unwrap();
1283 assert_eq!(profile.sub.as_deref(), Some(sub.as_str()));
1284 assert_eq!(profile.active, Some(true));
1285 assert!(profile.external_identities.is_empty());
1286 }
1287
1288 #[tokio::test]
1289 async fn get_profile_missing_user_returns_none() {
1290 let (_guard, store) = fresh().await;
1291 assert!(store.get_profile("nobody").await.unwrap().is_none());
1292 }
1293
1294 #[tokio::test]
1295 async fn register_empty_username_fails() {
1296 let (_guard, store) = fresh().await;
1297 assert!(store.register("").await.is_err());
1298 }
1299
1300 #[tokio::test]
1301 async fn set_profile_updates_columns() {
1302 let (_guard, store) = fresh().await;
1303 store.register("alice").await.unwrap();
1304 store
1305 .set_profile(
1306 "alice",
1307 UserProfilePatch {
1308 name: Some(Some("Alice".to_owned())),
1309 email: Some(Some("alice@example.com".to_owned())),
1310 email_verified: Some(Some(true)),
1311 ..Default::default()
1312 },
1313 )
1314 .await
1315 .unwrap();
1316 let profile = store.get_profile("alice").await.unwrap().unwrap();
1317 assert_eq!(profile.name.as_deref(), Some("Alice"));
1318 assert_eq!(profile.email.as_deref(), Some("alice@example.com"));
1319 assert_eq!(profile.email_verified, Some(true));
1320 }
1321
1322 #[tokio::test]
1323 async fn set_profile_atproto_did_clears_binding() {
1324 let (_guard, store) = fresh().await;
1325 store.register("alice").await.unwrap();
1326 store
1327 .set_profile(
1328 "alice",
1329 UserProfilePatch {
1330 atproto_did: Some(Some("did:web:alice.example".to_owned())),
1331 ..Default::default()
1332 },
1333 )
1334 .await
1335 .unwrap();
1336 assert_eq!(
1337 store
1338 .get_profile("alice")
1339 .await
1340 .unwrap()
1341 .unwrap()
1342 .atproto_did,
1343 Some("did:web:alice.example".to_owned())
1344 );
1345 store
1347 .set_profile(
1348 "alice",
1349 UserProfilePatch {
1350 atproto_did: Some(None),
1351 ..Default::default()
1352 },
1353 )
1354 .await
1355 .unwrap();
1356 assert_eq!(
1357 store
1358 .get_profile("alice")
1359 .await
1360 .unwrap()
1361 .unwrap()
1362 .atproto_did,
1363 None
1364 );
1365 }
1366
1367 #[tokio::test]
1368 async fn set_profile_unknown_user_fails() {
1369 let (_guard, store) = fresh().await;
1370 assert!(store
1371 .set_profile("nobody", UserProfilePatch::default())
1372 .await
1373 .is_err());
1374 }
1375
1376 #[tokio::test]
1377 async fn remove_cascades_pubkeys_and_did_binding() {
1378 let (_guard, store) = fresh().await;
1379 store.register("alice").await.unwrap();
1380 let key = make_key();
1381 let fp = store.add_pubkey("alice", key, None).await.unwrap();
1382 store
1383 .set_profile(
1384 "alice",
1385 UserProfilePatch {
1386 atproto_did: Some(Some("did:web:alice.example".to_owned())),
1387 ..Default::default()
1388 },
1389 )
1390 .await
1391 .unwrap();
1392 assert!(store.remove("alice").await.unwrap());
1393 assert!(store.get_profile("alice").await.unwrap().is_none());
1394 assert!(store.get_pubkey_user(&fp).await.unwrap().is_none());
1395 }
1396
1397 #[tokio::test]
1398 async fn set_active_toggles() {
1399 let (_guard, store) = fresh().await;
1400 store.register("alice").await.unwrap();
1401 store.set_active("alice", false).await.unwrap();
1402 assert_eq!(
1403 store.get_profile("alice").await.unwrap().unwrap().active,
1404 Some(false)
1405 );
1406 store.set_active("alice", true).await.unwrap();
1407 assert_eq!(
1408 store.get_profile("alice").await.unwrap().unwrap().active,
1409 Some(true)
1410 );
1411 }
1412
1413 #[tokio::test]
1416 async fn search_filters_and_paginates() {
1417 let (_guard, store) = fresh().await;
1418 store.register("alice").await.unwrap();
1419 store.register("bob").await.unwrap();
1420 store.register("carol").await.unwrap();
1421 store.set_active("bob", false).await.unwrap();
1422
1423 let active = store
1424 .search(&UserFilter {
1425 active_only: Some(true),
1426 ..Default::default()
1427 })
1428 .await
1429 .unwrap();
1430 assert_eq!(active.len(), 2);
1431
1432 let filtered = store
1433 .search(&UserFilter {
1434 filter: Some(r#"userName eq "alice""#.to_owned()),
1435 ..Default::default()
1436 })
1437 .await
1438 .unwrap();
1439 assert_eq!(filtered.len(), 1);
1440 assert_eq!(filtered[0].0, "alice");
1441
1442 let paged = store
1443 .search(&UserFilter {
1444 count: Some(1),
1445 start_index: Some(2),
1446 sort_by: Some("userName".to_owned()),
1447 ..Default::default()
1448 })
1449 .await
1450 .unwrap();
1451 assert_eq!(paged.len(), 1);
1452 assert_eq!(paged[0].0, "bob");
1453 }
1454
1455 #[tokio::test]
1458 async fn add_list_remove_pubkey() {
1459 let (_guard, store) = fresh().await;
1460 store.register("alice").await.unwrap();
1461 let key = make_key();
1462 let fp = store
1463 .add_pubkey("alice", key, Some("laptop".to_owned()))
1464 .await
1465 .unwrap();
1466 let keys = store.list_pubkeys("alice").await.unwrap();
1467 assert_eq!(keys.len(), 1);
1468 assert_eq!(keys[0].fingerprint, fp);
1469 assert_eq!(keys[0].label.as_deref(), Some("laptop"));
1470 assert_eq!(keys[0].algorithm, KeyAlgorithm::Ed25519);
1471 assert!(keys[0].pq_pubkey.is_none());
1472
1473 assert_eq!(
1474 store.get_pubkey_user(&fp).await.unwrap().as_deref(),
1475 Some("alice")
1476 );
1477
1478 store.touch_pubkey("alice", &fp).await.unwrap();
1479 let keys = store.list_pubkeys("alice").await.unwrap();
1480 assert!(keys[0].last_used_at.is_some());
1481
1482 assert!(store.remove_pubkey("alice", &fp).await.unwrap());
1483 assert!(store.list_pubkeys("alice").await.unwrap().is_empty());
1484 }
1485
1486 #[tokio::test]
1487 async fn add_pubkey_hybrid_upgrades_classical() {
1488 let (_guard, store) = fresh().await;
1489 store.register("alice").await.unwrap();
1490 let key = make_key();
1491 let fp = store.add_pubkey("alice", key, None).await.unwrap();
1492
1493 let pq_vk = vec![0u8; 1952];
1494 store
1495 .add_pubkey_hybrid("alice", key, pq_vk, Some("hybrid".to_owned()))
1496 .await
1497 .unwrap();
1498 let keys = store.list_pubkeys("alice").await.unwrap();
1499 assert_eq!(keys.len(), 1);
1500 assert_eq!(keys[0].fingerprint, fp);
1501 assert_eq!(keys[0].algorithm, KeyAlgorithm::HybridEd25519MlDsa65);
1502 assert!(keys[0].pq_pubkey.is_some());
1503 assert_eq!(keys[0].pq_pubkey.as_ref().unwrap().len(), 1952);
1504 }
1505
1506 #[tokio::test]
1507 async fn add_pubkey_hybrid_wrong_length_fails() {
1508 let (_guard, store) = fresh().await;
1509 store.register("alice").await.unwrap();
1510 let key = make_key();
1511 assert!(store
1512 .add_pubkey_hybrid("alice", key, vec![0u8; 100], None)
1513 .await
1514 .is_err());
1515 }
1516
1517 #[tokio::test]
1520 async fn resolve_or_bind_creates_and_resolves() {
1521 let (_guard, store) = fresh().await;
1522 let res1 = store
1523 .resolve_or_bind_external_idp("https://idp.example", "sub-123", "alice")
1524 .await
1525 .unwrap();
1526 assert!(res1.provisioned);
1527 assert_eq!(res1.username, "alice");
1528
1529 let res2 = store
1532 .resolve_or_bind_external_idp("https://idp.example", "sub-123", "bob")
1533 .await
1534 .unwrap();
1535 assert!(!res2.provisioned);
1536 assert_eq!(res2.username, "alice");
1537 assert_eq!(res2.sub, res1.sub);
1538 }
1539
1540 #[tokio::test]
1541 async fn external_oidc_cannot_claim_existing_username() {
1542 let (_guard, store) = fresh().await;
1543 let original_sub = store.register("alice").await.unwrap();
1544 assert!(store
1545 .resolve_or_bind_external_idp("https://idp.example", "attacker", "alice")
1546 .await
1547 .is_err());
1548 assert_eq!(
1549 store
1550 .get_external_identity_user("https://idp.example", "attacker")
1551 .await
1552 .unwrap(),
1553 None
1554 );
1555 assert_eq!(
1556 store.get_profile("alice").await.unwrap().unwrap().sub,
1557 Some(original_sub)
1558 );
1559 }
1560
1561 #[tokio::test]
1562 async fn external_oidc_concurrent_username_collision_has_one_winner() {
1563 let (_guard, store) = fresh().await;
1564 let (first, second) = tokio::time::timeout(std::time::Duration::from_secs(10), async {
1565 tokio::join!(
1566 store.resolve_or_bind_external_idp("https://idp.example", "sub-1", "alice"),
1567 store.resolve_or_bind_external_idp("https://idp.example", "sub-2", "alice")
1568 )
1569 })
1570 .await
1571 .unwrap();
1572 assert_eq!(usize::from(first.is_ok()) + usize::from(second.is_ok()), 1);
1573 let bound_1 = store
1574 .get_external_identity_user("https://idp.example", "sub-1")
1575 .await
1576 .unwrap();
1577 let bound_2 = store
1578 .get_external_identity_user("https://idp.example", "sub-2")
1579 .await
1580 .unwrap();
1581 assert_eq!(
1582 usize::from(bound_1.is_some()) + usize::from(bound_2.is_some()),
1583 1
1584 );
1585 }
1586
1587 #[tokio::test]
1588 async fn bind_existing_hosted_account_is_idempotent_and_never_provisions() {
1589 let (_guard, store) = fresh().await;
1590 let did = "did:web:alice.example.com";
1591 let hosted = active_hosted_account(store, "alice", did).await;
1592
1593 let first = store
1594 .bind_existing_external_idp_to_hosted_account(
1595 "https://login.federate.to",
1596 "federate-subject",
1597 "alice",
1598 did,
1599 )
1600 .await
1601 .unwrap();
1602 let repeat = store
1603 .bind_existing_external_idp_to_hosted_account(
1604 "https://login.federate.to",
1605 "federate-subject",
1606 "alice",
1607 did,
1608 )
1609 .await
1610 .unwrap();
1611 assert_eq!(first, repeat);
1612 assert_eq!(first.sub, hosted.sub);
1613 assert!(!first.provisioned);
1614 assert_eq!(
1615 store
1616 .get_external_identity_user("https://login.federate.to", "federate-subject")
1617 .await
1618 .unwrap()
1619 .as_deref(),
1620 Some("alice")
1621 );
1622 }
1623
1624 #[tokio::test]
1625 async fn bind_existing_hosted_account_rejects_missing_or_inactive_target() {
1626 let (_guard, store) = fresh().await;
1627 assert!(store
1628 .bind_existing_external_idp_to_hosted_account(
1629 "https://login.federate.to",
1630 "unknown-owner",
1631 "missing",
1632 "did:web:missing.example.com",
1633 )
1634 .await
1635 .is_err());
1636 assert!(store.get_profile("missing").await.unwrap().is_none());
1637
1638 let did = "did:web:staged.example.com";
1639 let staged = store
1640 .provision_hosted_account("staged", did, make_key(), AccountKeyCustody::SelfCustody)
1641 .await
1642 .unwrap();
1643 assert!(store
1644 .bind_existing_external_idp_to_hosted_account(
1645 "https://login.federate.to",
1646 "inactive-owner",
1647 "staged",
1648 did,
1649 )
1650 .await
1651 .is_err());
1652 assert!(store
1653 .get_external_identity_user("https://login.federate.to", "inactive-owner")
1654 .await
1655 .unwrap()
1656 .is_none());
1657 assert_eq!(
1658 store.get_profile("staged").await.unwrap().unwrap().sub,
1659 Some(staged.sub)
1660 );
1661 }
1662
1663 #[tokio::test]
1664 async fn bind_existing_hosted_account_rejects_identity_and_account_conflicts() {
1665 let (_guard, store) = fresh().await;
1666 let alice_did = "did:web:alice.example.com";
1667 let bob_did = "did:web:bob.example.com";
1668 active_hosted_account(store, "alice", alice_did).await;
1669 active_hosted_account(store, "bob", bob_did).await;
1670
1671 store
1672 .bind_existing_external_idp_to_hosted_account(
1673 "https://login.federate.to",
1674 "bound-owner",
1675 "alice",
1676 alice_did,
1677 )
1678 .await
1679 .unwrap();
1680 assert!(store
1681 .bind_existing_external_idp_to_hosted_account(
1682 "https://login.federate.to",
1683 "bound-owner",
1684 "bob",
1685 bob_did,
1686 )
1687 .await
1688 .is_err());
1689 assert!(store
1690 .bind_existing_external_idp_to_hosted_account(
1691 "https://login.federate.to",
1692 "second-owner",
1693 "alice",
1694 alice_did,
1695 )
1696 .await
1697 .is_err());
1698 assert_eq!(
1699 store
1700 .get_external_identity_user("https://login.federate.to", "bound-owner")
1701 .await
1702 .unwrap()
1703 .as_deref(),
1704 Some("alice")
1705 );
1706 assert!(store
1707 .get_external_identity_user("https://login.federate.to", "second-owner")
1708 .await
1709 .unwrap()
1710 .is_none());
1711 }
1712
1713 #[tokio::test]
1714 async fn bind_existing_hosted_account_concurrent_identity_has_one_winner() {
1715 let (_guard, store) = fresh().await;
1716 let alice_did = "did:web:alice.example.com";
1717 let bob_did = "did:web:bob.example.com";
1718 active_hosted_account(store, "alice", alice_did).await;
1719 active_hosted_account(store, "bob", bob_did).await;
1720 let (alice, bob) = tokio::time::timeout(std::time::Duration::from_secs(10), async {
1721 tokio::join!(
1722 store.bind_existing_external_idp_to_hosted_account(
1723 "https://login.federate.to",
1724 "same-owner",
1725 "alice",
1726 alice_did,
1727 ),
1728 store.bind_existing_external_idp_to_hosted_account(
1729 "https://login.federate.to",
1730 "same-owner",
1731 "bob",
1732 bob_did,
1733 )
1734 )
1735 })
1736 .await
1737 .unwrap();
1738 assert_eq!(usize::from(alice.is_ok()) + usize::from(bob.is_ok()), 1);
1739 let winner = store
1740 .get_external_identity_user("https://login.federate.to", "same-owner")
1741 .await
1742 .unwrap()
1743 .unwrap();
1744 assert_eq!(winner, if alice.is_ok() { "alice" } else { "bob" });
1745 }
1746
1747 #[tokio::test]
1748 async fn bind_existing_hosted_account_rechecks_did_after_row_lock() {
1749 let (_guard, store) = fresh().await;
1750 let original_did = "did:web:alice.example.com";
1751 active_hosted_account(store, "alice", original_did).await;
1752
1753 let tx = store.database.transaction().await.unwrap();
1754 tx.exec("UPDATE users SET active=active WHERE username='alice'")
1755 .await
1756 .unwrap();
1757 tx.exec(
1758 "UPDATE user_did_bindings SET atproto_did='did:web:changed.example.com' \
1759 WHERE username='alice'",
1760 )
1761 .await
1762 .unwrap();
1763
1764 let bind = tokio::spawn(async move {
1765 store
1766 .bind_existing_external_idp_to_hosted_account(
1767 "https://login.federate.to",
1768 "changed-owner",
1769 "alice",
1770 original_did,
1771 )
1772 .await
1773 });
1774 tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1775 tx.commit().await.unwrap();
1776 assert!(
1777 tokio::time::timeout(std::time::Duration::from_secs(10), bind)
1778 .await
1779 .unwrap()
1780 .unwrap()
1781 .is_err()
1782 );
1783 assert!(store
1784 .get_external_identity_user("https://login.federate.to", "changed-owner")
1785 .await
1786 .unwrap()
1787 .is_none());
1788 }
1789
1790 #[tokio::test]
1791 async fn list_and_get_external_identities() {
1792 let (_guard, store) = fresh().await;
1793 store
1794 .resolve_or_bind_external_idp("https://idp.example", "sub-1", "alice")
1795 .await
1796 .unwrap();
1797 let bindings = store.list_external_identities("alice").await.unwrap();
1798 assert_eq!(bindings.len(), 1);
1799 assert_eq!(bindings[0].issuer, "https://idp.example");
1800 assert_eq!(bindings[0].subject, "sub-1");
1801
1802 let user = store
1803 .get_external_identity_user("https://idp.example", "sub-1")
1804 .await
1805 .unwrap();
1806 assert_eq!(user.as_deref(), Some("alice"));
1807 }
1808
1809 #[tokio::test]
1812 async fn provision_stages_inactive_account() {
1813 let (_guard, store) = fresh().await;
1814 let key = make_key();
1815 let result = store
1816 .provision_hosted_account(
1817 "alice",
1818 "did:web:alice.example",
1819 key,
1820 AccountKeyCustody::SelfCustody,
1821 )
1822 .await
1823 .unwrap();
1824 assert!(!result.resumed);
1825 let profile = store.get_profile("alice").await.unwrap().unwrap();
1826 assert_eq!(profile.active, Some(false));
1827 assert_eq!(
1828 profile.atproto_did.as_deref(),
1829 Some("did:web:alice.example")
1830 );
1831 assert_eq!(profile.key_custody, Some(AccountKeyCustody::SelfCustody));
1832 let keys = store.list_pubkeys("alice").await.unwrap();
1833 assert_eq!(keys.len(), 1);
1834 assert_eq!(keys[0].fingerprint, result.fingerprint);
1835 }
1836
1837 #[tokio::test]
1838 async fn provision_exact_repeat_resumes() {
1839 let (_guard, store) = fresh().await;
1840 let key = make_key();
1841 let first = store
1842 .provision_hosted_account(
1843 "alice",
1844 "did:web:alice.example",
1845 key,
1846 AccountKeyCustody::SelfCustody,
1847 )
1848 .await
1849 .unwrap();
1850 let second = store
1851 .provision_hosted_account(
1852 "alice",
1853 "did:web:alice.example",
1854 key,
1855 AccountKeyCustody::SelfCustody,
1856 )
1857 .await
1858 .unwrap();
1859 assert!(second.resumed);
1860 assert_eq!(first.sub, second.sub);
1861 assert_eq!(first.fingerprint, second.fingerprint);
1862 }
1863
1864 #[tokio::test]
1865 async fn activate_flips_staged_to_active() {
1866 let (_guard, store) = fresh().await;
1867 let key = make_key();
1868 let provisioned = store
1869 .provision_hosted_account(
1870 "alice",
1871 "did:web:alice.example",
1872 key,
1873 AccountKeyCustody::SelfCustody,
1874 )
1875 .await
1876 .unwrap();
1877 store
1878 .activate_hosted_account(
1879 "alice",
1880 "did:web:alice.example",
1881 &provisioned.fingerprint,
1882 AccountKeyCustody::SelfCustody,
1883 )
1884 .await
1885 .unwrap();
1886 let profile = store.get_profile("alice").await.unwrap().unwrap();
1887 assert_eq!(profile.active, Some(true));
1888 }
1889
1890 #[tokio::test]
1891 async fn activate_idempotent_on_already_active() {
1892 let (_guard, store) = fresh().await;
1893 let key = make_key();
1894 let fp = super::super::pubkey_fingerprint(&key);
1895 store
1896 .provision_hosted_account(
1897 "alice",
1898 "did:web:alice.example",
1899 key,
1900 AccountKeyCustody::SelfCustody,
1901 )
1902 .await
1903 .unwrap();
1904 store
1905 .activate_hosted_account(
1906 "alice",
1907 "did:web:alice.example",
1908 &fp,
1909 AccountKeyCustody::SelfCustody,
1910 )
1911 .await
1912 .unwrap();
1913 store
1915 .activate_hosted_account(
1916 "alice",
1917 "did:web:alice.example",
1918 &fp,
1919 AccountKeyCustody::SelfCustody,
1920 )
1921 .await
1922 .unwrap();
1923 }
1924
1925 #[tokio::test]
1926 async fn activate_rejects_changed_did() {
1927 let (_guard, store) = fresh().await;
1928 let key = make_key();
1929 let fp = super::super::pubkey_fingerprint(&key);
1930 store
1931 .provision_hosted_account(
1932 "alice",
1933 "did:web:alice.example",
1934 key,
1935 AccountKeyCustody::SelfCustody,
1936 )
1937 .await
1938 .unwrap();
1939 assert!(store
1940 .activate_hosted_account(
1941 "alice",
1942 "did:web:wrong.example",
1943 &fp,
1944 AccountKeyCustody::SelfCustody,
1945 )
1946 .await
1947 .is_err());
1948 }
1949
1950 #[tokio::test]
1951 async fn provision_account_already_exists() {
1952 let (_guard, store) = fresh().await;
1953 let key = make_key();
1954 let provisioned = store
1956 .provision_hosted_account(
1957 "alice",
1958 "did:web:alice.example",
1959 key,
1960 AccountKeyCustody::SelfCustody,
1961 )
1962 .await
1963 .unwrap();
1964 store
1965 .activate_hosted_account(
1966 "alice",
1967 "did:web:alice.example",
1968 &provisioned.fingerprint,
1969 AccountKeyCustody::SelfCustody,
1970 )
1971 .await
1972 .unwrap();
1973 let other_key = make_key();
1975 let err = store
1976 .provision_hosted_account(
1977 "alice",
1978 "did:web:alice.example",
1979 other_key,
1980 AccountKeyCustody::SelfCustody,
1981 )
1982 .await
1983 .unwrap_err();
1984 assert!(matches!(
1985 err,
1986 HostedAccountProvisionError::AccountAlreadyExists
1987 ));
1988 }
1989
1990 #[tokio::test]
1991 async fn provision_key_already_bound() {
1992 let (_guard, store) = fresh().await;
1993 let key = make_key();
1994 let provisioned = store
1996 .provision_hosted_account(
1997 "alice",
1998 "did:web:alice.example",
1999 key,
2000 AccountKeyCustody::SelfCustody,
2001 )
2002 .await
2003 .unwrap();
2004 store
2005 .activate_hosted_account(
2006 "alice",
2007 "did:web:alice.example",
2008 &provisioned.fingerprint,
2009 AccountKeyCustody::SelfCustody,
2010 )
2011 .await
2012 .unwrap();
2013 let err = store
2015 .provision_hosted_account(
2016 "bob",
2017 "did:web:bob.example",
2018 key,
2019 AccountKeyCustody::SelfCustody,
2020 )
2021 .await
2022 .unwrap_err();
2023 assert!(matches!(err, HostedAccountProvisionError::KeyAlreadyBound));
2024 }
2025
2026 #[tokio::test]
2027 async fn provision_corrupt_inactive_state_is_backend_error() {
2028 let (_guard, store) = fresh().await;
2029 let key = make_key();
2030 store
2031 .provision_hosted_account(
2032 "alice",
2033 "did:web:alice.example",
2034 key,
2035 AccountKeyCustody::SelfCustody,
2036 )
2037 .await
2038 .unwrap();
2039 let other_key = make_key();
2042 let err = store
2043 .provision_hosted_account(
2044 "alice",
2045 "did:web:alice.example",
2046 other_key,
2047 AccountKeyCustody::SelfCustody,
2048 )
2049 .await
2050 .unwrap_err();
2051 assert!(matches!(err, HostedAccountProvisionError::Backend(_)));
2053 }
2054
2055 #[tokio::test]
2058 async fn from_database_shares_one_handle() {
2059 let (_guard, s) = fresh().await;
2060 let db = s.database();
2061 let store2 = PgliteUserStore::with_cipher(Arc::clone(&db), ColumnCipher::test_cipher())
2062 .await
2063 .unwrap();
2064 assert!(Arc::ptr_eq(&store2.database(), &db));
2066 }
2067
2068 #[tokio::test]
2071 async fn encrypted_store_leaves_no_plaintext_in_bytea() {
2072 let (_guard, store) = fresh().await;
2073 store.register("alice").await.unwrap();
2074 store
2075 .set_profile(
2076 "alice",
2077 UserProfilePatch {
2078 email: Some(Some("alice.secret@example.test".to_owned())),
2079 ..Default::default()
2080 },
2081 )
2082 .await
2083 .unwrap();
2084 let profile = store.get_profile("alice").await.unwrap().unwrap();
2086 assert_eq!(profile.email.as_deref(), Some("alice.secret@example.test"));
2087 let rows = store
2089 .database
2090 .query("SELECT email FROM users WHERE username='alice'", &[])
2091 .await
2092 .unwrap();
2093 let raw: Option<Vec<u8>> = rows.first().unwrap().get(0).unwrap();
2094 let raw = raw.unwrap();
2095 let needle = b"alice.secret@example.test";
2096 assert!(
2097 !raw.windows(needle.len()).any(|w| w == needle),
2098 "plaintext email found in stored BYTEA — encryption failed"
2099 );
2100 }
2101
2102 #[tokio::test]
2105 async fn schema_rejects_plaintext_and_invalid_algorithm_pairing() {
2106 let (_guard, store) = fresh().await;
2107 store.register("alice").await.unwrap();
2108
2109 let plaintext_name = b"Alice".to_vec();
2110 assert!(
2111 store
2112 .database
2113 .query(
2114 "UPDATE users SET name=$2 WHERE username=$1",
2115 &[&"alice", &plaintext_name],
2116 )
2117 .await
2118 .is_err(),
2119 "protected profile columns must reject plaintext bytes"
2120 );
2121
2122 let key = make_key();
2123 let fingerprint = store.add_pubkey("alice", key, None).await.unwrap();
2124 assert!(
2125 store
2126 .database
2127 .query(
2128 "UPDATE pubkeys SET algorithm='ed25519+ml-dsa-65' \
2129 WHERE fingerprint=$1",
2130 &[&fingerprint],
2131 )
2132 .await
2133 .is_err(),
2134 "hybrid key metadata must require encrypted ML-DSA-65 material"
2135 );
2136 }
2137
2138 #[tokio::test]
2140 async fn crypto_shred_after_dek_deletion() {
2141 let (_guard, store) = fresh().await;
2142 store.register("alice").await.unwrap();
2143 store
2144 .set_profile(
2145 "alice",
2146 UserProfilePatch {
2147 name: Some(Some("Alice".to_owned())),
2148 ..Default::default()
2149 },
2150 )
2151 .await
2152 .unwrap();
2153 assert!(store.get_profile("alice").await.unwrap().is_some());
2155 store
2157 .database
2158 .query(
2159 "DELETE FROM user_encryption_keys WHERE username='alice'",
2160 &[],
2161 )
2162 .await
2163 .unwrap();
2164 assert!(store.get_profile("alice").await.is_err());
2166 }
2167}