use std::future::Future;
use serde::{Serialize, de::DeserializeOwned};
use time::OffsetDateTime;
use crate::auth::login::forms::{LoginErrorCode, LoginOutcome};
use crate::auth::two_factor::api::{TwoFactorServerError, verify_totp_step};
use crate::auth::two_factor::{
TwoFactorChallenge, TwoFactorCode, TwoFactorLoginForm, TwoFactorLoginPayload,
};
use crate::messages::AuthMessage;
use crate::ratelimit::SecurityState;
use crate::status::{AuthDecision, AuthDenyReason, auth_deny_message};
const TWO_FACTOR_SESSION_KEY: &str = "two_factor_challenge";
pub trait LoginSession {
type User;
type Id;
fn session_get<T: DeserializeOwned>(&self, key: &str) -> Option<T>;
fn session_set<T: Serialize>(&mut self, key: &str, value: &T);
fn session_remove(&mut self, key: &str);
fn pending_two_factor_challenge(&self) -> Option<TwoFactorChallenge> {
self.session_get(TWO_FACTOR_SESSION_KEY)
}
fn set_pending_two_factor_challenge(&mut self, challenge: &TwoFactorChallenge) {
self.session_set(TWO_FACTOR_SESSION_KEY, challenge);
}
fn clear_pending_two_factor_challenge(&mut self) {
self.session_remove(TWO_FACTOR_SESSION_KEY);
}
fn session_opt_in(&mut self);
fn renew_session(&mut self);
fn login_user(&mut self, id: Self::Id);
fn remember_user(&mut self, remember: bool);
fn set_current_user(&mut self, user: Self::User);
fn establish_authenticated_session(&mut self, id: Self::Id, user: Self::User, remember: bool) {
self.renew_session();
self.session_opt_in();
self.login_user(id);
self.remember_user(remember);
self.set_current_user(user);
}
}
pub trait LoginAccount {
fn id(&self) -> &str;
fn auth_decision(&self) -> AuthDecision;
}
pub trait LoginCredentials {
type Account: LoginAccount;
fn account(&self) -> &Self::Account;
fn password_hash(&self) -> &str;
fn two_factor_enabled(&self) -> bool;
}
pub trait AccountHash {
fn account_hash(&self) -> &str;
}
#[macro_export]
macro_rules! impl_login_traits {
($account:ty, $credentials:ty, $decision:expr) => {
impl $crate::auth::login::api::LoginAccount for $account {
fn id(&self) -> &str {
self.id.as_str()
}
fn auth_decision(&self) -> $crate::status::AuthDecision {
($decision)(self)
}
}
impl $crate::auth::login::api::AccountHash for $account {
fn account_hash(&self) -> &str {
self.account_hash.as_str()
}
}
impl $crate::auth::login::api::LoginCredentials for $credentials {
type Account = $account;
fn account(&self) -> &Self::Account {
&self.account
}
fn password_hash(&self) -> &str {
self.password_hash.as_str()
}
fn two_factor_enabled(&self) -> bool {
self.twofa_enabled
}
}
};
}
impl<User, Type, Sess, Pool> LoginSession for axum_session_auth::AuthSession<User, Type, Sess, Pool>
where
User: axum_session_auth::Authentication<User, Type, Pool> + Clone + Send,
Pool: Clone + Send + Sync + std::fmt::Debug + 'static,
Type: Eq
+ Default
+ Clone
+ Send
+ Sync
+ std::hash::Hash
+ Serialize
+ DeserializeOwned
+ 'static,
Sess: axum_session::DatabasePool + Clone + std::fmt::Debug + Sync + Send + 'static,
{
type User = User;
type Id = Type;
fn session_get<T: DeserializeOwned>(&self, key: &str) -> Option<T> {
self.session.get::<T>(key)
}
fn session_set<T: Serialize>(&mut self, key: &str, value: &T) {
self.session.set(key, value);
}
fn session_remove(&mut self, key: &str) {
self.session.remove(key);
}
fn session_opt_in(&mut self) {
self.session.set_store(true);
}
fn renew_session(&mut self) {
self.session.renew();
}
fn login_user(&mut self, id: Self::Id) {
axum_session_auth::AuthSession::login_user(self, id);
}
fn remember_user(&mut self, remember: bool) {
axum_session_auth::AuthSession::remember_user(self, remember);
}
fn set_current_user(&mut self, user: Self::User) {
self.current_user = Some(user);
}
}
pub struct LoginContext<'a, Auth> {
auth: &'a mut Auth,
captcha_valid: bool,
}
impl<'a, Auth: LoginSession<Id = String>> LoginContext<'a, Auth> {
pub fn new(auth: &'a mut Auth, captcha_valid: bool) -> Self {
Self {
auth,
captcha_valid,
}
}
fn success_outcome(&self) -> LoginOutcome {
LoginOutcome::success(
Some(AuthMessage::from_static("auth.login.feedback.success")),
self.captcha_valid,
)
}
fn account_denied_outcome(&self, reason: AuthDenyReason) -> LoginOutcome {
let message = auth_deny_message(&reason);
LoginOutcome::account_denied(reason, Some(message), self.captcha_valid)
}
fn outcome_for_error(&self, code: LoginErrorCode, token: Option<String>) -> LoginOutcome {
LoginOutcome::failure_with_two_factor(code, code.message(), self.captcha_valid, token)
}
}
#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum LoginError {
#[error("login credentials are unavailable")]
CredentialsUnavailable,
#[error("password verification is unavailable")]
VerificationUnavailable,
}
pub fn noop_login_hook<Auth, Account>(_: &mut Auth, _: Account) -> std::future::Ready<()> {
std::future::ready(())
}
pub fn noop_session_hook<Auth>(_: &mut Auth) -> std::future::Ready<()> {
std::future::ready(())
}
pub fn rate_limited_login_outcome(captcha_valid: bool) -> LoginOutcome {
LoginOutcome::failure(
LoginErrorCode::RateLimited,
LoginErrorCode::RateLimited.message(),
captcha_valid,
)
}
pub async fn finalize_login<
'a,
Auth,
Account,
BuildUser,
OnTwoFactor,
OnTwoFactorFut,
OnSuccess,
OnSuccessFut,
>(
ctx: &'a mut LoginContext<'a, Auth>,
account: Account,
two_factor_enabled: bool,
build_user: BuildUser,
on_two_factor: OnTwoFactor,
on_success: OnSuccess,
) -> LoginOutcome
where
Auth: LoginSession<Id = String>,
Account: LoginAccount,
BuildUser: Fn(&Account) -> Auth::User,
OnTwoFactor: FnOnce(&'a mut Auth, Account) -> OnTwoFactorFut,
OnTwoFactorFut: Future<Output = ()>,
OnSuccess: FnOnce(&'a mut Auth, Account) -> OnSuccessFut,
OnSuccessFut: Future<Output = ()>,
{
if two_factor_enabled {
let challenge = TwoFactorChallenge::new(account.id().to_string());
let token = challenge.token().to_string();
ctx.auth.renew_session();
ctx.auth.session_opt_in();
ctx.auth.set_pending_two_factor_challenge(&challenge);
let outcome = LoginOutcome::success_with_two_factor(
Some(AuthMessage::from_static(
"auth.login.feedback.two_factor_required",
)),
ctx.captcha_valid,
Some(token),
);
on_two_factor(ctx.auth, account).await;
return outcome;
}
let account_id = account.id().to_string();
ctx.auth
.establish_authenticated_session(account_id, build_user(&account), true);
let outcome = ctx.success_outcome();
on_success(ctx.auth, account).await;
outcome
}
pub struct LoginWithCredentialsCallbacks<
FetchCredentials,
VerifyPassword,
BuildUser,
OnTwoFactor,
OnSuccess,
OnFailure,
> {
pub fetch_credentials: FetchCredentials,
pub verify_password: VerifyPassword,
pub dummy_password_hash: DummyPasswordHash,
pub build_user: BuildUser,
pub on_two_factor: OnTwoFactor,
pub on_success: OnSuccess,
pub on_failure: OnFailure,
}
#[derive(Clone, PartialEq, Eq)]
pub struct DummyPasswordHash(String);
impl DummyPasswordHash {
pub fn new(hash: impl Into<String>) -> Result<Self, DummyPasswordHashError> {
let hash = hash.into();
if hash.trim().is_empty() {
return Err(DummyPasswordHashError);
}
Ok(Self(hash))
}
#[must_use]
pub fn as_str(&self) -> &str {
self.0.as_str()
}
}
impl Default for DummyPasswordHash {
fn default() -> Self {
Self(
"$argon2id$v=19$m=19456,t=2,p=1$arjXQ/LUUIuovdLClWFtIw$J9sIrzrUPQ+mDJ2cgQdR90xL0PGfOwekiPGXJadZ/fE"
.to_owned(),
)
}
}
impl std::fmt::Debug for DummyPasswordHash {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_tuple("DummyPasswordHash")
.field(&"[REDACTED]")
.finish()
}
}
#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq, Eq)]
#[error("dummy password hash must not be empty")]
pub struct DummyPasswordHashError;
pub async fn login_with_credentials<
'a,
'b,
Auth,
Credentials,
FetchCredentials,
FetchFuture,
FetchError,
VerifyPassword,
VerifyError,
BuildUser,
OnTwoFactor,
OnTwoFactorFut,
OnSuccess,
OnSuccessFut,
OnFailure,
OnFailureFut,
>(
ctx: &'a mut LoginContext<'a, Auth>,
lookup: &'b str,
password: &'b str,
callbacks: LoginWithCredentialsCallbacks<
FetchCredentials,
VerifyPassword,
BuildUser,
OnTwoFactor,
OnSuccess,
OnFailure,
>,
) -> Result<LoginOutcome, LoginError>
where
Auth: LoginSession<Id = String>,
Credentials: LoginCredentials,
Credentials::Account: LoginAccount + Clone,
FetchCredentials: FnOnce(&'b str) -> FetchFuture,
FetchFuture: Future<Output = Result<Option<Credentials>, FetchError>>,
VerifyPassword: AsyncFnOnce(&str, &str) -> Result<bool, VerifyError>,
BuildUser: Fn(&Credentials::Account) -> Auth::User,
OnTwoFactor: FnOnce(&'a mut Auth, Credentials::Account) -> OnTwoFactorFut,
OnTwoFactorFut: Future<Output = ()>,
OnSuccess: FnOnce(&'a mut Auth, Credentials::Account) -> OnSuccessFut,
OnSuccessFut: Future<Output = ()>,
OnFailure: FnOnce(&'a mut Auth) -> OnFailureFut,
OnFailureFut: Future<Output = ()>,
{
let LoginWithCredentialsCallbacks {
fetch_credentials,
verify_password,
dummy_password_hash,
build_user,
on_two_factor,
on_success,
on_failure,
} = callbacks;
ctx.auth.clear_pending_two_factor_challenge();
let credentials = fetch_credentials(lookup)
.await
.map_err(|_error| LoginError::CredentialsUnavailable)?;
let password_matches = match credentials.as_ref() {
Some(credentials) => verify_password(password, credentials.password_hash()).await,
None => verify_password(password, dummy_password_hash.as_str()).await,
}
.map_err(|_error| LoginError::VerificationUnavailable)?;
if password_matches && let Some(credentials) = credentials {
let account = credentials.account();
let outcome = match account.auth_decision() {
AuthDecision::Allow => {
let account = account.clone();
Ok(finalize_login(
ctx,
account,
credentials.two_factor_enabled(),
build_user,
on_two_factor,
on_success,
)
.await)
}
AuthDecision::Deny(reason) => {
let outcome = ctx.account_denied_outcome(reason);
on_failure(ctx.auth).await;
Ok(outcome)
}
};
return outcome;
}
let outcome = ctx.outcome_for_error(LoginErrorCode::CredentialsInvalid, None);
on_failure(ctx.auth).await;
Ok(outcome)
}
pub struct TwoFactorLoginCallbacks<
LoadAccount,
LoadTwoFactorState,
ConsumeBackup,
ConsumeTotp,
BuildUser,
OnSuccess,
OnCleanup,
> {
pub load_account: LoadAccount,
pub load_two_factor_state: LoadTwoFactorState,
pub consume_backup_code: ConsumeBackup,
pub consume_totp_step: ConsumeTotp,
pub build_user: BuildUser,
pub on_success: OnSuccess,
pub on_cleanup: OnCleanup,
}
#[derive(Debug, thiserror::Error)]
pub enum TwoFactorLoginError {
#[error("auth.two_factor.invalid_input")]
InvalidInput(#[source] ch_parsing::error::ParseError),
#[error("auth.two_factor.state_unavailable")]
StateUnavailable,
#[error("auth.two_factor.verification_unavailable")]
Totp(#[source] TwoFactorServerError),
#[error("auth.two_factor.backup_unavailable")]
BackupUnavailable,
#[error("auth.two_factor.consumption_unavailable")]
ConsumptionUnavailable,
}
pub async fn complete_two_factor_login<
'a,
Auth,
Account,
LoadAccount,
LoadAccountFuture,
LoadAccountError,
LoadTwoFactorState,
LoadTwoFactorFuture,
LoadTwoFactorError,
ConsumeBackup,
ConsumeTotp,
ConsumeBackupFuture,
ConsumeBackupError,
ConsumeTotpError,
BuildUser,
OnSuccess,
OnSuccessFut,
OnCleanup,
OnCleanupFut,
>(
ctx: &'a mut LoginContext<'a, Auth>,
form: TwoFactorLoginForm,
security: &SecurityState,
callbacks: TwoFactorLoginCallbacks<
LoadAccount,
LoadTwoFactorState,
ConsumeBackup,
ConsumeTotp,
BuildUser,
OnSuccess,
OnCleanup,
>,
) -> Result<LoginOutcome, TwoFactorLoginError>
where
Auth: LoginSession<Id = String>,
Account: LoginAccount,
LoadAccount: FnOnce(&str) -> LoadAccountFuture,
LoadAccountFuture: Future<Output = Result<Account, LoadAccountError>>,
LoadTwoFactorState: FnOnce(&Account) -> LoadTwoFactorFuture,
LoadTwoFactorFuture: Future<Output = Result<(bool, Option<String>), LoadTwoFactorError>>,
ConsumeBackup: FnOnce(&Account, &str) -> ConsumeBackupFuture,
ConsumeBackupFuture: Future<Output = Result<bool, ConsumeBackupError>>,
ConsumeTotp: AsyncFnOnce(&Account, &str, u64) -> Result<bool, ConsumeTotpError>,
BuildUser: Fn(&Account) -> Auth::User,
OnSuccess: FnOnce(&'a mut Auth, Account) -> OnSuccessFut,
OnSuccessFut: Future<Output = ()>,
OnCleanup: FnOnce(&'a mut Auth) -> OnCleanupFut,
OnCleanupFut: Future<Output = ()>,
{
let TwoFactorLoginCallbacks {
load_account,
load_two_factor_state,
consume_backup_code,
consume_totp_step,
build_user,
on_success,
on_cleanup,
} = callbacks;
let parsed = TwoFactorLoginPayload::parse(form).map_err(TwoFactorLoginError::InvalidInput)?;
let token = parsed.token().as_str();
let code = parsed.code();
let now = OffsetDateTime::now_utc();
let Some(challenge) = ctx.auth.pending_two_factor_challenge() else {
return Ok(ctx.outcome_for_error(LoginErrorCode::TwoFactorMissing, None));
};
if challenge.is_expired(now) {
ctx.auth.clear_pending_two_factor_challenge();
let outcome = ctx.outcome_for_error(LoginErrorCode::TwoFactorExpired, None);
on_cleanup(ctx.auth).await;
return Ok(outcome);
}
if challenge.token() != token {
ctx.auth.clear_pending_two_factor_challenge();
let outcome = ctx.outcome_for_error(LoginErrorCode::TwoFactorMissing, None);
on_cleanup(ctx.auth).await;
return Ok(outcome);
}
if security
.check_two_factor_account(challenge.account_id())
.is_err()
{
return Ok(ctx.outcome_for_error(
LoginErrorCode::RateLimited,
Some(challenge.token().to_owned()),
));
}
let account = match load_account(challenge.account_id()).await {
Ok(account) => account,
Err(_error) => {
ctx.auth.clear_pending_two_factor_challenge();
let outcome = ctx.outcome_for_error(LoginErrorCode::TwoFactorMissing, None);
on_cleanup(ctx.auth).await;
return Ok(outcome);
}
};
if let AuthDecision::Deny(reason) = account.auth_decision() {
ctx.auth.clear_pending_two_factor_challenge();
let outcome = ctx.account_denied_outcome(reason);
on_cleanup(ctx.auth).await;
return Ok(outcome);
}
let (two_factor_enabled, two_factor_secret) = load_two_factor_state(&account)
.await
.map_err(|_error| TwoFactorLoginError::StateUnavailable)?;
if !two_factor_enabled {
ctx.auth.clear_pending_two_factor_challenge();
let outcome = ctx.outcome_for_error(LoginErrorCode::TwoFactorDisabled, None);
on_cleanup(ctx.auth).await;
return Ok(outcome);
}
let verified = match code {
TwoFactorCode::Totp(code) => {
let Some(secret) = two_factor_secret.as_deref() else {
ctx.auth.clear_pending_two_factor_challenge();
let outcome = ctx.outcome_for_error(LoginErrorCode::TwoFactorUnavailable, None);
on_cleanup(ctx.auth).await;
return Ok(outcome);
};
let value = code
.as_str()
.parse::<u32>()
.expect("validated six-digit TOTP");
match verify_totp_step(secret, value).map_err(TwoFactorLoginError::Totp)? {
Some(step) => consume_totp_step(&account, secret, step)
.await
.map_err(|_error| TwoFactorLoginError::ConsumptionUnavailable)?,
None => false,
}
}
TwoFactorCode::Backup(code) => consume_backup_code(&account, code.as_str())
.await
.map_err(|_error| TwoFactorLoginError::BackupUnavailable)?,
};
if !verified {
return Ok(ctx.outcome_for_error(
LoginErrorCode::TwoFactorInvalid,
Some(challenge.token().to_owned()),
));
}
let account_id = account.id().to_string();
ctx.auth
.establish_authenticated_session(account_id, build_user(&account), true);
ctx.auth.clear_pending_two_factor_challenge();
let outcome = ctx.success_outcome();
on_success(ctx.auth, account).await;
Ok(outcome)
}
pub async fn register_account_with_database<
Auth,
Account,
InsertAccount,
InsertFuture,
InsertError,
BuildUser,
>(
auth: &mut Auth,
form: crate::auth::login::forms::RegisterFormData,
insert_account: InsertAccount,
build_user: BuildUser,
) -> Result<crate::auth::login::forms::RegisterOutcome, ch_parsing::error::ParseError>
where
Auth: LoginSession<Id = String>,
Account: LoginAccount + AccountHash,
InsertAccount: FnOnce(Option<String>, Option<String>, &str) -> InsertFuture,
InsertFuture: Future<Output = Result<Account, InsertError>>,
BuildUser: Fn(&Account) -> Auth::User,
{
let parsed = form.parse()?;
Ok(register_account_with_values(
auth,
parsed.email,
parsed.full_name,
parsed.password,
insert_account,
build_user,
)
.await)
}
pub async fn register_account_with_values<
Auth,
Account,
InsertAccount,
InsertFuture,
InsertError,
BuildUser,
>(
auth: &mut Auth,
email: Option<String>,
full_name: Option<String>,
password: String,
insert_account: InsertAccount,
build_user: BuildUser,
) -> crate::auth::login::forms::RegisterOutcome
where
Auth: LoginSession<Id = String>,
Account: LoginAccount + AccountHash,
InsertAccount: FnOnce(Option<String>, Option<String>, &str) -> InsertFuture,
InsertFuture: Future<Output = Result<Account, InsertError>>,
BuildUser: Fn(&Account) -> Auth::User,
{
let success_message = AuthMessage::from_static("auth.register.feedback.success");
let failure_message = AuthMessage::from_static("auth.register.feedback.failed");
let account = match insert_account(email, full_name, password.as_str()).await {
Ok(account) => account,
Err(_error) => {
return crate::auth::login::forms::RegisterOutcome {
success: false,
message: Some(failure_message),
account_hash: None,
};
}
};
auth.establish_authenticated_session(account.id().to_string(), build_user(&account), true);
crate::auth::login::forms::RegisterOutcome {
success: true,
message: Some(success_message),
account_hash: Some(account.account_hash().to_string()),
}
}
#[cfg(test)]
mod tests {
use super::LoginError;
use super::{
AccountHash, DummyPasswordHash, LoginAccount, LoginContext, LoginCredentials, LoginOutcome,
LoginSession, LoginWithCredentialsCallbacks, TwoFactorLoginCallbacks, TwoFactorLoginError,
complete_two_factor_login, login_with_credentials,
};
use crate::auth::login::forms::LoginErrorCode;
use crate::auth::two_factor::api::TwoFactorServerError;
use crate::auth::two_factor::{TwoFactorChallenge, TwoFactorLoginForm};
use crate::ratelimit::SecurityState;
use crate::status::{AuthDecision, AuthDenyReason};
use anyhow::Error as AuthError;
use argon2::Argon2;
use argon2::password_hash::{PasswordHash, PasswordVerifier};
use serde::{Deserialize, Serialize};
use std::cell::Cell;
use std::collections::HashMap;
#[test]
fn default_dummy_password_hash_is_valid_argon2id() {
let dummy_hash = DummyPasswordHash::default();
let hash = PasswordHash::new(dummy_hash.as_str())
.expect("the published dummy hash must stay valid");
assert!(
Argon2::default()
.verify_password(b"deliberately-wrong", &hash)
.is_err()
);
}
#[test]
fn custom_dummy_password_hash_is_non_empty_and_redacted() {
assert!(DummyPasswordHash::new(" \t ").is_err());
let dummy_hash = DummyPasswordHash::new("algorithm-specific-hash")
.expect("non-empty custom hashes should be accepted");
assert_eq!(dummy_hash.as_str(), "algorithm-specific-hash");
assert!(!format!("{dummy_hash:?}").contains("algorithm-specific-hash"));
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct TestAccount {
id: String,
decision: AuthDecision,
account_hash: String,
}
impl LoginAccount for TestAccount {
fn id(&self) -> &str {
self.id.as_str()
}
fn auth_decision(&self) -> AuthDecision {
self.decision.clone()
}
}
impl AccountHash for TestAccount {
fn account_hash(&self) -> &str {
self.account_hash.as_str()
}
}
#[derive(Clone, Debug)]
struct TestCredentials {
account: TestAccount,
password_hash: String,
two_factor: bool,
}
impl LoginCredentials for TestCredentials {
type Account = TestAccount;
fn account(&self) -> &Self::Account {
&self.account
}
fn password_hash(&self) -> &str {
self.password_hash.as_str()
}
fn two_factor_enabled(&self) -> bool {
self.two_factor
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum MacroStatus {
Active,
Blocked,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct MacroAccount {
id: String,
status: MacroStatus,
account_hash: String,
}
#[derive(Clone, Debug)]
struct MacroCredentials {
account: MacroAccount,
password_hash: String,
twofa_enabled: bool,
}
impl_login_traits!(MacroAccount, MacroCredentials, |account: &MacroAccount| {
match account.status {
MacroStatus::Active => AuthDecision::allow(),
MacroStatus::Blocked => AuthDecision::deny(AuthDenyReason::blocked()),
}
});
#[derive(Default)]
struct TestSessionStore {
entries: HashMap<String, serde_json::Value>,
}
impl TestSessionStore {
fn get<T: for<'de> Deserialize<'de>>(&self, key: &str) -> Option<T> {
let value = self.entries.get(key)?;
serde_json::from_value(value.clone()).ok()
}
fn set<T: Serialize>(&mut self, key: &str, value: &T) {
if let Ok(serialized) = serde_json::to_value(value) {
self.entries.insert(key.to_string(), serialized);
}
}
fn remove(&mut self, key: &str) {
self.entries.remove(key);
}
}
#[derive(Default)]
struct TestAuthSession {
session: TestSessionStore,
store: bool,
logged_in: Option<String>,
remember: bool,
renewals: usize,
user: Option<TestAccount>,
}
impl LoginSession for TestAuthSession {
type User = TestAccount;
type Id = String;
fn session_get<T: for<'de> Deserialize<'de>>(&self, key: &str) -> Option<T> {
self.session.get(key)
}
fn session_set<T: Serialize>(&mut self, key: &str, value: &T) {
self.session.set(key, value);
}
fn session_remove(&mut self, key: &str) {
self.session.remove(key);
}
fn session_opt_in(&mut self) {
self.store = true;
}
fn renew_session(&mut self) {
self.renewals += 1;
}
fn login_user(&mut self, id: Self::Id) {
self.logged_in = Some(id);
}
fn remember_user(&mut self, remember: bool) {
self.remember = remember;
}
fn set_current_user(&mut self, user: Self::User) {
self.user = Some(user);
}
}
async fn login_with_test_credentials<'a>(
ctx: &'a mut LoginContext<'a, TestAuthSession>,
credentials: TestCredentials,
) -> Result<LoginOutcome, LoginError> {
login_with_credentials(
ctx,
"account-1",
"password",
LoginWithCredentialsCallbacks {
fetch_credentials: move |_lookup| {
std::future::ready(Ok::<Option<TestCredentials>, std::convert::Infallible>(
Some(credentials),
))
},
verify_password: async |_password: &str, _hash: &str| {
Ok::<_, std::convert::Infallible>(true)
},
dummy_password_hash: DummyPasswordHash::default(),
build_user: |account: &TestAccount| account.clone(),
on_two_factor: |_, _| std::future::ready(()),
on_success: |_, _| std::future::ready(()),
on_failure: |_| std::future::ready(()),
},
)
.await
}
#[tokio::test]
async fn login_with_credentials_success() {
let mut auth = TestAuthSession::default();
let mut ctx = LoginContext::new(&mut auth, true);
let credentials = TestCredentials {
account: TestAccount {
id: "account-1".to_string(),
decision: AuthDecision::allow(),
account_hash: "hash".to_string(),
},
password_hash: "hashed".to_string(),
two_factor: false,
};
let outcome = login_with_test_credentials(&mut ctx, credentials)
.await
.expect("login should succeed");
assert!(outcome.success);
assert_eq!(outcome.error_code, LoginErrorCode::None);
assert!(auth.logged_in.is_some());
assert!(auth.store);
assert!(auth.remember);
assert_eq!(auth.renewals, 1);
}
#[tokio::test]
async fn unknown_account_runs_the_injected_password_verifier() {
let mut auth = TestAuthSession::default();
let mut ctx = LoginContext::new(&mut auth, true);
let verifier_called = Cell::new(false);
let dummy_password_hash = DummyPasswordHash::default();
let expected_dummy_hash = dummy_password_hash.as_str().to_owned();
let outcome = login_with_credentials(
&mut ctx,
"missing@example.test",
"submitted-password",
LoginWithCredentialsCallbacks {
fetch_credentials: |_lookup| {
std::future::ready(Ok::<Option<TestCredentials>, std::convert::Infallible>(
None,
))
},
verify_password: async |password: &str, hash: &str| {
verifier_called.set(true);
assert_eq!(password, "submitted-password");
assert_eq!(hash, expected_dummy_hash);
Ok::<_, std::convert::Infallible>(true)
},
dummy_password_hash,
build_user: |account: &TestAccount| account.clone(),
on_two_factor: |_, _| std::future::ready(()),
on_success: |_, _| std::future::ready(()),
on_failure: |_| std::future::ready(()),
},
)
.await
.expect("unknown accounts should return a public login outcome");
assert!(verifier_called.get());
assert!(!outcome.success);
assert_eq!(outcome.error_code, LoginErrorCode::CredentialsInvalid);
assert!(auth.logged_in.is_none());
}
#[tokio::test]
async fn login_with_credentials_two_factor() {
let mut auth = TestAuthSession::default();
let mut ctx = LoginContext::new(&mut auth, true);
let credentials = TestCredentials {
account: TestAccount {
id: "account-1".to_string(),
decision: AuthDecision::allow(),
account_hash: "hash".to_string(),
},
password_hash: "hashed".to_string(),
two_factor: true,
};
let outcome = login_with_test_credentials(&mut ctx, credentials)
.await
.expect("login should succeed");
assert!(outcome.success);
assert!(outcome.requires_two_factor);
assert!(auth.store);
assert_eq!(auth.renewals, 1);
assert!(auth.logged_in.is_none());
let stored = auth.pending_two_factor_challenge();
assert!(stored.is_some());
}
#[tokio::test]
async fn two_factor_backup_code_success() {
let mut auth = TestAuthSession::default();
let challenge = TwoFactorChallenge::new("account-1".to_string());
auth.set_pending_two_factor_challenge(&challenge);
let mut ctx = LoginContext::new(&mut auth, true);
let form = TwoFactorLoginForm::new(challenge.token().to_string(), "ABCDEFGH".to_string());
let outcome = complete_two_factor_login(
&mut ctx,
form,
&SecurityState::new(100.try_into().unwrap()),
TwoFactorLoginCallbacks {
load_account: |_id: &str| {
std::future::ready(Ok::<TestAccount, std::convert::Infallible>(TestAccount {
id: "account-1".to_string(),
decision: AuthDecision::allow(),
account_hash: "hash".to_string(),
}))
},
load_two_factor_state: |_account: &TestAccount| {
std::future::ready(Ok::<(bool, Option<String>), std::convert::Infallible>((
true, None,
)))
},
consume_backup_code: |_account: &TestAccount, _code: &str| {
std::future::ready(Ok::<bool, std::convert::Infallible>(true))
},
consume_totp_step: async |_: &TestAccount, _: &str, _: u64| {
Ok::<_, std::convert::Infallible>(true)
},
build_user: |account: &TestAccount| account.clone(),
on_success: |_, _| std::future::ready(()),
on_cleanup: |_| std::future::ready(()),
},
)
.await
.expect("two factor should succeed");
assert!(outcome.success);
assert_eq!(outcome.error_code, LoginErrorCode::None);
assert!(auth.store);
assert_eq!(auth.renewals, 1);
assert!(auth.pending_two_factor_challenge().is_none());
}
#[tokio::test]
async fn two_factor_backup_code_invalid() {
let mut auth = TestAuthSession::default();
let challenge = TwoFactorChallenge::new("account-1".to_string());
auth.set_pending_two_factor_challenge(&challenge);
let mut ctx = LoginContext::new(&mut auth, true);
let form = TwoFactorLoginForm::new(challenge.token().to_string(), "ABCDEFGH".to_string());
let outcome = complete_two_factor_login(
&mut ctx,
form,
&SecurityState::new(100.try_into().unwrap()),
TwoFactorLoginCallbacks {
load_account: |_id: &str| {
std::future::ready(Ok::<TestAccount, std::convert::Infallible>(TestAccount {
id: "account-1".to_string(),
decision: AuthDecision::allow(),
account_hash: "hash".to_string(),
}))
},
load_two_factor_state: |_account: &TestAccount| {
std::future::ready(Ok::<(bool, Option<String>), std::convert::Infallible>((
true, None,
)))
},
consume_backup_code: |_account: &TestAccount, _code: &str| {
std::future::ready(Ok::<bool, std::convert::Infallible>(false))
},
consume_totp_step: async |_: &TestAccount, _: &str, _: u64| {
Ok::<_, std::convert::Infallible>(true)
},
build_user: |account: &TestAccount| account.clone(),
on_success: |_, _| std::future::ready(()),
on_cleanup: |_| std::future::ready(()),
},
)
.await
.expect("two factor should return outcome");
assert!(!outcome.success);
assert_eq!(outcome.error_code, LoginErrorCode::TwoFactorInvalid);
assert!(auth.pending_two_factor_challenge().is_some());
}
#[tokio::test]
async fn two_factor_malformed_input_is_typed_before_callbacks() {
fn assert_error_contract<E: std::error::Error + Send + Sync + 'static>() {}
assert_error_contract::<TwoFactorLoginError>();
let valid_token = "submitted-token-sensitive-marker";
for (token, code) in [
(valid_token.to_string(), "code-sensitive!marker".to_string()),
(String::new(), "123456".to_string()),
("token-sensitive-marker".repeat(13), "123456".to_string()),
(valid_token.to_string(), "code-sensitive-marker".repeat(4)),
] {
let mut auth = TestAuthSession::default();
let challenge = TwoFactorChallenge::new("account-1".to_string());
auth.set_pending_two_factor_challenge(&challenge);
let original_entries = auth.session.entries.clone();
let mut ctx = LoginContext::new(&mut auth, true);
let error = complete_two_factor_login(
&mut ctx,
TwoFactorLoginForm::new(token.clone(), code.clone()),
&SecurityState::new(100.try_into().unwrap()),
TwoFactorLoginCallbacks {
load_account:
|_id: &str| -> std::future::Ready<Result<TestAccount, AuthError>> {
panic!("malformed input must not load an account")
},
load_two_factor_state: |_account: &TestAccount| -> std::future::Ready<
Result<(bool, Option<String>), AuthError>,
> {
panic!("malformed input must not load verification state")
},
consume_backup_code:
|_account: &TestAccount,
_code: &str|
-> std::future::Ready<Result<bool, AuthError>> {
panic!("malformed input must not consume backup codes")
},
consume_totp_step: async |_: &TestAccount, _: &str, _: u64| {
Ok::<_, std::convert::Infallible>(true)
},
build_user: |_account: &TestAccount| -> TestAccount {
panic!("malformed input must not build a session user")
},
on_success: |_, _| -> std::future::Ready<()> {
panic!("malformed input must not invoke successful login work")
},
on_cleanup: |_| -> std::future::Ready<()> {
panic!("malformed input must preserve the pending challenge")
},
},
)
.await
.expect_err("malformed input must return a typed parser failure");
assert!(matches!(error, TwoFactorLoginError::InvalidInput(_)));
for rendered in [error.to_string(), format!("{error:?}")] {
assert!(!rendered.contains(&code));
if !token.is_empty() {
assert!(!rendered.contains(&token));
}
}
assert_eq!(auth.session.entries, original_entries);
assert!(!auth.store && !auth.remember);
assert_eq!(auth.renewals, 0);
assert!(auth.logged_in.is_none() && auth.user.is_none());
}
}
#[tokio::test]
async fn two_factor_state_backend_failure_preserves_pending_session() {
let mut auth = TestAuthSession::default();
let challenge = TwoFactorChallenge::new("account-1".to_string());
auth.set_pending_two_factor_challenge(&challenge);
let original_entries = auth.session.entries.clone();
let state_called = Cell::new(false);
let mut ctx = LoginContext::new(&mut auth, true);
let error = complete_two_factor_login(
&mut ctx,
TwoFactorLoginForm::new(challenge.token().to_string(), "123456".to_string()),
&SecurityState::new(100.try_into().unwrap()),
TwoFactorLoginCallbacks {
load_account: |id: &str| {
assert_eq!(id, "account-1");
std::future::ready(Ok::<_, AuthError>(TestAccount {
id: id.to_string(),
decision: AuthDecision::allow(),
account_hash: "hash".to_string(),
}))
},
load_two_factor_state: |_account: &TestAccount| {
state_called.set(true);
std::future::ready(Err::<(bool, Option<String>), _>(anyhow::anyhow!(
"state-backend-sensitive-marker"
)))
},
consume_backup_code:
|_account: &TestAccount,
_code: &str|
-> std::future::Ready<Result<bool, AuthError>> {
panic!("state backend failure must not consume backup codes")
},
consume_totp_step: async |_: &TestAccount, _: &str, _: u64| {
Ok::<_, std::convert::Infallible>(true)
},
build_user: |_account: &TestAccount| -> TestAccount {
panic!("state backend failure must not build a session user")
},
on_success: |_, _| -> std::future::Ready<()> {
panic!("state backend failure must not authenticate")
},
on_cleanup: |_| -> std::future::Ready<()> {
panic!("state backend failure must preserve the pending challenge")
},
},
)
.await
.expect_err("backend state failure must be typed");
assert!(state_called.get());
assert!(matches!(error, TwoFactorLoginError::StateUnavailable));
assert!(!format!("{error} {error:?}").contains("state-backend-sensitive-marker"));
assert_eq!(auth.session.entries, original_entries);
assert!(!auth.store && !auth.remember);
assert_eq!(auth.renewals, 0);
assert!(auth.logged_in.is_none() && auth.user.is_none());
}
#[tokio::test]
async fn two_factor_invalid_stored_secret_returns_totp_decode_error() {
let mut auth = TestAuthSession::default();
let challenge = TwoFactorChallenge::new("account-1".to_string());
auth.set_pending_two_factor_challenge(&challenge);
let original_entries = auth.session.entries.clone();
let mut ctx = LoginContext::new(&mut auth, true);
let error = complete_two_factor_login(
&mut ctx,
TwoFactorLoginForm::new(challenge.token().to_string(), "123456".to_string()),
&SecurityState::new(100.try_into().unwrap()),
TwoFactorLoginCallbacks {
load_account: |_id: &str| {
std::future::ready(Ok::<_, AuthError>(TestAccount {
id: "account-1".to_string(),
decision: AuthDecision::allow(),
account_hash: "hash".to_string(),
}))
},
load_two_factor_state: |_account: &TestAccount| {
std::future::ready(Ok::<_, AuthError>((
true,
Some("stored-secret-sensitive-marker!!!".to_string()),
)))
},
consume_backup_code:
|_account: &TestAccount,
_code: &str|
-> std::future::Ready<Result<bool, AuthError>> {
panic!("a TOTP request must not fall back to backup consumption")
},
consume_totp_step: async |_: &TestAccount, _: &str, _: u64| {
Ok::<_, std::convert::Infallible>(true)
},
build_user: |_account: &TestAccount| -> TestAccount {
panic!("a corrupt server secret must not build a session user")
},
on_success: |_, _| -> std::future::Ready<()> {
panic!("a corrupt server secret must not authenticate")
},
on_cleanup: |_| -> std::future::Ready<()> {
panic!("a corrupt server secret must preserve the pending challenge")
},
},
)
.await
.expect_err("real TOTP verification must reject an undecodable stored secret");
assert!(matches!(
error,
TwoFactorLoginError::Totp(TwoFactorServerError::TotpDecode)
));
assert!(!format!("{error} {error:?}").contains("stored-secret-sensitive-marker"));
assert_eq!(auth.session.entries, original_entries);
assert!(!auth.store && !auth.remember);
assert_eq!(auth.renewals, 0);
assert!(auth.logged_in.is_none() && auth.user.is_none());
}
#[tokio::test]
async fn two_factor_backup_backend_failure_is_redacted_and_preserves_session() {
let mut auth = TestAuthSession::default();
let challenge = TwoFactorChallenge::new("account-1".to_string());
auth.set_pending_two_factor_challenge(&challenge);
let original_entries = auth.session.entries.clone();
let consume_called = Cell::new(false);
let mut ctx = LoginContext::new(&mut auth, true);
let error = complete_two_factor_login(
&mut ctx,
TwoFactorLoginForm::new(challenge.token().to_string(), "ABCDEFGH".to_string()),
&SecurityState::new(100.try_into().unwrap()),
TwoFactorLoginCallbacks {
load_account: |_id: &str| {
std::future::ready(Ok::<_, AuthError>(TestAccount {
id: "account-1".to_string(),
decision: AuthDecision::allow(),
account_hash: "hash".to_string(),
}))
},
load_two_factor_state: |_account: &TestAccount| {
std::future::ready(Ok::<_, AuthError>((true, None)))
},
consume_backup_code: |account: &TestAccount, code: &str| {
assert_eq!(account.id, "account-1");
assert_eq!(code, "ABCDEFGH");
consume_called.set(true);
std::future::ready(Err::<bool, _>(anyhow::anyhow!(
"backup-backend-sensitive-marker"
)))
},
consume_totp_step: async |_: &TestAccount, _: &str, _: u64| {
Ok::<_, std::convert::Infallible>(true)
},
build_user: |_account: &TestAccount| -> TestAccount {
panic!("failed atomic consumption must not build a session user")
},
on_success: |_, _| -> std::future::Ready<()> {
panic!("failed atomic consumption must not authenticate")
},
on_cleanup: |_| -> std::future::Ready<()> {
panic!("failed atomic consumption must preserve the pending challenge")
},
},
)
.await
.expect_err("atomic backup consumption failure must be typed");
assert!(consume_called.get());
assert!(matches!(error, TwoFactorLoginError::BackupUnavailable));
assert!(std::error::Error::source(&error).is_none());
assert!(!format!("{error} {error:?}").contains("backup-backend-sensitive-marker"));
assert_eq!(auth.session.entries, original_entries);
assert!(!auth.store && !auth.remember);
assert_eq!(auth.renewals, 0);
assert!(auth.logged_in.is_none() && auth.user.is_none());
}
#[tokio::test]
async fn two_factor_real_totp_success_establishes_authenticated_session() {
const SECRET: &str = "JBSWY3DPEHPK3PXP";
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.expect("test clock must follow the Unix epoch");
let remainder = (now.as_millis() % 30_000) as u64;
if remainder >= 29_000 {
tokio::time::sleep(std::time::Duration::from_millis(30_020 - remainder)).await;
}
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.expect("test clock must follow the Unix epoch")
.as_secs();
let code = otpauth::TOTP::from_base32(SECRET)
.expect("synthetic TOTP secret must decode")
.generate(30, timestamp);
let mut auth = TestAuthSession::default();
let challenge = TwoFactorChallenge::new("account-1".to_string());
auth.set_pending_two_factor_challenge(&challenge);
let expected_account = TestAccount {
id: "account-1".to_string(),
decision: AuthDecision::allow(),
account_hash: "hash".to_string(),
};
let success_called = Cell::new(false);
let mut ctx = LoginContext::new(&mut auth, true);
let outcome = complete_two_factor_login(
&mut ctx,
TwoFactorLoginForm::new(challenge.token().to_string(), format!("{code:06}")),
&SecurityState::new(100.try_into().unwrap()),
TwoFactorLoginCallbacks {
load_account: |id: &str| {
assert_eq!(id, expected_account.id);
std::future::ready(Ok::<_, AuthError>(expected_account.clone()))
},
load_two_factor_state: |_account: &TestAccount| {
std::future::ready(Ok::<_, AuthError>((true, Some(SECRET.to_string()))))
},
consume_backup_code:
|_account: &TestAccount,
_code: &str|
-> std::future::Ready<Result<bool, AuthError>> {
panic!("real TOTP success must not consume a backup code")
},
consume_totp_step: async |_: &TestAccount, _: &str, _: u64| {
Ok::<_, std::convert::Infallible>(true)
},
build_user: |account: &TestAccount| account.clone(),
on_success: |session: &mut TestAuthSession, account: TestAccount| {
assert_eq!(account, expected_account);
assert_eq!(session.logged_in.as_deref(), Some("account-1"));
assert!(session.store && session.remember);
assert_eq!(session.renewals, 1);
assert!(session.pending_two_factor_challenge().is_none());
success_called.set(true);
std::future::ready(())
},
on_cleanup: |_| -> std::future::Ready<()> {
panic!("successful login must use its success callback")
},
},
)
.await
.expect("real current TOTP must authenticate");
assert!(outcome.success && !outcome.requires_two_factor);
assert_eq!(outcome.error_code, LoginErrorCode::None);
assert!(success_called.get());
assert_eq!(auth.logged_in.as_deref(), Some("account-1"));
assert_eq!(auth.user, Some(expected_account));
assert!(auth.store && auth.remember);
assert_eq!(auth.renewals, 1);
assert!(auth.pending_two_factor_challenge().is_none());
}
async fn complete_totp_fixture(
auth: &mut TestAuthSession,
form: TwoFactorLoginForm,
security: &SecurityState,
consume_result: Result<bool, AuthError>,
load_count: &Cell<usize>,
) -> Result<LoginOutcome, TwoFactorLoginError> {
let mut ctx = LoginContext::new(auth, true);
complete_two_factor_login(
&mut ctx,
form,
security,
TwoFactorLoginCallbacks {
load_account: |id: &str| {
load_count.set(load_count.get() + 1);
std::future::ready(Ok::<_, AuthError>(TestAccount {
id: id.to_owned(),
account_hash: "hash".to_owned(),
decision: AuthDecision::allow(),
}))
},
load_two_factor_state: |_: &TestAccount| {
std::future::ready(Ok::<_, AuthError>((
true,
Some("JBSWY3DPEHPK3PXP".to_owned()),
)))
},
consume_totp_step: async |_: &TestAccount, secret: &str, _: u64| {
assert_eq!(secret, "JBSWY3DPEHPK3PXP");
consume_result
},
consume_backup_code: |_: &TestAccount, _: &str| {
std::future::ready(Ok::<_, AuthError>(false))
},
build_user: |account: &TestAccount| account.clone(),
on_success: |_, _| std::future::ready(()),
on_cleanup: |_| std::future::ready(()),
},
)
.await
}
#[tokio::test]
async fn verified_totp_requires_successful_durable_consumption_before_session_creation() {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap();
let remainder = (now.as_millis() % 30_000) as u64;
if remainder >= 29_000 {
tokio::time::sleep(std::time::Duration::from_millis(30_020 - remainder)).await;
}
for consume_result in [
Ok(false),
Err(anyhow::anyhow!("private database secret")),
Ok(true),
] {
let expected = match &consume_result {
Ok(value) => Some(*value),
Err(_) => None,
};
let mut auth = TestAuthSession::default();
let challenge = TwoFactorChallenge::new("account-1".to_owned());
auth.set_pending_two_factor_challenge(&challenge);
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs();
let code = otpauth::TOTP::from_base32("JBSWY3DPEHPK3PXP")
.unwrap()
.generate(30, timestamp);
let result = complete_totp_fixture(
&mut auth,
TwoFactorLoginForm::new(challenge.token().to_owned(), format!("{code:06}")),
&SecurityState::new(100.try_into().unwrap()),
consume_result,
&Cell::new(0),
)
.await;
match expected {
Some(true) => assert!(result.expect("durable consumption").success),
Some(false) => assert_eq!(
result.expect("replay rejection").error_code,
LoginErrorCode::TwoFactorInvalid
),
None => {
let error = result.expect_err("storage failure must fail closed");
assert!(matches!(error, TwoFactorLoginError::ConsumptionUnavailable));
assert!(!format!("{error:?} {error}").contains("private"));
}
}
assert_eq!(auth.logged_in.is_some(), expected == Some(true));
assert_eq!(auth.renewals, usize::from(expected == Some(true)));
assert_eq!(
auth.pending_two_factor_challenge().is_some(),
expected != Some(true)
);
}
}
#[tokio::test]
async fn invalid_challenges_do_not_spend_account_budget_and_new_challenges_do_not_reset_it() {
let security = SecurityState::with_auth_policy(
100.try_into().unwrap(),
crate::ratelimit::AuthRateLimitPolicy {
two_factor_account_per_minute: 1.try_into().unwrap(),
..Default::default()
},
);
let loads = Cell::new(0);
for invalid_kind in 0..3 {
let mut auth = TestAuthSession::default();
let challenge = TwoFactorChallenge::new("account-1".to_owned());
if invalid_kind != 0 {
let challenge = if invalid_kind == 1 {
let mut value = serde_json::to_value(&challenge).unwrap();
value["issued_at"] = serde_json::to_value(
time::OffsetDateTime::now_utc() - time::Duration::hours(1),
)
.unwrap();
serde_json::from_value(value).unwrap()
} else {
challenge.clone()
};
auth.set_pending_two_factor_challenge(&challenge);
}
let token = if invalid_kind == 2 {
uuid::Uuid::new_v4().to_string()
} else {
challenge.token().to_owned()
};
let result = complete_totp_fixture(
&mut auth,
TwoFactorLoginForm::new(token, "000000".to_owned()),
&security,
Ok(true),
&loads,
)
.await
.unwrap();
assert!(!result.success);
assert_ne!(result.error_code, LoginErrorCode::RateLimited);
}
assert_eq!(loads.get(), 0);
for (attempt, expected) in [
LoginErrorCode::TwoFactorInvalid,
LoginErrorCode::RateLimited,
]
.into_iter()
.enumerate()
{
let mut auth = TestAuthSession::default();
let challenge = TwoFactorChallenge::new("account-1".to_owned());
auth.set_pending_two_factor_challenge(&challenge);
assert!(
security
.check_two_factor(&format!("192.0.2.{}", attempt + 1))
.is_ok()
);
let result = complete_totp_fixture(
&mut auth,
TwoFactorLoginForm::new(challenge.token().to_owned(), "ABCDEFGH".to_owned()),
&security,
Ok(true),
&loads,
)
.await
.unwrap();
assert_eq!(result.error_code, expected);
assert!(auth.logged_in.is_none());
}
assert_eq!(
loads.get(),
1,
"exhausted account must reject before backend work"
);
}
#[test]
fn macro_impls_expose_login_fields() {
let account = MacroAccount {
id: "account-1".to_string(),
status: MacroStatus::Active,
account_hash: "hash".to_string(),
};
let blocked_account = MacroAccount {
id: "account-2".to_string(),
status: MacroStatus::Blocked,
account_hash: "hash-2".to_string(),
};
let credentials = MacroCredentials {
account: account.clone(),
password_hash: "hashed".to_string(),
twofa_enabled: true,
};
assert_eq!(LoginAccount::id(&account), "account-1");
assert!(matches!(
LoginAccount::auth_decision(&account),
AuthDecision::Allow
));
assert!(matches!(
LoginAccount::auth_decision(&blocked_account),
AuthDecision::Deny(reason) if reason == AuthDenyReason::blocked()
));
assert_eq!(AccountHash::account_hash(&account), "hash");
assert_eq!(LoginCredentials::password_hash(&credentials), "hashed");
assert!(LoginCredentials::two_factor_enabled(&credentials));
assert_eq!(
LoginAccount::id(LoginCredentials::account(&credentials)),
"account-1"
);
}
}