use std::future::Future;
use std::sync::atomic::{AtomicU16, Ordering};
use anyhow::{Error as AuthError, anyhow};
use http::StatusCode;
use serde::{Serialize, de::DeserializeOwned};
use time::OffsetDateTime;
use crate::auth::login::feedback::{LoginErrorCode, LoginFeedbackMessages};
use crate::auth::login::forms::LoginOutcome;
use crate::auth::two_factor::api::verify_totp_code;
use crate::auth::two_factor::{
TwoFactorChallenge, TwoFactorCode, TwoFactorLoginForm, TwoFactorLoginPayload,
};
use crate::messages::AuthMessage;
use crate::status::{AuthDecision, AuthDenyReason, auth_deny_message};
const TWO_FACTOR_SESSION_KEY: &str = "two_factor_challenge";
pub trait LoginResponseOptions {
fn set_status(&self, status: StatusCode);
}
#[derive(Debug)]
pub struct LoginResponseStatus {
status: AtomicU16,
}
impl Default for LoginResponseStatus {
fn default() -> Self {
Self {
status: AtomicU16::new(StatusCode::OK.as_u16()),
}
}
}
impl LoginResponseStatus {
pub fn status(&self) -> StatusCode {
StatusCode::from_u16(self.status.load(Ordering::Relaxed))
.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)
}
}
impl LoginResponseOptions for LoginResponseStatus {
fn set_status(&self, status: StatusCode) {
self.status.store(status.as_u16(), Ordering::Relaxed);
}
}
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, Response> {
auth: &'a mut Auth,
response_options: &'a Response,
messages: LoginFeedbackMessages,
server_error_message: AuthMessage,
captcha_valid: bool,
}
impl<'a, Auth, Response> LoginContext<'a, Auth, Response>
where
Auth: LoginSession<Id = String>,
Response: LoginResponseOptions,
{
pub fn new(
auth: &'a mut Auth,
response_options: &'a Response,
server_error_message: AuthMessage,
captcha_valid: bool,
) -> Self {
let messages = LoginFeedbackMessages::default_messages();
Self {
auth,
response_options,
messages,
server_error_message,
captcha_valid,
}
}
pub fn with_messages(
auth: &'a mut Auth,
response_options: &'a Response,
messages: LoginFeedbackMessages,
server_error_message: AuthMessage,
captcha_valid: bool,
) -> Self {
Self {
auth,
response_options,
messages,
server_error_message,
captcha_valid,
}
}
fn set_status_ok(&self) {
self.response_options.set_status(StatusCode::OK);
}
fn success_outcome(&self) -> LoginOutcome {
let message = self.messages.success.clone();
LoginOutcome::success(Some(message), self.captcha_valid)
}
fn success_with_two_factor_outcome(&self, token: Option<String>) -> LoginOutcome {
let message = self.messages.two_factor_required.clone();
LoginOutcome::success_with_two_factor(Some(message), self.captcha_valid, token)
}
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 {
let message = match code {
LoginErrorCode::RateLimited => Some(self.messages.rate_limited.clone()),
LoginErrorCode::CredentialsInvalid => Some(self.messages.credentials_invalid.clone()),
LoginErrorCode::AccountDenied => Some(self.messages.account_denied.clone()),
LoginErrorCode::TwoFactorRequired => Some(self.messages.two_factor_required.clone()),
LoginErrorCode::TwoFactorInvalid => Some(self.messages.two_factor_invalid.clone()),
LoginErrorCode::TwoFactorExpired => Some(self.messages.two_factor_expired.clone()),
LoginErrorCode::TwoFactorMissing => Some(self.messages.two_factor_missing.clone()),
LoginErrorCode::TwoFactorUnavailable => {
Some(self.messages.two_factor_unavailable.clone())
}
LoginErrorCode::TwoFactorDisabled => Some(self.messages.two_factor_disabled.clone()),
LoginErrorCode::None => None,
};
LoginOutcome::failure_with_two_factor(code, message, self.captcha_valid, token)
}
}
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,
Some(LoginFeedbackMessages::default_messages().rate_limited),
captcha_valid,
)
}
pub async fn finalize_login<
'a,
Auth,
Response,
Account,
BuildUser,
OnTwoFactor,
OnTwoFactorFut,
OnSuccess,
OnSuccessFut,
>(
ctx: &'a mut LoginContext<'a, Auth, Response>,
account: Account,
two_factor_enabled: bool,
build_user: BuildUser,
on_two_factor: OnTwoFactor,
on_success: OnSuccess,
) -> Result<LoginOutcome, AuthError>
where
Auth: LoginSession<Id = String>,
Response: LoginResponseOptions,
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);
ctx.set_status_ok();
let outcome = ctx.success_with_two_factor_outcome(Some(token));
on_two_factor(ctx.auth, account).await;
return Ok(outcome);
}
let account_id = account.id().to_string();
ctx.auth
.establish_authenticated_session(account_id, build_user(&account), true);
ctx.set_status_ok();
let outcome = ctx.success_outcome();
on_success(ctx.auth, account).await;
Ok(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,
Response,
Credentials,
FetchCredentials,
FetchFuture,
FetchError,
VerifyPassword,
BuildUser,
OnTwoFactor,
OnTwoFactorFut,
OnSuccess,
OnSuccessFut,
OnFailure,
OnFailureFut,
>(
ctx: &'a mut LoginContext<'a, Auth, Response>,
lookup: &'b str,
password: &'b str,
callbacks: LoginWithCredentialsCallbacks<
FetchCredentials,
VerifyPassword,
BuildUser,
OnTwoFactor,
OnSuccess,
OnFailure,
>,
) -> Result<LoginOutcome, AuthError>
where
Auth: LoginSession<Id = String>,
Response: LoginResponseOptions,
Credentials: LoginCredentials,
Credentials::Account: LoginAccount + Clone,
FetchCredentials: FnOnce(&'b str) -> FetchFuture,
FetchFuture: Future<Output = Result<Option<Credentials>, FetchError>>,
VerifyPassword: Fn(&str, &str) -> bool,
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| anyhow!(ctx.server_error_message.key().as_str().to_string()))?;
let password_matches = match credentials.as_ref() {
Some(credentials) => verify_password(password, credentials.password_hash()),
None => verify_password(password, dummy_password_hash.as_str()),
};
if password_matches && let Some(credentials) = credentials {
let account = credentials.account();
let outcome = match account.auth_decision() {
AuthDecision::Allow => {
let account = account.clone();
finalize_login(
ctx,
account,
credentials.two_factor_enabled(),
build_user,
on_two_factor,
on_success,
)
.await
}
AuthDecision::Deny(reason) => {
ctx.set_status_ok();
let outcome = ctx.account_denied_outcome(reason);
on_failure(ctx.auth).await;
Ok(outcome)
}
};
return outcome;
}
ctx.set_status_ok();
let outcome = ctx.outcome_for_error(LoginErrorCode::CredentialsInvalid, None);
on_failure(ctx.auth).await;
Ok(outcome)
}
pub struct TwoFactorLoginCallbacks<
LoadAccount,
LoadTwoFactorState,
ConsumeBackup,
BuildUser,
OnSuccess,
OnCleanup,
> {
pub load_account: LoadAccount,
pub load_two_factor_state: LoadTwoFactorState,
pub consume_backup_code: ConsumeBackup,
pub build_user: BuildUser,
pub on_success: OnSuccess,
pub on_cleanup: OnCleanup,
}
pub async fn complete_two_factor_login<
'a,
Auth,
Response,
Account,
LoadAccount,
LoadAccountFuture,
LoadAccountError,
LoadTwoFactorState,
LoadTwoFactorFuture,
LoadTwoFactorError,
ConsumeBackup,
ConsumeBackupFuture,
ConsumeBackupError,
BuildUser,
OnSuccess,
OnSuccessFut,
OnCleanup,
OnCleanupFut,
>(
ctx: &'a mut LoginContext<'a, Auth, Response>,
form: TwoFactorLoginForm,
callbacks: TwoFactorLoginCallbacks<
LoadAccount,
LoadTwoFactorState,
ConsumeBackup,
BuildUser,
OnSuccess,
OnCleanup,
>,
) -> Result<LoginOutcome, AuthError>
where
Auth: LoginSession<Id = String>,
Response: LoginResponseOptions,
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>>,
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,
build_user,
on_success,
on_cleanup,
} = callbacks;
let parsed = match TwoFactorLoginPayload::parse(form) {
Ok(payload) => payload,
Err(error) => return Err(anyhow!(error.to_string())),
};
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 {
ctx.set_status_ok();
return Ok(ctx.outcome_for_error(LoginErrorCode::TwoFactorMissing, None));
};
if challenge.is_expired(now) {
ctx.auth.clear_pending_two_factor_challenge();
ctx.set_status_ok();
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();
ctx.set_status_ok();
let outcome = ctx.outcome_for_error(LoginErrorCode::TwoFactorMissing, None);
on_cleanup(ctx.auth).await;
return Ok(outcome);
}
let account = match load_account(challenge.account_id()).await {
Ok(account) => account,
Err(_error) => {
ctx.auth.clear_pending_two_factor_challenge();
ctx.set_status_ok();
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();
ctx.set_status_ok();
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| anyhow!(ctx.server_error_message.key().as_str().to_string()))?;
if !two_factor_enabled {
ctx.auth.clear_pending_two_factor_challenge();
ctx.set_status_ok();
let outcome = ctx.outcome_for_error(LoginErrorCode::TwoFactorDisabled, None);
on_cleanup(ctx.auth).await;
return Ok(outcome);
}
match code {
TwoFactorCode::Totp(code) => {
let Some(secret) = two_factor_secret.as_deref() else {
ctx.auth.clear_pending_two_factor_challenge();
ctx.set_status_ok();
let outcome = ctx.outcome_for_error(LoginErrorCode::TwoFactorUnavailable, None);
on_cleanup(ctx.auth).await;
return Ok(outcome);
};
let totp_value = code.as_str().parse::<u32>().unwrap_or(0);
let verified = verify_totp_code(secret, totp_value)
.map_err(|_error| anyhow!(ctx.server_error_message.key().as_str().to_string()))?;
if !verified {
ctx.set_status_ok();
let outcome = ctx.outcome_for_error(
LoginErrorCode::TwoFactorInvalid,
Some(challenge.token().to_string()),
);
return Ok(outcome);
}
}
TwoFactorCode::Backup(code) => {
let consumed = consume_backup_code(&account, code.as_str())
.await
.map_err(|_error| anyhow!(ctx.server_error_message.key().as_str().to_string()))?;
if !consumed {
ctx.set_status_ok();
let outcome = ctx.outcome_for_error(
LoginErrorCode::TwoFactorInvalid,
Some(challenge.token().to_string()),
);
return Ok(outcome);
}
}
}
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();
ctx.set_status_ok();
let outcome = ctx.success_outcome();
on_success(ctx.auth, account).await;
Ok(outcome)
}
pub async fn register_account_with_database<
Auth,
Response,
Account,
InsertAccount,
InsertFuture,
InsertError,
BuildUser,
>(
auth: &mut Auth,
response_options: &Response,
form: crate::auth::login::forms::RegisterFormData,
insert_account: InsertAccount,
build_user: BuildUser,
) -> Result<crate::auth::login::forms::RegisterOutcome, AuthError>
where
Auth: LoginSession<Id = String>,
Response: LoginResponseOptions,
Account: LoginAccount + AccountHash,
InsertAccount: FnOnce(Option<String>, Option<String>, &str) -> InsertFuture,
InsertFuture: Future<Output = Result<Account, InsertError>>,
BuildUser: Fn(&Account) -> Auth::User,
{
let parsed = match form.parse() {
Ok(parsed) => parsed,
Err(error) => return Err(anyhow!(error.to_string())),
};
register_account_with_values(
auth,
response_options,
parsed.email,
parsed.full_name,
parsed.password,
insert_account,
build_user,
)
.await
}
pub async fn register_account_with_values<
Auth,
Response,
Account,
InsertAccount,
InsertFuture,
InsertError,
BuildUser,
>(
auth: &mut Auth,
response_options: &Response,
email: Option<String>,
full_name: Option<String>,
password: String,
insert_account: InsertAccount,
build_user: BuildUser,
) -> Result<crate::auth::login::forms::RegisterOutcome, AuthError>
where
Auth: LoginSession<Id = String>,
Response: LoginResponseOptions,
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) => {
response_options.set_status(StatusCode::OK);
return Ok(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);
Ok(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::{
AccountHash, DummyPasswordHash, LoginAccount, LoginContext, LoginCredentials, LoginOutcome,
LoginResponseOptions, LoginSession, LoginWithCredentialsCallbacks, TwoFactorLoginCallbacks,
complete_two_factor_login, login_with_credentials,
};
use crate::auth::login::feedback::{LoginErrorCode, LoginFeedbackMessages};
use crate::auth::two_factor::{TwoFactorChallenge, TwoFactorLoginForm};
use crate::messages::AuthMessage;
use crate::status::{AuthDecision, AuthDenyReason};
use anyhow::Error as AuthError;
use argon2::Argon2;
use argon2::password_hash::{PasswordHash, PasswordVerifier};
use http::StatusCode;
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);
}
}
#[derive(Default)]
struct TestResponseOptions {
status: Cell<Option<StatusCode>>,
}
impl LoginResponseOptions for TestResponseOptions {
fn set_status(&self, status: StatusCode) {
self.status.set(Some(status));
}
}
async fn login_with_test_credentials<'a>(
ctx: &'a mut LoginContext<'a, TestAuthSession, TestResponseOptions>,
credentials: TestCredentials,
) -> Result<LoginOutcome, AuthError> {
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: |_password: &str, _hash: &str| 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 response = TestResponseOptions::default();
let mut ctx = LoginContext::with_messages(
&mut auth,
&response,
LoginFeedbackMessages::test_messages(),
AuthMessage::from_static("auth.server_error"),
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);
assert_eq!(response.status.get(), Some(StatusCode::OK));
}
#[tokio::test]
async fn unknown_account_runs_the_injected_password_verifier() {
let mut auth = TestAuthSession::default();
let response = TestResponseOptions::default();
let mut ctx = LoginContext::with_messages(
&mut auth,
&response,
LoginFeedbackMessages::test_messages(),
AuthMessage::from_static("auth.server_error"),
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: |password: &str, hash: &str| {
verifier_called.set(true);
assert_eq!(password, "submitted-password");
assert_eq!(hash, expected_dummy_hash);
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 response = TestResponseOptions::default();
let mut ctx = LoginContext::with_messages(
&mut auth,
&response,
LoginFeedbackMessages::test_messages(),
AuthMessage::from_static("auth.server_error"),
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 response = TestResponseOptions::default();
let challenge = TwoFactorChallenge::new("account-1".to_string());
auth.set_pending_two_factor_challenge(&challenge);
let mut ctx = LoginContext::with_messages(
&mut auth,
&response,
LoginFeedbackMessages::test_messages(),
AuthMessage::from_static("auth.server_error"),
true,
);
let form = TwoFactorLoginForm::new(challenge.token().to_string(), "ABCDEFGH".to_string());
let outcome = complete_two_factor_login(
&mut ctx,
form,
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))
},
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 response = TestResponseOptions::default();
let challenge = TwoFactorChallenge::new("account-1".to_string());
auth.set_pending_two_factor_challenge(&challenge);
let mut ctx = LoginContext::with_messages(
&mut auth,
&response,
LoginFeedbackMessages::test_messages(),
AuthMessage::from_static("auth.server_error"),
true,
);
let form = TwoFactorLoginForm::new(challenge.token().to_string(), "ABCDEFGH".to_string());
let outcome = complete_two_factor_login(
&mut ctx,
form,
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))
},
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());
}
#[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"
);
}
}