roles phase 3: dev tools are a row, not a hardcoded name

rolePermitsDevTools() was `role === 'Developer'` — one line gating two real
grants, a Postgres login role with CREATEDB and a rootless Docker daemon. A role
the owner created at runtime could never have either, which defeats the point of
roles being data.

Two boolean columns on `roles` now carry it, and roleDevGrants() reads the row.
A role that no longer exists reads as neither grant, matching "absence denies"
everywhere else.

NOT the `provisioningScript` D8 asked for, and that column is removed rather
than left dead. A shell script stored on a role row and run at provisioning time
is arbitrary root-level code in a database column, and D8's own warning says why
that is worse than it looks: `usermod -aG docker` is root by a longer route. So
the row CHOOSES from a vocabulary the platform already knows how to carry out —
the same shape as `multiarch` on a plugin's osDependencies, for the same reason.

The seed re-asserts both flags on every run for system roles, and only for them.
Without that, existing rows take the column default of false the moment it lands
and Developer silently loses its tools on the next deploy — every host already
has these four rows, so an insert-only seed would have shipped that. `description`
stays insert-only, because an edit made on one server must survive a deploy.

`db:push` could not apply this and said nothing. Dropping a column while adding
another makes drizzle-kit ask whether it is a rename; with no terminal it bails
and the wrapper still exits 0, leaving the seed to fail against an unchanged
schema. Recorded in src/databases/CLAUDE.md with the SQL, because it will hit
every host on the next deploy and no agent driving a rollout has a terminal.

