@interlace/eslint-devkit 1.19.8 → 1.20.1
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/ast/module-binding.js +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
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@interlace/eslint-devkit",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.20.1",
|
|
4
4
|
"description": "Toolkit for building ESLint plugins in TypeScript — AST helpers, type utilities, rule-creation scaffolding, security benchmarks, and SARIF output.",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.resolveModuleBinding=resolveModuleBinding;exports.isModuleBinding=isModuleBinding;const spellings_1=require("./spellings");const ast_node_types_1=require("../ast-node-types");function normalize(specifier,options){const bare=specifier.startsWith("node:")?specifier.slice("node:".length):specifier;return options.equivalents?.[bare]??bare}function requireTarget(node,options){if(node.type!==ast_node_types_1.AST_NODE_TYPES.CallExpression)return void 0;if(node.callee.type!==ast_node_types_1.AST_NODE_TYPES.Identifier||node.callee.name!=="require")return void 0;const[arg]=node.arguments;if(arg?.type!==ast_node_types_1.AST_NODE_TYPES.Literal)return void 0;return typeof arg.value==="string"?normalize(arg.value,options):void 0}function destructuredKey(pattern,boundName){if(pattern.type!==ast_node_types_1.AST_NODE_TYPES.ObjectPattern)return void 0;for(const property of pattern.properties){if(property.type!==ast_node_types_1.AST_NODE_TYPES.Property)continue;if(property.
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.resolveModuleBinding=resolveModuleBinding;exports.isModuleBinding=isModuleBinding;const spellings_1=require("./spellings");const ast_node_types_1=require("../ast-node-types");function normalize(specifier,options){const bare=specifier.startsWith("node:")?specifier.slice("node:".length):specifier;return options.equivalents?.[bare]??bare}function requireTarget(node,options){if(node.type!==ast_node_types_1.AST_NODE_TYPES.CallExpression)return void 0;if(node.callee.type!==ast_node_types_1.AST_NODE_TYPES.Identifier||node.callee.name!=="require")return void 0;const[arg]=node.arguments;if(arg?.type!==ast_node_types_1.AST_NODE_TYPES.Literal)return void 0;return typeof arg.value==="string"?normalize(arg.value,options):void 0}function destructuredKey(pattern,boundName){if(pattern.type!==ast_node_types_1.AST_NODE_TYPES.ObjectPattern)return void 0;for(const property of pattern.properties){if(property.type!==ast_node_types_1.AST_NODE_TYPES.Property)continue;if(property.value.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)continue;if(property.value.name!==boundName)continue;return(0,spellings_1.objectKeyName)(property)??void 0}return void 0}function lookup(name,scope){for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===name);if(variable)return variable}return void 0}function resolveModuleBinding(node,scope,options={}){return resolve(node,scope,options,new Set)}function resolve(node,scope,options,seen){if(seen.has(node))return void 0;seen.add(node);const required=requireTarget(node,options);if(required!==void 0)return{module:required,path:[]};if(node.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression){const property=(0,spellings_1.propertyName)(node);if(property===null)return void 0;const base2=resolve(node.object,scope,options,seen);return base2&&{module:base2.module,path:[...base2.path,property]}}if(node.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return void 0;const variable=lookup(node.name,scope);const def=variable?.defs[0];if(!def)return void 0;if(def.type==="ImportBinding"){const declaration=def.parent;if(declaration?.type!==ast_node_types_1.AST_NODE_TYPES.ImportDeclaration)return void 0;const module=normalize(String(declaration.source.value),options);if(def.node.type===ast_node_types_1.AST_NODE_TYPES.ImportSpecifier){const imported=def.node.imported;const name=imported.type===ast_node_types_1.AST_NODE_TYPES.Identifier?imported.name:String(imported.value);return{module,path:[name]}}return{module,path:[]}}if(def.type!=="Variable"||!def.node.init)return void 0;if(variable&&variable.references.filter(ref=>ref.isWrite()).length!==1)return void 0;const base=resolve(def.node.init,scope,options,seen);if(!base)return void 0;if(def.node.id.type===ast_node_types_1.AST_NODE_TYPES.Identifier)return base;const key=destructuredKey(def.node.id,node.name);return key===void 0?void 0:{module:base.module,path:[...base.path,key]}}function isModuleBinding(node,scope,module,exportPath,options={}){const binding=resolveModuleBinding(node,scope,options);if(!binding||binding.module!==module)return false;if(!exportPath)return true;return binding.path.length===exportPath.length&&exportPath.every((part,i)=>binding.path[i]===part)}
|
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
* taxonomy contract keeps it in the SDK's plugin rather than in
|
|
34
34
|
* `browser-security`.
|
|
35
35
|
*/
|
|
36
|
-
import type { TSESTree } from '@typescript-eslint/utils';
|
|
36
|
+
import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
|
|
37
37
|
/** The opt-in both SDKs spell identically. */
|
|
38
38
|
export declare const BROWSER_ESCAPE_FLAG = "dangerouslyAllowBrowser";
|
|
39
39
|
export interface BrowserEscapeHatchRuleConfig {
|
|
@@ -47,11 +47,45 @@ export interface BrowserEscapeHatchRuleConfig {
|
|
|
47
47
|
docsUrl: string;
|
|
48
48
|
/** Vendor documentation link carried in the message. */
|
|
49
49
|
documentationLink: string;
|
|
50
|
+
/**
|
|
51
|
+
* Client options that carry the credential, e.g. `['apiKey', 'authToken']`.
|
|
52
|
+
* Default `['apiKey']`.
|
|
53
|
+
*/
|
|
54
|
+
credentialProps?: readonly string[];
|
|
55
|
+
/**
|
|
56
|
+
* Client options that take a *token provider* instead of a key, e.g.
|
|
57
|
+
* `azureADTokenProvider`. Both SDKs' Azure clients turn the browser flag on
|
|
58
|
+
* themselves when one is passed — a per-user Entra token, not a shared key.
|
|
59
|
+
* Default `['azureADTokenProvider']`.
|
|
60
|
+
*/
|
|
61
|
+
tokenProviderProps?: readonly string[];
|
|
50
62
|
}
|
|
63
|
+
export type CredentialOrigin = 'runtime' | 'shipped';
|
|
64
|
+
/**
|
|
65
|
+
* Where a browser client's credential comes from.
|
|
66
|
+
*
|
|
67
|
+
* `shipped` — the build or the bundle carries it: a literal, an environment
|
|
68
|
+
* read (`import.meta.env.VITE_…` is inlined), an imported or global constant.
|
|
69
|
+
* That is the app's own key, and the flag hands it to every visitor.
|
|
70
|
+
*
|
|
71
|
+
* `runtime` — the browser obtains it per session: a function (the SDKs accept a
|
|
72
|
+
* key *provider*), a parameter (the visitor's own key, bring-your-own-key), or
|
|
73
|
+
* the result of an `await` or a call (an ephemeral token fetched from the
|
|
74
|
+
* app's server — the pattern OpenAI's Realtime docs prescribe for browsers).
|
|
75
|
+
* Nothing of the app's ships.
|
|
76
|
+
*
|
|
77
|
+
* A mixture (`userKey || import.meta.env.VITE_KEY`) is `shipped`: the fallback
|
|
78
|
+
* still ships.
|
|
79
|
+
*/
|
|
80
|
+
export declare function credentialOrigin(node: TSESTree.Node, sourceCode: Readonly<TSESLint.SourceCode>, hops?: number): CredentialOrigin;
|
|
51
81
|
export type FlagVerdict = 'enabled' | 'absent' | 'unreadable';
|
|
52
82
|
/**
|
|
53
83
|
* Whether the client options literal turns the browser escape hatch on.
|
|
54
84
|
*
|
|
85
|
+
* @deprecated The rule no longer calls this: it follows consts and same-file
|
|
86
|
+
* spreads through `readObjectProperty`, which a single-node reader cannot.
|
|
87
|
+
* Kept because it is public API.
|
|
88
|
+
*
|
|
55
89
|
* A non-literal value is `unreadable` — `{ dangerouslyAllowBrowser: isBrowser }`
|
|
56
90
|
* could be either at runtime, and reporting on a guess would flag correct code.
|
|
57
91
|
* An explicit `false` is `absent`: the author already made the safe choice.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BROWSER_ESCAPE_FLAG=void 0;exports.readFlag=readFlag;exports.createBrowserEscapeHatchRule=createBrowserEscapeHatchRule;const rule_creator_1=require("./rule-creator");const messaging_1=require("../messaging");const module_evidence_1=require("./module-evidence");exports.BROWSER_ESCAPE_FLAG="dangerouslyAllowBrowser";function isFlagProperty(prop){return prop.type!=="SpreadElement"&&!prop.computed&&(prop.key.type==="Identifier"&&prop.key.name===exports.BROWSER_ESCAPE_FLAG||prop.key.type==="Literal"&&prop.key.value===exports.BROWSER_ESCAPE_FLAG)}function readFlag(options){const props=options.properties;const index=props.findIndex(isFlagProperty);if(index===-1){return props.some(prop=>prop.type==="SpreadElement")?"unreadable":"absent"}for(let i=index+1;i<props.length;i++){if(props[i].type==="SpreadElement")return"unreadable"}const value=props[index].value;if(value.type==="Literal"&&value.value===true)return"enabled";if(value.type==="Literal")return"absent";return"unreadable"}function createBrowserEscapeHatchRule(config){const usesSdk=(0,module_evidence_1.createModuleListEvidence)(config.modules);return(0,rule_creator_1.createRule)({name:config.ruleName,meta:{type:"problem",docs:{url:config.docsUrl,description:`Forbid ${exports.BROWSER_ESCAPE_FLAG}, which exposes the ${config.vendor} API key to the client`,cwe:"CWE-522",cvss:8.6},messages:{browserKeyExposure:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:`${config.vendor} API Key Exposed to the Browser`,cwe:"CWE-522",owasp:"A07:2021",cvss:8.6,description:"dangerouslyAllowBrowser lets the SDK run client-side, which ships the API key to every visitor",severity:"HIGH",compliance:["SOC2","PCI-DSS"],fix:`Call ${config.vendor} from a server route and forward the result, so the key never leaves the server`,documentationLink:config.documentationLink})},schema:[]},defaultOptions:[],create(context){if(!usesSdk(context.sourceCode.ast))return{};function
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BROWSER_ESCAPE_FLAG=void 0;exports.credentialOrigin=credentialOrigin;exports.readFlag=readFlag;exports.createBrowserEscapeHatchRule=createBrowserEscapeHatchRule;const rule_creator_1=require("./rule-creator");const messaging_1=require("../messaging");const module_evidence_1=require("./module-evidence");const ast_node_types_1=require("../ast-node-types");const type_syntax_1=require("../ast/type-syntax");const sdk_flow_1=require("./sdk-flow");exports.BROWSER_ESCAPE_FLAG="dangerouslyAllowBrowser";function credentialOrigin(node,sourceCode,hops=sdk_flow_1.MAX_FOLLOW_HOPS){const current=(0,type_syntax_1.unwrapTypeSyntax)(node);if(hops<=0)return"shipped";const either=(a,b)=>credentialOrigin(a,sourceCode,hops-1)==="shipped"||credentialOrigin(b,sourceCode,hops-1)==="shipped"?"shipped":"runtime";switch(current.type){case ast_node_types_1.AST_NODE_TYPES.ArrowFunctionExpression:case ast_node_types_1.AST_NODE_TYPES.FunctionExpression:case ast_node_types_1.AST_NODE_TYPES.AwaitExpression:case ast_node_types_1.AST_NODE_TYPES.CallExpression:case ast_node_types_1.AST_NODE_TYPES.NewExpression:return"runtime";case ast_node_types_1.AST_NODE_TYPES.ConditionalExpression:return either(current.consequent,current.alternate);case ast_node_types_1.AST_NODE_TYPES.LogicalExpression:return either(current.left,current.right);case ast_node_types_1.AST_NODE_TYPES.MemberExpression:return(0,sdk_flow_1.isEnvironmentRead)(current,sourceCode)?"shipped":credentialOrigin(current.object,sourceCode,hops-1);case ast_node_types_1.AST_NODE_TYPES.Identifier:{const variable=(0,sdk_flow_1.variableOf)(current,sourceCode);const definition=variable?.defs[0];if(definition===void 0)return"shipped";if(definition.type==="Parameter"||definition.type==="FunctionName"){return"runtime"}const init=definition.type==="Variable"?definition.node.init:null;return init===null?"shipped":credentialOrigin(init,sourceCode,hops-1)}default:return"shipped"}}function isFlagProperty(prop){return prop.type!=="SpreadElement"&&!prop.computed&&(prop.key.type==="Identifier"&&prop.key.name===exports.BROWSER_ESCAPE_FLAG||prop.key.type==="Literal"&&prop.key.value===exports.BROWSER_ESCAPE_FLAG)}function readFlag(options){const props=options.properties;const index=props.findIndex(isFlagProperty);if(index===-1){return props.some(prop=>prop.type==="SpreadElement")?"unreadable":"absent"}for(let i=index+1;i<props.length;i++){if(props[i].type==="SpreadElement")return"unreadable"}const value=props[index].value;if(value.type==="Literal"&&value.value===true)return"enabled";if(value.type==="Literal")return"absent";return"unreadable"}function createBrowserEscapeHatchRule(config){const usesSdk=(0,module_evidence_1.createModuleListEvidence)(config.modules);const matcher=(0,sdk_flow_1.createSdkClientMatcher)((0,module_evidence_1.createModuleListMatcher)(config.modules));const credentialProps=config.credentialProps??["apiKey"];const tokenProviderProps=config.tokenProviderProps??["azureADTokenProvider"];return(0,rule_creator_1.createRule)({name:config.ruleName,meta:{type:"problem",docs:{url:config.docsUrl,description:`Forbid ${exports.BROWSER_ESCAPE_FLAG}, which exposes the ${config.vendor} API key to the client`,cwe:"CWE-522",cvss:8.6},messages:{browserKeyExposure:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:`${config.vendor} API Key Exposed to the Browser`,cwe:"CWE-522",owasp:"A07:2021",cvss:8.6,description:"dangerouslyAllowBrowser lets the SDK run client-side, which ships the API key to every visitor",severity:"HIGH",compliance:["SOC2","PCI-DSS"],fix:`Call ${config.vendor} from a server route and forward the result, so the key never leaves the server`,documentationLink:config.documentationLink})},schema:[]},defaultOptions:[],create(context){if(!usesSdk(context.sourceCode.ast))return{};const sourceCode=context.sourceCode;function flagEnabled(options){const read=(0,sdk_flow_1.readObjectProperty)(options,exports.BROWSER_ESCAPE_FLAG,sourceCode);if(read.kind!=="value")return false;const value=(0,sdk_flow_1.followConst)(read.node,sourceCode);return value.type===ast_node_types_1.AST_NODE_TYPES.Literal&&value.value===true}function hasTokenProvider(options){return tokenProviderProps.some(prop=>{const read=(0,sdk_flow_1.readObjectProperty)(options,prop,sourceCode);if(read.kind!=="value")return false;const value=(0,sdk_flow_1.followConst)(read.node,sourceCode);return!(value.type===ast_node_types_1.AST_NODE_TYPES.Literal||value.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&value.name==="undefined")})}function credentialIsRuntime(options){const values=credentialProps.map(prop=>(0,sdk_flow_1.readObjectProperty)(options,prop,sourceCode)).flatMap(read=>read.kind==="value"?[read.node]:[]);return values.length>0&&values.every(value=>credentialOrigin(value,sourceCode)==="runtime")}function inspect(node){for(const index of matcher.optionArguments(node,sourceCode)){const argument=node.arguments[index];if(argument===void 0||argument.type===ast_node_types_1.AST_NODE_TYPES.SpreadElement)continue;const options=(0,sdk_flow_1.resolveObjectLiteral)(argument,sourceCode);if(options===void 0||!flagEnabled(options))continue;if(hasTokenProvider(options)||credentialIsRuntime(options)){continue}context.report({node,messageId:"browserKeyExposure"});return}}return{NewExpression:inspect,CallExpression:inspect}}})}
|
|
@@ -0,0 +1,49 @@
|
|
|
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
|
+
* Shared evidence for the two connection-config detectors (TLS, credentials).
|
|
8
|
+
*
|
|
9
|
+
* Both scan object literals shaped like a database connection. Three things
|
|
10
|
+
* decide whether one is the driver's, and none of them is a name:
|
|
11
|
+
*
|
|
12
|
+
* - the FILE loads the driver, or holds the driver's own config-file shape
|
|
13
|
+
* with no import at all — a knexfile (`{ client: 'pg', connection }`), a
|
|
14
|
+
* sequelize-cli `config.js` (`{ dialect: 'mysql', username }`), a TypeORM
|
|
15
|
+
* `ormconfig.js` (`{ type: 'mysql', entities }`). The key and its value
|
|
16
|
+
* set are the library's documented contract;
|
|
17
|
+
* - the object is not handed to ANOTHER library: `new https.Agent({ host,
|
|
18
|
+
* rejectUnauthorized: false })` in a file that also imports mysql2 is an
|
|
19
|
+
* HTTPS client, and another plugin's finding;
|
|
20
|
+
* - a value is followed to where it is written, so `ssl: sslOptions` and
|
|
21
|
+
* `password: process.env.DB_PASSWORD || 'root'` are read, not skipped.
|
|
22
|
+
*/
|
|
23
|
+
import type { TSESTree } from '@typescript-eslint/utils';
|
|
24
|
+
import { type Origin } from './driver-origin';
|
|
25
|
+
import { type ExtraEvidence } from './module-evidence';
|
|
26
|
+
import { type Env, type Value } from './value-follow';
|
|
27
|
+
/**
|
|
28
|
+
* A driver's config-file contract: an object whose `key` holds one of
|
|
29
|
+
* `values`, beside at least one of `with`.
|
|
30
|
+
*/
|
|
31
|
+
export interface ConfigShape {
|
|
32
|
+
readonly key: string;
|
|
33
|
+
readonly values: readonly string[];
|
|
34
|
+
readonly with: readonly string[];
|
|
35
|
+
}
|
|
36
|
+
/** Evidence that a file holds one of the driver's config-file shapes. */
|
|
37
|
+
export declare function configShapeEvidence(shapes: readonly ConfigShape[]): ExtraEvidence | undefined;
|
|
38
|
+
/**
|
|
39
|
+
* Is this object literal an argument to a call or `new` whose callee is
|
|
40
|
+
* provably another library's — `new https.Agent({…})`, `axios.create({…})`?
|
|
41
|
+
*/
|
|
42
|
+
export declare function passedToForeign(object: TSESTree.ObjectExpression, originOf: (value: Value) => Origin, env: Env): boolean;
|
|
43
|
+
/**
|
|
44
|
+
* The values a configuration property can take: the value itself, both arms
|
|
45
|
+
* of a ternary, both sides of `||` / `??`, each followed to where it is
|
|
46
|
+
* written. Each comes back with the environment it must be read in — a value
|
|
47
|
+
* defined in another module cannot be reported there.
|
|
48
|
+
*/
|
|
49
|
+
export declare function possibleValues(value: Value, depth?: number): Value[];
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.configShapeEvidence=configShapeEvidence;exports.passedToForeign=passedToForeign;exports.possibleValues=possibleValues;const ast_node_types_1=require("../ast-node-types");const spellings_1=require("../ast/spellings");const type_syntax_1=require("../ast/type-syntax");const value_follow_1=require("./value-follow");function configShapeEvidence(shapes){if(shapes.length===0)return void 0;return node=>{if(node.type!==ast_node_types_1.AST_NODE_TYPES.ObjectExpression)return false;const keys=new Map;for(const property of node.properties){if(property.type!==ast_node_types_1.AST_NODE_TYPES.Property)continue;const key=(0,spellings_1.objectKeyName)(property);if(key!==null)keys.set(key,property.value)}return shapes.some(shape=>{const value=keys.get(shape.key);return value?.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof value.value==="string"&&shape.values.includes(value.value)&&shape.with.some(key=>keys.has(key))})}}function passedToForeign(object,originOf,env){const parent=object.parent;return(parent?.type===ast_node_types_1.AST_NODE_TYPES.CallExpression||parent?.type===ast_node_types_1.AST_NODE_TYPES.NewExpression)&&parent.arguments.some(argument=>argument===object)&&originOf((0,value_follow_1.valueAt)(parent.callee,env))==="foreign"}function possibleValues(value,depth=0){if(depth>8)return[value];const node=(0,type_syntax_1.unwrapTypeSyntax)(value.node);if(node.type===ast_node_types_1.AST_NODE_TYPES.ConditionalExpression){return[...possibleValues((0,value_follow_1.valueAt)(node.consequent,value.env),depth+1),...possibleValues((0,value_follow_1.valueAt)(node.alternate,value.env),depth+1)]}if(node.type===ast_node_types_1.AST_NODE_TYPES.LogicalExpression){return[...possibleValues((0,value_follow_1.valueAt)(node.left,value.env),depth+1),...possibleValues((0,value_follow_1.valueAt)(node.right,value.env),depth+1)]}if(node.type===ast_node_types_1.AST_NODE_TYPES.Identifier||node.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression){const followed=(0,value_follow_1.follow)(value);if(followed.node!==value.node)return possibleValues(followed,depth+1)}return[(0,value_follow_1.valueAt)(node,value.env)]}
|
|
@@ -0,0 +1,52 @@
|
|
|
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 receiver comes from, decided from structure — never from its name.
|
|
8
|
+
*
|
|
9
|
+
* The driver plugins used to decide "is `x.update(...)` a database write?" by
|
|
10
|
+
* matching the receiver's NAME against a pattern (`/^(knex|db|…)$|[Dd]b$/`).
|
|
11
|
+
* Renaming `db` to `store` silenced every finding, and naming a `Map` `db`
|
|
12
|
+
* produced one. This module replaces that with a bounded walk to where the
|
|
13
|
+
* receiver is written:
|
|
14
|
+
*
|
|
15
|
+
* - an `import` / `require` of one of the plugin's modules is `'ours'`;
|
|
16
|
+
* - an import of any other package, a literal, a local class that does not
|
|
17
|
+
* extend the driver's, or a JavaScript / TypeScript lib global (`Map`,
|
|
18
|
+
* `URLSearchParams`) is `'foreign'`;
|
|
19
|
+
* - a RELATIVE import is read from disk and judged where it is exported;
|
|
20
|
+
* - a parameter is judged by its type annotation, or as the callback
|
|
21
|
+
* parameter of a call on a driver receiver (`db.transaction(async (trx) => …)`);
|
|
22
|
+
* - `this.x` is judged by the class member, constructor parameter property
|
|
23
|
+
* or constructor assignment that declares it;
|
|
24
|
+
* - anything else — an undeclared name, an untyped parameter, a path alias
|
|
25
|
+
* the linter cannot read — is `'unknown'`, and the caller decides how much
|
|
26
|
+
* the call's own shape has to prove before it reports.
|
|
27
|
+
*/
|
|
28
|
+
import type { TSESTree } from '@typescript-eslint/utils';
|
|
29
|
+
import { type Value } from './value-follow';
|
|
30
|
+
/** Where a value comes from, relative to one plugin's driver modules. */
|
|
31
|
+
export type Origin = 'ours' | 'foreign' | 'unknown';
|
|
32
|
+
/** `@/lib/db`, `~/db`, `#db` — a path alias the linter cannot read from disk. */
|
|
33
|
+
export declare function isPathAlias(specifier: string): boolean;
|
|
34
|
+
/** Does `source` name one of `modules` (by package root)? */
|
|
35
|
+
export declare function sourceMatches(source: string, modules: readonly string[]): boolean;
|
|
36
|
+
/** Combine the origins of two values either of which may be the result. */
|
|
37
|
+
export declare function eitherOrigin(a: Origin, b: Origin): Origin;
|
|
38
|
+
/** Is this node a function of any form? */
|
|
39
|
+
export declare function isFunctionNode(node: TSESTree.Node): node is TSESTree.FunctionLike;
|
|
40
|
+
/** The type annotation written on a parameter or declarator id. */
|
|
41
|
+
export declare function writtenAnnotation(identifier: TSESTree.Node): TSESTree.TypeNode | undefined;
|
|
42
|
+
/**
|
|
43
|
+
* Build the origin classifier for one plugin's modules.
|
|
44
|
+
*
|
|
45
|
+
* Returns a function that classifies any expression; it is pure, and safe to
|
|
46
|
+
* call repeatedly within one lint run.
|
|
47
|
+
*/
|
|
48
|
+
export type OriginClassifier = ((value: Value) => Origin) & {
|
|
49
|
+
/** Where a written TYPE annotation comes from: `Knex.Raw`, `Prisma.Sql`. */
|
|
50
|
+
readonly ofType: (value: Value) => Origin;
|
|
51
|
+
};
|
|
52
|
+
export declare function createOriginClassifier(modules: readonly string[]): OriginClassifier;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isPathAlias=isPathAlias;exports.sourceMatches=sourceMatches;exports.eitherOrigin=eitherOrigin;exports.isFunctionNode=isFunctionNode;exports.writtenAnnotation=writtenAnnotation;exports.createOriginClassifier=createOriginClassifier;const ast_node_types_1=require("../ast-node-types");const spellings_1=require("../ast/spellings");const type_syntax_1=require("../ast/type-syntax");const module_evidence_1=require("./module-evidence");const value_follow_1=require("./value-follow");const PLATFORM_GLOBALS=new Set(["Array","Map","Set","WeakMap","WeakSet","Object","JSON","Math","Promise","Reflect","URL","URLSearchParams","Headers","FormData","Date","globalThis","window","document","console","process","Buffer"]);function isPathAlias(specifier){return/^(?:[@~]\/|~|#)/.test(specifier)}function sourceMatches(source,modules){return modules.some(m=>source===m||source.startsWith(`${m}/`))}function eitherOrigin(a,b){if(a==="ours"||b==="ours")return"ours";return a==="foreign"&&b==="foreign"?"foreign":"unknown"}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 writtenAnnotation(identifier){const holder=identifier;return holder.typeAnnotation?.typeAnnotation}function enclosingClass(node){for(let n=node.parent;n;n=n.parent){if(n.type===ast_node_types_1.AST_NODE_TYPES.ClassDeclaration||n.type===ast_node_types_1.AST_NODE_TYPES.ClassExpression){return n}}return void 0}function typeRoot(name){let cursor=name;while(cursor.type===ast_node_types_1.AST_NODE_TYPES.TSQualifiedName)cursor=cursor.left;return cursor.type===ast_node_types_1.AST_NODE_TYPES.Identifier?cursor:null}function createOriginClassifier(modules){const loadsDriver=(0,module_evidence_1.createModuleEvidence)({packages:modules});const classOrigin=(cls,value,depth,seen)=>cls.superClass===null?"foreign":classify((0,value_follow_1.valueAt)(cls.superClass,value.env),depth+1,seen);const declarationOrigin=(value,depth,seen)=>{const node=value.node;if(node.type===ast_node_types_1.AST_NODE_TYPES.TSTypeAliasDeclaration){return typeOrigin((0,value_follow_1.valueAt)(node.typeAnnotation,value.env),depth+1,seen)}if(node.type===ast_node_types_1.AST_NODE_TYPES.TSInterfaceDeclaration){return node.extends.map(base=>classify((0,value_follow_1.valueAt)(base.expression,value.env),depth+1,seen)).includes("ours")?"ours":"foreign"}return classify(value,depth+1,seen)};const typeOrigin=(value,depth,seen)=>{const node=value.node;if(node.type===ast_node_types_1.AST_NODE_TYPES.TSUnionType||node.type===ast_node_types_1.AST_NODE_TYPES.TSIntersectionType){return node.types.map(t=>typeOrigin((0,value_follow_1.valueAt)(t,value.env),depth+1,seen)).reduce(eitherOrigin)}if(node.type===ast_node_types_1.AST_NODE_TYPES.TSTypeQuery){const root2=node.exprName.type===ast_node_types_1.AST_NODE_TYPES.TSImportType?null:typeRoot(node.exprName);return root2===null?"unknown":classify((0,value_follow_1.valueAt)(root2,value.env),depth+1,seen)}if(node.type!==ast_node_types_1.AST_NODE_TYPES.TSTypeReference)return"foreign";const root=typeRoot(node.typeName);const variable=(0,value_follow_1.lookup)(root.name,value.env.scopeOf(root));if(variable===null)return"unknown";if(variable.defs.length===0)return"foreign";const specifier=(0,value_follow_1.importSpecifierOf)(variable);if(specifier!==null){if(sourceMatches(specifier.source,modules))return"ours";if(!(0,value_follow_1.isRelativeSpecifier)(specifier.source))return isPathAlias(specifier.source)?"unknown":"foreign";const origin=(0,value_follow_1.importOrigin)(variable,value.env);const exported=origin===null||origin.name==="*"?null:(0,value_follow_1.exportedValue)(origin.module,origin.name,value.env.parser);return exported===null?"unknown":declarationOrigin(exported,depth+1,seen)}return declarationOrigin((0,value_follow_1.valueAt)(variable.defs[0].node,value.env),depth,seen)};const thisOrigin=(at,key,value,depth,seen)=>{const cls=enclosingClass(at);if(cls===void 0)return"unknown";for(const element of key===null?[]:cls.body.body){if(element.type===ast_node_types_1.AST_NODE_TYPES.PropertyDefinition&&!element.computed&&element.key.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&element.key.name===key){if(element.typeAnnotation){return typeOrigin((0,value_follow_1.valueAt)(element.typeAnnotation.typeAnnotation,value.env),depth+1,seen)}return element.value===null?"unknown":classify((0,value_follow_1.valueAt)(element.value,value.env),depth+1,seen)}if(element.type!==ast_node_types_1.AST_NODE_TYPES.MethodDefinition||element.kind!=="constructor"){continue}for(const param of element.value.params){if(param.type!==ast_node_types_1.AST_NODE_TYPES.TSParameterProperty)continue;const inner=param.parameter.type===ast_node_types_1.AST_NODE_TYPES.AssignmentPattern?param.parameter.left:param.parameter;if(inner.type!==ast_node_types_1.AST_NODE_TYPES.Identifier||inner.name!==key)continue;const annotation=writtenAnnotation(inner);return annotation===void 0?"unknown":typeOrigin((0,value_follow_1.valueAt)(annotation,value.env),depth+1,seen)}for(const statement of element.value.body?.body??[]){if(statement.type===ast_node_types_1.AST_NODE_TYPES.ExpressionStatement&&statement.expression.type===ast_node_types_1.AST_NODE_TYPES.AssignmentExpression&&statement.expression.left.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&statement.expression.left.object.type===ast_node_types_1.AST_NODE_TYPES.ThisExpression&&(0,spellings_1.propertyName)(statement.expression.left)===key){return classify((0,value_follow_1.valueAt)(statement.expression.right,value.env),depth+1,seen)}}}return classOrigin(cls,value,depth,seen)==="ours"?"ours":"unknown"};const parameterOrigin=(identifier,fn,value,depth,seen)=>{const annotation=writtenAnnotation(identifier);if(annotation!==void 0){return typeOrigin((0,value_follow_1.valueAt)(annotation,value.env),depth+1,seen)}const call=fn.parent;if(call?.type===ast_node_types_1.AST_NODE_TYPES.CallExpression&&call.callee.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&call.arguments.some(argument=>argument===fn)&&classify((0,value_follow_1.valueAt)(call.callee.object,value.env),depth+1,seen)==="ours"){return"ours"}return"unknown"};const identifierOrigin=(node,value,depth,seen)=>{const variable=(0,value_follow_1.lookup)(node.name,value.scope);if(variable===null)return PLATFORM_GLOBALS.has(node.name)?"foreign":"unknown";if(variable.defs.length===0)return"foreign";const specifier=(0,value_follow_1.importSpecifierOf)(variable);if(specifier!==null){if(sourceMatches(specifier.source,modules))return"ours";if(!(0,value_follow_1.isRelativeSpecifier)(specifier.source))return isPathAlias(specifier.source)?"unknown":"foreign";const followed2=(0,value_follow_1.follow)(value);const judged=followed2.node===value.node||followed2.node.type===ast_node_types_1.AST_NODE_TYPES.Program?"unknown":classify(followed2,depth+1,seen);if(judged!=="unknown")return judged;const origin=(0,value_follow_1.importOrigin)(variable,value.env);return origin!==null&&loadsDriver(origin.module.ast)?"ours":judged}const def=variable.defs[0];if(def.type==="Parameter"){return parameterOrigin(variable.identifiers[0],def.node,value,depth,seen)}if(def.type==="ClassName"){return classOrigin(def.node,value,depth,seen)}if(def.type!=="Variable")return"foreign";const annotation=writtenAnnotation(def.node.id);if(annotation!==void 0){const typed=typeOrigin((0,value_follow_1.valueAt)(annotation,value.env),depth+1,seen);if(typed!=="unknown")return typed}const followed=(0,value_follow_1.follow)(value);if(followed.node!==value.node)return classify(followed,depth+1,seen);const writes=variable.references.filter(r=>r.isWrite()&&r.writeExpr).map(r=>classify((0,value_follow_1.valueAt)(r.writeExpr,value.env),depth+1,seen));return writes.length===0?"unknown":writes.reduce(eitherOrigin)};function classify(value,depth=0,seen=new Set){if(depth>value_follow_1.MAX_FOLLOW_DEPTH||seen.has(value.node))return"unknown";seen.add(value.node);const node=(0,type_syntax_1.unwrapTypeSyntax)(value.node);const inner=target=>classify((0,value_follow_1.valueAt)(target,value.env),depth+1,seen);switch(node.type){case ast_node_types_1.AST_NODE_TYPES.AwaitExpression:return inner(node.argument);case ast_node_types_1.AST_NODE_TYPES.ChainExpression:return inner(node.expression);case ast_node_types_1.AST_NODE_TYPES.Identifier:return identifierOrigin(node,(0,value_follow_1.valueAt)(node,value.env),depth,seen);case ast_node_types_1.AST_NODE_TYPES.ThisExpression:return thisOrigin(node,null,value,depth,seen);case ast_node_types_1.AST_NODE_TYPES.MemberExpression:{if(node.object.type===ast_node_types_1.AST_NODE_TYPES.ThisExpression)return thisOrigin(node,(0,spellings_1.propertyName)(node),value,depth,seen);const followed=(0,value_follow_1.follow)((0,value_follow_1.valueAt)(node,value.env));if(followed.node!==node)return classify(followed,depth+1,seen);return inner(node.object)}case ast_node_types_1.AST_NODE_TYPES.CallExpression:{const callee=(0,value_follow_1.follow)((0,value_follow_1.valueAt)(node.callee,value.env));if(isFunctionNode(callee.node)){const returned=(0,value_follow_1.returnedValue)(callee.node);return returned===null?"unknown":classify((0,value_follow_1.valueAt)(returned,callee.env),depth+1,seen)}return inner(node.callee)}case ast_node_types_1.AST_NODE_TYPES.NewExpression:return inner(node.callee);case ast_node_types_1.AST_NODE_TYPES.ClassDeclaration:case ast_node_types_1.AST_NODE_TYPES.ClassExpression:return classOrigin(node,value,depth,seen);case ast_node_types_1.AST_NODE_TYPES.LogicalExpression:return eitherOrigin(inner(node.left),inner(node.right));case ast_node_types_1.AST_NODE_TYPES.ConditionalExpression:return eitherOrigin(inner(node.consequent),inner(node.alternate));case ast_node_types_1.AST_NODE_TYPES.Literal:case ast_node_types_1.AST_NODE_TYPES.TemplateLiteral:case ast_node_types_1.AST_NODE_TYPES.ObjectExpression:case ast_node_types_1.AST_NODE_TYPES.ArrayExpression:case ast_node_types_1.AST_NODE_TYPES.FunctionExpression:case ast_node_types_1.AST_NODE_TYPES.ArrowFunctionExpression:case ast_node_types_1.AST_NODE_TYPES.FunctionDeclaration:return"foreign";default:return"unknown"}}return Object.assign(value=>classify(value),{ofType:value=>typeOrigin(value,0,new Set)})}
|
|
@@ -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
|
/**
|
|
8
9
|
* Two ids because the fixes differ in shape.
|
|
9
10
|
*
|
|
@@ -36,6 +37,17 @@ export interface HardcodedCredentialsRuleConfig {
|
|
|
36
37
|
readonly connectionKeys?: readonly string[];
|
|
37
38
|
/** URL schemes this driver accepts, e.g. `['postgres', 'postgresql']`. */
|
|
38
39
|
readonly urlSchemes: readonly string[];
|
|
40
|
+
/**
|
|
41
|
+
* The driver's config-file contracts — a sequelize-cli `{ dialect:
|
|
42
|
+
* 'mysql', username }` — that mark a file with no driver import as the
|
|
43
|
+
* driver's.
|
|
44
|
+
*/
|
|
45
|
+
readonly configShapes?: readonly ConfigShape[];
|
|
46
|
+
/**
|
|
47
|
+
* Argument index of a positional password in the driver's constructor —
|
|
48
|
+
* `new Sequelize(database, username, password, options)`.
|
|
49
|
+
*/
|
|
50
|
+
readonly positionalPassword?: number;
|
|
39
51
|
/** Remediation for a literal credential property. */
|
|
40
52
|
readonly fix: string;
|
|
41
53
|
/** Remediation for a credential embedded in a URL. */
|
|
@@ -79,3 +91,9 @@ export declare function staticStringValue(node: TSESTree.Node): string | undefin
|
|
|
79
91
|
export declare function isLiteralSecret(node: TSESTree.Node): boolean;
|
|
80
92
|
/** Build a CWE-798 rule for one driver's connection surface. */
|
|
81
93
|
export declare function createHardcodedCredentialsRule(config: HardcodedCredentialsRuleConfig): TSESLint.RuleModule<HardcodedCredentialsMessageIds, []>;
|
|
94
|
+
/**
|
|
95
|
+
* The text a connection URL starts with: a string literal's value, or the
|
|
96
|
+
* head of a template up to its first hole. `mysql://root:s3cret@${host}/db`
|
|
97
|
+
* still commits the password in the head.
|
|
98
|
+
*/
|
|
99
|
+
export declare function urlPrefix(node: TSESTree.Node): string | undefined;
|
|
@@ -1 +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){const[{value}]=node.quasis;return value.cooked??value.raw}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){
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.urlEmbedsCredentials=urlEmbedsCredentials;exports.staticStringValue=staticStringValue;exports.isLiteralSecret=isLiteralSecret;exports.createHardcodedCredentialsRule=createHardcodedCredentialsRule;exports.urlPrefix=urlPrefix;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 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){const[{value}]=node.quasis;return value.cooked??value.raw}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??[]];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:{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){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 scanned=new WeakSet;const report=(node,messageId)=>{if(reported.has(node))return;reported.add(node);context.report({node,messageId})};const reportSecrets=node=>{for(const value of(0,connection_config_1.possibleValues)((0,value_follow_1.valueAt)(node,env))){if(!isLiteralSecret(value.node))continue;report(value.env===env&&(0,require_tls_rule_1.within)(value.node,node)?value.node:node,"hardcodedPassword")}};const reportUrl=node=>{for(const value of(0,connection_config_1.possibleValues)((0,value_follow_1.valueAt)(node,env))){const url=urlPrefix(value.node);if(url===void 0||!urlEmbedsCredentials(url,config.urlSchemes))continue;report(value.env===env&&(0,require_tls_rule_1.within)(value.node,node)?value.node:node,"credentialsInUrl");return true}return false};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())){reportSecrets(prop.value);continue}if(reportUrl(prop.value))continue;if(connectionKeys.includes(name)){for(const value of(0,connection_config_1.possibleValues)((0,value_follow_1.valueAt)(prop.value,env))){if(value.env===env&&value.node.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression){scanConfig(value.node)}}}}};return{Program(program){ownsFile=usesModule(program)},ObjectExpression(node){if(!ownsFile)return;if(!(0,require_tls_rule_1.looksLikeConnectionConfig)(node,connectionKeys))return;if((0,connection_config_1.passedToForeign)(node,originOf,env))return;scanConfig(node)},"CallExpression, NewExpression"(node){if(!ownsFile)return;if(originOf((0,value_follow_1.valueAt)(node.callee,env))!=="ours")return;for(const argument of node.arguments){if(argument.type!==ast_node_types_1.AST_NODE_TYPES.SpreadElement)reportUrl(argument)}const index=config.positionalPassword;if(index!==void 0&&node.type===ast_node_types_1.AST_NODE_TYPES.NewExpression&&node.arguments.length>index){reportSecrets(node.arguments[index])}},"Literal, TemplateLiteral"(node){if(!ownsFile)return;const value=urlPrefix(node);if(value===void 0)return;if(!urlEmbedsCredentials(value,config.urlSchemes))return;if(!(0,require_tls_rule_1.inConnectionPosition)(node,connectionKeys,callee=>originOf((0,value_follow_1.valueAt)(callee,env))==="ours")){return}report(node,"credentialsInUrl")}}}}}function urlPrefix(node){const value=staticStringValue(node);if(value!==void 0)return value;if(node.type!==ast_node_types_1.AST_NODE_TYPES.TemplateLiteral)return void 0;const[head]=node.quasis;return head.value.raw}
|
|
@@ -1 +1 @@
|
|
|
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("./generated-file"),exports);__exportStar(require("./minified-file"),exports);__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("./message-source"),exports);__exportStar(require("./raw-identifier-rule"),exports);__exportStar(require("./module-evidence"),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("./generated-file"),exports);__exportStar(require("./minified-file"),exports);__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("./message-source"),exports);__exportStar(require("./raw-identifier-rule"),exports);__exportStar(require("./module-evidence"),exports);__exportStar(require("./sdk-flow"),exports);
|
|
@@ -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 Env } from './value-follow';
|
|
7
8
|
/**
|
|
8
9
|
* Two ids because the shapes read differently at the call site, and a reader
|
|
9
10
|
* who sees "spread" needs to be told the spread is the problem, not the object
|
|
@@ -42,38 +43,42 @@ export interface MassAssignmentRuleConfig {
|
|
|
42
43
|
/** Driver modules — the plugin-scope gate. */
|
|
43
44
|
readonly modules: readonly string[];
|
|
44
45
|
/**
|
|
45
|
-
*
|
|
46
|
+
* @deprecated Ignored. The receiver was once matched by NAME against this
|
|
47
|
+
* pattern; it is now classified by where it is written (`driver-origin.ts`).
|
|
48
|
+
* Kept so an existing caller still type-checks.
|
|
49
|
+
*/
|
|
50
|
+
readonly receiverPattern?: RegExp;
|
|
51
|
+
/**
|
|
52
|
+
* What a write must look like to be reported when its receiver cannot be
|
|
53
|
+
* traced to the driver (an undeclared name, an untyped parameter, a path
|
|
54
|
+
* alias the linter cannot read). A receiver PROVEN to be the driver's is
|
|
55
|
+
* always enough; one proven to be another library's — a `Map`, `Headers`,
|
|
56
|
+
* a cache client — never is.
|
|
46
57
|
*
|
|
47
|
-
*
|
|
48
|
-
*
|
|
49
|
-
*
|
|
50
|
-
*
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
*
|
|
58
|
+
* - `'model-accessor'` — Prisma's `<client>.<model>.create(…)`.
|
|
59
|
+
* - `'table-call'` — Knex's `<knex>('users').insert(…)`, or a chain that
|
|
60
|
+
* names its table with `.into()` / `.table()` / `.from()`.
|
|
61
|
+
* - `'builder-chain'` — Drizzle's `<db>.insert(t).values(…)` /
|
|
62
|
+
* `<db>.update(t).set(…)`: the write method follows the statement verb.
|
|
63
|
+
*
|
|
64
|
+
* Without one (Sequelize, TypeORM: `Model.create`, `repo.save`), an
|
|
65
|
+
* untraceable receiver is not reported — `cache.create(req.body)` and
|
|
66
|
+
* `User.create(req.body)` are the same program when neither name resolves.
|
|
55
67
|
*/
|
|
56
|
-
readonly
|
|
68
|
+
readonly distinctiveShape?: 'model-accessor' | 'table-call' | 'builder-chain';
|
|
69
|
+
/**
|
|
70
|
+
* An options key that is the driver's own column allowlist — Sequelize's
|
|
71
|
+
* `create(req.body, { fields: ['name'] })`. Its presence is the fix.
|
|
72
|
+
*/
|
|
73
|
+
readonly allowlistOption?: string;
|
|
57
74
|
readonly fix: string;
|
|
58
75
|
readonly documentationLink: string;
|
|
59
76
|
}
|
|
60
77
|
/**
|
|
61
|
-
*
|
|
62
|
-
*
|
|
63
|
-
*
|
|
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.
|
|
78
|
+
* Classify one write argument: the request payload itself, a spread of it
|
|
79
|
+
* into an object literal, or neither. The request is recognised by where it
|
|
80
|
+
* comes from (`request-source.ts`), never by what it is called.
|
|
76
81
|
*/
|
|
77
|
-
export declare function classifyPayload(node: TSESTree.Node): MassAssignmentMessageIds | false;
|
|
82
|
+
export declare function classifyPayload(node: TSESTree.Node, env: Env, isOurs?: (node: TSESTree.Node) => boolean): MassAssignmentMessageIds | false;
|
|
78
83
|
/** Build a CWE-915 rule for one driver's write surface. */
|
|
79
84
|
export declare function createMassAssignmentRule(config: MassAssignmentRuleConfig): TSESLint.RuleModule<MassAssignmentMessageIds, []>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.classifyPayload=classifyPayload;exports.createMassAssignmentRule=createMassAssignmentRule;const ast_node_types_1=require("../ast-node-types");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 unscoped_mutation_rule_1=require("./unscoped-mutation-rule");const value_follow_1=require("./value-follow");function classifyPayload(node,env,isOurs=()=>false){if((0,request_source_1.isRequestPayload)(node,env))return"untrustedPayload";if(node.type===ast_node_types_1.AST_NODE_TYPES.Identifier){const variable=(0,value_follow_1.lookup)(node.name,env.scopeOf(node));const filled=variable?.references.some(reference=>{const call=reference.identifier.parent;if(call===void 0||!isObjectAssign(call))return false;const args=call.arguments;return args[0]===reference.identifier&&!isOurs(reference.identifier)&&args.slice(1).some(source=>(0,request_source_1.isRequestPayload)(source,env))});if(filled===true)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((0,request_source_1.isRequestPayload)(prop.argument,env))return"untrustedSpread"}}return false}function isObjectAssign(node){return node.type===ast_node_types_1.AST_NODE_TYPES.CallExpression&&node.callee.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&node.callee.object.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&node.callee.object.name==="Object"&&!node.callee.computed&&node.callee.property.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&node.callee.property.name==="assign"}const WRITE_VERBS=new Set(["insert","update"]);function createMassAssignmentRule(config){const methods=new Set(config.methods);const payloadKeys=new Set(config.payloadKeys??[]);const usesModule=(0,module_evidence_1.createModuleEvidence)({packages:config.modules});const originOf=(0,driver_origin_1.createOriginClassifier)(config.modules);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){if((0,rule_creator_1.isTestFilePath)(context.filename))return{};const env=(0,value_follow_1.envOf)(context);let ownsFile=false;const isOurs=node=>originOf((0,value_follow_1.valueAt)(node,env))==="ours";const hasDistinctiveShape=node=>{const callee=node.callee;switch(config.distinctiveShape){case"model-accessor":return callee.object.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression;case"table-call":{const chained=(0,unscoped_mutation_rule_1.chainMethodNames)(node);return(0,unscoped_mutation_rule_1.startsWithTable)(callee.object)||["into","table","from"].some(m=>chained.has(m))}case"builder-chain":{const object=callee.object;return object.type===ast_node_types_1.AST_NODE_TYPES.CallExpression&&object.callee.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&WRITE_VERBS.has(object.callee.property.name)}default:return false}};return{Program(program){ownsFile=usesModule(program)},CallExpression(node){if(isObjectAssign(node)){const[target,...sources]=node.arguments;if(target===void 0||!isOurs(target))return;for(const source of sources){if((0,request_source_1.isRequestPayload)(source,env))context.report({node:source,messageId:"untrustedPayload"})}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 origin=originOf((0,value_follow_1.valueAt)(node.callee.object,env));if(origin==="foreign")return;if(origin==="unknown"&&!(ownsFile&&hasDistinctiveShape(node))){return}if(config.allowlistOption!==void 0&&node.arguments.some(arg=>arg.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression&&arg.properties.some(p=>p.type===ast_node_types_1.AST_NODE_TYPES.Property&&(0,unscoped_mutation_rule_1.propertyKeyName)(p)===config.allowlistOption))){return}for(const arg of node.arguments){if(arg.type===ast_node_types_1.AST_NODE_TYPES.SpreadElement)continue;const direct=classifyPayload(arg,env,isOurs);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,env,isOurs);if(nested)context.report({node:prop.value,messageId:nested})}}}}}}}
|
|
@@ -31,40 +31,6 @@ export interface ModuleEvidenceConfig {
|
|
|
31
31
|
/** Non-import shapes that also mean "this file uses the SDK". */
|
|
32
32
|
readonly extraEvidence?: ExtraEvidence;
|
|
33
33
|
}
|
|
34
|
-
/**
|
|
35
|
-
* Build a per-file "does this file use my SDK?" probe.
|
|
36
|
-
*
|
|
37
|
-
* Every SDK-specific plugin gates every rule on one of these. Measured over
|
|
38
|
-
* 107,382 files across 107 repositories, **40% of all SDK-plugin findings were
|
|
39
|
-
* about an SDK the file never imports** — `lambda-security` reported on any
|
|
40
|
-
* `try/catch`, `postgresql-security` on any `.connect()`, and the seven SQL
|
|
41
|
-
* plugins on each other. A rule that matches a method name is detecting a word,
|
|
42
|
-
* not an interface.
|
|
43
|
-
*
|
|
44
|
-
* This lives in the devkit because it previously did not: five plugins each
|
|
45
|
-
* carried their own copy, so the two false-negative classes the audit found —
|
|
46
|
-
* TypeScript's `import =` and Deno's specifiers — had to be fixed five times,
|
|
47
|
-
* and the next such class would have been fixed ten. One implementation, one
|
|
48
|
-
* fix.
|
|
49
|
-
*
|
|
50
|
-
* The returned probe caches per `Program`, because `create` runs once per rule:
|
|
51
|
-
* an uncached probe walks the whole AST once for every rule in the plugin, and
|
|
52
|
-
* the files paying that cost are mostly the ones the gate exists to skip.
|
|
53
|
-
*
|
|
54
|
-
* @example
|
|
55
|
-
* ```ts
|
|
56
|
-
* export const fileUsesPostgres = createModuleEvidence({
|
|
57
|
-
* packages: ['pg', 'postgres', 'slonik'],
|
|
58
|
-
* scopes: ['@neondatabase'],
|
|
59
|
-
* });
|
|
60
|
-
*
|
|
61
|
-
* // in a rule:
|
|
62
|
-
* create(context) {
|
|
63
|
-
* if (!fileUsesPostgres(context.sourceCode.ast)) return {};
|
|
64
|
-
* …
|
|
65
|
-
* }
|
|
66
|
-
* ```
|
|
67
|
-
*/
|
|
68
34
|
export declare function createModuleEvidence(config: ModuleEvidenceConfig): (ast: TSESTree.Program) => boolean;
|
|
69
35
|
/**
|
|
70
36
|
* Build a probe from a flat `modules` list of the kind the SDK rule factories
|
|
@@ -87,6 +53,13 @@ export declare function createModuleEvidence(config: ModuleEvidenceConfig): (ast
|
|
|
87
53
|
* in one place.
|
|
88
54
|
*/
|
|
89
55
|
export declare function createModuleListEvidence(modules: readonly string[]): (ast: TSESTree.Program) => boolean;
|
|
56
|
+
/**
|
|
57
|
+
* The specifier test {@link createModuleListEvidence} opens its gate with,
|
|
58
|
+
* for a rule that must also ask *which* binding came from the SDK — the probe
|
|
59
|
+
* answers "does this file load it?", this answers "did this name come from it?".
|
|
60
|
+
* Same normalisation (Deno `npm:` / `deno.land/x`), same package-root match.
|
|
61
|
+
*/
|
|
62
|
+
export declare function createModuleListMatcher(modules: readonly string[]): (specifier: string) => boolean;
|
|
90
63
|
/**
|
|
91
64
|
* Does a module specifier name a package, or something inside one?
|
|
92
65
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.createModuleEvidence=createModuleEvidence;exports.createModuleListEvidence=createModuleListEvidence;exports.matchesModule=matchesModule;const ast_node_types_1=require("../ast-node-types");function normalizeSpecifier(specifier){if(specifier.startsWith("npm:"))return specifier.slice(4);const deno=/^https?:\/\/deno\.land\/x\/([^@/]+)/.exec(specifier);return deno?deno[1]:specifier}function importEqualsSpecifier(node){if(node.type!==ast_node_types_1.AST_NODE_TYPES.TSImportEqualsDeclaration)return null;const ref=node.moduleReference;if(ref.type!==ast_node_types_1.AST_NODE_TYPES.TSExternalModuleReference)return null;return ref.expression.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof ref.expression.value==="string"?ref.expression.value:null}function bindsRequire(node){if(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){return node.params.some(p=>p.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&p.name==="require")}if(node.type===ast_node_types_1.AST_NODE_TYPES.Program||node.type===ast_node_types_1.AST_NODE_TYPES.BlockStatement){return node.body.some(stmt=>stmt.type===ast_node_types_1.AST_NODE_TYPES.VariableDeclaration&&stmt.declarations.some(d=>d.id.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&d.id.name==="require"))}return false}function
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.createModuleEvidence=createModuleEvidence;exports.createModuleListEvidence=createModuleListEvidence;exports.createModuleListMatcher=createModuleListMatcher;exports.matchesModule=matchesModule;const ast_node_types_1=require("../ast-node-types");function normalizeSpecifier(specifier){if(specifier.startsWith("npm:"))return specifier.slice(4);const deno=/^https?:\/\/deno\.land\/x\/([^@/]+)/.exec(specifier);return deno?deno[1]:specifier}function importEqualsSpecifier(node){if(node.type!==ast_node_types_1.AST_NODE_TYPES.TSImportEqualsDeclaration)return null;const ref=node.moduleReference;if(ref.type!==ast_node_types_1.AST_NODE_TYPES.TSExternalModuleReference)return null;return ref.expression.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof ref.expression.value==="string"?ref.expression.value:null}function bindsRequire(node){if(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){return node.params.some(p=>p.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&p.name==="require")}if(node.type===ast_node_types_1.AST_NODE_TYPES.Program||node.type===ast_node_types_1.AST_NODE_TYPES.BlockStatement){return node.body.some(stmt=>stmt.type===ast_node_types_1.AST_NODE_TYPES.VariableDeclaration&&stmt.declarations.some(d=>d.id.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&d.id.name==="require"))}return false}function createSpecifierMatcher(config){const packages=new Set(config.packages??[]);const scopes=new Set(config.scopes??[]);const prefixes=config.prefixes??[];return raw=>{const specifier=normalizeSpecifier(raw);if(specifier.startsWith(".")||specifier.startsWith("/"))return false;if(specifier.startsWith("@")){const[scope,name]=specifier.split("/");if(scopes.has(scope))return true;const root2=name===void 0?scope:`${scope}/${name}`;return packages.has(root2)||prefixes.some(p=>root2.startsWith(p))}const root=specifier.split("/")[0];return packages.has(root)||prefixes.some(p=>root.startsWith(p))}}function createModuleEvidence(config){const extra=config.extraEvidence;const owns=createSpecifierMatcher(config);const dynamicLoadSpecifier=(node,requireIsShadowed)=>{const argument=node.type===ast_node_types_1.AST_NODE_TYPES.ImportExpression?node.source:!requireIsShadowed&&node.type===ast_node_types_1.AST_NODE_TYPES.CallExpression&&node.callee.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&node.callee.name==="require"?node.arguments[0]:void 0;return argument?.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof argument.value==="string"?argument.value:null};const cache=new WeakMap;const compute=ast=>{let found=false;const visit=(node,requireIsShadowed)=>{if((node.type===ast_node_types_1.AST_NODE_TYPES.ImportDeclaration||node.type===ast_node_types_1.AST_NODE_TYPES.ExportNamedDeclaration||node.type===ast_node_types_1.AST_NODE_TYPES.ExportAllDeclaration)&&node.source?.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof node.source.value==="string"&&owns(node.source.value)){found=true;return}const importEquals=importEqualsSpecifier(node);if(importEquals!==null&&owns(importEquals)){found=true;return}const dynamic=dynamicLoadSpecifier(node,requireIsShadowed);if(dynamic!==null&&owns(dynamic)){found=true;return}if(extra?.(node)){found=true;return}const shadowedHere=requireIsShadowed||bindsRequire(node);for(const key of Object.keys(node)){if(key==="parent")continue;const value=node[key];if(Array.isArray(value)){for(const child of value){if(child&&typeof child.type==="string"){visit(child,shadowedHere);if(found)return}}}else if(value&&typeof value==="object"&&typeof value.type==="string"){visit(value,shadowedHere);if(found)return}}};visit(ast,false);return found};return ast=>{const cached=cache.get(ast);if(cached!==void 0)return cached;const result=compute(ast);cache.set(ast,result);return result}}function createModuleListEvidence(modules){return createModuleEvidence(moduleListConfig(modules))}function moduleListConfig(modules){const isBareScope=m=>m.startsWith("@")&&!m.includes("/");return{packages:modules.filter(m=>!isBareScope(m)),scopes:modules.filter(isBareScope)}}function createModuleListMatcher(modules){return createSpecifierMatcher(moduleListConfig(modules))}function matchesModule(source,modules){return modules.some(m=>source===m||source.startsWith(`${m}/`))}
|
|
@@ -61,6 +61,14 @@ export interface RawIdentifierRuleConfig {
|
|
|
61
61
|
* would miss the shape most codebases actually have.
|
|
62
62
|
*/
|
|
63
63
|
readonly requireImport: boolean;
|
|
64
|
+
/**
|
|
65
|
+
* Tag names that count only when the tag provably belongs to the driver —
|
|
66
|
+
* a bare tag imported from `modules` under that name (renamed or not), or a
|
|
67
|
+
* member tag whose object is the driver's (`Prisma.sql`). For a generic
|
|
68
|
+
* name in a plugin whose other tags stand alone. `requireImport: true`
|
|
69
|
+
* applies this to every tag.
|
|
70
|
+
*/
|
|
71
|
+
readonly driverTags?: readonly string[];
|
|
64
72
|
/**
|
|
65
73
|
* Callee texts that safely escape an identifier, e.g. `['sql.identifier']`.
|
|
66
74
|
*
|
|
@@ -1 +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 spellings_1=require("../ast/spellings");const messaging_1=require("../messaging");const
|
|
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 spellings_1=require("../ast/spellings");const messaging_1=require("../messaging");const type_syntax_1=require("../ast/type-syntax");const rule_creator_1=require("./rule-creator");const driver_origin_1=require("./driver-origin");const sql_safety_1=require("./sql-safety");const value_follow_1=require("./value-follow");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){const object=calleeText(node.object);const property=(0,spellings_1.propertyName)(node);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){return(0,spellings_1.propertyName)(tag)??void 0}return void 0}function createRawIdentifierRule(config){const tags=new Set([...config.tags,...config.driverTags??[]]);const driverTags=new Set(config.driverTags??[]);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){if((0,rule_creator_1.isTestFilePath)(context.filename))return{};const env=(0,value_follow_1.envOf)(context);const originOf=(0,driver_origin_1.createOriginClassifier)(config.modules);const safety=(0,sql_safety_1.createSqlSafety)({origin:originOf,escapers:new Set,fragmentFactories:new Set,modules:config.modules});const tagKey=tag=>{if(tag.type===ast_node_types_1.AST_NODE_TYPES.Identifier){const variable=(0,value_follow_1.lookup)(tag.name,env.scopeOf(tag));const specifier=variable===null?null:(0,value_follow_1.importSpecifierOf)(variable);if(specifier!==null&&(0,driver_origin_1.sourceMatches)(specifier.source,config.modules))return{name:specifier.name,driver:true};return{name:tag.name,driver:false}}const name=tagName(tag);if(name===void 0)return void 0;const object=tag.object;return{name,driver:originOf((0,value_follow_1.valueAt)(object,env))==="ours"}};const isDriverObject=(node,depth=0)=>{if(depth>8)return false;const value=(0,type_syntax_1.unwrapTypeSyntax)(node);switch(value.type){case ast_node_types_1.AST_NODE_TYPES.Identifier:{const variable=(0,value_follow_1.lookup)(value.name,env.scopeOf(value));if(variable===null)return false;const specifier=(0,value_follow_1.importSpecifierOf)(variable);if(specifier!==null){if((0,driver_origin_1.sourceMatches)(specifier.source,config.modules))return true;const followed=(0,value_follow_1.follow)((0,value_follow_1.valueAt)(value,env));return followed.node!==value&&followed.env!==env&&isExportedDriverObject(followed.node,followed.env)}const def=variable.defs[0];if(def?.type!=="Variable"||def.node.id.type!==ast_node_types_1.AST_NODE_TYPES.Identifier){return false}const written=(0,value_follow_1.singleWrite)(variable);return written!==null&&isDriverObject(written,depth+1)}case ast_node_types_1.AST_NODE_TYPES.MemberExpression:return isDriverObject(value.object,depth+1);case ast_node_types_1.AST_NODE_TYPES.ConditionalExpression:return isDriverObject(value.consequent,depth+1)&&isDriverObject(value.alternate,depth+1);case ast_node_types_1.AST_NODE_TYPES.TaggedTemplateExpression:return isDriverObject(value.tag,depth+1);case ast_node_types_1.AST_NODE_TYPES.NewExpression:return isDriverObject(value.callee,depth+1);case ast_node_types_1.AST_NODE_TYPES.CallExpression:{const callee=value.callee;if(callee.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&(0,spellings_1.propertyName)(callee)==="raw"){const[text]=value.arguments;return text!==void 0&&safety.isSafe((0,value_follow_1.valueAt)(text,env))}if(callee.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&(0,spellings_1.propertyName)(callee)==="as"){return originOf((0,value_follow_1.valueAt)(callee.object,env))==="ours"}return isDriverObject(callee,depth+1)}default:return false}};const isExportedDriverObject=(node,moduleEnv)=>{const value=(0,type_syntax_1.unwrapTypeSyntax)(node);if(value.type!==ast_node_types_1.AST_NODE_TYPES.CallExpression)return false;let root=value.callee;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 false;const variable=(0,value_follow_1.lookup)(root.name,moduleEnv.scopeOf(root));const specifier=variable===null?null:(0,value_follow_1.importSpecifierOf)(variable);return specifier!==null&&(0,driver_origin_1.sourceMatches)(specifier.source,config.modules)};const isUsedAsObject=node=>{const value=(0,type_syntax_1.unwrapTypeSyntax)(node);if(value.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return false;const variable=(0,value_follow_1.lookup)(value.name,env.scopeOf(value));return variable!==null&&variable.references.some(reference=>{const use=reference.identifier.parent;return use?.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&use.object===reference.identifier&&!use.computed&&use.property.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&!(use.property.name in String.prototype)})};return{TaggedTemplateExpression(node){const key=tagKey(node.tag);if(key===void 0||!tags.has(key.name))return;if((config.requireImport||driverTags.has(key.name))&&!key.driver){return}if(node.tag.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&originOf((0,value_follow_1.valueAt)(node.tag.object,env))==="foreign"){return}const{quasis,expressions}=node.quasi;expressions.forEach((expr,index)=>{if(isExemptExpression(expr,config.identifierHelpers,config.tags))return;if(isDriverObject(expr)||isUsedAsObject(expr))return;if(safety.isSafe((0,value_follow_1.valueAt)(expr,env)))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"})})}}}}}
|
|
@@ -0,0 +1,36 @@
|
|
|
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
|
+
* Is this value an inbound HTTP request payload — decided from structure?
|
|
8
|
+
*
|
|
9
|
+
* The mass-assignment detector used to recognise a request by the NAME of the
|
|
10
|
+
* object the payload was read from (`req`, `request`, `ctx`, `context`,
|
|
11
|
+
* `event`). Renaming the handler's parameter to anything else silenced it.
|
|
12
|
+
* What actually marks a request is where the object comes from:
|
|
13
|
+
*
|
|
14
|
+
* - `p.body`, `p.query`, `p.params` — and Koa's `p.request.body` — where
|
|
15
|
+
* `p` is a function PARAMETER (a handler receives its request as one), or
|
|
16
|
+
* a name the file never declares;
|
|
17
|
+
* - `await p.json()` / `await p.formData()` on such a parameter (the Fetch
|
|
18
|
+
* `Request` every Next.js / Remix / Hono handler receives), and
|
|
19
|
+
* `Object.fromEntries(…)` / `JSON.parse(…)` of one;
|
|
20
|
+
* - a parameter decorated with a framework's own `@Body()` / `@Query()` /
|
|
21
|
+
* `@Param()`, resolved through its import;
|
|
22
|
+
* - a handler parameter destructured as `({ body })`;
|
|
23
|
+
* - a local binding written once from any of the above, including the
|
|
24
|
+
* `...rest` of a destructured payload.
|
|
25
|
+
*
|
|
26
|
+
* The property names are the frameworks' API (Express, Koa, Fastify, Lambda
|
|
27
|
+
* proxy events), not a guess about what a variable is called.
|
|
28
|
+
*/
|
|
29
|
+
import type { TSESTree } from '@typescript-eslint/utils';
|
|
30
|
+
import { type Env } from './value-follow';
|
|
31
|
+
/** Is this name the runtime global — no binding in the file, or a TS lib one? */
|
|
32
|
+
export declare function isGlobal(node: TSESTree.Identifier, env: Env): boolean;
|
|
33
|
+
/** Does a decorator on this parameter inject the request payload? */
|
|
34
|
+
export declare function hasPayloadDecorator(param: TSESTree.Node, env: Env): boolean;
|
|
35
|
+
/** Is `node` the whole request payload — not one field of it? */
|
|
36
|
+
export declare function isRequestPayload(node: TSESTree.Node, env: Env, depth?: number): boolean;
|