diff --git a/community/src/api_v0/user/id/role/router.ts b/community/src/api_v0/user/id/role/router.ts index 7812055..5519f63 100644 --- a/community/src/api_v0/user/id/role/router.ts +++ b/community/src/api_v0/user/id/role/router.ts @@ -1,8 +1,7 @@ import { OpenAPIHono } from "@hono/zod-openapi"; import type { AppContext } from "../../../../core/types"; -import { getUserRolesByIdRoute, updateUserRolesRoute } from "./schema"; -import { getUserRolesByIdService, updateUserRolesService } from "./service"; +import { getUserRolesByIdRoute } from "./schema"; +import { getUserRolesByIdService } from "./service"; export const userDetailRoleRouter = new OpenAPIHono() - .openapi(getUserRolesByIdRoute, getUserRolesByIdService) - .openapi(updateUserRolesRoute, updateUserRolesService); + .openapi(getUserRolesByIdRoute, getUserRolesByIdService); diff --git a/community/src/api_v0/user/id/role/schema.ts b/community/src/api_v0/user/id/role/schema.ts index 4515c84..70189b7 100644 --- a/community/src/api_v0/user/id/role/schema.ts +++ b/community/src/api_v0/user/id/role/schema.ts @@ -13,18 +13,3 @@ export const getUserRolesByIdRoute = createRoute({ 404: { description: "Not Found" } } }); - -export const updateUserRolesRoute = createRoute({ - method: "put", - path: "/", - request: { - params: z.object({ id: z.string() }), - body: { content: { "application/json": { schema: z.object({ role_ids: z.string().array() }) } } } - }, - responses: { - 200: { - description: "特定ユーザーのロールを更新", - content: { "application/json": { schema: roleSchema.array() } } - } - } -}); diff --git a/community/src/api_v0/user/id/role/service.ts b/community/src/api_v0/user/id/role/service.ts index cc9b37f..790701d 100644 --- a/community/src/api_v0/user/id/role/service.ts +++ b/community/src/api_v0/user/id/role/service.ts @@ -1,8 +1,6 @@ -import { can } from "../../../../../../share/permissions"; import { RouteHandler } from "@hono/zod-openapi"; import { AppContext } from "../../../../core/types"; -import { getUserRolesByIdRoute, updateUserRolesRoute } from "./schema"; -import { HTTPException } from "hono/http-exception"; +import { getUserRolesByIdRoute } from "./schema"; export const getUserRolesByIdService: RouteHandler = async (c) => { const userId = c.req.param("id"); @@ -16,10 +14,3 @@ export const getUserRolesByIdService: RouteHandler = async (c) => { - const user = c.get("appUser"); - if (!can(user.permissions, "role.manage")) throw new HTTPException(403); - const mockRole = { roleId: "r-123", roleName: "admin" }; - return c.json([mockRole], 200); -}; diff --git a/member/src/api_v0/role/role.integration.test.ts b/member/src/api_v0/role/role.integration.test.ts new file mode 100644 index 0000000..733edc4 --- /dev/null +++ b/member/src/api_v0/role/role.integration.test.ts @@ -0,0 +1,153 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { PGlite } from '@electric-sql/pglite' +import { drizzle } from 'drizzle-orm/pglite' +import { CHECKED_PERMISSIONS } from '../../../../share/permissions' +import type { appUser } from '../../core/auth' +import { createRlsDatabase } from '../../core/db' +import { + applyAsNewUser, + approveMember, + promoteToAdmin, + replayThroughLatest, + replayThroughSplit, +} from '../../core/testing/migrations' +import { getMemberRolesService, grantRoleService, listRolesService, revokeRoleService } from './service' + +type JsonResponse = { body: any; status: number } + +const firstAdminMember = '00000000-0000-4000-8000-000000000901' +const secondMember = '00000000-0000-4000-8000-000000000902' +const pendingMember = '00000000-0000-4000-8000-000000000903' + +const firstAdmin: appUser = { id: 'role-first', name: 'First', memberId: firstAdminMember, permissions: [...CHECKED_PERMISSIONS] } +const second: appUser = { id: 'role-second', name: 'Second', memberId: secondMember, permissions: [...CHECKED_PERMISSIONS] } +const plainMember: appUser = { id: 'role-second', name: 'Second', memberId: secondMember, permissions: ['member.read_public'] } + +// 本物の RLS 付きのデータベースで、API の処理を 1 回呼ぶ +const call = async ( + client: PGlite, + service: (c: never) => unknown, + currentUser: appUser, + request: { params?: Record; body?: unknown } = {}, +): Promise => { + const db = createRlsDatabase(drizzle(client) as never) + db.setIdentity({ userId: currentUser.id }) + const context = { + req: { + valid: (target: string) => target === 'json' ? request.body : request.params ?? {}, + }, + get: (key: string) => { + if (key === 'appUser') return currentUser + if (key === 'db') return db + throw new Error(`Unexpected context key: ${key}`) + }, + header: () => {}, + json: (body: unknown, status: number): JsonResponse => ({ body, status }), + } + return await service(context as never) as JsonResponse +} + +const setUp = async () => { + const client = await PGlite.create() + await replayThroughSplit(client) + await applyAsNewUser(client, { userId: firstAdmin.id, memberId: firstAdminMember }) + await promoteToAdmin(client, firstAdmin.id) + await approveMember(client, firstAdmin.id, firstAdminMember) + await applyAsNewUser(client, { userId: second.id, memberId: secondMember }) + await approveMember(client, firstAdmin.id, secondMember) + await applyAsNewUser(client, { userId: 'role-pending', memberId: pendingMember }) + await replayThroughLatest(client) + return client +} + +test('role.manage を持たない人は、ロールの API を使えない', async () => { + const client = await setUp() + try { + const params = { memberId: secondMember } + assert.equal((await call(client, listRolesService as never, plainMember)).status, 403) + assert.equal((await call(client, getMemberRolesService as never, plainMember, { params })).status, 403) + assert.equal((await call(client, grantRoleService as never, plainMember, { params, body: { roleKey: 'admin' } })).status, 403) + assert.equal((await call(client, revokeRoleService as never, plainMember, { params: { ...params, roleKey: 'member' } })).status, 403) + } finally { + await client.close() + } +}) + +test('ロールを付けて外すと、結果と履歴が返る', async () => { + const client = await setUp() + try { + const roles = await call(client, listRolesService as never, firstAdmin) + assert.equal(roles.status, 200) + assert.deepEqual(roles.body.map((role: { roleKey: string }) => role.roleKey), ['admin', 'member']) + + // 2 人目に admin を付ける。同じロールを 2 回付けても、2 回目は何もしない + for (let attempt = 0; attempt < 2; attempt += 1) { + const granted = await call(client, grantRoleService as never, firstAdmin, { + params: { memberId: secondMember }, + body: { roleKey: 'admin' }, + }) + assert.equal(granted.status, 200) + assert.deepEqual(granted.body.roles.map((role: { roleKey: string }) => role.roleKey), ['admin', 'member']) + assert.deepEqual( + granted.body.history.map((row: { roleKey: string; action: string; actorUserId: string }) => + [row.roleKey, row.action, row.actorUserId]), + [['admin', 'grant', firstAdmin.id]], + '付与は 1 回だけ、付けた人と一緒に履歴に残る', + ) + } + + // 2 人目が、1 人目の admin を外す(管理者がまだ 1 人残るので許される) + const revoked = await call(client, revokeRoleService as never, second, { + params: { memberId: firstAdminMember, roleKey: 'admin' }, + }) + assert.equal(revoked.status, 200) + assert.deepEqual(revoked.body.roles.map((role: { roleKey: string }) => role.roleKey), ['member']) + assert.deepEqual( + [revoked.body.history[0].roleKey, revoked.body.history[0].action, revoked.body.history[0].actorUserId], + ['admin', 'revoke', second.id], + ) + + // 最後の管理者は外せない + const lastManager = await call(client, revokeRoleService as never, second, { + params: { memberId: secondMember, roleKey: 'admin' }, + }) + assert.equal(lastManager.status, 409) + assert.equal(lastManager.body.code, 'last_role_manager') + + // 部員のロールと履歴を読む + const current = await call(client, getMemberRolesService as never, second, { params: { memberId: secondMember } }) + assert.equal(current.status, 200) + assert.deepEqual(current.body.roles.map((role: { roleKey: string }) => role.roleKey), ['admin', 'member']) + } finally { + await client.close() + } +}) + +test('付けられない相手や存在しないロールは、理由つきで断る', async () => { + const client = await setUp() + try { + const grant = (memberId: string, roleKey: string) => + call(client, grantRoleService as never, firstAdmin, { params: { memberId }, body: { roleKey } }) + + const pending = await grant(pendingMember, 'admin') + assert.equal(pending.status, 409) + assert.equal(pending.body.code, 'member_not_active', '在籍中でない部員には付けない') + + const unknownRole = await grant(secondMember, 'treasurer') + assert.equal(unknownRole.status, 400) + assert.equal(unknownRole.body.code, 'unknown_role') + + const unknownMember = await grant('00000000-0000-4000-8000-000000000999', 'admin') + assert.equal(unknownMember.status, 404) + assert.equal(unknownMember.body.code, 'member_not_found') + + const notHeld = await call(client, revokeRoleService as never, firstAdmin, { + params: { memberId: pendingMember, roleKey: 'admin' }, + }) + assert.equal(notHeld.status, 404) + assert.equal(notHeld.body.code, 'role_not_held') + } finally { + await client.close() + } +}) diff --git a/member/src/api_v0/role/router.ts b/member/src/api_v0/role/router.ts new file mode 100644 index 0000000..42665a4 --- /dev/null +++ b/member/src/api_v0/role/router.ts @@ -0,0 +1,11 @@ +import { OpenAPIHono } from "@hono/zod-openapi" +import type { AppContext } from "../../core/types" +import { getMemberRolesRoute, grantRoleRoute, listRolesRoute, revokeRoleRoute } from "./schema" +import { getMemberRolesService, grantRoleService, listRolesService, revokeRoleService } from "./service" + +// ロールの付与・剥奪(U-5)。/api/v0/role 以下に置く。 +export const roleRouter = new OpenAPIHono() + .openapi(listRolesRoute, listRolesService) + .openapi(getMemberRolesRoute, getMemberRolesService) + .openapi(grantRoleRoute, grantRoleService) + .openapi(revokeRoleRoute, revokeRoleService) diff --git a/member/src/api_v0/role/schema.ts b/member/src/api_v0/role/schema.ts new file mode 100644 index 0000000..3795906 --- /dev/null +++ b/member/src/api_v0/role/schema.ts @@ -0,0 +1,95 @@ +import { createRoute, z } from "@hono/zod-openapi" + +// ロールの付与・剥奪(U-5、FR-5.1)。どの API も role.manage を持つ人だけが使える。 + +const ErrorSchema = z.object({ + error: z.string(), + code: z.string(), +}).openapi("RoleErrorResponse") + +// 選べるロール +export const RoleSchema = z.object({ + roleKey: z.string(), + displayName: z.string(), + description: z.string(), +}).openapi("Role") + +// 部員が今持っているロール +export const MemberRoleSchema = z.object({ + roleKey: z.string(), + displayName: z.string(), + grantedAt: z.string(), +}).openapi("MemberRole") + +// ロールの変更履歴(FR-5.3) +export const RoleHistorySchema = z.object({ + roleKey: z.string(), + action: z.enum(["grant", "revoke"]), + actorUserId: z.string(), + occurredAt: z.string(), +}).openapi("RoleHistory") + +export const MemberRolesResponseSchema = z.object({ + roles: z.array(MemberRoleSchema), + history: z.array(RoleHistorySchema), +}).openapi("MemberRolesResponse") + +const MemberParamsSchema = z.object({ + memberId: z.string().uuid().openapi({ param: { name: "memberId", in: "path" } }), +}) + +const MemberRoleParamsSchema = MemberParamsSchema.extend({ + roleKey: z.string().openapi({ param: { name: "roleKey", in: "path" } }), +}) + +export const GrantRoleSchema = z.object({ + roleKey: z.string(), +}).openapi("GrantRole") + +export const listRolesRoute = createRoute({ + method: "get", + path: "/", + responses: { + 200: { description: "選べるロールの一覧", content: { "application/json": { schema: z.array(RoleSchema) } } }, + 403: { description: "権限がありません", content: { "application/json": { schema: ErrorSchema } } }, + }, +}) + +export const getMemberRolesRoute = createRoute({ + method: "get", + path: "/members/{memberId}", + request: { params: MemberParamsSchema }, + responses: { + 200: { description: "部員のロールと変更履歴", content: { "application/json": { schema: MemberRolesResponseSchema } } }, + 403: { description: "権限がありません", content: { "application/json": { schema: ErrorSchema } } }, + 404: { description: "部員が見つかりません", content: { "application/json": { schema: ErrorSchema } } }, + }, +}) + +export const grantRoleRoute = createRoute({ + method: "post", + path: "/members/{memberId}", + request: { + params: MemberParamsSchema, + body: { content: { "application/json": { schema: GrantRoleSchema } } }, + }, + responses: { + 200: { description: "付与した後のロールと変更履歴", content: { "application/json": { schema: MemberRolesResponseSchema } } }, + 400: { description: "存在しないロール", content: { "application/json": { schema: ErrorSchema } } }, + 403: { description: "権限がありません", content: { "application/json": { schema: ErrorSchema } } }, + 404: { description: "部員が見つかりません", content: { "application/json": { schema: ErrorSchema } } }, + 409: { description: "在籍中でない部員にはロールを付けられません", content: { "application/json": { schema: ErrorSchema } } }, + }, +}) + +export const revokeRoleRoute = createRoute({ + method: "delete", + path: "/members/{memberId}/{roleKey}", + request: { params: MemberRoleParamsSchema }, + responses: { + 200: { description: "外した後のロールと変更履歴", content: { "application/json": { schema: MemberRolesResponseSchema } } }, + 403: { description: "権限がありません", content: { "application/json": { schema: ErrorSchema } } }, + 404: { description: "部員がそのロールを持っていません", content: { "application/json": { schema: ErrorSchema } } }, + 409: { description: "最後の管理者は外せません", content: { "application/json": { schema: ErrorSchema } } }, + }, +}) diff --git a/member/src/api_v0/role/service.ts b/member/src/api_v0/role/service.ts new file mode 100644 index 0000000..31f28dd --- /dev/null +++ b/member/src/api_v0/role/service.ts @@ -0,0 +1,168 @@ +import type { Context } from "hono" +import type { RouteHandler } from "@hono/zod-openapi" +import { and, desc, eq } from "drizzle-orm" +import { can } from "../../../../share/permissions" +import { appRoles, memberRoleHistory, memberRoles, members } from "../../../../share/drizzle/schema" +import type { AppTransaction } from "../../core/db" +import type { AppContext } from "../../core/types" +import { conflictForLastRoleManager } from "../member/service" +import { getMemberRolesRoute, grantRoleRoute, listRolesRoute, revokeRoleRoute } from "./schema" + +// ロールの情報は、ブラウザや途中の経路に保存させない +const setPrivateNoStore = (c: Context) => { + c.header("Cache-Control", "private, no-store, max-age=0") + c.header("Pragma", "no-cache") +} + +const forbidden = { error: "Forbidden", code: "forbidden" } +const memberNotFound = { error: "Member not found", code: "member_not_found" } + +// 部員が今持っているロールと、その部員のロールの変更履歴(新しい順) +const loadMemberRoles = async (tx: AppTransaction, memberId: string) => { + const roles = await tx + .select({ + roleKey: memberRoles.roleKey, + displayName: appRoles.displayName, + grantedAt: memberRoles.grantedAt, + }) + .from(memberRoles) + .innerJoin(appRoles, eq(appRoles.roleKey, memberRoles.roleKey)) + .where(eq(memberRoles.memberId, memberId)) + .orderBy(memberRoles.roleKey) + + const history = await tx + .select({ + roleKey: memberRoleHistory.roleKey, + action: memberRoleHistory.action, + actorUserId: memberRoleHistory.actorUserId, + occurredAt: memberRoleHistory.occurredAt, + }) + .from(memberRoleHistory) + .where(eq(memberRoleHistory.memberId, memberId)) + .orderBy(desc(memberRoleHistory.occurredAt), desc(memberRoleHistory.historyId)) + + return { roles, history } +} + +const findMemberStatus = async (tx: AppTransaction, memberId: string) => { + const [member] = await tx + .select({ memberStatus: members.memberStatus }) + .from(members) + .where(eq(members.memberId, memberId)) + .limit(1) + return member?.memberStatus +} + +export const listRolesService: RouteHandler = async (c) => { + setPrivateNoStore(c) + const appUser = c.get("appUser") + if (!can(appUser.permissions, "role.manage")) { + return c.json(forbidden, 403) + } + + const roles = await c.get("db").transaction((tx) => tx + .select({ + roleKey: appRoles.roleKey, + displayName: appRoles.displayName, + description: appRoles.description, + }) + .from(appRoles) + .orderBy(appRoles.roleKey)) + + return c.json(roles, 200) +} + +export const getMemberRolesService: RouteHandler = async (c) => { + setPrivateNoStore(c) + const appUser = c.get("appUser") + if (!can(appUser.permissions, "role.manage")) { + return c.json(forbidden, 403) + } + + const { memberId } = c.req.valid("param") + const result = await c.get("db").transaction(async (tx) => { + if (!await findMemberStatus(tx, memberId)) return null + return loadMemberRoles(tx, memberId) + }) + + if (!result) { + return c.json(memberNotFound, 404) + } + return c.json(result, 200) +} + +export const grantRoleService: RouteHandler = async (c) => { + setPrivateNoStore(c) + const appUser = c.get("appUser") + if (!can(appUser.permissions, "role.manage")) { + return c.json(forbidden, 403) + } + + const { memberId } = c.req.valid("param") + const { roleKey } = c.req.valid("json") + + const result = await c.get("db").transaction(async (tx) => { + const status = await findMemberStatus(tx, memberId) + if (!status) return "member_not_found" as const + + // 退部するとロールが外れる(U-6)ので、在籍中でない部員には付けない + if (status !== "active") return "member_not_active" as const + + const [role] = await tx + .select({ roleKey: appRoles.roleKey }) + .from(appRoles) + .where(eq(appRoles.roleKey, roleKey)) + .limit(1) + if (!role) return "unknown_role" as const + + // すでに持っているロールなら何もしない。履歴はトリガーが書く + await tx + .insert(memberRoles) + .values({ memberId, roleKey, grantedByUserId: appUser.id }) + .onConflictDoNothing() + + return loadMemberRoles(tx, memberId) + }) + + if (result === "member_not_found") { + return c.json(memberNotFound, 404) + } + if (result === "member_not_active") { + return c.json({ error: "Roles can be granted only to active members", code: "member_not_active" }, 409) + } + if (result === "unknown_role") { + return c.json({ error: "Unknown role", code: "unknown_role" }, 400) + } + return c.json(result, 200) +} + +export const revokeRoleService: RouteHandler = async (c) => { + setPrivateNoStore(c) + const appUser = c.get("appUser") + if (!can(appUser.permissions, "role.manage")) { + return c.json(forbidden, 403) + } + + const { memberId, roleKey } = c.req.valid("param") + + try { + const result = await c.get("db").transaction(async (tx) => { + // 最後の管理者を外そうとすると、データベースが拒む(keep_a_role_manager)。履歴はトリガーが書く + const removed = await tx + .delete(memberRoles) + .where(and(eq(memberRoles.memberId, memberId), eq(memberRoles.roleKey, roleKey))) + .returning({ roleKey: memberRoles.roleKey }) + if (removed.length === 0) return null + return loadMemberRoles(tx, memberId) + }) + + if (!result) { + return c.json({ error: "The member does not hold this role", code: "role_not_held" }, 404) + } + return c.json(result, 200) + } catch (error) { + const lastManager = conflictForLastRoleManager(error) + if (lastManager) return c.json(lastManager, 409) + throw error + } +} diff --git a/member/src/api_v0/router.ts b/member/src/api_v0/router.ts index 995cd0b..8cd62ac 100644 --- a/member/src/api_v0/router.ts +++ b/member/src/api_v0/router.ts @@ -3,7 +3,9 @@ import { AppContext } from "../core/types" import { userRouter } from './member/router' import { gradeRouter } from './grade/router' +import { roleRouter } from './role/router' export const apiv0Router = new OpenAPIHono() .route("/member", userRouter) .route("/grade", gradeRouter) + .route("/role", roleRouter) diff --git a/member/src/core/migration.integration.test.ts b/member/src/core/migration.integration.test.ts index 89292d9..4556142 100644 --- a/member/src/core/migration.integration.test.ts +++ b/member/src/core/migration.integration.test.ts @@ -7,23 +7,19 @@ import { PGlite } from '@electric-sql/pglite' import { drizzle } from 'drizzle-orm/pglite' import { CHECKED_PERMISSIONS } from '../../../share/permissions' import { findPermissions } from './permissions' +import { + applyAsNewUser, + approveMember, + createCurrentSchema, + createPlatformRolesAndAuthSchema, + membershipWorkflowMigrationPath, + migrationPath, + promoteToAdmin, + replayThroughSplit, + roleTablesMigrationPath, + splitAuthSchemaMigrationPath, +} from './testing/migrations' -const migrationPath = resolve( - dirname(fileURLToPath(import.meta.url)), - '../../../supabase/migrations/20260716005139_reconcile_better_auth_baseline.sql', -) -const membershipWorkflowMigrationPath = resolve( - dirname(fileURLToPath(import.meta.url)), - '../../../supabase/migrations/20260716123951_membership_workflow.sql', -) -const splitAuthSchemaMigrationPath = resolve( - dirname(fileURLToPath(import.meta.url)), - '../../../supabase/migrations/20260727000000_split_auth_schema.sql', -) -const roleTablesMigrationPath = resolve( - dirname(fileURLToPath(import.meta.url)), - '../../../supabase/migrations/20260904000000_add_role_tables.sql', -) const confirmedTestDataPurgeRunbookPath = resolve( dirname(fileURLToPath(import.meta.url)), '../../../supabase/runbooks/purge_confirmed_test_membership_data.sql', @@ -33,137 +29,6 @@ const provisionRuntimeLoginRunbookPath = resolve( '../../../supabase/runbooks/provision_app_runtime_login.sql', ) -const createPlatformRolesAndAuthSchema = async (client: PGlite) => { - await client.exec(` - create role anon; - create role authenticated; - create role service_role; - alter default privileges in schema public grant all on tables to service_role; - alter default privileges in schema public grant all on sequences to service_role; - alter default privileges in schema public grant execute on functions to service_role; - create schema auth; - create table auth.users (id uuid primary key default gen_random_uuid()); - `) -} - -const createCurrentSchema = async (client: PGlite, withFixture = true) => { - await client.exec(` - create table grades ( - id integer generated always as identity primary key, - display_grade text not null, - created_at timestamptz not null default now(), - updated_at timestamptz not null default now(), - year bigint not null default extract(year from current_date) - ); - - create table members ( - name text not null, - grade integer not null references grades(id) on delete set null, - emergency_contact text not null, - student_id text not null, - student_email text not null, - insurance boolean not null default false, - some_allergy boolean not null default false, - created_at timestamptz not null default now(), - updated_at timestamptz not null default now(), - member_id uuid primary key default gen_random_uuid() - ); - - create table "user" ( - id text primary key, - name text not null, - email text not null unique, - email_verified boolean not null, - image text, - created_at timestamp not null, - updated_at timestamp not null, - discord_user_id text, - display_name text, - member_id uuid references members(member_id) on delete set null, - role text not null default 'user' - ); - - create table account ( - id text primary key, - account_id text not null, - provider_id text not null, - user_id text not null references "user"(id) on delete cascade, - access_token text, - refresh_token text, - id_token text, - access_token_expires_at timestamp, - refresh_token_expires_at timestamp, - scope text, - password text, - created_at timestamp not null, - updated_at timestamp not null - ); - - create table session ( - id text primary key, - expires_at timestamp not null, - token text not null unique, - created_at timestamp not null, - updated_at timestamp not null, - ip_address text, - user_agent text, - user_id text not null references "user"(id) on delete cascade - ); - - create table verification ( - id text primary key, - identifier text not null, - value text not null, - expires_at timestamp not null, - created_at timestamp, - updated_at timestamp - ); - - create table event_messages ( - id uuid primary key default gen_random_uuid(), - channel_id text not null, - message_id text not null unique, - content text not null, - created_by text not null, - created_at timestamptz not null default now(), - updated_at timestamptz not null default now() - ); - - create function public.handle_new_user() - returns trigger - language plpgsql - security definer - as $$ begin return new; end $$; - - ${withFixture ? ` - insert into grades (id, display_grade) - overriding system value values (1, 'M1'); - - insert into members ( - member_id, name, grade, emergency_contact, student_id, student_email - ) values - ('00000000-0000-4000-8000-000000000001', 'One', 1, 'contact', 'A001', 'one@example.test'), - ('00000000-0000-4000-8000-000000000002', 'Two', 1, 'contact', 'A002', 'two@example.test'), - ('00000000-0000-4000-8000-000000000003', 'Three', 1, 'contact', 'A003', 'three@example.test'); - - insert into "user" ( - id, name, email, email_verified, created_at, updated_at, member_id, role - ) values - ('user-1', 'One', 'one@example.test', true, now(), now(), '00000000-0000-4000-8000-000000000001', 'admin'), - ('user-2', 'Two', 'two@example.test', true, now(), now(), '00000000-0000-4000-8000-000000000002', 'user'); - - insert into account ( - id, account_id, provider_id, user_id, created_at, updated_at - ) values - ('account-1', 'github-1', 'github', 'user-1', now(), now()), - ('account-2', 'github-2', 'github', 'user-2', now(), now()); - - insert into event_messages (channel_id, message_id, content, created_by) - values ('channel-1', 'message-1', 'event', 'user-1'); - ` : ''} - `) -} - const renderConfirmedFixturePurge = (source: string) => { const replacements: Record = { REPLACE_WITH_PIPE_SEPARATED_VERIFICATION_IDS_OR_EMPTY: 'EMPTY', @@ -672,54 +537,6 @@ test('splitting the auth schema leaves no reference from the domain into app_aut // the member. The migration only adds, so what matters is that it carries the // existing state across unchanged and that the new tables refuse a grant the // requirements say must be impossible. -const replayThroughSplit = async (client: PGlite) => { - await createCurrentSchema(client, false) - await client.exec(await readFile(membershipWorkflowMigrationPath, 'utf8')) - await client.exec(await readFile(splitAuthSchemaMigrationPath, 'utf8')) -} - -// Seeding has to follow the real path: the trigger cross-checks the role the -// caller claims against app_accounts, so an actor cannot simply assert it is an -// admin. The first admin is bootstrapped the way production was — apply, then -// promote the column directly — because approving requires an admin to exist. -const applyAsNewUser = async ( - client: PGlite, - { userId, memberId }: { userId: string; memberId: string }, -) => { - await client.exec(` - insert into app_auth."user" (id, name, email, email_verified, created_at, updated_at) - values ('${userId}', '${userId}', '${userId}@example.test', true, now(), now()); - insert into public.app_accounts (user_id, role) values ('${userId}', 'user'); - - select set_config('app.current_user_id', '${userId}', false); - select set_config('app.current_member_id', '${memberId}', false); - select set_config('app.current_user_role', 'user', false); - insert into public.members ( - member_id, registered_name, grade_id, emergency_contact, student_id, student_email - ) values ( - '${memberId}', '${userId}', 1, 'contact', upper('${userId}'), '${userId}@student.example' - ); - - update public.app_accounts set member_id = '${memberId}' where user_id = '${userId}'; - `) -} - -const promoteToAdmin = (client: PGlite, userId: string) => - client.exec(`update public.app_accounts set role = 'admin' where user_id = '${userId}'`) - -const approveMember = (client: PGlite, adminUserId: string, memberId: string) => - client.exec(` - select set_config('app.current_user_id', '${adminUserId}', false); - select set_config('app.current_member_id', '', false); - select set_config('app.current_user_role', 'admin', false); - update public.members - set member_status = 'active', - reviewed_at = now(), - reviewed_by_user_id = '${adminUserId}', - application_version = application_version + 1 - where member_id = '${memberId}'; - `) - test('the role tables carry the existing admin column across unchanged', async () => { const client = await PGlite.create() diff --git a/member/src/core/testing/migrations.ts b/member/src/core/testing/migrations.ts new file mode 100644 index 0000000..acfd4a2 --- /dev/null +++ b/member/src/core/testing/migrations.ts @@ -0,0 +1,216 @@ +// migration を実際に流して確かめるテストの、共通の準備処理。 +// 既存のスキーマを再現し、migration を順に流し、部員を本物と同じ手順で作る。 +import { readFile } from 'node:fs/promises' +import { dirname, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' +import type { PGlite } from '@electric-sql/pglite' + +export const migrationPath = resolve( + dirname(fileURLToPath(import.meta.url)), + '../../../../supabase/migrations/20260716005139_reconcile_better_auth_baseline.sql', +) +export const membershipWorkflowMigrationPath = resolve( + dirname(fileURLToPath(import.meta.url)), + '../../../../supabase/migrations/20260716123951_membership_workflow.sql', +) +export const splitAuthSchemaMigrationPath = resolve( + dirname(fileURLToPath(import.meta.url)), + '../../../../supabase/migrations/20260727000000_split_auth_schema.sql', +) +export const roleTablesMigrationPath = resolve( + dirname(fileURLToPath(import.meta.url)), + '../../../../supabase/migrations/20260904000000_add_role_tables.sql', +) +export const createPlatformRolesAndAuthSchema = async (client: PGlite) => { + await client.exec(` + create role anon; + create role authenticated; + create role service_role; + alter default privileges in schema public grant all on tables to service_role; + alter default privileges in schema public grant all on sequences to service_role; + alter default privileges in schema public grant execute on functions to service_role; + create schema auth; + create table auth.users (id uuid primary key default gen_random_uuid()); + `) +} + +export const createCurrentSchema = async (client: PGlite, withFixture = true) => { + await client.exec(` + create table grades ( + id integer generated always as identity primary key, + display_grade text not null, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now(), + year bigint not null default extract(year from current_date) + ); + + create table members ( + name text not null, + grade integer not null references grades(id) on delete set null, + emergency_contact text not null, + student_id text not null, + student_email text not null, + insurance boolean not null default false, + some_allergy boolean not null default false, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now(), + member_id uuid primary key default gen_random_uuid() + ); + + create table "user" ( + id text primary key, + name text not null, + email text not null unique, + email_verified boolean not null, + image text, + created_at timestamp not null, + updated_at timestamp not null, + discord_user_id text, + display_name text, + member_id uuid references members(member_id) on delete set null, + role text not null default 'user' + ); + + create table account ( + id text primary key, + account_id text not null, + provider_id text not null, + user_id text not null references "user"(id) on delete cascade, + access_token text, + refresh_token text, + id_token text, + access_token_expires_at timestamp, + refresh_token_expires_at timestamp, + scope text, + password text, + created_at timestamp not null, + updated_at timestamp not null + ); + + create table session ( + id text primary key, + expires_at timestamp not null, + token text not null unique, + created_at timestamp not null, + updated_at timestamp not null, + ip_address text, + user_agent text, + user_id text not null references "user"(id) on delete cascade + ); + + create table verification ( + id text primary key, + identifier text not null, + value text not null, + expires_at timestamp not null, + created_at timestamp, + updated_at timestamp + ); + + create table event_messages ( + id uuid primary key default gen_random_uuid(), + channel_id text not null, + message_id text not null unique, + content text not null, + created_by text not null, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now() + ); + + create function public.handle_new_user() + returns trigger + language plpgsql + security definer + as $$ begin return new; end $$; + + ${withFixture ? ` + insert into grades (id, display_grade) + overriding system value values (1, 'M1'); + + insert into members ( + member_id, name, grade, emergency_contact, student_id, student_email + ) values + ('00000000-0000-4000-8000-000000000001', 'One', 1, 'contact', 'A001', 'one@example.test'), + ('00000000-0000-4000-8000-000000000002', 'Two', 1, 'contact', 'A002', 'two@example.test'), + ('00000000-0000-4000-8000-000000000003', 'Three', 1, 'contact', 'A003', 'three@example.test'); + + insert into "user" ( + id, name, email, email_verified, created_at, updated_at, member_id, role + ) values + ('user-1', 'One', 'one@example.test', true, now(), now(), '00000000-0000-4000-8000-000000000001', 'admin'), + ('user-2', 'Two', 'two@example.test', true, now(), now(), '00000000-0000-4000-8000-000000000002', 'user'); + + insert into account ( + id, account_id, provider_id, user_id, created_at, updated_at + ) values + ('account-1', 'github-1', 'github', 'user-1', now(), now()), + ('account-2', 'github-2', 'github', 'user-2', now(), now()); + + insert into event_messages (channel_id, message_id, content, created_by) + values ('channel-1', 'message-1', 'event', 'user-1'); + ` : ''} + `) +} + +export const replayThroughSplit = async (client: PGlite) => { + await createCurrentSchema(client, false) + await client.exec(await readFile(membershipWorkflowMigrationPath, 'utf8')) + await client.exec(await readFile(splitAuthSchemaMigrationPath, 'utf8')) +} + +// Seeding has to follow the real path: the trigger cross-checks the role the +// caller claims against app_accounts, so an actor cannot simply assert it is an +// admin. The first admin is bootstrapped the way production was — apply, then +// promote the column directly — because approving requires an admin to exist. +export const applyAsNewUser = async ( + client: PGlite, + { userId, memberId }: { userId: string; memberId: string }, +) => { + await client.exec(` + insert into app_auth."user" (id, name, email, email_verified, created_at, updated_at) + values ('${userId}', '${userId}', '${userId}@example.test', true, now(), now()); + insert into public.app_accounts (user_id, role) values ('${userId}', 'user'); + + select set_config('app.current_user_id', '${userId}', false); + select set_config('app.current_member_id', '${memberId}', false); + select set_config('app.current_user_role', 'user', false); + insert into public.members ( + member_id, registered_name, grade_id, emergency_contact, student_id, student_email + ) values ( + '${memberId}', '${userId}', 1, 'contact', upper('${userId}'), '${userId}@student.example' + ); + + update public.app_accounts set member_id = '${memberId}' where user_id = '${userId}'; + `) +} + +export const promoteToAdmin = (client: PGlite, userId: string) => + client.exec(`update public.app_accounts set role = 'admin' where user_id = '${userId}'`) + +export const approveMember = (client: PGlite, adminUserId: string, memberId: string) => + client.exec(` + select set_config('app.current_user_id', '${adminUserId}', false); + select set_config('app.current_member_id', '', false); + select set_config('app.current_user_role', 'admin', false); + update public.members + set member_status = 'active', + reviewed_at = now(), + reviewed_by_user_id = '${adminUserId}', + application_version = application_version + 1 + where member_id = '${memberId}'; + `) + + +// これまでのすべての migration を、ロール関連まで含めて流す。 +// 呼ぶ前に、applyAsNewUser などで部員を作っておく(U-1 の migration が、そのときの管理者からロールを作るため)。 +export const replayThroughLatest = async (client: PGlite) => { + const migrationsDirectory = dirname(roleTablesMigrationPath) + for (const name of [ + '20260904000000_add_role_tables.sql', + '20261105072955_enforce_permissions.sql', + '20261109180000_role_history_and_last_manager.sql', + '20261110090000_remove_roles_on_withdrawal.sql', + ]) { + await client.exec(await readFile(resolve(migrationsDirectory, name), 'utf8')) + } +}