From Bicep to a running deployment
The infrastructure model end to end — network, compute, secrets — then the runbook that turns it into a live environment and the migration job that seeds the schema.
backend/src/scripts/runMigrations.ts244 lines · getDatabaseUrl L54–91
Outline 7 symbols
- AAD_SCOPE const
- reloadPostgrestSchemaCache function
- ensureSslMode function
- getDatabaseUrl function
- ensureAuthenticatorRole function
- provisionAuthSecrets function
- main function
1import { DefaultAzureCredential } from "@azure/identity";
2import { SecretClient } from "@azure/keyvault-secrets";
3import { randomBytes } from "node:crypto";
4import { Client } from "pg";
5import { createServerSupabase } from "../lib/supabase";
6import { initStorage } from "../lib/storage";
7import { syncWorkflowCatalog } from "../lib/workflowCatalogSync";
8import { resolveProviderSecret } from "../lib/envSecrets";
9import { assertDirectMigrationConnection, parseMigrationCommand, runMigrationCommand } from "./migrationLedger";
10
11const AAD_SCOPE = "https://ossrdbms-aad.database.windows.net/.default";
12
13// Tell PostgREST to rebuild its schema cache from pg_catalog.
14//
15// PostgREST builds its REST surface (which tables/columns are exposed,
16// which return types) at startup and on receipt of a `pgrst, 'reload
17// schema'` NOTIFY. Without this step the first request to a freshly-
18// added column will 500 with `Could not find the 'X' column of 'Y' in
19// the schema cache`. We do this from the migration job rather than by
20// restarting PostgREST because (a) it doesn't drop in-flight requests
21// and (b) the migration job already has DB credentials handy.
22//
23// The NOTIFY is best-effort: if PostgREST isn't listening yet (or isn't
24// running) the message is dropped, but the migration itself has already
25// committed. We log the failure and move on rather than retrying — a
26// transient failure here is recoverable by restarting PostgREST.
27async function reloadPostgrestSchemaCache(databaseUrl: string): Promise<void> {
28 const client = new Client({ connectionString: databaseUrl });
29 try {
30 await client.connect();
31 await client.query("NOTIFY pgrst, 'reload schema'");
32 console.log("[migrate] PostgREST schema cache reload notified");
33 } catch (err) {
34 console.error(
35 "[migrate] failed to NOTIFY PostgREST — schema cache may be stale until PostgREST restarts",
36 err,
37 );
38 } finally {
39 await client.end().catch(() => {});
40 }
41}
42
43// Azure Postgres Flexible Server rejects non-TLS connections from outside
44// the server's own subnet with `no pg_hba.conf entry for host ..., no
45// encryption`. The entra-mode path below builds its own URL with
46// `?sslmode=require`; the env-var path inherits whatever the operator (or
47// the marketplace deploy seed) set in KV. We've seen `pgrst-db-uri` seeded
48// without sslmode in real installs (gap #22), so default-add it here.
49function ensureSslMode(url: string): string {
50 if (/[?&]sslmode=/i.test(url)) return url;
51 return url + (url.includes("?") ? "&" : "?") + "sslmode=require";
52}
53
54async function getDatabaseUrl(): Promise<string> {
55 // Migrate-job DB connection strategy is independent of AUTH_PROVIDER
56 // (which is the app sign-in mode, consumed by routes/auth.ts).
57 // Conflating them blocked marketplace installs that legitimately want
58 // Entra sign-in for users + password auth from the migrate job — see
59 // docs/issues/azure-migration/037-migrate-job-auth-decoupling.md.
60 //
61 // Preference order:
62 // 1. DATABASE_URL — works for marketplace (KV pgrst-db-uri),
63 // supabase, local, and any entra-with-password setup.
64 // 2. MI-token path — for Entra-Postgres installs where the flex
65 // server has activeDirectoryAuth=Enabled and the UAMI is
66 // registered as a Postgres role.
67 const databaseUrl = process.env.DATABASE_URL;
68 if (databaseUrl) {
69 return ensureSslMode(databaseUrl);
70 }
71
72 const pgHost = process.env.PG_HOST;
73 const pgMiUsername = process.env.PG_MI_USERNAME;
74 if (pgHost && pgMiUsername) {
75 const pgDatabase = process.env.PG_DATABASE ?? "postgres";
76 const pgPort = process.env.PG_PORT ?? "5432";
77
78 const credential = new DefaultAzureCredential();
79 const token = await credential.getToken(AAD_SCOPE);
80
81 if (!token?.token) {
82 throw new Error("Failed to acquire Managed Identity token for PostgreSQL");
83 }
84
85 return `postgresql://${encodeURIComponent(pgMiUsername)}:${encodeURIComponent(token.token)}@${pgHost}:${pgPort}/${pgDatabase}?sslmode=require`;
86 }
87
88 throw new Error(
89 "Migrate job needs either DATABASE_URL, or PG_HOST + PG_MI_USERNAME for MI-token auth",
90 );
91}
92
93// Creates / refreshes the `authenticator` Postgres role that PostgREST
94// connects as in the marketplace flavour. The role has only LOGIN +
95// NOINHERIT plus membership in web_anon / authenticated / service_role
96// — minimum privileges to SET ROLE at PostgREST's connection boundary,
97// nothing else. Replaces the previous pattern where PostgREST connected
98// as `mikeadmin` (full superuser).
99//
100// Runs after node-pg-migrate (which created the role tier in
101// 0005_postgres_roles.sql) and is fully idempotent: creates the role if
102// missing, syncs the password every run, re-grants memberships.
103//
104// Password comes from PGRST_AUTHENTICATOR_PASSWORD env var, sourced
105// from a Bicep-generated KV secret (newGuid() per deploy). DDL can't
106// be parameterized so we interpolate into the SQL — Bicep's newGuid()
107// format is alphanumeric+hyphen only, which we validate defensively
108// before interpolation. Throws on a non-conforming value rather than
109// risking SQL injection.
110//
111// Skipped (no-op) when the env var is unset — keeps legacy installs
112// working until they pick up the Bicep change that sets the var. See
113// gap #24 in docs/issues/azure-migration/036-marketplace-install-gaps.md.
114async function ensureAuthenticatorRole(databaseUrl: string): Promise<void> {
115 const password = process.env.PGRST_AUTHENTICATOR_PASSWORD;
116 if (!password) {
117 console.log(
118 "[migrate] PGRST_AUTHENTICATOR_PASSWORD not set — skipping authenticator role setup (legacy install / OSS deploy)",
119 );
120 return;
121 }
122 // newGuid() output is alphanumeric + hyphen. Anything else would risk
123 // DDL injection because CREATE/ALTER ROLE don't support parameterized
124 // queries. Fail loudly rather than silently quote-escape something we
125 // didn't expect.
126 if (!/^[A-Za-z0-9-]+$/.test(password)) {
127 throw new Error(
128 "PGRST_AUTHENTICATOR_PASSWORD must be alphanumeric+hyphen (newGuid format)",
129 );
130 }
131
132 const client = new Client({ connectionString: databaseUrl, ssl: { rejectUnauthorized: false }, connectionTimeoutMillis: 15_000 });
133 try {
134 await client.connect();
135 const existsRow = await client.query<{ exists: boolean }>(
136 "SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'authenticator') AS exists",
137 );
138 const exists = Boolean(existsRow.rows[0]?.exists);
139 if (exists) {
140 await client.query(
141 `ALTER ROLE authenticator WITH LOGIN NOINHERIT PASSWORD '${password}'`,
142 );
143 console.log("[migrate] authenticator role: password refreshed");
144 } else {
145 await client.query(
146 `CREATE ROLE authenticator LOGIN NOINHERIT PASSWORD '${password}'`,
147 );
148 console.log("[migrate] authenticator role: created");
149 }
150 // Membership in the role tier (created by 0005_postgres_roles.sql).
151 // GRANT is idempotent — no-op if already a member.
152 await client.query("GRANT web_anon TO authenticator");
153 await client.query("GRANT authenticated TO authenticator");
154 await client.query("GRANT service_role TO authenticator");
155 console.log("[migrate] authenticator role: memberships ensured");
156 } finally {
157 await client.end().catch(() => {});
158 }
159}
160
161/** One direct PostgreSQL session serializes all cooperating migration jobs. */
162async function provisionAuthSecrets(databaseUrl: string): Promise<void> {
163 const mode = process.env.AUTH_SECRET_PROVISIONING_MODE;
164 if (mode === "local") return;
165 if (mode !== "keyvault" || !process.env.KEY_VAULT_NAME || !process.env.AZURE_CLIENT_ID) {
166 throw new Error("Auth secret provisioning requires explicit Key Vault mode, vault and managed identity");
167 }
168 const vault = new SecretClient(
169 `https://${process.env.KEY_VAULT_NAME}.vault.azure.net/`,
170 new DefaultAzureCredential({ managedIdentityClientId: process.env.AZURE_CLIENT_ID }),
171 );
172 const client = new Client({ connectionString: databaseUrl, ssl: { rejectUnauthorized: false }, connectionTimeoutMillis: 15_000 });
173 await client.connect();
174 const lockKey = "mike-auth-secret-provision-v1";
175 try {
176 await client.query("select pg_advisory_lock(hashtextextended($1, 0))", [lockKey]);
177 for (const name of [
178 "auth-state-secret", "auth-session-encryption-secret", "auth-handoff-encryption-secret",
179 ]) {
180 let existing: string | undefined;
181 try { existing = (await vault.getSecret(name, { abortSignal: AbortSignal.timeout(15_000) })).value; }
182 catch (error) {
183 if ((error as { statusCode?: number }).statusCode !== 404) throw error;
184 }
185 if (!existing || existing === "__unset__") {
186 const created = randomBytes(32).toString("base64url");
187 await vault.setSecret(name, created, { abortSignal: AbortSignal.timeout(15_000) });
188 console.log(`[migrate] auth secret created: ${name}`);
189 } else {
190 console.log(`[migrate] auth secret retained: ${name}`);
191 }
192 const confirmed = (await vault.getSecret(name, { abortSignal: AbortSignal.timeout(15_000) })).value;
193 if (!confirmed || confirmed === "__unset__") throw new Error(`Auth secret is unusable: ${name}`);
194 if (name !== "auth-state-secret" && Buffer.from(confirmed, "base64url").length !== 32) {
195 throw new Error(`Auth encryption secret has invalid length: ${name}`);
196 }
197 }
198 } finally {
199 await client.query("select pg_advisory_unlock(hashtextextended($1, 0))", [lockKey]).catch(() => {});
200 await client.end().catch(() => {});
201 }
202}
203
204async function main() {
205 const command = parseMigrationCommand(process.argv.slice(2));
206 const databaseUrl = await getDatabaseUrl();
207 assertDirectMigrationConnection(databaseUrl);
208 const client = new Client({ connectionString: databaseUrl, application_name: "mike-migrate" });
209 try {
210 await client.connect();
211 process.exitCode = await runMigrationCommand(client, command);
212 } finally {
213 await client.end().catch(() => {});
214 }
215 // Status/recovery commands inspect or record schema only. Deployment and
216 // local upgrade entrypoints keep their existing provisioning sequence.
217 if (command.kind !== "up" || process.exitCode) return;
218
219 await ensureAuthenticatorRole(databaseUrl);
220 await provisionAuthSecrets(databaseUrl);
221 await reloadPostgrestSchemaCache(databaseUrl);
222 // The same deployment job publishes the catalogue after its tables/RPCs
223 // exist and before the backend revision is activated. Reference bytes are
224 // uploaded first; a failed sync leaves the previous DB catalogue active and
225 // fails the job, so an empty or partial catalogue cannot be deployed.
226 // Catalogue assets upload through the storage facade, which stays disabled
227 // until the configured adapter is resolved (Key Vault first).
228 await initStorage();
229 const githubToken = await resolveProviderSecret("mike-workflows-github-token");
230 const result = await syncWorkflowCatalog(
231 createServerSupabase(),
232 githubToken ? { githubToken } : {},
233 );
234 console.log(
235 `[migrate] catalogue active: ${result.workflows} workflows, ` +
236 `${result.assets} assets, source ${result.sourceCommit}`,
237 );
238}
239
240main().catch((error) => {
241 console.error("Migration job failed", error);
242 process.exit(1);
243});
244