Compare commits
1 Commits
devin/1776
...
devin/1776
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
72ff0e4cc0 |
175
.github/workflows/ci.yml
vendored
175
.github/workflows/ci.yml
vendored
@@ -7,132 +7,139 @@ on:
|
||||
branches: [main, develop]
|
||||
|
||||
jobs:
|
||||
# -------------------------------------------------------------------------
|
||||
# Portal (Vite + React, lives at repo root after the webapp/ gitlink was
|
||||
# removed in PR #4)
|
||||
# -------------------------------------------------------------------------
|
||||
portal-lint:
|
||||
name: Portal Lint
|
||||
# Frontend CI
|
||||
frontend-lint:
|
||||
name: Frontend Lint
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "20"
|
||||
node-version: "18"
|
||||
cache: "npm"
|
||||
- run: npm ci
|
||||
- run: npm run lint
|
||||
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
|
||||
|
||||
portal-type-check:
|
||||
name: Portal Type Check
|
||||
frontend-type-check:
|
||||
name: Frontend Type Check
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "20"
|
||||
node-version: "18"
|
||||
cache: "npm"
|
||||
- run: npm ci
|
||||
- run: npx tsc --noEmit
|
||||
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
|
||||
|
||||
portal-build:
|
||||
name: Portal Build
|
||||
frontend-build:
|
||||
name: Frontend Build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "20"
|
||||
node-version: "18"
|
||||
cache: "npm"
|
||||
- run: npm ci
|
||||
- run: npm run build
|
||||
- uses: actions/upload-artifact@v4
|
||||
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
|
||||
with:
|
||||
name: portal-dist
|
||||
path: dist
|
||||
name: frontend-build
|
||||
path: webapp/.next
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Orchestrator (TypeScript + Express + Jest)
|
||||
# -------------------------------------------------------------------------
|
||||
orchestrator-type-check:
|
||||
name: Orchestrator Type Check
|
||||
frontend-e2e:
|
||||
name: Frontend E2E Tests
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: orchestrator
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "20"
|
||||
node-version: "18"
|
||||
cache: "npm"
|
||||
cache-dependency-path: orchestrator/package-lock.json
|
||||
- run: npm ci
|
||||
- run: npx tsc --noEmit
|
||||
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/
|
||||
|
||||
# Orchestrator CI
|
||||
orchestrator-build:
|
||||
name: Orchestrator Build
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: orchestrator
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "20"
|
||||
node-version: "18"
|
||||
cache: "npm"
|
||||
cache-dependency-path: orchestrator/package-lock.json
|
||||
- run: npm ci
|
||||
- run: npm run build
|
||||
|
||||
orchestrator-test:
|
||||
name: Orchestrator Test
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
- name: Install dependencies
|
||||
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
|
||||
run: npm ci
|
||||
- name: Build
|
||||
working-directory: orchestrator
|
||||
run: npm run build
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Smart Contracts (Hardhat)
|
||||
# -------------------------------------------------------------------------
|
||||
# Smart Contracts CI
|
||||
contracts-compile:
|
||||
name: Contracts Compile
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: contracts
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "20"
|
||||
node-version: "18"
|
||||
cache: "npm"
|
||||
cache-dependency-path: contracts/package-lock.json
|
||||
- run: npm ci
|
||||
- run: npm run compile
|
||||
- name: Install dependencies
|
||||
working-directory: contracts
|
||||
run: npm ci
|
||||
- name: Compile contracts
|
||||
working-directory: contracts
|
||||
run: npm run compile
|
||||
|
||||
contracts-test:
|
||||
name: Contracts Test
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: contracts
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "20"
|
||||
node-version: "18"
|
||||
cache: "npm"
|
||||
cache-dependency-path: contracts/package-lock.json
|
||||
- run: npm ci
|
||||
- run: npm run test
|
||||
- name: Install dependencies
|
||||
working-directory: contracts
|
||||
run: npm ci
|
||||
- name: Run tests
|
||||
working-directory: contracts
|
||||
run: npm run test
|
||||
|
||||
|
||||
@@ -22,10 +22,6 @@ 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(),
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -48,78 +44,8 @@ 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, assertProductionEnv } from "./config/env";
|
||||
import { validateEnv } from "./config/env";
|
||||
import {
|
||||
apiLimiter,
|
||||
securityHeaders,
|
||||
@@ -22,7 +22,6 @@ import { runMigration } from "./db/migrations";
|
||||
|
||||
// Validate environment on startup
|
||||
validateEnv();
|
||||
assertProductionEnv();
|
||||
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 8080;
|
||||
|
||||
304
orchestrator/src/services/rulesEngine.ts
Normal file
304
orchestrator/src/services/rulesEngine.ts
Normal file
@@ -0,0 +1,304 @@
|
||||
/**
|
||||
* Pluggable Rules Engine (arch §5.2 Rules Engine; gap v2 §5.2 partial).
|
||||
*
|
||||
* Before this PR, business rules were hardcoded at the call sites
|
||||
* (e.g. "plan must have a pay step" baked into iso20022.ts, SoD
|
||||
* matrix hard-coded in transactionState.ts). This module introduces
|
||||
* a minimal, declarative JSON DSL so that ruleSets can be loaded
|
||||
* from env (RULES_FILE) or swapped per-environment.
|
||||
*
|
||||
* Design principles
|
||||
* -----------------
|
||||
* - No eval. The evaluator is a small recursive switch over a
|
||||
* closed operator set — no runtime code injection.
|
||||
* - Pure, deterministic, side-effect free. Evaluation order is
|
||||
* explicit so the engine can be reasoned about and replayed.
|
||||
* - Context is a flat name → value map. Callers project whatever
|
||||
* shape they need ({plan, state, compliance, participants}).
|
||||
* - Failures are collected, not thrown. The caller decides whether
|
||||
* a single failure aborts, or whether to accumulate and report.
|
||||
*/
|
||||
|
||||
import { readFileSync } from "fs";
|
||||
|
||||
/** Supported primitive operators. */
|
||||
export type Operator =
|
||||
| "eq"
|
||||
| "neq"
|
||||
| "gt"
|
||||
| "gte"
|
||||
| "lt"
|
||||
| "lte"
|
||||
| "in"
|
||||
| "not_in"
|
||||
| "exists"
|
||||
| "matches" // regex
|
||||
| "length_gte"
|
||||
| "length_lte";
|
||||
|
||||
/** Leaf condition — references a context path against a literal. */
|
||||
export interface LeafCondition {
|
||||
path: string; // dotted path into the context object
|
||||
op: Operator;
|
||||
value?: unknown; // not required for `exists`
|
||||
/** Optional human label for failure messages. */
|
||||
message?: string;
|
||||
}
|
||||
|
||||
/** Combinator — AND / OR / NOT over child conditions. */
|
||||
export interface AndCondition {
|
||||
all: Condition[];
|
||||
message?: string;
|
||||
}
|
||||
export interface OrCondition {
|
||||
any: Condition[];
|
||||
message?: string;
|
||||
}
|
||||
export interface NotCondition {
|
||||
not: Condition;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export type Condition = LeafCondition | AndCondition | OrCondition | NotCondition;
|
||||
|
||||
export interface Rule {
|
||||
id: string;
|
||||
description?: string;
|
||||
when?: Condition; // precondition — rule only fires when `when` is true
|
||||
assert: Condition; // the rule passes when `assert` evaluates true
|
||||
/** Optional severity for reporting: "error" (default) blocks, "warn" does not. */
|
||||
severity?: "error" | "warn";
|
||||
}
|
||||
|
||||
export interface RuleSet {
|
||||
id: string;
|
||||
version?: string;
|
||||
rules: Rule[];
|
||||
}
|
||||
|
||||
export interface RuleFailure {
|
||||
ruleId: string;
|
||||
severity: "error" | "warn";
|
||||
message: string;
|
||||
path?: string;
|
||||
}
|
||||
|
||||
export interface EvaluationResult {
|
||||
ok: boolean;
|
||||
failures: RuleFailure[];
|
||||
}
|
||||
|
||||
/* -----------------------------------------------------------------
|
||||
* Dotted-path resolver. Supports a.b.c and a.b[0].c.
|
||||
* --------------------------------------------------------------- */
|
||||
function getPath(ctx: unknown, path: string): unknown {
|
||||
if (!path) return ctx;
|
||||
const parts = path
|
||||
.replace(/\[(\d+)\]/g, ".$1")
|
||||
.split(".")
|
||||
.filter(Boolean);
|
||||
let cur: unknown = ctx;
|
||||
for (const p of parts) {
|
||||
if (cur === null || cur === undefined) return undefined;
|
||||
if (typeof cur === "object") {
|
||||
cur = (cur as Record<string, unknown>)[p];
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
return cur;
|
||||
}
|
||||
|
||||
/* -----------------------------------------------------------------
|
||||
* Operator evaluation. Pure — no throws.
|
||||
* --------------------------------------------------------------- */
|
||||
function evalOp(op: Operator, actual: unknown, expected: unknown): boolean {
|
||||
switch (op) {
|
||||
case "eq":
|
||||
return actual === expected;
|
||||
case "neq":
|
||||
return actual !== expected;
|
||||
case "gt":
|
||||
return typeof actual === "number" && typeof expected === "number" && actual > expected;
|
||||
case "gte":
|
||||
return typeof actual === "number" && typeof expected === "number" && actual >= expected;
|
||||
case "lt":
|
||||
return typeof actual === "number" && typeof expected === "number" && actual < expected;
|
||||
case "lte":
|
||||
return typeof actual === "number" && typeof expected === "number" && actual <= expected;
|
||||
case "in":
|
||||
return Array.isArray(expected) && expected.includes(actual as never);
|
||||
case "not_in":
|
||||
return Array.isArray(expected) && !expected.includes(actual as never);
|
||||
case "exists":
|
||||
return actual !== undefined && actual !== null;
|
||||
case "matches":
|
||||
if (typeof actual !== "string" || typeof expected !== "string") return false;
|
||||
try {
|
||||
return new RegExp(expected).test(actual);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
case "length_gte":
|
||||
if (!Array.isArray(actual) && typeof actual !== "string") return false;
|
||||
return (actual as { length: number }).length >= (expected as number);
|
||||
case "length_lte":
|
||||
if (!Array.isArray(actual) && typeof actual !== "string") return false;
|
||||
return (actual as { length: number }).length <= (expected as number);
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isLeaf(c: Condition): c is LeafCondition {
|
||||
return (c as LeafCondition).op !== undefined && (c as LeafCondition).path !== undefined;
|
||||
}
|
||||
|
||||
export function evaluateCondition(
|
||||
condition: Condition,
|
||||
context: Record<string, unknown>,
|
||||
): boolean {
|
||||
if (isLeaf(condition)) {
|
||||
const actual = getPath(context, condition.path);
|
||||
return evalOp(condition.op, actual, condition.value);
|
||||
}
|
||||
if ("all" in condition) {
|
||||
return condition.all.every((c) => evaluateCondition(c, context));
|
||||
}
|
||||
if ("any" in condition) {
|
||||
return condition.any.some((c) => evaluateCondition(c, context));
|
||||
}
|
||||
if ("not" in condition) {
|
||||
return !evaluateCondition(condition.not, context);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/* -----------------------------------------------------------------
|
||||
* Public evaluate(): runs the full rule set and collects failures.
|
||||
* --------------------------------------------------------------- */
|
||||
export function evaluate(
|
||||
ruleSet: RuleSet,
|
||||
context: Record<string, unknown>,
|
||||
): EvaluationResult {
|
||||
const failures: RuleFailure[] = [];
|
||||
for (const rule of ruleSet.rules) {
|
||||
if (rule.when && !evaluateCondition(rule.when, context)) continue;
|
||||
const passed = evaluateCondition(rule.assert, context);
|
||||
if (!passed) {
|
||||
failures.push({
|
||||
ruleId: rule.id,
|
||||
severity: rule.severity ?? "error",
|
||||
message: rule.description ?? `rule ${rule.id} failed`,
|
||||
path: isLeaf(rule.assert) ? rule.assert.path : undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
const blocking = failures.filter((f) => f.severity === "error");
|
||||
return { ok: blocking.length === 0, failures };
|
||||
}
|
||||
|
||||
/* -----------------------------------------------------------------
|
||||
* Built-in rule sets. These mirror the pre-DSL hardcoded checks so
|
||||
* callers can migrate incrementally.
|
||||
* --------------------------------------------------------------- */
|
||||
|
||||
/** Preconditions check — arch §8 PRECONDITIONS_PENDING -> READY_FOR_PREPARE. */
|
||||
export const BUILTIN_PRECONDITIONS: RuleSet = {
|
||||
id: "preconditions.builtin",
|
||||
version: "1",
|
||||
rules: [
|
||||
{
|
||||
id: "plan.exists",
|
||||
description: "plan must be present on the context",
|
||||
assert: { path: "plan", op: "exists" },
|
||||
},
|
||||
{
|
||||
id: "plan.steps.non_empty",
|
||||
description: "plan must contain at least one step",
|
||||
assert: { path: "plan.steps", op: "length_gte", value: 1 },
|
||||
},
|
||||
{
|
||||
id: "plan.pay_step_present",
|
||||
description: "plan must contain at least one pay step (ISO-20022 envelope)",
|
||||
assert: {
|
||||
any: [
|
||||
{ path: "plan.steps[0].type", op: "eq", value: "pay" },
|
||||
{ path: "plan.steps[1].type", op: "eq", value: "pay" },
|
||||
{ path: "plan.steps[2].type", op: "eq", value: "pay" },
|
||||
{ path: "plan.steps[3].type", op: "eq", value: "pay" },
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "participants.at_least_one",
|
||||
description: "participant registry must not be empty",
|
||||
assert: { path: "participants", op: "length_gte", value: 1 },
|
||||
},
|
||||
{
|
||||
id: "compliance.kyc_ok",
|
||||
description: "compliance KYC status must be ok",
|
||||
when: { path: "compliance", op: "exists" },
|
||||
assert: { path: "compliance.kyc", op: "eq", value: "ok" },
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
/** Commit rule — arch §9.2. */
|
||||
export const BUILTIN_COMMIT: RuleSet = {
|
||||
id: "commit.builtin",
|
||||
version: "1",
|
||||
rules: [
|
||||
{
|
||||
id: "dlt.tx_hash",
|
||||
description: "DLT leg must produce a 0x + 64-hex tx hash",
|
||||
assert: { path: "dlt.txHash", op: "matches", value: "^0x[0-9a-fA-F]{64}$" },
|
||||
},
|
||||
{
|
||||
id: "bank.iso_message_id",
|
||||
description: "bank leg must produce a non-empty ISO message id",
|
||||
assert: { path: "bank.isoMessageId", op: "exists" },
|
||||
},
|
||||
{
|
||||
id: "state.is_validating",
|
||||
description: "commit is only valid from VALIDATING",
|
||||
assert: { path: "state", op: "eq", value: "VALIDATING" },
|
||||
},
|
||||
{
|
||||
id: "no_exception_holds",
|
||||
description: "no exception may be outstanding",
|
||||
assert: { path: "exceptions.active", op: "length_lte", value: 0 },
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
/* -----------------------------------------------------------------
|
||||
* Loader: RULES_FILE env points at a JSON file containing a map
|
||||
* {ruleSetId: RuleSet}. Falls back to built-ins on any error.
|
||||
* --------------------------------------------------------------- */
|
||||
|
||||
let cachedOverrides: Record<string, RuleSet> | undefined;
|
||||
|
||||
export function getRuleSet(id: string): RuleSet {
|
||||
if (cachedOverrides === undefined) {
|
||||
cachedOverrides = {};
|
||||
const path = process.env.RULES_FILE;
|
||||
if (path) {
|
||||
try {
|
||||
const raw = readFileSync(path, "utf8");
|
||||
const parsed = JSON.parse(raw) as Record<string, RuleSet>;
|
||||
if (parsed && typeof parsed === "object") cachedOverrides = parsed;
|
||||
} catch {
|
||||
// leave empty — silent fall-through to built-ins
|
||||
}
|
||||
}
|
||||
}
|
||||
if (cachedOverrides[id]) return cachedOverrides[id];
|
||||
if (id === BUILTIN_PRECONDITIONS.id) return BUILTIN_PRECONDITIONS;
|
||||
if (id === BUILTIN_COMMIT.id) return BUILTIN_COMMIT;
|
||||
return { id, rules: [] };
|
||||
}
|
||||
|
||||
export function __resetRulesCacheForTests(): void {
|
||||
cachedOverrides = undefined;
|
||||
}
|
||||
@@ -1,126 +0,0 @@
|
||||
/**
|
||||
* 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/);
|
||||
});
|
||||
});
|
||||
245
orchestrator/tests/unit/rulesEngine.test.ts
Normal file
245
orchestrator/tests/unit/rulesEngine.test.ts
Normal file
@@ -0,0 +1,245 @@
|
||||
/**
|
||||
* PR P — Pluggable Rules Engine (gap-analysis v2 §5.2 partial).
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach } from "@jest/globals";
|
||||
import {
|
||||
evaluate,
|
||||
evaluateCondition,
|
||||
getRuleSet,
|
||||
BUILTIN_PRECONDITIONS,
|
||||
BUILTIN_COMMIT,
|
||||
__resetRulesCacheForTests,
|
||||
type RuleSet,
|
||||
} from "../../src/services/rulesEngine";
|
||||
|
||||
describe("rulesEngine — primitive operators", () => {
|
||||
it("eq / neq / gt / gte / lt / lte", () => {
|
||||
expect(
|
||||
evaluateCondition({ path: "a", op: "eq", value: 1 }, { a: 1 }),
|
||||
).toBe(true);
|
||||
expect(
|
||||
evaluateCondition({ path: "a", op: "neq", value: 1 }, { a: 2 }),
|
||||
).toBe(true);
|
||||
expect(
|
||||
evaluateCondition({ path: "a", op: "gt", value: 1 }, { a: 2 }),
|
||||
).toBe(true);
|
||||
expect(
|
||||
evaluateCondition({ path: "a", op: "lte", value: 3 }, { a: 3 }),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("in / not_in / exists / matches", () => {
|
||||
expect(
|
||||
evaluateCondition(
|
||||
{ path: "role", op: "in", value: ["approver", "releaser"] },
|
||||
{ role: "approver" },
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
evaluateCondition(
|
||||
{ path: "role", op: "not_in", value: ["approver"] },
|
||||
{ role: "operator" },
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
evaluateCondition({ path: "x", op: "exists" }, { x: 0 }),
|
||||
).toBe(true);
|
||||
expect(
|
||||
evaluateCondition(
|
||||
{ path: "hash", op: "matches", value: "^0x[0-9a-f]+$" },
|
||||
{ hash: "0xabc" },
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("length_gte / length_lte work on arrays and strings", () => {
|
||||
expect(
|
||||
evaluateCondition({ path: "a", op: "length_gte", value: 2 }, { a: [1, 2] }),
|
||||
).toBe(true);
|
||||
expect(
|
||||
evaluateCondition({ path: "a", op: "length_lte", value: 5 }, { a: "abcd" }),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("dotted + indexed path resolution", () => {
|
||||
expect(
|
||||
evaluateCondition(
|
||||
{ path: "plan.steps[1].type", op: "eq", value: "pay" },
|
||||
{ plan: { steps: [{ type: "issue" }, { type: "pay" }] } },
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("rulesEngine — combinators", () => {
|
||||
const ctx = { role: "approver", amount: 1000 };
|
||||
|
||||
it("all (AND) — every child must pass", () => {
|
||||
expect(
|
||||
evaluateCondition(
|
||||
{
|
||||
all: [
|
||||
{ path: "role", op: "eq", value: "approver" },
|
||||
{ path: "amount", op: "gt", value: 500 },
|
||||
],
|
||||
},
|
||||
ctx,
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
evaluateCondition(
|
||||
{
|
||||
all: [
|
||||
{ path: "role", op: "eq", value: "approver" },
|
||||
{ path: "amount", op: "gt", value: 5000 },
|
||||
],
|
||||
},
|
||||
ctx,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("any (OR) — at least one child must pass", () => {
|
||||
expect(
|
||||
evaluateCondition(
|
||||
{
|
||||
any: [
|
||||
{ path: "role", op: "eq", value: "releaser" },
|
||||
{ path: "amount", op: "gt", value: 500 },
|
||||
],
|
||||
},
|
||||
ctx,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("not — inverts the child", () => {
|
||||
expect(
|
||||
evaluateCondition(
|
||||
{ not: { path: "role", op: "eq", value: "releaser" } },
|
||||
ctx,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("rulesEngine — evaluate() and failure reporting", () => {
|
||||
const ruleSet: RuleSet = {
|
||||
id: "test.rs",
|
||||
rules: [
|
||||
{
|
||||
id: "amount_positive",
|
||||
description: "amount must be > 0",
|
||||
assert: { path: "amount", op: "gt", value: 0 },
|
||||
},
|
||||
{
|
||||
id: "role_listed",
|
||||
description: "role must be in the allowed list",
|
||||
assert: {
|
||||
path: "role",
|
||||
op: "in",
|
||||
value: ["approver", "releaser", "operator"],
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "warning_only",
|
||||
description: "low amount warning",
|
||||
severity: "warn",
|
||||
assert: { path: "amount", op: "gte", value: 10_000 },
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
it("returns ok=true when all error-severity rules pass", () => {
|
||||
const res = evaluate(ruleSet, { amount: 1000, role: "approver" });
|
||||
expect(res.ok).toBe(true);
|
||||
// warn still reported even though ok=true
|
||||
expect(res.failures.some((f) => f.ruleId === "warning_only")).toBe(true);
|
||||
expect(res.failures.every((f) => f.severity === "warn")).toBe(true);
|
||||
});
|
||||
|
||||
it("returns ok=false with error failure when a blocking rule fails", () => {
|
||||
const res = evaluate(ruleSet, { amount: -1, role: "approver" });
|
||||
expect(res.ok).toBe(false);
|
||||
const amountFail = res.failures.find((f) => f.ruleId === "amount_positive");
|
||||
expect(amountFail?.severity).toBe("error");
|
||||
});
|
||||
|
||||
it("'when' gates a rule — false when-clause skips the assert", () => {
|
||||
const guarded: RuleSet = {
|
||||
id: "guarded.rs",
|
||||
rules: [
|
||||
{
|
||||
id: "kyc_if_present",
|
||||
when: { path: "compliance", op: "exists" },
|
||||
assert: { path: "compliance.kyc", op: "eq", value: "ok" },
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(evaluate(guarded, {}).ok).toBe(true);
|
||||
expect(evaluate(guarded, { compliance: { kyc: "ok" } }).ok).toBe(true);
|
||||
expect(evaluate(guarded, { compliance: { kyc: "fail" } }).ok).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("rulesEngine — built-in rule sets", () => {
|
||||
it("preconditions: pay step + non-empty participants passes", () => {
|
||||
const res = evaluate(BUILTIN_PRECONDITIONS, {
|
||||
plan: { steps: [{ type: "pay" }] },
|
||||
participants: [{ id: "p1" }],
|
||||
});
|
||||
expect(res.ok).toBe(true);
|
||||
});
|
||||
|
||||
it("preconditions: missing pay step fails", () => {
|
||||
const res = evaluate(BUILTIN_PRECONDITIONS, {
|
||||
plan: { steps: [{ type: "issueInstrument" }] },
|
||||
participants: [{ id: "p1" }],
|
||||
});
|
||||
expect(res.ok).toBe(false);
|
||||
expect(res.failures.some((f) => f.ruleId === "plan.pay_step_present")).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("commit: VALIDATING + matching refs + no exceptions passes", () => {
|
||||
const res = evaluate(BUILTIN_COMMIT, {
|
||||
state: "VALIDATING",
|
||||
dlt: { txHash: `0x${"a".repeat(64)}` },
|
||||
bank: { isoMessageId: "MSG-1" },
|
||||
exceptions: { active: [] },
|
||||
});
|
||||
expect(res.ok).toBe(true);
|
||||
});
|
||||
|
||||
it("commit: state != VALIDATING blocks", () => {
|
||||
const res = evaluate(BUILTIN_COMMIT, {
|
||||
state: "EXECUTING",
|
||||
dlt: { txHash: `0x${"a".repeat(64)}` },
|
||||
bank: { isoMessageId: "MSG-1" },
|
||||
exceptions: { active: [] },
|
||||
});
|
||||
expect(res.ok).toBe(false);
|
||||
expect(res.failures.some((f) => f.ruleId === "state.is_validating")).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("rulesEngine — pluggable loading", () => {
|
||||
beforeEach(() => {
|
||||
__resetRulesCacheForTests();
|
||||
delete process.env.RULES_FILE;
|
||||
});
|
||||
|
||||
it("returns built-ins when RULES_FILE is unset", () => {
|
||||
expect(getRuleSet(BUILTIN_PRECONDITIONS.id).rules.length).toBeGreaterThan(0);
|
||||
expect(getRuleSet(BUILTIN_COMMIT.id).rules.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("returns an empty rule set for unknown ids (no throw)", () => {
|
||||
const rs = getRuleSet("nonexistent");
|
||||
expect(rs.rules).toEqual([]);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user