Skip to content

Core Authentication

Kirak ships with a complete, production-grade authentication runtime—user registration, login, JWT token lifecycle, refresh token rotation, email verification, password reset, account closure, and API keys—with zero handwritten boilerplate.

Uniform Response Shape: Every auth endpoint returns the canonical response envelope:

  • Success: {"statusCode": 200, "status": "success", "message": "...", "data": {...}}
  • Error: {"statusCode": 4xx|5xx, "status": "error", "error": "<STABLE_CODE>", "message": "...", "data": null} Branch your frontend logic on the stable error machine code (INVALID_CREDENTIALS, EMAIL_NOT_VERIFIED, MFA_REQUIRED, TOKEN_EXPIRED, etc.), not the human-readable message.

The Mental Model: Stateless vs. Stateful Auth

Section titled “The Mental Model: Stateless vs. Stateful Auth”

Kirak implements a high-performance hybrid authentication architecture:

  1. API Requests are Stateless (Fast Path):
    • Incoming API requests validate the cryptographic signature of the JWT access token in memory with zero database lookups. With KIRAK_REDIS_URL set, they also read one Redis key, the user’s access token revocation (see Access token revocation).
    • Claims like user_id, role, and email are extracted directly from the verified token.
  2. Sessions are Stateful (Security Path):
    • Refresh tokens and API keys are hashed and tracked in the database (auth_tokens).
    • Token refresh operations verify user status, check session validity, and enforce reuse/theft detection.
    • If a user is deactivated or their role changes, the new permissions take effect immediately upon their next token refresh.
flowchart LR
subgraph Client["Client (Web / Mobile)"]
Req["API Call<br/>(Bearer Access Token)"]
Ref["Session Refresh<br/>(Refresh Token)"]
end
subgraph Kirak["Kirak Runtime"]
Verify["Stateless JWT Verify<br/>(In-Memory / Zero DB I/O)"]
Session["Stateful Session Check<br/>(Database auth_tokens)"]
end
Req --> Verify --> Serve["Execute CRUD / RLS"]
Ref --> Session --> Mint["Rotate Tokens & Issue New JWT"]

By default, all authentication routes are mounted at /auth. You can customize this prefix in kirak.json under routes.auth_prefix (e.g., "auth_prefix": "/api/v1/auth").

Method Endpoint Description
POST /auth/register Register a new user account (role is always user).
POST /auth/login Authenticate with email/password and receive tokens.
POST /auth/refresh-token Exchange a valid refresh token for new tokens (with rotation).
POST /auth/logout Terminate session(s): single, all, or others.
GET /auth/me Fetch profile for current authenticated user.
POST /auth/close-account Request account closure with grace period retention.
POST /auth/reopen-account Reopen an account its user closed, with the reopen_token sign-in answered with.
Method Endpoint Description
GET /auth/verify-email Page the verification email links to; its button calls the POST.
POST /auth/verify-email Verify an email address with the token of the verification link.
POST /auth/request-reset-password Request password reset email with signed link.
POST /auth/reset-password Set new password using token from reset email.
POST /auth/change-password Update password for current signed-in user.
POST /auth/email/change Initiate email address change (sends link to new inbox).
GET /auth/email/verify-change Confirm and apply new email address.
Method Endpoint Description
POST /auth/api-keys/create Generate a kirak_ API key with optional scopes.
GET /auth/api-keys/list List active API keys for authenticated user.
DELETE /auth/api-keys/revoke Revoke an API key immediately.
POST /auth/generate-verification-link Admin/System only: generate manual verification link.

POST /auth/register

{
"email": "alice@example.com",
"password": "Secret!Pass123",
"first_name": "Alice",
"last_name": "Smith"
}
  • Password Complexity: Minimum 12 characters, maximum 72 bytes (bcrypt limit). Requires uppercase, lowercase, digit, and special character. Returns 400 WEAK_PASSWORD if unmet.
  • Fixed Role: The role assigned during self-registration is strictly "user". Supplying a different role in the payload is ignored. Elevating a user to admin or custom roles must be done via direct admin action.
  • Email Verification Requirement: Registration always requires email verification before login is permitted.
  • Registered Email: Registering an address that already has an account returns 409 EMAIL_ALREADY_EXISTS. The response therefore reveals whether an address is registered. Kirak does not hide this, so do not treat registration responses as private.

