import assert from "node:assert/strict"; import test from "node:test"; import { closeLocalPostgresDataPools, createLocalPostgresDataClient, localPostgresPoolForTests, } from "../src/lib/db/local-postgres-client-core.ts"; import { startPostgresFixture } from "./helpers/postgres-fixture.ts"; const probeSql = ` create or replace function public.session_probe() returns table(db_user text, claim_sub text) language sql stable as $$ select current_user::text, current_setting('request.jwt.claim.sub', true); $$; grant usage on schema public to authenticated, service_role; grant execute on function public.session_probe() to authenticated, service_role; `; test("merged session setup applies the role only inside the transaction", async () => { const previous = { cache: process.env.JYOTISHA_PG_METADATA_CACHE, merged: process.env.JYOTISHA_PG_MERGED_SESSION_SETUP, }; process.env.JYOTISHA_PG_METADATA_CACHE = "on"; process.env.JYOTISHA_PG_MERGED_SESSION_SETUP = "on"; const fixture = startPostgresFixture(); const identity = { id: "018f4e6d-7a11-7000-8000-0000000000aa", email: "person@example.com", }; try { fixture.psqlScriptAs("postgres", "postgres-test-password", probeSql); const url = fixture.connectionUrl("app_runtime", "app-runtime-test-password"); const client = createLocalPostgresDataClient(url, identity, "authenticated"); const probe = await client.rpc("session_probe"); assert.equal(probe.error, null, probe.error?.message); const row = Array.isArray(probe.data) ? probe.data[0] as { db_user?: string; claim_sub?: string } : null; assert.equal(row?.db_user, "authenticated"); assert.equal(row?.claim_sub, identity.id); const pool = localPostgresPoolForTests(url); const borrowed = await pool.connect(); try { const after = await borrowed.query<{ db_user: string; claim_sub: string | null }>( "select current_user as db_user, current_setting('request.jwt.claim.sub', true) as claim_sub", ); assert.equal(after.rows[0]?.db_user, "app_runtime"); assert.equal(after.rows[0]?.claim_sub ?? "", ""); } finally { borrowed.release(); } } finally { await closeLocalPostgresDataPools(); fixture.stop(); if (previous.cache === undefined) delete process.env.JYOTISHA_PG_METADATA_CACHE; else process.env.JYOTISHA_PG_METADATA_CACHE = previous.cache; if (previous.merged === undefined) delete process.env.JYOTISHA_PG_MERGED_SESSION_SETUP; else process.env.JYOTISHA_PG_MERGED_SESSION_SETUP = previous.merged; } });