use crate::dao::GarrisonDao;
use crate::error::{GarrisonError, GarrisonResult};
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use super::code;
use super::limiter::InvitationAttemptLimiter;
use super::{
InvitationHandler, InvitationInvalidReason, InvitationRecord, InvitationSpec, InvitationStatus,
InvitationStatusReport,
};
pub(crate) const KEY_PREFIX: &str = "garrison:invitation:code:";
const MAX_COLLISION_RETRIES: usize = 3;
impl InvitationHandler {
pub fn new(dao: Arc<dyn GarrisonDao>) -> Self {
Self {
limiter: InvitationAttemptLimiter::new(dao.clone()),
dao,
#[cfg(feature = "listener")]
listener_manager: None,
hook: None,
}
}
#[cfg(feature = "listener")]
pub fn with_listener_manager(
mut self,
lm: Arc<crate::listener::GarrisonListenerManager>,
) -> Self {
self.listener_manager = Some(lm);
self
}
pub fn with_hook(mut self, hook: Arc<dyn super::InvitationRedeemHook>) -> Self {
self.hook = Some(hook);
self
}
pub async fn create(&self, spec: InvitationSpec) -> GarrisonResult<InvitationRecord> {
validate_spec(&spec)?;
let record = self.persist_new_record(spec).await?;
#[cfg(feature = "listener")]
if let Some(lm) = &self.listener_manager {
lm.broadcast(&crate::listener::GarrisonEvent::InvitationCreated {
code: record.code.clone(),
issuer_id: record.issuer_id.clone(),
})
.await;
}
Ok(record)
}
pub async fn create_batch(
&self,
spec: InvitationSpec,
count: usize,
) -> GarrisonResult<Vec<InvitationRecord>> {
if count == 0 {
return Err(GarrisonError::InvalidParam(
"invitation-count-invalid::".to_string(),
));
}
validate_spec(&spec)?;
let mut records = Vec::with_capacity(count);
for _ in 0..count {
records.push(self.persist_new_record(spec.clone()).await?);
}
#[cfg(feature = "listener")]
if let Some(lm) = &self.listener_manager {
for record in &records {
lm.broadcast(&crate::listener::GarrisonEvent::InvitationCreated {
code: record.code.clone(),
issuer_id: record.issuer_id.clone(),
})
.await;
}
}
Ok(records)
}
pub async fn revoke(&self, code_input: &str, _issuer_id: &str) -> GarrisonResult<()> {
let normalized = code::normalize(code_input)?;
let key = format!("{}{}", KEY_PREFIX, normalized);
let raw = match self.dao.get_and_delete(&key).await? {
Some(raw) => raw,
None => return Ok(()),
};
let mut record: InvitationRecord = match serde_json::from_str(&raw) {
Ok(r) => r,
Err(_) => return Ok(()),
};
let already_revoked = record.status == InvitationStatus::Revoked;
if !already_revoked {
record.status = InvitationStatus::Revoked;
}
self.restore(&key, &record).await?;
#[cfg(feature = "listener")]
if !already_revoked {
if let Some(lm) = &self.listener_manager {
lm.broadcast(&crate::listener::GarrisonEvent::InvitationRevoked {
code: record.code.clone(),
issuer_id: record.issuer_id.clone(),
})
.await;
}
}
Ok(())
}
pub async fn list(&self, issuer_id: &str) -> GarrisonResult<Vec<InvitationRecord>> {
let pattern = format!("{}*", KEY_PREFIX);
let keys = self.dao.keys(&pattern).await?;
let mut records = Vec::new();
for key in keys {
let Some(raw) = self.dao.get(&key).await? else {
continue;
};
if let Ok(record) = serde_json::from_str::<InvitationRecord>(&raw) {
if record.issuer_id == issuer_id {
records.push(record);
}
}
}
Ok(records)
}
pub async fn validate(&self, code_input: &str) -> GarrisonResult<InvitationStatusReport> {
let normalized = code::normalize(code_input)?;
let key = format!("{}{}", KEY_PREFIX, normalized);
let raw = match self.dao.get(&key).await? {
Some(raw) => raw,
None => {
return Ok(InvitationStatusReport {
record: None,
reason: Some(InvitationInvalidReason::NotFound),
})
},
};
let record: InvitationRecord = match serde_json::from_str(&raw) {
Ok(r) => r,
Err(_) => {
return Ok(InvitationStatusReport {
record: None,
reason: Some(InvitationInvalidReason::NotFound),
});
},
};
let reason = classify(&record, unix_now());
Ok(InvitationStatusReport {
record: Some(record),
reason,
})
}
pub async fn redeem(
&self,
code_input: &str,
redeemer_id: &str,
source: &str,
) -> GarrisonResult<InvitationRecord> {
self.limiter.check(source).await?;
let normalized = code::normalize(code_input)?;
let key = format!("{}{}", KEY_PREFIX, normalized);
let raw = match self.dao.get_and_delete(&key).await? {
Some(raw) => raw,
None => {
return Err(GarrisonError::InvalidParam(
"invitation-code-not-found::".to_string(),
))
},
};
let mut record: InvitationRecord = match serde_json::from_str(&raw) {
Ok(r) => r,
Err(_) => {
return Err(GarrisonError::InvalidParam(
"invitation-code-not-found::".to_string(),
));
},
};
let now = unix_now();
if record.status == InvitationStatus::Revoked {
if now < record.expires_at {
self.restore(&key, &record).await?;
}
return Err(GarrisonError::InvalidParam(format!(
"invitation-code-revoked::{}",
record.code
)));
}
if now >= record.expires_at {
return Err(GarrisonError::InvalidParam(
"invitation-code-expired::".to_string(),
));
}
if record.used_count >= record.max_uses {
self.restore(&key, &record).await?;
return Err(GarrisonError::InvalidParam(format!(
"invitation-code-exhausted::{}",
record.code
)));
}
let original = record.clone();
record.used_count += 1;
record.redeemed_by.push(redeemer_id.to_string());
if let Some(hook) = &self.hook {
if let Err(e) = hook.on_redeem(&record).await {
self.restore(&key, &original).await?;
return Err(e);
}
}
if record.max_uses > 1 || record.used_count < record.max_uses {
self.restore(&key, &record).await?;
}
self.limiter.reset(source).await?;
#[cfg(feature = "listener")]
if let Some(lm) = &self.listener_manager {
lm.broadcast(&crate::listener::GarrisonEvent::InvitationRedeemed {
code: record.code.clone(),
redeemer_id: redeemer_id.to_string(),
})
.await;
}
Ok(record)
}
pub(crate) async fn restore(&self, key: &str, record: &InvitationRecord) -> GarrisonResult<()> {
let remaining = (record.expires_at - unix_now()).max(1) as u64;
self.dao
.set(
key,
&serde_json::to_string(record)
.map_err(|e| GarrisonError::Dao(format!("invitation-serialize-failed::{e}")))?,
remaining,
)
.await
}
async fn persist_new_record(&self, spec: InvitationSpec) -> GarrisonResult<InvitationRecord> {
let now = unix_now();
let expires_at = now + spec.ttl_seconds;
for _ in 0..MAX_COLLISION_RETRIES {
let normalized = code::normalize(&code::generate())?;
let record = InvitationRecord {
code: normalized.clone(),
issuer_id: spec.issuer_id.clone(),
tenant_id: spec.tenant_id.clone(),
bound_roles: spec.bound_roles.clone(),
max_uses: spec.max_uses,
used_count: 0,
redeemed_by: Vec::new(),
created_at: now,
expires_at,
status: InvitationStatus::Active,
};
let key = format!("{}{}", KEY_PREFIX, normalized);
if self
.dao
.set_if_absent(
&key,
&serde_json::to_string(&record).map_err(|e| {
GarrisonError::Dao(format!("invitation-serialize-failed::{e}"))
})?,
(expires_at - now) as u64,
)
.await?
{
return Ok(record);
}
}
Err(GarrisonError::InvalidParam(
"invitation-code-collision::".to_string(),
))
}
}
pub(crate) fn validate_spec(spec: &InvitationSpec) -> GarrisonResult<()> {
if spec.ttl_seconds <= 0 {
return Err(GarrisonError::InvalidParam(
"invitation-ttl-invalid::".to_string(),
));
}
if spec.max_uses == 0 {
return Err(GarrisonError::InvalidParam(
"invitation-max-uses-invalid::".to_string(),
));
}
Ok(())
}
pub(crate) fn classify(record: &InvitationRecord, now: i64) -> Option<InvitationInvalidReason> {
if record.status == InvitationStatus::Revoked {
return Some(InvitationInvalidReason::Revoked);
}
if now >= record.expires_at {
return Some(InvitationInvalidReason::Expired);
}
if record.used_count >= record.max_uses {
return Some(InvitationInvalidReason::Exhausted);
}
None
}
pub(crate) fn unix_now() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}