routeguard-cli 1.0.0 → 1.1.0

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
@@ -60,6 +60,35 @@ node bin/cli.js <path-to-express-app> --fail-on HIGH # exit 2 only on HIGH find
60
60
  Requires Node 20 or later. Works with JavaScript and TypeScript, `require` and `import`, monorepos and
61
61
  package.json `#imports`.
62
62
 
63
+ ### Confirm findings against a running app
64
+
65
+ Static analysis says where a check *looks* missing. `verify` proves it: it replays routes against a
66
+ running test instance as two real users and compares the answers.
67
+
68
+ ```bash
69
+ npx routeguard-cli verify ./my-api --base-url http://localhost:3000 --config verify.json
70
+ ```
71
+
72
+ ```json
73
+ {
74
+ "users": {
75
+ "owner": { "login": { "path": "/api/login", "body": { "email": "alice@test.local", "password": "${ALICE_PASSWORD}" }, "token": "token" } },
76
+ "other": { "headers": { "Authorization": "Bearer ${BOB_TOKEN}" } }
77
+ },
78
+ "params": { "id": "42" },
79
+ "routes": { "/api/cards/:id": { "id": "7" } }
80
+ }
81
+ ```
82
+
83
+ - `owner` owns the ids in `params`; `other` is a second ordinary user. `${NAME}` reads environment
84
+ variables, so passwords stay out of the file.
85
+ - Every route that takes an id, and every operator route a static finding flagged, is requested as the
86
+ owner, as the other user and with no credentials.
87
+ - Verdicts: **CONFIRMED** (someone got in who should not), **PUBLIC** (open to anyone and the code asks
88
+ for no login), **PROTECTED** (the other user was refused), **INCONCLUSIVE**, **SKIPPED** (no id given).
89
+ - Reads only by default. `--allow-writes` also replays PUT, PATCH, DELETE and POST: use a disposable
90
+ test environment.
91
+
63
92
  ### In GitHub Actions
64
93
 
