use crate::time::{Duration, Instant};
use std::collections::HashMap;
use std::sync::Mutex;
use uuid::Uuid;
use crate::rest::authz::AccessDecision;
use crate::telemetry::{Telemetry, TelemetryEvent};
pub const MAX_TTL: Duration = Duration::from_secs(5);
const MAX_ENTRIES: usize = 1024;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) struct MemoKey {
subject_id: Option<Uuid>,
resource_id: Uuid,
action: String,
scope: Option<String>,
acting_tenant: Option<Uuid>,
}
impl MemoKey {
pub(crate) fn new(
subject_id: Option<Uuid>,
resource_id: Uuid,
action: &str,
scope: Option<&str>,
) -> Self {
Self {
subject_id,
resource_id,
action: action.to_string(),
scope: scope.map(str::to_string),
acting_tenant: None,
}
}
#[must_use]
pub(crate) fn in_acting_tenant(mut self, acting_tenant: Option<Uuid>) -> Self {
self.acting_tenant = acting_tenant;
self
}
}
struct Entry {
decision: AccessDecision,
stored_at: Instant,
}
pub(crate) struct DecisionMemo {
ttl: Duration,
entries: Mutex<HashMap<MemoKey, Entry>>,
order: Mutex<std::collections::VecDeque<MemoKey>>,
}
impl DecisionMemo {
pub(crate) fn report_clamp(requested: Duration, effective: Duration, telemetry: &Telemetry) {
if requested.is_zero() || requested == effective {
return;
}
telemetry.emit(TelemetryEvent::ConfigClamped {
setting: "decision_memo_ttl",
requested: format!("{requested:?}"),
effective: format!("{effective:?}"),
contract_reference: "§17.1 rule 2",
});
}
pub(crate) fn new(ttl: Duration) -> Self {
Self {
ttl: ttl.min(MAX_TTL),
entries: Mutex::new(HashMap::new()),
order: Mutex::new(std::collections::VecDeque::new()),
}
}
pub(crate) fn is_enabled(&self) -> bool {
!self.ttl.is_zero()
}
#[cfg(test)]
pub(crate) fn ttl(&self) -> Duration {
self.ttl
}
pub(crate) fn get_at(&self, key: &MemoKey, now: Instant) -> Option<AccessDecision> {
if !self.is_enabled() {
return None;
}
let entries = self.entries.lock().ok()?;
let entry = entries.get(key)?;
if now.duration_since(entry.stored_at) >= self.ttl {
return None;
}
Some(entry.decision.clone())
}
pub(crate) fn put_at(&self, key: MemoKey, decision: &AccessDecision, now: Instant) {
if !self.is_enabled() {
return;
}
let (Ok(mut entries), Ok(mut order)) = (self.entries.lock(), self.order.lock()) else {
return;
};
if entries
.insert(
key.clone(),
Entry {
decision: decision.clone(),
stored_at: now,
},
)
.is_none()
{
order.push_back(key);
}
while order.len() > MAX_ENTRIES {
if let Some(oldest) = order.pop_front() {
entries.remove(&oldest);
}
}
}
pub(crate) fn clear(&self) {
if let Ok(mut entries) = self.entries.lock() {
entries.clear();
}
if let Ok(mut order) = self.order.lock() {
order.clear();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn decision(allowed: bool, code: &str) -> AccessDecision {
AccessDecision {
allowed,
reason: None,
reason_code: Some(code.to_string()),
}
}
fn key(action: &str, scope: Option<&str>) -> MemoKey {
MemoKey::new(None, Uuid::nil(), action, scope)
}
#[test]
fn the_default_is_disabled_and_never_answers() {
let memo = DecisionMemo::new(Duration::ZERO);
assert!(!memo.is_enabled());
let now = Instant::now();
memo.put_at(key("read", None), &decision(true, "allowed"), now);
assert!(memo.get_at(&key("read", None), now).is_none());
}
#[test]
fn a_ttl_above_the_ceiling_is_clamped_not_rejected() {
assert_eq!(DecisionMemo::new(Duration::from_secs(60)).ttl(), MAX_TTL);
assert_eq!(DecisionMemo::new(Duration::from_secs(5)).ttl(), MAX_TTL);
assert_eq!(
DecisionMemo::new(Duration::from_secs(2)).ttl(),
Duration::from_secs(2)
);
}
#[test]
fn a_hit_inside_the_ttl_returns_the_whole_decision() {
let memo = DecisionMemo::new(Duration::from_secs(5));
let now = Instant::now();
memo.put_at(key("read", None), &decision(false, "denied_by_rule"), now);
let hit = memo
.get_at(&key("read", None), now + Duration::from_secs(4))
.expect("still live");
assert!(!hit.allowed);
assert_eq!(hit.reason_code.as_deref(), Some("denied_by_rule"));
}
#[test]
fn an_entry_expires_exactly_at_the_ttl() {
let memo = DecisionMemo::new(Duration::from_secs(5));
let now = Instant::now();
memo.put_at(key("read", None), &decision(true, "allowed"), now);
assert!(
memo.get_at(&key("read", None), now + Duration::from_millis(4_999))
.is_some()
);
assert!(
memo.get_at(&key("read", None), now + Duration::from_secs(5))
.is_none()
);
}
#[test]
fn allows_and_denies_are_memoized_identically() {
let memo = DecisionMemo::new(Duration::from_secs(5));
let now = Instant::now();
memo.put_at(key("allow-me", None), &decision(true, "allowed"), now);
memo.put_at(key("deny-me", None), &decision(false, "no_grant"), now);
assert!(memo.get_at(&key("allow-me", None), now).unwrap().allowed);
assert!(!memo.get_at(&key("deny-me", None), now).unwrap().allowed);
}
#[test]
fn every_key_component_is_load_bearing() {
let memo = DecisionMemo::new(Duration::from_secs(5));
let now = Instant::now();
let base = MemoKey::new(None, Uuid::nil(), "read", None);
memo.put_at(base.clone(), &decision(true, "allowed"), now);
assert!(memo.get_at(&base, now).is_some());
assert!(memo.get_at(&key("write", None), now).is_none());
assert!(memo.get_at(&key("read", Some("col-a")), now).is_none());
assert!(
memo.get_at(&MemoKey::new(None, Uuid::from_u128(7), "read", None), now)
.is_none()
);
assert!(
memo.get_at(
&MemoKey::new(Some(Uuid::from_u128(9)), Uuid::nil(), "read", None),
now
)
.is_none()
);
}
#[test]
fn an_absent_scope_and_a_present_scope_are_distinct_keys() {
let memo = DecisionMemo::new(Duration::from_secs(5));
let now = Instant::now();
memo.put_at(key("read", None), &decision(true, "allowed"), now);
memo.put_at(
key("read", Some("col-a")),
&decision(false, "no_grant"),
now,
);
assert!(memo.get_at(&key("read", None), now).unwrap().allowed);
assert!(
!memo
.get_at(&key("read", Some("col-a")), now)
.unwrap()
.allowed
);
}
#[test]
fn clear_drops_everything() {
let memo = DecisionMemo::new(Duration::from_secs(5));
let now = Instant::now();
memo.put_at(key("read", None), &decision(true, "allowed"), now);
assert!(memo.get_at(&key("read", None), now).is_some());
memo.clear();
assert!(memo.get_at(&key("read", None), now).is_none());
}
#[test]
fn the_entry_cap_evicts_rather_than_growing() {
let memo = DecisionMemo::new(Duration::from_secs(5));
let now = Instant::now();
for i in 0..(MAX_ENTRIES + 50) {
memo.put_at(
MemoKey::new(None, Uuid::from_u128(i as u128), "read", None),
&decision(true, "allowed"),
now,
);
}
assert!(memo.entries.lock().unwrap().len() <= MAX_ENTRIES);
assert!(
memo.get_at(&MemoKey::new(None, Uuid::from_u128(0), "read", None), now)
.is_none()
);
assert!(
memo.get_at(
&MemoKey::new(
None,
Uuid::from_u128((MAX_ENTRIES + 49) as u128),
"read",
None
),
now
)
.is_some()
);
}
}