postgresai 0.12.0-beta.7 → 0.14.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,33 @@
1
+ -- Required permissions for postgres_ai monitoring user (template-filled by cli/lib/init.ts)
2
+
3
+ -- Allow connect
4
+ grant connect on database {{DB_IDENT}} to {{ROLE_IDENT}};
5
+
6
+ -- Standard monitoring privileges
7
+ grant pg_monitor to {{ROLE_IDENT}};
8
+ grant select on pg_catalog.pg_index to {{ROLE_IDENT}};
9
+
10
+ -- Optional, for bloat analysis: expose pg_statistic via a view
11
+ create or replace view public.pg_statistic as
12
+ select
13
+ n.nspname as schemaname,
14
+ c.relname as tablename,
15
+ a.attname,
16
+ s.stanullfrac as null_frac,
17
+ s.stawidth as avg_width,
18
+ false as inherited
19
+ from pg_catalog.pg_statistic s
20
+ join pg_catalog.pg_class c on c.oid = s.starelid
21
+ join pg_catalog.pg_namespace n on n.oid = c.relnamespace
22
+ join pg_catalog.pg_attribute a on a.attrelid = s.starelid and a.attnum = s.staattnum
23
+ where a.attnum > 0 and not a.attisdropped;
24
+
25
+ grant select on public.pg_statistic to {{ROLE_IDENT}};
26
+
27
+ -- Hardened clusters sometimes revoke PUBLIC on schema public
28
+ grant usage on schema public to {{ROLE_IDENT}};
29
+
30
+ -- Keep search_path predictable
31
+ alter user {{ROLE_IDENT}} set search_path = "$user", public, pg_catalog;
32
+
33
+
@@ -0,0 +1,6 @@
1
+ -- Optional permissions for RDS Postgres / Aurora (best effort)
2
+
3
+ create extension if not exists rds_tools;
4
+ grant execute on function rds_tools.pg_ls_multixactdir() to {{ROLE_IDENT}};
5
+
6
+
@@ -0,0 +1,8 @@
1
+ -- Optional permissions for self-managed Postgres (best effort)
2
+
3
+ grant execute on function pg_catalog.pg_stat_file(text) to {{ROLE_IDENT}};
4
+ grant execute on function pg_catalog.pg_stat_file(text, boolean) to {{ROLE_IDENT}};
5
+ grant execute on function pg_catalog.pg_ls_dir(text) to {{ROLE_IDENT}};
6
+ grant execute on function pg_catalog.pg_ls_dir(text, boolean, boolean) to {{ROLE_IDENT}};
7
+
8
+
@@ -0,0 +1,382 @@
1
+ const test = require("node:test");
2
+ const assert = require("node:assert/strict");
3
+ const fs = require("node:fs");
4
+ const os = require("node:os");
5
+ const path = require("node:path");
6
+ const net = require("node:net");
7
+ const { spawn, spawnSync } = require("node:child_process");
8
+
9
+ function sqlLiteral(value) {
10
+ return `'${String(value).replace(/'/g, "''")}'`;
11
+ }
12
+
13
+ function findOnPath(cmd) {
14
+ const which = spawnSync("sh", ["-lc", `command -v ${cmd}`], { encoding: "utf8" });
15
+ if (which.status === 0) return String(which.stdout || "").trim();
16
+ return null;
17
+ }
18
+
19
+ function findPgBin(cmd) {
20
+ const p = findOnPath(cmd);
21
+ if (p) return p;
22
+
23
+ // Debian/Ubuntu (GitLab CI node:*-bullseye images): binaries usually live here.
24
+ // We avoid filesystem globbing in JS and just ask the shell.
25
+ const probe = spawnSync(
26
+ "sh",
27
+ [
28
+ "-lc",
29
+ `ls -1 /usr/lib/postgresql/*/bin/${cmd} 2>/dev/null | head -n 1 || true`,
30
+ ],
31
+ { encoding: "utf8" }
32
+ );
33
+ const out = String(probe.stdout || "").trim();
34
+ if (out) return out;
35
+
36
+ return null;
37
+ }
38
+
39
+ function havePostgresBinaries() {
40
+ return !!(findPgBin("initdb") && findPgBin("postgres"));
41
+ }
42
+
43
+ async function getFreePort() {
44
+ return await new Promise((resolve, reject) => {
45
+ const srv = net.createServer();
46
+ srv.listen(0, "127.0.0.1", () => {
47
+ const addr = srv.address();
48
+ srv.close((err) => {
49
+ if (err) return reject(err);
50
+ resolve(addr.port);
51
+ });
52
+ });
53
+ srv.on("error", reject);
54
+ });
55
+ }
56
+
57
+ async function waitFor(fn, { timeoutMs = 10000, intervalMs = 100 } = {}) {
58
+ const start = Date.now();
59
+ // eslint-disable-next-line no-constant-condition
60
+ while (true) {
61
+ try {
62
+ return await fn();
63
+ } catch (e) {
64
+ if (Date.now() - start > timeoutMs) throw e;
65
+ await new Promise((r) => setTimeout(r, intervalMs));
66
+ }
67
+ }
68
+ }
69
+
70
+ async function withTempPostgres(t) {
71
+ const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), "postgresai-init-"));
72
+ const dataDir = path.join(tmpRoot, "data");
73
+ const socketDir = path.join(tmpRoot, "sock");
74
+ fs.mkdirSync(socketDir, { recursive: true });
75
+
76
+ const initdb = findPgBin("initdb");
77
+ const postgresBin = findPgBin("postgres");
78
+ assert.ok(initdb && postgresBin, "PostgreSQL binaries not found (need initdb and postgres)");
79
+
80
+ const init = spawnSync(initdb, ["-D", dataDir, "-U", "postgres", "-A", "trust"], {
81
+ encoding: "utf8",
82
+ });
83
+ assert.equal(init.status, 0, init.stderr || init.stdout);
84
+
85
+ // Configure: local socket trust, TCP scram.
86
+ const hbaPath = path.join(dataDir, "pg_hba.conf");
87
+ fs.appendFileSync(
88
+ hbaPath,
89
+ "\n# Added by postgresai init integration tests\nlocal all all trust\nhost all all 127.0.0.1/32 scram-sha-256\nhost all all ::1/128 scram-sha-256\n",
90
+ "utf8"
91
+ );
92
+
93
+ const port = await getFreePort();
94
+
95
+ let postgresProc;
96
+ try {
97
+ postgresProc = spawn(
98
+ postgresBin,
99
+ ["-D", dataDir, "-k", socketDir, "-h", "127.0.0.1", "-p", String(port)],
100
+ {
101
+ stdio: ["ignore", "pipe", "pipe"],
102
+ }
103
+ );
104
+
105
+ // Register cleanup immediately so failures below don't leave a running postgres and hang CI.
106
+ t.after(async () => {
107
+ postgresProc.kill("SIGTERM");
108
+ try {
109
+ await waitFor(
110
+ async () => {
111
+ if (postgresProc.exitCode === null) throw new Error("still running");
112
+ },
113
+ { timeoutMs: 5000, intervalMs: 100 }
114
+ );
115
+ } catch {
116
+ postgresProc.kill("SIGKILL");
117
+ }
118
+ fs.rmSync(tmpRoot, { recursive: true, force: true });
119
+ });
120
+ } catch (e) {
121
+ // If anything goes wrong before cleanup is registered, ensure we don't leak a running postgres.
122
+ try {
123
+ if (postgresProc) postgresProc.kill("SIGKILL");
124
+ } catch {
125
+ // ignore
126
+ }
127
+ fs.rmSync(tmpRoot, { recursive: true, force: true });
128
+ throw e;
129
+ }
130
+
131
+ const { Client } = require("pg");
132
+
133
+ const connectLocal = async (database = "postgres") => {
134
+ // IMPORTANT: must match the port Postgres is started with; otherwise pg defaults to 5432 and the socket path won't exist.
135
+ const c = new Client({ host: socketDir, port, user: "postgres", database });
136
+ await c.connect();
137
+ return c;
138
+ };
139
+
140
+ await waitFor(async () => {
141
+ const c = await connectLocal();
142
+ await c.end();
143
+ });
144
+
145
+ const postgresPassword = "postgrespw";
146
+ {
147
+ const c = await connectLocal();
148
+ await c.query(`alter user postgres password ${sqlLiteral(postgresPassword)};`);
149
+ await c.query("create database testdb");
150
+ await c.end();
151
+ }
152
+
153
+ const adminUri = `postgresql://postgres:${postgresPassword}@127.0.0.1:${port}/testdb`;
154
+ return { port, socketDir, adminUri, postgresPassword };
155
+ }
156
+
157
+ async function runCliInit(args, env = {}) {
158
+ const node = process.execPath;
159
+ const cliPath = path.resolve(__dirname, "..", "dist", "bin", "postgres-ai.js");
160
+ const res = spawnSync(node, [cliPath, "init", ...args], {
161
+ encoding: "utf8",
162
+ env: { ...process.env, ...env },
163
+ });
164
+ return res;
165
+ }
166
+
167
+ test(
168
+ "integration: init supports URI / conninfo / psql-like connection styles",
169
+ { skip: !havePostgresBinaries() },
170
+ async (t) => {
171
+ const pg = await withTempPostgres(t);
172
+
173
+ // 1) positional URI
174
+ {
175
+ const r = await runCliInit([pg.adminUri, "--password", "monpw", "--skip-optional-permissions"]);
176
+ assert.equal(r.status, 0, r.stderr || r.stdout);
177
+ }
178
+
179
+ // 2) conninfo
180
+ {
181
+ const conninfo = `dbname=testdb host=127.0.0.1 port=${pg.port} user=postgres password=${pg.postgresPassword}`;
182
+ const r = await runCliInit([conninfo, "--password", "monpw2", "--skip-optional-permissions"]);
183
+ assert.equal(r.status, 0, r.stderr || r.stdout);
184
+ }
185
+
186
+ // 3) psql-like options (+ PGPASSWORD)
187
+ {
188
+ const r = await runCliInit(
189
+ [
190
+ "-h",
191
+ "127.0.0.1",
192
+ "-p",
193
+ String(pg.port),
194
+ "-U",
195
+ "postgres",
196
+ "-d",
197
+ "testdb",
198
+ "--password",
199
+ "monpw3",
200
+ "--skip-optional-permissions",
201
+ ],
202
+ { PGPASSWORD: pg.postgresPassword }
203
+ );
204
+ assert.equal(r.status, 0, r.stderr || r.stdout);
205
+ }
206
+ }
207
+ );
208
+
209
+ test(
210
+ "integration: init requires explicit monitoring password in non-interactive mode (unless --print-password)",
211
+ { skip: !havePostgresBinaries() },
212
+ async (t) => {
213
+ const pg = await withTempPostgres(t);
214
+
215
+ // spawnSync captures stdout/stderr (non-TTY). We should not print a generated password unless explicitly requested.
216
+ {
217
+ const r = await runCliInit([pg.adminUri, "--skip-optional-permissions"]);
218
+ assert.notEqual(r.status, 0);
219
+ assert.match(r.stderr, /not printed in non-interactive mode/i);
220
+ assert.match(r.stderr, /--print-password/);
221
+ }
222
+
223
+ // With explicit opt-in, it should succeed (and will print the generated password).
224
+ {
225
+ const r = await runCliInit([pg.adminUri, "--print-password", "--skip-optional-permissions"]);
226
+ assert.equal(r.status, 0, r.stderr || r.stdout);
227
+ assert.match(r.stderr, /Generated monitoring password for postgres_ai_mon/i);
228
+ assert.match(r.stderr, /PGAI_MON_PASSWORD=/);
229
+ }
230
+ }
231
+ );
232
+
233
+ test(
234
+ "integration: init fixes slightly-off permissions idempotently",
235
+ { skip: !havePostgresBinaries() },
236
+ async (t) => {
237
+ const pg = await withTempPostgres(t);
238
+ const { Client } = require("pg");
239
+
240
+ // Create monitoring role with wrong password, no grants.
241
+ {
242
+ const c = new Client({ connectionString: pg.adminUri });
243
+ await c.connect();
244
+ await c.query(
245
+ "do $$ begin if not exists (select 1 from pg_roles where rolname='postgres_ai_mon') then create role postgres_ai_mon login password 'wrong'; end if; end $$;"
246
+ );
247
+ await c.end();
248
+ }
249
+
250
+ // Run init (should grant everything).
251
+ {
252
+ const r = await runCliInit([pg.adminUri, "--password", "correctpw", "--skip-optional-permissions"]);
253
+ assert.equal(r.status, 0, r.stderr || r.stdout);
254
+ }
255
+
256
+ // Verify privileges.
257
+ {
258
+ const c = new Client({ connectionString: pg.adminUri });
259
+ await c.connect();
260
+ const dbOk = await c.query(
261
+ "select has_database_privilege('postgres_ai_mon', current_database(), 'CONNECT') as ok"
262
+ );
263
+ assert.equal(dbOk.rows[0].ok, true);
264
+ const roleOk = await c.query("select pg_has_role('postgres_ai_mon', 'pg_monitor', 'member') as ok");
265
+ assert.equal(roleOk.rows[0].ok, true);
266
+ const idxOk = await c.query(
267
+ "select has_table_privilege('postgres_ai_mon', 'pg_catalog.pg_index', 'SELECT') as ok"
268
+ );
269
+ assert.equal(idxOk.rows[0].ok, true);
270
+ const viewOk = await c.query(
271
+ "select has_table_privilege('postgres_ai_mon', 'public.pg_statistic', 'SELECT') as ok"
272
+ );
273
+ assert.equal(viewOk.rows[0].ok, true);
274
+ const sp = await c.query("select rolconfig from pg_roles where rolname='postgres_ai_mon'");
275
+ assert.ok(Array.isArray(sp.rows[0].rolconfig));
276
+ assert.ok(sp.rows[0].rolconfig.some((v) => String(v).includes("search_path=")));
277
+ await c.end();
278
+ }
279
+
280
+ // Run init again (idempotent).
281
+ {
282
+ const r = await runCliInit([pg.adminUri, "--password", "correctpw", "--skip-optional-permissions"]);
283
+ assert.equal(r.status, 0, r.stderr || r.stdout);
284
+ }
285
+ }
286
+ );
287
+
288
+ test("integration: init reports nicely when lacking permissions", { skip: !havePostgresBinaries() }, async (t) => {
289
+ const pg = await withTempPostgres(t);
290
+ const { Client } = require("pg");
291
+
292
+ // Create limited user that can connect but cannot create roles / grant.
293
+ const limitedPw = "limitedpw";
294
+ {
295
+ const c = new Client({ connectionString: pg.adminUri });
296
+ await c.connect();
297
+ await c.query(`do $$ begin
298
+ if not exists (select 1 from pg_roles where rolname='limited') then
299
+ begin
300
+ create role limited login password ${sqlLiteral(limitedPw)};
301
+ exception when duplicate_object then
302
+ null;
303
+ end;
304
+ end if;
305
+ end $$;`);
306
+ await c.query("grant connect on database testdb to limited");
307
+ await c.end();
308
+ }
309
+
310
+ const limitedUri = `postgresql://limited:${limitedPw}@127.0.0.1:${pg.port}/testdb`;
311
+ const r = await runCliInit([limitedUri, "--password", "monpw", "--skip-optional-permissions"]);
312
+ assert.notEqual(r.status, 0);
313
+ assert.match(r.stderr, /Error: init:/);
314
+ // Should include step context and hint.
315
+ assert.match(r.stderr, /Failed at step "/);
316
+ assert.match(r.stderr, /Fix: connect as a superuser/i);
317
+ });
318
+
319
+ test("integration: init --verify returns 0 when ok and non-zero when missing", { skip: !havePostgresBinaries() }, async (t) => {
320
+ const pg = await withTempPostgres(t);
321
+ const { Client } = require("pg");
322
+
323
+ // Prepare: run init
324
+ {
325
+ const r = await runCliInit([pg.adminUri, "--password", "monpw", "--skip-optional-permissions"]);
326
+ assert.equal(r.status, 0, r.stderr || r.stdout);
327
+ }
328
+
329
+ // Verify should pass
330
+ {
331
+ const r = await runCliInit([pg.adminUri, "--verify", "--skip-optional-permissions"]);
332
+ assert.equal(r.status, 0, r.stderr || r.stdout);
333
+ assert.match(r.stdout, /init verify: OK/i);
334
+ }
335
+
336
+ // Break a required privilege and ensure verify fails
337
+ {
338
+ const c = new Client({ connectionString: pg.adminUri });
339
+ await c.connect();
340
+ // pg_catalog tables are often readable via PUBLIC by default; revoke from PUBLIC too so the failure is deterministic.
341
+ await c.query("revoke select on pg_catalog.pg_index from public");
342
+ await c.query("revoke select on pg_catalog.pg_index from postgres_ai_mon");
343
+ await c.end();
344
+ }
345
+ {
346
+ const r = await runCliInit([pg.adminUri, "--verify", "--skip-optional-permissions"]);
347
+ assert.notEqual(r.status, 0);
348
+ assert.match(r.stderr, /init verify failed/i);
349
+ assert.match(r.stderr, /pg_catalog\.pg_index/i);
350
+ }
351
+ });
352
+
353
+ test("integration: init --reset-password updates the monitoring role login password", { skip: !havePostgresBinaries() }, async (t) => {
354
+ const pg = await withTempPostgres(t);
355
+ const { Client } = require("pg");
356
+
357
+ // Initial setup with password pw1
358
+ {
359
+ const r = await runCliInit([pg.adminUri, "--password", "pw1", "--skip-optional-permissions"]);
360
+ assert.equal(r.status, 0, r.stderr || r.stdout);
361
+ }
362
+
363
+ // Reset to pw2
364
+ {
365
+ const r = await runCliInit([pg.adminUri, "--reset-password", "--password", "pw2", "--skip-optional-permissions"]);
366
+ assert.equal(r.status, 0, r.stderr || r.stdout);
367
+ assert.match(r.stdout, /password reset/i);
368
+ }
369
+
370
+ // Connect as monitoring user with new password should work
371
+ {
372
+ const c = new Client({
373
+ connectionString: `postgresql://postgres_ai_mon:pw2@127.0.0.1:${pg.port}/testdb`,
374
+ });
375
+ await c.connect();
376
+ const ok = await c.query("select 1 as ok");
377
+ assert.equal(ok.rows[0].ok, 1);
378
+ await c.end();
379
+ }
380
+ });
381
+
382
+