|
Orbit Framework 2.0.0
A high-performance asynchronous C++20 HTTP server framework.
|
Middleware functions have access to the request object, the response writer, and can intercept or modify the flow of the application. They return a bool: true to continue to the next handler, false to halt execution (e.g., if the middleware already sent a response).
Use app.use() to apply middleware to every incoming request.
A middleware that computes something for later middleware or the handler — the authenticated user, a tenant, timing — has nowhere typed to put it beyond the few fixed HttpRequest fields (user, session, request_id). req.set<T>(value) / req.get<T>() / req.ensure<T>(args...) give it one, keyed by type, with no header or global needed:
set replaces any earlier one.get<T>() returns nullptr if nothing was set; ensure<T>(args...) constructs and stores one only if there is none yet, and always returns the same reference afterwards.T must be copy-constructible, as std::any requires. Wrap a move-only resource (a DB transaction handle) in a shared_ptr first.std::any itself needs for the value (none for a pointer, a shared_ptr, or another small type).req.context is the orbit::http::RequestContext these forward to, for code that takes a context by itself. It also has named string attributes (req.context.set_attr("tenant", id) / .attr("tenant")) for keys only known at runtime.orbit::middleware::session() gives every client a session and exposes it as req.session (and its identifier as req.session_id). Data is stored on the server; the client only holds an opaque HttpOnly cookie.
save_uninitialized = false creates no session (and sends no cookie) until something is written, so anonymous traffic and bots do not fill the store.orbit::middleware::SessionStore (load, save, touch, destroy) to keep sessions elsewhere, e.g. in a database.orbit::middleware::cors() with no arguments allows every origin (Access-Control-Allow-Origin: *) without credentials. To restrict origins, list them:
With an allow-list, only a listed Origin is echoed back in Access-Control-Allow-Origin, Vary: Origin is always sent so shared caches keep per-origin copies, and unlisted origins get no CORS headers (the browser then blocks the response). Preflights (OPTIONS with Access-Control-Request-Method) are answered with 204; other OPTIONS requests reach your routes. allow_credentials is ignored when allowed_origins contains "*", because allowing credentials from every origin would let any website act as the signed-in user.
orbit::middleware::jwt_auth() verifies an Authorization: Bearer <token> header and stores the token's claims in req.user. HS256, RS256 and ES256 are supported. Each configured key has exactly one algorithm, and a token must use the algorithm of the key it is checked against, so it cannot pick a weaker one (e.g. none, or HS256 with the public key as the secret).
exp and nbf are enforced whenever they are present. Failures return 401 with WWW-Authenticate: Bearer. Configuring no key throws std::invalid_argument; secrets shorter than 32 bytes log a warning.
Public keys (RS256 / ES256). Tokens from an identity provider (Auth0, Keycloak, Cognito, Azure AD, ...) are signed with a private key; verify them with the public key, or let Orbit fetch the provider's key set:
The key set is fetched on first use and cached. A token whose kid is unknown triggers a refetch (so key rotation works without a restart), but never more often than jwks_min_refetch (default 30 s), so forged kids cannot flood the provider. If a fetch fails, the previous keys stay in use.
Issuing tokens. orbit::jwt::sign() creates tokens that jwt_auth() accepts, for a login endpoint: HS256 with the shared secret, or RS256 / ES256 with a private key PEM (the key type picks the algorithm, as for verification). It sets iat, and exp, nbf, iss, aud and sub from the options; claims you pass yourself take precedence.
In a handler behind jwt_auth(), orbit::jwt::claim<std::string>(req.user, "sub") reads a claim with its type (std::nullopt if it is missing or has another type).
You can inject middleware into specific routes using an initializer list vector<Middleware>:
Orbit comes with Several high-performance built-in middlewares:
Automatically validates request bodies and returns 422 Unprocessable Entity if the JSON is malformed.
Serves files from a directory for GET and HEAD; anything not found falls through to the next middleware or route.
mount, only requests under the prefix are considered, and the prefix is stripped before the path is resolved. fallthrough = false answers 404 for a miss instead of continuing to the next middleware or route.403.ETag, Last-Modified, Cache-Control and Accept-Ranges: bytes. If-None-Match and If-Modified-Since give 304.Range: bytes=0-1023, bytes=-500, ...) gives 206 with Content-Range, or 416 if it starts past the end. If-Range is honoured. Multi-range requests get the whole file.orbit::middleware::mime_type_for_extension(".woff2") exposes the built-in type table.compress() does not compress files from static_files() (they are sent with sendfile, not from memory). Compress them at build time instead and set precompressed = true: for app.js, an app.js.br, app.js.zst or app.js.gz next to it is served when the client's Accept-Encoding takes that coding, with Content-Encoding, the original's Content-Type and Vary: Accept-Encoding (ranges and conditional requests work on the compressed file, which has its own ETag). The plain file must exist too; it is served to everyone else. orbit::middleware::compress() compresses response bodies with brotli (br), zstd or gzip, whichever the client's Accept-Encoding allows with the highest q-value; ties go to the server's preference (brotli, zstd, gzip). Every compressible response gets Vary: Accept-Encoding. Bodies that are small, already encoded, already-compressed media, streamed, or marked Cache-Control: no-transform are left alone, and a strong ETag on a compressed body becomes weak.
Brotli and zstd come from the ORBIT_ENABLE_BROTLI and ORBIT_ENABLE_ZSTD build options (both on by default; with vcpkg, the brotli and zstd manifest features). A coding left out of the build is simply never chosen.
Adds common hardening headers to every response. They are defaults: a handler that sets the same header keeps its own value.
Behind a load balancer or reverse proxy, the socket peer is the proxy. List your proxies and req.client_ip becomes the real client, taken from X-Forwarded-For (or RFC 7239 Forwarded). Requests that do not come from a listed proxy keep their socket address, so clients cannot spoof their IP. The socket address is always available as req.peer_ip.
The header is read right to left, skipping listed proxies, so an address a client prepends to X-Forwarded-For is never used.
Global in-memory or Redis-backed distributed rate limiting. Rejected requests get 429 Too Many Requests with a Retry-After header (seconds).
The in-memory limiter is a token bucket: each client may burst up to max_requests and regains capacity continuously at max_requests / window. Idle clients are evicted, and at most max_tracked_clients are tracked, so memory stays bounded under IP spraying.
The Redis-backed limiter shares a fixed window across all instances. The counter and its expiry are set atomically. If Redis is unreachable, requests are rejected with 503 unless allow_when_unavailable is true.
Catch all unhandled exceptions thrown inside route handlers (a group can override this for its own routes; see Route Grouping):