ai-secure-audit 0.0.3 → 0.0.11

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
@@ -1,6 +1,9 @@
1
1
  # ai-secure-audit
2
2
 
3
- > Status: 0.0.x on npm runs the basic secret check with `npx ai-secure-audit`. v0.1 is not released yet.
3
+ > Status: 0.0.x on npm runs the basic check with `npx ai-secure-audit`: secrets, libraries with known holes and, from
4
+ > 0.0.5, code rules for routes anyone can repeat without limit and, from 0.0.9, for session checks that a built-in
5
+ > name such as `constructor` passes. From 0.0.10 it also checks Dockerfiles with trivy (Compose files are not read yet,
6
+ > and the report says so), and from 0.0.11 it warns when a Docker build would copy these results into the image. v0.1 is not released yet.
4
7
  >
5
8
  > **มือใหม่เริ่มตรงนี้:** [learn/](learn/) ควรตรวจอะไรก่อน เพราะอะไร และแก้ยังไง (ภาษาไทย)
6
9
  >
@@ -56,7 +59,10 @@ Or ask your AI assistant: *"Run `node <path-to>/ai-secure-audit/bin/ai-secure-au
56
59
  results in simple words, and help me fix the most serious ones first."*
57
60
 
58
61
  Results go to `.audit/out/` in your project (`report.md` for people, `findings.json` for tools and AI). That folder
