-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapigate.js
More file actions
executable file
·476 lines (427 loc) · 17.2 KB
/
Copy pathapigate.js
File metadata and controls
executable file
·476 lines (427 loc) · 17.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
#!/usr/bin/env node
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { loadConfig } from "./lib/config.mjs";
import { buildInventory } from "./lib/inventory.mjs";
import { classifyAll } from "./lib/auth.mjs";
import { diff as specDiff } from "./lib/drift.mjs";
import { computeScore, SCORE_VERSION, bandFromScore } from "./lib/score.mjs";
import { renderHtml, LIMITATIONS } from "./lib/report.mjs";
import { annotateIntentionalPublic, DEFAULT_PUBLIC_AUTH_PATTERNS } from "./lib/heuristics.mjs";
import { resolveGate, parseFailOnFlag } from "./lib/gate.mjs";
import { PARSER_CAPABILITIES, KNOWN_UNRESOLVED_REASONS, RISK_TIER_INFO } from "./lib/capabilities.mjs";
import { annotateRisk } from "./lib/risk.mjs";
import { buildRefDiff } from "./lib/diff.mjs";
import { parseFilter, applyFilter, describeFilter } from "./lib/filter.mjs";
import { explain } from "./lib/explain.mjs";
import { DEFAULT_EXCLUDE_DIRS, DEFAULT_SCAN_OPTIONS, ScanLimitError } from "./lib/utils.mjs";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, "package.json"), "utf-8"));
const argv = process.argv.slice(2);
if (argv.includes("--version") || argv.includes("-v")) {
console.log(pkg.version);
process.exit(0);
}
if (argv.includes("--help") || argv.includes("-h")) {
console.log(`
░▒▓█ APIGATE █▓▒░ v${pkg.version}
Static API surface audit — Express · Fastify · NestJS · OpenAPI 2/3
Usage:
apigate [target] [options]
Output:
--output-dir <dir> Directory to write report files (default: target)
--format <fmt> Output formats: 'json,html' (default), 'json', 'html'
--max-files <n> Stop scan after n visited files (default: ${DEFAULT_SCAN_OPTIONS.maxFiles})
--max-depth <n> Stop descending after n directory levels (default: ${DEFAULT_SCAN_OPTIONS.maxDepth})
--max-file-bytes <n> Skip parsing matching files larger than n bytes
(default: ${DEFAULT_SCAN_OPTIONS.maxFileBytes})
--scan-timeout-ms <n> Stop scan after n milliseconds (default: ${DEFAULT_SCAN_OPTIONS.timeoutMs})
--allow-workspace Scan even when target looks like a multi-project
workspace. Prefer targeting a single project.
Investigation:
--diff <ref> Compare current scan to git <ref>. Emits refDiff
(added/removed/changedPosture/changedRisk) and
enables the new-open-write gate.
--filter <expr> Narrow the visible endpoint table (view-only —
summary + gate are always derived from the full
scan). Tokens:
risk=HIGH|MED|LOW
posture=GUARDED|OPEN|UNKNOWN
framework=express|fastify|nest|openapi
method=GET|POST|...
changed=added|removed|changedPosture|changedRisk
Example: --filter risk=HIGH,posture=OPEN
--explain <m> <path> Print one endpoint's evidence chain to stdout
(file, posture, marker, risk, refDiff). No files
written. Exit 0 always.
Policy:
--fail-on <list> Comma list, tightens exit-1 policy on top of config.
Tokens: open-write, open-read, unknown, drift,
intentional-public, new-open-write, missing-spec
Debug:
--strip-paths Relativize target to repo basename (auto-on if CI=true)
--debug Print parser warnings to stderr
--version, -v Print version and exit
--help, -h Show this help
Environment:
APIGATE_TIMESTAMP=<iso> Override the timestamp in the report. Set this
in CI for byte-stable output across runs.
Config file (.apigate.config.json in target):
frameworks Toggle parsers: { express, fastify, nest, openapi }
auth Per-framework auth identifier names
failOn Exit-code policy: { openWriteMethods, openReadMethods,
unknown, drift, intentionalPublic,
newOpenWrite }
requireSpec Exit 1 when no OpenAPI spec is found
strictPublic Disable built-in public-auth patterns unless explicitly
configured
severityOverrides Pin specific (method, path) to a risk tier:
[{ "method": "POST", "path": "/admin/wipe",
"risk": "LOW", "reason": "scheduled only" }]
excludePaths Glob list of files to skip
See .apigate.config.example.json for a fully-commented template.
Exit codes:
0 PASS — gate.reasons is empty
1 FAIL — gate.reasons[] lists the exact gate(s) that fired
2 Invalid target or CLI error
Output files:
apigate-report.json Machine-readable JSON report (gate, refDiff,
parserCapabilities, riskTier, ...)
<repo-name>.html Self-contained HTML report (via @stelnyx/report-theme)
ApiGate makes zero network calls. No code or telemetry leaves the machine.
`);
process.exit(0);
}
function argValue(flag) {
const i = argv.indexOf(flag);
if (i === -1) return null;
const v = argv[i + 1];
if (!v || v.startsWith("--")) return null;
return v;
}
function explainArgs() {
const i = argv.indexOf("--explain");
if (i === -1) return null;
const method = argv[i + 1];
const epath = argv[i + 2];
if (!method || method.startsWith("--") || !epath || epath.startsWith("--")) {
console.error('--explain requires <method> <path>, e.g. --explain GET /users/:id');
process.exit(2);
}
return { method, path: epath };
}
const rawTarget = argv[0] && !argv[0].startsWith("--") ? argv[0] : ".";
const DEBUG = argv.includes("--debug");
const STRIP_PATHS = argv.includes("--strip-paths") || process.env.CI === "true";
const OUTPUT_DIR_FLAG = argValue("--output-dir");
const FORMAT_RAW = argValue("--format");
const FORMAT_SET = new Set((FORMAT_RAW || "json,html").split(",").map(s => s.trim().toLowerCase()));
const FAIL_ON_FLAG = argValue("--fail-on");
const DIFF_REF = argValue("--diff");
const FILTER_RAW = argValue("--filter");
const EXPLAIN = explainArgs();
const ALLOW_WORKSPACE = argv.includes("--allow-workspace");
const target = path.resolve(rawTarget);
if (!fs.existsSync(target)) {
console.error(`Target not found: ${rawTarget}`);
process.exit(2);
}
if (!fs.statSync(target).isDirectory()) {
console.error(`Target is not a directory: ${rawTarget}`);
process.exit(2);
}
const outputDir = OUTPUT_DIR_FLAG ? path.resolve(OUTPUT_DIR_FLAG) : target;
if (OUTPUT_DIR_FLAG && !fs.existsSync(outputDir)) {
try { fs.mkdirSync(outputDir, { recursive: true }); }
catch (e) {
console.error(`Cannot create --output-dir ${outputDir}: ${e.message}`);
process.exit(2);
}
}
const repoName = path.basename(path.resolve(target));
const reportTarget = STRIP_PATHS ? repoName : target;
const config = loadConfig(target);
for (const [flag, key] of [
["--max-files", "maxFiles"],
["--max-depth", "maxDepth"],
["--max-file-bytes", "maxFileBytes"],
["--scan-timeout-ms", "timeoutMs"]
]) {
const parsed = parsePositiveIntFlag(flag);
if (parsed !== null) config.scan[key] = parsed;
}
config.scan.onProgress = EXPLAIN ? null : (stats) => {
console.error(`[apigate] scanning... ${stats.visitedFiles} files visited, ${stats.matchedFiles} candidate files`);
};
for (const fmt of FORMAT_SET) {
if (fmt !== "json" && fmt !== "html") {
console.error(`[apigate] Invalid --format value: ${fmt}`);
process.exit(2);
}
}
if (FAIL_ON_FLAG !== null) {
try {
const { failOn: overrides, requireSpec } = parseFailOnFlag(FAIL_ON_FLAG);
config.failOn = { ...config.failOn, ...overrides };
if (requireSpec) config.requireSpec = true;
} catch (e) {
console.error(`[apigate] ${e.message}`);
process.exit(2);
}
}
let filter = null;
if (FILTER_RAW !== null) {
try { filter = parseFilter(FILTER_RAW); }
catch (e) {
console.error(`[apigate] ${e.message}`);
process.exit(2);
}
}
if (!ALLOW_WORKSPACE) {
const workspace = detectWorkspace(target);
if (workspace.isWorkspace) {
console.error(`[apigate] This looks like a workspace with ${workspace.projects.length} sub-projects — point ApiGate at a single project, or pass --allow-workspace with scan bounds.`);
for (const p of workspace.projects.slice(0, 8)) console.error(` - ${p}`);
if (workspace.projects.length > 8) console.error(` ... ${workspace.projects.length - 8} more`);
process.exit(2);
}
}
// EXPLAIN mode silences the banner so stdout is a clean evidence chain
// when piped to a tool.
if (!EXPLAIN) {
console.log(`
░▒▓█ APIGATE v${pkg.version} █▓▒░`);
console.log("Target:", reportTarget);
console.log("Mode: STATIC");
console.log("────────────────────────────────");
}
let inventory;
try {
inventory = buildInventory(target, config);
} catch (e) {
if (e instanceof ScanLimitError) {
console.error(`[apigate] ${e.message}`);
if (e.stats) {
console.error(`[apigate] visited ${e.stats.visitedFiles} files / ${e.stats.visitedDirs} dirs; matched ${e.stats.matchedFiles} candidate files; skipped ${e.stats.skippedSymlinks} symlinks`);
}
process.exit(2);
}
console.error(`[apigate] scan failed: ${e.message}`);
process.exit(2);
}
const patterns = config.publicAuthPatterns ?? (config.strictPublic ? [] : DEFAULT_PUBLIC_AUTH_PATTERNS);
const codeClassified = annotateIntentionalPublic(classifyAll(inventory.code, config), patterns);
const specClassified = annotateIntentionalPublic(classifyAll(inventory.spec, config), patterns);
const codeWithRisk = annotateRisk(codeClassified, config.severityOverrides);
const driftResult = inventory.spec.length > 0
? specDiff(codeWithRisk, specClassified)
: { shadow: [], stale: [], authDrift: [] };
let refDiff = null;
if (DIFF_REF) {
try {
refDiff = buildRefDiff({
ref: DIFF_REF,
repoRoot: target,
currentEndpoints: codeWithRisk,
config
});
} catch (e) {
console.error(`[apigate] --diff ${DIFF_REF}: ${e.message}`);
process.exit(2);
}
}
const allEndpoints = [...codeWithRisk, ...specClassified];
const summary = summarize(codeWithRisk, specClassified, driftResult);
const { headline, rubrics } = computeScore({
endpoints: codeWithRisk,
drift: driftResult,
specPresent: inventory.spec.length > 0
});
const gate = resolveGate({
code: codeWithRisk,
drift: driftResult,
config,
specPresent: inventory.spec.length > 0,
refDiff
});
const status = gate.status;
const timestamp = process.env.APIGATE_TIMESTAMP
? process.env.APIGATE_TIMESTAMP
: new Date().toISOString();
const report = {
version: pkg.version,
rubricVersion: SCORE_VERSION,
riskVersion: RISK_TIER_INFO.version,
timestamp,
target: reportTarget,
mode: "static",
status,
gate,
headlineScore: headline,
rubrics,
summary,
endpoints: allEndpoints.map(stripInternal),
drift: driftResult,
...(refDiff ? { refDiff } : {}),
frameworksDetected: inventory.frameworksDetected,
specsDetected: inventory.specsDetected,
parserCapabilities: PARSER_CAPABILITIES,
riskTier: RISK_TIER_INFO,
...(filter ? { filter: describeFilter(filter) } : {}),
warnings: inventory.warnings,
limitations: [...LIMITATIONS]
};
// EXPLAIN short-circuits: print one endpoint to stdout, no files, exit 0.
if (EXPLAIN) {
process.stdout.write(explain(report, EXPLAIN.method, EXPLAIN.path));
process.exit(0);
}
const visibleEndpoints = filter
? applyFilter(report.endpoints, filter, { refDiff })
: report.endpoints;
const renderedReport = { ...report, _visibleEndpoints: visibleEndpoints };
const jsonFile = path.join(outputDir, "apigate-report.json");
const htmlFile = path.join(outputDir, `${repoName}.html`);
if (FORMAT_SET.has("json")) {
try {
fs.writeFileSync(jsonFile, JSON.stringify(report, null, 2) + "\n");
} catch (e) {
console.error(`[apigate] Cannot write JSON report to ${jsonFile}: ${e.message}`);
process.exit(2);
}
}
if (FORMAT_SET.has("html")) {
try {
fs.writeFileSync(htmlFile, renderHtml(renderedReport, repoName));
} catch (e) {
console.error(`[apigate] Cannot write HTML report to ${htmlFile}: ${e.message}`);
process.exit(2);
}
}
const bar = (() => {
const filled = Math.round(headline / 5);
return "█".repeat(filled) + "░".repeat(20 - filled);
})();
console.log(`Headline: ${headline} / 100 ${bar} ${bandFromScore(headline)} rubric ${SCORE_VERSION}`);
console.log("");
for (const [key, val] of Object.entries(rubrics)) {
const label = ({
inventoryResolved: "Inventory",
authCoverage: "Auth Coverage",
openEndpointRisk: "Open Risk",
specDrift: "Spec Drift",
determinism: "Determinism"
})[key] || key;
const v = val === null ? " n/a" : String(val).padStart(5);
const sub = val === null ? " " : "█".repeat(Math.round(val / 5)).padEnd(20, "░");
console.log(` ${label.padEnd(14)} ${v} / 100 ${sub}`);
}
console.log("────────────────────────────────");
console.log("STATUS: ", status);
if (gate.reasons.length) {
console.log("REASONS: ", gate.reasons.join(", "));
}
console.log("ENDPOINTS: ", summary.endpoints, ` (${summary.guarded} guarded, ${summary.open} open, ${summary.unknown} unknown, ${summary.intentionalPublic} intentional-public)`);
if (summary.endpoints === 0 && summary.specEndpoints === 0) {
console.log("NOTICE: ", "No API routes or OpenAPI specs were detected in this target.");
}
console.log("RISK: ", `${summary.risk.HIGH} high · ${summary.risk.MED} med · ${summary.risk.LOW} low`);
if (inventory.spec.length > 0) {
console.log("DRIFT: ", `${driftResult.shadow.length} shadow, ${driftResult.stale.length} stale, ${driftResult.authDrift.length} auth-drift`);
}
if (refDiff) {
console.log("DIFF vs", refDiff.baseRef, `(${refDiff.baseSha.slice(0, 8)}):`, `${refDiff.added.length} added, ${refDiff.removed.length} removed, ${refDiff.changedPosture.length} posture-changed, ${refDiff.changedRisk.length} risk-changed`);
}
if (filter) {
console.log("FILTER: ", describeFilter(filter), `(${visibleEndpoints.length}/${report.endpoints.length} visible)`);
}
console.log("");
if (DEBUG && inventory.warnings.length) {
console.error("Parser warnings:");
for (const w of inventory.warnings) console.error(` ${w.file}: ${w.reason}`);
}
if (FORMAT_SET.has("json")) console.log("JSON report:", jsonFile);
if (FORMAT_SET.has("html")) console.log("HTML report:", htmlFile);
console.log("");
console.log("Note: static analysis cannot verify runtime authorization (BOLA / object-level access).");
console.log(" See the 'Limitations' section of the report.");
process.exit(status === "PASS" ? 0 : 1);
function summarize(code, spec, drift) {
const counts = {
endpoints: code.length,
resolved: 0,
unresolved: 0,
guarded: 0,
open: 0,
unknown: 0,
intentionalPublic: 0,
risk: { HIGH: 0, MED: 0, LOW: 0 },
specEndpoints: spec.length,
shadow: drift.shadow?.length || 0,
stale: drift.stale?.length || 0,
authDrift: drift.authDrift?.length || 0,
unknownReasons: {}
};
const reasonCounts = {};
for (const reason of KNOWN_UNRESOLVED_REASONS) reasonCounts[reason] = 0;
for (const e of code) {
if (e.resolved === false) {
counts.unresolved++;
const reason = e.unresolvedReason || "unspecified";
reasonCounts[reason] = (reasonCounts[reason] || 0) + 1;
} else {
counts.resolved++;
}
if (e.intentionalPublic) counts.intentionalPublic++;
if (e.posture === "GUARDED") counts.guarded++;
else if (e.posture === "OPEN") counts.open++;
else counts.unknown++;
if (e.risk === "HIGH" || e.risk === "MED" || e.risk === "LOW") counts.risk[e.risk]++;
}
for (const key of Object.keys(reasonCounts).sort()) {
if (reasonCounts[key] > 0) counts.unknownReasons[key] = reasonCounts[key];
}
return counts;
}
function stripInternal(e) {
const out = { ...e };
delete out.declaredPosture;
return out;
}
function parsePositiveIntFlag(flag) {
const raw = argValue(flag);
if (raw === null) return null;
if (!/^[1-9]\d*$/.test(raw)) {
console.error(`[apigate] ${flag} requires a positive integer`);
process.exit(2);
}
return Number(raw);
}
function detectWorkspace(root) {
const projects = [];
const queue = [{ dir: root, depth: 0 }];
while (queue.length) {
const { dir, depth } = queue.shift();
let entries;
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
continue;
}
const hasPkg = depth > 0 && entries.some(e => e.isFile() && e.name === "package.json");
const hasNestedState = entries.some(e => e.isDirectory() && (e.name === "node_modules" || e.name === ".git"));
if (hasPkg && hasNestedState) {
projects.push(path.relative(root, dir).split(path.sep).join("/"));
continue;
}
if (depth >= 2) continue;
for (const ent of entries) {
if (!ent.isDirectory() || ent.isSymbolicLink()) continue;
if (DEFAULT_EXCLUDE_DIRS.includes(ent.name)) continue;
queue.push({ dir: path.join(dir, ent.name), depth: depth + 1 });
}
}
projects.sort();
return { isWorkspace: projects.length >= 3, projects };
}