hyperlane-plugin-audit 23.3.1

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::*;

/// Compresses a single 64-byte SHA-256 block into `state`.
///
/// # Arguments
///
/// - `&mut [u32; 8]` - Mutable SHA-256 state words.
/// - `&[u8; 64]` - 64-byte message block.
#[inline(always)]
pub(crate) fn sha256_compress(state: &mut [u32; 8], block: &[u8; 64]) {
    let mut w: [u32; 64] = [0u32; 64];
    for (i, slot) in w.iter_mut().enumerate().take(16usize) {
        let j: usize = i * 4;
        *slot = u32::from_be_bytes([block[j], block[j + 1], block[j + 2], block[j + 3]]);
    }
    for i in 16..64usize {
        let s0: u32 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
        let s1: u32 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
        w[i] = w[i - 16]
            .wrapping_add(s0)
            .wrapping_add(w[i - 7])
            .wrapping_add(s1);
    }
    let mut a: u32 = state[0];
    let mut b: u32 = state[1];
    let mut c: u32 = state[2];
    let mut d: u32 = state[3];
    let mut e: u32 = state[4];
    let mut f: u32 = state[5];
    let mut g: u32 = state[6];
    let mut h: u32 = state[7];
    for i in 0..64usize {
        let s1: u32 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
        let ch: u32 = (e & f) ^ ((!e) & g);
        let t1: u32 = h
            .wrapping_add(s1)
            .wrapping_add(ch)
            .wrapping_add(SHA256_K[i])
            .wrapping_add(w[i]);
        let s0: u32 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
        let maj: u32 = (a & b) ^ (a & c) ^ (b & c);
        let t2: u32 = s0.wrapping_add(maj);
        h = g;
        g = f;
        f = e;
        e = d.wrapping_add(t1);
        d = c;
        c = b;
        b = a;
        a = t1.wrapping_add(t2);
    }
    state[0] = state[0].wrapping_add(a);
    state[1] = state[1].wrapping_add(b);
    state[2] = state[2].wrapping_add(c);
    state[3] = state[3].wrapping_add(d);
    state[4] = state[4].wrapping_add(e);
    state[5] = state[5].wrapping_add(f);
    state[6] = state[6].wrapping_add(g);
    state[7] = state[7].wrapping_add(h);
}

/// Formats `value` as ASCII base-10 digits into a stack buffer without heap allocation.
///
/// # Arguments
///
/// - `u64` - Unsigned integer to format.
/// - `&mut [u8; U64_STACK_BUF_LEN]` - Stack scratch buffer.
///
/// # Returns
///
/// - `&[u8]` - Borrowed ASCII decimal digit slice.
#[inline(always)]
pub(crate) fn format_u64_bytes(mut value: u64, buf: &mut [u8; U64_STACK_BUF_LEN]) -> &[u8] {
    if value == 0 {
        buf[U64_STACK_BUF_LEN - 1] = ASCII_ZERO;
        return &buf[U64_STACK_BUF_LEN - 1..];
    }
    let mut pos: usize = U64_STACK_BUF_LEN;
    while value > 0 {
        pos -= 1;
        buf[pos] = ASCII_ZERO + ((value % 10) as u8);
        value /= 10;
    }
    &buf[pos..]
}

/// Computes the canonical 64-byte ASCII hex SHA-256 digest for audit fields without heap allocation.
///
/// # Arguments
///
/// - `(u64, u64, usize)` - Tuple `(sequence, timestamp_ms, status_code)`.
/// - `&[u8]` - Previous record hash ASCII bytes.
/// - `(&str, &str)` - Tuple `(method, path)`.
/// - `(&str, &str, &str)` - Tuple `(actor, action, request_id)`.
///
/// # Returns
///
/// - `[u8; 64]` - 64-byte lowercase hexadecimal ASCII SHA-256 digest.
#[inline]
pub(crate) fn compute_record_hash_bytes(
    meta: (u64, u64, usize),
    prev_hash: &[u8],
    req: (&str, &str),
    ctx_fields: (&str, &str, &str),
) -> [u8; 64] {
    let (sequence, timestamp_ms, status_code): (u64, u64, usize) = meta;
    let (method, path): (&str, &str) = req;
    let (actor, action, request_id): (&str, &str, &str) = ctx_fields;
    let mut hasher: AuditSha256 = AuditSha256::new();
    let mut num_buf: [u8; U64_STACK_BUF_LEN] = [0u8; U64_STACK_BUF_LEN];
    hasher.update(format_u64_bytes(sequence, &mut num_buf));
    hasher.update_byte(AUDIT_FIELD_SEP);
    hasher.update(format_u64_bytes(timestamp_ms, &mut num_buf));
    hasher.update_byte(AUDIT_FIELD_SEP);
    hasher.update(prev_hash);
    hasher.update_byte(AUDIT_FIELD_SEP);
    hasher.update(method.as_bytes());
    hasher.update_byte(AUDIT_FIELD_SEP);
    hasher.update(path.as_bytes());
    hasher.update_byte(AUDIT_FIELD_SEP);
    hasher.update(format_u64_bytes(status_code as u64, &mut num_buf));
    hasher.update_byte(AUDIT_FIELD_SEP);
    hasher.update(actor.as_bytes());
    hasher.update_byte(AUDIT_FIELD_SEP);
    hasher.update(action.as_bytes());
    hasher.update_byte(AUDIT_FIELD_SEP);
    hasher.update(request_id.as_bytes());
    hasher.finalize_hex()
}

