-
NEVER compare ids or roles to decide access; call the helper for the case.
authzStaticGuard.test.ts fails on a new
x.userId === user, role === 'admin', findFirst({ where: { id, userId } }) or isAdmin
under src/app/api and src/lib (it caught an inline ctx.token.userId !== owner in the MCP
triage start, b54b78fe).
| You need | Call (all in webapp/src/lib/authz/) |
|---|
| a route's permission, on a project or the instance | requirePermission(request, perm, { projectId }) or withPermission(perm, handler, { projectId }) (guards.ts) |
| a second permission in the same request | requireAlso(auth, perm) (guards.ts); e.g. a chat delete that also deletes the agent's findings asks graph:edit (conversations/[id]) |
a level beyond the permission's own (raw data is 'R*') | requireLevel(auth, level) (guards.ts) |
| a project outside a route (a lib, a job, a socket) | projectAccess(subject, id, opts), then meetsLevel(access, level) (projectAccess.ts, levelTable.ts) |
| a per-user row (preset, conversation author, token, user scope) | ownsRow(subject, row.userId); a list: rowOwnerFilter(subject) (rowOwner.ts) |
| the projects a person sees | visibleProjectsWhere(subject) / visibleProjects(subject) (visibleProjects.ts) |
| an administration permission of the signed-in person | requireSessionPermission(session, perm); a route that changes the host reads the account again: accountHolds(userId, perm, { fresh: true }) (adminPermission.ts) |
an account's own catalog under /api/users/[id]/ | requireSelfPermission(request, accountId, perm) (selfService.ts) |
-
Under act-as, pass { actingAs: true } to projectAccess. An admin acting as a
collaborator reaches the share at Read and never more; without the option the acting admin gets
the share's write level. can() passes it; a lib that calls projectAccess itself must too.
-
NEVER let a level-less owner helper guard a write. guardProject, requireProjectAccess,
requireProjectScopedResource, requireProjectOwner and the conversation helpers admit a read
share, oversight and break-glass as readily as the owner. Only a permission at W or above on
the same path stops them; levelLessHelpers.test.ts
fails on a POST, PUT, PATCH or DELETE that reaches one without it.
-
Name the project in the guard whenever the route acts on one, as a literal projectId key.
Without it can() makes a capability-only check: neither the person's access to the project
nor its level is decided, auth.access is null, and the manifest classes the call as a session
guard.
-
ALWAYS update the route manifest in the same commit as the route. Run
node scripts/gen-route-manifest.mjs and commit routeManifest.ts with routeManifest.json;
routePermissions.test.ts fails when a
handler's first permission differs from its entry, or a handler asks none (add it to
SESSION_ONLY with the reason). The live matrix rows are generated from the manifest:
node scripts/gen-rbac-matrix-rows.mjs --check.
-
A new permission goes in the registry with all its metadata
(permissions.ts: level, crossTenant,
gatesExisting, closesCrossTenantHole, mcpScopes; introducedIn stays UNRELEASED). Then
regenerate the JSON copy with npx vitest run src/lib/authz/builtinSets.test.ts -u; never edit
permissionCatalog.json by hand.
-
A non-owner's read goes through the read views, never a hand-picked field list. A project
row: projectReadView(row, auth.access) (projectReadView.ts)
drops every column marked share: secret in registry.yaml,
so a new owner-only column is marked there. A graph answer: graphReadView(graph, access)
(graphReadView.ts); any other output of chain
nodes (export, versions, MCP): stripStepContent(nodes, access)
(stepContent.ts). Raw files (traffic, workspace,
scan outputs) need requireLevel(auth, 'R*').
-
A caller's own Cypher runs only through an allowlist. Saved views go through
injectProjectFilter.ts,
which refuses any character, call or node pattern it does not positively know; the agent, the
triage tools and the sandbox CLI go through scope_query in
tenant_filter.py (inject, then find_unscoped_node_pattern
refuses what it cannot prove scoped). Never add a denylist regex for one more shape: every shape
Neo4j read and a denylist missed ran unscoped, a read of every project's graph. A new function
or procedure joins the positive allowlist with a test of its cross-tenant case.
-
Keep the tenant and the person apart in every hop. The tenant (the project's owner) keys
graph, traffic, credential and model reads and writes; the person keys sessions, chats, the loop,
quotas and the audit actor. Swapping them writes a collaborator's work into an empty graph of
their own, or hands the owner's chats to the collaborator.
| Hop | Tenant | Person |
|---|
| webapp route | auth.access.project.userId | auth.effective.userId |
| WebSocket ticket (auth.ts) | ten, always written | sub; act under act-as |
| plugin call token (callToken.ts) | ten | sub |
| run credential (machine_credential.py) | ten | sub, act |
| scan job credential (machineCredential.ts) | ten | on the job row, re-checked when it fires: actorScanRefusal (scanActor.ts) |
| agent run (config.py) | get_tenant_id(state, config) | get_identifiers(state, config) |
| MCP tool | assertMcpProjectAccess(...).userId | ctx.token.userId |
A ticket or token without ten reads as sub only so tokens minted before an update still
verify; a new minting site always writes it (ws_ticket.py ticket_tenant).
-
A collaborator spends the owner's credentials only through a run toggle and the owner's
consent. effectiveToggles turns Run scans, Use AI agent and Exploitation & shells off without
the consent row (ownerConsent.ts): never read a
share's toggle columns yourself. A model-calling feature whose permission sits below Use AI agent
asks ownerCredentialRefusal(auth), then writes the credits.used row first with
recordFeatureSpend(auth, feature) (ownerSpend.ts):
no row, no spend.
-
Every loss of access calls onAccessReduced once its change has committed
(revocation.ts): a share revoked, narrowed, left or
expired, consent withdrawn, an account disabled, deleted or reset, a capability removed, a device
session revoked. A ticket and a queued scan are checked only when they start, so without it the
person's runs, sockets, queued scans, schedules and triage run go on. A new reason joins
ProjectReduction or AccountReduction with its entry in PLANS, which also names what
happens to the person's Kali sandboxes (sandbox: reconcile stops the instances that mount
a project the person lost, stop stops them all, none leaves them; the hooks live in
lib/sandbox/lifecycle.ts).
-
A start that writes a project asks who else is writing it. With sharing in force one
person writes a project at a time: while anyone writes it (a scan, an agent run, a triage run, a
mute-rule apply), another person's scan start or agent run is refused, 409 project_writer_busy
naming who holds it (secondWriterRefusal / secondWriterResponse,
projectWriters.ts; SECOND_WRITER_POLICY).
The scan starts and the chat ticket ask it; a new start path asks the same function, never its
own query. A socket outlives its ticket, so the agent asks again before every run it starts on
the socket (a message, an approval, an answer, a tool confirmation, a resume: _refused_second_writer
in websocket_api.py) through
writer_check.py and the internal-key
writer-check route, which reads
the owner from the database. Keep the agent's answer map: 200 {allowed: true} starts; 409
project_writer_busy refuses in the webapp's words; no answer or a 5xx is unverified (the owner,
sub == ten, goes ahead with [rbac] project_writer_unverified, anyone else is refused); any
other answer (400, 401, 404, a malformed body) refuses everyone, the owner included, because the
browser picks the session id and an answer it can provoke must never let a run through.
-
One rule for a session id: isWsSessionId (wsTicket.ts:
1-200 characters, no control or line-separator character). The ticket mint (400
invalid_session_id) and the writer-check route use it, so a ticket the mint signed is never
refused by the check. A client value written into an [rbac] log line goes through logValue
(routeErrors.ts; the agent's _loggable).
-
A privileged change and its audit row commit together. Write the row with
writeAuditTx(tx, entry) inside auditedTransaction(prisma, async (tx) => ...)
(audit.ts, auditForward.ts):
a failed insert rolls the change back. A bare prisma.$transaction around an audit write, or a
direct tx.auditLog.create, fails auditWriters.static.test.ts
(its row would never be forwarded). The actor is auditActorOf(real, effectiveUserId)
(auditActor.ts): the person signed in, the account acted as
in onBehalfOfUserId. writeAudit (best effort, swallows a failed insert) is never the row of
a privileged change.
-
A new audit action needs a label, and a reader of it a retention rule.
auditLabels.test.ts fails on an action without
an AUDIT_ACTION_LABELS entry; auditRetention.test.ts
fails on an audit_log reader whose actions no KEPT_AUDIT_RULES rule keeps, since retention
would delete the rows the code decides on.
-
A new feature sits behind its switch, and that switch's flags-off test proves nothing
changed. Read a switch only through rbacFlags() (flags.ts).
A new reader of the switch, or of a table it introduces, joins the readers list of
webapp/src/lib/authz/<switch>.flags.off.test.ts (IDENTITY_READERS, PERMISSION_READERS,
SHARING_STORAGE_READERS, WRITE_SWITCH_READERS, GOVERNANCE_READERS, ...), with a block
appended (never a rewrite) saying what the off state does. A schema change stays additive: a
column added to an existing table is nullable or has a default
(schemaAdditive.test.ts).
-
A live matrix row whose answer depends on a switch carries its tag (identity:,
permissions:, sharing:, sharingwrite:, governance: with on or off, read by
rbac_matrix_live.sh), or it fails in the other state.
The Kali sandbox has one mode, so a row carrying a sandbox: tag is a LINT error.
sharing: is sharing in force (the switch and Root's policy); a route or field gated on
RBAC_SHARING_ENABLED itself, which exists with the switch on and the policy {}, takes
sharingswitch: (the S3a red: four sharing:off rows failed there). A write grant refused
while write sharing is not in force answers per the write switch (write_sharing_off off,
above_max_level on with Root's policy at Read): sharingwrite:off plus sharingwriteswitch:.
A row that raises a share to write with it in force acts on viewer_tmp and puts it back: the
runner seeds once, so a raised viewer fails every later Read-viewer row (the S5 red).
-
A project the caller cannot see and one that does not exist are the same 404. A 403 names
the permission (forbiddenResponse, requireLevel) and goes only to someone who reaches the
project below the level.