middleware — Overviewactixutils::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.
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:
req.extensions_mut() so
downstream handlers can pull it out with HttpMessage::extensions() or a
FromRequest extractor. Used by Auth<T>, RequestId, SessionMiddleware<T>,
RequiredSession<T>, ReadContext<T>, ClientIpMiddleware, and PathParams.PaginationMiddleware and the generic
AttachLocal<T>.| 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 |
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.
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”.
RequestId should generally be outermost. ReadContext<T> requires
RequestIdStr to already be present.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.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).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).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)
RateLimiter lets a request through unlimited when its key extractor
fails (no valid token, no client IP). It reads and writes the store in two
steps, so concurrent requests from one identity can slightly exceed the
limit. For strict limits across nodes use a shared store with atomic updates.Idempotency caches every completed response, including 4xx and 5xx,
and keys on the header value alone (not per user or route). A repeat while the
first request is running gets 409 Conflict. Response headers that are not
valid UTF-8 are dropped from the cached copy.Singleflight buffers the whole response body, so use it on bounded,
non-streaming reads. If the leading request fails, panics, or is cancelled,
waiting followers receive an error rather than hanging.TimeoutMiddleware drops the in-flight future at the deadline, so any
side effects the handler already performed are not rolled back.ResponseEqualizer pads only responses that come back as Ok. An error
returned by an inner middleware skips the padding.PaginationMiddleware falls back to page = 0, limit = 100 on missing or
unparseable values and does not cap limit. Pagination::offset() is
page * limit in u32, so clamp both before building queries.SessionMiddleware only writes to the store when a handler calls
Session::write(). The one exception is a request with no session cookie at
all: its fresh session is saved once so the cookie it receives refers to a
real entry. (A cookie that is present but not a valid UUID gets a new cookie
without an initial save, so nothing is stored until a handler writes.)Auth<T>.ResponseEqualizer.RateLimiter<T>.Idempotency<S>.Singleflight<K, KeyFn>.TimeoutMiddleware.ClientIpMiddleware (paired with the ClientIp extractor).PathParams.RequestId.ReadContext<T>.?page=&limit= without threading params through
every layer → PaginationMiddleware.SessionMiddleware<T> or RequiredSession<T> with Session<T>/ReadSession<T>.AttachLocal<T>.authority(bit) /
identity from fns.rs.See TUTORIALS for a walkthrough of assembling several of these into a service, and EXAMPLES for focused, copy-pasteable snippets for each middleware.