plexus_auth_core/identity/
linking.rs1use 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#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
74#[non_exhaustive]
75pub enum CredentialClass {
76 Password,
78 ApiKey,
80 NostrKey,
82 Oidc,
84 Other(String),
86}
87
88impl CredentialClass {
89 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 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#[derive(Debug, Clone, PartialEq, Eq)]
122#[non_exhaustive]
123pub enum LinkError {
124 AlreadyLinked {
130 class: String,
132 locator: String,
134 existing: String,
136 },
137
138 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#[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 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 pub fn with_roles(mut self, roles: Vec<String>) -> Self {
190 self.roles = roles;
191 self
192 }
193
194 pub fn with_claims(mut self, claims: Value) -> Self {
196 self.claims = claims;
197 self
198 }
199
200 pub fn expiring_at(mut self, at: DateTime<Utc>) -> Self {
202 self.expires_at = Some(at);
203 self
204 }
205
206 pub fn revoked(mut self) -> Self {
208 self.revoked = true;
209 self
210 }
211
212 pub fn created_at(mut self, at: DateTime<Utc>) -> Self {
214 self.created_at = at;
215 self
216 }
217
218 pub fn class(&self) -> &CredentialClass {
220 &self.class
221 }
222 pub fn locator(&self) -> &str {
224 &self.locator
225 }
226 pub fn principal(&self) -> &Principal {
228 &self.principal
229 }
230 pub fn roles(&self) -> &[String] {
232 &self.roles
233 }
234 pub fn claims(&self) -> &Value {
236 &self.claims
237 }
238 pub fn is_revoked(&self) -> bool {
240 self.revoked
241 }
242 pub fn expires_at(&self) -> Option<DateTime<Utc>> {
244 self.expires_at
245 }
246 pub fn created(&self) -> DateTime<Utc> {
248 self.created_at
249 }
250
251 pub fn is_expired_at(&self, now: DateTime<Utc>) -> bool {
257 self.expires_at.is_some_and(|e| e < now)
258 }
259}
260
261#[async_trait]
267pub trait CredentialLink: Send + Sync + 'static {
268 async fn link(&self, credential: LinkedCredential) -> Result<(), LinkError>;
274
275 async fn resolve(
282 &self,
283 class: CredentialClass,
284 locator: &str,
285 ) -> Result<Option<LinkedCredential>, LinkError>;
286
287 async fn credentials_for(
289 &self,
290 principal: &Principal,
291 ) -> Result<Vec<LinkedCredential>, LinkError>;
292
293 async fn unlink(&self, class: CredentialClass, locator: &str) -> Result<bool, LinkError>;
295}
296
297#[derive(Debug, Default)]
299pub struct InMemoryCredentialLink {
300 rows: Mutex<HashMap<(String, String), LinkedCredential>>,
301}
302
303impl InMemoryCredentialLink {
304 pub fn new() -> Self {
306 Self::default()
307 }
308
309 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 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 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 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 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}