Skip to main content

plexus_auth_core/identity/
linking.rs

1//! Credential linking: one [`Principal`], many credentials.
2//!
3//! # The problem this solves
4//!
5//! Today a credential *is* an identity. Register with a password and you get
6//! a user row whose UUID is your identity; mint an API key and the key is
7//! resolved back to that same user row only because `api_keys.user_id` is a
8//! foreign key someone remembered to add. There is no general statement that
9//! "these two things are the same person", and so a nostr key — which cannot
10//! be a `users` row, because nobody mints it — has nowhere to attach.
11//!
12//! A [`CredentialLink`] store makes that statement explicit and generic: a
13//! row per credential, each pointing at the [`Principal`] it authenticates.
14//! A human with a password, an API key, and a nostr key is one principal with
15//! three rows.
16//!
17//! # Schema
18//!
19//! The reference SQL shape (plexus-idp implements exactly this over SQLite):
20//!
21//! ```sql
22//! CREATE TABLE credential_links (
23//!     class      TEXT NOT NULL,   -- CredentialClass::as_str()
24//!     locator    TEXT NOT NULL,   -- digest/username/pubkey; NEVER the secret
25//!     principal  TEXT NOT NULL,   -- Principal::to_string(), e.g. idp:<uuid>
26//!     roles      TEXT NOT NULL DEFAULT '[]',
27//!     claims     TEXT NOT NULL DEFAULT '{}',
28//!     revoked    INTEGER NOT NULL DEFAULT 0,
29//!     expires_at TEXT,
30//!     created_at TEXT NOT NULL,
31//!     PRIMARY KEY (class, locator)
32//! );
33//! CREATE INDEX idx_credential_links_principal ON credential_links(principal);
34//! ```
35//!
36//! `(class, locator)` is the primary key, which is the schema-level
37//! expression of the store's central rule: **a credential resolves to exactly
38//! one principal.** Two principals sharing one credential is the failure this
39//! type exists to make unrepresentable.
40//!
41//! The reverse is unconstrained on purpose — a principal may hold any number
42//! of credentials, and that is the whole point.
43//!
44//! # What a locator is, and is not
45//!
46//! A locator is a *non-secret* handle: the SHA-256 of an API key, a username,
47//! a nostr pubkey. It is never the secret itself. Storing a raw API key here
48//! would turn a read of this table into a full compromise, so
49//! [`ApiKeyAuthenticator`](super::ApiKeyAuthenticator) digests before it
50//! looks up, and this module never sees plaintext.
51//!
52//! # Out of scope
53//!
54//! Tenancy. A link says who a credential belongs to, not what they may reach.
55//! Orgs, membership records, and tenant mounts are M4 (PLX-73
56//! `q-tenant-isolation`, `q-user-provisioning`); `claims` carries the
57//! existing `org_id` *hint* and nothing here interprets it.
58
59use std::collections::HashMap;
60use std::sync::{Arc, Mutex};
61
62use async_trait::async_trait;
63use chrono::{DateTime, Utc};
64use serde_json::Value;
65
66use super::principal::Principal;
67
68/// What kind of credential a link describes.
69///
70/// `#[non_exhaustive]` plus a lossless `Other` variant: a deployment can
71/// store a credential class this crate has never heard of without the class
72/// being silently coerced into a neighbouring one.
73#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
74#[non_exhaustive]
75pub enum CredentialClass {
76    /// A username + password login (locator: the username).
77    Password,
78    /// An API key (locator: the key's digest).
79    ApiKey,
80    /// A nostr secp256k1 keypair (locator: the 64-hex x-only pubkey).
81    NostrKey,
82    /// A federated OIDC identity (locator: `<issuer>|<sub>`).
83    Oidc,
84    /// Anything else, kept verbatim.
85    Other(String),
86}
87
88impl CredentialClass {
89    /// The stored discriminant.
90    pub fn as_str(&self) -> &str {
91        match self {
92            Self::Password => "password",
93            Self::ApiKey => "apikey",
94            Self::NostrKey => "nostr_key",
95            Self::Oidc => "oidc",
96            Self::Other(s) => s,
97        }
98    }
99
100    /// Read a stored discriminant back. Total: unknown values become
101    /// [`Other`](CredentialClass::Other) rather than an error, so a row
102    /// written by a newer build is still readable by an older one.
103    pub fn from_stored(s: &str) -> Self {
104        match s {
105            "password" => Self::Password,
106            "apikey" => Self::ApiKey,
107            "nostr_key" => Self::NostrKey,
108            "oidc" => Self::Oidc,
109            other => Self::Other(other.to_string()),
110        }
111    }
112}
113
114impl std::fmt::Display for CredentialClass {
115    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116        f.write_str(self.as_str())
117    }
118}
119
120/// Why a link operation failed.
121#[derive(Debug, Clone, PartialEq, Eq)]
122#[non_exhaustive]
123pub enum LinkError {
124    /// `(class, locator)` is already linked to a *different* principal.
125    ///
126    /// Re-linking a credential to the principal it already names is a no-op,
127    /// not an error; moving it to another principal is refused, because that
128    /// would silently transfer an authentication path between identities.
129    AlreadyLinked {
130        /// The credential's class.
131        class: String,
132        /// The credential's locator.
133        locator: String,
134        /// The principal it is already bound to.
135        existing: String,
136    },
137
138    /// The store could not be reached.
139    Backend(String),
140}
141
142impl std::fmt::Display for LinkError {
143    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
144        match self {
145            Self::AlreadyLinked {
146                class,
147                locator,
148                existing,
149            } => write!(
150                f,
151                "credential `{class}:{locator}` is already linked to `{existing}`"
152            ),
153            Self::Backend(why) => write!(f, "credential link store error: {why}"),
154        }
155    }
156}
157
158impl std::error::Error for LinkError {}
159
160/// One credential, bound to the principal it authenticates.
161#[derive(Debug, Clone, PartialEq)]
162pub struct LinkedCredential {
163    class: CredentialClass,
164    locator: String,
165    principal: Principal,
166    roles: Vec<String>,
167    claims: Value,
168    revoked: bool,
169    expires_at: Option<DateTime<Utc>>,
170    created_at: DateTime<Utc>,
171}
172
173impl LinkedCredential {
174    /// Bind `locator` (a non-secret handle) to `principal`.
175    pub fn new(class: CredentialClass, locator: impl Into<String>, principal: Principal) -> Self {
176        Self {
177            class,
178            locator: locator.into(),
179            principal,
180            roles: Vec::new(),
181            claims: Value::Null,
182            revoked: false,
183            expires_at: None,
184            created_at: Utc::now(),
185        }
186    }
187
188    /// Roles this credential asserts.
189    pub fn with_roles(mut self, roles: Vec<String>) -> Self {
190        self.roles = roles;
191        self
192    }
193
194    /// Extra claims (`org_id`, `username`, …) this credential carries.
195    pub fn with_claims(mut self, claims: Value) -> Self {
196        self.claims = claims;
197        self
198    }
199
200    /// Give the credential a validity window.
201    pub fn expiring_at(mut self, at: DateTime<Utc>) -> Self {
202        self.expires_at = Some(at);
203        self
204    }
205
206    /// Mark the credential withdrawn.
207    pub fn revoked(mut self) -> Self {
208        self.revoked = true;
209        self
210    }
211
212    /// Override the creation timestamp (for stores reading rows back).
213    pub fn created_at(mut self, at: DateTime<Utc>) -> Self {
214        self.created_at = at;
215        self
216    }
217
218    /// The credential's class.
219    pub fn class(&self) -> &CredentialClass {
220        &self.class
221    }
222    /// The non-secret handle this credential is found by.
223    pub fn locator(&self) -> &str {
224        &self.locator
225    }
226    /// The principal this credential authenticates.
227    pub fn principal(&self) -> &Principal {
228        &self.principal
229    }
230    /// Roles asserted by this credential.
231    pub fn roles(&self) -> &[String] {
232        &self.roles
233    }
234    /// Claims carried by this credential.
235    pub fn claims(&self) -> &Value {
236        &self.claims
237    }
238    /// Has this credential been withdrawn?
239    pub fn is_revoked(&self) -> bool {
240        self.revoked
241    }
242    /// When it stops being valid, if ever.
243    pub fn expires_at(&self) -> Option<DateTime<Utc>> {
244        self.expires_at
245    }
246    /// When it was linked.
247    pub fn created(&self) -> DateTime<Utc> {
248        self.created_at
249    }
250
251    /// Is this credential past its validity window at `now`?
252    ///
253    /// A credential with no `expires_at` never expires — that is today's
254    /// behavior for API keys with a null `expires_at` column and is
255    /// preserved deliberately.
256    pub fn is_expired_at(&self, now: DateTime<Utc>) -> bool {
257        self.expires_at.is_some_and(|e| e < now)
258    }
259}
260
261/// A store mapping credentials to the principals they authenticate.
262///
263/// Object-safe and async so a SQLite, Postgres, or in-memory implementation
264/// can be handed to an [`Authenticator`](super::Authenticator) as
265/// `Arc<dyn CredentialLink>`.
266#[async_trait]
267pub trait CredentialLink: Send + Sync + 'static {
268    /// Bind a credential to a principal.
269    ///
270    /// Idempotent when the credential is already bound to the *same*
271    /// principal (metadata is refreshed); [`LinkError::AlreadyLinked`] when
272    /// it is bound to a different one.
273    async fn link(&self, credential: LinkedCredential) -> Result<(), LinkError>;
274
275    /// Find the credential — and therefore the principal — behind a locator.
276    ///
277    /// Returns the full [`LinkedCredential`] rather than a bare
278    /// [`Principal`] so the caller can enforce revocation and expiry; a
279    /// store that filtered those out itself would make the two states
280    /// indistinguishable from "never existed".
281    async fn resolve(
282        &self,
283        class: CredentialClass,
284        locator: &str,
285    ) -> Result<Option<LinkedCredential>, LinkError>;
286
287    /// Every credential held by a principal.
288    async fn credentials_for(
289        &self,
290        principal: &Principal,
291    ) -> Result<Vec<LinkedCredential>, LinkError>;
292
293    /// Remove a link. Returns whether a row was removed.
294    async fn unlink(&self, class: CredentialClass, locator: &str) -> Result<bool, LinkError>;
295}
296
297/// In-memory [`CredentialLink`], for tests and single-process deployments.
298#[derive(Debug, Default)]
299pub struct InMemoryCredentialLink {
300    rows: Mutex<HashMap<(String, String), LinkedCredential>>,
301}
302
303impl InMemoryCredentialLink {
304    /// An empty store.
305    pub fn new() -> Self {
306        Self::default()
307    }
308
309    /// Wrap in an `Arc` for handing to an authenticator.
310    pub fn shared() -> Arc<Self> {
311        Arc::new(Self::new())
312    }
313
314    fn key(class: &CredentialClass, locator: &str) -> (String, String) {
315        (class.as_str().to_string(), locator.to_string())
316    }
317}
318
319#[async_trait]
320impl CredentialLink for InMemoryCredentialLink {
321    async fn link(&self, credential: LinkedCredential) -> Result<(), LinkError> {
322        let key = Self::key(credential.class(), credential.locator());
323        let mut rows = self.rows.lock().expect("credential link store poisoned");
324        if let Some(existing) = rows.get(&key) {
325            if existing.principal() != credential.principal() {
326                return Err(LinkError::AlreadyLinked {
327                    class: key.0,
328                    locator: key.1,
329                    existing: existing.principal().to_string(),
330                });
331            }
332        }
333        rows.insert(key, credential);
334        Ok(())
335    }
336
337    async fn resolve(
338        &self,
339        class: CredentialClass,
340        locator: &str,
341    ) -> Result<Option<LinkedCredential>, LinkError> {
342        let rows = self.rows.lock().expect("credential link store poisoned");
343        Ok(rows.get(&Self::key(&class, locator)).cloned())
344    }
345
346    async fn credentials_for(
347        &self,
348        principal: &Principal,
349    ) -> Result<Vec<LinkedCredential>, LinkError> {
350        let rows = self.rows.lock().expect("credential link store poisoned");
351        let mut out: Vec<LinkedCredential> = rows
352            .values()
353            .filter(|c| c.principal() == principal)
354            .cloned()
355            .collect();
356        out.sort_by(|a, b| {
357            (a.class(), a.locator()).cmp(&(b.class(), b.locator()))
358        });
359        Ok(out)
360    }
361
362    async fn unlink(&self, class: CredentialClass, locator: &str) -> Result<bool, LinkError> {
363        let mut rows = self.rows.lock().expect("credential link store poisoned");
364        Ok(rows.remove(&Self::key(&class, locator)).is_some())
365    }
366}
367
368#[cfg(test)]
369mod tests {
370    use super::*;
371
372    const UUID: &str = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
373    const PUBKEY: &str = "3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d";
374
375    fn alice() -> Principal {
376        format!("idp:{UUID}").parse().unwrap()
377    }
378
379    #[tokio::test]
380    async fn one_principal_many_credentials_resolve_to_one_subject() {
381        let store = InMemoryCredentialLink::new();
382        let alice = alice();
383
384        // A password login and a nostr key: two credentials, one human.
385        store
386            .link(LinkedCredential::new(
387                CredentialClass::Password,
388                "alice",
389                alice.clone(),
390            ))
391            .await
392            .unwrap();
393        store
394            .link(LinkedCredential::new(
395                CredentialClass::NostrKey,
396                PUBKEY,
397                alice.clone(),
398            ))
399            .await
400            .unwrap();
401
402        let via_password = store
403            .resolve(CredentialClass::Password, "alice")
404            .await
405            .unwrap()
406            .unwrap();
407        let via_nostr = store
408            .resolve(CredentialClass::NostrKey, PUBKEY)
409            .await
410            .unwrap()
411            .unwrap();
412
413        assert_eq!(via_password.principal(), via_nostr.principal());
414        assert_eq!(via_password.principal(), &alice);
415
416        let held = store.credentials_for(&alice).await.unwrap();
417        assert_eq!(held.len(), 2);
418    }
419
420    #[tokio::test]
421    async fn locators_are_scoped_by_class() {
422        // The same string under two classes is two different credentials.
423        let store = InMemoryCredentialLink::new();
424        let alice = alice();
425        let bob: Principal = "idp:00000000-0000-4000-8000-000000000001".parse().unwrap();
426
427        store
428            .link(LinkedCredential::new(
429                CredentialClass::Password,
430                "shared",
431                alice.clone(),
432            ))
433            .await
434            .unwrap();
435        store
436            .link(LinkedCredential::new(
437                CredentialClass::ApiKey,
438                "shared",
439                bob.clone(),
440            ))
441            .await
442            .unwrap();
443
444        assert_eq!(
445            store
446                .resolve(CredentialClass::Password, "shared")
447                .await
448                .unwrap()
449                .unwrap()
450                .principal(),
451            &alice
452        );
453        assert_eq!(
454            store
455                .resolve(CredentialClass::ApiKey, "shared")
456                .await
457                .unwrap()
458                .unwrap()
459                .principal(),
460            &bob
461        );
462    }
463
464    #[tokio::test]
465    async fn a_credential_cannot_be_moved_to_another_principal() {
466        let store = InMemoryCredentialLink::new();
467        let alice = alice();
468        let mallory: Principal = "idp:00000000-0000-4000-8000-00000000dead".parse().unwrap();
469
470        store
471            .link(LinkedCredential::new(
472                CredentialClass::ApiKey,
473                "k1",
474                alice.clone(),
475            ))
476            .await
477            .unwrap();
478
479        // Re-linking to the same principal refreshes metadata.
480        store
481            .link(
482                LinkedCredential::new(CredentialClass::ApiKey, "k1", alice.clone())
483                    .with_roles(vec!["admin".into()]),
484            )
485            .await
486            .unwrap();
487        assert_eq!(
488            store
489                .resolve(CredentialClass::ApiKey, "k1")
490                .await
491                .unwrap()
492                .unwrap()
493                .roles(),
494            ["admin"]
495        );
496
497        // Stealing it is refused.
498        let err = store
499            .link(LinkedCredential::new(
500                CredentialClass::ApiKey,
501                "k1",
502                mallory,
503            ))
504            .await
505            .unwrap_err();
506        assert!(matches!(err, LinkError::AlreadyLinked { .. }), "{err:?}");
507    }
508
509    #[tokio::test]
510    async fn unlink_removes_only_the_named_credential() {
511        let store = InMemoryCredentialLink::new();
512        let alice = alice();
513        store
514            .link(LinkedCredential::new(
515                CredentialClass::Password,
516                "alice",
517                alice.clone(),
518            ))
519            .await
520            .unwrap();
521        store
522            .link(LinkedCredential::new(
523                CredentialClass::ApiKey,
524                "k1",
525                alice.clone(),
526            ))
527            .await
528            .unwrap();
529
530        assert!(store.unlink(CredentialClass::ApiKey, "k1").await.unwrap());
531        assert!(!store.unlink(CredentialClass::ApiKey, "k1").await.unwrap());
532        assert_eq!(store.credentials_for(&alice).await.unwrap().len(), 1);
533    }
534
535    #[test]
536    fn credential_class_round_trips_including_unknown() {
537        for c in [
538            CredentialClass::Password,
539            CredentialClass::ApiKey,
540            CredentialClass::NostrKey,
541            CredentialClass::Oidc,
542            CredentialClass::Other("webauthn".into()),
543        ] {
544            assert_eq!(CredentialClass::from_stored(c.as_str()), c);
545        }
546    }
547
548    #[test]
549    fn expiry_is_opt_in() {
550        let c = LinkedCredential::new(CredentialClass::ApiKey, "k", alice());
551        assert!(!c.is_expired_at(Utc::now()));
552        let c = c.expiring_at(Utc::now() - chrono::Duration::seconds(1));
553        assert!(c.is_expired_at(Utc::now()));
554    }
555}