Skip to content

Security Hardening

This document describes Kirak’s built-in defense-in-depth security model, security invariants, and production hardening requirements.

flowchart TD
A["Inbound Request"] --> B["Origin & Trusted Proxy IP Check"]
B --> C["SecurityHeadersMiddleware<br/>(nosniff, DENY, XSS, strict-origin)"]
C --> D["Rate Limiter<br/>(Sliding Window Quota Evaluation)"]
D --> E["JWT HMAC Verification<br/>(HS256/384/512 Only; None & Asymmetric Blocked)"]
E --> F["Body Size Guard<br/>(Enforces max_body_mb on Streamed Bytes)"]
F --> G["RBAC & RLS Grammar Evaluation<br/>(Startup Grammar Enforcement)"]
G --> H["Dialect Parameterized Query Builder<br/>(Zero String Interpolation)"]
H --> I["Error Redactor & Sanitizer<br/>(Secret & Token Masking in Logs)"]

Category Requirement Default Recommended Production
JWT Secret KIRAK_AUTH_JWT_SECRET_KEY >= 32 bytes Enforced at startup 64+ random bytes (secrets.token_hex(32))
JWT Algorithm Strict HMAC (HS256, HS384, HS512) HS256 HS256 (Asymmetric and none blocked)
Password Cost auth.bcrypt_rounds 12 12 to 14
Encryption Keys KIRAK_AUTH_ENCRYPTION_KEYS for AES-256-GCM Falls back to SHA-256 of JWT secret Explicit comma-separated 32-byte Base64 keys
Cookie Flags Session cookies if enabled HttpOnly; Secure; SameSite=Lax Unconditionally enforced
API Docs docs.public and openapi.public true Set to false for closed/private APIs
Trusted Proxies rate_limit.trusted_proxy_ips Empty Exact CIDR/IP list of your reverse proxies
CDN Client IP Header rate_limit.client_ip_header Empty Only when every request comes through the CDN that sets it
Rate Limit Backend KIRAK_REDIS_URL and the kirak_rate_limits table Database counts when Redis is down Keep the table migrated: auth routes refuse with 503 AUTH_UNAVAILABLE when neither backend can count
Access Control Model access block defined Deny by default Strict access rules for every role

All SQL values are parameterized. No user input is ever interpolated into SQL query strings.

The query_builder module uses dialect-aware parameter placeholders:

  • MySQL: %s
  • PostgreSQL: $1, $2, …
  • SQLite: ?1, ?2, …

Filter keys are parsed by parse_field_operator() and verified against declared model fields; unknown fields are never passed to the SQL compiler. Read and write operations reject unknown filter keys with 400 VALIDATION_ERROR (Unknown filter field(s): ...), ensuring a typo cannot widen a read or a write.

[!SECURITY] Any custom query logic must use dialect.placeholder(index) or the build_condition() helpers. Never concatenate user input into SQL strings.


Row-level security conditions in access.condition fields are verified at startup against a strict regular grammar (_SAFE_CONDITION_RE in access.py). Conditions outside this grammar raise ConfigurationError and halt server startup.

  • Permitted: field operator {variable}, field operator <number>, field = TRUE/FALSE, field = NULL, field IS NULL, field IS NOT NULL, combined with AND/OR.
  • Prohibited: Subqueries, function calls, raw string literals (status = 'active'). Pass string filters through {variable} placeholders.
  • Boolean Safety: PostgreSQL lacks implicit boolean = integer casting. Boolean fields must use TRUE or FALSE, not 1 or 0.

At runtime, {variable} placeholders are resolved from the caller’s JWT claims and bound as parameterized values.


JWT tokens are verified with an explicit allowlist of HMAC algorithms:

_ALLOWED_ALGORITHMS = {"HS256", "HS384", "HS512"}

Asymmetric algorithms (RS256, ES256, etc.) and the none algorithm are unconditionally rejected. This prevents algorithm confusion attacks where an attacker replaces RS256 with HS256 and signs tokens with the server’s public key.


