pgsafe 2.7.0 → 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/README.md +255 -116
- 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 +73 -46
- 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
- package/bin/pgsafe.js +0 -3
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# Consolidated development build — testing guide
|
|
2
|
+
|
|
3
|
+
This is a development candidate, **not** a verified production release. Package version stays at 2.1.0.
|
|
4
|
+
|
|
5
|
+
## Combined report (Windows CMD, Docker running)
|
|
6
|
+
|
|
7
|
+
```cmd
|
|
8
|
+
npm ci
|
|
9
|
+
npm test
|
|
10
|
+
node bin/cli.js --assess --migrations-dir examples/migrations --baseline examples/baseline.sql --verify-sql examples/verify.sql --postgres-version 16 --team-policy examples/team-policy.json --output assessment.json
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
The `assessment.json` contains execution steps, static lint findings, heuristic locks, advice, risk scoring, and local team-policy outcome. A migration that executes successfully may still fail static lint or policy. `--verify-sql` runs after migrations; write assertions that raise PostgreSQL errors on unexpected state.
|
|
14
|
+
|
|
15
|
+
## PostgreSQL 14–18 matrix
|
|
16
|
+
|
|
17
|
+
```cmd
|
|
18
|
+
node scripts/test-pg-matrix.cjs
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
This starts five separate disposable Docker containers in sequence. Requires local Docker images or permission to pull them. A passing matrix on one computer does not guarantee performance or production safety on all server versions.
|
|
22
|
+
|
|
23
|
+
## Failure case
|
|
24
|
+
|
|
25
|
+
Create a migration with invalid SQL or a post-migration assertion that raises an exception. Expect nonzero exit status and a failed `execution` stage. Docker container cleanup should be verified with `docker ps -a --filter name=pg-safe-sim`.
|
|
26
|
+
|
|
27
|
+
## VS Code extension (local development)
|
|
28
|
+
|
|
29
|
+
The `vscode-extension/` folder is an **unpackaged local prototype**. Open it as a VS Code extension development project and run an Extension Development Host; open the pg-safe-migrate project folder in that host, open a `.sql` file, and run **PG Safe Migrate: Lint Current SQL File** from the Command Palette. It calls the project's local CLI and shows diagnostics. It does not yet include VSIX packaging, automated extension-host tests, marketplace publication, or remote CLI discovery.
|
|
30
|
+
|
|
31
|
+
## Team policies
|
|
32
|
+
|
|
33
|
+
`examples/team-policy.json` shows supported local constraints: `maxRiskScore`, `maxWarnings`, `blockedRules`, `requireSimulation`. These are file-based policies, not centralized administration, authentication, dashboards, or multi-tenant reporting.
|
|
34
|
+
|
|
35
|
+
## Verification status
|
|
36
|
+
|
|
37
|
+
- 10 simulator/policy focused tests passed in the build environment.
|
|
38
|
+
- JavaScript syntax and npm pack dry run passed.
|
|
39
|
+
- Full suite could not run here because `libpg-query` tarball was unavailable offline.
|
|
40
|
+
- PostgreSQL 14–18 Docker matrix not executed here.
|
|
41
|
+
- VS Code extension host not executed here.
|
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## [2.7.1]
|
|
4
|
+
|
|
5
|
+
- Make `pgsafe` the standalone npm engine instead of a wrapper.
|
|
6
|
+
- Preserve the `pg-safe-migrate` executable and configuration filename.
|
|
7
|
+
- Update installation documentation and consumer CI example.
|
|
8
|
+
- No changes to SQL analysis rules.
|
|
9
|
+
|
|
10
|
+
## [2.7.0]
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- SQL-aware inline rule suppression.
|
|
15
|
+
|
|
16
|
+
- AST-based suppression targeting for individual SQL statements.
|
|
17
|
+
|
|
18
|
+
- Mandatory suppression reasons for auditability.
|
|
19
|
+
|
|
20
|
+
- Configurable protected migration safety rules.
|
|
21
|
+
|
|
22
|
+
- Suppression audit reporting in terminal, JSON, SARIF and Markdown formats.
|
|
23
|
+
|
|
24
|
+
- Enterprise suppression policies with configurable limits.
|
|
25
|
+
|
|
26
|
+
- Detection of rejected, unused and invalid suppression directives.
|
|
27
|
+
|
|
28
|
+
- Suppression-aware VS Code diagnostics and audit reporting.
|
|
29
|
+
|
|
30
|
+
### Security
|
|
31
|
+
|
|
32
|
+
- Protected rules cannot be suppressed through ordinary inline directives.
|
|
33
|
+
|
|
34
|
+
- Enterprise gates reject project exclusions and severity-weakening overrides.
|
|
35
|
+
|
|
36
|
+
- Suppressed findings remain included in enterprise risk calculations.
|
|
37
|
+
|
|
38
|
+
- Ambiguous SQL scanning fails closed.
|
|
39
|
+
|
|
40
|
+
### Verification
|
|
41
|
+
|
|
42
|
+
- 363 automated regression tests passed.
|
|
43
|
+
|
|
44
|
+
- Compatibility verified on Node.js 18, 20, 22 and 24.
|
|
45
|
+
|
|
46
|
+
- Repeated memory retention testing across 200,000 measured SQL statements.
|
|
47
|
+
|
|
48
|
+
- Performance benchmarks covering up to 10,000 SQL statements per workload.
|
|
49
|
+
|
|
50
|
+
### Compatibility and limitations
|
|
51
|
+
|
|
52
|
+
- Inline suppression is disabled by default.
|
|
53
|
+
|
|
54
|
+
- Enterprise gates now reject configurations that weaken rule severity or exclude files.
|
|
55
|
+
|
|
56
|
+
- Some combinations of suppression, risk baselines and combined simulation are not supported.
|
|
57
|
+
|
|
58
|
+
- Enterprise enforcement requires trusted CLI code, configuration, policies and CI workflows.
|
|
59
|
+
|
|
60
|
+
- Static migration analysis does not guarantee zero downtime.
|
|
61
|
+
|
|
62
|
+
## [2.6.0]
|
|
63
|
+
|
|
64
|
+
* Unicode-aware SQL positions, leading comment handling and transaction tracking for savepoints and chained transactions.
|
|
65
|
+
* Optimized statement position tracking.
|
|
66
|
+
* Corrected rule catalog coverage and default severity metadata (no enforcement changes).
|
|
67
|
+
|
|
68
|
+
## [2.5.0] - 2026-11-20
|
|
69
|
+
|
|
70
|
+
### Added
|
|
71
|
+
|
|
72
|
+
* Configurable CI migration safety gates.
|
|
73
|
+
* Reviewed migration risk baselines to distinguish new, existing, and resolved findings.
|
|
74
|
+
* Production-aware migration recommendations using optional workload and table-size estimates.
|
|
75
|
+
* GitHub Actions pull-request safety reporting.
|
|
76
|
+
* Improved onboarding, examples, and adoption documentation.
|
|
77
|
+
|
|
78
|
+
### Improved
|
|
79
|
+
|
|
80
|
+
* JSON reporting for risk baselines, production context, and policy decisions.
|
|
81
|
+
* Migration safety guidance for deployment planning.
|
|
82
|
+
* Release-readiness verification and regression coverage.
|
|
83
|
+
|
|
84
|
+
### Notes
|
|
85
|
+
|
|
86
|
+
* Production context uses supplied estimates, not live database measurements.
|
|
87
|
+
* Static analysis does not guarantee zero downtime.
|
|
88
|
+
* Existing migration safety rules remain available.
|
package/CONTRIBUTING.md
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
# Contributing
|
|
2
|
+
|
|
3
|
+
Fork the repository and create a focused branch. Install dependencies with `npm ci`. Add regression tests for rule changes and preserve stable diagnostic IDs. Run `npm run test:release` and `git diff --check`. For extension changes run `npm run build:standalone` and `npm run verify:standalone` in `vscode-extension`. Document limitations and include sanitized SQL reproductions. Do not commit secrets, generated VSIX files or local logs. Open a pull request describing the change and test results. Security reports should follow SECURITY.md.
|
package/README.md
CHANGED
|
@@ -1,116 +1,255 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
```
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
1
|
+
# PG Safe Migrate
|
|
2
|
+
|
|
3
|
+
**Catch risky PostgreSQL migrations before they reach production.**
|
|
4
|
+
|
|
5
|
+
Open-source, AST-based migration linting for Prisma, Drizzle, Flyway and raw SQL. Detect destructive changes, locking risks and transaction hazards before deployment.
|
|
6
|
+
|
|
7
|
+
[](https://www.npmjs.com/package/pgsafe) [](https://marketplace.visualstudio.com/items?itemName=sukoaa.pg-safe-migrate-vscode) [](LICENSE)
|
|
8
|
+
|
|
9
|
+
[Product website](https://www.sukoaa.com/pg-safe-migrate) · [Rule reference](docs/RULES.md) · [VS Code](https://marketplace.visualstudio.com/items?itemName=sukoaa.pg-safe-migrate-vscode) · [Report an issue](https://github.com/subodhsingh001/pg-safe-migrate/issues)
|
|
10
|
+
|
|
11
|
+

|
|
12
|
+
|
|
13
|
+
## Quick start
|
|
14
|
+
|
|
15
|
+
Requires Node.js 18 or later; use a maintained Node.js release for new installations.
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
npx pgsafe
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Or install in your project:
|
|
22
|
+
|
|
23
|
+
```sh
|
|
24
|
+
npm install --save-dev pgsafe
|
|
25
|
+
npx --no-install pgsafe prisma/migrations --advisor
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Use `drizzle`, `db/migrations` or a specific SQL file instead of `prisma/migrations`. With no path, the CLI detects common migration directories.
|
|
29
|
+
|
|
30
|
+
### Example
|
|
31
|
+
|
|
32
|
+
```sql
|
|
33
|
+
ALTER TABLE users DROP COLUMN email;
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
```text
|
|
37
|
+
unsafe.sql:1:1 [PG002] error: Dropping column "users.email" can break older application instances.
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Remove application references before dropping the column in a later deployment. A passing lint check is not a guarantee of zero downtime.
|
|
41
|
+
|
|
42
|
+
### Existing installations
|
|
43
|
+
|
|
44
|
+
The standalone `pgsafe` package replaces the wrapper starting in 2.7.1. Existing scoped releases remain available. To migrate a project, uninstall `@subodh001/pg-safe-migrate` and install `pgsafe`; do not install both packages in the same project because both expose `pg-safe-migrate`. The legacy executable and configuration filename remain supported.
|
|
45
|
+
|
|
46
|
+
## GitHub Actions
|
|
47
|
+
|
|
48
|
+
Save as `.github/workflows/migration-lint.yml`:
|
|
49
|
+
|
|
50
|
+
```yaml
|
|
51
|
+
name: PostgreSQL migration safety
|
|
52
|
+
on:
|
|
53
|
+
pull_request:
|
|
54
|
+
paths:
|
|
55
|
+
- '**/*.sql'
|
|
56
|
+
permissions:
|
|
57
|
+
contents: read
|
|
58
|
+
jobs:
|
|
59
|
+
migrations:
|
|
60
|
+
runs-on: ubuntu-latest
|
|
61
|
+
steps:
|
|
62
|
+
- uses: actions/checkout@v4
|
|
63
|
+
with:
|
|
64
|
+
fetch-depth: 0
|
|
65
|
+
persist-credentials: false
|
|
66
|
+
- uses: actions/setup-node@v4
|
|
67
|
+
with:
|
|
68
|
+
node-version: '22'
|
|
69
|
+
- name: Check changed SQL
|
|
70
|
+
env:
|
|
71
|
+
BASE_REF: ${{ github.base_ref }}
|
|
72
|
+
run: npx --yes pgsafe@2.7.1 --changed "origin/$BASE_REF" --fail-on error
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Start with reporting-only mode (`--fail-on none`) if introducing linting into an existing project. Review findings before enforcing a gate. See the [adoption guide](docs/ADOPTION-GUIDE.md).
|
|
76
|
+
|
|
77
|
+
## What it detects
|
|
78
|
+
|
|
79
|
+
| ID | Diagnostic | Default | Guidance |
|
|
80
|
+
|---|---|---|---|
|
|
81
|
+
| PG001 | Non-concurrent index creation | error | Use CREATE INDEX CONCURRENTLY outside a transaction. |
|
|
82
|
+
| PG002 | Dropping a column | error | Deprecate consumers before removing the column. |
|
|
83
|
+
| PG003 | Changing a column type | error | Check binary compatibility; consider expand/backfill/contract. |
|
|
84
|
+
| PG004 | Adding NOT NULL column without default | error | Add nullable, backfill, then enforce NOT NULL. |
|
|
85
|
+
| PG005 | Adding validated foreign key | error | Add NOT VALID then VALIDATE CONSTRAINT separately. |
|
|
86
|
+
| PG006 | Renaming an object | error | Use an expand/contract deployment. |
|
|
87
|
+
| PG007 | Dropping index without CONCURRENTLY | error | Use DROP INDEX CONCURRENTLY where supported. |
|
|
88
|
+
| PG008 | Concurrent index operation inside transaction | error | Run outside BEGIN/COMMIT. |
|
|
89
|
+
| PG010 | Adding UNIQUE constraint | error | Consider a concurrent unique index and attach it where applicable. |
|
|
90
|
+
| PG011 | Dropping a table | error | Verify retention and application dependencies. |
|
|
91
|
+
| PG012 | Adding validated CHECK constraint | error | Add NOT VALID and validate separately. |
|
|
92
|
+
| PG013 | Legacy SET NOT NULL diagnostic (superseded by PG025) | error | Validate an equivalent CHECK constraint first. |
|
|
93
|
+
| PG014 | Adding column with default on PostgreSQL 10 | error | Use controlled backfill or evaluate upgrading PostgreSQL. |
|
|
94
|
+
| PG015 | Prisma concurrent index migration | warning | Use a separately managed nontransactional migration. |
|
|
95
|
+
| PG016 | Drizzle concurrent index migration | warning | Use a separately managed nontransactional migration. |
|
|
96
|
+
| PG017 | Potential cross-file dependency or Flyway transaction advisory | warning | Review migration order; this is a heuristic. |
|
|
97
|
+
| PG019 | MERGE requires PostgreSQL 15+ | error | Use a compatible INSERT ... ON CONFLICT pattern where applicable. |
|
|
98
|
+
| PG020 | UNIQUE NULLS NOT DISTINCT requires PostgreSQL 15+ | error | Use a version-compatible uniqueness strategy. |
|
|
99
|
+
| PG021 | Volatile default may rewrite table | error | Add column, backfill in batches, then set default. |
|
|
100
|
+
| PG022 | SET LOGGED rewrites table | error | Schedule controlled maintenance and evaluate alternatives. |
|
|
101
|
+
| PG023 | TRUNCATE removes table rows | error | Confirm retention, backups and downstream dependencies. |
|
|
102
|
+
| PG024 | Dropping a constraint | error | Review dependent queries and data-integrity requirements. |
|
|
103
|
+
| PG025 | SET NOT NULL may scan table | error | Backfill and validate a CHECK constraint first where appropriate. |
|
|
104
|
+
|
|
105
|
+
See the [full rule reference](docs/RULES.md) for defaults, version constraints and legacy identifiers. PG013 is superseded by PG025; PG009 and PG018 are unused.
|
|
106
|
+
|
|
107
|
+
## Reporting and configuration
|
|
108
|
+
|
|
109
|
+
Example configuration (`pg-safe-migrate.config.json`):
|
|
110
|
+
|
|
111
|
+
```json
|
|
112
|
+
{
|
|
113
|
+
"severity": "error",
|
|
114
|
+
"postgresVersion": 16,
|
|
115
|
+
"rules": { "PG015": "warning", "PG016": "warning" },
|
|
116
|
+
"exclude": ["archive"]
|
|
117
|
+
}
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
Report options: `--format text|json|sarif|markdown`, `--output <file>`, `--advisor`, `--postgres-version <major>`, and `--fail-on warning|error|none`.
|
|
121
|
+
|
|
122
|
+
Each finding includes a description of the risk and a suggested safer migration approach.
|
|
123
|
+
|
|
124
|
+
A passing result means no configured patterns were detected, not that a migration is guaranteed to be safe.
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
## Inline Rule Suppression
|
|
128
|
+
|
|
129
|
+
Introduced in v2.7.0, inline suppression allows teams to acknowledge reviewed migration risks without disabling an entire safety rule.
|
|
130
|
+
|
|
131
|
+
Suppression is disabled by default.
|
|
132
|
+
|
|
133
|
+
### Enable suppression
|
|
134
|
+
|
|
135
|
+
Create or update `pg-safe-migrate.config.json`:
|
|
136
|
+
|
|
137
|
+
```json
|
|
138
|
+
{
|
|
139
|
+
"suppression": {
|
|
140
|
+
"enabled": true,
|
|
141
|
+
"requireReason": true,
|
|
142
|
+
"reportSuppressed": true,
|
|
143
|
+
"protectedRules": ["PG011", "PG023"]
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
### Suppress a reviewed finding
|
|
149
|
+
|
|
150
|
+
```sql
|
|
151
|
+
-- pg-safe-migrate-disable-next-line PG002 -- reason: DBA approved after application compatibility review
|
|
152
|
+
ALTER TABLE users DROP COLUMN legacy_email;
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
The directive applies only to the immediately following SQL statement.
|
|
156
|
+
|
|
157
|
+
Multiple rule IDs can be specified using commas.
|
|
158
|
+
|
|
159
|
+
### Built-in safeguards
|
|
160
|
+
|
|
161
|
+
- Mandatory suppression reasons.
|
|
162
|
+
- PostgreSQL AST-based statement targeting.
|
|
163
|
+
- SQL-aware comment scanning.
|
|
164
|
+
- Protected rule enforcement.
|
|
165
|
+
- Unknown rule detection.
|
|
166
|
+
- Rejected and unused directive reporting.
|
|
167
|
+
- Fail-closed handling of ambiguous SQL scanning.
|
|
168
|
+
- Audit reporting in terminal, JSON, SARIF and Markdown.
|
|
169
|
+
- Suppression-aware VS Code diagnostics.
|
|
170
|
+
|
|
171
|
+
### Generate an audit report
|
|
172
|
+
|
|
173
|
+
```sh
|
|
174
|
+
npx --no-install pgsafe migrations \
|
|
175
|
+
--config pg-safe-migrate.config.json \
|
|
176
|
+
--format json \
|
|
177
|
+
--output migration-report.json
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
Suppressed findings remain available in the audit report.
|
|
181
|
+
|
|
182
|
+
### Enterprise Migration Governance
|
|
183
|
+
|
|
184
|
+
Teams can enforce additional suppression restrictions using a trusted gate policy.
|
|
185
|
+
|
|
186
|
+
Example `enterprise-policy.json`:
|
|
187
|
+
|
|
188
|
+
```json
|
|
189
|
+
{
|
|
190
|
+
"name": "Production Migration Safety",
|
|
191
|
+
"maxRiskScore": 60,
|
|
192
|
+
"maxWarnings": 5,
|
|
193
|
+
"blockedRules": ["PG002", "PG011", "PG023"],
|
|
194
|
+
"suppression": {
|
|
195
|
+
"protectedRules": ["PG008", "PG011", "PG023"],
|
|
196
|
+
"maxSuppressedFindings": 2,
|
|
197
|
+
"failOnRejected": true,
|
|
198
|
+
"failOnUnused": true
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
Run the enterprise gate:
|
|
204
|
+
|
|
205
|
+
```sh
|
|
206
|
+
npx --no-install pgsafe migrations \
|
|
207
|
+
--config pg-safe-migrate.config.json \
|
|
208
|
+
--gate-policy enterprise-policy.json \
|
|
209
|
+
--format json \
|
|
210
|
+
--output migration-report.json
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
Enterprise enforcement:
|
|
214
|
+
|
|
215
|
+
- Prevents suppression of blocked and protected rules.
|
|
216
|
+
- Includes suppressed findings in risk calculations.
|
|
217
|
+
- Enforces suppression limits.
|
|
218
|
+
- Rejects project exclusions and severity-weakening overrides.
|
|
219
|
+
- Can block a migration even when `--fail-on none` is supplied.
|
|
220
|
+
|
|
221
|
+
Use a separate trusted configuration for enterprise gates. Do not reuse ordinary lint configurations containing exclusions or warning/off rule overrides.
|
|
222
|
+
|
|
223
|
+
The CLI, policy, configuration and CI workflow must come from trusted sources.
|
|
224
|
+
|
|
225
|
+
### VS Code Integration
|
|
226
|
+
|
|
227
|
+
The PG Safe Migrate extension supports inline suppression through workspace configuration.
|
|
228
|
+
|
|
229
|
+
- Suppressed findings are removed from active diagnostics.
|
|
230
|
+
- Protected findings remain visible.
|
|
231
|
+
- Suppression audit counts appear in the PG Safe Migrate Output channel.
|
|
232
|
+
- Disabling suppression restores the original findings.
|
|
233
|
+
|
|
234
|
+
### Limitations
|
|
235
|
+
|
|
236
|
+
- Suppression is not evidence of migration safety.
|
|
237
|
+
- Some combinations of suppression, risk baselines and combined simulation are not supported.
|
|
238
|
+
- Static analysis cannot guarantee zero downtime.
|
|
239
|
+
|
|
240
|
+
## Advanced capabilities
|
|
241
|
+
|
|
242
|
+
- [Advanced usage, simulation, database inspection and limitations](docs/advanced.md)
|
|
243
|
+
- [Adoption and CI troubleshooting](docs/ADOPTION-GUIDE.md)
|
|
244
|
+
- [Release history](CHANGELOG.md)
|
|
245
|
+
- [Verification commands](ALL-MILESTONES-TESTING.md)
|
|
246
|
+
|
|
247
|
+
## Development
|
|
248
|
+
|
|
249
|
+
```sh
|
|
250
|
+
npm ci
|
|
251
|
+
npm run test:release
|
|
252
|
+
npm pack --dry-run
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md) and [SECURITY.md](SECURITY.md). MIT licensed.
|
package/SECURITY.md
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# Security policy
|
|
2
|
+
|
|
3
|
+
## Reporting
|
|
4
|
+
|
|
5
|
+
Use the repository [private vulnerability reporting page](https://github.com/subodhsingh001/pg-safe-migrate/security/advisories/new) if enabled. If unavailable, request a private reporting channel through a public issue without disclosing exploit details, credentials or customer SQL. Include affected version, environment and a minimal sanitized reproduction.
|
|
6
|
+
|
|
7
|
+
## Safety boundaries
|
|
8
|
+
|
|
9
|
+
Static linting does not execute migrations or guarantee downtime avoidance. Optional Docker simulation executes trusted SQL in disposable containers and is not a hostile-code sandbox. Database inspection requires least-privilege credentials. Do not submit secrets or production data. The extension file size and output limits are not hard process memory limits.
|
|
10
|
+
|
|
11
|
+
## Support
|
|
12
|
+
|
|
13
|
+
No formal support lifetime or response SLA is promised. Use the latest reviewed release and report reproducible security issues.
|
package/bin/cli.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { program } from 'commander';
|
|
5
|
+
import chalk from 'chalk';
|
|
6
|
+
import { createRequire } from 'node:module';
|
|
7
|
+
import { toGitHubAnnotations, toMarkdownSummary } from '../src/github.js';
|
|
8
|
+
import { summarizeRisk } from '../src/risk.js';
|
|
9
|
+
import { getPreset } from '../src/presets.js';
|
|
10
|
+
const require = createRequire(import.meta.url);
|
|
11
|
+
const { version } = require('../package.json');
|
|
12
|
+
import { findMigrationFiles } from '../src/detector.js';
|
|
13
|
+
import { getChangedSqlFiles } from '../src/gitDiff.js';
|
|
14
|
+
import { loadConfig, isExcluded } from '../src/config.js';
|
|
15
|
+
import { analyzeFiles } from '../src/analysis.js';
|
|
16
|
+
import { suppressionReport, suppressionText, suppressionMarkdown } from '../src/suppression-report.js';
|
|
17
|
+
import { toJson, toSarif, toMarkdownReport } from '../src/reports.js';
|
|
18
|
+
import { inspectDatabaseUrl } from '../src/db-inspect.js';
|
|
19
|
+
import { simulateSqlFile } from '../src/simulator.js';
|
|
20
|
+
import { combinedAssessment } from '../src/combined.js';
|
|
21
|
+
import { loadTeamPolicy, assessTeamPolicy, assessLintPolicy, validateGateConfig, applySuppressionPolicy, enforceSuppressionAudit } from '../src/team-policy.js';
|
|
22
|
+
import { loadProductionContext, productionAssessment } from '../src/production-context.js';
|
|
23
|
+
import { createRiskBaseline, loadRiskBaseline, compareRiskBaseline, writeRiskBaseline } from '../src/risk-baseline.js';
|
|
24
|
+
|
|
25
|
+
program.name('pgsafe').description('AST-based PostgreSQL migration risk linter (not a downtime guarantee)').version(version)
|
|
26
|
+
.argument('[target]', 'SQL file or migrations directory')
|
|
27
|
+
.option('-c, --changed [baseBranch]', 'Lint changed SQL files')
|
|
28
|
+
.option('--format <format>', 'text, json, sarif or markdown', 'text')
|
|
29
|
+
.option('--output <file>', 'Write report to file')
|
|
30
|
+
.option('--config <file>', 'JSON configuration file', 'pg-safe-migrate.config.json')
|
|
31
|
+
.option('--postgres-version <version>', 'Target PostgreSQL major version')
|
|
32
|
+
.option('--fail-on <severity>', 'warning, error or none', 'error')
|
|
33
|
+
.option('--advisor', 'Include deployment guidance')
|
|
34
|
+
.option('--preset <name>', 'recommended or strict', 'recommended')
|
|
35
|
+
.option('--github', 'Emit GitHub workflow annotations')
|
|
36
|
+
.option('--summary <file>', 'Write Markdown PR summary')
|
|
37
|
+
.option('--risk', 'Include heuristic risk score in text output')
|
|
38
|
+
.option('--production-context <file>', 'Optional read-only JSON production estimates for advisory output')
|
|
39
|
+
.option('--assess', 'Combine static linting with disposable PostgreSQL simulation')
|
|
40
|
+
.option('--verify-sql <file>', 'Run post-migration SQL assertions (SQL errors or exceptions fail verification)')
|
|
41
|
+
.option('--team-policy <file>', 'Local JSON team policy for combined assessment')
|
|
42
|
+
.option('--gate-policy <file>', 'Opt-in static CI gate policy (JSON); blocks matching risks')
|
|
43
|
+
.option('--write-risk-baseline <file>', 'Write baseline of current static findings (review before committing)')
|
|
44
|
+
.option('--risk-baseline <file>', 'Compare findings with a previously reviewed baseline')
|
|
45
|
+
.option('--simulate <sqlFile>', 'Execute one SQL file against a disposable Docker PostgreSQL container')
|
|
46
|
+
.option('--baseline <sqlFile>', 'Apply baseline SQL before simulation')
|
|
47
|
+
.option('--migrations-dir <directory>', 'Simulate top-level SQL migrations in filename order')
|
|
48
|
+
.option('--simulate-timeout <seconds>', 'Simulation execution timeout (10-300 seconds)', '60')
|
|
49
|
+
.option('--inspect-db', 'Inspect database catalog (requires DATABASE_URL and optional pg dependency)')
|
|
50
|
+
.action(async (target,opts)=>{
|
|
51
|
+
try {
|
|
52
|
+
if (!['text','json','sarif','markdown'].includes(opts.format)) throw new Error('format must be text, json, sarif or markdown');
|
|
53
|
+
if (!['none','warning','error'].includes(opts.failOn)) throw new Error('fail-on must be none, warning or error');
|
|
54
|
+
const preset = getPreset(opts.preset);
|
|
55
|
+
const userConfig = loadConfig(opts.config);
|
|
56
|
+
const config = { ...preset, ...userConfig, rules: { ...preset.rules, ...userConfig.rules } };
|
|
57
|
+
if(opts.postgresVersion!==undefined) {
|
|
58
|
+
const version=Number(opts.postgresVersion);
|
|
59
|
+
if (!Number.isInteger(version)||version<10||version>99) throw new Error('postgres-version must be an integer >= 10');
|
|
60
|
+
config.postgresVersion=version;
|
|
61
|
+
}
|
|
62
|
+
if ((opts.gatePolicy || opts.riskBaseline || opts.writeRiskBaseline || opts.productionContext) && (opts.assess || opts.simulate || opts.migrationsDir || opts.inspectDb)) throw new Error('--gate-policy is for static lint mode only');
|
|
63
|
+
if (config.suppression?.enabled && (opts.assess || opts.teamPolicy || ((opts.riskBaseline || opts.writeRiskBaseline) && opts.gatePolicy))) throw new Error('Inline suppression is not supported with combined assessment or gate plus risk baseline');
|
|
64
|
+
if (opts.assess) {
|
|
65
|
+
const policy = opts.teamPolicy ? loadTeamPolicy(opts.teamPolicy) : null;
|
|
66
|
+
validateGateConfig(config, policy);
|
|
67
|
+
const assessment = await combinedAssessment({ file: opts.simulate, migrationsDir: opts.migrationsDir, baseline: opts.baseline, verifySql: opts.verifySql, postgresVersion: String(opts.postgresVersion ?? '16'), config });
|
|
68
|
+
if (policy) assessment.teamPolicy = assessTeamPolicy(assessment, policy);
|
|
69
|
+
if (opts.output) { fs.mkdirSync(path.dirname(path.resolve(opts.output)), {recursive:true}); fs.writeFileSync(opts.output, JSON.stringify(assessment,null,2)+'\n'); }
|
|
70
|
+
else console.log(JSON.stringify(assessment,null,2));
|
|
71
|
+
process.exitCode = assessment.passed && (!assessment.teamPolicy || assessment.teamPolicy.passed) ? 0 : 1;
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
if (opts.simulate || opts.migrationsDir) {
|
|
75
|
+
const result = simulateSqlFile(opts.simulate, { baseline: opts.baseline, migrationsDir: opts.migrationsDir, postgresVersion: String(opts.postgresVersion ?? '16'), timeoutSeconds: Number(opts.simulateTimeout), verifySql: opts.verifySql });
|
|
76
|
+
console.log(JSON.stringify(result, null, 2));
|
|
77
|
+
process.exitCode = result.passed ? 0 : 1;
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
if (opts.inspectDb) {
|
|
81
|
+
const snapshot = await inspectDatabaseUrl(process.env.DATABASE_URL);
|
|
82
|
+
console.log(JSON.stringify(snapshot, null, 2));
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
const gatePolicy = opts.gatePolicy ? loadTeamPolicy(opts.gatePolicy) : null;
|
|
86
|
+
validateGateConfig(config, gatePolicy);
|
|
87
|
+
if (gatePolicy?.requireSimulation) throw new Error('requireSimulation requires --assess with a disposable PostgreSQL simulation');
|
|
88
|
+
const files=(opts.changed?getChangedSqlFiles(typeof opts.changed==='string'?opts.changed:undefined):findMigrationFiles(target)).filter(f=>!isExcluded(f,config.exclude));
|
|
89
|
+
const entries=files.map(file=>({file:path.relative(process.cwd(),file)||file,sql:fs.readFileSync(file,'utf8')}));
|
|
90
|
+
const suppressionAudit = [];
|
|
91
|
+
const findings=await analyzeFiles(entries,applySuppressionPolicy(config, gatePolicy),{advisor:opts.advisor,suppressionAudit});
|
|
92
|
+
const suppression = config.suppression?.enabled ? suppressionReport(suppressionAudit) : undefined;
|
|
93
|
+
const allFindings = [...findings, ...suppressionAudit.filter(r => r.status === 'suppressed').map(r => r.finding)];
|
|
94
|
+
const production = opts.productionContext ? productionAssessment(allFindings, loadProductionContext(opts.productionContext)) : null;
|
|
95
|
+
if (opts.writeRiskBaseline && opts.riskBaseline) throw new Error('Cannot combine --write-risk-baseline and --risk-baseline');
|
|
96
|
+
if (opts.writeRiskBaseline && opts.gatePolicy) throw new Error('Baseline creation cannot be combined with a gate policy');
|
|
97
|
+
const baselineComparison = opts.riskBaseline ? compareRiskBaseline(allFindings, entries, loadRiskBaseline(opts.riskBaseline)) : null;
|
|
98
|
+
// In baseline mode, only newly introduced findings are subject to the opt-in gate.
|
|
99
|
+
const gateFindings = baselineComparison ? baselineComparison.newFindings : findings;
|
|
100
|
+
const gate = opts.gatePolicy ? enforceSuppressionAudit(assessLintPolicy(suppression ? allFindings : gateFindings, gatePolicy, summarizeRisk(suppression ? allFindings : gateFindings)), gatePolicy, suppression) : null;
|
|
101
|
+
if (opts.writeRiskBaseline) writeRiskBaseline(opts.writeRiskBaseline, createRiskBaseline(allFindings, entries));
|
|
102
|
+
if (opts.github) process.stdout.write(toGitHubAnnotations(findings));
|
|
103
|
+
if (opts.summary) {fs.mkdirSync(path.dirname(path.resolve(opts.summary)),{recursive:true});fs.writeFileSync(opts.summary,toMarkdownSummary(findings,files.length) + (suppression ? suppressionMarkdown(suppression) : ''));}
|
|
104
|
+
const report=opts.format==='json'?toJson(findings,{filesChecked:files.length,postgresVersion:config.postgresVersion,...(suppression ? { suppression } : {})}):opts.format==='sarif'?toSarif(findings,suppression):opts.format==='markdown'?toMarkdownReport(findings,{filesChecked:files.length,postgresVersion:config.postgresVersion,risk:opts.risk?summarizeRisk(allFindings):undefined,suppression}):[
|
|
105
|
+
...findings.flatMap(f=>[`${f.file}:${f.line}:${f.column} [${f.ruleId}] ${f.severity}: ${f.message}`,` Fix: ${f.fix}`,...(f.advisor?f.advisor.steps.map((s,i)=>` ${i+1}. ${s}`):[])]),
|
|
106
|
+
...(opts.risk?[`Risk: ${JSON.stringify(summarizeRisk(allFindings))}`]:[]),
|
|
107
|
+
...(suppression ? [suppressionText(suppression)] : []),
|
|
108
|
+
`Checked ${files.length} SQL file(s); found ${findings.length} configured risk(s). No downtime guarantee.`
|
|
109
|
+
].join('\n');
|
|
110
|
+
const gateReport = opts.format === 'json' && (gate || baselineComparison || production) ? JSON.stringify({ ...JSON.parse(report), ...(baselineComparison ? { baseline: { newCount: baselineComparison.newCount, existingCount: baselineComparison.existingCount, resolvedCount: baselineComparison.resolvedCount, newFindings: baselineComparison.newFindings } } : {}), ...(production ? { production } : {}), ...(gate ? { gate: { name: gate.name, decision: gate.passed ? 'PASS' : 'BLOCK', passed: gate.passed, reasons: gate.reasons, note: gate.note } } : {}) }, null, 2) : report;
|
|
111
|
+
if(opts.output) {fs.mkdirSync(path.dirname(path.resolve(opts.output)),{recursive:true});fs.writeFileSync(opts.output,gateReport+'\n');}
|
|
112
|
+
else console.log(opts.format==='text'?(findings.length?chalk.yellow(gateReport):chalk.green(gateReport)):gateReport);
|
|
113
|
+
if (production && opts.format !== 'json') console.error(`[PG Safe Migrate production] Advisory context evaluated for ${production.assessments.length} finding(s). Use --format json for details. No downtime guarantee.`);
|
|
114
|
+
if (baselineComparison && opts.format !== 'json') console.error(`[PG Safe Migrate baseline] ${baselineComparison.newCount} new, ${baselineComparison.existingCount} existing, ${baselineComparison.resolvedCount} resolved finding(s).`);
|
|
115
|
+
if (opts.writeRiskBaseline) console.error(`[PG Safe Migrate baseline] Wrote ${allFindings.length} finding fingerprint(s) to ${opts.writeRiskBaseline}; review before committing.`);
|
|
116
|
+
if (gate) console.error(`[PG Safe Migrate gate] ${gate.passed ? 'PASS' : 'BLOCK'} (${gate.name})${gate.reasons.length ? ': '+gate.reasons.join('; ') : ''}. ${gate.note}`);
|
|
117
|
+
process.exitCode=(gate && !gate.passed) || (opts.failOn==='warning' && gateFindings.length>0) || (opts.failOn==='error' && gateFindings.some(f=>f.severity==='error')) ? 1 : 0;
|
|
118
|
+
}catch(e){console.error(`Error: ${e.message}`);process.exitCode=2;}
|
|
119
|
+
});
|
|
120
|
+
program.parse();
|