Three routes create an account for someone who has none:

Route method
POST /auth/register password
POST /auth/verify-otp for a phone number no user has phone
A social sign-in (web callback, mobile, code exchange) whose identity matches no user social

auth.registration in kirak.json decides whether they may:

{
"auth": { "registration": "closed" }
}
  • "open" (default): each route creates the account.
  • "closed": each answers 403 REGISTRATION_CLOSED and creates nothing. Existing users still sign in every way, including a social sign-in that links to their account while its email is verified.

App code is not refused when registration is closed: kirak.auth.register({...}) and kirak.create("users", ...) still create accounts. Use them in your own routes for invitations or approved sign-ups.

Every new account runs the same hooks, whichever route created it:

  • before_register gets the request for password (email, password, first_name, last_name, method), and for the others {"method": "phone", "phone_number": ...} or {"method": "social", "provider", "email", "email_verified", "first_name", "last_name"}. A sync hook that raises refuses the sign-up; raise a KirakException (for example PermissionDenied) to choose the error the client gets. For phone and social the hook’s return value is not used.
  • after_register gets {"data": {"user": {"user_id", "email", "phone_number", ...}, "method": ...}}, the shape /auth/register answers with.
from kirak.core.exceptions import PermissionDenied
@kirak.auth.hook("before_register")
def company_emails_only(payload):
email = payload.get("email") or ""
if not email.endswith("@example.com"):
raise PermissionDenied("Sign-up is for example.com addresses")

When a user registers, Kirak emails a link with a Fernet-signed token valid for 24 hours. Verification takes two steps, like a password reset:

  1. The link opens a page, GET /auth/verify-email?token=.... Opening it changes nothing, so a mail scanner or link preview that follows the link verifies no one.
  2. The page’s Verify my email button sends the token to POST /auth/verify-email:
POST /auth/verify-email
{"token": "gAAAAABn..."}

It answers 200 with {"user_id", "email", "is_verified": true}, 400 INVALID_VERIFICATION_TOKEN (invalid, expired, or the account or its address changed), or 409 EMAIL_ALREADY_VERIFIED.

To use your own page instead, set auth.verify_email_page_url. The emailed link becomes {verify_email_page_url}?token=...; your page POSTs the token to /auth/verify-email and shows the result:

{
"auth": { "verify_email_page_url": "https://app.example.com/verify-email" }
}

POST /auth/verify-email runs the before_verify_email and after_verify_email hooks. after_verify_email gets the response, so an app can act once an address is verified:

@kirak.auth.hook("after_verify_email")
async def welcome(result):
user_id = result["data"]["user_id"]
...
  1. In Production (Notifications Enabled): Kirak emails the link automatically using your configured provider (SES, SendGrid, SMTP, etc.).
  2. In Local Development (No Provider): Kirak prints the verification link directly to the Uvicorn server console:
    [kirak] No verification email was sent for alice@example.com. Open this link to verify the account:
    http://localhost:8000/auth/verify-email?token=...
    Open it and press Verify my email.
  3. Admin Verification Flow: An administrator or backend task can generate a secure link on demand:
    Terminal window
    POST /auth/generate-verification-link
    {"user_id": 42, "email": "alice@example.com", "type": "email_verification"}

POST /auth/login