An access token is valid until it expires. The default lifetime is 15 minutes (auth.access_token_expire_minutes), which bounds how long a stolen or stale token works.

Set KIRAK_REDIS_URL to end tokens early. Then a logout of all sessions, a password change or reset, a role change and a deactivation (closing an account included) refuse the user’s access tokens issued before that moment (401 TOKEN_REVOKED). Redis is the only store for this; the revocation key lives as long as an access token can.

Without Redis, access tokens are not revoked. A stolen access token works until it expires, even after the user logs out or is deactivated. After a logout, a password change or reset, or a deactivation, the refresh tokens are deleted or refused, so the attacker cannot get a new access token from them. If that window is too long for your app, shorten the access token lifetime or run Redis.

With Redis configured but unreachable, requests carrying an access token are refused with 503 AUTH_UNAVAILABLE (fail closed) until it is back. See Core Authentication and Redis.


  • Bcrypt Hashing: Passwords are hashed with bcrypt at auth.bcrypt_rounds (default 12; values below 10 are elevated to 10 with a startup warning). Hashing runs in an isolated thread pool so CPU spikes do not block the event loop.
  • Length Constraints: Minimum password length is 12 characters and maximum length is 72 bytes (UTF-8, the bcrypt truncation boundary), enforced unconditionally.
  • Complexity: When auth.password_complexity: true (the default), passwords require at least one uppercase letter, one lowercase letter, one digit, and one special character.
  • Timing Equalization: Non-existent emails are verified against a dummy bcrypt hash with identical cost (auth.bcrypt_rounds), ensuring login operations take constant time regardless of whether an account exists.

Social provider tokens (auth_social), MFA TOTP secrets (auth_mfa.totp_secret), and integration credentials are encrypted with AES-256-GCM before storage.

  • Keyring: Configured via KIRAK_AUTH_ENCRYPTION_KEYS as a comma-separated list of 32-byte Base64-encoded keys.
  • Ciphertext Format: Stored as v3:<key_id>:<nonce>:<ciphertext>. The key_id is the first 8 hex characters of the key’s SHA-256 hash.
  • Key Rotation: Zero-downtime key rotation is supported via POST /auth/keys/rotate, re-encrypting existing rows in batches in the background.

Local storage sandboxes every file it serves and downloads every type except images and PDFs (see Storage). A script in an upload therefore cannot run on the API origin, but it can still reach the page’s cookies. Serve uploads from a separate media origin without auth cookies: a different host, through your CDN or reverse proxy, that does not forward the app’s cookies. Record the origin in your shared responsibility matrix.

SecurityHeadersMiddleware attaches standard security headers to every response unconditionally:

Header Value Purpose
X-Content-Type-Options nosniff Prevents MIME-type sniffing
X-Frame-Options DENY Prevents clickjacking in iframes
X-XSS-Protection 1; mode=block Legacy XSS filter activation
Referrer-Policy strict-origin-when-cross-origin Protects referrer privacy

All external payment and integration webhooks are verified against their provider’s signature before any processing or hook execution:

  • Stripe: stripe.Webhook.construct_event
  • Razorpay: HMAC-SHA256 over order_id|payment_id
  • Square: Base64 HMAC-SHA256 over notification URL and raw body
  • PayPal: Online verification via PayPal verify-webhook-signature API
  • Paddle: HMAC-SHA256 over <timestamp>:<raw_body>
  • Paystack: HMAC-SHA512 over raw body
  • Flutterwave: Constant-time verif-hash comparison + API re-read
  • Mercado Pago: HMAC-SHA256 over x-signature header + API re-read
  • Airwallex: HMAC-SHA256 over <x-timestamp><raw_body> + API re-read

Unverified webhooks immediately return 400 with no hooks executed.


Internal database and driver exceptions are never returned to clients. Database errors return generic messages (Database error during fetch operation on posts), while the full traceback is recorded in kirak.log.

Sensitive tokens and query parameters (access_token, refresh_token, api_key, client_secret, Bearer tokens) are automatically replaced with [REDACTED] by RedactionFilter before reaching log files or monitoring sinks.


