Skip to main content

Control

Kilimanjaro's policy plane unifies three concerns behind one declarative surface: JSON-policy ABAC for fine-grained access control on collections, IRREVERSIBLE_ACTION_GATE for destructive actions that require multi-party approval, and the Maker-Checker framework for data-write workflows that route through approval chains before commit.

1. Policy model​

1.1 Two-layer access control​

Every protected operation passes through two sequential gates:

Caller → [Layer 1: RBAC] → [Layer 2: JSON-policy ABAC] → Operation
  1. RBAC. The edge verifies the caller holds the minimum platform role for the endpoint (e.g., PROJECT_MEMBER). Failures return K9O_ACCESS_DENIED (403) before any policy evaluation.
  2. JSON-policy ABAC. The origin server evaluates the project's JSON-policy rule for the specific action and resource. A passing RBAC check does not guarantee policy-level access — even a PROJECT_ADMIN is subject to the project's JSON policies unless the policy explicitly grants access.

1.2 One policy language, one source of truth​

The JSON-policy primitive is the single authoring surface for all access control across collections (RLS). Policy authors write one expression syntax for row access, approval predicates and the other policy surfaces.

1.3 Evaluation model​

PropertyBehaviour
DefaultDeny-by-default. Absent rules are equivalent to { "rule": false }.
CompositionAdditive with RBAC. RBAC passes first; policy is the second gate.
GranularityPer-action. Each action (select / insert / update / delete for collections) has an independent rule. Granting insert does not imply select.
Collection scopeRow-scoped. SELECT policies compile to Postgres WHERE predicates appended to every query. Rows not matching are silently excluded — no 403, empty result set.

2. JSON-policy expression syntax​

2.1 Rule shape​

A policy rule is a JSON object with a single top-level operator key. Rules may nest to a maximum depth of 20.

rule:
<operator>: [<operand>, <operand>, ...]

Boolean shorthand: rule: true (always allow) and rule: false (always deny) are valid terminal rules.

2.2 Subject context​

The subject object carries the authenticated caller's claims at evaluation time:

FieldTypeDescription
subject.idstringThe authenticated identity (usr_<base62> for operators; eu_<base62> for end-users; absent for anon)
subject.rolestring"anon" for the anon key; the platform role for authenticated callers; "service_role" for service-role callers
subject.rolesstring[]Full array of platform roles from the JWT roles claim
subject.groupsstring[]Group memberships from the JWT groups claim
subject.emailstringThe caller's email (subject to PII-JOIN authority gating for end-users)
subject.projectId / subject.orgIdstringActive scope for the request

Operator vs end-user identity. The subject.id prefix distinguishes record types — usr_* for operator-class identities, eu_* for end-user identities. Policies that need to distinguish check the caller's roles rather than the prefix:

policy:
collections:
documents:
actions:
select:
rule:
or:
- contains: [subject.roles, "PROJECT_ADMIN"] # operator — full access
- eq: [resource.ownerId, subject.id] # end-user — own records

2.3 Resource context — collections​

For collection operations, resource.* exposes the record being accessed:

FieldTypeDescription
resource.idstringThe record's id field
resource.collectionstringThe collection name
resource.<field>anyAny top-level field on the record
resource_new.<field>anyUPDATE only — the proposed updated values

resource_new enables rules like "users may not escalate their own role": neq: [resource_new.role, "admin"] paired with the user's own-record predicate.

2.4 Operator vocabulary​

CategoryOperators
Comparisoneq, neq, gt, lt, gte, lte, is, btw
Membershipcontains, not_contains, in, not_in
Logicaland, or, not
Terminaltrue (allow all), false (deny all), null (absent — evaluates to deny)

All operators use array operand form: { "<operator>": [<operand1>, <operand2>] }. Operands are resolved as context references (strings starting with subject. or resource.) or literal values (other strings, numbers, booleans). Unknown context references resolve to null, and comparisons against null evaluate to false — a missing claim never grants access.

