actixutils

middleware — Overview

actixutils::middleware is a collection of independent, composable Actix Web middleware components. Each one solves a single cross-cutting HTTP concern (authentication, rate limiting, request coalescing, sessions, pagination, request tracing, authorization, idempotency, timeouts, client-IP resolution, timing-attack mitigation) and they are designed to be mixed and matched per route, per scope, or per app rather than adopted as an all-or-nothing framework.

Design philosophy

Every middleware in this module follows the same shape: a lightweight configuration struct (e.g. RateLimiter, Auth<T>) implements Actix’s Transform trait, which produces a per-worker service wrapper that does the actual request interception. Where a piece of state needs to be shared beyond the middleware itself (a store trait, a task-local snapshot, a plain data struct), it lives in crate::locals. Some of those items are re-exported from middleware for convenience (Pagination, Context, GetId). This keeps the “how do I configure it” surface (middleware) separate from the “what shape is the data” surface (locals).

Everything that handlers pull out of the request via FromRequest lives in crate::extractors: Jwt<T>, Session<T>, ReadSession<T>, Filters, and ClientIp. Their Transform-based counterparts (Auth<T>, SessionMiddleware<T>, PathParams, ClientIpMiddleware) live here.

Two related but distinct patterns show up repeatedly:

Middleware catalog

Middleware Purpose Backing state
Auth<T> Validates a Bearer JWT (header or access_token cookie) once per request, stores claims of type T in request extensions Arc<dyn Validate<T>> you supply
ResponseEqualizer Pads every response to a minimum duration (+ optional jitter) to blunt timing-attack information leaks none (stateless)
RateLimiter<T> Sliding-window, per-identity request limiting; returns 429 when exceeded Arc<dyn ferrumec::Store<T::Id, VecDeque<Instant>>> you supply
Idempotency<S> Caches responses by an Idempotency-Key header so retried mutations aren’t re-executed Arc<S> where S: locals::IdempotencyStore
Singleflight<K, KeyFn> Coalesces concurrent requests mapping to the same key into a single execution, cloning the result to all waiters in-process HashMap behind a mutex
TimeoutMiddleware Races the wrapped service against a fixed Duration; returns 504 Gateway Timeout on expiry none (stateless)
ClientIpMiddleware Resolves the real client IP, trusting X-Forwarded-For only from configured proxy networks locals::ProxyConfig (trusted CIDR list)
PathParams Merges matched path parameters on top of the query-string Filters map writes extractors::Filters into extensions
RequestId Generates a UUIDv4 per request, records it on the tracing span, adds X-Request-Id to the response none; writes RequestIdStr to extensions
ReadContext<T> Builds a per-request event-publishing Context (request id + user id + event stream handle) Arc<dyn ferrumec::EventStream> you supply
PaginationMiddleware Parses ?page=&limit= and exposes it via a task-local Tokio task-local
SessionMiddleware<T> Cookie-based, server-side sessions with dirty tracking; creates a session when none exists (or 401 with .required()) Arc<dyn ferrumec::Store<Uuid, T>> you supply
RequiredSession<T> Cookie-based sessions that must already exist; otherwise 401 Arc<dyn ferrumec::Store<Uuid, T>> you supply
AttachLocal<T> Generic building block: extracts a T and scopes the rest of the request inside T::scope(...) whatever T::scope scopes
identity / authority(bit) (feature jwt) from_fn-style functions that gate on a valid Identity / Authority JWT delegates to the Jwt<T> extractor

Module layout

middleware/
├── mod.rs              # re-exports and module-level docs
├── attach_local.rs     → AttachLocal<T>, SetLocal
├── auth.rs             → Auth<T>
├── client_ip.rs        → ClientIpMiddleware   (extractor: extractors::ClientIp)
├── coalesce.rs         → Singleflight<K, KeyFn>
├── constant_time.rs    → ResponseEqualizer
├── context.rs          → Context, ReadContext<T>
├── fns.rs              → identity, authority()   (feature = "jwt")
├── idempotency.rs      → Idempotency<S>
├── pagination.rs       → Pagination, PaginationMiddleware
├── path_params.rs      → PathParams
├── rate_limiter.rs     → RateLimiter<T>
├── request_id.rs       → RequestId, RequestIdStr
├── required_session.rs → RequiredSession<T>   (extractor: extractors::Session<T>)
├── session.rs          → SessionMiddleware<T> (extractor: extractors::Session<T>)
├── timeout.rs          → TimeoutMiddleware
├── test_coalesce.rs    # tests for Singleflight
└── test_session.rs     # tests for sessions (cfg(test)); in-memory Store example

Only fns is feature-gated here (jwt, because it uses the Jwt<T> extractor). Auth<T> is always compiled; it only needs a Validate<T> implementation, which HS256Signer and RS256Validator provide when jwt is on.

Ordering matters

Several middleware read state that another middleware wrote into request extensions, so registration order is significant. In Actix, the last .wrap() call is the outermost layer and runs first. Read a stack written top to bottom in code as “innermost first”.

  1. RequestId should generally be outermost. ReadContext<T> requires RequestIdStr to already be present.
  2. ClientIpMiddleware must run before anything that keys off extractors::ClientIp (for example RateLimiter<ClientIp>). The extractor returns 500 if the middleware never ran, and ClientIpMiddleware inserts nothing when the connection has no peer address.
  3. An auth middleware (Auth<T>, a session middleware, or the Jwt<T> extractor via identity/authority) must run before anything that reads the resulting principal: ReadContext<T>, RateLimiter<T> when keyed on an authenticated identity, and authority(bit).
  4. ReadContext<T> depends on both (1) and (3) having populated extensions. T must implement locals::GetId and be in extensions (Identity and Authority already qualify).
  5. PathParams must run before any handler that reads Filters and expects path segments included. Path parameters are only visible once the route has been matched, so prefer attaching it at the resource or scope that owns the dynamic segments.

A typical stack, outermost first:

RequestId → ClientIpMiddleware → Auth<Identity> → ReadContext<Identity> → handler

In code that is written in reverse:

web::scope("/api")
    .wrap(ReadContext::<Identity>::new(event_stream, "svc".into()))
    .wrap(Auth { validator })
    .wrap(ClientIpMiddleware::new(proxy_config))
    .wrap(RequestId)

Behaviour worth knowing

When to reach for which middleware

See TUTORIALS for a walkthrough of assembling several of these into a service, and EXAMPLES for focused, copy-pasteable snippets for each middleware.