orion-server 1.4.0

Turn business logic into live REST/Kafka services. Declare workflows as JSON and Orion runs them, with rate limiting, circuit breakers, versioning, and observability built in
//! The per-request identity that code deep inside a handler reads without
//! having a `Request` to extract from.
//!
//! Two consumers, and neither is the HTTP layer: `OrionError::IntoResponse`
//! embeds `request_id` in the error body so a client does not have to
//! correlate header to body, and a channel's custom error body can interpolate
//! it. `errors` sits below `server` — every module in the tree produces an
//! `OrionError` — so reading the context out of `server::request_context` made
//! the error type depend on the HTTP layer.
//!
//! A parameter would be the obvious alternative, but `IntoResponse::into_response`
//! takes `self` and nothing else, so there is nowhere to put one. A task-local
//! is the right mechanism; it was only in the wrong place. The middleware that
//! *fills* it stays in [`crate::server::request_context`], where the `Request`
//! and the trusted-proxy policy are.

/// Longest inbound `x-request-id` carried in the context. The value is
/// attacker-controlled — `SetRequestIdLayer` only *generates* an id when the
/// header is absent, so a caller that sends one controls this string end to
/// end — and it is persisted in an audit row's `details` and echoed in
/// `error.request_id`. Generous next to the 36-byte UUID we generate, but
/// bounded. Truncating here does not change the response header, which
/// `PropagateRequestIdLayer` echoes verbatim.
pub(crate) const MAX_REQUEST_ID_LEN: usize = 200;

/// Longest user-agent string persisted in an audit row. Real agents are well
/// under 200 bytes; the cap exists for the same reason as
/// [`MAX_REQUEST_ID_LEN`].
pub(crate) const MAX_USER_AGENT_LEN: usize = 256;

/// The caller-supplied change context (K5): tooling stamps what a mutation
/// was part of — the packaging CLI sends `package=<name>@<version>` — and the
/// audit trail records it, making a multi-request apply reconstructible.
/// Free-form; same cap and reasoning.
pub(crate) const MAX_CHANGE_CONTEXT_LEN: usize = 256;

/// Request-scoped identity of the caller.
#[derive(Debug, Clone, Default)]
pub struct RequestContext {
    /// The `x-request-id` value (generated by `SetRequestIdLayer` when the
    /// client sends none), truncated at `MAX_REQUEST_ID_LEN`. Empty when the
    /// task-local was entered outside the middleware, e.g. a unit test.
    pub request_id: String,
    /// Client address, resolved with the same trusted-proxy policy the rate
    /// limiter uses: `X-Forwarded-For` / `X-Real-IP` are honoured only when
    /// the immediate peer is inside `rate_limit.trusted_proxies`. Without
    /// that, an audit row's IP would be whatever the caller typed.
    pub client_ip: String,
    /// The caller's `user-agent`, truncated. `None` when absent or non-ASCII.
    pub user_agent: Option<String>,
    /// The caller's `x-orion-change-context` header (K5), truncated. `None`
    /// when absent or non-ASCII. Recorded verbatim in audit `details`.
    pub change_context: Option<String>,
}

tokio::task_local! {
    pub static REQUEST_CONTEXT: RequestContext;
}

/// The current request id, or `None` outside a request scope.
pub fn request_id() -> Option<String> {
    REQUEST_CONTEXT
        .try_with(|ctx| ctx.request_id.clone())
        .ok()
        .filter(|id| !id.is_empty())
}

/// A clone of the current request context, or `None` outside a request scope.
pub fn current() -> Option<RequestContext> {
    REQUEST_CONTEXT.try_with(|ctx| ctx.clone()).ok()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn request_id_is_none_outside_a_scope() {
        assert!(request_id().is_none());
        assert!(current().is_none());
    }

    #[tokio::test]
    async fn empty_request_id_reads_as_absent() {
        let ctx = RequestContext::default();
        REQUEST_CONTEXT
            .scope(ctx, async {
                assert!(request_id().is_none(), "an empty id is not an id");
                assert!(current().is_some(), "the context itself is still in scope");
            })
            .await;
    }
}