hyperlane-plugin-audit 23.3.0

A tamper-evident SHA-256 hash-chained security audit trail plugin for the Hyperlane framework with bounded in-memory ring-buffer sink, pluggable AuditSink trait, header redaction, and chain integrity verification.
Documentation
use super::*;

/// Single tamper-evident hash-chained HTTP audit event.
#[derive(Clone, Debug, Deserialize, Eq, Getter, PartialEq, Serialize)]
pub struct AuditRecord {
    /// Monotonically increasing sequence number (`1`, `2`, ...).
    #[get(type(copy))]
    pub(crate) sequence: u64,
    /// Wall-clock UTC timestamp in milliseconds since Unix epoch.
    #[get(type(copy))]
    pub(crate) timestamp_ms: u64,
    /// HTTP method string.
    pub(crate) method: String,
    /// Request path.
    pub(crate) path: String,
    /// HTTP response status code.
    #[get(type(copy))]
    pub(crate) status_code: usize,
    /// Request processing latency in microseconds.
    #[get(type(copy))]
    pub(crate) latency_us: u64,
    /// Actor identity (from [`set_audit_actor`] or `"anonymous"`).
    pub(crate) actor: String,
    /// Semantic action label (from [`set_audit_action`] or empty).
    pub(crate) action: String,
    /// Correlation ID extracted from request headers, if present.
    pub(crate) request_id: String,
    /// Captured safe/redacted request headers.
    pub(crate) headers: Vec<(String, String)>,
    /// Previous record's `entry_hash` (or [`AUDIT_GENESIS_HASH`]).
    pub(crate) prev_hash: String,
    /// SHA-256 chain hash binding all fields and `prev_hash`.
    pub(crate) entry_hash: String,
}

/// Bounded in-memory ring-buffer [`AuditSink`] suitable for testing and recent audit queries.
#[derive(Debug)]
pub struct InMemoryAuditSink {
    /// Maximum retained records before oldest eviction.
    pub(crate) capacity: usize,
    /// Guarded ring buffer of recent records.
    pub(crate) records: Mutex<VecDeque<AuditRecord>>,
}

/// Configuration for [`AuditPlugin`].
#[derive(Clone, Data, Debug, Eq, PartialEq)]
pub struct AuditConfig {
    /// When `true`, only mutating methods (`POST`, `PUT`, `PATCH`, `DELETE`) are audited.
    #[get(type(copy))]
    pub(crate) mutations_only: bool,
    /// Optional prefix allowlist; empty audits all non-excluded paths.
    pub(crate) include_prefixes: Vec<String>,
    /// Path prefixes excluded from audit recording (for example `"/healthz"`, `"/metrics"`).
    pub(crate) exclude_prefixes: Vec<String>,
    /// Request header names copied into each [`AuditRecord`].
    pub(crate) capture_headers: Vec<String>,
    /// Sensitive header names whose values are always replaced with `[REDACTED]`.
    pub(crate) redact_headers: Vec<String>,
    /// Header name used to extract correlation request ID.
    pub(crate) request_id_header: String,
    /// Default ring-buffer capacity when initialized with [`AuditPlugin::init`].
    #[get(type(copy))]
    pub(crate) in_memory_capacity: usize,
}

/// Compiled tamper-evident audit engine backing [`AuditRequestHook`] and [`AuditResponseHook`].
pub struct AuditPlugin {
    /// Retained configuration.
    pub(crate) config: AuditConfig,
    /// Normalized include prefixes.
    pub(crate) include_prefixes: Box<[String]>,
    /// Normalized exclude prefixes.
    pub(crate) exclude_prefixes: Box<[String]>,
    /// Lowercased capture headers.
    pub(crate) capture_headers_lower: Box<[String]>,
    /// Lowercased redacted header names.
    pub(crate) redact_headers_lower: Box<[String]>,
    /// Lowercased request ID header name.
    pub(crate) request_id_header_lower: String,
    /// Next sequence number counter.
    pub(crate) seq: AtomicU64,
    /// Previous record hash protected by a short critical section.
    pub(crate) last_hash: Mutex<[u8; 64]>,
    /// Active sink receiving finalized audit events.
    pub(crate) sink: Arc<dyn AuditSink>,
    /// Optional reference to the built-in in-memory sink for direct snapshots.
    pub(crate) memory_sink: Option<Arc<InMemoryAuditSink>>,
}

/// Incremental stack-allocated FIPS 180-4 SHA-256 hasher avoiding intermediate string formatting.
pub(crate) struct AuditSha256 {
    /// Current 256-bit SHA-256 state words.
    pub(crate) state: [u32; 8],
    /// Partial 64-byte input block buffer.
    pub(crate) block: [u8; 64],
    /// Number of valid buffered bytes in `block`.
    pub(crate) block_len: usize,
    /// Total number of bytes absorbed so far.
    pub(crate) total_bytes: u64,
}

/// Opt-in request middleware capturing entry timestamps for audited requests.
#[derive(Clone, Copy, Debug, Default)]
#[hyperlane::request_middleware(-118)]
pub struct AuditRequestHook;

/// Opt-in response middleware emitting hash-chained [`AuditRecord`] events to the configured sink.
#[derive(Clone, Copy, Debug, Default)]
#[hyperlane::response_middleware(92)]
pub struct AuditResponseHook;