@interlace/eslint-devkit 1.19.8 → 1.20.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 +35 -1
- package/src/rule-creation/browser-escape-hatch-rule.js +1 -1
- package/src/rule-creation/connection-config.d.ts +49 -0
- package/src/rule-creation/connection-config.js +1 -0
- package/src/rule-creation/driver-origin.d.ts +52 -0
- package/src/rule-creation/driver-origin.js +1 -0
- package/src/rule-creation/hardcoded-credentials-rule.d.ts +18 -0
- package/src/rule-creation/hardcoded-credentials-rule.js +1 -1
- package/src/rule-creation/index.d.ts +1 -0
- package/src/rule-creation/index.js +1 -1
- package/src/rule-creation/mass-assignment-rule.d.ts +31 -26
- package/src/rule-creation/mass-assignment-rule.js +1 -1
- package/src/rule-creation/module-evidence.d.ts +7 -34
- package/src/rule-creation/module-evidence.js +1 -1
- package/src/rule-creation/raw-identifier-rule.d.ts +8 -0
- package/src/rule-creation/raw-identifier-rule.js +1 -1
- package/src/rule-creation/request-source.d.ts +36 -0
- package/src/rule-creation/request-source.js +1 -0
- package/src/rule-creation/require-tls-rule.d.ts +9 -1
- package/src/rule-creation/require-tls-rule.js +1 -1
- package/src/rule-creation/sdk-api-key-rule.d.ts +13 -2
- package/src/rule-creation/sdk-api-key-rule.js +1 -1
- package/src/rule-creation/sdk-flow.d.ts +161 -0
- package/src/rule-creation/sdk-flow.js +1 -0
- package/src/rule-creation/sql-injection-rule.d.ts +86 -9
- package/src/rule-creation/sql-injection-rule.js +1 -1
- package/src/rule-creation/sql-position.d.ts +51 -0
- package/src/rule-creation/sql-position.js +1 -0
- package/src/rule-creation/sql-safety.d.ts +75 -0
- package/src/rule-creation/sql-safety.js +1 -0
- package/src/rule-creation/system-prompt-injection-rule.d.ts +42 -1
- package/src/rule-creation/system-prompt-injection-rule.js +1 -1
- package/src/rule-creation/unscoped-mutation-rule.d.ts +52 -7
- package/src/rule-creation/unscoped-mutation-rule.js +1 -1
- package/src/rule-creation/value-follow.d.ts +108 -0
- package/src/rule-creation/value-follow.js +1 -0
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* MIT license that can be found in the LICENSE file.
|
|
5
5
|
*/
|
|
6
6
|
import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
|
|
7
|
+
import { type ConfigShape } from './connection-config';
|
|
7
8
|
/** Message ids every rule built by this factory reports. */
|
|
8
9
|
export type RequireTlsMessageIds = 'tlsDisabled' | 'certificateValidationDisabled';
|
|
9
10
|
export interface RequireTlsRuleConfig {
|
|
@@ -48,6 +49,11 @@ export interface RequireTlsRuleConfig {
|
|
|
48
49
|
* `sslmode=disable` / `ssl=false`. Omit for drivers that take no URL.
|
|
49
50
|
*/
|
|
50
51
|
readonly urlSchemes?: readonly string[];
|
|
52
|
+
/**
|
|
53
|
+
* The driver's config-file contracts — a knexfile's `{ client: 'pg',
|
|
54
|
+
* connection }` — that mark a file with no driver import as the driver's.
|
|
55
|
+
*/
|
|
56
|
+
readonly configShapes?: readonly ConfigShape[];
|
|
51
57
|
/** Remediation line in the emitted message. */
|
|
52
58
|
readonly fix: string;
|
|
53
59
|
/** Reference link in the emitted message. */
|
|
@@ -83,6 +89,8 @@ export declare function looksLikeConnectionConfig(obj: TSESTree.ObjectExpression
|
|
|
83
89
|
* driver parses as a connection option, so this is not a finding.
|
|
84
90
|
*/
|
|
85
91
|
export declare function urlDisablesTls(value: string, schemes: readonly string[]): boolean;
|
|
92
|
+
/** Is `inner` inside (or the same node as) `outer`? */
|
|
93
|
+
export declare function within(inner: TSESTree.Node, outer: TSESTree.Node): boolean;
|
|
86
94
|
/**
|
|
87
95
|
* Is this string literal actually being used as a connection string?
|
|
88
96
|
*
|
|
@@ -102,7 +110,7 @@ export declare function urlDisablesTls(value: string, schemes: readonly string[]
|
|
|
102
110
|
* plugin the one users switch off. The cost is a false negative when the DSN is
|
|
103
111
|
* built in one statement and passed in another.
|
|
104
112
|
*/
|
|
105
|
-
export declare function inConnectionPosition(node: TSESTree.Literal | TSESTree.TemplateLiteral, connectionKeys: readonly string[],
|
|
113
|
+
export declare function inConnectionPosition(node: TSESTree.Literal | TSESTree.TemplateLiteral, connectionKeys: readonly string[], isDriverCallee: (callee: TSESTree.Node) => boolean): boolean;
|
|
106
114
|
/**
|
|
107
115
|
* Build a CWE-319 rule for the given driver.
|
|
108
116
|
*
|
|
@@ -1 +1 @@
|
|
|
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,
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isLiteralBoolean=isLiteralBoolean;exports.looksLikeConnectionConfig=looksLikeConnectionConfig;exports.urlDisablesTls=urlDisablesTls;exports.within=within;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 module_evidence_1=require("./module-evidence");const rule_creator_1=require("./rule-creator");const driver_origin_1=require("./driver-origin");const connection_config_1=require("./connection-config");const value_follow_1=require("./value-follow");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 within(inner,outer){return outer.range[0]<=inner.range[0]&&inner.range[1]<=outer.range[1]}function inConnectionPosition(node,connectionKeys,isDriverCallee){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 isDriverCallee(parent.callee)}return false}function createRequireTlsRule(config){const connectionKeys=[...DEFAULT_CONNECTION_KEYS,...config.connectionKeys??[]];const urlSchemes=config.urlSchemes??[];const usesModule=(0,module_evidence_1.createModuleEvidence)({packages:config.modules,extraEvidence:(0,connection_config_1.configShapeEvidence)(config.configShapes??[])});const originOf=(0,driver_origin_1.createOriginClassifier)(config.modules);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){if((0,rule_creator_1.isTestFilePath)(context.filename))return{};const env=(0,value_follow_1.envOf)(context);let ownsFile=false;const reported=new WeakSet;const report=(node,messageId)=>{if(reported.has(node))return;reported.add(node);context.report({node,messageId})};const judgeProperty=(prop,name,depth)=>{const tlsKey=TLS_OFF_KEYS.includes(name);const verifyKey=VERIFY_OFF_KEYS.includes(name);const inverted=name==="trustServerCertificate";for(const value of(0,connection_config_1.possibleValues)((0,value_follow_1.valueAt)(prop.value,env))){const inline=value.env===env&&within(value.node,prop.value);if(tlsKey&&isLiteralBoolean(value.node,false)){report(prop,"tlsDisabled");return}if(verifyKey&&isLiteralBoolean(value.node,inverted)){report(prop,"certificateValidationDisabled");return}if(value.node.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression&&(tlsKey||connectionKeys.includes(name))){if(inline)scanTlsKeys(value.node,depth+1);else if(disablesTls(value.node))report(prop,"certificateValidationDisabled")}}};const disablesTls=obj=>obj.properties.some(prop=>prop.type===ast_node_types_1.AST_NODE_TYPES.Property&&VERIFY_OFF_KEYS.includes((0,unscoped_mutation_rule_1.propertyKeyName)(prop))&&isLiteralBoolean(prop.value,(0,unscoped_mutation_rule_1.propertyKeyName)(prop)==="trustServerCertificate"));const scanTlsKeys=(obj,depth=0)=>{if(depth>4)return;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;judgeProperty(prop,name,depth)}};return{Program(program){ownsFile=usesModule(program)},ObjectExpression(node){if(!ownsFile)return;if(!looksLikeConnectionConfig(node,connectionKeys))return;if((0,connection_config_1.passedToForeign)(node,originOf,env))return;scanTlsKeys(node)},Literal(node){if(!ownsFile)return;if(typeof node.value!=="string")return;if(!urlDisablesTls(node.value,urlSchemes))return;if(!inConnectionPosition(node,connectionKeys,isDriverCallee))return;context.report({node,messageId:"tlsDisabled"})}};function isDriverCallee(callee){return originOf((0,value_follow_1.valueAt)(callee,env))==="ours"}}}}
|
|
@@ -54,8 +54,11 @@ export interface SdkApiKeyRuleConfig {
|
|
|
54
54
|
/** Vendor documentation link carried in the message. */
|
|
55
55
|
documentationLink: string;
|
|
56
56
|
/**
|
|
57
|
-
*
|
|
58
|
-
* `new GoogleGenerativeAI('AIza…')`.
|
|
57
|
+
* SDK exports whose *first positional argument* is the key itself, e.g.
|
|
58
|
+
* `new GoogleGenerativeAI('AIza…')`. Matched against the name the SDK
|
|
59
|
+
* exports, resolved through the import — `import { GoogleGenerativeAI as G }`
|
|
60
|
+
* is still `GoogleGenerativeAI` — never against the local identifier.
|
|
61
|
+
* Empty for SDKs that only take options.
|
|
59
62
|
*/
|
|
60
63
|
positionalKeyConstructors?: readonly string[];
|
|
61
64
|
}
|
|
@@ -81,6 +84,10 @@ export type KeyVerdict = {
|
|
|
81
84
|
/**
|
|
82
85
|
* Whether the client options literal carries an inline credential.
|
|
83
86
|
*
|
|
87
|
+
* @deprecated The rule no longer calls this: it follows consts and spreads
|
|
88
|
+
* (`readObjectProperty`) and rejects placeholder values (`isCredentialShaped`),
|
|
89
|
+
* neither of which a single-node reader can do. Kept because it is public API.
|
|
90
|
+
*
|
|
84
91
|
* `process.env.OPENAI_API_KEY` and any other non-literal expression are `safe`
|
|
85
92
|
* — reading a key from the environment is the correct pattern. A spread is
|
|
86
93
|
* `unreadable`: the key may be in the spread source, and guessing there would
|
|
@@ -96,6 +103,10 @@ export declare function readCredential(options: TSESTree.ObjectExpression, keyPr
|
|
|
96
103
|
/**
|
|
97
104
|
* The callee name of a `new X(...)` / `X(...)`, if it is statically known.
|
|
98
105
|
* `new pkg.Client()` counts as `Client` — the namespace is not the identity.
|
|
106
|
+
*
|
|
107
|
+
* @deprecated The rule no longer calls this: a local identifier is not the
|
|
108
|
+
* export it binds (`import { GoogleGenerativeAI as G }`), so the positional
|
|
109
|
+
* check resolves the import instead. Kept because it is public API.
|
|
99
110
|
*/
|
|
100
111
|
export declare function calleeName(node: TSESTree.Node): string | undefined;
|
|
101
112
|
export declare function createSdkApiKeyRule(config: SdkApiKeyRuleConfig): import("./rule-creator").RuleModuleWithName<"hardcodedApiKey", [], unknown>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.POSITIONAL_KEY_LABEL=void 0;exports.readCredential=readCredential;exports.calleeName=calleeName;exports.createSdkApiKeyRule=createSdkApiKeyRule;const rule_creator_1=require("./rule-creator");const module_evidence_1=require("./module-evidence");const messaging_1=require("../messaging");exports.POSITIONAL_KEY_LABEL="The first argument";function readCredential(options,keyProps){for(const prop of options.properties){if(prop.type==="SpreadElement")return{kind:"unreadable"};if(prop.computed)continue;const name=prop.key.type==="Identifier"?prop.key.name:String(prop.key.value);if(!keyProps.has(name))continue;if(prop.value.type!=="Literal")continue;if(typeof prop.value.value==="string"&&prop.value.value.length>0){return{kind:"literal",prop:name}}}return{kind:"safe"}}function calleeName(node){if(node.type==="Identifier")return node.name;if(node.type==="MemberExpression"&&!node.computed&&node.property.type==="Identifier"){return node.property.name}return void 0}function createSdkApiKeyRule(config){const
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.POSITIONAL_KEY_LABEL=void 0;exports.readCredential=readCredential;exports.calleeName=calleeName;exports.createSdkApiKeyRule=createSdkApiKeyRule;const rule_creator_1=require("./rule-creator");const module_evidence_1=require("./module-evidence");const messaging_1=require("../messaging");const sdk_flow_1=require("./sdk-flow");exports.POSITIONAL_KEY_LABEL="The first argument";function readCredential(options,keyProps){for(const prop of options.properties){if(prop.type==="SpreadElement")return{kind:"unreadable"};if(prop.computed)continue;const name=prop.key.type==="Identifier"?prop.key.name:String(prop.key.value);if(!keyProps.has(name))continue;if(prop.value.type!=="Literal")continue;if(typeof prop.value.value==="string"&&prop.value.value.length>0){return{kind:"literal",prop:name}}}return{kind:"safe"}}function calleeName(node){if(node.type==="Identifier")return node.name;if(node.type==="MemberExpression"&&!node.computed&&node.property.type==="Identifier"){return node.property.name}return void 0}function createSdkApiKeyRule(config){const positional=new Set(config.positionalKeyConstructors??[]);const usesSdk=(0,module_evidence_1.createModuleListEvidence)(config.modules);const matcher=(0,sdk_flow_1.createSdkClientMatcher)((0,module_evidence_1.createModuleListMatcher)(config.modules));return(0,rule_creator_1.createRule)({name:config.ruleName,meta:{type:"problem",docs:{url:config.docsUrl,description:`Forbid a literal API key in the ${config.vendor} client options`,cwe:"CWE-798",cvss:9.1},messages:{hardcodedApiKey:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:`Hardcoded ${config.vendor} Credential`,cwe:"CWE-798",owasp:"A07:2021",cvss:9.1,description:"{{prop}} is a string literal, so the credential is committed to source control and readable by anyone with repository access",severity:"CRITICAL",compliance:["SOC2","PCI-DSS"],fix:`Read it from the environment: ${config.fixTemplate}`,documentationLink:config.documentationLink})},schema:[]},defaultOptions:[],create(context){if(!usesSdk(context.sourceCode.ast))return{};const sourceCode=context.sourceCode;const isHardcodedKey=node=>(0,sdk_flow_1.committedStrings)(node,sourceCode).some(sdk_flow_1.isCredentialShaped);function credentialProp(options){return config.keyProps.find(prop=>{const read=(0,sdk_flow_1.readObjectProperty)(options,prop,sourceCode);return read.kind==="value"&&isHardcodedKey(read.node)})}function inspect(node){const indices=matcher.optionArguments(node,sourceCode);if(indices.length===0)return;const first=node.arguments[0];if(positional.size>0&&first!==void 0&&indices.includes(0)){const binding=matcher.exportOf(node.callee,sourceCode);if(binding!==void 0&&positional.has((0,sdk_flow_1.sdkExportName)(binding))&&isHardcodedKey(first)){context.report({node,messageId:"hardcodedApiKey",data:{prop:exports.POSITIONAL_KEY_LABEL}});return}}for(const index of indices){const argument=node.arguments[index];if(argument===void 0||argument.type==="SpreadElement")continue;const options=(0,sdk_flow_1.resolveObjectLiteral)(argument,sourceCode);const prop=options&&credentialProp(options);if(prop!==void 0){context.report({node,messageId:"hardcodedApiKey",data:{prop}});return}}}return{NewExpression:inspect,CallExpression:inspect}}})}
|
|
@@ -0,0 +1,161 @@
|
|
|
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 Bounded same-file value following and SDK-binding resolution
|
|
8
|
+
* for the three inference-SDK factories (`createSdkApiKeyRule`,
|
|
9
|
+
* `createBrowserEscapeHatchRule`, `createSystemPromptInjectionRule`).
|
|
10
|
+
*
|
|
11
|
+
* The factories used to read only what was written inline at the call. The
|
|
12
|
+
* 2026-10-12 FP/FN audit measured what that costs on real code:
|
|
13
|
+
*
|
|
14
|
+
* - **Inline only.** `const opts = { apiKey: 'sk-…' }; new OpenAI(opts)`, a
|
|
15
|
+
* key in a const, and a system prompt built one line above the call were
|
|
16
|
+
* all invisible (false negatives).
|
|
17
|
+
* - **Any call.** The key rule inspected every `new X({ apiKey })` in a file
|
|
18
|
+
* that imported the SDK, so `new Pinecone({ apiKey })`,
|
|
19
|
+
* `expect.objectContaining({ apiKey })` and `createAnthropic({ apiKey })`
|
|
20
|
+
* (the Vercel AI provider, owned by vercel-ai-security) were all reported as
|
|
21
|
+
* a hardcoded Anthropic / OpenAI credential (false positives, and a line
|
|
22
|
+
* reported by two plugins).
|
|
23
|
+
* - **Local names.** The positional-key check compared the *local* identifier
|
|
24
|
+
* to `GoogleGenerativeAI`, so `import { GoogleGenerativeAI as G }` went
|
|
25
|
+
* silent — a verdict decided by a variable's name.
|
|
26
|
+
*
|
|
27
|
+
* Everything here answers from structure: the scope manager says what an
|
|
28
|
+
* identifier is bound to, and an import or `require()` says which module a
|
|
29
|
+
* binding came from. No verdict reads an identifier's spelling. Following is
|
|
30
|
+
* bounded ({@link MAX_FOLLOW_HOPS}) and abstains — returns the node it was
|
|
31
|
+
* given, or `undefined` — whenever a binding is reassigned, imported from a
|
|
32
|
+
* file it cannot see, or a parameter.
|
|
33
|
+
*/
|
|
34
|
+
import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
|
|
35
|
+
type SourceCode = Readonly<TSESLint.SourceCode>;
|
|
36
|
+
type Variable = TSESLint.Scope.Variable;
|
|
37
|
+
/** How many bindings a single question may follow before it gives up. */
|
|
38
|
+
export declare const MAX_FOLLOW_HOPS = 8;
|
|
39
|
+
/** The variable an identifier refers to, through the scope manager. */
|
|
40
|
+
export declare function variableOf(id: TSESTree.Identifier, sourceCode: SourceCode): Variable | undefined;
|
|
41
|
+
/**
|
|
42
|
+
* Does this identifier name a global — undeclared, or declared only by the
|
|
43
|
+
* environment (`globals: node` puts `process` and `require` in scope with no
|
|
44
|
+
* definition in the file)? A local binding of the same name is not the global.
|
|
45
|
+
*/
|
|
46
|
+
export declare function isGlobalReference(id: TSESTree.Identifier, sourceCode: SourceCode): boolean;
|
|
47
|
+
/**
|
|
48
|
+
* Follow `const x = <expr>` to `<expr>`, as many links as {@link MAX_FOLLOW_HOPS}.
|
|
49
|
+
*
|
|
50
|
+
* Also follows a property destructured out of an object literal
|
|
51
|
+
* (`const { k } = { k: v }`). Returns the node it was given — type wrappers
|
|
52
|
+
* stripped — when the binding cannot be followed: a parameter, an import, a
|
|
53
|
+
* reassigned `let`, a global.
|
|
54
|
+
*/
|
|
55
|
+
export declare function followConst(node: TSESTree.Node, sourceCode: SourceCode, hops?: number): TSESTree.Node;
|
|
56
|
+
/** The object literal an expression holds, after following consts. */
|
|
57
|
+
export declare function resolveObjectLiteral(node: TSESTree.Node, sourceCode: SourceCode, hops?: number): TSESTree.ObjectExpression | undefined;
|
|
58
|
+
/** The array literal an expression holds, after following consts. */
|
|
59
|
+
export declare function resolveArrayLiteral(node: TSESTree.Node, sourceCode: SourceCode, hops?: number): TSESTree.ArrayExpression | undefined;
|
|
60
|
+
export type PropertyRead = {
|
|
61
|
+
kind: 'value';
|
|
62
|
+
node: TSESTree.Node;
|
|
63
|
+
} | {
|
|
64
|
+
kind: 'absent';
|
|
65
|
+
} | {
|
|
66
|
+
kind: 'unknown';
|
|
67
|
+
};
|
|
68
|
+
/**
|
|
69
|
+
* What an object literal holds under `key`, the way JavaScript evaluates it:
|
|
70
|
+
* the LAST write wins.
|
|
71
|
+
*
|
|
72
|
+
* Read from the end, so `{ ...base, k: v }` is `v` whatever `base` holds, and
|
|
73
|
+
* `{ k: v, ...base }` is whatever `base` says — followed when `base` is a
|
|
74
|
+
* same-file object literal, `unknown` when it is not. A computed key that is
|
|
75
|
+
* not a static string could be `key`, so it is `unknown` too. `unknown` is the
|
|
76
|
+
* caller's cue to abstain rather than guess.
|
|
77
|
+
*/
|
|
78
|
+
export declare function readObjectProperty(object: TSESTree.ObjectExpression, key: string, sourceCode: SourceCode, hops?: number): PropertyRead;
|
|
79
|
+
/**
|
|
80
|
+
* Could this string literal be a working credential?
|
|
81
|
+
*
|
|
82
|
+
* Every vendor credential these rules cover is a generated token: at least 20
|
|
83
|
+
* characters, no whitespace, letters and digits mixed. The SDKs' own tests,
|
|
84
|
+
* READMEs and local-model setups pass stand-ins instead — `'my-anthropic-api-key'`,
|
|
85
|
+
* `'test-key'`, `'...'`, `'ollama'`, `'<YOUR_API_KEY>'` — and the 2026-10-12 scan
|
|
86
|
+
* found 946 of those reported as committed credentials across the two vendor SDK
|
|
87
|
+
* repositories, against zero real keys. The value's own shape tells them apart:
|
|
88
|
+
*
|
|
89
|
+
* - shorter than 20 characters, or containing whitespace;
|
|
90
|
+
* - no digit (a word-built name like `my-anthropic-api-key`), or no letter;
|
|
91
|
+
* - a template slot (`<…>`, `{{…}}`, `${…}`, `[…]`) or an elided `...`;
|
|
92
|
+
* - a run of eight identical characters (`sk-xxxxxxxx…`, a masked value);
|
|
93
|
+
* - a placeholder word standing as its own token (`fake`, `example`, `your`).
|
|
94
|
+
*/
|
|
95
|
+
export declare function isCredentialShaped(value: string): boolean;
|
|
96
|
+
/**
|
|
97
|
+
* The string a credential expression holds, when this file fixes it: a string
|
|
98
|
+
* literal or an interpolation-free template, directly or through consts.
|
|
99
|
+
*/
|
|
100
|
+
export declare function literalString(node: TSESTree.Node, sourceCode: SourceCode): string | undefined;
|
|
101
|
+
/**
|
|
102
|
+
* Every string a credential expression can evaluate to that this file commits:
|
|
103
|
+
* the literal itself, through consts, and both sides of a fallback
|
|
104
|
+
* (`process.env.KEY ?? 'sk-…'`, `a || 'sk-…'`, `c ? env : 'sk-…'`). A key
|
|
105
|
+
* written as the fallback is in source exactly as much as a bare one.
|
|
106
|
+
*/
|
|
107
|
+
export declare function committedStrings(node: TSESTree.Node, sourceCode: SourceCode, hops?: number): string[];
|
|
108
|
+
/**
|
|
109
|
+
* Where a binding came from: the module specifier and the export path walked
|
|
110
|
+
* from the module object (`['default']` for a default import, `[]` for the
|
|
111
|
+
* module object itself, `['AzureOpenAI']` for a named one).
|
|
112
|
+
*/
|
|
113
|
+
export interface SdkExport {
|
|
114
|
+
module: string;
|
|
115
|
+
path: readonly string[];
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Resolve an expression to the SDK export it denotes, or `undefined` when it
|
|
119
|
+
* does not come from a module `owns` accepts.
|
|
120
|
+
*
|
|
121
|
+
* Covers every spelling the module probe accepts: ESM default / named /
|
|
122
|
+
* namespace imports, `require()` with and without destructuring,
|
|
123
|
+
* `import x = require()`, and `await import()` — each through renames, consts
|
|
124
|
+
* and member access (`new sdk.default()`).
|
|
125
|
+
*/
|
|
126
|
+
export declare function resolveSdkExport(node: TSESTree.Node, sourceCode: SourceCode, owns: (specifier: string) => boolean, hops?: number): SdkExport | undefined;
|
|
127
|
+
/**
|
|
128
|
+
* The export name a resolved binding denotes. A default import, a CommonJS
|
|
129
|
+
* module object and `.default` all name the module's main export.
|
|
130
|
+
*/
|
|
131
|
+
export declare function sdkExportName(binding: SdkExport): string;
|
|
132
|
+
/**
|
|
133
|
+
* Which arguments of a call carry options for an SDK client.
|
|
134
|
+
*
|
|
135
|
+
* Built once per rule; the per-function wrapper analysis is cached by node, so
|
|
136
|
+
* it is paid once per file however many calls ask.
|
|
137
|
+
*/
|
|
138
|
+
export interface SdkClientMatcher {
|
|
139
|
+
/**
|
|
140
|
+
* The indices of `node`'s arguments that hold SDK client options, or an empty
|
|
141
|
+
* list when the call is not an SDK client construction:
|
|
142
|
+
*
|
|
143
|
+
* - a callee bound to an SDK export (`new Anthropic()`, `new sdk.default()`,
|
|
144
|
+
* `bedrock()`, `new OpenAIProvider()`) — every argument;
|
|
145
|
+
* - `client.withOptions(...)`, the SDKs' clone-with-overrides method;
|
|
146
|
+
* - a same-file subclass of an SDK class, and `super(...)` inside one;
|
|
147
|
+
* - a same-file wrapper that passes one of its parameters straight into an
|
|
148
|
+
* SDK constructor (`function make(o) { return new OpenAI(o) }`) — that
|
|
149
|
+
* parameter's position only.
|
|
150
|
+
*/
|
|
151
|
+
optionArguments(node: TSESTree.NewExpression | TSESTree.CallExpression, sourceCode: SourceCode): readonly number[];
|
|
152
|
+
/** The SDK export a callee resolves to, through the same resolution. */
|
|
153
|
+
exportOf(callee: TSESTree.Node, sourceCode: SourceCode): SdkExport | undefined;
|
|
154
|
+
}
|
|
155
|
+
export declare function createSdkClientMatcher(owns: (specifier: string) => boolean): SdkClientMatcher;
|
|
156
|
+
/**
|
|
157
|
+
* `process.env.X`, `process.env['X']` and `import.meta.env.X` — a value a build
|
|
158
|
+
* or a server process supplies, the opposite of one a visitor supplies.
|
|
159
|
+
*/
|
|
160
|
+
export declare function isEnvironmentRead(node: TSESTree.Node, sourceCode: SourceCode): boolean;
|
|
161
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.MAX_FOLLOW_HOPS=void 0;exports.variableOf=variableOf;exports.isGlobalReference=isGlobalReference;exports.followConst=followConst;exports.resolveObjectLiteral=resolveObjectLiteral;exports.resolveArrayLiteral=resolveArrayLiteral;exports.readObjectProperty=readObjectProperty;exports.isCredentialShaped=isCredentialShaped;exports.literalString=literalString;exports.committedStrings=committedStrings;exports.resolveSdkExport=resolveSdkExport;exports.sdkExportName=sdkExportName;exports.createSdkClientMatcher=createSdkClientMatcher;exports.isEnvironmentRead=isEnvironmentRead;const ast_node_types_1=require("../ast-node-types");const type_syntax_1=require("../ast/type-syntax");const spellings_1=require("../ast/spellings");exports.MAX_FOLLOW_HOPS=8;function variableOf(id,sourceCode){for(let scope=sourceCode.getScope(id);scope;scope=scope.upper){const reference=scope.references.find(r=>r.identifier===id);if(reference)return reference.resolved??void 0;const declared=scope.set.get(id.name);if(declared)return declared}return void 0}function isGlobalReference(id,sourceCode){const variable=variableOf(id,sourceCode);return variable===void 0||variable.defs.length===0}function singleDefinition(variable){if(!variable||variable.defs.length!==1)return void 0;const writes=variable.references.filter(r=>r.isWrite()).length;return writes<=1?variable.defs[0]:void 0}function patternKeyFor(pattern,name){for(const property of pattern.properties){if(property.type!==ast_node_types_1.AST_NODE_TYPES.Property)continue;const value=unwrapPatternDefault(property.value);if(value.type!==ast_node_types_1.AST_NODE_TYPES.Identifier||value.name!==name)continue;return(0,spellings_1.objectKeyName)(property)??void 0}return void 0}function unwrapPatternDefault(node){return node.type===ast_node_types_1.AST_NODE_TYPES.AssignmentPattern?node.left:node}function followConst(node,sourceCode,hops=exports.MAX_FOLLOW_HOPS){const current=(0,type_syntax_1.unwrapTypeSyntax)(node);if(hops<=0||current.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return current;const definition=singleDefinition(variableOf(current,sourceCode));if(definition?.type!=="Variable")return current;const declarator=definition.node;if(declarator.init===null)return current;if(declarator.id.type===ast_node_types_1.AST_NODE_TYPES.Identifier){return followConst(declarator.init,sourceCode,hops-1)}if(declarator.id.type!==ast_node_types_1.AST_NODE_TYPES.ObjectPattern)return current;const key=patternKeyFor(declarator.id,current.name);const source=resolveObjectLiteral(declarator.init,sourceCode,hops-1);if(key===void 0||source===void 0)return current;const read=readObjectProperty(source,key,sourceCode,hops-1);return read.kind==="value"?followConst(read.node,sourceCode,hops-1):current}function resolveObjectLiteral(node,sourceCode,hops=exports.MAX_FOLLOW_HOPS){const resolved=followConst(node,sourceCode,hops);return resolved.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression?resolved:void 0}function resolveArrayLiteral(node,sourceCode,hops=exports.MAX_FOLLOW_HOPS){const resolved=followConst(node,sourceCode,hops);return resolved.type===ast_node_types_1.AST_NODE_TYPES.ArrayExpression?resolved:void 0}function readObjectProperty(object,key,sourceCode,hops=exports.MAX_FOLLOW_HOPS){for(let i=object.properties.length-1;i>=0;i--){const property=object.properties[i];if(property.type===ast_node_types_1.AST_NODE_TYPES.SpreadElement){const inner=hops>0?resolveObjectLiteral(property.argument,sourceCode,hops-1):void 0;if(inner===void 0)return{kind:"unknown"};const read=readObjectProperty(inner,key,sourceCode,hops-1);if(read.kind!=="absent")return read;continue}const name=(0,spellings_1.objectKeyName)(property);if(name===null)return{kind:"unknown"};if(name===key)return{kind:"value",node:property.value}}return{kind:"absent"}}const PLACEHOLDER_TOKENS=new Set(["test","testing","fake","dummy","mock","mocked","example","sample","placeholder","your","yours","changeme","replace","replaceme","redacted","todo","tbd","xxx","xxxx","foo","bar","baz","demo","synthetic","invalid","notreal"]);const MIN_CREDENTIAL_LENGTH=20;function isCredentialShaped(value){if(value.length<MIN_CREDENTIAL_LENGTH||/\s/.test(value))return false;if(!/[A-Za-z]/.test(value)||!/[0-9]/.test(value))return false;if(/^(?:<.*>|\{\{.*\}\}|\$\{.*\}|\[.*\])$/.test(value))return false;if(value.includes("...")||value.includes("\u2026"))return false;if(/(.)\1{7}/.test(value))return false;const tokens=value.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/);return!tokens.some(token=>PLACEHOLDER_TOKENS.has(token))}function literalString(node,sourceCode){const resolved=followConst(node,sourceCode);if(resolved.type===ast_node_types_1.AST_NODE_TYPES.Literal){return typeof resolved.value==="string"?resolved.value:void 0}if(resolved.type===ast_node_types_1.AST_NODE_TYPES.TemplateLiteral&&resolved.expressions.length===0){return String(resolved.quasis[0].value.cooked)}return void 0}function committedStrings(node,sourceCode,hops=exports.MAX_FOLLOW_HOPS){if(hops<=0)return[];const resolved=followConst(node,sourceCode);if(resolved.type===ast_node_types_1.AST_NODE_TYPES.LogicalExpression){return[...committedStrings(resolved.left,sourceCode,hops-1),...committedStrings(resolved.right,sourceCode,hops-1)]}if(resolved.type===ast_node_types_1.AST_NODE_TYPES.ConditionalExpression){return[...committedStrings(resolved.consequent,sourceCode,hops-1),...committedStrings(resolved.alternate,sourceCode,hops-1)]}const value=literalString(resolved,sourceCode);return value===void 0?[]:[value]}function requiredSpecifier(node,sourceCode){if(node.callee.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return void 0;if(node.callee.name!=="require")return void 0;if(!isGlobalReference(node.callee,sourceCode))return void 0;const[argument]=node.arguments;return argument?.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof argument.value==="string"?argument.value:void 0}function resolveSdkExport(node,sourceCode,owns,hops=exports.MAX_FOLLOW_HOPS){const current=(0,type_syntax_1.unwrapTypeSyntax)(node);if(hops<=0)return void 0;switch(current.type){case ast_node_types_1.AST_NODE_TYPES.AwaitExpression:return resolveSdkExport(current.argument,sourceCode,owns,hops-1);case ast_node_types_1.AST_NODE_TYPES.ImportExpression:{const source=current.source;return source.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof source.value==="string"&&owns(source.value)?{module:source.value,path:[]}:void 0}case ast_node_types_1.AST_NODE_TYPES.CallExpression:{const specifier=requiredSpecifier(current,sourceCode);return specifier!==void 0&&owns(specifier)?{module:specifier,path:[]}:void 0}case ast_node_types_1.AST_NODE_TYPES.MemberExpression:{const name=(0,spellings_1.propertyName)(current);if(name===null)return void 0;const base=resolveSdkExport(current.object,sourceCode,owns,hops-1);return base&&{module:base.module,path:[...base.path,name]}}case ast_node_types_1.AST_NODE_TYPES.Identifier:return resolveIdentifierExport(current,sourceCode,owns,hops);default:return void 0}}function resolveIdentifierExport(id,sourceCode,owns,hops){const definition=singleDefinition(variableOf(id,sourceCode));if(definition===void 0)return void 0;if(definition.type==="ImportBinding"){const declaration=definition.parent;if(declaration.type===ast_node_types_1.AST_NODE_TYPES.TSImportEqualsDeclaration){const reference=declaration.moduleReference;return reference.type===ast_node_types_1.AST_NODE_TYPES.TSExternalModuleReference&&reference.expression.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof reference.expression.value==="string"&&owns(reference.expression.value)?{module:reference.expression.value,path:[]}:void 0}const importDeclaration=declaration;const module=importDeclaration.source.value;if(!owns(module))return void 0;const specifier=definition.node;if(specifier.type===ast_node_types_1.AST_NODE_TYPES.ImportDefaultSpecifier){return{module,path:["default"]}}if(specifier.type===ast_node_types_1.AST_NODE_TYPES.ImportNamespaceSpecifier){return{module,path:[]}}const imported=specifier.imported;return{module,path:[imported.type===ast_node_types_1.AST_NODE_TYPES.Identifier?imported.name:String(imported.value)]}}if(definition.type!=="Variable")return void 0;const declarator=definition.node;if(declarator.init===null)return void 0;const base=resolveSdkExport(declarator.init,sourceCode,owns,hops-1);if(base===void 0)return void 0;if(declarator.id.type===ast_node_types_1.AST_NODE_TYPES.Identifier)return base;if(declarator.id.type!==ast_node_types_1.AST_NODE_TYPES.ObjectPattern)return void 0;const key=patternKeyFor(declarator.id,id.name);return key===void 0?void 0:{module:base.module,path:[...base.path,key]}}function sdkExportName(binding){const last=binding.path[binding.path.length-1];return last===void 0?"default":last}function isFunctionNode(node){return node.type===ast_node_types_1.AST_NODE_TYPES.FunctionDeclaration||node.type===ast_node_types_1.AST_NODE_TYPES.FunctionExpression||node.type===ast_node_types_1.AST_NODE_TYPES.ArrowFunctionExpression}function isClassNode(node){return node.type===ast_node_types_1.AST_NODE_TYPES.ClassDeclaration||node.type===ast_node_types_1.AST_NODE_TYPES.ClassExpression}function declaredCallable(id,sourceCode){const definition=singleDefinition(variableOf(id,sourceCode));if(definition===void 0)return void 0;const declared=definition.type==="Variable"?definition.node.init:definition.node;if(!declared)return void 0;const node=(0,type_syntax_1.unwrapTypeSyntax)(declared);return isFunctionNode(node)||isClassNode(node)?node:void 0}function walkOwnBody(root,visit){const stack=[root];while(stack.length>0){const node=stack.pop();visit(node);for(const key of Object.keys(node)){if(key==="parent")continue;const value=node[key];const children=Array.isArray(value)?value:[value];for(const child of children){if(child!==null&&typeof child==="object"&&typeof child.type==="string"&&!isFunctionNode(child)){stack.push(child)}}}}}function enclosingClass(node){let current=node.parent;while(!isClassNode(current))current=current.parent;return current}function createSdkClientMatcher(owns){const wrapperCache=new WeakMap;const isSdkCallee=(callee,sourceCode)=>resolveSdkExport(callee,sourceCode,owns)!==void 0;function wrapperParameter(fn,sourceCode){const cached=wrapperCache.get(fn);if(cached!==void 0)return cached;const parameters=sourceCode.getDeclaredVariables(fn);const indexOf=node=>{const arg=(0,type_syntax_1.unwrapTypeSyntax)(node);if(arg.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return-1;const variable=variableOf(arg,sourceCode);if(variable===void 0||!parameters.includes(variable))return-1;return fn.params.findIndex(param=>unwrapPatternDefault(param)===variable.defs[0]?.name)};let found=null;walkOwnBody(fn.body,node=>{if(found!==null)return;if(node.type!==ast_node_types_1.AST_NODE_TYPES.NewExpression&&node.type!==ast_node_types_1.AST_NODE_TYPES.CallExpression)return;if(!isSdkCallee(node.callee,sourceCode))return;for(const argument of node.arguments){const direct=indexOf(argument);if(direct>=0){found=direct;return}if(argument.type!==ast_node_types_1.AST_NODE_TYPES.ObjectExpression)continue;for(const property of argument.properties){if(property.type!==ast_node_types_1.AST_NODE_TYPES.SpreadElement)continue;const spread=indexOf(property.argument);if(spread>=0){found=spread;return}}}});wrapperCache.set(fn,found);return found}function optionArguments(node,sourceCode){const all=node.arguments.map((_,i)=>i);const callee=(0,type_syntax_1.unwrapTypeSyntax)(node.callee);if(callee.type===ast_node_types_1.AST_NODE_TYPES.Super){const superClass=enclosingClass(node).superClass;return superClass&&isSdkCallee(superClass,sourceCode)?all:[]}if(callee.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&(0,spellings_1.propertyName)(callee)==="withOptions"){return all}if(isSdkCallee(callee,sourceCode))return all;if(callee.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return[];const declared=declaredCallable(callee,sourceCode);if(declared===void 0)return[];if(isClassNode(declared)){return declared.superClass&&isSdkCallee(declared.superClass,sourceCode)?all:[]}const parameter=wrapperParameter(declared,sourceCode);return parameter===null?[]:[parameter]}return{optionArguments,exportOf:(callee,sourceCode)=>resolveSdkExport(callee,sourceCode,owns)}}function isEnvironmentRead(node,sourceCode){const current=(0,type_syntax_1.unwrapTypeSyntax)(node);if(current.type!==ast_node_types_1.AST_NODE_TYPES.MemberExpression)return false;const owner=(0,type_syntax_1.unwrapTypeSyntax)(current.object);if(owner.type!==ast_node_types_1.AST_NODE_TYPES.MemberExpression)return false;if((0,spellings_1.propertyName)(owner)!=="env")return false;const root=(0,type_syntax_1.unwrapTypeSyntax)(owner.object);if(root.type===ast_node_types_1.AST_NODE_TYPES.MetaProperty)return true;return root.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&root.name==="process"&&isGlobalReference(root,sourceCode)}
|
|
@@ -6,6 +6,19 @@
|
|
|
6
6
|
import type { TSESLint } from '@typescript-eslint/utils';
|
|
7
7
|
/** Message ids every rule built by this factory reports. */
|
|
8
8
|
export type SqlInjectionMessageIds = 'noUnsafeQuery' | 'unsafeTemplateLiteral';
|
|
9
|
+
/** A raw-SQL fragment sink: a method whose argument at `arg` is SQL text. */
|
|
10
|
+
export interface SqlFragmentSink {
|
|
11
|
+
/** Method name, e.g. `whereRaw`. */
|
|
12
|
+
readonly name: string;
|
|
13
|
+
/** Argument index holding the SQL text. Default `0`. */
|
|
14
|
+
readonly arg?: number;
|
|
15
|
+
/**
|
|
16
|
+
* Only on a receiver PROVEN to come from the plugin's modules. For a name
|
|
17
|
+
* other libraries also use (`raw`), so a same-named method of an unrelated
|
|
18
|
+
* object is never a sink.
|
|
19
|
+
*/
|
|
20
|
+
readonly requireDriverReceiver?: boolean;
|
|
21
|
+
}
|
|
9
22
|
export interface SqlInjectionRuleConfig {
|
|
10
23
|
/**
|
|
11
24
|
* The rule's own `meta.type` + `meta.docs`, spelled out by the caller.
|
|
@@ -26,8 +39,58 @@ export interface SqlInjectionRuleConfig {
|
|
|
26
39
|
readonly confidence: 'high' | 'medium' | 'low';
|
|
27
40
|
};
|
|
28
41
|
};
|
|
29
|
-
/**
|
|
42
|
+
/**
|
|
43
|
+
* Method names that execute a whole SQL STATEMENT passed as argument 0,
|
|
44
|
+
* e.g. `['query']` or `['prepare', 'exec']`. Subject to the keyword gate
|
|
45
|
+
* when `requireSqlKeywords` is set and the receiver is not proven to be the
|
|
46
|
+
* driver.
|
|
47
|
+
*/
|
|
30
48
|
readonly methods: readonly string[];
|
|
49
|
+
/**
|
|
50
|
+
* Methods that take a raw SQL FRAGMENT — `whereRaw`, `orderByRaw`,
|
|
51
|
+
* `Sequelize.literal`, `sql.raw` — never keyword-gated: a fragment carries
|
|
52
|
+
* no statement verb.
|
|
53
|
+
*/
|
|
54
|
+
readonly fragmentMethods?: readonly (string | SqlFragmentSink)[];
|
|
55
|
+
/**
|
|
56
|
+
* Functions imported from the plugin's modules whose argument 0 is a raw
|
|
57
|
+
* SQL fragment — objection's `raw('…')`.
|
|
58
|
+
*/
|
|
59
|
+
readonly fragmentFunctions?: readonly string[];
|
|
60
|
+
/**
|
|
61
|
+
* Functions imported from the plugin's modules that take a callback
|
|
62
|
+
* returning a raw SQL fragment, whose first parameter is the column alias
|
|
63
|
+
* the driver substitutes — TypeORM's `Raw((alias) => \`${alias} > 1\`)`.
|
|
64
|
+
*/
|
|
65
|
+
readonly aliasCallbacks?: readonly string[];
|
|
66
|
+
/**
|
|
67
|
+
* Methods whose result is a prepared statement or a query builder, whose
|
|
68
|
+
* own methods take bound VALUES — better-sqlite3's `db.prepare(sql)` then
|
|
69
|
+
* `.get(id)`, Drizzle's `db.insert(t)` then `.values(row)`. Request data
|
|
70
|
+
* handed to one of those is a parameter, not SQL text.
|
|
71
|
+
*/
|
|
72
|
+
readonly statementFactories?: readonly string[];
|
|
73
|
+
/**
|
|
74
|
+
* Properties of a query-options object that hold the statement text —
|
|
75
|
+
* mysql2's `query({ sql, values })`.
|
|
76
|
+
*/
|
|
77
|
+
readonly sqlTextProperties?: readonly string[];
|
|
78
|
+
/**
|
|
79
|
+
* Driver functions whose result is escaped SQL text (`escape`, `escapeId`,
|
|
80
|
+
* `format`). A member call of that name on a receiver not provably from
|
|
81
|
+
* another library, or a binding imported under that name from the modules.
|
|
82
|
+
*/
|
|
83
|
+
readonly escapers?: readonly string[];
|
|
84
|
+
/**
|
|
85
|
+
* Standalone escaping libraries for this driver whose `escapers` count too —
|
|
86
|
+
* `sqlstring`, the escaper mysql and mysql2 are built on.
|
|
87
|
+
*/
|
|
88
|
+
readonly escaperModules?: readonly string[];
|
|
89
|
+
/**
|
|
90
|
+
* Members of the driver whose result is a parameterised fragment rather
|
|
91
|
+
* than text (`Prisma.join`, `sql.identifier`, `knex.ref`).
|
|
92
|
+
*/
|
|
93
|
+
readonly fragmentFactories?: readonly string[];
|
|
31
94
|
/**
|
|
32
95
|
* Modules whose API these sinks belong to. **The rule stays silent in a file
|
|
33
96
|
* that loads none of them** — by `import`, `require`, `await import()` or
|
|
@@ -45,15 +108,26 @@ export interface SqlInjectionRuleConfig {
|
|
|
45
108
|
* scan, nothing to go stale, and a file that does not import the driver is
|
|
46
109
|
* one this rule genuinely has nothing to say about.
|
|
47
110
|
*
|
|
111
|
+
* One exception keeps that partition: a sink the code-agnostic
|
|
112
|
+
* `secure-coding/no-sql-injection` does not own (anything but `query` /
|
|
113
|
+
* `execute`) also reports in a file that reaches the driver only through a
|
|
114
|
+
* RELATIVE import, when its receiver is read from disk and proven to be the
|
|
115
|
+
* driver's — `import prisma from './lib/prisma'; prisma.$queryRawUnsafe(…)`.
|
|
116
|
+
*
|
|
48
117
|
* Matched against the specifier's package root, so `'mysql2/promise'`
|
|
49
118
|
* matches `'mysql2'` and `'@prisma/client/edge'` matches `'@prisma/client'`.
|
|
50
119
|
*/
|
|
51
120
|
readonly modules: readonly string[];
|
|
52
121
|
/**
|
|
53
|
-
*
|
|
54
|
-
*
|
|
55
|
-
|
|
56
|
-
|
|
122
|
+
* `"…"` delimits a string in this driver's default dialect (MySQL), not an
|
|
123
|
+
* identifier — so `= "${x}"` is a value position.
|
|
124
|
+
*/
|
|
125
|
+
readonly doubleQuotedStrings?: boolean;
|
|
126
|
+
/**
|
|
127
|
+
* Require the *static* part of a STATEMENT sink's text to read as a SQL
|
|
128
|
+
* statement (`SELECT … FROM`, `INSERT INTO`, `UPDATE … SET` …) before
|
|
129
|
+
* reporting, unless the receiver is proven to be the driver. Precision
|
|
130
|
+
* guard for names other libraries share (`.get()`, `.run()`, `.execute()`).
|
|
57
131
|
*/
|
|
58
132
|
readonly requireSqlKeywords: boolean;
|
|
59
133
|
/** Remediation line in the emitted message. */
|
|
@@ -61,12 +135,15 @@ export interface SqlInjectionRuleConfig {
|
|
|
61
135
|
/** Reference link in the emitted message. */
|
|
62
136
|
readonly documentationLink: string;
|
|
63
137
|
}
|
|
138
|
+
/** Whether a string's static half reads as a SQL statement. */
|
|
139
|
+
export declare function looksLikeSqlStatement(text: string): boolean;
|
|
64
140
|
/**
|
|
65
141
|
* Build a CWE-89 rule for the given sinks and remediation copy.
|
|
66
142
|
*
|
|
67
|
-
* Detects
|
|
68
|
-
*
|
|
69
|
-
*
|
|
70
|
-
* same-file helper that forwards the
|
|
143
|
+
* Detects: an unproven value concatenated or interpolated into a sink's SQL
|
|
144
|
+
* text, directly or through a binding (including `+=` builders and a local
|
|
145
|
+
* function that returns the text); request data passed as the SQL text
|
|
146
|
+
* itself; and either of those passed to a same-file helper that forwards the
|
|
147
|
+
* argument into a sink.
|
|
71
148
|
*/
|
|
72
149
|
export declare function createSqlInjectionRule(config: SqlInjectionRuleConfig): TSESLint.RuleModule<SqlInjectionMessageIds, []>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.createSqlInjectionRule=createSqlInjectionRule;const ast_node_types_1=require("../ast-node-types");const spellings_1=require("../ast/spellings");const messaging_1=require("../messaging");const module_evidence_1=require("./module-evidence");const SQL_KEYWORDS=/\b(?:select|insert|update|delete|drop|alter|truncate|union|from|where|values|set)\b/i;const FUNCTION_TYPES=new Set([ast_node_types_1.AST_NODE_TYPES.FunctionDeclaration,ast_node_types_1.AST_NODE_TYPES.FunctionExpression,ast_node_types_1.AST_NODE_TYPES.ArrowFunctionExpression]);function enclosingFunction(node){for(let n=node.parent;n;n=n.parent){if(FUNCTION_TYPES.has(n.type))return n}return void 0}function callableName(fn){if(fn.type===ast_node_types_1.AST_NODE_TYPES.FunctionDeclaration&&fn.id)return fn.id.name;const parent=fn.parent;if(parent.type===ast_node_types_1.AST_NODE_TYPES.VariableDeclarator&&parent.id.type===ast_node_types_1.AST_NODE_TYPES.Identifier){return parent.id.name}if((parent.type===ast_node_types_1.AST_NODE_TYPES.MethodDefinition||parent.type===ast_node_types_1.AST_NODE_TYPES.PropertyDefinition||parent.type===ast_node_types_1.AST_NODE_TYPES.Property)&&parent.key.type===ast_node_types_1.AST_NODE_TYPES.Identifier){return parent.key.name}return void 0}function staticText(node){if(node.type===ast_node_types_1.AST_NODE_TYPES.TemplateLiteral){return node.quasis.map(q=>q.value.raw).join(" ")}if(node.type===ast_node_types_1.AST_NODE_TYPES.BinaryExpression){return`${staticText(node.left)} ${staticText(node.right)}`}if(node.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof node.value==="string"){return node.value}return""}function classify(node,requireSqlKeywords){let kind=false;if(node.type===ast_node_types_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){kind="concat"}if(node.type===ast_node_types_1.AST_NODE_TYPES.TemplateLiteral&&node.expressions.length>0){kind="template"}if(kind===false)return false;if(kind==="concat"&&staticText(node).trim()==="")return false;if(requireSqlKeywords&&!SQL_KEYWORDS.test(staticText(node)))return false;return kind}function createSqlInjectionRule(config){const sinks=new Set(config.methods);const usesModule=(0,module_evidence_1.createModuleEvidence)({packages:config.modules});return{meta:{type:config.meta.type,docs:{...config.meta.docs},messages:{noUnsafeQuery:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"SQL Injection Risk",description:"Unsafe SQL query detected. Variable interpolation found.",severity:"CRITICAL",cwe:config.meta.docs.cwe,owasp:"A03:2021",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"high",fix:config.fix,documentationLink:config.documentationLink}),unsafeTemplateLiteral:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"SQL Injection Risk",description:"Unsafe SQL query construction detected (template literal).",severity:"CRITICAL",cwe:config.meta.docs.cwe,owasp:"A03:2021",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"high",fix:config.fix,documentationLink:config.documentationLink})},schema:[]},defaultOptions:[],create(context){const tainted=new Map;const sqlish=new Set;const wrappers=new Map;const definitions=new Map;const wrapperFns=new Map;const pending=[];let ownsFile=false;const report=(node,kind)=>{if(!ownsFile)return;context.report({node,messageId:kind==="template"?"unsafeTemplateLiteral":"noUnsafeQuery"})};return{Program(program){ownsFile=usesModule(program)},"FunctionDeclaration, FunctionExpression, ArrowFunctionExpression"(node){const name=callableName(node);if(name!==void 0)definitions.set(name,(definitions.get(name)??0)+1)},VariableDeclarator(node){if(node.id.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&node.init){const kind=classify(node.init,config.requireSqlKeywords);if(kind)tainted.set(node.id.name,kind);if(SQL_KEYWORDS.test(staticText(node.init)))sqlish.add(node.id.name)}},AssignmentExpression(node){if(node.operator==="+="&&node.left.type===ast_node_types_1.AST_NODE_TYPES.Identifier){const gate=config.requireSqlKeywords&&!sqlish.has(node.left.name);const kind=classify(node.right,gate);if(kind)tainted.set(node.left.name,kind);if(SQL_KEYWORDS.test(staticText(node.right)))sqlish.add(node.left.name)}},CallExpression(node){const isMember=node.callee.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression;const calleeName=isMember?(0,spellings_1.propertyName)(node.callee)??void 0:node.callee.type===ast_node_types_1.AST_NODE_TYPES.Identifier?node.callee.name:void 0;if(calleeName===void 0)return;if(!isMember||!sinks.has(calleeName)){for(const[index,arg]of node.arguments.entries()){if(arg.type===ast_node_types_1.AST_NODE_TYPES.SpreadElement)continue;const kind=classify(arg,true);if(kind)pending.push({name:calleeName,index,arg,kind});else if(arg.type===ast_node_types_1.AST_NODE_TYPES.Identifier)pending.push({name:calleeName,index,arg,kind:void 0})}return}const queryArg=node.arguments[0];if(!queryArg)return;if(queryArg.type===ast_node_types_1.AST_NODE_TYPES.Identifier){const fn=enclosingFunction(node);const index=fn?.params.findIndex(p=>p.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&p.name===queryArg.name)??-1;const name=fn&&index>=0?callableName(fn):void 0;if(name!==void 0&&fn){wrappers.set(name,index);wrapperFns.set(fn,name)}}const direct=classify(queryArg,config.requireSqlKeywords);if(direct){report(queryArg,direct);return}if(queryArg.type===ast_node_types_1.AST_NODE_TYPES.Identifier){const taint=tainted.get(queryArg.name);if(taint)report(queryArg,taint)}},"Program:exit"(){const proven=new Map;for(const name of wrapperFns.values())proven.set(name,(proven.get(name)??0)+1);for(const{name,index,arg,kind}of pending){if(wrappers.get(name)!==index)continue;if(definitions.get(name)!==proven.get(name))continue;if(kind){report(arg,kind);continue}const varName=arg.name;const taint=tainted.get(varName);if(taint&&sqlish.has(varName))report(arg,taint)}}}}}}
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.looksLikeSqlStatement=looksLikeSqlStatement;exports.createSqlInjectionRule=createSqlInjectionRule;const ast_node_types_1=require("../ast-node-types");const spellings_1=require("../ast/spellings");const type_syntax_1=require("../ast/type-syntax");const messaging_1=require("../messaging");const module_evidence_1=require("./module-evidence");const rule_creator_1=require("./rule-creator");const driver_origin_1=require("./driver-origin");const request_source_1=require("./request-source");const sql_safety_1=require("./sql-safety");const sql_position_1=require("./sql-position");const value_follow_1=require("./value-follow");const SQL_STATEMENTS=[/^[\s(]*select\b[\s\S]*\bfrom\b/i,/^[\s(]*select\s/i,/^\s*insert\s+(?:or\s+\w+\s+|ignore\s+)?into\b/i,/^\s*update\b[\s\S]*\bset\b/i,/^\s*delete\s+from\b/i,/^\s*(?:replace|merge)\s+into\b/i,/^\s*with\b[\s\S]*\bas\s*\(/i,/^\s*(?:create|drop|alter|truncate)\s+(?:unique\s+|temp(?:orary)?\s+|or\s+replace\s+)*(?:table|index|view|schema|database|sequence|trigger|function|procedure|user|role)\b/i,/^\s*(?:pragma|attach|detach|vacuum|analyze|reindex|show|describe|explain)\b/i,/^\s*call\s+[\w".`]+\s*\(/i];const PARTITION_SHARED_SINKS=new Set(["query","execute"]);function looksLikeSqlStatement(text){return SQL_STATEMENTS.some(pattern=>pattern.test(text))}function enclosingFunction(node){for(let n=node.parent;n;n=n.parent){if((0,driver_origin_1.isFunctionNode)(n))return n}return void 0}function callableName(fn){if(fn.type===ast_node_types_1.AST_NODE_TYPES.FunctionDeclaration&&fn.id)return fn.id.name;const parent=fn.parent;if(parent.type===ast_node_types_1.AST_NODE_TYPES.VariableDeclarator&&parent.id.type===ast_node_types_1.AST_NODE_TYPES.Identifier){return parent.id.name}if((parent.type===ast_node_types_1.AST_NODE_TYPES.MethodDefinition||parent.type===ast_node_types_1.AST_NODE_TYPES.PropertyDefinition||parent.type===ast_node_types_1.AST_NODE_TYPES.Property)&&parent.key.type===ast_node_types_1.AST_NODE_TYPES.Identifier){return parent.key.name}return void 0}function createSqlInjectionRule(config){const statementSinks=new Set(config.methods);const fragmentSinks=new Map;for(const sink of config.fragmentMethods??[]){const spec=typeof sink==="string"?{name:sink}:sink;fragmentSinks.set(spec.name,{name:spec.name,arg:spec.arg??0,requireDriverReceiver:spec.requireDriverReceiver??false})}const fragmentFunctions=new Set(config.fragmentFunctions??[]);const aliasCallbacks=new Set(config.aliasCallbacks??[]);const sqlTextProperties=new Set(config.sqlTextProperties??[]);const statementFactories=new Set(config.statementFactories??[]);const usesModule=(0,module_evidence_1.createModuleEvidence)({packages:config.modules});const originOf=(0,driver_origin_1.createOriginClassifier)(config.modules);const safety=(0,sql_safety_1.createSqlSafety)({origin:originOf,escapers:new Set(config.escapers??[]),fragmentFactories:new Set(config.fragmentFactories??[]),modules:config.modules,escaperModules:config.escaperModules});return{meta:{type:config.meta.type,docs:{...config.meta.docs},messages:{noUnsafeQuery:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"SQL Injection Risk",description:"Unsafe SQL query detected. Variable interpolation found.",severity:"CRITICAL",cwe:config.meta.docs.cwe,owasp:"A03:2021",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"high",fix:config.fix,documentationLink:config.documentationLink}),unsafeTemplateLiteral:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"SQL Injection Risk",description:"Unsafe SQL query construction detected (template literal).",severity:"CRITICAL",cwe:config.meta.docs.cwe,owasp:"A03:2021",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"high",fix:config.fix,documentationLink:config.documentationLink})},schema:[]},defaultOptions:[],create(context){if((0,rule_creator_1.isTestFilePath)(context.filename))return{};const env=(0,value_follow_1.envOf)(context);const wrappers=new Map;const definitions=new Map;const wrapperFns=new Map;const pending=[];let ownsFile=false;const judge=(node,gate,depth=0)=>{const arg=(0,type_syntax_1.unwrapTypeSyntax)(node);if(arg.type===ast_node_types_1.AST_NODE_TYPES.TemplateLiteral||arg.type===ast_node_types_1.AST_NODE_TYPES.BinaryExpression&&arg.operator==="+"){if(arg.type===ast_node_types_1.AST_NODE_TYPES.TemplateLiteral&&arg.expressions.length===0){return false}const kind=arg.type===ast_node_types_1.AST_NODE_TYPES.TemplateLiteral?"template":"concat";const text=(0,sql_safety_1.sqlStaticText)(arg);if(kind==="concat"&&text.trim()==="")return false;if(gate&&!looksLikeSqlStatement(text))return false;return(0,sql_position_1.sqlHoles)(arg).some(isUnsafeHole)?kind:false}if(depth>2)return false;if(arg.type===ast_node_types_1.AST_NODE_TYPES.Identifier){return judgeBinding(arg,gate,depth)}if(arg.type===ast_node_types_1.AST_NODE_TYPES.CallExpression){const target=(0,value_follow_1.follow)((0,value_follow_1.valueAt)(arg.callee,env));if(target.env!==env||!(0,driver_origin_1.isFunctionNode)(target.node))return false;for(const result of(0,value_follow_1.returnedValues)(target.node)??[]){const kind=judge(result,gate,depth+1);if(kind)return kind}}return false};const isUnsafeHole=({expression,preceding})=>!safety.isSafe((0,value_follow_1.valueAt)(expression,env),(0,sql_position_1.isQuoted)(preceding))&&((0,sql_position_1.isValuePosition)(preceding,config.doubleQuotedStrings)||(0,sql_position_1.isRequestDerived)(expression,env));const judgeBinding=(node,gate,depth)=>{const variable=(0,value_follow_1.lookup)(node.name,env.scopeOf(node));if(variable===null||!variable.defs.some(def=>def.type==="Variable")||variable.defs.some(def=>def.type==="Parameter")){return false}const writes=variable.references.filter(r=>r.isWrite()&&r.writeExpr).map(r=>r.writeExpr);const text=writes.map(sql_safety_1.sqlStaticText).join(" ");if(gate&&!looksLikeSqlStatement(text))return false;for(const write of writes){const kind=judge(write,false,depth+1);if(kind)return kind}return false};const isRequestText=node=>{let cursor=(0,type_syntax_1.unwrapTypeSyntax)(node);while(cursor.type===ast_node_types_1.AST_NODE_TYPES.CallExpression&&cursor.callee.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&cursor.callee.name==="String"&&cursor.arguments.length===1){cursor=(0,type_syntax_1.unwrapTypeSyntax)(cursor.arguments[0])}for(let link=cursor;;link=link.object){if((0,request_source_1.isRequestPayload)(link,env))return true;if(link.type!==ast_node_types_1.AST_NODE_TYPES.MemberExpression)return false}};const report=(node,kind)=>{context.report({node,messageId:kind==="template"?"unsafeTemplateLiteral":"noUnsafeQuery"})};let requestTextSink=true;const isStatementObject=receiver=>{const value=(0,type_syntax_1.unwrapTypeSyntax)((0,value_follow_1.follow)((0,value_follow_1.valueAt)(receiver,env)).node);return value.type===ast_node_types_1.AST_NODE_TYPES.CallExpression&&value.callee.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&statementFactories.has((0,spellings_1.propertyName)(value.callee)??"")};const check=(arg,gate)=>{let text=(0,type_syntax_1.unwrapTypeSyntax)(arg);if(text.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression&&sqlTextProperties.size>0){const property=text.properties.find(p=>p.type===ast_node_types_1.AST_NODE_TYPES.Property&&sqlTextProperties.has((0,spellings_1.objectKeyName)(p)??""));if(property===void 0)return;text=property.value}const kind=judge(text,gate);if(kind){report(text,kind);return}if(requestTextSink&&isRequestText(text))report(text,"concat")};const importedName=callee=>{const variable=(0,value_follow_1.lookup)(callee.name,env.scopeOf(callee));const specifier=variable===null?null:(0,value_follow_1.importSpecifierOf)(variable);return specifier!==null&&config.modules.some(m=>specifier.source===m||specifier.source.startsWith(`${m}/`))?specifier.name:null};const checkAliasCallback=node=>{const callback=node.arguments[0];if(!callback||!(0,driver_origin_1.isFunctionNode)(callback))return;const alias=callback.params[0];for(const result of(0,value_follow_1.returnedValues)(callback)??[]){const text=(0,type_syntax_1.unwrapTypeSyntax)(result);if(text.type!==ast_node_types_1.AST_NODE_TYPES.TemplateLiteral)continue;const unsafe=(0,sql_position_1.sqlHoles)(text).some(hole=>!(hole.expression.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&alias?.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&hole.expression.name===alias.name)&&isUnsafeHole(hole));if(unsafe)report(text,"template")}};return{Program(program){ownsFile=usesModule(program)},"FunctionDeclaration, FunctionExpression, ArrowFunctionExpression"(node){const name=callableName(node);if(name!==void 0)definitions.set(name,(definitions.get(name)??0)+1)},CallExpression(node){const callee=node.callee;const isMember=callee.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression;const calleeName=isMember?(0,spellings_1.propertyName)(callee)??void 0:callee.type===ast_node_types_1.AST_NODE_TYPES.Identifier?callee.name:void 0;if(calleeName===void 0)return;if(!isMember&&ownsFile){const imported=importedName(callee);if(imported!==null&&fragmentFunctions.has(imported)){requestTextSink=true;if(node.arguments[0])check(node.arguments[0],false);return}if(imported!==null&&aliasCallbacks.has(imported)){checkAliasCallback(node);return}}const fragment=isMember?fragmentSinks.get(calleeName):void 0;if(!isMember||!statementSinks.has(calleeName)&&!fragment){for(const[index,arg]of node.arguments.entries()){if(arg.type===ast_node_types_1.AST_NODE_TYPES.SpreadElement)continue;pending.push({name:calleeName,index,arg})}return}const receiver=originOf((0,value_follow_1.valueAt)(callee.object,env));if(receiver==="foreign")return;if(fragment?.requireDriverReceiver&&receiver!=="ours")return;if(!ownsFile&&!(receiver==="ours"&&!PARTITION_SHARED_SINKS.has(calleeName))){return}const queryArg=node.arguments[fragment?.arg??0];if(!queryArg||queryArg.type===ast_node_types_1.AST_NODE_TYPES.SpreadElement)return;if(queryArg.type===ast_node_types_1.AST_NODE_TYPES.Identifier){const fn=enclosingFunction(node);const index=fn?.params.findIndex(p=>p.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&p.name===queryArg.name)??-1;const name=fn&&index>=0?callableName(fn):void 0;if(name!==void 0&&fn){wrappers.set(name,index);wrapperFns.set(fn,name)}}const gate=fragment===void 0&&config.requireSqlKeywords&&receiver!=="ours";requestTextSink=!isStatementObject(callee.object);check(queryArg,gate)},"Program:exit"(){if(!ownsFile)return;const proven=new Map;for(const name of wrapperFns.values())proven.set(name,(proven.get(name)??0)+1);for(const{name,index,arg}of pending){if(wrappers.get(name)!==index)continue;if(definitions.get(name)!==proven.get(name))continue;const kind=judge(arg,true);if(kind)report((0,type_syntax_1.unwrapTypeSyntax)(arg),kind)}}}}}}
|
|
@@ -0,0 +1,51 @@
|
|
|
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
|
+
* Where a hole sits in a SQL string — and so what it takes to report it.
|
|
8
|
+
*
|
|
9
|
+
* A VALUE position (after `=`, `<`, `LIKE`, inside `'…'`, in an `IN (…)` or
|
|
10
|
+
* `VALUES (…)` list, after `LIMIT`) always has a safe alternative: a bind
|
|
11
|
+
* parameter. Any value the file cannot prove fixed is a finding there.
|
|
12
|
+
*
|
|
13
|
+
* A FRAGMENT position (a table or column name, `ORDER BY` / `SAVEPOINT`
|
|
14
|
+
* targets, a whole clause or subquery spliced in) has no bind parameter, so
|
|
15
|
+
* composing it is the only way to build the statement. Query builders,
|
|
16
|
+
* migration helpers and savepoint managers do exactly that with values from
|
|
17
|
+
* their own callers. There a hole is reported when the file can trace it to
|
|
18
|
+
* the inbound request — `ORDER BY ${req.query.sort}` — not merely because it
|
|
19
|
+
* is unproven.
|
|
20
|
+
*/
|
|
21
|
+
import type { TSESTree } from '@typescript-eslint/utils';
|
|
22
|
+
import { type Env } from './value-follow';
|
|
23
|
+
/** One interpolated value, with the SQL text written before it. */
|
|
24
|
+
export interface SqlHole {
|
|
25
|
+
readonly expression: TSESTree.Node;
|
|
26
|
+
readonly preceding: string;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Every value spliced into a template or `+` chain, with the static text in
|
|
30
|
+
* front of it. A ternary or `||` between two string-building arms is walked
|
|
31
|
+
* into, so `${a ? \` AND x = '${v}'\` : ''}` yields `v` with `… AND x = '`.
|
|
32
|
+
*/
|
|
33
|
+
export declare function sqlHoles(node: TSESTree.Node, prefix?: string): SqlHole[];
|
|
34
|
+
/**
|
|
35
|
+
* Is a hole preceded by `text` inside a quoted token — a `'…'` string, or an
|
|
36
|
+
* identifier quote (`` ` ``, `[`, `"`)? An escaper's output carries its own
|
|
37
|
+
* quotes, so there it closes the author's token instead of staying inside it.
|
|
38
|
+
*/
|
|
39
|
+
export declare function isQuoted(text: string): boolean;
|
|
40
|
+
/**
|
|
41
|
+
* Is a hole preceded by `text` in a VALUE position?
|
|
42
|
+
*
|
|
43
|
+
* @param doubleQuotedStrings `"…"` delimits a string (MySQL's default mode)
|
|
44
|
+
* rather than an identifier (standard SQL, SQLite, PostgreSQL).
|
|
45
|
+
*/
|
|
46
|
+
export declare function isValuePosition(text: string, doubleQuotedStrings?: boolean): boolean;
|
|
47
|
+
/**
|
|
48
|
+
* Can this value be traced, in this file, to the inbound request — the
|
|
49
|
+
* payload itself, a field of it, or text derived from one?
|
|
50
|
+
*/
|
|
51
|
+
export declare function isRequestDerived(node: TSESTree.Node, env: Env, depth?: number): boolean;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.sqlHoles=sqlHoles;exports.isQuoted=isQuoted;exports.isValuePosition=isValuePosition;exports.isRequestDerived=isRequestDerived;const ast_node_types_1=require("../ast-node-types");const spellings_1=require("../ast/spellings");const type_syntax_1=require("../ast/type-syntax");const request_source_1=require("./request-source");const driver_origin_1=require("./driver-origin");const value_follow_1=require("./value-follow");function sqlHoles(node,prefix=""){const value=(0,type_syntax_1.unwrapTypeSyntax)(node);if(value.type===ast_node_types_1.AST_NODE_TYPES.TemplateLiteral){const holes=[];let text=prefix;value.quasis.forEach((quasi,index)=>{text+=quasi.value.raw;const expression=value.expressions[index];if(expression===void 0)return;holes.push(...sqlHoles(expression,text));text+=textOf(expression)});return holes}if(value.type===ast_node_types_1.AST_NODE_TYPES.BinaryExpression&&value.operator==="+"){const left=sqlHoles(value.left,prefix);return[...left,...sqlHoles(value.right,prefix+textOf(value.left))]}if(value.type===ast_node_types_1.AST_NODE_TYPES.ConditionalExpression&&buildsText(value)){return[...sqlHoles(value.consequent,prefix),...sqlHoles(value.alternate,prefix)]}if(value.type===ast_node_types_1.AST_NODE_TYPES.LogicalExpression&&value.operator!=="&&"&&buildsText(value)){return[...sqlHoles(value.left,prefix),...sqlHoles(value.right,prefix)]}if((0,spellings_1.staticString)(value)!==null)return[];return[{expression:value,preceding:prefix}]}function buildsText(node){const arms=node.type===ast_node_types_1.AST_NODE_TYPES.ConditionalExpression?[node.consequent,node.alternate]:[node.left,node.right];return arms.some(arm=>{const value=(0,type_syntax_1.unwrapTypeSyntax)(arm);return value.type===ast_node_types_1.AST_NODE_TYPES.TemplateLiteral||value.type===ast_node_types_1.AST_NODE_TYPES.BinaryExpression&&value.operator==="+"||(value.type===ast_node_types_1.AST_NODE_TYPES.ConditionalExpression||value.type===ast_node_types_1.AST_NODE_TYPES.LogicalExpression)&&buildsText(value)})}function isQuoted(text){const quotes=text.replace(/''/g,"").split("'").length-1;return quotes%2===1||/[`["]$/.test(text)}function textOf(node){const value=(0,type_syntax_1.unwrapTypeSyntax)(node);if(value.type===ast_node_types_1.AST_NODE_TYPES.TemplateLiteral)return value.quasis.map(q=>q.value.raw).join("");if(value.type===ast_node_types_1.AST_NODE_TYPES.BinaryExpression&&value.operator==="+")return textOf(value.left)+textOf(value.right);return(0,spellings_1.staticString)(value)??""}const VALUE_OPERATOR=/(?:[=<>]|!=|\b(?:like|ilike|limit|offset|between|then|else|regexp|glob|match|escape))$/i;function isValuePosition(text,doubleQuotedStrings=false){if(/^\s*pragma\b/i.test(text))return false;const quotes=text.replace(/''/g,"").split("'").length-1;if(quotes%2===1)return true;if(/[`[]$/.test(text)||!doubleQuotedStrings&&text.endsWith('"'))return false;const tail=text.replace(/[\s"%]+$/,"");if(VALUE_OPERATOR.test(tail))return true;let depth=0;for(let i=tail.length-1;i>=0;i--){const ch=tail[i];if(ch===")")depth++;else if(ch==="("){if(depth===0)return/\b(?:in|values)\s*$/i.test(tail.slice(0,i));depth--}}return false}function isRequestDerived(node,env,depth=0){if(depth>value_follow_1.MAX_FOLLOW_DEPTH)return false;const value=(0,type_syntax_1.unwrapTypeSyntax)(node);if((0,request_source_1.isRequestPayload)(value,env))return true;const derived=next=>isRequestDerived(next,env,depth+1);switch(value.type){case ast_node_types_1.AST_NODE_TYPES.MemberExpression:return derived(value.object);case ast_node_types_1.AST_NODE_TYPES.TemplateLiteral:return value.expressions.some(derived);case ast_node_types_1.AST_NODE_TYPES.BinaryExpression:return derived(value.left)||derived(value.right);case ast_node_types_1.AST_NODE_TYPES.LogicalExpression:return derived(value.left)||derived(value.right);case ast_node_types_1.AST_NODE_TYPES.ConditionalExpression:return derived(value.consequent)||derived(value.alternate);case ast_node_types_1.AST_NODE_TYPES.AwaitExpression:return derived(value.argument);case ast_node_types_1.AST_NODE_TYPES.CallExpression:{const callee=value.callee;if(callee.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&derived(callee.object))return true;if(!isMethodOfData(callee,env)&&value.arguments.some(a=>a.type!==ast_node_types_1.AST_NODE_TYPES.SpreadElement&&derived(a))){return true}if(callee.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression)return false;const target=(0,value_follow_1.follow)((0,value_follow_1.valueAt)(callee,env));return target.env===env&&(0,driver_origin_1.isFunctionNode)(target.node)&&((0,value_follow_1.returnedValues)(target.node)??[]).some(derived)}case ast_node_types_1.AST_NODE_TYPES.Identifier:{const variable=(0,value_follow_1.lookup)(value.name,env.scopeOf(value));const def=variable?.defs[0];if(variable===null||def?.type!=="Variable")return false;if(def.node.id.type!==ast_node_types_1.AST_NODE_TYPES.Identifier){return def.node.init!==null&&derived(def.node.init)}const loop=def.node.parent.parent;if(loop?.type===ast_node_types_1.AST_NODE_TYPES.ForOfStatement&&loop.left===def.node.parent){return derived(loop.right)}const written=(0,value_follow_1.singleWrite)(variable);if(written!==null)return derived(written);return variable.references.some(r=>r.isWrite()&&r.writeExpr!=null&&derived(r.writeExpr))}default:return false}}function isMethodOfData(callee,env){if(callee.type!==ast_node_types_1.AST_NODE_TYPES.MemberExpression)return false;let root=callee.object;while(root.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression)root=root.object;if(root.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return true;const variable=(0,value_follow_1.lookup)(root.name,env.scopeOf(root));return variable!==null&&variable.defs.length>0&&(0,value_follow_1.importSpecifierOf)(variable)===null}
|