Reusable middleware, extractors, and framework-agnostic building blocks for Actix Web 4: JWT authentication, cookie sessions, rate limiting, idempotency, request coalescing, pagination, request IDs, per-request timeouts, trusted-proxy client-IP resolution, bitmask permission checks, timing-attack mitigation, and event-publishing context propagation.
This project is pre-1.0 and still changing. Ideas for features and optimizations are welcome.
This documents the crate as it exists in src/. For a short introduction and
install instructions, start with the README.
The crate is split into three top-level modules, by whether an item depends on
actix-web:
| Module | Contains |
|---|---|
extractors |
Types implementing FromRequest: Jwt<T>, Session<T>, ReadSession<T>, Filters, ClientIp |
middleware |
Types implementing Transform: the full middleware suite |
locals |
Framework-agnostic pieces: claim structs, signing/validation traits, IdempotencyStore, ProxyConfig, task-local state |
Plus a standalone pubkey module for serving an RSA public key (see below).
The most commonly used items are re-exported at the crate root:
extractors: Jwt (feature jwt), Filters, Session, ReadSessionlocals: Authority, Identity, Provider, Sign, Validate, and
HS256Signer, RS256Signer, RS256Validator (feature jwt)ClientIp and every middleware type are not re-exported at the root; import
them through actixutils::extractors and actixutils::middleware.
| Flag | Enables |
|---|---|
jwt |
The Jwt<T> extractor, HS256Signer, RS256Signer/RS256Validator, and the identity/authority helper functions (pulls in jsonwebtoken) |
jwt is not enabled by default. Everything else is available without a flag,
including middleware::Auth<T> (it only needs some Validate<T>
implementation), sessions, rate limiting, idempotency, coalescing, timeouts,
client IP, pagination, request IDs, and Context/ReadContext.
ferrumec is a regular dependency, not an optional one. Its Store and
EventStream traits appear in the public API, so applications that use
sessions, rate limiting, or ReadContext should depend on ferrumec (0.5)
directly.
Requires the jwt feature.
use actix_web::{web, App, HttpResponse, HttpServer};
use actixutils::{HS256Signer, Identity, Jwt, Validate};
use std::sync::Arc;
#[actix_web::main]
async fn main() -> std::io::Result<()> {
let signer = Arc::new(HS256Signer::new(
"my-app".to_string(),
"super-secret-key".to_string(),
));
HttpServer::new(move || {
App::new()
.app_data(signer.clone() as Arc<dyn Validate<Identity>>)
.route("/protected", web::get().to(protected))
})
.bind("127.0.0.1:8080")?
.run()
.await
}
async fn protected(auth: Jwt<Identity>) -> HttpResponse {
HttpResponse::Ok().json(&auth.0)
}
The extractor looks up exactly Arc<dyn Validate<T>> in app data. Registering
it with web::Data::from(...) stores a different type (Data<dyn Validate<T>>)
that the extractor will not find, and every request would fail with 500.
Two independent ways to require a valid JWT, sharing the same signer or validator:
extractors::Jwt<T> (feature jwt): validates per handler. Add it as a
handler argument. If T is already in the request extensions it is cloned
and returned. Otherwise the bearer token is read from the Authorization
header (falling back to an access_token cookie) and validated via the
Arc<dyn Validate<T>> in app data. Errors: 500 if the validator is not
registered, 401 if the token is missing or invalid.middleware::Auth<T>: validates once per request via .wrap(...) and
stores the claims in the request extensions for every downstream handler and
middleware. Same token sources. If a T is already present, validation is
skipped. Construct it with a struct literal: Auth { validator }.Signers and validators (all feature jwt):
HS256Signer::new(aud, secret): symmetric HMAC-SHA-256. Implements both
Sign<T> and Validate<T>, so one instance can issue and verify its own tokens.RS256Signer::new(private_key, aud) / RS256Validator::new(public_key, aud):
asymmetric RSA-SHA-256. An auth service holds the private key and signs;
downstream services hold only the public key and verify. Both constructors
panic on an invalid PEM. Note the argument order differs from HS256Signer.
RS256Signer::default(aud, private_key) and
RS256Validator::default(aud, public_key) are swapped-order aliases.Validation requires the token’s aud claim to match the audience passed to the
validator, and enforces exp.
Claim structs (locals):
Identity: sub (user UUID), aud, iat, exp. Identity::new sets a
500-second expiry.Authority: adds role (a u128 permission bitmask) and rcpt (a
target resource or tenant UUID). Authority::check(perm_id) tests a bit;
perm_id must be below 128 (larger values overflow the shift and panic in
debug builds).middleware::{identity, authority} are Next-style functions for
actix_web::middleware::from_fn. identity requires a valid Identity;
authority(bit) requires a valid Authority whose role has that bit set
(401 if the token is bad, 403 if the bit is missing).
pubkey::configure serves a PEM key at GET /.well-known/public-key.pem,
read at call time from the validate.key environment variable. It panics if
the variable is unset. The name contains a dot, which most shells will not let
you export; set it with env 'validate.key=...' ./app or your process
manager. This is handy for RS256 downstream services that fetch the issuer’s
public key.
The crate ships no storage backends. Two trait families are involved:
| Trait | Defined in | Used by |
|---|---|---|
Store<K, V> |
ferrumec |
RateLimiter<T> (Store<T::Id, VecDeque<Instant>>), SessionMiddleware<T> and RequiredSession<T> (Store<Uuid, T>) |
IdempotencyStore |
actixutils::locals |
Idempotency<S> |
ferrumec::Store<K, V> is an #[async_trait] with four methods, get, set,
delete and clear, each returning Result<_, Box<dyn Error>>. You implement
it once per backend (in-memory, Redis, a database table) and reuse it. A
HashMap behind a lock is enough for a single process.
IdempotencyStore is a separate, TTL-aware trait (acquire, get,
complete, release) with its own associated Error type. It is not a
Store.
Cookie-based, server-side sessions are split across two modules:
extractors::Session<T> (also actixutils::Session): a FromRequest
handle to the current session. read()/write() return async RwLock
guards; any write() marks the session dirty.extractors::ReadSession<T> (also actixutils::ReadSession): an owned
read guard (OwnedRwLockReadGuard<T>) that derefs to T. Never marks the
session dirty.middleware::SessionMiddleware<T>: resolves the session cookie (default
name "session", change with .cookie_name(...)), loads and saves through an
Arc<dyn ferrumec::Store<Uuid, T>>, and persists dirty sessions after the
handler runs. T must be Default + Clone.
SessionMiddleware::new gives a request with no cookie, or an unparseable
one, a fresh default session and sets a new cookie on the response.SessionMiddleware::required instead rejects those requests with 401.
A well-formed cookie whose ID is not in the store still yields a default
session (it is only saved if a handler calls write()).middleware::RequiredSession<T>: always requires an existing session.
A missing cookie, an unparseable ID, or an ID not found in the store is
401 Unauthorized. T only needs Clone. Never creates sessions or sets cookies.The cookie set by SessionMiddleware has Path=/ and HttpOnly; there is no
Secure or SameSite attribute.
Handlers that use Session<T> or ReadSession<T> get a 500 if no session
middleware ran for the request.
| Middleware | What it does |
|---|---|
Auth<T> |
Validates a Bearer JWT (header or access_token cookie) and stores claims in request extensions |
ResponseEqualizer |
Pads every response to a minimum duration (optionally plus random jitter), mitigating timing side-channels on auth/lookup endpoints |
RateLimiter<T> |
Sliding-window per-identity rate limiting; keys on any extractor implementing locals::rate_limiter::GetId; backed by a caller-supplied ferrumec::Store |
Idempotency<S> |
Caches responses by an Idempotency-Key header to prevent duplicate mutations on retried requests; pluggable IdempotencyStore |
Singleflight<K, KeyFn> |
Request coalescing: concurrent requests that map to the same key share a single execution of the wrapped service |
TimeoutMiddleware |
Fails a request with 504 Gateway Timeout if it exceeds a fixed duration |
ClientIpMiddleware |
Resolves the real client IP from X-Forwarded-For, honouring a configured set of trusted proxy networks; exposed via the ClientIp extractor |
PathParams |
Merges matched path parameters into Filters, overlaying them on the query string |
RequestId / RequestIdStr |
Generates a UUIDv4 per request, records it in the tracing span, stores it in extensions, and returns it as X-Request-Id |
Context / ReadContext<T> |
Builds a per-request event-publishing context from the request ID and an identity’s UUID |
Pagination / PaginationMiddleware |
Parses ?page=&limit= into a task-local, readable anywhere via Pagination::get() |
SessionMiddleware<T> / RequiredSession<T> |
Cookie-based server-side sessions (see above) |
AttachLocal<T> / SetLocal |
Generic helper: extracts a T up front, then runs the rest of the request inside T::scope(...), the mechanism PaginationMiddleware-style task-locals are built on |
identity / authority(bit) |
from_fn guards for a valid Identity / an Authority with a given permission bit (feature jwt) |
Continue with the middleware overview, the tutorial, or the examples.
GetIdlocals::rate_limiter::GetId has an associated Id type and an id()
method. Implement it on an extractor to use that extractor as a
RateLimiter key. ClientIp implements it (Id = IpAddr).locals::GetId (also middleware::GetId) has a single get_id() -> Uuid
method. ReadContext<T> uses it to find the acting user. It is implemented
for Identity and Authority (returning sub).middleware::test_session (compiled only under #[cfg(test)]) contains an
in-memory ferrumec::Store<Uuid, T> and integration tests exercising
Session<T> / SessionMiddleware end to end, which makes it a useful reference
for writing your own store. middleware::test_coalesce holds the Singleflight
tests.
Several rustdoc examples use the jwt feature, so run the full suite with:
cargo test --all-features
MIT (see Cargo.toml).