Threat model
The boundary each layer enforces, and how it composes with your deployment's own controls.
The security layers nestrs ships cover a specific slice. They catch the bug classes that ship most often in business apps — forgotten filters, leaked fields, missing auth — and they catch them structurally, not by review. They do not cover everything a real production deployment must think about. This page lists what each layer covers, what it does not, and where the responsibility falls back on you.
What each layer catches
Section titled “What each layer catches”| Layer | Catches | Does not catch |
|---|---|---|
AuthnGuard + JwtStrategy | Missing, malformed, expired, unsigned-incorrectly tokens; against a JWK Set, a token naming an algorithm its key was not published for (HS*, none, another key type) | Stolen-but-unexpired tokens, replay before expiry, key compromise; a key an issuer withdrew from its JWK Set, until the set is refreshed — within about an hour while the issuer answers, an hour more while it does not |
OAuthClient | CSRF (state cookie), a cookie planted from a sibling subdomain (__Host-), code-interception (PKCE), SSRF on token exchange (no redirects) | Phishing the provider, malicious provider, callback URL takeover |
hash_password + burn_verify | Timing-based account enumeration via login | Slow GPU farms cracking dumped hashes, weak passwords, password reuse |
AbilityGuard | A class gate no ability reaches (the boot refuses), a malformed Ability (500), unauthenticated GraphQL/WS (UNAUTHENTICATED, the 401 class) | Logic bugs in your AbilityFactory itself |
Repo::scoped | Scope leakage on every read — handler cannot forget the filter, and no service holds a connection to forget it on | A named escape (Repo::unscoped, insert_unscoped, with_tombstones) used past the bar its rustdoc states; a select’s statement rewritten through query(); a job unit a feature opens on a task of its own |
#[authorize(A, bind = S)] | Cross-tenant by-id reads (403) and missing rows (404) | Handlers that fetch by id without binding the subject and skip access |
The judged row (#[expose]) | Leak of an unexposed column or of one a field grant withholds, in every shape that carries the row, on every edge; a row kept in a cache or carried to another caller (500) | A column a body copies into a value of its own — a DTO filled from a row, a hand-built serde_json::Value — which ships as written: that body’s visible line, read in review |
ThrottlerGuard | Brute-force login, naïve enumeration scrapes | DDoS at network or HTTP layer (use a CDN / edge throttler) |
| Browser-origin check | Cross-site WebSocket hijacking and a cross-site call to MCP: a page on another origin opening a gateway or GraphQL socket, or posting to /mcp, under its visitor’s credentials — 403, CORS on or off; once CORS is set, any origin it does not list, the server’s own included | A client that is no browser, which sends no Origin and authenticates like any other; DNS rebinding, which <PREFIX>_MCP__ALLOWED_HOSTS covers for MCP |
| Connection deadlines | A client holding connections it does not use: a head sent a byte at a time, a TLS handshake never finished, an idle socket, a peer that stops reading | Many clients each staying inside the deadlines (the connection cap holds them back; a CDN sheds them) |
| MCP session binding | A caller with a valid token of its own and another principal’s session id: posting into the session, opening or resuming its stream, closing it — 404, as for a session the endpoint does not hold, here and on an instance restoring it from a SessionStore | A public endpoint’s sessions, which authenticate no one; two principals sharing one actor id and one tenant |
| MCP session cap | A client opening MCP sessions in a loop, each holding a worker until it idles out — 503 with Retry-After past the cap, an idle session closed after its timeout | Many callers sharing the cap, which is per endpoint and not per caller (a throttler holds one caller back). On an endpoint McpAccess::Public opens, no guard runs at the request, so no throttler meters its sessions: <PREFIX>_MCP__LEGACY_SESSION_MODE=false or a proxy’s limit does. |
What the framework dials
Section titled “What the framework dials”Every URL a framework client dials follows one plaintext rule: plaintext where the protocol’s own URL declares it, refused where the governing standard requires TLS. The rule is held where the client is built, so a call site cannot open a door the configuration kept shut.
| Client | Where its URL comes from | Plaintext |
|---|---|---|
Postgres pool and EphemeralDatabase | <PREFIX>_SEAORM__URL | only with sslmode=disable written in the URL, or libpq’s PGSSLMODE=disable beside a URL naming no mode; any other mode short of verify-full is refused |
| Redis, all three topologies | <PREFIX>_REDIS__URL | only a URL whose scheme says it (redis://, redis-sentinel://, redis-cluster://); a #insecure fragment is refused |
| Storage | <PREFIX>_STORAGE__ENDPOINT | only with <PREFIX>_STORAGE__ALLOW_HTTP open: a declared development or test profile opens it by default, and true in any other is honoured and said at warn |
| JWK Set | <PREFIX>_AUTHN__JWKS_URI | refused when the module is built, and by the client on every fetch |
| OAuth token and userinfo endpoints | <PREFIX>_OAUTH__CLIENT__TOKEN_URL, USERINFO_URL | refused when the client is built (RFC 6749 §3.2), and by the client on every call |
OAuthClient::fetch | a provider’s code, at run time | refused before the call (RFC 6750 §5.3), and by the client whatever path reaches it |
| OAuth authorize and redirect URLs | <PREFIX>_OAUTH__CLIENT__AUTH_URL, REDIRECT_URL; followed by the browser, never dialled | the authorize URL never (RFC 6749 §3.1); the redirect only on a loopback address (RFC 8252 §7.3), in a declared development or test profile alone |
| GitHub and Google sign-in | the providers’ own constants | none: every endpoint is https |
| OTLP exporter | OTEL_EXPORTER_OTLP_ENDPOINT, and per signal OTEL_EXPORTER_OTLP_TRACES_ENDPOINT (_METRICS_, _LOGS_) | an http:// endpoint declares it, as OTLP/HTTP allows; TLS material set beside it is refused, and so are a header (OTEL_EXPORTER_OTLP_HEADERS, a collector’s credential) and a query in the endpoint unless the host is loopback (RFC 6750 §5.3), which is dialled past any proxy the environment names; userinfo, which no request carries, is refused in any endpoint |
A provider package building a URL at run time inherits the same rule: the
OAuth client speaks https alone, so a URL that slipped past every check
still never leaves the process in plaintext with a token on it.
A plaintext opening is a visible line. A deployed profile — staging, production,
or none declared — files one warn for each, naming the endpoint and never what
its URL carries: Postgres when the pool opens, Redis when each instance opens,
OTLP for each signal it exports, storage when the store opens, and a connection
you open yourself as SeaOrmConfig::connect_options builds its options, which
every Postgres opening goes through. What reaches this machine’s loopback or a socket crosses no network, the
common shape of a sidecar or an authenticating proxy, and says nothing; storage
alone says it there too,
since ALLOW_HTTP is a setting a deployment opts into anywhere, and a Sentinel or
Cluster URL says it whatever its hosts, since its link reaches a primary and nodes
the URL does not name.
Every client the framework opens verifies TLS
Section titled “Every client the framework opens verifies TLS”An encrypted connection the framework opens checks the server’s
certificate, every time: it chains to an authority the system’s store
holds, or to the ones a TLS_CA_CERT setting names in place of them
(for Postgres, the file its URL or libpq names, and sqlx keeps the
public authorities it compiles in beside either, as its row says), and
it names the host dialled. No setting, URL parameter or code path
turns the check off — the framework’s lints refuse the libraries’ own
switches in its code — and each client below has a test that dials a
server whose certificate a private authority signed and sees it refused
before any request, login or credential crosses.
| Client | Trusts | Private authority |
|---|---|---|
Postgres pool, connect_from_env, EphemeralDatabase | the system’s store, verify-full by default, and the public authorities sqlx compiles in | the file sslrootcert names in <PREFIX>_SEAORM__URL, or libpq’s PGSSLROOTCERT beside a URL naming none, in the store’s place and beside sqlx’s authorities |
| Redis, all three topologies | the system’s store, for a rediss:// URL | <PREFIX>_REDIS__TLS_CA_CERT |
| Storage | the system’s store, for an https:// endpoint | <PREFIX>_STORAGE__TLS_CA_CERT |
| JWK Set | the system’s store | <PREFIX>_AUTHN__TLS_CA_CERT |
| OAuth client | the system’s store | <PREFIX>_OAUTH__CLIENT__TLS_CA_CERT |
| GitHub and Google sign-in | the system’s store | none: both serve publicly trusted certificates |
| OTLP exporter | the system’s store, for an https:// endpoint | OTEL_EXPORTER_OTLP_CERTIFICATE, and per signal |
A client certificate goes to Postgres through the URL’s sslcert and
sslkey, which sqlx presents. The everyday development Postgres and CI’s
sign in by password, so the suite presenting one — and one omitting it,
refused at once — runs in a dev container environment of its own,
postgres-mutual-tls, by hand when the connection’s TLS changes.
A refused certificate fails the call or the boot — never a fallback to
an unverified connection. Redis, the JWK Set and the client
OAuthClientModule builds say which setting fixes it; a sign-in
provider’s client, whose URLs and trust no variable sets, keeps rustls’s
reason alone.
What the framework does not do
Section titled “What the framework does not do”These are out of scope on purpose. They matter, they belong in your deployment, and they are not part of the framework’s surface.
Token theft and replay before expiry
Section titled “Token theft and replay before expiry”A stolen JWT remains valid until exp. The framework’s mitigation is
short access tokens (default 1 hour, configurable via
JwtOptions::expires_in) paired with a refresh-token endpoint your
app exposes. Verification is stateless by design — no shared revocation
store on the hot path, so a resource server needs nothing but the public
key. Server-side revocation is a revoked_tokens table your Strategy
consults on verify, read through the same Repo as everything else.
The framework’s posture is bearer tokens, which are immune to
CSRF by construction (the browser does not auto-attach an
Authorization header). No nestrs credential rides a cookie, so the
framework ships no CSRF middleware. The one cookie it writes is the
OAuth transaction, read on the provider’s GET callback and held by
the state comparison (RFC 6749 §10.12), PKCE and its binding to one
provider; its __Host- prefix keeps a sibling subdomain from planting
it. Cookie-based sessions are not supported as a first-party
credential. If you bridge to one (an SSR layer that forwards cookies),
add CSRF protection at the bridge — Sec-Fetch-Site and Origin
checks, OWASP’s Fetch Metadata defence, are the current standard.
Key management
Section titled “Key management”EdDSA splits the issuer’s private key from every verifier’s public
key — see Split deployment.
Rotation, HSM integration, and secret-store wiring are not the
framework’s job. Treat <PREFIX>_AUTHN__PRIVATE_KEY as you would
treat any production secret: load it from a real secret store, never
commit it, rotate on a schedule. Against an external issuer’s JWK Set
(<PREFIX>_AUTHN__JWKS_URI), rotation is the issuer’s: a token signed by a
new key earns one refetch of the set, and a withdrawn key stops verifying once
the set is refreshed — see the
bounds.
TLS terminates either at your edge — the common production shape: CDN,
ingress, load balancer — or at the app itself, via
HttpConfig. The transport serves whichever you
configure and does not assume an edge it cannot see, so pick one and pin
it in your deployment checklist.
Network-level DDoS
Section titled “Network-level DDoS”The throttler is a per-handler guard, not a network defense. A real deployment fronts the app with a CDN, WAF, or rate-limiter that sheds load before the request reaches the process.
Cryptographic primitives
Section titled “Cryptographic primitives”The framework wraps jsonwebtoken,
argon2,
and oauth2. The
cryptographic correctness comes from those crates. The framework’s
job is to wire them correctly — call hash_password instead of
storing plaintext, verify_password instead of comparing strings,
JwtService::verify instead of decoding manually.
Defense in depth — what to layer
Section titled “Defense in depth — what to layer”For a production app:
- Bearer tokens with short TTL + refresh.
- EdDSA split between split deployments.
- Authz guards bound on every controller (negative-path tests catch the missing one).
- Exposure is opt-in — no
#[expose]on server-only columns. A column crosses the wire only when its field carries#[expose], so a forgotten or newly-migrated column is hidden, not leaked. Each wire row’s judgement is the second line for columns you do expose but restrict, covering them only when the field rule is.fields([...]). - CDN / WAF in front for DDoS and bot defense.
- Real secret store for
<PREFIX>_AUTHN__PRIVATE_KEY, OAuth secrets, DB credentials. - TLS terminated at the edge or at the app (
HttpConfig). - Logging at the right level.
nest_rs::authnandnest_rs::ormemitwarn+ on denials and security events — pipe them to your SIEM, do not silence them.
Going further
Section titled “Going further”- Security overview — the concept map.
- Negative-path tests — auth refused, cross-tenant denied, rollback verified.
- Throttler — per-handler rate limiting.