There is no string-pattern operator (no starts_with, ends_with or regular-expression matching); use eq, in and contains. is is a null check whose second operand must be the literal null (it compiles to SQL IS NULL, closing the trap that eq: [field, null] would never match); express "is not null" by composing { not: [{ is: [field, null] }] }. btw is an inclusive range — { btw: [field, [low, high]] } — over numbers or ISO 8601 dates.

3. Collection RLS policy​

3.1 Declaration in migration files​

Collection policies live alongside the schema in migration files — schema and access rules version together.

# 20260502143022_create_users.migration.yaml
schema:
  collections:
    users:
      columns:
        id:       { type: uuid, default: gen_random_uuid(), primary: true }
        email:    { type: text, notNull: true, unique: true }
        ownerId:  { type: text, notNull: true }
        role:     { type: text, default: "'member'" }

policy:
  collections:
    users:
      actions:
        select:
          rule:
            or:
              - eq: [subject.id, resource.ownerId]
              - contains: [subject.roles, "PROJECT_ADMIN"]
        insert:
          rule:
            contains: [subject.roles, "PROJECT_MEMBER"]
        update:
          rule:
            or:
              - and:
                  - eq: [subject.id, resource.ownerId]
                  - neq: [resource_new.role, "admin"]
              - contains: [subject.roles, "PROJECT_ADMIN"]
        delete:
          rule:
            contains: [subject.roles, "PROJECT_ADMIN"]

Policy declarations may also appear in a standalone k9o.policy.yaml file at the project root. When both a migration-embedded policy and a k9o.policy.yaml entry exist for the same collection action, the more recently applied migration policy wins (last-write-wins).

3.2 Compilation to Postgres RLS​

The platform compiles JSON-policy rules to Postgres RLS policies at migration-apply time. For each collection + action pair:

  1. Translate the JSON-policy rule to a SQL expression safe to embed in USING (...) or WITH CHECK (...).
  2. Create a Postgres RLS policy on the collection table.
  3. Enable RLS on the table.

The data-plane DB credential has no BYPASSRLS attribute — RLS is always active. UPDATE rules compile selectively: sub-rules that reference only resource.* land in USING (read predicate); sub-rules that reference resource_new.* additionally emit WITH CHECK (write predicate); sub-rules touching only subject/literal contexts land in both.

A single comparison expression within UPDATE MUST NOT mix resource.* and resource_new.* on the same comparison's two sides — resource.status != resource_new.status is rejected at policy compile time with K9O_POLICY_BUNDLE_INVALID. Use two separate rule conditions or a trigger function for old-vs-new comparisons.

3.3 Policy update lifecycle​

Policy changes take effect at migration-apply time — they are not hot-reloadable. Changing a policy rule requires a new migration file. The migration pipeline ensures policy changes apply atomically with schema changes.

Setting rule: true (allow all) compiles to USING (true) — the Postgres RLS policy remains in place. To fully remove a policy (returning the table to default-deny), the migration must explicitly drop it: DROP POLICY <name> ON <table>.

3.4 Native vs Standalone mode (Gate end-user JWTs)​

When the project's data plane lives on Kilimanjaro AND the calling JWT is a project-level end-user JWT (subject.id prefix eu_*), the gateway compiles a restrictive end-user scope, <collection>_end_user_scope, keyed on the collection's declared owner column (ownerColumn). A customer-authored rule can narrow that scope and never widen it. The author of the collection's RLS policy does not write per-end-user filter logic for this baseline; the gateway prepends a subject.id-bound predicate ahead of the authored clauses:

-- Author writes:
USING (subject.role = 'admin' OR resource.published = true)

-- Gateway compiles for end-user JWT (subject.id = "eu_abc123"):
USING (
resource.owner_id = 'eu_abc123' -- gateway-prepended scope
AND (subject.role = 'admin' OR resource.published = true)
)

