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::session_residency::Residency;
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: Arc<dyn Clock>,
idle_timeout: Duration,
live: Option<LiveUnlock>,
}
struct LiveUnlock {
seed: Arc<UnlockedMasterSeed>,
residency: Arc<Residency>,
}
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: Arc::from(clock),
idle_timeout,
live: None,
}
}
pub fn is_unlocked(&self) -> bool {
self.live
.as_ref()
.is_some_and(|live| live.residency.is_live())
}
fn account_handle(&self, live: &LiveUnlock) -> UnlockedAccount {
UnlockedAccount::with_residency(
self.account.clone(),
live.seed.clone(),
self.default_profile_ix,
live.residency.clone(),
)
}
fn end_unlock(&mut self) {
if let Some(live) = self.live.take() {
live.residency.revoke();
}
}
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.end_unlock();
let live = LiveUnlock {
seed,
residency: Arc::new(Residency::idle_bounded(
self.clock.clone(),
self.idle_timeout,
)),
};
let handle = self.account_handle(&live);
self.live = Some(live);
Ok(handle)
}
pub fn access(&mut self) -> Option<UnlockedAccount> {
if !self.is_unlocked() {
self.end_unlock();
return None;
}
let live = self.live.as_ref().expect("checked live just above");
live.residency.touch();
Some(self.account_handle(live))
}
pub fn lock(&mut self) {
self.end_unlock();
}
}
impl Drop for UnlockGate {
fn drop(&mut self) {
self.end_unlock();
}
}
#[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, ENTROPY_LEN};
const SEED: [u8; ENTROPY_LEN] = [0xC3; ENTROPY_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());
}
fn gate_money_key() -> crate::keys::wallet_key::WalletKey {
let root = bip39::Mnemonic::from_entropy_in(bip39::Language::English, &SEED)
.expect("32 bytes is valid 24-word BIP-39 entropy")
.to_seed("");
crate::keys::wallet_key::WalletKey::from_seed_at(&root[..], ProfileIx::ROOT)
}
fn legit_send(send: u64, fee: u64, coin_amount: u64) -> Vec<chia_protocol::CoinSpend> {
use chia_puzzle_types::Memos;
use chia_wallet_sdk::driver::{SpendContext, StandardLayer};
use chia_wallet_sdk::types::Conditions;
let key = gate_money_key();
let mut ctx = SpendContext::new();
let recipient = chia_protocol::Bytes32::new([7u8; 32]);
let hint = ctx.hint(recipient).unwrap();
let mut conditions = Conditions::new().create_coin(recipient, send, hint);
let change = coin_amount - send - fee;
if change > 0 {
conditions = conditions.create_coin(key.puzzle_hash(), change, Memos::None);
}
if fee > 0 {
conditions = conditions.reserve_fee(fee);
}
let coin = chia_protocol::Coin::new(
chia_protocol::Bytes32::new([1u8; 32]),
key.puzzle_hash(),
coin_amount,
);
StandardLayer::new(key.public_key())
.spend(&mut ctx, coin, conditions)
.unwrap();
ctx.take()
}
fn approval_over(
coin_spends: &[chia_protocol::CoinSpend],
) -> crate::wallet::approval::SpendApproval {
use crate::wallet::summary::{SpendSummary, SpendTier};
let summary = SpendSummary::from_coin_spends(coin_spends, SpendTier::AutoSend)
.expect("the fixture spend must be summarizable");
let scope = crate::wallet::policy::CustodyScope::new(
ProfileIx::ROOT,
&crate::wallet::policy::CustodyPolicy::Hot(Default::default()),
gate_money_key().puzzle_hash(),
);
crate::wallet::approval::SpendApproval::new(coin_spends.to_vec(), summary, scope)
}
#[test]
fn lock_revokes_a_money_signer_retained_from_the_unlock() {
use crate::wallet::money_signer::MoneySigner;
use dig_wallet_backend::types::Network;
let mut gate = gate_with(
Box::new(PasswordOnlyPolicy),
Duration::from_secs(600),
TestClock::new(),
);
let account = gate
.unlock(AuthFactors::password_only(Password::new(PW)))
.unwrap();
let signer = account.wallet_ops().money_signer(Network::Mainnet);
let bundle = signer
.sign_approved(approval_over(&legit_send(610, 10, 1_000)))
.expect("a live session must sign");
assert_ne!(
bundle.aggregated_signature,
chia_bls::Signature::default(),
"the control must be a real signature over a real spend, not an empty aggregate"
);
gate.lock();
let after = signer.sign_approved(approval_over(&legit_send(610, 10, 1_000)));
assert!(
matches!(after, Err(crate::error::AccountError::Locked)),
"a signer retained across lock() must refuse as Locked, not sign a mainnet spend: \
{:?}",
after.map(|b| b.aggregated_signature)
);
}
#[test]
fn lock_revokes_the_residency_the_unlock_handed_out() {
let mut gate = gate_with(
Box::new(PasswordOnlyPolicy),
Duration::from_secs(600),
TestClock::new(),
);
let residency = gate
.unlock(AuthFactors::password_only(Password::new(PW)))
.unwrap()
.residency();
assert!(residency.is_live(), "a fresh unlock is live");
gate.lock();
assert!(
!residency.is_live(),
"a host that asks whether its capabilities are still valid must be told the truth"
);
}
#[test]
fn one_unlock_yields_one_shared_residency_across_every_handle() {
let mut gate = gate_with(
Box::new(PasswordOnlyPolicy),
Duration::from_secs(600),
TestClock::new(),
);
let first = gate
.unlock(AuthFactors::password_only(Password::new(PW)))
.unwrap()
.residency();
let second = gate
.access()
.expect("still within the idle window")
.residency();
assert!(first.is_live() && second.is_live());
gate.lock();
assert!(
!first.is_live(),
"the earlier handle's token must be revoked"
);
assert!(!second.is_live(), "and so must the later handle's");
}
#[test]
fn idle_expiry_revokes_the_residency_too() {
let clock = TestClock::new();
let mut gate = gate_with(
Box::new(PasswordOnlyPolicy),
Duration::from_secs(60),
clock.clone(),
);
let residency = gate
.unlock(AuthFactors::password_only(Password::new(PW)))
.unwrap()
.residency();
clock.advance(Duration::from_secs(61));
assert!(gate.access().is_none(), "the idle window has elapsed");
assert!(
!residency.is_live(),
"an idle-expired session must revoke the capabilities it issued"
);
}
#[test]
fn elapsing_the_idle_window_revokes_without_any_gate_call() {
use crate::wallet::money_signer::MoneySigner;
use dig_wallet_backend::types::Network;
let clock = TestClock::new();
let mut gate = gate_with(
Box::new(PasswordOnlyPolicy),
Duration::from_secs(60),
clock.clone(),
);
let account = gate
.unlock(AuthFactors::password_only(Password::new(PW)))
.unwrap();
let residency = account.residency();
let signer = account.wallet_ops().money_signer(Network::Mainnet);
let bundle = signer
.sign_approved(approval_over(&legit_send(610, 10, 1_000)))
.expect("a live session must sign");
assert_ne!(
bundle.aggregated_signature,
chia_bls::Signature::default(),
"the control must be a real signature over a real spend"
);
clock.advance(Duration::from_secs(3_600));
assert!(
!residency.is_live(),
"the idle window has elapsed, so the capabilities it issued are no longer live"
);
assert!(!gate.is_unlocked(), "and the gate must agree it is locked");
let after = signer.sign_approved(approval_over(&legit_send(610, 10, 1_000)));
assert!(
matches!(after, Err(crate::error::AccountError::Locked)),
"a signer retained past the idle window must refuse as Locked, not sign a mainnet \
spend: {:?}",
after.map(|b| b.aggregated_signature)
);
}
#[test]
fn access_within_the_window_refreshes_the_deadline() {
let clock = TestClock::new();
let mut gate = gate_with(
Box::new(PasswordOnlyPolicy),
Duration::from_secs(60),
clock.clone(),
);
let residency = gate
.unlock(AuthFactors::password_only(Password::new(PW)))
.unwrap()
.residency();
for _ in 0..3 {
clock.advance(Duration::from_secs(45));
assert!(gate.access().is_some(), "still within the refreshed window");
assert!(residency.is_live(), "and its capabilities are still live");
}
clock.advance(Duration::from_secs(60));
assert!(!residency.is_live(), "the refreshed window has now elapsed");
}
#[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());
}
}