Access Control & Row-Level Security
Kirak enforces a zero-trust, deny-by-default access control model. Every request is evaluated by the stateless AccessPolicyEngine before any SQL query is constructed or executed.
Deny by Default
Section titled “Deny by Default”Access rules are declared in the model’s "access" block:
| Model Configuration | Runtime Behavior |
|---|---|
"access" block present |
Deny-by-default. Only operations and roles explicitly declared are permitted. |
No "access" block |
Completely locked. All operations return 403 PERMISSION_DENIED for all roles. |
Production Tip (
strict_access): Set"strict_access": trueinkirak.json. Any model missing an"access"block will cause the application to fail at startup rather than throwing runtime 403 errors in production.
Access Policy Decision Pipeline
Section titled “Access Policy Decision Pipeline”Every incoming operation runs through the exact decision tree below:
flowchart TD Req["Incoming Operation Request<br/>(e.g., PUT /tasks/update)"] --> CheckAccess{"Does model have an 'access' block?"} CheckAccess -- No --> DenyNoAccess["403 PERMISSION_DENIED<br/>(Locked: No open mode)"] CheckAccess -- Yes --> CheckOp{"Is operation explicitly listed?"} CheckOp -- No --> DenyNoOp["403 PERMISSION_DENIED<br/>(Operation not exposed)"] CheckOp -- Yes --> MatchRole{"Does caller's role match a rule?<br/>1. Exact Match<br/>2. Wildcard '*'"} MatchRole -- No Match --> DenyRole["403 PERMISSION_DENIED<br/>(Role unauthorized)"] MatchRole -- Matches Rule --> CheckRLS{"Is 'condition' defined in rule?<br/>(e.g. user_id = {user_id})"} CheckRLS -- Yes --> AppendRLS["Append Parameterized WHERE Fragment<br/>(Enforces Row-Level Security)"] CheckRLS -- No --> CheckFields AppendRLS --> CheckFields{"Are 'access.fields' defined?"} CheckFields -- Yes --> ApplyFields["Filter readable / writable fields"] CheckFields -- No --> AllowFull["All fields accessible"] ApplyFields --> AllowFull AllowFull --> Exec["Execute Database Query"]A caller’s role is stored in users.role and encoded in their signed JWT access token.
Built-In Roles:
Section titled “Built-In Roles:”| Role | Description |
|---|---|
guest |
Unauthenticated requests (no Authorization header present). Cannot be assigned to a user account. |
user |
Default role assigned to all new user registrations. |
admin |
Full administrator privileges across models and admin endpoints. |
agent |
Used by coding agents or background worker profiles. |
system |
Internal Kirak runtime code running within with as_system():. Cannot be assigned to accounts or acquired via tokens. |
Custom Application Roles:
Section titled “Custom Application Roles:”You can define any lowercase alphanumeric role (e.g. "manager", "support", "billing", "editor"). Assign it to a user account via an admin action or direct database update:
from kirak.core.context import as_system
with as_system(): await kirak.update("users", {"id": 42}, {"role": "support"})The new role takes effect on the user’s next token refresh.
The access Policy Block
Section titled “The access Policy Block”{ "access": { "fetch": [{ "role": "admin" }, { "role": "*" }], "create": [{ "role": "user", "condition": "user_id = {user_id}" }, { "role": "admin" }], "update": [{ "role": "user", "condition": "user_id = {user_id}" }, { "role": "admin" }], "delete": [{ "role": "user", "condition": "user_id = {user_id}" }, { "role": "admin" }], "destroy": [{ "role": "admin" }] }}Rule Evaluation Order:
Section titled “Rule Evaluation Order:”- Exact Role Match: If
current_user.role == rule.role, this rule is applied immediately. - Wildcard Match (
*): Matches any authenticated user or guest. Applied only if no exact role match exists. - Deny: If neither matches, Kirak rejects the request with
403 PERMISSION_DENIED.
Row-Level Security (RLS)
Section titled “Row-Level Security (RLS)”Adding a "condition" string to an access rule restricts database rows using a parameterized SQL WHERE fragment:
{ "fetch": [ { "role": "user", "condition": "user_id = {user_id}" }, { "role": "admin" } ]}- When a regular user queries
/tasks/fetch, Kirak automatically appends:WHERE user_id = $1 AND deleted_at IS NULL {user_id}is extracted directly from the verified JWTsubclaim.- Admins have no condition, so they see all rows across all users.
Safe-Deny on Missing Claims:
Section titled “Safe-Deny on Missing Claims:”If a placeholder references a claim missing from the token, the value resolves to SQL NULL. Because column = NULL matches zero rows, the query safely fails closed.
Ownership Injection on create:
Section titled “Ownership Injection on create:”When create contains a simple equality condition like "user_id = {user_id}", Kirak automatically injects the caller’s user ID into the INSERT statement. The caller does not need to send user_id and cannot overwrite it.
The injected owner alone is enough for a row: a model whose other fields only the app writes (a
balance, a cart, a subscription record, all write: ["admin", "system"] or set by a
before_create hook) is created with {"data": {}}, and those fields take their defaults. A
create with no data on a model with no such condition is refused (No data provided for creation), and so is one that sends only fields the caller may not write.
Field-Level Security (access.fields)
Section titled “Field-Level Security (access.fields)”Control read and write permissions on individual columns using access.fields:
{ "access": { "fetch": [{ "role": "*" }], "create": [{ "role": "user" }], "fields": { "salary": { "read": ["admin", "hr"], "write": ["admin"] }, "internal_notes": { "read": ["admin"], "write": ["admin"] }, "password_hash": { "read": [], "write": [] } } }}Field-Level Rules:
Section titled “Field-Level Rules:”read: ["admin"]: Only users with theadminrole receive this column infetch,search, or GraphQL queries. For other roles, the field is stripped from responses.read: []: Completely hidden from all external roles (useful for sensitive tokens or hashes).write: ["admin"]: Only admins can set or update this column. Abefore_createorbefore_updatehook can still set it for any caller – see Setting fields the caller may not write.write_error: Customize the rejection message when an unauthorized user attempts to update a restricted column:"status": {"read": ["*"],"write": ["admin"],"write_error": "Status can only be updated by reviewers via the approval endpoint."}
Common Security Patterns
Section titled “Common Security Patterns”1. Public Read, Authenticated Author Write (Blog / Forum)
Section titled “1. Public Read, Authenticated Author Write (Blog / Forum)”{ "access": { "fetch": [{ "role": "*" }], "search": [{ "role": "*" }], "create": [{ "role": "user", "condition": "author_id = {user_id}" }, { "role": "admin" }], "update": [{ "role": "user", "condition": "author_id = {user_id}" }, { "role": "admin" }], "delete": [{ "role": "user", "condition": "author_id = {user_id}" }, { "role": "admin" }], "destroy": [{ "role": "admin" }] }}2. Multi-Tenant Organization Isolation
Section titled “2. Multi-Tenant Organization Isolation”{ "access": { "fetch": [{ "role": "user", "condition": "tenant_id = {tenant_id}" }], "create": [{ "role": "user", "condition": "tenant_id = {tenant_id}" }], "update": [{ "role": "user", "condition": "tenant_id = {tenant_id}" }], "delete": [{ "role": "user", "condition": "tenant_id = {tenant_id}" }] }}To resolve {tenant_id}, set the tenant context in your custom FastAPI endpoint:
from kirak import Caller, user_context
@app.get("/tenant/projects")async def get_projects(caller: Caller): # Fetch tenant membership membership = await kirak.fetch("memberships", {"user_id": caller["user_id"]}, limit=1) tenant_id = membership["data"][0]["tenant_id"]
# Execute fetch with tenant context injected with user_context({**caller, "tenant_id": tenant_id}): return await kirak.fetch("projects")The Caller in Custom Routes
Section titled “The Caller in Custom Routes”Kirak’s request middleware makes every request the current one, so a facade call in your own FastAPI route already runs as that request’s caller. To read the caller, or to refuse a request before the route does any work, use the same dependencies Kirak’s own routes use:
from fastapi import Dependsfrom kirak import Caller
@app.get("/my-orders")async def my_orders(caller: Caller): # any caller, guest included return await kirak.fetch("orders", {"status": "pending"})
@app.post("/reports")async def report(caller: dict = Depends(kirak.auth.requires("User"))): ...| Dependency | Behaviour |
|---|---|
Caller |
The caller as a dict. Accepts a Bearer JWT, an API key as the Bearer token, or the auth cookie; a request without a credential is a guest. A credential that is present but invalid answers 401 |
kirak.auth.requires(level) |
The same caller, after checking the access level (Guest, User, Admin or System): 401 MISSING_TOKEN without a credential, 403 PERMISSION_DENIED when the caller’s level is too low |
The caller dict has these keys:
| Key | Value |
|---|---|
user_id |
The user’s id; None for a guest |
role |
The user’s role, or guest |
email |
The user’s email (signed-in callers) |
token |
The access token for a JWT caller; None for an API key or a guest |
api_key_scopes |
API key callers only: the key’s scopes (for example ["mcp:support"]), or [] for a key without scopes. See API Keys |