forked from mtusi2026/mtusi2026lab7
85 lines
2.4 KiB
TypeScript
85 lines
2.4 KiB
TypeScript
import { readFile } from "node:fs/promises";
|
|
import { resolve } from "node:path";
|
|
import { decrypt, operatorPassword } from "./operator-crypto";
|
|
import { local, compose, safeFailure, requireThat } from "./runtime";
|
|
export async function provisionDB(password: string, grantSchema = false) {
|
|
const secrets = decrypt<any>(
|
|
await readFile(resolve(local, "operator", "services.enc"), "utf8"),
|
|
password,
|
|
);
|
|
for (const role of ["api", "worker"]) {
|
|
const secret = secrets[role === "api" ? "dbApi" : "dbWorker"];
|
|
requireThat(/^[a-f0-9]{64}$/.test(secret), "INVALID_DATABASE_PASSWORD");
|
|
// Roles are idempotent; role and password values have fixed grammar before SQL interpolation.
|
|
await compose(
|
|
[
|
|
"exec",
|
|
"-T",
|
|
"postgres",
|
|
"psql",
|
|
"-X",
|
|
"-v",
|
|
"ON_ERROR_STOP=1",
|
|
"-U",
|
|
"operator",
|
|
"-d",
|
|
"messenger",
|
|
],
|
|
{
|
|
input: `DO $$ BEGIN IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname='${role}') THEN CREATE ROLE ${role} LOGIN; END IF; END $$;\nALTER ROLE ${role} WITH LOGIN PASSWORD '${secret}' NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION;\nGRANT CONNECT ON DATABASE messenger TO ${role};\nGRANT USAGE ON SCHEMA public TO ${role};\n`,
|
|
},
|
|
);
|
|
}
|
|
await compose(
|
|
[
|
|
"exec",
|
|
"-T",
|
|
"postgres",
|
|
"psql",
|
|
"-X",
|
|
"-v",
|
|
"ON_ERROR_STOP=1",
|
|
"-U",
|
|
"operator",
|
|
"-d",
|
|
"messenger",
|
|
],
|
|
{
|
|
input:
|
|
"REVOKE CREATE ON SCHEMA public FROM PUBLIC;\nREVOKE ALL ON DATABASE messenger FROM PUBLIC;\nGRANT CONNECT ON DATABASE messenger TO api,worker;\n",
|
|
},
|
|
);
|
|
if (grantSchema)
|
|
await compose(
|
|
[
|
|
"exec",
|
|
"-T",
|
|
"postgres",
|
|
"psql",
|
|
"-X",
|
|
"-v",
|
|
"ON_ERROR_STOP=1",
|
|
"-U",
|
|
"operator",
|
|
"-d",
|
|
"messenger",
|
|
],
|
|
{
|
|
input:
|
|
"GRANT SELECT,INSERT,UPDATE,DELETE ON users,chats,chat_members,messages,sessions,idempotency,attachments,message_attachments,attachment_jobs TO api;\nGRANT SELECT,UPDATE ON login_limits TO api;\nGRANT SELECT,UPDATE ON attachments,attachment_jobs TO worker;\n",
|
|
},
|
|
);
|
|
console.log(
|
|
grantSchema
|
|
? "PASS_DB_SCOPED_SCHEMA_GRANTS"
|
|
: "PASS_DB_SEPARATE_LOGIN_ROLES",
|
|
);
|
|
}
|
|
if (import.meta.main) {
|
|
try {
|
|
await provisionDB(await operatorPassword(), Bun.argv.includes("--schema"));
|
|
} catch (e) {
|
|
safeFailure(e);
|
|
}
|
|
}
|