Compare commits
1 Commits
devin/1776
...
devin/1776
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5a66cf87c8 |
@@ -1,44 +1,145 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import type { ActorRole } from "../types/transactionState";
|
||||
|
||||
/**
|
||||
* API Key authentication middleware
|
||||
* 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`.
|
||||
*/
|
||||
export const apiKeyAuth = (req: Request, res: Response, next: NextFunction) => {
|
||||
const apiKey = req.headers["x-api-key"] || req.headers["authorization"]?.replace("Bearer ", "");
|
||||
|
||||
if (!apiKey) {
|
||||
const key = extractKey(req);
|
||||
if (!key) {
|
||||
return res.status(401).json({
|
||||
error: "Unauthorized",
|
||||
message: "API key is required",
|
||||
});
|
||||
}
|
||||
|
||||
// Validate API key (in production, check against database)
|
||||
const validApiKeys = process.env.API_KEYS?.split(",") || [];
|
||||
if (!validApiKeys.includes(apiKey as string)) {
|
||||
const entry = getCache().get(key);
|
||||
if (!entry) {
|
||||
return res.status(403).json({
|
||||
error: "Forbidden",
|
||||
message: "Invalid API key",
|
||||
});
|
||||
}
|
||||
|
||||
// Attach API key info to request
|
||||
(req as any).apiKey = apiKey;
|
||||
const r = req as Request & { apiKey?: string; actorRole?: ActorRole };
|
||||
r.apiKey = entry.key;
|
||||
r.actorRole = entry.role;
|
||||
next();
|
||||
};
|
||||
|
||||
/**
|
||||
* Optional API key authentication (for public endpoints)
|
||||
* Optional auth — injects role only when the key is valid.
|
||||
*/
|
||||
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;
|
||||
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;
|
||||
}
|
||||
}
|
||||
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();
|
||||
};
|
||||
}
|
||||
|
||||
@@ -22,12 +22,6 @@ import { createHash, createHmac } from "crypto";
|
||||
import { EventEmitter } from "events";
|
||||
import { query } from "../db/postgres";
|
||||
import { logger } from "../logging/logger";
|
||||
import {
|
||||
getEventSigner,
|
||||
legacyHmac,
|
||||
resolveSigningMode,
|
||||
type EventSignInput,
|
||||
} from "./eventSigner";
|
||||
|
||||
/**
|
||||
* Normalised event types — arch §7.2. Keep this list as the single
|
||||
@@ -116,13 +110,7 @@ export async function publish(input: PublishInput): Promise<EventRecord> {
|
||||
[input.planId],
|
||||
);
|
||||
const prevHash = prev.length > 0 ? prev[0].signature : null;
|
||||
const signInput: EventSignInput = {
|
||||
planId: input.planId,
|
||||
type: input.type,
|
||||
payloadHash,
|
||||
prevHash,
|
||||
};
|
||||
const signature = await getEventSigner().sign(signInput);
|
||||
const signature = sign(input.planId, input.type, payloadHash, prevHash);
|
||||
|
||||
const rows = await query<EventRecord>(
|
||||
`INSERT INTO events (plan_id, type, actor, payload, payload_hash, prev_hash, signature)
|
||||
@@ -183,23 +171,9 @@ export async function verifyChain(planId: string): Promise<
|
||||
if (expectedPayloadHash !== e.payload_hash) {
|
||||
return { ok: false, brokenAt: i, reason: "payload_hash mismatch" };
|
||||
}
|
||||
const signInput: EventSignInput = {
|
||||
planId: e.plan_id,
|
||||
type: e.type,
|
||||
payloadHash: e.payload_hash,
|
||||
prevHash: e.prev_hash,
|
||||
};
|
||||
const signer = getEventSigner();
|
||||
const ok = await signer.verify(signInput, e.signature);
|
||||
// Back-compat: rows persisted before EVENT_SIGNING_MODE existed are
|
||||
// HMAC, so if the active signer rejects them, fall through to the
|
||||
// legacy check before declaring a mismatch.
|
||||
if (!ok && legacyHmac(signInput) !== e.signature) {
|
||||
return {
|
||||
ok: false,
|
||||
brokenAt: i,
|
||||
reason: `signature mismatch (mode=${resolveSigningMode()})`,
|
||||
};
|
||||
const expectedSig = sign(e.plan_id, e.type, e.payload_hash, e.prev_hash);
|
||||
if (expectedSig !== e.signature) {
|
||||
return { ok: false, brokenAt: i, reason: "signature mismatch" };
|
||||
}
|
||||
prevSig = e.signature;
|
||||
}
|
||||
|
||||
@@ -1,302 +0,0 @@
|
||||
/**
|
||||
* Pluggable event signer (arch §7.5, §13; gap-analysis v2 §7.5 / §10.5).
|
||||
*
|
||||
* Three interchangeable strategies, selected via EVENT_SIGNING_MODE:
|
||||
*
|
||||
* - `hmac` (default; back-compat) HMAC-SHA256 keyed by
|
||||
* EVENT_BUS_HMAC_SECRET / SESSION_SECRET.
|
||||
* - `eip712` EIP-712 typed-data signature produced via ethers (when
|
||||
* ORCHESTRATOR_PRIVATE_KEY is set) or via the HSM
|
||||
* (services/hsm.ts) if EVENT_SIGNING_HSM_KEY_ID is set
|
||||
* and the HSM sign() path returns a 65-byte secp256k1
|
||||
* compact signature. Domain = {name: "CurrenciCombo",
|
||||
* version: "1", chainId: CHAIN_138_CHAIN_ID (138 by default)}.
|
||||
* - `jws` Compact JWS with HS256 headers, keyed by
|
||||
* EVENT_BUS_HMAC_SECRET.
|
||||
*
|
||||
* All strategies produce an opaque `string` signature suitable for
|
||||
* persisting to `events.signature` (varchar). Verification is done
|
||||
* by the same strategy code path — the prior record's signature is
|
||||
* still chained via `prev_hash` regardless of the mode.
|
||||
*/
|
||||
|
||||
import { createHmac, createHash } from "crypto";
|
||||
import { ethers } from "ethers";
|
||||
import { getHSMService } from "./hsm";
|
||||
|
||||
export type SigningMode = "hmac" | "eip712" | "jws";
|
||||
|
||||
export interface EventSignInput {
|
||||
planId: string;
|
||||
type: string;
|
||||
payloadHash: string;
|
||||
prevHash: string | null;
|
||||
}
|
||||
|
||||
export interface EventSigner {
|
||||
readonly mode: SigningMode;
|
||||
sign(input: EventSignInput): Promise<string>;
|
||||
verify(input: EventSignInput, signature: string): Promise<boolean>;
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------------
|
||||
* Shared canonical payload used across modes. Keeping it stable means
|
||||
* a signature produced in one mode can, in principle, be replayed into
|
||||
* a verifier configured for the same mode on another replica.
|
||||
* ----------------------------------------------------------------- */
|
||||
function canonicalMessage(input: EventSignInput): string {
|
||||
return `${input.planId}|${input.type}|${input.payloadHash}|${input.prevHash ?? ""}`;
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------------
|
||||
* HMAC (default / back-compat with the pre-existing signing scheme).
|
||||
* ----------------------------------------------------------------- */
|
||||
function getHmacSecret(): string {
|
||||
return (
|
||||
process.env.EVENT_BUS_HMAC_SECRET ??
|
||||
process.env.SESSION_SECRET ??
|
||||
"dev-event-bus-secret-change-in-production"
|
||||
);
|
||||
}
|
||||
|
||||
class HmacSigner implements EventSigner {
|
||||
readonly mode: SigningMode = "hmac";
|
||||
async sign(input: EventSignInput): Promise<string> {
|
||||
return createHmac("sha256", getHmacSecret())
|
||||
.update(canonicalMessage(input))
|
||||
.digest("hex");
|
||||
}
|
||||
async verify(input: EventSignInput, signature: string): Promise<boolean> {
|
||||
const expected = await this.sign(input);
|
||||
return timingSafeEqual(expected, signature);
|
||||
}
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------------
|
||||
* EIP-712 — typed-data signing via ethers. Structured according to
|
||||
* EIP-712; domain separator pins the signer to Chain-138 orchestrator.
|
||||
* ----------------------------------------------------------------- */
|
||||
function getEip712Domain() {
|
||||
const chainId = Number(process.env.CHAIN_138_CHAIN_ID ?? 138);
|
||||
return {
|
||||
name: "CurrenciCombo",
|
||||
version: "1",
|
||||
chainId,
|
||||
verifyingContract:
|
||||
process.env.NOTARY_REGISTRY_ADDRESS ??
|
||||
"0x0000000000000000000000000000000000000000",
|
||||
} as const;
|
||||
}
|
||||
|
||||
const EIP712_TYPES: Record<string, Array<{ name: string; type: string }>> = {
|
||||
Event: [
|
||||
{ name: "planId", type: "string" },
|
||||
{ name: "eventType", type: "string" },
|
||||
{ name: "payloadHash", type: "bytes32" },
|
||||
{ name: "prevHash", type: "bytes32" },
|
||||
],
|
||||
};
|
||||
|
||||
function toBytes32(hexOrHash: string | null): string {
|
||||
if (!hexOrHash) return "0x" + "0".repeat(64);
|
||||
const h = hexOrHash.startsWith("0x") ? hexOrHash.slice(2) : hexOrHash;
|
||||
// hash is sha256 (64 hex chars) — just pad/trim to 32 bytes.
|
||||
if (h.length === 64) return `0x${h}`;
|
||||
if (h.length > 64) return `0x${h.slice(0, 64)}`;
|
||||
return `0x${h.padEnd(64, "0")}`;
|
||||
}
|
||||
|
||||
class Eip712Signer implements EventSigner {
|
||||
readonly mode: SigningMode = "eip712";
|
||||
private wallet: ethers.Wallet | null = null;
|
||||
|
||||
constructor() {
|
||||
const pk = process.env.ORCHESTRATOR_PRIVATE_KEY;
|
||||
if (pk && /^0x[0-9a-fA-F]{64}$/.test(pk)) {
|
||||
this.wallet = new ethers.Wallet(pk);
|
||||
}
|
||||
}
|
||||
|
||||
private messageValue(input: EventSignInput) {
|
||||
return {
|
||||
planId: input.planId,
|
||||
eventType: input.type,
|
||||
payloadHash: toBytes32(input.payloadHash),
|
||||
prevHash: toBytes32(input.prevHash),
|
||||
};
|
||||
}
|
||||
|
||||
async sign(input: EventSignInput): Promise<string> {
|
||||
const message = this.messageValue(input);
|
||||
if (this.wallet) {
|
||||
// ethers v6: signTypedData(domain, types, value)
|
||||
return this.wallet.signTypedData(getEip712Domain(), EIP712_TYPES, message);
|
||||
}
|
||||
// HSM fallback — the mock HSM returns an opaque buffer. Wrap it
|
||||
// with the domain digest so it is still tamper-evident against
|
||||
// the canonical message.
|
||||
const digest = ethers.TypedDataEncoder.hash(
|
||||
getEip712Domain(),
|
||||
EIP712_TYPES,
|
||||
message,
|
||||
);
|
||||
const hsm = getHSMService();
|
||||
const keyId = process.env.EVENT_SIGNING_HSM_KEY_ID ?? "orchestrator";
|
||||
const raw = await hsm.sign(Buffer.from(digest.slice(2), "hex"), keyId);
|
||||
return `0x${raw.toString("hex")}`;
|
||||
}
|
||||
|
||||
async verify(input: EventSignInput, signature: string): Promise<boolean> {
|
||||
const message = this.messageValue(input);
|
||||
if (!signature.startsWith("0x")) return false;
|
||||
try {
|
||||
const recovered = ethers.verifyTypedData(
|
||||
getEip712Domain(),
|
||||
EIP712_TYPES,
|
||||
message,
|
||||
signature,
|
||||
);
|
||||
if (this.wallet) {
|
||||
return recovered.toLowerCase() === this.wallet.address.toLowerCase();
|
||||
}
|
||||
// HSM-backed: fall back to validity check only (we don't know
|
||||
// the pubkey without a separate HSM round-trip).
|
||||
return /^0x[0-9a-fA-F]+$/.test(signature);
|
||||
} catch {
|
||||
// Not an ECDSA signature (likely HSM-opaque). Return best-effort
|
||||
// by delegating to the HSM.
|
||||
const digest = ethers.TypedDataEncoder.hash(
|
||||
getEip712Domain(),
|
||||
EIP712_TYPES,
|
||||
message,
|
||||
);
|
||||
const hsm = getHSMService();
|
||||
const keyId = process.env.EVENT_SIGNING_HSM_KEY_ID ?? "orchestrator";
|
||||
const raw = Buffer.from(signature.slice(2), "hex");
|
||||
return hsm.verify(Buffer.from(digest.slice(2), "hex"), raw, keyId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------------
|
||||
* JWS compact (HS256). Useful when signing has to travel through a
|
||||
* JWT-aware infrastructure layer (API gateway, service mesh).
|
||||
* ----------------------------------------------------------------- */
|
||||
function base64UrlEncode(input: Buffer | string): string {
|
||||
const buf = Buffer.isBuffer(input) ? input : Buffer.from(input);
|
||||
return buf
|
||||
.toString("base64")
|
||||
.replace(/\+/g, "-")
|
||||
.replace(/\//g, "_")
|
||||
.replace(/=+$/, "");
|
||||
}
|
||||
|
||||
class JwsSigner implements EventSigner {
|
||||
readonly mode: SigningMode = "jws";
|
||||
async sign(input: EventSignInput): Promise<string> {
|
||||
const header = base64UrlEncode(
|
||||
JSON.stringify({ alg: "HS256", typ: "JWS", kid: "event-bus" }),
|
||||
);
|
||||
const body = base64UrlEncode(
|
||||
JSON.stringify({
|
||||
planId: input.planId,
|
||||
type: input.type,
|
||||
payloadHash: input.payloadHash,
|
||||
prevHash: input.prevHash,
|
||||
iat: Math.floor(Date.now() / 1000),
|
||||
}),
|
||||
);
|
||||
const signingInput = `${header}.${body}`;
|
||||
const mac = createHmac("sha256", getHmacSecret())
|
||||
.update(signingInput)
|
||||
.digest();
|
||||
return `${signingInput}.${base64UrlEncode(mac)}`;
|
||||
}
|
||||
|
||||
async verify(input: EventSignInput, jws: string): Promise<boolean> {
|
||||
const parts = jws.split(".");
|
||||
if (parts.length !== 3) return false;
|
||||
const [header, body, sig] = parts;
|
||||
const signingInput = `${header}.${body}`;
|
||||
const expected = base64UrlEncode(
|
||||
createHmac("sha256", getHmacSecret()).update(signingInput).digest(),
|
||||
);
|
||||
if (!timingSafeEqual(expected, sig)) return false;
|
||||
// Re-check that the body still describes the same canonical event —
|
||||
// protects against a valid JWS being replayed onto a different event.
|
||||
let decoded: Record<string, unknown>;
|
||||
try {
|
||||
decoded = JSON.parse(
|
||||
Buffer.from(body.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString(),
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
decoded.planId === input.planId &&
|
||||
decoded.type === input.type &&
|
||||
decoded.payloadHash === input.payloadHash &&
|
||||
(decoded.prevHash ?? null) === (input.prevHash ?? null)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------------
|
||||
* Registry.
|
||||
* ----------------------------------------------------------------- */
|
||||
|
||||
function timingSafeEqual(a: string, b: string): boolean {
|
||||
if (a.length !== b.length) return false;
|
||||
// Simple constant-time compare over the hex/base64 strings.
|
||||
let diff = 0;
|
||||
for (let i = 0; i < a.length; i++) {
|
||||
diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
||||
}
|
||||
return diff === 0;
|
||||
}
|
||||
|
||||
let cachedSigner: EventSigner | undefined;
|
||||
let cachedMode: SigningMode | undefined;
|
||||
|
||||
export function resolveSigningMode(): SigningMode {
|
||||
const raw = (process.env.EVENT_SIGNING_MODE ?? "hmac").toLowerCase();
|
||||
if (raw === "eip712" || raw === "jws" || raw === "hmac") return raw;
|
||||
return "hmac";
|
||||
}
|
||||
|
||||
export function getEventSigner(): EventSigner {
|
||||
const mode = resolveSigningMode();
|
||||
if (cachedSigner && cachedMode === mode) return cachedSigner;
|
||||
cachedMode = mode;
|
||||
cachedSigner =
|
||||
mode === "eip712"
|
||||
? new Eip712Signer()
|
||||
: mode === "jws"
|
||||
? new JwsSigner()
|
||||
: new HmacSigner();
|
||||
return cachedSigner;
|
||||
}
|
||||
|
||||
export function __resetSignerForTests(): void {
|
||||
cachedSigner = undefined;
|
||||
cachedMode = undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compatibility helper: the pre-PR-O signing scheme was
|
||||
* `hmac_sha256(secret, canonical)` returned as hex. Keep it for
|
||||
* verifying historical rows written before EVENT_SIGNING_MODE existed.
|
||||
*/
|
||||
export function legacyHmac(input: EventSignInput): string {
|
||||
return createHmac("sha256", getHmacSecret())
|
||||
.update(canonicalMessage(input))
|
||||
.digest("hex");
|
||||
}
|
||||
|
||||
/**
|
||||
* Deterministic sha256 over the payload — re-exported so the bus
|
||||
* doesn't have to import `crypto` directly.
|
||||
*/
|
||||
export function payloadHashOf(payload: unknown): string {
|
||||
return createHash("sha256").update(JSON.stringify(payload)).digest("hex");
|
||||
}
|
||||
134
orchestrator/tests/unit/apiKeyAuth.test.ts
Normal file
134
orchestrator/tests/unit/apiKeyAuth.test.ts
Normal file
@@ -0,0 +1,134 @@
|
||||
/**
|
||||
* 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();
|
||||
});
|
||||
});
|
||||
@@ -1,187 +0,0 @@
|
||||
/**
|
||||
* PR O — EIP-712 / JWS event signatures (gap-analysis v2 §7.5 / §10.5).
|
||||
*
|
||||
* Covers:
|
||||
* - HMAC default mode (back-compat) — round-trip sign/verify
|
||||
* - JWS compact mode — valid signature, payload-tamper detection,
|
||||
* signature-tamper detection
|
||||
* - EIP-712 mode — round-trip via ethers wallet, tamper detection
|
||||
* - Mode switching via EVENT_SIGNING_MODE + getEventSigner()
|
||||
* - legacyHmac helper preserves the pre-PR-O signature shape
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach } from "@jest/globals";
|
||||
import { ethers } from "ethers";
|
||||
import {
|
||||
getEventSigner,
|
||||
resolveSigningMode,
|
||||
legacyHmac,
|
||||
__resetSignerForTests,
|
||||
type EventSignInput,
|
||||
} from "../../src/services/eventSigner";
|
||||
|
||||
const TEST_KEY = "0x" + "ab".repeat(32); // deterministic test wallet
|
||||
|
||||
function makeInput(overrides: Partial<EventSignInput> = {}): EventSignInput {
|
||||
return {
|
||||
planId: "plan-x",
|
||||
type: "transaction.created",
|
||||
payloadHash: "a".repeat(64),
|
||||
prevHash: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("eventSigner — mode resolution", () => {
|
||||
beforeEach(() => {
|
||||
__resetSignerForTests();
|
||||
delete process.env.EVENT_SIGNING_MODE;
|
||||
delete process.env.ORCHESTRATOR_PRIVATE_KEY;
|
||||
});
|
||||
|
||||
it("defaults to hmac when env var absent", () => {
|
||||
expect(resolveSigningMode()).toBe("hmac");
|
||||
expect(getEventSigner().mode).toBe("hmac");
|
||||
});
|
||||
|
||||
it("honours eip712 / jws / hmac values", () => {
|
||||
for (const mode of ["eip712", "jws", "hmac"] as const) {
|
||||
__resetSignerForTests();
|
||||
process.env.EVENT_SIGNING_MODE = mode;
|
||||
expect(resolveSigningMode()).toBe(mode);
|
||||
expect(getEventSigner().mode).toBe(mode);
|
||||
}
|
||||
});
|
||||
|
||||
it("falls through to hmac on unknown mode", () => {
|
||||
process.env.EVENT_SIGNING_MODE = "bogus";
|
||||
expect(resolveSigningMode()).toBe("hmac");
|
||||
});
|
||||
});
|
||||
|
||||
describe("eventSigner — HMAC round-trip", () => {
|
||||
beforeEach(() => {
|
||||
__resetSignerForTests();
|
||||
process.env.EVENT_SIGNING_MODE = "hmac";
|
||||
process.env.EVENT_BUS_HMAC_SECRET = "test-secret";
|
||||
});
|
||||
|
||||
it("signs + verifies", async () => {
|
||||
const signer = getEventSigner();
|
||||
const input = makeInput();
|
||||
const sig = await signer.sign(input);
|
||||
expect(sig).toMatch(/^[0-9a-f]{64}$/);
|
||||
expect(await signer.verify(input, sig)).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a tampered payload hash", async () => {
|
||||
const signer = getEventSigner();
|
||||
const input = makeInput();
|
||||
const sig = await signer.sign(input);
|
||||
expect(
|
||||
await signer.verify({ ...input, payloadHash: "b".repeat(64) }, sig),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("legacyHmac produces the same hex as the HMAC signer", async () => {
|
||||
const input = makeInput();
|
||||
const sig = await getEventSigner().sign(input);
|
||||
expect(legacyHmac(input)).toBe(sig);
|
||||
});
|
||||
});
|
||||
|
||||
describe("eventSigner — JWS compact", () => {
|
||||
beforeEach(() => {
|
||||
__resetSignerForTests();
|
||||
process.env.EVENT_SIGNING_MODE = "jws";
|
||||
process.env.EVENT_BUS_HMAC_SECRET = "jws-secret";
|
||||
});
|
||||
|
||||
it("produces header.body.sig shape", async () => {
|
||||
const sig = await getEventSigner().sign(makeInput());
|
||||
expect(sig.split(".")).toHaveLength(3);
|
||||
});
|
||||
|
||||
it("round-trips sign/verify", async () => {
|
||||
const signer = getEventSigner();
|
||||
const input = makeInput();
|
||||
expect(await signer.verify(input, await signer.sign(input))).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a different event being presented with a valid sig", async () => {
|
||||
const signer = getEventSigner();
|
||||
const signed = await signer.sign(makeInput());
|
||||
expect(
|
||||
await signer.verify(makeInput({ type: "transaction.aborted" }), signed),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects a truncated signature", async () => {
|
||||
const signer = getEventSigner();
|
||||
const sig = await signer.sign(makeInput());
|
||||
expect(await signer.verify(makeInput(), sig.slice(0, -3))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("eventSigner — EIP-712 (ethers wallet)", () => {
|
||||
beforeEach(() => {
|
||||
__resetSignerForTests();
|
||||
process.env.EVENT_SIGNING_MODE = "eip712";
|
||||
process.env.ORCHESTRATOR_PRIVATE_KEY = TEST_KEY;
|
||||
process.env.CHAIN_138_CHAIN_ID = "138";
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete process.env.ORCHESTRATOR_PRIVATE_KEY;
|
||||
});
|
||||
|
||||
it("produces a 65-byte 0x-prefixed ECDSA signature", async () => {
|
||||
const sig = await getEventSigner().sign(makeInput());
|
||||
expect(sig).toMatch(/^0x[0-9a-fA-F]{130}$/);
|
||||
});
|
||||
|
||||
it("verifies as the signing wallet", async () => {
|
||||
const signer = getEventSigner();
|
||||
const input = makeInput();
|
||||
const sig = await signer.sign(input);
|
||||
expect(await signer.verify(input, sig)).toBe(true);
|
||||
// Recovered address should match the wallet derived from TEST_KEY.
|
||||
const expectedAddress = new ethers.Wallet(TEST_KEY).address;
|
||||
const recovered = ethers.verifyTypedData(
|
||||
{
|
||||
name: "CurrenciCombo",
|
||||
version: "1",
|
||||
chainId: 138,
|
||||
verifyingContract:
|
||||
process.env.NOTARY_REGISTRY_ADDRESS ??
|
||||
"0x0000000000000000000000000000000000000000",
|
||||
},
|
||||
{
|
||||
Event: [
|
||||
{ name: "planId", type: "string" },
|
||||
{ name: "eventType", type: "string" },
|
||||
{ name: "payloadHash", type: "bytes32" },
|
||||
{ name: "prevHash", type: "bytes32" },
|
||||
],
|
||||
},
|
||||
{
|
||||
planId: input.planId,
|
||||
eventType: input.type,
|
||||
payloadHash: `0x${input.payloadHash}`,
|
||||
prevHash: "0x" + "0".repeat(64),
|
||||
},
|
||||
sig,
|
||||
);
|
||||
expect(recovered.toLowerCase()).toBe(expectedAddress.toLowerCase());
|
||||
});
|
||||
|
||||
it("rejects a signature for a different event", async () => {
|
||||
const signer = getEventSigner();
|
||||
const sig = await signer.sign(makeInput());
|
||||
// Valid signature but rebound to a different event → fails because
|
||||
// the recovered address won't be our wallet.
|
||||
expect(
|
||||
await signer.verify(makeInput({ type: "transaction.committed" }), sig),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user