feat: restrict customer DB user permissions on provision
Some checks failed
Build & Release / build (push) Failing after 1m3s

This commit is contained in:
Ryan Moon
2026-04-03 06:25:51 -05:00
parent 32399a417a
commit 6e68cb83c0
5 changed files with 45 additions and 0 deletions

37
src/services/db.ts Normal file
View File

@@ -0,0 +1,37 @@
import postgres from "postgres";
import { config } from "../lib/config";
// Runs setup SQL as doadmin against a specific database
export async function setupCustomerDatabase(dbName: string, username: string) {
const sql = postgres(config.doadminDbUrl.replace(/\/\w+(\?|$)/, `/${dbName}$1`), { max: 1 });
try {
// Revoke all public access, then grant only to this user
await sql.unsafe(`
REVOKE ALL ON DATABASE "${dbName}" FROM PUBLIC;
GRANT CONNECT ON DATABASE "${dbName}" TO "${username}";
GRANT ALL PRIVILEGES ON DATABASE "${dbName}" TO "${username}";
ALTER DATABASE "${dbName}" OWNER TO "${username}";
`);
// Set default privileges so any tables the app creates are accessible to itself
await sql.unsafe(`
ALTER DEFAULT PRIVILEGES FOR ROLE "${username}" IN SCHEMA public
GRANT ALL ON TABLES TO "${username}";
ALTER DEFAULT PRIVILEGES FOR ROLE "${username}" IN SCHEMA public
GRANT ALL ON SEQUENCES TO "${username}";
`);
} finally {
await sql.end();
}
}
export async function teardownCustomerDatabase(dbName: string, username: string) {
// Reassign ownership back to doadmin before dropping
const sql = postgres(config.doadminDbUrl.replace(/\/\w+(\?|$)/, `/${dbName}$1`), { max: 1 });
try {
await sql.unsafe(`REASSIGN OWNED BY "${username}" TO doadmin;`);
} finally {
await sql.end();
}
}