use std::collections::BTreeMap;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::amqp::hmac::{sign_payload, verify_payload};
pub const REACTOR_EXCHANGE: &str = "axiam.reactor.events";
pub const REACTOR_KEY_VERSION: u8 = 2;
pub const DEFAULT_FRESHNESS_SKEW_SECS: i64 = 300;
pub fn routing_key(tenant_id: Uuid, event: &str) -> String {
format!("{tenant_id}.{event}")
}
pub fn queue_name(tenant_id: Uuid, reactor_id: Uuid) -> String {
format!("axiam.reactor.q.{tenant_id}.{reactor_id}")
}
pub fn is_fresh(issued_at: DateTime<Utc>, now: DateTime<Utc>, skew: chrono::Duration) -> bool {
now.signed_duration_since(issued_at).abs() <= skew
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReactorEvent {
pub tenant_id: Uuid,
pub event: String,
pub correlation_id: Uuid,
pub payload: serde_json::Value,
pub timeout_ms: u32,
pub key_version: u8,
pub nonce: Uuid,
pub issued_at: DateTime<Utc>,
pub hmac_signature: Option<String>,
}
impl ReactorEvent {
pub fn chained_patch(&self) -> Option<&serde_json::Value> {
self.payload.get("_reactor_patch")
}
pub fn spec(&self) -> Option<&'static super::registry::ReactorEventSpec> {
super::registry::event_spec(&self.event)
}
pub fn timeout(&self) -> std::time::Duration {
std::time::Duration::from_millis(u64::from(self.timeout_ms))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EventRejection {
Malformed(&'static str),
KeyVersionTooOld(u8),
BadSignature,
Stale,
ReplayedNonce,
}
impl std::fmt::Display for EventRejection {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Malformed(what) => write!(f, "malformed reactor event: {what}"),
Self::KeyVersionTooOld(v) => {
write!(f, "event key_version {v} is below the accepted floor")
}
Self::BadSignature => write!(f, "event signature is missing or invalid"),
Self::Stale => write!(f, "event issued_at is outside the freshness window"),
Self::ReplayedNonce => write!(f, "event nonce was already seen (replay)"),
}
}
}
impl std::error::Error for EventRejection {}
pub fn canonical_event_bytes(body: &serde_json::Value) -> Result<Vec<u8>, EventRejection> {
let mut canonical = body.clone();
let obj = canonical
.as_object_mut()
.ok_or(EventRejection::Malformed("body is not a JSON object"))?;
if !obj.contains_key("hmac_signature") {
return Err(EventRejection::Malformed("hmac_signature is absent"));
}
obj.insert("hmac_signature".into(), serde_json::Value::Null);
serde_json::to_vec(&canonical)
.map_err(|_| EventRejection::Malformed("body could not be re-serialized"))
}
pub fn verify_event(
body: &serde_json::Value,
signing_key: &[u8],
now: DateTime<Utc>,
skew: chrono::Duration,
) -> Result<ReactorEvent, EventRejection> {
let key_version = body
.get("key_version")
.and_then(serde_json::Value::as_u64)
.and_then(|v| u8::try_from(v).ok())
.ok_or(EventRejection::Malformed(
"key_version is absent or invalid",
))?;
if key_version < REACTOR_KEY_VERSION {
return Err(EventRejection::KeyVersionTooOld(key_version));
}
let signature = body
.get("hmac_signature")
.and_then(serde_json::Value::as_str)
.ok_or(EventRejection::BadSignature)?
.to_owned();
let canonical = canonical_event_bytes(body)?;
if !verify_payload(signing_key, &canonical, &signature) {
return Err(EventRejection::BadSignature);
}
let event: ReactorEvent = serde_json::from_value(body.clone())
.map_err(|_| EventRejection::Malformed("body does not decode as a reactor event"))?;
if !is_fresh(event.issued_at, now, skew) {
return Err(EventRejection::Stale);
}
Ok(event)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ReplyDecision {
Allow,
Deny,
Mutate,
}
impl ReplyDecision {
pub const fn as_str(self) -> &'static str {
match self {
Self::Allow => "allow",
Self::Deny => "deny",
Self::Mutate => "mutate",
}
}
}
impl std::fmt::Display for ReplyDecision {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReactorReply {
pub correlation_id: Uuid,
pub tenant_id: Uuid,
pub event: String,
pub decision: ReplyDecision,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub patch: Option<BTreeMap<String, String>>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub require_mfa: bool,
pub key_version: u8,
pub nonce: Uuid,
pub issued_at: DateTime<Utc>,
pub hmac_signature: Option<String>,
}
impl ReactorReply {
pub fn answering(event: &ReactorEvent, decision: ReplyDecision, now: DateTime<Utc>) -> Self {
Self {
correlation_id: event.correlation_id,
tenant_id: event.tenant_id,
event: event.event.clone(),
decision,
reason: None,
patch: None,
require_mfa: false,
key_version: REACTOR_KEY_VERSION,
nonce: Uuid::new_v4(),
issued_at: now,
hmac_signature: None,
}
}
pub fn canonical_signed_bytes(&self) -> Result<Vec<u8>, serde_json::Error> {
let mut unsigned = self.clone();
unsigned.hmac_signature = None;
serde_json::to_vec(&unsigned)
}
pub fn sign(&mut self, signing_key: &[u8]) -> Result<(), serde_json::Error> {
self.hmac_signature = None;
self.key_version = REACTOR_KEY_VERSION;
let bytes = self.canonical_signed_bytes()?;
self.hmac_signature = Some(sign_payload(signing_key, &bytes));
Ok(())
}
pub fn signature_valid(&self, signing_key: &[u8]) -> bool {
let Some(signature) = self.hmac_signature.as_deref() else {
return false;
};
let Ok(bytes) = self.canonical_signed_bytes() else {
return false;
};
verify_payload(signing_key, &bytes, signature)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReplyRejection {
WrongCorrelation,
TenantMismatch,
EventMismatch,
KeyVersionTooOld(u8),
Stale,
BadSignature,
RequireMfaNotSupported,
NotMutable,
ForbiddenPatchField(String),
MalformedMutation,
}
impl std::fmt::Display for ReplyRejection {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::WrongCorrelation => write!(f, "reply correlation_id does not match the event"),
Self::TenantMismatch => write!(f, "reply is for a different tenant"),
Self::EventMismatch => write!(f, "reply is for a different event"),
Self::KeyVersionTooOld(v) => {
write!(f, "reply key_version {v} is below the accepted floor")
}
Self::Stale => write!(f, "reply issued_at is outside the freshness window"),
Self::BadSignature => write!(f, "reply signature is missing or invalid"),
Self::RequireMfaNotSupported => {
write!(f, "require_mfa is not supported for this event")
}
Self::NotMutable => write!(f, "event is veto-only; a mutate reply is not accepted"),
Self::ForbiddenPatchField(key) => {
write!(f, "patch field '{key}' is outside the event's allow-list")
}
Self::MalformedMutation => write!(f, "mutate without a patch, or patch without mutate"),
}
}
}
impl std::error::Error for ReplyRejection {}