{
"email": "alice@example.com",
"password": "Secret!Pass123"
}
{
"statusCode": 200,
"status": "success",
"message": "Login successful",
"data": {
"user": {
"user_id": 1,
"email": "alice@example.com",
"first_name": "Alice",
"last_name": "Smith",
"phone_number": null,
"role": "user",
"is_verified": true,
"created_at": "2026-08-01T09:00:00+00:00",
"last_login_at": "2026-08-27T10:11:12+00:00"
},
"accessToken": "eyJhbGciOi...",
"refreshToken": "eyJhbGciOi...",
"expiresIn": 3600
}
}
  • Unverified Accounts: Attempting to log in with an unverified email returns 403 EMAIL_NOT_VERIFIED. A social sign-in does not apply this check; it links to an existing account only when that account’s email is verified, and otherwise answers 409 SOCIAL_EMAIL_NOT_VERIFIED (see Social Authentication).
  • MFA Challenge: If the user has MFA enabled, login returns 403 MFA_REQUIRED with an mfa_token in details. The client must prompt for the TOTP code and call /auth/mfa/challenge.
  • Rate Limits: 5 requests/min per IP, and 3 requests/min per email address. After 5 failed passwords for one email from one IP within 15 minutes, that pair is locked: its next attempt answers 429 RATE_LIMIT_EXCEEDED, even with the right password, until the 15 minutes end. Other IPs are not affected. Only failed passwords count toward the lock. MFA codes have their own per-user lock.
  • HttpOnly Cookies: If cookie_name is set in kirak.json under auth, Kirak automatically sets an HttpOnly, Secure, SameSite=Lax cookie containing the access token. For the refresh token, see Refresh Token Cookie.

A browser app should not keep the refresh token where page scripts can read it. Set refresh_cookie_name and Kirak keeps it in a cookie instead:

{
"auth": {
"cookie_name": "kirak_access",
"refresh_cookie_name": "kirak_refresh",
"cookie_domain": ".example.com"
}
}
  • Every route that issues a refresh token (login, /auth/mfa/challenge, /auth/verify-otp, /auth/refresh-token, social sign-ins) sets it as an HttpOnly, Secure, SameSite=Strict cookie whose path is the auth routes (/auth, or routes.auth_prefix), and leaves refreshToken out of the response body.
  • POST /auth/refresh-token and POST /auth/logout read it from the cookie when the body has none, so the page sends an empty body. The browser sends the cookie when the request includes credentials (fetch(url, {method: "POST", credentials: "include"})).
  • Refreshing replaces the cookie with the rotated token. Logout and closing the account delete both cookies.
  • SameSite=Strict and the Origin check mean a page on another site cannot refresh or end the session. The app’s pages and the API must therefore be on the same site, such as app.example.com and api.example.com; list the app’s origin in cors.origins.

Without refresh_cookie_name (the default), refreshToken is in the body and the client sends it back in the body. Mobile and server clients use that mode.


Lifetimes are configured in kirak.json under the "auth" block:

Token Default Lifetime Configuration Key Usage
Access Token 15 minutes access_token_expire_minutes (or access_token_expire_hours) Included in Authorization: Bearer <token> on all API calls
Refresh Token 14 days refresh_token_expire_days Sent to POST /auth/refresh-token to renew access
{
"sub": "1",
"role": "user",
"email": "alice@example.com",
"jti": "b47e2a91-4c12-4e89-9a2c-f60a92d830b1",
"type": "access",
"iat": 1724184000,
"exp": 1724187600
}
  • sub: The user’s ID as a string.
  • jti: Unique token identifier to prevent replay or collision.
  • role: The user’s role, used by the Access Policy Engine to enforce RLS.

Kirak enforces Refresh Token Rotation with Automatic Reuse Detection:

  1. Every time a refresh token is exchanged, Kirak issues both a new access token and a new refresh token.
  2. The old refresh token is marked as rotated_at.
  3. All refresh tokens minted from an initial login share a family_id.
  4. Grace Period (10s): If concurrent browser tabs exchange the old refresh token within refresh_token_reuse_interval_seconds (default 10s), Kirak gracefully issues tokens within the same family.
  5. Theft Detection: If an old, already-rotated refresh token is presented after the 10-second window, Kirak flags a token replay attack, immediately revokes all tokens in that entire family, logs a security alert, and returns 401 TOKEN_REVOKED.
