cwist
Modern C web framework with libttak runtime
Loading...
Searching...
No Matches
middleware.h File Reference

Built-in middleware factories. More...

#include <cwist/sys/app/app.h>
#include <cwist/sys/app/waf.h>
#include <cwist/security/jwt/jwt.h>
#include <cwist/net/redis/cwist_redis.h>
#include <stdbool.h>
Include dependency graph for middleware.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Classes

struct  cwist_rate_limit_redis_cfg_t
 Redis-backed rate limiter configuration. Strings are copied. More...
 
struct  cwist_otel_cfg_t
 Configuration for cwist_mw_otel_trace(). More...
 

Enumerations

enum  cwist_log_format_t { CWIST_LOG_COMMON , CWIST_LOG_COMBINED , CWIST_LOG_JSON }
 Access log middleware output formats. More...
 

Functions

cwist_middleware_func cwist_mw_request_id (const char *header_name)
 Request ID middleware.
 
cwist_middleware_func cwist_mw_access_log (cwist_log_format_t format)
 Access log middleware factory.
 
cwist_middleware_func cwist_mw_rate_limit_ip (int requests_per_minute)
 Fixed-window rate limiter middleware (per-IP).
 
cwist_middleware_func cwist_mw_rate_limit_ip_redis (const cwist_rate_limit_redis_cfg_t *cfg)
 Shared per-IP 60-second window using one atomic Redis Lua command.
 
void cwist_mw_rate_limit_reset (void)
 Reset the process-local IP table; Redis configs and keys are unchanged.
 
cwist_middleware_func cwist_mw_metrics (void)
 Prometheus metrics collection middleware.
 
cwist_middleware_func cwist_mw_cors (void)
 CORS middleware. Adds CORS headers and handles OPTIONS requests (returns 204).
 
cwist_middleware_func cwist_mw_jwt_auth (const char *secret)
 JWT authentication middleware factory.
 
cwist_middleware_func cwist_mw_compress (size_t min_body_size)
 Response compression middleware factory.
 
const cwist_jwt_claims * cwist_mw_jwt_get_claims (const cwist_http_request *req)
 Retrieve JWT claims stored by cwist_mw_jwt_auth from a request.
 
cwist_middleware_func cwist_mw_otel_trace (const cwist_otel_cfg_t *cfg)
 OpenTelemetry tracing middleware.
 
const char * cwist_mw_otel_get_trace_id (const cwist_http_request *req)
 Trace id of the span cwist_mw_otel_trace() opened for req.
 

Detailed Description

Built-in middleware factories.

Definition in file middleware.h.

Enumeration Type Documentation

◆ cwist_log_format_t

Access log middleware output formats.

Enumerator
CWIST_LOG_COMMON 
CWIST_LOG_COMBINED 
CWIST_LOG_JSON 

Definition at line 22 of file middleware.h.

Function Documentation

◆ cwist_mw_access_log()

cwist_middleware_func cwist_mw_access_log ( cwist_log_format_t  format)

Access log middleware factory.

Access log middleware factory.

Parameters
formatLog format selector (COMMON, COMBINED, JSON).
Returns
Middleware function pointer for access logging.

Definition at line 296 of file middleware.c.

◆ cwist_mw_compress()

cwist_middleware_func cwist_mw_compress ( size_t  min_body_size)

Response compression middleware factory.

Inspects Accept-Encoding, compresses the response body using a registered backend, and adds the Content-Encoding header.

Parameters
min_body_sizeMinimum uncompressed body size (bytes) to trigger compression.
Returns
Middleware function pointer.

Response compression middleware factory.

Compression middleware factory.

Parameters
min_body_sizeMinimum body size, in bytes, for compression to apply.
Returns
Middleware handler that compresses eligible responses.

Definition at line 713 of file compress.c.

◆ cwist_mw_cors()

cwist_middleware_func cwist_mw_cors ( void  )

CORS middleware. Adds CORS headers and handles OPTIONS requests (returns 204).

CORS middleware. Adds CORS headers and handles OPTIONS requests (returns 204).

Returns
Middleware function pointer for CORS handling.

Definition at line 525 of file middleware.c.

References cwist_mw_cors_handler().

◆ cwist_mw_jwt_auth()

cwist_middleware_func cwist_mw_jwt_auth ( const char *  secret)

JWT authentication middleware factory.

Reads the Authorization header, expects "Bearer <token>". On success the decoded claims are available via cwist_mw_jwt_get_claims(). On failure responds with 401 Unauthorized and short-circuits the chain.

Parameters
secretHMAC-SHA256 signing secret (null-terminated, must outlive the middleware invocations - typically a static/global string).
Returns
Middleware function pointer, or NULL when secret is NULL or eight distinct secrets are already registered in this process.

JWT authentication middleware factory.

Parameters
secretBorrowed signing secret used to verify bearer tokens.
Returns
Middleware wrapper bound to the supplied secret, or NULL on overflow or when the JWT module is compiled out (CWIST_JWT=0).

Definition at line 649 of file middleware.c.

References cap.

◆ cwist_mw_jwt_get_claims()

const cwist_jwt_claims * cwist_mw_jwt_get_claims ( const cwist_http_request *  req)

Retrieve JWT claims stored by cwist_mw_jwt_auth from a request.

Only valid inside a handler that sits behind the JWT middleware, on the thread running that request's middleware chain; the claims are released when the chain returns to the middleware.

