const assert = require("assert"); const fs = require("fs"); const path = require("path"); const vm = require("vm"); const rootDir = path.resolve(__dirname, "..", ".."); const loadRelayForwardingModule = (injected = {}) => { const filePath = path.join( rootDir, "pages/api/middleware/relayForwarding.js" ); let source = fs.readFileSync(filePath, "utf8"); source = source.replace(/import[\s\S]*?from\s+"[^"]+";\n?/g, ""); source = source.replace(/export const\s+/g, "const "); source += "\nmodule.exports = { relayGet, relayGetData, forwardGetData };\n"; const context = { module: { exports: {} }, exports: {}, require, process, setTimeout, clearTimeout, console: { log: () => {}, info: () => {}, warn: () => {}, error: () => {} }, ...injected }; vm.runInNewContext(source, context, { filename: filePath }); return context.module.exports; }; const tests = []; const test = (name, fn) => tests.push({ name, fn }); test("forwardGetData retries retryable HTTP status and then succeeds", async () => { let callCount = 0; const infoLogs = []; const mod = loadRelayForwardingModule({ axios: { get: async () => { callCount += 1; if (callCount === 1) { const error = new Error("temporary outage"); error.response = { status: 503 }; throw error; } return { data: { ok: true } }; } }, getToken: async () => ({ access_token: "token" }), hashAPIPath: () => "&hash=abc", azureHeaders: () => ({ headers: { Authorization: "Bearer token" } }), redactSensitive: (value) => value, consoleLogger: () => {}, console: { log: () => {}, info: (...args) => infoLogs.push(args), warn: () => {}, error: () => {} } }); const result = await mod.forwardGetData({ queryUrl: "incidents?$top=1", maxRetries: 1, retryBaseDelayMs: 0, retryMaxDelayMs: 0 }); assert.strictEqual(callCount, 2); assert.deepStrictEqual(result.data, { ok: true }); assert.strictEqual(result.accessToken, "token"); const eventNames = infoLogs.map((entry) => entry[0]); assert.ok(eventNames.includes("relay_request_started")); assert.ok(eventNames.includes("relay_request_retrying")); assert.ok(eventNames.includes("relay_request_succeeded")); const retryEvent = infoLogs.find( (entry) => entry[0] === "relay_request_retrying" ); assert.ok(retryEvent); const retryPayload = retryEvent[1]; assert.strictEqual(retryPayload.statusClass, "5xx"); assert.strictEqual(retryPayload.attemptsMade, 1); assert.strictEqual(retryPayload.retryCountUsed, 0); assert.strictEqual(retryPayload.remainingRetries, 1); assert.ok(typeof retryPayload.relayRequestId === "string"); const successEvent = infoLogs.find( (entry) => entry[0] === "relay_request_succeeded" ); assert.ok(successEvent); const successPayload = successEvent[1]; assert.strictEqual(successPayload.statusClass, "none"); assert.strictEqual(successPayload.attemptsMade, 2); assert.strictEqual(successPayload.retryCountUsed, 1); assert.ok(typeof successPayload.elapsedMs === "number"); }); test("forwardGetData does not retry non-retryable HTTP status", async () => { let callCount = 0; const infoLogs = []; const mod = loadRelayForwardingModule({ axios: { get: async () => { callCount += 1; const error = new Error("bad request"); error.response = { status: 400 }; throw error; } }, getToken: async () => ({ access_token: "token" }), hashAPIPath: () => "&hash=abc", azureHeaders: () => ({ headers: {} }), redactSensitive: (value) => value, consoleLogger: () => {}, console: { log: () => {}, info: (...args) => infoLogs.push(args), warn: () => {}, error: () => {} } }); let thrown = null; try { await mod.forwardGetData({ queryUrl: "incidents?$top=1", maxRetries: 3, retryBaseDelayMs: 0, retryMaxDelayMs: 0 }); } catch (error) { thrown = error; } assert.ok(thrown); assert.strictEqual(callCount, 1); const failedEvent = infoLogs.find( (entry) => entry[0] === "relay_request_failed" ); assert.ok(failedEvent); const failedPayload = failedEvent[1]; assert.strictEqual(failedPayload.statusClass, "4xx"); assert.strictEqual(failedPayload.attemptsMade, 1); assert.strictEqual(failedPayload.retryCountUsed, 0); assert.ok(typeof failedPayload.elapsedMs === "number"); }); test("forwardGetData does not retry unauthorized status", async () => { let callCount = 0; const mod = loadRelayForwardingModule({ axios: { get: async () => { callCount += 1; const error = new Error("unauthorized"); error.response = { status: 401 }; throw error; } }, getToken: async () => ({ access_token: "token" }), hashAPIPath: () => "&hash=abc", azureHeaders: () => ({ headers: {} }), redactSensitive: (value) => value, consoleLogger: () => {} }); let thrown = null; try { await mod.forwardGetData({ queryUrl: "incidents?$top=1", maxRetries: 3, retryBaseDelayMs: 0, retryMaxDelayMs: 0 }); } catch (error) { thrown = error; } assert.ok(thrown); assert.strictEqual(callCount, 1); }); test("relayGet avoids duplicate consoleLogger when relay layer already logged", async () => { let consoleLoggerCalls = 0; let respondErrorCalls = 0; const mod = loadRelayForwardingModule({ axios: { get: async () => { const error = new Error("bad request"); error.response = { status: 400 }; throw error; } }, getToken: async () => ({ access_token: "token" }), hashAPIPath: () => "&hash=abc", azureHeaders: () => ({ headers: {} }), redactSensitive: (value) => value, consoleLogger: () => { consoleLoggerCalls += 1; }, respondSuccess: () => {}, respondError: () => { respondErrorCalls += 1; } }); await mod.relayGet({ queryUrl: "incidents?$top=1", res: {}, errorResponse: { code: "FAILED" } }); assert.strictEqual(consoleLoggerCalls, 0); assert.strictEqual(respondErrorCalls, 1); }); test("forwardGetData clamps invalid env config values to safe bounds", async () => { const previousEnv = { RELAY_TIMEOUT_MS: process.env.RELAY_TIMEOUT_MS, RELAY_RETRY_MAX: process.env.RELAY_RETRY_MAX, RELAY_RETRY_BASE_DELAY_MS: process.env.RELAY_RETRY_BASE_DELAY_MS, RELAY_RETRY_MAX_DELAY_MS: process.env.RELAY_RETRY_MAX_DELAY_MS }; process.env.RELAY_TIMEOUT_MS = "999999"; process.env.RELAY_RETRY_MAX = "999"; process.env.RELAY_RETRY_BASE_DELAY_MS = "-1"; process.env.RELAY_RETRY_MAX_DELAY_MS = "999999"; let capturedOptions = null; const mod = loadRelayForwardingModule({ axios: { get: async (url, options) => { capturedOptions = options; return { data: { ok: true } }; } }, getToken: async () => ({ access_token: "token" }), hashAPIPath: () => "&hash=abc", azureHeaders: () => ({ headers: {} }), redactSensitive: (value) => value, consoleLogger: () => {} }); await mod.forwardGetData({ queryUrl: "incidents?$top=1" }); assert.strictEqual(capturedOptions.timeout, 30000); process.env.RELAY_TIMEOUT_MS = previousEnv.RELAY_TIMEOUT_MS; process.env.RELAY_RETRY_MAX = previousEnv.RELAY_RETRY_MAX; process.env.RELAY_RETRY_BASE_DELAY_MS = previousEnv.RELAY_RETRY_BASE_DELAY_MS; process.env.RELAY_RETRY_MAX_DELAY_MS = previousEnv.RELAY_RETRY_MAX_DELAY_MS; }); test("forwardGetData applies timeout and appendHash=false behavior", async () => { let capturedUrl = null; let capturedOptions = null; const mod = loadRelayForwardingModule({ axios: { get: async (url, options) => { capturedUrl = url; capturedOptions = options; return { data: { ok: true } }; } }, getToken: async () => ({ access_token: "token" }), hashAPIPath: () => "&hash=abc", azureHeaders: () => ({ headers: { Accept: "application/json" } }), redactSensitive: (value) => value, consoleLogger: () => {} }); await mod.forwardGetData({ baseUrl: "http://localhost:3000", queryUrl: "/api/endpoint/example", appendHash: false, timeoutMs: 1234, maxRetries: 0 }); assert.strictEqual( capturedUrl, "http://localhost:3000/api/endpoint/example" ); assert.strictEqual(capturedOptions.timeout, 1234); assert.strictEqual(capturedOptions.headers.Accept, "application/json"); }); test("forwardGetData telemetry request id is stable across lifecycle events", async () => { const infoLogs = []; let callCount = 0; const mod = loadRelayForwardingModule({ axios: { get: async () => { callCount += 1; if (callCount === 1) { const error = new Error("service unavailable"); error.response = { status: 503 }; throw error; } return { data: { ok: true }, status: 200 }; } }, getToken: async () => ({ access_token: "token" }), hashAPIPath: () => "&hash=abc", azureHeaders: () => ({ headers: {} }), redactSensitive: (value) => value, consoleLogger: () => {}, console: { log: () => {}, info: (...args) => infoLogs.push(args), warn: () => {}, error: () => {} } }); await mod.forwardGetData({ queryUrl: "incidents?$top=1", maxRetries: 1, retryBaseDelayMs: 0, retryMaxDelayMs: 0 }); const lifecycleEvents = infoLogs .filter((entry) => [ "relay_request_started", "relay_request_retrying", "relay_request_succeeded" ].includes(entry[0]) ) .map((entry) => entry[1]); assert.strictEqual(lifecycleEvents.length, 3); const relayRequestIds = lifecycleEvents.map( (event) => event.relayRequestId ); assert.ok( relayRequestIds.every((id) => typeof id === "string" && id.length > 0) ); assert.strictEqual(new Set(relayRequestIds).size, 1); }); test("forwardGetData relayPolicy override controls retry behavior", async () => { let callCount = 0; const infoLogs = []; const mod = loadRelayForwardingModule({ axios: { get: async () => { callCount += 1; if (callCount < 3) { const error = new Error("temporary outage"); error.response = { status: 503 }; throw error; } return { data: { ok: true }, status: 200 }; } }, getToken: async () => ({ access_token: "token" }), hashAPIPath: () => "&hash=abc", azureHeaders: () => ({ headers: {} }), redactSensitive: (value) => value, consoleLogger: () => {}, console: { log: () => {}, info: (...args) => infoLogs.push(args), warn: () => {}, error: () => {} } }); const result = await mod.forwardGetData({ queryUrl: "incidents?$top=1", maxRetries: 0, relayPolicy: { maxRetries: 2, retryBaseDelayMs: 0, retryMaxDelayMs: 0, method: "GET" } }); assert.strictEqual(callCount, 3); assert.deepStrictEqual(result.data, { ok: true }); const startEvent = infoLogs.find( (entry) => entry[0] === "relay_request_started" ); assert.ok(startEvent); assert.strictEqual(startEvent[1].maxRetries, 2); assert.strictEqual(startEvent[1].method, "GET"); }); test("forwardGetData blocks retries for non-idempotent methods by default", async () => { let callCount = 0; const infoLogs = []; const mod = loadRelayForwardingModule({ axios: { get: async () => { callCount += 1; const error = new Error("temporary outage"); error.response = { status: 503 }; throw error; } }, getToken: async () => ({ access_token: "token" }), hashAPIPath: () => "&hash=abc", azureHeaders: () => ({ headers: {} }), redactSensitive: (value) => value, consoleLogger: () => {}, console: { log: () => {}, info: (...args) => infoLogs.push(args), warn: () => {}, error: () => {} } }); let thrown = null; try { await mod.forwardGetData({ queryUrl: "incidents?$top=1", relayPolicy: { method: "POST", maxRetries: 3, retryBaseDelayMs: 0, retryMaxDelayMs: 0 } }); } catch (error) { thrown = error; } assert.ok(thrown); assert.strictEqual(callCount, 1); const retryEvents = infoLogs.filter( (entry) => entry[0] === "relay_request_retrying" ); assert.strictEqual(retryEvents.length, 0); const failedEvent = infoLogs.find( (entry) => entry[0] === "relay_request_failed" ); assert.ok(failedEvent); assert.strictEqual(failedEvent[1].method, "POST"); }); test("forwardGetData can allow retries for non-idempotent methods when explicitly enabled", async () => { let callCount = 0; const mod = loadRelayForwardingModule({ axios: { get: async () => { callCount += 1; if (callCount === 1) { const error = new Error("temporary outage"); error.response = { status: 503 }; throw error; } return { data: { ok: true }, status: 200 }; } }, getToken: async () => ({ access_token: "token" }), hashAPIPath: () => "&hash=abc", azureHeaders: () => ({ headers: {} }), redactSensitive: (value) => value, consoleLogger: () => {} }); const result = await mod.forwardGetData({ queryUrl: "incidents?$top=1", relayPolicy: { method: "PATCH", maxRetries: 1, retryBaseDelayMs: 0, retryMaxDelayMs: 0, allowNonIdempotentRetries: true } }); assert.strictEqual(callCount, 2); assert.deepStrictEqual(result.data, { ok: true }); }); const run = async () => { let passed = 0; for (const currentTest of tests) { await currentTest.fn(); passed += 1; } console.log( `Phase 21 relay-forwarding hardening tests passed (${passed}/${tests.length}).` ); }; module.exports = run; if (require.main === module) { run().catch((error) => { console.error(error); process.exit(1); }); }