A declarative ReBAC policy language, and why we compiled it to tuples
Access control that stays in sync with code
Role-based access usually rots in the same way. Someone hand-writes the rules, the code moves on, and the rules don't. One day a new endpoint ships without a rule, or an old rule still grants access to a resource that has changed shape, and nobody notices until it matters.
On a multi-tenant API platform I built, I wanted two things from authorization: rules that couldn't drift from the code they protect, and checks fast enough to run on every request without anyone thinking about the cost. This post is about how I got there — a small declarative policy language, compiled down to relationship tuples — and the one design decision I'd make differently.
The shape of the problem
The platform had three levels of scope: organisations, projects inside organisations, and resources inside projects. A user could be an admin of one organisation, a member of a project in another, and hold an API token scoped to a single project. Every request had to answer one question quickly: can this principal do this thing to this resource?
There are two broad ways to answer that. You can evaluate policies at request time — load the relevant documents, match them against the request, decide. Or you can precompute the answer into a form that makes the check a lookup. I chose the second, using the model from Google's Zanzibar paper: access expressed as relationship tuples, stored in Ory Keto, and checked with a single call.
A declarative policy language
People don't want to write tuples. They want to say "members of this project can read its gateways". So the source of truth was a small policy document, validated with Zod:
const policySchema = z.object({
version: z.literal("1"),
effect: z.enum(["allow"]),
role: z.string(),
resources: z.array(z.string()),
principals: z.array(z.string()),
});
A document names a role, the resources it applies to, and the principals who hold it. Policies were bound at organisation or project level, so the same document could express access at any of the three scopes. Creating an organisation or a project seeded a default set of roles, so a new tenant started with sensible access instead of none.
Why compile to tuples
Each policy document expands into relationship tuples — "this principal holds this role on this resource" — and those tuples are what the authorization store actually holds:
[
{ "namespace": "project", "object": "proj_42", "relation": "member", "subject": "user_7" },
{ "namespace": "project", "object": "proj_42", "relation": "admin", "subject": "user_3" }
]
Compiling rather than interpreting buys three things:
- Fast checks. A permission check becomes a question about stored relationships, not an evaluation of documents. Checks came back in under a millisecond, cheap enough to put on every request.
- One mental model at every scope. Organisations, projects and resources are all just objects that tuples point at. Inheritance down the hierarchy is a property of the relationships, not special-case code.
- A clean split between authoring and enforcement. Humans edit policies; the enforcement layer only ever sees tuples. You can change the authoring language without touching the hot path.
Diff-based reconciliation
The obvious way to keep tuples in sync is to delete everything for a scope and rewrite it whenever a policy changes. That works until it doesn't: there's a window where the old tuples are gone and the new ones aren't written, and during that window real users get denied.
Instead, reconciliation computes a diff. Expand the current policies into the tuples they should produce, read the tuples that exist, and apply only the difference:
async function reconcile(scope: Scope) {
const desired = expandPolicies(await policies.forScope(scope));
const actual = await tupleStore.list(scope);
const toAdd = desired.filter((t) => !actual.some((a) => sameTuple(a, t)));
const toRemove = actual.filter((a) => !desired.some((t) => sameTuple(a, t)));
await tupleStore.patch({ insert: toAdd, delete: toRemove });
}
Unchanged tuples are never touched, so there is no window where access disappears. The reconciliation step also became the natural place for telemetry: every run recorded what it added and removed, which made "why can't this user see that project" a question you could answer from traces instead of guesswork.
Never let the tuple store get ahead of the database
The subtler bug is ordering. Policy changes live in Postgres; tuples live in Keto. If you write tuples inside the request and the database transaction later rolls back, the tuple store now grants access that the database says doesn't exist.
The fix was to tie reconciliation to the transaction's outcome. Each request ran in its own database session, and reconciliation was registered as an after-commit hook:
await db.transaction(async (session) => {
await policies.bind(session, projectId, policy);
session.afterCommit(() => reconcile({ project: projectId }));
});
If the commit fails, the hook never runs and the tuple store is untouched. If it succeeds, the tuples follow. The tuple store can lag the database for a moment; it can never get ahead of it. For authorization, that is the right way round — a brief delay in gaining access is a support ticket, phantom access is an incident.
Generating gateway rules from the code
The second half of "can't drift" was the edge. Requests passed through Ory Oathkeeper, which needs a rule for every route: how to authenticate the caller, and whether to ask the authorization store before forwarding the request. Writing those rules by hand is exactly the kind of configuration that drifts.
So the rules were declared where the routes are, as decorators on the NestJS controllers:
@Controller("projects/:projectId/gateways")
export class GatewaysController {
@Get()
@OathkeeperAccessRules()
@OathkeeperJwtAuthenticator()
@OathkeeperKetoAuthorizer()
list(@Param("projectId") projectId: string) {
/* ... */
}
}
At startup, a generator reflected over every controller, read the decorator metadata, and compiled the full set of Oathkeeper rules: the authenticator, a remote authorizer that calls the authorization store, and header mutators that pass the caller's identity downstream. A validator then checked the compiled rules against the platform's own constraints before they were used.
The effect was that a route and its access rule could no longer exist separately. Add an endpoint and its rule comes with it; delete one and the rule goes too. A whole class of misconfiguration bugs — the forgotten rule, the stale rule, the typo in a path — stopped being possible, because there was no manual rule configuration left to get wrong.
What I'd do differently: policies, not roles
The design decision I regret is modelling access around roles first.
Roles are the natural starting point: admin, member, viewer. The first version bound principals to roles, and policies were mostly a way of saying which role applied where. That held up until the platform needed assume-role — a principal temporarily acting with a different set of permissions, the way AWS lets you assume a role for a session.
Assume-role is natural when the unit of access is a policy: you attach a policy to a session for a while. It is awkward when the unit of access is a role membership, because "temporarily a member" is not something the role model expresses well. I ended up reworking the model so that policies were the primary unit and roles were a convenient way of naming common ones.
The lesson I took from it: pick the most general unit of access you can afford on day one. Roles can always be built from policies. Policies can't easily be retrofitted onto a system that was built from roles. If your product is likely to need delegated, temporary or scoped access — and most B2B products eventually are — start with policies and let roles be a convenience on top.
Takeaways
- Compile authoring into enforcement. Let people write policies; let the hot path read precomputed relationships.
- Reconcile by diff, not rewrite. Apply only what changed so access never blinks.
- Order writes by commit. Run reconciliation after the database commits, so the tuple store can lag but never lead.
- Generate edge rules from code. If a route and its rule are declared in the same place, they can't drift.
- Start with policies. Roles are easy to add later; generality is not.
Building something in this space?