The scope column is the collection's declared ownerColumn, not a column that must be named owner_id. A collection with no owner column denies end users unless it declares gate_scope: none (migration DSL) or gateScope: "none" (collection create and update bodies): an operator choice that is audited as data.write.collection.gate_scope_changed and is not approval-gated. A write that supplies an owner other than the caller is refused with 400 K9O_INVALID_FIELD_VALUE and context.reason: "owner_not_caller".

Standalone-mode customers — whose data plane lives outside Kilimanjaro — receive Gate JWT issuance and hardware attestation only. Auto-scoping is the customer's responsibility on their own data plane; the JSON-policy evaluation surface is identical across modes, but Kilimanjaro does not enforce RLS predicates against an external database.

4. Storage access​

Access to buckets and objects follows the caller's project role: read and list for project members, upload and delete for writers, and bucket lifecycle for admins. A project's IAM policy can further narrow what a role may do; that ceiling applies to the buckets:<verb> actions and is qualified by bucket name. A denied call returns K9O_ACCESS_DENIED (403).

5. Service-role subject context​

The service_role API key presents subject.role = "service_role" at policy evaluation time. It does not automatically bypass policies. Policies must explicitly grant elevated access:

actions:
insert:
rule:
or:
- eq: [subject.role, "service_role"]
- contains: [subject.roles, "PROJECT_ADMIN"]

This design preserves the single-policy-language principle — there is no out-of-band bypass path that circumvents policy evaluation. If a project's policy does not explicitly grant service_role access, service-role calls pass through the same evaluation as PROJECT_ADMIN (whose RBAC level service_role inherits).

6. IRREVERSIBLE_ACTION_GATE​

6.1 Gated actions​

Certain platform actions are destructive, hard to reverse, or require multi-party attestation. These actions require an approved gate token before the platform executes them. The gate mechanism implements a configurable maker-checker chain.

ActionTrigger context
Project force-delete (non-empty, Sovereign tiers)Project management
CUSTODY_MODE_DOWNGRADE — move to a weaker custody modeCustody transitions
PROJECT_KEK_ZEROIZE — crypto-shred the project's key-encryption keyZero-Residue erasure
RESIDENCY_REGION_REMOVE — drop a jurisdiction from the residency setData residency
K9O-CORE de-provisioningProject lifecycle
MFA device unenrollment without replacementAccount security
EXTENSION_PURGE — destroy extension's per-project schemaExtension lifecycle

6.2 Gate flow​

1. Requester calls POST /@<projectSlug>/gates with the action context.
2. Platform creates a gate token (status: "pending_approval").
3. Approvers are notified.
4. Each approver calls POST /@<projectSlug>/gates/<gate-id>/approvals.
5. Platform evaluates each approver against the chain constraints.
6. Once minApprovals is reached (status: "approved"), the token is redeemable.
7. Requester includes X-K9O-Gate-Token: <gate-id> in the gated action call.
8. Platform verifies the token is approved and unexpired, then executes (status: "redeemed").

6.3 Gate token shape​

{
"id": "apr_kQ3pZ9rL2sW8",
"orgId": "org_def456",
"projectId": "proj_abc123",
"requestedBy": "usr_alice",
"actionType": "CUSTODY_MODE_DOWNGRADE",
"actionContext": { "targetMode": "PLATFORM_MANAGED" },
"chainConfig": {
"minApprovals": 1,
"constraints": [
{ "type": "not_originator" },
{ "type": "role_required", "role": "PROJECT_ADMIN" }
]
},
"requiredApproval": { "min": 2 },
"approvals": [],
"status": "pending_approval",
"expiresAt": "2026-05-03T14:30:22Z",
"redeemedAt": null
}

This is the shape returned for a gate created with chainConfig.minApprovals: 2; request minApprovals: 2 to get requiredApproval.min of 2.