/docs (the API described for AI agents) and /openapi.json are public by default, in production too. Anyone can read the routes, models and fields without signing in.

Before the API goes public, make both private in kirak.json:

{
"docs": { "public": false },
"openapi": { "public": false }
}

Guests then get 401 MISSING_TOKEN. Set enabled to false in the same sections to remove the routes. See API Docs Endpoint.


Each row names who must act. Kirak means the framework enforces it. App means your application code or configuration decides it. Operator means the team that deploys and runs the service provides it.

Area Owner Responsibility
TLS termination Operator Terminate TLS at a reverse proxy or load balancer. Kirak has no TLS settings.
Trusted proxies Operator List your proxies in rate_limit.trusted_proxy_ips, so X-Forwarded-For is trusted from them only.
HSTS and CSP Operator Kirak sets neither Strict-Transport-Security nor Content-Security-Policy on API responses. Set HSTS at the proxy.
Security response headers Kirak Sets the headers in Security Response Headers.
Column encryption Kirak Encrypts MFA secrets, social sign-in data and integration credentials with AES-256-GCM. See Encryption at Rest.
Database disk or engine encryption Operator Encrypt the database volume, or use the engine’s transparent encryption (PostgreSQL, MySQL). Kirak does not encrypt the database as a whole.
Database roles Operator Give the app a least-privilege database role.
Database connection TLS Operator To confirm: Kirak documents no database TLS setting. Check the driver options for your database.
Database backups Operator Kirak ships no backup tooling. For SQLite, use the online backup API (see Database). Schedule backups and test restores.
Disaster recovery targets Operator Set recovery point and recovery time targets. Kirak defines none.
Redis TLS Operator Use a rediss:// URL in KIRAK_REDIS_URL (see Redis).
Redis ACL Operator Create a Redis user limited to the app’s key prefix (see Redis).
Redis for auth Operator Run Redis for access-token revocation and shared rate limits. Without it, see Access Token Revocation.
Secrets Operator Inject KIRAK_AUTH_* values from a secrets manager. Do not commit them.
Key rotation Operator Rotate on a schedule, using the Key Rotation Runbook.
Log shipping Operator Kirak writes kirak.log (log_output: file, stdout or both) and sends monitoring records to stdout when the stdout sink is on. Ship them to your log store.
Monitoring SQLite store Operator var/kirak/metrics.db is not encrypted and lives on one node. Kirak does not replicate it. Keep it on encrypted disk, or use the stdout sink and ship the records elsewhere. Defaults keep request records 7 days and audit events 30 days (monitoring.retention_days, monitoring.audit_retention_days).
Multiple replicas Operator Replicas need Redis for shared token revocation and rate limits. Run Redis before you scale out.
Uploaded file origin Operator Serve uploads from an origin without auth cookies (see Uploaded Files).
Access rules and row-level security App Define an access block on every model (see Access Control).
Registration policy App Set auth.registration in kirak.json for your sign-up model.
Hooks and custom routes App Hook and route code runs with your permissions. Check the caller in custom routes.
Password hashing, JWT checks, SQL parameters, webhook signatures Kirak Enforced by the framework (see the sections above).
Rate limiting and audit events Kirak Kirak applies the limits and writes audit events. The Operator stores and ships them.

What rotating KIRAK_AUTH_JWT_SECRET_KEY breaks

Section titled “What rotating KIRAK_AUTH_JWT_SECRET_KEY breaks”

The JWT secret is the root of several other keys. Rotating it without preparation has these effects:

