#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FailurePolicy {
FailClosed,
FailOpen,
}
impl FailurePolicy {
pub const fn as_str(self) -> &'static str {
match self {
Self::FailClosed => "fail_closed",
Self::FailOpen => "fail_open",
}
}
pub fn from_wire(raw: &str) -> Option<Self> {
match raw.trim().to_ascii_lowercase().as_str() {
"fail_closed" => Some(Self::FailClosed),
"fail_open" => Some(Self::FailOpen),
_ => None,
}
}
}
impl std::fmt::Display for FailurePolicy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ReactorMode {
Intercept,
Listen,
}
impl ReactorMode {
pub const fn as_str(self) -> &'static str {
match self {
Self::Intercept => "intercept",
Self::Listen => "listen",
}
}
pub fn from_wire(raw: &str) -> Option<Self> {
match raw.trim().to_ascii_lowercase().as_str() {
"intercept" => Some(Self::Intercept),
"listen" => Some(Self::Listen),
_ => None,
}
}
}
impl std::fmt::Display for ReactorMode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ReactorEventSpec {
pub name: &'static str,
pub interceptable: bool,
pub mutable: bool,
pub mutable_fields: &'static [&'static str],
pub default_failure_policy: FailurePolicy,
pub description: &'static str,
}
impl ReactorEventSpec {
pub fn patch_field_allowed(&self, field: &str) -> bool {
if !self.mutable {
return false;
}
self.mutable_fields.iter().any(|allowed| {
if allowed.ends_with('.') {
field.len() > allowed.len() && field.starts_with(allowed)
} else {
field == *allowed
}
})
}
}
pub const EVENT_REGISTRY: &[ReactorEventSpec] = &[
ReactorEventSpec {
name: events::TOKEN_PRE_ISSUE,
interceptable: true,
mutable: true,
mutable_fields: &["ext."],
default_failure_policy: FailurePolicy::FailOpen,
description: "Enrich or veto token issuance. May add claims under `ext.` only.",
},
ReactorEventSpec {
name: events::LOGIN_POST_AUTH,
interceptable: true,
mutable: false,
mutable_fields: &[],
default_failure_policy: FailurePolicy::FailClosed,
description: "After credentials verify, before session issuance: veto or require step-up MFA.",
},
ReactorEventSpec {
name: events::USER_PRE_CREATE,
interceptable: true,
mutable: true,
mutable_fields: &["username", "email", "metadata."],
default_failure_policy: FailurePolicy::FailClosed,
description: "Validate or normalize a new user's profile fields.",
},
ReactorEventSpec {
name: events::USER_PRE_UPDATE,
interceptable: true,
mutable: true,
mutable_fields: &["username", "email", "metadata."],
default_failure_policy: FailurePolicy::FailClosed,
description: "Validate or normalize a profile update.",
},
ReactorEventSpec {
name: events::GRANT_PRE_ASSIGN,
interceptable: true,
mutable: false,
mutable_fields: &[],
default_failure_policy: FailurePolicy::FailClosed,
description: "Veto a role or permission assignment (four-eyes workflows). Veto-only.",
},
];
pub mod events {
pub const TOKEN_PRE_ISSUE: &str = "token.pre_issue";
pub const LOGIN_POST_AUTH: &str = "login.post_auth";
pub const USER_PRE_CREATE: &str = "user.pre_create";
pub const USER_PRE_UPDATE: &str = "user.pre_update";
pub const GRANT_PRE_ASSIGN: &str = "grant.pre_assign";
}
pub fn event_spec(name: &str) -> Option<&'static ReactorEventSpec> {
EVENT_REGISTRY.iter().find(|spec| spec.name == name)
}
pub fn default_failure_policy_for<I, S>(event_names: I) -> FailurePolicy
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
let mut any = false;
for name in event_names {
any = true;
match event_spec(name.as_ref()) {
Some(spec) if spec.default_failure_policy == FailurePolicy::FailOpen => {}
_ => return FailurePolicy::FailClosed,
}
}
if any {
FailurePolicy::FailOpen
} else {
FailurePolicy::FailClosed
}
}
pub const DEFAULT_TIMEOUT_MS: u32 = 500;
pub const MIN_TIMEOUT_MS: u32 = 1;
pub const MAX_TIMEOUT_MS: u32 = 5_000;
pub const DEFAULT_MAX_IN_FLIGHT: u32 = 64;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_registry_holds_exactly_the_five_v1_events() {
let names: Vec<&str> = EVENT_REGISTRY.iter().map(|spec| spec.name).collect();
assert_eq!(
names,
vec![
"token.pre_issue",
"login.post_auth",
"user.pre_create",
"user.pre_update",
"grant.pre_assign",
]
);
}
#[test]
fn the_hot_path_operations_are_absent_from_the_registry() {
for excluded in ["authz.check", "authz.check_batch", "token.introspect"] {
assert!(
event_spec(excluded).is_none(),
"{excluded} must not be hookable (§22.7)"
);
assert!(EVENT_REGISTRY.iter().all(|spec| spec.name != excluded));
}
}
#[test]
fn token_pre_issue_admits_the_ext_namespace_and_nothing_else() {
let spec = event_spec("token.pre_issue").unwrap();
for allowed in ["ext.department", "ext.a.b.c", "ext.x"] {
assert!(
spec.patch_field_allowed(allowed),
"{allowed} must be allowed"
);
}
for refused in [
"ext.",
"ext",
"extra",
"external_id",
"evil.ext.department",
"iss",
"sub",
"aud",
"exp",
"iat",
"nbf",
"jti",
"scope",
"scp",
"azp",
"act",
"client_id",
] {
assert!(
!spec.patch_field_allowed(refused),
"{refused} must be refused"
);
}
}
#[test]
fn the_user_events_admit_profile_fields_and_refuse_credentials() {
for event in ["user.pre_create", "user.pre_update"] {
let spec = event_spec(event).unwrap();
for allowed in ["username", "email", "metadata.source", "metadata.a.b"] {
assert!(spec.patch_field_allowed(allowed), "{event}: {allowed}");
}
for refused in [
"password",
"password_hash",
"tenant_id",
"id",
"roles",
"is_admin",
"metadata",
"metadata.",
] {
assert!(!spec.patch_field_allowed(refused), "{event}: {refused}");
}
}
}
#[test]
fn the_veto_only_events_accept_no_patch_field_at_all() {
for event in ["login.post_auth", "grant.pre_assign"] {
let spec = event_spec(event).unwrap();
assert!(!spec.mutable);
assert!(spec.mutable_fields.is_empty());
for field in ["anything", "username", "ext.department", "require_mfa"] {
assert!(!spec.patch_field_allowed(field), "{event}: {field}");
}
}
}
#[test]
fn the_strictest_default_failure_policy_wins_regardless_of_order() {
assert_eq!(
default_failure_policy_for(["token.pre_issue"]),
FailurePolicy::FailOpen
);
assert_eq!(
default_failure_policy_for(["token.pre_issue", "login.post_auth"]),
FailurePolicy::FailClosed
);
assert_eq!(
default_failure_policy_for(["login.post_auth", "token.pre_issue"]),
FailurePolicy::FailClosed
);
assert_eq!(
default_failure_policy_for(["token.pre_issue", "authz.check"]),
FailurePolicy::FailClosed
);
assert_eq!(
default_failure_policy_for(Vec::<&str>::new()),
FailurePolicy::FailClosed
);
}
#[test]
fn wire_strings_round_trip() {
for policy in [FailurePolicy::FailOpen, FailurePolicy::FailClosed] {
assert_eq!(FailurePolicy::from_wire(policy.as_str()), Some(policy));
}
assert_eq!(
FailurePolicy::from_wire(" FAIL_OPEN "),
Some(FailurePolicy::FailOpen)
);
assert_eq!(FailurePolicy::from_wire("open"), None);
for mode in [ReactorMode::Intercept, ReactorMode::Listen] {
assert_eq!(ReactorMode::from_wire(mode.as_str()), Some(mode));
}
assert_eq!(ReactorMode::from_wire("observe"), None);
}
#[test]
fn the_timeout_bounds_match_the_contract() {
assert_eq!(DEFAULT_TIMEOUT_MS, 500);
assert_eq!(MIN_TIMEOUT_MS, 1);
assert_eq!(MAX_TIMEOUT_MS, 5_000);
assert_eq!(DEFAULT_MAX_IN_FLIGHT, 64);
}
}