59
- ignores itself in git, so results are not committed by accident.
62
+ ignores itself in git, so results are not committed by accident. Git is not the only way out, though: a `Dockerfile`
63
+ with `COPY . .` puts every file in the folder into the image. From 0.0.11 the report warns (under "About these
64
+ results") when a `Dockerfile` at the top of the project copies the whole folder and `.dockerignore` does not leave out
65
+ `.audit`.
60
66
 
61
67
  ## Repository layout
62
68
 
@@ -79,17 +85,19 @@ Checks are released one at a time, each after passing its own tests. The version
79
85
  switched on.
80
86
 
81
87
  For anyone who builds apps with AI and wants to check their own project. You do not need Docker, Homebrew, Python
82
- or Java. The tools are single files for Windows, macOS and Linux, downloaded at pinned versions and checked against
88
+ or Java. The tools are single files for Windows, macOS and Linux (including Alpine), downloaded at pinned versions and checked against
83
89
  SHA-256 checksums. The check reads only your project folder and never uploads your code.
84
90
 
85
91
  | Checks | Tool | License |
86
92
  |---|---|---|
87
93
  | Passwords, API keys and tokens in the code, in files not committed yet, in git history and in build output (v0.1) | gitleaks | MIT |
88
94
  | Libraries with known vulnerabilities (v0.2) | osv-scanner (offline database) | Apache-2.0 |
89
- | Dockerfile and config mistakes (v0.3) | trivy config | Apache-2.0 |
90
- | Code mistakes AI-generated apps often make (see below), planned | opengrep + this kit's own rules | LGPL-2.1 (rules: Apache-2.0) |
95
+ | Dockerfile and config mistakes (0.0.10): Dockerfile, Kubernetes, Helm, Terraform, CloudFormation, Azure ARM, Ansible. trivy does not read Docker Compose files; the report names any it found as not checked | trivy config | Apache-2.0 |
96
+ | Code mistakes AI-generated apps often make (see below), one rule at a time: sign-in, sign-up and join routes with no limit on repeats (Express 0.0.5, NestJS 0.0.6), vote and like routes that never check who is voting (0.0.6), session, token or admin checks that a built-in name like `constructor` passes (0.0.9); the rest planned | opengrep + this kit's own rules | LGPL-2.1 (rules: Apache-2.0) |
91
97
 
92
- Common mistakes the kit's own rules look for: secret keys in frontend code or `NEXT_PUBLIC_*` variables, Supabase
98
+ Common mistakes the kit's own rules look for: sign-in, sign-up and join routes that anyone can call without limit
99
+ (Express and NestJS), vote routes that never check who is voting, session checks done on a plain object (a cookie
100
+ `admin=constructor` passes), secret keys in frontend code or `NEXT_PUBLIC_*` variables, Supabase
93
101
  `service_role` key outside the server, tables without row-level security, Firebase rules that allow everything,
94
102
  API routes without an auth check, permission checks done only in the browser, committed `.env` files, CORS `*`,
95
103
  and stack traces returned to users.
@@ -120,6 +128,10 @@ Every tool sends traffic only to hosts listed in `.audit/targets.yml`, and produ
120
128
  - It does not certify anything. A report states which standard and level were self-assessed, on which date and commit.
121
129
  - Automated tools cannot fully check business logic or whether one user can reach another user's data;
122
130
  the report lists these for manual review.
131
+ - Code rules exist for JavaScript and TypeScript only so far. Secrets are found in any language, and libraries in
132
+ npm, PHP, Go, Rust, Ruby, C# and Python lockfiles; the report says which languages and lockfiles it could not
133
+ check, so "0 findings" is never read as "checked". For those, [docs/ai-review-prompt.md](docs/ai-review-prompt.md) is a
134
+ prompt for your AI assistant that works in any language (its results vary between runs; treat them as leads).
123
135
 
124
136
  ## Privacy
125
137
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-secure-audit",
3
- "version": "0.0.3",
3
+ "version": "0.0.11",
4
4
  "description": "Free, open-source security check for apps built with AI. Runs pinned open-source scanners; no AI needed to run.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -0,0 +1,66 @@
1
+ // Test cases for express-route-no-rate-limit. Run: opengrep scan --test rules/
2
+ const express = require('express');
3
+ const app = express();
4
+ const router = express.Router();
5
+
6
+ // ruleid: express-route-no-rate-limit
7
+ app.post('/api/admin/login', (req, res) => {
8
+ if (req.body.password !== process.env.ADMIN_PASSWORD) return res.status(401).end();
9
+ res.json({ ok: true });
10
+ });
11
+
12
+ // ruleid: express-route-no-rate-limit
13
+ app.post('/api/join', (req, res) => {
14
+ res.json({ token: newToken() });
15
+ });
16
+
17
+ // ruleid: express-route-no-rate-limit
18
+ router.post('/register', async (req, res) => {
19
+ await saveUser(req.body);
20
+ res.json({ ok: true });
21
+ });
22
+
23
+ // ruleid: express-route-no-rate-limit
24
+ app.put('/auth/reset-password', handler);
25
+
26
+ // ruleid: express-route-no-rate-limit
27
+ userRouter.post('/sign-up', handler);
28
+
29
+ // ok: express-route-no-rate-limit
30
+ app.post('/api/join', loginLimiter, (req, res) => res.json({}));
31
+
32
+ // ok: express-route-no-rate-limit
33
+ app.post('/api/vote', rateLimit({ windowMs: 60000, max: 10 }), handler);
34
+
35
+ // ok: express-route-no-rate-limit
36
+ app.post('/api/join', (req, res) => {
37
+ const wait = limits.joinIp.wait(req.ip);
38
+ if (wait) return limited(res, wait);
39
+ res.json({});
40
+ });
41
+
42
+ // ok: express-route-no-rate-limit
43
+ app.post('/api/admin/login', (req, res) => {
44
+ if (tooManyAttempts(req.ip)) return res.status(429).end();
45
+ res.json({});
46
+ });
47
+
48
+ // Not a sign-in, join or sign-up route.
49
+ // ok: express-route-no-rate-limit
50
+ app.post('/api/admin/topics', handler);
51
+
52
+ // Admin routes behind a login, even when the path says reset or join.
53
+ // ok: express-route-no-rate-limit
54
+ app.post('/api/admin/reset-votes', handler);
55
+
56
+ // A vote needs a token from /api/join; the join route is what must be limited.
57
+ // ok: express-route-no-rate-limit
58
+ app.post('/api/vote', handler);
59
+
60
+ // Reading, not submitting.
61
+ // ok: express-route-no-rate-limit
62
+ app.get('/login', (req, res) => res.sendFile('login.html'));
63
+
64
+ // An outgoing request, not a route.
65
+ // ok: express-route-no-rate-limit
66
+ axios.post('/api/login', { user, password });
@@ -0,0 +1,47 @@
1
+ rules:
2
+ - id: express-route-no-rate-limit
3
+ languages: [javascript, typescript]
4
+ severity: WARNING
5
+ message: >-
6
+ This route accepts sign-ins, sign-ups, joins or codes, and nothing in this file limits how often one person can
7
+ call it. A short script can repeat it thousands of times: guess passwords or codes, or create as many accounts
8
+ or voters as it likes. Add a per-IP or per-account limit (for example express-rate-limit, or a counter in the
9
+ handler) and lock out after repeated failures. If a limiter is applied somewhere this rule cannot see (another
10
+ file, the reverse proxy), confirm it actually covers this route.
11
+ metadata:
12
+ category: code
13
+ cwe: 'CWE-307: Improper Restriction of Excessive Authentication Attempts'
14
+ asvs: 'OWASP ASVS 5.0 V6.3.1 (brute force), V2.4.1 (anti-automation)'
15
+ confidence: MEDIUM
16
+ limitations: >-
17
+ Express-style routes with a literal path only. Does not see limiters defined in another file and applied
18
+ with app.use, limits set at a proxy or CDN, or frameworks with decorators (NestJS). Vote routes are not matched: a vote usually needs an identity from a join or
19
+ sign-in route, and that route is what has to be limited.
20
+ patterns:
21
+ - pattern-either:
22
+ - pattern: $APP.$METHOD("$PATH", ...)
23
+ - metavariable-regex:
24
+ metavariable: $APP
25
+ regex: ^(app|router|server|api|[A-Za-z]*[Rr]outer|[A-Za-z]*Routes)$
26
+ - metavariable-regex:
27
+ metavariable: $METHOD
28
+ regex: ^(post|put|patch|all)$
29
+ - metavariable-regex:
30
+ metavariable: $PATH
31
+ # Admin routes other than the admin sign-in sit behind a login already.
32
+ regex: (?i)^(?!.*/admin/(?!log-?in|sign-?in)).*(log-?in|sign-?in|sign-?up|register|join|otp|verify|forgot|reset|password|passcode|redeem)
33
+ # The route itself names a limiter, or its handler counts attempts.
34
+ - pattern-not-regex: (?i)(rate.?limit|limiter|throttl|slow.?down|brute|bucket|lockout|too.?many|\blimited\(|\blimits\.)
35
+ # A known limiter package is loaded in this file.
36
+ - pattern-not-inside: |
37
+ import $X from "=~/^(express-rate-limit|rate-limiter-flexible|express-slow-down|express-brute)$/";
38
+ ...
39
+ - pattern-not-inside: |
40
+ import { ... } from "=~/^(express-rate-limit|rate-limiter-flexible|express-slow-down|express-brute)$/";
41
+ ...
42
+ - pattern-not-inside: |
43
+ $X = require("=~/^(express-rate-limit|rate-limiter-flexible|express-slow-down|express-brute)$/");
44
+ ...
45
+ - pattern-not-inside: |
46
+ $X = require("=~/^(express-rate-limit|rate-limiter-flexible|express-slow-down|express-brute)$/").$Y;
47
+ ...
@@ -0,0 +1,93 @@
1
+ // Test cases for express-session-lookup-plain-object. Run: opengrep scan --test rules/
2
+ const express = require('express');
3
+ const crypto = require('crypto');
4
+ const app = express();
5
+ const db = { adminSessions: {}, sessions: {}, codes: {} };
6
+ const sessions = {};
7
+ const apiKeys = {};
8
+
9
+ function cookies(req) {
10
+ return Object.fromEntries((req.headers.cookie || '').split(';').map((c) => c.trim().split('=')));
11
+ }
12
+ const hashToken = (t) => crypto.createHash('sha256').update(String(t)).digest('hex');
13
+
14
+ // The case that was found: cookie admin=constructor passes.
15
+ function requireAdmin(req, res, next) {
16
+ const t = cookies(req).admin;
17
+ // ruleid: express-session-lookup-plain-object
18
+ if (t && db.adminSessions[t]) return next();
19
+ res.status(401).end();
20
+ }
21
+
22
+ app.get('/me', (req, res) => {
23
+ // ruleid: express-session-lookup-plain-object
24
+ if (!sessions[req.cookies.sid]) return res.status(401).end();
25
+ res.json({});
26
+ });
27
+
28
+ app.get('/data', (req, res) => {
29
+ const key = req.get('x-api-key');
30
+ // ruleid: express-session-lookup-plain-object
31
+ if (key in apiKeys) return res.json({});
32
+ res.status(403).end();
33
+ });
34
+
35
+ app.get('/token', (req, res) => {
36
+ // ruleid: express-session-lookup-plain-object
37
+ res.json({ ok: sessions[req.query.token] ? true : false });
38
+ });
39
+
40
+ // A hash of the token is looked up instead.
41
+ function requireAdminHashed(req, res, next) {
42
+ const t = cookies(req).admin;
43
+ // ok: express-session-lookup-plain-object
44
+ if (t && db.adminSessions[hashToken(t)]) return next();
45
+ res.status(401).end();
46
+ }
47
+
48
+ // Own-property check first.
49
+ app.get('/me2', (req, res) => {
50
+ const sid = req.cookies.sid;
51
+ // ok: express-session-lookup-plain-object
52
+ if (Object.hasOwn(sessions, sid) && sessions[sid]) return res.json({});
53
+ res.status(401).end();
54
+ });
55
+
56
+ // A Map has no built-in keys.
57
+ const store = new Map();
58
+ app.get('/me3', (req, res) => {
59
+ // ok: express-session-lookup-plain-object
60
+ if (!store.get(req.cookies.sid)) return res.status(401).end();
61
+ res.json({});
62
+ });
63
+
64
+ // Upper-cased codes cannot spell a built-in key, and "codes" is not a session store.
65
+ app.post('/join', (req, res) => {
66
+ const code = String(req.body.code || '').toUpperCase();
67
+ // ok: express-session-lookup-plain-object
68
+ if (!db.codes[code]) return res.status(404).end();
69
+ res.json({});
70
+ });
71
+
72
+ // A key the server chose, not the request.
73
+ app.get('/admin-count', (req, res) => {
74
+ // ok: express-session-lookup-plain-object
75
+ if (db.adminSessions['current']) return res.json({ n: 1 });
76
+ res.json({ n: 0 });
77
+ });
78
+
79
+ // Writing a session is not a check.
80
+ app.post('/login', (req, res) => {
81
+ const t = crypto.randomBytes(32).toString('hex');
82
+ // ok: express-session-lookup-plain-object
83
+ sessions[t] = { at: Date.now() };
84
+ res.json({ t });
85
+ });
86
+
87
+ // A store made without a prototype.
88
+ const tokens = Object.create(null);
89
+ app.get('/me4', (req, res) => {
90
+ // ok: express-session-lookup-plain-object
91
+ if (!tokens[req.cookies.sid]) return res.status(401).end();
92
+ res.json({});
93
+ });
@@ -0,0 +1,85 @@
1
+ rules:
2
+ - id: express-session-lookup-plain-object
3
+ languages: [javascript, typescript]
4
+ severity: ERROR
5
+ message: >-
6
+ A session, token or admin check looks up a value from the request (a cookie, header, query or body field) in a
7
+ plain object. Every plain object already has keys such as "constructor", "toString" and "__proto__", so a
8
+ request that sends one of those names passes the check without knowing any real token. Store sessions in a Map
9
+ or an object made with Object.create(null), check with Object.hasOwn first, or look up a hash of the token
10
+ (which also keeps raw tokens out of storage).
11
+ metadata:
12
+ category: code
13
+ cwe: 'CWE-287: Improper Authentication'
14
+ asvs: 'OWASP ASVS 5.0 V7.2.1 (session tokens verified by a trusted back end)'
15
+ confidence: MEDIUM
16
+ limitations: >-
17
+ Express-style request objects (req or request) only, and only a lookup tested directly (in an if, a ternary,
18
+ a negation or "in"). Misses a lookup stored in a variable and tested later, a request value passed into
19
+ another function first, and stores whose name does not look like sessions, tokens, admins or keys.
20
+ mode: taint
21
+ pattern-sources:
22
+ - patterns:
23
+ - pattern-either:
24
+ - pattern: $REQ.cookies
25
+ - pattern: $REQ.signedCookies
26
+ - pattern: $REQ.headers
27
+ - pattern: $REQ.query
28
+ - pattern: $REQ.body
29
+ - pattern: $REQ.params
30
+ - pattern: $REQ.get(...)
31
+ - pattern: $REQ.header(...)
32
+ # A home-made cookie parser: cookies(req), parseCookies(req), ...
33
+ - patterns:
34
+ - pattern: $PARSE($REQ, ...)
35
+ - metavariable-regex:
36
+ metavariable: $PARSE
37
+ regex: (?i)cookie
38
+ - metavariable-regex:
39
+ metavariable: $REQ
40
+ regex: ^(req|request)$
41
+ pattern-sanitizers:
42
+ # A hash of the token is never a built-in key name.
43
+ - patterns:
44
+ - pattern: $HASH(...)
45
+ - metavariable-regex:
46
+ metavariable: $HASH
47
+ regex: (?i)(hash|sha\d*|digest|hmac)
48
+ - pattern: $X.digest(...)
49
+ # Upper case cannot spell constructor or __proto__.
50
+ - pattern: $X.toUpperCase()
51
+ pattern-sinks:
52
+ - patterns:
53
+ - pattern-either:
54
+ - pattern-inside: if (<... $O[$K] ...>) ...
55
+ - pattern-inside: '!$O[$K]'
56
+ - pattern-inside: '$O[$K] ? $A : $B'
57
+ - pattern-inside: '($O[$K]) ? $A : $B'
58
+ - pattern-inside: $K in $O
59
+ - pattern-either:
60
+ - pattern: $NAME[$K]
61
+ - pattern: $X.$NAME[$K]
62
+ - pattern: $X.$Y.$NAME[$K]
63
+ - pattern: $K in $NAME
64
+ - pattern: $K in $X.$NAME
65
+ - focus-metavariable: $K
66
+ # The store's own name (db.adminSessions -> adminSessions). Matched on the last identifier because a
67
+ # regex on a whole member expression does not match in taint mode (opengrep 1.33.1).
68
+ - metavariable-regex:
69
+ metavariable: $NAME
70
+ regex: (?i)(session|token|admin|auth|apikey|api_key|login|cred|secret|grant|allow)
71
+ # The same check guarded by an own-property test is safe.
72
+ - pattern-not-inside: if (<... Object.hasOwn($S, $K) ...>) ...
73
+ - pattern-not-inside: if (<... $S.hasOwnProperty($K) ...>) ...
74
+ - pattern-not-inside: if (<... Object.prototype.hasOwnProperty.call($S, $K) ...>) ...
75
+ - pattern-not-inside: Object.hasOwn($S, $K) && ...
76
+ # A store made without a prototype has none of those keys.
77
+ - pattern-not-inside: |
78
+ $NAME = Object.create(null);
79
+ ...
80
+ - pattern-not-inside: |
81
+ $NAME = { __proto__: null };
82
+ ...
83
+ - pattern-not-inside: |
84
+ $X.$NAME = Object.create(null);
85
+ ...
@@ -0,0 +1,49 @@
1
+ // Test cases for express-vote-route-no-identity. Run: opengrep scan --test rules/
2
+ const express = require('express');
3
+ const app = express();
4
+ const router = express.Router();
5
+ const counts = {};
6
+
7
+ // ruleid: express-vote-route-no-identity
8
+ app.post('/api/vote', (req, res) => {
9
+ counts[req.body.contestantId] = (counts[req.body.contestantId] || 0) + 1;
10
+ res.json({ ok: true });
11
+ });
12
+
13
+ // ruleid: express-vote-route-no-identity
14
+ router.post('/posts/:id/like', async (req, res) => {
15
+ await db.posts.increment(req.params.id, 'likes');
16
+ res.end();
17
+ });
18
+
19
+ // ruleid: express-vote-route-no-identity
20
+ app.put('/rating', handler);
21
+
22
+ // A vote tied to a token the server issued.
23
+ // ok: express-vote-route-no-identity
24
+ app.post('/api/vote', (req, res) => {
25
+ const v = voterFromReq(req);
26
+ if (!v) return res.status(401).end();
27
+ res.json({});
28
+ });
29
+
30
+ // ok: express-vote-route-no-identity
31
+ app.post('/api/vote', requireAuth, (req, res) => res.json({}));
32
+
33
+ // ok: express-vote-route-no-identity
34
+ app.post('/vote', (req, res) => {
35
+ if (seen.has(req.ip)) return res.status(429).end();
36
+ res.json({});
37
+ });
38
+
39
+ // Admin routes sit behind a login.
40
+ // ok: express-vote-route-no-identity
41
+ app.post('/api/admin/reset-votes', handler);
42
+
43
+ // Not a vote: the word only starts the same way.
44
+ // ok: express-vote-route-no-identity
45
+ app.post('/api/reactivate', handler);
46
+
47
+ // Reading results, not voting.
48
+ // ok: express-vote-route-no-identity
49
+ app.get('/api/votes', handler);
@@ -0,0 +1,44 @@
1
+ rules:
2
+ - id: express-vote-route-no-identity
3
+ languages: [javascript, typescript]
4
+ severity: WARNING
5
+ message: >-
6
+ This route takes votes, likes or ratings, and its handler never checks who is sending them or how often. Anyone
7
+ can call it again and again with a short script, so the count means nothing. Tie each vote to an identity the
8
+ server issued (a sign-in, a one-time code, a token from a join step that is itself limited), keep one vote per
9
+ identity on the server, and add a per-IP limit. Remembering "already voted" in the browser (localStorage, a
10
+ cookie the server does not check) does not stop a script.
11
+ metadata:
12
+ category: code
13
+ cwe: 'CWE-799: Improper Control of Interaction Frequency'
14
+ asvs: 'OWASP ASVS 5.0 V2.4.1 (anti-automation)'
15
+ confidence: MEDIUM
16
+ limitations: >-
17
+ Express-style routes with a literal path only. Does not see a check in middleware applied with app.use in
18
+ another file, or a limit at a proxy or CDN.
19
+ patterns:
20
+ - pattern: $APP.$METHOD("$PATH", ...)
21
+ - metavariable-regex:
22
+ metavariable: $APP
23
+ regex: ^(app|router|server|api|[A-Za-z]*[Rr]outer|[A-Za-z]*Routes)$
24
+ - metavariable-regex:
25
+ metavariable: $METHOD
26
+ regex: ^(post|put|patch|all)$
27
+ - metavariable-regex:
28
+ metavariable: $PATH
29
+ # Admin routes sit behind a login already.
30
+ regex: (?i)^(?!.*/admin/).*(^|[/_-])(votes?|ballots?|polls?|likes?|upvotes?|ratings?|rate|reactions?|react|cheers?|claps?)([/_?-]|$)
31
+ # The handler (or a middleware named in the route) looks at who is calling, or limits them.
32
+ - pattern-not-regex: (?i)(req\.(user|session|auth|ip|cookies|signedCookies|headers)|session|token|cookie|auth|voter|account|userId|user_id|fingerprint|rate.?limit|limiter|throttl|bucket|limited\(|limits\.)
33
+ - pattern-not-inside: |
34
+ import $X from "=~/^(express-rate-limit|rate-limiter-flexible|express-slow-down|express-brute)$/";
35
+ ...
36
+ - pattern-not-inside: |
37
+ import { ... } from "=~/^(express-rate-limit|rate-limiter-flexible|express-slow-down|express-brute)$/";
38
+ ...
39
+ - pattern-not-inside: |
40
+ $X = require("=~/^(express-rate-limit|rate-limiter-flexible|express-slow-down|express-brute)$/");
41
+ ...
42
+ - pattern-not-inside: |
43
+ $X = require("=~/^(express-rate-limit|rate-limiter-flexible|express-slow-down|express-brute)$/").$Y;
44
+ ...
@@ -0,0 +1,59 @@
1
+ // Test cases for nestjs-route-no-throttle and nestjs-global-throttler. Run: opengrep scan --test rules/
2
+ import { Controller, Post, Body, UseGuards, Get, Module } from '@nestjs/common';
3
+ import { APP_GUARD } from '@nestjs/core';
4
+ import { Throttle, ThrottlerGuard } from '@nestjs/throttler';
5
+
6
+ @Controller('auth')
7
+ export class AuthController {
8
+ // ruleid: nestjs-route-no-throttle
9
+ @Post('login')
10
+ async login(@Body() dto: LoginDto) {
11
+ return this.auth.login(dto);
12
+ }
13
+
14
+ // ruleid: nestjs-route-no-throttle
15
+ @Post('reset-password')
16
+ reset(@Body() dto: ResetDto) {}
17
+
18
+ // ok: nestjs-route-no-throttle
19
+ @Throttle({ default: { limit: 5, ttl: 60000 } })
20
+ @Post('register')
21
+ register(@Body() dto: RegisterDto) {}
22
+
23
+ // ok: nestjs-route-no-throttle
24
+ @UseGuards(ThrottlerGuard)
25
+ @Post('verify')
26
+ verify() {}
27
+
28
+ // Reading, not submitting.
29
+ // ok: nestjs-route-no-throttle
30
+ @Get('login')
31
+ page() {}
32
+
33
+ // ok: nestjs-route-no-throttle
34
+ @Post('profile')
35
+ update() {}
36
+ }
37
+
38
+ @Controller('sign-up')
39
+ export class SignupController {
40
+ // ruleid: nestjs-route-no-throttle
41
+ @Post()
42
+ create() {}
43
+ }
44
+
45
+ @UseGuards(ThrottlerGuard)
46
+ @Controller('otp')
47
+ export class OtpController {
48
+ // ok: nestjs-route-no-throttle
49
+ @Post('verify')
50
+ verify() {}
51
+ }
52
+
53
+ @Module({
54
+ providers: [
55
+ // ruleid: nestjs-global-throttler
56
+ { provide: APP_GUARD, useClass: ThrottlerGuard },
57
+ ],
58
+ })
59
+ export class AppModule {}
@@ -0,0 +1,67 @@
1
+ rules:
2
+ - id: nestjs-route-no-throttle
3
+ languages: [typescript]
4
+ severity: WARNING
5
+ message: >-
6
+ This NestJS route accepts sign-ins, sign-ups, joins or codes, and no throttle covers it here. A short script can
7
+ repeat it thousands of times: guess passwords or codes, or create as many accounts as it likes. Add
8
+ @nestjs/throttler: register ThrottlerGuard for the whole app (APP_GUARD) or put @Throttle on this route with a
9
+ low limit, and lock out after repeated failures. If a limit is set somewhere this rule cannot see (the reverse
10
+ proxy), confirm it actually covers this route.
11
+ metadata:
12
+ category: code
13
+ cwe: 'CWE-307: Improper Restriction of Excessive Authentication Attempts'
14
+ asvs: 'OWASP ASVS 5.0 V6.3.1 (brute force), V2.4.1 (anti-automation)'
15
+ confidence: MEDIUM
16
+ # Dropped when the project registers ThrottlerGuard globally (rule nestjs-global-throttler, any file).
17
+ suppressed-by: nestjs-global-throttler
18
+ limitations: >-
19
+ Literal paths only. Does not see a guard of another name that limits requests, or limits at a proxy or CDN.
20
+ patterns:
21
+ - pattern-either:
22
+ - patterns:
23
+ - pattern: |
24
+ @$DEC($PATH)
25
+ $M(...) { ... }
26
+ - metavariable-regex:
27
+ metavariable: $PATH
28
+ regex: (?i).*(log-?in|sign-?in|sign-?up|register|join|otp|verify|forgot|reset|password|passcode|redeem)
29
+ # @Controller('auth/login') with @Post() and no path of its own.
30
+ - patterns:
31
+ - pattern-inside: |
32
+ @Controller($CPATH)
33
+ class $C { ... }
34
+ - pattern: |
35
+ @$DEC()
36
+ $M(...) { ... }
37
+ - metavariable-regex:
38
+ metavariable: $CPATH
39
+ regex: (?i).*(log-?in|sign-?in|sign-?up|register|join|otp|verify|forgot|reset|password|passcode|redeem)
40
+ - metavariable-regex:
41
+ metavariable: $DEC
42
+ regex: ^(Post|Put|Patch|All)$
43
+ - pattern-not: |
44
+ @Throttle(...)
45
+ $M(...) { ... }
46
+ - pattern-not: |
47
+ @UseGuards(..., ThrottlerGuard, ...)
48
+ $M(...) { ... }
49
+ - pattern-not-inside: |
50
+ @Throttle(...)
51
+ class $C2 { ... }
52
+ - pattern-not-inside: |
53
+ @UseGuards(..., ThrottlerGuard, ...)
54
+ class $C2 { ... }
55
+
56
+ - id: nestjs-global-throttler
57
+ languages: [typescript]
58
+ severity: INFO
59
+ message: ThrottlerGuard is registered for the whole app.
60
+ metadata:
61
+ category: code
62
+ # Not a problem: only used to drop nestjs-route-no-throttle findings. Never shown to the user.
63
+ internal: true
64
+ pattern-either:
65
+ - pattern: '{ provide: APP_GUARD, useClass: ThrottlerGuard }'
66
+ - pattern: '{ provide: APP_GUARD, useClass: ThrottlerBehindProxyGuard }'
67
+ - pattern: $APP.useGlobalGuards(..., new ThrottlerGuard(...), ...)
@@ -0,0 +1,124 @@
1
+ import { readdirSync, readFileSync } from 'node:fs';
2
+ import { basename, join } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ // What the check can and cannot read in this project, so a "0 findings" result is never mistaken for "checked".
6
+
7
+ // Installed or generated code: not code the project wrote (same list as the code scanner).
8
+ export const SKIP_DIRS = new Set(['node_modules', '.git', '.audit', 'dist', 'build', '.next', '.nuxt', '.output',
9
+ '.svelte-kit', 'coverage', 'vendor', 'target', '.venv', 'venv', '__pycache__', 'Pods', '.dart_tool']);
10
+
11
+ const LANGUAGES = {
12
+ javascript: ['.js', '.jsx', '.mjs', '.cjs'],
13
+ typescript: ['.ts', '.tsx', '.mts', '.cts'],
14
+ php: ['.php'],
15
+ python: ['.py'],
16
+ go: ['.go'],
17
+ rust: ['.rs'],
18
+ ruby: ['.rb'],
19
+ java: ['.java'],
20
+ kotlin: ['.kt', '.kts'],
21
+ csharp: ['.cs'],
22
+ c: ['.c', '.h'],
23
+ cpp: ['.cpp', '.cc', '.cxx', '.hpp', '.hh'],
24
+ dart: ['.dart'],
25
+ swift: ['.swift'],
26
+ // Single-file components: the JavaScript rules do not read the <script> block inside them.
27
+ vue: ['.vue'],
28
+ svelte: ['.svelte'],
29
+ };
30
+ // Docker Compose files: trivy (the config checker) does not read them, so the report must say they were not checked.
31
+ // compose.yaml, compose.yml, docker-compose.yml, docker-compose.prod.yaml and the like.
32
+ export const isComposeFile = (name) => /^(docker-)?compose(\.[\w-]+)?\.ya?ml$/i.test(name);
33
+
34
+ const BY_EXT = new Map(Object.entries(LANGUAGES).flatMap(([lang, exts]) => exts.map((e) => [e, lang])));
35
+
36
+ // Lockfiles osv-scanner reads, and whether this kit has tested that ecosystem with known-answer cases.
37
+ // Update `tested` only after a probe case for that ecosystem passes (lab/probes/osv-probe.mjs in the private repo).
38
+ export const LOCKFILES = {
39
+ 'package-lock.json': { ecosystem: 'npm', tested: true },
40
+ 'npm-shrinkwrap.json': { ecosystem: 'npm', tested: false },
41
+ 'yarn.lock': { ecosystem: 'npm', tested: false },
42
+ 'pnpm-lock.yaml': { ecosystem: 'npm', tested: false },
43
+ 'bun.lock': { ecosystem: 'npm', tested: false },
44
+ 'composer.lock': { ecosystem: 'Packagist (PHP)', tested: true },
45
+ 'go.mod': { ecosystem: 'Go', tested: true },
46
+ 'Cargo.lock': { ecosystem: 'crates.io (Rust)', tested: true },
47
+ 'Gemfile.lock': { ecosystem: 'RubyGems', tested: true },
48
+ 'packages.lock.json': { ecosystem: 'NuGet (C#)', tested: true },
49
+ 'requirements.txt': { ecosystem: 'PyPI (Python)', tested: true },
50
+ 'poetry.lock': { ecosystem: 'PyPI (Python)', tested: false },
51
+ 'Pipfile.lock': { ecosystem: 'PyPI (Python)', tested: false },
52
+ 'uv.lock': { ecosystem: 'PyPI (Python)', tested: false },
53
+ 'pubspec.lock': { ecosystem: 'Pub (Dart/Flutter)', tested: false },
54
+ 'pom.xml': { ecosystem: 'Maven (Java)', tested: false },
55
+ 'gradle.lockfile': { ecosystem: 'Maven (Java)', tested: false },
56
+ 'conan.lock': { ecosystem: 'ConanCenter (C/C++)', tested: false },
57
+ 'mix.lock': { ecosystem: 'Hex (Elixir)', tested: false },
58
+ };
59
+
60
+ // Languages the kit's own code rules read, taken from the rule files so the list cannot fall behind them.
61
+ export function ruleLanguages(rulesDir = fileURLToPath(new URL('../rules/', import.meta.url))) {
62
+ const langs = new Set();
63
+ for (const f of readdirSync(rulesDir).filter((n) => /\.ya?ml$/.test(n)).sort()) {
64
+ for (const m of readFileSync(join(rulesDir, f), 'utf8').matchAll(/languages:\s*\[([^\]]*)\]/g)) {
65
+ for (const l of m[1].split(',')) langs.add(l.trim());
66
+ }
67
+ }
68
+ return langs;
69
+ }
70
+
71
+ function walk(dir, rel, out, limit) {
72
+ let entries;
73
+ try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
74
+ for (const e of entries.sort((a, b) => (a.name < b.name ? -1 : 1))) {
75
+ if (out.length >= limit) return;
76
+ const path = rel ? `${rel}/${e.name}` : e.name;
77
+ if (e.isDirectory()) { if (!SKIP_DIRS.has(e.name)) walk(join(dir, e.name), path, out, limit); }
78
+ else if (e.isFile()) out.push(path);
79
+ }
80
+ }
81
+
82
+ export function projectCoverage(root, { rulesDir, limit = 200_000 } = {}) {
83
+ const files = [];
84
+ walk(root, '', files, limit);
85
+ const covered = ruleLanguages(rulesDir);
86
+ const counts = new Map();
87
+ const lockfiles = [];
88
+ const compose = [];
89
+ for (const f of files) {
90
+ const name = basename(f);
91
+ const ext = name.includes('.') ? name.slice(name.lastIndexOf('.')).toLowerCase() : '';
92
+ const lang = BY_EXT.get(ext);
93
+ if (lang) counts.set(lang, (counts.get(lang) ?? 0) + 1);
94
+ if (LOCKFILES[name]) lockfiles.push({ file: f, ...LOCKFILES[name] });
95
+ if (isComposeFile(name)) compose.push(f);
96
+ }
97
+ const languages = [...counts].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))
98
+ .map(([language, n]) => ({ language, files: n, code_rules: covered.has(language) }));
99
+ return { languages, lockfiles, compose, truncated: files.length >= limit };
100
+ }
101
+
102
+ // Plain sentences for the report and for the AI assistant. Empty when everything found is covered.
103
+ export function coverageGaps(cov) {
104
+ const gaps = [];
105
+ const noRules = cov.languages.filter((l) => !l.code_rules);
106
+ if (noRules.length) {
107
+ gaps.push(`Code rules: this kit has no rules yet for ${noRules.map((l) => `${l.language} (${l.files} file${l.files === 1 ? "" : "s"})`).join(', ')}. ` +
108
+ 'Code in these languages was not checked for mistakes; "0 findings" says nothing about it. To review it, ask an ' +
109
+ 'AI assistant with the prompt in https://github.com/surapas3022/ai-secure-audit/blob/main/docs/ai-review-prompt.md ' +
110
+ '(its results are leads to check, not findings).');
111
+ }
112
+ const untested = cov.lockfiles.filter((l) => !l.tested);
113
+ if (untested.length) {
114
+ gaps.push(`Libraries: ${untested.map((l) => `${l.file} (${l.ecosystem})`).join(', ')} ` +
115
+ 'were read by osv-scanner, but this kit has not tested that ecosystem with known answers yet.');
116
+ }
117
+ if (cov.compose?.length) {
118
+ gaps.push(`Docker Compose: ${cov.compose.join(', ')} ${cov.compose.length === 1 ? 'was' : 'were'} not checked. trivy reads ` +
119
+ 'Dockerfiles but not Compose files, so settings such as privileged: true, network_mode: host, a mounted ' +
120
+ 'docker.sock or a database port open to every network were not looked at; "0 findings" says nothing about them.');
121
+ }
122
+ if (cov.truncated) gaps.push('The project has more files than this check counts; the lists above may be incomplete.');
123
+ return gaps;
124
+ }
@@ -0,0 +1,107 @@
1
+ // Does a Docker build of the scanned folder take this tool's own results (.audit/) into the image?
2
+ // trivy only reads Dockerfile instructions, so nothing else notices: .audit/ appears on the first scan, and a
3
+ // Dockerfile with COPY . . then ships the list of the app's weak points in every image.
4
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
5
+ import { join, posix } from 'node:path';
6
+
7
+ // The files a scan writes; if any of them gets into the build context, the results do.
8
+ const AUDIT_FILES = ['.audit/out/findings.json', '.audit/out/report.md', '.audit/out/raw/x.json'];
9
+
10
+ const DOCKERFILE = /^(Dockerfile|Containerfile)(\.[\w.-]+)?$|^[\w.-]+\.(Dockerfile|dockerfile)$/;
11
+
12
+ function patternToRegex(p) {
13
+ let re = '';
14
+ for (let i = 0; i < p.length; i++) {
15
+ const c = p[i];
16
+ if (c === '*') {
17
+ if (p[i + 1] === '*') {
18
+ i++;
19
+ if (p[i + 1] === '/') { i++; re += '(?:.*/)?'; } else re += '.*';
20
+ } else re += '[^/]*';
21
+ } else if (c === '?') re += '[^/]';
22
+ else if (c === '[') {
23
+ const end = p.indexOf(']', i + 1);
24
+ if (end < 0) { re += '\\['; continue; }
25
+ re += '[' + p.slice(i + 1, end).replace(/^!/, '^').replace(/\\/g, '\\\\') + ']';
26
+ i = end;
27
+ } else if (c === '\\' && i + 1 < p.length) re += '\\' + p[++i];
28
+ else re += c.replace(/[.+^${}()|]/g, '\\$&');
29
+ }
30
+ return new RegExp(`^${re}$`);
31
+ }
32
+
33
+ // .dockerignore rules as Docker reads them: one pattern per line, # comments, surrounding space trimmed, a leading
34
+ // ! re-includes, paths cleaned (leading /, ./ and trailing / dropped). The last matching line wins.
35
+ export function parseDockerignore(text) {
36
+ const rules = [];
37
+ for (let line of text.split(/\r?\n/)) {
38
+ line = line.trim();
39
+ if (!line || line.startsWith('#')) continue;
40
+ const negate = line.startsWith('!');
41
+ if (negate) line = line.slice(1).trim();
42
+ let p = posix.normalize(line).replace(/^\/+/, '').replace(/\/+$/, '');
43
+ if (!p || p === '.') continue;
44
+ rules.push({ negate, re: patternToRegex(p) });
45
+ }
46
+ return rules;
47
+ }
48
+
49
+ // A path is excluded when a pattern matches it or one of its parent folders.
50
+ export function isExcluded(rules, file) {
51
+ const parts = file.split('/');
52
+ const paths = parts.map((_, i) => parts.slice(0, i + 1).join('/'));
53
+ let excluded = false;
54
+ for (const r of rules) if (paths.some((p) => r.re.test(p))) excluded = !r.negate;
55
+ return excluded;
56
+ }
57
+
58
+ // COPY or ADD whose sources include the whole context: ".", "./", "*" or "./*" (shell or JSON form).
59
+ export function copiesWholeFolder(dockerfile) {
60
+ const text = dockerfile.replace(/\\\r?\n/g, ' ');
61
+ for (const line of text.split(/\r?\n/)) {
62
+ const m = /^\s*(?:COPY|ADD)\s+(.*)$/i.exec(line);
63
+ if (!m) continue;
64
+ let rest = m[1].trim();
65
+ while (/^--\S+/.test(rest)) rest = rest.replace(/^--\S+\s*/, '');
66
+ if (/--from=/i.test(m[1])) continue; // copies from another stage, not from the folder
67
+ let args;
68
+ if (rest.startsWith('[')) {
69
+ try { args = JSON.parse(rest); } catch { continue; }
70
+ } else args = rest.split(/\s+/);
71
+ if (args.slice(0, -1).some((a) => ['.', './', '*', './*'].includes(a))) return true;
72
+ }
73
+ return false;
74
+ }
75
+
76
+ // One notice per Dockerfile at the top of the scanned folder (the usual build context) that would ship .audit/.
77
+ // Not checked: Dockerfiles in subfolders built with a context above them (compose build.context: ..).
78
+ export function dockerignoreNotices(root) {
79
+ let names;
80
+ try { names = readdirSync(root); } catch { return []; }
81
+ const notices = [];
82
+ for (const name of names.filter((n) => DOCKERFILE.test(n)).sort()) {
83
+ let text;
84
+ try { text = readFileSync(join(root, name), 'utf8'); } catch { continue; }
85
+ if (!copiesWholeFolder(text)) continue;
86
+ // BuildKit reads <Dockerfile>.dockerignore next to the Dockerfile first, then .dockerignore.
87
+ const own = `${name}.dockerignore`;
88
+ const ignoreFile = existsSync(join(root, own)) ? own : existsSync(join(root, '.dockerignore')) ? '.dockerignore' : null;
89
+ if (!ignoreFile) {
90
+ notices.push({
91
+ id: 'dockerignore-audit', file: name,
92
+ message: `${name} copies the whole folder and there is no .dockerignore, so this check's results in .audit/ ` +
93
+ '(a list of the app\'s weak points) go into the image, together with .env, .git and anything else in the ' +
94
+ 'folder. Add a .dockerignore with at least these lines: .audit, .env, .git',
95
+ });
96
+ continue;
97
+ }
98
+ const rules = parseDockerignore(readFileSync(join(root, ignoreFile), 'utf8'));
99
+ if (AUDIT_FILES.every((f) => isExcluded(rules, f))) continue;
100
+ notices.push({
101
+ id: 'dockerignore-audit', file: name,
102
+ message: `${name} copies the whole folder and ${ignoreFile} does not exclude .audit/, so this check's results ` +
103
+ `(a list of the app's weak points) go into the image. Add the line .audit to ${ignoreFile}.`,
104
+ });
105
+ }
106
+ return notices;
107
+ }
package/src/report.js CHANGED
@@ -14,6 +14,10 @@ const PLAIN = {
14
14
  what: 'A setting in your Docker or infrastructure files is unsafe.',
15
15
  why: 'Unsafe defaults make a break-in easier or do more damage once someone is in.',
16
16
  },