FieldNotes
idapr_ + base62 (12 chars)
actionTypeUpper-case value from the gated-actions table, for example CUSTODY_MODE_DOWNGRADE
actionContextAction-specific metadata; included in audit log
chainConfig.minApprovalsRequest field: required count of valid approvals before the token becomes redeemable (1 to 10). In the response the threshold is requiredApproval.min; chainConfig.minApprovals always reads 1
chainConfig.constraintsApprover constraints applied to each approval
statuspending_approval / approved / redeemed / expired / cancelled / rejected
expiresAtDefault 24h from creation; configurable (max 7 days)

6.4 Approver constraints​

ConstraintBehaviour
not_originatorApprover cannot be the gate's requestedBy
not_subject_ofApprover cannot be the subject of the gated action (e.g., a user being removed cannot approve their own removal)
distinct_fromApprover must be distinct from all prior approvers
role_requiredApprover must hold the specified platform role
group_requiredApprover must be a member of the specified org Group (live lookup, not JWT-cached)

Violations return K9O_GATE_CONSTRAINT_VIOLATION (422) with context.constraint naming the failing constraint.

6.5 Lifecycle endpoints​

POST /@<projectSlug>/gates — create
GET /@<projectSlug>/gates — list (cursor-paginated)
GET /@<projectSlug>/gates/<gate-id> — single-gate detail (includes yourStep)
POST /@<projectSlug>/gates/<gate-id>/approvals — approve
POST /@<projectSlug>/gates/<gate-id>/reject — reject (carries a comment)
DELETE /@<projectSlug>/gates/<gate-id> — cancel (requester or PROJECT_ADMIN)

yourStep field. Single-gate GET includes a computed yourStep reporting whether the authenticated caller is currently eligible to act as an approver. eligible: true when the user passes all approver constraints; reason carries a machine-readable code when ineligible (NOT_ORIGINATOR, ALREADY_APPROVED, INSUFFICIENT_ROLE, GROUP_MEMBERSHIP_REQUIRED, GATE_NOT_PENDING). Computed per-request from current state — not stored on the token.

Immutability. Gate fields are immutable after creation. There is no PATCH .../gates/<id> endpoint. To change a gate, cancel it and create a new one; prior approvals do not carry over. An approver who wants a change rejects the gate with a comment saying what to change, and the requester creates a new gate.

Redemption. Include X-K9O-Gate-Token: <gate-id> in the gated action call. The token transitions to "redeemed" immediately on successful action execution. For CUSTODY_MODE_DOWNGRADE the gated call is POST /@<projectSlug>/custody-mode-transition with the body { "targetMode": "PLATFORM_MANAGED" }; the gate's actionContext.targetMode must match it.

Custody-mode descent. A downgrade is one gate per transition, whichever rungs it spans. Any two distinct modes transition directly — dropping from HYOK straight to Platform-Managed is a single transition, so a single gate and a single redemption, not one gate per rung skipped.

6.6 Org-scoped gates​

The gate mechanism supports org-scope as well as project-scope: org-scoped gates use /gates on the org subdomain (<orgSlug>.api.k9o.io/gates; no @<projectSlug> marker). Token shape, chainConfig defaults, approver constraints, yourStep semantics, immutability, redemption mechanics, and audit events are identical to project-scoped gates; the differences are the URL prefix and the minimum auth role (ORG_ADMIN rather than PROJECT_ADMIN for creation).

No org-level gated action is defined at v2 launch — the org-scope enum is empty, and the mechanism is in place for a future org-scoped destructive action to use. The scope split is enforced at creation: a project-level actionType submitted at org scope, or vice versa, returns K9O_GATE_ACTION_SCOPE_MISMATCH (400).

7. Maker-Checker policy framework​

7.1 What it does​

Maker-Checker is the multi-row data-write generalization of IRREVERSIBLE_ACTION_GATE. Where the gate primitive gates a single platform action behind multi-party attestation, Maker-Checker gates ordinary data writes (insert / update / delete on collections) behind a declarative approval policy graph that mixes auto-approval predicates, queue-to-approver fallback, escalation paths, delegation rules, bulk-approval criteria, and concurrent-edit conflict resolution.

