pgserve 1.2.0 → 2.0.0

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,201 @@
1
+ /**
2
+ * PR #24 regression tests for the v2 daemon.
3
+ *
4
+ * The daemon (src/daemon.js) shares a PostgresManager lifecycle with the
5
+ * v1 router (src/router.js). PR #24's fixes for issue #24 (stale socketDir
6
+ * leaks across stop/start cycles) must remain in force after the v2 cut.
7
+ *
8
+ * Coverage:
9
+ * 1. PostgresManager.stop() nulls socketDir/databaseDir.
10
+ * 2. start() + stop() + start() yields a fresh socketDir (no leak).
11
+ * 3. Double start() is a no-op (re-entry guard).
12
+ * 4. Daemon mode does NOT introduce a new socketDir leak path under
13
+ * abnormal exit (kill -9): orphaned socket file + pid lock are cleaned
14
+ * up by the next `PgserveDaemon.start()` boot via stale-pid detection.
15
+ */
16
+
17
+ import { describe, test, expect } from 'bun:test';
18
+ import fs from 'fs';
19
+ import os from 'os';
20
+ import path from 'path';
21
+
22
+ import { PostgresManager } from '../src/postgres.js';
23
+ import { createLogger } from '../src/logger.js';
24
+ import {
25
+ PgserveDaemon,
26
+ acquirePidLock,
27
+ resolveControlSocketPath,
28
+ resolvePidLockPath,
29
+ isProcessAlive,
30
+ } from '../src/daemon.js';
31
+
32
+ function silentLogger() {
33
+ return createLogger({ level: 'warn' });
34
+ }
35
+
36
+ // Each test uses a unique controlSocketDir under tmp so concurrent runs
37
+ // (and the existing host's real /run/user/<uid>/pgserve) cannot collide.
38
+ function makeDaemonDirs(tag) {
39
+ const dir = path.join(os.tmpdir(), `pgserve-daemon-test-${tag}-${process.pid}-${Date.now()}`);
40
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
41
+ return dir;
42
+ }
43
+
44
+ describe('PR #24 regression — PostgresManager lifecycle', () => {
45
+ test('stop() nulls socketDir/databaseDir', async () => {
46
+ const pg = new PostgresManager({ port: 16001, logger: silentLogger() });
47
+ await pg.start();
48
+ expect(pg.socketDir).not.toBeNull();
49
+ expect(fs.existsSync(pg.socketDir)).toBe(true);
50
+ const stale = pg.socketDir;
51
+
52
+ await pg.stop();
53
+
54
+ expect(pg.socketDir).toBeNull();
55
+ expect(pg.databaseDir).toBeNull();
56
+ expect(pg.getSocketPath()).toBeNull();
57
+ expect(fs.existsSync(stale)).toBe(false);
58
+ });
59
+
60
+ test('start()+stop()+start() yields fresh socketDir, no leak', async () => {
61
+ const pg = new PostgresManager({ port: 16002, logger: silentLogger() });
62
+
63
+ await pg.start();
64
+ const dirA = pg.socketDir;
65
+ expect(dirA).not.toBeNull();
66
+
67
+ await pg.stop();
68
+ expect(pg.socketDir).toBeNull();
69
+
70
+ await pg.start();
71
+ const dirB = pg.socketDir;
72
+ expect(dirB).not.toBeNull();
73
+ expect(dirB).not.toBe(dirA);
74
+ expect(fs.existsSync(dirB)).toBe(true);
75
+ // Old dir must be gone; PR #24 guarantees no leak across cycles.
76
+ expect(fs.existsSync(dirA)).toBe(false);
77
+
78
+ await pg.stop();
79
+ });
80
+
81
+ test('double start() is a no-op (re-entry guard preserved)', async () => {
82
+ const pg = new PostgresManager({ port: 16003, logger: silentLogger() });
83
+ await pg.start();
84
+ const before = pg.socketDir;
85
+
86
+ const result = await pg.start();
87
+ expect(result).toBe(pg);
88
+ expect(pg.socketDir).toBe(before);
89
+
90
+ await pg.stop();
91
+ });
92
+ });
93
+
94
+ describe('PR #24 regression — daemon does not leak under abnormal exit', () => {
95
+ test('stale pid lock + orphaned socket are cleaned up by next daemon boot', async () => {
96
+ const dir = makeDaemonDirs('stale');
97
+ const socketPath = resolveControlSocketPath(dir);
98
+ const pidLockPath = resolvePidLockPath(dir);
99
+
100
+ // Simulate kill -9: write a pid file pointing at a guaranteed-dead pid
101
+ // and create a fake stale socket file beside it. PID 1 is always alive
102
+ // on Unix, so we manufacture a dead one by reading max_pid + 1 (Linux)
103
+ // or just using a high value not currently in use.
104
+ const deadPid = pickDeadPid();
105
+ expect(isProcessAlive(deadPid)).toBe(false);
106
+
107
+ fs.writeFileSync(pidLockPath, String(deadPid), { mode: 0o600 });
108
+ fs.writeFileSync(socketPath, ''); // stand-in for an orphaned socket file
109
+ expect(fs.existsSync(pidLockPath)).toBe(true);
110
+ expect(fs.existsSync(socketPath)).toBe(true);
111
+
112
+ const lock = acquirePidLock({
113
+ pidLockPath,
114
+ socketPath,
115
+ logger: silentLogger(),
116
+ });
117
+ expect(lock.acquired).toBe(true);
118
+
119
+ // The lock file now belongs to *us* (this test's process pid), and the
120
+ // orphaned socket placeholder must have been removed during stale-pid
121
+ // cleanup so the daemon can bind a fresh socket on the same path.
122
+ expect(fs.existsSync(pidLockPath)).toBe(true);
123
+ expect(fs.readFileSync(pidLockPath, 'utf8').trim()).toBe(String(process.pid));
124
+ expect(fs.existsSync(socketPath)).toBe(false);
125
+
126
+ // Cleanup the test's lock so we don't leak between tests.
127
+ fs.unlinkSync(pidLockPath);
128
+ fs.rmSync(dir, { recursive: true, force: true });
129
+ });
130
+
131
+ test('PgserveDaemon.start refuses second invocation while first is alive', async () => {
132
+ const dir = makeDaemonDirs('singleton');
133
+ const d1 = new PgserveDaemon({
134
+ controlSocketDir: dir,
135
+ controlSocketPath: resolveControlSocketPath(dir),
136
+ pidLockPath: resolvePidLockPath(dir),
137
+ pgPort: 16010,
138
+ logger: silentLogger(),
139
+ });
140
+ await d1.start();
141
+
142
+ const d2 = new PgserveDaemon({
143
+ controlSocketDir: dir,
144
+ controlSocketPath: resolveControlSocketPath(dir),
145
+ pidLockPath: resolvePidLockPath(dir),
146
+ pgPort: 16011,
147
+ logger: silentLogger(),
148
+ });
149
+
150
+ let captured;
151
+ try {
152
+ await d2.start();
153
+ } catch (err) {
154
+ captured = err;
155
+ }
156
+ expect(captured).toBeDefined();
157
+ expect(captured.code).toBe('EALREADYRUNNING');
158
+ expect(captured.pid).toBe(process.pid);
159
+
160
+ await d1.stop();
161
+ expect(fs.existsSync(d1.controlSocketPath)).toBe(false);
162
+ expect(fs.existsSync(d1.pidLockPath)).toBe(false);
163
+ fs.rmSync(dir, { recursive: true, force: true });
164
+ });
165
+
166
+ test('PgserveDaemon.stop unlinks both socket and pid lock', async () => {
167
+ const dir = makeDaemonDirs('cleanup');
168
+ const d = new PgserveDaemon({
169
+ controlSocketDir: dir,
170
+ controlSocketPath: resolveControlSocketPath(dir),
171
+ pidLockPath: resolvePidLockPath(dir),
172
+ pgPort: 16020,
173
+ logger: silentLogger(),
174
+ });
175
+ await d.start();
176
+ expect(fs.existsSync(d.controlSocketPath)).toBe(true);
177
+ expect(fs.existsSync(d.pidLockPath)).toBe(true);
178
+
179
+ await d.stop();
180
+ expect(fs.existsSync(d.controlSocketPath)).toBe(false);
181
+ expect(fs.existsSync(d.pidLockPath)).toBe(false);
182
+
183
+ // PR #24 invariant carries through: PostgresManager nulled its paths.
184
+ expect(d.pgManager.socketDir).toBeNull();
185
+
186
+ fs.rmSync(dir, { recursive: true, force: true });
187
+ });
188
+ });
189
+
190
+ /**
191
+ * Pick a pid that is reasonably guaranteed not to be alive. We try a high
192
+ * pid first (most kernels recycle low pids), then walk down until we find
193
+ * one that is dead. As a final fallback we use 999999.
194
+ */
195
+ function pickDeadPid() {
196
+ const candidates = [987654, 765432, 543210, 321098, 109876];
197
+ for (const pid of candidates) {
198
+ if (!isProcessAlive(pid)) return pid;
199
+ }
200
+ return 999999;
201
+ }
@@ -0,0 +1,249 @@
1
+ /**
2
+ * Tests for src/fingerprint.js — kernel-rooted peer identity.
3
+ *
4
+ * Coverage:
5
+ * - getPeerCred() returns the calling process's pid/uid/gid via SO_PEERCRED
6
+ * - findNearestPackageJson() walks upward; deepest match wins (monorepo)
7
+ * - derivePackageFingerprint() is stable across cwd changes in the same project
8
+ * - same name + different paths → different fingerprints
9
+ * - same path + different uid → different fingerprints
10
+ * - script fallback triggers when no package.json above cwd
11
+ * - end-to-end: handleControlAccept() emits a connection_routed audit entry
12
+ */
13
+
14
+ import { test, expect, beforeAll, beforeEach, afterEach } from 'bun:test';
15
+ import fs from 'fs';
16
+ import os from 'os';
17
+ import path from 'path';
18
+ import net from 'net';
19
+ import {
20
+ initFingerprintFfi,
21
+ getPeerCred,
22
+ findNearestPackageJson,
23
+ readPackageName,
24
+ derivePackageFingerprint,
25
+ deriveScriptFingerprint,
26
+ fingerprintFromCred,
27
+ handleControlAccept,
28
+ _setPeerCredImpl,
29
+ } from '../src/fingerprint.js';
30
+ import { configureAudit, AUDIT_EVENTS } from '../src/audit.js';
31
+
32
+ let scratch;
33
+
34
+ beforeAll(async () => {
35
+ await initFingerprintFfi();
36
+ });
37
+
38
+ beforeEach(() => {
39
+ scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'pgserve-fp-test-'));
40
+ configureAudit({
41
+ logFile: path.join(scratch, 'audit.log'),
42
+ target: 'file',
43
+ });
44
+ });
45
+
46
+ afterEach(() => {
47
+ _setPeerCredImpl(null);
48
+ try { fs.rmSync(scratch, { recursive: true, force: true }); } catch { /* noop */ }
49
+ });
50
+
51
+ // ---------------------------------------------------------------------------
52
+ // SO_PEERCRED smoke — proves the FFI path works end-to-end on this kernel.
53
+ // ---------------------------------------------------------------------------
54
+
55
+ test('getPeerCred reads kernel-attested pid/uid/gid via Unix socket pair', async () => {
56
+ const sockPath = path.join(scratch, 'peer.sock');
57
+ const expectedUid = process.getuid();
58
+ const expectedGid = process.getgid();
59
+ const expectedPid = process.pid;
60
+
61
+ const cred = await new Promise((resolve, reject) => {
62
+ const server = net.createServer((socket) => {
63
+ try {
64
+ const c = getPeerCred(socket);
65
+ socket.end();
66
+ server.close(() => resolve(c));
67
+ } catch (err) {
68
+ server.close(() => reject(err));
69
+ }
70
+ });
71
+ server.on('error', reject);
72
+ server.listen(sockPath, () => {
73
+ const client = net.createConnection(sockPath);
74
+ client.on('error', reject);
75
+ });
76
+ });
77
+
78
+ expect(cred.pid).toBe(expectedPid);
79
+ expect(cred.uid).toBe(expectedUid);
80
+ expect(cred.gid).toBe(expectedGid);
81
+ });
82
+
83
+ // ---------------------------------------------------------------------------
84
+ // Pure-function tests on derivation surface
85
+ // ---------------------------------------------------------------------------
86
+
87
+ test('fingerprint stable across cwd change in the same project', () => {
88
+ // Layout:
89
+ // <scratch>/proj/package.json (name=alpha)
90
+ // <scratch>/proj/sub/deep/
91
+ // Same project → same fingerprint regardless of starting cwd.
92
+ const proj = path.join(scratch, 'proj');
93
+ fs.mkdirSync(path.join(proj, 'sub', 'deep'), { recursive: true });
94
+ fs.writeFileSync(path.join(proj, 'package.json'), JSON.stringify({ name: 'alpha' }));
95
+
96
+ const root = findNearestPackageJson(proj);
97
+ const fromSub = findNearestPackageJson(path.join(proj, 'sub'));
98
+ const fromDeep = findNearestPackageJson(path.join(proj, 'sub', 'deep'));
99
+
100
+ expect(root).not.toBeNull();
101
+ expect(fromSub).toBe(root);
102
+ expect(fromDeep).toBe(root);
103
+
104
+ const fp1 = derivePackageFingerprint({ packageRealpath: root, name: 'alpha', uid: 1000 });
105
+ const fp2 = derivePackageFingerprint({ packageRealpath: fromSub, name: 'alpha', uid: 1000 });
106
+ const fp3 = derivePackageFingerprint({ packageRealpath: fromDeep, name: 'alpha', uid: 1000 });
107
+ expect(fp1).toBe(fp2);
108
+ expect(fp2).toBe(fp3);
109
+ expect(fp1).toMatch(/^[0-9a-f]{12}$/);
110
+ });
111
+
112
+ test('two projects with the same name but different paths get different fingerprints', () => {
113
+ const a = path.join(scratch, 'a-project');
114
+ const b = path.join(scratch, 'b-project');
115
+ fs.mkdirSync(a);
116
+ fs.mkdirSync(b);
117
+ fs.writeFileSync(path.join(a, 'package.json'), JSON.stringify({ name: 'shared' }));
118
+ fs.writeFileSync(path.join(b, 'package.json'), JSON.stringify({ name: 'shared' }));
119
+
120
+ const pa = findNearestPackageJson(a);
121
+ const pb = findNearestPackageJson(b);
122
+ expect(pa).not.toBe(pb);
123
+
124
+ const fpa = derivePackageFingerprint({ packageRealpath: pa, name: 'shared', uid: 1000 });
125
+ const fpb = derivePackageFingerprint({ packageRealpath: pb, name: 'shared', uid: 1000 });
126
+ expect(fpa).not.toBe(fpb);
127
+ });
128
+
129
+ test('same path + different uid → different fingerprints', () => {
130
+ const proj = path.join(scratch, 'multi-user');
131
+ fs.mkdirSync(proj);
132
+ fs.writeFileSync(path.join(proj, 'package.json'), JSON.stringify({ name: 'multi' }));
133
+ const realpath = findNearestPackageJson(proj);
134
+
135
+ const fp1000 = derivePackageFingerprint({ packageRealpath: realpath, name: 'multi', uid: 1000 });
136
+ const fp1001 = derivePackageFingerprint({ packageRealpath: realpath, name: 'multi', uid: 1001 });
137
+ expect(fp1000).not.toBe(fp1001);
138
+ });
139
+
140
+ test('script fallback triggered when no package.json above cwd', () => {
141
+ // Build an isolated path tree under scratch with no package.json anywhere.
142
+ // We point fingerprintFromCred at an override cwd inside scratch so the
143
+ // upward walk hits the filesystem root (no package.json in /tmp/.. either,
144
+ // because we use a deliberately ephemeral dir tree owned by the test).
145
+ const isolated = path.join(scratch, 'isolated', 'deep');
146
+ fs.mkdirSync(isolated, { recursive: true });
147
+
148
+ // Sanity: walking up from `isolated` finds no package.json (until at least
149
+ // /tmp/... or higher; we trust the host doesn't have one in /tmp).
150
+ // If the host *does* have one above /tmp, the result would still be deterministic
151
+ // and correct (mode='package'), but we want to test the script-fallback branch
152
+ // here. Mock findNearestPackageJson by passing a cwdOverride beneath a fake
153
+ // chroot — the easiest way is to walk to a path that we control: use an
154
+ // empty subtree under scratch and pretend the walk has hit the root.
155
+ const sentinelFile = findNearestPackageJson(isolated);
156
+ // If the host has no package.json anywhere up to /, sentinelFile is null.
157
+ // If it does, this assertion would falsely target the host's package.json.
158
+ // To make the test deterministic, we drive the script branch directly via
159
+ // deriveScriptFingerprint; the integration of "no package.json found" is
160
+ // covered by fingerprintFromCred's branch logic with cmdlineOverride.
161
+
162
+ const fp = deriveScriptFingerprint({
163
+ uid: 1000,
164
+ cwd: '/some/orphan/dir',
165
+ cmdline1: '/usr/local/bin/foo.js',
166
+ });
167
+ expect(fp).toMatch(/^[0-9a-f]{12}$/);
168
+
169
+ // Also verify fingerprintFromCred picks the script branch when cwdOverride
170
+ // points at a path with no ancestor package.json — we use a path under
171
+ // scratch since scratch itself has no package.json, and we pass cmdlineOverride.
172
+ const info = fingerprintFromCred(
173
+ { pid: 9999, uid: 1000, gid: 1000 },
174
+ {
175
+ cwdOverride: isolated,
176
+ cmdlineOverride: ['/usr/local/bin/bun', '/some/orphan/dir/foo.js'],
177
+ },
178
+ );
179
+ // sentinelFile may be null (script mode) or non-null (if host has /package.json upstream).
180
+ if (sentinelFile === null) {
181
+ expect(info.mode).toBe('script');
182
+ expect(info.fingerprint).toMatch(/^[0-9a-f]{12}$/);
183
+ expect(info.packageRealpath).toBeNull();
184
+ } else {
185
+ // Host has an ancestor package.json. Still verify that derivation produces
186
+ // a 12-hex value and that the 'package' branch was chosen — the
187
+ // script-fallback behavior is independently exercised by deriveScriptFingerprint above.
188
+ expect(info.mode).toBe('package');
189
+ expect(info.fingerprint).toMatch(/^[0-9a-f]{12}$/);
190
+ }
191
+ });
192
+
193
+ test('monorepo: nested package.json wins (deepest match)', () => {
194
+ // Layout:
195
+ // <scratch>/mono/package.json (name=workspace-root)
196
+ // <scratch>/mono/packages/api/package.json (name=api)
197
+ // <scratch>/mono/packages/api/src/
198
+ // Walking up from src/ must find the api package.json, not the workspace root.
199
+ const root = path.join(scratch, 'mono');
200
+ const api = path.join(root, 'packages', 'api');
201
+ const apiSrc = path.join(api, 'src');
202
+ fs.mkdirSync(apiSrc, { recursive: true });
203
+ fs.writeFileSync(path.join(root, 'package.json'), JSON.stringify({ name: 'workspace-root' }));
204
+ fs.writeFileSync(path.join(api, 'package.json'), JSON.stringify({ name: 'api' }));
205
+
206
+ const found = findNearestPackageJson(apiSrc);
207
+ expect(found).toBe(fs.realpathSync(path.join(api, 'package.json')));
208
+ expect(readPackageName(found)).toBe('api');
209
+
210
+ const info = fingerprintFromCred(
211
+ { pid: 9999, uid: 1000, gid: 1000 },
212
+ { cwdOverride: apiSrc, cmdlineOverride: ['bun', 'src/index.js'] },
213
+ );
214
+ expect(info.mode).toBe('package');
215
+ expect(info.name).toBe('api');
216
+ expect(info.packageRealpath).toBe(found);
217
+ });
218
+
219
+ // ---------------------------------------------------------------------------
220
+ // End-to-end: handleControlAccept emits connection_routed
221
+ // ---------------------------------------------------------------------------
222
+
223
+ test('handleControlAccept emits a connection_routed audit event with 12-hex fingerprint', () => {
224
+ const proj = path.join(scratch, 'audit-target');
225
+ fs.mkdirSync(proj);
226
+ fs.writeFileSync(path.join(proj, 'package.json'), JSON.stringify({ name: 'audit-app' }));
227
+
228
+ // Stub peer-cred impl so we don't need a real socket.
229
+ _setPeerCredImpl(() => ({ pid: 4242, uid: 1000, gid: 1000 }));
230
+
231
+ const info = handleControlAccept(
232
+ { /* fake socket */ },
233
+ { cwdOverride: proj, cmdlineOverride: ['bun', 'index.js'] },
234
+ );
235
+
236
+ expect(info.fingerprint).toMatch(/^[0-9a-f]{12}$/);
237
+ expect(info.mode).toBe('package');
238
+ expect(info.name).toBe('audit-app');
239
+
240
+ const logFile = path.join(scratch, 'audit.log');
241
+ const lines = fs.readFileSync(logFile, 'utf8').trim().split('\n').filter(Boolean);
242
+ expect(lines.length).toBe(1);
243
+ const entry = JSON.parse(lines[0]);
244
+ expect(entry.event).toBe(AUDIT_EVENTS.CONNECTION_ROUTED);
245
+ expect(entry.fingerprint).toBe(info.fingerprint);
246
+ expect(entry.peer_pid).toBe(4242);
247
+ expect(entry.peer_uid).toBe(1000);
248
+ expect(entry.mode).toBe('package');
249
+ });
@@ -0,0 +1,30 @@
1
+ -- Group 5 — synthetic orphan fixture.
2
+ --
3
+ -- Seeds 240 rows in `pgserve_meta` with stale `last_connection_at`
4
+ -- (48 hours old, well past the 24h TTL) and a dead `liveness_pid`. Half
5
+ -- the rows use a guaranteed-out-of-range PID (2147483646, far above
6
+ -- Linux's pid_max ≤ 2^22 ≈ 4M); the other half use NULL so the sweep
7
+ -- exercises both audit code paths (`db_reaped_liveness` vs `db_reaped_ttl`).
8
+ --
9
+ -- The accompanying harness `tests/orphan-cleanup.test.js` runs this file
10
+ -- and then `CREATE DATABASE`s each row's `database_name` so the sweep
11
+ -- actually has something to DROP.
12
+
13
+ INSERT INTO pgserve_meta (
14
+ database_name,
15
+ fingerprint,
16
+ peer_uid,
17
+ package_realpath,
18
+ last_connection_at,
19
+ liveness_pid,
20
+ persist
21
+ )
22
+ SELECT
23
+ format('app_orphan_%s', lpad(to_hex(i), 12, '0')),
24
+ lpad(to_hex(i), 12, '0'),
25
+ 1000,
26
+ NULL,
27
+ now() - interval '48 hours',
28
+ CASE WHEN i % 2 = 0 THEN 2147483646 ELSE NULL END,
29
+ false
30
+ FROM generate_series(1, 240) AS i;