Are you an LLM? Read llms.txt for a summary of the docs, or llms-full.txt for the full context.
Skip to content

Security

Security is one of Ultimo's two core pillars (with performance). The framework is secure by default, follows defense in depth, and aims to be provable (audited, no unsafe, public disclosure policy).

100% Safe Rust

The framework enforces #![forbid(unsafe_code)] — there is zero unsafe in Ultimo. Combined with Rust's guarantees, that rules out memory-safety bugs (buffer overflows, use-after-free, data races) in the framework itself.

Security headers

Add secure-by-default response headers with one line:

use ultimo::middleware::builtin::security_headers;
 
app.use_middleware(security_headers());

Sets HSTS, X-Content-Type-Options: nosniff, X-Frame-Options: DENY, Referrer-Policy, and a restrictive Permissions-Policy. Content-Security-Policy is opt-in (a wrong CSP breaks more than it protects). Headers are applied only if the handler didn't already set them, so per-route overrides win. Customize:

use ultimo::middleware::builtin::SecurityHeaders;
 
app.use_middleware(
    SecurityHeaders::new()
        .csp("default-src 'self'")
        .frame_options("SAMEORIGIN")
        .build(),
);

Request body-size limit

Cap request bodies to reject oversized payloads (DoS protection) with 413:

app.max_body_size(2 * 1024 * 1024); // 2 MB

On the live server an oversized body is never fully buffered. No limit by default — set one in production.

Client IP & trusted proxies

let ip = ctx.client_ip();   // Option<IpAddr> — best-effort originating client
let peer = ctx.peer_addr(); // Option<SocketAddr> — direct connection peer

By default client_ip() returns the connection peer. Behind a trusted proxy/load balancer, enable header trust so it honors X-Forwarded-For (leftmost) then Forwarded: for=:

app.trust_proxy(true); // ONLY behind a trusted proxy

IP allow/deny (CIDR filtering)

Block or allow requests by client IP using CIDR notation. Respects trust_proxy when enabled.

use ultimo::middleware::builtin::IpFilter;
 
// Allow only private networks + localhost:
app.use_middleware(IpFilter::allow(&[
    "10.0.0.0/8",
    "172.16.0.0/12",
    "192.168.0.0/16",
    "127.0.0.1",
    "::1",
]).build());
 
// Or deny specific ranges:
app.use_middleware(IpFilter::deny(&["203.0.113.0/24"]).build());

Denied requests receive a 403 Forbidden response. Supports IPv4 and IPv6, bare IPs (treated as /32 or /128), and any valid prefix length.

Request guards (custom rules)

Guard runs your own predicate on every request, before it reaches a handler — a lightweight in-app "WAF-lite" hook for rules on IP, path, user agent, headers or anything else on the Context:

use ultimo::guard::{Decision, Guard};
 
// Block well-known scanners.
app.use_middleware(
    Guard::new(|ctx: &Context| {
        let ua = ctx.req.header("user-agent").unwrap_or_default();
        Decision::deny_if(ua.contains("sqlmap") || ua.contains("nikto"))
    })
    .build(),
);
 
// Hide /admin (answer 404) unless the request carries the internal header.
app.use_middleware(
    Guard::new(|ctx: &Context| {
        if ctx.req.path().starts_with("/admin") && ctx.req.header("x-internal").is_none() {
            Decision::respond(404, "Not Found")
        } else {
            Decision::Allow
        }
    })
    .build(),
);
DecisionEffect
Decision::AllowContinue to the next middleware and the handler
Decision::Deny403 Forbidden (change with .deny_status(status, body))
Decision::respond(status, b)Answer with that status and plain-text body

Decision::deny_if(cond) and Decision::allow_if(cond) turn a boolean into a decision. Guard, Decision and GeoFilter live in ultimo::guard and are also available from ultimo::middleware::builtin, next to IpFilter. The predicate is synchronous and runs on every request, so keep it cheap; register several guards for several rules (they run in order). Blocked requests are logged at debug level with the path and client IP. For checks that need I/O (a database blocklist, say), write a custom middleware instead.

Geo-blocking

GeoFilter allows or blocks countries (ISO 3166-1 alpha-2 codes, compared case-insensitively). Ultimo bundles no GeoIP database — the country comes from your CDN or from a lookup you supply:

use ultimo::guard::GeoFilter;
 
// Behind Cloudflare: use its country header.
app.trust_proxy(true);
app.use_middleware(GeoFilter::allow(&["US", "CA"]).header("CF-IPCountry").build());
 
// Or resolve the client IP yourself, e.g. with a MaxMind GeoLite2 reader.
app.use_middleware(
    GeoFilter::deny(&["KP"])
        .lookup(move |ip| reader.lookup_country(ip)) // -> Option<String>
        .build(),
);
  • The header is read only when app.trust_proxy(true). Without a proxy in front, any client could send CF-IPCountry: US and walk through an allow-list. Common headers: CF-IPCountry (Cloudflare), CloudFront-Viewer-Country (AWS CloudFront), X-Vercel-IP-Country (Vercel).
  • With both .header(...) and .lookup(...), the header wins and the lookup is the fallback (it receives client_ip()).
  • Unknown country (no header, lookup returns None, or Cloudflare's XX): denied on an allow-list, allowed on a deny-list. Override with .allow_unknown() / .deny_unknown().
  • Blocked requests get 403 Forbidden. Handlers can read the resolved country with ctx.country().await (Option<String>, e.g. Some("US")).

Sessions & cookies

Cookie-based sessions are secure by default (HttpOnly, Secure, SameSite, 256-bit ids, anti session-fixation, server-side storage). See Sessions.

CSRF protection

The csrf feature provides double-submit cookie CSRF protection. The middleware issues a random token in a (non-HttpOnly) cookie; on unsafe methods (POST/PUT/PATCH/DELETE) the request must echo that token in a header, and the two are compared in constant time (mismatch → 403). Safe methods are exempt.

// Cargo.toml: ultimo = { version = "0.10", features = ["csrf"] }
app.use_middleware(ultimo::csrf::csrf());
 
// or customized:
app.use_middleware(
    ultimo::csrf::Csrf::new()
        .header_name("x-csrf-token")
        .same_site(ultimo::cookie::SameSite::Strict)
        .build(),
);

The frontend reads the csrf_token cookie and sends it back as the x-csrf-token header:

const token = document.cookie.split('; ')
  .find((c) => c.startsWith('csrf_token='))?.split('=')[1];
await fetch('/api/action', { method: 'POST', headers: { 'x-csrf-token': token } });

See the session-auth example for a working login flow with CSRF.

Supply chain

  • cargo audit (RUSTSEC advisories) runs in CI on every PR.
  • cargo deny gates advisories, banned/duplicate deps, and source pinning.
  • Cargo.lock is committed for reproducible builds.
  • cargo-semver-checks guards the public API against accidental breakage.
  • Minimal dependency surface (the WebSocket layer is zero-dependency).

Defense in depth

For production, deploy Ultimo behind a managed WAF/CDN (Cloudflare, AWS WAF, …) for full WAF rules, DDoS mitigation, and geo controls. Ultimo provides the in-app building blocks; the edge handles volumetric and signature-based threats.

Reporting a vulnerability

Please report privately — see SECURITY.md (GitHub Security Advisories). Do not open a public issue for vulnerabilities.

Roadmap

Auth middleware (JWT, API keys, OIDC, OAuth2 login), authorization guards, IP allow/deny, request guards and geo-blocking have all shipped. See the roadmap for what's next.