7.2 Bindings​

BindingSubstance
Built into the platformMaker-Checker is a first-class capability of the platform — not extension-only, not optional. Extensions cannot bypass at the gateway.
Read-Committed defaultPending changes are invisible to standard SDK reads, downstream extensions, workflow triggers, realtime subscriptions, and other readers. Pending state is visible only via dedicated approval-queue surfaces and the maker's own session-aware UI affordance.
Auto-approval is the primary scale primitiveMost changes auto-commit through declarative JSON-policy predicates. Per-row human approval at sustained 3 changes/sec is unworkable; human approval is the residual exception path, not the base case.
Bulk human approval — full taxonomyby-maker-session bulk + by-criteria-predicate bulk + by-time-window bulk + by-table-scope bulk + delegation. Once one dimension is supported, the marginal cost of adding others is near zero.

7.3 Approval policy predicate​

A data write enters the approval queue when it matches an approval policy. An approval policy is created with POST /@<projectSlug>/approval-policies and names a collection, an operation, the action queue, and a JSON predicate over the pending change. A write that matches the predicate is held for a second person to approve; a write that does not match commits directly.

{
"collection": "orders",
"operation": "update",
"action": "queue",
"predicate": { "gt": ["change.row.amount", 1000] }
}

The predicate is a JSON object in the same operator vocabulary as RLS (§2.4); a string or YAML body is refused. change.row is the request body, so on an update change.row.amount matches only when the update sends amount. An update that leaves amount out does not match this predicate and commits directly.

7.4 Approval queue API​

Pending changes are worked through the /pending-approvals surface, keyed by pending-approval ID:

GET /@<projectSlug>/pending-approvals — list pending changes
GET /@<projectSlug>/pending-approvals/<pendingId> — a single pending change
POST /@<projectSlug>/pending-approvals/<pendingId>/approve — approve
POST /@<projectSlug>/pending-approvals/<pendingId>/reject — reject, with an optional reason
POST /@<projectSlug>/pending-approvals/bulk — approve or reject a matched subset in one call

Bulk approval accepts a predicate that selects the subset of pending changes to act on in one call — by maker session, by criteria, by time window, or by table scope. It runs the same constraint evaluation as per-change approval; the bulk surface is an efficiency primitive, not a relaxation of the rules. A pending change whose base committed-state version has gone stale under a concurrent write is auto-rejected with K9O_APPROVAL_STALE_BASE (409); an admin may override with ?force_overwrite=true.

The server SDKs wrap this queue as approvals (list, approve, reject, bulk) and create queue policies with approvalPolicies. An approval policy names a collection, an operation, the action queue, and a predicate over the pending change (change.row.<column> for the proposed values, change.table for the collection):

Create the client once

client
import { createClient } from "@k9o/core";

const k9o = createClient({
  orgSlug: "acme",
  projectSlug: "task-app",
  apiKey: process.env.K9O_API_KEY,
});

Control · E1: Agentic Governance: approvals and approval policies

A policy decides which writes wait for a person. A write sent with requireApproval() is queued when a queue policy matches (HTTP 202) and applied at once when an auto_approve policy matches. Project admins and auditors see the whole queue; other members see only the changes they proposed.

1. Queue writes
// The collection this example uses (created once, by a migration): expenses (id text PRIMARY KEY, amount integer)
import { isQueuedWrite } from "@k9o/core";

// 1. A rule: inserts into "expenses" above 1000 wait for a decision.
const { data: policy } = await k9o.approvalPolicies.create({
  collection: "expenses",
  operation: "insert",
  action: "queue",
  predicate: { gt: ["change.row.amount", 1000] },
});
console.log(policy.id, policy.action);