sequenceDiagram
autonumber
participant Client as Client (Browser / App)
participant Server as Kirak Auth Runtime
participant DB as auth_tokens DB
Note over Client,Server: Normal Token Rotation
Client->>Server: POST /auth/refresh-token (Refresh Token 1)
Server->>DB: Verify Token 1 (Active, Family A)
Server->>DB: Mark Token 1 as rotated_at=NOW()
Server->>DB: Insert new Refresh Token 2 (Family A)
Server-->>Client: 200 OK (New Access Token + Refresh Token 2)
Note over Client,Server: Theft / Replay Attack Detected
Note right of DB: Malicious actor presents old, already-rotated Token 1
Client->>Server: POST /auth/refresh-token (Refresh Token 1 Replayed)
Server->>DB: Lookup Token 1 (Rotated > 10s ago!)
Server->>DB: REVOKE ENTIRE FAMILY A (All active tokens deleted)
Server-->>Client: 401 Unauthorized (TOKEN_REVOKED)
Note over Client,DB: Stolen session terminated for all parties

POST /auth/logout

{
"token": "<refreshToken>",
"logout_type": "single"
}
  • "single" (default): Revokes the presented token family (logs out this device session).
  • "all": Revokes all refresh tokens belonging to the user (logs out all devices).
  • "others": Revokes all other sessions except the current token family.

An access token stays valid until it expires (exp), unless Redis revokes it. Logout, a password change or reset, and closing the account delete the user’s refresh tokens. A deactivated account cannot refresh. Either way no new access token is issued. A role change takes effect when the client next refreshes, which reads the user again. Access tokens already issued are revoked only when KIRAK_REDIS_URL is set:

  • logout with logout_type all records a revocation for the user;
  • a password change or reset, and a role change or deactivation (closing the account deactivates it), do the same.

A revoked user’s access tokens, issued up to the revocation, are refused with 401 TOKEN_REVOKED, on the next request. Reactivating an account does not revoke. Logout with single or others does not revoke access tokens: they stay valid until they expire.

Without KIRAK_REDIS_URL, no access token is revoked: an access token stays valid until it expires, and a role change or deactivation takes effect when the access token expires and the client refreshes. The default lifetime is 15 minutes; set "access_token_expire_minutes" lower, such as 5, for a smaller window.

With Redis configured but unreachable, a request that carries an access token is refused with 503 AUTH_UNAVAILABLE. If Redis cannot record a revocation, the change itself is still saved and its request answers 503 AUTH_UNAVAILABLE; the access tokens then stay valid until they expire.


POST /auth/change-password (Requires Bearer token)

{
"current_password": "Secret!Pass123",
"new_password": "NewSecret!Pass456",
"confirm_password": "NewSecret!Pass456"
}

Upon success, all active refresh tokens for the user are revoked, forcing re-authentication on other devices. With KIRAK_REDIS_URL set, the user’s access tokens are revoked too (see Access token revocation).

  1. Request Reset: User submits email to POST /auth/request-reset-password.
    • Always returns a generic success message to prevent user enumeration.
    • Generates a signed 1-hour Fernet token and emails the reset link.
  2. Submit New Password: User submits the token from their email:
    POST /auth/reset-password
    {
    "token": "<fernet_reset_token>",
    "new_password": "NewSecret!Pass456",
    "confirm_password": "NewSecret!Pass456"
    }
    A successful reset immediately revokes all refresh tokens and API keys across all devices, and with KIRAK_REDIS_URL set the user’s access tokens too.

To prevent account takeover, email addresses cannot be modified via standard CRUD updates (PUT /users/update). Email changes must follow a 2-step verification handshake:

  1. Authenticated user calls:
    Terminal window
    POST /auth/email/change
    {"new_email": "newalice@example.com"}
  2. Kirak sends a verification link to newalice@example.com.
  3. The user clicks GET /auth/email/verify-change?token=....
  4. The database updates users.email and sends a security notification to the old address.

A new address that already belongs to an account is refused at step 1 with 409 EMAIL_ALREADY_EXISTS, like registration.


POST /auth/close-account (Requires Bearer token + password)

{
"password": "Secret!Pass123"
}

Configured via kirak.json:

