hyperlane-plugin-webhook 22.14.1

A production inbound HTTP webhook verification plugin for the Hyperlane framework featuring zero-allocation precomputed-midstate pure-Rust HMAC-SHA256 (Hex, Base64, and Stripe-style timestamped schemes), per-route secret rotation, timestamp skew enforcement, 64-shard bounded TTL replay-nonce caching, and verified WebhookEvent Context injection.
Documentation
use super::*;

/// Streaming FIPS 180-4 SHA-256 hasher with zero heap allocations.
#[derive(Clone)]
pub struct Sha256State {
    /// Eight 32-bit working hash state words.
    pub(crate) state: [u32; 8],
    /// Partial 64-byte input block accumulator.
    pub(crate) buf: [u8; 64],
    /// Number of valid bytes currently buffered in `buf`.
    pub(crate) buf_len: usize,
    /// Total message length absorbed in bytes.
    pub(crate) total_bytes: u64,
}

/// Precomputed HMAC-SHA256 key holding ipad and opad midstates for zero-allocation signing/verification.
#[derive(Clone)]
pub struct HmacSha256Key {
    /// SHA-256 state after compressing the 64-byte `key ^ 0x36` inner pad block.
    pub(crate) ipad_state: [u32; 8],
    /// SHA-256 state after compressing the 64-byte `key ^ 0x5c` outer pad block.
    pub(crate) opad_state: [u32; 8],
}

/// Named secret key participating in per-route webhook secret rotation.
#[derive(Clone, Data, Eq, PartialEq)]
pub struct WebhookSecret {
    /// Logical key identifier surfaced in [`WebhookEvent`] upon successful verification.
    pub(crate) id: String,
    /// Raw HMAC-SHA256 signing secret bytes.
    pub(crate) secret: Vec<u8>,
}

/// Verification rules for one inbound webhook route or prefix.
#[derive(Clone, Data, Debug, Eq, PartialEq)]
pub struct WebhookEndpoint {
    /// Route path or segment-bounded prefix (for example `"/webhooks/stripe"`).
    pub(crate) path_prefix: String,
    /// Request header carrying the webhook signature (stored lowercased).
    pub(crate) signature_header: String,
    /// Signature framing and encoding scheme.
    pub(crate) scheme: WebhookScheme,
    /// Active signing secrets checked in constant time for zero-downtime key rotation.
    pub(crate) secrets: Vec<WebhookSecret>,
    /// Optional separate Unix-seconds timestamp header for `Hex`/`Base64` schemes.
    #[get(type(clone))]
    pub(crate) timestamp_header: Option<String>,
    /// Optional separator when signing `<timestamp><sep><body>` with a separate `timestamp_header`.
    #[get(type(clone))]
    pub(crate) timestamp_payload_separator: Option<String>,
    /// Optional delivery nonce header (for example `X-GitHub-Delivery`) keyed into the replay cache.
    #[get(type(clone))]
    pub(crate) id_header: Option<String>,
    /// Maximum allowed absolute clock skew in seconds (`0` disables skew checks when no timestamp is required).
    #[get(type(copy))]
    pub(crate) tolerance_secs: u64,
    /// Replay-nonce retention TTL in seconds (`0` disables replay caching for this endpoint).
    #[get(type(copy))]
    pub(crate) replay_ttl_secs: u64,
    /// Maximum inbound body length in bytes accepted for verification.
    #[get(type(copy))]
    pub(crate) max_body_bytes: usize,
}

/// Top-level configuration for [`WebhookVerifier`] and [`WebhookPlugin`].
#[derive(Clone, Data, Debug, Eq, PartialEq)]
pub struct WebhookConfig {
    /// Configured webhook endpoints (matched longest-prefix first).
    pub(crate) endpoints: Vec<WebhookEndpoint>,
    /// Maximum tracked replay nonces across all 64 shards.
    #[get(type(copy))]
    pub(crate) replay_max_entries: usize,
}

