orion-server 1.0.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
//! Per-request context carried in a task-local, for code that runs deep
//! inside a handler and has no `Request` to extract from.
//!
//! Two consumers: `OrionError::IntoResponse` embeds `request_id` in the error
//! body so a client does not have to correlate header to body, and the audit
//! log records who did what *from where* (O7 — before this, an audit row had
//! no IP, no user-agent and no request id, so a mutation could not be tied to
//! the session that made it).

use axum::extract::{Request, State};
use axum::middleware::Next;
use axum::response::Response;

use crate::server::state::AppState;

/// The header carrying the client's user-agent, truncated at
/// [`MAX_USER_AGENT_LEN`] before it is stored.
const USER_AGENT: &str = "user-agent";

/// Longest user-agent string persisted in an audit row. Real agents are well
/// under 200 bytes; the cap exists because the value is attacker-controlled
/// and lands in a DB column and a log line.
const MAX_USER_AGENT_LEN: usize = 256;

/// Longest inbound `x-request-id` carried in the context. Same reasoning as
/// [`MAX_USER_AGENT_LEN`], and it applies for the same reason: `SetRequestIdLayer`
/// only *generates* an id when the header is absent, so a caller that sends one
/// controls this string end to end — 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.
const MAX_REQUEST_ID_LEN: usize = 200;

/// 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 as [`MAX_USER_AGENT_LEN`].
const CHANGE_CONTEXT: &str = "x-orion-change-context";
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()
}

/// A header's value, truncated to `max_len` bytes. `None` when absent, empty
/// or non-ASCII — `HeaderValue::to_str` only succeeds for visible ASCII, so
/// every char is one byte and the slice is always on a char boundary.
fn ascii_header(req: &Request, name: &str, max_len: usize) -> Option<String> {
    req.headers()
        .get(name)
        .and_then(|v| v.to_str().ok())
        .filter(|v| !v.is_empty())
        .map(|v| v[..v.len().min(max_len)].to_string())
}

/// Middleware that scopes the per-request task-local [`REQUEST_CONTEXT`].
///
/// Must run inside `SetRequestIdLayer` so the `x-request-id` header is already
/// populated when we read it, and it takes `State` because resolving the
/// client address honestly needs the trusted-proxy list.
pub async fn request_context_scope(
    State(state): State<AppState>,
    req: Request,
    next: Next,
) -> Response {
    // Same ASCII/byte-boundary reasoning as `ascii_header`, spelled inline
    // because the request id keeps an empty-string (not None) representation.
    let request_id = req
        .headers()
        .get("x-request-id")
        .and_then(|v| v.to_str().ok())
        .map(|v| &v[..v.len().min(MAX_REQUEST_ID_LEN)])
        .unwrap_or("")
        .to_string();
    let user_agent = ascii_header(&req, USER_AGENT, MAX_USER_AGENT_LEN);
    let change_context = ascii_header(&req, CHANGE_CONTEXT, MAX_CHANGE_CONTEXT_LEN);
    let client_ip = crate::server::rate_limit::extract_client_ip(&req, state.trusted_proxies());
    let ctx = RequestContext {
        request_id,
        client_ip,
        user_agent,
        change_context,
    };
    REQUEST_CONTEXT.scope(ctx, next.run(req)).await
}

#[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;
    }
}