/// Computes the canonical hash-chain digest for an [`AuditRecord`] given its fields.
///
/// # Arguments
///
/// - `&AuditRecord` - Audit record whose `entry_hash` is computed.
///
/// # Returns
///
/// - `String` - 64-character lowercase hex SHA-256 chain hash.
pub fn compute_record_hash(record: &AuditRecord) -> String {
    let digest: [u8; 64] = compute_record_hash_bytes(
        (
            record.get_sequence(),
            record.get_timestamp_ms(),
            record.get_status_code(),
        ),
        record.get_prev_hash().as_bytes(),
        (record.get_method(), record.get_path()),
        (
            record.get_actor(),
            record.get_action(),
            record.get_request_id(),
        ),
    );
    from_utf8(&digest).unwrap_or_default().to_owned()
}

/// Verifies cryptographic hash-chain integrity across an ordered slice of [`AuditRecord`]s.
///
/// # Arguments
///
/// - `&[AuditRecord]` - Ordered slice of consecutive audit records.
///
/// # Returns
///
/// - `bool` - `true` iff every record's `entry_hash` and `prev_hash` link are cryptographically valid.
pub fn verify_audit_chain(records: &[AuditRecord]) -> bool {
    let mut expected_prev: Option<&str> = None;
    for rec in records {
        if let Some(prev) = expected_prev
            && rec.get_prev_hash().as_str() != prev
        {
            return false;
        }
        let recomputed: String = compute_record_hash(rec);
        if recomputed != *rec.get_entry_hash() {
            return false;
        }
        expected_prev = Some(rec.get_entry_hash().as_str());
    }
    true
}

/// Returns current Unix timestamp in milliseconds.
///
/// # Returns
///
/// - `u64` - Milliseconds since Unix epoch.
#[inline]
pub(crate) fn current_unix_ms() -> u64 {
    match SystemTime::now().duration_since(UNIX_EPOCH) {
        Ok(d) => d.as_millis() as u64,
        Err(_) => 0,
    }
}

/// Normalizes a path prefix by ensuring a leading `/` and trimming trailing `/`.
///
/// # Arguments
///
/// - `&str` - Raw prefix path.
///
/// # Returns
///
/// - `String` - Normalized prefix.
pub(crate) fn normalize_prefix(raw: &str) -> String {
    let trimmed: &str = raw.trim().trim_end_matches('/');
    if trimmed.is_empty() || trimmed == ROOT_SLASH {
        return ROOT_SLASH.to_owned();
    }
    if trimmed.starts_with('/') {
        trimmed.to_owned()
    } else {
        format!("/{trimmed}")
    }
}

/// Reports whether `path` matches `prefix` on a segment boundary.
///
/// # Arguments
///
/// - `&str` - Incoming request path.
/// - `&str` - Normalized path prefix.
///
/// # Returns
///
/// - `bool` - `true` when matched.
#[inline]
pub(crate) fn path_matches_prefix(path: &str, prefix: &str) -> bool {
    if prefix == ROOT_SLASH {
        return true;
    }
    if let Some(rest) = path.strip_prefix(prefix) {
        rest.is_empty() || rest.starts_with('/')
    } else {
        false
    }
}

/// Reports whether `method` is a state-mutating HTTP method.
///
/// # Arguments
///
/// - `&Method` - HTTP method.
///
/// # Returns
///
/// - `bool` - `true` for non-safe methods (`POST`, `PUT`, `PATCH`, `DELETE`, etc.).
#[inline(always)]
pub(crate) fn is_mutating_method(method: &Method) -> bool {
    !method.is_get() && !method.is_head() && !method.is_options()
}

/// Attaches an authenticated actor identifier to `ctx` for audit trail attribution.
///
/// # Arguments
///
/// - `&mut Context` - Active Hyperlane context.
/// - `S` - Actor/user/service identifier.
pub fn set_audit_actor<S>(ctx: &mut Context, actor: S)
where
    S: Into<String>,
{
    ctx.set_attribute(ATTR_AUDIT_ACTOR, actor.into());
}

/// Attaches a semantic action name (for example `"billing.refund"`) to `ctx`.
///
/// # Arguments
///
/// - `&mut Context` - Active Hyperlane context.
/// - `S` - Semantic action label.
pub fn set_audit_action<S>(ctx: &mut Context, action: S)
where
    S: Into<String>,
{
    ctx.set_attribute(ATTR_AUDIT_ACTION, action.into());
}