routeguard-cli 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +164 -2
- package/bin/cli.js +116 -0
- package/package.json +45 -4
- package/src/flow.js +217 -0
- package/src/mapper.js +714 -0
- package/src/rules/bfla.js +51 -0
- package/src/rules/bola.js +69 -0
- package/src/rules/businessFlow.js +50 -0
- package/src/rules/consumption.js +164 -0
- package/src/rules/dataExposure.js +107 -0
- package/src/rules/handler.js +159 -0
- package/src/rules/inventory.js +84 -0
- package/src/rules/massAssignment.js +99 -0
- package/src/rules/misconfig.js +205 -0
- package/src/rules/rateLimit.js +53 -0
- package/src/rules/ssrf.js +57 -0
- package/src/sarif.js +45 -0
- package/src/spec.js +43 -0
- package/src/verify.js +142 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Keerti Deshpande
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,165 @@
|
|
|
1
|
-
#
|
|
1
|
+
# routeguard
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Find broken authorisation in Express APIs before attackers do.**
|
|
4
|
+
|
|
5
|
+
routeguard reads your Express code without running it. It maps every route to the checks that protect
|
|
6
|
+
it, then flags the [OWASP API Security Top 10](https://owasp.org/API-Security/editions/2023/en/0x11-t10/)
|
|
7
|
+
risks that general code scanners miss. The biggest of these is one user reaching another user's data.
|
|
8
|
+
|
|
9
|
+
```
|
|
10
|
+
$ routeguard ./my-api
|
|
11
|
+
|
|
12
|
+
METHOD PATH MIDDLEWARE AUTH ROLE WHERE
|
|
13
|
+
GET /api/orders/:id auth ✅ ❌ routes/orders.js:12
|
|
14
|
+
DELETE /api/users/:id auth, admin ✅ ✅ routes/users.js:40
|
|
15
|
+
...
|
|
16
|
+
|
|
17
|
+
[HIGH] BOLA GET /api/orders/:id (services/order.service.js:18)
|
|
18
|
+
API1:2023 Broken Object Level Authorization
|
|
19
|
+
findById via getOrder uses an id from the URL, and nothing on the way checks it against the caller.
|
|
20
|
+
Fix: scope the query to the caller: findOne({ _id: id, owner: req.user._id }).
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Why
|
|
24
|
+
|
|
25
|
+
Tools like Semgrep and Bearer are good at injection and secrets. Authorisation bugs are different:
|
|
26
|
+
the code looks fine line by line, and the flaw is a check that is *missing*. On a deliberately
|
|
27
|
+
vulnerable API, Semgrep found 1 of 9 bugs and Bearer found none ([benchmark](https://github.com/12keerti21/routeguard/blob/main/benchmark.md)).
|
|
28
|
+
|
|
29
|
+
## What it checks
|
|
30
|
+
|
|
31
|
+
| OWASP API 2023 | Check |
|
|
32
|
+
|---|---|
|
|
33
|
+
| API1 Broken Object Level Authorization | A record is loaded or changed by a URL id, and nothing on the way checks it belongs to the caller. Follows the id into service functions. |
|
|
34
|
+
| API2 Broken Authentication | JWT algorithm confusion, `alg: none`, ignored expiry, signing keys in the code |
|
|
35
|
+
| API3 Broken Object Property Level Authorization | Whole request bodies written to records (`new User(req.body)`), `isAdmin` taken from the client, whole user records sent back |
|
|
36
|
+
| API4 Unrestricted Resource Consumption | Login, OTP, reset and sign-up routes with no rate limit |
|
|
37
|
+
| API5 Broken Function Level Authorization | Admin, debug, metrics and log routes with no role check; shared data any user can change |
|
|
38
|
+
| API6 Unrestricted Access to Sensitive Business Flows | Checkout, coupon, booking and review flows with nothing against bots |
|
|
39
|
+
| API7 Server Side Request Forgery | The server fetches a URL the client chose |
|
|
40
|
+
| API8 Security Misconfiguration | CORS open to any origin with credentials, stack traces in responses, missing security headers |
|
|
41
|
+
| API9 Improper Inventory Management | Old or development copies of an endpoint with weaker checks, routes missing from the OpenAPI spec |
|
|
42
|
+
| API10 Unsafe Consumption of APIs | Third-party responses stored, run or redirected to without validation; plain-http calls; API keys in URLs |
|
|
43
|
+
|
|
44
|
+
## Use it
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
npx routeguard-cli <path-to-express-app>
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Or install it with `npm install -g routeguard-cli` and run `routeguard`. From a clone of this repo:
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
cd tool && npm install
|
|
54
|
+
node bin/cli.js <path-to-express-app> # table and findings
|
|
55
|
+
node bin/cli.js <path-to-express-app> --json # machine-readable
|
|
56
|
+
node bin/cli.js <path-to-express-app> --sarif # for GitHub code scanning
|
|
57
|
+
node bin/cli.js <path-to-express-app> --fail-on HIGH # exit 2 only on HIGH findings
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Requires Node 20 or later. Works with JavaScript and TypeScript, `require` and `import`, monorepos and
|
|
61
|
+
package.json `#imports`.
|
|
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
|
+
|
|
92
|
+
### In GitHub Actions
|
|
93
|
+
|
|
94
|
+
```yaml
|
|
95
|
+
name: routeguard
|
|
96
|
+
on: [pull_request]
|
|
97
|
+
permissions:
|
|
98
|
+
contents: read
|
|
99
|
+
security-events: write
|
|
100
|
+
jobs:
|
|
101
|
+
scan:
|
|
102
|
+
runs-on: ubuntu-latest
|
|
103
|
+
steps:
|
|
104
|
+
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
|
105
|
+
with:
|
|
106
|
+
persist-credentials: false
|
|
107
|
+
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
|
108
|
+
with:
|
|
109
|
+
node-version: 20
|
|
110
|
+
- id: routeguard
|
|
111
|
+
uses: 12keerti21/routeguard@v1
|
|
112
|
+
with:
|
|
113
|
+
path: .
|
|
114
|
+
fail-on: HIGH
|
|
115
|
+
- uses: github/codeql-action/upload-sarif@915412ff23e8b7659517e607487dbeae018f2934 # v4.39.5
|
|
116
|
+
if: always()
|
|
117
|
+
with:
|
|
118
|
+
sarif_file: ${{ steps.routeguard.outputs.sarif-file }}
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
Findings appear on the pull request and under **Security → Code scanning**.
|
|
122
|
+
|
|
123
|
+
### Silence a reviewed finding
|
|
124
|
+
|
|
125
|
+
Put a comment in the three lines above the route:
|
|
126
|
+
|
|
127
|
+
```js
|
|
128
|
+
// the share id is unguessable and is the key
|
|
129
|
+
// routeguard-ignore BOLA
|
|
130
|
+
router.get("/shared/:shareId", getSharedNote)
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
Leave out the rule name to silence every rule for that route.
|
|
134
|
+
|
|
135
|
+
## How it works
|
|
136
|
+
|
|
137
|
+
1. **Map the routes.** Parses every source file and follows `app.use` and `router.use` mounts, so each
|
|
138
|
+
route gets its full path and every middleware in front of it, including middleware applied to a
|
|
139
|
+
whole path or router.
|
|
140
|
+
2. **Read the handlers.** Finds each route's handler, even in another file, a controller object or a
|
|
141
|
+
wrapper like `catchAsync(...)`.
|
|
142
|
+
3. **Follow the data.** For object-level checks, traces the URL id from the handler into the
|
|
143
|
+
services it calls. It looks for the caller (`req.user`) limiting that id along the way: in the
|
|
144
|
+
query, in a comparison, or in a check such as `canEdit(user, course)`.
|
|
145
|
+
4. **Report.** Each finding has a severity, the OWASP category, the file and line, and a fix.
|
|
146
|
+
|
|
147
|
+
## Limits
|
|
148
|
+
|
|
149
|
+
- Static analysis trusts what a check returns. If `canEdit()` itself has a logic bug, only `verify` against a running app will show it.
|
|
150
|
+
- Static analysis cannot know an id is unguessable. Capability links need a `routeguard-ignore` comment.
|
|
151
|
+
- Express only for now.
|
|
152
|
+
|
|
153
|
+
## Results
|
|
154
|
+
|
|
155
|
+
Tested on deliberately vulnerable APIs and 14 open-source Express apps (1,400+ routes). See
|
|
156
|
+
[benchmark.md](https://github.com/12keerti21/routeguard/blob/main/benchmark.md).
|
|
157
|
+
|
|
158
|
+
## Development
|
|
159
|
+
|
|
160
|
+
```bash
|
|
161
|
+
cd tool && npm test
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
Tests run every check against a small fixture app that has a vulnerable and a safe version of each
|
|
165
|
+
pattern.
|
package/bin/cli.js
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFileSync } from "node:fs"
|
|
3
|
+
import path from "node:path"
|
|
4
|
+
import { mapRoutes } from "../src/mapper.js"
|
|
5
|
+
import { toSarif } from "../src/sarif.js"
|
|
6
|
+
import { bola } from "../src/rules/bola.js"
|
|
7
|
+
import { bfla } from "../src/rules/bfla.js"
|
|
8
|
+
import { massAssignment } from "../src/rules/massAssignment.js"
|
|
9
|
+
import { ssrf } from "../src/rules/ssrf.js"
|
|
10
|
+
import { rateLimit } from "../src/rules/rateLimit.js"
|
|
11
|
+
import { dataExposure } from "../src/rules/dataExposure.js"
|
|
12
|
+
import { misconfig } from "../src/rules/misconfig.js"
|
|
13
|
+
import { inventory } from "../src/rules/inventory.js"
|
|
14
|
+
import { businessFlow } from "../src/rules/businessFlow.js"
|
|
15
|
+
import { consumption } from "../src/rules/consumption.js"
|
|
16
|
+
import { verify } from "../src/verify.js"
|
|
17
|
+
|
|
18
|
+
const RULES = [bola, bfla, massAssignment, dataExposure, ssrf, rateLimit, businessFlow]
|
|
19
|
+
|
|
20
|
+
const SEVERITIES = ["LOW", "MEDIUM", "HIGH"]
|
|
21
|
+
|
|
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"])
|
|
29
|
+
const option = name => {
|
|
30
|
+
const i = args.indexOf(name)
|
|
31
|
+
return i === -1 ? null : args[i + 1]
|
|
32
|
+
}
|
|
33
|
+
const json = args.includes("--json")
|
|
34
|
+
const sarif = args.includes("--sarif")
|
|
35
|
+
// --fail-on HIGH: exit 2 only for findings at or above that severity (default LOW: any finding)
|
|
36
|
+
const failOn = (option("--fail-on") ?? "LOW").toUpperCase()
|
|
37
|
+
const target = args.find((a, i) => !a.startsWith("--") && !VALUE_FLAGS.has(args[i - 1]))
|
|
38
|
+
|
|
39
|
+
if (!target || !SEVERITIES.includes(failOn) || (verifying && (!option("--base-url") || !option("--config")))) {
|
|
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]")
|
|
42
|
+
process.exit(1)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const routes = mapRoutes(path.resolve(target))
|
|
46
|
+
const suppressed = (route, finding) => route.ignored === "all" || route.ignored?.has(finding.rule)
|
|
47
|
+
// a router mounted twice reports the same code twice
|
|
48
|
+
const seen = new Set()
|
|
49
|
+
const root = path.resolve(target)
|
|
50
|
+
const findings = [
|
|
51
|
+
...routes.flatMap(r => RULES.map(rule => rule(r)).filter(f => f && !suppressed(r, f))),
|
|
52
|
+
// checks that look at the app as a whole, not one route
|
|
53
|
+
...inventory(routes, root),
|
|
54
|
+
...misconfig(root),
|
|
55
|
+
...consumption(root)
|
|
56
|
+
].filter(f => !seen.has(`${f.rule} ${f.route} ${f.where}`) && seen.add(`${f.rule} ${f.route} ${f.where}`))
|
|
57
|
+
|
|
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(" ")
|
|
64
|
+
|
|
65
|
+
console.log(line(header))
|
|
66
|
+
console.log(widths.map(w => "-".repeat(w)).join(" "))
|
|
67
|
+
rows.forEach(r => console.log(line(r)))
|
|
68
|
+
|
|
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`)
|
|
71
|
+
|
|
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
|
+
}
|
|
80
|
+
|
|
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
|
+
}
|
|
97
|
+
|
|
98
|
+
const exitCode = findings.some(f => SEVERITIES.indexOf(f.severity) >= SEVERITIES.indexOf(failOn)) ? 2 : 0
|
|
99
|
+
|
|
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)
|
|
116
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,47 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "routeguard-cli",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.1.0",
|
|
4
|
+
"description": "Find broken authorisation in Express APIs: maps routes to their checks and flags the OWASP API Security Top 10",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"routeguard": "bin/cli.js"
|
|
8
|
+
},
|
|
9
|
+
"scripts": {
|
|
10
|
+
"map": "node bin/cli.js",
|
|
11
|
+
"test": "node --test test/*.test.js",
|
|
12
|
+
"prepack": "cp ../README.md ../LICENSE ."
|
|
13
|
+
},
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": ">=20"
|
|
16
|
+
},
|
|
17
|
+
"license": "MIT",
|
|
18
|
+
"dependencies": {
|
|
19
|
+
"@babel/parser": "^7.29.15"
|
|
20
|
+
},
|
|
21
|
+
"keywords": [
|
|
22
|
+
"security",
|
|
23
|
+
"owasp",
|
|
24
|
+
"api-security",
|
|
25
|
+
"express",
|
|
26
|
+
"authorization",
|
|
27
|
+
"bola",
|
|
28
|
+
"sast",
|
|
29
|
+
"static-analysis"
|
|
30
|
+
],
|
|
31
|
+
"author": "Keerti Deshpande",
|
|
32
|
+
"repository": {
|
|
33
|
+
"type": "git",
|
|
34
|
+
"url": "git+https://github.com/12keerti21/routeguard.git",
|
|
35
|
+
"directory": "tool"
|
|
36
|
+
},
|
|
37
|
+
"homepage": "https://github.com/12keerti21/routeguard#readme",
|
|
38
|
+
"bugs": {
|
|
39
|
+
"url": "https://github.com/12keerti21/routeguard/issues"
|
|
40
|
+
},
|
|
41
|
+
"files": [
|
|
42
|
+
"bin",
|
|
43
|
+
"src",
|
|
44
|
+
"README.md",
|
|
45
|
+
"LICENSE"
|
|
46
|
+
]
|
|
47
|
+
}
|
package/src/flow.js
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import { walk, isCallNode, isMemberNode } from "./mapper.js"
|
|
2
|
+
import { DB_CALL, DB_WRITE, handlerParams, isMember } from "./rules/handler.js"
|
|
3
|
+
|
|
4
|
+
// a call that takes the caller and decides: canEdit(user, course), assertCourseReach(user, id), findOwnedCourse(id, user)
|
|
5
|
+
const CHECK_FN = /can[A-Z_]|check|assert|ensure|reach|access|permi(t|ssion)|authori[sz]|verify|owned|own[A-Z]|allowed|guard|scope/i
|
|
6
|
+
// an unresolved call that looks like it loads a record: userService.getUserById(id)
|
|
7
|
+
const SERVICE_LOOKUP = /^(get|find|fetch|load|read|update|edit|patch|delete|remove|destroy|archive)[A-Z_]/
|
|
8
|
+
const IDENTITY_KEYS = new Set(["user", "auth", "session", "userId", "currentUser"])
|
|
9
|
+
const IDENTITY_FN = /user|auth|jwt|token|session|identity|principal|caller/i
|
|
10
|
+
const APPENDS_USER = /(append|set|attach|inject|add)_?user/i
|
|
11
|
+
const BODY_USER_FIELD = /^(user_?id|owner_?id|owner)$/i
|
|
12
|
+
const MAX_DEPTH = 4
|
|
13
|
+
// a record created for the caller: comment.create({ author: user.id })
|
|
14
|
+
const CREATE = /^(create|insert|insertOne|insertMany|save|build|bulkCreate)$/
|
|
15
|
+
const SERVICE_WRITE = /^(update|edit|patch|delete|remove|destroy|archive)[A-Z_]/
|
|
16
|
+
|
|
17
|
+
// identifiers a node reads, skipping property names: in course.user, "user" is not a variable
|
|
18
|
+
function identifiers(node, out = []) {
|
|
19
|
+
if (!node || typeof node.type !== "string") return out
|
|
20
|
+
if (node.type === "Identifier") {
|
|
21
|
+
out.push(node.name)
|
|
22
|
+
return out
|
|
23
|
+
}
|
|
24
|
+
if (isMemberNode(node)) {
|
|
25
|
+
identifiers(node.object, out)
|
|
26
|
+
if (node.computed) identifiers(node.property, out)
|
|
27
|
+
return out
|
|
28
|
+
}
|
|
29
|
+
if (node.type === "ObjectProperty") {
|
|
30
|
+
if (node.computed) identifiers(node.key, out)
|
|
31
|
+
identifiers(node.value, out)
|
|
32
|
+
return out
|
|
33
|
+
}
|
|
34
|
+
for (const key of Object.keys(node)) {
|
|
35
|
+
if (key === "loc" || key === "start" || key === "end") continue
|
|
36
|
+
const child = node[key]
|
|
37
|
+
if (Array.isArray(child)) child.forEach(c => identifiers(c, out))
|
|
38
|
+
else if (child && typeof child.type === "string") identifiers(child, out)
|
|
39
|
+
}
|
|
40
|
+
return out
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function boundNames(id) {
|
|
44
|
+
if (!id) return []
|
|
45
|
+
if (id.type === "Identifier") return [id.name]
|
|
46
|
+
if (id.type === "AssignmentPattern") return boundNames(id.left)
|
|
47
|
+
if (id.type === "RestElement") return boundNames(id.argument)
|
|
48
|
+
if (id.type === "ObjectPattern") return id.properties.flatMap(p => boundNames(p.value ?? p.argument))
|
|
49
|
+
if (id.type === "ArrayPattern") return id.elements.flatMap(boundNames)
|
|
50
|
+
return []
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const isFunction = node => ["ArrowFunctionExpression", "FunctionExpression"].includes(node?.type)
|
|
54
|
+
|
|
55
|
+
// solveIf(() => user.bid != id): a callback is code, not a value; its body is read where it is written
|
|
56
|
+
const valueArgs = call => call.arguments.filter(a => !isFunction(a))
|
|
57
|
+
|
|
58
|
+
const calleeName = call => (isMemberNode(call.callee) ? call.callee.property.name : call.callee.name) ?? ""
|
|
59
|
+
|
|
60
|
+
// how a request object marks URL values and the caller, under whatever name it has here
|
|
61
|
+
function requestPredicates(req, bodyIsCaller) {
|
|
62
|
+
if (!req) return { isId: () => false, isCaller: () => false }
|
|
63
|
+
return {
|
|
64
|
+
isId: n => isMember(n, req, "params") || (isMemberNode(n) && isMember(n.object, req, "params")),
|
|
65
|
+
isCaller: n =>
|
|
66
|
+
(isMember(n, req) && IDENTITY_KEYS.has(n.property.name)) ||
|
|
67
|
+
(bodyIsCaller && isMemberNode(n) && isMember(n.object, req, "body") && BODY_USER_FIELD.test(n.property.name ?? "")) ||
|
|
68
|
+
(isCallNode(n) &&
|
|
69
|
+
n.arguments.some(a => a.type === "Identifier" && a.name === req) &&
|
|
70
|
+
IDENTITY_FN.test(isMemberNode(n.callee) ? `${n.callee.object.name ?? n.callee.object.property?.name ?? ""}.${n.callee.property.name}` : (n.callee.name ?? "")))
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function reads(node, names, predicate) {
|
|
75
|
+
if (!node) return false
|
|
76
|
+
if (identifiers(node).some(name => names.has(name))) return true
|
|
77
|
+
let found = false
|
|
78
|
+
walk(node, n => {
|
|
79
|
+
if (!found && predicate(n)) found = true
|
|
80
|
+
})
|
|
81
|
+
return found
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// pass the caller's arguments onto the callee's parameters
|
|
85
|
+
function bindArguments(fn, args, ctx, readsId, readsCaller) {
|
|
86
|
+
const ids = new Set()
|
|
87
|
+
const callers = new Set()
|
|
88
|
+
let req = null
|
|
89
|
+
fn.params.forEach((param, i) => {
|
|
90
|
+
const arg = args[i]
|
|
91
|
+
if (!arg || isFunction(arg)) return
|
|
92
|
+
const target = param.type === "AssignmentPattern" ? param.left : param
|
|
93
|
+
// service(req): the whole request travels, under the parameter's name
|
|
94
|
+
if (arg.type === "Identifier" && arg.name === ctx.req && target.type === "Identifier") req = target.name
|
|
95
|
+
if (target.type === "ObjectPattern" && arg.type === "ObjectExpression") {
|
|
96
|
+
for (const prop of target.properties) {
|
|
97
|
+
const value = arg.properties.find(a => a.key?.name === prop.key?.name)?.value
|
|
98
|
+
if (!value) continue
|
|
99
|
+
if (readsCaller(value)) boundNames(prop.value).forEach(n => callers.add(n))
|
|
100
|
+
else if (readsId(value)) boundNames(prop.value).forEach(n => ids.add(n))
|
|
101
|
+
}
|
|
102
|
+
return
|
|
103
|
+
}
|
|
104
|
+
if (readsCaller(arg)) boundNames(target).forEach(n => callers.add(n))
|
|
105
|
+
if (readsId(arg)) boundNames(target).forEach(n => ids.add(n))
|
|
106
|
+
})
|
|
107
|
+
return { ids, callers, req }
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// Does the caller limit the record that the URL id reaches, here or in what this function calls?
|
|
111
|
+
// scoped: true, the caller is in the query, a guard or a check call
|
|
112
|
+
// scoped: false, a query uses the id and nothing on the way looks at the caller (at: where)
|
|
113
|
+
// scoped: null, nothing conclusive (trusted: the caller was handed to code we cannot read)
|
|
114
|
+
export function traceScope(ctx) {
|
|
115
|
+
const { fn, file, resolve, depth = 0, seen = new Set(), chain = [] } = ctx
|
|
116
|
+
const ids = new Set(ctx.ids ?? [])
|
|
117
|
+
const callers = new Set(ctx.callers ?? [])
|
|
118
|
+
const { isId, isCaller } = requestPredicates(ctx.req, ctx.bodyIsCaller)
|
|
119
|
+
const readsId = node => reads(node, ids, isId)
|
|
120
|
+
const readsCaller = node => reads(node, callers, isCaller)
|
|
121
|
+
|
|
122
|
+
// const course = await findOwnedCourse(id, user) stands for the caller from here on
|
|
123
|
+
for (let pass = 0; pass < 2; pass++) {
|
|
124
|
+
walk(fn.body, n => {
|
|
125
|
+
if (n.type !== "VariableDeclarator" || !n.init) return
|
|
126
|
+
// a value built from both (findOwnedCourse(id, user)) belongs to both sets
|
|
127
|
+
const caller = readsCaller(n.init)
|
|
128
|
+
const id = readsId(n.init)
|
|
129
|
+
if (caller) boundNames(n.id).forEach(name => callers.add(name))
|
|
130
|
+
if (id) boundNames(n.id).forEach(name => ids.add(name))
|
|
131
|
+
})
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
let scoped = false
|
|
135
|
+
let why = null
|
|
136
|
+
let trusted = false
|
|
137
|
+
let ownedCreate = false
|
|
138
|
+
const scope = (n, reason) => {
|
|
139
|
+
if (!scoped) why = { file, line: n.loc.start.line, reason, chain }
|
|
140
|
+
scoped = true
|
|
141
|
+
}
|
|
142
|
+
const unscoped = []
|
|
143
|
+
|
|
144
|
+
walk(fn.body, n => {
|
|
145
|
+
// if (course.ownerOrgId !== user.orgId): the caller compared with what the id reached.
|
|
146
|
+
// if (!user) alone checks login, not ownership.
|
|
147
|
+
// history[noteId] where history is the caller's own: the id only picks among the caller's records
|
|
148
|
+
if (isMemberNode(n) && n.computed && readsCaller(n.object) && readsId(n.property)) scope(n, "id looked up in the caller's own data")
|
|
149
|
+
if ((n.type === "IfStatement" || n.type === "ConditionalExpression") && readsCaller(n.test) && readsId(n.test))
|
|
150
|
+
scope(n, "guard comparing the caller with the record")
|
|
151
|
+
if (!isCallNode(n)) return
|
|
152
|
+
|
|
153
|
+
const name = calleeName(n)
|
|
154
|
+
const takesId = valueArgs(n).some(readsId)
|
|
155
|
+
const takesCaller = valueArgs(n).some(readsCaller)
|
|
156
|
+
if (takesCaller && CHECK_FN.test(name)) scope(n, `${name}(… caller …)`)
|
|
157
|
+
if (takesCaller && CREATE.test(name)) ownedCreate = true
|
|
158
|
+
// getHistory(req.user.id, (err, history) => …): history is the caller's
|
|
159
|
+
if (takesCaller) n.arguments.filter(isFunction).forEach(cb => cb.params.flatMap(boundNames).forEach(p => callers.add(p)))
|
|
160
|
+
if (!takesId || scoped) return
|
|
161
|
+
|
|
162
|
+
const line = n.loc.start.line
|
|
163
|
+
if (DB_CALL.test(name)) {
|
|
164
|
+
if (takesCaller) scope(n, `${name} scoped to the caller`)
|
|
165
|
+
else unscoped.push({ file, line, method: name, chain, write: DB_WRITE.test(name) })
|
|
166
|
+
return
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const target = depth < MAX_DEPTH ? resolve?.(file, n.callee) : null
|
|
170
|
+
const key = target && `${target.file}:${target.fn.start}`
|
|
171
|
+
if (!target || seen.has(key)) {
|
|
172
|
+
if (takesCaller) trusted = true
|
|
173
|
+
else if (SERVICE_LOOKUP.test(name)) unscoped.push({ file, line, method: name, chain, write: SERVICE_WRITE.test(name) })
|
|
174
|
+
return
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const bound = bindArguments(target.fn, n.arguments, ctx, readsId, readsCaller)
|
|
178
|
+
const result = traceScope({
|
|
179
|
+
fn: target.fn,
|
|
180
|
+
file: target.file,
|
|
181
|
+
resolve,
|
|
182
|
+
ids: bound.ids,
|
|
183
|
+
callers: bound.callers,
|
|
184
|
+
req: bound.req,
|
|
185
|
+
bodyIsCaller: ctx.bodyIsCaller,
|
|
186
|
+
depth: depth + 1,
|
|
187
|
+
seen: new Set([...seen, key]),
|
|
188
|
+
chain: [...chain, name]
|
|
189
|
+
})
|
|
190
|
+
if (result.scoped === true) {
|
|
191
|
+
if (!scoped) why = result.why
|
|
192
|
+
scoped = true
|
|
193
|
+
}
|
|
194
|
+
else if (result.scoped === false) unscoped.push(...result.unscoped)
|
|
195
|
+
else if (takesCaller || result.trusted) trusted = true
|
|
196
|
+
if (result.ownedCreate) ownedCreate = true
|
|
197
|
+
})
|
|
198
|
+
|
|
199
|
+
if (scoped) return { scoped: true, why }
|
|
200
|
+
const writes = unscoped.filter(u => u.write)
|
|
201
|
+
// reading a public parent to attach the caller's own record is fine; changing it is not
|
|
202
|
+
if (ownedCreate && writes.length === 0) return { scoped: true, why: { file, line: fn.loc.start.line, reason: "new record owned by the caller", chain }, ownedCreate }
|
|
203
|
+
if (unscoped.length) return { scoped: false, at: writes[0] ?? unscoped[0], unscoped, ownedCreate }
|
|
204
|
+
return { scoped: null, trusted, ownedCreate }
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// start at a route's handler, where req.params are the ids and req.user is the caller
|
|
208
|
+
export function traceRoute(route) {
|
|
209
|
+
const { req } = handlerParams(route.fn)
|
|
210
|
+
return traceScope({
|
|
211
|
+
fn: route.fn,
|
|
212
|
+
file: route.fnPath,
|
|
213
|
+
resolve: route.resolve,
|
|
214
|
+
req,
|
|
215
|
+
bodyIsCaller: route.middleware.some(m => APPENDS_USER.test(m))
|
|
216
|
+
})
|
|
217
|
+
}
|