use super::action_token::{unix_now, ActionTokenService};
use super::consumer::ActionTokenConsumer;
use super::restricted::RestrictedSessionGuard;
use crate::account::credential::password::PasswordHasher;
use crate::account::credential::CredentialRepository;
use crate::account::policy::PasswordPolicyEngine;
use crate::account::policy::PolicyContext;
use crate::constants::DaoKeyPrefix;
use crate::dao::repository::PasswordHistoryRepository;
use crate::dao::GarrisonDao;
use crate::error::{GarrisonError, GarrisonResult};
use crate::session::GarrisonSession;
use std::sync::Arc;
pub const DEFAULT_RATE_WINDOW_SECS: u64 = 3600;
pub const DEFAULT_RATE_LIMIT_MAX: u64 = 5;
pub const HISTORY_CHECK_COUNT: u32 = 24;
pub const DUMMY_RESET_SUBJECT: &str = "__garrison_pwdreset_dummy__";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResetRequestOutcome {
pub message_key: &'static str,
pub rate_count: u64,
}
#[async_trait::async_trait]
pub trait ResetIdentityResolver: Send + Sync {
async fn resolve_subject(
&self,
tenant_id: i64,
identifier: &str,
) -> GarrisonResult<Option<String>>;
}
#[async_trait::async_trait]
pub trait ResetMailSender: Send + Sync {
async fn deliver(&self, to: &str, subject: &str, body: &str) -> GarrisonResult<()>;
}
pub struct EmailResetMailSender {
inner: Arc<dyn crate::secure::email::EmailSender>,
}
impl EmailResetMailSender {
pub fn new(inner: Arc<dyn crate::secure::email::EmailSender>) -> Self {
Self { inner }
}
}
#[async_trait::async_trait]
impl ResetMailSender for EmailResetMailSender {
async fn deliver(&self, to: &str, subject: &str, body: &str) -> GarrisonResult<()> {
self.inner.send(to, subject, body).await
}
}
pub struct PasswordResetService {
dao: Arc<dyn GarrisonDao>,
session: Arc<GarrisonSession>,
tokens: ActionTokenService,
consumer: ActionTokenConsumer,
credentials: Arc<dyn CredentialRepository>,
hasher: Arc<dyn PasswordHasher>,
policy: PasswordPolicyEngine,
history: Arc<dyn PasswordHistoryRepository>,
resolver: Arc<dyn ResetIdentityResolver>,
sender: Arc<dyn ResetMailSender>,
rate_window_secs: u64,
rate_limit_max: u64,
}
impl std::fmt::Debug for PasswordResetService {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PasswordResetService")
.field("rate_window_secs", &self.rate_window_secs)
.field("rate_limit_max", &self.rate_limit_max)
.finish_non_exhaustive()
}
}
impl PasswordResetService {
#[allow(clippy::too_many_arguments)]
pub fn new(
dao: Arc<dyn GarrisonDao>,
session: Arc<GarrisonSession>,
tokens: ActionTokenService,
credentials: Arc<dyn CredentialRepository>,
hasher: Arc<dyn PasswordHasher>,
policy: PasswordPolicyEngine,
history: Arc<dyn PasswordHistoryRepository>,
resolver: Arc<dyn ResetIdentityResolver>,
sender: Arc<dyn ResetMailSender>,
) -> Self {
let consumer = ActionTokenConsumer::new(dao.clone());
Self {
dao,
session,
tokens,
consumer,
credentials,
hasher,
policy,
history,
resolver,
sender,
rate_window_secs: DEFAULT_RATE_WINDOW_SECS,
rate_limit_max: DEFAULT_RATE_LIMIT_MAX,
}
}
pub fn with_rate_limit(mut self, window_secs: u64, max: u64) -> Self {
self.rate_window_secs = window_secs;
self.rate_limit_max = max;
self
}
pub async fn request_reset(
&self,
tenant_id: i64,
identifier: &str,
) -> GarrisonResult<ResetRequestOutcome> {
let identifier = normalize_identifier(identifier);
validate_identifier(&identifier)?;
let count = self
.dao
.incr(&rate_key(&identifier), self.rate_window_secs)
.await?;
if count > self.rate_limit_max {
return Err(GarrisonError::RateLimited {
retry_after_secs: self.rate_window_secs,
});
}
match self
.resolver
.resolve_subject(tenant_id, &identifier)
.await?
{
Some(subject) => {
let issued = self.tokens.issue(&subject)?;
let ttl = (issued.claims.exp - unix_now()?).clamp(1, i64::MAX) as u64;
self.dao
.set(&binding_key(&issued.claims.jti), &subject, ttl)
.await?;
self.dao
.set(
&binding_tenant_key(&issued.claims.jti),
&tenant_id.to_string(),
ttl,
)
.await?;
let (subject_line, body_line) = render_mail(&issued.token);
let sender = self.sender.clone();
let to = identifier.clone();
tokio::spawn(async move {
if let Err(e) = sender.deliver(&to, &subject_line, &body_line).await {
tracing::error!(
to = %mask_email_for_log(&to),
error = %e,
"{}",
crate::i18n::translate_detail("logs-pwdreset-mail-delivery-failed", &[])
);
}
});
},
None => {
let _dummy = self.tokens.issue(DUMMY_RESET_SUBJECT)?;
},
}
Ok(ResetRequestOutcome {
message_key: "pwdreset-request-accepted",
rate_count: count,
})
}
pub async fn reset(
&self,
tenant_id: i64,
session_token: &str,
action_token: &str,
new_password: &str,
) -> GarrisonResult<()> {
let claims = self.tokens.verify(action_token)?;
let bound = self.dao.get(&binding_key(&claims.jti)).await?;
match bound {
Some(bound) if bound == claims.sub => {},
Some(bound) => {
return Err(GarrisonError::NotPermission(format!(
"pwdreset-subject-binding-mismatch::token-sub={}::binding={bound}",
claims.sub
)));
},
None => {
return Err(GarrisonError::InvalidToken(
"pwdreset-binding-missing::".to_string(),
));
},
}
let bound_tenant = self.dao.get(&binding_tenant_key(&claims.jti)).await?;
match bound_tenant {
Some(t) if t == tenant_id.to_string() => {},
Some(_) => {
return Err(GarrisonError::NotPermission(
"pwdreset-tenant-mismatch::".to_string(),
));
},
None => {
return Err(GarrisonError::InvalidToken(
"pwdreset-tenant-binding-missing::".to_string(),
));
},
}
let session_subject = self
.session
.get_token_session(session_token)
.await?
.ok_or_else(|| GarrisonError::InvalidToken("pwdreset-session-not-found::".to_string()))?
.login_id;
if session_subject != claims.sub {
return Err(GarrisonError::NotPermission(format!(
"pwdreset-session-subject-mismatch::session={}::token={}",
session_subject, claims.sub
)));
}
RestrictedSessionGuard::grant(self.session.clone(), session_token).await?;
let existing = self
.credentials
.find_by_user_and_type(&claims.sub, "password")
.await?;
let current = existing.into_iter().find(|c| c.enabled).ok_or_else(|| {
GarrisonError::InvalidParam("pwdreset-password-credential-missing::".to_string())
})?;
if self.hasher.verify(new_password, ¤t.secret_data)? {
return Err(GarrisonError::InvalidParam(
"pwdreset-policy-violated-current-password::".to_string(),
));
}
let history = self
.history
.recent(tenant_id, &claims.sub, HISTORY_CHECK_COUNT)
.await?;
let ctx = PolicyContext {
user_id: claims.sub.clone(),
tenant_id: Some(tenant_id.to_string()),
username: None,
email: None,
password_history: history,
password_created_at: None,
};
if let Err(errors) = self.policy.validate(&ctx, new_password) {
let first = errors.first();
let detail = match first {
Some(e) => format!("{}::{}", e.rule_name, e.message),
None => "unknown".to_string(),
};
return Err(GarrisonError::InvalidParam(format!(
"pwdreset-policy-violated::{detail}"
)));
}
let remaining = (claims.exp - unix_now()?).clamp(1, i64::MAX) as u64;
if !self.consumer.consume(&claims.jti, remaining).await? {
return Err(GarrisonError::InvalidToken(
"pwdreset-token-consume-failed::".to_string(),
));
}
let original = current.clone();
let original_secret_hash = current.secret_data.clone();
let new_hash = self.hasher.hash(new_password)?;
let mut updated = current;
updated.secret_data = new_hash.clone();
self.credentials.update(&claims.sub, updated).await?;
if let Err(e) = self
.history
.append(tenant_id, &claims.sub, &original_secret_hash)
.await
{
tracing::error!(
error = %e,
"{}",
crate::i18n::translate_detail(
"logs-pwdreset-history-append-replaced-generation-failed",
&[]
)
);
}
if let Err(e) = self.history.append(tenant_id, &claims.sub, &new_hash).await {
if let Err(re) = self.credentials.update(&claims.sub, original).await {
tracing::error!(
error = %re,
"{}",
crate::i18n::translate_detail(
"logs-pwdreset-history-append-and-rollback-failed",
&[]
)
);
}
return Err(e);
}
Ok(())
}
}
fn validate_identifier(identifier: &str) -> GarrisonResult<()> {
if identifier.is_empty()
|| identifier.len() > 254
|| identifier.contains(':')
|| identifier.chars().any(|c| c.is_control())
{
return Err(GarrisonError::InvalidParam(format!(
"pwdreset-identifier-invalid::len={}",
identifier.len()
)));
}
Ok(())
}
fn mask_email_for_log(email: &str) -> String {
match email.find('@') {
Some(at_pos) if at_pos > 0 => {
let first = email[..at_pos].chars().next().unwrap_or('*');
format!("{first}***{}", &email[at_pos..])
},
_ => "*".repeat(email.chars().count()),
}
}
fn normalize_identifier(identifier: &str) -> String {
identifier.trim().to_lowercase()
}
pub(crate) fn rate_key(identifier: &str) -> String {
format!("{}rate:{}", DaoKeyPrefix::PasswordReset, identifier)
}
pub(crate) fn binding_key(jti: &str) -> String {
format!("{}bind:{}", DaoKeyPrefix::PasswordReset, jti)
}
pub(crate) fn binding_tenant_key(jti: &str) -> String {
format!("{}bindt:{}", DaoKeyPrefix::PasswordReset, jti)
}
fn render_mail(token: &str) -> (String, String) {
let subject = crate::i18n::translate_detail("pwdreset-mail-subject", &[]);
let minutes = (super::action_token::DEFAULT_TOKEN_TTL_SECS / 60).to_string();
let body = crate::i18n::translate_detail(
"pwdreset-mail-body",
&[("token", token), ("minutes", minutes.as_str())],
);
(subject, body)
}