hyperlane-plugin-session 22.14.0

A high-concurrency sharded session management plugin for the Hyperlane framework with pluggable async SessionStore traits, optional HMAC-SHA256 signed cookies, dirty-tracked zero-write reads, and session-fixation ID regeneration.
Documentation
use super::*;

/// Configuration controlling cookie attributes, signing, TTL, and capacity for [`SessionPlugin`].
#[derive(Clone, Data, Debug, Eq, PartialEq)]
pub struct SessionConfig {
    /// Cookie name carrying the session token (default `"hyperlane_sid"`).
    pub(crate) cookie_name: String,
    /// Cookie `Path` attribute (default `"/"`).
    pub(crate) cookie_path: String,
    /// Optional cookie `Domain` attribute.
    #[get(type(clone))]
    pub(crate) cookie_domain: Option<String>,
    /// Cookie `SameSite` policy (`"Lax"`, `"Strict"`, `"None"`).
    pub(crate) same_site: String,
    /// Sets `HttpOnly` flag on session cookies when `true`.
    #[get(type(copy))]
    pub(crate) http_only: bool,
    /// Sets `Secure` flag on session cookies when `true`.
    #[get(type(copy))]
    pub(crate) secure: bool,
    /// Session idle TTL in seconds (also emitted as cookie `Max-Age`).
    #[get(type(copy))]
    pub(crate) ttl_secs: u64,
    /// Maximum active sessions allowed in the built-in [`InMemorySessionStore`].
    #[get(type(copy))]
    pub(crate) max_sessions: usize,
    /// Optional HMAC-SHA256 secret signing cookie values (`<sid>.<mac>`).
    #[get(type(clone))]
    pub(crate) signing_secret: Option<Vec<u8>>,
}

/// Mutable per-request session state tracking dirty writes, regeneration, and destruction.
#[derive(Clone, Debug)]
pub(crate) struct SessionState {
    /// Current session identifier.
    pub(crate) id: String,
    /// Previous session identifier deleted from the store after [`SessionHandle::regenerate_id`].
    pub(crate) previous_id: Option<String>,
    /// Shared copy-on-write key-value session attributes.
    pub(crate) values: Arc<HashMap<String, String>>,
    /// `true` when loaded from an existing persisted session.
    pub(crate) existed: bool,
    /// `true` when modified during this request (drives zero-write read optimization).
    pub(crate) dirty: bool,
    /// `true` when [`SessionHandle::destroy`] was called.
    pub(crate) destroyed: bool,
}

/// Precomputed SHA-256 ipad and opad midstates for zero-allocation session cookie HMAC.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) 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],
}

/// Shared per-request session handle interior combining a lock-free dirty flag and mutex-protected state.
#[derive(Debug)]
pub(crate) struct SessionHandleInner {
    /// Lock-free dirty flag enabling zero-lock zero-clone read-only response persistence checks.
    pub(crate) dirty: AtomicBool,
    /// Protected per-request session state.
    pub(crate) state: Mutex<SessionState>,
}

/// Thread-safe handle stored in Hyperlane [`Context`] allowing handlers to read and mutate the active session.
#[derive(Clone, Debug)]
pub struct SessionHandle {
    /// Shared per-request handle state.
    pub(crate) inner: Arc<SessionHandleInner>,
}

/// Internal record stored inside each shard of [`InMemorySessionStore`].
#[derive(Clone)]
pub(crate) struct StoredSession {
    /// Shared immutable snapshot of persisted key-value pairs for zero-clone reads.
    pub(crate) values: Arc<HashMap<String, String>>,
    /// Expiration Unix timestamp in seconds.
    pub(crate) expires_at_secs: u64,
}

/// Shared interior state of [`InMemorySessionStore`].
pub(crate) struct InMemorySessionStoreInner {
    /// Maximum tracked concurrent sessions across all shards.
    pub(crate) max_sessions: usize,
    /// Lock-free active session counter.
    pub(crate) count: AtomicUsize,
    /// 64-way lock-striped session tables.
    pub(crate) shards: SessionShardArray,
}

/// High-concurrency 64-way sharded bounded in-memory [`SessionStore`].
#[derive(Clone)]
pub struct InMemorySessionStore {
    /// Shared sharded store state.
    pub(crate) inner: Arc<InMemorySessionStoreInner>,
}

/// Precompiled cookie template and HMAC key states derived once from [`SessionConfig`].
#[derive(Clone, Debug)]
pub(crate) struct SessionCompiled {
    /// Precomputed HMAC-SHA256 midstates when signing is enabled.
    pub(crate) hmac_key: Option<HmacSha256Key>,
    /// Preformatted `"<cookie_name>="` prefix.
    pub(crate) cookie_prefix: String,
    /// Preformatted `"; Max-Age=...; Path=...; ..."` suffix matching `CookieBuilder::build`.
    pub(crate) cookie_suffix: String,
    /// Preformatted expiration `Set-Cookie` header string for cleared sessions.
    pub(crate) clear_cookie: String,
    /// Whether `CookieBuilder::try_build` accepted the configured name and attributes.
    pub(crate) valid_cookie_config: bool,
}

/// Process-wide [`SessionPlugin`] singleton storing [`SessionConfig`] and a pluggable [`SessionStore`].
#[derive(Clone)]
pub struct SessionPlugin {
    /// Cookie, signing, and TTL configuration.
    pub(crate) config: SessionConfig,
    /// Backing session store.
    pub(crate) store: SharedSessionStore,
    /// Precompiled HMAC key and `Set-Cookie` templates.
    pub(crate) compiled: Arc<SessionCompiled>,
    /// Optional direct handle to the built-in [`InMemorySessionStore`] bypassing boxed async futures.
    pub(crate) fast_store: Option<InMemorySessionStore>,
}

/// Opt-in request middleware loading the incoming session cookie into [`SessionHandle`].
#[derive(Clone, Copy, Debug, Default)]
#[hyperlane::request_middleware(-85)]
pub struct SessionRequestHook;

/// Opt-in response middleware persisting modified/regenerated/destroyed sessions and emitting `Set-Cookie`.
#[derive(Clone, Copy, Debug, Default)]
#[hyperlane::response_middleware(-70)]
pub struct SessionResponseHook;