-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathinit.test.ts
More file actions
1777 lines (1569 loc) · 76.8 KB
/
init.test.ts
File metadata and controls
1777 lines (1569 loc) · 76.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { describe, test, expect, beforeAll, afterAll } from "bun:test";
import path, { resolve } from "path";
import * as fs from "fs";
import * as os from "os";
// Import from source directly since we're using Bun
import * as init from "../lib/init";
const DEFAULT_MONITORING_USER = init.DEFAULT_MONITORING_USER;
function runCli(args: string[], env: Record<string, string> = {}) {
const cliPath = resolve(import.meta.dir, "..", "bin", "postgres-ai.ts");
const bunBin = typeof process.execPath === "string" && process.execPath.length > 0 ? process.execPath : "bun";
const result = Bun.spawnSync([bunBin, cliPath, ...args], {
env: { ...process.env, ...env },
});
return {
status: result.exitCode,
stdout: new TextDecoder().decode(result.stdout),
stderr: new TextDecoder().decode(result.stderr),
};
}
function runPgai(args: string[], env: Record<string, string> = {}) {
// For testing, run the CLI directly since pgai is just a thin wrapper
// In production, pgai wrapper will properly resolve and spawn the postgresai CLI
const cliPath = resolve(import.meta.dir, "..", "bin", "postgres-ai.ts");
const bunBin = typeof process.execPath === "string" && process.execPath.length > 0 ? process.execPath : "bun";
const result = Bun.spawnSync([bunBin, cliPath, ...args], {
env: { ...process.env, ...env },
});
return {
status: result.exitCode,
stdout: new TextDecoder().decode(result.stdout),
stderr: new TextDecoder().decode(result.stderr),
};
}
describe("init module", () => {
test("maskConnectionString hides password when present", () => {
const masked = init.maskConnectionString("postgresql://user:secret@localhost:5432/mydb");
expect(masked).toMatch(/postgresql:\/\/user:\*{5}@localhost:5432\/mydb/);
expect(masked).not.toMatch(/secret/);
});
test("parseLibpqConninfo parses basic host/dbname/user/port/password", () => {
const cfg = init.parseLibpqConninfo("dbname=mydb host=localhost user=alice port=5432 password=secret");
expect(cfg.database).toBe("mydb");
expect(cfg.host).toBe("localhost");
expect(cfg.user).toBe("alice");
expect(cfg.port).toBe(5432);
expect(cfg.password).toBe("secret");
});
test("parseLibpqConninfo supports quoted values", () => {
const cfg = init.parseLibpqConninfo("dbname='my db' host='local host'");
expect(cfg.database).toBe("my db");
expect(cfg.host).toBe("local host");
});
test("buildInitPlan includes a race-safe role DO block", async () => {
const plan = await init.buildInitPlan({
database: "mydb",
monitoringUser: DEFAULT_MONITORING_USER,
monitoringPassword: "pw",
includeOptionalPermissions: false,
});
expect(plan.database).toBe("mydb");
const roleStep = plan.steps.find((s: { name: string }) => s.name === "01.role");
expect(roleStep).toBeTruthy();
expect(roleStep!.sql).toMatch(/do\s+\$\$/i);
expect(roleStep!.sql).toMatch(/create\s+user/i);
expect(roleStep!.sql).toMatch(/alter\s+user/i);
expect(plan.steps.some((s: { optional?: boolean }) => s.optional)).toBe(false);
});
test("buildInitPlan handles special characters in monitoring user and database identifiers", async () => {
const monitoringUser = 'user "with" quotes ✓';
const database = 'db name "with" quotes ✓';
const plan = await init.buildInitPlan({
database,
monitoringUser,
monitoringPassword: "pw",
includeOptionalPermissions: false,
});
const roleStep = plan.steps.find((s: { name: string }) => s.name === "01.role");
expect(roleStep).toBeTruthy();
expect(roleStep!.sql).toMatch(/create\s+user\s+"user ""with"" quotes ✓"/i);
expect(roleStep!.sql).toMatch(/alter\s+user\s+"user ""with"" quotes ✓"/i);
const permStep = plan.steps.find((s: { name: string }) => s.name === "03.permissions");
expect(permStep).toBeTruthy();
expect(permStep!.sql).toMatch(/grant connect on database "db name ""with"" quotes ✓" to "user ""with"" quotes ✓"/i);
});
test("buildInitPlan keeps backslashes in passwords (no unintended escaping)", async () => {
const pw = String.raw`pw\with\backslash`;
const plan = await init.buildInitPlan({
database: "mydb",
monitoringUser: DEFAULT_MONITORING_USER,
monitoringPassword: pw,
includeOptionalPermissions: false,
});
const roleStep = plan.steps.find((s: { name: string }) => s.name === "01.role");
expect(roleStep).toBeTruthy();
expect(roleStep!.sql).toContain(`password '${pw}'`);
});
test("buildInitPlan rejects identifiers with null bytes", async () => {
await expect(
init.buildInitPlan({
database: "mydb",
monitoringUser: "bad\0user",
monitoringPassword: "pw",
includeOptionalPermissions: false,
})
).rejects.toThrow(/Identifier cannot contain null bytes/);
});
test("buildInitPlan rejects literals with null bytes", async () => {
await expect(
init.buildInitPlan({
database: "mydb",
monitoringUser: DEFAULT_MONITORING_USER,
monitoringPassword: "pw\0bad",
includeOptionalPermissions: false,
})
).rejects.toThrow(/Literal cannot contain null bytes/);
});
test("buildInitPlan inlines password safely for CREATE/ALTER ROLE grammar", async () => {
const plan = await init.buildInitPlan({
database: "mydb",
monitoringUser: DEFAULT_MONITORING_USER,
monitoringPassword: "pa'ss",
includeOptionalPermissions: false,
});
const step = plan.steps.find((s: { name: string }) => s.name === "01.role");
expect(step).toBeTruthy();
expect(step!.sql).toMatch(/password 'pa''ss'/);
expect(step!.params).toBeUndefined();
});
test("buildInitPlan includes optional steps when enabled", async () => {
const plan = await init.buildInitPlan({
database: "mydb",
monitoringUser: DEFAULT_MONITORING_USER,
monitoringPassword: "pw",
includeOptionalPermissions: true,
});
expect(plan.steps.some((s: { optional?: boolean }) => s.optional)).toBe(true);
});
test("buildInitPlan skips role creation for supabase provider", async () => {
const plan = await init.buildInitPlan({
database: "mydb",
monitoringUser: DEFAULT_MONITORING_USER,
monitoringPassword: "pw",
includeOptionalPermissions: false,
provider: "supabase",
});
expect(plan.steps.some((s) => s.name === "01.role")).toBe(false);
expect(plan.steps.some((s) => s.name === "03.permissions")).toBe(true);
});
test("buildInitPlan removes ALTER USER for supabase provider", async () => {
const plan = await init.buildInitPlan({
database: "mydb",
monitoringUser: DEFAULT_MONITORING_USER,
monitoringPassword: "pw",
includeOptionalPermissions: false,
provider: "supabase",
});
const permStep = plan.steps.find((s) => s.name === "03.permissions");
expect(permStep).toBeDefined();
expect(permStep!.sql.toLowerCase()).not.toMatch(/alter user/);
});
test("buildInitPlan includes role creation for unknown provider", async () => {
const plan = await init.buildInitPlan({
database: "mydb",
monitoringUser: DEFAULT_MONITORING_USER,
monitoringPassword: "pw",
includeOptionalPermissions: false,
provider: "some-custom-provider",
});
expect(plan.steps.some((s) => s.name === "01.role")).toBe(true);
});
test("resolveAdminConnection accepts positional URI", () => {
const r = init.resolveAdminConnection({ conn: "postgresql://u:p@h:5432/d" });
expect(r.clientConfig.connectionString).toBeTruthy();
expect(r.display).not.toMatch(/:p@/);
});
test("resolveAdminConnection accepts positional conninfo", () => {
const r = init.resolveAdminConnection({ conn: "dbname=mydb host=localhost user=alice" });
expect(r.clientConfig.database).toBe("mydb");
expect(r.clientConfig.host).toBe("localhost");
expect(r.clientConfig.user).toBe("alice");
});
test("resolveAdminConnection rejects invalid psql-like port", () => {
expect(() => init.resolveAdminConnection({ host: "localhost", port: "abc", username: "u", dbname: "d" }))
.toThrow(/Invalid port value/);
});
test("resolveAdminConnection rejects when only PGPASSWORD is provided (no connection details)", () => {
expect(() => init.resolveAdminConnection({ envPassword: "pw" })).toThrow(/Connection is required/);
});
test("resolveAdminConnection rejects when connection is missing", () => {
expect(() => init.resolveAdminConnection({})).toThrow(/Connection is required/);
});
test("resolveMonitoringPassword auto-generates a strong, URL-safe password by default", async () => {
const r = await init.resolveMonitoringPassword({ monitoringUser: DEFAULT_MONITORING_USER });
expect(r.generated).toBe(true);
expect(typeof r.password).toBe("string");
expect(r.password.length).toBeGreaterThanOrEqual(30);
expect(r.password).toMatch(/^[A-Za-z0-9_-]+$/);
});
test("applyInitPlan preserves Postgres error fields on step failures", async () => {
const plan = {
monitoringUser: DEFAULT_MONITORING_USER,
database: "mydb",
steps: [{ name: "01.role", sql: "select 1" }],
};
const pgErr = Object.assign(new Error("permission denied to create role"), {
code: "42501",
detail: "some detail",
hint: "some hint",
schema: "pg_catalog",
table: "pg_roles",
constraint: "some_constraint",
routine: "aclcheck_error",
});
const calls: string[] = [];
const client = {
query: async (sql: string) => {
calls.push(sql);
if (sql === "begin;") return { rowCount: 1 };
if (sql === "rollback;") return { rowCount: 1 };
if (sql === "select 1") throw pgErr;
throw new Error(`unexpected sql: ${sql}`);
},
};
try {
await init.applyInitPlan({ client: client as any, plan: plan as any });
expect(true).toBe(false); // Should not reach here
} catch (e: any) {
expect(e).toBeInstanceOf(Error);
expect(e.message).toMatch(/Failed at step "01\.role":/);
expect(e.code).toBe("42501");
expect(e.detail).toBe("some detail");
expect(e.hint).toBe("some hint");
expect(e.schema).toBe("pg_catalog");
expect(e.table).toBe("pg_roles");
expect(e.constraint).toBe("some_constraint");
expect(e.routine).toBe("aclcheck_error");
}
expect(calls).toEqual(["begin;", "select 1", "rollback;"]);
});
test("verifyInitSetup runs inside a repeatable read snapshot and rolls back", async () => {
const calls: string[] = [];
const client = {
query: async (sql: string, params?: any) => {
calls.push(String(sql));
if (String(sql).toLowerCase().startsWith("begin isolation level repeatable read")) {
return { rowCount: 1, rows: [] };
}
if (String(sql).toLowerCase() === "rollback;") {
return { rowCount: 1, rows: [] };
}
if (String(sql).includes("select rolconfig")) {
return { rowCount: 1, rows: [{ rolconfig: ['search_path=postgres_ai, extensions, "$user", public, pg_catalog'] }] };
}
if (String(sql).includes("from pg_catalog.pg_roles")) {
return { rowCount: 1, rows: [] };
}
if (String(sql).includes("has_database_privilege")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
if (String(sql).includes("pg_has_role")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
if (String(sql).includes("has_table_privilege") && String(sql).includes("pg_catalog.pg_index")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
if (String(sql).includes("to_regclass('postgres_ai.pg_statistic')")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
if (String(sql).includes("has_table_privilege") && String(sql).includes("postgres_ai.pg_statistic")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
if (String(sql).includes("has_function_privilege")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
if (String(sql).includes("has_schema_privilege")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
// Query for pg_stat_statements extension schema location
if (String(sql).includes("pg_extension e") && String(sql).includes("pg_stat_statements")) {
return { rowCount: 1, rows: [{ schema: "pg_catalog" }] };
}
throw new Error(`unexpected sql: ${sql} params=${JSON.stringify(params)}`);
},
};
const r = await init.verifyInitSetup({
client: client as any,
database: "mydb",
monitoringUser: DEFAULT_MONITORING_USER,
includeOptionalPermissions: false,
});
expect(r.ok).toBe(true);
expect(r.missingRequired.length).toBe(0);
expect(calls.length).toBeGreaterThan(2);
expect(calls[0].toLowerCase()).toMatch(/^begin isolation level repeatable read/);
expect(calls[calls.length - 1].toLowerCase()).toBe("rollback;");
});
test("verifyInitSetup skips search_path check for supabase provider", async () => {
const calls: string[] = [];
const client = {
query: async (sql: string, params?: any) => {
calls.push(String(sql));
if (String(sql).toLowerCase().startsWith("begin isolation level repeatable read")) {
return { rowCount: 1, rows: [] };
}
if (String(sql).toLowerCase() === "rollback;") {
return { rowCount: 1, rows: [] };
}
// Return empty rolconfig - would fail without provider=supabase
if (String(sql).includes("select rolconfig")) {
return { rowCount: 1, rows: [{ rolconfig: null }] };
}
if (String(sql).includes("from pg_catalog.pg_roles")) {
return { rowCount: 1, rows: [{ rolname: DEFAULT_MONITORING_USER }] };
}
if (String(sql).includes("has_database_privilege")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
if (String(sql).includes("pg_has_role")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
if (String(sql).includes("has_table_privilege")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
if (String(sql).includes("to_regclass")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
if (String(sql).includes("has_function_privilege")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
if (String(sql).includes("has_schema_privilege")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
// Query for pg_stat_statements extension schema location (Supabase uses 'extensions' schema)
if (String(sql).includes("pg_extension e") && String(sql).includes("pg_stat_statements")) {
return { rowCount: 1, rows: [{ schema: "extensions" }] };
}
throw new Error(`unexpected sql: ${sql} params=${JSON.stringify(params)}`);
},
};
// With provider=supabase, should pass even without search_path
const r = await init.verifyInitSetup({
client: client as any,
database: "mydb",
monitoringUser: DEFAULT_MONITORING_USER,
includeOptionalPermissions: false,
provider: "supabase",
});
expect(r.ok).toBe(true);
expect(r.missingRequired.length).toBe(0);
// Should not have queried for rolconfig since we skip search_path check
expect(calls.some((c) => c.includes("select rolconfig"))).toBe(false);
});
test("verifyInitSetup checks extensions schema when pg_stat_statements is there", async () => {
const calls: string[] = [];
const client = {
query: async (sql: string, params?: any) => {
calls.push(String(sql));
if (String(sql).toLowerCase().startsWith("begin isolation level repeatable read")) {
return { rowCount: 1, rows: [] };
}
if (String(sql).toLowerCase() === "rollback;") {
return { rowCount: 1, rows: [] };
}
if (String(sql).includes("select rolconfig")) {
return { rowCount: 1, rows: [{ rolconfig: ['search_path=postgres_ai, extensions, "$user", public, pg_catalog'] }] };
}
if (String(sql).includes("from pg_catalog.pg_roles")) {
return { rowCount: 1, rows: [{ rolname: DEFAULT_MONITORING_USER }] };
}
if (String(sql).includes("has_database_privilege")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
if (String(sql).includes("pg_has_role")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
if (String(sql).includes("has_table_privilege")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
if (String(sql).includes("to_regclass")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
if (String(sql).includes("has_function_privilege")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
// pg_stat_statements is in 'extensions' schema
if (String(sql).includes("pg_extension e") && String(sql).includes("pg_stat_statements")) {
return { rowCount: 1, rows: [{ schema: "extensions" }] };
}
// Check for USAGE on extensions schema
if (String(sql).includes("has_schema_privilege") && params?.[1] === "extensions") {
return { rowCount: 1, rows: [{ ok: true }] };
}
if (String(sql).includes("has_schema_privilege")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
throw new Error(`unexpected sql: ${sql} params=${JSON.stringify(params)}`);
},
};
const r = await init.verifyInitSetup({
client: client as any,
database: "mydb",
monitoringUser: DEFAULT_MONITORING_USER,
includeOptionalPermissions: false,
});
expect(r.ok).toBe(true);
expect(r.missingRequired.length).toBe(0);
// Should have queried for pg_stat_statements schema location
expect(calls.some((c) => c.includes("pg_extension e") && c.includes("pg_stat_statements"))).toBe(true);
});
test("verifyInitSetup reports missing extensions schema access", async () => {
const client = {
query: async (sql: string, params?: any) => {
if (String(sql).toLowerCase().startsWith("begin isolation level repeatable read")) {
return { rowCount: 1, rows: [] };
}
if (String(sql).toLowerCase() === "rollback;") {
return { rowCount: 1, rows: [] };
}
if (String(sql).includes("select rolconfig")) {
return { rowCount: 1, rows: [{ rolconfig: ['search_path=postgres_ai, "$user", public, pg_catalog'] }] };
}
if (String(sql).includes("from pg_catalog.pg_roles")) {
return { rowCount: 1, rows: [{ rolname: DEFAULT_MONITORING_USER }] };
}
if (String(sql).includes("has_database_privilege")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
if (String(sql).includes("pg_has_role")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
if (String(sql).includes("has_table_privilege")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
if (String(sql).includes("to_regclass")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
if (String(sql).includes("has_function_privilege")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
// pg_stat_statements is in 'extensions' schema
if (String(sql).includes("pg_extension e") && String(sql).includes("pg_stat_statements")) {
return { rowCount: 1, rows: [{ schema: "extensions" }] };
}
// No USAGE on extensions schema
if (String(sql).includes("has_schema_privilege") && params?.[1] === "extensions") {
return { rowCount: 1, rows: [{ ok: false }] };
}
if (String(sql).includes("has_schema_privilege")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
throw new Error(`unexpected sql: ${sql} params=${JSON.stringify(params)}`);
},
};
const r = await init.verifyInitSetup({
client: client as any,
database: "mydb",
monitoringUser: DEFAULT_MONITORING_USER,
includeOptionalPermissions: false,
});
expect(r.ok).toBe(false);
// Should report missing USAGE on extensions schema
expect(r.missingRequired.some((m) => m.includes("extensions") && m.includes("pg_stat_statements"))).toBe(true);
// Should also report missing extensions in search_path
expect(r.missingRequired.some((m) => m.includes("search_path") && m.includes("extensions"))).toBe(true);
});
test("buildInitPlan includes dynamic search_path with extension schema detection", async () => {
const plan = await init.buildInitPlan({
database: "mydb",
monitoringUser: DEFAULT_MONITORING_USER,
monitoringPassword: "pw",
includeOptionalPermissions: false,
});
const permStep = plan.steps.find((s) => s.name === "03.permissions");
expect(permStep).toBeTruthy();
// Should use dynamic DO block to set search_path based on detected extension schema
expect(permStep!.sql).toMatch(/alter\s+user.*set\s+search_path\s*=/i);
// Should detect pg_stat_statements extension schema dynamically
expect(permStep!.sql).toMatch(/quote_ident\(ext_schema\)/i);
});
test("buildInitPlan includes dynamic extension schema grant", async () => {
const plan = await init.buildInitPlan({
database: "mydb",
monitoringUser: DEFAULT_MONITORING_USER,
monitoringPassword: "pw",
includeOptionalPermissions: false,
});
const permStep = plan.steps.find((s) => s.name === "03.permissions");
expect(permStep).toBeTruthy();
// Should include DO block that grants USAGE on extension schema
expect(permStep!.sql).toMatch(/do\s+\$\$/i);
expect(permStep!.sql).toMatch(/pg_stat_statements/);
expect(permStep!.sql).toMatch(/grant usage on schema/i);
});
test("verifyInitSetup handles pg_stat_statements not installed", async () => {
const calls: string[] = [];
const client = {
query: async (sql: string, params?: any) => {
calls.push(String(sql));
if (String(sql).toLowerCase().startsWith("begin isolation level repeatable read")) {
return { rowCount: 1, rows: [] };
}
if (String(sql).toLowerCase() === "rollback;") {
return { rowCount: 1, rows: [] };
}
if (String(sql).includes("select rolconfig")) {
return { rowCount: 1, rows: [{ rolconfig: ['search_path=postgres_ai, extensions, "$user", public, pg_catalog'] }] };
}
if (String(sql).includes("from pg_catalog.pg_roles")) {
return { rowCount: 1, rows: [{ rolname: DEFAULT_MONITORING_USER }] };
}
if (String(sql).includes("has_database_privilege")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
if (String(sql).includes("pg_has_role")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
if (String(sql).includes("has_table_privilege")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
if (String(sql).includes("to_regclass")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
if (String(sql).includes("has_function_privilege")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
// pg_stat_statements is NOT installed - empty result
if (String(sql).includes("pg_extension e") && String(sql).includes("pg_stat_statements")) {
return { rowCount: 0, rows: [] };
}
if (String(sql).includes("has_schema_privilege")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
throw new Error(`unexpected sql: ${sql} params=${JSON.stringify(params)}`);
},
};
const r = await init.verifyInitSetup({
client: client as any,
database: "mydb",
monitoringUser: DEFAULT_MONITORING_USER,
includeOptionalPermissions: false,
});
// Should pass without errors - missing extension shouldn't cause failure
expect(r.ok).toBe(true);
expect(r.missingRequired.length).toBe(0);
// Should have queried for pg_stat_statements schema location
expect(calls.some((c) => c.includes("pg_extension e") && c.includes("pg_stat_statements"))).toBe(true);
});
test("verifyInitSetup skips extension schema check when in pg_catalog", async () => {
const calls: string[] = [];
const client = {
query: async (sql: string, params?: any) => {
calls.push(String(sql));
if (String(sql).toLowerCase().startsWith("begin isolation level repeatable read")) {
return { rowCount: 1, rows: [] };
}
if (String(sql).toLowerCase() === "rollback;") {
return { rowCount: 1, rows: [] };
}
if (String(sql).includes("select rolconfig")) {
return { rowCount: 1, rows: [{ rolconfig: ['search_path=postgres_ai, "$user", public, pg_catalog'] }] };
}
if (String(sql).includes("from pg_catalog.pg_roles")) {
return { rowCount: 1, rows: [{ rolname: DEFAULT_MONITORING_USER }] };
}
if (String(sql).includes("has_database_privilege")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
if (String(sql).includes("pg_has_role")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
if (String(sql).includes("has_table_privilege")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
if (String(sql).includes("to_regclass")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
if (String(sql).includes("has_function_privilege")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
// pg_stat_statements is in pg_catalog (standard location)
if (String(sql).includes("pg_extension e") && String(sql).includes("pg_stat_statements")) {
return { rowCount: 1, rows: [{ schema: "pg_catalog" }] };
}
if (String(sql).includes("has_schema_privilege")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
throw new Error(`unexpected sql: ${sql} params=${JSON.stringify(params)}`);
},
};
const r = await init.verifyInitSetup({
client: client as any,
database: "mydb",
monitoringUser: DEFAULT_MONITORING_USER,
includeOptionalPermissions: false,
});
// Should pass - pg_catalog doesn't need extra USAGE grant
expect(r.ok).toBe(true);
expect(r.missingRequired.length).toBe(0);
// Should NOT have queried for has_schema_privilege on pg_catalog specifically
// (the code skips the check for pg_catalog and public schemas)
const pgCatalogPrivCheck = calls.filter(
(c) => c.includes("has_schema_privilege") && c.includes("pg_catalog")
);
// Should only have the standard public schema check, not a pg_catalog check for extension
expect(pgCatalogPrivCheck.length).toBe(0);
});
test("verifyInitSetup skips extension schema check when in public", async () => {
const calls: string[] = [];
const client = {
query: async (sql: string, params?: any) => {
calls.push(String(sql));
if (String(sql).toLowerCase().startsWith("begin isolation level repeatable read")) {
return { rowCount: 1, rows: [] };
}
if (String(sql).toLowerCase() === "rollback;") {
return { rowCount: 1, rows: [] };
}
if (String(sql).includes("select rolconfig")) {
return { rowCount: 1, rows: [{ rolconfig: ['search_path=postgres_ai, "$user", public, pg_catalog'] }] };
}
if (String(sql).includes("from pg_catalog.pg_roles")) {
return { rowCount: 1, rows: [{ rolname: DEFAULT_MONITORING_USER }] };
}
if (String(sql).includes("has_database_privilege")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
if (String(sql).includes("pg_has_role")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
if (String(sql).includes("has_table_privilege")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
if (String(sql).includes("to_regclass")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
if (String(sql).includes("has_function_privilege")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
// pg_stat_statements is in public schema
if (String(sql).includes("pg_extension e") && String(sql).includes("pg_stat_statements")) {
return { rowCount: 1, rows: [{ schema: "public" }] };
}
if (String(sql).includes("has_schema_privilege")) {
return { rowCount: 1, rows: [{ ok: true }] };
}
throw new Error(`unexpected sql: ${sql} params=${JSON.stringify(params)}`);
},
};
const r = await init.verifyInitSetup({
client: client as any,
database: "mydb",
monitoringUser: DEFAULT_MONITORING_USER,
includeOptionalPermissions: false,
});
// Should pass - public doesn't need extra USAGE grant for extension
expect(r.ok).toBe(true);
expect(r.missingRequired.length).toBe(0);
});
test("buildInitPlan preserves comments when filtering ALTER USER", async () => {
const plan = await init.buildInitPlan({
database: "mydb",
monitoringUser: DEFAULT_MONITORING_USER,
monitoringPassword: "pw",
includeOptionalPermissions: false,
provider: "supabase",
});
const permStep = plan.steps.find((s) => s.name === "03.permissions");
expect(permStep).toBeDefined();
// Should have removed ALTER USER but kept comments
expect(permStep!.sql.toLowerCase()).not.toMatch(/^\s*alter\s+user/m);
// Should still have comment lines
expect(permStep!.sql).toMatch(/^--/m);
});
test("validateProvider returns null for known providers", () => {
expect(init.validateProvider(undefined)).toBe(null);
expect(init.validateProvider("self-managed")).toBe(null);
expect(init.validateProvider("supabase")).toBe(null);
});
test("validateProvider returns warning for unknown providers", () => {
const warning = init.validateProvider("unknown-provider");
expect(warning).not.toBe(null);
expect(warning).toMatch(/Unknown provider/);
expect(warning).toMatch(/unknown-provider/);
});
test("redactPasswordsInSql redacts password literals with embedded quotes", async () => {
const plan = await init.buildInitPlan({
database: "mydb",
monitoringUser: DEFAULT_MONITORING_USER,
monitoringPassword: "pa'ss",
includeOptionalPermissions: false,
});
const step = plan.steps.find((s: { name: string }) => s.name === "01.role");
expect(step).toBeTruthy();
const redacted = init.redactPasswordsInSql(step!.sql);
expect(redacted).toMatch(/password '<redacted>'/i);
});
// Tests for buildUninitPlan
test("buildUninitPlan generates correct steps with dropRole=true", async () => {
const plan = await init.buildUninitPlan({
database: "mydb",
monitoringUser: DEFAULT_MONITORING_USER,
dropRole: true,
});
expect(plan.database).toBe("mydb");
expect(plan.monitoringUser).toBe(DEFAULT_MONITORING_USER);
expect(plan.dropRole).toBe(true);
expect(plan.steps.length).toBe(3);
expect(plan.steps.map((s) => s.name)).toEqual([
"01.drop_helpers",
"02.revoke_permissions",
"03.drop_role",
]);
});
test("buildUninitPlan skips role drop when dropRole=false", async () => {
const plan = await init.buildUninitPlan({
database: "mydb",
monitoringUser: DEFAULT_MONITORING_USER,
dropRole: false,
});
expect(plan.dropRole).toBe(false);
expect(plan.steps.length).toBe(2);
expect(plan.steps.map((s) => s.name)).toEqual([
"01.drop_helpers",
"02.revoke_permissions",
]);
});
test("buildUninitPlan skips role drop for supabase provider", async () => {
const plan = await init.buildUninitPlan({
database: "mydb",
monitoringUser: DEFAULT_MONITORING_USER,
dropRole: true,
provider: "supabase",
});
// Even with dropRole=true, supabase provider skips role operations
expect(plan.steps.length).toBe(2);
expect(plan.steps.some((s) => s.name === "03.drop_role")).toBe(false);
});
test("buildUninitPlan handles special characters in identifiers", async () => {
const monitoringUser = 'user "with" quotes';
const database = 'db "name"';
const plan = await init.buildUninitPlan({
database,
monitoringUser,
dropRole: true,
});
// Check that identifiers are properly quoted in SQL
const dropHelpersStep = plan.steps.find((s) => s.name === "01.drop_helpers");
expect(dropHelpersStep).toBeTruthy();
const revokeStep = plan.steps.find((s) => s.name === "02.revoke_permissions");
expect(revokeStep).toBeTruthy();
expect(revokeStep!.sql).toContain('"user ""with"" quotes"');
expect(revokeStep!.sql).toContain('"db ""name"""');
const dropRoleStep = plan.steps.find((s) => s.name === "03.drop_role");
expect(dropRoleStep).toBeTruthy();
// Uses ROLE_LITERAL (single-quoted) for format('%I', ...) in dynamic SQL
expect(dropRoleStep!.sql).toContain("'user \"with\" quotes'");
});
test("buildUninitPlan rejects identifiers with null bytes", async () => {
await expect(
init.buildUninitPlan({
database: "mydb",
monitoringUser: "bad\0user",
dropRole: true,
})
).rejects.toThrow(/Identifier cannot contain null bytes/);
});
test("applyUninitPlan continues on errors and reports them", async () => {
const plan = {
monitoringUser: DEFAULT_MONITORING_USER,
database: "mydb",
dropRole: true,
steps: [
{ name: "01.drop_helpers", sql: "drop function if exists postgres_ai.test()" },
{ name: "02.revoke_permissions", sql: "select 1/0" }, // Will fail
{ name: "03.drop_role", sql: "select 1" },
],
};
const calls: string[] = [];
const client = {
query: async (sql: string) => {
calls.push(sql);
if (sql === "begin;") return { rowCount: 1 };
if (sql === "commit;") return { rowCount: 1 };
if (sql === "rollback;") return { rowCount: 1 };
if (sql.includes("1/0")) throw new Error("division by zero");
return { rowCount: 1 };
},
};
const result = await init.applyUninitPlan({ client: client as any, plan: plan as any });
// Should have applied steps 1 and 3, with step 2 in errors
expect(result.applied).toContain("01.drop_helpers");
expect(result.applied).toContain("03.drop_role");
expect(result.applied).not.toContain("02.revoke_permissions");
expect(result.errors.length).toBe(1);
expect(result.errors[0]).toMatch(/02\.revoke_permissions.*division by zero/);
});
test("buildInitPlan includes 02.extensions step with pg_stat_statements", async () => {
const plan = await init.buildInitPlan({
database: "mydb",
monitoringUser: DEFAULT_MONITORING_USER,
monitoringPassword: "pw",
includeOptionalPermissions: false,
});
const extStep = plan.steps.find((s) => s.name === "02.extensions");
expect(extStep).toBeTruthy();
// Should create pg_stat_statements with IF NOT EXISTS
expect(extStep!.sql).toMatch(/create extension if not exists pg_stat_statements/i);
});
test("buildInitPlan creates extensions before permissions", async () => {
const plan = await init.buildInitPlan({
database: "mydb",
monitoringUser: DEFAULT_MONITORING_USER,
monitoringPassword: "pw",
includeOptionalPermissions: false,
});
const stepNames = plan.steps.map((s) => s.name);
const extIndex = stepNames.indexOf("02.extensions");
const permIndex = stepNames.indexOf("03.permissions");
expect(extIndex).toBeGreaterThanOrEqual(0);
expect(permIndex).toBeGreaterThanOrEqual(0);
// Extensions should come before permissions
expect(extIndex).toBeLessThan(permIndex);
});
test("buildInitPlan uses IF NOT EXISTS for postgres_ai schema (idempotent)", async () => {
const plan = await init.buildInitPlan({
database: "mydb",
monitoringUser: DEFAULT_MONITORING_USER,
monitoringPassword: "pw",
includeOptionalPermissions: false,
});
const permStep = plan.steps.find((s) => s.name === "03.permissions");
expect(permStep).toBeTruthy();
// Should use IF NOT EXISTS for idempotent behavior
expect(permStep!.sql).toMatch(/create schema if not exists postgres_ai/i);
});
test("buildUninitPlan does NOT drop pg_stat_statements extension", async () => {
const plan = await init.buildUninitPlan({
database: "mydb",
monitoringUser: DEFAULT_MONITORING_USER,
dropRole: true,
});
// Check all steps - none should drop pg_stat_statements
for (const step of plan.steps) {
expect(step.sql.toLowerCase()).not.toMatch(/drop extension.*pg_stat_statements/);
}
});
});
describe("CLI commands", () => {
test("cli: prepare-db with missing connection prints help/options", () => {
const r = runCli(["prepare-db"]);
expect(r.status).not.toBe(0);
expect(r.stderr).toMatch(/--print-sql/);
expect(r.stderr).toMatch(/--monitoring-user/);
});
test("cli: prepare-db --print-sql works without connection (offline mode)", () => {
const r = runCli(["prepare-db", "--print-sql", "-d", "mydb", "--password", "monpw"]);
expect(r.status).toBe(0);
expect(r.stdout).toMatch(/SQL plan \(offline; not connected\)/);
expect(r.stdout).toMatch(new RegExp(`grant connect on database "mydb" to "${DEFAULT_MONITORING_USER}"`, "i"));
});
test("cli: prepare-db --print-sql with --provider supabase skips role step", () => {
const r = runCli(["prepare-db", "--print-sql", "-d", "mydb", "--password", "monpw", "--provider", "supabase"]);
expect(r.status).toBe(0);
expect(r.stdout).toMatch(/provider: supabase/);
// Should not have 01.role step
expect(r.stdout).not.toMatch(/-- 01\.role/);
// Should have 02.extensions and 03.permissions steps
expect(r.stdout).toMatch(/-- 02\.extensions/);
expect(r.stdout).toMatch(/-- 03\.permissions/);
});
test("cli: prepare-db warns about unknown provider", () => {
const r = runCli(["prepare-db", "--print-sql", "-d", "mydb", "--password", "monpw", "--provider", "unknown-cloud"]);
expect(r.status).toBe(0);
// Should warn about unknown provider
expect(r.stderr).toMatch(/Unknown provider.*unknown-cloud/);
});
test("cli: prepare-db --reset-password with supabase provider would have no role step", async () => {
// When using supabase provider, the role creation step is skipped.
// This means --reset-password (which only runs 01.role) would have no steps.
// The CLI should error in this case. We test the underlying plan logic here.
const plan = await (await import("../lib/init")).buildInitPlan({
database: "mydb",
monitoringUser: "mon",
monitoringPassword: "pw",
includeOptionalPermissions: false,
provider: "supabase",
});
// Simulate what --reset-password does: filter to only 01.role step
const resetPasswordSteps = plan.steps.filter((s) => s.name === "01.role");
// For supabase, this should be empty (role creation is skipped)
expect(resetPasswordSteps.length).toBe(0);
});
test("pgai wrapper forwards to postgresai CLI", () => {
const r = runPgai(["--help"]);
expect(r.status).toBe(0);
expect(r.stdout).toMatch(/postgresai|PostgresAI/i);
});
test("cli: prepare-db command exists and shows help", () => {
const r = runCli(["prepare-db", "--help"]);
expect(r.status).toBe(0);
expect(r.stdout).toMatch(/monitoring user/i);
expect(r.stdout).toMatch(/--print-sql/);
});