@interlace/eslint-devkit 1.8.0 → 1.10.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/aria-definitions.js +1 -990
- package/src/ast/ast-utils.js +1 -133
- package/src/ast/index.js +1 -17
- package/src/ast-node-types.js +1 -174
- package/src/index.js +1 -43
- package/src/messaging/config.js +1 -98
- package/src/messaging/constants.js +1 -678
- package/src/messaging/formatters-ai.js +2 -176
- package/src/messaging/formatters-v2.js +10 -212
- package/src/messaging/formatters.js +3 -186
- package/src/messaging/index.js +1 -21
- package/src/messaging/types-v2.js +1 -2
- package/src/messaging/types.js +1 -2
- package/src/node/fs.js +1 -104
- package/src/node/index.js +1 -19
- package/src/node/os.js +1 -52
- package/src/node/path.js +1 -143
- package/src/resolver/dependency-analysis.js +1 -740
- package/src/resolver/index.js +1 -20
- package/src/resolver/resolver-adapter.js +1 -92
- package/src/resolver/resolver-detection.js +1 -189
- package/src/resolver/resolver.js +1 -206
- package/src/resolver.js +1 -17
- package/src/rule-creation/browser-escape-hatch-rule.d.ts +72 -0
- package/src/rule-creation/browser-escape-hatch-rule.js +1 -0
- package/src/rule-creation/hardcoded-credentials-rule.d.ts +81 -0
- package/src/rule-creation/hardcoded-credentials-rule.js +1 -0
- package/src/rule-creation/index.d.ts +6 -0
- package/src/rule-creation/index.js +1 -21
- package/src/rule-creation/mass-assignment-rule.d.ts +79 -0
- package/src/rule-creation/mass-assignment-rule.js +1 -0
- package/src/rule-creation/mock-context.js +1 -39
- package/src/rule-creation/raw-identifier-rule.d.ts +127 -0
- package/src/rule-creation/raw-identifier-rule.js +1 -0
- package/src/rule-creation/require-tls-rule.d.ts +1 -1
- package/src/rule-creation/require-tls-rule.js +1 -190
- package/src/rule-creation/rule-creator.js +1 -70
- package/src/rule-creation/sdk-api-key-rule.d.ts +108 -0
- package/src/rule-creation/sdk-api-key-rule.js +1 -0
- package/src/rule-creation/sql-injection-rule.js +1 -207
- package/src/rule-creation/system-prompt-injection-rule.d.ts +78 -0
- package/src/rule-creation/system-prompt-injection-rule.js +1 -0
- package/src/rule-creation/unscoped-mutation-rule.js +1 -234
- package/src/security/index.js +1 -17
- package/src/security/security-utils.js +1 -461
- package/src/types/index.js +1 -18
- package/src/types/meta-augmentation.js +1 -2
- package/src/types/type-utils.js +1 -222
|
@@ -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 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.urlEmbedsCredentials=urlEmbedsCredentials;exports.staticStringValue=staticStringValue;exports.isLiteralSecret=isLiteralSecret;exports.createHardcodedCredentialsRule=createHardcodedCredentialsRule;const ast_node_types_1=require("../ast-node-types");const messaging_1=require("../messaging");const unscoped_mutation_rule_1=require("./unscoped-mutation-rule");const require_tls_rule_1=require("./require-tls-rule");const CREDENTIAL_KEYS=["password","pass","pwd","secret","passwd","auth"];const DEFAULT_CONNECTION_KEYS=["host","hostname","port","database","connectionString","socketPath","uri","url","connection","pool","schema"];function urlEmbedsCredentials(value,schemes){const match=/^([a-z][a-z0-9+.-]*):\/\/([^/@\s:]*:[^/@\s]+)@/i.exec(value);if(match===null)return false;return schemes.some(scheme=>scheme.toLowerCase()===match[1].toLowerCase())}function staticStringValue(node){if(node.type===ast_node_types_1.AST_NODE_TYPES.Literal){return typeof node.value==="string"?node.value:void 0}if(node.type===ast_node_types_1.AST_NODE_TYPES.TemplateLiteral&&node.expressions.length===0){return node.quasis[0].value.cooked}return void 0}function isLiteralSecret(node){const value=staticStringValue(node);return value!==void 0&&value.length>0}function createHardcodedCredentialsRule(config){const connectionKeys=[...DEFAULT_CONNECTION_KEYS,...config.connectionKeys??[]];return{meta:{type:config.meta.type,docs:{...config.meta.docs},messages:{hardcodedPassword:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"Hardcoded Credentials",description:"A database password is written as a literal. It is in git history, every fork, and the built image \u2014 rotating it means rewriting history, so it never gets rotated.",severity:"CRITICAL",cwe:config.meta.docs.cwe,owasp:"A07:2021",compliance:["SOC2","PCI-DSS","ISO27001","NIST-CSF"],effort:"low",fix:config.fix,documentationLink:config.documentationLink}),credentialsInUrl:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"Hardcoded Credentials",description:"A connection URL embeds a password in its userinfo section, so the secret is committed with the string.",severity:"CRITICAL",cwe:config.meta.docs.cwe,owasp:"A07:2021",compliance:["SOC2","PCI-DSS","ISO27001","NIST-CSF"],effort:"low",fix:config.urlFix,documentationLink:config.documentationLink})},schema:[]},defaultOptions:[],create(context){let bindings=new Set;let reported=new WeakSet;let scanned=new WeakSet;const report=(node,messageId)=>{if(reported.has(node))return;reported.add(node);context.report({node,messageId})};const scanConfig=obj=>{if(scanned.has(obj))return;scanned.add(obj);for(const prop of obj.properties){if(prop.type!==ast_node_types_1.AST_NODE_TYPES.Property)continue;const name=(0,unscoped_mutation_rule_1.propertyKeyName)(prop);if(name===void 0)continue;if(CREDENTIAL_KEYS.includes(name.toLowerCase())){if(isLiteralSecret(prop.value))report(prop.value,"hardcodedPassword");continue}const url=staticStringValue(prop.value);if(url!==void 0&&urlEmbedsCredentials(url,config.urlSchemes)){report(prop.value,"credentialsInUrl");continue}if(prop.value.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression&&connectionKeys.includes(name)){scanConfig(prop.value)}}};return{Program(program){bindings=(0,unscoped_mutation_rule_1.driverBindings)(program,config.modules);reported=new WeakSet;scanned=new WeakSet},ObjectExpression(node){if(bindings.size===0)return;if(!(0,require_tls_rule_1.looksLikeConnectionConfig)(node,connectionKeys))return;scanConfig(node)},"Literal, TemplateLiteral"(node){if(bindings.size===0)return;const value=staticStringValue(node);if(value===void 0)return;if(!urlEmbedsCredentials(value,config.urlSchemes))return;if(!(0,require_tls_rule_1.inConnectionPosition)(node,connectionKeys,bindings))return;report(node,"credentialsInUrl")}}}}}
|
|
@@ -8,3 +8,9 @@ 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 './system-prompt-injection-rule';
|
|
16
|
+
export * from './raw-identifier-rule';
|
|
@@ -1,21 +1 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
-
if (k2 === undefined) k2 = k;
|
|
4
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
-
}
|
|
8
|
-
Object.defineProperty(o, k2, desc);
|
|
9
|
-
}) : (function(o, m, k, k2) {
|
|
10
|
-
if (k2 === undefined) k2 = k;
|
|
11
|
-
o[k2] = m[k];
|
|
12
|
-
}));
|
|
13
|
-
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
-
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
-
};
|
|
16
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
__exportStar(require("./rule-creator"), exports);
|
|
18
|
-
__exportStar(require("./mock-context"), exports);
|
|
19
|
-
__exportStar(require("./sql-injection-rule"), exports);
|
|
20
|
-
__exportStar(require("./unscoped-mutation-rule"), exports);
|
|
21
|
-
__exportStar(require("./require-tls-rule"), exports);
|
|
1
|
+
"use strict";var __createBinding=this&&this.__createBinding||(Object.create?(function(o,m,k,k2){if(k2===void 0)k2=k;var desc=Object.getOwnPropertyDescriptor(m,k);if(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable)){desc={enumerable:true,get:function(){return m[k]}}}Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){if(k2===void 0)k2=k;o[k2]=m[k]}));var __exportStar=this&&this.__exportStar||function(m,exports2){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p))__createBinding(exports2,m,p)};Object.defineProperty(exports,"__esModule",{value:true});__exportStar(require("./rule-creator"),exports);__exportStar(require("./mock-context"),exports);__exportStar(require("./sql-injection-rule"),exports);__exportStar(require("./unscoped-mutation-rule"),exports);__exportStar(require("./require-tls-rule"),exports);__exportStar(require("./mass-assignment-rule"),exports);__exportStar(require("./hardcoded-credentials-rule"),exports);__exportStar(require("./sdk-api-key-rule"),exports);__exportStar(require("./browser-escape-hatch-rule"),exports);__exportStar(require("./system-prompt-injection-rule"),exports);__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 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isUntrustedSource=isUntrustedSource;exports.classifyPayload=classifyPayload;exports.createMassAssignmentRule=createMassAssignmentRule;const ast_node_types_1=require("../ast-node-types");const messaging_1=require("../messaging");const unscoped_mutation_rule_1=require("./unscoped-mutation-rule");const REQUEST_OBJECTS=["req","request","ctx","context","event"];const UNTRUSTED_PROPS=["body","query","params","payload"];function isUntrustedSource(node){if(node.type!==ast_node_types_1.AST_NODE_TYPES.MemberExpression||node.computed)return false;if(node.property.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return false;if(!UNTRUSTED_PROPS.includes(node.property.name)){return false}return baseIsRequest(node.object)}function baseIsRequest(node){let cursor=node;while(cursor.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression)cursor=cursor.object;return cursor.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&REQUEST_OBJECTS.includes(cursor.name)}function classifyPayload(node){if(isUntrustedSource(node))return"untrustedPayload";if(node.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression){for(const prop of node.properties){if(prop.type!==ast_node_types_1.AST_NODE_TYPES.SpreadElement)continue;if(isUntrustedSource(prop.argument))return"untrustedSpread"}}return false}function createMassAssignmentRule(config){const methods=new Set(config.methods);const payloadKeys=new Set(config.payloadKeys??[]);return{meta:{type:config.meta.type,docs:{...config.meta.docs},messages:{untrustedPayload:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"Mass Assignment",description:"The request object is written straight to the database, so every column the model exposes is settable by the caller \u2014 including ones this code never mentions.",severity:"HIGH",cwe:config.meta.docs.cwe,owasp:"A04:2021",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"medium",fix:config.fix,documentationLink:config.documentationLink}),untrustedSpread:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"Mass Assignment",description:"Spreading the request into the payload carries every key it happens to hold, not just the ones written beside it.",severity:"HIGH",cwe:config.meta.docs.cwe,owasp:"A04:2021",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"medium",fix:config.fix,documentationLink:config.documentationLink})},schema:[]},defaultOptions:[],create(context){let bindings=new Set;return{Program(program){bindings=(0,unscoped_mutation_rule_1.driverBindings)(program,config.modules)},CallExpression(node){if(bindings.size===0)return;if(node.callee.type!==ast_node_types_1.AST_NODE_TYPES.MemberExpression||node.callee.property.type!==ast_node_types_1.AST_NODE_TYPES.Identifier||!methods.has(node.callee.property.name)){return}const base=(0,unscoped_mutation_rule_1.receiverBaseName)(node.callee);if(base===void 0)return;if(!bindings.has(base)&&!config.receiverPattern.test(base))return;for(const arg of node.arguments){if(arg.type===ast_node_types_1.AST_NODE_TYPES.SpreadElement)continue;const direct=classifyPayload(arg);if(direct){context.report({node:arg,messageId:direct});continue}if(arg.type!==ast_node_types_1.AST_NODE_TYPES.ObjectExpression)continue;for(const prop of arg.properties){if(prop.type!==ast_node_types_1.AST_NODE_TYPES.Property)continue;const name=(0,unscoped_mutation_rule_1.propertyKeyName)(prop);if(name===void 0||!payloadKeys.has(name))continue;const nested=classifyPayload(prop.value);if(nested)context.report({node:prop.value,messageId:nested})}}}}}}}
|
|
@@ -1,39 +1 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.createWithMockContext = createWithMockContext;
|
|
4
|
-
function createWithMockContext(rule, opts = {}) {
|
|
5
|
-
const reports = [];
|
|
6
|
-
const filename = opts.filename ?? 'mock.ts';
|
|
7
|
-
const emptyScope = { variables: [], references: [], childScopes: [] };
|
|
8
|
-
const sourceCode = {
|
|
9
|
-
ast: opts.ast ?? { type: 'Program', body: [], tokens: [], comments: [] },
|
|
10
|
-
text: opts.sourceText ?? '',
|
|
11
|
-
getText: () => opts.sourceText ?? '',
|
|
12
|
-
getScope: () => emptyScope,
|
|
13
|
-
getAncestors: () => [],
|
|
14
|
-
getCommentsBefore: () => [],
|
|
15
|
-
getDeclaredVariables: () => [],
|
|
16
|
-
};
|
|
17
|
-
const context = {
|
|
18
|
-
id: 'mock-rule',
|
|
19
|
-
filename,
|
|
20
|
-
physicalFilename: filename,
|
|
21
|
-
cwd: '/',
|
|
22
|
-
options: opts.options ?? rule.defaultOptions ?? [],
|
|
23
|
-
settings: opts.settings ?? {},
|
|
24
|
-
parserOptions: {},
|
|
25
|
-
languageOptions: {},
|
|
26
|
-
sourceCode,
|
|
27
|
-
getFilename: () => filename,
|
|
28
|
-
getPhysicalFilename: () => filename,
|
|
29
|
-
getCwd: () => '/',
|
|
30
|
-
getSourceCode: () => sourceCode,
|
|
31
|
-
getScope: () => emptyScope,
|
|
32
|
-
getAncestors: () => [],
|
|
33
|
-
report: (descriptor) => {
|
|
34
|
-
reports.push(descriptor);
|
|
35
|
-
},
|
|
36
|
-
};
|
|
37
|
-
const listeners = rule.create(context);
|
|
38
|
-
return { listeners, reports, context };
|
|
39
|
-
}
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.createWithMockContext=createWithMockContext;function createWithMockContext(rule,opts={}){const reports=[];const filename=opts.filename??"mock.ts";const emptyScope={variables:[],references:[],childScopes:[]};const sourceCode={ast:opts.ast??{type:"Program",body:[],tokens:[],comments:[]},text:opts.sourceText??"",getText:()=>opts.sourceText??"",getScope:()=>emptyScope,getAncestors:()=>[],getCommentsBefore:()=>[],getDeclaredVariables:()=>[]};const context={id:"mock-rule",filename,physicalFilename:filename,cwd:"/",options:opts.options??rule.defaultOptions??[],settings:opts.settings??{},parserOptions:{},languageOptions:{},sourceCode,getFilename:()=>filename,getPhysicalFilename:()=>filename,getCwd:()=>"/",getSourceCode:()=>sourceCode,getScope:()=>emptyScope,getAncestors:()=>[],report:descriptor=>{reports.push(descriptor)}};const listeners=rule.create(context);return{listeners,reports,context}}
|
|
@@ -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 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.stripIdentifierGap=stripIdentifierGap;exports.lastClause=lastClause;exports.identifierPosition=identifierPosition;exports.calleeText=calleeText;exports.isExemptExpression=isExemptExpression;exports.tagName=tagName;exports.createRawIdentifierRule=createRawIdentifierRule;const ast_node_types_1=require("../ast-node-types");const messaging_1=require("../messaging");const unscoped_mutation_rule_1=require("./unscoped-mutation-rule");const IDENTIFIER_KEYWORDS=/\b(?:from|join|into|update|table|order\s+by|group\s+by|select|distinct\s+on)$/i;const GAP_CHAR=/[\s"'`[]/;function stripIdentifierGap(text){let end=text.length;while(end>0&&GAP_CHAR.test(text[end-1]))end--;return text.slice(0,end)}const CLAUSE_KEYWORDS=/\b(select|from|where|group\s+by|having|order\s+by|limit|offset|union|returning|values|set)\b/gi;function lastClause(text){const matches=[...text.matchAll(CLAUSE_KEYWORDS)];const last=matches.at(-1);return last?last[1].toLowerCase().replace(/\s+/g," "):""}function identifierPosition(precedingText){if(IDENTIFIER_KEYWORDS.test(stripIdentifierGap(precedingText)))return"identifier";if(lastClause(precedingText)==="order by")return"sortDirection";return false}function calleeText(node){if(node.type===ast_node_types_1.AST_NODE_TYPES.Identifier)return node.name;if(node.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&!node.computed){const object=calleeText(node.object);const property=calleeText(node.property);return object&&property?`${object}.${property}`:""}return""}function isExemptExpression(expr,identifierHelpers,tags){if(expr.type===ast_node_types_1.AST_NODE_TYPES.Literal)return true;if(expr.type===ast_node_types_1.AST_NODE_TYPES.CallExpression){if(identifierHelpers.includes(calleeText(expr.callee)))return true}if(expr.type===ast_node_types_1.AST_NODE_TYPES.TaggedTemplateExpression){const nested=tagName(expr.tag);return nested!==void 0&&tags.includes(nested)}return false}function tagName(tag){if(tag.type===ast_node_types_1.AST_NODE_TYPES.Identifier)return tag.name;if(tag.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&!tag.computed&&tag.property.type===ast_node_types_1.AST_NODE_TYPES.Identifier){return tag.property.name}return void 0}function createRawIdentifierRule(config){const tags=new Set(config.tags);return{meta:{type:config.meta.type,docs:{...config.meta.docs},messages:{identifierInterpolation:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"SQL Injection Risk",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.",severity:"CRITICAL",cwe:config.meta.docs.cwe,owasp:"A03:2021",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"medium",fix:config.fix,documentationLink:config.documentationLink}),sortDirectionInterpolation:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"SQL Injection Risk",description:"A value is interpolated inside an ORDER BY clause, where a bind parameter cannot reach.",severity:"HIGH",cwe:config.meta.docs.cwe,owasp:"A03:2021",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"low",fix:config.sortDirectionFix,documentationLink:config.documentationLink})},schema:[]},defaultOptions:[],create(context){let bindings=new Set;return{Program(program){bindings=(0,unscoped_mutation_rule_1.driverBindings)(program,config.modules)},TaggedTemplateExpression(node){const name=tagName(node.tag);if(name===void 0||!tags.has(name))return;if(config.requireImport){if(node.tag.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return;if(!bindings.has(name))return}const{quasis,expressions}=node.quasi;expressions.forEach((expr,index)=>{if(isExemptExpression(expr,config.identifierHelpers,config.tags))return;const preceding=quasis.slice(0,index+1).map(q=>q.value.raw).join(" ");const position=identifierPosition(preceding);if(position===false)return;context.report({node:expr,messageId:position==="identifier"?"identifierInterpolation":"sortDirectionInterpolation"})})}}}}}
|
|
@@ -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
|
*
|
|
@@ -1,190 +1 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.isLiteralBoolean = isLiteralBoolean;
|
|
4
|
-
exports.looksLikeConnectionConfig = looksLikeConnectionConfig;
|
|
5
|
-
exports.urlDisablesTls = urlDisablesTls;
|
|
6
|
-
exports.inConnectionPosition = inConnectionPosition;
|
|
7
|
-
exports.createRequireTlsRule = createRequireTlsRule;
|
|
8
|
-
const ast_node_types_1 = require("../ast-node-types");
|
|
9
|
-
const messaging_1 = require("../messaging");
|
|
10
|
-
const unscoped_mutation_rule_1 = require("./unscoped-mutation-rule");
|
|
11
|
-
const DEFAULT_CONNECTION_KEYS = [
|
|
12
|
-
'host',
|
|
13
|
-
'hostname',
|
|
14
|
-
'port',
|
|
15
|
-
'user',
|
|
16
|
-
'username',
|
|
17
|
-
'password',
|
|
18
|
-
'database',
|
|
19
|
-
'connectionString',
|
|
20
|
-
'socketPath',
|
|
21
|
-
'uri',
|
|
22
|
-
'url',
|
|
23
|
-
'connection',
|
|
24
|
-
'pool',
|
|
25
|
-
'schema',
|
|
26
|
-
];
|
|
27
|
-
const TLS_OFF_KEYS = ['ssl', 'secure', 'tls', 'encrypt', 'useSSL', 'requireSSL'];
|
|
28
|
-
const VERIFY_OFF_KEYS = [
|
|
29
|
-
'rejectUnauthorized',
|
|
30
|
-
'verifyServerCertificate',
|
|
31
|
-
'checkServerIdentity',
|
|
32
|
-
'trustServerCertificate',
|
|
33
|
-
];
|
|
34
|
-
function isLiteralBoolean(value, expect) {
|
|
35
|
-
if (value.type !== ast_node_types_1.AST_NODE_TYPES.Literal)
|
|
36
|
-
return false;
|
|
37
|
-
if (typeof value.value !== 'boolean') {
|
|
38
|
-
return expect === false && !value.value;
|
|
39
|
-
}
|
|
40
|
-
return value.value === expect;
|
|
41
|
-
}
|
|
42
|
-
function looksLikeConnectionConfig(obj, connectionKeys) {
|
|
43
|
-
return obj.properties.some((prop) => {
|
|
44
|
-
const name = (0, unscoped_mutation_rule_1.propertyKeyName)(prop);
|
|
45
|
-
return name !== undefined && connectionKeys.includes(name);
|
|
46
|
-
});
|
|
47
|
-
}
|
|
48
|
-
function urlDisablesTls(value, schemes) {
|
|
49
|
-
if (!schemes.some((scheme) => value.startsWith(`${scheme}://`)))
|
|
50
|
-
return false;
|
|
51
|
-
const query = value.split('#')[0];
|
|
52
|
-
return /[?&](?:sslmode=disable|ssl=(?:false|0))(?:&|$)/i.test(query);
|
|
53
|
-
}
|
|
54
|
-
function inConnectionPosition(node, connectionKeys, bindings) {
|
|
55
|
-
const parent = node.parent;
|
|
56
|
-
if (!parent)
|
|
57
|
-
return false;
|
|
58
|
-
if (parent.type === ast_node_types_1.AST_NODE_TYPES.Property && parent.value === node) {
|
|
59
|
-
const name = (0, unscoped_mutation_rule_1.propertyKeyName)(parent);
|
|
60
|
-
return name !== undefined && connectionKeys.includes(name);
|
|
61
|
-
}
|
|
62
|
-
if (parent.type === ast_node_types_1.AST_NODE_TYPES.CallExpression ||
|
|
63
|
-
parent.type === ast_node_types_1.AST_NODE_TYPES.NewExpression) {
|
|
64
|
-
if (!parent.arguments.includes(node))
|
|
65
|
-
return false;
|
|
66
|
-
return calleeBaseIsDriver(parent.callee, bindings);
|
|
67
|
-
}
|
|
68
|
-
return false;
|
|
69
|
-
}
|
|
70
|
-
function calleeBaseIsDriver(callee, bindings) {
|
|
71
|
-
let cursor = callee;
|
|
72
|
-
for (;;) {
|
|
73
|
-
if (cursor.type === ast_node_types_1.AST_NODE_TYPES.MemberExpression) {
|
|
74
|
-
cursor = cursor.object;
|
|
75
|
-
continue;
|
|
76
|
-
}
|
|
77
|
-
if (cursor.type === ast_node_types_1.AST_NODE_TYPES.CallExpression) {
|
|
78
|
-
cursor = cursor.callee;
|
|
79
|
-
continue;
|
|
80
|
-
}
|
|
81
|
-
return cursor.type === ast_node_types_1.AST_NODE_TYPES.Identifier && bindings.has(cursor.name);
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
function createRequireTlsRule(config) {
|
|
85
|
-
const connectionKeys = [...DEFAULT_CONNECTION_KEYS, ...(config.connectionKeys ?? [])];
|
|
86
|
-
const urlSchemes = config.urlSchemes ?? [];
|
|
87
|
-
return {
|
|
88
|
-
meta: {
|
|
89
|
-
type: config.meta.type,
|
|
90
|
-
docs: { ...config.meta.docs },
|
|
91
|
-
messages: {
|
|
92
|
-
tlsDisabled: (0, messaging_1.formatLLMMessage)({
|
|
93
|
-
icon: messaging_1.MessageIcons.SECURITY,
|
|
94
|
-
issueName: 'Cleartext Database Connection',
|
|
95
|
-
description: 'TLS is explicitly disabled on this database connection. Queries, result rows and the credentials that open the session all cross the network in cleartext.',
|
|
96
|
-
severity: 'HIGH',
|
|
97
|
-
cwe: config.meta.docs.cwe,
|
|
98
|
-
owasp: 'A02:2021',
|
|
99
|
-
compliance: ['SOC2', 'PCI-DSS', 'HIPAA', 'NIST-CSF'],
|
|
100
|
-
effort: 'low',
|
|
101
|
-
fix: config.fix,
|
|
102
|
-
documentationLink: config.documentationLink,
|
|
103
|
-
}),
|
|
104
|
-
certificateValidationDisabled: (0, messaging_1.formatLLMMessage)({
|
|
105
|
-
icon: messaging_1.MessageIcons.SECURITY,
|
|
106
|
-
issueName: 'Unverified Database TLS Peer',
|
|
107
|
-
description: 'Certificate validation is disabled on this database connection. The traffic is encrypted but the server is never authenticated, so it encrypts just as willingly to whoever answered in its place.',
|
|
108
|
-
severity: 'HIGH',
|
|
109
|
-
cwe: config.meta.docs.cwe,
|
|
110
|
-
owasp: 'A02:2021',
|
|
111
|
-
compliance: ['SOC2', 'PCI-DSS', 'HIPAA', 'NIST-CSF'],
|
|
112
|
-
effort: 'medium',
|
|
113
|
-
fix: 'Supply the server CA instead of switching verification off — `ssl: { ca: fs.readFileSync(caPath) }`. If the certificate is self-signed, add that CA to the trust store rather than trusting everything.',
|
|
114
|
-
documentationLink: config.documentationLink,
|
|
115
|
-
}),
|
|
116
|
-
},
|
|
117
|
-
schema: [],
|
|
118
|
-
},
|
|
119
|
-
defaultOptions: [],
|
|
120
|
-
create(context) {
|
|
121
|
-
let bindings = new Set();
|
|
122
|
-
let reported = new WeakSet();
|
|
123
|
-
const report = (prop, messageId) => {
|
|
124
|
-
if (reported.has(prop))
|
|
125
|
-
return;
|
|
126
|
-
reported.add(prop);
|
|
127
|
-
context.report({ node: prop, messageId });
|
|
128
|
-
};
|
|
129
|
-
const reportVerifyOffProperty = (prop, name) => {
|
|
130
|
-
if (!VERIFY_OFF_KEYS.includes(name))
|
|
131
|
-
return;
|
|
132
|
-
const inverted = name === 'trustServerCertificate';
|
|
133
|
-
if (!isLiteralBoolean(prop.value, inverted))
|
|
134
|
-
return;
|
|
135
|
-
report(prop, 'certificateValidationDisabled');
|
|
136
|
-
};
|
|
137
|
-
const scanTlsKeys = (obj) => {
|
|
138
|
-
for (const prop of obj.properties) {
|
|
139
|
-
if (prop.type !== ast_node_types_1.AST_NODE_TYPES.Property)
|
|
140
|
-
continue;
|
|
141
|
-
const name = (0, unscoped_mutation_rule_1.propertyKeyName)(prop);
|
|
142
|
-
if (name === undefined)
|
|
143
|
-
continue;
|
|
144
|
-
if (TLS_OFF_KEYS.includes(name)) {
|
|
145
|
-
if (isLiteralBoolean(prop.value, false)) {
|
|
146
|
-
report(prop, 'tlsDisabled');
|
|
147
|
-
continue;
|
|
148
|
-
}
|
|
149
|
-
if (prop.value.type === ast_node_types_1.AST_NODE_TYPES.ObjectExpression) {
|
|
150
|
-
scanTlsKeys(prop.value);
|
|
151
|
-
}
|
|
152
|
-
continue;
|
|
153
|
-
}
|
|
154
|
-
reportVerifyOffProperty(prop, name);
|
|
155
|
-
if (prop.value.type === ast_node_types_1.AST_NODE_TYPES.ObjectExpression &&
|
|
156
|
-
connectionKeys.includes(name)) {
|
|
157
|
-
scanTlsKeys(prop.value);
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
};
|
|
161
|
-
const checkObject = (obj) => {
|
|
162
|
-
if (!looksLikeConnectionConfig(obj, connectionKeys))
|
|
163
|
-
return;
|
|
164
|
-
scanTlsKeys(obj);
|
|
165
|
-
};
|
|
166
|
-
return {
|
|
167
|
-
Program(program) {
|
|
168
|
-
bindings = (0, unscoped_mutation_rule_1.driverBindings)(program, config.modules);
|
|
169
|
-
reported = new WeakSet();
|
|
170
|
-
},
|
|
171
|
-
ObjectExpression(node) {
|
|
172
|
-
if (bindings.size === 0)
|
|
173
|
-
return;
|
|
174
|
-
checkObject(node);
|
|
175
|
-
},
|
|
176
|
-
Literal(node) {
|
|
177
|
-
if (bindings.size === 0)
|
|
178
|
-
return;
|
|
179
|
-
if (typeof node.value !== 'string')
|
|
180
|
-
return;
|
|
181
|
-
if (!urlDisablesTls(node.value, urlSchemes))
|
|
182
|
-
return;
|
|
183
|
-
if (!inConnectionPosition(node, connectionKeys, bindings))
|
|
184
|
-
return;
|
|
185
|
-
context.report({ node, messageId: 'tlsDisabled' });
|
|
186
|
-
},
|
|
187
|
-
};
|
|
188
|
-
},
|
|
189
|
-
};
|
|
190
|
-
}
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isLiteralBoolean=isLiteralBoolean;exports.looksLikeConnectionConfig=looksLikeConnectionConfig;exports.urlDisablesTls=urlDisablesTls;exports.inConnectionPosition=inConnectionPosition;exports.createRequireTlsRule=createRequireTlsRule;const ast_node_types_1=require("../ast-node-types");const messaging_1=require("../messaging");const unscoped_mutation_rule_1=require("./unscoped-mutation-rule");const DEFAULT_CONNECTION_KEYS=["host","hostname","port","user","username","password","database","connectionString","socketPath","uri","url","connection","pool","schema"];const TLS_OFF_KEYS=["ssl","secure","tls","encrypt","useSSL","requireSSL"];const VERIFY_OFF_KEYS=["rejectUnauthorized","verifyServerCertificate","checkServerIdentity","trustServerCertificate"];function isLiteralBoolean(value,expect){if(value.type!==ast_node_types_1.AST_NODE_TYPES.Literal)return false;if(typeof value.value!=="boolean"){return expect===false&&!value.value}return value.value===expect}function looksLikeConnectionConfig(obj,connectionKeys){return obj.properties.some(prop=>{const name=(0,unscoped_mutation_rule_1.propertyKeyName)(prop);return name!==void 0&&connectionKeys.includes(name)})}function urlDisablesTls(value,schemes){if(!schemes.some(scheme=>value.startsWith(`${scheme}://`)))return false;const query=value.split("#")[0];return/[?&](?:sslmode=disable|ssl=(?:false|0))(?:&|$)/i.test(query)}function inConnectionPosition(node,connectionKeys,bindings){const parent=node.parent;if(!parent)return false;if(parent.type===ast_node_types_1.AST_NODE_TYPES.Property&&parent.value===node){const name=(0,unscoped_mutation_rule_1.propertyKeyName)(parent);return name!==void 0&&connectionKeys.includes(name)}if(parent.type===ast_node_types_1.AST_NODE_TYPES.CallExpression||parent.type===ast_node_types_1.AST_NODE_TYPES.NewExpression){if(!parent.arguments.includes(node))return false;return calleeBaseIsDriver(parent.callee,bindings)}return false}function calleeBaseIsDriver(callee,bindings){let cursor=callee;for(;;){if(cursor.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression){cursor=cursor.object;continue}if(cursor.type===ast_node_types_1.AST_NODE_TYPES.CallExpression){cursor=cursor.callee;continue}return cursor.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&bindings.has(cursor.name)}}function createRequireTlsRule(config){const connectionKeys=[...DEFAULT_CONNECTION_KEYS,...config.connectionKeys??[]];const urlSchemes=config.urlSchemes??[];return{meta:{type:config.meta.type,docs:{...config.meta.docs},messages:{tlsDisabled:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"Cleartext Database Connection",description:"TLS is explicitly disabled on this database connection. Queries, result rows and the credentials that open the session all cross the network in cleartext.",severity:"HIGH",cwe:config.meta.docs.cwe,owasp:"A02:2021",compliance:["SOC2","PCI-DSS","HIPAA","NIST-CSF"],effort:"low",fix:config.fix,documentationLink:config.documentationLink}),certificateValidationDisabled:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"Unverified Database TLS Peer",description:"Certificate validation is disabled on this database connection. The traffic is encrypted but the server is never authenticated, so it encrypts just as willingly to whoever answered in its place.",severity:"HIGH",cwe:config.meta.docs.cwe,owasp:"A02:2021",compliance:["SOC2","PCI-DSS","HIPAA","NIST-CSF"],effort:"medium",fix:"Supply the server CA instead of switching verification off \u2014 `ssl: { ca: fs.readFileSync(caPath) }`. If the certificate is self-signed, add that CA to the trust store rather than trusting everything.",documentationLink:config.documentationLink})},schema:[]},defaultOptions:[],create(context){let bindings=new Set;let reported=new WeakSet;const report=(prop,messageId)=>{if(reported.has(prop))return;reported.add(prop);context.report({node:prop,messageId})};const reportVerifyOffProperty=(prop,name)=>{if(!VERIFY_OFF_KEYS.includes(name))return;const inverted=name==="trustServerCertificate";if(!isLiteralBoolean(prop.value,inverted))return;report(prop,"certificateValidationDisabled")};const scanTlsKeys=obj=>{for(const prop of obj.properties){if(prop.type!==ast_node_types_1.AST_NODE_TYPES.Property)continue;const name=(0,unscoped_mutation_rule_1.propertyKeyName)(prop);if(name===void 0)continue;if(TLS_OFF_KEYS.includes(name)){if(isLiteralBoolean(prop.value,false)){report(prop,"tlsDisabled");continue}if(prop.value.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression){scanTlsKeys(prop.value)}continue}reportVerifyOffProperty(prop,name);if(prop.value.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression&&connectionKeys.includes(name)){scanTlsKeys(prop.value)}}};const checkObject=obj=>{if(!looksLikeConnectionConfig(obj,connectionKeys))return;scanTlsKeys(obj)};return{Program(program){bindings=(0,unscoped_mutation_rule_1.driverBindings)(program,config.modules);reported=new WeakSet},ObjectExpression(node){if(bindings.size===0)return;checkObject(node)},Literal(node){if(bindings.size===0)return;if(typeof node.value!=="string")return;if(!urlDisablesTls(node.value,urlSchemes))return;if(!inConnectionPosition(node,connectionKeys,bindings))return;context.report({node,messageId:"tlsDisabled"})}}}}}
|