{
"auth": {
"account_close_window": "30d"
}
}
  • "30d" (default): Access is disabled immediately (403 ACCOUNT_CLOSED), and user data is permanently deleted after 30 days. During this window the user can reopen the account (below) and an administrator can restore it.
  • "24h": Permanent deletion after 24 hours.
  • "immediate": Account and all associated data purged in the same request.

When users close their own account with a window, Kirak emails them the deletion date (template account_closed), if the notifications module is configured.

A user who closed their own account can reopen it before its data is deleted, by signing in:

  1. They sign in as usual: password, phone code or social sign-in, and the MFA challenge if MFA is on. The closed state is revealed only after every check has passed; a wrong password still answers 401 INVALID_CREDENTIALS.
  2. Instead of tokens, sign-in answers:
    {
    "statusCode": 403,
    "error": "ACCOUNT_CLOSED",
    "details": {
    "reopen_token": "eyJ1Ijo...",
    "reopen_expires_in": 600,
    "closed_at": "2026-11-04T10:00:00",
    "purge_at": "2026-12-04T10:00:00"
    }
    }
    Show something like “You closed this account on 4 November. It will be deleted on 4 December. Reopen it?”
  3. If they choose to reopen, send the token:
    POST /auth/reopen-account
    {"reopen_token": "eyJ1Ijo..."}
    It answers like /auth/login, so the user is signed in. The token is valid for 10 minutes and works once (401 INVALID_REOPEN_TOKEN otherwise).

Sessions, API keys and integration connections ended at the close stay ended: the user reconnects their integrations. The before_reopen_account and after_reopen_account hooks run, and the audit log records auth.account_reopened.

ACCOUNT_CLOSED has no reopen_token when an administrator closed the account (only an administrator restores it), when the deletion date has passed, or when reopening is turned off:

{
"auth": { "account_reopen": false }
}

API keys enable server-to-server or script authentication without an interactive user session.

  • Prefix: All keys begin with kirak_ (55 characters, including a CRC32 checksum for offline validation).
  • Default Expiration: 365 days (enforced by design).
  • MCP Server Scoping: Restrict a key to specific MCP tools with "scopes": ["mcp:support"]. A request made with the key carries them as the caller’s api_key_scopes (The Caller in Custom Routes).
Terminal window
POST /auth/api-keys/create
{"name": "CI Deployment Worker", "expires_at": "2027-12-31T23:59:59Z"}
Authorization: Bearer kirak_a1B2c3D4e5F6...

To expose endpoints to unauthenticated users, add {"role": "*"} to the model’s access rules in models/*.json:

{
"access": {
"fetch": [{ "role": "*" }],
"create": [{ "role": "user" }]
}
}
  • Guest Principal: Requests without an Authorization header resolve to {"role": "guest"}.
  • Invalid Tokens Fail Fast: If an Authorization header is present but expired or invalid, Kirak returns 401 Unauthorized rather than silently downgrading the user to guest.
  • Rate Limits: Guests are rate-limited by client IP address.

Attach custom Python logic to authentication events without modifying runtime code:

# src/auth_hooks.py -- call register_auth_hooks(kirak) from register() in src/__init__.py
def register_auth_hooks(kirak):
@kirak.auth.hook("after_login")
async def add_tenant_info(result):
if result.get("status") == "success":
user_id = result["data"]["user"]["user_id"]
result["data"]["user"]["tenant_id"] = "tenant_123"
return result
@kirak.auth.hook("after_register")
async def notify_admin(result):
if result.get("status") == "success":
email = result["data"]["user"]["email"]
print(f"[AUTH HOOK] New user registered: {email}")
return result

Kirak automatically creates and manages these tables in your database:

Table Purpose
users Accounts, hashed passwords, roles, verification status, closure timestamps
auth_tokens Hashed refresh tokens, API keys, password reset tokens
auth_social Social provider identities mapped to user_id
auth_mfa Registered TOTP authenticators and encrypted secrets
auth_mfa_backup_codes Hashed backup codes
auth_otp Phone verification codes with expiration timestamps
auth_token_blacklist Expired single-use nonces and social exchange codes
kirak_rate_limits Sliding/fixed window counters for rate limiting