Verified here: SQL applied guarded, Developer keeps both grants and no other role
gained any, second push emits zero DDL and no prompt, 1423 pass / 0 fail.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Officer-Session: 656f5c85-e49a-4f1f-b9f3-042a04b4d043
This commit is contained in:
2026-08-23 21:32:42 +00:00
co-authored by Claude Opus 5
parent a6509f6456
commit c38f02afa3
11 changed files with 477 additions and 79 deletions
+29
View File
@@ -1,5 +1,34 @@
# Database Patterns
## Dropping and adding a column in the same push makes drizzle ASK
`drizzle-kit push` cannot tell a drop-plus-add from a rename, so it stops and asks:
```
Is grants_postgres column in roles table created or renamed from another column?
❯ + grants_postgres create column
~ provisioning_script › grants_postgres rename column
```
**Non-interactively that is fatal and silent.** With stdin closed it bails, `bun db:push` still exits 0, and
the `postdb:push` seed then runs against a schema that never changed — which is how you get a confusing
error about a column that does not exist, several steps from the thing that failed.
Hit on 2026-08-23 replacing `roles.provisioning_script` with `grants_postgres`/`grants_docker`. It is the
same family as the composite-unique truncate prompt below, and it matters more on a deploy: no agent driving
a rollout over SSH has a terminal to answer with.
**So a release whose schema drops a column carries the SQL in its plan**, guarded and idempotent, and treats
`bun db:push` as the check that it worked rather than the thing that does it:
```sql
ALTER TABLE roles ADD COLUMN IF NOT EXISTS grants_postgres boolean NOT NULL DEFAULT false;
ALTER TABLE roles ADD COLUMN IF NOT EXISTS grants_docker boolean NOT NULL DEFAULT false;
ALTER TABLE roles DROP COLUMN IF EXISTS provisioning_script;
```
Then push, and expect zero DDL. If it still wants to change something, the SQL was wrong.
## Overview
**One PostgreSQL database**, `officer_db`, exposed as the workspace package `officerdb`. Managed with
@@ -6,8 +6,10 @@ export {
createRole,
renameRole,
deleteRole,
setRoleGrants,
type RoleRow,
type CreateRoleResult,
type RenameRoleResult,
type DeleteRoleResult,
type SetRoleGrantsResult,
} from './queries';
@@ -0,0 +1,131 @@
import { afterEach, describe, expect, test } from 'bun:test';
import { eq, like } from 'drizzle-orm';
import { db } from '../db';
import { roles } from './schema';
import { createRole, getRole, seedRole, setRoleGrants } from './queries';
/*
Phase 3 of docs/roles-and-teams.md: `grantsPostgres`/`grantsDocker` replace `rolePermitsDevTools()`'s
hardcoded `role === 'Developer'`. These tests hit the real database, like chat-session-cleanup.test.ts —
the thing being pinned is column plumbing (does the value survive a write and a read back), which a fake
store would pass regardless of whether the SQL is right.
Every role name here is prefixed `zz-test-role-`, cleaned up in `afterEach` by prefix rather than by an
exact list, so a test that fails before reaching its own cleanup does not leave a row for the next run to
trip over.
*/
const PREFIX = 'zz-test-role-';
const name = (suffix: string) => `${PREFIX}${suffix}`;
afterEach(async () => {
await db.delete(roles).where(like(roles.name, `${PREFIX}%`));
});
describe('grants round trip through create and read', () => {
test('a role created with both flags true reads back with both true', async () => {
const created = await createRole({ name: name('both'), grantsPostgres: true, grantsDocker: true });
expect(created.ok).toBe(true);
if (!created.ok) return;
expect(created.role.grantsPostgres).toBe(true);
expect(created.role.grantsDocker).toBe(true);
const read = await getRole(name('both'));
expect(read?.grantsPostgres).toBe(true);
expect(read?.grantsDocker).toBe(true);
});
test('omitted flags default to false, matching the column default', async () => {
const created = await createRole({ name: name('bare') });
expect(created.ok).toBe(true);
if (!created.ok) return;
expect(created.role.grantsPostgres).toBe(false);
expect(created.role.grantsDocker).toBe(false);
});
test('a role with grantsDocker false does not carry it after a Postgres-only grant', async () => {
const created = await createRole({ name: name('pg-only'), grantsPostgres: true });
expect(created.ok).toBe(true);
if (!created.ok) return;
expect(created.role.grantsPostgres).toBe(true);
expect(created.role.grantsDocker).toBe(false);
});
});
describe('setRoleGrants', () => {
test('changes only the flags supplied, leaving the other as it was', async () => {
const created = await createRole({ name: name('partial'), grantsPostgres: true, grantsDocker: true });
expect(created.ok).toBe(true);
const updated = await setRoleGrants(name('partial'), { grantsDocker: false });
expect(updated).toEqual({
ok: true,
role: expect.objectContaining({ grantsPostgres: true, grantsDocker: false }),
});
});
test('refuses a system role, so an edit cannot look like it worked and then revert on the next deploy', async () => {
// isSystem is not settable through createRole, so insert the row directly — this is standing in for
// one of the four seeded rows, which this function must never touch.
await db.insert(roles).values({ name: name('system'), isSystem: true, grantsPostgres: false });
const result = await setRoleGrants(name('system'), { grantsPostgres: true });
expect(result).toEqual({ ok: false, reason: 'system' });
// And the value is genuinely unchanged, not just the result code.
expect((await getRole(name('system')))?.grantsPostgres).toBe(false);
});
test('reports not-found for a role that does not exist', async () => {
expect(await setRoleGrants(name('missing'), { grantsPostgres: true })).toEqual({
ok: false,
reason: 'not-found',
});
});
});
describe('seedRole', () => {
test('is idempotent: seeding the same system role twice does not duplicate or error', async () => {
const first = await seedRole({ name: name('seed'), isSystem: true, grantsPostgres: true });
const second = await seedRole({ name: name('seed'), isSystem: true, grantsPostgres: true });
expect(first).toBe(true); // created
expect(second).toBe(false); // already present
const rows = await db.select().from(roles).where(eq(roles.name, name('seed')));
expect(rows).toHaveLength(1);
});
test('corrects a system role whose grants were wrong, without touching a non-system role the same way', async () => {
await seedRole({ name: name('correct-sys'), isSystem: true, grantsPostgres: true, grantsDocker: true });
// Simulate the migration case: a `db:push` column-add left the row at the boolean default.
await db.update(roles).set({ grantsPostgres: false, grantsDocker: false }).where(eq(roles.name, name('correct-sys')));
expect(await getRole(name('correct-sys'))).toMatchObject({ grantsPostgres: false, grantsDocker: false });
// Re-running the same seed call is the fix — no separate migration script.
await seedRole({ name: name('correct-sys'), isSystem: true, grantsPostgres: true, grantsDocker: true });
expect(await getRole(name('correct-sys'))).toMatchObject({ grantsPostgres: true, grantsDocker: true });
});
test('never rewrites description once a row exists, only grants', async () => {
await seedRole({ name: name('desc'), description: 'original', isSystem: true, grantsPostgres: false });
// An operator's edit, which the next deploy's seed call must not revert.
await db.update(roles).set({ description: 'edited by an operator' }).where(eq(roles.name, name('desc')));
await seedRole({ name: name('desc'), description: 'original', isSystem: true, grantsPostgres: true });
const row = await getRole(name('desc'));
expect(row?.description).toBe('edited by an operator');
expect(row?.grantsPostgres).toBe(true);
});
test('does not touch a non-system role at all, even if seeded once as one', async () => {
// A non-system row's grants belong to whoever created it; seedRole's correction pass only applies
// when `isSystem` is true in the call.
const created = await createRole({ name: name('custom'), grantsPostgres: true });
expect(created.ok).toBe(true);
await seedRole({ name: name('custom'), isSystem: false, grantsPostgres: false });
expect((await getRole(name('custom')))?.grantsPostgres).toBe(true);
});
});
+94 -13
View File
@@ -7,7 +7,8 @@ export type RoleRow = {
name: string;
description: string | null;
isSystem: boolean;
provisioningScript: string | null;
grantsPostgres: boolean;
grantsDocker: boolean;
createdAt: Date;
};
@@ -24,13 +25,14 @@ export async function listRoles(): Promise<(RoleRow & { userCount: number })[]>
name: roles.name,
description: roles.description,
isSystem: roles.isSystem,
provisioningScript: roles.provisioningScript,
grantsPostgres: roles.grantsPostgres,
grantsDocker: roles.grantsDocker,
createdAt: roles.createdAt,
userCount: sql<number>`count(${users.id})::int`,
})
.from(roles)
.leftJoin(users, eq(users.role, roles.name))
.groupBy(roles.name, roles.description, roles.isSystem, roles.provisioningScript, roles.createdAt)
.groupBy(roles.name, roles.description, roles.isSystem, roles.grantsPostgres, roles.grantsDocker, roles.createdAt)
.orderBy(asc(roles.name));
return rows;
}
@@ -41,22 +43,48 @@ export async function getRole(name: string): Promise<RoleRow | undefined> {
}
/**
* Seed a role if it is not there. Idempotent, and it does NOT overwrite an existing row.
* Seed a role if it is not there. Idempotent, but NOT symmetric across columns.
*
* Called from `postdb:push` on every machine, so it runs again on every schema push for the rest of this
* platform's life. An upsert would mean a description edited on one server is silently reverted by the next
* deploy — so the seed establishes a row and never touches it again.
* platform's life. `description` is never rewritten once a row exists: an upsert there would mean a
* description edited on one server is silently reverted by the next deploy — so that column is set on
* insert and never touched again.
*
* `grantsPostgres`/`grantsDocker` are the opposite, and only for a role seeded with `isSystem: true`: they
* ARE re-asserted on every run, because for a system role they are not an operator's data, they are the
* platform's own declaration of what the role means — the same standing as its name. Two things need that:
*
* - A row can predate these columns. `db:push` adds them with `default false`, so an existing `Developer`
* row gets `grantsPostgres: false, grantsDocker: false` the moment the column lands — an insert-only
* seed would leave it there forever and silently take away dev tooling nobody asked to revoke.
* - It is also what makes the guard in `setRoleGrants` (below) honest. That function refuses to touch a
* system role's grants specifically so an edit cannot LOOK like it worked and then vanish on the next
* deploy; this is the other half of that promise — the seed is the only writer, and it always writes
* the same thing.
*
* A non-system role's grants are never touched here — those belong to whoever created the role, through
* `setRoleGrants`, and this function has no opinion about a row it did not seed.
*/
export async function seedRole(row: {
name: string;
description?: string | null;
isSystem?: boolean;
grantsPostgres?: boolean;
grantsDocker?: boolean;
}): Promise<boolean> {
const isSystem = row.isSystem ?? false;
const grantsPostgres = row.grantsPostgres ?? false;
const grantsDocker = row.grantsDocker ?? false;
const inserted = await db
.insert(roles)
.values({ name: row.name, description: row.description ?? null, isSystem: row.isSystem ?? false })
.values({ name: row.name, description: row.description ?? null, isSystem, grantsPostgres, grantsDocker })
.onConflictDoNothing({ target: roles.name })
.returning({ name: roles.name });
if (inserted.length === 0 && isSystem) {
await db.update(roles).set({ grantsPostgres, grantsDocker }).where(eq(roles.name, row.name));
}
return inserted.length > 0;
}
@@ -83,14 +111,30 @@ export type CreateRoleResult = { ok: true; role: RoleRow } | { ok: false; reason
* Create a role at runtime. `isSystem` is always false here — a role the platform's own code names by
* string (Developer, Super Admin, Member; see the schema comment) is one seeded at startup, never one
* typed into a form, and nothing reachable through this function may claim otherwise.
*
* `grantsPostgres`/`grantsDocker` default to false, same as the column defaults — a role created through a
* form should not hand out a Postgres login and a Docker daemon because nobody unchecked a box. There is
* no `isSystem` guard needed on the write itself: a role created here is never system, so nothing later
* pins these two values the way `seedRole` pins Developer's.
*/
export async function createRole(input: { name: string; description?: string | null }): Promise<CreateRoleResult> {
export async function createRole(input: {
name: string;
description?: string | null;
grantsPostgres?: boolean;
grantsDocker?: boolean;
}): Promise<CreateRoleResult> {
const name = input.name.trim();
if (!name) return { ok: false, reason: 'invalid-name' };
const inserted = await db
.insert(roles)
.values({ name, description: input.description?.trim() || null, isSystem: false })
.values({
name,
description: input.description?.trim() || null,
isSystem: false,
grantsPostgres: input.grantsPostgres ?? false,
grantsDocker: input.grantsDocker ?? false,
})
.onConflictDoNothing({ target: roles.name })
.returning();
const role = inserted[0];
@@ -98,15 +142,52 @@ export async function createRole(input: { name: string; description?: string | n
return { ok: true, role };
}
export type SetRoleGrantsResult = { ok: true; role: RoleRow } | { ok: false; reason: 'not-found' | 'system' };
/**
* Change a role's provisioning flags after it has been created.
*
* Refuses on `isSystem`, and for a different reason than `renameRole`'s refusal: renaming protects the
* NAME code depends on, this protects a PROMISE. `seedRole` re-asserts a system role's grants on every
* `postdb:push`, so writing here would look like it worked and then silently revert on the next deploy —
* exactly the "says something untrue" trap `manage-users.ts` calls out for the Postgres-follows-role case.
* A custom role has no seed pinning it, so this is the only place its grants are ever set after creation.
*
* Only the two flags supplied are changed; the other keeps its current value, so a caller adjusting just
* `grantsDocker` cannot accidentally reset `grantsPostgres` to false.
*/
export async function setRoleGrants(
name: string,
grants: { grantsPostgres?: boolean; grantsDocker?: boolean },
): Promise<SetRoleGrantsResult> {
const existing = await getRole(name);
if (!existing) return { ok: false, reason: 'not-found' };
if (existing.isSystem) return { ok: false, reason: 'system' };
// Same re-check as renameRole/deleteRole, same reason: the row must not have become system between the
// read above and this write.
const [role] = await db
.update(roles)
.set({
grantsPostgres: grants.grantsPostgres ?? existing.grantsPostgres,
grantsDocker: grants.grantsDocker ?? existing.grantsDocker,
})
.where(and(eq(roles.name, name), eq(roles.isSystem, false)))
.returning();
if (!role) return { ok: false, reason: 'system' };
return { ok: true, role };
}
export type RenameRoleResult =
| { ok: true; role: RoleRow }
| { ok: false; reason: 'not-found' | 'system' | 'invalid-name' | 'duplicate' };
/**
* Rename a role. Refuses outright on `isSystem` (D4 in docs/roles-and-teams.md): `rolePermitsDevTools()`
* tests for `'Developer'` by string, `bootstrap.ts` writes `'Super Admin'`, and `users.role` defaults to
* `'Member'`. Renaming one of those four is a code change across three call sites that has not happened,
* not a data edit — so this refuses rather than quietly breaking them.
* Rename a role. Refuses outright on `isSystem` (D4 in docs/roles-and-teams.md): `scripts/seed-roles.ts`
* matches its four rows by name on every deploy, `bootstrap.ts` writes `'Super Admin'`, and `users.role`
* defaults to `'Member'`. Renaming one of those four is a code change across those call sites that has not
* happened, not a data edit — a rename would leave the seed re-creating the old name from under it rather
* than correcting the row that moved.
*
* `users.role` and `role_permissions.role` are foreign keys onto this table with `ON UPDATE CASCADE`
* (phase 2 part 2), so the `UPDATE` below moves every holder and every grant automatically, in the same
+21 -11
View File
@@ -13,7 +13,7 @@ import { pgTable, text, boolean, timestamp } from 'drizzle-orm/pg-core';
* changes.
*
* The cost is that a rename is a data migration rather than a label edit. That is honest — a role name
* appears in `rolePermitsDevTools`, in report text and in whatever a plugin has written down.
* appears in `scripts/seed-roles.ts`'s seed table, in report text and in whatever a plugin has written down.
*
* ── What is NOT here ──
*
@@ -33,20 +33,30 @@ export const roles = pgTable('roles', {
/**
* A role the platform's own code names, so it cannot be deleted or renamed.
*
* `rolePermitsDevTools()` tests for `'Developer'` by name, `bootstrap.ts` sets `'Super Admin'`, and the
* users table defaults to `'Member'`. Deleting or renaming one of those is not a data change, it is a
* code change that has not happened yet — so the delete and rename paths refuse on this flag rather than
* discovering it as a runtime failure somewhere else.
* `scripts/seed-roles.ts` matches `'Developer'`, `'Admin'` and `'Member'` by name on every deploy,
* `bootstrap.ts` sets `'Super Admin'`, and the users table defaults to `'Member'`. Deleting or renaming
* one of those is not a data change, it is a code change that has not happened yet — so the delete and
* rename paths refuse on this flag rather than discovering it as a runtime failure somewhere else.
*/
isSystem: boolean('is_system').notNull().default(false),
/**
* Reserved for the per-role provisioning that comes next: a script run when an account is given this
* role, so "Developer gets rootless Docker" stops being a special case in `os-user-postgres.ts` and
* becomes a row. Null today, and nothing reads it.
* Per-role provisioning, as a closed vocabulary rather than a script.
*
* Declared now rather than later on purpose — it is the reason the owner wanted a table at all, and a
* column that arrives with the feature that uses it is a second migration for no gain.
* D8 in docs/roles-and-teams.md proposed a `provisioningScript` column: a shell script stored on the row
* and run when an account is given the role. That was rejected before it was built — it is arbitrary
* root-level code living in a database row, and D8's own warning explains why that is worse than it
* looks: `usermod -aG docker` is root by a longer route
* (`docker run -v /:/host -it alpine chroot /host` reads `.env`, every member's home and the wallet
* seed). A role editable at runtime must not be a way to grant root by writing a string into a form.
*
* So the row CHOOSES from options the platform code already knows how to carry out safely, the same
* shape as `multiarch` on a plugin's `osDependencies` (`src/servers/plugins/manifest.ts`): a fixed list
* instead of a free string, so the manifest picks rather than supplies. `os-user-postgres.ts` and
* `os-user-docker.ts` still own how each is provisioned; these columns only say whether a given role's
* accounts get it.
*/
provisioningScript: text('provisioning_script'),
grantsPostgres: boolean('grants_postgres').notNull().default(false),
/** A rootless Docker daemon. See `grantsPostgres` above and `os-user-docker.ts` for what it costs per member. */
grantsDocker: boolean('grants_docker').notNull().default(false),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
});