use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;
use crate::types::DateTime;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum AuthorizationStatus {
Accepted,
Blocked,
ConcurrentTx,
Expired,
Invalid,
Unknown,
}
impl AuthorizationStatus {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
AuthorizationStatus::Accepted => "Accepted",
AuthorizationStatus::Blocked => "Blocked",
AuthorizationStatus::ConcurrentTx => "ConcurrentTx",
AuthorizationStatus::Expired => "Expired",
AuthorizationStatus::Invalid => "Invalid",
AuthorizationStatus::Unknown => "Unknown",
}
}
}
impl fmt::Display for AuthorizationStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct IdToken {
pub value: String,
pub kind: Option<String>,
}
impl IdToken {
#[must_use]
pub fn new(value: impl Into<String>, kind: impl Into<String>) -> Self {
Self {
value: value.into(),
kind: Some(kind.into()),
}
}
#[must_use]
pub fn tag(value: impl Into<String>) -> Self {
Self {
value: value.into(),
kind: None,
}
}
#[must_use]
pub fn is_central(&self) -> bool {
self.kind.as_deref() == Some("Central")
}
}
impl fmt::Display for IdToken {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.kind {
Some(kind) => write!(f, "{} ({kind})", self.value),
None => f.write_str(&self.value),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct IdTokenInfo {
pub status: AuthorizationStatus,
pub expires: Option<DateTime>,
pub group_id: Option<String>,
pub language: Option<String>,
}
impl IdTokenInfo {
#[must_use]
pub fn accepted() -> Self {
Self {
status: AuthorizationStatus::Accepted,
expires: None,
group_id: None,
language: None,
}
}
#[must_use]
pub fn new(status: AuthorizationStatus) -> Self {
Self {
status,
expires: None,
group_id: None,
language: None,
}
}
#[must_use]
pub fn expiring(mut self, at: DateTime) -> Self {
self.expires = Some(at);
self
}
#[must_use]
pub fn in_group(mut self, group_id: impl Into<String>) -> Self {
self.group_id = Some(group_id.into());
self
}
#[must_use]
pub fn status_at(&self, now: DateTime) -> AuthorizationStatus {
match self.expires {
Some(expiry) if expiry <= now => AuthorizationStatus::Expired,
_ => self.status,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum UpdateType {
Full,
Differential,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
#[must_use = "a refused update left the list unchanged — `VersionMismatch` in particular means \
the CSMS and the station now disagree about what is on it"]
pub enum UpdateStatus {
Accepted,
Failed,
NotSupported,
VersionMismatch,
}
#[derive(Clone, Debug, Default)]
pub struct LocalAuthorizationList {
version: i32,
entries: BTreeMap<IdToken, IdTokenInfo>,
limit: Option<usize>,
}
impl LocalAuthorizationList {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn bounded(limit: usize) -> Self {
Self {
limit: Some(limit),
..Self::default()
}
}
#[must_use]
pub const fn version(&self) -> i32 {
self.version
}
#[must_use]
pub fn len(&self) -> usize {
self.entries.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn update(
&mut self,
update: UpdateType,
version: i32,
entries: Vec<(IdToken, Option<IdTokenInfo>)>,
) -> UpdateStatus {
if update == UpdateType::Differential && version <= self.version {
return UpdateStatus::VersionMismatch;
}
let projected = match update {
UpdateType::Full => entries.iter().filter(|(_, info)| info.is_some()).count(),
UpdateType::Differential => {
let added = entries
.iter()
.filter(|(token, info)| info.is_some() && !self.entries.contains_key(token))
.count();
let removed = entries
.iter()
.filter(|(token, info)| info.is_none() && self.entries.contains_key(token))
.count();
self.entries.len() + added - removed
}
};
if self.limit.is_some_and(|limit| projected > limit) {
return UpdateStatus::Failed;
}
if update == UpdateType::Full {
self.entries.clear();
}
for (token, info) in entries {
match info {
Some(info) => {
self.entries.insert(token, info);
}
None => {
self.entries.remove(&token);
}
}
}
self.version = version;
UpdateStatus::Accepted
}
pub fn clear(&mut self) {
self.entries.clear();
self.version = 0;
}
#[must_use]
pub fn get(&self, id_token: &IdToken) -> Option<&IdTokenInfo> {
self.entries.get(id_token)
}
}
#[derive(Clone, Debug)]
pub struct AuthorizationCache {
entries: BTreeMap<IdToken, CacheEntry>,
capacity: usize,
clock: u64,
enabled: bool,
lifetime: Option<i64>,
}
#[derive(Clone, Debug)]
struct CacheEntry {
used: u64,
updated: DateTime,
info: IdTokenInfo,
}
impl Default for AuthorizationCache {
fn default() -> Self {
Self::with_capacity(512)
}
}
impl AuthorizationCache {
#[must_use]
pub fn with_capacity(capacity: usize) -> Self {
Self {
entries: BTreeMap::new(),
capacity: capacity.max(1),
clock: 0,
enabled: true,
lifetime: None,
}
}
#[must_use]
pub fn with_lifetime(mut self, seconds: u32) -> Self {
self.lifetime = Some(i64::from(seconds));
self
}
pub fn set_enabled(&mut self, enabled: bool) {
self.enabled = enabled;
if !enabled {
self.entries.clear();
}
}
#[must_use]
pub const fn is_enabled(&self) -> bool {
self.enabled
}
#[must_use]
pub fn len(&self) -> usize {
self.entries.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn remember(&mut self, id_token: IdToken, info: IdTokenInfo, now: DateTime) {
if !self.enabled || id_token.is_central() {
return;
}
if info.expires.is_some_and(|expiry| expiry <= now) {
self.entries.remove(&id_token);
return;
}
self.clock += 1;
let used = self.clock;
self.entries.insert(
id_token,
CacheEntry {
used,
updated: now,
info,
},
);
while self.entries.len() > self.capacity {
if let Some(oldest) = self
.entries
.iter()
.min_by_key(|(_, entry)| entry.used)
.map(|(token, _)| token.clone())
{
self.entries.remove(&oldest);
} else {
break;
}
}
}
pub fn get(&mut self, id_token: &IdToken, now: DateTime) -> Option<IdTokenInfo> {
if !self.enabled {
return None;
}
let entry = self.entries.get(id_token)?;
if entry.info.expires.is_none()
&& self.lifetime.is_some_and(|lifetime| {
now.timestamp().as_second() - entry.updated.timestamp().as_second() > lifetime
})
{
self.entries.remove(id_token);
return None;
}
self.clock += 1;
let used = self.clock;
let entry = self.entries.get_mut(id_token)?;
entry.used = used;
Some(entry.info.clone())
}
pub fn clear(&mut self) {
self.entries.clear();
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LocalSource {
LocalList,
Cache,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
#[must_use = "this is the authorization decision: discarding it authorizes everyone"]
pub enum Decision {
Local {
source: LocalSource,
info: IdTokenInfo,
},
AskCsms,
OfflineUnknown {
start_anyway: bool,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
#[allow(clippy::struct_excessive_bools)]
pub struct AuthorizationPolicy {
pub local_auth_list_enabled: bool,
pub local_authorize_offline: bool,
pub local_pre_authorize: bool,
pub offline_tx_for_unknown_id: bool,
pub local_list_supports_expiry: bool,
}
impl Default for AuthorizationPolicy {
fn default() -> Self {
Self {
local_auth_list_enabled: true,
local_authorize_offline: true,
local_pre_authorize: false,
offline_tx_for_unknown_id: false,
local_list_supports_expiry: true,
}
}
}
impl AuthorizationPolicy {
#[must_use]
pub const fn local_auth_list_enabled(mut self, enabled: bool) -> Self {
self.local_auth_list_enabled = enabled;
self
}
#[must_use]
pub const fn local_authorize_offline(mut self, enabled: bool) -> Self {
self.local_authorize_offline = enabled;
self
}
#[must_use]
pub const fn local_pre_authorize(mut self, enabled: bool) -> Self {
self.local_pre_authorize = enabled;
self
}
#[must_use]
pub const fn offline_tx_for_unknown_id(mut self, enabled: bool) -> Self {
self.offline_tx_for_unknown_id = enabled;
self
}
#[must_use]
pub const fn local_list_supports_expiry(mut self, enabled: bool) -> Self {
self.local_list_supports_expiry = enabled;
self
}
}
#[derive(Clone, Debug, Default)]
pub struct Authorizer {
pub list: LocalAuthorizationList,
pub cache: AuthorizationCache,
pub policy: AuthorizationPolicy,
}
impl Authorizer {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_policy(mut self, policy: AuthorizationPolicy) -> Self {
self.policy = policy;
self
}
pub fn decide(&mut self, id_token: &IdToken, online: bool, now: DateTime) -> Decision {
let may_use_local = if online {
self.policy.local_pre_authorize
} else {
self.policy.local_authorize_offline
};
let local = self
.policy
.local_auth_list_enabled
.then(|| self.list.get(id_token).cloned())
.flatten()
.map(|info| (LocalSource::LocalList, info))
.or_else(|| {
self.cache
.get(id_token, now)
.map(|info| (LocalSource::Cache, info))
});
if let Some((source, info)) = local {
let status =
if source == LocalSource::LocalList && !self.policy.local_list_supports_expiry {
info.status
} else {
info.status_at(now)
};
if status == AuthorizationStatus::Accepted {
if may_use_local {
return Decision::Local {
source,
info: IdTokenInfo { status, ..info },
};
}
} else if !online {
return Decision::Local {
source,
info: IdTokenInfo { status, ..info },
};
}
if online {
return Decision::AskCsms;
}
}
if online {
Decision::AskCsms
} else {
Decision::OfflineUnknown {
start_anyway: self.policy.offline_tx_for_unknown_id,
}
}
}
pub fn remember(&mut self, id_token: IdToken, info: IdTokenInfo, now: DateTime) {
self.cache.remember(id_token, info, now);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn at(text: &str) -> DateTime {
DateTime::parse(text).unwrap()
}
fn now() -> DateTime {
at("2024-06-01T12:00:00Z")
}
#[test]
fn a_differential_update_must_advance_the_version() {
let mut list = LocalAuthorizationList::new();
assert_eq!(
list.update(
UpdateType::Full,
5,
alloc::vec![(IdToken::tag("A"), Some(IdTokenInfo::accepted()))]
),
UpdateStatus::Accepted
);
assert_eq!(list.version(), 5);
assert_eq!(
list.update(UpdateType::Differential, 5, alloc::vec![]),
UpdateStatus::VersionMismatch
);
assert_eq!(
list.update(
UpdateType::Differential,
6,
alloc::vec![
(IdToken::tag("B"), Some(IdTokenInfo::accepted())),
(IdToken::tag("A"), None)
]
),
UpdateStatus::Accepted
);
assert!(list.get(&IdToken::tag("A")).is_none());
assert!(list.get(&IdToken::tag("B")).is_some());
}
#[test]
fn a_full_update_replaces_the_list() {
let mut list = LocalAuthorizationList::new();
let _ = list.update(
UpdateType::Full,
1,
alloc::vec![(IdToken::tag("A"), Some(IdTokenInfo::accepted()))],
);
let _ = list.update(
UpdateType::Full,
2,
alloc::vec![(IdToken::tag("B"), Some(IdTokenInfo::accepted()))],
);
assert!(list.get(&IdToken::tag("A")).is_none());
assert_eq!(list.len(), 1);
}
#[test]
fn a_bounded_list_refuses_to_overflow() {
let mut list = LocalAuthorizationList::bounded(1);
assert_eq!(
list.update(
UpdateType::Full,
1,
alloc::vec![
(IdToken::tag("A"), Some(IdTokenInfo::accepted())),
(IdToken::tag("B"), Some(IdTokenInfo::accepted()))
]
),
UpdateStatus::Failed
);
assert!(list.is_empty(), "{list:?}");
}
fn seeded() -> Authorizer {
let mut authorizer = Authorizer::new();
let _ = authorizer.list.update(
UpdateType::Full,
1,
alloc::vec![
(
IdToken::tag("BLOCKED"),
Some(IdTokenInfo::new(AuthorizationStatus::Blocked))
),
(
IdToken::tag("OLD"),
Some(IdTokenInfo::accepted().expiring(at("2024-01-01T00:00:00Z")))
),
(IdToken::tag("LISTED"), Some(IdTokenInfo::accepted())),
],
);
authorizer.remember(IdToken::tag("CACHED"), IdTokenInfo::accepted(), now());
authorizer
}
#[test]
fn the_list_outranks_the_cache_and_expiry_is_honoured() {
let mut authorizer = seeded();
authorizer.remember(
IdToken::tag("LISTED"),
IdTokenInfo::new(AuthorizationStatus::Blocked),
now(),
);
let decision = authorizer.decide(&IdToken::tag("LISTED"), false, now());
assert!(
matches!(
&decision,
Decision::Local {
source: LocalSource::LocalList,
info
} if info.status == AuthorizationStatus::Accepted
),
"{decision:?}"
);
let decision = authorizer.decide(&IdToken::tag("OLD"), false, now());
assert!(
matches!(&decision, Decision::Local { info, .. }
if info.status == AuthorizationStatus::Expired),
"{decision:?}"
);
}
#[test]
fn an_online_station_asks_the_csms_about_a_locally_refused_token_c10() {
let mut authorizer = seeded();
assert_eq!(
authorizer.decide(&IdToken::tag("BLOCKED"), true, now()),
Decision::AskCsms
);
assert_eq!(
authorizer.decide(&IdToken::tag("NEVER-SEEN"), true, now()),
Decision::AskCsms
);
}
#[test]
fn an_offline_station_honours_a_local_refusal() {
let mut authorizer = seeded();
let decision = authorizer.decide(&IdToken::tag("BLOCKED"), false, now());
assert!(
matches!(&decision, Decision::Local { info, .. }
if info.status == AuthorizationStatus::Blocked),
"{decision:?}"
);
}
#[test]
fn local_authorize_offline_gates_the_local_answer() {
let mut authorizer =
seeded().with_policy(AuthorizationPolicy::default().local_authorize_offline(false));
assert_eq!(
authorizer.decide(&IdToken::tag("LISTED"), false, now()),
Decision::OfflineUnknown {
start_anyway: false
}
);
}
#[test]
fn local_pre_authorize_lets_the_cache_answer_while_online_c06() {
let mut authorizer =
seeded().with_policy(AuthorizationPolicy::default().local_pre_authorize(true));
let decision = authorizer.decide(&IdToken::tag("CACHED"), true, now());
assert!(
matches!(
&decision,
Decision::Local {
source: LocalSource::Cache,
info
} if info.status == AuthorizationStatus::Accepted
),
"{decision:?}"
);
let mut strict = seeded();
assert_eq!(
strict.decide(&IdToken::tag("CACHED"), true, now()),
Decision::AskCsms
);
}
#[test]
fn offline_tx_for_unknown_id_is_reported_with_the_decision_c15() {
let mut authorizer = seeded();
assert_eq!(
authorizer.decide(&IdToken::tag("NEVER-SEEN"), false, now()),
Decision::OfflineUnknown {
start_anyway: false
}
);
let mut permissive =
seeded().with_policy(AuthorizationPolicy::default().offline_tx_for_unknown_id(true));
assert_eq!(
permissive.decide(&IdToken::tag("NEVER-SEEN"), false, now()),
Decision::OfflineUnknown { start_anyway: true }
);
}
#[test]
fn a_listed_tokens_expiry_counts_only_where_the_station_supports_it() {
let mut supports = seeded();
assert!(matches!(
supports.decide(&IdToken::tag("OLD"), false, now()),
Decision::Local { info, .. } if info.status == AuthorizationStatus::Expired
));
assert_eq!(
supports.decide(&IdToken::tag("OLD"), true, now()),
Decision::AskCsms
);
let mut ignores =
seeded().with_policy(AuthorizationPolicy::default().local_list_supports_expiry(false));
assert!(matches!(
ignores.decide(&IdToken::tag("OLD"), false, now()),
Decision::Local { info, .. } if info.status == AuthorizationStatus::Accepted
));
}
#[test]
fn a_disabled_local_list_is_not_consulted() {
let mut authorizer =
seeded().with_policy(AuthorizationPolicy::default().local_auth_list_enabled(false));
assert_eq!(
authorizer.decide(&IdToken::tag("LISTED"), false, now()),
Decision::OfflineUnknown {
start_anyway: false
}
);
assert_eq!(authorizer.list.len(), 3, "the list is still there");
}
#[test]
fn tokens_compare_by_value_and_type() {
let mut list = LocalAuthorizationList::new();
let _ = list.update(
UpdateType::Full,
1,
alloc::vec![(
IdToken::new("04A2", "ISO14443"),
Some(IdTokenInfo::accepted())
)],
);
assert!(list.get(&IdToken::new("04A2", "ISO14443")).is_some());
assert!(list.get(&IdToken::new("04A2", "Local")).is_none());
assert!(list.get(&IdToken::tag("04A2")).is_none());
}
#[test]
fn a_central_token_is_never_cached() {
let mut cache = AuthorizationCache::default();
cache.remember(
IdToken::new("APP-1", "Central"),
IdTokenInfo::accepted(),
now(),
);
assert!(cache.is_empty());
cache.remember(
IdToken::new("APP-1", "eMAID"),
IdTokenInfo::accepted(),
now(),
);
assert_eq!(cache.len(), 1);
}
#[test]
fn cache_entries_expire_after_the_lifetime_unless_they_carry_a_date() {
let mut cache = AuthorizationCache::default().with_lifetime(3600);
let token = IdToken::tag("A");
cache.remember(
token.clone(),
IdTokenInfo::accepted(),
at("2024-06-01T12:00:00Z"),
);
assert!(cache.get(&token, at("2024-06-01T12:59:59Z")).is_some());
assert!(cache.get(&token, at("2024-06-01T13:00:01Z")).is_none());
assert!(cache.is_empty(), "removed, not merely hidden");
let dated = IdToken::tag("B");
let until = at("2024-06-02T00:00:00Z");
cache.remember(
dated.clone(),
IdTokenInfo::accepted().expiring(until),
at("2024-06-01T12:00:00Z"),
);
let later = cache.get(&dated, at("2024-06-01T18:00:00Z")).unwrap();
assert_eq!(
later.status_at(at("2024-06-01T18:00:00Z")),
AuthorizationStatus::Accepted
);
cache.remember(
IdToken::tag("C"),
IdTokenInfo::accepted().expiring(at("2024-01-01T00:00:00Z")),
now(),
);
assert!(cache.get(&IdToken::tag("C"), now()).is_none());
}
#[test]
fn the_cache_evicts_the_least_recently_used_token() {
let mut cache = AuthorizationCache::with_capacity(2);
cache.remember(IdToken::tag("A"), IdTokenInfo::accepted(), now());
cache.remember(IdToken::tag("B"), IdTokenInfo::accepted(), now());
assert!(
cache.get(&IdToken::tag("A"), now()).is_some(),
"touching A makes B the oldest"
);
cache.remember(IdToken::tag("C"), IdTokenInfo::accepted(), now());
assert!(cache.get(&IdToken::tag("B"), now()).is_none());
assert!(cache.get(&IdToken::tag("A"), now()).is_some());
assert!(cache.get(&IdToken::tag("C"), now()).is_some());
}
#[test]
fn disabling_the_cache_empties_it() {
let mut cache = AuthorizationCache::default();
cache.remember(IdToken::tag("A"), IdTokenInfo::accepted(), now());
cache.set_enabled(false);
assert!(cache.get(&IdToken::tag("A"), now()).is_none());
cache.remember(IdToken::tag("B"), IdTokenInfo::accepted(), now());
assert!(cache.is_empty(), "{cache:?}");
}
}