Skip to main content

hyprstream_core/auth/
user_store.rs

1//! User credential store abstraction.
2//!
3//! `UserStore` is the sealed backend trait. Production callers obtain an
4//! admitted [`super::ProductionUserStore`] rather than constructing or
5//! injecting an arbitrary implementation.
6
7use anyhow::Result;
8use async_trait::async_trait;
9use ed25519_dalek::VerifyingKey;
10use serde::{Deserialize, Serialize};
11
12/// Private supertrait preventing downstream crates from implementing
13/// `UserStore` and injecting a plaintext persistence backend.
14pub(crate) mod private {
15    pub trait Sealed {}
16
17    // Unit tests inside this crate use purpose-built fault stores. Integration
18    // and downstream crates compile the library without `cfg(test)` and cannot
19    // access this module.
20    #[cfg(test)]
21    impl<T: Send + Sync> Sealed for T {}
22}
23
24/// Who controls the account's authentication key material.
25///
26/// Cold signup provisions [`Self::SelfCustody`]. [`Self::Managed`] is the
27/// persisted seam for a later external-IdP-gated account flow; no such flow is
28/// implemented by the OAuth server today.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
30#[serde(rename_all = "snake_case")]
31pub enum AccountKeyCustody {
32    SelfCustody,
33    Managed,
34}
35
36impl AccountKeyCustody {
37    pub fn as_str(self) -> &'static str {
38        match self {
39            Self::SelfCustody => "self_custody",
40            Self::Managed => "managed",
41        }
42    }
43
44    pub fn parse(value: &str) -> Result<Self> {
45        match value {
46            "self_custody" => Ok(Self::SelfCustody),
47            "managed" => Ok(Self::Managed),
48            other => anyhow::bail!("unknown account key custody value '{other}'"),
49        }
50    }
51}
52
53/// One external identity allowed to authenticate as a hosted account.
54///
55/// Demo cold-signup records carry an empty collection. Keeping the normalized
56/// `(issuer, subject)` pair in the account model makes a later OIDC RP additive
57/// instead of requiring a credential-store migration.
58#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
59pub struct ExternalIdentityBinding {
60    pub issuer: String,
61    pub subject: String,
62}
63
64/// User profile data (OIDC standard claims + SCIM-informed fields).
65#[derive(Debug, Clone, Default, Serialize, Deserialize)]
66pub struct UserProfile {
67    /// Stable subject identifier (UUID). Generated at registration, never changes.
68    #[serde(default)]
69    pub sub: Option<String>,
70    /// Display name (SCIM: displayName / OIDC: name).
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub name: Option<String>,
73    /// Email address (SCIM: emails[0].value / OIDC: email).
74    #[serde(default, skip_serializing_if = "Option::is_none")]
75    pub email: Option<String>,
76    /// Whether the email is verified (OIDC: email_verified).
77    #[serde(default, skip_serializing_if = "Option::is_none")]
78    pub email_verified: Option<bool>,
79    /// Whether the user is active (SCIM: active). None defaults to true.
80    #[serde(default, skip_serializing_if = "Option::is_none")]
81    pub active: Option<bool>,
82    /// External identity ID from upstream IdP (SCIM: externalId).
83    #[serde(default, skip_serializing_if = "Option::is_none")]
84    pub external_id: Option<String>,
85    /// The account's mapped atproto DID (did:plc or host-form did:web), if
86    /// provisioned. PROVISIONING is tracked in #1124; the LOOKUP seam exists
87    /// here so the atproto OAuth profile can emit the mapped DID as `sub` (#1113 r5).
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub atproto_did: Option<String>,
90    /// Account key custody mode. Absent only on records created before the
91    /// hosted-account model gained an explicit custody discriminator.
92    #[serde(default, skip_serializing_if = "Option::is_none")]
93    pub key_custody: Option<AccountKeyCustody>,
94    /// Zero or more external IdP bindings. Empty for vault self-custody signup.
95    #[serde(default, skip_serializing_if = "Vec::is_empty")]
96    pub external_identities: Vec<ExternalIdentityBinding>,
97}
98
99/// Tri-state patch for profile fields: omitted, explicitly cleared, or replaced.
100#[derive(Debug, Clone, Default)]
101pub struct UserProfilePatch {
102    pub sub: Option<Option<String>>,
103    pub name: Option<Option<String>>,
104    pub email: Option<Option<String>>,
105    pub email_verified: Option<Option<bool>>,
106    pub active: Option<Option<bool>>,
107    pub external_id: Option<Option<String>>,
108    pub atproto_did: Option<Option<String>>,
109    pub key_custody: Option<Option<AccountKeyCustody>>,
110    pub external_identities: Option<Vec<ExternalIdentityBinding>>,
111}
112
113impl From<UserProfile> for UserProfilePatch {
114    fn from(profile: UserProfile) -> Self {
115        Self {
116            sub: profile.sub.map(Some),
117            name: profile.name.map(Some),
118            email: profile.email.map(Some),
119            email_verified: profile.email_verified.map(Some),
120            active: profile.active.map(Some),
121            external_id: profile.external_id.map(Some),
122            atproto_did: profile.atproto_did.map(Some),
123            key_custody: profile.key_custody.map(Some),
124            external_identities: (!profile.external_identities.is_empty())
125                .then_some(profile.external_identities),
126        }
127    }
128}
129
130/// Result of atomically inserting a hosted account into the AS credential
131/// store together with its first authentication key.
132#[derive(Debug, Clone, PartialEq, Eq)]
133pub struct HostedAccountProvisioning {
134    pub sub: String,
135    pub fingerprint: String,
136    /// True when this call found the same complete credential binding created
137    /// by an earlier attempt. It may still be staged inactive; callers must
138    /// resume downstream publication/activation instead of treating it as a
139    /// conflict.
140    pub resumed: bool,
141}
142
143/// Fail-closed conflict/backend distinction for hosted-account provisioning.
144#[derive(Debug, thiserror::Error)]
145pub enum HostedAccountProvisionError {
146    #[error("the requested account already exists")]
147    AccountAlreadyExists,
148    #[error("the supplied key is already bound to another account")]
149    KeyAlreadyBound,
150    #[error("credential-store provisioning failed")]
151    Backend(#[source] anyhow::Error),
152}
153
154/// The public-key algorithm of a stored [`PubkeyEntry`].
155///
156/// - [`Ed25519`](Self::Ed25519) — classical anchor only (the pre-#439 default,
157///   and what SSH/raw-seed adopt still contributes as its classical component).
158/// - [`HybridEd25519MlDsa65`](Self::HybridEd25519MlDsa65) — the Ed25519 anchor
159///   with a **bound ML-DSA-65 verifying key** (#439 PQ enrollment). This mirrors
160///   the `register_pq_trust` / `KeyedPqTrustStore` envelope model and the
161///   did:at9p ed25519→ml_dsa binding: the fingerprint stays the Ed25519 anchor's
162///   SHA256, and the ML-DSA-65 vk is carried alongside in `pq_pubkey`.
163///
164/// Invariant enforced by the stores: `HybridEd25519MlDsa65 ⇔ pq_pubkey.is_some()`.
165/// A hybrid record with missing PQ bytes is a **read error** (fail closed),
166/// never a silent downgrade to Ed25519.
167#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
168#[serde(rename_all = "lowercase")]
169pub enum KeyAlgorithm {
170    Ed25519,
171    /// EdDSA (Ed25519) anchor + bound ML-DSA-65 (FIPS 204) — post-quantum hybrid.
172    #[serde(rename = "ed25519+ml-dsa-65")]
173    HybridEd25519MlDsa65,
174}
175
176impl Default for KeyAlgorithm {
177    /// Ed25519 is the classical floor for records with no algorithm tag
178    /// (pre-#439) and for the SSH/raw-seed adopt paths' classical component.
179    fn default() -> Self {
180        Self::Ed25519
181    }
182}
183
184impl KeyAlgorithm {
185    /// Canonical lowercase algorithm tag written into stored records.
186    pub fn as_str(&self) -> &'static str {
187        match self {
188            Self::Ed25519 => "ed25519",
189            Self::HybridEd25519MlDsa65 => "ed25519+ml-dsa-65",
190        }
191    }
192
193    /// Whether this algorithm carries a post-quantum (ML-DSA-65) component.
194    pub fn is_hybrid(&self) -> bool {
195        matches!(self, Self::HybridEd25519MlDsa65)
196    }
197
198    /// Parse an algorithm tag read back from a stored record.
199    ///
200    /// Unknown tags error rather than silently falling back, so a future PQ
201    /// tag written by a newer build is never misread as Ed25519 by this one.
202    pub fn parse(s: &str) -> anyhow::Result<Self> {
203        match s.trim().to_ascii_lowercase().as_str() {
204            "ed25519" => Ok(Self::Ed25519),
205            "ed25519+ml-dsa-65" => Ok(Self::HybridEd25519MlDsa65),
206            other => anyhow::bail!(
207                "Unknown key algorithm tag '{other}'; this build implements \
208                 'ed25519' and 'ed25519+ml-dsa-65'"
209            ),
210        }
211    }
212}
213
214/// A pubkey entry associated with a user (like GitHub SSH keys).
215#[derive(Debug, Clone)]
216pub struct PubkeyEntry {
217    /// Base64url SHA-256 fingerprint of the pubkey bytes.
218    pub fingerprint: String,
219    /// The actual Ed25519 public key.
220    pub pubkey: VerifyingKey,
221    /// User-provided label (e.g., "laptop", "work").
222    pub label: Option<String>,
223    /// Unix timestamp when the key was added.
224    pub created_at: i64,
225    /// Unix timestamp when the key was last used for auth, or None if never.
226    pub last_used_at: Option<i64>,
227    /// Algorithm tag (#439). Defaults to [`KeyAlgorithm::Ed25519`] for records
228    /// written before the tag existed.
229    pub algorithm: KeyAlgorithm,
230    /// Bound ML-DSA-65 verifying key bytes (~1952B) for a
231    /// [`KeyAlgorithm::HybridEd25519MlDsa65`] record; `None` for classical
232    /// Ed25519. Kid-anchored to `fingerprint` (the Ed25519 anchor); resolved
233    /// by the challenge verifier, never carried in a login request. The
234    /// `algorithm.is_hybrid() ⇔ pq_pubkey.is_some()` invariant is enforced at
235    /// store read/write.
236    pub pq_pubkey: Option<Vec<u8>>,
237}
238
239/// Filter parameters for user search (SCIM-aligned).
240#[derive(Debug, Clone, Default)]
241pub struct UserFilter {
242    /// SCIM filter expression: `userName eq "alice"`, `active pr`, etc.
243    /// Minimum viable: `eq` and `pr` on userName, id, externalId, active.
244    pub filter: Option<String>,
245    /// If true, only return active users.
246    pub active_only: Option<bool>,
247    /// SCIM: max results per page (default 100).
248    pub count: Option<usize>,
249    /// SCIM: 1-indexed start position (converted to 0-indexed internally).
250    pub start_index: Option<usize>,
251    /// SCIM: attribute name to sort by (e.g., "userName", "id").
252    pub sort_by: Option<String>,
253    /// SCIM: sort order ("ascending" or "descending"). Default: ascending.
254    pub sort_order: Option<String>,
255}
256
257/// Durable result of atomically resolving or binding an external IdP identity.
258#[derive(Debug, Clone, PartialEq, Eq)]
259pub struct ExternalIdentityResolution {
260    /// The authoritative local username. This can differ from the candidate
261    /// when `(issuer, subject)` was already bound.
262    pub username: String,
263    /// Stable local OIDC subject.
264    pub sub: String,
265    /// True only when this transaction created the local user.
266    pub provisioned: bool,
267}
268
269/// Abstraction over user credential stores.
270///
271/// Supports profile CRUD and multi-pubkey management (like GitHub SSH keys).
272#[async_trait]
273pub trait UserStore: private::Sealed + Send + Sync {
274    // ─── Profile CRUD ────────────────────────────────────────────────────────
275
276    /// Get a user's profile (OIDC claims).
277    async fn get_profile(&self, username: &str) -> Result<Option<UserProfile>>;
278
279    /// Register a new user. Returns the generated subject UUID.
280    async fn register(&self, username: &str) -> Result<String>;
281
282    /// Atomically resolve an existing external identity or create a new
283    /// candidate username bound to it. A username that already belongs to a
284    /// local account must never be claimed by a new external identity.
285    ///
286    /// Existing `(issuer, subject)` bindings are authoritative and are never
287    /// rebound to the candidate. Empty identifiers, dangling references, and
288    /// non-exact uniqueness races must fail closed.
289    async fn resolve_or_bind_external_idp(
290        &self,
291        _issuer: &str,
292        _subject: &str,
293        _username: &str,
294    ) -> Result<ExternalIdentityResolution> {
295        anyhow::bail!("external IdP binding is unsupported by this credential store")
296    }
297
298    /// Atomically bind a verified external identity to the named, active,
299    /// already-provisioned hosted account whose authority-resolved DID is
300    /// `expected_hosted_did`.
301    ///
302    /// This operation must never create an account. Existing identical
303    /// `(issuer, subject)` bindings are idempotent only when they point to the
304    /// same DID owner; identity or issuer/account conflicts fail closed.
305    async fn bind_existing_external_idp_to_hosted_account(
306        &self,
307        _issuer: &str,
308        _subject: &str,
309        _username: &str,
310        _expected_hosted_did: &str,
311    ) -> Result<ExternalIdentityResolution> {
312        anyhow::bail!(
313            "external identity binding to hosted accounts is unsupported by this credential store"
314        )
315    }
316
317    /// Atomically create a hosted AS account and its first authentication key.
318    ///
319    /// Implementations must not overwrite either an existing username or an
320    /// existing key reverse-index entry. The account profile, DID mapping,
321    /// custody discriminator, empty external-binding collection, public key,
322    /// and reverse index become visible together. Repeating the exact same
323    /// `(username, DID, key, custody)` returns `Ok` with `resumed = true`.
324    ///
325    /// Conflict errors are trustworthy recovery signals: implementations may
326    /// return them only when the conflicting profile, key, and reverse index
327    /// form a complete usable hosted-account binding. Partial/corrupt state is
328    /// a backend error and must fail closed.
329    async fn provision_hosted_account(
330        &self,
331        _username: &str,
332        _atproto_did: &str,
333        _pubkey: VerifyingKey,
334        _custody: AccountKeyCustody,
335    ) -> std::result::Result<HostedAccountProvisioning, HostedAccountProvisionError> {
336        Err(HostedAccountProvisionError::Backend(anyhow::anyhow!(
337            "hosted-account provisioning is unsupported by this credential store"
338        )))
339    }
340
341    /// Atomically mark an exactly matching staged hosted binding active after
342    /// its durable PDS genesis is known to exist.
343    async fn activate_hosted_account(
344        &self,
345        _username: &str,
346        _atproto_did: &str,
347        _fingerprint: &str,
348        _custody: AccountKeyCustody,
349    ) -> std::result::Result<(), HostedAccountProvisionError> {
350        Err(HostedAccountProvisionError::Backend(anyhow::anyhow!(
351            "hosted-account activation is unsupported by this credential store"
352        )))
353    }
354
355    /// Update a user's profile fields with tri-state patch semantics.
356    async fn set_profile(&self, username: &str, patch: UserProfilePatch) -> Result<()>;
357
358    /// Remove a user and all their pubkeys.
359    async fn remove(&self, username: &str) -> Result<bool>;
360
361    /// List all registered usernames.
362    async fn list_users(&self) -> Result<Vec<String>>;
363
364    /// Search users with SCIM-aligned filtering, sorting, and pagination.
365    async fn search(&self, filter: &UserFilter) -> Result<Vec<(String, UserProfile)>>;
366
367    /// Set a user's active status.
368    async fn set_active(&self, username: &str, active: bool) -> Result<()>;
369
370    // ─── Pubkey Management ───────────────────────────────────────────────────
371
372    /// List all pubkeys for a user.
373    async fn list_pubkeys(&self, username: &str) -> Result<Vec<PubkeyEntry>>;
374
375    /// Add a classical Ed25519 pubkey to a user. Returns the fingerprint.
376    ///
377    /// Records `KeyAlgorithm::Ed25519` with no PQ component. For post-quantum
378    /// hybrid enrollment use [`add_pubkey_hybrid`](Self::add_pubkey_hybrid).
379    async fn add_pubkey(
380        &self,
381        username: &str,
382        pubkey: VerifyingKey,
383        label: Option<String>,
384    ) -> Result<String>;
385
386    /// Add a post-quantum **hybrid** identity key: the Ed25519 anchor plus its
387    /// bound ML-DSA-65 verifying key (#439). Returns the fingerprint (of the
388    /// Ed25519 anchor — the PQ vk does not change the kid).
389    ///
390    /// Records `KeyAlgorithm::HybridEd25519MlDsa65` with `pq_pubkey = Some(..)`.
391    /// If a classical Ed25519 record for the same anchor already exists, this is
392    /// the in-place upgrade path (Ed25519 → Hybrid for the same fingerprint);
393    /// the reverse transition is rejected.
394    ///
395    /// `ml_dsa_vk` must be the ~1952-byte ML-DSA-65 verifying key encoding
396    /// (`pq::ml_dsa_vk_bytes`). Required of every backend — no fail-open default
397    /// that could silently drop the PQ binding.
398    async fn add_pubkey_hybrid(
399        &self,
400        username: &str,
401        pubkey: VerifyingKey,
402        ml_dsa_vk: Vec<u8>,
403        label: Option<String>,
404    ) -> Result<String>;
405
406    /// Remove a pubkey by fingerprint.
407    async fn remove_pubkey(&self, username: &str, fingerprint: &str) -> Result<bool>;
408
409    /// Reverse lookup: find username by pubkey fingerprint (for auth).
410    async fn get_pubkey_user(&self, fingerprint: &str) -> Result<Option<String>>;
411
412    /// Update last_used_at timestamp for a pubkey.
413    async fn touch_pubkey(&self, username: &str, fingerprint: &str) -> Result<()>;
414
415    /// List the normalized external identities bound to one local account.
416    /// Cold signup always returns an empty list.
417    async fn list_external_identities(
418        &self,
419        username: &str,
420    ) -> Result<Vec<ExternalIdentityBinding>> {
421        self.get_profile(username)
422            .await?
423            .map(|profile| profile.external_identities)
424            .ok_or_else(|| anyhow::anyhow!("User '{username}' not found"))
425    }
426
427    /// Resolve a normalized external `(issuer, subject)` identity to its local
428    /// account. The cold-signup demo never populates these bindings; this
429    /// interface is reserved for the later OIDC RP.
430    async fn get_external_identity_user(
431        &self,
432        issuer: &str,
433        subject: &str,
434    ) -> Result<Option<String>> {
435        if issuer.is_empty() || subject.is_empty() {
436            anyhow::bail!("external identity issuer and subject must be non-empty");
437        }
438        let mut match_user = None;
439        for username in self.list_users().await? {
440            let Some(profile) = self.get_profile(&username).await? else {
441                continue;
442            };
443            if profile
444                .external_identities
445                .iter()
446                .any(|binding| binding.issuer == issuer && binding.subject == subject)
447            {
448                if match_user.is_some() {
449                    anyhow::bail!("external identity binding is ambiguous for issuer and subject");
450                }
451                match_user = Some(username);
452            }
453        }
454        Ok(match_user)
455    }
456
457    /// Resolve a unique local username from its authority-bound hosted DID.
458    ///
459    /// This reverse lookup is used only after a browser session has already
460    /// established that DID. Implementations must reject duplicate matches;
461    /// callers still have to recheck active status and authority ownership
462    /// before using the result for account binding.
463    async fn get_username_by_atproto_did(&self, did: &str) -> Result<Option<String>> {
464        if did.is_empty() {
465            anyhow::bail!("hosted account DID must not be empty");
466        }
467        let mut match_user = None;
468        for username in self.list_users().await? {
469            let Some(profile) = self.get_profile(&username).await? else {
470                continue;
471            };
472            if profile.atproto_did.as_deref() == Some(did) {
473                if match_user.is_some() {
474                    anyhow::bail!("hosted account DID maps to multiple local users");
475                }
476                match_user = Some(username);
477            }
478        }
479        Ok(match_user)
480    }
481}
482
483/// Compute the SSH fingerprint of a pubkey (matches `ssh-keygen -l -E sha256`).
484///
485/// Hashes the SSH wire-format blob (u32be(11) "ssh-ed25519" u32be(32) <key>)
486/// with SHA-256 and encodes as standard base64 without padding, prefixed "SHA256:".
487pub fn pubkey_fingerprint(pubkey: &VerifyingKey) -> String {
488    use base64::engine::general_purpose::STANDARD_NO_PAD;
489    use base64::Engine;
490    use sha2::{Digest, Sha256};
491    let wire = ssh_wire_encode(pubkey);
492    format!("SHA256:{}", STANDARD_NO_PAD.encode(Sha256::digest(wire)))
493}
494
495/// Encode an Ed25519 verifying key in SSH wire format (51 bytes).
496///
497/// Format: u32be(11) "ssh-ed25519" u32be(32) <32-byte key>
498fn ssh_wire_encode(pubkey: &VerifyingKey) -> [u8; 51] {
499    let mut wire = [0u8; 51];
500    wire[0..4].copy_from_slice(&11u32.to_be_bytes());
501    wire[4..15].copy_from_slice(b"ssh-ed25519");
502    wire[15..19].copy_from_slice(&32u32.to_be_bytes());
503    wire[19..51].copy_from_slice(pubkey.as_bytes());
504    wire
505}
506
507/// Decode a base64-encoded Ed25519 public key.
508///
509/// Accepts two formats:
510/// - SSH wire format (base64 of 51-byte blob): validates the "ssh-ed25519" type tag.
511/// - Raw Ed25519 (base64 of 32-byte key).
512pub fn decode_pubkey_base64(s: &str) -> anyhow::Result<VerifyingKey> {
513    use base64::engine::general_purpose::STANDARD;
514    use base64::Engine;
515
516    let raw = STANDARD
517        .decode(s.trim())
518        .map_err(|e| anyhow::anyhow!("Invalid base64: {e}"))?;
519
520    let key_bytes: [u8; 32] = if raw.len() == 51 {
521        let type_len = u32::from_be_bytes(
522            raw[0..4]
523                .try_into()
524                .map_err(|_| anyhow::anyhow!("Malformed SSH wire prefix"))?,
525        ) as usize;
526        if type_len != 11 || &raw[4..15] != b"ssh-ed25519" {
527            anyhow::bail!(
528                "Unsupported SSH key type: only Ed25519 is accepted. \
529                 Use: ssh-keygen -t ed25519"
530            );
531        }
532        raw[19..51]
533            .try_into()
534            .map_err(|_| anyhow::anyhow!("Malformed SSH wire payload"))?
535    } else if raw.len() == 32 {
536        raw.try_into()
537            .map_err(|_| anyhow::anyhow!("Expected 32-byte raw Ed25519 key"))?
538    } else {
539        anyhow::bail!(
540            "Expected 32-byte raw or 51-byte SSH wire Ed25519 key, got {} bytes",
541            raw.len()
542        );
543    };
544
545    VerifyingKey::from_bytes(&key_bytes).map_err(|e| anyhow::anyhow!("Invalid Ed25519 key: {e}"))
546}
547
548/// A parsed SCIM filter expression (RFC 7644 §3.4.2.2).
549///
550/// Only the subset actually sent by IdP SCIM clients is parsed.
551/// Unsupported expressions are captured as `Unrecognised` — RocksDB falls
552/// through to in-memory evaluation; Valkey returns `invalidFilter` (HTTP 400).
553#[derive(Debug, Clone, PartialEq, Eq)]
554pub enum ScimFilter {
555    UserNameEq(String),
556    IdEq(String),
557    ExternalIdEq(String),
558    ActiveEq(bool),
559    Presence(String),
560    Unrecognised(String),
561}
562
563impl ScimFilter {
564    pub fn parse(expr: &str) -> Self {
565        let expr = expr.trim();
566        if let Some(attr) = expr.strip_suffix(" pr") {
567            return ScimFilter::Presence(attr.trim().to_owned());
568        }
569        if let Some(rest) = expr.strip_prefix("userName eq ") {
570            return ScimFilter::UserNameEq(unquote(rest).to_owned());
571        }
572        if let Some(rest) = expr
573            .strip_prefix("id eq ")
574            .or_else(|| expr.strip_prefix("sub eq "))
575        {
576            return ScimFilter::IdEq(unquote(rest).to_owned());
577        }
578        if let Some(rest) = expr.strip_prefix("externalId eq ") {
579            return ScimFilter::ExternalIdEq(unquote(rest).to_owned());
580        }
581        if let Some(rest) = expr.strip_prefix("active eq ") {
582            return ScimFilter::ActiveEq(rest.trim() == "true");
583        }
584        ScimFilter::Unrecognised(expr.to_owned())
585    }
586}
587
588/// Evaluate a simple SCIM filter expression against a user entry.
589///
590/// Supports:
591/// - `userName eq "value"` — exact match on username
592/// - `id eq "value"` or `sub eq "value"` — exact match on subject UUID
593/// - `externalId eq "value"` — exact match on external ID
594/// - `active eq true/false` — match on active status
595/// - `userName pr` — presence (non-empty/non-None)
596/// - `active pr` — presence check
597pub(crate) fn matches_filter(
598    expr: &str,
599    username: &str,
600    sub: &Option<String>,
601    external_id: &Option<String>,
602    active: Option<bool>,
603) -> bool {
604    let expr = expr.trim();
605
606    // Presence operator: `attribute pr`
607    if let Some(attr) = expr.strip_suffix(" pr") {
608        let attr = attr.trim();
609        return match attr {
610            "userName" => !username.is_empty(),
611            "id" | "sub" => sub.is_some(),
612            "externalId" => external_id.is_some(),
613            "active" => active.is_some(),
614            "displayName" | "name" | "email" => true, // always "present" even if None conceptually
615            _ => false,
616        };
617    }
618
619    // Equality operator: `attribute eq "value"` or `attribute eq true/false`
620    if let Some(rest) = expr.strip_prefix("userName eq ") {
621        return username == unquote(rest);
622    }
623    if let Some(rest) = expr.strip_prefix("id eq ") {
624        return sub.as_deref() == Some(unquote(rest));
625    }
626    if let Some(rest) = expr.strip_prefix("sub eq ") {
627        return sub.as_deref() == Some(unquote(rest));
628    }
629    if let Some(rest) = expr.strip_prefix("externalId eq ") {
630        return external_id.as_deref() == Some(unquote(rest));
631    }
632    if let Some(rest) = expr.strip_prefix("active eq ") {
633        let val = rest.trim();
634        let expected = val == "true";
635        return active.unwrap_or(true) == expected;
636    }
637
638    tracing::warn!(%expr, "Unsupported SCIM filter expression");
639    false
640}
641
642/// Strip surrounding double-quotes from a SCIM filter value.
643fn unquote(s: &str) -> &str {
644    s.trim().trim_matches('"')
645}
646
647// ────────────────────────────────────────────────────────────────────────────
648// Anonymous device identity
649// ────────────────────────────────────────────────────────────────────────────
650
651/// An anonymous device identity record.
652///
653/// Created by the device enrollment flow (`POST /api/device/enroll`). Exists
654/// independently before any user logs in. `user_sub` is populated when the
655/// device cookie accompanies an OAuth token request.
656#[derive(Debug, Clone, Serialize, Deserialize)]
657pub struct DeviceRecord {
658    /// Raw 32-byte Ed25519 public key.
659    pub pubkey: [u8; 32],
660    /// Base58 encoding of `pubkey` — used as the RocksDB key suffix and JWT `sub`.
661    pub fingerprint: String,
662    /// Optional human-readable label.
663    #[serde(default, skip_serializing_if = "Option::is_none")]
664    pub label: Option<String>,
665    /// Unix timestamp of first enrollment.
666    pub enrolled_at: i64,
667    /// Unix timestamp of most recent activity (`touch_device`).
668    #[serde(default, skip_serializing_if = "Option::is_none")]
669    pub last_seen_at: Option<i64>,
670    /// Subject of the linked user, if OAuth login has been observed.
671    #[serde(default, skip_serializing_if = "Option::is_none")]
672    pub user_sub: Option<String>,
673}
674
675/// Storage operations for anonymous device records.
676#[async_trait]
677pub trait DeviceStore: Send + Sync {
678    /// Upsert a device record. On conflict (same fingerprint), updates `enrolled_at`
679    /// but preserves any existing `user_sub` and `label`.
680    async fn enroll_device(&self, record: DeviceRecord) -> Result<()>;
681
682    /// Associate a user subject with an existing device record.
683    async fn link_device_user(&self, fingerprint: &str, user_sub: &str) -> Result<()>;
684
685    /// Retrieve a device record by fingerprint.
686    async fn get_device(&self, fingerprint: &str) -> Result<Option<DeviceRecord>>;
687
688    /// Update `last_seen_at` to now.
689    async fn touch_device(&self, fingerprint: &str) -> Result<()>;
690
691    /// Delete a device record. Returns `true` if the record existed.
692    async fn revoke_device(&self, fingerprint: &str) -> Result<bool>;
693}
694
695#[cfg(test)]
696#[allow(clippy::unwrap_used, clippy::expect_used)]
697mod tests {
698    use super::*;
699
700    #[test]
701    fn test_matches_filter_username_eq() {
702        assert!(matches_filter(
703            r#"userName eq "alice""#,
704            "alice",
705            &None,
706            &None,
707            None
708        ));
709        assert!(!matches_filter(
710            r#"userName eq "alice""#,
711            "bob",
712            &None,
713            &None,
714            None
715        ));
716    }
717
718    #[test]
719    fn test_matches_filter_active_eq() {
720        assert!(matches_filter(
721            "active eq true",
722            "u",
723            &None,
724            &None,
725            Some(true)
726        ));
727        assert!(!matches_filter(
728            "active eq true",
729            "u",
730            &None,
731            &None,
732            Some(false)
733        ));
734    }
735
736    #[test]
737    fn test_matches_filter_presence() {
738        let sub = Some("uuid-1".to_owned());
739        assert!(matches_filter("userName pr", "alice", &None, &None, None));
740        assert!(matches_filter("id pr", "alice", &sub, &None, None));
741        assert!(!matches_filter("active pr", "alice", &None, &None, None));
742    }
743
744    #[test]
745    fn test_key_algorithm_parse_and_roundtrip() {
746        assert_eq!(KeyAlgorithm::Ed25519.as_str(), "ed25519");
747        assert_eq!(KeyAlgorithm::default(), KeyAlgorithm::Ed25519);
748        // Accepts case/whitespace variants.
749        assert_eq!(
750            KeyAlgorithm::parse("ed25519").unwrap(),
751            KeyAlgorithm::Ed25519
752        );
753        assert_eq!(
754            KeyAlgorithm::parse("  Ed25519 ").unwrap(),
755            KeyAlgorithm::Ed25519
756        );
757        // Unknown tags error (never silently fall back to Ed25519).
758        assert!(KeyAlgorithm::parse("ml-dsa-65").is_err());
759        assert!(KeyAlgorithm::parse("").is_err());
760    }
761}