@interlace/eslint-devkit 1.8.0 → 1.9.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/package.json +1 -1
- package/src/rule-creation/browser-escape-hatch-rule.d.ts +72 -0
- package/src/rule-creation/browser-escape-hatch-rule.js +100 -0
- package/src/rule-creation/hardcoded-credentials-rule.d.ts +81 -0
- package/src/rule-creation/hardcoded-credentials-rule.js +143 -0
- package/src/rule-creation/index.d.ts +5 -0
- package/src/rule-creation/index.js +5 -0
- package/src/rule-creation/mass-assignment-rule.d.ts +79 -0
- package/src/rule-creation/mass-assignment-rule.js +121 -0
- package/src/rule-creation/raw-identifier-rule.d.ts +127 -0
- package/src/rule-creation/raw-identifier-rule.js +140 -0
- package/src/rule-creation/require-tls-rule.d.ts +1 -1
- package/src/rule-creation/sdk-api-key-rule.d.ts +108 -0
- package/src/rule-creation/sdk-api-key-rule.js +121 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@interlace/eslint-devkit",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.9.0",
|
|
4
4
|
"description": "Toolkit for building ESLint plugins in TypeScript — AST helpers, type utilities, rule-creation scaffolding, security benchmarks, and SARIF output.",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) 2025 Ofri Peretz
|
|
3
|
+
* Licensed under the MIT License. Use of this source code is governed by the
|
|
4
|
+
* MIT license that can be found in the LICENSE file.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* @fileoverview Shared CWE-522 detector — an inference SDK's browser escape
|
|
8
|
+
* hatch turned on.
|
|
9
|
+
*
|
|
10
|
+
* Both the OpenAI and Anthropic Node SDKs refuse to run in a browser by
|
|
11
|
+
* default, and both unlock it with the same opt-in flag. Turning it on means
|
|
12
|
+
* the API key is shipped to the client and is readable by anyone who opens
|
|
13
|
+
* devtools; a leaked key is billable by whoever finds it.
|
|
14
|
+
*
|
|
15
|
+
* ## Which SDKs this can cover, and which it cannot
|
|
16
|
+
*
|
|
17
|
+
* Verified against the published tarballs (2026-08-05), not assumed:
|
|
18
|
+
*
|
|
19
|
+
* | SDK | Flag |
|
|
20
|
+
* |---|---|
|
|
21
|
+
* | `openai@6` | `dangerouslyAllowBrowser` |
|
|
22
|
+
* | `@anthropic-ai/sdk@0.115` | `dangerouslyAllowBrowser` (`client.d.ts:140`) |
|
|
23
|
+
* | `@google/generative-ai@0.24` | none |
|
|
24
|
+
* | `@google/genai@2.15` | none |
|
|
25
|
+
*
|
|
26
|
+
* Neither Gemini SDK has a browser escape hatch, because neither refuses the
|
|
27
|
+
* browser in the first place — there is no flag to detect and no equivalent
|
|
28
|
+
* structural signal a linter can read without knowing whether the file ships
|
|
29
|
+
* to a client. So this factory has two instantiations, not three. Inventing a
|
|
30
|
+
* fuzzy third would report correct code.
|
|
31
|
+
*
|
|
32
|
+
* The gate compares against an exact SDK module specifier, which by the
|
|
33
|
+
* taxonomy contract keeps it in the SDK's plugin rather than in
|
|
34
|
+
* `browser-security`.
|
|
35
|
+
*/
|
|
36
|
+
import type { TSESTree } from '@typescript-eslint/utils';
|
|
37
|
+
/** The opt-in both SDKs spell identically. */
|
|
38
|
+
export declare const BROWSER_ESCAPE_FLAG = "dangerouslyAllowBrowser";
|
|
39
|
+
export interface BrowserEscapeHatchRuleConfig {
|
|
40
|
+
/** Rule id, e.g. `no-browser-api-key-exposure`. */
|
|
41
|
+
ruleName: string;
|
|
42
|
+
/** Vendor name for the message, e.g. `OpenAI`. */
|
|
43
|
+
vendor: string;
|
|
44
|
+
/** Module names that open the gate — exact specifier or subpath. */
|
|
45
|
+
modules: readonly string[];
|
|
46
|
+
/** Rule documentation URL. */
|
|
47
|
+
docsUrl: string;
|
|
48
|
+
/** Vendor documentation link carried in the message. */
|
|
49
|
+
documentationLink: string;
|
|
50
|
+
}
|
|
51
|
+
export type FlagVerdict = 'enabled' | 'absent' | 'unreadable';
|
|
52
|
+
/**
|
|
53
|
+
* Whether the client options literal turns the browser escape hatch on.
|
|
54
|
+
*
|
|
55
|
+
* A non-literal value is `unreadable` — `{ dangerouslyAllowBrowser: isBrowser }`
|
|
56
|
+
* could be either at runtime, and reporting on a guess would flag correct code.
|
|
57
|
+
* An explicit `false` is `absent`: the author already made the safe choice.
|
|
58
|
+
*
|
|
59
|
+
* Spreads are positional, not fatal. Only a spread that can *override* the flag
|
|
60
|
+
* hides it:
|
|
61
|
+
*
|
|
62
|
+
* { ...base } → unreadable, base may set it
|
|
63
|
+
* { dangerouslyAllowBrowser: true, ...base } → unreadable, base may unset it
|
|
64
|
+
* { ...base, dangerouslyAllowBrowser: true } → ENABLED — the explicit key
|
|
65
|
+
* wins, whatever base held
|
|
66
|
+
*
|
|
67
|
+
* Bailing on the first spread seen made that last shape silent, which is a
|
|
68
|
+
* false negative on a definite finding rather than caution about an
|
|
69
|
+
* ambiguous one.
|
|
70
|
+
*/
|
|
71
|
+
export declare function readFlag(options: TSESTree.ObjectExpression): FlagVerdict;
|
|
72
|
+
export declare function createBrowserEscapeHatchRule(config: BrowserEscapeHatchRuleConfig): import("./rule-creator").RuleModuleWithName<"browserKeyExposure", [], unknown>;
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.BROWSER_ESCAPE_FLAG = void 0;
|
|
4
|
+
exports.readFlag = readFlag;
|
|
5
|
+
exports.createBrowserEscapeHatchRule = createBrowserEscapeHatchRule;
|
|
6
|
+
const rule_creator_1 = require("./rule-creator");
|
|
7
|
+
const messaging_1 = require("../messaging");
|
|
8
|
+
const sdk_api_key_rule_1 = require("./sdk-api-key-rule");
|
|
9
|
+
exports.BROWSER_ESCAPE_FLAG = 'dangerouslyAllowBrowser';
|
|
10
|
+
function isFlagProperty(prop) {
|
|
11
|
+
return (prop.type !== 'SpreadElement' &&
|
|
12
|
+
!prop.computed &&
|
|
13
|
+
((prop.key.type === 'Identifier' && prop.key.name === exports.BROWSER_ESCAPE_FLAG) ||
|
|
14
|
+
(prop.key.type === 'Literal' && prop.key.value === exports.BROWSER_ESCAPE_FLAG)));
|
|
15
|
+
}
|
|
16
|
+
function readFlag(options) {
|
|
17
|
+
const props = options.properties;
|
|
18
|
+
const index = props.findIndex(isFlagProperty);
|
|
19
|
+
if (index === -1) {
|
|
20
|
+
return props.some((prop) => prop.type === 'SpreadElement') ? 'unreadable' : 'absent';
|
|
21
|
+
}
|
|
22
|
+
for (let i = index + 1; i < props.length; i++) {
|
|
23
|
+
if (props[i].type === 'SpreadElement')
|
|
24
|
+
return 'unreadable';
|
|
25
|
+
}
|
|
26
|
+
const value = props[index].value;
|
|
27
|
+
if (value.type === 'Literal' && value.value === true)
|
|
28
|
+
return 'enabled';
|
|
29
|
+
if (value.type === 'Literal')
|
|
30
|
+
return 'absent';
|
|
31
|
+
return 'unreadable';
|
|
32
|
+
}
|
|
33
|
+
function createBrowserEscapeHatchRule(config) {
|
|
34
|
+
return (0, rule_creator_1.createRule)({
|
|
35
|
+
name: config.ruleName,
|
|
36
|
+
meta: {
|
|
37
|
+
type: 'problem',
|
|
38
|
+
docs: {
|
|
39
|
+
url: config.docsUrl,
|
|
40
|
+
description: `Forbid ${exports.BROWSER_ESCAPE_FLAG}, which exposes the ${config.vendor} API key to the client`,
|
|
41
|
+
cwe: 'CWE-522',
|
|
42
|
+
cvss: 8.6,
|
|
43
|
+
},
|
|
44
|
+
messages: {
|
|
45
|
+
browserKeyExposure: (0, messaging_1.formatLLMMessage)({
|
|
46
|
+
icon: messaging_1.MessageIcons.SECURITY,
|
|
47
|
+
issueName: `${config.vendor} API Key Exposed to the Browser`,
|
|
48
|
+
cwe: 'CWE-522',
|
|
49
|
+
owasp: 'A07:2021',
|
|
50
|
+
cvss: 8.6,
|
|
51
|
+
description: 'dangerouslyAllowBrowser lets the SDK run client-side, which ships the API key to every visitor',
|
|
52
|
+
severity: 'HIGH',
|
|
53
|
+
compliance: ['SOC2', 'PCI-DSS'],
|
|
54
|
+
fix: `Call ${config.vendor} from a server route and forward the result, so the key never leaves the server`,
|
|
55
|
+
documentationLink: config.documentationLink,
|
|
56
|
+
}),
|
|
57
|
+
},
|
|
58
|
+
schema: [],
|
|
59
|
+
},
|
|
60
|
+
defaultOptions: [],
|
|
61
|
+
create(context) {
|
|
62
|
+
let importsSdk = false;
|
|
63
|
+
const candidates = [];
|
|
64
|
+
function inspect(node, args) {
|
|
65
|
+
const options = args[0];
|
|
66
|
+
if (options?.type !== 'ObjectExpression')
|
|
67
|
+
return;
|
|
68
|
+
if (readFlag(options) === 'enabled')
|
|
69
|
+
candidates.push(node);
|
|
70
|
+
}
|
|
71
|
+
return {
|
|
72
|
+
ImportDeclaration(node) {
|
|
73
|
+
if ((0, sdk_api_key_rule_1.matchesModule)(String(node.source.value), config.modules))
|
|
74
|
+
importsSdk = true;
|
|
75
|
+
},
|
|
76
|
+
NewExpression(node) {
|
|
77
|
+
inspect(node, node.arguments);
|
|
78
|
+
},
|
|
79
|
+
CallExpression(node) {
|
|
80
|
+
if (node.callee.type === 'Identifier' &&
|
|
81
|
+
node.callee.name === 'require' &&
|
|
82
|
+
node.arguments[0]?.type === 'Literal' &&
|
|
83
|
+
typeof node.arguments[0].value === 'string' &&
|
|
84
|
+
(0, sdk_api_key_rule_1.matchesModule)(node.arguments[0].value, config.modules)) {
|
|
85
|
+
importsSdk = true;
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
inspect(node, node.arguments);
|
|
89
|
+
},
|
|
90
|
+
'Program:exit'() {
|
|
91
|
+
if (!importsSdk)
|
|
92
|
+
return;
|
|
93
|
+
for (const node of candidates) {
|
|
94
|
+
context.report({ node, messageId: 'browserKeyExposure' });
|
|
95
|
+
}
|
|
96
|
+
},
|
|
97
|
+
};
|
|
98
|
+
},
|
|
99
|
+
});
|
|
100
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) 2025 Ofri Peretz
|
|
3
|
+
* Licensed under the MIT License. Use of this source code is governed by the
|
|
4
|
+
* MIT license that can be found in the LICENSE file.
|
|
5
|
+
*/
|
|
6
|
+
import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
|
|
7
|
+
/**
|
|
8
|
+
* Two ids because the fixes differ in shape.
|
|
9
|
+
*
|
|
10
|
+
* A `password` property is replaced in place with `process.env.…`. A URL has
|
|
11
|
+
* to be rebuilt, or — better — split so the secret never sits in the string.
|
|
12
|
+
*/
|
|
13
|
+
export type HardcodedCredentialsMessageIds = 'hardcodedPassword' | 'credentialsInUrl';
|
|
14
|
+
export interface HardcodedCredentialsRuleConfig {
|
|
15
|
+
/**
|
|
16
|
+
* The rule's own `meta.type` + `meta.docs`, spelled out by the caller.
|
|
17
|
+
*
|
|
18
|
+
* Deliberately not derived in here: `scripts/audit-rule-meta-completeness.ts`
|
|
19
|
+
* statically parses each rule's source, so metadata hidden inside a factory
|
|
20
|
+
* is invisible to it.
|
|
21
|
+
*/
|
|
22
|
+
readonly meta: {
|
|
23
|
+
readonly type: 'problem';
|
|
24
|
+
readonly docs: {
|
|
25
|
+
readonly description: string;
|
|
26
|
+
readonly url: string;
|
|
27
|
+
readonly cwe: string;
|
|
28
|
+
readonly cweJustification?: string;
|
|
29
|
+
readonly cvss: number;
|
|
30
|
+
readonly confidence: 'high' | 'medium' | 'low';
|
|
31
|
+
};
|
|
32
|
+
};
|
|
33
|
+
/** Driver modules — the plugin-scope gate. */
|
|
34
|
+
readonly modules: readonly string[];
|
|
35
|
+
/** Extra keys that mark an object as this driver's connection config. */
|
|
36
|
+
readonly connectionKeys?: readonly string[];
|
|
37
|
+
/** URL schemes this driver accepts, e.g. `['postgres', 'postgresql']`. */
|
|
38
|
+
readonly urlSchemes: readonly string[];
|
|
39
|
+
/** Remediation for a literal credential property. */
|
|
40
|
+
readonly fix: string;
|
|
41
|
+
/** Remediation for a credential embedded in a URL. */
|
|
42
|
+
readonly urlFix: string;
|
|
43
|
+
readonly documentationLink: string;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Does this URL embed a password?
|
|
47
|
+
*
|
|
48
|
+
* Requires the `user:pass@` form specifically. `postgres://localhost:5432/app`
|
|
49
|
+
* and `postgres://app@host/db` carry no secret and are safe to commit — the
|
|
50
|
+
* whole point of this helper is that they do not report.
|
|
51
|
+
*
|
|
52
|
+
* The username may be empty, so `postgres://:pw@host/db` reports: that is a
|
|
53
|
+
* real password. The known over-match is `scheme://host:5432@other/db`, where
|
|
54
|
+
* a host:port lands in the userinfo slot and `5432` reads as the password.
|
|
55
|
+
* That URL is malformed for every driver here, so accepting the over-match is
|
|
56
|
+
* cheaper than a parser — but it is a deliberate choice, not an oversight.
|
|
57
|
+
*/
|
|
58
|
+
export declare function urlEmbedsCredentials(value: string, schemes: readonly string[]): boolean;
|
|
59
|
+
/**
|
|
60
|
+
* The static string value of a node, or `undefined` if it has none.
|
|
61
|
+
*
|
|
62
|
+
* A template literal with no interpolations is a string constant that happens
|
|
63
|
+
* to use backticks — `password: \`hunter2\`` is exactly as committed, exactly
|
|
64
|
+
* as unrotatable, as the single-quoted spelling. Reading only `Literal` let
|
|
65
|
+
* both credential paths be bypassed by changing one character.
|
|
66
|
+
*
|
|
67
|
+
* An *interpolated* template stays `undefined`: its value is decided at
|
|
68
|
+
* runtime, so there is no secret in the file.
|
|
69
|
+
*/
|
|
70
|
+
export declare function staticStringValue(node: TSESTree.Node): string | undefined;
|
|
71
|
+
/**
|
|
72
|
+
* A non-empty static string — the only value shape that is a real secret.
|
|
73
|
+
*
|
|
74
|
+
* `process.env.DB_PASSWORD` is the fix, and an interpolated template is a
|
|
75
|
+
* runtime value; neither is reported. An empty string is a driver-specific
|
|
76
|
+
* "no password" sentinel, common in local trust-auth setups, and reporting it
|
|
77
|
+
* teaches people the rule cries wolf.
|
|
78
|
+
*/
|
|
79
|
+
export declare function isLiteralSecret(node: TSESTree.Node): boolean;
|
|
80
|
+
/** Build a CWE-798 rule for one driver's connection surface. */
|
|
81
|
+
export declare function createHardcodedCredentialsRule(config: HardcodedCredentialsRuleConfig): TSESLint.RuleModule<HardcodedCredentialsMessageIds, []>;
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.urlEmbedsCredentials = urlEmbedsCredentials;
|
|
4
|
+
exports.staticStringValue = staticStringValue;
|
|
5
|
+
exports.isLiteralSecret = isLiteralSecret;
|
|
6
|
+
exports.createHardcodedCredentialsRule = createHardcodedCredentialsRule;
|
|
7
|
+
const ast_node_types_1 = require("../ast-node-types");
|
|
8
|
+
const messaging_1 = require("../messaging");
|
|
9
|
+
const unscoped_mutation_rule_1 = require("./unscoped-mutation-rule");
|
|
10
|
+
const require_tls_rule_1 = require("./require-tls-rule");
|
|
11
|
+
const CREDENTIAL_KEYS = ['password', 'pass', 'pwd', 'secret', 'passwd', 'auth'];
|
|
12
|
+
const DEFAULT_CONNECTION_KEYS = [
|
|
13
|
+
'host',
|
|
14
|
+
'hostname',
|
|
15
|
+
'port',
|
|
16
|
+
'database',
|
|
17
|
+
'connectionString',
|
|
18
|
+
'socketPath',
|
|
19
|
+
'uri',
|
|
20
|
+
'url',
|
|
21
|
+
'connection',
|
|
22
|
+
'pool',
|
|
23
|
+
'schema',
|
|
24
|
+
];
|
|
25
|
+
function urlEmbedsCredentials(value, schemes) {
|
|
26
|
+
const match = /^([a-z][a-z0-9+.-]*):\/\/([^/@\s:]*:[^/@\s]+)@/i.exec(value);
|
|
27
|
+
if (match === null)
|
|
28
|
+
return false;
|
|
29
|
+
return schemes.some((scheme) => scheme.toLowerCase() === match[1].toLowerCase());
|
|
30
|
+
}
|
|
31
|
+
function staticStringValue(node) {
|
|
32
|
+
if (node.type === ast_node_types_1.AST_NODE_TYPES.Literal) {
|
|
33
|
+
return typeof node.value === 'string' ? node.value : undefined;
|
|
34
|
+
}
|
|
35
|
+
if (node.type === ast_node_types_1.AST_NODE_TYPES.TemplateLiteral && node.expressions.length === 0) {
|
|
36
|
+
return node.quasis[0].value.cooked;
|
|
37
|
+
}
|
|
38
|
+
return undefined;
|
|
39
|
+
}
|
|
40
|
+
function isLiteralSecret(node) {
|
|
41
|
+
const value = staticStringValue(node);
|
|
42
|
+
return value !== undefined && value.length > 0;
|
|
43
|
+
}
|
|
44
|
+
function createHardcodedCredentialsRule(config) {
|
|
45
|
+
const connectionKeys = [...DEFAULT_CONNECTION_KEYS, ...(config.connectionKeys ?? [])];
|
|
46
|
+
return {
|
|
47
|
+
meta: {
|
|
48
|
+
type: config.meta.type,
|
|
49
|
+
docs: { ...config.meta.docs },
|
|
50
|
+
messages: {
|
|
51
|
+
hardcodedPassword: (0, messaging_1.formatLLMMessage)({
|
|
52
|
+
icon: messaging_1.MessageIcons.SECURITY,
|
|
53
|
+
issueName: 'Hardcoded Credentials',
|
|
54
|
+
description: 'A database password is written as a literal. It is in git history, every fork, and the built image — rotating it means rewriting history, so it never gets rotated.',
|
|
55
|
+
severity: 'CRITICAL',
|
|
56
|
+
cwe: config.meta.docs.cwe,
|
|
57
|
+
owasp: 'A07:2021',
|
|
58
|
+
compliance: ['SOC2', 'PCI-DSS', 'ISO27001', 'NIST-CSF'],
|
|
59
|
+
effort: 'low',
|
|
60
|
+
fix: config.fix,
|
|
61
|
+
documentationLink: config.documentationLink,
|
|
62
|
+
}),
|
|
63
|
+
credentialsInUrl: (0, messaging_1.formatLLMMessage)({
|
|
64
|
+
icon: messaging_1.MessageIcons.SECURITY,
|
|
65
|
+
issueName: 'Hardcoded Credentials',
|
|
66
|
+
description: 'A connection URL embeds a password in its userinfo section, so the secret is committed with the string.',
|
|
67
|
+
severity: 'CRITICAL',
|
|
68
|
+
cwe: config.meta.docs.cwe,
|
|
69
|
+
owasp: 'A07:2021',
|
|
70
|
+
compliance: ['SOC2', 'PCI-DSS', 'ISO27001', 'NIST-CSF'],
|
|
71
|
+
effort: 'low',
|
|
72
|
+
fix: config.urlFix,
|
|
73
|
+
documentationLink: config.documentationLink,
|
|
74
|
+
}),
|
|
75
|
+
},
|
|
76
|
+
schema: [],
|
|
77
|
+
},
|
|
78
|
+
defaultOptions: [],
|
|
79
|
+
create(context) {
|
|
80
|
+
let bindings = new Set();
|
|
81
|
+
let reported = new WeakSet();
|
|
82
|
+
let scanned = new WeakSet();
|
|
83
|
+
const report = (node, messageId) => {
|
|
84
|
+
if (reported.has(node))
|
|
85
|
+
return;
|
|
86
|
+
reported.add(node);
|
|
87
|
+
context.report({ node, messageId });
|
|
88
|
+
};
|
|
89
|
+
const scanConfig = (obj) => {
|
|
90
|
+
if (scanned.has(obj))
|
|
91
|
+
return;
|
|
92
|
+
scanned.add(obj);
|
|
93
|
+
for (const prop of obj.properties) {
|
|
94
|
+
if (prop.type !== ast_node_types_1.AST_NODE_TYPES.Property)
|
|
95
|
+
continue;
|
|
96
|
+
const name = (0, unscoped_mutation_rule_1.propertyKeyName)(prop);
|
|
97
|
+
if (name === undefined)
|
|
98
|
+
continue;
|
|
99
|
+
if (CREDENTIAL_KEYS.includes(name.toLowerCase())) {
|
|
100
|
+
if (isLiteralSecret(prop.value))
|
|
101
|
+
report(prop.value, 'hardcodedPassword');
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
const url = staticStringValue(prop.value);
|
|
105
|
+
if (url !== undefined && urlEmbedsCredentials(url, config.urlSchemes)) {
|
|
106
|
+
report(prop.value, 'credentialsInUrl');
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
if (prop.value.type === ast_node_types_1.AST_NODE_TYPES.ObjectExpression &&
|
|
110
|
+
connectionKeys.includes(name)) {
|
|
111
|
+
scanConfig(prop.value);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
return {
|
|
116
|
+
Program(program) {
|
|
117
|
+
bindings = (0, unscoped_mutation_rule_1.driverBindings)(program, config.modules);
|
|
118
|
+
reported = new WeakSet();
|
|
119
|
+
scanned = new WeakSet();
|
|
120
|
+
},
|
|
121
|
+
ObjectExpression(node) {
|
|
122
|
+
if (bindings.size === 0)
|
|
123
|
+
return;
|
|
124
|
+
if (!(0, require_tls_rule_1.looksLikeConnectionConfig)(node, connectionKeys))
|
|
125
|
+
return;
|
|
126
|
+
scanConfig(node);
|
|
127
|
+
},
|
|
128
|
+
'Literal, TemplateLiteral'(node) {
|
|
129
|
+
if (bindings.size === 0)
|
|
130
|
+
return;
|
|
131
|
+
const value = staticStringValue(node);
|
|
132
|
+
if (value === undefined)
|
|
133
|
+
return;
|
|
134
|
+
if (!urlEmbedsCredentials(value, config.urlSchemes))
|
|
135
|
+
return;
|
|
136
|
+
if (!(0, require_tls_rule_1.inConnectionPosition)(node, connectionKeys, bindings))
|
|
137
|
+
return;
|
|
138
|
+
report(node, 'credentialsInUrl');
|
|
139
|
+
},
|
|
140
|
+
};
|
|
141
|
+
},
|
|
142
|
+
};
|
|
143
|
+
}
|
|
@@ -8,3 +8,8 @@ export * from './mock-context';
|
|
|
8
8
|
export * from './sql-injection-rule';
|
|
9
9
|
export * from './unscoped-mutation-rule';
|
|
10
10
|
export * from './require-tls-rule';
|
|
11
|
+
export * from './mass-assignment-rule';
|
|
12
|
+
export * from './hardcoded-credentials-rule';
|
|
13
|
+
export * from './sdk-api-key-rule';
|
|
14
|
+
export * from './browser-escape-hatch-rule';
|
|
15
|
+
export * from './raw-identifier-rule';
|
|
@@ -19,3 +19,8 @@ __exportStar(require("./mock-context"), exports);
|
|
|
19
19
|
__exportStar(require("./sql-injection-rule"), exports);
|
|
20
20
|
__exportStar(require("./unscoped-mutation-rule"), exports);
|
|
21
21
|
__exportStar(require("./require-tls-rule"), exports);
|
|
22
|
+
__exportStar(require("./mass-assignment-rule"), exports);
|
|
23
|
+
__exportStar(require("./hardcoded-credentials-rule"), exports);
|
|
24
|
+
__exportStar(require("./sdk-api-key-rule"), exports);
|
|
25
|
+
__exportStar(require("./browser-escape-hatch-rule"), exports);
|
|
26
|
+
__exportStar(require("./raw-identifier-rule"), exports);
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) 2025 Ofri Peretz
|
|
3
|
+
* Licensed under the MIT License. Use of this source code is governed by the
|
|
4
|
+
* MIT license that can be found in the LICENSE file.
|
|
5
|
+
*/
|
|
6
|
+
import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
|
|
7
|
+
/**
|
|
8
|
+
* Two ids because the shapes read differently at the call site, and a reader
|
|
9
|
+
* who sees "spread" needs to be told the spread is the problem, not the object
|
|
10
|
+
* around it.
|
|
11
|
+
*/
|
|
12
|
+
export type MassAssignmentMessageIds = 'untrustedPayload' | 'untrustedSpread';
|
|
13
|
+
export interface MassAssignmentRuleConfig {
|
|
14
|
+
/**
|
|
15
|
+
* The rule's own `meta.type` + `meta.docs`, spelled out by the caller.
|
|
16
|
+
*
|
|
17
|
+
* Deliberately not derived in here: `scripts/audit-rule-meta-completeness.ts`
|
|
18
|
+
* statically parses each rule's source, so metadata hidden inside a factory
|
|
19
|
+
* is invisible to it.
|
|
20
|
+
*/
|
|
21
|
+
readonly meta: {
|
|
22
|
+
readonly type: 'problem';
|
|
23
|
+
readonly docs: {
|
|
24
|
+
readonly description: string;
|
|
25
|
+
readonly url: string;
|
|
26
|
+
readonly cwe: string;
|
|
27
|
+
readonly cweJustification?: string;
|
|
28
|
+
readonly cvss: number;
|
|
29
|
+
readonly confidence: 'high' | 'medium' | 'low';
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
/** Write methods, e.g. `['create', 'update', 'save']`. */
|
|
33
|
+
readonly methods: readonly string[];
|
|
34
|
+
/**
|
|
35
|
+
* Property names inside an options object that carry the row payload —
|
|
36
|
+
* Prisma's `data` / `create` / `update`, Drizzle's `values` / `set`.
|
|
37
|
+
*
|
|
38
|
+
* Empty means the payload is the argument itself (`User.create(req.body)`).
|
|
39
|
+
* Both are checked regardless; this list only adds the nested positions.
|
|
40
|
+
*/
|
|
41
|
+
readonly payloadKeys?: readonly string[];
|
|
42
|
+
/** Driver modules — the plugin-scope gate. */
|
|
43
|
+
readonly modules: readonly string[];
|
|
44
|
+
/**
|
|
45
|
+
* Names a receiver may have for its call to count as a driver write.
|
|
46
|
+
*
|
|
47
|
+
* Carried over from `createUnscopedMutationRule`, and for the same reason:
|
|
48
|
+
* importing the driver does not make every matching method call in the file
|
|
49
|
+
* a database write. Without it, `bindings.size === 0` only proves that *some*
|
|
50
|
+
* driver import exists somewhere in the file, and the method names here are
|
|
51
|
+
* among the most generic in JavaScript — `Map.prototype.set`, `Headers.set`,
|
|
52
|
+
* `URLSearchParams.set`, `FormData.set`, and any `cache.create`. One
|
|
53
|
+
* `req.body` reaching any of those in a file that also imports the ORM would
|
|
54
|
+
* report.
|
|
55
|
+
*/
|
|
56
|
+
readonly receiverPattern: RegExp;
|
|
57
|
+
readonly fix: string;
|
|
58
|
+
readonly documentationLink: string;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Does this expression evaluate to attacker-controlled input?
|
|
62
|
+
*
|
|
63
|
+
* Matches `req.body`, `request.query`, `ctx.request.body`, `event.body` — the
|
|
64
|
+
* property must be an untrusted one *and* the chain must bottom out in a
|
|
65
|
+
* request-shaped identifier. Requiring both is what keeps `config.data` and
|
|
66
|
+
* `form.body` out of the findings.
|
|
67
|
+
*/
|
|
68
|
+
export declare function isUntrustedSource(node: TSESTree.Node): boolean;
|
|
69
|
+
/**
|
|
70
|
+
* Classify a payload expression.
|
|
71
|
+
*
|
|
72
|
+
* `false` for anything that names its fields, which is the fix:
|
|
73
|
+
* `{ name: req.body.name }` reads one value out of the request and is not a
|
|
74
|
+
* mass assignment. Only handing over the object itself, or splatting it into
|
|
75
|
+
* one, opens every column.
|
|
76
|
+
*/
|
|
77
|
+
export declare function classifyPayload(node: TSESTree.Node): MassAssignmentMessageIds | false;
|
|
78
|
+
/** Build a CWE-915 rule for one driver's write surface. */
|
|
79
|
+
export declare function createMassAssignmentRule(config: MassAssignmentRuleConfig): TSESLint.RuleModule<MassAssignmentMessageIds, []>;
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.isUntrustedSource = isUntrustedSource;
|
|
4
|
+
exports.classifyPayload = classifyPayload;
|
|
5
|
+
exports.createMassAssignmentRule = createMassAssignmentRule;
|
|
6
|
+
const ast_node_types_1 = require("../ast-node-types");
|
|
7
|
+
const messaging_1 = require("../messaging");
|
|
8
|
+
const unscoped_mutation_rule_1 = require("./unscoped-mutation-rule");
|
|
9
|
+
const REQUEST_OBJECTS = ['req', 'request', 'ctx', 'context', 'event'];
|
|
10
|
+
const UNTRUSTED_PROPS = ['body', 'query', 'params', 'payload'];
|
|
11
|
+
function isUntrustedSource(node) {
|
|
12
|
+
if (node.type !== ast_node_types_1.AST_NODE_TYPES.MemberExpression || node.computed)
|
|
13
|
+
return false;
|
|
14
|
+
if (node.property.type !== ast_node_types_1.AST_NODE_TYPES.Identifier)
|
|
15
|
+
return false;
|
|
16
|
+
if (!UNTRUSTED_PROPS.includes(node.property.name)) {
|
|
17
|
+
return false;
|
|
18
|
+
}
|
|
19
|
+
return baseIsRequest(node.object);
|
|
20
|
+
}
|
|
21
|
+
function baseIsRequest(node) {
|
|
22
|
+
let cursor = node;
|
|
23
|
+
while (cursor.type === ast_node_types_1.AST_NODE_TYPES.MemberExpression)
|
|
24
|
+
cursor = cursor.object;
|
|
25
|
+
return (cursor.type === ast_node_types_1.AST_NODE_TYPES.Identifier &&
|
|
26
|
+
REQUEST_OBJECTS.includes(cursor.name));
|
|
27
|
+
}
|
|
28
|
+
function classifyPayload(node) {
|
|
29
|
+
if (isUntrustedSource(node))
|
|
30
|
+
return 'untrustedPayload';
|
|
31
|
+
if (node.type === ast_node_types_1.AST_NODE_TYPES.ObjectExpression) {
|
|
32
|
+
for (const prop of node.properties) {
|
|
33
|
+
if (prop.type !== ast_node_types_1.AST_NODE_TYPES.SpreadElement)
|
|
34
|
+
continue;
|
|
35
|
+
if (isUntrustedSource(prop.argument))
|
|
36
|
+
return 'untrustedSpread';
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
function createMassAssignmentRule(config) {
|
|
42
|
+
const methods = new Set(config.methods);
|
|
43
|
+
const payloadKeys = new Set(config.payloadKeys ?? []);
|
|
44
|
+
return {
|
|
45
|
+
meta: {
|
|
46
|
+
type: config.meta.type,
|
|
47
|
+
docs: { ...config.meta.docs },
|
|
48
|
+
messages: {
|
|
49
|
+
untrustedPayload: (0, messaging_1.formatLLMMessage)({
|
|
50
|
+
icon: messaging_1.MessageIcons.SECURITY,
|
|
51
|
+
issueName: 'Mass Assignment',
|
|
52
|
+
description: 'The request object is written straight to the database, so every column the model exposes is settable by the caller — including ones this code never mentions.',
|
|
53
|
+
severity: 'HIGH',
|
|
54
|
+
cwe: config.meta.docs.cwe,
|
|
55
|
+
owasp: 'A04:2021',
|
|
56
|
+
compliance: ['SOC2', 'PCI-DSS', 'NIST-CSF'],
|
|
57
|
+
effort: 'medium',
|
|
58
|
+
fix: config.fix,
|
|
59
|
+
documentationLink: config.documentationLink,
|
|
60
|
+
}),
|
|
61
|
+
untrustedSpread: (0, messaging_1.formatLLMMessage)({
|
|
62
|
+
icon: messaging_1.MessageIcons.SECURITY,
|
|
63
|
+
issueName: 'Mass Assignment',
|
|
64
|
+
description: 'Spreading the request into the payload carries every key it happens to hold, not just the ones written beside it.',
|
|
65
|
+
severity: 'HIGH',
|
|
66
|
+
cwe: config.meta.docs.cwe,
|
|
67
|
+
owasp: 'A04:2021',
|
|
68
|
+
compliance: ['SOC2', 'PCI-DSS', 'NIST-CSF'],
|
|
69
|
+
effort: 'medium',
|
|
70
|
+
fix: config.fix,
|
|
71
|
+
documentationLink: config.documentationLink,
|
|
72
|
+
}),
|
|
73
|
+
},
|
|
74
|
+
schema: [],
|
|
75
|
+
},
|
|
76
|
+
defaultOptions: [],
|
|
77
|
+
create(context) {
|
|
78
|
+
let bindings = new Set();
|
|
79
|
+
return {
|
|
80
|
+
Program(program) {
|
|
81
|
+
bindings = (0, unscoped_mutation_rule_1.driverBindings)(program, config.modules);
|
|
82
|
+
},
|
|
83
|
+
CallExpression(node) {
|
|
84
|
+
if (bindings.size === 0)
|
|
85
|
+
return;
|
|
86
|
+
if (node.callee.type !== ast_node_types_1.AST_NODE_TYPES.MemberExpression ||
|
|
87
|
+
node.callee.property.type !== ast_node_types_1.AST_NODE_TYPES.Identifier ||
|
|
88
|
+
!methods.has(node.callee.property.name)) {
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
const base = (0, unscoped_mutation_rule_1.receiverBaseName)(node.callee);
|
|
92
|
+
if (base === undefined)
|
|
93
|
+
return;
|
|
94
|
+
if (!bindings.has(base) && !config.receiverPattern.test(base))
|
|
95
|
+
return;
|
|
96
|
+
for (const arg of node.arguments) {
|
|
97
|
+
if (arg.type === ast_node_types_1.AST_NODE_TYPES.SpreadElement)
|
|
98
|
+
continue;
|
|
99
|
+
const direct = classifyPayload(arg);
|
|
100
|
+
if (direct) {
|
|
101
|
+
context.report({ node: arg, messageId: direct });
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
if (arg.type !== ast_node_types_1.AST_NODE_TYPES.ObjectExpression)
|
|
105
|
+
continue;
|
|
106
|
+
for (const prop of arg.properties) {
|
|
107
|
+
if (prop.type !== ast_node_types_1.AST_NODE_TYPES.Property)
|
|
108
|
+
continue;
|
|
109
|
+
const name = (0, unscoped_mutation_rule_1.propertyKeyName)(prop);
|
|
110
|
+
if (name === undefined || !payloadKeys.has(name))
|
|
111
|
+
continue;
|
|
112
|
+
const nested = classifyPayload(prop.value);
|
|
113
|
+
if (nested)
|
|
114
|
+
context.report({ node: prop.value, messageId: nested });
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
},
|
|
118
|
+
};
|
|
119
|
+
},
|
|
120
|
+
};
|
|
121
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) 2025 Ofri Peretz
|
|
3
|
+
* Licensed under the MIT License. Use of this source code is governed by the
|
|
4
|
+
* MIT license that can be found in the LICENSE file.
|
|
5
|
+
*/
|
|
6
|
+
import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
|
|
7
|
+
/**
|
|
8
|
+
* Two ids because the remediations are genuinely different.
|
|
9
|
+
*
|
|
10
|
+
* A table or column name is fixed by an allowlist or the driver's identifier
|
|
11
|
+
* escaper. A sort direction has exactly two legal values, so the fix is a
|
|
12
|
+
* ternary — reaching for an escaper there is overkill and reads as noise.
|
|
13
|
+
*/
|
|
14
|
+
export type RawIdentifierMessageIds = 'identifierInterpolation' | 'sortDirectionInterpolation';
|
|
15
|
+
export interface RawIdentifierRuleConfig {
|
|
16
|
+
/**
|
|
17
|
+
* The rule's own `meta.type` + `meta.docs`, spelled out by the caller.
|
|
18
|
+
*
|
|
19
|
+
* Deliberately not derived in here: `scripts/audit-rule-meta-completeness.ts`
|
|
20
|
+
* reads rule metadata by statically parsing the rule's source file, so
|
|
21
|
+
* metadata hidden inside a factory is invisible to it.
|
|
22
|
+
*/
|
|
23
|
+
readonly meta: {
|
|
24
|
+
readonly type: 'problem';
|
|
25
|
+
readonly docs: {
|
|
26
|
+
readonly description: string;
|
|
27
|
+
readonly url: string;
|
|
28
|
+
readonly cwe: string;
|
|
29
|
+
readonly cweJustification?: string;
|
|
30
|
+
readonly cvss: number;
|
|
31
|
+
readonly confidence: 'high' | 'medium' | 'low';
|
|
32
|
+
};
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* Tag names of the parameterizing template APIs, e.g. `['sql']` or
|
|
36
|
+
* `['$queryRaw', '$executeRaw']`. Matched against a bare tag (`` sql`…` ``)
|
|
37
|
+
* or the property of a member tag (`` prisma.$queryRaw`…` ``).
|
|
38
|
+
*/
|
|
39
|
+
readonly tags: readonly string[];
|
|
40
|
+
/** Modules the tag must be imported from, when `requireImport` is set. */
|
|
41
|
+
readonly modules: readonly string[];
|
|
42
|
+
/**
|
|
43
|
+
* Does a matched tag have to resolve to a `modules` import?
|
|
44
|
+
*
|
|
45
|
+
* This is a property of the *tag name*, not of the AST shape it appears in,
|
|
46
|
+
* and an earlier version got that wrong: it applied the gate only when the
|
|
47
|
+
* tag was a bare `Identifier`. A generic name reached through a member
|
|
48
|
+
* expression then skipped the gate entirely, so
|
|
49
|
+
*
|
|
50
|
+
* import { createQueryBuilder } from 'some-internal-lib';
|
|
51
|
+
* await q.sql`SELECT * FROM ${table}`;
|
|
52
|
+
*
|
|
53
|
+
* reported under `drizzle-security` in a file with no Drizzle anywhere —
|
|
54
|
+
* precisely the false positive the gate exists to prevent.
|
|
55
|
+
*
|
|
56
|
+
* - `true` for a generic name like `sql`, which any project may define.
|
|
57
|
+
* Only a bare tag bound to a driver import qualifies.
|
|
58
|
+
* - `false` for a name specific enough to stand alone, like Prisma's
|
|
59
|
+
* `$queryRaw`. The client is routinely re-exported from a local module
|
|
60
|
+
* (`import { prisma } from '@/lib/db'`), so demanding an import here
|
|
61
|
+
* would miss the shape most codebases actually have.
|
|
62
|
+
*/
|
|
63
|
+
readonly requireImport: boolean;
|
|
64
|
+
/**
|
|
65
|
+
* Callee texts that safely escape an identifier, e.g. `['sql.identifier']`.
|
|
66
|
+
*
|
|
67
|
+
* These are the *fix*. Reporting the remediation the message recommends is
|
|
68
|
+
* the fastest way to get a security rule switched off, so they are exempt.
|
|
69
|
+
*/
|
|
70
|
+
readonly identifierHelpers: readonly string[];
|
|
71
|
+
/** Remediation line for the identifier finding. */
|
|
72
|
+
readonly fix: string;
|
|
73
|
+
/** Remediation line for the sort-direction finding. */
|
|
74
|
+
readonly sortDirectionFix: string;
|
|
75
|
+
readonly documentationLink: string;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Drop trailing whitespace and opening quotes, by scanning — not by regex.
|
|
79
|
+
*
|
|
80
|
+
* This is a security property rather than a style choice. The keyword pattern
|
|
81
|
+
* used to end `\s*["'`[]?\s*$`: two quantifiers with an optional token between
|
|
82
|
+
* them, so a run of tabs gave the engine O(n) ways to split them, at O(n)
|
|
83
|
+
* start positions. CodeQL flagged it as `js/polynomial-redos`, correctly —
|
|
84
|
+
* this rule reads whatever source it is pointed at, so a template literal
|
|
85
|
+
* padded with whitespace is genuinely attacker-supplied.
|
|
86
|
+
*
|
|
87
|
+
* Splitting it into a separate *regex* does not help: `[\s"'`[]+$` backtracks
|
|
88
|
+
* the same way, because every position inside the run is a candidate start
|
|
89
|
+
* that only fails once it reaches the anchor. Measured on
|
|
90
|
+
* `` `SELECT * FROM` + '\t'.repeat(40_000) + 'x' ``, both spellings take
|
|
91
|
+
* ~800ms. A reverse scan touches each trailing character once and returns in
|
|
92
|
+
* microseconds, which is the only version of this that is actually linear.
|
|
93
|
+
*/
|
|
94
|
+
export declare function stripIdentifierGap(text: string): string;
|
|
95
|
+
/** The clause an interpolation falls in, normalized (`order by`), or `''`. */
|
|
96
|
+
export declare function lastClause(text: string): string;
|
|
97
|
+
/**
|
|
98
|
+
* Classify one interpolation hole by the static SQL that precedes it.
|
|
99
|
+
*
|
|
100
|
+
* `false` is the answer for every value position — `WHERE id = ${id}`,
|
|
101
|
+
* `LIMIT ${n}`, `VALUES (${a})` — because those are exactly what the tagged
|
|
102
|
+
* template parameterizes correctly. Reporting them would make the rule fire on
|
|
103
|
+
* the API's intended use, which is the failure mode that gets a plugin
|
|
104
|
+
* uninstalled.
|
|
105
|
+
*/
|
|
106
|
+
export declare function identifierPosition(precedingText: string): 'identifier' | 'sortDirection' | false;
|
|
107
|
+
/** Dotted source text of a callee, e.g. `sql.identifier`. */
|
|
108
|
+
export declare function calleeText(node: TSESTree.Node): string;
|
|
109
|
+
/**
|
|
110
|
+
* Is this interpolated expression exempt?
|
|
111
|
+
*
|
|
112
|
+
* Three shapes are, and each would otherwise be a false positive on correct
|
|
113
|
+
* code:
|
|
114
|
+
*
|
|
115
|
+
* - **A literal.** `` sql`SELECT * FROM ${'users'}` `` is a constant the
|
|
116
|
+
* developer typed. There is no untrusted input anywhere in it.
|
|
117
|
+
* - **The driver's identifier escaper.** This is the fix the message asks
|
|
118
|
+
* for; flagging it would punish the correction.
|
|
119
|
+
* - **A nested template with the same tag.** Composition is the intended
|
|
120
|
+
* primitive in both Drizzle and Prisma, and the nested template is visited
|
|
121
|
+
* on its own — so its holes are still checked, just not twice.
|
|
122
|
+
*/
|
|
123
|
+
export declare function isExemptExpression(expr: TSESTree.Expression, identifierHelpers: readonly string[], tags: readonly string[]): boolean;
|
|
124
|
+
/** The matched name of a template tag: `sql` or `$queryRaw`. */
|
|
125
|
+
export declare function tagName(tag: TSESTree.Node): string | undefined;
|
|
126
|
+
/** Build a CWE-89 identifier-interpolation rule for one driver's template API. */
|
|
127
|
+
export declare function createRawIdentifierRule(config: RawIdentifierRuleConfig): TSESLint.RuleModule<RawIdentifierMessageIds, []>;
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.stripIdentifierGap = stripIdentifierGap;
|
|
4
|
+
exports.lastClause = lastClause;
|
|
5
|
+
exports.identifierPosition = identifierPosition;
|
|
6
|
+
exports.calleeText = calleeText;
|
|
7
|
+
exports.isExemptExpression = isExemptExpression;
|
|
8
|
+
exports.tagName = tagName;
|
|
9
|
+
exports.createRawIdentifierRule = createRawIdentifierRule;
|
|
10
|
+
const ast_node_types_1 = require("../ast-node-types");
|
|
11
|
+
const messaging_1 = require("../messaging");
|
|
12
|
+
const unscoped_mutation_rule_1 = require("./unscoped-mutation-rule");
|
|
13
|
+
const IDENTIFIER_KEYWORDS = /\b(?:from|join|into|update|table|order\s+by|group\s+by|select|distinct\s+on)$/i;
|
|
14
|
+
const GAP_CHAR = /[\s"'`[]/;
|
|
15
|
+
function stripIdentifierGap(text) {
|
|
16
|
+
let end = text.length;
|
|
17
|
+
while (end > 0 && GAP_CHAR.test(text[end - 1]))
|
|
18
|
+
end--;
|
|
19
|
+
return text.slice(0, end);
|
|
20
|
+
}
|
|
21
|
+
const CLAUSE_KEYWORDS = /\b(select|from|where|group\s+by|having|order\s+by|limit|offset|union|returning|values|set)\b/gi;
|
|
22
|
+
function lastClause(text) {
|
|
23
|
+
const matches = [...text.matchAll(CLAUSE_KEYWORDS)];
|
|
24
|
+
const last = matches.at(-1);
|
|
25
|
+
return last ? last[1].toLowerCase().replace(/\s+/g, ' ') : '';
|
|
26
|
+
}
|
|
27
|
+
function identifierPosition(precedingText) {
|
|
28
|
+
if (IDENTIFIER_KEYWORDS.test(stripIdentifierGap(precedingText)))
|
|
29
|
+
return 'identifier';
|
|
30
|
+
if (lastClause(precedingText) === 'order by')
|
|
31
|
+
return 'sortDirection';
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
function calleeText(node) {
|
|
35
|
+
if (node.type === ast_node_types_1.AST_NODE_TYPES.Identifier)
|
|
36
|
+
return node.name;
|
|
37
|
+
if (node.type === ast_node_types_1.AST_NODE_TYPES.MemberExpression && !node.computed) {
|
|
38
|
+
const object = calleeText(node.object);
|
|
39
|
+
const property = calleeText(node.property);
|
|
40
|
+
return object && property ? `${object}.${property}` : '';
|
|
41
|
+
}
|
|
42
|
+
return '';
|
|
43
|
+
}
|
|
44
|
+
function isExemptExpression(expr, identifierHelpers, tags) {
|
|
45
|
+
if (expr.type === ast_node_types_1.AST_NODE_TYPES.Literal)
|
|
46
|
+
return true;
|
|
47
|
+
if (expr.type === ast_node_types_1.AST_NODE_TYPES.CallExpression) {
|
|
48
|
+
if (identifierHelpers.includes(calleeText(expr.callee)))
|
|
49
|
+
return true;
|
|
50
|
+
}
|
|
51
|
+
if (expr.type === ast_node_types_1.AST_NODE_TYPES.TaggedTemplateExpression) {
|
|
52
|
+
const nested = tagName(expr.tag);
|
|
53
|
+
return nested !== undefined && tags.includes(nested);
|
|
54
|
+
}
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
function tagName(tag) {
|
|
58
|
+
if (tag.type === ast_node_types_1.AST_NODE_TYPES.Identifier)
|
|
59
|
+
return tag.name;
|
|
60
|
+
if (tag.type === ast_node_types_1.AST_NODE_TYPES.MemberExpression &&
|
|
61
|
+
!tag.computed &&
|
|
62
|
+
tag.property.type === ast_node_types_1.AST_NODE_TYPES.Identifier) {
|
|
63
|
+
return tag.property.name;
|
|
64
|
+
}
|
|
65
|
+
return undefined;
|
|
66
|
+
}
|
|
67
|
+
function createRawIdentifierRule(config) {
|
|
68
|
+
const tags = new Set(config.tags);
|
|
69
|
+
return {
|
|
70
|
+
meta: {
|
|
71
|
+
type: config.meta.type,
|
|
72
|
+
docs: { ...config.meta.docs },
|
|
73
|
+
messages: {
|
|
74
|
+
identifierInterpolation: (0, messaging_1.formatLLMMessage)({
|
|
75
|
+
icon: messaging_1.MessageIcons.SECURITY,
|
|
76
|
+
issueName: 'SQL Injection Risk',
|
|
77
|
+
description: 'A table or column name is interpolated into a parameterized query. Bind parameters only ever substitute values, so this identifier is spliced into the SQL as text.',
|
|
78
|
+
severity: 'CRITICAL',
|
|
79
|
+
cwe: config.meta.docs.cwe,
|
|
80
|
+
owasp: 'A03:2021',
|
|
81
|
+
compliance: ['SOC2', 'PCI-DSS', 'NIST-CSF'],
|
|
82
|
+
effort: 'medium',
|
|
83
|
+
fix: config.fix,
|
|
84
|
+
documentationLink: config.documentationLink,
|
|
85
|
+
}),
|
|
86
|
+
sortDirectionInterpolation: (0, messaging_1.formatLLMMessage)({
|
|
87
|
+
icon: messaging_1.MessageIcons.SECURITY,
|
|
88
|
+
issueName: 'SQL Injection Risk',
|
|
89
|
+
description: 'A value is interpolated inside an ORDER BY clause, where a bind parameter cannot reach.',
|
|
90
|
+
severity: 'HIGH',
|
|
91
|
+
cwe: config.meta.docs.cwe,
|
|
92
|
+
owasp: 'A03:2021',
|
|
93
|
+
compliance: ['SOC2', 'PCI-DSS', 'NIST-CSF'],
|
|
94
|
+
effort: 'low',
|
|
95
|
+
fix: config.sortDirectionFix,
|
|
96
|
+
documentationLink: config.documentationLink,
|
|
97
|
+
}),
|
|
98
|
+
},
|
|
99
|
+
schema: [],
|
|
100
|
+
},
|
|
101
|
+
defaultOptions: [],
|
|
102
|
+
create(context) {
|
|
103
|
+
let bindings = new Set();
|
|
104
|
+
return {
|
|
105
|
+
Program(program) {
|
|
106
|
+
bindings = (0, unscoped_mutation_rule_1.driverBindings)(program, config.modules);
|
|
107
|
+
},
|
|
108
|
+
TaggedTemplateExpression(node) {
|
|
109
|
+
const name = tagName(node.tag);
|
|
110
|
+
if (name === undefined || !tags.has(name))
|
|
111
|
+
return;
|
|
112
|
+
if (config.requireImport) {
|
|
113
|
+
if (node.tag.type !== ast_node_types_1.AST_NODE_TYPES.Identifier)
|
|
114
|
+
return;
|
|
115
|
+
if (!bindings.has(name))
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
const { quasis, expressions } = node.quasi;
|
|
119
|
+
expressions.forEach((expr, index) => {
|
|
120
|
+
if (isExemptExpression(expr, config.identifierHelpers, config.tags))
|
|
121
|
+
return;
|
|
122
|
+
const preceding = quasis
|
|
123
|
+
.slice(0, index + 1)
|
|
124
|
+
.map((q) => q.value.raw)
|
|
125
|
+
.join(' ');
|
|
126
|
+
const position = identifierPosition(preceding);
|
|
127
|
+
if (position === false)
|
|
128
|
+
return;
|
|
129
|
+
context.report({
|
|
130
|
+
node: expr,
|
|
131
|
+
messageId: position === 'identifier'
|
|
132
|
+
? 'identifierInterpolation'
|
|
133
|
+
: 'sortDirectionInterpolation',
|
|
134
|
+
});
|
|
135
|
+
});
|
|
136
|
+
},
|
|
137
|
+
};
|
|
138
|
+
},
|
|
139
|
+
};
|
|
140
|
+
}
|
|
@@ -102,7 +102,7 @@ export declare function urlDisablesTls(value: string, schemes: readonly string[]
|
|
|
102
102
|
* plugin the one users switch off. The cost is a false negative when the DSN is
|
|
103
103
|
* built in one statement and passed in another.
|
|
104
104
|
*/
|
|
105
|
-
export declare function inConnectionPosition(node: TSESTree.Literal, connectionKeys: readonly string[], bindings: ReadonlySet<string>): boolean;
|
|
105
|
+
export declare function inConnectionPosition(node: TSESTree.Literal | TSESTree.TemplateLiteral, connectionKeys: readonly string[], bindings: ReadonlySet<string>): boolean;
|
|
106
106
|
/**
|
|
107
107
|
* Build a CWE-319 rule for the given driver.
|
|
108
108
|
*
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) 2025 Ofri Peretz
|
|
3
|
+
* Licensed under the MIT License. Use of this source code is governed by the
|
|
4
|
+
* MIT license that can be found in the LICENSE file.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* @fileoverview Shared CWE-798 detector — a literal API key in an inference
|
|
8
|
+
* SDK's client construction.
|
|
9
|
+
*
|
|
10
|
+
* ## Why this is not `secure-coding/no-hardcoded-credentials`
|
|
11
|
+
*
|
|
12
|
+
* Measured, not assumed: every rule in `eslint-plugin-secure-coding` reports
|
|
13
|
+
* *nothing* on `new OpenAI({ apiKey: 'sk-proj-…' })`,
|
|
14
|
+
* `new GoogleGenerativeAI('AIza…')` or the Anthropic equivalent. The generic
|
|
15
|
+
* credential rules look for password-shaped names and connection strings; an
|
|
16
|
+
* SDK's client options are a different shape and no rule in the ecosystem
|
|
17
|
+
* covers them.
|
|
18
|
+
*
|
|
19
|
+
* The gate here compares against an exact SDK module specifier, which by the
|
|
20
|
+
* taxonomy contract puts it in that SDK's plugin — not in `secure-coding`.
|
|
21
|
+
* The logic is shared because the three SDKs differ only in the module name,
|
|
22
|
+
* the option names, and the remediation copy.
|
|
23
|
+
*/
|
|
24
|
+
import type { TSESTree } from '@typescript-eslint/utils';
|
|
25
|
+
export interface SdkApiKeyRuleConfig {
|
|
26
|
+
/** Rule id, e.g. `no-hardcoded-api-key`. */
|
|
27
|
+
ruleName: string;
|
|
28
|
+
/** Vendor name for the message, e.g. `OpenAI`. */
|
|
29
|
+
vendor: string;
|
|
30
|
+
/**
|
|
31
|
+
* Module names that open the gate. Matched as the exact specifier or a
|
|
32
|
+
* subpath of it (`openai` matches `openai` and `openai/resources`, but not
|
|
33
|
+
* `openai-edge`, which is a different package with a different client).
|
|
34
|
+
* A bare scope (`@anthropic-ai`) matches every package under it.
|
|
35
|
+
*/
|
|
36
|
+
modules: readonly string[];
|
|
37
|
+
/** Client-option names that hold the credential, e.g. `apiKey`. */
|
|
38
|
+
keyProps: readonly string[];
|
|
39
|
+
/**
|
|
40
|
+
* The corrected construction shown in the fix.
|
|
41
|
+
*
|
|
42
|
+
* A template, not a computed string: `{{prop}}` here is resolved by ESLint
|
|
43
|
+
* from the same report data as the description, so a consumer's RuleTester
|
|
44
|
+
* cases only ever declare `prop`. Passing a pre-computed string instead
|
|
45
|
+
* leaves an unhydrated placeholder in every expected message.
|
|
46
|
+
*
|
|
47
|
+
* SDKs whose key can be positional should keep this static — `{{prop}}`
|
|
48
|
+
* reads as "The first argument" there and would render nonsense inside an
|
|
49
|
+
* options literal.
|
|
50
|
+
*/
|
|
51
|
+
fixTemplate: string;
|
|
52
|
+
/** Rule documentation URL. */
|
|
53
|
+
docsUrl: string;
|
|
54
|
+
/** Vendor documentation link carried in the message. */
|
|
55
|
+
documentationLink: string;
|
|
56
|
+
/**
|
|
57
|
+
* Constructors whose *first positional argument* is the key itself, e.g.
|
|
58
|
+
* `new GoogleGenerativeAI('AIza…')`. Empty for SDKs that only take options.
|
|
59
|
+
*/
|
|
60
|
+
positionalKeyConstructors?: readonly string[];
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* What `{{prop}}` reads as when the credential is a positional argument rather
|
|
64
|
+
* than a named option. Exported so a test can pin the string the
|
|
65
|
+
* description renders, without duplicating the literal.
|
|
66
|
+
*/
|
|
67
|
+
export declare const POSITIONAL_KEY_LABEL = "The first argument";
|
|
68
|
+
/**
|
|
69
|
+
* Does this import specifier belong to one of the configured modules?
|
|
70
|
+
*
|
|
71
|
+
* Exact match or a subpath, never a prefix match on the bare name — `openai`
|
|
72
|
+
* must not open the gate for `openai-edge`.
|
|
73
|
+
*/
|
|
74
|
+
export declare function matchesModule(source: string, modules: readonly string[]): boolean;
|
|
75
|
+
/**
|
|
76
|
+
* `literal` carries the property name that actually held the credential.
|
|
77
|
+
* A bare verdict left the caller guessing, and it guessed the first configured
|
|
78
|
+
* prop — naming the wrong option whenever a later one was the offender.
|
|
79
|
+
*/
|
|
80
|
+
export type KeyVerdict = {
|
|
81
|
+
kind: 'literal';
|
|
82
|
+
prop: string;
|
|
83
|
+
} | {
|
|
84
|
+
kind: 'safe';
|
|
85
|
+
} | {
|
|
86
|
+
kind: 'unreadable';
|
|
87
|
+
};
|
|
88
|
+
/**
|
|
89
|
+
* Whether the client options literal carries an inline credential.
|
|
90
|
+
*
|
|
91
|
+
* `process.env.OPENAI_API_KEY` and any other non-literal expression are `safe`
|
|
92
|
+
* — reading a key from the environment is the correct pattern. A spread is
|
|
93
|
+
* `unreadable`: the key may be in the spread source, and guessing there would
|
|
94
|
+
* flag correct code.
|
|
95
|
+
*
|
|
96
|
+
* A safe credential prop `continue`s rather than returning, because a config
|
|
97
|
+
* can carry more than one: Anthropic's `{ apiKey, authToken }` meant an
|
|
98
|
+
* environment-read `apiKey` returned early and a hardcoded `authToken` right
|
|
99
|
+
* after it was never inspected. `safe` is only the verdict once every property
|
|
100
|
+
* has been looked at.
|
|
101
|
+
*/
|
|
102
|
+
export declare function readCredential(options: TSESTree.ObjectExpression, keyProps: ReadonlySet<string>): KeyVerdict;
|
|
103
|
+
/**
|
|
104
|
+
* The callee name of a `new X(...)` / `X(...)`, if it is statically known.
|
|
105
|
+
* `new pkg.Client()` counts as `Client` — the namespace is not the identity.
|
|
106
|
+
*/
|
|
107
|
+
export declare function calleeName(node: TSESTree.Node): string | undefined;
|
|
108
|
+
export declare function createSdkApiKeyRule(config: SdkApiKeyRuleConfig): import("./rule-creator").RuleModuleWithName<"hardcodedApiKey", [], unknown>;
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.POSITIONAL_KEY_LABEL = void 0;
|
|
4
|
+
exports.matchesModule = matchesModule;
|
|
5
|
+
exports.readCredential = readCredential;
|
|
6
|
+
exports.calleeName = calleeName;
|
|
7
|
+
exports.createSdkApiKeyRule = createSdkApiKeyRule;
|
|
8
|
+
const rule_creator_1 = require("./rule-creator");
|
|
9
|
+
const messaging_1 = require("../messaging");
|
|
10
|
+
exports.POSITIONAL_KEY_LABEL = 'The first argument';
|
|
11
|
+
function matchesModule(source, modules) {
|
|
12
|
+
return modules.some((m) => source === m || source.startsWith(`${m}/`));
|
|
13
|
+
}
|
|
14
|
+
function readCredential(options, keyProps) {
|
|
15
|
+
for (const prop of options.properties) {
|
|
16
|
+
if (prop.type === 'SpreadElement')
|
|
17
|
+
return { kind: 'unreadable' };
|
|
18
|
+
if (prop.computed)
|
|
19
|
+
continue;
|
|
20
|
+
const name = prop.key.type === 'Identifier' ? prop.key.name : String(prop.key.value);
|
|
21
|
+
if (!keyProps.has(name))
|
|
22
|
+
continue;
|
|
23
|
+
if (prop.value.type !== 'Literal')
|
|
24
|
+
continue;
|
|
25
|
+
if (typeof prop.value.value === 'string' && prop.value.value.length > 0) {
|
|
26
|
+
return { kind: 'literal', prop: name };
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return { kind: 'safe' };
|
|
30
|
+
}
|
|
31
|
+
function calleeName(node) {
|
|
32
|
+
if (node.type === 'Identifier')
|
|
33
|
+
return node.name;
|
|
34
|
+
if (node.type === 'MemberExpression' && !node.computed && node.property.type === 'Identifier') {
|
|
35
|
+
return node.property.name;
|
|
36
|
+
}
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
function createSdkApiKeyRule(config) {
|
|
40
|
+
const keyProps = new Set(config.keyProps);
|
|
41
|
+
const positional = new Set(config.positionalKeyConstructors ?? []);
|
|
42
|
+
return (0, rule_creator_1.createRule)({
|
|
43
|
+
name: config.ruleName,
|
|
44
|
+
meta: {
|
|
45
|
+
type: 'problem',
|
|
46
|
+
docs: {
|
|
47
|
+
url: config.docsUrl,
|
|
48
|
+
description: `Forbid a literal API key in the ${config.vendor} client options`,
|
|
49
|
+
cwe: 'CWE-798',
|
|
50
|
+
cvss: 9.1,
|
|
51
|
+
},
|
|
52
|
+
messages: {
|
|
53
|
+
hardcodedApiKey: (0, messaging_1.formatLLMMessage)({
|
|
54
|
+
icon: messaging_1.MessageIcons.SECURITY,
|
|
55
|
+
issueName: `Hardcoded ${config.vendor} Credential`,
|
|
56
|
+
cwe: 'CWE-798',
|
|
57
|
+
owasp: 'A07:2021',
|
|
58
|
+
cvss: 9.1,
|
|
59
|
+
description: '{{prop}} is a string literal, so the credential is committed to source control and readable by anyone with repository access',
|
|
60
|
+
severity: 'CRITICAL',
|
|
61
|
+
compliance: ['SOC2', 'PCI-DSS'],
|
|
62
|
+
fix: `Read it from the environment: ${config.fixTemplate}`,
|
|
63
|
+
documentationLink: config.documentationLink,
|
|
64
|
+
}),
|
|
65
|
+
},
|
|
66
|
+
schema: [],
|
|
67
|
+
},
|
|
68
|
+
defaultOptions: [],
|
|
69
|
+
create(context) {
|
|
70
|
+
let importsSdk = false;
|
|
71
|
+
const candidates = [];
|
|
72
|
+
function inspect(node, args) {
|
|
73
|
+
const first = args[0];
|
|
74
|
+
if (first === undefined)
|
|
75
|
+
return;
|
|
76
|
+
if (first.type === 'Literal') {
|
|
77
|
+
const name = calleeName(node.callee);
|
|
78
|
+
if (name !== undefined &&
|
|
79
|
+
positional.has(name) &&
|
|
80
|
+
typeof first.value === 'string' &&
|
|
81
|
+
first.value.length > 0) {
|
|
82
|
+
candidates.push({ node, prop: exports.POSITIONAL_KEY_LABEL });
|
|
83
|
+
}
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
if (first.type !== 'ObjectExpression')
|
|
87
|
+
return;
|
|
88
|
+
const verdict = readCredential(first, keyProps);
|
|
89
|
+
if (verdict.kind === 'literal')
|
|
90
|
+
candidates.push({ node, prop: verdict.prop });
|
|
91
|
+
}
|
|
92
|
+
return {
|
|
93
|
+
ImportDeclaration(node) {
|
|
94
|
+
if (matchesModule(String(node.source.value), config.modules))
|
|
95
|
+
importsSdk = true;
|
|
96
|
+
},
|
|
97
|
+
NewExpression(node) {
|
|
98
|
+
inspect(node, node.arguments);
|
|
99
|
+
},
|
|
100
|
+
CallExpression(node) {
|
|
101
|
+
if (node.callee.type === 'Identifier' &&
|
|
102
|
+
node.callee.name === 'require' &&
|
|
103
|
+
node.arguments[0]?.type === 'Literal' &&
|
|
104
|
+
typeof node.arguments[0].value === 'string' &&
|
|
105
|
+
matchesModule(node.arguments[0].value, config.modules)) {
|
|
106
|
+
importsSdk = true;
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
inspect(node, node.arguments);
|
|
110
|
+
},
|
|
111
|
+
'Program:exit'() {
|
|
112
|
+
if (!importsSdk)
|
|
113
|
+
return;
|
|
114
|
+
for (const { node, prop } of candidates) {
|
|
115
|
+
context.report({ node, messageId: 'hardcodedApiKey', data: { prop } });
|
|
116
|
+
}
|
|
117
|
+
},
|
|
118
|
+
};
|
|
119
|
+
},
|
|
120
|
+
});
|
|
121
|
+
}
|