use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde_json::Value;
use super::principal::Principal;
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
pub enum CredentialClass {
Password,
ApiKey,
NostrKey,
Oidc,
Other(String),
}
impl CredentialClass {
pub fn as_str(&self) -> &str {
match self {
Self::Password => "password",
Self::ApiKey => "apikey",
Self::NostrKey => "nostr_key",
Self::Oidc => "oidc",
Self::Other(s) => s,
}
}
pub fn from_stored(s: &str) -> Self {
match s {
"password" => Self::Password,
"apikey" => Self::ApiKey,
"nostr_key" => Self::NostrKey,
"oidc" => Self::Oidc,
other => Self::Other(other.to_string()),
}
}
}
impl std::fmt::Display for CredentialClass {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum LinkError {
AlreadyLinked {
class: String,
locator: String,
existing: String,
},
Backend(String),
}
impl std::fmt::Display for LinkError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::AlreadyLinked {
class,
locator,
existing,
} => write!(
f,
"credential `{class}:{locator}` is already linked to `{existing}`"
),
Self::Backend(why) => write!(f, "credential link store error: {why}"),
}
}
}
impl std::error::Error for LinkError {}
#[derive(Debug, Clone, PartialEq)]
pub struct LinkedCredential {
class: CredentialClass,
locator: String,
principal: Principal,
roles: Vec<String>,
claims: Value,
revoked: bool,
expires_at: Option<DateTime<Utc>>,
created_at: DateTime<Utc>,
}
impl LinkedCredential {
pub fn new(class: CredentialClass, locator: impl Into<String>, principal: Principal) -> Self {
Self {
class,
locator: locator.into(),
principal,
roles: Vec::new(),
claims: Value::Null,
revoked: false,
expires_at: None,
created_at: Utc::now(),
}
}
pub fn with_roles(mut self, roles: Vec<String>) -> Self {
self.roles = roles;
self
}
pub fn with_claims(mut self, claims: Value) -> Self {
self.claims = claims;
self
}
pub fn expiring_at(mut self, at: DateTime<Utc>) -> Self {
self.expires_at = Some(at);
self
}
pub fn revoked(mut self) -> Self {
self.revoked = true;
self
}
pub fn created_at(mut self, at: DateTime<Utc>) -> Self {
self.created_at = at;
self
}
pub fn class(&self) -> &CredentialClass {
&self.class
}
pub fn locator(&self) -> &str {
&self.locator
}
pub fn principal(&self) -> &Principal {
&self.principal
}
pub fn roles(&self) -> &[String] {
&self.roles
}
pub fn claims(&self) -> &Value {
&self.claims
}
pub fn is_revoked(&self) -> bool {
self.revoked
}
pub fn expires_at(&self) -> Option<DateTime<Utc>> {
self.expires_at
}
pub fn created(&self) -> DateTime<Utc> {
self.created_at
}
pub fn is_expired_at(&self, now: DateTime<Utc>) -> bool {
self.expires_at.is_some_and(|e| e < now)
}
}
#[async_trait]
pub trait CredentialLink: Send + Sync + 'static {
async fn link(&self, credential: LinkedCredential) -> Result<(), LinkError>;
async fn resolve(
&self,
class: CredentialClass,
locator: &str,
) -> Result<Option<LinkedCredential>, LinkError>;
async fn credentials_for(
&self,
principal: &Principal,
) -> Result<Vec<LinkedCredential>, LinkError>;
async fn unlink(&self, class: CredentialClass, locator: &str) -> Result<bool, LinkError>;
}
#[derive(Debug, Default)]
pub struct InMemoryCredentialLink {
rows: Mutex<HashMap<(String, String), LinkedCredential>>,
}
impl InMemoryCredentialLink {
pub fn new() -> Self {
Self::default()
}
pub fn shared() -> Arc<Self> {
Arc::new(Self::new())
}
fn key(class: &CredentialClass, locator: &str) -> (String, String) {
(class.as_str().to_string(), locator.to_string())
}
}
#[async_trait]
impl CredentialLink for InMemoryCredentialLink {
async fn link(&self, credential: LinkedCredential) -> Result<(), LinkError> {
let key = Self::key(credential.class(), credential.locator());
let mut rows = self.rows.lock().expect("credential link store poisoned");
if let Some(existing) = rows.get(&key) {
if existing.principal() != credential.principal() {
return Err(LinkError::AlreadyLinked {
class: key.0,
locator: key.1,
existing: existing.principal().to_string(),
});
}
}
rows.insert(key, credential);
Ok(())
}
async fn resolve(
&self,
class: CredentialClass,
locator: &str,
) -> Result<Option<LinkedCredential>, LinkError> {
let rows = self.rows.lock().expect("credential link store poisoned");
Ok(rows.get(&Self::key(&class, locator)).cloned())
}
async fn credentials_for(
&self,
principal: &Principal,
) -> Result<Vec<LinkedCredential>, LinkError> {
let rows = self.rows.lock().expect("credential link store poisoned");
let mut out: Vec<LinkedCredential> = rows
.values()
.filter(|c| c.principal() == principal)
.cloned()
.collect();
out.sort_by(|a, b| {
(a.class(), a.locator()).cmp(&(b.class(), b.locator()))
});
Ok(out)
}
async fn unlink(&self, class: CredentialClass, locator: &str) -> Result<bool, LinkError> {
let mut rows = self.rows.lock().expect("credential link store poisoned");
Ok(rows.remove(&Self::key(&class, locator)).is_some())
}
}
#[cfg(test)]
mod tests {
use super::*;
const UUID: &str = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
const PUBKEY: &str = "3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d";
fn alice() -> Principal {
format!("idp:{UUID}").parse().unwrap()
}
#[tokio::test]
async fn one_principal_many_credentials_resolve_to_one_subject() {
let store = InMemoryCredentialLink::new();
let alice = alice();
store
.link(LinkedCredential::new(
CredentialClass::Password,
"alice",
alice.clone(),
))
.await
.unwrap();
store
.link(LinkedCredential::new(
CredentialClass::NostrKey,
PUBKEY,
alice.clone(),
))
.await
.unwrap();
let via_password = store
.resolve(CredentialClass::Password, "alice")
.await
.unwrap()
.unwrap();
let via_nostr = store
.resolve(CredentialClass::NostrKey, PUBKEY)
.await
.unwrap()
.unwrap();
assert_eq!(via_password.principal(), via_nostr.principal());
assert_eq!(via_password.principal(), &alice);
let held = store.credentials_for(&alice).await.unwrap();
assert_eq!(held.len(), 2);
}
#[tokio::test]
async fn locators_are_scoped_by_class() {
let store = InMemoryCredentialLink::new();
let alice = alice();
let bob: Principal = "idp:00000000-0000-4000-8000-000000000001".parse().unwrap();
store
.link(LinkedCredential::new(
CredentialClass::Password,
"shared",
alice.clone(),
))
.await
.unwrap();
store
.link(LinkedCredential::new(
CredentialClass::ApiKey,
"shared",
bob.clone(),
))
.await
.unwrap();
assert_eq!(
store
.resolve(CredentialClass::Password, "shared")
.await
.unwrap()
.unwrap()
.principal(),
&alice
);
assert_eq!(
store
.resolve(CredentialClass::ApiKey, "shared")
.await
.unwrap()
.unwrap()
.principal(),
&bob
);
}
#[tokio::test]
async fn a_credential_cannot_be_moved_to_another_principal() {
let store = InMemoryCredentialLink::new();
let alice = alice();
let mallory: Principal = "idp:00000000-0000-4000-8000-00000000dead".parse().unwrap();
store
.link(LinkedCredential::new(
CredentialClass::ApiKey,
"k1",
alice.clone(),
))
.await
.unwrap();
store
.link(
LinkedCredential::new(CredentialClass::ApiKey, "k1", alice.clone())
.with_roles(vec!["admin".into()]),
)
.await
.unwrap();
assert_eq!(
store
.resolve(CredentialClass::ApiKey, "k1")
.await
.unwrap()
.unwrap()
.roles(),
["admin"]
);
let err = store
.link(LinkedCredential::new(
CredentialClass::ApiKey,
"k1",
mallory,
))
.await
.unwrap_err();
assert!(matches!(err, LinkError::AlreadyLinked { .. }), "{err:?}");
}
#[tokio::test]
async fn unlink_removes_only_the_named_credential() {
let store = InMemoryCredentialLink::new();
let alice = alice();
store
.link(LinkedCredential::new(
CredentialClass::Password,
"alice",
alice.clone(),
))
.await
.unwrap();
store
.link(LinkedCredential::new(
CredentialClass::ApiKey,
"k1",
alice.clone(),
))
.await
.unwrap();
assert!(store.unlink(CredentialClass::ApiKey, "k1").await.unwrap());
assert!(!store.unlink(CredentialClass::ApiKey, "k1").await.unwrap());
assert_eq!(store.credentials_for(&alice).await.unwrap().len(), 1);
}
#[test]
fn credential_class_round_trips_including_unknown() {
for c in [
CredentialClass::Password,
CredentialClass::ApiKey,
CredentialClass::NostrKey,
CredentialClass::Oidc,
CredentialClass::Other("webauthn".into()),
] {
assert_eq!(CredentialClass::from_stored(c.as_str()), c);
}
}
#[test]
fn expiry_is_opt_in() {
let c = LinkedCredential::new(CredentialClass::ApiKey, "k", alice());
assert!(!c.is_expired_at(Utc::now()));
let c = c.expiring_at(Utc::now() - chrono::Duration::seconds(1));
assert!(c.is_expired_at(Utc::now()));
}
}