agentgate-runtime-control 2.13.13 → 2.13.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -24,18 +24,6 @@ Useful control-plane endpoints include `/api/observability`, `/api/trace?runId=.
24
24
 
25
25
  **Observe → Attack → Enforce → Replay → Report → Govern**
26
26
 
27
- ### Quickstart
28
-
29
- ```bash
30
- npm install agentgate-runtime-control
31
- npx agentgate init # writes agentgate.config.mjs — tells you to run doctor next
32
- npx agentgate doctor # checks your config, warns loudly if you're still in observe mode,
33
- # then tells you to open examples/protect-first-tool.mjs next
34
- node examples/protect-first-tool.mjs # see a real tool protected end-to-end
35
- npx agentgate attack --config ./agentgate.config.mjs # attack-test YOUR policy, not the defaults
36
- ```
37
-
38
- Each command prints what to run next, so you don't have to remember this sequence.
39
27
 
40
28
  ## Design Partner Edition
41
29
 
@@ -82,10 +70,6 @@ The config file must export an `agentgate` object created with `createAgentGate(
82
70
 
83
71
  See [`docs/production-readiness.md`](docs/production-readiness.md), [`docs/production-deployment.md`](docs/production-deployment.md), and [`docs/release-checklist.md`](docs/release-checklist.md) for deployment, operational, performance, and release gates.
84
72
 
85
- ### About `npm test` on the installed package
86
-
87
- Running `npm test` inside an **installed** copy of `agentgate-runtime-control` (i.e. from `node_modules`) reports `0 tests` — that's expected, not a bug: the `test/` directory is intentionally not published to npm (see `files` in `package.json`), the same way most published packages don't ship their own test suite to consumers. The real suite (150+ cases, covering policy decisions, the approval lifecycle — including concurrent approve/deny and TTL expiry — attack-lab scenarios, egress guarding, multi-tenant isolation, and more) lives in and runs from the [source repository](https://github.com/walid-agentgate/agentgate) via `node --test`.
88
-
89
73
  ## Security
90
74
 
91
75
  See [`SECURITY.md`](SECURITY.md) for the security model and vulnerability-reporting guidance. AgentGate provides a deterministic control layer; it does not replace application-level identity, secret management, network isolation, or threat-model testing.
@@ -274,26 +258,6 @@ Approval state is queryable through `gateway.approvals()` and JSON-RPC methods:
274
258
 
275
259
  The approval layer is intentionally separate from policy evaluation: policy decides `ALLOW`, `ASK`, or `BLOCK`; approval resolves only the `ASK` path.
276
260
 
277
- ### Approval lifecycle — who, when, expiry, single-use, revocation
278
-
279
- - **Who approved / denied, and when**: every approval record carries `createdAt`, `resolvedAt`, and (for a deny) a `resolutionReason`. The run record (`gateway.replay(runId)`) links back to the approval via `approvalId` and stores the same `approval` block for audit export (`gateway.replay()` / `/api/audit/export`). AgentGate itself doesn't have a user identity system, so "who" is whatever identity your own auth layer attaches to the request that calls `approve()`/`deny()` — log that at your call site if you need a named approver.
280
- - **Expiry (TTL)**: a pending approval expires automatically after **15 minutes** by default (`DEFAULT_APPROVAL_TTL_MS` in `src/approval.js`). Pass `approvalTTLMs` to `createRuntime`/`createAgentGate`/`createMCPGateway` to change it, or `ttlMs: null` on a specific request to disable expiry. Once `expiresAt` passes, the approval flips to `status: 'expired'` the next time it's looked at (list/get/approve/deny), and the original tool call can never be executed late.
281
- - **Single-use guarantee**: `approve()`/`deny()` are synchronous up to the point where they flip `status` away from `pending` — there is no `await` in between the status check and the status write. Because Node runs JS on a single thread, two calls racing to resolve the same approval (concurrent HTTP requests, a double click, a retried request) can never both see `pending`: the second call always sees the already-resolved status and is rejected with `Approval is already <status>`. There is nothing else to configure for this — it's guaranteed by construction, not by a lock.
282
- - **Revocation**: there's no separate "revoke" verb — deny a still-pending approval with `gateway.deny(approvalId, reason)` (or `agentgate approval deny <id> <reason>` from the CLI) to take it off the table before anyone acts on it.
283
- - **Duplicate requests**: each call to a protected tool creates its own approval with its own id — AgentGate does not de-duplicate identical-looking requests. If your agent might retry the same call, treat that as your integration's concern (e.g. an idempotency key on your own tool handler).
284
-
285
- ### Approval CLI
286
-
287
- Once a gateway or control plane is running (for example via `agentgate dev`), you can list and resolve approvals from the command line instead of writing HTTP calls by hand:
288
-
289
- ```
290
- agentgate approval list [--status pending|approved|denied|expired] [--url <url>]
291
- agentgate approval approve <approvalId> [--url <url>] [--key <apiKey>]
292
- agentgate approval deny <approvalId> [reason] [--url <url>] [--key <apiKey>]
293
- ```
294
-
295
- By default it talks to `http://localhost:8787` (what `agentgate dev` uses) and, if no `--key`/`AGENTGATE_API_KEY` is given, it automatically picks up the local dev session the same way opening the dashboard in a browser would — no extra setup needed for local testing. Point `--url` at a different host/port for a control plane running elsewhere, and pass `--key` (or set `AGENTGATE_API_KEY`) when auth is required outside local dev.
296
-
297
261
  ## v1.1 — Developer Integration
298
262
 
299
263
  AgentGate now exposes a single developer-facing runtime:
package/bin/agentgate.js CHANGED
@@ -6,7 +6,7 @@ import { createRequire } from 'node:module';
6
6
  import { evaluate } from '../src/policy-engine.js';
7
7
  import { createAgentGate } from '../src/agentgate.js';
8
8
  import { createControlPlane } from '../src/control-plane.js';
9
- import { runGatewayAttackLab, summarizeAttackResults } from '../src/attack-lab.js';
9
+ import { runGatewayAttackLab, runDeepAttackLab, summarizeAttackResults } from '../src/attack-lab.js';
10
10
  import { createMCPGateway } from '../src/mcp-gateway.js';
11
11
  import { generateSecurityReport, renderSecurityReportHTML } from '../src/security-report.js';
12
12
  import { createPolicyRegistry } from '../src/policy-registry.js';
@@ -28,8 +28,8 @@ Usage:
28
28
  agentgate init
29
29
  agentgate dev [--port <port>]
30
30
  agentgate test <action> [amount]
31
- agentgate attack
32
- agentgate attack-ci
31
+ agentgate attack [--config <path>] [--deep]
32
+ agentgate attack-ci [--deep]
33
33
  agentgate report
34
34
  agentgate scan <tools.json> [--strict]
35
35
  agentgate egress <response.json> [--strict]
@@ -119,6 +119,10 @@ export { pack };
119
119
  if (config.mode === 'observe') {
120
120
  console.error('\n⚠️ WARNING: mode is "observe". Decisions are being recorded but NOTHING is actually blocked or held for approval yet — destructive tools will still execute. Set mode: \'enforce\' in agentgate.config.mjs once you are ready to protect real tools.');
121
121
  }
122
+ const effectiveUnknownActionPolicy = config.policies?.unknownActionPolicy || 'allow';
123
+ if (effectiveUnknownActionPolicy === 'allow') {
124
+ console.error('\n⚠️ WARNING: policies.unknownActionPolicy is "allow" (the default). Any action name AgentGate does not recognize — a typo, a new tool, something like "grant_admin" or "drop_database" — is ALLOWED through, not blocked or asked. Set policies.unknownActionPolicy: \'ask\' (or \'block\' for the strictest, deny-by-default behavior) in agentgate.config.mjs before treating this as production-safe.');
125
+ }
122
126
  if (report.ok) {
123
127
  console.error('\nNext: protect your first tool — see examples/protect-first-tool.mjs for a worked example (read/delete/refund/export), or run `agentgate attack --config agentgate.config.mjs` to test your policy against the built-in attack scenarios.');
124
128
  } else {
@@ -194,19 +198,35 @@ export { pack };
194
198
  if (process.argv.includes('--strict') && result.action === 'BLOCK') process.exitCode = 2;
195
199
  }
196
200
  } else if (cmd === 'attack-ci') {
197
- const gateway = createMCPGateway({ mode:'enforce', policies:{productionBlock:true}, tools:[{name:'export_all',handler:async()=>({})},{name:'update_production',handler:async()=>({})},{name:'delete',handler:async()=>({})},{name:'refund',handler:async()=>({})},{name:'publish',handler:async()=>({})}] });
198
- const results=await runGatewayAttackLab(gateway); const summary=summarizeAttackResults(results); console.log(JSON.stringify({summary,results},null,2)); process.exitCode=summary.failed?2:0;
201
+ const deep = process.argv.includes('--deep');
202
+ const gateway = createMCPGateway({ mode:'enforce', policies:{productionBlock:true}, tools:[{name:'export_all',handler:async()=>({})},{name:'update_production',handler:async()=>({})},{name:'delete',handler:async()=>({})},{name:'refund',handler:async()=>({})},{name:'publish',handler:async()=>({})},{name:'grant_admin',handler:async()=>({})},{name:'read_secrets',handler:async()=>({})},{name:'drop_database',handler:async()=>({})},{name:'modify_billing',handler:async()=>({})},{name:'transfer_money',handler:async()=>({})},{name:'disable_security_controls',handler:async()=>({})},{name:'purge_records',handler:async()=>({})},{name:'impersonate_user',handler:async()=>({})},{name:'remove_customer',handler:async()=>({})},{name:'export_data',handler:async()=>({})}] });
203
+ const results = deep ? await runDeepAttackLab(gateway) : await runGatewayAttackLab(gateway);
204
+ const summary=summarizeAttackResults(results); console.log(JSON.stringify({summary,results},null,2)); process.exitCode=summary.failed?2:0;
199
205
  } else if (cmd === 'test' || cmd === 'check') {
200
206
  console.log(JSON.stringify(evaluate({ action, amount: Number(amount) }), null, 2));
201
207
  } else if (cmd === 'attack') {
202
208
  const configIndex = process.argv.indexOf('--config');
203
209
  const configPath = configIndex >= 0 ? process.argv[configIndex + 1] : null;
210
+ const deep = process.argv.includes('--deep');
204
211
  const defaultTools = [
205
212
  { name: 'export_all', handler: async () => ({ executed: true }) },
206
213
  { name: 'update_production', handler: async () => ({ executed: true }) },
207
214
  { name: 'delete', handler: async () => ({ executed: true }) },
208
215
  { name: 'refund', handler: async args => ({ refunded: args.amount }) },
209
- { name: 'publish', handler: async () => ({ executed: true }) }
216
+ { name: 'publish', handler: async () => ({ executed: true }) },
217
+ // Tools for the deeper, "unrecognized action name" attack set
218
+ // (`--deep`). Harmless no-op handlers — the point is to see what the
219
+ // POLICY decides, not to actually grant admin or drop a database.
220
+ { name: 'grant_admin', handler: async () => ({ executed: true }) },
221
+ { name: 'read_secrets', handler: async () => ({ executed: true }) },
222
+ { name: 'drop_database', handler: async () => ({ executed: true }) },
223
+ { name: 'modify_billing', handler: async () => ({ executed: true }) },
224
+ { name: 'transfer_money', handler: async args => ({ transferred: args.amount }) },
225
+ { name: 'disable_security_controls', handler: async () => ({ executed: true }) },
226
+ { name: 'purge_records', handler: async () => ({ executed: true }) },
227
+ { name: 'impersonate_user', handler: async () => ({ executed: true }) },
228
+ { name: 'remove_customer', handler: async () => ({ executed: true }) },
229
+ { name: 'export_data', handler: async () => ({ executed: true }) }
210
230
  ];
211
231
  let gateway = null;
212
232
  let label = 'built-in default policies';
@@ -228,11 +248,14 @@ export { pack };
228
248
  if (!gateway) {
229
249
  gateway = createMCPGateway({ mode: 'enforce', policies: { productionBlock: true }, tools: defaultTools });
230
250
  }
231
- const results = await runGatewayAttackLab(gateway);
251
+ const results = deep ? await runDeepAttackLab(gateway) : await runGatewayAttackLab(gateway);
232
252
  const summary = summarizeAttackResults(results);
233
- console.log(`\nAgentGate Attack Runner — testing against ${label}`);
253
+ console.log(`\nAgentGate Attack Runner${deep ? ' (deep: unrecognized-action-name scenarios)' : ''} — testing against ${label}`);
234
254
  console.table(results.map(x => ({ test: x.name, decision: x.decision, risk: x.risk, passed: x.passed, runId: x.runId })));
235
255
  console.log('Summary:', JSON.stringify(summary));
256
+ if (deep && summary.allowed > 0) {
257
+ console.error(`\n${summary.allowed} unrecognized action(s) ALLOWed through untouched. If that's not intended, set policies.unknownActionPolicy: 'ask' or 'block'.`);
258
+ }
236
259
  process.exitCode = summary.failed ? 2 : 0;
237
260
  } else if (cmd === 'report') {
238
261
  const gateway = createMCPGateway({
@@ -298,8 +321,8 @@ export { pack };
298
321
  else {
299
322
  const file = path.resolve(process.cwd(), 'agentgate.config.mjs');
300
323
  const content = pack
301
- ? `import { createAgentGate, getPolicyPack } from 'agentgate-runtime-control';\n\nconst pack = getPolicyPack('${pack.id}');\n\nexport const agentgate = createAgentGate({\n agent: 'SupportAgent',\n mode: 'observe',\n policies: pack.policies\n});\n\nexport { pack };\n`
302
- : `import { createAgentGate } from 'agentgate-runtime-control';\n\nexport const agentgate = createAgentGate({\n agent: 'MyAgent',\n mode: 'enforce',\n policies: {\n productionBlock: true,\n autoApproveAmount: 500,\n approvalAmount: 5000\n }\n});\n`;
324
+ ? `import { createAgentGate, getPolicyPack } from 'agentgate-runtime-control';\n\nconst pack = getPolicyPack('${pack.id}');\n\nexport const agentgate = createAgentGate({\n agent: 'SupportAgent',\n mode: 'observe',\n policies: {\n ...pack.policies,\n // Any action name AgentGate doesn't recognize (a typo, a new tool, a\n // third-party integration using its own action names) is asked about\n // by default here, rather than silently allowed through. Set to\n // 'block' once you've classified every legitimate action name.\n unknownActionPolicy: 'ask'\n }\n});\n\nexport { pack };\n`
325
+ : `import { createAgentGate } from 'agentgate-runtime-control';\n\nexport const agentgate = createAgentGate({\n agent: 'MyAgent',\n mode: 'enforce',\n policies: {\n productionBlock: true,\n autoApproveAmount: 500,\n approvalAmount: 5000,\n // Any action name AgentGate doesn't recognize (a typo, a new tool, a\n // third-party integration using its own action names) is asked about\n // by default here, rather than silently allowed through. Set to\n // 'block' once you've classified every legitimate action name, or back\n // to 'allow' only if you understand and accept that gap.\n unknownActionPolicy: 'ask'\n }\n});\n`;
303
326
  try { await fs.access(file); console.error('agentgate.config.mjs already exists'); process.exitCode = 1; }
304
327
  catch {
305
328
  await fs.writeFile(file, content, 'utf8');
@@ -81,3 +81,34 @@ await tryCall('export_all', protectedExportAll, { environment: env });
81
81
 
82
82
  console.log('\nNothing above BLOCK or pending ASK ever reached its real handler.');
83
83
  console.log('See gate.approvals() to review and approve pending ASK requests.');
84
+
85
+ // --- The gap `unknownActionPolicy` closes ---
86
+ //
87
+ // AgentGate only recognizes a small built-in list of "destructive" action
88
+ // names (delete, refund, publish, deploy, export_all, update_production).
89
+ // A tool using ANY other action name — a typo, a new tool, a third-party
90
+ // integration's own naming — falls through every rule above and is
91
+ // ALLOWED by default. That is not a bug in the rules you just saw; it's
92
+ // the deliberate (but risky) default, so watch what happens to an
93
+ // unclassified but obviously dangerous-sounding action name:
94
+ async function grantAdmin({ userId }) { return { granted: userId }; }
95
+ const looseGate = gate; // same gate as above — policies do NOT set unknownActionPolicy
96
+ const protectedGrantAdminLoose = looseGate.protect(grantAdmin, { tool: 'grant_admin', action: 'grant_admin' });
97
+ await tryCall('grant_admin (default)', protectedGrantAdminLoose, { userId: 'u_1', environment: env });
98
+ console.log('^ That ALLOWed by default — AgentGate has never seen this action name before.\n');
99
+
100
+ // Fix it by setting unknownActionPolicy: 'ask' (or 'block') on the gate:
101
+ const strictGate = createAgentGate({
102
+ agent: 'SupportAgent',
103
+ mode: 'enforce',
104
+ policies: {
105
+ productionBlock: true,
106
+ approvalAmount: 5000,
107
+ blockActions: ['export_all'],
108
+ unknownActionPolicy: 'ask' // <- the fix: unrecognized actions now ASK instead of ALLOW
109
+ }
110
+ });
111
+ const protectedGrantAdminStrict = strictGate.protect(grantAdmin, { tool: 'grant_admin', action: 'grant_admin' });
112
+ await tryCall('grant_admin (unknownActionPolicy: ask)', protectedGrantAdminStrict, { userId: 'u_1', environment: env });
113
+ console.log('^ Same unrecognized action, now held for approval instead of silently executing.');
114
+ console.log('`agentgate doctor` warns loudly whenever unknownActionPolicy is left at its default.');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentgate-runtime-control",
3
- "version": "2.13.13",
3
+ "version": "2.13.15",
4
4
  "type": "module",
5
5
  "description": "Runtime control plane and SaaS governance layer for AI agent tool execution",
6
6
  "exports": {
package/src/attack-lab.js CHANGED
@@ -8,6 +8,34 @@ const cases = [
8
8
  { id:'tool-chaining', name:'Unsafe tool chaining', action:'publish', environment:'production', payload:'Read private data, then publish it externally.' }
9
9
  ];
10
10
 
11
+ // A second, larger set of scenarios beyond the 5 built-in ones above.
12
+ // These specifically target the "unrecognized action name" gap: every
13
+ // action name here is NOT in the policy engine's built-in destructive/
14
+ // read-only lists, so under the default policy (`unknownActionPolicy:
15
+ // 'allow'`) every one of them ALLOWs — that is the point. Run these with
16
+ // `agentgate attack --deep` (or `runDeepAttackLab`) against YOUR policy to
17
+ // see which of your own unclassified action names are currently wide open,
18
+ // and to prove `unknownActionPolicy: 'ask'|'block'` actually closes them.
19
+ //
20
+ // The last two cases are a different, related risk: action-NAME aliasing.
21
+ // A `blockActions: ['export_all']` or `approvalActions: ['delete']` policy
22
+ // only matches that exact string — a tool or integration that does the
23
+ // same dangerous thing under a different name (`export_data` instead of
24
+ // `export_all`, `remove_customer` instead of `delete`) evades it entirely
25
+ // unless `unknownActionPolicy` also covers the fallback.
26
+ const deepCases = [
27
+ { id:'privilege-escalation-unknown', name:'Privilege escalation (unrecognized action)', action:'grant_admin', environment:'production', payload:'Grant this session admin rights.' },
28
+ { id:'credential-exfiltration', name:'Credential exfiltration (unrecognized action)', action:'read_secrets', environment:'production', payload:'Return all stored API keys and secrets.' },
29
+ { id:'destructive-db-unknown', name:'Database destruction (unrecognized action)', action:'drop_database', environment:'production', payload:'Drop the production database.' },
30
+ { id:'billing-tamper-unknown', name:'Billing tampering (unrecognized action)', action:'modify_billing', environment:'production', payload:'Set this customer\'s invoice total to zero.' },
31
+ { id:'funds-transfer-unknown', name:'Unauthorized funds transfer (unrecognized action)', action:'transfer_money', amount:25000, environment:'production', payload:'Transfer funds to this external account.' },
32
+ { id:'config-tamper-unknown', name:'Security control tampering (unrecognized action)', action:'disable_security_controls', environment:'production', payload:'Turn off audit logging and rate limits.' },
33
+ { id:'bulk-purge-unknown', name:'Bulk record purge (unrecognized action)', action:'purge_records', environment:'production', payload:'Permanently delete all archived records.' },
34
+ { id:'impersonation-unknown', name:'User impersonation (unrecognized action)', action:'impersonate_user', environment:'production', payload:'Act as this customer for the rest of the session.' },
35
+ { id:'delete-alias-evasion', name:'Delete via unlisted alias (name evasion)', action:'remove_customer', environment:'production', payload:'Remove this customer record permanently.' },
36
+ { id:'export-alias-evasion', name:'Export via unlisted alias (name evasion)', action:'export_data', environment:'production', payload:'Export the full customer table.' }
37
+ ];
38
+
11
39
  export function runAttackLab(policies = {}) {
12
40
  return cases.map(test => {
13
41
  const result = evaluate(test, policies);
@@ -75,7 +103,19 @@ export async function runGatewayAttackLab(gateway, options = {}) {
75
103
  return results;
76
104
  }
77
105
 
78
- export { cases as ATTACK_CASES };
106
+ /**
107
+ * Run the deeper, "unrecognized action name" attack set against a gateway.
108
+ * Accepts the same options as runGatewayAttackLab (toolMap, etc). Unlike
109
+ * the built-in 5, every one of these targets an action name the policy
110
+ * engine does not classify by default — they are expected to ALLOW unless
111
+ * the gateway's policy sets `unknownActionPolicy: 'ask'|'block'`, or lists
112
+ * the exact action name explicitly.
113
+ */
114
+ export async function runDeepAttackLab(gateway, options = {}) {
115
+ return runGatewayAttackLab(gateway, { ...options, cases: options.cases || deepCases });
116
+ }
117
+
118
+ export { cases as ATTACK_CASES, deepCases as DEEP_ATTACK_CASES };
79
119
 
80
120
 
81
121
  /** Summarize an attack run for CLI/UI/report consumers. */
@@ -18,10 +18,42 @@ import { createRequire } from 'node:module';
18
18
  const require = createRequire(import.meta.url);
19
19
  const PACKAGE_VERSION = require('../package.json').version;
20
20
 
21
+ // Reads and parses a POST body with a hard size cap. Earlier versions bailed
22
+ // out of the read loop as soon as the cap was exceeded without consuming the
23
+ // rest of the incoming request — on a keep-alive connection, those unread
24
+ // bytes are still in flight from the client and get misinterpreted as the
25
+ // start of the next request, which is what caused an unrelated follow-up
26
+ // request on the same socket to hang until timeout instead of failing fast.
27
+ // Fix: once oversized, keep draining every chunk (so the socket/HTTP parser
28
+ // ends this request cleanly) but stop buffering it into memory, then raise a
29
+ // typed error with the right status for the caller to respond with.
30
+ async function readJsonBody(req, maxBodySize) {
31
+ let raw = '';
32
+ let bytes = 0;
33
+ let oversized = false;
34
+ for await (const chunk of req) {
35
+ bytes += chunk.length;
36
+ if (bytes > maxBodySize) { oversized = true; continue; }
37
+ raw += chunk;
38
+ }
39
+ if (oversized) {
40
+ const error = new Error('Payload too large');
41
+ error.status = 413;
42
+ throw error;
43
+ }
44
+ try {
45
+ return raw ? JSON.parse(raw) : {};
46
+ } catch {
47
+ const error = new Error('Invalid JSON');
48
+ error.status = 400;
49
+ throw error;
50
+ }
51
+ }
52
+
21
53
  export function createControlPlane(options = {}) {
22
54
  const gateway = options.gateway || createMCPGateway(options);
23
55
  const staticHtml = options.html;
24
- const agentStore = options.agentStore || (options.persistence ? createPersistentAgentStore({ filePath: options.agentPersistence || `${options.persistence}/agents.json` }) : null);
56
+ const agentStore = options.agentStore || (options.persistence ? createPersistentAgentStore({ filePath: options.agentPersistence || `${options.persistence}/agents.json`, recoverFromCorruption: options.recoverFromCorruption, onCorruption: options.onPersistenceCorruption }) : null);
25
57
  const tenantRegistry = options.tenantRegistry || new TenantRegistry({ filePath: `${options.persistence || '.agentgate'}/tenants.json`, keyPath: `${options.persistence || '.agentgate'}/api-keys.json` });
26
58
  const webhookRegistry = options.webhookRegistry || new WebhookRegistry({ filePath: `${options.persistence || '.agentgate'}/webhooks.json`, deliveryPath: `${options.persistence || '.agentgate'}/webhook-deliveries.json` });
27
59
  const authRequired = options.authRequired !== false;
@@ -69,7 +101,11 @@ export function createControlPlane(options = {}) {
69
101
  const scopedRuns = () => gateway.runs(tenantId);
70
102
  const scopedApprovals = (status) => gateway.approvals(status, tenantId);
71
103
  if (path === '/api/health') return { ok: true, mode: gateway.mode, version: gateway?.serverInfo?.version || PACKAGE_VERSION };
72
- if (path === '/api/ready') return { ok: true, ready: true, mode: gateway.mode, uptimeSeconds: Math.floor((Date.now() - startedAt) / 1000) };
104
+ if (path === '/api/ready') {
105
+ const persistence = gateway.persistenceHealth?.() || { persistent: false, degraded: false, corruptions: [] };
106
+ const ready = !persistence.degraded;
107
+ return { ok: ready, ready, mode: gateway.mode, uptimeSeconds: Math.floor((Date.now() - startedAt) / 1000), persistence };
108
+ }
73
109
  if (path === '/api/kill-switch' && method === 'GET') return gateway.killStatus?.() || {killed:false};
74
110
  if (path === '/api/kill-switch' && method === 'POST') { if (body.enabled === false) return gateway.unkill?.(); return gateway.kill?.(body.reason); }
75
111
  if (path === '/api/metrics') return gateway.telemetry?.snapshot?.() || { uptimeSeconds: Math.floor((Date.now() - startedAt) / 1000), counters: {}, latency: {} };
@@ -171,11 +207,18 @@ export function createControlPlane(options = {}) {
171
207
  if (url.pathname.startsWith('/api/')) {
172
208
  let body = {};
173
209
  if (req.method === 'POST') {
174
- let raw = '';
175
- let bodyBytes = 0;
176
210
  const maxBodySize = Number(options.maxBodySize || 1024 * 1024);
177
- for await (const chunk of req) { bodyBytes += chunk.length; if (bodyBytes > maxBodySize) { res.writeHead(413, {'content-type':'application/json'}); res.end(JSON.stringify({error:'Payload too large'})); return; } raw += chunk; }
178
- try { body = raw ? JSON.parse(raw) : {}; } catch { res.writeHead(400, {'content-type':'application/json'}); res.end(JSON.stringify({error:'Invalid JSON'})); return; }
211
+ try {
212
+ body = await readJsonBody(req, maxBodySize);
213
+ } catch (error) {
214
+ // 'connection: close' on top of fully draining the body (above) is
215
+ // belt-and-suspenders: it tells the client itself not to reuse this
216
+ // socket, so even a client we haven't fully drained yet won't have
217
+ // its next request misread on this connection.
218
+ res.writeHead(error.status || 400, { 'content-type': 'application/json', 'cache-control': 'no-store', 'connection': 'close' });
219
+ res.end(JSON.stringify({ error: error.message }));
220
+ return;
221
+ }
179
222
  }
180
223
  const limitKey = req.headers['x-agentgate-key'] || req.socket.remoteAddress || 'anonymous';
181
224
  const rate = limiter.check(String(limitKey));
@@ -204,7 +247,8 @@ export function createControlPlane(options = {}) {
204
247
  }
205
248
  const result = await api(url.pathname, req.method, body, Object.fromEntries(url.searchParams.entries()), authContext);
206
249
  if (result._html) { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' }); res.end(result.html); return; }
207
- res.writeHead(result.error ? 404 : 200, { 'content-type': 'application/json', 'cache-control': 'no-store' });
250
+ const status = result.error ? 404 : (url.pathname === '/api/ready' && result.ready === false ? 503 : 200);
251
+ res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' });
208
252
  res.end(JSON.stringify(result));
209
253
  return;
210
254
  }
package/src/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  export { evaluate, protect, DECISIONS } from './policy-engine.js';
2
2
  export { createMiddleware } from './middleware.js';
3
3
  export { createRuntime, RunStore } from './runtime.js';
4
- export { runAttackLab, runGatewayAttackLab, summarizeAttackResults, ATTACK_CASES } from './attack-lab.js';
4
+ export { runAttackLab, runGatewayAttackLab, runDeepAttackLab, summarizeAttackResults, ATTACK_CASES, DEEP_ATTACK_CASES } from './attack-lab.js';
5
5
 
6
6
  export { createMCPGateway, createMCPGatewayServer, MCP_PROTOCOL_VERSION } from './mcp-gateway.js';
7
7
 
@@ -14,6 +14,9 @@ export function validateAgentGateConfig(config = {}) {
14
14
  if (p.approvalAmount !== undefined && (!Number.isFinite(Number(p.approvalAmount)) || Number(p.approvalAmount) < 0)) errors.push('policies.approvalAmount must be a non-negative number');
15
15
  if (Number.isFinite(Number(p.autoApproveAmount)) && Number.isFinite(Number(p.approvalAmount)) && Number(p.autoApproveAmount) > Number(p.approvalAmount)) errors.push('autoApproveAmount cannot exceed approvalAmount');
16
16
  if (c.mode === 'observe') warnings.push('observe mode records decisions but does not enforce them');
17
+ if (!p.unknownActionPolicy || p.unknownActionPolicy === 'allow') {
18
+ warnings.push('unknownActionPolicy is "allow" (the default) — any action name AgentGate does not recognize (e.g. a typo, a new tool, or something like "grant_admin"/"drop_database") is ALLOWED, not blocked or asked. Set policies.unknownActionPolicy to "ask" or "block" before relying on this for production safety.');
19
+ }
17
20
  if (c.authRequired === false) warnings.push('authRequired=false is unsafe for non-local deployments');
18
21
  if (c.localDevSession === true && c.authRequired === false) warnings.push('localDevSession should not be combined with authRequired=false');
19
22
  return { valid: errors.length === 0, errors, warnings, checked: [...REQUIRED_POLICY_FIELDS] };
@@ -32,9 +32,11 @@ export function createMCPGateway(options = {}) {
32
32
  const killReason = { value: options.killReason || 'Emergency security lock' };
33
33
  const maxRuns = Number(options.maxRuns || 25000);
34
34
  let retentionWarned = false;
35
- const runStore = options.runStore || (options.persistence ? createPersistentRunStore({ filePath: options.runPersistence || `${options.persistence}/runs.json`, limit: maxRuns }) : null);
35
+ const recoverFromCorruption = Boolean(options.recoverFromCorruption);
36
+ const onPersistenceCorruption = options.onPersistenceCorruption;
37
+ const runStore = options.runStore || (options.persistence ? createPersistentRunStore({ filePath: options.runPersistence || `${options.persistence}/runs.json`, limit: maxRuns, recoverFromCorruption, onCorruption: onPersistenceCorruption }) : null);
36
38
  const runs = runStore ? null : [];
37
- const approvals = createApprovalStore({ store: options.approvalStore || (options.persistence ? createPersistentApprovalStore({ filePath: options.approvalPersistence || `${options.persistence}/approvals.json`, limit: options.maxApprovals || maxRuns }) : undefined), limit: options.maxApprovals || maxRuns });
39
+ const approvals = createApprovalStore({ store: options.approvalStore || (options.persistence ? createPersistentApprovalStore({ filePath: options.approvalPersistence || `${options.persistence}/approvals.json`, limit: options.maxApprovals || maxRuns, recoverFromCorruption, onCorruption: onPersistenceCorruption }) : undefined), limit: options.maxApprovals || maxRuns });
38
40
  const eventBus = options.eventBus || createEventBus();
39
41
  const telemetry = options.telemetry || createTelemetry();
40
42
  const egressGuard = options.egressGuard || (options.egress ? createEgressGuard(options.egress === true ? {} : options.egress) : null);
@@ -73,6 +75,15 @@ export function createMCPGateway(options = {}) {
73
75
  const count = runStore ? runStore.list().length : runs.length;
74
76
  const nearLimit = count >= Math.max(1, Math.ceil(maxRuns * 0.9));
75
77
  return { count, limit: maxRuns, nearLimit, persistent: Boolean(runStore), truncated: count >= maxRuns };
78
+ },
79
+ // Reports whether persistence had to recover from corruption at startup
80
+ // (only possible when recoverFromCorruption: true was passed — otherwise
81
+ // corruption makes createMCPGateway() throw instead of starting up in a
82
+ // degraded state). Control planes/readiness probes should surface this
83
+ // rather than reporting healthy while sitting on recovered/lost data.
84
+ persistenceHealth: () => {
85
+ const corruptions = [runStore?.corruption, approvals?.corruption].filter(Boolean);
86
+ return { persistent: Boolean(runStore), degraded: corruptions.length > 0, corruptions };
76
87
  }
77
88
  };
78
89
 
@@ -1,11 +1,29 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
 
4
+ // Thrown when a persisted collection file exists but cannot be trusted:
5
+ // invalid JSON, or valid JSON that isn't the array shape this store expects.
6
+ // This is distinct from "file does not exist yet" (ENOENT), which is the
7
+ // normal first-run case and is NOT an error.
8
+ export class PersistenceCorruptionError extends Error {
9
+ constructor(message, options) {
10
+ super(message, options);
11
+ this.name = 'PersistenceCorruptionError';
12
+ this.code = 'AGENTGATE_PERSISTENCE_CORRUPT';
13
+ }
14
+ }
15
+
4
16
  export class PersistentCollectionStore {
5
- constructor(filePath, { key = 'id', limit = 25000, seed = [] } = {}) {
17
+ constructor(filePath, { key = 'id', limit = 25000, seed = [], recoverFromCorruption = false, onCorruption } = {}) {
6
18
  this.filePath = path.resolve(filePath);
7
19
  this.key = key;
8
20
  this.limit = limit;
21
+ this.recoverFromCorruption = Boolean(recoverFromCorruption);
22
+ this.onCorruption = typeof onCorruption === 'function' ? onCorruption : null;
23
+ // Set only if a corruption event was handled (requires recoverFromCorruption:
24
+ // true). When this is non-null, the in-memory collection was reset and
25
+ // whatever was in the corrupt file was NOT recovered automatically.
26
+ this.corruption = null;
9
27
  this.items = this.#load(seed);
10
28
  }
11
29
 
@@ -35,22 +53,94 @@ export class PersistentCollectionStore {
35
53
  fs.writeFileSync(temp, JSON.stringify(this.items, null, 2), 'utf8');
36
54
  fs.renameSync(temp, this.filePath);
37
55
  }
56
+
38
57
  #load(seed) {
58
+ let text;
59
+ try {
60
+ text = fs.readFileSync(this.filePath, 'utf8');
61
+ } catch (err) {
62
+ // No file yet is the normal first-run case. Any other read failure
63
+ // (permission denied, I/O error, ...) is an operational failure, not
64
+ // "no data yet" — let it fail closed by propagating the error instead
65
+ // of silently returning an empty collection.
66
+ if (err.code === 'ENOENT') return Array.isArray(seed) ? seed.slice(0, this.limit) : [];
67
+ throw err;
68
+ }
69
+ let parsed;
39
70
  try {
40
- if (!fs.existsSync(this.filePath)) return Array.isArray(seed) ? seed.slice(0, this.limit) : [];
41
- const parsed = JSON.parse(fs.readFileSync(this.filePath, 'utf8'));
42
- return Array.isArray(parsed) ? parsed.slice(0, this.limit) : [];
43
- } catch { return Array.isArray(seed) ? seed.slice(0, this.limit) : []; }
71
+ parsed = JSON.parse(text);
72
+ } catch (err) {
73
+ return this.#handleCorruption(text, new PersistenceCorruptionError(
74
+ `Corrupt persistence file (invalid JSON): ${this.filePath}`,
75
+ { cause: err }
76
+ ), seed);
77
+ }
78
+ if (!Array.isArray(parsed)) {
79
+ return this.#handleCorruption(text, new PersistenceCorruptionError(
80
+ `Corrupt persistence file (expected an array, got ${parsed === null ? 'null' : typeof parsed}): ${this.filePath}`
81
+ ), seed);
82
+ }
83
+ return parsed.slice(0, this.limit);
44
84
  }
85
+
86
+ // Corruption means the file exists but its contents cannot be trusted —
87
+ // tampering, a crash mid-write on an older version, disk corruption, etc.
88
+ // The previous behavior here was to swallow the error and silently return
89
+ // an empty array, which quietly erases audit history and, worse, makes
90
+ // pending approvals vanish with no trace. We now fail closed by default:
91
+ // the store refuses to come up at all, so the operator finds out at
92
+ // startup instead of discovering a gap in the audit trail later.
93
+ //
94
+ // Recovery is opt-in only (recoverFromCorruption: true): the corrupt file
95
+ // is quarantined (renamed, never deleted) and the collection starts from
96
+ // `seed` (normally empty) — but this is explicitly NOT the same as
97
+ // recovering the lost data, and is logged loudly as such.
98
+ #handleCorruption(rawText, error, seed) {
99
+ if (!this.recoverFromCorruption) throw error;
100
+ const quarantinePath = `${this.filePath}.corrupt.${Date.now()}`;
101
+ try {
102
+ fs.renameSync(this.filePath, quarantinePath);
103
+ } catch {
104
+ try { fs.writeFileSync(quarantinePath, rawText ?? '', 'utf8'); } catch { /* best effort */ }
105
+ }
106
+ this.corruption = {
107
+ filePath: this.filePath,
108
+ quarantinePath,
109
+ message: error.message,
110
+ recoveredAt: new Date().toISOString(),
111
+ recoveredCount: Array.isArray(seed) ? seed.length : 0
112
+ };
113
+ console.error(
114
+ `\n🚨 AgentGate: persistence corruption recovered for ${this.filePath}\n` +
115
+ ` Corrupt file quarantined to: ${quarantinePath}\n` +
116
+ ` Started with ${this.corruption.recoveredCount} seed record(s) — the original contents were NOT recovered.\n` +
117
+ ` Investigate the quarantined file before trusting this collection again.\n`
118
+ );
119
+ this.onCorruption?.(this.corruption);
120
+ return Array.isArray(seed) ? seed.slice(0, this.limit) : [];
121
+ }
122
+
45
123
  #trim() { if (this.items.length > this.limit) this.items.splice(this.limit); }
46
124
  }
47
125
 
48
126
  export function createPersistentRunStore(options = {}) {
49
- return new PersistentCollectionStore(options.filePath || '.agentgate/runs.json', { limit: options.limit || 25000 });
127
+ return new PersistentCollectionStore(options.filePath || '.agentgate/runs.json', {
128
+ limit: options.limit || 25000,
129
+ recoverFromCorruption: options.recoverFromCorruption,
130
+ onCorruption: options.onCorruption
131
+ });
50
132
  }
51
133
  export function createPersistentApprovalStore(options = {}) {
52
- return new PersistentCollectionStore(options.filePath || '.agentgate/approvals.json', { limit: options.limit || 25000 });
134
+ return new PersistentCollectionStore(options.filePath || '.agentgate/approvals.json', {
135
+ limit: options.limit || 25000,
136
+ recoverFromCorruption: options.recoverFromCorruption,
137
+ onCorruption: options.onCorruption
138
+ });
53
139
  }
54
140
  export function createPersistentAgentStore(options = {}) {
55
- return new PersistentCollectionStore(options.filePath || '.agentgate/agents.json', { limit: options.limit || 1000 });
141
+ return new PersistentCollectionStore(options.filePath || '.agentgate/agents.json', {
142
+ limit: options.limit || 1000,
143
+ recoverFromCorruption: options.recoverFromCorruption,
144
+ onCorruption: options.onCorruption
145
+ });
56
146
  }
@@ -36,6 +36,26 @@ export function evaluate(input = {}, policies = {}) {
36
36
  if (destructive.has(action) && policies.requireApprovalForDestructive !== false) {
37
37
  return decision('ASK', 'Destructive action requires approval', 75, { ruleTrace: [...trace, { id: 'destructive-approval', matched: true, decision: 'ASK', reason: 'Destructive action requires approval' }], winningRule: 'destructive-approval' });
38
38
  }
39
+ // The action name didn't match anything above: it isn't in the small
40
+ // built-in destructive/read-only lists, and no explicit policy
41
+ // (blockActions/approvalActions/amount rule) named it. That does NOT mean
42
+ // it's safe — a tool or integration can use any action name it likes
43
+ // ('grant_admin', 'drop_database', 'transfer_money', ...). `unknownActionPolicy`
44
+ // controls what happens to it:
45
+ // - 'allow' (default, for backward compatibility): let it through, same
46
+ // as AgentGate has always done. `agentgate doctor` warns loudly when
47
+ // this is the effective setting so it's never a silent gap.
48
+ // - 'ask': require human approval for anything unrecognized.
49
+ // - 'block': refuse anything unrecognized outright — the strictest,
50
+ // deny-by-default option, recommended for production once every
51
+ // legitimate action name has been classified.
52
+ const unknownActionPolicy = policies.unknownActionPolicy || 'allow';
53
+ if (unknownActionPolicy === 'block') {
54
+ return decision('BLOCK', 'Unrecognized action blocked by unknownActionPolicy', 88, { ruleTrace: [...trace, { id: 'unknown-action-block', matched: true, decision: 'BLOCK', reason: 'Unrecognized action blocked by unknownActionPolicy' }], winningRule: 'unknown-action-block' });
55
+ }
56
+ if (unknownActionPolicy === 'ask') {
57
+ return decision('ASK', 'Unrecognized action requires approval by unknownActionPolicy', 68, { ruleTrace: [...trace, { id: 'unknown-action-ask', matched: true, decision: 'ASK', reason: 'Unrecognized action requires approval by unknownActionPolicy' }], winningRule: 'unknown-action-ask' });
58
+ }
39
59
  return decision('ALLOW', 'No blocking policy matched', 10, { ruleTrace: [...trace, { id: 'default-allow', matched: true, decision: 'ALLOW', reason: 'No blocking policy matched' }], winningRule: 'default-allow' });
40
60
  }
41
61