pgsafe 0.0.0-stage → 2.7.1
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/ALL-MILESTONES-TESTING.md +41 -0
- package/CHANGELOG.md +88 -0
- package/CONTRIBUTING.md +3 -0
- package/LICENSE +9 -0
- package/README.md +254 -2
- package/SECURITY.md +13 -0
- package/bin/cli.js +120 -0
- package/docs/RULES.md +31 -0
- package/examples/baseline.sql +7 -0
- package/examples/consumer-workflow.yml +22 -0
- package/examples/migrations/001_add_phone.sql +1 -0
- package/examples/migrations/002_add_email_index.sql +1 -0
- package/examples/reviewed-risk-baseline.json +7 -0
- package/examples/safe.sql +2 -0
- package/examples/suppression-gate-policy.json +11 -0
- package/examples/team-policy.json +7 -0
- package/examples/test-unsafe.sql +1 -0
- package/examples/unsafe.sql +2 -0
- package/examples/verify.sql +8 -0
- package/examples/week3-gate-policy.json +6 -0
- package/examples/week3-production-context.json +8 -0
- package/package.json +71 -4
- package/scripts/orm-runner/README.md +35 -0
- package/scripts/orm-runner/package-lock.json +659 -0
- package/scripts/orm-runner/package.json +14 -0
- package/scripts/orm-runner/verify.mjs +360 -0
- package/scripts/test-pg-matrix.cjs +30 -0
- package/src/advisor.js +77 -0
- package/src/analysis.js +411 -0
- package/src/combined.js +60 -0
- package/src/config.js +38 -0
- package/src/db-inspect.js +30 -0
- package/src/detector.js +25 -0
- package/src/engine.js +48 -0
- package/src/gitDiff.js +33 -0
- package/src/github.js +17 -0
- package/src/locks.js +134 -0
- package/src/parser.js +86 -0
- package/src/plans.js +9 -0
- package/src/presets.js +5 -0
- package/src/production-context.js +78 -0
- package/src/reports.js +38 -0
- package/src/risk-baseline.js +54 -0
- package/src/risk.js +29 -0
- package/src/rules/additionalRules.js +9 -0
- package/src/rules/alterTableRules.js +65 -0
- package/src/rules/concurrentIndex.js +18 -0
- package/src/rules/dataIntegrityRules.js +40 -0
- package/src/rules/dropColumn.js +12 -0
- package/src/rules/operationalRiskRules.js +57 -0
- package/src/rules/ruleCatalog.js +37 -0
- package/src/rules/versionCatalog.js +16 -0
- package/src/rules/versionRules.js +49 -0
- package/src/simulator.js +135 -0
- package/src/suppression-matcher.js +24 -0
- package/src/suppression-report.js +19 -0
- package/src/suppression.js +78 -0
- package/src/team-policy.js +84 -0
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/** Public metadata for implemented safety diagnostics. This does not change lint behavior. */
|
|
2
|
+
const definitions = [
|
|
3
|
+
['PG001','Non-concurrent index creation','locking','ERROR',null,'Use CREATE INDEX CONCURRENTLY outside a transaction.'],
|
|
4
|
+
['PG002','Dropping a column','data-loss','ERROR',null,'Deprecate consumers before removing the column.'],
|
|
5
|
+
['PG003','Changing a column type','rewrite','ERROR',null,'Check binary compatibility; consider expand/backfill/contract.'],
|
|
6
|
+
['PG004','Adding NOT NULL column without default','constraint','ERROR',null,'Add nullable, backfill, then enforce NOT NULL.'],
|
|
7
|
+
['PG005','Adding validated foreign key','locking','ERROR',null,'Add NOT VALID then VALIDATE CONSTRAINT separately.'],
|
|
8
|
+
['PG006','Renaming an object','compatibility','ERROR',null,'Use an expand/contract deployment.'],
|
|
9
|
+
['PG007','Dropping index without CONCURRENTLY','locking','ERROR',null,'Use DROP INDEX CONCURRENTLY where supported.'],
|
|
10
|
+
['PG008','Concurrent index operation inside transaction','compatibility','ERROR',null,'Run outside BEGIN/COMMIT.'],
|
|
11
|
+
['PG010','Adding UNIQUE constraint','locking','ERROR',null,'Consider a concurrent unique index and attach it where applicable.'],
|
|
12
|
+
['PG011','Dropping a table','data-loss','ERROR',null,'Verify retention and application dependencies.'],
|
|
13
|
+
['PG012','Adding validated CHECK constraint','constraint','ERROR',null,'Add NOT VALID and validate separately.'],
|
|
14
|
+
['PG013','Legacy SET NOT NULL diagnostic (superseded by PG025)','constraint','ERROR',null,'Validate an equivalent CHECK constraint first.'],
|
|
15
|
+
['PG014','Adding column with default on PostgreSQL 10','rewrite','ERROR',null,'Use controlled backfill or evaluate upgrading PostgreSQL.'],
|
|
16
|
+
['PG015','Prisma concurrent index migration','integration','WARNING',null,'Use a separately managed nontransactional migration.'],
|
|
17
|
+
['PG016','Drizzle concurrent index migration','integration','WARNING',null,'Use a separately managed nontransactional migration.'],
|
|
18
|
+
['PG017','Potential cross-file dependency or Flyway transaction advisory','dependency','WARNING',null,'Review migration order; this is a heuristic.'],
|
|
19
|
+
['PG019','MERGE requires PostgreSQL 15+','version','ERROR',15,'Use a compatible INSERT ... ON CONFLICT pattern where applicable.'],
|
|
20
|
+
['PG020','UNIQUE NULLS NOT DISTINCT requires PostgreSQL 15+','version','ERROR',15,'Use a version-compatible uniqueness strategy.'],
|
|
21
|
+
['PG021','Volatile default may rewrite table','rewrite','ERROR',null,'Add column, backfill in batches, then set default.'],
|
|
22
|
+
['PG022','SET LOGGED rewrites table','rewrite','ERROR',null,'Schedule controlled maintenance and evaluate alternatives.'],
|
|
23
|
+
['PG023','TRUNCATE removes table rows','data-loss','ERROR',null,'Confirm retention, backups and downstream dependencies.'],
|
|
24
|
+
['PG024','Dropping a constraint','constraint','WARNING',null,'Review dependent queries and data-integrity requirements.'],
|
|
25
|
+
['PG025','SET NOT NULL may scan table','constraint','WARNING',null,'Backfill and validate a CHECK constraint first where appropriate.']
|
|
26
|
+
];
|
|
27
|
+
|
|
28
|
+
export const RULE_CATALOG = Object.freeze(definitions.map(([id,title,category,defaultSeverity,minPostgresVersion,recommendation]) => Object.freeze({id,title,category,defaultSeverity,defaultCliSeverity: ['PG024','PG025'].includes(id) ? 'ERROR' : defaultSeverity,minPostgresVersion,recommendation})));
|
|
29
|
+
|
|
30
|
+
export function getRule(id) {
|
|
31
|
+
return RULE_CATALOG.find(rule => rule.id === String(id).toUpperCase()) ?? null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function searchRules(query = '') {
|
|
35
|
+
const needle = String(query).trim().toLowerCase();
|
|
36
|
+
return RULE_CATALOG.filter(rule => Object.values(rule).some(value => value != null && String(value).toLowerCase().includes(needle)));
|
|
37
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** Compatibility facts used by the static version rules (not a complete SQL feature matrix). */
|
|
2
|
+
export const VERSION_FEATURES = Object.freeze({
|
|
3
|
+
merge: Object.freeze({ minVersion: 15, ruleId: 'PG019', label: 'MERGE statement' }),
|
|
4
|
+
nullsNotDistinct: Object.freeze({ minVersion: 15, ruleId: 'PG020', label: 'UNIQUE NULLS NOT DISTINCT' })
|
|
5
|
+
});
|
|
6
|
+
|
|
7
|
+
export function getVersionCompatibility(feature, targetVersion) {
|
|
8
|
+
const definition = VERSION_FEATURES[feature];
|
|
9
|
+
if (!definition) throw new RangeError(`Unknown PostgreSQL feature: ${feature}`);
|
|
10
|
+
if (targetVersion == null) return { ...definition, supported: null };
|
|
11
|
+
const version = Number(targetVersion);
|
|
12
|
+
if (!Number.isInteger(version) || version < 10 || version > 99) {
|
|
13
|
+
throw new RangeError('PostgreSQL target version must be an integer from 10 to 99');
|
|
14
|
+
}
|
|
15
|
+
return { ...definition, supported: version >= definition.minVersion };
|
|
16
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { getVersionCompatibility } from './versionCatalog.js';
|
|
2
|
+
|
|
3
|
+
/** Static PostgreSQL feature compatibility checks; they do not execute SQL. */
|
|
4
|
+
export const versionRules = {
|
|
5
|
+
id: 'PG019',
|
|
6
|
+
name: 'postgres-version-compatibility',
|
|
7
|
+
check(stmt, context = {}) {
|
|
8
|
+
const version = context.postgresVersion;
|
|
9
|
+
if (version == null) return [];
|
|
10
|
+
const major = Number(version);
|
|
11
|
+
if (!Number.isInteger(major) || major < 10 || major > 99) return [];
|
|
12
|
+
|
|
13
|
+
const issues = [];
|
|
14
|
+
if (stmt.MergeStmt && !getVersionCompatibility('merge', major).supported) {
|
|
15
|
+
issues.push({
|
|
16
|
+
ruleId: 'PG019',
|
|
17
|
+
message: `MERGE requires PostgreSQL 15 or later; target version is ${major}.`,
|
|
18
|
+
fix: 'Use a version-compatible INSERT ... ON CONFLICT or UPDATE/INSERT strategy, or upgrade PostgreSQL.'
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// libpg-query versions may use snake_case or camelCase AST fields.
|
|
23
|
+
const hasNullsNotDistinct = (node) =>
|
|
24
|
+
node?.nullsNotDistinct === true || node?.nulls_not_distinct === true;
|
|
25
|
+
const isUnique = (node) => node?.contype === 'CONSTR_UNIQUE';
|
|
26
|
+
|
|
27
|
+
const uniqueIndex = stmt.IndexStmt;
|
|
28
|
+
const uniqueConstraint = stmt.AlterTableStmt?.cmds?.some(cmd => {
|
|
29
|
+
const constraint = cmd.AlterTableCmd?.def?.Constraint;
|
|
30
|
+
return isUnique(constraint) && hasNullsNotDistinct(constraint);
|
|
31
|
+
}) ?? false;
|
|
32
|
+
const createTableConstraint = stmt.CreateStmt?.tableElts?.some(el => {
|
|
33
|
+
const constraint = el.Constraint;
|
|
34
|
+
return isUnique(constraint) && hasNullsNotDistinct(constraint);
|
|
35
|
+
}) ?? false;
|
|
36
|
+
const usesNullsNotDistinct =
|
|
37
|
+
(uniqueIndex?.unique === true && hasNullsNotDistinct(uniqueIndex)) ||
|
|
38
|
+
uniqueConstraint || createTableConstraint;
|
|
39
|
+
|
|
40
|
+
if (usesNullsNotDistinct && !getVersionCompatibility('nullsNotDistinct', major).supported) {
|
|
41
|
+
issues.push({
|
|
42
|
+
ruleId: 'PG020',
|
|
43
|
+
message: `UNIQUE NULLS NOT DISTINCT requires PostgreSQL 15 or later; target version is ${major}.`,
|
|
44
|
+
fix: 'Use a PostgreSQL 14-compatible uniqueness strategy after reviewing NULL semantics, or upgrade PostgreSQL.'
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
return issues;
|
|
48
|
+
}
|
|
49
|
+
};
|
package/src/simulator.js
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { spawnSync } from 'node:child_process';
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
|
|
6
|
+
const MAX_SQL_BYTES = 1024 * 1024;
|
|
7
|
+
const MAX_FILES = 100;
|
|
8
|
+
const ALLOWED_VERSIONS = new Set(['14', '15', '16', '17', '18']);
|
|
9
|
+
|
|
10
|
+
function readSql(file) {
|
|
11
|
+
const resolved = path.resolve(file);
|
|
12
|
+
const stat = fs.statSync(resolved);
|
|
13
|
+
if (!stat.isFile() || stat.size > MAX_SQL_BYTES) throw new Error('SQL file must be a regular file <= 1 MiB');
|
|
14
|
+
const sql = fs.readFileSync(resolved, 'utf8');
|
|
15
|
+
if (!sql.trim()) throw new Error(`SQL file is empty: ${resolved}`);
|
|
16
|
+
return { file: resolved, sql };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function migrationFiles(dir) {
|
|
20
|
+
const root = path.resolve(dir);
|
|
21
|
+
if (!fs.statSync(root).isDirectory()) throw new Error('migrations-dir must be a directory');
|
|
22
|
+
const files = fs.readdirSync(root, { withFileTypes: true })
|
|
23
|
+
.filter(entry => entry.isFile() && entry.name.toLowerCase().endsWith('.sql'))
|
|
24
|
+
.map(entry => path.join(root, entry.name)).sort();
|
|
25
|
+
if (!files.length || files.length > MAX_FILES) throw new Error('migrations-dir must contain 1-100 top-level .sql files');
|
|
26
|
+
return files.map(readSql);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Run SQL in a disposable, network-isolated PostgreSQL container.
|
|
30
|
+
* Baseline and target steps are separate. Not a production safety or rollback guarantee.
|
|
31
|
+
*/
|
|
32
|
+
export function simulateSqlFile(file, {
|
|
33
|
+
postgresVersion = '16', timeoutSeconds = 60, baseline,
|
|
34
|
+
migrationsDir, verifySql, run = spawnSync
|
|
35
|
+
} = {}) {
|
|
36
|
+
if (!ALLOWED_VERSIONS.has(String(postgresVersion))) throw new Error('Simulation supports PostgreSQL 14-18');
|
|
37
|
+
if (!Number.isInteger(timeoutSeconds) || timeoutSeconds < 10 || timeoutSeconds > 300) throw new Error('timeoutSeconds must be 10-300');
|
|
38
|
+
if (file && migrationsDir) throw new Error('Use either --simulate <file> or --migrations-dir, not both');
|
|
39
|
+
if (!file && !migrationsDir) throw new Error('Provide a SQL file or --migrations-dir');
|
|
40
|
+
const baselineStep = baseline ? readSql(baseline) : null;
|
|
41
|
+
const targets = migrationsDir ? migrationFiles(migrationsDir) : [readSql(file)];
|
|
42
|
+
const verification = verifySql ? readSql(verifySql) : null;
|
|
43
|
+
const name = `pg-safe-sim-${randomUUID().slice(0, 12)}`;
|
|
44
|
+
const image = `postgres:${postgresVersion}`;
|
|
45
|
+
const call = (args, options = {}) => {
|
|
46
|
+
const result = run('docker', args, {
|
|
47
|
+
encoding: 'utf8', timeout: options.timeout ?? 15000,
|
|
48
|
+
input: options.input, maxBuffer: 2 * 1024 * 1024, windowsHide: true
|
|
49
|
+
});
|
|
50
|
+
if (result.error) throw new Error(`Docker ${args[0]} failed: ${result.error.message}`);
|
|
51
|
+
return result;
|
|
52
|
+
};
|
|
53
|
+
let created = false;
|
|
54
|
+
let primaryError;
|
|
55
|
+
try {
|
|
56
|
+
const started = call(['run', '-d', '--name', name, '--network', 'none', '--memory', '512m', '--cpus', '1', '--pids-limit', '128', '--security-opt', 'no-new-privileges', '-e', 'POSTGRES_HOST_AUTH_METHOD=trust', image], { timeout: 120000 });
|
|
57
|
+
if (started.status !== 0) throw new Error(`Docker could not start disposable PostgreSQL: ${(started.stderr || '').trim()}`);
|
|
58
|
+
created = true;
|
|
59
|
+
let ready = false;
|
|
60
|
+
for (let attempt = 0; attempt < 30; attempt++) {
|
|
61
|
+
const result = call([
|
|
62
|
+
'exec', name,
|
|
63
|
+
'pg_isready',
|
|
64
|
+
'-h', '127.0.0.1',
|
|
65
|
+
'-p', '5432',
|
|
66
|
+
'-U', 'postgres',
|
|
67
|
+
'-d', 'postgres'
|
|
68
|
+
], { timeout: 5000 });
|
|
69
|
+
if (result.status === 0) { ready = true; break; }
|
|
70
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1000);
|
|
71
|
+
}
|
|
72
|
+
if (!ready) throw new Error('Disposable PostgreSQL did not become ready within 30 seconds');
|
|
73
|
+
const execute = (step, stage) => {
|
|
74
|
+
const result = call([
|
|
75
|
+
'exec', '-i', name,
|
|
76
|
+
'psql',
|
|
77
|
+
'-h', '127.0.0.1',
|
|
78
|
+
'-p', '5432',
|
|
79
|
+
'-X',
|
|
80
|
+
'-v', 'ON_ERROR_STOP=1',
|
|
81
|
+
'-U', 'postgres',
|
|
82
|
+
'-d', 'postgres',
|
|
83
|
+
'-f', '-'
|
|
84
|
+
], {
|
|
85
|
+
input: step.sql,
|
|
86
|
+
timeout: timeoutSeconds * 1000
|
|
87
|
+
});
|
|
88
|
+
return {
|
|
89
|
+
stage, file: step.file, passed: result.status === 0,
|
|
90
|
+
stdout: (result.stdout || '').slice(-4000), stderr: (result.stderr || '').slice(-4000),
|
|
91
|
+
exitCode: result.status
|
|
92
|
+
};
|
|
93
|
+
};
|
|
94
|
+
const steps = [];
|
|
95
|
+
if (baselineStep) {
|
|
96
|
+
const result = execute(baselineStep, 'baseline');
|
|
97
|
+
steps.push(result);
|
|
98
|
+
if (!result.passed) return summary(result, steps, postgresVersion);
|
|
99
|
+
}
|
|
100
|
+
for (const target of targets) {
|
|
101
|
+
const result = execute(target, 'migration');
|
|
102
|
+
steps.push(result);
|
|
103
|
+
if (!result.passed) return summary(result, steps, postgresVersion);
|
|
104
|
+
}
|
|
105
|
+
if (verification) {
|
|
106
|
+
const result = execute(verification, 'verification');
|
|
107
|
+
steps.push(result);
|
|
108
|
+
if (!result.passed) return summary(result, steps, postgresVersion);
|
|
109
|
+
}
|
|
110
|
+
return summary(steps.at(-1), steps, postgresVersion);
|
|
111
|
+
} catch (error) {
|
|
112
|
+
primaryError = error;
|
|
113
|
+
throw error;
|
|
114
|
+
} finally {
|
|
115
|
+
if (created) {
|
|
116
|
+
try {
|
|
117
|
+
const removed = call(['rm', '-f', name], { timeout: 30000 });
|
|
118
|
+
if (removed.status !== 0) throw new Error((removed.stderr || 'docker rm failed').trim());
|
|
119
|
+
} catch (error) {
|
|
120
|
+
const message = `CRITICAL: Disposable container ${name} could not be removed: ${error.message}`;
|
|
121
|
+
if (primaryError) throw new AggregateError([primaryError, error], message);
|
|
122
|
+
throw new Error(message);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function summary(last, steps, postgresVersion) {
|
|
129
|
+
return {
|
|
130
|
+
passed: last.passed, postgresVersion: Number(postgresVersion), isolated: true,
|
|
131
|
+
disposable: true, stage: last.stage, file: last.file,
|
|
132
|
+
stdout: last.stdout, stderr: last.stderr, exitCode: last.exitCode,
|
|
133
|
+
steps, limitation: 'Checks SQL execution against an empty disposable database plus optional baseline; not a downtime, production-data, or rollback guarantee.'
|
|
134
|
+
};
|
|
135
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { parseSqlFile } from './parser.js';
|
|
2
|
+
import { scanSuppressions } from './suppression.js';
|
|
3
|
+
import { getRule } from './rules/ruleCatalog.js';
|
|
4
|
+
|
|
5
|
+
// Preview only: no findings are removed and no CLI policy is changed.
|
|
6
|
+
export async function matchSuppressions(sql, parsed) {
|
|
7
|
+
const statements = parsed ?? await parseSqlFile(sql, { details: true });
|
|
8
|
+
const scan = scanSuppressions(sql);
|
|
9
|
+
const matches = [], rejected = [...scan.invalid];
|
|
10
|
+
let index = 0;
|
|
11
|
+
for (const directive of scan.directives) {
|
|
12
|
+
while (index < statements.length && statements[index].offset < directive.endOffset) index++;
|
|
13
|
+
const target = statements[index];
|
|
14
|
+
let message;
|
|
15
|
+
if (!directive.reason) message = 'Suppression reason required';
|
|
16
|
+
else if (directive.ruleIds.some(id => !getRule(id))) message = 'Unknown rule ID';
|
|
17
|
+
else if (!target || !/^[ \t\r\n]*$/.test(sql.slice(directive.endOffset, target.offset))) message = 'No immediately following statement';
|
|
18
|
+
// A comment inside a statement cannot bind across its terminating semicolon:
|
|
19
|
+
// the whitespace-only gap above rejects that semicolon and all SQL tokens.
|
|
20
|
+
if (message) rejected.push({ ...directive, message });
|
|
21
|
+
else matches.push({ ...directive, statementIndex: index, statementOffset: target.offset });
|
|
22
|
+
}
|
|
23
|
+
return { matches, rejected, scanError: scan.scanError };
|
|
24
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export function suppressionReport(records) {
|
|
2
|
+
const summary = { suppressed: 0, rejected: 0, unused: 0, scanErrors: 0 };
|
|
3
|
+
for (const r of records) {
|
|
4
|
+
const key = r.status === 'scan-error' ? 'scanErrors' : r.status;
|
|
5
|
+
if (!Object.hasOwn(summary, key)) throw new Error('Unknown suppression audit status');
|
|
6
|
+
summary[key]++;
|
|
7
|
+
}
|
|
8
|
+
return { summary, records };
|
|
9
|
+
}
|
|
10
|
+
const safe = value => String(value ?? '').replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, ' ');
|
|
11
|
+
const cell = value => safe(value).replace(/[&<>\\|`*_~\[\]#!]/g, c => `&#${c.charCodeAt(0)};`);
|
|
12
|
+
export function suppressionText(audit) {
|
|
13
|
+
const s = audit.summary;
|
|
14
|
+
return [`Suppression audit: ${s.suppressed} suppressed, ${s.rejected} rejected, ${s.unused} unused, ${s.scanErrors} scan errors.`, ...audit.records.map(r => ` ${safe(r.status)} ${safe(r.finding?.ruleId ?? r.ruleId ?? r.ruleIds?.join(', '))} ${safe(r.file)}:${r.directiveLine ?? r.line ?? '?'} — ${safe(r.reason)} ${safe(r.message)}`), 'Suppression is not evidence of migration safety.'].join('\n');
|
|
15
|
+
}
|
|
16
|
+
export function suppressionMarkdown(audit) {
|
|
17
|
+
const s = audit.summary;
|
|
18
|
+
return ['','## Suppression audit','',`${s.suppressed} suppressed, ${s.rejected} rejected, ${s.unused} unused, ${s.scanErrors} scan errors.`, '', '| Status | Rule | File | Directive line | Reason | Detail |','|---|---|---|---:|---|---|', ...audit.records.map(r => `| ${cell(r.status)} | ${cell(r.finding?.ruleId ?? r.ruleId ?? r.ruleIds?.join(', '))} | ${cell(r.file)} | ${cell(r.directiveLine ?? r.line)} | ${cell(r.reason)} | ${cell(r.message ?? r.finding?.message)} |`), '', 'Suppression is not evidence of migration safety.', ''].join('\n');
|
|
19
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// Detection only. Never use these candidates to suppress findings without AST binding.
|
|
2
|
+
const directive = /^\s*pg-safe-migrate-disable-next-line\b(.*)$/i;
|
|
3
|
+
const syntax = /^\s+(PG\d{3}(?:[ \t]*,[ \t]*PG\d{3})*)[ \t]*(?:--[ \t]*reason:[ \t]*(.*))?$/i;
|
|
4
|
+
const identifier = /[a-zA-Z_\u0080-\uffff]/;
|
|
5
|
+
const continuation = /[a-zA-Z_0-9$\u0080-\uffff]/;
|
|
6
|
+
|
|
7
|
+
export function scanSuppressions(sql) {
|
|
8
|
+
if (typeof sql !== 'string') throw new TypeError('SQL must be a string');
|
|
9
|
+
const directives = [], invalid = [];
|
|
10
|
+
let i = 0, line = 1, lineStart = 0;
|
|
11
|
+
function advance(end) {
|
|
12
|
+
while (i < end) {
|
|
13
|
+
if (sql[i] === '\r' || (sql[i] === '\n' && sql[i-1] !== '\r')) line++;
|
|
14
|
+
if (sql[i] === '\r' || sql[i] === '\n') lineStart = i + 1;
|
|
15
|
+
i++;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
function fail(message) { return { directives: [], invalid: [], scanError: { line, offset: i, message } }; }
|
|
19
|
+
while (i < sql.length) {
|
|
20
|
+
const c = sql[i];
|
|
21
|
+
if (sql.startsWith('--', i)) {
|
|
22
|
+
const start = i, startLine = line;
|
|
23
|
+
let end = i + 2;
|
|
24
|
+
while (end < sql.length && !/[\r\n]/.test(sql[end])) end++;
|
|
25
|
+
const match = directive.exec(sql.slice(i+2,end));
|
|
26
|
+
if (match && /^[ \t]*$/.test(sql.slice(lineStart,i))) {
|
|
27
|
+
const parsed = syntax.exec(match[1]);
|
|
28
|
+
const location = { line: startLine, offset: start, endOffset: end };
|
|
29
|
+
if (!parsed) invalid.push({ ...location, message: 'Malformed suppression directive' });
|
|
30
|
+
else directives.push({ ...location, ruleIds: [...new Set(parsed[1].toUpperCase().split(',').map(s=>s.trim()))], reason: (parsed[2] || '').trim() });
|
|
31
|
+
}
|
|
32
|
+
advance(end); continue;
|
|
33
|
+
}
|
|
34
|
+
if (sql.startsWith('/*', i)) {
|
|
35
|
+
let depth = 1; advance(i+2);
|
|
36
|
+
while (i < sql.length && depth) {
|
|
37
|
+
if (sql.startsWith('/*',i)) { depth++; advance(i+2); }
|
|
38
|
+
else if (sql.startsWith('*/',i)) { depth--; advance(i+2); }
|
|
39
|
+
else advance(i+1);
|
|
40
|
+
}
|
|
41
|
+
if (depth) return fail('Unterminated block comment');
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
const escape = /[eE]/.test(c) && sql[i+1] === "'";
|
|
45
|
+
if (escape || c === "'" || c === '"') {
|
|
46
|
+
const quote = escape ? "'" : c;
|
|
47
|
+
advance(i+(escape?2:1)); let closed = false;
|
|
48
|
+
while (i < sql.length) {
|
|
49
|
+
if (sql[i] === '\\' && quote === "'") {
|
|
50
|
+
if (!escape) return fail('Ambiguous backslash in ordinary string; suppression scan disabled');
|
|
51
|
+
advance(Math.min(i+2,sql.length)); continue;
|
|
52
|
+
}
|
|
53
|
+
if (sql[i] === quote) {
|
|
54
|
+
if (sql[i+1] === quote) { advance(i+2); continue; }
|
|
55
|
+
advance(i+1); closed = true; break;
|
|
56
|
+
}
|
|
57
|
+
advance(i+1);
|
|
58
|
+
}
|
|
59
|
+
if (!closed) return fail('Unterminated quoted token');
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
if (c === '$') {
|
|
63
|
+
const tag = /^\$(?:[a-zA-Z_\u0080-\uffff][a-zA-Z_0-9\u0080-\uffff]*)?\$/.exec(sql.slice(i));
|
|
64
|
+
if (tag) {
|
|
65
|
+
const end = sql.indexOf(tag[0], i+tag[0].length);
|
|
66
|
+
if (end < 0) return fail('Unterminated dollar quote');
|
|
67
|
+
advance(end+tag[0].length); continue;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (identifier.test(c)) {
|
|
71
|
+
let end = i+1;
|
|
72
|
+
while (end < sql.length && continuation.test(sql[end])) end++;
|
|
73
|
+
advance(end); continue;
|
|
74
|
+
}
|
|
75
|
+
advance(i+1);
|
|
76
|
+
}
|
|
77
|
+
return { directives, invalid, scanError: null };
|
|
78
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import { getRule } from './rules/ruleCatalog.js';
|
|
3
|
+
|
|
4
|
+
export function loadTeamPolicy(file) {
|
|
5
|
+
const policy = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
6
|
+
if (!policy || typeof policy !== 'object' || Array.isArray(policy)) throw new Error('Team policy must be a JSON object');
|
|
7
|
+
const allowed = ['name', 'maxRiskScore', 'maxWarnings', 'blockedRules', 'requireSimulation', 'suppression'];
|
|
8
|
+
for (const key of Object.keys(policy)) if (!allowed.includes(key)) throw new Error(`Unknown team policy key: ${key}`);
|
|
9
|
+
if (policy.name !== undefined && (typeof policy.name !== 'string' || !policy.name.trim() || policy.name.length > 100)) throw new Error('name must be a nonempty string of at most 100 characters');
|
|
10
|
+
if (policy.maxRiskScore !== undefined && (!Number.isInteger(policy.maxRiskScore) || policy.maxRiskScore < 0 || policy.maxRiskScore > 100)) throw new Error('maxRiskScore must be 0-100');
|
|
11
|
+
if (policy.maxWarnings !== undefined && (!Number.isInteger(policy.maxWarnings) || policy.maxWarnings < 0)) throw new Error('maxWarnings must be >= 0');
|
|
12
|
+
if (policy.blockedRules !== undefined && (!Array.isArray(policy.blockedRules) || policy.blockedRules.some(x => typeof x !== 'string' || !/^PG\d{3}$/.test(x) || !getRule(x)))) throw new Error('blockedRules must be an array of PG rule IDs');
|
|
13
|
+
if (policy.blockedRules && new Set(policy.blockedRules).size !== policy.blockedRules.length) throw new Error('blockedRules must not contain duplicates');
|
|
14
|
+
if (policy.requireSimulation !== undefined && typeof policy.requireSimulation !== 'boolean') throw new Error('requireSimulation must be boolean');
|
|
15
|
+
if (policy.suppression !== undefined) {
|
|
16
|
+
const s = policy.suppression;
|
|
17
|
+
if (!s || typeof s !== 'object' || Array.isArray(s)) throw new Error('policy.suppression must be an object');
|
|
18
|
+
for (const key of Object.keys(s)) if (!['protectedRules','maxSuppressedFindings','failOnRejected','failOnUnused'].includes(key)) throw new Error(`Unknown policy suppression key: ${key}`);
|
|
19
|
+
if (s.protectedRules !== undefined && (!Array.isArray(s.protectedRules) || s.protectedRules.some(id => typeof id !== 'string' || !/^PG\d{3}$/.test(id) || !getRule(id)))) throw new Error('Invalid policy protectedRules');
|
|
20
|
+
if (s.maxSuppressedFindings !== undefined && (!Number.isSafeInteger(s.maxSuppressedFindings) || s.maxSuppressedFindings < 0)) throw new Error('Invalid maxSuppressedFindings');
|
|
21
|
+
for (const key of ['failOnRejected','failOnUnused']) if (s[key] !== undefined && typeof s[key] !== 'boolean') throw new Error(`Invalid ${key}`);
|
|
22
|
+
}
|
|
23
|
+
return policy;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function assessTeamPolicy(report, policy) {
|
|
27
|
+
const reasons = [];
|
|
28
|
+
const findings = report.lint.findings;
|
|
29
|
+
if (policy.requireSimulation && !report.execution?.passed) reasons.push('Simulation must pass');
|
|
30
|
+
if (policy.maxRiskScore !== undefined && report.lint.risk.score > policy.maxRiskScore) reasons.push(`Risk score exceeds ${policy.maxRiskScore}`);
|
|
31
|
+
if (policy.maxWarnings !== undefined && findings.filter(f => f.severity === 'warning').length > policy.maxWarnings) reasons.push(`Warnings exceed ${policy.maxWarnings}`);
|
|
32
|
+
for (const f of findings) if (policy.blockedRules?.includes(f.ruleId)) reasons.push(`Blocked rule ${f.ruleId}: ${f.file}`);
|
|
33
|
+
return { name: policy.name ?? 'local-team', passed: reasons.length === 0, reasons: [...new Set(reasons)] };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Week 3: static-only CI gate. The existing --assess policy behavior is unchanged.
|
|
37
|
+
export function validateLintPolicy(policy) {
|
|
38
|
+
if (policy.requireSimulation === true) throw new Error('requireSimulation requires --assess with a disposable PostgreSQL simulation');
|
|
39
|
+
return policy;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function assessLintPolicy(findings, policy, risk = {}) {
|
|
43
|
+
validateLintPolicy(policy);
|
|
44
|
+
// A score is only a heuristic derived from the configured lint findings.
|
|
45
|
+
const reasons = [];
|
|
46
|
+
const warningCount = findings.filter(f => f.severity === 'warning').length;
|
|
47
|
+
if (policy.maxWarnings !== undefined && warningCount > policy.maxWarnings) reasons.push(`Warnings ${warningCount} exceed ${policy.maxWarnings}`);
|
|
48
|
+
if (policy.maxRiskScore !== undefined) {
|
|
49
|
+
const severityScore = Math.min(100, findings.reduce((n, f) => n + (f.severity === 'error' ? 20 : f.severity === 'warning' ? 5 : 0), 0));
|
|
50
|
+
// Actual heuristic is calculated by the caller and passed separately when available.
|
|
51
|
+
const score = risk.score ?? severityScore;
|
|
52
|
+
if (score > policy.maxRiskScore) reasons.push(`Heuristic risk score ${score} exceeds ${policy.maxRiskScore}`);
|
|
53
|
+
}
|
|
54
|
+
for (const f of findings) if (policy.blockedRules?.includes(f.ruleId)) reasons.push(`Blocked rule ${f.ruleId}: ${f.file}`);
|
|
55
|
+
return { name: policy.name ?? 'local-team', passed: reasons.length === 0, reasons: [...new Set(reasons)], note: 'Passing a static gate is not a safety guarantee; unknown locks and production workloads still require review.' };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// A static gate always evaluates all configured risks, including suppressed ones.
|
|
59
|
+
export function applySuppressionPolicy(config, policy) {
|
|
60
|
+
if (!config.suppression?.enabled || !policy) return config;
|
|
61
|
+
const protectedRules = [...new Set([...config.suppression.protectedRules, ...['PG011','PG023'], ...(policy.blockedRules ?? []), ...(policy.suppression?.protectedRules ?? [])])];
|
|
62
|
+
return { ...config, suppression: { ...config.suppression, protectedRules } };
|
|
63
|
+
}
|
|
64
|
+
export function enforceSuppressionAudit(gate, policy, audit) {
|
|
65
|
+
if (!audit) return gate;
|
|
66
|
+
const s = audit.summary;
|
|
67
|
+
const limits = policy.suppression ?? {};
|
|
68
|
+
const reasons = [...gate.reasons];
|
|
69
|
+
if (s.suppressed > (limits.maxSuppressedFindings ?? 0)) reasons.push('Suppression limit exceeded');
|
|
70
|
+
if (s.rejected && limits.failOnRejected !== false) reasons.push('Rejected suppression directives');
|
|
71
|
+
if (s.unused && limits.failOnUnused !== false) reasons.push('Unused suppression directives');
|
|
72
|
+
if (s.scanErrors) reasons.push('Suppression scan failed');
|
|
73
|
+
return { ...gate, reasons, passed: reasons.length === 0 };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// CI must supply trusted configuration, policy, target and PostgreSQL version.
|
|
77
|
+
export function validateGateConfig(config, policy) {
|
|
78
|
+
if (!policy) return;
|
|
79
|
+
if (config.exclude?.length) throw new Error('Enterprise policy does not allow project exclusions');
|
|
80
|
+
if (config.severity !== 'error') throw new Error('Enterprise policy requires default error severity');
|
|
81
|
+
for (const [id, severity] of Object.entries(config.rules ?? {})) {
|
|
82
|
+
if (severity === 'off' || severity === 'warning') throw new Error(`Enterprise policy does not allow weakening rule ${id}`);
|
|
83
|
+
}
|
|
84
|
+
}
|