Middleware & Request Context
Kirak configures an ASGI middleware pipeline automatically during application startup.
flowchart TD subgraph Inbound ["Inbound Pipeline (Outermost to Innermost)"] A["Client Request"] --> B["CORSMiddleware<br/>(When cors.enabled is true)"] B --> C["Custom App Middlewares<br/>(Registered via middlewares=[...])"] C --> D["SecurityHeadersMiddleware<br/>(nosniff, DENY, XSS, strict-origin)"] D --> E["OriginValidationMiddleware<br/>(DNS Rebinding & Origin Protection)"] E --> F["RequestContextMiddleware<br/>(Request ID & Principal Correlation)"] F --> G["MonitoringMiddleware<br/>(RED Request Timing & Metrics)"] G --> H["BodySizeLimitMiddleware<br/>(Enforces max_body_mb)"] H --> I["FastAPI Route Handler"] endBuilt-In Middleware Stack
Section titled “Built-In Middleware Stack”create_kirak_app() mounts these middlewares in strict execution order:
CORSMiddleware(Outermost): Evaluates CORS preflight and origin headers whencors.enabled: trueinkirak.json.- Custom Middlewares: Any middlewares supplied in
create_kirak_app(middlewares=[...])execute here, surrounding Kirak’s core pipeline. SecurityHeadersMiddleware: Injects standard security headers into every response.OriginValidationMiddleware: Validates browserOriginheaders againstbase_urlandcors.originsto prevent DNS rebinding attacks.RequestContextMiddleware: Extracts or generates uniqueX-Request-IDcorrelation identifiers.MonitoringMiddleware: Captures request duration and status codes when themonitoringmodule is enabled.BodySizeLimitMiddleware(Innermost): Enforces payload limits (max_body_mb, default 10MB) before request bodies are buffered.
BodySizeLimitMiddleware
Section titled “BodySizeLimitMiddleware”- File:
kirak/middleware/body_size.py - Configuration: Defined by
max_body_mbinkirak.json(default: 10 MB). - Streaming Byte Enforcement: Enforced directly on streaming bytes. Chunked requests without a
Content-Lengthheader are terminated as soon as transferred bytes exceed the limit. - Error Response: Exceeding the threshold returns
413 PAYLOAD_TOO_LARGEwith the standard error envelope. - Upload Overrides: Storage upload routes (
/storage/upload/*) automatically useimage_max_sizeorfile_max_sizeplus 1MB for multipart form boundaries.
SecurityHeadersMiddleware
Section titled “SecurityHeadersMiddleware”- File:
kirak/middleware/security_headers.py
Applies standard defensive headers to all responses:
| Header | Value | Description |
|---|---|---|
X-Content-Type-Options |
nosniff |
Disables MIME type sniffing |
X-Frame-Options |
DENY |
Prevents framing and clickjacking |
X-XSS-Protection |
1; mode=block |
Enables browser XSS filters |
Referrer-Policy |
strict-origin-when-cross-origin |
Protects referrer privacy across origins |
Strict-Transport-Security |
max-age=31536000 |
Only when kirak.json hsts is true: browsers use HTTPS only for the host for a year |
RequestContextMiddleware
Section titled “RequestContextMiddleware”- File:
kirak/middleware/request_context.py
Tracks every incoming request with an async correlation ID:
- Header Inspection: Reads
X-Request-IDfrom the request headers only when the connection comes from arate_limit.trusted_proxy_ipsaddress, and the value must match^[a-zA-Z0-9-]{1,64}$. Otherwise the request gets a standard UUID4, and any client value not used is logged with it. - Context Propagation: Stores the request ID in an async
ContextVaraccessible across all hooks, background tasks, and database operations. - Response Header Attachment: Emits
X-Request-IDon all responses. - Automatic Cleanup: Resets context variables after response dispatch to prevent cross-request leakage.
Context Access API
Section titled “Context Access API”from kirak.middleware.request_context import ( get_request_id, get_user_id, get_current_user,)
@kirak.on("orders").hook("after_create")async def audit_order(result): req_id = get_request_id() user_id = get_user_id() kirak.logger.info(f"Order created under request {req_id} by user {user_id}") return resultLogging Filters
Section titled “Logging Filters”Kirak injects two logging filters into all loggers automatically:
RequestContextFilter(kirak/middleware/logging_filter.py): Formats log messages with the current request ID and user ID:2026-11-06 12:00:01 - [550e8400-e29b-41d4-a716-446655440000] - crud - INFO - [user:42] - [FETCH] Model: postsRedactionFilter(kirak/middleware/logging_filter.py): Automatically masks sensitive tokens, passwords, and authorization headers ([REDACTED]) before records reach log files or monitoring sinks.
Adding Custom Middleware
Section titled “Adding Custom Middleware”Register third-party ASGI middlewares via create_kirak_app():
from starlette.middleware.gzip import GZipMiddlewarefrom kirak.kirak_instance import create_kirak_app
app = create_kirak_app( models_path="./models/", middlewares=[ (GZipMiddleware, {"minimum_size": 1000}), ],)