Parameters
reqThe current HTTP request.
Returns
Read-only pointer to the claims, or NULL if not authenticated.

Retrieve JWT claims stored by cwist_mw_jwt_auth from a request.

Parameters
reqRequest currently executing behind the JWT middleware.
Returns
Active decoded claims, or NULL when the request is not inside JWT auth on this thread.

Definition at line 687 of file middleware.c.

References cap.

◆ cwist_mw_metrics()

cwist_middleware_func cwist_mw_metrics ( void  )

Prometheus metrics collection middleware.

Prometheus metrics collection middleware.

Returns
Middleware function pointer for request metrics.

Definition at line 333 of file middleware.c.

References cwist_mw_metrics_handler().

◆ cwist_mw_otel_get_trace_id()

const char * cwist_mw_otel_get_trace_id ( const cwist_http_request *  req)

Trace id of the span cwist_mw_otel_trace() opened for req.

Parameters
reqThe current request.
Returns
32 lowercase hex characters (the caller's trace id when the request carried a valid traceparent, a fresh one otherwise), or NULL when req is not running behind the middleware on this thread.

Definition at line 300 of file otel.c.

References cap.

◆ cwist_mw_otel_trace()

cwist_middleware_func cwist_mw_otel_trace ( const cwist_otel_cfg_t *  cfg)

OpenTelemetry tracing middleware.

Records one SERVER span per request covering the rest of the chain, with the method, path, status and start/end time, and exports the spans to the collector as OTLP/HTTP JSON from a background thread in each worker process. A valid W3C traceparent header makes the span a child of the caller's span; otherwise a new trace starts.

Export is fail-open: a full queue drops its oldest span and a failed export drops the batch; requests are never slowed or failed by the collector.

There is one exporter per process: the first call fixes the configuration and later calls return the same middleware.

Parameters
cfgExporter configuration, or NULL for the defaults.
Returns
The middleware, or NULL when memory could not be had.

Definition at line 272 of file otel.c.

References batch, cwist_otel_cfg_t::batch_size, cap, cwist_alloc_array(), cwist_free(), cwist_strdup(), cwist_otel_cfg_t::endpoint, endpoint, OTEL_DEFAULT_BATCH, OTEL_DEFAULT_ENDPOINT, OTEL_DEFAULT_QUEUE, OTEL_DEFAULT_SERVICE, cwist_otel_cfg_t::queue_cap, and cwist_otel_cfg_t::service_name.

◆ cwist_mw_rate_limit_ip()

cwist_middleware_func cwist_mw_rate_limit_ip ( int  requests_per_minute)

Fixed-window rate limiter middleware (per-IP).

Fixed-window rate limiter middleware (per-IP).

Reuses an existing wrapper when the same rate was already registered. If all CWIST_RATE_LIMIT_MAX_CFGS config slots are taken, logs a warning and falls back to the first registered wrapper.

Parameters
requests_per_minuteAllowed requests per minute (token bucket rate); values <= 0 fall back to 60.
Returns
Middleware function pointer for per-IP rate limiting.

Definition at line 467 of file middleware.c.

◆ cwist_mw_rate_limit_ip_redis()

cwist_middleware_func cwist_mw_rate_limit_ip_redis ( const cwist_rate_limit_redis_cfg_t *  cfg)

Shared per-IP 60-second window using one atomic Redis Lua command.

Uses the socket peer, never forwarded headers. A rejected request returns 429 with Retry-After: 60. Backend errors and missing peer addresses follow fail_closed. The first backend failure per configuration in each process writes its error code and policy to stderr (no keys or credentials). No local fallback counter is used. Requests do not extend TTL. Use a dedicated pool on DB 0, with the default user and no AUTH.

Create the pool separately in every serving process after fork. Pool creation and DNS are blocking; timeout_ms bounds request-time pool wait and I/O. Use cwist_app_listen_ex() with one worker or CWIST_WORKERS=1, so the application listener does not fork the initialized pool. Do not destroy the pool while calls may still run. Eight distinct immutable configurations are supported per process; equal configurations reuse a slot.

Returns
Middleware, or NULL for invalid configuration or exhausted slots.

Definition at line 129 of file rate_limit_redis.c.

References cap, cwist_rate_limit_redis_cfg_t::fail_closed, cwist_rate_limit_redis_cfg_t::key_prefix, cwist_rate_limit_redis_cfg_t::pool, REDIS_RATE_PREFIX_MAX, REDIS_RATE_SLOTS, cwist_rate_limit_redis_cfg_t::requests_per_minute, and cwist_rate_limit_redis_cfg_t::timeout_ms.

◆ cwist_mw_rate_limit_reset()

void cwist_mw_rate_limit_reset ( void  )

Reset the process-local IP table; Redis configs and keys are unchanged.

Reset the process-local IP table; Redis configs and keys are unchanged.

Definition at line 450 of file middleware.c.

References cap.

◆ cwist_mw_request_id()

cwist_middleware_func cwist_mw_request_id ( const char *  header_name)

Request ID middleware.

Parameters
header_nameOptional override for the header (defaults to "X-Request-Id").

Request ID middleware.

Request ID middleware factory.

Parameters
header_nameCurrently unused custom header override.
Returns
Middleware function pointer for request ID injection.

Definition at line 79 of file middleware.c.