65
94
  ```yaml
@@ -117,7 +146,7 @@ Leave out the rule name to silence every rule for that route.
117
146
 
118
147
  ## Limits
119
148
 
120
- - routeguard trusts what a check returns. If `canEdit()` itself has a logic bug, it won't see it.
149
+ - Static analysis trusts what a check returns. If `canEdit()` itself has a logic bug, only `verify` against a running app will show it.
121
150
  - Static analysis cannot know an id is unguessable. Capability links need a `routeguard-ignore` comment.
122
151
  - Express only for now.
123
152
 
package/bin/cli.js CHANGED
@@ -13,12 +13,19 @@ import { misconfig } from "../src/rules/misconfig.js"
13
13
  import { inventory } from "../src/rules/inventory.js"
14
14
  import { businessFlow } from "../src/rules/businessFlow.js"
15
15
  import { consumption } from "../src/rules/consumption.js"
16
+ import { verify } from "../src/verify.js"
16
17
 
17
18
  const RULES = [bola, bfla, massAssignment, dataExposure, ssrf, rateLimit, businessFlow]
18
19
 
19
20
  const SEVERITIES = ["LOW", "MEDIUM", "HIGH"]
20
21
 
21
- const args = process.argv.slice(2)
22
+ // process.exit() drops what is still buffered for a pipe, which cut large --json output short
23
+ const finish = code => process.stdout.write("", () => process.exit(code))
24
+
25
+ // routeguard verify <dir> --base-url … --config …: replay the routes against a running app
26
+ const verifying = process.argv[2] === "verify"
27
+ const args = process.argv.slice(verifying ? 3 : 2)
28
+ const VALUE_FLAGS = new Set(["--fail-on", "--base-url", "--config"])
22
29
  const option = name => {
23
30
  const i = args.indexOf(name)
24
31
  return i === -1 ? null : args[i + 1]
@@ -27,10 +34,11 @@ const json = args.includes("--json")
27
34
  const sarif = args.includes("--sarif")
28
35
  // --fail-on HIGH: exit 2 only for findings at or above that severity (default LOW: any finding)
29
36
  const failOn = (option("--fail-on") ?? "LOW").toUpperCase()
30
- const target = args.find((a, i) => !a.startsWith("--") && args[i - 1] !== "--fail-on")
37
+ const target = args.find((a, i) => !a.startsWith("--") && !VALUE_FLAGS.has(args[i - 1]))
31
38
 
32
- if (!target || !SEVERITIES.includes(failOn)) {
39
+ if (!target || !SEVERITIES.includes(failOn) || (verifying && (!option("--base-url") || !option("--config")))) {
33
40
  console.error("Usage: routeguard <express-project-dir> [--json | --sarif] [--fail-on LOW|MEDIUM|HIGH]")
41
+ console.error(" routeguard verify <express-project-dir> --base-url <url> --config <file.json> [--allow-writes] [--json]")
34
42
  process.exit(1)
35
43
  }
36
44
 
@@ -47,44 +55,62 @@ const findings = [
47
55
  ...consumption(root)
48
56
  ].filter(f => !seen.has(`${f.rule} ${f.route} ${f.where}`) && seen.add(`${f.rule} ${f.route} ${f.where}`))
49
57
 
50
- const exitCode = findings.some(f => SEVERITIES.indexOf(f.severity) >= SEVERITIES.indexOf(failOn)) ? 2 : 0
58
+ function printReport() {
59
+ const mark = ok => (ok ? "✅" : "❌")
60
+ const rows = routes.map(r => [r.method, r.path, r.middleware.join(", ") || "-", mark(r.auth), mark(r.role), `${r.file}:${r.line}`])
61
+ const header = ["METHOD", "PATH", "MIDDLEWARE", "AUTH", "ROLE", "WHERE"]
62
+ const widths = header.map((h, i) => Math.max(h.length, ...rows.map(r => r[i].length)))
63
+ const line = cells => cells.map((c, i) => c.padEnd(widths[i])).join(" ")
51
64
 
52
- if (json) {
53
- console.log(JSON.stringify({ routes, findings }, null, 2))
54
- process.exit(exitCode)
55
- }
65
+ console.log(line(header))
66
+ console.log(widths.map(w => "-".repeat(w)).join(" "))
67
+ rows.forEach(r => console.log(line(r)))
56
68
 
57
- if (sarif) {
58
- const { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"))
59
- console.log(JSON.stringify(toSarif(findings, version), null, 2))
60
- process.exit(exitCode)
61
- }
69
+ const noAuth = routes.filter(r => !r.auth).length
70
+ console.log(`\n${routes.length} routes · ${noAuth} without an auth check · ${routes.filter(r => !r.role).length} without a role check`)
62
71
 
63
- const mark = ok => (ok ? "✅" : "❌")
64
- const rows = routes.map(r => [
65
- r.method,
66
- r.path,
67
- r.middleware.join(", ") || "-",
68
- mark(r.auth),
69
- mark(r.role),
70
- `${r.file}:${r.line}`
71
- ])
72
- const header = ["METHOD", "PATH", "MIDDLEWARE", "AUTH", "ROLE", "WHERE"]
73
- const widths = header.map((h, i) => Math.max(h.length, ...rows.map(r => r[i].length)))
74
- const line = cells => cells.map((c, i) => c.padEnd(widths[i])).join(" ")
72
+ console.log(`\nFINDINGS (${findings.length})\n`)
73
+ for (const f of findings) {
74
+ console.log(`[${f.severity}] ${f.rule} ${f.route} (${f.where})`)
75
+ console.log(` ${f.owasp}`)
76
+ console.log(` ${f.message}`)
77
+ console.log(` Fix: ${f.fix}\n`)
78
+ }
79
+ }
75
80
 
76
- console.log(line(header))
77
- console.log(widths.map(w => "-".repeat(w)).join(" "))
78
- rows.forEach(r => console.log(line(r)))
81
+ function printVerification(results) {
82
+ const order = { CONFIRMED: 0, INCONCLUSIVE: 1, PUBLIC: 2, PROTECTED: 3, SKIPPED: 4 }
83
+ const sorted = [...results].sort((a, b) => order[a.verdict] - order[b.verdict])
84
+ for (const r of sorted) {
85
+ const codes = r.status ? `owner ${r.status.owner ?? "-"} · other ${r.status.other} · anonymous ${r.status.anonymous}` : ""
86
+ const agreement =
87
+ r.verdict === "CONFIRMED" && r.staticRule ? "static finding confirmed"
88
+ : r.verdict === "CONFIRMED" ? "missed by static analysis"
89
+ : r.verdict === "PROTECTED" && r.staticRule ? `static ${r.staticRule} not reproduced`
90
+ : ""
91
+ console.log(`[${r.verdict}] ${r.route}${codes ? ` (${codes})` : ""}`)
92
+ console.log(` ${r.reason}${agreement ? ` · ${agreement}` : ""}`)
93
+ }
94
+ const count = verdict => results.filter(r => r.verdict === verdict).length
95
+ console.log(`\n${results.length} routes replayed · ${count("CONFIRMED")} confirmed · ${count("PUBLIC")} public · ${count("PROTECTED")} protected · ${count("INCONCLUSIVE")} inconclusive · ${count("SKIPPED")} skipped`)
96
+ }
79
97
 
80
- const noAuth = routes.filter(r => !r.auth).length
81
- console.log(`\n${routes.length} routes · ${noAuth} without an auth check · ${routes.filter(r => !r.role).length} without a role check`)
98
+ const exitCode = findings.some(f => SEVERITIES.indexOf(f.severity) >= SEVERITIES.indexOf(failOn)) ? 2 : 0
82
99
 
83
- console.log(`\nFINDINGS (${findings.length})\n`)
84
- for (const f of findings) {
85
- console.log(`[${f.severity}] ${f.rule} ${f.route} (${f.where})`)
86
- console.log(` ${f.owasp}`)
87
- console.log(` ${f.message}`)
88
- console.log(` Fix: ${f.fix}\n`)
100
+ if (verifying) {
101
+ const config = JSON.parse(readFileSync(path.resolve(option("--config")), "utf8"))
102
+ const results = await verify({ routes, findings, baseUrl: option("--base-url"), config, allowWrites: args.includes("--allow-writes") })
103
+ if (json) console.log(JSON.stringify(results, null, 2))
104
+ else printVerification(results)
105
+ finish(results.some(r => r.verdict === "CONFIRMED") ? 2 : 0)
106
+ } else if (json) {
107
+ console.log(JSON.stringify({ routes, findings }, null, 2))
108
+ finish(exitCode)
109
+ } else if (sarif) {
110
+ const { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"))
111
+ console.log(JSON.stringify(toSarif(findings, version), null, 2))
112
+ finish(exitCode)
113
+ } else {
114
+ printReport()
115
+ finish(exitCode)
89
116
  }
90
- process.exit(exitCode)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "routeguard-cli",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Find broken authorisation in Express APIs: maps routes to their checks and flags the OWASP API Security Top 10",
5
5
  "type": "module",
6
6
  "bin": {
package/src/verify.js ADDED
@@ -0,0 +1,142 @@
1
+ // Runtime check: replay routes against a running app as two real users and compare the answers.
2
+ // Static analysis says where a check looks missing; this says whether another user really gets in.
3
+
4
+ const WRITE = new Set(["PUT", "PATCH", "DELETE", "POST"])
5
+ const OK = status => status >= 200 && status < 300
6
+ const DENIED = status => [401, 403, 404].includes(status)
7
+
8
+ // "${JUICE_PASSWORD}" in the config reads the environment, so passwords stay out of the file
9
+ function expand(value) {
10
+ if (typeof value === "string") return value.replace(/\$\{(\w+)\}/g, (_, name) => process.env[name] ?? "")
11
+ if (Array.isArray(value)) return value.map(expand)
12
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, expand(v)]))
13
+ return value
14
+ }
15
+
16
+ const pick = (object, dotted) => dotted.split(".").reduce((o, k) => o?.[k], object)
17
+
18
+ async function call(baseUrl, method, path, headers = {}, body, timeoutMs) {
19
+ const controller = new AbortController()
20
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
21
+ try {
22
+ const res = await fetch(new URL(path, baseUrl), {
23
+ method,
24
+ headers: { accept: "application/json", ...(body ? { "content-type": "application/json" } : {}), ...headers },
25
+ body: body ? JSON.stringify(body) : undefined,
26
+ redirect: "manual",
27
+ signal: controller.signal
28
+ })
29
+ return { status: res.status, text: await res.text() }
30
+ } catch (error) {
31
+ return { status: 0, text: "", error: error.name === "AbortError" ? "timeout" : error.message }
32
+ } finally {
33
+ clearTimeout(timer)
34
+ }
35
+ }
36
+
37
+ // a user is fixed headers, or a login call whose answer holds the token
38
+ async function signIn(baseUrl, user, timeoutMs) {
39
+ if (!user) return null
40
+ if (user.headers) return user.headers
41
+ const { login } = user
42
+ const res = await call(baseUrl, login.method ?? "POST", login.path, {}, login.body, timeoutMs)
43
+ if (!OK(res.status)) throw new Error(`login ${login.path} answered ${res.status}`)
44
+ const token = pick(JSON.parse(res.text), login.token)
45
+ if (!token) throw new Error(`login ${login.path}: no value at "${login.token}"`)
46
+ return { [login.header ?? "Authorization"]: `${login.prefix ?? "Bearer "}${token}` }
47
+ }
48
+
49
+ // the same object, by content: ignore key order and timestamps that change between calls
50
+ function sameObject(a, b) {
51
+ if (a.text === b.text) return true
52
+ try {
53
+ const strip = value =>
54
+ JSON.stringify(value, (key, v) => (/^(updatedAt|createdAt|timestamp|time|date|requestId|csrf\w*)$/i.test(key) ? undefined : v))
55
+ return strip(JSON.parse(a.text)) === strip(JSON.parse(b.text))
56
+ } catch {
57
+ return false
58
+ }
59
+ }
60
+
61
+ function fillPath(route, params, overrides) {
62
+ const own = overrides[`${route.method} ${route.path}`] ?? overrides[route.path] ?? {}
63
+ const missing = []
64
+ const path = route.path.replace(/[:{](\w+)\}?(\([^)]*\))?/g, (_, name) => {
65
+ const value = own[name] ?? params[name]
66
+ if (value === undefined) missing.push(name)
67
+ return encodeURIComponent(value ?? "")
68
+ })
69
+ return { path, missing }
70
+ }
71
+
72
+ // which routes to replay: every route that takes an id (BOLA) and every route a static finding
73
+ // called operator-only (BFLA), reads always, writes only when asked
74
+ function candidates(routes, findings, allowWrites) {
75
+ const flagged = new Map(findings.map(f => [f.route, f.rule]))
76
+ const seen = new Set()
77
+ return routes.filter(r => {
78
+ const key = `${r.method} ${r.path}`
79
+ if (seen.has(key) || /[*<]/.test(r.path) || r.method === "ALL" || r.method === "OPTIONS" || r.method === "HEAD") return false
80
+ if (WRITE.has(r.method) && !allowWrites) return false
81
+ const takesId = /[:{]/.test(r.path)
82
+ const operator = ["BFLA"].includes(flagged.get(key))
83
+ if (!takesId && !operator) return false
84
+ seen.add(key)
85
+ return true
86
+ }).map(r => ({ route: r, staticRule: flagged.get(`${r.method} ${r.path}`) ?? null }))
87
+ }
88
+
89
+ // owner: the user who owns the ids in the config · other: a second ordinary user · anonymous: no credentials
90
+ export async function verify({ routes, findings, baseUrl, config, allowWrites = false, timeoutMs = 10000 }) {
91
+ const settings = expand(config)
92
+ const prefix = settings.pathPrefix ?? ""
93
+ const headers = {
94
+ owner: await signIn(baseUrl, settings.users?.owner, timeoutMs),
95
+ other: await signIn(baseUrl, settings.users?.other, timeoutMs)
96
+ }
97
+ if (!headers.owner || !headers.other) throw new Error("the config needs users.owner and users.other")
98
+
99
+ const results = []
100
+ for (const { route, staticRule } of candidates(routes, findings, allowWrites)) {
101
+ const { path, missing } = fillPath(route, settings.params ?? {}, settings.routes ?? {})
102
+ const key = `${route.method} ${route.path}`
103
+ if (missing.length) {
104
+ results.push({ route: key, staticRule, verdict: "SKIPPED", reason: `no value for :${missing.join(", :")}` })
105
+ continue
106
+ }
107
+ const body = settings.bodies?.[key]
108
+ const url = prefix + path
109
+ // the owner goes last for writes, so a delete by the other user is not hidden by the owner's own
110
+ const owner = WRITE.has(route.method) ? null : await call(baseUrl, route.method, url, headers.owner, body, timeoutMs)
111
+ const other = await call(baseUrl, route.method, url, headers.other, body, timeoutMs)
112
+ const anonymous = await call(baseUrl, route.method, url, {}, body, timeoutMs)
113
+ results.push({ route: key, path: url, staticRule, ...judge(route, staticRule, owner, other, anonymous), status: { owner: owner?.status, other: other.status, anonymous: anonymous.status } })
114
+ }
115
+ return results
116
+ }
117
+
118
+ // CONFIRMED: someone got in who should not · PUBLIC: open to anyone, and the code never asks for a login,
119
+ // so it is probably meant to be public · PROTECTED: the second user was refused or got their own data
120
+ function judge(route, staticRule, owner, other, anonymous) {
121
+ if (other.error) return { verdict: "INCONCLUSIVE", reason: `request failed: ${other.error}` }
122
+ const takesId = /[:{]/.test(route.path)
123
+
124
+ if (OK(anonymous.status) && (!takesId || (owner && OK(owner.status) && sameObject(owner, anonymous)))) {
125
+ if (route.auth) return { verdict: "CONFIRMED", reason: "the code expects a login, but it answers without any credentials" }
126
+ if (staticRule) return { verdict: "CONFIRMED", reason: "anyone can reach it, with no credentials" }
127
+ return { verdict: "PUBLIC", reason: "open to anyone and the code asks for no login; confirm it is meant to be public" }
128
+ }
129
+ if (owner && !OK(owner.status)) return { verdict: "INCONCLUSIVE", reason: `the owner got ${owner.status}: check the ids and paths in the config` }
130
+ // readable with no credentials and the code asks for none, even if the answer varies per viewer
131
+ if (OK(anonymous.status) && !route.auth && !staticRule)
132
+ return { verdict: "PUBLIC", reason: "open to anyone and the code asks for no login; confirm it is meant to be public" }
133
+ if (owner && OK(other.status) && takesId && sameObject(owner, other))
134
+ return { verdict: "CONFIRMED", reason: "another user got the owner's data" }
135
+ if (!owner && OK(other.status)) return { verdict: "CONFIRMED", reason: "another user's write was accepted" }
136
+ if (!takesId && OK(other.status) && staticRule) return { verdict: "CONFIRMED", reason: "an ordinary user reaches this operator route" }
137
+ if (owner && OK(other.status)) return { verdict: "PROTECTED", reason: "another user got different data (likely their own)" }
138
+ // the owner got in and the other user got any 4xx: some apps refuse with 400 rather than 403
139
+ if (DENIED(other.status) || (owner && OK(owner.status) && other.status >= 400 && other.status < 500))
140
+ return { verdict: "PROTECTED", reason: `another user was refused (${other.status})` }
141
+ return { verdict: "INCONCLUSIVE", reason: `another user got ${other.status}` }
142
+ }