Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 16 additions & 6 deletions community/src/core/auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', 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;
// 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 }) };
},
};
const db = {
Expand Down Expand Up @@ -58,6 +63,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, {
Expand Down Expand Up @@ -129,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', permissionKey: null }];
const limit = async () => rows;
// 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 }) };
},
};
const db = {
Expand Down
27 changes: 22 additions & 5 deletions community/src/core/auth.ts
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -13,18 +14,28 @@ 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[]
}


// Who the caller is, according to the authentication store.
const subjectSelection = {
id: user.id,
name: user.name,
}

// What the caller may do, according to the domain.
// 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,
permissionKey: rolePermissions.permissionKey,
}

// This is the boundary between the authentication store and the domain, and the
Expand Down Expand Up @@ -56,11 +67,14 @@ const loadAppUser = async (

if (!subject) return null;

const [account] = await db
const grants = await db
.select(accountSelection)
.from(appAccounts)
.where(eq(appAccounts.userId, subject.id))
.limit(1);
.leftJoin(memberRoles, eq(memberRoles.memberId, appAccounts.memberId))
.leftJoin(rolePermissions, eq(rolePermissions.roleKey, memberRoles.roleKey))
.where(eq(appAccounts.userId, subject.id));

const [account] = grants;

if (!account) return null;

Expand All @@ -69,6 +83,9 @@ const loadAppUser = async (
name: subject.name,
memberId: account.memberId,
role: account.role === 'admin' ? 'admin' as const : 'user' as const,
// 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 ?? []))),
};
});

Expand Down
38 changes: 37 additions & 1 deletion docs/aidlc/components.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,11 @@ Cloudflare の Service Bindings は採らない。速度で有利だが、
**権限もロールへの割り当ても、すべてデータとして持つ**(2026-09-03 決定)。

権限は行として存在し、ロールとの対応も行として持つ。
コード側に権限の一覧を持たない。
コード側に権限の一覧を持たない。権限を存在させるのはデータベースの行だけである。

ただし、コードが名前で参照する権限は `share/permissions.ts` に書き出す(U-2)。
これは権限の正典ではなく、綴りの誤りをコンパイラに弾かせるための部分集合である。
データベースにあってコードにない権限は許す。逆は下の検査で失敗させる。

**この方式の弱点と対策**

Expand Down Expand Up @@ -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. 書き込みの共通化
Expand Down
17 changes: 17 additions & 0 deletions member/src/api_v0/member/join.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }

Expand All @@ -39,13 +40,16 @@ const applicant: appUser = {
name: 'Applicant',
memberId: null,
role: 'user',
// Not a member yet, so no role grants it anything.
permissions: [],
}

const admin: appUser = {
id: 'test-admin',
name: 'Admin',
memberId: null,
role: 'admin',
permissions: [...CHECKED_PERMISSIONS],
}

const createContext = (
Expand Down Expand Up @@ -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');
Expand All @@ -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)
Expand Down
27 changes: 22 additions & 5 deletions member/src/core/auth.ts
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -13,18 +14,28 @@ 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[]
}


// Who the caller is, according to the authentication store.
const subjectSelection = {
id: user.id,
name: user.name,
}

// What the caller may do, according to the domain.
// 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,
permissionKey: rolePermissions.permissionKey,
}

// This is the boundary between the authentication store and the domain, and the
Expand Down Expand Up @@ -56,11 +67,14 @@ const loadAppUser = async (

if (!subject) return null;

const [account] = await db
const grants = await db
.select(accountSelection)
.from(appAccounts)
.where(eq(appAccounts.userId, subject.id))
.limit(1);
.leftJoin(memberRoles, eq(memberRoles.memberId, appAccounts.memberId))
.leftJoin(rolePermissions, eq(rolePermissions.roleKey, memberRoles.roleKey))
.where(eq(appAccounts.userId, subject.id));

const [account] = grants;

if (!account) return null;

Expand All @@ -69,6 +83,9 @@ const loadAppUser = async (
name: subject.name,
memberId: account.memberId,
role: account.role === 'admin' ? 'admin' as const : 'user' as const,
// 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 ?? []))),
};
});

Expand Down
28 changes: 28 additions & 0 deletions member/src/core/migration.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)),
Expand Down Expand Up @@ -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()
}
})
41 changes: 41 additions & 0 deletions member/src/core/pgtap-plan.test.ts
Original file line number Diff line number Diff line change
@@ -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}`,
)
}
})
Loading
Loading