/// Verified webhook delivery metadata injected into Hyperlane [`Context`] under [`ATTR_WEBHOOK_EVENT`].
#[derive(Clone, Data, Debug, Eq, PartialEq)]
pub struct WebhookEvent {
    /// Matched configured endpoint prefix.
    pub(crate) endpoint_prefix: String,
    /// Identifier of the active [`WebhookSecret`] that authenticated the payload.
    pub(crate) secret_id: String,
    /// Verified Unix epoch timestamp in seconds, when supplied by the scheme or timestamp header.
    #[get(type(copy))]
    pub(crate) timestamp: Option<u64>,
    /// Extracted delivery identifier header value, when present.
    #[get(type(clone))]
    pub(crate) delivery_id: Option<String>,
    /// Verified raw request body length in bytes.
    #[get(type(copy))]
    pub(crate) body_len: usize,
    /// Always `true` when produced by a passing verification.
    #[get(type(copy))]
    pub(crate) verified: bool,
}

/// Precompiled named secret with precomputed HMAC-SHA256 midstates.
#[derive(Clone)]
pub(crate) struct CompiledSecret {
    /// Logical key identifier.
    pub(crate) id: String,
    /// Precomputed zero-allocation HMAC-SHA256 key.
    pub(crate) key: HmacSha256Key,
}

/// Precompiled endpoint entry ready for hot-path verification.
#[derive(Clone)]
pub(crate) struct CompiledEndpoint {
    /// Normalized path prefix.
    pub(crate) prefix: String,
    /// Lowercased signature header name.
    pub(crate) signature_header: String,
    /// Signature framing scheme.
    pub(crate) scheme: WebhookScheme,
    /// Precompiled active signing secrets.
    pub(crate) secrets: Vec<CompiledSecret>,
    /// Optional lowercased separate timestamp header name.
    pub(crate) timestamp_header: Option<String>,
    /// Optional separator when signing `<timestamp><sep><body>`.
    pub(crate) timestamp_payload_separator: Option<String>,
    /// Optional lowercased delivery ID header name.
    pub(crate) id_header: Option<String>,
    /// Timestamp skew window in seconds.
    pub(crate) tolerance_secs: u64,
    /// Replay-nonce retention TTL in seconds.
    pub(crate) replay_ttl_secs: u64,
    /// Maximum accepted payload length in bytes.
    pub(crate) max_body_bytes: usize,
}

/// Shared interior state of the 64-way sharded bounded [`ReplayNonceCache`].
pub(crate) struct ReplayNonceCacheInner {
    /// Maximum tracked nonces across all 64 shards.
    pub(crate) max_entries: usize,
    /// Lock-free active entry count.
    pub(crate) count: AtomicUsize,
    /// 64-way lock-striped digest tables.
    pub(crate) shards: ReplayShardArray,
}

/// High-concurrency 64-way sharded bounded TTL replay-nonce cache.
#[derive(Clone)]
pub struct ReplayNonceCache {
    /// Shared sharded cache state.
    pub(crate) inner: Arc<ReplayNonceCacheInner>,
}

/// Compiled inbound webhook verification engine backing [`WebhookPlugin`].
#[derive(Clone)]
pub struct WebhookVerifier {
    /// Precompiled endpoints sorted longest-prefix first.
    pub(crate) endpoints: Arc<Vec<CompiledEndpoint>>,
    /// 64-shard bounded replay-nonce cache.
    pub(crate) replay_cache: ReplayNonceCache,
    /// Prebuilt `401 Unauthorized` wire bytes.
    pub(crate) prebuilt_unauthorized_wire: ResponseData,
    /// Prebuilt `409 Conflict` wire bytes for detected replays.
    pub(crate) prebuilt_replay_wire: ResponseData,
    /// Prebuilt `413 Payload Too Large` wire bytes.
    pub(crate) prebuilt_too_large_wire: ResponseData,
}

/// Process-wide [`WebhookPlugin`] singleton holding a [`WebhookVerifier`].
#[derive(Clone)]
pub struct WebhookPlugin {
    /// Compiled webhook verifier.
    pub(crate) verifier: WebhookVerifier,
}

/// Opt-in request middleware verifying inbound webhook signatures and injecting [`WebhookEvent`].
#[derive(Clone, Copy, Debug, Default)]
#[hyperlane::request_middleware(-58)]
pub struct WebhookHook;