Item Key source Effect of rotating the JWT secret
Access tokens KIRAK_AUTH_JWT_SECRET_KEY Every access token fails. KIRAK_AUTH_JWT_OLD_SECRET_KEY keeps the old secret valid until its tokens expire (15 minutes by default).
Refresh tokens and sessions KIRAK_AUTH_JWT_REFRESH_SECRET_KEY, else KIRAK_AUTH_JWT_SECRET_KEY Refresh fails for every session when no separate refresh key is set. KIRAK_AUTH_JWT_REFRESH_OLD_SECRET_KEY (or KIRAK_AUTH_JWT_OLD_SECRET_KEY) keeps them valid until they expire (14 days by default). Users sign in again after that. Refresh tokens are stored as SHA-256 hashes, which do not depend on the secret.
API keys HMAC-SHA256 keyed with KIRAK_AUTH_API_KEY_SECRET, else KIRAK_AUTH_JWT_SECRET_KEY Every API key stops working. There is no old-key fallback. Set KIRAK_AUTH_API_KEY_SECRET before issuing keys. Changing it later also breaks existing keys, so those keys must be reissued.
Signed storage URLs KIRAK_STORAGE_URL_SIGNING_KEY, else KIRAK_AUTH_JWT_SECRET_KEY Signed links already issued stop working. They expire on their own, and new links are signed with the new key. Set KIRAK_STORAGE_URL_SIGNING_KEY to keep signing independent.
At-rest encryption KIRAK_AUTH_ENCRYPTION_KEYS, else SHA-256 of KIRAK_AUTH_JWT_SECRET_KEY When KIRAK_AUTH_ENCRYPTION_KEYS is unset, the encryption key changes with the JWT secret. Stored MFA secrets, social sign-in data and integration credentials then fail with ENCRYPTION_KEY_UNKNOWN. Follow the steps below.
Internal HMAC values (kirak/core/utils/signing.py) HMAC-SHA256 of KIRAK_AUTH_JWT_SECRET_KEY, one key per purpose Values in flight are refused: OTP codes, MFA challenge tokens, account reopen tokens, queued and scheduled jobs, and paused AI approvals. Let them expire before rotating.
Email verification and password reset links KIRAK_AUTH_VERIFICATION_KEY Not affected.

When KIRAK_AUTH_ENCRYPTION_KEYS is unset, the AES-256-GCM key is the SHA-256 digest of KIRAK_AUTH_JWT_SECRET_KEY. The JWT secret and the at-rest encryption key therefore share one source. While the keyring is unset, a leaked JWT secret also decrypts the stored secrets. Set KIRAK_AUTH_ENCRYPTION_KEYS to an independent key, so a leaked JWT secret alone does not decrypt stored data.

Run these steps in order. Do not skip step 2: without the old key in the keyring, stored values stay unreadable. Kirak reports them and leaves them untouched.

  1. Generate a new encryption key:

    Terminal window
    python -c "import os, base64; print(base64.b64encode(os.urandom(32)).decode())"
  2. If KIRAK_AUTH_ENCRYPTION_KEYS is unset, compute the current derived key from the old JWT secret:

    Terminal window
    python -c "import hashlib, base64, os; print(base64.b64encode(hashlib.sha256(os.environ['KIRAK_AUTH_JWT_SECRET_KEY'].encode('utf-8')).digest()).decode())"
  3. Set the new secret and the keyring together, then restart:

    • KIRAK_AUTH_ENCRYPTION_KEYS to the new key, then the derived key from step 2. The first key encrypts.
    • KIRAK_AUTH_JWT_SECRET_KEY to the new secret.
    • KIRAK_AUTH_JWT_OLD_SECRET_KEY to the old secret.
    • KIRAK_AUTH_JWT_REFRESH_OLD_SECRET_KEY to the old secret, if refresh tokens use the JWT secret.
  4. Start the background re-encryption as an admin or system caller: POST /auth/keys/rotate (answers 202). If it answers 409 KEY_ROTATION_UNAVAILABLE, enable the scheduler module.

  5. Wait for the run to finish. Kirak logs a line when no row uses an old key, and it names the keys that can be removed.

  6. Remove the old keys from KIRAK_AUTH_ENCRYPTION_KEYS and the *_OLD_SECRET_KEY variables after the longest token lifetime has passed (15 minutes for access tokens, 14 days for refresh tokens by default).

For API keys, no runbook step keeps existing keys working once the JWT secret changes unless KIRAK_AUTH_API_KEY_SECRET was already set. Plan a key reissue if it was not.