// 2. Writes that ask to be queued. Each one is either queued (202) or applied at once.
for (const [id, amount] of [["e1", 5000], ["e2", 7000], ["e3", 9000]] as const) {
  const write = await k9o.from("expenses").insert({ id, amount }).requireApproval();
  console.log(id, isQueuedWrite(write) ? "queued" : "applied");
}
Output · bash
apo_c5bV8hGbeor3 queue
e1 queued
e2 queued
e3 queued
  • Remove the rule when the example is done: k9o.approvalPolicies.delete(policy.id).

list returns an empty list when the queue is empty, so check before reading the first entry. approve and bulk act on changes other people proposed, and the queue is project-wide: bulk decides every pending change that matches the predicate, including other people's, so keep the criteria narrow and compare affectedIds with what you meant. The bulk response carries affectedCount and affectedIds for the changes it decided, and failed: [{id, code, reason}] for each change it could not decide; a failed row does not abort the others. approve and bulk need the queue-admin role, and reject needs a non-empty reason. A policy you no longer need can be deleted with approvalPolicies.delete(id).

7.5 Composition with RLS​

Maker-Checker composes with the underlying RLS policy. A write that satisfies the RLS policy may still be queued by Maker-Checker; a write that fails RLS is rejected before Maker-Checker evaluates. Both layers are active simultaneously — there is no bypass path.

7.6 Audit attribution​

Maker-Checker-gated changes emit a chain of audit events: the maker's proposal (data.write.approval.proposed), each checker decision (data.write.approval.approved / data.write.approval.rejected), and the first-applied-write event paired with the originating proposal ID for forensic continuity. The original data event (data.write.collection.<name>.update etc.) carries meta.approvalChain.<id> pointing back to the proposal.

8. Policy authoring surface​

Policy is authored in one of two equivalent locations, both resolving to the project's _sys.authorization_policies table (last-write-wins on identical collection + action keys):

  • Migration files — for engineering teams operating the schema lifecycle through migrations/*.k9o.yaml. Policy and schema version together.
  • k9o.policy.yaml — a standalone policy document at the project root, for policy that isn't coupled to a schema migration.

The Console's visual policy builder and the CLI both write through the REST bundle API below rather than being a third parallel store.

9. Policy bundle management​

A project's entire policy — every RLS rule, approval rule, and gate constraint — is one versioned document: the bundle, identified by pol_<base62>. Bundles move through a four-state lifecycle, and publishing is itself gated (see §9.2):

StateMeaning
draftAuthored, not active; freely editable; no runtime effect
publish-pendingPublish requested; awaiting the second approver
activeCurrently live; evaluated at runtime; immutable
archivedPreviously active and replaced; retained for audit; immutable

9.1 Endpoints​

GET /@<projectSlug>/policy — the current active bundle
GET /@<projectSlug>/policies — list bundles
POST /@<projectSlug>/policies — create a draft
GET /@<projectSlug>/policies/<policyId> — a specific bundle
PATCH /@<projectSlug>/policies/<policyId> — update a draft
DELETE /@<projectSlug>/policies/<policyId> — delete a draft
POST /@<projectSlug>/policies/<policyId>/publish — publish a draft (gated; see §9.2)

Editing, deleting, or republishing an active or archived bundle returns K9O_POLICY_PUBLISH_CONFLICT (409) — past bundles are immutable. A bundle that fails validation at publish (a referenced column dropped since the draft was written, for example) returns K9O_POLICY_BUNDLE_INVALID (422), and the previously-active bundle stays live. A request for a policyId that doesn't exist returns K9O_POLICY_NOT_FOUND (404).

9.2 Publishing is gated​

Publishing a bundle is a maker-checker action in its own right: the admin who authored a draft cannot also activate it. A distinct second PROJECT_ADMIN must approve the publish before it takes effect — server-enforced, with no per-org opt-out. A solo-admin project cannot change its own policy without adding a second admin.

Recovering from a bad publish is always a forward publish, never an edit to history. To return to an earlier bundle, create a new draft with that bundle's content and publish it through the same gated path; the platform-shipped Lockdown template is a deny-all starting document for the "stop evaluating a permissive policy now" case.