Row-level security (RLS) — filter by rule
Declarative per-row policies compiled into query filters — the grammar, the context variables, how policies compose, and the fail-closed contract.
RLS answers a question the other layers can't: which rows of an object may this user touch? Object permissions say "can read tasks"; the OWD baseline says "tasks are private"; RLS says "only the tasks assigned to you" — as a declarative policy, compiled into the query.
Two properties define how it behaves:
- It's a filter, not a row hook. Policies compile to a data filter that is pushed down into the query, so a restricted user's list is narrower — they don't get denied, they get fewer rows.
- It's fail-closed — where it applies. If policies apply and every one of them fails to compile, the query denies everything rather than admitting anything; an object with no applicable policy is left unfiltered, not hidden. See the contract.
RLS is the expert escape hatch. Reach for it when sharing rules, the OWD baseline, and scope depth can't express the rule — not before.
Anatomy of a policy
Policies live on a permission set under rowLevelSecurity:
import { definePermissionSet } from '@objectstack/spec';
export const ContributorAccess = definePermissionSet({
name: 'contributor',
label: 'Contributor',
objects: {
showcase_task: { allowRead: true, allowEdit: true },
},
rowLevelSecurity: [
{
name: 'task_own_rows',
label: 'Own Tasks Only',
object: 'showcase_task',
operation: 'select',
using: 'assignee == current_user.email',
positions: ['contributor'],
enabled: true,
},
],
});| Property | Type | Notes |
|---|---|---|
name | string | snake_case identifier |
label | string | Human-readable name |
object | string | Target object — or '*' to apply to every object |
operation | 'select' | 'insert' | 'update' | 'delete' | 'all' | Which operation the policy guards. A select policy also bounds writes when no write-class policy applies — see below |
using | string | Predicate for rows the user may see / act on (compiled into the query filter) |
check | string | Predicate every row an insert or an update writes must satisfy: each row of an insert (an array insert included) as its beforeInsert hooks leave it, and each row an update changes (by id or multi: true) after its beforeUpdate hooks. One failing row refuses the whole write. Omit it and using stands in, unless another applicable policy for the same operation declares a check — see the fail-closed contract |
positions | string[] | Which positions the policy applies to. Omit = everyone |
enabled | boolean | Default true. false switches the policy off — a disabled policy is not evaluated |
At least one of using / check is required.
Choosing operation: select narrows reads (the common case);
insert / update / delete guard the matching write; all applies to
everything. Internally find / findOne / count / aggregate all map to
select.
select also bounds writes when nothing else does. A write target must be
inside the caller's readable set, so when no write-class policy applies
to a caller on an object, the update / delete scope is derived from that
caller's select policies — a record they cannot read is one they cannot
modify, by id or in bulk. Authoring a write-class policy switches the
derivation off for that class: an authored update predicate then joins
the update filter as one more OR term, widening past the platform's
owner-scoped write floor exactly as written. A write policy adds rows; it
does not take away a row the floor admits (one the caller created), whether
or not record sharing replaces the floor for that row. Two exceptions: on an
object whose org-wide default is public_read_write, an update has no floor,
so an authored update policy is the whole scope and does refuse the caller's
own non-matching row; and on a controlled_by_parent detail, a write is
judged by its master gate instead of the floor, so a detail policy bounds every
detail row written, by id or by predicate (a write made on another user's
behalf keeps the floor). To cap what a caller
may do to rows they created, use a check (it judges the stored image) or a
beforeUpdate / beforeDelete lifecycle hook (it sees the prior row as
ctx.previous). Nothing is derived for insert
(there is no pre-existing row to be visible), and a caller holding the
read-side superuser bypass (viewAllRecords on a private or deployment-level
object) is not narrowed, because their readable set is already unbounded.
A write widener never reaches a row the caller cannot read. "You may not
modify what you cannot see" is a floor, not a default the write filter
overrides: before a single-record update / delete runs, the target row is
re-read under the caller's own read scope together with the write filter,
and a row that read cannot see answers exactly what a missing id answers
(404 RECORD_NOT_FOUND). A predicate (multi: true) update / delete is
narrowed the same way: it matches only the rows the caller's read returns for
its predicate, so a row the widener admits but the caller cannot read is not
written and not counted. On a
public_read object that read scope is every row (minus any select
narrowing you authored), so an update widener works as written. On a
private object — the default OWD — the read scope is the caller's own
records, their access depth and the records shared with them, so an update
widener reaches only rows the caller can already read; everything else it
admits by predicate is still refused.
Under record sharing, a predicate write is bounded by the write scope, not
the read scope. When record sharing is composed (@objectstack/plugin-sharing),
a predicate (multi: true) update / delete on a private object writes only
the rows the caller may write: their own records, their access depth and
queue membership, plus edit shares for an update (a share never grants
delete, ADR-0111 D3). A row the caller holds only through
a read share is readable, and an app update widener admits it, but a
predicate write does not reach it: the row is left as it was and the write
answers no error. To write such a row, address it by id alone
(where: { id }, or the payload id): a by-id write is judged by id, and the
widener admits it as written. A where that carries a scalar id beside
other keys under multi: true, and an id that is falsy ('', 0), run as
predicate writes and meet the same bound.
Known limitation — an app-authored write widener does nothing on a
private object without a matching read grant. To let a position edit
other people's records on a private object, grant read reach to the same
rows as well: viewAllRecords (or a wider readScope depth) on the
object in the same permission set, or a
sharing rule or record share that shares
those rows with the position. An additional select policy is not a read
grant — RLS only narrows, so it cannot make a private row visible. The
paired spelling is shown in the
supervisor recipe.
The expression grammar
RLS predicates are canonical CEL, lowered into a query filter by the shared pushdown compiler — the same lowering sharing rules use. A broad subset compiles; anything the compiler can't lower fails closed (the policy matches zero rows) rather than raising at query time.
These all compile:
| Form | Example |
|---|---|
| Column equals a context value | created_by == current_user.id |
| Column equals a literal | status == 'active' |
Comparison (!=, >, >=, <, <=) | amount > 1000 |
| Set membership | owner_id in current_user.org_user_ids |
| Null check | deleted_at == null |
| Prefix / suffix / substring | code.startsWith('EU-') |
Boolean combination (&&, ||, !) | owner_id == current_user.id && status == 'open' |
| Always true | 1 == 1 |
What fails closed (never silently dropped, per the security contract): a
subquery, a cross-object / relation hop (account.region), arithmetic
(+ - * /), and any function call — including time functions like NOW() /
CURRENT_DATE. Express anything subquery-shaped as a pre-resolved
current_user.* array instead (see Context variables).
The legacy SQL-ish spellings (= for equality, IN (...)) still compile through
a transitional bridge that rewrites them to == / in, but canonical CEL is the
authoring form — the bridge logs a deprecation warning.
Two ways to combine conditions. Within one policy, use CEL && / || —
owner_id == current_user.id && status == 'open' compiles. Across policies,
separate policies on the same object also compose with OR (see below), so
"owner or team member" can be one || predicate or two policies. Reach for
multiple policies when the alternatives apply to different positions.
Context variables
Predicates reference the acting user through current_user, and record fields
as bare column names (no record. prefix — that's the UI/flow convention,
not this one):
| Variable | Source |
|---|---|
current_user.id | The acting user's id |
current_user.organization_id | The acting tenant |
current_user.positions | The user's positions (array) |
current_user.org_user_ids | User ids in the user's org (array) |
current_user.queues | The ownership queues the user belongs to in the active organization (array of queue names) — the set that lets a queue's members see the records parked in it (Queues and assignment rules) |
current_user.email | The user's email |
current_user.KEY | A set a roster object declares under membershipKeys (array, read with in) |
current_user.name is deliberately not exposed. Names aren't unique — a
policy keyed on a display name would hand a second "John Smith" someone else's
rows. Match on id or email, which are.
Any other current_user.KEY is a membership set: a pre-resolved array that
lets a policy express set membership without the subqueries the grammar doesn't
allow. Declare it first — a membershipKeys entry on the roster object whose
rows define the set names the user column (userField), the column whose
values form the set (valueField: a reference column, or id) and an optional filter over the
roster's own columns, and every policy reads the result as current_user.KEY:
import { ObjectSchema } from '@objectstack/spec/data';
import { definePermissionSet } from '@objectstack/spec';
// Roster: one row per (portal user, account)
export const AccountMember = ObjectSchema.create({
name: 'account_member',
sharingModel: 'private',
fields: {
user: { type: 'user', required: true },
account: { type: 'lookup', reference: 'account', required: true },
active: { type: 'boolean', defaultValue: true },
},
membershipKeys: {
portal_account_ids: { userField: 'user', valueField: 'account', filter: 'active == true' },
},
});
export const PortalAccess = definePermissionSet({
name: 'portal_user',
label: 'Portal User',
objects: { order: { allowRead: true } },
rowLevelSecurity: [
{ name: 'portal_orders', object: 'order', operation: 'select', using: 'account in current_user.portal_account_ids' },
],
});The set is read once per request, only when a policy reads the key, as a system read inside the caller's organization — the caller needs no read on the roster, and whoever can write roster rows can grant the key. A set no roster object holds (team ids, territory codes) comes from the deployment side instead: an installed plugin registers a membership resolver that supplies the key. A key both sources claim resolves from neither, and a key nothing supplies, or one over 1,000 values, matches no rows (fail closed).
When the person is a record. HR, service-desk and portal apps often model
the person as a row (an employee, an agent, a customer) with a user column
pointing at the sign-in. Name id, the roster's own primary key, as
valueField, and the set holds the ids of the caller's own rows of that object,
"the records I am":
import { ObjectSchema } from '@objectstack/spec/data';
import { definePermissionSet } from '@objectstack/spec';
// Roster: the person is a record, linked to the user who signs in
export const Employee = ObjectSchema.create({
name: 'employee',
sharingModel: 'private',
fields: {
user: { type: 'user', required: true },
},
membershipKeys: {
my_employee_ids: { userField: 'user', valueField: 'id' },
},
});
export const LeaveRequest = ObjectSchema.create({
name: 'leave_request',
sharingModel: 'public_read',
fields: {
employee: { type: 'lookup', reference: 'employee', required: true },
},
});
export const EmployeeSelfService = definePermissionSet({
name: 'employee_self_service',
label: 'Employee Self-Service',
objects: { leave_request: { allowRead: true } },
rowLevelSecurity: [
{ name: 'own_leave', object: 'leave_request', operation: 'select', using: 'employee in current_user.my_employee_ids' },
],
});Such a key holds ids of the roster object itself, so a policy compares it with a
column that references the roster (the leave request's employee) or with the
roster's own id. Tested against a column that references another object, a
column that is not a reference, or another object's id, the set could never
match, and the policy is refused (rls-predicate-membership-key-target). The
key grants nothing by itself: it yields only the rows whose userField is the
caller, and what a policy lets through with it is the author's choice.
leave_request is public_read so that the policy decides which rows the
holder reads: RLS only narrows what the org-wide default already allowed, so
under private it would narrow the employee's own rows, and a request someone
else filed for them would stay hidden.
How policies compose
Layer 0 (tenant isolation) ─┐
├── AND ──► the query's final filter
Layer 1 (business RLS) ─┘
policy A OR policy B OR …- Tenant isolation is a separate layer that always applies first and is never OR-ed away by a business policy.
- Multiple policies on the same object are OR-ed — on a read, a row is admitted if it matches any applicable policy (for writes, see item 4 of the fail-closed contract below). This is the intended way to express alternatives.
- The full evaluation pipeline around RLS is: object CRUD → FLS → OWD baseline → depth → sharing → RLS. RLS narrows what the earlier layers already allowed; it never widens.
- A superuser bypasses business policies but not tenant isolation — crossing tenants requires a genuine platform admin.
- Children of a master-detail parent with
sharingModel: 'controlled_by_parent'derive access from the master record instead. A child whose master is optional (required: false, ADR-0055 §1 as amended) and empty is read by its owner and by View All on the child, and written by its owner and by Modify All on the child. - A write of such a child asks edit access on its master by default. A child
that declares
sharing.controlledByParent.writeRequiresMasterRead: trueasks only read access on the master (on every hop of a chain) for insert, update and delete; the child's own object permissions, RLS and field-level security then decide, so an RLS policy on the child narrows writes as it narrows reads. A principal who cannot read the master still cannot write.
The fail-closed contract
Five ways a policy denies rather than leaks:
- A policy exists but every applicable expression fails to compile → a deny-everything filter.
- A referenced context variable is missing, null, or an empty array → that policy drops out (it cannot match).
- A policy references a column the object doesn't have → deny.
- A policy compares a column with a literal its declared type cannot be
compared with → that policy drops out, for
usingandcheckalike: on aboolean/togglecolumn, anything buttrue/falseand the spellings'true'/'false',1/0and'1'/'0'(active == 'yes',active != 'TRUE',active == 2); on a numeric column, a comparand that is not a number (a string with no numeric reading, a boolean). These are the comparisons a caller'swhereis refused for (INVALID_FILTER). An accepted spelling is read as the value it names, soactive != 'true'hides thetruerows exactly asactive != truedoes. checkis omitted →usingstands in as thecheck. The choice is made per operation across all the applicable policies, not policy by policy: when any of them declares acheck, only the declared checks decide, and a USING-only sibling'susingis not part of the check.
The one non-obvious case: no applicable policy means no restriction, not "deny". RLS only narrows what other layers granted — it is not what stops an un-permissioned user. If a user sees rows you expected RLS to hide, check whether any policy actually applies to their positions and the operation.
Verify it
Don't guess — ask the runtime:
curl -b cookies.txt \
"https://your-app.example.com/api/v1/security/explain?object=showcase_task&operation=read&userId=usr_123"The response walks the layers (tenant_isolation, object_crud, fls,
owd_baseline, depth, sharing, rls) with a verdict per layer —
grants, denies, narrows, widens, neutral, or not_applicable — and
tags each with kernelTier (layer_0_tenant vs layer_1_business). An RLS
policy that fired shows up as narrows on the rls layer; per-record
explanations mark rows admitted / excluded.
Explaining another user's access requires manage_users or delegated-admin
rights. Pair it with Impersonate in the Console to see the same rows they'd see.
Related
- Authorization Model — how all the layers fit together
- Sharing Rules — the declarative layer to try first
- Explain — the verdict vocabulary in full
- Access Recipes — requirement → layer mapping
Sharing Rules
Record-level access in ObjectStack: organization-wide defaults per object, the external sharing dial, criteria sharing rules and RLS-safe analytics reads.
Field-Level Security
Control visibility and editability of specific fields — readable/editable rules, hidden vs. read-only semantics, and server-side enforcement of declared rules.