PermDock
Guides

Shared cache

Share one better-supabase cache entry between callers who hold the same grants, and skip the live version read for writes that Postgres checks again.

authorizationHooks sets shareKey, the hook better-supabase calls to key a share: "tenant" cache entry. Callers in one tenant whose grants for the entry's permissions are equal get the same key and read one entry. The entry is still filled through the caller's own client under RLS.

Grant fingerprint

grantFingerprint(permdock, permissions) from permdock/better-supabase returns gf1: and a SHA-256 digest of what the instance grants for permissions in its tenant. It leaves out the user id and the names of the roles, so an editor and an admin that grant quote.read under the same terms get the same digest.

It returns null, and the entry stays per user, for:

  • a permission the policy does not declare, or an empty list;
  • an instance without a principal or a tenant, or a delegated or simulated one;
  • a grant whose condition is opaque, a sqlFunction, a liveSession check or not portable;
  • an instance that grants none of the permissions.

The hook adds three cases: a token marked truncated in team_ids_truncated or permissions_truncated, a token whose authz_ver is behind the version in runtime.versions, and a subject that is not a user. A token with memberships_truncated answers only in the case described under truncated tokens.

Truncated tokens

When the size budget cuts a user's memberships, the token carries memberships_truncated: true. shareKey still answers for the active tenant when the token holds at least one entry outside that tenant. The hook ranks the active tenant's entries first and keeps a prefix of that order, so a kept entry of another tenant means the prefix passed every entry of the active tenant. The digest then covers exactly the entries the database holds for the tenant. With only active-tenant entries, or none, the cut may have fallen inside them, and shareKey returns null. A cut that dropped attrs does not change the grants, so it does not block a key. tests/better-supabase/share-key.test.ts covers the three cases and tests/integration/src/hook-token-shape.test.ts the ranking.

Doctor PD138 counts the users the budget truncates, so you can see how many requests skip the key.

Provider tables

authorizationProvider({ manifest, catalog, tables: true }) fills better-supabase's tables. For each resource the manifest maps to a table it lists the keys of the read, list and get permissions and marks the table tenant only when every one of them is held at the tenant scope alone, carries no row condition and has a grant. A resource with a restriction, a field mask or a grant at another scope is row. Without tables: true the provider sets none, and every entry stays per user. Doctor BS428 checks each entry against the generated select policies.

When permdock.manifest.json has rls.tableReads, the provider answers from it instead, keyed by the qualified table (public.orders). permdock supabase inspect writes rls.tableReads from the select policies the schema files, migrations and rls.out leave defined, so hand-written policies count too. A table is tenant only when:

  • row level security is on and the table has no field view;
  • every permissive select policy for authenticated is <column> in (select <schema>.permitted_<root>_ids_by_permission('<key>')) on one column, written by hand or rendered from an @bsb access tag;
  • every restrictive select policy reads no column of the row, such as one that checks the session.

Every other table is row, with the rules it breaks:

RuleThe table has
forma policy on the plain permitted_<root>_ids(key); permdock codemod bsb-access-tags moves it to a tag
follows, via, walka policy that calls a follows, via or walk helper
ownera policy that compares a column with auth.uid() or permdock_user_id()
conditionanother select expression, or tenant policies on two columns
restrictivea restrictive select policy that reads a column
fieldsa field view
unknownrow level security off, or no permissive select policy

Tables in the helpers' schema, better_supabase and the platform schemas are left out. The manifest is read from the files on disk, so run permdock supabase inspect --out after permdock generate changes a select policy. Doctor PD128 fails when the committed manifest marks a table tenant that the files now make row.

How many CentraKit tables can share

Of the 229 row tables in the CentraKit dry run, permdock codemod bsb-access-tags --check would move none: a migration, a policy or a tenant column the codemod does not rewrite keeps each of the 66 form entries. 59 tables carry a tenantFor key, so a read of them can share by key without moving the policy; the other 170 stay per user. A table can break more than one rule, so the rule counts (66 form, 54 owner, 90 condition, 6 restrictive, 16 unknown) add up to more than 229. scripts/centrakit-dry-run.json holds every table with its reason.

