From 04e7f1f9b6034293706e656be9a435f1b2730af1 Mon Sep 17 00:00:00 2001 From: mihir Date: Thu, 8 Oct 2026 22:20:21 +0530 Subject: [PATCH 1/2] fix(security): patch Express proxy trust subnet handling --- pnpm-lock.yaml | 9 +++++---- pnpm-workspace.yaml | 1 + scripts/test/proxy-trust.test.mjs | 16 ++++++++++++++++ 3 files changed, 22 insertions(+), 4 deletions(-) create mode 100644 scripts/test/proxy-trust.test.mjs diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 357c6c2..db9adc7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -10,6 +10,7 @@ overrides: '@nestjs/platform-express>multer': 2.4.0 '@nestjs/swagger>js-yaml': 5.4.1 ajv>fast-uri: 3.1.8 + express>proxy-addr: 2.0.8 importers: @@ -2449,8 +2450,8 @@ packages: proper-lockfile@4.1.2: resolution: {integrity: sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==} - proxy-addr@2.0.7: - resolution: {integrity: sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==} + proxy-addr@2.0.8: + resolution: {integrity: sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==} engines: {node: '>= 0.10'} pure-rand@6.1.0: @@ -4505,7 +4506,7 @@ snapshots: on-finished: 2.4.1 once: 1.4.0 parseurl: 1.3.3 - proxy-addr: 2.0.7 + proxy-addr: 2.0.8 qs: 6.16.0 range-parser: 1.3.0 router: 2.2.0(supports-color@8.1.1) @@ -5382,7 +5383,7 @@ snapshots: retry: 0.12.0 signal-exit: 3.0.7 - proxy-addr@2.0.7: + proxy-addr@2.0.8: dependencies: forwarded: 0.2.0 ipaddr.js: 1.9.1 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 0b4732c..823b15a 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -11,3 +11,4 @@ overrides: '@nestjs/platform-express>multer': 2.4.0 '@nestjs/swagger>js-yaml': 5.4.1 'ajv>fast-uri': 3.1.8 + 'express>proxy-addr': 2.0.8 diff --git a/scripts/test/proxy-trust.test.mjs b/scripts/test/proxy-trust.test.mjs new file mode 100644 index 0000000..1935adc --- /dev/null +++ b/scripts/test/proxy-trust.test.mjs @@ -0,0 +1,16 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createRequire } from 'node:module'; + +test('Express rejects IPv4 peers outside the configured trust subnet', () => { + const require = createRequire(import.meta.url); + const platformRequire = createRequire( + require.resolve('@nestjs/platform-express'), + ); + const expressRequire = createRequire(platformRequire.resolve('express')); + const proxyaddr = expressRequire('proxy-addr'); + assert.equal(proxyaddr.compile('::ffff:10.0.0.0/8')('203.0.113.10'), false); + const trust = proxyaddr.compile('10.0.0.0/8'); + assert.equal(trust('10.1.2.3'), true); + assert.equal(trust('203.0.113.10'), false); +}); -- 2.40.1 From a83a0c0742b6e868291c5ed928d8ef133051f7ee Mon Sep 17 00:00:00 2001 From: mihir Date: Thu, 8 Oct 2026 22:36:12 +0530 Subject: [PATCH 2/2] feat(ci): require native concurrency evidence and document release gates --- .gitea/workflows/backend.yml | 46 ++++++++++++----- README.md | 2 + docs/production-readiness.md | 42 ++++++++++++++++ docs/roadmap.md | 4 ++ package.json | 4 +- scripts/test-native.mjs | 83 +++++++++++++++++++++++++++++++ scripts/test/native-gate.test.mjs | 55 ++++++++++++++++++++ 7 files changed, 222 insertions(+), 14 deletions(-) create mode 100644 docs/production-readiness.md create mode 100644 scripts/test-native.mjs create mode 100644 scripts/test/native-gate.test.mjs diff --git a/.gitea/workflows/backend.yml b/.gitea/workflows/backend.yml index be59bc1..a052b2c 100644 --- a/.gitea/workflows/backend.yml +++ b/.gitea/workflows/backend.yml @@ -7,27 +7,47 @@ on: jobs: quality: runs-on: ubuntu-latest + container: node:24.15-bookworm + timeout-minutes: 30 + env: + DATABASE_URL: postgresql://postgres:postgres@127.0.0.1:5432/postgres + TEST_DATABASE_URL: '' + steps: + - uses: https://github.com/actions/checkout@v4 + - name: Install locked dependencies + run: npm install --global pnpm@11.19.0 && pnpm install --frozen-lockfile + - name: Audit production dependencies + run: pnpm security:audit + - name: Generate Prisma client + run: pnpm db:generate + - name: Validate embedded migration upgrade and schema drift + run: pnpm db:test + - name: Formatting, types, tooling, coverage and build + run: pnpm check + native-postgres: + runs-on: ubuntu-latest + container: node:24.15-bookworm + timeout-minutes: 15 services: postgres: image: postgres:17 env: POSTGRES_USER: mani - POSTGRES_PASSWORD: ci_only_password + POSTGRES_PASSWORD: ${{ secrets.CI_POSTGRES_PASSWORD }} POSTGRES_DB: mani_ci options: >- --health-cmd "pg_isready -U mani -d mani_ci" --health-interval 5s --health-timeout 5s --health-retries 10 env: - DATABASE_URL: postgresql://mani:ci_only_password@postgres:5432/mani_ci - TEST_DATABASE_URL: postgresql://mani:ci_only_password@postgres:5432/mani_ci + DATABASE_URL: postgresql://mani:${{ secrets.CI_POSTGRES_PASSWORD }}@postgres:5432/mani_ci + TEST_DATABASE_URL: postgresql://mani:${{ secrets.CI_POSTGRES_PASSWORD }}@postgres:5432/mani_ci steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - with: - node-version: '24' - - run: npm install --global pnpm@11.19.0 - - run: pnpm install --frozen-lockfile - - run: pnpm security:audit - - run: pnpm db:generate - - run: node scripts/verify-migrations.mjs - - run: pnpm check + - uses: https://github.com/actions/checkout@v4 + - name: Install locked dependencies + run: npm install --global pnpm@11.19.0 && pnpm install --frozen-lockfile + - name: Generate Prisma client + run: pnpm db:generate + - name: Validate native migration upgrade and schema drift + run: node scripts/verify-migrations.mjs + - name: Require native concurrency tests without skips + run: pnpm test:native diff --git a/README.md b/README.md index 9ec2900..44500cd 100644 --- a/README.md +++ b/README.md @@ -98,3 +98,5 @@ Accounting source events: see [Phase 5D API guide](docs/accounting-source-feed-a Indicative batch material contribution: see [Phase 5E API guide](docs/batch-contribution-api.md). Bounded order expiry automation: see [Phase 5F API guide](docs/order-expiry-workflow-api.md). + +Production verification gates and launch procedure: see [Phase 6A runbook](docs/production-readiness.md). diff --git a/docs/production-readiness.md b/docs/production-readiness.md new file mode 100644 index 0000000..8d77957 --- /dev/null +++ b/docs/production-readiness.md @@ -0,0 +1,42 @@ +# Phase 6A: release gates and production readiness + +This milestone prepares repeatable verification and the launch procedure. It does not deploy the service or establish that the production environment is ready. + +## Required merge checks + +The `Backend quality` workflow runs on feature/fix pushes, main pushes and pull requests targeting main. Two independent jobs must pass: + +| Job | Evidence | +| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `quality` | Frozen dependency installation, production dependency audit, embedded migration deployment/status/drift, immutable migration hashes, formatting, Prisma validation, TypeScript, tooling tests, coverage and compilation. | +| `native-postgres` | PostgreSQL 17 migration deployment/status/drift and the existing checkout, inventory, recovery and outbox concurrency tests. The gate fails on missing configuration, failures, empty results or any skipped/todo test. | + +Configure a Docker-capable Gitea runner with the existing `ubuntu-latest` label, able to pull Node/PostgreSQL images, GitHub checkout and npm packages. Both jobs explicitly run in `node:24.15-bookworm`; the native job reaches its database by the `postgres` service hostname. Absolute action URLs avoid dependence on the instance's default action host; see [Gitea action compatibility](https://docs.gitea.com/usage/actions/comparison/). + +Enable Actions for the repository and instance if it is disabled. An unavailable Actions page does not establish whether execution is disabled or the viewer lacks permission; inspect the authenticated settings and runner status before claiming the gates are active. + +Add repository Actions secret `CI_POSTGRES_PASSWORD`: a random alphanumeric password used only for the disposable CI PostgreSQL service. Alphanumeric characters keep the connection URL valid without URL encoding. CI tests create and drop isolated databases, so the CI role needs `CREATEDB`. Never supply a production database URL or credentials. No service port is published to the runner host. + +Express's transitive `proxy-addr` is pinned to 2.0.8 through the existing workspace override mechanism to address [GHSA-jqcg-44mw-7w3h](https://github.com/advisories/GHSA-jqcg-44mw-7w3h). Keep the production audit gate enabled; remove the override when the upstream dependency graph resolves a patched version itself. + +In Gitea branch protection for `main`, require both job statuses using their exact names from the first successful run, require review, and disable force pushes. These repository settings are operational prerequisites; committing YAML does not enable branch protection or register a runner. + +The existing `.drone.yml` is a separate build/deploy pipeline: a push to `main` publishes `git.midastix.com/ci-docker-repo-user/manicandle-backend:latest` and then invokes the server deployment script. It does not wait for the new Gitea jobs. Require the reviewed commit's checks before merging and avoid direct main pushes; otherwise deployment can run before validation completes. Its registry secrets are Drone repository secrets `docker_username` and `docker_password`, not `CI_POSTGRES_PASSWORD`. For `unauthorized: reqPackageAccess`, verify that the credentials belong to the target package owner or an authorized publisher, and use a Gitea token with package write access. Retrying a successful main build also runs deployment; server credentials and settings are managed manually by the operator. + +Locally, run `pnpm check` and `pnpm db:test`. To exercise all six native-only tests and the surrounding regression cases, provide `TEST_DATABASE_URL` for a disposable native PostgreSQL administrator connection, then run `pnpm test:native`. The native command uses the normal test helper to create separate randomly named databases and remove them afterward. Embedded PostgreSQL is useful for ordinary tests but does not prove multi-connection locking behavior. + +## Staging and launch procedure + +1. Select a reviewed commit whose two CI jobs pass. Record its SHA, the previous release SHA and migration manifest. Agree on the launch feature cut: payments, carriers, live marketing and automated scheduler invocation remain deferred. +2. Provision the deployment target, TLS boundary and PostgreSQL 17 service. Store secrets outside Git and logs; separate migration, application and CI database roles. Verify connection limits against `DATABASE_POOL_SIZE` and replica count. Configure explicit HTTPS `CORS_ORIGINS`, `NODE_ENV=production` and `SWAGGER_ENABLED=false`. Configure recovery SMTP and the HTTPS recovery URL together before promising password recovery. Validate network-boundary rate limiting and proxy behavior against [VAPT readiness](vapt-readiness.md). +3. Build the existing image or compiled application from that exact commit. For a source installation: `pnpm install --frozen-lockfile`, `pnpm db:generate`, `pnpm build`. The current Dockerfile is a development-derived build; non-root runtime, graceful shutdown verification, image scanning and a tested deployment definition remain launch work, not proven by this CI milestone. +4. Take a database backup and restore it into isolated staging. Verify representative immutable audit, order, supplier-payment and inventory records after restore. Keep production secrets and outbound provider access out of the staging restore. +5. Run `pnpm migrations:check`, then `pnpm db:deploy` and `pnpm db:status` against staging with migration credentials. Start the built service with restricted application credentials. Verify `/api/v1/health/live` and `/api/v1/health/ready`; readiness must fail when PostgreSQL is unavailable. +6. Smoke-test login, denied/foreign-organization access, checkout and cancellation/hold release, procurement and stock reads, and expiry replay using staging identities. Confirm errors/logs omit credentials, tokens, addresses and document bodies. Exercise the deployment's shutdown/restart behavior before enabling traffic. +7. After the restore drill and staging checks pass, take a fresh production backup, apply reviewed additive migrations, deploy the same artifact and verify readiness before routing traffic. Keep a named operator monitoring health, errors, latency, database connections and integrity-sensitive flows during the first hour. Define alert destinations and acceptable baselines for the actual environment before launch. + +## Rollback and remaining decisions + +Stop scheduler invocation and route traffic back to the previous compatible application artifact if readiness, authentication, stock integrity or error/latency checks regress. Preserve additive tables, audit history, completed expiry runs and released holds; an application rollback cannot reopen cancelled orders. Never edit committed migration SQL or reverse financial/stock history with database deletes. A destructive schema rollback or database restore requires a separate incident decision, an assessed data-loss window and reconciliation. + +Before public launch, the operator still needs to select the host/database/secret store, enable and observe both CI jobs, configure branch protection, validate backup restoration, complete monitoring and incident ownership, verify the runtime container/process lifecycle, settle tax/shipping/retention policy and perform deployed-environment security testing. Live providers and SaaS tenancy/billing remain separate decisions. diff --git a/docs/roadmap.md b/docs/roadmap.md index d0cd714..f4f0331 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -74,6 +74,10 @@ Moderated forums, advanced analytics, forecasts, accounting adapters, profitabil - 5E (material-contribution baseline implemented): explicit net-price scenarios against sealed batch material/packaging cost, signed exact contribution, upward break-even prices and zero-output handling. Realized net profit, complete expense/COGS attribution, sales-to-batch linkage and dashboards remain separate milestones. - 5F (expiry workflow implemented): bounded, idempotent expired-order sweeps with shared cancellation/hold-release logic, immutable run history, atomic rollback and an authenticated scheduler-ready command. Deployment scheduling, broader workflow rules, live providers and complete production launch work remain separate milestones. +## Phase 6: Production readiness + +- 6A (release gates implemented; operational activation pending): separate embedded quality and native PostgreSQL concurrency jobs, fail-closed native test evidence, and a staging/backup/rollback runbook. Runner/secret setup, required branch checks, observed remote CI, hardened runtime, deployment infrastructure, restore drills, monitoring and live launch remain operational or later milestones. + ## Definition of done for every feature Small cohesive files; no duplicated business rules; unit tests for success, failure and boundaries; HTTP/integration tests where behavior crosses boundaries; schema migration and upgrade validation when persistence changes; documented API and permission contract; passing checks; focused Conventional Commit; reviewed pull request. Do not mark an entire phase complete until its end-to-end acceptance criteria pass. diff --git a/package.json b/package.json index 1ecfab9..31bd6f1 100644 --- a/package.json +++ b/package.json @@ -19,7 +19,9 @@ "db:validate": "prisma validate", "db:migrate": "prisma migrate dev", "db:deploy": "prisma migrate deploy", - "check": "pnpm migrations:check && pnpm format:check && pnpm db:validate && pnpm typecheck && pnpm test:coverage && pnpm build", + "check": "pnpm migrations:check && pnpm format:check && pnpm db:validate && pnpm typecheck && pnpm test:tooling && pnpm test:coverage && pnpm build", + "test:tooling": "node --test scripts/test/*.test.mjs", + "test:native": "node scripts/test-native.mjs", "start:watch": "node --watch dist/main.js", "db:status": "prisma migrate status", "bootstrap:owner": "node dist/cli/bootstrap-owner.js", diff --git a/scripts/test-native.mjs b/scripts/test-native.mjs new file mode 100644 index 0000000..b4f3cc3 --- /dev/null +++ b/scripts/test-native.mjs @@ -0,0 +1,83 @@ +import { spawnSync } from 'node:child_process'; +import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +export function assertNativeReport(report) { + const nativeTests = (report.testResults ?? []).flatMap((suite) => + (suite.assertionResults ?? []).filter((test) => + test.fullName.includes('native PostgreSQL'), + ), + ); + if ( + report.success !== true || + nativeTests.length < 6 || + !(report.numTotalTests > 0) || + report.numPassedTests !== report.numTotalTests || + report.numPendingTests !== 0 || + report.numTodoTests !== 0 || + report.numRuntimeErrorTestSuites !== 0 + ) { + throw new Error( + 'Native PostgreSQL gate requires all six concurrency checks and no skipped tests', + ); + } +} + +function run() { + const value = process.env.TEST_DATABASE_URL; + if ( + !value || + !URL.canParse(value) || + !['postgres:', 'postgresql:'].includes(new URL(value).protocol) + ) { + throw new Error( + 'TEST_DATABASE_URL must identify a disposable native PostgreSQL database', + ); + } + const directory = mkdtempSync(join(tmpdir(), 'mani-native-')); + try { + const reportPath = join(directory, 'report.json'); + const child = spawnSync( + process.execPath, + [ + '--experimental-vm-modules', + 'node_modules/jest/bin/jest.js', + '--runInBand', + '--runTestsByPath', + 'test/checkout-concurrency.spec.ts', + 'test/events-concurrency.spec.ts', + 'test/inventory.spec.ts', + 'test/migration-integrity.spec.ts', + '--json', + '--outputFile', + reportPath, + ], + { stdio: 'inherit', env: process.env }, + ); + if (child.error) throw new Error('Could not start native PostgreSQL tests'); + if (child.status !== 0) throw new Error('Native PostgreSQL tests failed'); + assertNativeReport(JSON.parse(readFileSync(reportPath, 'utf8'))); + console.log('Native PostgreSQL gate passed: no selected tests skipped'); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +} + +if ( + process.argv[1] && + resolve(process.argv[1]) === fileURLToPath(import.meta.url) +) { + try { + run(); + } catch (error) { + // Database credentials and provider errors must not appear in gate diagnostics. + console.error( + error instanceof Error && error.message.startsWith('Native PostgreSQL') + ? error.message + : 'Native gate failed; check TEST_DATABASE_URL and test output', + ); + process.exitCode = 1; + } +} diff --git a/scripts/test/native-gate.test.mjs b/scripts/test/native-gate.test.mjs new file mode 100644 index 0000000..dd45809 --- /dev/null +++ b/scripts/test/native-gate.test.mjs @@ -0,0 +1,55 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { assertNativeReport } from '../test-native.mjs'; + +const passing = { + success: true, + numTotalTests: 6, + numPassedTests: 6, + numPendingTests: 0, + numTodoTests: 0, + numRuntimeErrorTestSuites: 0, + testResults: [ + { + assertionResults: Array.from({ length: 6 }, () => ({ + fullName: 'native PostgreSQL concurrency check', + })), + }, + ], +}; + +test('requires complete passing evidence, including zero skipped tests', () => { + assert.doesNotThrow(() => assertNativeReport(passing)); + for (const changed of [ + { success: false }, + { numTotalTests: 0, numPassedTests: 0 }, + { numPassedTests: 5 }, + { numPendingTests: 1 }, + { numTodoTests: 1 }, + { numRuntimeErrorTestSuites: 1 }, + { testResults: [] }, + { + testResults: [ + { assertionResults: [{ fullName: 'ordinary embedded test' }] }, + ], + }, + ]) + assert.throws(() => assertNativeReport({ ...passing, ...changed })); +}); + +test('rejects absent or invalid database configuration without leaking it', () => { + for (const value of [ + '', + 'https://user:private-password@localhost/db', + 'invalid', + ]) { + const child = spawnSync(process.execPath, ['scripts/test-native.mjs'], { + env: { ...process.env, TEST_DATABASE_URL: value }, + encoding: 'utf8', + }); + assert.equal(child.status, 1); + assert.match(child.stderr, /Native gate failed/); + assert.doesNotMatch(child.stderr, /private-password/); + } +}); -- 2.40.1