use std::sync::Arc;
use std::time::Duration;
use dig_session::UnlockedMasterSeed;
use super::factors::AuthFactors;
use super::second_factor::SecondFactor;
use crate::id::{AccountId, ProfileIx};
use crate::store::{AccountStore, AccountStoreError};
use crate::unlocked::UnlockedAccount;
#[derive(Debug, thiserror::Error)]
pub enum UnlockError {
#[error("authorization refused: {0}")]
Unauthorized(String),
#[error(transparent)]
Keystore(#[from] AccountStoreError),
}
pub trait AuthPolicy: Send + Sync {
fn authorize(&self, factors: &AuthFactors) -> Result<(), UnlockError>;
}
pub struct PasswordOnlyPolicy;
impl AuthPolicy for PasswordOnlyPolicy {
fn authorize(&self, _factors: &AuthFactors) -> Result<(), UnlockError> {
Ok(())
}
}
pub struct AllOf {
factors: Vec<Box<dyn SecondFactor>>,
}
impl AllOf {
pub fn new(factors: Vec<Box<dyn SecondFactor>>) -> Self {
Self { factors }
}
}
impl AuthPolicy for AllOf {
fn authorize(&self, factors: &AuthFactors) -> Result<(), UnlockError> {
for factor in &self.factors {
factor
.verify(factors)
.map_err(|why| UnlockError::Unauthorized(format!("{}: {why}", factor.name())))?;
}
Ok(())
}
}
pub trait Clock: Send + Sync {
fn now(&self) -> std::time::Instant;
}
pub struct SystemClock;
impl Clock for SystemClock {
fn now(&self) -> std::time::Instant {
std::time::Instant::now()
}
}
pub struct UnlockGate {
account: AccountId,
default_profile_ix: ProfileIx,
store: AccountStore,
policy: Box<dyn AuthPolicy>,
clock: Box<dyn Clock>,
idle_timeout: Duration,
live: Option<(Arc<UnlockedMasterSeed>, std::time::Instant)>,
}
impl UnlockGate {
pub fn new(
account: AccountId,
default_profile_ix: ProfileIx,
store: AccountStore,
policy: Box<dyn AuthPolicy>,
idle_timeout: Duration,
clock: Box<dyn Clock>,
) -> Self {
Self {
account,
default_profile_ix,
store,
policy,
clock,
idle_timeout,
live: None,
}
}
pub fn is_unlocked(&self) -> bool {
match &self.live {
Some((_, last)) => self.clock.now().duration_since(*last) < self.idle_timeout,
None => false,
}
}
fn account_handle(&self, seed: Arc<UnlockedMasterSeed>) -> UnlockedAccount {
UnlockedAccount::new(self.account.clone(), seed, self.default_profile_ix)
}
pub fn unlock(&mut self, factors: AuthFactors) -> Result<UnlockedAccount, UnlockError> {
self.policy.authorize(&factors)?;
let seed = Arc::new(self.store.unlock(&self.account, factors.password)?);
self.live = Some((seed.clone(), self.clock.now()));
Ok(self.account_handle(seed))
}
pub fn access(&mut self) -> Option<UnlockedAccount> {
let now = self.clock.now();
match self.live.take() {
Some((seed, last)) if now.duration_since(last) < self.idle_timeout => {
self.live = Some((seed.clone(), now));
Some(self.account_handle(seed))
}
_ => None,
}
}
pub fn lock(&mut self) {
self.live = None;
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc as StdArc;
use std::time::Instant;
use dig_keystore::MemoryBackend;
use dig_session::{Password, SEED_LEN};
const SEED: [u8; SEED_LEN] = [0xC3; SEED_LEN];
const PW: &str = "correct horse battery staple";
#[derive(Clone)]
struct TestClock {
base: Instant,
advanced_ms: StdArc<AtomicU64>,
}
impl TestClock {
fn new() -> Self {
Self {
base: Instant::now(),
advanced_ms: StdArc::new(AtomicU64::new(0)),
}
}
fn advance(&self, d: Duration) {
self.advanced_ms
.fetch_add(d.as_millis() as u64, Ordering::SeqCst);
}
}
impl Clock for TestClock {
fn now(&self) -> Instant {
self.base + Duration::from_millis(self.advanced_ms.load(Ordering::SeqCst))
}
}
struct FixedCodeFactor(&'static str);
impl SecondFactor for FixedCodeFactor {
fn name(&self) -> &str {
"TOTP"
}
fn verify(&self, factors: &AuthFactors) -> Result<(), String> {
match factors.totp.as_deref() {
Some(code) if code == self.0 => Ok(()),
Some(_) => Err("invalid code".into()),
None => Err("code required".into()),
}
}
}
fn enrolled_store(id: &AccountId) -> AccountStore {
let ks = AccountStore::new(StdArc::new(MemoryBackend::new()));
ks.enroll(id, Password::new(PW), &SEED).unwrap();
ks
}
fn gate_with(policy: Box<dyn AuthPolicy>, idle: Duration, clock: TestClock) -> UnlockGate {
let id = AccountId::new("acct");
let ks = enrolled_store(&id);
UnlockGate::new(id, ProfileIx::ROOT, ks, policy, idle, Box::new(clock))
}
#[test]
fn password_only_unlock_yields_an_unlocked_account_not_a_raw_seed() {
let mut gate = gate_with(
Box::new(PasswordOnlyPolicy),
Duration::from_secs(60),
TestClock::new(),
);
let account = gate
.unlock(AuthFactors::password_only(Password::new(PW)))
.unwrap();
assert_eq!(account.account_id(), &AccountId::new("acct"));
assert!(gate.is_unlocked());
}
#[test]
fn a_wrong_password_fails_closed_and_stays_locked() {
let mut gate = gate_with(
Box::new(PasswordOnlyPolicy),
Duration::from_secs(60),
TestClock::new(),
);
assert!(matches!(
gate.unlock(AuthFactors::password_only(Password::new("wrong"))),
Err(UnlockError::Keystore(_))
));
assert!(!gate.is_unlocked());
assert!(gate.access().is_none());
}
#[test]
fn the_auth_policy_gates_the_unlock_before_the_password() {
let policy = AllOf::new(vec![Box::new(FixedCodeFactor("123456"))]);
let mut gate = gate_with(Box::new(policy), Duration::from_secs(60), TestClock::new());
let refused = gate.unlock(AuthFactors {
password: Password::new(PW),
totp: None,
passkey: None,
});
assert!(matches!(refused, Err(UnlockError::Unauthorized(_))));
assert!(!gate.is_unlocked());
let account = gate
.unlock(AuthFactors {
password: Password::new(PW),
totp: Some("123456".into()),
passkey: None,
})
.unwrap();
assert_eq!(account.account_id(), &AccountId::new("acct"));
assert!(gate.is_unlocked());
}
#[test]
fn access_within_the_idle_window_refreshes_the_deadline() {
let clock = TestClock::new();
let mut gate = gate_with(
Box::new(PasswordOnlyPolicy),
Duration::from_secs(60),
clock.clone(),
);
gate.unlock(AuthFactors::password_only(Password::new(PW)))
.unwrap();
for _ in 0..5 {
clock.advance(Duration::from_secs(59));
assert!(
gate.access().is_some(),
"access should refresh the deadline"
);
}
}
#[test]
fn idle_beyond_the_window_relocks_fail_closed() {
let clock = TestClock::new();
let mut gate = gate_with(
Box::new(PasswordOnlyPolicy),
Duration::from_secs(60),
clock.clone(),
);
gate.unlock(AuthFactors::password_only(Password::new(PW)))
.unwrap();
clock.advance(Duration::from_secs(61));
assert!(!gate.is_unlocked());
assert!(gate.access().is_none(), "an idle-expired seed must relock");
assert!(gate.access().is_none());
}
#[test]
fn lock_now_drops_the_seed_immediately() {
let mut gate = gate_with(
Box::new(PasswordOnlyPolicy),
Duration::from_secs(600),
TestClock::new(),
);
gate.unlock(AuthFactors::password_only(Password::new(PW)))
.unwrap();
assert!(gate.is_unlocked());
gate.lock();
assert!(!gate.is_unlocked());
assert!(gate.access().is_none());
}
}