Make a form table tenant

A form table has a select policy on permitted_<root>_ids('<key>'). permdock codemod bsb-access-tags moves it to a tag, and the table becomes tenant, when every grant of the key is an allow of that key with no condition and no deny. When it leaves the policy, permdock codemod bsb-access-tags --check, permdock rls report and permdock rls explain name the first grant that decides it, and rls.tableReads[].reason in the manifest holds the same sentence.

ReasonWhat the app changes to make the table tenantWhen it must not
role R on S denies itRemove the deny and leave the permission out of the role that should not read; or give the deny's roles a permission of their own and check that in the policy.The deny hides rows from some holders only. Another holder's cached rows would reach them.
grants it under a condition (grant key k#n)Drop the condition when it restates the tenant scope. Otherwise split the permission: k unconditional for the tenant list, k.own with the condition for rows.The condition reads the row or the caller (ownerId, a level such as k@own, a status). Rows differ per holder.
grants it through another key (grant key g)Check the key the role holds in the policy, g, or grant k itself.Two roles hold different keys that the policy treats as one. The policy answers per role.
under a row condition or a validity windowRemove the window or the requires; a window changes the answer with the clock, so keep it off a shared table.The grant expires per member.
every grant of it is unconditional and still keptRead the codemod's kept line: another policy for the command, a tenant column that differs from the table's other policies, or a role other than authenticated.The second policy filters by row.
policy P is still defined in F next to an @bsb access tagWrite the migration that drops P (supabase db diff). The tag renders the replacement policy; until a migration drops P, the database holds both, and the table reads as form.Never: the table is already tenant in the schema files.

After the change run permdock generate, permdock codemod bsb-access-tags, permdock supabase inspect --out and both doctors. Doctor BS428 then checks that the tag and the policy agree. A table that reads one row per member (owner) or per condition stays row, however many members hold the key: sharing it would serve one member's rows to another.

A table shares per tenant only when its select policy filters by permission and not by row. Prove it per entry with expectTenantShare from better-supabase/testing: two callers with the same grant get the same key and read the same rows, and a member without the grant gets no key.

Shared functions

authorizationProvider({ manifest, catalog, tables: true, sharedFunctions: true }) fills better-supabase's sharedFunctions: the functions a share: "tenant" fill may call. permdock supabase inspect writes rls.sharedFunctions into the manifest, one entry { function, tables, permissions } for each function the schema files, migrations and rls.out define that passes better-supabase's BS430:

  • language sql, security invoker, stable or immutable (a function that states no volatility is volatile and is left out);
  • no auth.*, current_user, session_user, current_setting, or helper of the helpers' schema other than a permissionFilters helper called with a string literal;
  • every function it calls is itself listed, or a built-in;
  • every relation it reads is a tenant table in rls.tableReads, resolved through [<function schema>, public] like better-supabase does.

permissions is the union of the keys those tables check. A function that reads one row table is not listed. An overloaded name is listed when every overload qualifies. sharedFunctions: true needs tables: true and a manifest from inspect 0.31 or later; the provider names either gap in problems.

Doctor PD137 fails when the committed manifest lists a function that the files now make read a row table or the caller. better-supabase's BS430 checks the same properties on the database.

Helpers that answer the same for equal grants

Two callers with an equal grantFingerprint for a key hold the same grants of that key in the tenant. A helper gives them the same answer only when its result depends on nothing else. permdock supabase inspect writes the helpers that do into rls.tenantPureHelpers, with the argument that holds the key and the argument that holds the tenant:

HelperKey argumentTenant argumentWhy it is the same for equal grants
permdock_<root>_has(p_grant, p_tenant)p_grantp_tenantIt tests one grant key in one tenant.
permitted_<root>_permission_keys(p_id, p_keys) (p_keys overload)p_keysp_idIt lists which of p_keys the caller holds on one tenant.

The answer is the same only when the tenant argument is the entry's tenant and the key argument is one of the entry's permissions. A call with another tenant reads grants the fingerprint does not cover.

These helpers are left out, and the guide says why:

HelperWhy callers with an equal fingerprint differ
permitted_<root>_ids_by_permission, permitted_<root>_ids, permitted_<root>_id_arrayThey list every tenant the caller holds the key in. A caller who is also a member of another tenant gets a longer list.
permdock_has, permdock_has_permissionThey answer for the global scope, not for the tenant.
permitted_<resource>_rows, permitted_<resource>_idsThey decide per row, through restrictions, instance grants and row conditions the fingerprint does not cover.
permdock_subject, permdock_bootstrap_permissions, permdock_user_idThey read the caller.

tests/integration/src/tenant-pure-helpers.test.ts checks both lists on PGlite: callers with an equal fingerprint get one answer from each listed helper, and permitted_<root>_ids_by_permission returns acme for one and acme, beta, delta for another. permdock_<root>_has takes the grant key, which equals the permission key for an unconditional allow.

permdock supabase inspect also writes rls.permissionFilters: permdock_<root>_has_active(p_grant) and permitted_<root>_permission_keys_active(p_keys). Each is stable, security invoker and language sql, and calls the two-argument helper with the tenant the token names. authorizationProvider fills better-supabase's permissionFilters from that list. BS430 accepts a call that passes a string literal as the key and adds the key to the share key. It refuses the two-argument helpers, because it checks the key argument only, and a call whose key is not a string literal. A text[] literal is not a string literal, so a call of permitted_<root>_permission_keys_active does not pass BS430 until better-supabase accepts one. The request for a checked tenant argument is in better-supabase requests.

Why a widening key can share

tenantFor with widenedKeys, and authorizationHooks with widened, lets two holders of a widening key read every row of the tenant. The fingerprint plus the tenant keys that entry: both callers hold the same widening grant, so they read the same rows. A caller without the key gets no share key, so that read stays per user.

The entry is not sound when the widening grant carries a condition, or when a restrictive policy reads a column. Two holders then read different rows. packages/permdock/tests/better-supabase/share-key.test.ts covers the sound case, under shareKey with widened keys.

CentraKit dry run

node scripts/centrakit-dry-run.ts --stack copies CentraKit, runs the 0.31 codemods and generate, sets tables: true and sharedFunctions: true, starts the copy's local Supabase stack, loads its schema files with supabase db schema declarative sync and runs permdock rls verify --shadow and better-supabase's doctor against it. The report is scripts/centrakit-dry-run.json. It ran on 24 November 2026 with better-supabase 0.85.0 and Supabase CLI 3.3.0.

CheckResult
Tables in rls.tableReads256: 28 tenant, 228 row (65 form, 54 owner, 90 condition, 6 restrictive, 16 unknown)
rls verify --shadowno findings: the schema files and the database agree on policies, functions and grants
BS430 on the 4 functions of rls.sharedFunctions0 findings
BS4290 findings
BS4093 warnings about blocks.permissions.activeTenant and disabled, which are CentraKit config
BS428 on the 28 tenant tables28 findings, its select policies check []
The same 28 tables with ::text removed from pg_policies.qual28 of 28 check exactly their permissions

The 28 findings are not a table fault. better-supabase 0.85.0 matches the provider's permitted_{scope}_ids_by_permission({permission}) template against pg_policies.qual, which Postgres stores as permitted_organization_ids_by_permission('asset.read'::text); the pattern expects ) after the literal and finds ::text. The release therefore does not state that the 28 tables pass BS428: they pass once better-supabase reads the cast (request). The dry run found two PermDock faults and fixed them: rls.tableReads kept a table a later migration drops or renames (27 stale entries, which BS428 reported as the database has no such table), and permdock rls verify --shadow looked for supabase/schemas in the package directory, so it found no file in a monorepo whose supabase/ sits at the root.

Writes that RLS checks again

better-supabase sets context.enforcement to rls on a write that Postgres checks on current data. authorizer maps such a write to the database-write intent: claimsFirst takes the authorization version from the shared cache, as for a read. A role change inside the cache window can therefore let PermDock admit a write that RLS then refuses, and it cannot admit a write RLS would also accept on stale data. A write with enforcement: "definer", or without it, reads the version live.

authorizer({ policy, memberships, versions });

Version store

memoryVersionCache({ shared }) takes a VersionStore with better-supabase's shape: get(id) answers { version, at }, set(id, version, at) writes the time of the database read, and delete(id) forgets. maxStaleMs counts from at on every instance, so a store that never expires cannot keep a version past it. A stored entry dated in the future counts as read now, and one older than maxStaleMs is a miss.

StoreUse it when
runtimeCacheVersionStore(getCache())The app runs on Vercel; entries expire after 60 s.
postgresCacheVersionStore(pool, "schema.t")The app has no runtime cache; the table is (user_id text primary key, version bigint, at bigint).

testVersionStore from permdock/testing checks a store against that shape.

Warm the first request

authorizationHooks(...).warm(), authorizer(...).warm() and warm(policy) from permdock/next build one anonymous instance and run one can. They never reject: a failure answers { ok: false, ms }. Call one in instrumentation.ts after the policy import, so the first request does not pay for the instance.

instrumentation.ts
export async function register() {
  const { warm } = await import("permdock/next");
  const { policy } = await import("./src/policy");
  await warm(policy);
}

node scripts/authz-latency.ts measures these against the local Supabase stack of apps/examples/next-better-supabase and writes scripts/authz-latency.json. The numbers below are from 24 November 2026 on an Apple M5 Max (18 cores, 64 GB), Darwin 25.6.0 arm64, Node.js 26.13.1, Postgres 17.11 and permdock 0.30.0. The database holds the example's seed data: 4 users and 2 organisations.

Each cell is the mean, with the p95 in brackets. Version reads and helpers ran 200 times, cold instances 30 times in a fresh node process each, and the fingerprint and the hook 10,000 times on a built instance. Before is the generated helper where a variant ran against it; a dash means there is one measurement.

MeasurementBeforeAfter or todaySource
authz_version_for, round trip over pg-0.101 ms (0.204)versionRead.authzVersionFor.pgRoundTrip
authz_version_for, server time-0.010 ms (0.019), 4 buffersversionRead.authzVersionFor.server
custom_roles_version_for, round trip over pg-0.103 ms (0.157)versionRead.customRolesVersionFor.pgRoundTrip
custom_roles_version_for, server time-0.022 ms (0.045), 5 buffersversionRead.customRolesVersionFor.server
PostgREST round trip of a one-row read as anon-1.331 ms (1.752)versionRead.postgrestRpcFloor
Cold instance, generate-perf fixture: definePolicy to first can-17.30 ms (18.36)coldInstance.fixture.cold
Cold instance, example policy: definePolicy to first can-6.44 ms (6.89)coldInstance.example.cold
Policy imported in register(), fixture: first getPermDock-1.03 ms (1.30)coldInstance.fixture.warm
Policy imported in register(), fixture: first can-1.34 ms (1.55)coldInstance.fixture.warm
grantFingerprint, example, 2 keys-0.039 ms (0.052)grantFingerprint.example
grantFingerprint, fixture admin, 1 key-0.966 ms (1.213)grantFingerprint.fixtureOneKey
grantFingerprint, fixture admin, 39 keys-3.452 ms (4.315)grantFingerprint.fixtureAllReads
shareKey hook through permdockFor, 2 keys-0.049 ms (0.054)shareKey.instances
permitted_organization_ids, server time (variant B after)0.403 ms (0.484), 9 buffers0.385 ms (0.454), 7 buffershelpers.today.ids, helpers.variantB.ids
permitted_organization_ids_by_permission, server time (variant B after)0.430 ms (0.503), 9 buffers0.416 ms (0.492), 7 buffershelpers.today.byPermission

The cold instance is above the 3 ms threshold of a compiled policy index: on the fixture's 273 keys and 1,790 grants, definePolicy takes 14.9 ms, the first getPermDock 1.0 ms and the first can 1.4 ms. Importing the policy in register() moves definePolicy out of the first request, which then pays 2.4 ms.

At 17.30 ms the fixture is over the 3 ms at which a compiled policy-index kind would ship, and the example, at 6.44 ms, is too. PermDock 0.31 does not ship it: the profile puts most of definePolicy in the SHA-256 digest of the canonical policy string, and a check of the grant count and key order cannot tell a stale digest from a current one. Import the policy in register() instead.

grantFingerprint made no source call on a built instance, and the hook read no membership. Without a version cache, permdockFor read version once per hook call; with versions: memoryVersionCache() it read it once in 10,201 calls.

Variant B stores permdock_token_current() once per transaction and cuts the helpers' mean by 4.5% (0.403 to 0.385 ms) and 3.3% (0.430 to 0.416 ms), under the fifth a variant needs to ship, so the generated helpers stay as they are. Buffers are shared hits per statement.

CentraKit fixture timings

node scripts/centrakit-latency.ts measures the 0.31 request costs on tests/integration/fixtures/centrakit and writes scripts/centrakit-latency.json. It starts no database. A version read waits for 1.331 ms, the PostgREST round trip of versionRead.postgrestRpcFloor in scripts/authz-latency.json, so the call counts are exact and the milliseconds are that wait times the calls plus the work in process. Same machine and versions as above; cold instances ran 30 times in a fresh process each, the Server Action 200 times after the first, and shareKey 10,000 times.

MeasurementBeforeAfterSource
Server Action (quotes.read, quotes.update twice): first run3 version reads, 8.73 ms1 version read, 1.66 msserverAction.before/after.firstActionMs
Server Action: every later run within the window2 version reads, 2.76 ms (2.84)0 version reads, 0.063 ms (0.089)serverAction.before/after.laterActions
Shared bsb.kept entry, two members with equal grants2 fills1 fillsharedEntry.fillsForTwoMembers*
shareKey for one page of 3 keys-0.024 ms (0.033)sharedEntry.shareKeyOnePage
First request of a process, runtimeCacheVersionStore filled1 version read, 1.43 ms0 version reads, 0.012 msruntimeCacheVersionStore
Cold instance, CentraKit fixture: policy module (with zod)-35.73 ms (37.11)coldInstance.policyModule
Cold instance, CentraKit fixture: first getPermDock-0.88 ms (1.03)coldInstance.getPermDock
Cold instance, CentraKit fixture: first can-1.11 ms (1.36)coldInstance.firstCan
First request after the policy import: getPermDock and one can1.95 ms (2.06)1.17 ms (1.31), warm() 1.24 msfirstRequest.withoutWarm/withWarm/warmCost

The Server Action asks database-write for its update instead of write: RLS checks the row again on current data, so the cached version cannot grant the row change itself, and a role change shows within the 5 second window for reads and at once for a write that RLS does not check again (definer or no enforcement stays write).

The two members share a bsb.kept entry only through the key. The fingerprint covers grants, not the tenant id: admins of two organisations get the same string, so a key for tenant data adds the tenant.

The 8 keys and 6 roles of the fixture are CentraKit's target model, not its 0.28 policy; the policy module's 35.73 ms is the zod import plus definePolicy. warm() moves getPermDock and the first can out of the first request and costs the same 1.24 ms at boot.

Measured on the app's own stack, not here: permdock_authz_version_for over PostgREST, the helper without the suspension join, and a signed-in Server Action. Each needs the app's database, its suspension table and its supabase.hook.api wrapper, none of which this repository holds. permdock rls measure --as <user> runs requests as a user against that database and prints the version reads per request, the helper times from pg_stat_user_functions and pg_stat_statements, and the share of tenant tokens that get a share key (rls measure). The Server Action row above models the version reads of a signed-in action; the command counts them on the database.

An earlier run on the same machine, with other processes busy, gave round trips up to 3.5 times higher. Compare numbers from one run.

0.33 against 0.32

Same machine, versions and fixture as above. The numbers come from scripts/centrakit-latency.json, scripts/centrakit-dry-run.json, the integration tests and the changesets named in the last column.

Measurement0.320.33Source
Page of a member with a custom role (4 instances): version reads, first page6 reads, 21.85 ms1 read, 14.14 mscustomRoleMember.before/after
The same page, second page within the window6 reads, 21.00 ms0 reads, 12.50 mscustomRoleMember.before/after
Memberships that fit the 1,024-byte claim budget (CentraKit user)925compact-memberships-claim
Memberships that fit with 2 custom roles823compact-memberships-claim
row tables with a reason0 of 229229 of 229tableReads.rowWithoutReason
row tables that can share by keynot counted59tableReads.couldShareByKey
public.*_payload functions listed with the reason each is not sharednot listed26, 0 sharedfunctions in the dry-run report
Read-only actor policies: median plan time added per statementnot measured0.06 to 0.08 ms, noise 0.11 to 0.13 msstack.readOnlyActors
permdock_actor_may_write() callnot measured0.139 µsstack.readOnlyActors.guardCallMicros
permdock generate, 579 policies on 208 tablesnot measured1.5 stimings.generateMs
permdock rls verify --shadow on the local stacknot measured41.5 sstack.shadow.ms

The read-only actor policies cost less than the run-to-run noise, so 0.33 adds no trigger mode. A suspended tenant now reaches the app through the suspended_in claim and permdock_subject(); the database still denies it.

0.34 against 0.33

Same machine. The dry run is node scripts/centrakit-dry-run.ts --stack on CentraKit 2fe64cf61 with better-supabase 0.87.0. The in-process rows above keep their call counts; the 26 November run of scripts/centrakit-latency.json stays in the same range, so it is not copied here.

Measurement0.330.34Source
public.*_payload functions that pass the share check0 of 260 of 27functions in the dry-run report
Tables that can share28 as tenant, 59 row tables by key28 as tenant, 59 row tables by keyafter.tableReads
permdock_organization_has_active('x')not generated33 µs per call; the two-argument helper 28 µsstack.activeHelpers, 2,000 calls
permitted_organization_permission_keys_active(array['x'])not generated1,279 µs per call; the two-argument helper 98 µsstack.activeHelpers, 2,000 calls

CentraKit 2fe64cf61 adds public.my_day_payload, which is the 27th function. None of the 27 call permdock_organization_has_active, so the new filters do not move them. Each fails for one of these reasons: 11 call a function that is not shared, 6 are not language sql, security invoker and stable, 3 read the caller through auth.uid(), 3 call permdock.permitted_organization_ids() (it lists every tenant, so it is not a permission filter), 2 read a row table, 1 reads no table, and 1 reads better_supabase.pipeline_stages, which the schema files do not create.

The wrapper times are the statement, which is what pg_stat_statements records and what permdock rls measure prints. The dry-run database has no users, so that command was not run; the figures are 2,000 calls of each statement on that database. The has_active wrapper adds 5 µs to the inner call. The keys wrapper's statement takes 1,279 µs against 98 µs for the inner helper. The database has no rows and no token, so both answers are empty; the difference is the extra call.

The brief counts the policies declared in CentraKit's helpers.sql. At 2fe64cf61 that file declares 594: 211 insert, 192 update and 191 delete. The brief's 591 (210 insert, 191 update, 190 delete) is three policies below that, one of each command. The dry run counts pg_policies after supabase db schema declarative sync, which is 579: 206 insert, 187 update and 186 delete, on 208 tables. That is the same 579 the 24 November run measured. rls verify --shadow loads the schema files into a shadow database and reports no difference, so those 15 policies are absent from the shadow load as well. Four of them are on realtime.messages and storage.objects, which no schema file creates. The file says to apply the policies after the migrations that create the tables, and the dry run does not run migrations.

Last updated on

On this page