Skip to content

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.


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": true in kirak.json. Any model missing an "access" block will cause the application to fail at startup rather than throwing runtime 403 errors in production.


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.

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.

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.


{
"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" }]
}
}
  1. Exact Role Match: If current_user.role == rule.role, this rule is applied immediately.
  2. Wildcard Match (*): Matches any authenticated user or guest. Applied only if no exact role match exists.
  3. Deny: If neither matches, Kirak rejects the request with 403 PERMISSION_DENIED.

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 JWT sub claim.
  • Admins have no condition, so they see all rows across all users.

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.

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.


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": []
}
}
}
}
  • read: ["admin"]: Only users with the admin role receive this column in fetch, 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. A before_create or before_update hook 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."
    }

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" }]
}
}
{
"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")

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 Depends
from 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