17
+ code: {
18
+ what: 'Your code has a pattern that apps built with AI often get wrong.',
19
+ why: 'These mistakes are easy to find from the outside, and a short script is enough to use them.',
20
+ },
17
21
  };
18
22
 
19
23
  function where(f) {
@@ -24,7 +28,7 @@ function whereSentence(f) {
24
28
  return f.evidence.map((e) => {
25
29
  const commits = e.commits?.length ? ` (commit ${e.commits.join(', ')})` : '';
26
30
  if (e.history_only) {
27
- return `\`${e.location}\`. This file is no longer in your project, but it is still in git history${commits}, ` +
31
+ return `\`${e.location}\`. This key is no longer in the files of your project, but it is still in git history${commits}, ` +
28
32
  'so anyone with a copy of the repository can still read it';
29
33
  }
30
34
  if (e.not_committed) return `\`${e.location}\`. This is not in git yet, so you can still keep it out of your history`;
@@ -77,6 +81,22 @@ export function reportMarkdown(result, date) {
77
81
  lines.push('');
78
82
  }
79
83
 
84
+ // Medium and low findings still need a fix written out, not only a row in the table.
85
+ const rest = findings.filter((f) => !top.includes(f) && f.fix).slice(0, 10);
86
+ if (rest.length) {
87
+ lines.push(top.length ? '## Then check these' : '## Check these');
88
+ lines.push('');
89
+ for (const f of rest) {
90
+ const p = PLAIN[f.category] ?? {};
91
+ lines.push(`### ${f.id}: ${f.title}`);
92
+ lines.push('');
93
+ if (p.what) lines.push(`**What is wrong:** ${p.what} Found at ${whereSentence(f)}.`);
94
+ if (f.category === 'code') lines.push('**Check first:** this comes from a code rule, which can be wrong. Look at the code before changing it.');
95
+ lines.push(`**How to fix it:** ${f.fix}`);
96
+ lines.push('');
97
+ }
98
+ }
99
+
80
100
  if (findings.length) {
81
101
  lines.push('## All findings');
82
102
  lines.push('');
@@ -88,13 +108,20 @@ export function reportMarkdown(result, date) {
88
108
  lines.push('');
89
109
  }
90
110
 
111
+ if (result.notices?.length) {
112
+ lines.push('## About these results');
113
+ lines.push('');
114
+ for (const n of result.notices) lines.push(`- ${n.message}`);
115
+ lines.push('');
116
+ }
117
+
91
118
  lines.push('## What this check could not see');
92
119
  lines.push('');
93
120
  lines.push('- Whether one user can open or change another user\'s data (for example by changing an id in the URL)');
94
121
  lines.push('- Business rules: prices, coupons, approvals, payments');
95
122
  lines.push('- Database rules such as Supabase row-level security or Firebase security rules (planned)');
96
123
  lines.push('- Anything about the live server or website');
97
- lines.push('- Docker/config mistakes: not in this version yet (coming in v0.3)');
124
+ for (const g of result.coverage?.gaps ?? []) lines.push(`- ${g}`);
98
125
  lines.push('');
99
126
  lines.push('## Tools');
100
127
  lines.push('');
@@ -119,8 +146,11 @@ export function consoleSummary(result, outRel) {
119
146
  '- Ask before changing code. Fix one finding at a time; run `npx ai-secure-audit retest` after.',
120
147
  '- Use each finding\'s fix field. A key that is in git or was deployed must be rotated at the provider: deleting it from the code is not enough.',
121
148
  '- A finding marked not_committed can be moved out of the code without rotating, unless the key was shared or pasted somewhere else.',
122
- '- Not checked: whether one user can reach another user\'s data, business rules, and (in this version)',
123
- ' Docker/config files. Say so.',
149
+ '- Findings of type code come from pattern rules and can be wrong. Read the code at that location and tell the user',
150
+ ' if a limit or check exists somewhere the rule cannot see (another file, the proxy) before changing anything.',
151
+ '- Not checked: whether one user can reach another user\'s data, and business rules. Say so.',
152
+ ...(result.coverage?.gaps ?? []).map((g) => `- ${g} Tell the user.`),
153
+ ...(result.notices ?? []).map((n) => `- ${n.message} Tell the user, and ask before editing the file.`),
124
154
  ...(failed.length ? ['- Some tools did not run (see NOT RUN above). Tell the user the check is incomplete.'] : []),
125
155
  ].join('\n');
126
156
  }
package/src/scan.js CHANGED
@@ -3,12 +3,16 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
3
  import { join, resolve } from 'node:path';
4
4
  import { cacheDir, ensureTool, lockedTools } from './tools.js';
5
5
  import { sortAndNumber } from './findings.js';
6
+ import { coverageGaps, projectCoverage } from './coverage.js';
7
+ import { dockerignoreNotices } from './dockerignore.js';
6
8
  import gitleaks from './scanners/gitleaks.js';
7
9
  import osv from './scanners/osv.js';
10
+ import opengrep from './scanners/opengrep.js';
11
+ import trivy from './scanners/trivy.js';
8
12
 
9
13
  // Scanners are released one at a time, each after passing its own tests (see CLAUDE.md).
10
14
  // Scanners still in development are kept outside this repository until they pass.
11
- export const BASIC_SCANNERS = [gitleaks, osv];
15
+ export const BASIC_SCANNERS = [gitleaks, osv, opengrep, trivy];
12
16
 
13
17
  function git(root, args) {
14
18
  const r = spawnSync('git', ['-C', root, ...args], { encoding: 'utf8' });
@@ -77,14 +81,20 @@ export async function scan(target, { log = () => {}, version }) {
77
81
  }
78
82
  }
79
83
 
84
+ const coverage = projectCoverage(root);
80
85
  const result = {
81
86
  generator: `ai-secure-audit ${version}`,
82
87
  check: 'basic',
83
88
  target: { git: isGit, commit: ctx.commit, uncommitted_changes: ctx.dirty },
84
89
  tools: runs,
90
+ coverage: { ...coverage, gaps: coverageGaps(coverage) },
91
+ // About this tool's own output, not a weakness of the app: kept apart from findings so it is never rated.
92
+ notices: dockerignoreNotices(root),
85
93
  notes: [
86
94
  'Not checked by this tool: whether one user can reach another user\'s data, business rules, and anything running on a server.',
87
- `Not checked yet in this version: Docker/config files (trivy, coming in v0.3).`,
95
+ 'Code rules (category code) are this kit\'s own opengrep rules. They can be wrong: check the location before changing code.',
96
+ 'Config files are checked by trivy: Dockerfiles, Kubernetes, Helm, Terraform, CloudFormation, Azure ARM and Ansible files. ' +
97
+ 'trivy does not read Docker Compose files; coverage.gaps names any that were not checked.',
88
98
  ],
89
99
  findings: sortAndNumber(findings),
90
100
  };
@@ -74,6 +74,8 @@ export default {
74
74
  parse(json, ctx) {
75
75
  const prefix = ctx.prefix ?? '';
76
76
  const groups = new Map();
77
+ // Rule and file pairs the files pass saw, counted before the ignore filter: a key still on disk is not "history only".
78
+ const inFiles = new Set();
77
79
  for (const leak of json ?? []) {
78
80
  const fromFiles = leak.pass === 'files';
79
81
  let file = rel(ctx.root, leak.File);
@@ -82,6 +84,7 @@ export default {
82
84
  if (!file.startsWith(prefix)) continue;
83
85
  file = file.slice(prefix.length);
84
86
  }
87
+ if (fromFiles) inFiles.add(`${leak.RuleID}:${file}`);
85
88
  const kind = fileKind(file);
86
89
  if (kind === 'internal') continue;
87
90
  // A file git ignores stays on this machine. Build output is the exception: it gets deployed.
@@ -93,11 +96,16 @@ export default {
93
96
  groups.set(key, g);
94
97
  }
95
98
  const fileExists = ctx.fileExists ?? ((f) => existsSync(join(ctx.root, f)));
99
+ const filesPassRan = (json ?? []).some((l) => l.pass);
96
100
  return [...groups].map(([key, { leak, file, kind, commits, inHistory }]) => {
97
101
  const commitList = [...commits].sort();
98
- // A secret in a file that no longer exists is only in git history. Say so: people look for the file and
99
- // cannot find it, then think the tool is wrong.
100
- const historyOnly = ctx.isGit !== false && !fileExists(file);
102
+ // A secret that is no longer in the current files is only in git history: the file was deleted, or the key was
103
+ // taken out of a file that is still there. Say so: people look for it, cannot find it, then think the tool is
104
+ // wrong. The files pass decides when it ran (it always does when there is history); otherwise fall back to
105
+ // whether the file exists. The same rule anywhere in the same file counts as still there, so a key that only
106
+ // moved to another line is never called history only.
107
+ const historyOnly = ctx.isGit !== false && inHistory && !inFiles.has(`${leak.RuleID}:${file}`) &&
108
+ (filesPassRan || !fileExists(file));
101
109
  const built = kind === 'built';
102
110
  const notCommitted = Boolean(ctx.isGit) && !inHistory && !built;
103
111
  const guess = built && leak.RuleID === 'generic-api-key';
@@ -0,0 +1,59 @@
1
+ import { readdirSync } from 'node:fs';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { rel } from '../paths.js';
4
+
5
+ // This kit's own rules, shipped in the package. Rules from the Semgrep Registry are not used: their license is not
6
+ // open source (see README).
7
+ const RULES = fileURLToPath(new URL('../../rules/', import.meta.url));
8
+
9
+ // Folders that hold installed or generated code, not code the project wrote.
10
+ const EXCLUDE = ['node_modules', '.git', '.audit', 'dist', 'build', '.next', '.nuxt', '.output', '.svelte-kit',
11
+ 'coverage', 'vendor'];
12
+
13
+ // Each rule has a test file beside it (same name, code extension) full of deliberate matches. Never scan those,
14
+ // or a project that contains this kit (this repository, a vendored copy) reports its own test cases.
15
+ const RULE_TESTS = readdirSync(RULES).filter((f) => !/\.ya?ml$/.test(f));
16
+
17
+ const SEVERITY = { ERROR: 'high', WARNING: 'medium', INFO: 'low' };
18
+
19
+ export default {
20
+ id: 'opengrep',
21
+ category: 'code',
22
+
23
+ // Local rules only, no version check: nothing about the project leaves the machine.
24
+ // --no-git-ignore: code that is not committed yet is still code that will run.
25
+ args(ctx, out) {
26
+ return ['scan', '--config', RULES, '--json', '--output', out, '--disable-version-check', '--quiet',
27
+ '--no-git-ignore', ...[...EXCLUDE, ...RULE_TESTS].flatMap((d) => ['--exclude', d]), ctx.root];
28
+ },
29
+
30
+ okExit: [0],
31
+
32
+ parse(json, ctx) {
33
+ // opengrep prefixes the rule id with the config path, joined by dots; our rule ids have no dots.
34
+ const results = (json?.results ?? []).map((r) => ({ ...r, ruleId: r.check_id.split('.').at(-1) }));
35
+ // Internal rules are never shown: they only record that something exists anywhere in the project (for example a
36
+ // throttle registered for the whole app), and a rule with suppressed-by: <id> is dropped when that rule matched.
37
+ const seen = new Set(results.filter((r) => r.extra?.metadata?.internal).map((r) => r.ruleId));
38
+ const findings = [];
39
+ for (const r of results) {
40
+ const meta = r.extra?.metadata ?? {};
41
+ if (meta.internal || (meta['suppressed-by'] && seen.has(meta['suppressed-by']))) continue;
42
+ const ruleId = r.ruleId;
43
+ const location = `${rel(ctx.root, r.path)}:${r.start.line}`;
44
+ const [title, ...rest] = (r.extra?.message ?? ruleId).split('. ');
45
+ findings.push({
46
+ fingerprint: `opengrep:${ruleId}:${location}`,
47
+ category: 'code',
48
+ title,
49
+ severity: { tool: r.extra?.severity ?? 'WARNING', normalized: SEVERITY[r.extra?.severity] ?? 'medium' },
50
+ source: { kind: 'tool', tool: 'opengrep', rule_id: ruleId },
51
+ // Only the first line of the match: enough to find it, without copying the handler body.
52
+ evidence: [{ location, detail: (r.extra?.lines ?? '').split('\n')[0].trim().slice(0, 160) }],
53
+ fix: rest.join('. '),
54
+ references: { cwe: meta.cwe ?? null, asvs: meta.asvs ?? null, confidence: meta.confidence ?? null },
55
+ });
56
+ }
57
+ return findings;
58
+ },
59
+ };
@@ -28,7 +28,11 @@ function fixedVersion(vulns, pkgName) {
28
28
  for (const v of vulns) {
29
29
  for (const a of v.affected ?? []) {
30
30
  if (a.package?.name !== pkgName) continue;
31
- for (const r of a.ranges ?? []) for (const e of r.events ?? []) if (e.fixed) fixed.push(e.fixed);
31
+ // GIT ranges give commit hashes, not versions a user can install.
32
+ for (const r of a.ranges ?? []) {
33
+ if (r.type === 'GIT') continue;
34
+ for (const e of r.events ?? []) if (e.fixed) fixed.push(e.fixed);
35
+ }
32
36
  }
33
37
  }
34
38
  return fixed.sort(compareVersions).at(-1) ?? null;
@@ -0,0 +1,40 @@
1
+ import { join } from 'node:path';
2
+ import { rel } from '../paths.js';
3
+
4
+ export default {
5
+ id: 'trivy',
6
+ category: 'config',
7
+
8
+ // --skip-check-update keeps the checks built into the pinned trivy version, so results do not drift.
9
+ args(ctx, out) {
10
+ return ['config', '--format', 'json', '--output', out, '--skip-check-update', '--quiet',
11
+ '--cache-dir', join(ctx.cache, 'trivy'),
12
+ '--skip-dirs', '**/node_modules', '--skip-dirs', '**/.git', ctx.root];
13
+ },
14
+
15
+ okExit: [0],
16
+
17
+ parse(json, ctx) {
18
+ const findings = [];
19
+ for (const result of json?.Results ?? []) {
20
+ const file = rel(ctx.root, result.Target);
21
+ for (const m of result.Misconfigurations ?? []) {
22
+ if (m.Status !== 'FAIL') continue;
23
+ const line = m.CauseMetadata?.StartLine;
24
+ const location = line ? `${file}:${line}` : file;
25
+ const sev = (m.Severity ?? 'UNKNOWN').toLowerCase();
26
+ findings.push({
27
+ fingerprint: `trivy:${m.ID}:${location}`,
28
+ category: 'config',
29
+ title: m.Title,
30
+ severity: { tool: m.Severity, normalized: ['critical', 'high', 'medium', 'low'].includes(sev) ? sev : 'medium' },
31
+ source: { kind: 'tool', tool: 'trivy', rule_id: m.ID },
32
+ evidence: [{ location, detail: m.Message }],
33
+ fix: m.Resolution,
34
+ references: { urls: m.PrimaryURL ? [m.PrimaryURL] : [] },
35
+ });
36
+ }
37
+ }
38
+ return findings;
39
+ },
40
+ };
package/src/tools.js CHANGED
@@ -11,8 +11,14 @@ export function lockedTools() {
11
11
  return lock.tools;
12
12
  }
13
13
 
14
+ // Linux without glibc (Alpine and other musl systems) needs builds of its own for tools that are not static.
15
+ export function isMusl() {
16
+ if (process.platform !== 'linux') return false;
17
+ return !process.report?.getReport?.().header?.glibcVersionRuntime;
18
+ }
19
+
14
20
  export function platformKey() {
15
- return `${process.platform}-${process.arch}`;
21
+ return `${process.platform}-${process.arch}${isMusl() ? '-musl' : ''}`;
16
22
  }
17
23
 
18
24
  export function cacheDir() {
package/tools.lock.json CHANGED
@@ -30,6 +30,18 @@
30
30
  "archive": "tar.gz",
31
31
  "binary": "gitleaks"
32
32
  },
33
+ "linux-arm64-musl": {
34
+ "url": "https://github.com/gitleaks/gitleaks/releases/download/v8.30.1/gitleaks_8.30.1_linux_arm64.tar.gz",
35
+ "sha256": "e4a487ee7ccd7d3a7f7ec08657610aa3606637dab924210b3aee62570fb4b080",
36
+ "archive": "tar.gz",
37
+ "binary": "gitleaks"
38
+ },
39
+ "linux-x64-musl": {
40
+ "url": "https://github.com/gitleaks/gitleaks/releases/download/v8.30.1/gitleaks_8.30.1_linux_x64.tar.gz",
41
+ "sha256": "551f6fc83ea457d62a0d98237cbad105af8d557003051f41f3e7ca7b3f2470eb",
42
+ "archive": "tar.gz",
43
+ "binary": "gitleaks"
44
+ },
33
45
  "win32-arm64": {
34
46
  "url": "https://github.com/gitleaks/gitleaks/releases/download/v8.30.1/gitleaks_8.30.1_windows_arm64.zip",
35
47
  "sha256": "b95f5e4f5c425cedca7ee203d9afd29597e692c4924a12ed42f970537c72cc0f",
@@ -73,6 +85,18 @@
73
85
  "archive": "raw",
74
86
  "binary": "osv-scanner_linux_amd64"
75
87
  },
88
+ "linux-arm64-musl": {
89
+ "url": "https://github.com/google/osv-scanner/releases/download/v2.7.0/osv-scanner_linux_arm64",
90
+ "sha256": "4061ef4c021ed3c47f203b818f337e351336cc5cd67c0274fc36bd1dfc728dd7",
91
+ "archive": "raw",
92
+ "binary": "osv-scanner_linux_arm64"
93
+ },
94
+ "linux-x64-musl": {
95
+ "url": "https://github.com/google/osv-scanner/releases/download/v2.7.0/osv-scanner_linux_amd64",
96
+ "sha256": "160c6253e2922e9e0a6a9771c5c4c40a4b3c6090b34a3cdd5e80c96cc2e4218b",
97
+ "archive": "raw",
98
+ "binary": "osv-scanner_linux_amd64"
99
+ },
76
100
  "win32-arm64": {
77
101
  "url": "https://github.com/google/osv-scanner/releases/download/v2.7.0/osv-scanner_windows_arm64.exe",
78
102
  "sha256": "3e630381c1f1fd3c9c4d447e6ff2ef6c737083371722773db8337eead0f97962",
@@ -86,6 +110,116 @@
86
110
  "binary": "osv-scanner_windows_amd64.exe"
87
111
  }
88
112
  }
113
+ },
114
+ "opengrep": {
115
+ "version": "1.33.1",
116
+ "license": "LGPL-2.1",
117
+ "repo": "https://github.com/opengrep/opengrep",
118
+ "platforms": {
119
+ "darwin-arm64": {
120
+ "url": "https://github.com/opengrep/opengrep/releases/download/v1.33.1/opengrep_osx_arm64",
121
+ "sha256": "a17c1881bb40e3214266a7a291cf4f2ae3bc56c1715628b5712d2ec816bc3e2d",
122
+ "archive": "raw",
123
+ "binary": "opengrep_osx_arm64"
124
+ },
125
+ "darwin-x64": {
126
+ "url": "https://github.com/opengrep/opengrep/releases/download/v1.33.1/opengrep_osx_x86",
127
+ "sha256": "c3bd18e0d898d44e28419d95dad57c8928bb46ab32889a0ee1f72a87ad9627af",
128
+ "archive": "raw",
129
+ "binary": "opengrep_osx_x86"
130
+ },
131
+ "linux-arm64": {
132
+ "url": "https://github.com/opengrep/opengrep/releases/download/v1.33.1/opengrep_manylinux_aarch64",
133
+ "sha256": "d1433f63a90b8bc0b6ad4b498a13b372b856ce9a754a43484ba4920fe2d76dcf",
134
+ "archive": "raw",
135
+ "binary": "opengrep_manylinux_aarch64"
136
+ },
137
+ "linux-x64": {
138
+ "url": "https://github.com/opengrep/opengrep/releases/download/v1.33.1/opengrep_manylinux_x86",
139
+ "sha256": "46e8133cc490f9f50518061590ce2f6be5a08afaeda034471c0ceda4b3899808",
140
+ "archive": "raw",
141
+ "binary": "opengrep_manylinux_x86"
142
+ },
143
+ "linux-arm64-musl": {
144
+ "url": "https://github.com/opengrep/opengrep/releases/download/v1.33.1/opengrep_musllinux_aarch64",
145
+ "sha256": "17c6917b53d8f8af794d8effb13c1a068018c602435d33fefc105aaa23d96f4b",
146
+ "archive": "raw",
147
+ "binary": "opengrep_musllinux_aarch64"
148
+ },
149
+ "linux-x64-musl": {
150
+ "url": "https://github.com/opengrep/opengrep/releases/download/v1.33.1/opengrep_musllinux_x86",
151
+ "sha256": "aa03c3bfff105dc122cbbe6e239dc39a5cae486f1837bba3af7a16bca173f8d6",
152
+ "archive": "raw",
153
+ "binary": "opengrep_musllinux_x86"
154
+ },
155
+ "win32-arm64": {
156
+ "url": "https://github.com/opengrep/opengrep/releases/download/v1.33.1/opengrep_windows_x86.exe",
157
+ "sha256": "132e606e071bdd3928286fddc893198a6106a90820d46e21197e0ace1a23e0c1",
158
+ "archive": "raw",
159
+ "binary": "opengrep_windows_x86.exe"
160
+ },
161
+ "win32-x64": {
162
+ "url": "https://github.com/opengrep/opengrep/releases/download/v1.33.1/opengrep_windows_x86.exe",
163
+ "sha256": "132e606e071bdd3928286fddc893198a6106a90820d46e21197e0ace1a23e0c1",
164
+ "archive": "raw",
165
+ "binary": "opengrep_windows_x86.exe"
166
+ }
167
+ }
168
+ },
169
+ "trivy": {
170
+ "version": "0.76.1",
171
+ "license": "Apache-2.0",
172
+ "repo": "https://github.com/aquasecurity/trivy",
173
+ "platforms": {
174
+ "darwin-arm64": {
175
+ "url": "https://github.com/aquasecurity/trivy/releases/download/v0.76.1/trivy_0.76.1_macOS-ARM64.tar.gz",
176
+ "sha256": "11a9b6cd2752011b54f01ea4bd0dbfa9f0c41dc6538d5a3f9d23955f471bf4e5",
177
+ "archive": "tar.gz",
178
+ "binary": "trivy"
179
+ },
180
+ "darwin-x64": {
181
+ "url": "https://github.com/aquasecurity/trivy/releases/download/v0.76.1/trivy_0.76.1_macOS-64bit.tar.gz",
182
+ "sha256": "7aa762eacd582052d053b62dcf972a1ab058abe39a57ccae234ed8894945b6b7",
183
+ "archive": "tar.gz",
184
+ "binary": "trivy"
185
+ },
186
+ "linux-arm64": {
187
+ "url": "https://github.com/aquasecurity/trivy/releases/download/v0.76.1/trivy_0.76.1_Linux-ARM64.tar.gz",
188
+ "sha256": "e174dff2a6dba5e3ae41f8d0537a6324405bd08132497340304c6b20e0f16a1f",
189
+ "archive": "tar.gz",
190
+ "binary": "trivy"
191
+ },
192
+ "linux-x64": {
193
+ "url": "https://github.com/aquasecurity/trivy/releases/download/v0.76.1/trivy_0.76.1_Linux-64bit.tar.gz",
194
+ "sha256": "c7cbe3137fb8a48a17574bede3dd6beb16742d1e9772929940fc90082c39d9c0",
195
+ "archive": "tar.gz",
196
+ "binary": "trivy"
197
+ },
198
+ "linux-arm64-musl": {
199
+ "url": "https://github.com/aquasecurity/trivy/releases/download/v0.76.1/trivy_0.76.1_Linux-ARM64.tar.gz",
200
+ "sha256": "e174dff2a6dba5e3ae41f8d0537a6324405bd08132497340304c6b20e0f16a1f",
201
+ "archive": "tar.gz",
202
+ "binary": "trivy"
203
+ },
204
+ "linux-x64-musl": {
205
+ "url": "https://github.com/aquasecurity/trivy/releases/download/v0.76.1/trivy_0.76.1_Linux-64bit.tar.gz",
206
+ "sha256": "c7cbe3137fb8a48a17574bede3dd6beb16742d1e9772929940fc90082c39d9c0",
207
+ "archive": "tar.gz",
208
+ "binary": "trivy"
209
+ },
210
+ "win32-arm64": {
211
+ "url": "https://github.com/aquasecurity/trivy/releases/download/v0.76.1/trivy_0.76.1_windows-64bit.zip",
212
+ "sha256": "1051f49cb22d5284f43425f72aad9cda63ca12ceb92e7caa06903490c82dc9bf",
213
+ "archive": "zip",
214
+ "binary": "trivy.exe"
215
+ },
216
+ "win32-x64": {
217
+ "url": "https://github.com/aquasecurity/trivy/releases/download/v0.76.1/trivy_0.76.1_windows-64bit.zip",
218
+ "sha256": "1051f49cb22d5284f43425f72aad9cda63ca12ceb92e7caa06903490c82dc9bf",
219
+ "archive": "zip",
220
+ "binary": "trivy.exe"
221
+ }
222
+ }
89
223
  }
90
224
  }
91
225
  }