pgleash 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +170 -2
- package/dist/audit.d.ts +7 -0
- package/dist/audit.js +14 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +143 -0
- package/dist/config.d.ts +29 -0
- package/dist/config.js +148 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +3 -0
- package/dist/mcp.d.ts +2 -0
- package/dist/mcp.js +96 -0
- package/dist/policy.d.ts +37 -0
- package/dist/policy.js +380 -0
- package/dist/protocol.d.ts +66 -0
- package/dist/protocol.js +171 -0
- package/dist/proxy.d.ts +23 -0
- package/dist/proxy.js +443 -0
- package/dist/scram.d.ts +11 -0
- package/dist/scram.js +55 -0
- package/dist/upstream.d.ts +37 -0
- package/dist/upstream.js +286 -0
- package/package.json +64 -4
package/dist/proxy.js
ADDED
|
@@ -0,0 +1,443 @@
|
|
|
1
|
+
// The proxy. The agent connects here with a pgleash token; pgleash connects to the real
|
|
2
|
+
// database with credentials the agent never sees, checks every query, and relays the rest.
|
|
3
|
+
import { createHash, randomBytes, randomInt, timingSafeEqual } from 'node:crypto';
|
|
4
|
+
import net from 'node:net';
|
|
5
|
+
import { checkSql, initPolicy } from './policy.js';
|
|
6
|
+
import * as P from './protocol.js';
|
|
7
|
+
import { connectUpstream, fetchRows, parseUpstreamUrl, sendCancel, UpstreamError } from './upstream.js';
|
|
8
|
+
// Startup parameters passed through to the real server. Anything else ("options" in
|
|
9
|
+
// particular, which can set arbitrary server settings) is dropped.
|
|
10
|
+
const FORWARDED_PARAMS = ['DateStyle', 'TimeZone', 'IntervalStyle', 'extra_float_digits', 'search_path'];
|
|
11
|
+
const HINTS = {
|
|
12
|
+
'statement-type': 'pgleash only lets this connection run the statements its mode allows. Ask a person to run this one.',
|
|
13
|
+
'multi-statement': 'Send each statement as its own query.',
|
|
14
|
+
'unbounded-write': 'Add a WHERE clause that names a column, so the change is limited to the rows you mean.',
|
|
15
|
+
'read-write-transaction': 'This connection is read-only. Ask a person to run changes.',
|
|
16
|
+
setting: 'The session settings are fixed by pgleash.',
|
|
17
|
+
'deny-table': 'This table is marked off limits in the pgleash config.',
|
|
18
|
+
'deny-column': 'This column is marked off limits in the pgleash config. Select the other columns by name.',
|
|
19
|
+
'deny-function': 'This function can change server state or bypass the guardrails.',
|
|
20
|
+
'parse-error': 'Check the SQL syntax.',
|
|
21
|
+
};
|
|
22
|
+
const isLoopback = (host) => host === 'localhost' || host === '::1' || host.startsWith('127.');
|
|
23
|
+
function sameSecret(a, b) {
|
|
24
|
+
const ha = createHash('sha256').update(a).digest();
|
|
25
|
+
const hb = createHash('sha256').update(b).digest();
|
|
26
|
+
return timingSafeEqual(ha, hb);
|
|
27
|
+
}
|
|
28
|
+
class Session {
|
|
29
|
+
pid;
|
|
30
|
+
key = randomInt(1, 2 ** 31 - 1);
|
|
31
|
+
shared;
|
|
32
|
+
client;
|
|
33
|
+
up;
|
|
34
|
+
upPid = 0;
|
|
35
|
+
upKey = 0;
|
|
36
|
+
state = 'startup';
|
|
37
|
+
fromClient = new P.MessageReader(true);
|
|
38
|
+
fromUpstream = new P.MessageReader(false);
|
|
39
|
+
queued = [];
|
|
40
|
+
startupParams = {};
|
|
41
|
+
user = '';
|
|
42
|
+
app = '';
|
|
43
|
+
blocked = new Map();
|
|
44
|
+
nextBlockId = 1;
|
|
45
|
+
// Per result set
|
|
46
|
+
rows = 0;
|
|
47
|
+
mask = null;
|
|
48
|
+
maskedNames = [];
|
|
49
|
+
upPaused = false;
|
|
50
|
+
clientPaused = false;
|
|
51
|
+
constructor(shared, client, pid) {
|
|
52
|
+
this.shared = shared;
|
|
53
|
+
this.client = client;
|
|
54
|
+
this.pid = pid;
|
|
55
|
+
client.setNoDelay(true);
|
|
56
|
+
client.on('data', (chunk) => this.onClientData(chunk));
|
|
57
|
+
client.on('error', () => this.close());
|
|
58
|
+
client.on('close', () => this.close());
|
|
59
|
+
}
|
|
60
|
+
// ---- client side -------------------------------------------------------
|
|
61
|
+
onClientData(chunk) {
|
|
62
|
+
this.fromClient.push(chunk);
|
|
63
|
+
try {
|
|
64
|
+
let m;
|
|
65
|
+
while (this.state !== 'closed' && (m = this.fromClient.next())) {
|
|
66
|
+
if (this.state === 'startup')
|
|
67
|
+
this.onStartup(m);
|
|
68
|
+
else if (this.state === 'password')
|
|
69
|
+
this.onPassword(m);
|
|
70
|
+
else if (this.state === 'connecting')
|
|
71
|
+
this.queued.push(m);
|
|
72
|
+
else
|
|
73
|
+
this.onClientMessage(m);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
catch (err) {
|
|
77
|
+
this.fatal('08P01', err instanceof Error ? err.message : String(err));
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
onStartup(m) {
|
|
81
|
+
const { code, params } = P.parseStartup(m.payload);
|
|
82
|
+
if (code === P.SSL_REQUEST || code === P.GSSENC_REQUEST) {
|
|
83
|
+
this.client.write(Buffer.from('N')); // plain TCP on the agent side; bind to loopback
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
if (code === P.CANCEL_REQUEST) {
|
|
87
|
+
this.shared.sessions.get(m.payload.readInt32BE(4))?.cancel(m.payload.readInt32BE(8));
|
|
88
|
+
this.close();
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
if (code >> 16 !== 3) {
|
|
92
|
+
this.fatal('0A000', `unsupported frontend protocol ${code >> 16}.${code & 0xffff}`);
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
this.fromClient.startup = false;
|
|
96
|
+
const extensions = Object.keys(params).filter((k) => k.startsWith('_pq_.'));
|
|
97
|
+
if ((code & 0xffff) > 0 || extensions.length > 0)
|
|
98
|
+
this.client.write(P.negotiateProtocolVersion(0, extensions));
|
|
99
|
+
if (params.replication && !['false', 'off', 'no', '0'].includes(params.replication.toLowerCase())) {
|
|
100
|
+
this.fatal('0A000', 'pgleash does not proxy replication connections');
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
this.startupParams = params;
|
|
104
|
+
this.user = params.user ?? '';
|
|
105
|
+
this.app = params.application_name ?? '';
|
|
106
|
+
if (this.shared.opts.token !== undefined) {
|
|
107
|
+
this.state = 'password';
|
|
108
|
+
this.client.write(P.authCleartextPassword());
|
|
109
|
+
}
|
|
110
|
+
else {
|
|
111
|
+
this.connect();
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
onPassword(m) {
|
|
115
|
+
if (m.type !== 'p') {
|
|
116
|
+
this.fatal('08P01', 'expected a password message');
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
const [password] = P.readCString(m.payload, 0);
|
|
120
|
+
if (!sameSecret(password, this.shared.opts.token ?? '')) {
|
|
121
|
+
this.shared.opts.audit?.write({ session: this.pid, event: 'auth-failed', user: this.user, app: this.app });
|
|
122
|
+
this.fatal('28P01', `password authentication failed for user "${this.user}"`);
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
this.connect();
|
|
126
|
+
}
|
|
127
|
+
connect() {
|
|
128
|
+
this.state = 'connecting';
|
|
129
|
+
const { opts } = this.shared;
|
|
130
|
+
const setup = [];
|
|
131
|
+
if (opts.policy.mode === 'read-only')
|
|
132
|
+
setup.push('SET default_transaction_read_only = on');
|
|
133
|
+
setup.push(`SET statement_timeout = ${Math.max(0, Math.floor(opts.statementTimeoutMs ?? 10_000))}`);
|
|
134
|
+
setup.push(`SET idle_in_transaction_session_timeout = ${Math.max(0, Math.floor(opts.idleInTransactionTimeoutMs ?? 60_000))}`);
|
|
135
|
+
const startupParams = { application_name: this.app ? `pgleash:${this.app}`.slice(0, 63) : 'pgleash' };
|
|
136
|
+
for (const k of FORWARDED_PARAMS) {
|
|
137
|
+
const v = this.startupParams[k];
|
|
138
|
+
if (v !== undefined)
|
|
139
|
+
startupParams[k] = v;
|
|
140
|
+
}
|
|
141
|
+
connectUpstream(this.shared.upstream, { startupParams, setupSql: setup.join('; ') })
|
|
142
|
+
.then((up) => {
|
|
143
|
+
if (this.state === 'closed') {
|
|
144
|
+
up.socket.destroy();
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
this.up = up.socket;
|
|
148
|
+
this.upPid = up.pid;
|
|
149
|
+
this.upKey = up.key;
|
|
150
|
+
const hello = [P.authOk()];
|
|
151
|
+
for (const [k, v] of up.params)
|
|
152
|
+
hello.push(P.parameterStatus(k, v));
|
|
153
|
+
hello.push(P.backendKeyData(this.pid, this.key), P.readyForQuery('I'));
|
|
154
|
+
this.client.write(Buffer.concat(hello));
|
|
155
|
+
this.shared.opts.audit?.write({ session: this.pid, event: 'connect', user: this.user, app: this.app, mode: opts.policy.mode });
|
|
156
|
+
up.socket.on('data', (chunk) => this.onUpstreamData(chunk));
|
|
157
|
+
up.socket.on('error', () => this.upstreamGone());
|
|
158
|
+
up.socket.on('close', () => this.upstreamGone());
|
|
159
|
+
up.socket.resume();
|
|
160
|
+
this.state = 'ready';
|
|
161
|
+
if (up.pending.length > 0)
|
|
162
|
+
this.onUpstreamData(up.pending);
|
|
163
|
+
for (const m of this.queued.splice(0))
|
|
164
|
+
this.onClientMessage(m);
|
|
165
|
+
})
|
|
166
|
+
.catch((err) => {
|
|
167
|
+
const code = err instanceof UpstreamError ? err.code : '08006';
|
|
168
|
+
this.shared.log(`session ${this.pid}: upstream connection failed: ${err instanceof Error ? err.message : err}`);
|
|
169
|
+
this.fatal(code, `pgleash could not connect to the database: ${err instanceof Error ? err.message : err}`);
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
onClientMessage(m) {
|
|
173
|
+
switch (m.type) {
|
|
174
|
+
case 'Q': {
|
|
175
|
+
const [sql] = P.readCString(m.payload, 0);
|
|
176
|
+
const d = this.decide(sql, 'query');
|
|
177
|
+
this.toUpstream(d.allowed ? m.raw : P.query(this.blockedSql(d)));
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
case 'P': {
|
|
181
|
+
const { name, sql } = P.parseParse(m.payload);
|
|
182
|
+
const d = this.decide(sql, 'prepare');
|
|
183
|
+
this.toUpstream(d.allowed ? m.raw : P.buildParse(name, this.blockedSql(d)));
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
case 'F':
|
|
187
|
+
this.fatal('0A000', 'pgleash does not allow fast-path function calls');
|
|
188
|
+
return;
|
|
189
|
+
case 'X':
|
|
190
|
+
this.toUpstream(m.raw);
|
|
191
|
+
this.close();
|
|
192
|
+
return;
|
|
193
|
+
default:
|
|
194
|
+
this.toUpstream(m.raw);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
decide(sql, kind) {
|
|
198
|
+
const d = checkSql(sql, this.shared.opts.policy, this.shared.schema);
|
|
199
|
+
this.shared.opts.audit?.write({
|
|
200
|
+
session: this.pid,
|
|
201
|
+
user: this.user,
|
|
202
|
+
app: this.app,
|
|
203
|
+
kind,
|
|
204
|
+
sql: sql.length > 10_000 ? `${sql.slice(0, 10_000)}…` : sql,
|
|
205
|
+
allowed: d.allowed,
|
|
206
|
+
...(d.allowed ? {} : { rule: d.rule, reason: d.reason }),
|
|
207
|
+
});
|
|
208
|
+
if (!d.allowed) {
|
|
209
|
+
const oneLine = sql.replace(/\s+/g, ' ').trim();
|
|
210
|
+
this.shared.log(`blocked [${d.rule}] ${d.reason}: ${oneLine.length > 200 ? `${oneLine.slice(0, 200)}…` : oneLine}`);
|
|
211
|
+
}
|
|
212
|
+
return d;
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* A blocked statement is swapped for one that fails on the server with a marker in its
|
|
216
|
+
* message. The real server then produces the error, so transaction state and message
|
|
217
|
+
* order stay exactly what the client expects. pgleash rewrites that error on the way back.
|
|
218
|
+
*/
|
|
219
|
+
blockedSql(d) {
|
|
220
|
+
const id = this.nextBlockId++;
|
|
221
|
+
this.blocked.set(id, d);
|
|
222
|
+
if (this.blocked.size > 1000)
|
|
223
|
+
this.blocked.delete(this.blocked.keys().next().value);
|
|
224
|
+
return `SELECT 1 FROM "${this.shared.markerPrefix}${id}"`;
|
|
225
|
+
}
|
|
226
|
+
// ---- upstream side -----------------------------------------------------
|
|
227
|
+
onUpstreamData(chunk) {
|
|
228
|
+
this.fromUpstream.push(chunk);
|
|
229
|
+
try {
|
|
230
|
+
let m;
|
|
231
|
+
while (this.state === 'ready' && (m = this.fromUpstream.next()))
|
|
232
|
+
this.onUpstreamMessage(m);
|
|
233
|
+
}
|
|
234
|
+
catch (err) {
|
|
235
|
+
this.fatal('08P01', `bad message from the database: ${err instanceof Error ? err.message : err}`);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
onUpstreamMessage(m) {
|
|
239
|
+
switch (m.type) {
|
|
240
|
+
case 'T': {
|
|
241
|
+
this.rows = 0;
|
|
242
|
+
this.mask = null;
|
|
243
|
+
this.maskedNames = [];
|
|
244
|
+
if (this.shared.denyColumns.size > 0) {
|
|
245
|
+
const names = P.rowDescriptionNames(m.payload);
|
|
246
|
+
const mask = new Set();
|
|
247
|
+
names.forEach((n, i) => {
|
|
248
|
+
if (this.shared.denyColumns.has(n.toLowerCase())) {
|
|
249
|
+
mask.add(i);
|
|
250
|
+
this.maskedNames.push(n);
|
|
251
|
+
}
|
|
252
|
+
});
|
|
253
|
+
if (mask.size > 0)
|
|
254
|
+
this.mask = mask;
|
|
255
|
+
}
|
|
256
|
+
this.toClient(m.raw);
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
case 'D': {
|
|
260
|
+
this.rows++;
|
|
261
|
+
if (this.shared.maxRows > 0 && this.rows > this.shared.maxRows)
|
|
262
|
+
return;
|
|
263
|
+
this.toClient(this.mask ? P.maskDataRow(m.payload, this.mask) : m.raw);
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
case 'C':
|
|
267
|
+
this.endResult(m);
|
|
268
|
+
return;
|
|
269
|
+
case 'E': {
|
|
270
|
+
const fields = P.parseFields(m.payload);
|
|
271
|
+
const hit = fields.M ? this.shared.marker.exec(fields.M) : null;
|
|
272
|
+
const d = hit ? this.blocked.get(Number(hit[1])) : undefined;
|
|
273
|
+
if (hit)
|
|
274
|
+
this.blocked.delete(Number(hit[1]));
|
|
275
|
+
this.toClient(d
|
|
276
|
+
? P.errorResponse({
|
|
277
|
+
S: 'ERROR',
|
|
278
|
+
V: 'ERROR',
|
|
279
|
+
C: '42501',
|
|
280
|
+
M: `pgleash blocked this query: ${d.reason}`,
|
|
281
|
+
H: d.rule ? HINTS[d.rule] : undefined,
|
|
282
|
+
})
|
|
283
|
+
: m.raw);
|
|
284
|
+
this.rows = 0;
|
|
285
|
+
this.mask = null;
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
default:
|
|
289
|
+
this.toClient(m.raw);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
endResult(m) {
|
|
293
|
+
const { maxRows, opts } = this.shared;
|
|
294
|
+
const out = [];
|
|
295
|
+
let raw = m.raw;
|
|
296
|
+
if (maxRows > 0 && this.rows > maxRows) {
|
|
297
|
+
out.push(P.errorResponse({
|
|
298
|
+
S: 'NOTICE',
|
|
299
|
+
V: 'NOTICE',
|
|
300
|
+
C: '01000',
|
|
301
|
+
M: `pgleash: result truncated to ${maxRows} rows (the query returned ${this.rows})`,
|
|
302
|
+
H: 'Add a LIMIT or a narrower WHERE clause.',
|
|
303
|
+
}, 'N'));
|
|
304
|
+
const [tag] = P.readCString(m.payload, 0);
|
|
305
|
+
const t = /^(SELECT|FETCH) \d+$/.exec(tag);
|
|
306
|
+
if (t)
|
|
307
|
+
raw = P.message('C', P.cstr(`${t[1]} ${maxRows}`));
|
|
308
|
+
opts.audit?.write({ session: this.pid, event: 'truncated', rows: this.rows, delivered: maxRows });
|
|
309
|
+
}
|
|
310
|
+
if (this.maskedNames.length > 0 && this.rows > 0) {
|
|
311
|
+
opts.audit?.write({ session: this.pid, event: 'masked', columns: this.maskedNames });
|
|
312
|
+
}
|
|
313
|
+
out.push(raw);
|
|
314
|
+
this.toClient(out.length === 1 ? raw : Buffer.concat(out));
|
|
315
|
+
this.rows = 0;
|
|
316
|
+
this.mask = null;
|
|
317
|
+
this.maskedNames = [];
|
|
318
|
+
}
|
|
319
|
+
// ---- plumbing ----------------------------------------------------------
|
|
320
|
+
toClient(buf) {
|
|
321
|
+
if (this.client.destroyed)
|
|
322
|
+
return;
|
|
323
|
+
if (!this.client.write(buf) && this.up && !this.upPaused) {
|
|
324
|
+
this.upPaused = true;
|
|
325
|
+
this.up.pause();
|
|
326
|
+
this.client.once('drain', () => {
|
|
327
|
+
this.upPaused = false;
|
|
328
|
+
this.up?.resume();
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
toUpstream(buf) {
|
|
333
|
+
const up = this.up;
|
|
334
|
+
if (!up || up.destroyed)
|
|
335
|
+
return;
|
|
336
|
+
if (!up.write(buf) && !this.clientPaused) {
|
|
337
|
+
this.clientPaused = true;
|
|
338
|
+
this.client.pause();
|
|
339
|
+
up.once('drain', () => {
|
|
340
|
+
this.clientPaused = false;
|
|
341
|
+
this.client.resume();
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
cancel(key) {
|
|
346
|
+
if (key !== this.key || !this.upPid)
|
|
347
|
+
return;
|
|
348
|
+
sendCancel(this.shared.upstream, this.upPid, this.upKey).catch(() => { });
|
|
349
|
+
}
|
|
350
|
+
upstreamGone() {
|
|
351
|
+
if (this.state === 'closed')
|
|
352
|
+
return;
|
|
353
|
+
this.fatal('08006', 'the database closed the connection');
|
|
354
|
+
}
|
|
355
|
+
fatal(code, message) {
|
|
356
|
+
if (this.state !== 'closed' && !this.client.destroyed) {
|
|
357
|
+
this.client.end(P.errorResponse({ S: 'FATAL', V: 'FATAL', C: code, M: message }));
|
|
358
|
+
}
|
|
359
|
+
this.close();
|
|
360
|
+
}
|
|
361
|
+
close() {
|
|
362
|
+
if (this.state === 'closed')
|
|
363
|
+
return;
|
|
364
|
+
this.state = 'closed';
|
|
365
|
+
this.shared.sessions.delete(this.pid);
|
|
366
|
+
if (this.up && !this.up.destroyed)
|
|
367
|
+
this.up.end(P.terminate());
|
|
368
|
+
if (!this.client.destroyed)
|
|
369
|
+
this.client.end();
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
export async function startProxy(opts) {
|
|
373
|
+
await initPolicy();
|
|
374
|
+
const host = opts.host ?? '127.0.0.1';
|
|
375
|
+
if (opts.token === undefined && !isLoopback(host)) {
|
|
376
|
+
throw new Error('refusing to listen on a non-loopback address without a token');
|
|
377
|
+
}
|
|
378
|
+
const markerPrefix = `pgleash_blocked_${randomBytes(6).toString('hex')}_`;
|
|
379
|
+
const shared = {
|
|
380
|
+
opts,
|
|
381
|
+
upstream: parseUpstreamUrl(opts.upstream),
|
|
382
|
+
markerPrefix,
|
|
383
|
+
marker: new RegExp(`${markerPrefix}(\\d+)`),
|
|
384
|
+
sessions: new Map(),
|
|
385
|
+
maxRows: opts.maxRows ?? 1000,
|
|
386
|
+
denyColumns: new Set((opts.policy.denyColumns ?? []).map((c) => c.toLowerCase())),
|
|
387
|
+
log: opts.log ?? (() => { }),
|
|
388
|
+
};
|
|
389
|
+
// With denied columns, pgleash needs to know which tables and views contain them, so it
|
|
390
|
+
// can block SELECT * over those. Loaded now and refreshed every minute.
|
|
391
|
+
let refresh;
|
|
392
|
+
if (shared.denyColumns.size > 0) {
|
|
393
|
+
shared.schema = await loadSchema(shared.upstream, [...shared.denyColumns]);
|
|
394
|
+
refresh = setInterval(() => {
|
|
395
|
+
loadSchema(shared.upstream, [...shared.denyColumns])
|
|
396
|
+
.then((schema) => (shared.schema = schema))
|
|
397
|
+
.catch((err) => shared.log(`schema refresh failed: ${err instanceof Error ? err.message : err}`));
|
|
398
|
+
}, 60_000);
|
|
399
|
+
refresh.unref();
|
|
400
|
+
}
|
|
401
|
+
let nextPid = 1;
|
|
402
|
+
const server = net.createServer((socket) => {
|
|
403
|
+
const pid = nextPid++;
|
|
404
|
+
shared.sessions.set(pid, new Session(shared, socket, pid));
|
|
405
|
+
});
|
|
406
|
+
await new Promise((resolve, reject) => {
|
|
407
|
+
server.once('error', reject);
|
|
408
|
+
server.listen(opts.port ?? 6433, host, () => {
|
|
409
|
+
server.off('error', reject);
|
|
410
|
+
resolve();
|
|
411
|
+
});
|
|
412
|
+
});
|
|
413
|
+
const address = server.address();
|
|
414
|
+
return {
|
|
415
|
+
host,
|
|
416
|
+
port: address.port,
|
|
417
|
+
close: () => new Promise((resolve) => {
|
|
418
|
+
if (refresh)
|
|
419
|
+
clearInterval(refresh);
|
|
420
|
+
for (const s of shared.sessions.values())
|
|
421
|
+
s.close();
|
|
422
|
+
server.close(() => resolve());
|
|
423
|
+
}),
|
|
424
|
+
};
|
|
425
|
+
}
|
|
426
|
+
async function loadSchema(cfg, columns) {
|
|
427
|
+
const list = columns.map((c) => `'${c.replace(/'/g, "''")}'`).join(', ');
|
|
428
|
+
const rows = await fetchRows(cfg, `SELECT n.nspname, c.relname
|
|
429
|
+
FROM pg_catalog.pg_attribute a
|
|
430
|
+
JOIN pg_catalog.pg_class c ON c.oid = a.attrelid
|
|
431
|
+
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
|
|
432
|
+
WHERE a.attnum > 0 AND NOT a.attisdropped
|
|
433
|
+
AND c.relkind IN ('r', 'p', 'v', 'm', 'f')
|
|
434
|
+
AND lower(a.attname) IN (${list})`);
|
|
435
|
+
const sensitiveRelations = new Set();
|
|
436
|
+
for (const [schema, name] of rows) {
|
|
437
|
+
if (!schema || !name)
|
|
438
|
+
continue;
|
|
439
|
+
sensitiveRelations.add(name.toLowerCase());
|
|
440
|
+
sensitiveRelations.add(`${schema.toLowerCase()}.${name.toLowerCase()}`);
|
|
441
|
+
}
|
|
442
|
+
return { sensitiveRelations };
|
|
443
|
+
}
|
package/dist/scram.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare class ScramClient {
|
|
2
|
+
private readonly password;
|
|
3
|
+
private readonly nonce;
|
|
4
|
+
private readonly clientFirstBare;
|
|
5
|
+
private serverSignature?;
|
|
6
|
+
constructor(password: string);
|
|
7
|
+
clientFirst(): Buffer;
|
|
8
|
+
clientFinal(serverFirst: string): Buffer;
|
|
9
|
+
verifyServerFinal(serverFinal: string): void;
|
|
10
|
+
}
|
|
11
|
+
export declare function md5Password(user: string, password: string, salt: Buffer): string;
|
package/dist/scram.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// Client side of SCRAM-SHA-256 (RFC 5802 / RFC 7677), as Postgres uses it, without channel binding.
|
|
2
|
+
import { createHash, createHmac, pbkdf2Sync, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
3
|
+
const hmac = (key, data) => createHmac('sha256', key).update(data).digest();
|
|
4
|
+
const sha256 = (data) => createHash('sha256').update(data).digest();
|
|
5
|
+
function attributes(message) {
|
|
6
|
+
const out = {};
|
|
7
|
+
for (const part of message.split(',')) {
|
|
8
|
+
const eq = part.indexOf('=');
|
|
9
|
+
if (eq > 0)
|
|
10
|
+
out[part.slice(0, eq)] = part.slice(eq + 1);
|
|
11
|
+
}
|
|
12
|
+
return out;
|
|
13
|
+
}
|
|
14
|
+
export class ScramClient {
|
|
15
|
+
password;
|
|
16
|
+
nonce = randomBytes(18).toString('base64');
|
|
17
|
+
clientFirstBare;
|
|
18
|
+
serverSignature;
|
|
19
|
+
constructor(password) {
|
|
20
|
+
// Postgres runs passwords through SASLprep; for ASCII that is the identity.
|
|
21
|
+
// NFKC covers the common non-ASCII cases.
|
|
22
|
+
this.password = /^[\x00-\x7f]*$/.test(password) ? password : password.normalize('NFKC');
|
|
23
|
+
this.clientFirstBare = `n=*,r=${this.nonce}`;
|
|
24
|
+
}
|
|
25
|
+
clientFirst() {
|
|
26
|
+
return Buffer.from(`n,,${this.clientFirstBare}`);
|
|
27
|
+
}
|
|
28
|
+
clientFinal(serverFirst) {
|
|
29
|
+
const { r, s, i } = attributes(serverFirst);
|
|
30
|
+
if (!r || !s || !i || !r.startsWith(this.nonce) || r.length === this.nonce.length) {
|
|
31
|
+
throw new Error('invalid SCRAM server-first message');
|
|
32
|
+
}
|
|
33
|
+
const salted = pbkdf2Sync(this.password, Buffer.from(s, 'base64'), Number(i), 32, 'sha256');
|
|
34
|
+
const clientKey = hmac(salted, 'Client Key');
|
|
35
|
+
const withoutProof = `c=biws,r=${r}`;
|
|
36
|
+
const authMessage = `${this.clientFirstBare},${serverFirst},${withoutProof}`;
|
|
37
|
+
const signature = hmac(sha256(clientKey), authMessage);
|
|
38
|
+
const proof = Buffer.alloc(clientKey.length);
|
|
39
|
+
for (let k = 0; k < proof.length; k++)
|
|
40
|
+
proof[k] = clientKey[k] ^ signature[k];
|
|
41
|
+
this.serverSignature = hmac(hmac(salted, 'Server Key'), authMessage);
|
|
42
|
+
return Buffer.from(`${withoutProof},p=${proof.toString('base64')}`);
|
|
43
|
+
}
|
|
44
|
+
verifyServerFinal(serverFinal) {
|
|
45
|
+
const { v } = attributes(serverFinal);
|
|
46
|
+
const got = Buffer.from(v ?? '', 'base64');
|
|
47
|
+
if (!this.serverSignature || got.length !== this.serverSignature.length || !timingSafeEqual(got, this.serverSignature)) {
|
|
48
|
+
throw new Error('SCRAM server signature did not match');
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
export function md5Password(user, password, salt) {
|
|
53
|
+
const inner = createHash('md5').update(password + user).digest('hex');
|
|
54
|
+
return `md5${createHash('md5').update(Buffer.concat([Buffer.from(inner), salt])).digest('hex')}`;
|
|
55
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import net from 'node:net';
|
|
2
|
+
export type SslMode = 'disable' | 'prefer' | 'require' | 'verify-ca' | 'verify-full';
|
|
3
|
+
export interface UpstreamConfig {
|
|
4
|
+
host: string;
|
|
5
|
+
port: number;
|
|
6
|
+
user: string;
|
|
7
|
+
password?: string;
|
|
8
|
+
database: string;
|
|
9
|
+
sslmode: SslMode;
|
|
10
|
+
ca?: Buffer;
|
|
11
|
+
}
|
|
12
|
+
export declare class UpstreamError extends Error {
|
|
13
|
+
readonly code: string;
|
|
14
|
+
constructor(message: string, code?: string);
|
|
15
|
+
}
|
|
16
|
+
/** Parses postgres://user:password@host:port/database?sslmode=require&sslrootcert=/path/ca.pem */
|
|
17
|
+
export declare function parseUpstreamUrl(url: string): UpstreamConfig;
|
|
18
|
+
export interface UpstreamSession {
|
|
19
|
+
socket: net.Socket;
|
|
20
|
+
/** ParameterStatus values reported by the server, after the setup query ran. */
|
|
21
|
+
params: Map<string, string>;
|
|
22
|
+
pid: number;
|
|
23
|
+
key: number;
|
|
24
|
+
/** Bytes already received after the handshake finished. */
|
|
25
|
+
pending: Buffer;
|
|
26
|
+
}
|
|
27
|
+
export interface ConnectOptions {
|
|
28
|
+
startupParams?: Record<string, string>;
|
|
29
|
+
/** Run once after login, e.g. "SET default_transaction_read_only = on". */
|
|
30
|
+
setupSql?: string;
|
|
31
|
+
timeoutMs?: number;
|
|
32
|
+
}
|
|
33
|
+
export declare function connectUpstream(cfg: UpstreamConfig, opts?: ConnectOptions): Promise<UpstreamSession>;
|
|
34
|
+
/** Sends a CancelRequest for an upstream backend, over a fresh connection. */
|
|
35
|
+
export declare function sendCancel(cfg: UpstreamConfig, pid: number, key: number): Promise<void>;
|
|
36
|
+
/** Runs one query on a fresh connection and returns its rows as text. Used for schema lookups. */
|
|
37
|
+
export declare function fetchRows(cfg: UpstreamConfig, sql: string): Promise<(string | null)[][]>;
|