27 tests on the file standing between a member and a shell

authorize.ts had none, and its own header is what says why that mattered: every deny path in the platform
ends there, and the failure mode of a permissive default is not a bug report, it is someone else's session.

It had none for a structural reason rather than an oversight. Every path needed two database calls, and the
only file here that mocks officerdb leaks its stub into whatever runs after it — so the obvious approach
would have traded one untested file for a flaky suite.

So the decisions are split from the fetching. resolveEffectivePermissions, decideApiRequest and
decideWsProvider are pure functions of their arguments; the async wrappers keep the role cache, the
fail-closed catches and the shape callers use. No behaviour change, and the live gate still answers 401 on
file-browser, users and tasks.

REAL registry keys throughout, deliberately: a suite built on invented permissions keeps passing after a
rename, which is the failure an authorization table can least afford. If a key here disappears this file
goes red.

Pinned beyond the happy paths — the owner carries no grants to consult; core is write unconditionally; a
confined grant is dropped without a Linux user and all three drop together; execution and admin grants in
the table are ignored even though no CHECK stops the row existing; an unknown key is ignored without
disturbing what is legitimately held; self-service is exact in method AND path; a socket needs no level; an
unauthenticated caller is refused every door.

Two gaps are stated in the file rather than left to be found: ownerOnly has no declaring permission yet, so
testing it would test the fixtures; and the grant cache's contract is a claim about call sites, not logic.

Found while writing them: readOnlyWrites paths are relative to the permission's api prefix, and getting that
wrong fails as "no permission covers this path" rather than as a level error — a misleading message for a
misleading path, now commented at the test that hit it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-22 04:42:56 +00:00
co-authored by Claude Opus 5
parent 7e054ddf11
commit a15fadbddc
4 changed files with 317 additions and 39 deletions
+68 -35
View File
@@ -65,6 +65,57 @@ async function grantsForRole(role: UserRole): Promise<Map<string, PermissionLeve
* write such a row, but this is the layer that has to hold if one ever exists — a constraint the database
* does not enforce is a constraint the reader must.
*/
/**
* The resolution itself, with no database in it.
*
* Split out on 2026-08-22 so it can be tested. `authorize.ts` is described in its own header as the file
* standing between a Member and a shell, and it had no automated tests at all — because every path through
* it needed two database calls, and the only file in this repository that mocks `officerdb` has a stub that
* leaks into whatever runs after it. Pulling the decision away from the fetching removes the need for a
* mock rather than working around one: everything below this line is a pure function of two arguments.
*
* The async wrapper keeps the caching, the error handling and the single-question shape callers rely on.
*/
export function resolveEffectivePermissions(
user: { role: UserRole; osUser: string | null },
roleGrants: Map<string, PermissionLevel>,
): EffectivePermissions {
if (user.role === 'Super Admin') return { isOwner: true, grants: new Map() };
const grants = new Map<string, PermissionLevel>();
for (const permission of CORE_PERMISSIONS) grants.set(permission.key, 'write');
// Whether the kernel can enforce a boundary for this account. `confined` permissions are dropped
// without it — see below.
const hasOsAccount = !!user.osUser;
for (const [key, level] of roleGrants) {
const permission = PERMISSION_BY_KEY.get(key);
// Unknown key: a permission that was renamed or removed while a grant survived. Ignore it — the
// alternative is honouring a name nothing defines.
if (!permission) continue;
// A confined permission touches the filesystem or runs a process, and is safe only because the
// account has its own Linux user to be confined to. Without one there is no boundary, so the grant
// resolves to nothing rather than to the owner's home — which is what it WOULD resolve to, since
// `getOwnerHomeDir` ignores the email it is passed, always.
//
// Dropped here rather than refused per-router so that one rule covers the HTTP routes, the
// websocket doors and the dock all at once. A member with `files` granted but no OS account sees no
// Files icon, gets a 403 from /api/file-browser, and cannot open the terminal socket — from this.
if (permission.kind === 'confined') {
if (!hasOsAccount) continue;
grants.set(key, level);
continue;
}
if (permission.kind !== 'app') continue;
grants.set(key, level);
}
return { isOwner: false, grants };
}
export async function getEffectivePermissions(userId: number | undefined): Promise<EffectivePermissions> {
const empty: EffectivePermissions = { isOwner: false, grants: new Map() };
if (!userId) return empty;
@@ -73,39 +124,7 @@ export async function getEffectivePermissions(userId: number | undefined): Promi
const user = await getUserById(userId);
if (!user) return empty;
if (user.role === 'Super Admin') return { isOwner: true, grants: new Map() };
const grants = new Map<string, PermissionLevel>();
for (const permission of CORE_PERMISSIONS) grants.set(permission.key, 'write');
// Whether the kernel can enforce a boundary for this account. `confined` permissions are dropped
// without it — see below.
const hasOsAccount = !!user.osUser;
for (const [key, level] of await grantsForRole(user.role)) {
const permission = PERMISSION_BY_KEY.get(key);
// Unknown key: a permission that was renamed or removed while a grant survived. Ignore it — the
// alternative is honouring a name nothing defines.
if (!permission) continue;
// A confined permission touches the filesystem or runs a process, and is safe only because the
// account has its own Linux user to be confined to. Without one there is no boundary, so the grant
// resolves to nothing rather than to the owner's home — which is what it WOULD resolve to, since
// `getOwnerHomeDir` ignores the email it is passed, always.
//
// Dropped here rather than refused per-router so that one rule covers the HTTP routes, the
// websocket doors and the dock all at once. A member with `files` granted but no OS account sees no
// Files icon, gets a 403 from /api/file-browser, and cannot open the terminal socket — from this.
if (permission.kind === 'confined') {
if (!hasOsAccount) continue;
grants.set(key, level);
continue;
}
if (permission.kind !== 'app') continue;
grants.set(key, level);
}
return { isOwner: false, grants };
return resolveEffectivePermissions(user, await grantsForRole(user.role));
} catch {
// A transient database error must never grant anything. Deny, and let the next request retry.
return empty;
@@ -123,7 +142,16 @@ export async function isApiRequestAllowed(
method: string,
path: string,
): Promise<{ allowed: boolean; reason?: string }> {
const { isOwner, grants } = await getEffectivePermissions(userId);
return decideApiRequest(await getEffectivePermissions(userId), method, path);
}
/** The decision, given an already-resolved account. Pure, and where every rule below actually lives. */
export function decideApiRequest(
effective: EffectivePermissions,
method: string,
path: string,
): { allowed: boolean; reason?: string } {
const { isOwner, grants } = effective;
if (isOwner) return { allowed: true };
const permission = permissionForApiPath(path);
@@ -170,7 +198,12 @@ export async function isApiRequestAllowed(
* rather than by being left off a list. The rule stays because the first plugin to own a socket needs it.
*/
export async function isWsProviderAllowed(userId: number | undefined, provider: string): Promise<boolean> {
const { isOwner, grants } = await getEffectivePermissions(userId);
return decideWsProvider(await getEffectivePermissions(userId), provider);
}
/** The decision, given an already-resolved account. See `isWsProviderAllowed` for why level is not read. */
export function decideWsProvider(effective: EffectivePermissions, provider: string): boolean {
const { isOwner, grants } = effective;
if (isOwner) return true;
const permission = permissionForWsProvider(provider);