Compare commits
1 Commits
devin/1776
...
devin/1776
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d6d74f2267 |
177
.github/workflows/ci.yml
vendored
177
.github/workflows/ci.yml
vendored
@@ -7,139 +7,132 @@ on:
|
||||
branches: [main, develop]
|
||||
|
||||
jobs:
|
||||
# Frontend CI
|
||||
frontend-lint:
|
||||
name: Frontend Lint
|
||||
# -------------------------------------------------------------------------
|
||||
# Portal (Vite + React, lives at repo root after the webapp/ gitlink was
|
||||
# removed in PR #4)
|
||||
# -------------------------------------------------------------------------
|
||||
portal-lint:
|
||||
name: Portal Lint
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-node@v6
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "18"
|
||||
node-version: "20"
|
||||
cache: "npm"
|
||||
cache-dependency-path: webapp/package-lock.json
|
||||
- name: Install dependencies
|
||||
working-directory: webapp
|
||||
run: npm ci
|
||||
- name: Lint
|
||||
working-directory: webapp
|
||||
run: npm run lint
|
||||
- run: npm ci
|
||||
- run: npm run lint
|
||||
|
||||
frontend-type-check:
|
||||
name: Frontend Type Check
|
||||
portal-type-check:
|
||||
name: Portal Type Check
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-node@v6
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "18"
|
||||
node-version: "20"
|
||||
cache: "npm"
|
||||
cache-dependency-path: webapp/package-lock.json
|
||||
- name: Install dependencies
|
||||
working-directory: webapp
|
||||
run: npm ci
|
||||
- name: Type check
|
||||
working-directory: webapp
|
||||
run: npx tsc --noEmit
|
||||
- run: npm ci
|
||||
- run: npx tsc --noEmit
|
||||
|
||||
frontend-build:
|
||||
name: Frontend Build
|
||||
portal-build:
|
||||
name: Portal Build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-node@v6
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "18"
|
||||
node-version: "20"
|
||||
cache: "npm"
|
||||
cache-dependency-path: webapp/package-lock.json
|
||||
- name: Install dependencies
|
||||
working-directory: webapp
|
||||
run: npm ci
|
||||
- name: Build
|
||||
working-directory: webapp
|
||||
run: npm run build
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
- run: npm ci
|
||||
- run: npm run build
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: frontend-build
|
||||
path: webapp/.next
|
||||
name: portal-dist
|
||||
path: dist
|
||||
|
||||
frontend-e2e:
|
||||
name: Frontend E2E Tests
|
||||
# -------------------------------------------------------------------------
|
||||
# Orchestrator (TypeScript + Express + Jest)
|
||||
# -------------------------------------------------------------------------
|
||||
orchestrator-type-check:
|
||||
name: Orchestrator Type Check
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: orchestrator
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-node@v6
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "18"
|
||||
node-version: "20"
|
||||
cache: "npm"
|
||||
cache-dependency-path: webapp/package-lock.json
|
||||
- name: Install dependencies
|
||||
working-directory: webapp
|
||||
run: npm ci
|
||||
- name: Install Playwright
|
||||
working-directory: webapp
|
||||
run: npx playwright install --with-deps
|
||||
- name: Run E2E tests
|
||||
working-directory: webapp
|
||||
run: npm run test:e2e
|
||||
- name: Upload test results
|
||||
uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
with:
|
||||
name: playwright-report
|
||||
path: webapp/playwright-report/
|
||||
cache-dependency-path: orchestrator/package-lock.json
|
||||
- run: npm ci
|
||||
- run: npx tsc --noEmit
|
||||
|
||||
# Orchestrator CI
|
||||
orchestrator-build:
|
||||
name: Orchestrator Build
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: orchestrator
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-node@v6
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "18"
|
||||
node-version: "20"
|
||||
cache: "npm"
|
||||
cache-dependency-path: orchestrator/package-lock.json
|
||||
- name: Install dependencies
|
||||
working-directory: orchestrator
|
||||
run: npm ci
|
||||
- name: Build
|
||||
working-directory: orchestrator
|
||||
run: npm run build
|
||||
- run: npm ci
|
||||
- run: npm run build
|
||||
|
||||
# Smart Contracts CI
|
||||
orchestrator-test:
|
||||
name: Orchestrator Test
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: orchestrator
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "20"
|
||||
cache: "npm"
|
||||
cache-dependency-path: orchestrator/package-lock.json
|
||||
- run: npm ci
|
||||
- run: npm test -- --ci
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Smart Contracts (Hardhat)
|
||||
# -------------------------------------------------------------------------
|
||||
contracts-compile:
|
||||
name: Contracts Compile
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: contracts
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-node@v6
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "18"
|
||||
node-version: "20"
|
||||
cache: "npm"
|
||||
cache-dependency-path: contracts/package-lock.json
|
||||
- name: Install dependencies
|
||||
working-directory: contracts
|
||||
run: npm ci
|
||||
- name: Compile contracts
|
||||
working-directory: contracts
|
||||
run: npm run compile
|
||||
- run: npm ci
|
||||
- run: npm run compile
|
||||
|
||||
contracts-test:
|
||||
name: Contracts Test
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: contracts
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-node@v6
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "18"
|
||||
node-version: "20"
|
||||
cache: "npm"
|
||||
cache-dependency-path: contracts/package-lock.json
|
||||
- name: Install dependencies
|
||||
working-directory: contracts
|
||||
run: npm ci
|
||||
- name: Run tests
|
||||
working-directory: contracts
|
||||
run: npm run test
|
||||
|
||||
- run: npm ci
|
||||
- run: npm run test
|
||||
|
||||
@@ -22,6 +22,10 @@ const envSchema = z.object({
|
||||
CHAIN_138_CHAIN_ID: z.string().regex(/^\d+$/).optional(),
|
||||
NOTARY_REGISTRY_ADDRESS: z.string().regex(/^0x[0-9a-fA-F]{40}$/).optional(),
|
||||
ORCHESTRATOR_PRIVATE_KEY: z.string().regex(/^0x[0-9a-fA-F]{64}$/).optional(),
|
||||
// Event bus signing (arch §7 + §13 non-repudiation). Defaults to a
|
||||
// dev placeholder; boot-time assertion refuses this placeholder in
|
||||
// NODE_ENV=production.
|
||||
EVENT_BUS_HMAC_SECRET: z.string().min(32).optional(),
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -44,8 +48,78 @@ export const env = envSchema.parse({
|
||||
CHAIN_138_CHAIN_ID: process.env.CHAIN_138_CHAIN_ID,
|
||||
NOTARY_REGISTRY_ADDRESS: process.env.NOTARY_REGISTRY_ADDRESS,
|
||||
ORCHESTRATOR_PRIVATE_KEY: process.env.ORCHESTRATOR_PRIVATE_KEY,
|
||||
EVENT_BUS_HMAC_SECRET: process.env.EVENT_BUS_HMAC_SECRET,
|
||||
});
|
||||
|
||||
/**
|
||||
* Dev-mode placeholders that must never be used in NODE_ENV=production.
|
||||
* Kept in sync with the `||` / `??` fallbacks sprinkled through the
|
||||
* codebase (env.ts, eventBus.ts, …) — if those placeholders change,
|
||||
* update this list too.
|
||||
*/
|
||||
const DEV_PLACEHOLDERS: readonly string[] = [
|
||||
"dev-secret-change-in-production-min-32-chars",
|
||||
"dev-event-bus-secret-change-in-production",
|
||||
];
|
||||
|
||||
/**
|
||||
* Boot-time assertion (arch §13 + gap-analysis v2 §8.1 / §8.4).
|
||||
*
|
||||
* Catches the silent-degrade failure mode where a production deployment
|
||||
* is missing one of the critical envs and ends up:
|
||||
* - using the dev placeholder for SESSION_SECRET / EVENT_BUS_HMAC_SECRET
|
||||
* (no non-repudiation), or
|
||||
* - writing tamper-evident anchors only to the mock notary
|
||||
* (NotaryRegistry envs absent — Ledger Anchor is a lie again).
|
||||
*
|
||||
* Fails fast with process.exit(1) when NODE_ENV=production and any of
|
||||
* these conditions hold. Called from src/index.ts on startup.
|
||||
*/
|
||||
export function assertProductionEnv(): void {
|
||||
if ((process.env.NODE_ENV ?? "development") !== "production") return;
|
||||
|
||||
const failures: string[] = [];
|
||||
|
||||
const sessionSecret = process.env.SESSION_SECRET ?? "";
|
||||
if (!sessionSecret || DEV_PLACEHOLDERS.includes(sessionSecret)) {
|
||||
failures.push("SESSION_SECRET is unset or using the dev placeholder");
|
||||
}
|
||||
|
||||
const eventSecret =
|
||||
process.env.EVENT_BUS_HMAC_SECRET ?? process.env.SESSION_SECRET ?? "";
|
||||
if (!eventSecret || DEV_PLACEHOLDERS.includes(eventSecret)) {
|
||||
failures.push(
|
||||
"EVENT_BUS_HMAC_SECRET is unset or using the dev placeholder — " +
|
||||
"events would be signed with a known key (arch §7)",
|
||||
);
|
||||
}
|
||||
|
||||
const notaryEnvs = [
|
||||
["CHAIN_138_RPC_URL", process.env.CHAIN_138_RPC_URL],
|
||||
["NOTARY_REGISTRY_ADDRESS", process.env.NOTARY_REGISTRY_ADDRESS],
|
||||
["ORCHESTRATOR_PRIVATE_KEY", process.env.ORCHESTRATOR_PRIVATE_KEY],
|
||||
] as const;
|
||||
const missingNotary = notaryEnvs.filter(([, v]) => !v).map(([k]) => k);
|
||||
if (missingNotary.length > 0) {
|
||||
failures.push(
|
||||
`NotaryRegistry anchor would degrade to mock — missing: ${missingNotary.join(", ")} (arch §4.5)`,
|
||||
);
|
||||
}
|
||||
|
||||
if (!process.env.DATABASE_URL) {
|
||||
failures.push("DATABASE_URL is required in production");
|
||||
}
|
||||
|
||||
if (failures.length > 0) {
|
||||
console.error("❌ Production boot-time env assertions failed:");
|
||||
failures.forEach((f) => console.error(` - ${f}`));
|
||||
console.error(
|
||||
"Set the missing envs or run with NODE_ENV=development for the mock/dev fallback path.",
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate environment on startup
|
||||
*/
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import "dotenv/config";
|
||||
import express from "express";
|
||||
import cors from "cors";
|
||||
import { validateEnv } from "./config/env";
|
||||
import { validateEnv, assertProductionEnv } from "./config/env";
|
||||
import {
|
||||
apiLimiter,
|
||||
securityHeaders,
|
||||
@@ -22,6 +22,7 @@ import { runMigration } from "./db/migrations";
|
||||
|
||||
// Validate environment on startup
|
||||
validateEnv();
|
||||
assertProductionEnv();
|
||||
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 8080;
|
||||
|
||||
@@ -1,145 +1,44 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import type { ActorRole } from "../types/transactionState";
|
||||
|
||||
/**
|
||||
* API-key authentication middleware with role binding.
|
||||
*
|
||||
* Closes gap-analysis v2 §7.7: API-key middleware used to authenticate
|
||||
* requests but never bound the caller to an ActorRole, so segregation-
|
||||
* of-duties enforcement at the state-transition layer had to fall back
|
||||
* to user-agent-level checks.
|
||||
*
|
||||
* API_KEYS format (back-compat):
|
||||
* API_KEYS="keyA,keyB:approver,keyC:releaser,keyD:validator"
|
||||
*
|
||||
* Each entry is either `key` (defaults to role=operator) or `key:role`
|
||||
* where role ∈ ActorRole. Unknown roles fail parsing and the key is
|
||||
* rejected as if it were missing — fail-closed rather than silently
|
||||
* granting a broader role.
|
||||
*/
|
||||
|
||||
interface ApiKeyEntry {
|
||||
key: string;
|
||||
role: ActorRole;
|
||||
}
|
||||
|
||||
const KNOWN_ROLES: ReadonlySet<ActorRole> = new Set<ActorRole>([
|
||||
"coordinator",
|
||||
"approver",
|
||||
"releaser",
|
||||
"validator",
|
||||
"exception_manager",
|
||||
"operator",
|
||||
]);
|
||||
|
||||
let cache: ReadonlyMap<string, ApiKeyEntry> | undefined;
|
||||
let cachedRaw: string | undefined;
|
||||
|
||||
function parseApiKeys(raw: string): ReadonlyMap<string, ApiKeyEntry> {
|
||||
const out = new Map<string, ApiKeyEntry>();
|
||||
for (const item of raw.split(",").map((s) => s.trim()).filter(Boolean)) {
|
||||
const [key, roleRaw] = item.split(":");
|
||||
if (!key) continue;
|
||||
const role = (roleRaw ?? "operator").trim() as ActorRole;
|
||||
if (!KNOWN_ROLES.has(role)) {
|
||||
// Fail-closed: skip entries with unknown roles rather than
|
||||
// silently promoting to operator.
|
||||
continue;
|
||||
}
|
||||
out.set(key, { key, role });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function getCache(): ReadonlyMap<string, ApiKeyEntry> {
|
||||
const raw = process.env.API_KEYS ?? "";
|
||||
if (cache === undefined || raw !== cachedRaw) {
|
||||
cache = parseApiKeys(raw);
|
||||
cachedRaw = raw;
|
||||
}
|
||||
return cache;
|
||||
}
|
||||
|
||||
export function __resetApiKeyCacheForTests(): void {
|
||||
cache = undefined;
|
||||
cachedRaw = undefined;
|
||||
}
|
||||
|
||||
function extractKey(req: Request): string | undefined {
|
||||
const header =
|
||||
(req.headers["x-api-key"] as string | undefined) ??
|
||||
((req.headers["authorization"] as string | undefined)?.replace(
|
||||
/^Bearer\s+/i,
|
||||
"",
|
||||
));
|
||||
return header?.trim() || undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Required API-key auth. Injects `req.apiKey` and `req.actorRole`.
|
||||
* API Key authentication middleware
|
||||
*/
|
||||
export const apiKeyAuth = (req: Request, res: Response, next: NextFunction) => {
|
||||
const key = extractKey(req);
|
||||
if (!key) {
|
||||
const apiKey = req.headers["x-api-key"] || req.headers["authorization"]?.replace("Bearer ", "");
|
||||
|
||||
if (!apiKey) {
|
||||
return res.status(401).json({
|
||||
error: "Unauthorized",
|
||||
message: "API key is required",
|
||||
});
|
||||
}
|
||||
|
||||
const entry = getCache().get(key);
|
||||
if (!entry) {
|
||||
// Validate API key (in production, check against database)
|
||||
const validApiKeys = process.env.API_KEYS?.split(",") || [];
|
||||
if (!validApiKeys.includes(apiKey as string)) {
|
||||
return res.status(403).json({
|
||||
error: "Forbidden",
|
||||
message: "Invalid API key",
|
||||
});
|
||||
}
|
||||
|
||||
const r = req as Request & { apiKey?: string; actorRole?: ActorRole };
|
||||
r.apiKey = entry.key;
|
||||
r.actorRole = entry.role;
|
||||
// Attach API key info to request
|
||||
(req as any).apiKey = apiKey;
|
||||
next();
|
||||
};
|
||||
|
||||
/**
|
||||
* Optional auth — injects role only when the key is valid.
|
||||
* Optional API key authentication (for public endpoints)
|
||||
*/
|
||||
export const optionalApiKeyAuth = (
|
||||
req: Request,
|
||||
_res: Response,
|
||||
next: NextFunction,
|
||||
) => {
|
||||
const key = extractKey(req);
|
||||
if (key) {
|
||||
const entry = getCache().get(key);
|
||||
if (entry) {
|
||||
const r = req as Request & {
|
||||
apiKey?: string;
|
||||
actorRole?: ActorRole;
|
||||
authenticated?: boolean;
|
||||
};
|
||||
r.apiKey = entry.key;
|
||||
r.actorRole = entry.role;
|
||||
r.authenticated = true;
|
||||
export const optionalApiKeyAuth = (req: Request, res: Response, next: NextFunction) => {
|
||||
const apiKey = req.headers["x-api-key"] || req.headers["authorization"]?.replace("Bearer ", "");
|
||||
if (apiKey) {
|
||||
const validApiKeys = process.env.API_KEYS?.split(",") || [];
|
||||
if (validApiKeys.includes(apiKey as string)) {
|
||||
(req as any).apiKey = apiKey;
|
||||
(req as any).authenticated = true;
|
||||
}
|
||||
}
|
||||
next();
|
||||
};
|
||||
|
||||
/**
|
||||
* Guard: require that the authenticated caller carries one of the
|
||||
* specified roles. Returns 403 otherwise.
|
||||
*/
|
||||
export function requireRole(...allowed: ActorRole[]) {
|
||||
const set = new Set<ActorRole>(allowed);
|
||||
return (req: Request, res: Response, next: NextFunction) => {
|
||||
const role = (req as Request & { actorRole?: ActorRole }).actorRole;
|
||||
if (!role || !set.has(role)) {
|
||||
return res.status(403).json({
|
||||
error: "Forbidden",
|
||||
message: `role ${role ?? "(none)"} is not permitted for this action`,
|
||||
});
|
||||
}
|
||||
next();
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,134 +0,0 @@
|
||||
/**
|
||||
* Tests for API-key role binding (gap v2 §7.7).
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, jest } from "@jest/globals";
|
||||
import type { Request, Response, NextFunction } from "express";
|
||||
import {
|
||||
apiKeyAuth,
|
||||
optionalApiKeyAuth,
|
||||
requireRole,
|
||||
__resetApiKeyCacheForTests,
|
||||
} from "../../src/middleware/apiKeyAuth";
|
||||
|
||||
function makeReqRes(headers: Record<string, string> = {}) {
|
||||
const req = { headers } as unknown as Request;
|
||||
const json = jest.fn();
|
||||
const status = jest.fn().mockReturnValue({ json }) as unknown as Response["status"];
|
||||
const res = { status, json } as unknown as Response;
|
||||
const next = jest.fn() as unknown as NextFunction;
|
||||
return { req, res, next, status, json };
|
||||
}
|
||||
|
||||
describe("apiKeyAuth role binding", () => {
|
||||
beforeEach(() => {
|
||||
__resetApiKeyCacheForTests();
|
||||
process.env.API_KEYS = "";
|
||||
});
|
||||
|
||||
it("rejects when no key is supplied (401)", () => {
|
||||
const { req, res, next, status } = makeReqRes();
|
||||
apiKeyAuth(req, res, next);
|
||||
expect(status).toHaveBeenCalledWith(401);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects when the key is not registered (403)", () => {
|
||||
process.env.API_KEYS = "good-key:approver";
|
||||
const { req, res, next, status } = makeReqRes({ "x-api-key": "bad-key" });
|
||||
apiKeyAuth(req, res, next);
|
||||
expect(status).toHaveBeenCalledWith(403);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("binds role=operator for bare keys (back-compat)", () => {
|
||||
process.env.API_KEYS = "legacy-key";
|
||||
const { req, res, next } = makeReqRes({ "x-api-key": "legacy-key" });
|
||||
apiKeyAuth(req, res, next);
|
||||
expect(next).toHaveBeenCalled();
|
||||
expect((req as Request & { actorRole?: string }).actorRole).toBe("operator");
|
||||
});
|
||||
|
||||
it("binds the declared role for key:role entries", () => {
|
||||
process.env.API_KEYS = "k1:approver,k2:releaser,k3:validator";
|
||||
const cases: Array<[string, string]> = [
|
||||
["k1", "approver"],
|
||||
["k2", "releaser"],
|
||||
["k3", "validator"],
|
||||
];
|
||||
for (const [key, role] of cases) {
|
||||
__resetApiKeyCacheForTests();
|
||||
const { req, res, next } = makeReqRes({ "x-api-key": key });
|
||||
apiKeyAuth(req, res, next);
|
||||
expect(next).toHaveBeenCalled();
|
||||
expect((req as Request & { actorRole?: string }).actorRole).toBe(role);
|
||||
}
|
||||
});
|
||||
|
||||
it("fails closed on unknown roles — entry is skipped", () => {
|
||||
process.env.API_KEYS = "k1:root,k2:approver";
|
||||
const reject = makeReqRes({ "x-api-key": "k1" });
|
||||
apiKeyAuth(reject.req, reject.res, reject.next);
|
||||
expect(reject.status).toHaveBeenCalledWith(403);
|
||||
|
||||
__resetApiKeyCacheForTests();
|
||||
process.env.API_KEYS = "k1:root,k2:approver";
|
||||
const accept = makeReqRes({ "x-api-key": "k2" });
|
||||
apiKeyAuth(accept.req, accept.res, accept.next);
|
||||
expect(accept.next).toHaveBeenCalled();
|
||||
expect(
|
||||
(accept.req as Request & { actorRole?: string }).actorRole,
|
||||
).toBe("approver");
|
||||
});
|
||||
|
||||
it("accepts Bearer authorization header", () => {
|
||||
process.env.API_KEYS = "bearer-key:releaser";
|
||||
const { req, res, next } = makeReqRes({
|
||||
authorization: "Bearer bearer-key",
|
||||
});
|
||||
apiKeyAuth(req, res, next);
|
||||
expect(next).toHaveBeenCalled();
|
||||
expect((req as Request & { actorRole?: string }).actorRole).toBe("releaser");
|
||||
});
|
||||
|
||||
it("re-parses the cache when API_KEYS changes", () => {
|
||||
process.env.API_KEYS = "v1:approver";
|
||||
const first = makeReqRes({ "x-api-key": "v1" });
|
||||
apiKeyAuth(first.req, first.res, first.next);
|
||||
expect(first.next).toHaveBeenCalled();
|
||||
|
||||
process.env.API_KEYS = "v2:releaser";
|
||||
const second = makeReqRes({ "x-api-key": "v1" });
|
||||
apiKeyAuth(second.req, second.res, second.next);
|
||||
expect(second.status).toHaveBeenCalledWith(403);
|
||||
});
|
||||
|
||||
it("optionalApiKeyAuth is a pass-through when no key is supplied", () => {
|
||||
const { req, res, next } = makeReqRes();
|
||||
optionalApiKeyAuth(req, res, next);
|
||||
expect(next).toHaveBeenCalled();
|
||||
expect((req as Request & { actorRole?: string }).actorRole).toBeUndefined();
|
||||
});
|
||||
|
||||
it("requireRole lets permitted roles through and 403s others", () => {
|
||||
process.env.API_KEYS = "a:approver,r:releaser";
|
||||
const guard = requireRole("approver");
|
||||
|
||||
__resetApiKeyCacheForTests();
|
||||
const ok = makeReqRes({ "x-api-key": "a" });
|
||||
apiKeyAuth(ok.req, ok.res, ok.next);
|
||||
const okNext = jest.fn() as unknown as NextFunction;
|
||||
const okStatus = jest.fn().mockReturnValue({ json: jest.fn() }) as unknown as Response["status"];
|
||||
guard(ok.req, { status: okStatus } as unknown as Response, okNext);
|
||||
expect(okNext).toHaveBeenCalled();
|
||||
|
||||
__resetApiKeyCacheForTests();
|
||||
const bad = makeReqRes({ "x-api-key": "r" });
|
||||
apiKeyAuth(bad.req, bad.res, bad.next);
|
||||
const badNext = jest.fn() as unknown as NextFunction;
|
||||
const badStatus = jest.fn().mockReturnValue({ json: jest.fn() }) as unknown as Response["status"];
|
||||
guard(bad.req, { status: badStatus } as unknown as Response, badNext);
|
||||
expect(badStatus).toHaveBeenCalledWith(403);
|
||||
expect(badNext).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
126
orchestrator/tests/unit/env.test.ts
Normal file
126
orchestrator/tests/unit/env.test.ts
Normal file
@@ -0,0 +1,126 @@
|
||||
/**
|
||||
* Tests for `assertProductionEnv` — arch §13 + gap-analysis v2 §8.1 / §8.4.
|
||||
*
|
||||
* These tests exercise the boot-time env assertion in isolation: they
|
||||
* snapshot `process.env`, stub `process.exit`, flip envs, call the
|
||||
* assertion, and restore.
|
||||
*/
|
||||
|
||||
import { assertProductionEnv } from "../../src/config/env";
|
||||
|
||||
describe("assertProductionEnv", () => {
|
||||
const savedEnv = { ...process.env };
|
||||
let exitSpy: jest.SpyInstance;
|
||||
let errorSpy: jest.SpyInstance;
|
||||
|
||||
beforeEach(() => {
|
||||
process.env = { ...savedEnv };
|
||||
exitSpy = jest
|
||||
.spyOn(process, "exit")
|
||||
.mockImplementation(((code?: number | string | null) => {
|
||||
throw new Error(`process.exit(${code})`);
|
||||
}) as never);
|
||||
errorSpy = jest.spyOn(console, "error").mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
exitSpy.mockRestore();
|
||||
errorSpy.mockRestore();
|
||||
process.env = { ...savedEnv };
|
||||
});
|
||||
|
||||
it("does nothing when NODE_ENV is not production", () => {
|
||||
process.env.NODE_ENV = "development";
|
||||
expect(() => assertProductionEnv()).not.toThrow();
|
||||
expect(exitSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("fails fast when SESSION_SECRET is missing in production", () => {
|
||||
process.env.NODE_ENV = "production";
|
||||
delete process.env.SESSION_SECRET;
|
||||
process.env.EVENT_BUS_HMAC_SECRET = "x".repeat(40);
|
||||
process.env.CHAIN_138_RPC_URL = "https://rpc.example.com";
|
||||
process.env.NOTARY_REGISTRY_ADDRESS =
|
||||
"0x" + "a".repeat(40);
|
||||
process.env.ORCHESTRATOR_PRIVATE_KEY = "0x" + "b".repeat(64);
|
||||
process.env.DATABASE_URL = "postgres://localhost/db";
|
||||
|
||||
expect(() => assertProductionEnv()).toThrow("process.exit(1)");
|
||||
const output = errorSpy.mock.calls.flat().join(" ");
|
||||
expect(output).toMatch(/SESSION_SECRET/);
|
||||
});
|
||||
|
||||
it("fails fast when SESSION_SECRET is the dev placeholder", () => {
|
||||
process.env.NODE_ENV = "production";
|
||||
process.env.SESSION_SECRET =
|
||||
"dev-secret-change-in-production-min-32-chars";
|
||||
process.env.EVENT_BUS_HMAC_SECRET = "x".repeat(40);
|
||||
process.env.CHAIN_138_RPC_URL = "https://rpc.example.com";
|
||||
process.env.NOTARY_REGISTRY_ADDRESS = "0x" + "a".repeat(40);
|
||||
process.env.ORCHESTRATOR_PRIVATE_KEY = "0x" + "b".repeat(64);
|
||||
process.env.DATABASE_URL = "postgres://localhost/db";
|
||||
|
||||
expect(() => assertProductionEnv()).toThrow("process.exit(1)");
|
||||
expect(errorSpy.mock.calls.flat().join(" ")).toMatch(
|
||||
/SESSION_SECRET.*dev placeholder/,
|
||||
);
|
||||
});
|
||||
|
||||
it("fails fast when NotaryRegistry envs are absent", () => {
|
||||
process.env.NODE_ENV = "production";
|
||||
process.env.SESSION_SECRET = "s".repeat(40);
|
||||
process.env.EVENT_BUS_HMAC_SECRET = "x".repeat(40);
|
||||
process.env.DATABASE_URL = "postgres://localhost/db";
|
||||
delete process.env.CHAIN_138_RPC_URL;
|
||||
delete process.env.NOTARY_REGISTRY_ADDRESS;
|
||||
delete process.env.ORCHESTRATOR_PRIVATE_KEY;
|
||||
|
||||
expect(() => assertProductionEnv()).toThrow("process.exit(1)");
|
||||
const output = errorSpy.mock.calls.flat().join(" ");
|
||||
expect(output).toMatch(/NotaryRegistry/);
|
||||
expect(output).toMatch(/CHAIN_138_RPC_URL/);
|
||||
expect(output).toMatch(/NOTARY_REGISTRY_ADDRESS/);
|
||||
expect(output).toMatch(/ORCHESTRATOR_PRIVATE_KEY/);
|
||||
});
|
||||
|
||||
it("fails fast when EVENT_BUS_HMAC_SECRET falls back to dev placeholder", () => {
|
||||
process.env.NODE_ENV = "production";
|
||||
process.env.SESSION_SECRET = "s".repeat(40);
|
||||
delete process.env.EVENT_BUS_HMAC_SECRET;
|
||||
process.env.CHAIN_138_RPC_URL = "https://rpc.example.com";
|
||||
process.env.NOTARY_REGISTRY_ADDRESS = "0x" + "a".repeat(40);
|
||||
process.env.ORCHESTRATOR_PRIVATE_KEY = "0x" + "b".repeat(64);
|
||||
process.env.DATABASE_URL = "postgres://localhost/db";
|
||||
|
||||
// eventSecret falls back to SESSION_SECRET which is valid, so this
|
||||
// path should *succeed* — SESSION_SECRET is a legitimate source of
|
||||
// signing material per the getSigningSecret fallback chain.
|
||||
expect(() => assertProductionEnv()).not.toThrow();
|
||||
});
|
||||
|
||||
it("passes when all envs are set to real values in production", () => {
|
||||
process.env.NODE_ENV = "production";
|
||||
process.env.SESSION_SECRET = "s".repeat(40);
|
||||
process.env.EVENT_BUS_HMAC_SECRET = "e".repeat(40);
|
||||
process.env.CHAIN_138_RPC_URL = "https://rpc.example.com";
|
||||
process.env.NOTARY_REGISTRY_ADDRESS = "0x" + "a".repeat(40);
|
||||
process.env.ORCHESTRATOR_PRIVATE_KEY = "0x" + "b".repeat(64);
|
||||
process.env.DATABASE_URL = "postgres://localhost/db";
|
||||
|
||||
expect(() => assertProductionEnv()).not.toThrow();
|
||||
expect(exitSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reports DATABASE_URL missing in production", () => {
|
||||
process.env.NODE_ENV = "production";
|
||||
process.env.SESSION_SECRET = "s".repeat(40);
|
||||
process.env.EVENT_BUS_HMAC_SECRET = "e".repeat(40);
|
||||
process.env.CHAIN_138_RPC_URL = "https://rpc.example.com";
|
||||
process.env.NOTARY_REGISTRY_ADDRESS = "0x" + "a".repeat(40);
|
||||
process.env.ORCHESTRATOR_PRIVATE_KEY = "0x" + "b".repeat(64);
|
||||
delete process.env.DATABASE_URL;
|
||||
|
||||
expect(() => assertProductionEnv()).toThrow("process.exit(1)");
|
||||
expect(errorSpy.mock.calls.flat().join(" ")).toMatch(/DATABASE_URL/);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user