From 7f6df23b5d1e07898365571a5e7e95b09323c219 Mon Sep 17 00:00:00 2001 From: yufoxda Date: Wed, 9 Sep 2026 21:53:51 +0900 Subject: [PATCH 1/8] feat(auth): resolve what a caller may do, not what they are called MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds the permission side of the role work. Nothing checks permissions yet — U-3 moves the call sites — so this changes no behaviour: it puts the resolved permissions on the caller and gives the code a way to ask about them. Permissions load in a second transaction, after the identity is installed. member_roles is readable only by the member it belongs to, and that policy needs app.current_member_id, which is not set until the caller has been resolved. Reading it in the first transaction returns nothing and would quietly leave everyone with no permissions at all — a failure that looks like a permissions bug rather than an ordering one. The listed keys are not the source of truth; the database is, as Q-2 settled. They are the subset the code names, written down so that `member.readPrivate` fails to compile rather than becoming a string nobody holds and a check that never passes. A test asserts every listed key exists in the database, which is the mitigation the design records for keeping permissions as data. It was confirmed to fail on a deliberately misspelled key rather than assumed to work. Implements U-2 (docs/aidlc/unit-of-work.md) for FR-4.5 and NFR-1.1. Co-Authored-By: Claude Opus 4.8 --- community/src/core/auth.test.ts | 2 ++ community/src/core/auth.ts | 30 ++++++++++++++-- .../api_v0/member/join.integration.test.ts | 17 ++++++++++ member/src/core/auth.ts | 30 ++++++++++++++-- member/src/core/migration.integration.test.ts | 28 +++++++++++++++ share/permissions.ts | 34 +++++++++++++++++++ 6 files changed, 137 insertions(+), 4 deletions(-) create mode 100644 share/permissions.ts diff --git a/community/src/core/auth.test.ts b/community/src/core/auth.test.ts index 81bf5d4..e3ae651 100644 --- a/community/src/core/auth.test.ts +++ b/community/src/core/auth.test.ts @@ -58,6 +58,8 @@ test('auth middleware reloads the application user and does not turn downstream id: 'user-1', name: 'Test User', memberId: null, + // No member row, so no role, so nothing granted. + permissions: [], role: 'user', }); assert.deepEqual(capturedIdentity, { diff --git a/community/src/core/auth.ts b/community/src/core/auth.ts index 68257c4..1749449 100644 --- a/community/src/core/auth.ts +++ b/community/src/core/auth.ts @@ -1,8 +1,9 @@ import type { Context, Next } from 'hono' import { AppContext } from './types' +import type { RlsDatabase } from './db' import { verify } from 'hono/jwt' import { and, eq, gt } from 'drizzle-orm' -import { appAccounts, session, user } from '../../../share/drizzle/schema' +import { appAccounts, memberRoles, rolePermissions, session, user } from '../../../share/drizzle/schema' export type authUser = { id: string @@ -13,6 +14,31 @@ export type appUser = { name: string memberId: string | null role: 'admin' | 'user' + /** + * What this caller may do, resolved through the roles their member holds. + * Ask with `can()` from share/permissions; never branch on `role`. + */ + permissions: readonly string[] +} + +// Permissions are read in a second transaction, after the identity is installed. +// member_roles is only readable by the member it belongs to (or an admin), and +// that policy needs app.current_member_id — which is not set until the caller +// has been resolved. Reading it earlier would return nothing and quietly leave +// everyone with no permissions. +const loadPermissions = async ( + db: RlsDatabase, + memberId: string | null, +): Promise => { + if (!memberId) return [] + + const rows = await db.transaction((tx) => tx + .selectDistinct({ permissionKey: rolePermissions.permissionKey }) + .from(memberRoles) + .innerJoin(rolePermissions, eq(rolePermissions.roleKey, memberRoles.roleKey)) + .where(eq(memberRoles.memberId, memberId))) + + return rows.map((row) => row.permissionKey) } // Who the caller is, according to the authentication store. @@ -82,7 +108,7 @@ const loadAppUser = async ( role: resolved.role, }); - return resolved; + return { ...resolved, permissions: await loadPermissions(c.get('db'), resolved.memberId) }; } // The development bypass skips token verification entirely, so reaching it on a diff --git a/member/src/api_v0/member/join.integration.test.ts b/member/src/api_v0/member/join.integration.test.ts index 79d8dfc..5881d6b 100644 --- a/member/src/api_v0/member/join.integration.test.ts +++ b/member/src/api_v0/member/join.integration.test.ts @@ -20,6 +20,7 @@ import { updateMemberService, } from './service' import { chooseInitialDisplayName, type DiscordMembershipEvidence } from './verification' +import { CHECKED_PERMISSIONS } from '../../../../share/permissions' type JsonResponse = { body: unknown; status: number } @@ -39,6 +40,8 @@ const applicant: appUser = { name: 'Applicant', memberId: null, role: 'user', + // Not a member yet, so no role grants it anything. + permissions: [], } const admin: appUser = { @@ -46,6 +49,7 @@ const admin: appUser = { name: 'Admin', memberId: null, role: 'admin', + permissions: [...CHECKED_PERMISSIONS], } const createContext = ( @@ -764,6 +768,18 @@ test('development auth reloads memberId and downstream failures remain server er user_id text not null references app_auth."user"(id), expires_at timestamp not null ); + create table app_roles (role_key text primary key); + create table permissions (permission_key text primary key); + create table role_permissions ( + role_key text not null references app_roles(role_key), + permission_key text not null references permissions(permission_key), + primary key (role_key, permission_key) + ); + create table member_roles ( + member_id uuid not null references members(member_id), + role_key text not null references app_roles(role_key), + primary key (member_id, role_key) + ); insert into members values ('${memberId}'); insert into app_auth."user" values ('user-1', 'test-user'); insert into app_accounts values ('user-1', '${memberId}', 'user'); @@ -772,6 +788,7 @@ test('development auth reloads memberId and downstream failures remain server er grant usage on schema app_auth to app_rls; grant select on app_auth."user", app_auth.session to app_rls; grant select on app_accounts to app_rls; + grant select on member_roles, role_permissions to app_rls; set role app_rls; `) const db = createRlsDatabase(drizzle(client) as never) diff --git a/member/src/core/auth.ts b/member/src/core/auth.ts index 76afd69..c4374b8 100644 --- a/member/src/core/auth.ts +++ b/member/src/core/auth.ts @@ -1,8 +1,9 @@ import type { Context, Next } from 'hono' import { AppContext } from './types' +import type { RlsDatabase } from './db' import { verify } from 'hono/jwt' import { and, eq, gt } from 'drizzle-orm' -import { appAccounts, session, user } from '../../../share/drizzle/schema' +import { appAccounts, memberRoles, rolePermissions, session, user } from '../../../share/drizzle/schema' export type authUser = { id: string @@ -13,6 +14,31 @@ export type appUser = { name: string memberId: string | null role: 'admin' | 'user' + /** + * What this caller may do, resolved through the roles their member holds. + * Ask with `can()` from share/permissions; never branch on `role`. + */ + permissions: readonly string[] +} + +// Permissions are read in a second transaction, after the identity is installed. +// member_roles is only readable by the member it belongs to (or an admin), and +// that policy needs app.current_member_id — which is not set until the caller +// has been resolved. Reading it earlier would return nothing and quietly leave +// everyone with no permissions. +const loadPermissions = async ( + db: RlsDatabase, + memberId: string | null, +): Promise => { + if (!memberId) return [] + + const rows = await db.transaction((tx) => tx + .selectDistinct({ permissionKey: rolePermissions.permissionKey }) + .from(memberRoles) + .innerJoin(rolePermissions, eq(rolePermissions.roleKey, memberRoles.roleKey)) + .where(eq(memberRoles.memberId, memberId))) + + return rows.map((row) => row.permissionKey) } // Who the caller is, according to the authentication store. @@ -82,7 +108,7 @@ const loadAppUser = async ( role: resolved.role, }); - return resolved; + return { ...resolved, permissions: await loadPermissions(c.get('db'), resolved.memberId) }; } // The development bypass skips token verification entirely, so reaching it on a diff --git a/member/src/core/migration.integration.test.ts b/member/src/core/migration.integration.test.ts index bc2bb23..80f6858 100644 --- a/member/src/core/migration.integration.test.ts +++ b/member/src/core/migration.integration.test.ts @@ -4,6 +4,7 @@ import { dirname, resolve } from 'node:path' import test from 'node:test' import { fileURLToPath } from 'node:url' import { PGlite } from '@electric-sql/pglite' +import { CHECKED_PERMISSIONS } from '../../../share/permissions' const migrationPath = resolve( dirname(fileURLToPath(import.meta.url)), @@ -809,3 +810,30 @@ test('the role migration refuses to run when an admin has no member row', async await client.close() } }) + +// U-2 (docs/aidlc/unit-of-work.md). Permissions live in the database, so a +// permission name in the source is just a string: misspell it and the check +// silently asks for something nobody holds. This is the check that makes the +// mismatch fail here instead of in production. +test('every permission the code checks exists in the database', async () => { + const client = await PGlite.create() + + try { + await replayThroughSplit(client) + await client.exec(await readFile(roleTablesMigrationPath, 'utf8')) + + const stored = await client.query<{ permission_key: string }>( + 'select permission_key from public.permissions', + ) + const storedKeys = new Set(stored.rows.map((row) => row.permission_key)) + + const missing = CHECKED_PERMISSIONS.filter((key) => !storedKeys.has(key)) + assert.deepEqual( + missing, + [], + 'these permission names appear in the code but not in the database', + ) + } finally { + await client.close() + } +}) diff --git a/share/permissions.ts b/share/permissions.ts new file mode 100644 index 0000000..42b174a --- /dev/null +++ b/share/permissions.ts @@ -0,0 +1,34 @@ +// The permissions the code actually checks. +// +// The database is where permissions live (docs/aidlc/components.md Q-2): a row +// in public.permissions is what makes one exist, and roles reach them through +// role_permissions. This list is not that source of truth — it is the subset the +// application refers to by name, written down so the compiler can reject a +// typo. Without it `can(user, 'member.readPrivate')` would be a string nobody +// holds, and the check would simply never pass. +// +// A migration may add a permission no code checks yet; that is fine. The +// reverse is not, so a test asserts every key here exists in the database. +export const CHECKED_PERMISSIONS = [ + 'member.read_public', + 'member.read_private', + 'member.review', + 'member.edit', + 'role.manage', + 'event.manage', + 'reaction.read', +] as const + +export type PermissionKey = typeof CHECKED_PERMISSIONS[number] + +/** + * Whether the caller may do this. + * + * Ask about the permission, never about the role: a role is a bundle that the + * club rearranges, and code that asks "is this person an admin" has to be found + * and rewritten every time a new role appears. + */ +export const can = ( + held: readonly string[] | undefined, + required: PermissionKey, +) => held?.includes(required) ?? false From d13a3857beef226cf92a09f92602942d24fd1b50 Mon Sep 17 00:00:00 2001 From: yufoxda Date: Wed, 9 Sep 2026 22:03:24 +0900 Subject: [PATCH 2/8] refactor(auth): resolve a caller in one transaction, not two MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The permission lookup was in its own transaction, which was the wrong fix for a policy that should not have been written that way. member_roles was readable only by the member it belongs to, and satisfying that needs the request context — which does not exist until the caller has been resolved. The ordering hazard was real: read it too early and everyone silently has no permissions. app_accounts is readable to the application unconditionally for exactly this reason, and it already carries the same fact — who is an administrator. A grant is authorization metadata, not a member's personal information; the directory view and the policies on members are what protect that. So member_roles now reads the same way, and writing it stays restricted. With the policy right, the aggregate belongs in the query that was already fetching the account. A caller now resolves in one transaction and two queries: one against the authentication store, one against the domain — the boundary the design cares about, unchanged. The separate loader is gone, and so is the window where the two reads could disagree. Co-Authored-By: Claude Opus 4.8 --- community/src/core/auth.test.ts | 20 +++++++--- community/src/core/auth.ts | 39 +++++++++---------- member/src/core/auth.ts | 39 +++++++++---------- .../20260904000000_add_role_tables.sql | 18 ++++++--- supabase/tests/004_roles.test.sql | 7 +++- 5 files changed, 67 insertions(+), 56 deletions(-) diff --git a/community/src/core/auth.test.ts b/community/src/core/auth.test.ts index e3ae651..b203ba4 100644 --- a/community/src/core/auth.test.ts +++ b/community/src/core/auth.test.ts @@ -17,9 +17,14 @@ test('auth middleware reloads the application user and does not turn downstream selectCall += 1; const rows = selectCall === 1 ? [{ id: 'user-1', name: 'Test User' }] - : [{ memberId: null, role: 'user' }]; - const where = () => ({ limit: async () => rows }); - return { from: () => ({ innerJoin: () => ({ where }), where }) }; + : [{ memberId: null, role: 'user', permissions: [] }]; + // The domain lookup left-joins the grants and groups by the account, so + // the stub has to offer the same shape as the builder it stands in for. + const limit = async () => rows; + const groupBy = () => ({ limit }); + const where = () => ({ limit, groupBy }); + const leftJoin = () => ({ leftJoin, where }); + return { from: () => ({ innerJoin: () => ({ where }), leftJoin, where }) }; }, }; const db = { @@ -131,9 +136,12 @@ test('the development bypass still applies to a local request', async () => { selectCall += 1; const rows = selectCall === 1 ? [{ id: 'user-1', name: 'Local Dev' }] - : [{ memberId: null, role: 'user' }]; - const where = () => ({ limit: async () => rows }); - return { from: () => ({ innerJoin: () => ({ where }), where }) }; + : [{ memberId: null, role: 'user', permissions: [] }]; + const limit = async () => rows; + const groupBy = () => ({ limit }); + const where = () => ({ limit, groupBy }); + const leftJoin = () => ({ leftJoin, where }); + return { from: () => ({ innerJoin: () => ({ where }), leftJoin, where }) }; }, }; const db = { diff --git a/community/src/core/auth.ts b/community/src/core/auth.ts index 1749449..58a4231 100644 --- a/community/src/core/auth.ts +++ b/community/src/core/auth.ts @@ -2,7 +2,7 @@ import type { Context, Next } from 'hono' import { AppContext } from './types' import type { RlsDatabase } from './db' import { verify } from 'hono/jwt' -import { and, eq, gt } from 'drizzle-orm' +import { and, eq, gt, sql } from 'drizzle-orm' import { appAccounts, memberRoles, rolePermissions, session, user } from '../../../share/drizzle/schema' export type authUser = { @@ -21,25 +21,6 @@ export type appUser = { permissions: readonly string[] } -// Permissions are read in a second transaction, after the identity is installed. -// member_roles is only readable by the member it belongs to (or an admin), and -// that policy needs app.current_member_id — which is not set until the caller -// has been resolved. Reading it earlier would return nothing and quietly leave -// everyone with no permissions. -const loadPermissions = async ( - db: RlsDatabase, - memberId: string | null, -): Promise => { - if (!memberId) return [] - - const rows = await db.transaction((tx) => tx - .selectDistinct({ permissionKey: rolePermissions.permissionKey }) - .from(memberRoles) - .innerJoin(rolePermissions, eq(rolePermissions.roleKey, memberRoles.roleKey)) - .where(eq(memberRoles.memberId, memberId))) - - return rows.map((row) => row.permissionKey) -} // Who the caller is, according to the authentication store. const subjectSelection = { @@ -48,9 +29,21 @@ const subjectSelection = { } // What the caller may do, according to the domain. +// +// The permissions are aggregated here rather than fetched afterwards, so the +// whole domain side of a caller is one query and one consistent moment. Left +// joins because a caller who has not joined has no member row, and a member may +// hold no roles; the filter drops the nulls those produce. const accountSelection = { memberId: appAccounts.memberId, role: appAccounts.role, + permissions: sql` + coalesce( + array_agg(distinct ${rolePermissions.permissionKey}) + filter (where ${rolePermissions.permissionKey} is not null), + '{}' + ) + `, } // This is the boundary between the authentication store and the domain, and the @@ -85,7 +78,10 @@ const loadAppUser = async ( const [account] = await db .select(accountSelection) .from(appAccounts) + .leftJoin(memberRoles, eq(memberRoles.memberId, appAccounts.memberId)) + .leftJoin(rolePermissions, eq(rolePermissions.roleKey, memberRoles.roleKey)) .where(eq(appAccounts.userId, subject.id)) + .groupBy(appAccounts.memberId, appAccounts.role) .limit(1); if (!account) return null; @@ -95,6 +91,7 @@ const loadAppUser = async ( name: subject.name, memberId: account.memberId, role: account.role === 'admin' ? 'admin' as const : 'user' as const, + permissions: account.permissions, }; }); @@ -108,7 +105,7 @@ const loadAppUser = async ( role: resolved.role, }); - return { ...resolved, permissions: await loadPermissions(c.get('db'), resolved.memberId) }; + return resolved; } // The development bypass skips token verification entirely, so reaching it on a diff --git a/member/src/core/auth.ts b/member/src/core/auth.ts index c4374b8..c657661 100644 --- a/member/src/core/auth.ts +++ b/member/src/core/auth.ts @@ -2,7 +2,7 @@ import type { Context, Next } from 'hono' import { AppContext } from './types' import type { RlsDatabase } from './db' import { verify } from 'hono/jwt' -import { and, eq, gt } from 'drizzle-orm' +import { and, eq, gt, sql } from 'drizzle-orm' import { appAccounts, memberRoles, rolePermissions, session, user } from '../../../share/drizzle/schema' export type authUser = { @@ -21,25 +21,6 @@ export type appUser = { permissions: readonly string[] } -// Permissions are read in a second transaction, after the identity is installed. -// member_roles is only readable by the member it belongs to (or an admin), and -// that policy needs app.current_member_id — which is not set until the caller -// has been resolved. Reading it earlier would return nothing and quietly leave -// everyone with no permissions. -const loadPermissions = async ( - db: RlsDatabase, - memberId: string | null, -): Promise => { - if (!memberId) return [] - - const rows = await db.transaction((tx) => tx - .selectDistinct({ permissionKey: rolePermissions.permissionKey }) - .from(memberRoles) - .innerJoin(rolePermissions, eq(rolePermissions.roleKey, memberRoles.roleKey)) - .where(eq(memberRoles.memberId, memberId))) - - return rows.map((row) => row.permissionKey) -} // Who the caller is, according to the authentication store. const subjectSelection = { @@ -48,9 +29,21 @@ const subjectSelection = { } // What the caller may do, according to the domain. +// +// The permissions are aggregated here rather than fetched afterwards, so the +// whole domain side of a caller is one query and one consistent moment. Left +// joins because a caller who has not joined has no member row, and a member may +// hold no roles; the filter drops the nulls those produce. const accountSelection = { memberId: appAccounts.memberId, role: appAccounts.role, + permissions: sql` + coalesce( + array_agg(distinct ${rolePermissions.permissionKey}) + filter (where ${rolePermissions.permissionKey} is not null), + '{}' + ) + `, } // This is the boundary between the authentication store and the domain, and the @@ -85,7 +78,10 @@ const loadAppUser = async ( const [account] = await db .select(accountSelection) .from(appAccounts) + .leftJoin(memberRoles, eq(memberRoles.memberId, appAccounts.memberId)) + .leftJoin(rolePermissions, eq(rolePermissions.roleKey, memberRoles.roleKey)) .where(eq(appAccounts.userId, subject.id)) + .groupBy(appAccounts.memberId, appAccounts.role) .limit(1); if (!account) return null; @@ -95,6 +91,7 @@ const loadAppUser = async ( name: subject.name, memberId: account.memberId, role: account.role === 'admin' ? 'admin' as const : 'user' as const, + permissions: account.permissions, }; }); @@ -108,7 +105,7 @@ const loadAppUser = async ( role: resolved.role, }); - return { ...resolved, permissions: await loadPermissions(c.get('db'), resolved.memberId) }; + return resolved; } // The development bypass skips token verification entirely, so reaching it on a diff --git a/supabase/migrations/20260904000000_add_role_tables.sql b/supabase/migrations/20260904000000_add_role_tables.sql index 65006dd..8204603 100644 --- a/supabase/migrations/20260904000000_add_role_tables.sql +++ b/supabase/migrations/20260904000000_add_role_tables.sql @@ -159,13 +159,19 @@ create policy role_permissions_select on public.role_permissions for select to app_rls using (true); --- A member sees their own grants; an administrator sees everyone's. -create policy member_roles_select_self_or_admin on public.member_roles +-- Readable to the application unconditionally, like app_accounts. Resolving who +-- is calling has to happen before any request context exists, so a policy that +-- depends on that context cannot be satisfied here: the read would return +-- nothing and leave every caller with no permissions at all. +-- +-- Nothing is given away by this. app_accounts.role already tells the same +-- application role who is an administrator, and a grant is authorization +-- metadata rather than a member's personal information — that is what the +-- directory view and the policies on members exist to protect. Writing is a +-- different matter and stays restricted below. +create policy member_roles_select on public.member_roles for select to app_rls - using ( - (select current_setting('app.current_user_role', true)) = 'admin' - or member_id = nullif((select current_setting('app.current_member_id', true)), '')::uuid - ); + using (true); create policy member_roles_insert_admin on public.member_roles for insert to app_rls diff --git a/supabase/tests/004_roles.test.sql b/supabase/tests/004_roles.test.sql index 87bb77a..e544951 100644 --- a/supabase/tests/004_roles.test.sql +++ b/supabase/tests/004_roles.test.sql @@ -3,7 +3,7 @@ begin; create extension if not exists pgtap with schema extensions; set local search_path = public, extensions, pg_catalog; -select plan(16); +select plan(15); select has_table('public', 'permissions', 'permissions exist as data, not as a list in the source'); select has_table('public', 'app_roles', 'roles exist as rows'); @@ -140,10 +140,13 @@ select throws_ok( 'a member cannot grant themselves a role' ); +-- Grants are readable to the application, like app_accounts: resolving who is +-- calling happens before any request context exists. Scoping what a person is +-- shown is the API's job; RLS here is about who may change a grant. select results_eq( $$select role_key from public.member_roles$$, $$values ('member'::text)$$, - 'a member sees the roles they hold' + 'grants are readable so a caller can be resolved at all' ); -- A DELETE that no policy admits is filtered, not rejected: the statement From 8d5a4463cc20d78c6218b0cbe96f7c0800d9b848 Mon Sep 17 00:00:00 2001 From: yufoxda Date: Wed, 9 Sep 2026 22:12:24 +0900 Subject: [PATCH 3/8] refactor(auth): drop the raw aggregate and let the query builder describe itself MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The permission list was built with a hand-written array_agg wrapped in coalesce and a filter clause, embedded in the selection. Drizzle has no array-aggregate helper, so that was the only way to do the aggregation in SQL — but the aggregation itself was not needed. Selecting the joined rows says the same thing in the builder's own vocabulary: account columns, one row per permission the member's roles carry, left joins because a caller may have no member row and a member may hold no roles. The grouping, the coalesce and the null filter all go away, and deduplicating two roles that grant the same permission is a Set. The rows this collapses are few — a member's roles times their permissions — so nothing is gained by making the database do it, and the query is now readable by anyone who knows drizzle rather than anyone who knows postgres aggregate syntax. Co-Authored-By: Claude Opus 4.8 --- community/src/core/auth.test.ts | 12 ++++++------ community/src/core/auth.ts | 34 +++++++++++++++------------------ member/src/core/auth.ts | 34 +++++++++++++++------------------ 3 files changed, 36 insertions(+), 44 deletions(-) diff --git a/community/src/core/auth.test.ts b/community/src/core/auth.test.ts index b203ba4..b49e6c3 100644 --- a/community/src/core/auth.test.ts +++ b/community/src/core/auth.test.ts @@ -17,12 +17,12 @@ test('auth middleware reloads the application user and does not turn downstream selectCall += 1; const rows = selectCall === 1 ? [{ id: 'user-1', name: 'Test User' }] - : [{ memberId: null, role: 'user', permissions: [] }]; + : [{ memberId: null, role: 'user', permissionKey: null }]; // The domain lookup left-joins the grants and groups by the account, so // the stub has to offer the same shape as the builder it stands in for. const limit = async () => rows; - const groupBy = () => ({ limit }); - const where = () => ({ limit, groupBy }); + // The domain lookup left-joins the grants; the subject lookup does not. + const where = () => Object.assign(limit(), { limit }); const leftJoin = () => ({ leftJoin, where }); return { from: () => ({ innerJoin: () => ({ where }), leftJoin, where }) }; }, @@ -136,10 +136,10 @@ test('the development bypass still applies to a local request', async () => { selectCall += 1; const rows = selectCall === 1 ? [{ id: 'user-1', name: 'Local Dev' }] - : [{ memberId: null, role: 'user', permissions: [] }]; + : [{ memberId: null, role: 'user', permissionKey: null }]; const limit = async () => rows; - const groupBy = () => ({ limit }); - const where = () => ({ limit, groupBy }); + // The domain lookup left-joins the grants; the subject lookup does not. + const where = () => Object.assign(limit(), { limit }); const leftJoin = () => ({ leftJoin, where }); return { from: () => ({ innerJoin: () => ({ where }), leftJoin, where }) }; }, diff --git a/community/src/core/auth.ts b/community/src/core/auth.ts index 58a4231..71283f1 100644 --- a/community/src/core/auth.ts +++ b/community/src/core/auth.ts @@ -2,7 +2,7 @@ import type { Context, Next } from 'hono' import { AppContext } from './types' import type { RlsDatabase } from './db' import { verify } from 'hono/jwt' -import { and, eq, gt, sql } from 'drizzle-orm' +import { and, eq, gt } from 'drizzle-orm' import { appAccounts, memberRoles, rolePermissions, session, user } from '../../../share/drizzle/schema' export type authUser = { @@ -28,22 +28,14 @@ const subjectSelection = { name: user.name, } -// What the caller may do, according to the domain. -// -// The permissions are aggregated here rather than fetched afterwards, so the -// whole domain side of a caller is one query and one consistent moment. Left -// joins because a caller who has not joined has no member row, and a member may -// hold no roles; the filter drops the nulls those produce. +// What the caller may do, according to the domain: the account, and one row per +// permission the member's roles carry. Left joins because someone who has not +// joined has no member row and a member may hold no roles, so those columns +// come back null. const accountSelection = { memberId: appAccounts.memberId, role: appAccounts.role, - permissions: sql` - coalesce( - array_agg(distinct ${rolePermissions.permissionKey}) - filter (where ${rolePermissions.permissionKey} is not null), - '{}' - ) - `, + permissionKey: rolePermissions.permissionKey, } // This is the boundary between the authentication store and the domain, and the @@ -75,14 +67,14 @@ const loadAppUser = async ( if (!subject) return null; - const [account] = await db + const grants = await db .select(accountSelection) .from(appAccounts) .leftJoin(memberRoles, eq(memberRoles.memberId, appAccounts.memberId)) .leftJoin(rolePermissions, eq(rolePermissions.roleKey, memberRoles.roleKey)) - .where(eq(appAccounts.userId, subject.id)) - .groupBy(appAccounts.memberId, appAccounts.role) - .limit(1); + .where(eq(appAccounts.userId, subject.id)); + + const [account] = grants; if (!account) return null; @@ -91,7 +83,11 @@ const loadAppUser = async ( name: subject.name, memberId: account.memberId, role: account.role === 'admin' ? 'admin' as const : 'user' as const, - permissions: account.permissions, + // The same permission can arrive from two roles, and a caller holding no + // roles arrives as a single row whose permission column is null. + permissions: [...new Set( + grants.map((grant) => grant.permissionKey).filter((key) => key !== null), + )], }; }); diff --git a/member/src/core/auth.ts b/member/src/core/auth.ts index c657661..cdc784a 100644 --- a/member/src/core/auth.ts +++ b/member/src/core/auth.ts @@ -2,7 +2,7 @@ import type { Context, Next } from 'hono' import { AppContext } from './types' import type { RlsDatabase } from './db' import { verify } from 'hono/jwt' -import { and, eq, gt, sql } from 'drizzle-orm' +import { and, eq, gt } from 'drizzle-orm' import { appAccounts, memberRoles, rolePermissions, session, user } from '../../../share/drizzle/schema' export type authUser = { @@ -28,22 +28,14 @@ const subjectSelection = { name: user.name, } -// What the caller may do, according to the domain. -// -// The permissions are aggregated here rather than fetched afterwards, so the -// whole domain side of a caller is one query and one consistent moment. Left -// joins because a caller who has not joined has no member row, and a member may -// hold no roles; the filter drops the nulls those produce. +// What the caller may do, according to the domain: the account, and one row per +// permission the member's roles carry. Left joins because someone who has not +// joined has no member row and a member may hold no roles, so those columns +// come back null. const accountSelection = { memberId: appAccounts.memberId, role: appAccounts.role, - permissions: sql` - coalesce( - array_agg(distinct ${rolePermissions.permissionKey}) - filter (where ${rolePermissions.permissionKey} is not null), - '{}' - ) - `, + permissionKey: rolePermissions.permissionKey, } // This is the boundary between the authentication store and the domain, and the @@ -75,14 +67,14 @@ const loadAppUser = async ( if (!subject) return null; - const [account] = await db + const grants = await db .select(accountSelection) .from(appAccounts) .leftJoin(memberRoles, eq(memberRoles.memberId, appAccounts.memberId)) .leftJoin(rolePermissions, eq(rolePermissions.roleKey, memberRoles.roleKey)) - .where(eq(appAccounts.userId, subject.id)) - .groupBy(appAccounts.memberId, appAccounts.role) - .limit(1); + .where(eq(appAccounts.userId, subject.id)); + + const [account] = grants; if (!account) return null; @@ -91,7 +83,11 @@ const loadAppUser = async ( name: subject.name, memberId: account.memberId, role: account.role === 'admin' ? 'admin' as const : 'user' as const, - permissions: account.permissions, + // The same permission can arrive from two roles, and a caller holding no + // roles arrives as a single row whose permission column is null. + permissions: [...new Set( + grants.map((grant) => grant.permissionKey).filter((key) => key !== null), + )], }; }); From 06c4a2977ce6f437864f8be68cf0d33d16516d04 Mon Sep 17 00:00:00 2001 From: yufoxda Date: Wed, 9 Sep 2026 22:16:13 +0900 Subject: [PATCH 4/8] test: count pgTAP assertions where the edit happens, not only in CI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The suite declared fifteen assertions and made sixteen, which pgTAP reports as a failed test. That is the second miscount in this branch, and both times it surfaced only in the CI job that needs Docker — not available on the machine editing the file, so the feedback arrived several minutes and one push later. Counting them locally is a file read. The plan sits twenty lines from the assertions it counts, so adding or splitting one will keep getting this wrong; now it fails immediately and says which file and by how much. Confirmed by declaring the wrong number on purpose rather than assuming the check works. Co-Authored-By: Claude Opus 4.8 --- member/src/core/pgtap-plan.test.ts | 41 ++++++++++++++++++++++++++++++ supabase/tests/004_roles.test.sql | 2 +- 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 member/src/core/pgtap-plan.test.ts diff --git a/member/src/core/pgtap-plan.test.ts b/member/src/core/pgtap-plan.test.ts new file mode 100644 index 0000000..9a11ea7 --- /dev/null +++ b/member/src/core/pgtap-plan.test.ts @@ -0,0 +1,41 @@ +import assert from 'node:assert/strict' +import { readdir, readFile } from 'node:fs/promises' +import { dirname, join, resolve } from 'node:path' +import test from 'node:test' +import { fileURLToPath } from 'node:url' + +const suiteDirectory = resolve( + dirname(fileURLToPath(import.meta.url)), + '../../../supabase/tests', +) + +// pgTAP compares the number of assertions it ran against the number the file +// declared, and reports a miscount as a failed test. Getting that number wrong +// is easy — adding or splitting an assertion is a two-line edit and the plan is +// twenty lines away — and the only place it currently surfaces is the CI job +// that needs Docker, which is not available on every machine that edits these +// files. Counting them here costs nothing and fails where the edit happens. +test('every pgTAP suite plans the number of assertions it makes', async () => { + const files = (await readdir(suiteDirectory)).filter((name) => name.endsWith('.test.sql')) + assert.ok(files.length > 0, 'expected pgTAP suites to exist') + + for (const file of files) { + const suite = await readFile(join(suiteDirectory, file), 'utf8') + + const planned = suite.match(/^select plan\((\d+)\);$/m) + assert.ok(planned, `${file} declares no plan`) + + // Assertions are the pgTAP functions called at the top level of a file. The + // same names appear inside quoted SQL passed to lives_ok and throws_ok, so + // only a call starting its own line counts. + const assertions = suite.match( + /^select (?:ok|is|isnt|has_table|hasnt_table|has_column|hasnt_column|has_view|has_index|col_is_pk|results_eq|results_ne|lives_ok|throws_ok|is_empty)\(/gm, + ) ?? [] + + assert.equal( + assertions.length, + Number(planned[1]), + `${file} plans ${planned[1]} assertions but makes ${assertions.length}`, + ) + } +}) diff --git a/supabase/tests/004_roles.test.sql b/supabase/tests/004_roles.test.sql index e544951..653fe67 100644 --- a/supabase/tests/004_roles.test.sql +++ b/supabase/tests/004_roles.test.sql @@ -3,7 +3,7 @@ begin; create extension if not exists pgtap with schema extensions; set local search_path = public, extensions, pg_catalog; -select plan(15); +select plan(16); select has_table('public', 'permissions', 'permissions exist as data, not as a list in the source'); select has_table('public', 'app_roles', 'roles exist as rows'); From 2dc6d2a49e1ddb44cd3df802996241b41d0fe735 Mon Sep 17 00:00:00 2001 From: yufoxda Date: Wed, 9 Sep 2026 22:22:12 +0900 Subject: [PATCH 5/8] style(auth): collect permissions the way this codebase already does MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Deduplication here was spelled with a spread over a Set, inline in the object being returned. Everywhere else — collectDiscordUserIds, parseTags, splitProfileTags — it is Array.from(new Set(...)) inside a named function, so the transformation has a name and the call site reads as one thing. filter(Boolean) is the shorter form those use, but it does not narrow away null here; the comparison stays because the column is nullable and the type has to follow. Co-Authored-By: Claude Opus 4.8 --- community/src/core/auth.ts | 14 +++++++++----- member/src/core/auth.ts | 14 +++++++++----- 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/community/src/core/auth.ts b/community/src/core/auth.ts index 71283f1..067f1ba 100644 --- a/community/src/core/auth.ts +++ b/community/src/core/auth.ts @@ -38,6 +38,14 @@ const accountSelection = { permissionKey: rolePermissions.permissionKey, } +// The same permission can arrive from two roles, and a caller holding no roles +// arrives as a single row whose permission column is null. +const collectPermissions = (grants: { permissionKey: string | null }[]) => ( + Array.from(new Set( + grants.map((grant) => grant.permissionKey).filter((key) => key !== null), + )) +) + // This is the boundary between the authentication store and the domain, and the // only place that reads both. The two lookups stay separate rather than joining // across app_auth and public, so moving the authentication store to its own @@ -83,11 +91,7 @@ const loadAppUser = async ( name: subject.name, memberId: account.memberId, role: account.role === 'admin' ? 'admin' as const : 'user' as const, - // The same permission can arrive from two roles, and a caller holding no - // roles arrives as a single row whose permission column is null. - permissions: [...new Set( - grants.map((grant) => grant.permissionKey).filter((key) => key !== null), - )], + permissions: collectPermissions(grants), }; }); diff --git a/member/src/core/auth.ts b/member/src/core/auth.ts index cdc784a..8c51afa 100644 --- a/member/src/core/auth.ts +++ b/member/src/core/auth.ts @@ -38,6 +38,14 @@ const accountSelection = { permissionKey: rolePermissions.permissionKey, } +// The same permission can arrive from two roles, and a caller holding no roles +// arrives as a single row whose permission column is null. +const collectPermissions = (grants: { permissionKey: string | null }[]) => ( + Array.from(new Set( + grants.map((grant) => grant.permissionKey).filter((key) => key !== null), + )) +) + // This is the boundary between the authentication store and the domain, and the // only place that reads both. The two lookups stay separate rather than joining // across app_auth and public, so moving the authentication store to its own @@ -83,11 +91,7 @@ const loadAppUser = async ( name: subject.name, memberId: account.memberId, role: account.role === 'admin' ? 'admin' as const : 'user' as const, - // The same permission can arrive from two roles, and a caller holding no - // roles arrives as a single row whose permission column is null. - permissions: [...new Set( - grants.map((grant) => grant.permissionKey).filter((key) => key !== null), - )], + permissions: collectPermissions(grants), }; }); From b90bef69e31154dcb2627ce27937930c3afe2bf4 Mon Sep 17 00:00:00 2001 From: yufoxda Date: Wed, 9 Sep 2026 22:28:52 +0900 Subject: [PATCH 6/8] style(auth): collect the permission keys in one pass MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The helper existed to hold a hand-written row type that restated the shape of the selection above it, and to run map and filter so the nulls a left join produces could be dropped with the type following along. flatMap with `?? []` drops them in one pass and infers string[] on its own, and the same line already collects Discord user IDs in this codebase. Inline, it needs no invented type and no name — it is one expression that says what it returns. Co-Authored-By: Claude Opus 4.8 --- community/src/core/auth.ts | 12 +++--------- member/src/core/auth.ts | 12 +++--------- 2 files changed, 6 insertions(+), 18 deletions(-) diff --git a/community/src/core/auth.ts b/community/src/core/auth.ts index 067f1ba..16ebba8 100644 --- a/community/src/core/auth.ts +++ b/community/src/core/auth.ts @@ -38,14 +38,6 @@ const accountSelection = { permissionKey: rolePermissions.permissionKey, } -// The same permission can arrive from two roles, and a caller holding no roles -// arrives as a single row whose permission column is null. -const collectPermissions = (grants: { permissionKey: string | null }[]) => ( - Array.from(new Set( - grants.map((grant) => grant.permissionKey).filter((key) => key !== null), - )) -) - // This is the boundary between the authentication store and the domain, and the // only place that reads both. The two lookups stay separate rather than joining // across app_auth and public, so moving the authentication store to its own @@ -91,7 +83,9 @@ const loadAppUser = async ( name: subject.name, memberId: account.memberId, role: account.role === 'admin' ? 'admin' as const : 'user' as const, - permissions: collectPermissions(grants), + // Two roles can carry the same permission, and a caller holding none + // arrives as one row whose permission is null. + permissions: Array.from(new Set(grants.flatMap((grant) => grant.permissionKey ?? []))), }; }); diff --git a/member/src/core/auth.ts b/member/src/core/auth.ts index 8c51afa..8a6abc5 100644 --- a/member/src/core/auth.ts +++ b/member/src/core/auth.ts @@ -38,14 +38,6 @@ const accountSelection = { permissionKey: rolePermissions.permissionKey, } -// The same permission can arrive from two roles, and a caller holding no roles -// arrives as a single row whose permission column is null. -const collectPermissions = (grants: { permissionKey: string | null }[]) => ( - Array.from(new Set( - grants.map((grant) => grant.permissionKey).filter((key) => key !== null), - )) -) - // This is the boundary between the authentication store and the domain, and the // only place that reads both. The two lookups stay separate rather than joining // across app_auth and public, so moving the authentication store to its own @@ -91,7 +83,9 @@ const loadAppUser = async ( name: subject.name, memberId: account.memberId, role: account.role === 'admin' ? 'admin' as const : 'user' as const, - permissions: collectPermissions(grants), + // Two roles can carry the same permission, and a caller holding none + // arrives as one row whose permission is null. + permissions: Array.from(new Set(grants.flatMap((grant) => grant.permissionKey ?? []))), }; }); From 51cdc769939a4137469033e1cf663a990ec88890 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 1 Nov 2026 10:03:22 +0000 Subject: [PATCH 7/8] docs(auth): record why grants are readable without request context U-2 opens SELECT on member_roles to app_rls unconditionally, an exception to "enforce in the database" (3.4). Record the reason, what stays restricted, what it obliges the API to do, and the alternatives that were rejected, so the decision is findable outside the migration comment. Also reconcile 3.2 with share/permissions.ts: the list in the code is the subset it refers to by name, not a second source of truth. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vm1iXpgdwQfcWuyNzX9KF7 --- docs/aidlc/components.md | 38 +++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/docs/aidlc/components.md b/docs/aidlc/components.md index 14c44ba..6c30fdf 100644 --- a/docs/aidlc/components.md +++ b/docs/aidlc/components.md @@ -89,7 +89,11 @@ Cloudflare の Service Bindings は採らない。速度で有利だが、 **権限もロールへの割り当ても、すべてデータとして持つ**(2026-09-03 決定)。 権限は行として存在し、ロールとの対応も行として持つ。 -コード側に権限の一覧を持たない。 +コード側に権限の一覧を持たない。権限を存在させるのはデータベースの行だけである。 + +ただし、コードが名前で参照する権限は `share/permissions.ts` に書き出す(U-2)。 +これは権限の正典ではなく、綴りの誤りをコンパイラに弾かせるための部分集合である。 +データベースにあってコードにない権限は許す。逆は下の検査で失敗させる。 **この方式の弱点と対策** @@ -150,6 +154,38 @@ RLS ポリシーの4箇所も同様に、渡す識別子をロール名から権 最後の2つは、既存の `member_status_history` と同じ方式(トリガーが書き、アプリは書けない)にする。 +### 3.5 ロール付与の読み取りはデータベースで絞らない(U-2 で決定) + +`member_roles` の SELECT は、`app_accounts` と同じく `app_rls` に無条件で許す(`using (true)`)。 +3.4 の「データベース側で守る」の例外として、範囲と理由をここに残す。 + +**理由** + +- 権限は呼び出し元を解決する処理の中で読む。その時点ではまだ `app.current_member_id` が設定されていない。 + このため、本人の行に絞るポリシーでは結果が空になり、**全員の権限がゼロになる**。 + しかも見た目は権限のバグで、実際の原因である読み取り順序にはたどり着きにくい +- 絞っても守れるものがほぼない。`app_rls` は `app_accounts.role` を既に無条件で読めるので、 + アプリ層が侵害された時点で誰が管理者かは分かってしまう。 + また、ロールの付与は認可のための情報であり、部員の個人情報ではない。 + 個人情報を守っているのは `members` のポリシーと名簿ビュー + +**緩めないもの** + +- 付与と剥奪(INSERT / DELETE)は今まで通り制限する。権限昇格につながるのはこちら。 + 申告されたロールを実値と突き合わせる対策は U-2.5 で行う(`unit-of-work.md`) + +**この決定の帰結** + +- 部員のロールを画面に出す API は、**誰に何を見せるかを API 側で絞る**。データベースは絞ってくれない +- U-3 で RLS ポリシーを権限ベースへ変えるとき、ポリシーの中から `member_roles` を参照してよい + +**採らなかった案** + +- 呼び出し元の解決を2つのトランザクションに分け、2つ目で `app.current_member_id` を設定してから読む。 + 読み取りの順序という見えにくい前提に正しさを頼ることになる。 + 順序を誤ったときの症状(全員の権限がゼロ)も原因にたどり着きにくい +- SECURITY DEFINER 関数で権限を返す。仕組みが増えるわりに、上の理由で守れるものがない + --- ## 4. 書き込みの共通化 From 261c1c369e551948c9cf5bdb3d5b2a1d99061e73 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 1 Nov 2026 10:50:49 +0000 Subject: [PATCH 8/8] test(db): read grants with no request context, as the middleware does The assertion that grants are readable ran with the member's own context set, so a policy scoped to the member's own rows passed it too. Narrowing the policy back would have left every caller with no permissions while the suite stayed green: nothing else reads member_roles as app_rls without context (the migration test reads as superuser, the join test uses its own tables). Clear the context before the read and restore it after. The assertion count is unchanged. Verified against PGlite with the migrations replayed: with no context set, the current policy returns the grant and the old self-only policy returns nothing. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vm1iXpgdwQfcWuyNzX9KF7 --- supabase/tests/004_roles.test.sql | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/supabase/tests/004_roles.test.sql b/supabase/tests/004_roles.test.sql index 653fe67..aa4924f 100644 --- a/supabase/tests/004_roles.test.sql +++ b/supabase/tests/004_roles.test.sql @@ -143,12 +143,27 @@ select throws_ok( -- Grants are readable to the application, like app_accounts: resolving who is -- calling happens before any request context exists. Scoping what a person is -- shown is the API's job; RLS here is about who may change a grant. +-- +-- So read them the way the auth middleware does, with no context set. Read with +-- the member's context instead and a policy scoped to the member's own rows +-- would pass too, and narrowing it back would leave every caller with no +-- permissions while this suite stayed green. +select + set_config('app.current_user_id', '', true), + set_config('app.current_member_id', '', true), + set_config('app.current_user_role', '', true); + select results_eq( $$select role_key from public.member_roles$$, $$values ('member'::text)$$, - 'grants are readable so a caller can be resolved at all' + 'grants are readable before the caller is resolved' ); +select + set_config('app.current_user_id', 'roles-member', true), + set_config('app.current_member_id', '00000000-0000-4000-8000-00000000030a', true), + set_config('app.current_user_role', 'user', true); + -- A DELETE that no policy admits is filtered, not rejected: the statement -- succeeds having removed nothing. Only the surviving row proves the point, so -- asserting an exception here would have passed for the wrong reason.