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/policy.d.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export type Mode = 'read-only' | 'guarded-write';
|
|
2
|
+
export interface PolicyOptions {
|
|
3
|
+
mode: Mode;
|
|
4
|
+
/** Allow more than one statement in a single query string. Off by default. */
|
|
5
|
+
allowMultiStatement?: boolean;
|
|
6
|
+
/** Tables the agent may not touch: "secrets" (any schema) or "public.secrets". */
|
|
7
|
+
denyTables?: string[];
|
|
8
|
+
/** Columns the agent may not read, by name, e.g. "password_hash". */
|
|
9
|
+
denyColumns?: string[];
|
|
10
|
+
/** Extra functions to block. A trailing * blocks every name with that prefix. */
|
|
11
|
+
denyFunctions?: string[];
|
|
12
|
+
/** Extra settings the agent may change with SET. */
|
|
13
|
+
allowSettings?: string[];
|
|
14
|
+
}
|
|
15
|
+
export type Rule = 'parse-error' | 'multi-statement' | 'statement-type' | 'select-into' | 'row-lock' | 'read-write-transaction' | 'setting' | 'unbounded-write' | 'deny-function' | 'deny-table' | 'deny-column';
|
|
16
|
+
/**
|
|
17
|
+
* What pgleash knows about the live schema. The proxy loads it so that SELECT * can be
|
|
18
|
+
* blocked when it would include an off-limits column.
|
|
19
|
+
*/
|
|
20
|
+
export interface SchemaInfo {
|
|
21
|
+
/** Relations (lowercase "name" and "schema.name") that have at least one denied column. */
|
|
22
|
+
sensitiveRelations: Set<string>;
|
|
23
|
+
}
|
|
24
|
+
export interface Decision {
|
|
25
|
+
allowed: boolean;
|
|
26
|
+
rule?: Rule;
|
|
27
|
+
reason?: string;
|
|
28
|
+
/** Top-level statement types, e.g. ["SelectStmt"]. */
|
|
29
|
+
statements: string[];
|
|
30
|
+
}
|
|
31
|
+
/** Loads the parser. Call once before checkSql. */
|
|
32
|
+
export declare function initPolicy(): Promise<void>;
|
|
33
|
+
/**
|
|
34
|
+
* Decides whether one query string may run. Synchronous; call initPolicy() first.
|
|
35
|
+
* An empty string is allowed (Postgres answers it with EmptyQueryResponse).
|
|
36
|
+
*/
|
|
37
|
+
export declare function checkSql(sql: string, opts: PolicyOptions, schema?: SchemaInfo): Decision;
|
package/dist/policy.js
ADDED
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
// The SQL policy. Every statement is parsed with Postgres's own parser (libpg-query),
|
|
2
|
+
// so pgleash sees the same tree the server will, and anything it cannot parse is blocked.
|
|
3
|
+
import { loadModule, parseSync } from 'libpg-query';
|
|
4
|
+
let loading;
|
|
5
|
+
/** Loads the parser. Call once before checkSql. */
|
|
6
|
+
export function initPolicy() {
|
|
7
|
+
loading ??= loadModule();
|
|
8
|
+
return loading;
|
|
9
|
+
}
|
|
10
|
+
const READ_STATEMENTS = new Set([
|
|
11
|
+
'SelectStmt',
|
|
12
|
+
'ExplainStmt',
|
|
13
|
+
'VariableShowStmt',
|
|
14
|
+
'VariableSetStmt',
|
|
15
|
+
'TransactionStmt',
|
|
16
|
+
'DeclareCursorStmt',
|
|
17
|
+
'FetchStmt',
|
|
18
|
+
'ClosePortalStmt',
|
|
19
|
+
'PrepareStmt',
|
|
20
|
+
'ExecuteStmt',
|
|
21
|
+
'DeallocateStmt',
|
|
22
|
+
'ListenStmt',
|
|
23
|
+
'UnlistenStmt',
|
|
24
|
+
'DiscardStmt',
|
|
25
|
+
]);
|
|
26
|
+
const WRITE_STATEMENTS = new Set([...READ_STATEMENTS, 'InsertStmt', 'UpdateStmt', 'DeleteStmt']);
|
|
27
|
+
// Settings an agent may change. Everything else is blocked, which covers
|
|
28
|
+
// default_transaction_read_only, statement_timeout, role and session_authorization.
|
|
29
|
+
// client_encoding and standard_conforming_strings stay blocked on purpose: either one would
|
|
30
|
+
// let the server read a string literal differently from the parser pgleash checks with.
|
|
31
|
+
const SAFE_SETTINGS = [
|
|
32
|
+
'application_name',
|
|
33
|
+
'search_path',
|
|
34
|
+
'timezone',
|
|
35
|
+
'datestyle',
|
|
36
|
+
'intervalstyle',
|
|
37
|
+
'client_min_messages',
|
|
38
|
+
'extra_float_digits',
|
|
39
|
+
'bytea_output',
|
|
40
|
+
'lc_messages',
|
|
41
|
+
'lc_monetary',
|
|
42
|
+
'lc_numeric',
|
|
43
|
+
'lc_time',
|
|
44
|
+
];
|
|
45
|
+
// Functions that change server or session state, read server files, open other
|
|
46
|
+
// connections, or run SQL passed in as a string (which would skip these checks).
|
|
47
|
+
const DENIED_FUNCTIONS = [
|
|
48
|
+
'set_config',
|
|
49
|
+
'pg_terminate_backend',
|
|
50
|
+
'pg_cancel_backend',
|
|
51
|
+
'pg_reload_conf',
|
|
52
|
+
'pg_rotate_logfile*',
|
|
53
|
+
'pg_switch_wal',
|
|
54
|
+
'pg_switch_xlog',
|
|
55
|
+
'pg_promote',
|
|
56
|
+
'pg_create_restore_point',
|
|
57
|
+
'pg_log_backend_memory_contexts',
|
|
58
|
+
'pg_read_file',
|
|
59
|
+
'pg_read_binary_file',
|
|
60
|
+
'pg_ls_*',
|
|
61
|
+
'pg_stat_file',
|
|
62
|
+
'pg_file_*',
|
|
63
|
+
'lo_*',
|
|
64
|
+
'loread',
|
|
65
|
+
'lowrite',
|
|
66
|
+
'dblink*',
|
|
67
|
+
'pg_sleep*',
|
|
68
|
+
'pg_advisory*',
|
|
69
|
+
'pg_try_advisory*',
|
|
70
|
+
'query_to_xml*',
|
|
71
|
+
'cursor_to_xml*',
|
|
72
|
+
'table_to_xml*',
|
|
73
|
+
'schema_to_xml*',
|
|
74
|
+
'database_to_xml*',
|
|
75
|
+
'pg_notify',
|
|
76
|
+
'pg_logical_emit_message',
|
|
77
|
+
'pg_create_physical_replication_slot',
|
|
78
|
+
'pg_create_logical_replication_slot',
|
|
79
|
+
'pg_drop_replication_slot',
|
|
80
|
+
'pg_copy_*',
|
|
81
|
+
'pg_replication_origin_*',
|
|
82
|
+
'pg_replication_slot_advance',
|
|
83
|
+
'pg_logical_slot_*',
|
|
84
|
+
'pg_import_system_collations',
|
|
85
|
+
'pg_stat_reset*',
|
|
86
|
+
'pg_stat_statements_reset',
|
|
87
|
+
'pg_backup_*',
|
|
88
|
+
'pg_start_backup',
|
|
89
|
+
'pg_stop_backup',
|
|
90
|
+
'pg_wal_replay_*',
|
|
91
|
+
'setval',
|
|
92
|
+
];
|
|
93
|
+
// Read-only mode also blocks nextval, which writes to a sequence.
|
|
94
|
+
const DENIED_IN_READ_ONLY = ['nextval'];
|
|
95
|
+
const SQL_NAMES = {
|
|
96
|
+
InsertStmt: 'INSERT',
|
|
97
|
+
UpdateStmt: 'UPDATE',
|
|
98
|
+
DeleteStmt: 'DELETE',
|
|
99
|
+
MergeStmt: 'MERGE',
|
|
100
|
+
DropStmt: 'DROP',
|
|
101
|
+
TruncateStmt: 'TRUNCATE',
|
|
102
|
+
AlterTableStmt: 'ALTER TABLE',
|
|
103
|
+
CreateStmt: 'CREATE TABLE',
|
|
104
|
+
CreateTableAsStmt: 'CREATE TABLE AS',
|
|
105
|
+
IndexStmt: 'CREATE INDEX',
|
|
106
|
+
CopyStmt: 'COPY',
|
|
107
|
+
DoStmt: 'DO',
|
|
108
|
+
CallStmt: 'CALL',
|
|
109
|
+
GrantStmt: 'GRANT/REVOKE',
|
|
110
|
+
GrantRoleStmt: 'GRANT/REVOKE',
|
|
111
|
+
VacuumStmt: 'VACUUM/ANALYZE',
|
|
112
|
+
LockStmt: 'LOCK',
|
|
113
|
+
AlterSystemStmt: 'ALTER SYSTEM',
|
|
114
|
+
CreateFunctionStmt: 'CREATE FUNCTION',
|
|
115
|
+
CreateExtensionStmt: 'CREATE EXTENSION',
|
|
116
|
+
LoadStmt: 'LOAD',
|
|
117
|
+
ReindexStmt: 'REINDEX',
|
|
118
|
+
ClusterStmt: 'CLUSTER',
|
|
119
|
+
CheckPointStmt: 'CHECKPOINT',
|
|
120
|
+
RefreshMatViewStmt: 'REFRESH MATERIALIZED VIEW',
|
|
121
|
+
RenameStmt: 'ALTER ... RENAME',
|
|
122
|
+
CreateRoleStmt: 'CREATE ROLE',
|
|
123
|
+
AlterRoleStmt: 'ALTER ROLE',
|
|
124
|
+
DropRoleStmt: 'DROP ROLE',
|
|
125
|
+
CreateSchemaStmt: 'CREATE SCHEMA',
|
|
126
|
+
ViewStmt: 'CREATE VIEW',
|
|
127
|
+
CommentStmt: 'COMMENT',
|
|
128
|
+
NotifyStmt: 'NOTIFY',
|
|
129
|
+
CreateTrigStmt: 'CREATE TRIGGER',
|
|
130
|
+
RuleStmt: 'CREATE RULE',
|
|
131
|
+
AlterOwnerStmt: 'ALTER ... OWNER',
|
|
132
|
+
CreatedbStmt: 'CREATE DATABASE',
|
|
133
|
+
DropdbStmt: 'DROP DATABASE',
|
|
134
|
+
CreateSeqStmt: 'CREATE SEQUENCE',
|
|
135
|
+
AlterSeqStmt: 'ALTER SEQUENCE',
|
|
136
|
+
SecLabelStmt: 'SECURITY LABEL',
|
|
137
|
+
};
|
|
138
|
+
function sqlName(type) {
|
|
139
|
+
return SQL_NAMES[type] ?? type.replace(/Stmt$/, '').replace(/([a-z])([A-Z])/g, '$1 $2').toUpperCase();
|
|
140
|
+
}
|
|
141
|
+
function nameMatcher(names) {
|
|
142
|
+
const exact = new Set();
|
|
143
|
+
const prefixes = [];
|
|
144
|
+
for (const raw of names) {
|
|
145
|
+
const n = raw.trim().toLowerCase();
|
|
146
|
+
if (!n)
|
|
147
|
+
continue;
|
|
148
|
+
if (n.endsWith('*'))
|
|
149
|
+
prefixes.push(n.slice(0, -1));
|
|
150
|
+
else
|
|
151
|
+
exact.add(n);
|
|
152
|
+
}
|
|
153
|
+
return (name) => exact.has(name) || prefixes.some((p) => name.startsWith(p));
|
|
154
|
+
}
|
|
155
|
+
const compiledCache = new WeakMap();
|
|
156
|
+
function compile(opts) {
|
|
157
|
+
const cached = compiledCache.get(opts);
|
|
158
|
+
if (cached)
|
|
159
|
+
return cached;
|
|
160
|
+
const functions = [...DENIED_FUNCTIONS, ...(opts.denyFunctions ?? [])];
|
|
161
|
+
if (opts.mode === 'read-only')
|
|
162
|
+
functions.push(...DENIED_IN_READ_ONLY);
|
|
163
|
+
const compiled = {
|
|
164
|
+
mode: opts.mode,
|
|
165
|
+
allowMultiStatement: opts.allowMultiStatement ?? false,
|
|
166
|
+
allowed: opts.mode === 'guarded-write' ? WRITE_STATEMENTS : READ_STATEMENTS,
|
|
167
|
+
isDeniedFunction: nameMatcher(functions),
|
|
168
|
+
deniedTables: (opts.denyTables ?? []).map((t) => {
|
|
169
|
+
const parts = t.trim().toLowerCase().split('.');
|
|
170
|
+
return parts.length > 1 ? { schema: parts[0], name: parts.slice(1).join('.') } : { name: parts[0] };
|
|
171
|
+
}),
|
|
172
|
+
deniedColumns: new Set((opts.denyColumns ?? []).map((c) => c.trim().toLowerCase()).filter(Boolean)),
|
|
173
|
+
settings: new Set([...SAFE_SETTINGS, ...(opts.allowSettings ?? [])].map((s) => s.toLowerCase())),
|
|
174
|
+
};
|
|
175
|
+
compiledCache.set(opts, compiled);
|
|
176
|
+
return compiled;
|
|
177
|
+
}
|
|
178
|
+
class Blocked extends Error {
|
|
179
|
+
rule;
|
|
180
|
+
constructor(rule, reason) {
|
|
181
|
+
super(reason);
|
|
182
|
+
this.rule = rule;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
/** Walks every object in the tree, calling visit(key, value) for each property. */
|
|
186
|
+
function walk(node, visit) {
|
|
187
|
+
if (Array.isArray(node)) {
|
|
188
|
+
for (const item of node)
|
|
189
|
+
walk(item, visit);
|
|
190
|
+
}
|
|
191
|
+
else if (node && typeof node === 'object') {
|
|
192
|
+
for (const [key, value] of Object.entries(node)) {
|
|
193
|
+
visit(key, value);
|
|
194
|
+
walk(value, visit);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
function stringField(field) {
|
|
199
|
+
const s = field?.String?.sval;
|
|
200
|
+
return typeof s === 'string' ? s : undefined;
|
|
201
|
+
}
|
|
202
|
+
function hasColumnRef(node) {
|
|
203
|
+
let found = false;
|
|
204
|
+
walk(node, (key) => {
|
|
205
|
+
if (key === 'ColumnRef' || key === 'CurrentOfExpr')
|
|
206
|
+
found = true;
|
|
207
|
+
});
|
|
208
|
+
return found;
|
|
209
|
+
}
|
|
210
|
+
function isFalse(arg) {
|
|
211
|
+
const c = arg?.A_Const;
|
|
212
|
+
if (!c)
|
|
213
|
+
return false;
|
|
214
|
+
if (c.ival)
|
|
215
|
+
return !c.ival.ival;
|
|
216
|
+
if (c.boolval)
|
|
217
|
+
return !c.boolval.boolval;
|
|
218
|
+
if (c.sval)
|
|
219
|
+
return ['off', 'false', 'no', '0'].includes(String(c.sval.sval).toLowerCase());
|
|
220
|
+
return false;
|
|
221
|
+
}
|
|
222
|
+
function checkStatement(type, stmt, c) {
|
|
223
|
+
if (!c.allowed.has(type)) {
|
|
224
|
+
throw new Blocked('statement-type', `${sqlName(type)} is not allowed in ${c.mode} mode`);
|
|
225
|
+
}
|
|
226
|
+
switch (type) {
|
|
227
|
+
case 'SelectStmt':
|
|
228
|
+
if (stmt.intoClause)
|
|
229
|
+
throw new Blocked('select-into', 'SELECT ... INTO creates a table');
|
|
230
|
+
if (stmt.lockingClause && c.mode === 'read-only') {
|
|
231
|
+
throw new Blocked('row-lock', 'SELECT ... FOR UPDATE/SHARE takes row locks');
|
|
232
|
+
}
|
|
233
|
+
break;
|
|
234
|
+
case 'VariableSetStmt': {
|
|
235
|
+
const name = String(stmt.name ?? '').toLowerCase();
|
|
236
|
+
if (stmt.kind === 'VAR_RESET_ALL')
|
|
237
|
+
throw new Blocked('setting', 'RESET ALL would undo the session guards');
|
|
238
|
+
if (!c.settings.has(name)) {
|
|
239
|
+
throw new Blocked('setting', `changing "${stmt.name ?? 'this setting'}" is not allowed`);
|
|
240
|
+
}
|
|
241
|
+
break;
|
|
242
|
+
}
|
|
243
|
+
case 'TransactionStmt':
|
|
244
|
+
if (['TRANS_STMT_PREPARE', 'TRANS_STMT_COMMIT_PREPARED', 'TRANS_STMT_ROLLBACK_PREPARED'].includes(stmt.kind)) {
|
|
245
|
+
throw new Blocked('statement-type', 'prepared (two-phase) transactions are not allowed');
|
|
246
|
+
}
|
|
247
|
+
if (c.mode === 'read-only') {
|
|
248
|
+
for (const opt of stmt.options ?? []) {
|
|
249
|
+
const def = opt.DefElem;
|
|
250
|
+
if (def?.defname === 'transaction_read_only' && isFalse(def.arg)) {
|
|
251
|
+
throw new Blocked('read-write-transaction', 'READ WRITE transactions are not allowed in read-only mode');
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
break;
|
|
256
|
+
case 'DiscardStmt':
|
|
257
|
+
if (stmt.target === 'DISCARD_ALL')
|
|
258
|
+
throw new Blocked('setting', 'DISCARD ALL would undo the session guards');
|
|
259
|
+
break;
|
|
260
|
+
case 'UpdateStmt':
|
|
261
|
+
case 'DeleteStmt':
|
|
262
|
+
if (!stmt.whereClause || !hasColumnRef(stmt.whereClause)) {
|
|
263
|
+
throw new Blocked('unbounded-write', `${sqlName(type)} without a WHERE clause on a column would touch every row`);
|
|
264
|
+
}
|
|
265
|
+
break;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
function checkTree(root, c, schema) {
|
|
269
|
+
// Tables and views in the query, and what each alias points at. Used to resolve u.* and
|
|
270
|
+
// whole-row references like SELECT u FROM users u.
|
|
271
|
+
const relations = [];
|
|
272
|
+
const aliases = new Map();
|
|
273
|
+
if (c.deniedColumns.size > 0) {
|
|
274
|
+
// A CTE's own columns are checked inside its query, so a reference to it is not a table.
|
|
275
|
+
const ctes = new Set();
|
|
276
|
+
walk(root, (key, value) => {
|
|
277
|
+
if (key === 'CommonTableExpr' && typeof value?.ctename === 'string')
|
|
278
|
+
ctes.add(value.ctename.toLowerCase());
|
|
279
|
+
});
|
|
280
|
+
walk(root, (_key, value) => {
|
|
281
|
+
if (!value || typeof value !== 'object' || typeof value.relname !== 'string')
|
|
282
|
+
return;
|
|
283
|
+
if (!value.schemaname && ctes.has(value.relname.toLowerCase()))
|
|
284
|
+
return;
|
|
285
|
+
const rel = {
|
|
286
|
+
name: value.relname.toLowerCase(),
|
|
287
|
+
schema: typeof value.schemaname === 'string' ? value.schemaname.toLowerCase() : undefined,
|
|
288
|
+
};
|
|
289
|
+
relations.push(rel);
|
|
290
|
+
aliases.set(rel.name, rel);
|
|
291
|
+
if (typeof value.alias?.aliasname === 'string')
|
|
292
|
+
aliases.set(value.alias.aliasname.toLowerCase(), rel);
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
// Without schema info (pgleash check), a table might hold a denied column, so assume it does
|
|
296
|
+
// for whole-row references. SELECT * is only blocked when the schema says so.
|
|
297
|
+
const isSensitive = (rel) => !!schema && schema.sensitiveRelations.has(rel.schema ? `${rel.schema}.${rel.name}` : rel.name);
|
|
298
|
+
walk(root, (key, value) => {
|
|
299
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
300
|
+
return;
|
|
301
|
+
if (/^[A-Z]\w*Stmt$/.test(key))
|
|
302
|
+
checkStatement(key, value, c);
|
|
303
|
+
if (typeof value.relname === 'string' && c.deniedTables.length > 0) {
|
|
304
|
+
const name = value.relname.toLowerCase();
|
|
305
|
+
const schemaName = typeof value.schemaname === 'string' ? value.schemaname.toLowerCase() : undefined;
|
|
306
|
+
for (const t of c.deniedTables) {
|
|
307
|
+
if (t.name === name && (!t.schema || t.schema === schemaName)) {
|
|
308
|
+
throw new Blocked('deny-table', `table "${schemaName ? `${schemaName}.` : ''}${value.relname}" is off limits`);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
if (key === 'FuncCall') {
|
|
313
|
+
const parts = value.funcname ?? [];
|
|
314
|
+
const name = stringField(parts[parts.length - 1])?.toLowerCase() ?? '';
|
|
315
|
+
if (c.isDeniedFunction(name))
|
|
316
|
+
throw new Blocked('deny-function', `function ${name}() is not allowed`);
|
|
317
|
+
if (c.deniedColumns.size > 0) {
|
|
318
|
+
walk(value.args, (k, v) => {
|
|
319
|
+
if (k === 'ColumnRef' && (v.fields ?? []).some((f) => f.A_Star)) {
|
|
320
|
+
throw new Blocked('deny-column', `passing a whole row (*) to ${name}() could expose a denied column`);
|
|
321
|
+
}
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
if (key === 'ColumnRef' && c.deniedColumns.size > 0) {
|
|
326
|
+
const fields = value.fields ?? [];
|
|
327
|
+
const last = stringField(fields[fields.length - 1])?.toLowerCase();
|
|
328
|
+
if (last && c.deniedColumns.has(last))
|
|
329
|
+
throw new Blocked('deny-column', `column "${last}" is off limits`);
|
|
330
|
+
const rowRel = fields.length === 1 && last ? aliases.get(last) : undefined;
|
|
331
|
+
if (rowRel && (!schema || isSensitive(rowRel))) {
|
|
332
|
+
throw new Blocked('deny-column', `whole-row reference "${last}" could expose a denied column`);
|
|
333
|
+
}
|
|
334
|
+
if (fields[fields.length - 1]?.A_Star) {
|
|
335
|
+
const qualifier = stringField(fields[fields.length - 2])?.toLowerCase();
|
|
336
|
+
const targets = qualifier ? [aliases.get(qualifier) ?? { name: qualifier }] : relations;
|
|
337
|
+
const hit = targets.find(isSensitive);
|
|
338
|
+
if (hit) {
|
|
339
|
+
throw new Blocked('deny-column', `SELECT * on "${hit.name}" would include an off-limits column; list the columns you need`);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* Decides whether one query string may run. Synchronous; call initPolicy() first.
|
|
347
|
+
* An empty string is allowed (Postgres answers it with EmptyQueryResponse).
|
|
348
|
+
*/
|
|
349
|
+
export function checkSql(sql, opts, schema) {
|
|
350
|
+
const c = compile(opts);
|
|
351
|
+
if (sql.trim() === '')
|
|
352
|
+
return { allowed: true, statements: [] };
|
|
353
|
+
let stmts;
|
|
354
|
+
try {
|
|
355
|
+
stmts = (parseSync(sql).stmts ?? []).map((s) => s.stmt ?? {});
|
|
356
|
+
}
|
|
357
|
+
catch (err) {
|
|
358
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
359
|
+
return { allowed: false, rule: 'parse-error', reason: `could not parse the query (${message})`, statements: [] };
|
|
360
|
+
}
|
|
361
|
+
const statements = stmts.map((s) => Object.keys(s)[0] ?? 'Unknown');
|
|
362
|
+
if (stmts.length > 1 && !c.allowMultiStatement) {
|
|
363
|
+
return {
|
|
364
|
+
allowed: false,
|
|
365
|
+
rule: 'multi-statement',
|
|
366
|
+
reason: `send one statement at a time (this query has ${stmts.length})`,
|
|
367
|
+
statements,
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
try {
|
|
371
|
+
for (const stmt of stmts)
|
|
372
|
+
checkTree(stmt, c, schema);
|
|
373
|
+
}
|
|
374
|
+
catch (err) {
|
|
375
|
+
if (err instanceof Blocked)
|
|
376
|
+
return { allowed: false, rule: err.rule, reason: err.message, statements };
|
|
377
|
+
throw err;
|
|
378
|
+
}
|
|
379
|
+
return { allowed: true, statements };
|
|
380
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
export declare const PROTOCOL_3_0 = 196608;
|
|
2
|
+
export declare const SSL_REQUEST = 80877103;
|
|
3
|
+
export declare const GSSENC_REQUEST = 80877104;
|
|
4
|
+
export declare const CANCEL_REQUEST = 80877102;
|
|
5
|
+
export declare class ProtocolError extends Error {
|
|
6
|
+
}
|
|
7
|
+
export interface Message {
|
|
8
|
+
/** One-letter message type, or '' for untyped startup-phase packets. */
|
|
9
|
+
type: string;
|
|
10
|
+
payload: Buffer;
|
|
11
|
+
/** The whole message as received, for forwarding unchanged. */
|
|
12
|
+
raw: Buffer;
|
|
13
|
+
}
|
|
14
|
+
/** Splits a byte stream into messages. Set `startup` while reading untyped startup packets. */
|
|
15
|
+
export declare class MessageReader {
|
|
16
|
+
startup: boolean;
|
|
17
|
+
private buf;
|
|
18
|
+
private readonly maxLength;
|
|
19
|
+
constructor(startup?: boolean, maxLength?: number);
|
|
20
|
+
push(chunk: Buffer): void;
|
|
21
|
+
next(): Message | null;
|
|
22
|
+
/** Bytes received but not yet returned as a message. */
|
|
23
|
+
take(): Buffer;
|
|
24
|
+
}
|
|
25
|
+
export declare function int32(n: number): Buffer;
|
|
26
|
+
export declare function int16(n: number): Buffer;
|
|
27
|
+
export declare function cstr(s: string): Buffer;
|
|
28
|
+
export declare function readCString(buf: Buffer, offset: number): [string, number];
|
|
29
|
+
export declare function message(type: string, payload?: Buffer): Buffer;
|
|
30
|
+
export declare function parseStartup(payload: Buffer): {
|
|
31
|
+
code: number;
|
|
32
|
+
params: Record<string, string>;
|
|
33
|
+
};
|
|
34
|
+
export declare function startupMessage(params: Record<string, string>): Buffer;
|
|
35
|
+
export declare const sslRequest: () => Buffer;
|
|
36
|
+
export declare const cancelRequest: (pid: number, key: number) => Buffer;
|
|
37
|
+
export declare const authOk: () => Buffer;
|
|
38
|
+
export declare const authCleartextPassword: () => Buffer;
|
|
39
|
+
export declare const parameterStatus: (k: string, v: string) => Buffer;
|
|
40
|
+
export declare const backendKeyData: (pid: number, key: number) => Buffer;
|
|
41
|
+
export declare const readyForQuery: (status?: string) => Buffer;
|
|
42
|
+
export declare function negotiateProtocolVersion(newestMinor: number, unsupported: string[]): Buffer;
|
|
43
|
+
export interface ErrorFields {
|
|
44
|
+
S: string;
|
|
45
|
+
V?: string;
|
|
46
|
+
C: string;
|
|
47
|
+
M: string;
|
|
48
|
+
D?: string;
|
|
49
|
+
H?: string;
|
|
50
|
+
}
|
|
51
|
+
/** ErrorResponse ('E') or NoticeResponse ('N'). */
|
|
52
|
+
export declare function errorResponse(fields: ErrorFields, type?: 'E' | 'N'): Buffer;
|
|
53
|
+
export declare function parseFields(payload: Buffer): Record<string, string>;
|
|
54
|
+
export declare const query: (sql: string) => Buffer;
|
|
55
|
+
export declare const terminate: () => Buffer;
|
|
56
|
+
export declare const passwordMessage: (s: string) => Buffer;
|
|
57
|
+
export declare const saslInitialResponse: (mechanism: string, data: Buffer) => Buffer;
|
|
58
|
+
export declare const saslResponse: (data: Buffer) => Buffer;
|
|
59
|
+
export declare function parseParse(payload: Buffer): {
|
|
60
|
+
name: string;
|
|
61
|
+
sql: string;
|
|
62
|
+
};
|
|
63
|
+
export declare function buildParse(name: string, sql: string): Buffer;
|
|
64
|
+
export declare function rowDescriptionNames(payload: Buffer): string[];
|
|
65
|
+
/** Replaces the masked columns of a DataRow with NULL. */
|
|
66
|
+
export declare function maskDataRow(payload: Buffer, mask: Set<number>): Buffer;
|
package/dist/protocol.js
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
// Postgres wire protocol (v3) framing and the few messages pgleash builds or rewrites.
|
|
2
|
+
// Reference: https://www.postgresql.org/docs/current/protocol-message-formats.html
|
|
3
|
+
export const PROTOCOL_3_0 = 196608;
|
|
4
|
+
export const SSL_REQUEST = 80877103;
|
|
5
|
+
export const GSSENC_REQUEST = 80877104;
|
|
6
|
+
export const CANCEL_REQUEST = 80877102;
|
|
7
|
+
export class ProtocolError extends Error {
|
|
8
|
+
}
|
|
9
|
+
/** Splits a byte stream into messages. Set `startup` while reading untyped startup packets. */
|
|
10
|
+
export class MessageReader {
|
|
11
|
+
startup;
|
|
12
|
+
buf = Buffer.alloc(0);
|
|
13
|
+
maxLength;
|
|
14
|
+
constructor(startup = false, maxLength = 256 * 1024 * 1024) {
|
|
15
|
+
this.startup = startup;
|
|
16
|
+
this.maxLength = maxLength;
|
|
17
|
+
}
|
|
18
|
+
push(chunk) {
|
|
19
|
+
this.buf = this.buf.length === 0 ? chunk : Buffer.concat([this.buf, chunk]);
|
|
20
|
+
}
|
|
21
|
+
next() {
|
|
22
|
+
if (this.startup) {
|
|
23
|
+
if (this.buf.length < 4)
|
|
24
|
+
return null;
|
|
25
|
+
const len = this.buf.readUInt32BE(0);
|
|
26
|
+
if (len < 8 || len > 10_000)
|
|
27
|
+
throw new ProtocolError(`invalid startup packet length ${len}`);
|
|
28
|
+
if (this.buf.length < len)
|
|
29
|
+
return null;
|
|
30
|
+
const raw = this.buf.subarray(0, len);
|
|
31
|
+
this.buf = this.buf.subarray(len);
|
|
32
|
+
return { type: '', payload: raw.subarray(4), raw };
|
|
33
|
+
}
|
|
34
|
+
if (this.buf.length < 5)
|
|
35
|
+
return null;
|
|
36
|
+
const len = this.buf.readUInt32BE(1);
|
|
37
|
+
if (len < 4 || len > this.maxLength)
|
|
38
|
+
throw new ProtocolError(`invalid message length ${len}`);
|
|
39
|
+
if (this.buf.length < len + 1)
|
|
40
|
+
return null;
|
|
41
|
+
const raw = this.buf.subarray(0, len + 1);
|
|
42
|
+
this.buf = this.buf.subarray(len + 1);
|
|
43
|
+
return { type: String.fromCharCode(raw[0]), payload: raw.subarray(5), raw };
|
|
44
|
+
}
|
|
45
|
+
/** Bytes received but not yet returned as a message. */
|
|
46
|
+
take() {
|
|
47
|
+
const rest = this.buf;
|
|
48
|
+
this.buf = Buffer.alloc(0);
|
|
49
|
+
return rest;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
export function int32(n) {
|
|
53
|
+
const b = Buffer.alloc(4);
|
|
54
|
+
b.writeInt32BE(n);
|
|
55
|
+
return b;
|
|
56
|
+
}
|
|
57
|
+
export function int16(n) {
|
|
58
|
+
const b = Buffer.alloc(2);
|
|
59
|
+
b.writeInt16BE(n);
|
|
60
|
+
return b;
|
|
61
|
+
}
|
|
62
|
+
export function cstr(s) {
|
|
63
|
+
return Buffer.from(`${s}\0`, 'utf8');
|
|
64
|
+
}
|
|
65
|
+
export function readCString(buf, offset) {
|
|
66
|
+
const end = buf.indexOf(0, offset);
|
|
67
|
+
if (end < 0)
|
|
68
|
+
throw new ProtocolError('unterminated string in message');
|
|
69
|
+
return [buf.toString('utf8', offset, end), end + 1];
|
|
70
|
+
}
|
|
71
|
+
export function message(type, payload = Buffer.alloc(0)) {
|
|
72
|
+
const out = Buffer.allocUnsafe(5 + payload.length);
|
|
73
|
+
out[0] = type.charCodeAt(0);
|
|
74
|
+
out.writeUInt32BE(payload.length + 4, 1);
|
|
75
|
+
payload.copy(out, 5);
|
|
76
|
+
return out;
|
|
77
|
+
}
|
|
78
|
+
// ---- startup phase -------------------------------------------------------
|
|
79
|
+
export function parseStartup(payload) {
|
|
80
|
+
const code = payload.readUInt32BE(0);
|
|
81
|
+
const params = {};
|
|
82
|
+
if (code >> 16 === 3) {
|
|
83
|
+
let i = 4;
|
|
84
|
+
while (i < payload.length && payload[i] !== 0) {
|
|
85
|
+
const [key, a] = readCString(payload, i);
|
|
86
|
+
const [value, b] = readCString(payload, a);
|
|
87
|
+
params[key] = value;
|
|
88
|
+
i = b;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return { code, params };
|
|
92
|
+
}
|
|
93
|
+
export function startupMessage(params) {
|
|
94
|
+
const parts = [int32(PROTOCOL_3_0)];
|
|
95
|
+
for (const [k, v] of Object.entries(params))
|
|
96
|
+
parts.push(cstr(k), cstr(v));
|
|
97
|
+
parts.push(Buffer.from([0]));
|
|
98
|
+
const body = Buffer.concat(parts);
|
|
99
|
+
return Buffer.concat([int32(body.length + 4), body]);
|
|
100
|
+
}
|
|
101
|
+
export const sslRequest = () => Buffer.concat([int32(8), int32(SSL_REQUEST)]);
|
|
102
|
+
export const cancelRequest = (pid, key) => Buffer.concat([int32(16), int32(CANCEL_REQUEST), int32(pid), int32(key)]);
|
|
103
|
+
// ---- backend messages pgleash sends to clients ---------------------------
|
|
104
|
+
export const authOk = () => message('R', int32(0));
|
|
105
|
+
export const authCleartextPassword = () => message('R', int32(3));
|
|
106
|
+
export const parameterStatus = (k, v) => message('S', Buffer.concat([cstr(k), cstr(v)]));
|
|
107
|
+
export const backendKeyData = (pid, key) => message('K', Buffer.concat([int32(pid), int32(key)]));
|
|
108
|
+
export const readyForQuery = (status = 'I') => message('Z', Buffer.from(status));
|
|
109
|
+
export function negotiateProtocolVersion(newestMinor, unsupported) {
|
|
110
|
+
return message('v', Buffer.concat([int32(newestMinor), int32(unsupported.length), ...unsupported.map(cstr)]));
|
|
111
|
+
}
|
|
112
|
+
/** ErrorResponse ('E') or NoticeResponse ('N'). */
|
|
113
|
+
export function errorResponse(fields, type = 'E') {
|
|
114
|
+
const parts = [];
|
|
115
|
+
for (const [code, value] of Object.entries(fields)) {
|
|
116
|
+
if (value !== undefined)
|
|
117
|
+
parts.push(Buffer.from(code), cstr(value));
|
|
118
|
+
}
|
|
119
|
+
parts.push(Buffer.from([0]));
|
|
120
|
+
return message(type, Buffer.concat(parts));
|
|
121
|
+
}
|
|
122
|
+
export function parseFields(payload) {
|
|
123
|
+
const out = {};
|
|
124
|
+
let i = 0;
|
|
125
|
+
while (i < payload.length && payload[i] !== 0) {
|
|
126
|
+
const code = String.fromCharCode(payload[i]);
|
|
127
|
+
const [value, next] = readCString(payload, i + 1);
|
|
128
|
+
out[code] = value;
|
|
129
|
+
i = next;
|
|
130
|
+
}
|
|
131
|
+
return out;
|
|
132
|
+
}
|
|
133
|
+
// ---- frontend messages pgleash sends upstream ----------------------------
|
|
134
|
+
export const query = (sql) => message('Q', cstr(sql));
|
|
135
|
+
export const terminate = () => message('X');
|
|
136
|
+
export const passwordMessage = (s) => message('p', cstr(s));
|
|
137
|
+
export const saslInitialResponse = (mechanism, data) => message('p', Buffer.concat([cstr(mechanism), int32(data.length), data]));
|
|
138
|
+
export const saslResponse = (data) => message('p', data);
|
|
139
|
+
export function parseParse(payload) {
|
|
140
|
+
const [name, a] = readCString(payload, 0);
|
|
141
|
+
const [sql] = readCString(payload, a);
|
|
142
|
+
return { name, sql };
|
|
143
|
+
}
|
|
144
|
+
export function buildParse(name, sql) {
|
|
145
|
+
return message('P', Buffer.concat([cstr(name), cstr(sql), int16(0)]));
|
|
146
|
+
}
|
|
147
|
+
// ---- result rewriting ----------------------------------------------------
|
|
148
|
+
export function rowDescriptionNames(payload) {
|
|
149
|
+
const count = payload.readInt16BE(0);
|
|
150
|
+
const names = [];
|
|
151
|
+
let i = 2;
|
|
152
|
+
for (let f = 0; f < count; f++) {
|
|
153
|
+
const [name, next] = readCString(payload, i);
|
|
154
|
+
names.push(name);
|
|
155
|
+
i = next + 18; // table oid, attnum, type oid, typlen, typmod, format
|
|
156
|
+
}
|
|
157
|
+
return names;
|
|
158
|
+
}
|
|
159
|
+
/** Replaces the masked columns of a DataRow with NULL. */
|
|
160
|
+
export function maskDataRow(payload, mask) {
|
|
161
|
+
const count = payload.readInt16BE(0);
|
|
162
|
+
const parts = [payload.subarray(0, 2)];
|
|
163
|
+
let i = 2;
|
|
164
|
+
for (let c = 0; c < count; c++) {
|
|
165
|
+
const len = payload.readInt32BE(i);
|
|
166
|
+
const end = i + 4 + Math.max(len, 0);
|
|
167
|
+
parts.push(mask.has(c) && len !== -1 ? int32(-1) : payload.subarray(i, end));
|
|
168
|
+
i = end;
|
|
169
|
+
}
|
|
170
|
+
return message('D', Buffer.concat(parts));
|
|
171
|
+
}
|
package/dist/proxy.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { AuditLog } from './audit.ts';
|
|
2
|
+
import { type PolicyOptions } from './policy.ts';
|
|
3
|
+
export interface ProxyOptions {
|
|
4
|
+
/** postgres:// URL of the real database. Use a least-privilege role. */
|
|
5
|
+
upstream: string;
|
|
6
|
+
host?: string;
|
|
7
|
+
port?: number;
|
|
8
|
+
/** Password the agent must send. Leave undefined to accept any password (loopback only). */
|
|
9
|
+
token?: string;
|
|
10
|
+
policy: PolicyOptions;
|
|
11
|
+
/** Rows returned per result before the rest are dropped. 0 turns the cap off. */
|
|
12
|
+
maxRows?: number;
|
|
13
|
+
statementTimeoutMs?: number;
|
|
14
|
+
idleInTransactionTimeoutMs?: number;
|
|
15
|
+
audit?: AuditLog;
|
|
16
|
+
log?: (line: string) => void;
|
|
17
|
+
}
|
|
18
|
+
export interface RunningProxy {
|
|
19
|
+
host: string;
|
|
20
|
+
port: number;
|
|
21
|
+
close(): Promise<void>;
|
|
22
|
+
}
|
|
23
|
+
export declare function startProxy(opts: ProxyOptions): Promise<RunningProxy>;
|