eslint-plugin-secure-coding 5.3.1 → 5.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/package.json +8 -2
- package/src/index.js +1 -1
- package/src/rules/no-graphql-injection/index.js +1 -1
- package/src/rules/no-hardcoded-credentials/index.js +1 -1
- package/src/rules/no-improper-sanitization/index.js +1 -1
- package/src/rules/no-improper-type-validation/index.js +1 -1
- package/src/rules/no-ldap-injection/index.js +1 -1
- package/src/rules/no-privilege-escalation/index.js +1 -1
- package/src/rules/no-sql-injection/index.js +1 -1
- package/src/rules/no-template-injection/index.js +1 -1
package/README.md
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
<p align="center">
|
|
2
|
-
<a href="https://eslint.interlace.tools
|
|
2
|
+
<a href="https://eslint.interlace.tools/docs/security/plugin-secure-coding?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding" target="blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://eslint.interlace.tools/logos/interlace-dark.svg"><img src="https://eslint.interlace.tools/logos/interlace-light.svg" alt="Interlace" height="90" /></picture></a>
|
|
3
3
|
|
|
4
4
|
<a href="https://oxc.rs" target="_blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://eslint.interlace.tools/logos/oxlint-dark.svg"><img src="https://eslint.interlace.tools/logos/oxlint-light.svg" alt="oxlint" height="90" /></picture></a>
|
|
5
5
|
|
|
@@ -227,5 +227,5 @@ MIT © [Ofri Peretz](https://github.com/ofri-peretz)
|
|
|
227
227
|
</p>
|
|
228
228
|
|
|
229
229
|
<p align="center">
|
|
230
|
-
<a href="https://eslint.interlace.tools
|
|
230
|
+
<a href="https://eslint.interlace.tools/docs/security/plugin-secure-coding?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding" target="blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://eslint.interlace.tools/logos/interlace-dark.svg"><img src="https://eslint.interlace.tools/logos/interlace-light.svg" alt="Interlace" height="70" /></picture></a>
|
|
231
231
|
</p>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "eslint-plugin-secure-coding",
|
|
3
|
-
"version": "5.3.
|
|
3
|
+
"version": "5.3.3",
|
|
4
4
|
"description": "ESLint plugin for secure coding — detects LDAP, XPath, XXE, GraphQL and template injection, unsafe deserialization, ReDoS, missing authentication, and PII in logs.",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -78,7 +78,7 @@
|
|
|
78
78
|
"node": ">=18.0.0"
|
|
79
79
|
},
|
|
80
80
|
"dependencies": {
|
|
81
|
-
"@interlace/eslint-devkit": "^1.19.
|
|
81
|
+
"@interlace/eslint-devkit": "^1.19.2",
|
|
82
82
|
"scslre": "^0.3.0",
|
|
83
83
|
"@eslint-community/regexpp": "^4.10.0"
|
|
84
84
|
},
|
|
@@ -94,5 +94,11 @@
|
|
|
94
94
|
"recheck": {
|
|
95
95
|
"optional": true
|
|
96
96
|
}
|
|
97
|
+
},
|
|
98
|
+
"interlace": {
|
|
99
|
+
"surface": {
|
|
100
|
+
"kind": "language",
|
|
101
|
+
"note": "Generic JS: eval, Function, regex, serialization, credentials. `recheck` is a ReDoS oracle this plugin CALLS, not a surface it analyses — the distinction the measurement got wrong, reading its surface as recheck's two exports."
|
|
102
|
+
}
|
|
97
103
|
}
|
|
98
104
|
}
|
package/src/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.configs=exports.plugin=exports.rules=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.rules={get"no-graphql-injection"(){return require("./rules/no-graphql-injection").noGraphqlInjection},get"no-xxe-injection"(){return require("./rules/no-xxe-injection").noXxeInjection},get"no-xpath-injection"(){return require("./rules/no-xpath-injection").noXpathInjection},get"no-ldap-injection"(){return require("./rules/no-ldap-injection").noLdapInjection},get"no-directive-injection"(){return require("./rules/no-directive-injection").noDirectiveInjection},get"no-format-string-injection"(){return require("./rules/no-format-string-injection").noFormatStringInjection},get"no-template-injection"(){return require("./rules/no-template-injection").noTemplateInjection},get"no-sql-injection"(){return require("./rules/no-sql-injection").noSqlInjection},get"no-log-injection"(){return require("./rules/no-log-injection").noLogInjection},get"no-fail-open-auth"(){return require("./rules/no-fail-open-auth").noFailOpenAuth},get"no-homoglyph-identifiers"(){return require("./rules/no-homoglyph-identifiers").noHomoglyphIdentifiers},get"detect-non-literal-regexp"(){return require("./rules/detect-non-literal-regexp").detectNonLiteralRegexp},get"no-redos-vulnerable-regex"(){return require("./rules/no-redos-vulnerable-regex").noRedosVulnerableRegex},get"no-unsafe-regex-construction"(){return require("./rules/no-unsafe-regex-construction").noUnsafeRegexConstruction},get"detect-object-injection"(){return require("./rules/detect-object-injection").detectObjectInjection},get"no-unsafe-deserialization"(){return require("./rules/no-unsafe-deserialization").noUnsafeDeserialization},get"no-insecure-comparison"(){return require("./rules/no-insecure-comparison").noInsecureComparison},get"no-improper-sanitization"(){return require("./rules/no-improper-sanitization").noImproperSanitization},get"no-improper-type-validation"(){return require("./rules/no-improper-type-validation").noImproperTypeValidation},get"no-missing-authentication"(){return require("./rules/no-missing-authentication").noMissingAuthentication},get"no-privilege-escalation"(){return require("./rules/no-privilege-escalation").noPrivilegeEscalation},get"no-weak-password-recovery"(){return require("./rules/no-weak-password-recovery").noWeakPasswordRecovery},get"require-backend-authorization"(){return require("./rules/require-backend-authorization").requireBackendAuthorization},get"no-hardcoded-credentials"(){return require("./rules/no-hardcoded-credentials").noHardcodedCredentials},get"no-sensitive-data-exposure"(){return require("./rules/no-sensitive-data-exposure").noSensitiveDataExposure},get"no-pii-in-logs"(){return require("./rules/no-pii-in-logs").noPiiInLogs},get"no-unlimited-resource-allocation"(){return require("./rules/no-unlimited-resource-allocation").noUnlimitedResourceAllocation},get"no-unchecked-loop-condition"(){return require("./rules/no-unchecked-loop-condition").noUncheckedLoopCondition},get"detect-weak-password-validation"(){return require("./rules/detect-weak-password-validation").detectWeakPasswordValidation},get"no-electron-security-issues"(){return require("./rules/no-electron-security-issues").noElectronSecurityIssues},get"no-hardcoded-session-tokens"(){return require("./rules/no-hardcoded-session-tokens").noHardcodedSessionTokens},get"require-secure-defaults"(){return require("./rules/require-secure-defaults").requireSecureDefaults},get"no-bidi-characters"(){return require("./rules/no-bidi-characters").noBidiCharacters}};(0,eslint_devkit_1.withCanonicalDocsUrls)("plugin-secure-coding",exports.rules);exports.plugin={meta:{name:"eslint-plugin-secure-coding",version:"5.3.
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.configs=exports.plugin=exports.rules=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.rules={get"no-graphql-injection"(){return require("./rules/no-graphql-injection").noGraphqlInjection},get"no-xxe-injection"(){return require("./rules/no-xxe-injection").noXxeInjection},get"no-xpath-injection"(){return require("./rules/no-xpath-injection").noXpathInjection},get"no-ldap-injection"(){return require("./rules/no-ldap-injection").noLdapInjection},get"no-directive-injection"(){return require("./rules/no-directive-injection").noDirectiveInjection},get"no-format-string-injection"(){return require("./rules/no-format-string-injection").noFormatStringInjection},get"no-template-injection"(){return require("./rules/no-template-injection").noTemplateInjection},get"no-sql-injection"(){return require("./rules/no-sql-injection").noSqlInjection},get"no-log-injection"(){return require("./rules/no-log-injection").noLogInjection},get"no-fail-open-auth"(){return require("./rules/no-fail-open-auth").noFailOpenAuth},get"no-homoglyph-identifiers"(){return require("./rules/no-homoglyph-identifiers").noHomoglyphIdentifiers},get"detect-non-literal-regexp"(){return require("./rules/detect-non-literal-regexp").detectNonLiteralRegexp},get"no-redos-vulnerable-regex"(){return require("./rules/no-redos-vulnerable-regex").noRedosVulnerableRegex},get"no-unsafe-regex-construction"(){return require("./rules/no-unsafe-regex-construction").noUnsafeRegexConstruction},get"detect-object-injection"(){return require("./rules/detect-object-injection").detectObjectInjection},get"no-unsafe-deserialization"(){return require("./rules/no-unsafe-deserialization").noUnsafeDeserialization},get"no-insecure-comparison"(){return require("./rules/no-insecure-comparison").noInsecureComparison},get"no-improper-sanitization"(){return require("./rules/no-improper-sanitization").noImproperSanitization},get"no-improper-type-validation"(){return require("./rules/no-improper-type-validation").noImproperTypeValidation},get"no-missing-authentication"(){return require("./rules/no-missing-authentication").noMissingAuthentication},get"no-privilege-escalation"(){return require("./rules/no-privilege-escalation").noPrivilegeEscalation},get"no-weak-password-recovery"(){return require("./rules/no-weak-password-recovery").noWeakPasswordRecovery},get"require-backend-authorization"(){return require("./rules/require-backend-authorization").requireBackendAuthorization},get"no-hardcoded-credentials"(){return require("./rules/no-hardcoded-credentials").noHardcodedCredentials},get"no-sensitive-data-exposure"(){return require("./rules/no-sensitive-data-exposure").noSensitiveDataExposure},get"no-pii-in-logs"(){return require("./rules/no-pii-in-logs").noPiiInLogs},get"no-unlimited-resource-allocation"(){return require("./rules/no-unlimited-resource-allocation").noUnlimitedResourceAllocation},get"no-unchecked-loop-condition"(){return require("./rules/no-unchecked-loop-condition").noUncheckedLoopCondition},get"detect-weak-password-validation"(){return require("./rules/detect-weak-password-validation").detectWeakPasswordValidation},get"no-electron-security-issues"(){return require("./rules/no-electron-security-issues").noElectronSecurityIssues},get"no-hardcoded-session-tokens"(){return require("./rules/no-hardcoded-session-tokens").noHardcodedSessionTokens},get"require-secure-defaults"(){return require("./rules/require-secure-defaults").requireSecureDefaults},get"no-bidi-characters"(){return require("./rules/no-bidi-characters").noBidiCharacters}};(0,eslint_devkit_1.withCanonicalDocsUrls)("plugin-secure-coding",exports.rules);exports.plugin={meta:{name:"eslint-plugin-secure-coding",version:"5.3.3"},rules:exports.rules};const recommendedRules={"secure-coding/no-graphql-injection":"warn","secure-coding/no-xxe-injection":"error","secure-coding/no-xpath-injection":"error","secure-coding/no-ldap-injection":"error","secure-coding/no-sql-injection":"error","secure-coding/no-log-injection":"error","secure-coding/no-fail-open-auth":"error","secure-coding/no-homoglyph-identifiers":"error","secure-coding/no-unsafe-deserialization":"warn","secure-coding/no-redos-vulnerable-regex":"error","secure-coding/no-unsafe-regex-construction":"error","secure-coding/no-hardcoded-credentials":"error","secure-coding/no-template-injection":"error","secure-coding/no-improper-sanitization":"error","secure-coding/no-privilege-escalation":"warn","secure-coding/no-weak-password-recovery":"warn","secure-coding/no-sensitive-data-exposure":"warn","secure-coding/no-unlimited-resource-allocation":"warn"};exports.configs={flagship:{plugins:{"secure-coding":exports.plugin},rules:{"secure-coding/no-hardcoded-credentials":"error","secure-coding/no-redos-vulnerable-regex":"error"}},recommended:{plugins:{"secure-coding":exports.plugin},rules:recommendedRules},"recommended-strict":{plugins:{"secure-coding":exports.plugin},rules:Object.fromEntries(Object.keys(recommendedRules).map(rule=>[rule,"error"]))},strict:{plugins:{"secure-coding":exports.plugin},rules:Object.fromEntries(Object.keys(exports.rules).map(ruleName=>[`secure-coding/${ruleName}`,"error"]))},"owasp-top-10":{plugins:{"secure-coding":exports.plugin},rules:{"secure-coding/no-privilege-escalation":"warn","secure-coding/no-hardcoded-credentials":"error","secure-coding/no-sensitive-data-exposure":"warn","secure-coding/no-graphql-injection":"error","secure-coding/no-xxe-injection":"error","secure-coding/no-xpath-injection":"error","secure-coding/no-ldap-injection":"error","secure-coding/no-weak-password-recovery":"error","secure-coding/no-unsafe-deserialization":"error"}}};exports.default=exports.plugin;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noGraphqlInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const resolve_reference_1=require("../../utils/resolve-reference");const eslint_devkit_3=require("@interlace/eslint-devkit");exports.noGraphqlInjection=(0,eslint_devkit_1.createRule)({name:"no-graphql-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-graphql-injection.md",description:"Detects GraphQL injection vulnerabilities and DoS attacks",cwe:"CWE-89"},messages:{graphqlInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"GraphQL Injection",cwe:"CWE-89",description:"GraphQL injection vulnerability detected",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://owasp.org/Top10/2025/A05_2025-Injection/"}),introspectionQuery:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous Introspection Query",cwe:"CWE-200",description:"Introspection query may leak schema information",severity:"HIGH",fix:"Disable introspection in production",documentationLink:"https://graphql.org/learn/introspection/"}),complexQueryDos:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Complex Query DoS Risk",cwe:"CWE-400",description:"Complex query may cause DoS",severity:"MEDIUM",fix:"Limit query depth and complexity",documentationLink:"https://graphql.org/learn/queries/"}),unsafeVariableInterpolation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Variable Interpolation",cwe:"CWE-89",description:"Unsafe interpolation in GraphQL query",severity:"HIGH",fix:"Use GraphQL variables instead of string interpolation",documentationLink:"https://graphql.org/learn/queries/#variables"}),missingInputValidation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Input Validation",cwe:"CWE-20",description:"GraphQL input not validated",severity:"MEDIUM",fix:"Validate all user inputs before GraphQL execution",documentationLink:"https://graphql.org/learn/validation/"})},schema:[{type:"object",properties:{allowIntrospection:{type:"boolean",default:false,description:"Allow introspection queries"},maxQueryDepth:{type:"number",minimum:1,default:10,description:"Maximum query nesting depth before reporting a DoS risk"},trustedGraphqlLibraries:{type:"array",items:{type:"string"},default:["graphql","apollo-server","graphql-tools","graphql-tag"],description:"GraphQL libraries recognised as query builders"},validationFunctions:{type:"array",items:{type:"string"},default:["validate","sanitize","isValid","assertValid"],description:"Function names that count as query validation"},safeTemplateLiteralCallers:{type:"array",items:{type:"string"},default:[],description:"Additional callers where template literals are never GraphQL. Format: object.method or ClassName."},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as GraphQL sanitizers"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},defaultOptions:[{allowIntrospection:false,maxQueryDepth:10,trustedGraphqlLibraries:["graphql","apollo-server","graphql-tools","graphql-tag"],validationFunctions:["validate","sanitize","isValid","assertValid"],safeTemplateLiteralCallers:[],trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{allowIntrospection=false,maxQueryDepth=10,trustedGraphqlLibraries=["graphql","apollo-server","graphql-tools","graphql-tag"],validationFunctions=["validate","sanitize","isValid","assertValid"],safeTemplateLiteralCallers=[],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const filename=context.filename;const sourceCode=context.sourceCode;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const isGraphqlRelated=node=>{const callee=node.callee;if(callee.type==="Identifier"){return trustedGraphqlLibraries.some(lib=>callee.name.toLowerCase().includes(lib.toLowerCase()))}if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"){const objectName=callee.object.name;return trustedGraphqlLibraries.some(lib=>objectName.toLowerCase().includes(lib.toLowerCase()))}return false};const BUILTIN_SAFE_MEMBER_CALLERS=new Set(["console.log","console.warn","console.error","console.info","console.debug","console.trace","logger.log","logger.info","logger.warn","logger.error","logger.debug"]);const BUILTIN_SAFE_CONSTRUCTORS=new Set(["URL","Error","TypeError","RangeError"]);const safeMemberCallers=new Set(BUILTIN_SAFE_MEMBER_CALLERS);const safeConstructors=new Set(BUILTIN_SAFE_CONSTRUCTORS);for(const caller of safeTemplateLiteralCallers){if(caller.includes(".")){safeMemberCallers.add(caller)}else{safeConstructors.add(caller)}}const isInSafeCallerContext=node=>{let current=node.parent;while(current){if(current.type==="CallExpression"){const callee=current.callee;const method=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&method!==null){const key=`${callee.object.name}.${method}`;if(safeMemberCallers.has(key))return true}break}if(current.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression){if(current.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&safeConstructors.has(current.callee.name)){return true}break}if(current.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration){break}current=current.parent}return false};const isWordChar=ch=>{const code=ch.charCodeAt(0);return code>=65&&code<=90||code>=97&&code<=122||code>=48&&code<=57||code===95};const isWhitespace=ch=>ch===" "||ch==="\n"||ch===" "||ch==="\r";const GRAPHQL_OP_KEYWORDS=["query","mutation","subscription"];const GRAPHQL_SCHEMA_KEYWORDS=["type","interface","enum","scalar","input"];const isAtLineStart=(text,idx)=>{for(let i=idx-1;i>=0;i--){const ch=text[i];if(ch==="\n")return true;if(!isWhitespace(ch))return false}return true};const isStandaloneSelectionSet=text=>{const trimmed=text.trim();if(!trimmed.startsWith("{")||!trimmed.endsWith("}"))return false;if(/\{\{|\}\}/.test(trimmed))return false;if(/"[^"]*"\s*:/.test(trimmed))return false;let braceDepth=0;for(const ch of trimmed){if(ch==="{"){braceDepth++;if(braceDepth>=2)return true}else if(ch==="}"){braceDepth=Math.max(0,braceDepth-1)}}return false};const findKeywordAtBoundary=(text,keyword,startFrom=0)=>{let pos=startFrom;while(true){const idx=text.indexOf(keyword,pos);if(idx===-1)return-1;const beforeOk=idx===0||!isWordChar(text[idx-1]);const afterIdx=idx+keyword.length;const afterOk=afterIdx>=text.length||!isWordChar(text[afterIdx]);if(beforeOk&&afterOk)return idx;pos=idx+1}};const GRAPHQL_TAG_NAMES=new Set(["gql","graphql"]);const GRAPHQL_SCHEMA_BINDING=/typedef|schema|sdl/i;const hasGraphqlAttribution=node=>{let current=node;while(current.parent?.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){current=current.parent}const parent=current.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.TaggedTemplateExpression){const tag=parent.tag;const tagName=tag.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?tag.name:tag.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&tag.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?tag.property.name:"";return GRAPHQL_TAG_NAMES.has(tagName.toLowerCase())}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return GRAPHQL_SCHEMA_BINDING.test(parent.id.name)}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.Property&&parent.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return GRAPHQL_SCHEMA_BINDING.test(parent.key.name)}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){return isGraphqlRelated(parent)}return false};const isGraphqlTemplate=node=>{const staticText=node.quasis.map(q=>(q.value.cooked??q.value.raw).toLowerCase()).join("");for(const keyword of GRAPHQL_OP_KEYWORDS){let pos=0;while(pos<staticText.length){const idx=findKeywordAtBoundary(staticText,keyword,pos);if(idx===-1)break;pos=idx+1;if(!isAtLineStart(staticText,idx))continue;let scan=idx+keyword.length;while(scan<staticText.length&&isWhitespace(staticText[scan]))scan++;while(scan<staticText.length&&isWordChar(staticText[scan]))scan++;while(scan<staticText.length&&isWhitespace(staticText[scan]))scan++;if(scan<staticText.length&&staticText[scan]==="("){return true}if(scan<staticText.length&&staticText[scan]==="{"){let probe=scan+1;while(probe<staticText.length&&isWhitespace(staticText[probe]))probe++;if(probe<staticText.length&&isWordChar(staticText[probe])){return true}continue}}}{let pos=0;while(pos<staticText.length){const idx=findKeywordAtBoundary(staticText,"fragment",pos);if(idx===-1)break;pos=idx+1;if(!isAtLineStart(staticText,idx))continue;let scan=idx+8;while(scan<staticText.length&&isWhitespace(staticText[scan]))scan++;const nameStart=scan;while(scan<staticText.length&&isWordChar(staticText[scan]))scan++;if(scan===nameStart)continue;while(scan<staticText.length&&isWhitespace(staticText[scan]))scan++;if(staticText.slice(scan,scan+2)==="on"&&(scan+2>=staticText.length||!isWordChar(staticText[scan+2]))){return true}}}if(hasGraphqlAttribution(node)&&staticText.includes("{"))for(const keyword of GRAPHQL_SCHEMA_KEYWORDS){let pos=0;while(pos<staticText.length){const idx=findKeywordAtBoundary(staticText,keyword,pos);if(idx===-1)break;pos=idx+1;if(!isAtLineStart(staticText,idx))continue;let scan=idx+keyword.length;if(scan>=staticText.length||!isWhitespace(staticText[scan]))continue;while(scan<staticText.length&&isWhitespace(staticText[scan]))scan++;if(scan<staticText.length&&isWordChar(staticText[scan])){return true}}}return isStandaloneSelectionSet(staticText)};const isGraphqlComposition=expr=>{if(expr.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const variable=(0,resolve_reference_1.resolvedReference)(sourceCode.getScope(expr),expr);if(variable===null||variable.defs.length!==1)return false;const def=variable.defs[0];if(def.type!=="Variable")return false;if(variable.references.filter(ref=>ref.isWrite()).length>1){return false}const init=def.node.init;if(init===null)return false;const literal=init.type===eslint_devkit_1.AST_NODE_TYPES.TSAsExpression?init.expression:init;return literal.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&isGraphqlTemplate(literal)};const hasIntrospectionField=text=>{const lower=text.toLowerCase();return findKeywordAtBoundary(lower,"__schema")!==-1||findKeywordAtBoundary(lower,"__type")!==-1};const templateHasIntrospection=node=>{return node.quasis.some(q=>hasIntrospectionField(q.value.cooked??q.value.raw))};const templateQueryDepth=node=>{let depth=0;let braceCount=0;for(const q of node.quasis){const text=q.value.cooked??q.value.raw;for(const char of text){if(char==="{"){braceCount++;depth=Math.max(depth,braceCount)}else if(char==="}"){braceCount--}}}return depth};const containsGraphqlText=(text,attributed)=>{const lower=text.toLowerCase();for(const keyword of GRAPHQL_OP_KEYWORDS){const idx=findKeywordAtBoundary(lower,keyword);if(idx===-1)continue;if(!isAtLineStart(lower,idx))continue;let scan=idx+keyword.length;while(scan<lower.length&&isWhitespace(lower[scan]))scan++;while(scan<lower.length&&isWordChar(lower[scan]))scan++;while(scan<lower.length&&isWhitespace(lower[scan]))scan++;if(scan<lower.length&&lower[scan]==="(")return true;if(scan<lower.length&&lower[scan]==="{"){if(attributed)return true;let probe=scan+1;while(probe<lower.length&&isWhitespace(lower[probe]))probe++;if(probe<lower.length&&isWordChar(lower[probe]))return true}}const fragIdx=findKeywordAtBoundary(lower,"fragment");if(fragIdx!==-1&&isAtLineStart(lower,fragIdx)){let scan=fragIdx+8;while(scan<lower.length&&isWhitespace(lower[scan]))scan++;const nameStart=scan;while(scan<lower.length&&isWordChar(lower[scan]))scan++;if(scan>nameStart){while(scan<lower.length&&isWhitespace(lower[scan]))scan++;if(lower.slice(scan,scan+2)==="on"&&(scan+2>=lower.length||!isWordChar(lower[scan+2])))return true}}if(attributed&&lower.includes("{"))for(const keyword of GRAPHQL_SCHEMA_KEYWORDS){const idx=findKeywordAtBoundary(lower,keyword);if(idx===-1)continue;if(!isAtLineStart(lower,idx))continue;let scan=idx+keyword.length;if(scan>=lower.length||!isWhitespace(lower[scan]))continue;while(scan<lower.length&&isWhitespace(lower[scan]))scan++;if(scan<lower.length&&isWordChar(lower[scan]))return true}return isStandaloneSelectionSet(text)};const concatenatedStaticText=node=>{if(node.type==="BinaryExpression"&&node.operator==="+"){return concatenatedStaticText(node.left)+concatenatedStaticText(node.right)}if(node.type==="TemplateLiteral"){return node.quasis.map(q=>q.value.cooked??q.value.raw).join("")}return(0,eslint_devkit_1.staticString)(node)??""};const isInputValidated=inputNode=>{let current=inputNode;while(current){if(current.type==="CallExpression"&¤t.callee.type==="Identifier"&&validationFunctions.includes(current.callee.name)){return true}current=current.parent}return false};return{TemplateLiteral(node){if(isInSafeCallerContext(node)){return}if(!isGraphqlTemplate(node)){return}if(!allowIntrospection&&templateHasIntrospection(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"introspectionQuery",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(node.expressions.length>0){const allExpressionsSafe=node.expressions.every(expr=>isGraphqlComposition(expr)||isInputValidated(expr)||safetyChecker.isSafe(expr,context));if(!allExpressionsSafe){context.report({node,messageId:"unsafeVariableInterpolation",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}const depth=templateQueryDepth(node);if(depth>maxQueryDepth){context.report({node,messageId:"complexQueryDos",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},Literal(node){const queryText=(0,eslint_devkit_1.staticString)(node);if(queryText===null)return;if(!containsGraphqlText(queryText,hasGraphqlAttribution(node))){return}if(!allowIntrospection&&hasIntrospectionField(queryText)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"introspectionQuery",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}let depth=0;let bc=0;for(const ch of queryText){if(ch==="{"){bc++;depth=Math.max(depth,bc)}else if(ch==="}"){bc--}}if(depth>maxQueryDepth){context.report({node,messageId:"complexQueryDos",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},BinaryExpression(node){if(node.operator!=="+"){return}const fullText=concatenatedStaticText(node);if(!containsGraphqlText(fullText,hasGraphqlAttribution(node))){return}if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"graphqlInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Use GraphQL variables or query builders instead of string concatenation"}})},CallExpression(node){if(!isGraphqlRelated(node)){return}const callee=node.callee;if(callee.type==="MemberExpression"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),["execute","executeQuery","query","mutate","subscribe"])){for(const arg of node.arguments){if(arg.type==="Identifier"&&!isInputValidated(arg)){if(safetyChecker.isSafe(arg,context)){continue}context.report({node:arg,messageId:"missingInputValidation",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noGraphqlInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const resolve_reference_1=require("../../utils/resolve-reference");const eslint_devkit_3=require("@interlace/eslint-devkit");exports.noGraphqlInjection=(0,eslint_devkit_1.createRule)({name:"no-graphql-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-graphql-injection.md",description:"Detects GraphQL injection vulnerabilities and DoS attacks",cwe:"CWE-89"},messages:{graphqlInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"GraphQL Injection",cwe:"CWE-89",description:"GraphQL injection vulnerability detected",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://owasp.org/Top10/2025/A05_2025-Injection/"}),introspectionQuery:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous Introspection Query",cwe:"CWE-200",description:"Introspection query may leak schema information",severity:"HIGH",fix:"Disable introspection in production",documentationLink:"https://graphql.org/learn/introspection/"}),complexQueryDos:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Complex Query DoS Risk",cwe:"CWE-400",description:"Complex query may cause DoS",severity:"MEDIUM",fix:"Limit query depth and complexity",documentationLink:"https://graphql.org/learn/queries/"}),unsafeVariableInterpolation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Variable Interpolation",cwe:"CWE-89",description:"Unsafe interpolation in GraphQL query",severity:"HIGH",fix:"Use GraphQL variables instead of string interpolation",documentationLink:"https://graphql.org/learn/queries/#variables"}),missingInputValidation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Input Validation",cwe:"CWE-20",description:"GraphQL input not validated",severity:"MEDIUM",fix:"Validate all user inputs before GraphQL execution",documentationLink:"https://graphql.org/learn/validation/"})},schema:[{type:"object",properties:{allowIntrospection:{type:"boolean",default:false,description:"Allow introspection queries"},maxQueryDepth:{type:"number",minimum:1,default:10,description:"Maximum query nesting depth before reporting a DoS risk"},trustedGraphqlLibraries:{type:"array",items:{type:"string"},default:["graphql","apollo-server","graphql-tools","graphql-tag"],description:"GraphQL libraries recognised as query builders"},validationFunctions:{type:"array",items:{type:"string"},default:["validate","sanitize","isValid","assertValid"],description:"Function names that count as query validation"},safeTemplateLiteralCallers:{type:"array",items:{type:"string"},default:[],description:"Additional callers where template literals are never GraphQL. Format: object.method or ClassName."},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as GraphQL sanitizers"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},defaultOptions:[{allowIntrospection:false,maxQueryDepth:10,trustedGraphqlLibraries:["graphql","apollo-server","graphql-tools","graphql-tag"],validationFunctions:["validate","sanitize","isValid","assertValid"],safeTemplateLiteralCallers:[],trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{allowIntrospection=false,maxQueryDepth=10,trustedGraphqlLibraries=["graphql","apollo-server","graphql-tools","graphql-tag"],validationFunctions=["validate","sanitize","isValid","assertValid"],safeTemplateLiteralCallers=[],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const filename=context.filename;const sourceCode=context.sourceCode;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const isGraphqlRelated=node=>{const callee=node.callee;if(callee.type==="Identifier"){return trustedGraphqlLibraries.some(lib=>callee.name.toLowerCase().includes(lib.toLowerCase()))}if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"){const objectName=callee.object.name;return trustedGraphqlLibraries.some(lib=>objectName.toLowerCase().includes(lib.toLowerCase()))}return false};const BUILTIN_SAFE_MEMBER_CALLERS=new Set(["console.log","console.warn","console.error","console.info","console.debug","console.trace","logger.log","logger.info","logger.warn","logger.error","logger.debug"]);const BUILTIN_SAFE_CONSTRUCTORS=new Set(["URL","Error","TypeError","RangeError"]);const safeMemberCallers=new Set(BUILTIN_SAFE_MEMBER_CALLERS);const safeConstructors=new Set(BUILTIN_SAFE_CONSTRUCTORS);for(const caller of safeTemplateLiteralCallers){if(caller.includes(".")){safeMemberCallers.add(caller)}else{safeConstructors.add(caller)}}const isInSafeCallerContext=node=>{let current=node.parent;while(current){if(current.type==="CallExpression"){const callee=current.callee;const method=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&method!==null){const key=`${callee.object.name}.${method}`;if(safeMemberCallers.has(key))return true}break}if(current.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression){if(current.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&safeConstructors.has(current.callee.name)){return true}break}if(current.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration){break}current=current.parent}return false};const isWordChar=ch=>{const code=ch.charCodeAt(0);return code>=65&&code<=90||code>=97&&code<=122||code>=48&&code<=57||code===95};const isWhitespace=ch=>ch===" "||ch==="\n"||ch===" "||ch==="\r";const GRAPHQL_OP_KEYWORDS=["query","mutation","subscription"];const GRAPHQL_SCHEMA_KEYWORDS=["type","interface","enum","scalar","input"];const isAtLineStart=(text,idx)=>{for(let i=idx-1;i>=0;i--){const ch=text[i];if(ch==="\n")return true;if(!isWhitespace(ch))return false}return true};const isStandaloneSelectionSet=text=>{const trimmed=text.trim();if(!trimmed.startsWith("{")||!trimmed.endsWith("}"))return false;if(/\{\{|\}\}/.test(trimmed))return false;if(/"[^"]*"\s*:/.test(trimmed))return false;let braceDepth=0;for(const ch of trimmed){if(ch==="{"){braceDepth++;if(braceDepth>=2)return true}else if(ch==="}"){braceDepth=Math.max(0,braceDepth-1)}}return false};const findKeywordAtBoundary=(text,keyword,startFrom=0)=>{let pos=startFrom;while(true){const idx=text.indexOf(keyword,pos);if(idx===-1)return-1;const beforeOk=idx===0||!isWordChar(text[idx-1]);const afterIdx=idx+keyword.length;const afterOk=afterIdx>=text.length||!isWordChar(text[afterIdx]);if(beforeOk&&afterOk)return idx;pos=idx+1}};const GRAPHQL_TAG_NAMES=new Set(["gql","graphql"]);const GRAPHQL_SCHEMA_BINDING=/typedef|schema|sdl/i;const hasGraphqlAttribution=node=>{let current=node;while(current.parent?.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){current=current.parent}const parent=current.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.TaggedTemplateExpression){const tag=parent.tag;const tagName=tag.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?tag.name:tag.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression?(0,eslint_devkit_1.propertyName)(tag)??"":"";return GRAPHQL_TAG_NAMES.has(tagName.toLowerCase())}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return GRAPHQL_SCHEMA_BINDING.test(parent.id.name)}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.Property&&parent.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return GRAPHQL_SCHEMA_BINDING.test(parent.key.name)}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){return isGraphqlRelated(parent)}return false};const isGraphqlTemplate=node=>{const staticText=node.quasis.map(q=>(q.value.cooked??q.value.raw).toLowerCase()).join("");for(const keyword of GRAPHQL_OP_KEYWORDS){let pos=0;while(pos<staticText.length){const idx=findKeywordAtBoundary(staticText,keyword,pos);if(idx===-1)break;pos=idx+1;if(!isAtLineStart(staticText,idx))continue;let scan=idx+keyword.length;while(scan<staticText.length&&isWhitespace(staticText[scan]))scan++;while(scan<staticText.length&&isWordChar(staticText[scan]))scan++;while(scan<staticText.length&&isWhitespace(staticText[scan]))scan++;if(scan<staticText.length&&staticText[scan]==="("){return true}if(scan<staticText.length&&staticText[scan]==="{"){let probe=scan+1;while(probe<staticText.length&&isWhitespace(staticText[probe]))probe++;if(probe<staticText.length&&isWordChar(staticText[probe])){return true}continue}}}{let pos=0;while(pos<staticText.length){const idx=findKeywordAtBoundary(staticText,"fragment",pos);if(idx===-1)break;pos=idx+1;if(!isAtLineStart(staticText,idx))continue;let scan=idx+8;while(scan<staticText.length&&isWhitespace(staticText[scan]))scan++;const nameStart=scan;while(scan<staticText.length&&isWordChar(staticText[scan]))scan++;if(scan===nameStart)continue;while(scan<staticText.length&&isWhitespace(staticText[scan]))scan++;if(staticText.slice(scan,scan+2)==="on"&&(scan+2>=staticText.length||!isWordChar(staticText[scan+2]))){return true}}}if(hasGraphqlAttribution(node)&&staticText.includes("{"))for(const keyword of GRAPHQL_SCHEMA_KEYWORDS){let pos=0;while(pos<staticText.length){const idx=findKeywordAtBoundary(staticText,keyword,pos);if(idx===-1)break;pos=idx+1;if(!isAtLineStart(staticText,idx))continue;let scan=idx+keyword.length;if(scan>=staticText.length||!isWhitespace(staticText[scan]))continue;while(scan<staticText.length&&isWhitespace(staticText[scan]))scan++;if(scan<staticText.length&&isWordChar(staticText[scan])){return true}}}return isStandaloneSelectionSet(staticText)};const isGraphqlComposition=expr=>{if(expr.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const variable=(0,resolve_reference_1.resolvedReference)(sourceCode.getScope(expr),expr);if(variable===null||variable.defs.length!==1)return false;const def=variable.defs[0];if(def.type!=="Variable")return false;if(variable.references.filter(ref=>ref.isWrite()).length>1){return false}const init=def.node.init;if(init===null)return false;const literal=init.type===eslint_devkit_1.AST_NODE_TYPES.TSAsExpression?init.expression:init;return literal.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&isGraphqlTemplate(literal)};const hasIntrospectionField=text=>{const lower=text.toLowerCase();return findKeywordAtBoundary(lower,"__schema")!==-1||findKeywordAtBoundary(lower,"__type")!==-1};const templateHasIntrospection=node=>{return node.quasis.some(q=>hasIntrospectionField(q.value.cooked??q.value.raw))};const templateQueryDepth=node=>{let depth=0;let braceCount=0;for(const q of node.quasis){const text=q.value.cooked??q.value.raw;for(const char of text){if(char==="{"){braceCount++;depth=Math.max(depth,braceCount)}else if(char==="}"){braceCount--}}}return depth};const containsGraphqlText=(text,attributed)=>{const lower=text.toLowerCase();for(const keyword of GRAPHQL_OP_KEYWORDS){const idx=findKeywordAtBoundary(lower,keyword);if(idx===-1)continue;if(!isAtLineStart(lower,idx))continue;let scan=idx+keyword.length;while(scan<lower.length&&isWhitespace(lower[scan]))scan++;while(scan<lower.length&&isWordChar(lower[scan]))scan++;while(scan<lower.length&&isWhitespace(lower[scan]))scan++;if(scan<lower.length&&lower[scan]==="(")return true;if(scan<lower.length&&lower[scan]==="{"){if(attributed)return true;let probe=scan+1;while(probe<lower.length&&isWhitespace(lower[probe]))probe++;if(probe<lower.length&&isWordChar(lower[probe]))return true}}const fragIdx=findKeywordAtBoundary(lower,"fragment");if(fragIdx!==-1&&isAtLineStart(lower,fragIdx)){let scan=fragIdx+8;while(scan<lower.length&&isWhitespace(lower[scan]))scan++;const nameStart=scan;while(scan<lower.length&&isWordChar(lower[scan]))scan++;if(scan>nameStart){while(scan<lower.length&&isWhitespace(lower[scan]))scan++;if(lower.slice(scan,scan+2)==="on"&&(scan+2>=lower.length||!isWordChar(lower[scan+2])))return true}}if(attributed&&lower.includes("{"))for(const keyword of GRAPHQL_SCHEMA_KEYWORDS){const idx=findKeywordAtBoundary(lower,keyword);if(idx===-1)continue;if(!isAtLineStart(lower,idx))continue;let scan=idx+keyword.length;if(scan>=lower.length||!isWhitespace(lower[scan]))continue;while(scan<lower.length&&isWhitespace(lower[scan]))scan++;if(scan<lower.length&&isWordChar(lower[scan]))return true}return isStandaloneSelectionSet(text)};const concatenatedStaticText=node=>{if(node.type==="BinaryExpression"&&node.operator==="+"){return concatenatedStaticText(node.left)+concatenatedStaticText(node.right)}if(node.type==="TemplateLiteral"){return node.quasis.map(q=>q.value.cooked??q.value.raw).join("")}return(0,eslint_devkit_1.staticString)(node)??""};const isInputValidated=inputNode=>{let current=inputNode;while(current){if(current.type==="CallExpression"&¤t.callee.type==="Identifier"&&validationFunctions.includes(current.callee.name)){return true}current=current.parent}return false};return{TemplateLiteral(node){if(isInSafeCallerContext(node)){return}if(!isGraphqlTemplate(node)){return}if(!allowIntrospection&&templateHasIntrospection(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"introspectionQuery",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(node.expressions.length>0){const allExpressionsSafe=node.expressions.every(expr=>isGraphqlComposition(expr)||isInputValidated(expr)||safetyChecker.isSafe(expr,context));if(!allExpressionsSafe){context.report({node,messageId:"unsafeVariableInterpolation",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}const depth=templateQueryDepth(node);if(depth>maxQueryDepth){context.report({node,messageId:"complexQueryDos",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},Literal(node){const queryText=(0,eslint_devkit_1.staticString)(node);if(queryText===null)return;if(!containsGraphqlText(queryText,hasGraphqlAttribution(node))){return}if(!allowIntrospection&&hasIntrospectionField(queryText)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"introspectionQuery",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}let depth=0;let bc=0;for(const ch of queryText){if(ch==="{"){bc++;depth=Math.max(depth,bc)}else if(ch==="}"){bc--}}if(depth>maxQueryDepth){context.report({node,messageId:"complexQueryDos",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},BinaryExpression(node){if(node.operator!=="+"){return}const fullText=concatenatedStaticText(node);if(!containsGraphqlText(fullText,hasGraphqlAttribution(node))){return}if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"graphqlInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Use GraphQL variables or query builders instead of string concatenation"}})},CallExpression(node){if(!isGraphqlRelated(node)){return}const callee=node.callee;if(callee.type==="MemberExpression"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),["execute","executeQuery","query","mutate","subscribe"])){for(const arg of node.arguments){if(arg.type==="Identifier"&&!isInputValidated(arg)){if(safetyChecker.isSafe(arg,context)){continue}context.report({node:arg,messageId:"missingInputValidation",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noHardcodedCredentials=void 0;exports.isNaturalWordString=isNaturalWordString;exports.looksRandom=looksRandom;exports.isSecretShaped=isSecretShaped;exports.isPlaceholderValue=isPlaceholderValue;exports.isPublishableKeyValue=isPublishableKeyValue;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const CREDENTIAL_PATTERNS={apiKey:/^(?:[A-Za-z0-9_-]{32,}|sk_[A-Za-z0-9_-]{32,}|pk_[A-Za-z0-9_-]{32,}|AKIA[0-9A-Z]{16})$/,jwtToken:/^eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,oauthToken:/^(?:ghp_|gho_|ghu_|ghs_|ghr_)[A-Za-z0-9]{36,}$/,awsAccessKey:/^AKIA[0-9A-Z]{16}$/,databaseString:/^(?:mysql|postgres|mongodb|redis):\/\/[^:]+:[^@]+@/,commonPassword:/^(?:password|admin|123456|qwerty|letmein|welcome|monkey|1234567890|12345678|password123|root|test|guest)$/i,secretKey:/^(?:[A-Za-z0-9+/]{32,}={0,2}|[A-Fa-f0-9]{32,})$/};const CREDENTIAL_VARIABLE_NAMES=new Set(["apikey","api_key","apiKey","secret","secretkey","secret_key","secretKey","clientsecret","client_secret","clientSecret","token","authtoken","auth_token","authToken","accesstoken","access_token","accessToken","refreshtoken","refresh_token","refreshToken","idtoken","id_token","idToken","password","passwd","pass","pwd","privatekey","private_key","privateKey","credentials","creds","authorization","auth","connectionstring","connection_string","connectionString","connectionuri","connectionURI","dburl","db_url","dbUrl","databaseurl","database_url","databaseUrl"]);const WORD_SEPARATORS=new Set(["_","-","."," "]);function shannonEntropy(value){const freq=new Map;for(const ch of value)freq.set(ch,(freq.get(ch)??0)+1);let entropy=0;for(const count of freq.values()){const p=count/value.length;entropy-=p*Math.log2(p)}return entropy}function charClasses(value){const classes={lower:false,upper:false,digit:false,symbol:false};for(const ch of value){if(WORD_SEPARATORS.has(ch))continue;if(ch>="a"&&ch<="z")classes.lower=true;else if(ch>="A"&&ch<="Z")classes.upper=true;else if(ch>="0"&&ch<="9")classes.digit=true;else classes.symbol=true}return classes}function classCount(classes){return Number(classes.lower)+Number(classes.upper)+Number(classes.digit)+Number(classes.symbol)}function isPronounceable(token){const lower=token.toLowerCase();if(!/[aeiouy]/.test(lower))return false;if(/[bcdfghjklmnpqrstvwxz]{4,}/.test(lower))return false;return true}function isNaturalWordString(value){if(!/^[A-Za-z][A-Za-z0-9_\-. ]*$/.test(value))return false;const digits=value.replace(/[^0-9]/g,"").length;if(digits>0&&(digits/value.length>.2||/[0-9]{4,}/.test(value)))return false;const tokens=value.replace(/([a-z])([A-Z])/g,"$1 $2").split(/[^A-Za-z]+/).filter(Boolean);const meaningful=tokens.filter(t=>t.length>=3);if(meaningful.length===0)return false;if(meaningful.every(isPronounceable))return true;if(/[0-9]/.test(value))return false;const waived=meaningful.filter(token=>!isPronounceable(token));if(waived.some(token=>token.length>4))return false;return waived.length*2<=meaningful.length}function hasSequentialRun(value,min=5){let run=1;for(let i=1;i<value.length;i++){run=value.charCodeAt(i)===value.charCodeAt(i-1)+1?run+1:1;if(run>=min)return true}return false}function looksRandom(value){if(value.length<20)return false;if(!/^[A-Za-z0-9]+$/.test(value))return false;const classes=charClasses(value);if(!classes.lower||!classes.upper||!classes.digit)return false;if(hasSequentialRun(value))return false;if(isNaturalWordString(value))return false;return shannonEntropy(value)>=3.5}const CONTEXT_FREE_RANDOM_LENGTH=32;function isUrlOrPath(value){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(value)){return!/^[^/]*\/\/[^/@]*:[^/@]*@/.test(value)}const rooted=value.replace(/^(?:<[A-Za-z_$][\w$]*>|\[[A-Za-z_$][\w$]*\])(?=\/)/,"");if(rooted!==value)return isUrlOrPath(rooted);if(!value.startsWith("/")||value.startsWith("//"))return false;const path=value.split(/[?#]/)[0];const segments=path.slice(1).split("/");if(!segments.every(segment=>/^[A-Za-z0-9._~%:@-]*$/.test(segment))){return false}const looksGenerated=segment=>/[a-z]/.test(segment)&&/[A-Z]/.test(segment)&&/[0-9]/.test(segment);if(segments.length===1){return!looksGenerated(segments[0])}return!segments.some(segment=>segment.length>=16&&looksGenerated(segment))}function echoesItsOwnSlotName(value,slotName){if(slotName==="")return false;const fold=text=>text.replace(/[-_.\s]/g,"").toLowerCase();return fold(value)===fold(slotName)}function isSecretShaped(value,minLength){if(value.length<minLength)return false;if(/\s/.test(value))return false;if(isUrlOrPath(value))return false;if(isNaturalWordString(value))return false;if(classCount(charClasses(value))>=2)return true;return value.length>=20&&shannonEntropy(value)>=3}const DEFAULT_PLACEHOLDER_WORDS=["changeme","change","replaceme","replace","yours","your","placeholder","example","sample","dummy","todo","tbd","redacted","notreal","xxx"];function isPlaceholderValue(value,words){const trimmed=value.trim();if(trimmed.length===0)return false;if(/^(?:<.*>|\{\{.*\}\}|\$\{.*\}|\[.*\])$/.test(trimmed))return true;const dunder=/^__(.+)__$/.exec(trimmed);if(dunder!==null){const inner=dunder[1];const candidate=inner.trim();return/^[^A-Za-z]*[A-Z]{3,}/.test(candidate)&&!looksRandom(candidate)}if(trimmed.length>=4&&new Set(trimmed).size===1)return true;const tokens=trimmed.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return tokens.some(token=>words.has(token))}function isPublishableKeyValue(value){if(/^pk_(?:live|test)_[A-Za-z0-9_-]{8,}$/.test(value))return true;if(/^phc_[A-Za-z0-9]{20,}$/.test(value))return true;if(/^https?:\/\/[A-Za-z0-9]+@[A-Za-z0-9.-]+(?::\d+)?\/\d+$/.test(value)){return true}if(/^0x[A-Fa-f0-9]{40}$/.test(value))return true;return false}const SECRET_SIDE_VALUE=/^(?:sk|rk)_(?:live|test)_|^sk-[A-Za-z0-9]|^gh[pousr]_|^ph[xs]_|^sntry[su]_|^xox[baprs]-|^AKIA[0-9A-Z]{16}$|^ey[A-Za-z0-9_-]+\.ey|-----BEGIN|^(?:mysql|postgres|mongodb|redis):\/\//;const SECRET_SIDE_SLOT=/secret|private|signing|password|passwd|serviceaccount|serverkey|adminkey|masterkey/;const PUBLISHABLE_VENDORS=[{vendor:"Bugsnag",packages:["bugsnag","bugsnag-js","bugsnag-build-reporter","bugsnag-sourcemaps"],scopes:["@bugsnag"],named:/bugsnag/,slots:/^(?:bugsnag)?(?:notifier)?(?:api)?key$/},{vendor:"Sentry",scopes:["@sentry"],named:/sentry/,slots:/^(?:sentry)?dsn$/},{vendor:"PostHog",packages:["posthog-js","posthog-node"],named:/posthog/,slots:/^(?:posthog)?(?:project)?(?:api)?key$/},{vendor:"Segment",packages:["analytics-node"],scopes:["@segment"],named:/segment/,slots:/^(?:segment)?write(?:key|token)$/},{vendor:"Amplitude",packages:["amplitude-js"],scopes:["@amplitude"],named:/amplitude/,slots:/^(?:amplitude)?(?:api)?key$/},{vendor:"Mixpanel",packages:["mixpanel","mixpanel-browser"],named:/mixpanel/,slots:/^(?:mixpanel)?(?:project)?token$/},{vendor:"Firebase",packages:["firebase"],scopes:["@firebase"],named:/firebase/,slots:/^(?:firebase)?(?:web)?apikey$/}];const VENDOR_PROBES=PUBLISHABLE_VENDORS.map(entry=>({entry,loadsSdk:(0,eslint_devkit_2.createModuleEvidence)({packages:entry.packages,scopes:entry.scopes})}));function slotNameOf(parent){if(parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){return parent.id.name.toLowerCase()}if(parent.type==="Property"){const key=parent.key;if(key.type==="Identifier")return key.name.toLowerCase();return String(key.value).toLowerCase()}if(parent.type==="AssignmentExpression"){const left=parent.left;if(left.type==="MemberExpression"&&left.property.type==="Identifier"){return left.property.name.toLowerCase()}}return""}function looksLikeCredential(value,options,ignorePatterns){const NONE={isCredential:false,type:"",confidence:"ambiguous"};if(ignorePatterns.some(pattern=>pattern.test(value)))return NONE;for(const customPattern of options.customPatterns){try{const regex=new RegExp(customPattern.pattern);if(regex.test(value)){return{isCredential:true,type:customPattern.type,confidence:"structural"}}}catch{continue}}if(options.detectPasswords&&CREDENTIAL_PATTERNS.commonPassword.test(value)){return{isCredential:true,type:"Common password",confidence:"ambiguous"}}if(options.detectDatabaseStrings&&CREDENTIAL_PATTERNS.databaseString.test(value)){return{isCredential:true,type:"Database connection string",confidence:"structural"}}if(value.length<options.minLength)return NONE;if(options.detectTokens&&CREDENTIAL_PATTERNS.jwtToken.test(value)){return{isCredential:true,type:"JWT token",confidence:"structural"}}if(options.detectTokens&&CREDENTIAL_PATTERNS.oauthToken.test(value)){return{isCredential:true,type:"OAuth token",confidence:"structural"}}if(options.detectApiKeys&&CREDENTIAL_PATTERNS.awsAccessKey.test(value)){return{isCredential:true,type:"AWS access key",confidence:"structural"}}if(options.detectApiKeys&&/^(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9_-]{16,}$/.test(value)){return{isCredential:true,type:"API key",confidence:"structural"}}if(options.detectApiKeys&&looksRandom(value)){return{isCredential:true,type:"Secret key",confidence:value.length>=CONTEXT_FREE_RANDOM_LENGTH?"structural":"ambiguous"}}if(value.length>=32&&CREDENTIAL_PATTERNS.secretKey.test(value)&&!isNaturalWordString(value)){return{isCredential:true,type:"Secret key",confidence:"ambiguous"}}if(options.detectApiKeys&&/^[A-Za-z0-9_-]{32,}$/.test(value)&&!isNaturalWordString(value)){return{isCredential:true,type:"API key",confidence:"ambiguous"}}return NONE}exports.noHardcodedCredentials=(0,eslint_devkit_2.createRule)({name:"no-hardcoded-credentials",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-hardcoded-credentials.md",description:"Detects hardcoded passwords, API keys, tokens, and other sensitive credentials",cwe:"CWE-798",cvss:9.8,confidence:"medium"},fixable:"code",hasSuggestions:true,messages:{useEnvironmentVariable:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Hard-coded Credential",cwe:"CWE-798",description:"Hard-coded {{credentialType}} detected",severity:"CRITICAL",fix:"Use environment variable: process.env.{{envVarName}} or secret management service",documentationLink:"https://cwe.mitre.org/data/definitions/798.html"}),useSecretManager:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Use Secret Manager",cwe:"CWE-798",description:"Use secure secret management service",severity:"HIGH",fix:"Use AWS Secrets Manager, HashiCorp Vault, Azure Key Vault, or similar",documentationLink:"https://cwe.mitre.org/data/definitions/798.html"})},schema:[{type:"object",properties:{credentialWords:{type:"array",items:{type:"string"},default:[...CREDENTIAL_VARIABLE_NAMES],description:"Variable and property names this project uses for a credential. REPLACES the default list."},ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Regex patterns to ignore"},allowInTests:{type:"boolean",default:true,description:"Allow credentials in test files"},minLength:{type:"number",default:8,description:"Minimum length for credential detection"},detectApiKeys:{type:"boolean",default:true,description:"Detect API keys"},detectPasswords:{type:"boolean",default:true,description:"Detect passwords"},detectTokens:{type:"boolean",default:true,description:"Detect tokens"},detectDatabaseStrings:{type:"boolean",default:true,description:"Detect database connection strings"},customPatterns:{type:"array",items:{type:"object",properties:{type:{type:"string",description:'The type of credential (e.g., "API key", "token")'},pattern:{type:"string",description:"Regex pattern to match"}},required:["type","pattern"],additionalProperties:false},default:[],description:"Custom credential patterns to detect"},allowPlaceholders:{type:"boolean",default:true,description:"Skip self-evident placeholder values (`<your-secret-here>`, `changeme`, `xxxxxxxx`)"},placeholderWords:{type:"array",items:{type:"string"},default:DEFAULT_PLACEHOLDER_WORDS,description:"Words that mark a value as a self-evident stand-in rather than a secret, matched as a WHOLE token inside the value and never as a substring. Replaces the built-in list. Read only when `allowPlaceholders` is true."},additionalPlaceholderWords:{type:"array",items:{type:"string"},default:[],description:"Extra placeholder words, on top of `placeholderWords`."}},additionalProperties:false}]},defaultOptions:[{ignorePatterns:[],allowInTests:true,minLength:8,detectApiKeys:true,detectPasswords:true,detectTokens:true,detectDatabaseStrings:true,customPatterns:[],allowPlaceholders:true,placeholderWords:DEFAULT_PLACEHOLDER_WORDS,additionalPlaceholderWords:[]}],create(context){const options=context.options[0]||{};const credentialWords=new Set((options.credentialWords??[...CREDENTIAL_VARIABLE_NAMES]).map(w=>w.toLowerCase()));const{ignorePatterns=[],allowInTests=true,minLength=8,detectApiKeys=true,detectPasswords=true,detectTokens=true,detectDatabaseStrings=true,customPatterns=[],allowPlaceholders=true,placeholderWords=DEFAULT_PLACEHOLDER_WORDS,additionalPlaceholderWords=[]}=options;const placeholderWordSet=new Set([...placeholderWords,...additionalPlaceholderWords]);const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_2.isTestFilePath)(filename);const compiledIgnorePatterns=(0,eslint_devkit_1.compileUserPatterns)(ignorePatterns);const detectionOptions={minLength,detectApiKeys,detectPasswords,detectTokens,detectDatabaseStrings,customPatterns};const LABEL_CONTEXT_NAMES=new Set(["type","name","id","placeholder","label","title","role","autocomplete","autoFocus","autocapitalize","inputmode","aria-label","aria-labelledby","aria-describedby","fieldName","fieldType","fieldLabel","inputType","inputName","displayName","columnName","paramName","i18nKey","translationKey","messageKey"]);function isLabelContext(node,parent){if(!parent)return false;if(parent.type==="ObjectExpression"){const grand=parent.parent;if(grand)return isLabelContext(node,grand);return false}if(parent.type==="ArrayExpression"){const grand=parent.parent;if(grand)return isLabelContext(node,grand);return false}if(parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){const n=parent.id.name.toLowerCase();if(LABEL_CONTEXT_NAMES.has(n)||n==="labels"||n.endsWith("label")||n.endsWith("labels")||n.endsWith("name")||n.endsWith("placeholder"))return true}if(parent.type==="AssignmentExpression"&&parent.right===node){const left=parent.left;if(left.type==="MemberExpression"&&left.property.type==="Identifier"){if(LABEL_CONTEXT_NAMES.has(left.property.name))return true}}if(parent.type==="Property"&&parent.value===node){const key=parent.key;const keyText=key.type==="Identifier"?key.name:(0,eslint_devkit_1.staticString)(key)!==null?(0,eslint_devkit_1.staticString)(key):null;if(keyText!==null&&node.type==="Literal"&&typeof node.value==="string"){const keyTokens=keyText.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase().split(/[^A-Z0-9]+/).filter(Boolean);if(keyTokens.includes(node.value.toUpperCase()))return true}if(key.type==="Identifier"&&LABEL_CONTEXT_NAMES.has(key.name))return true;if(key.type==="Literal"&&typeof key.value==="string"){if(LABEL_CONTEXT_NAMES.has(key.value))return true}const obj=parent.parent;if(obj?.type==="ObjectExpression"){const grand=obj.parent;if(grand)return isLabelContext(node,grand)}}if(parent.type==="CallExpression"&&parent.callee.type==="MemberExpression"&&parent.callee.property.type==="Identifier"){const callee=parent.callee;const methodName=callee.property.name;if(methodName==="setAttribute"||methodName==="getAttribute"){const args=parent.arguments;if(args[1]===node)return true}}if(parent.type==="JSXAttribute")return true;return false}function inferCredentialTypeFromContext(parent){const name=slotNameOf(parent);if(/(?:^|[_-])(password|passwd|pass|pwd)$/.test(name))return"password";if(/(?:^|[_-])(token|authtoken|auth_token|accesstoken|access_token|refreshtoken|refresh_token|idtoken|id_token)$/.test(name))return"token";if(/(?:^|[_-])(dburl|db_url|databaseurl|database_url|connectionstring|connection_string|connectionuri)$/.test(name))return"database";if(/(?:^|[_-])(apikey|api_key|secretkey|secret_key|privatekey|private_key|secret|key|clientsecret|client_secret)$/.test(name))return"apikey";return"other"}function isCredentialContext(node,parent){if(!parent)return false;const matches=name=>{const lower=name.toLowerCase();if(lower==="key"||lower==="keys"){return node.type==="Literal"&&typeof node.value==="string"&&looksRandom(node.value)}const singular=lower.endsWith("s")?lower.slice(0,-1):lower;if(credentialWords.has(lower)||credentialWords.has(singular))return true;return[...credentialWords].some(word=>lower.endsWith(word)||lower.endsWith(`${word}s`))};if(parent.type==="ArrayExpression"){const grand=parent.parent;if(grand)return isCredentialContext(node,grand);return false}if(parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){if(matches(parent.id.name))return true}if(parent.type==="AssignmentExpression"&&parent.right===node){const left=parent.left;if(left.type==="MemberExpression"&&left.property.type==="Identifier"){if(matches(left.property.name))return true}if(left.type==="Identifier"){if(matches(left.name))return true}}if(parent.type==="Property"&&parent.value===node){const key=parent.key;if(key.type==="Identifier"&&matches(key.name))return true;if(key.type==="Literal"&&typeof key.value==="string"){if(matches(key.value))return true}}return false}let loadedVendors=null;function vendorsInFile(){if(loadedVendors===null){const found=new Set;for(const{entry,loadsSdk}of VENDOR_PROBES){if(loadsSdk(context.sourceCode.ast))found.add(entry.vendor)}loadedVendors=found}return loadedVendors}function isPublishableKey(value,parent){if(SECRET_SIDE_VALUE.test(value))return false;if(isPublishableKeyValue(value))return true;const slot=slotNameOf(parent);if(slot===""||SECRET_SIDE_SLOT.test(slot))return false;for(const{entry}of VENDOR_PROBES){if(!entry.named.test(slot)&&!vendorsInFile().has(entry.vendor)){continue}if(entry.slots.test(slot))return true}return false}function checkStringLiteral(node,parent){if(typeof node.value!=="string"){return}const value=node.value;if(isTestFile){return}if(parent?.type==="LogicalExpression"&&parent.operator==="||"&&parent.right===node){const left=parent.left;if(left.type==="MemberExpression"&&left.object.type==="MemberExpression"&&left.object.object.type==="Identifier"&&left.object.object.name==="process"&&(0,eslint_devkit_1.propertyName)(left.object)==="env"){return}}if(isLabelContext(node,parent)){return}const{isCredential,type,confidence}=looksLikeCredential(value,detectionOptions,compiledIgnorePatterns);let finalIsCredential=isCredential;let finalType=type;if(isCredential&&confidence==="ambiguous"&&!isCredentialContext(node,parent)){finalIsCredential=false}const echoesSlot=confidence!=="structural"&&parent!==void 0&&echoesItsOwnSlotName(value,slotNameOf(parent));if(echoesSlot){finalIsCredential=false}const isPlaceholder=allowPlaceholders&&isPlaceholderValue(value,placeholderWordSet);if(isPlaceholder&&confidence!=="structural"){finalIsCredential=false}if(!finalIsCredential&&!isPlaceholder&&!echoesSlot&&!compiledIgnorePatterns.some(pattern=>pattern.test(value))&&isSecretShaped(value,detectionOptions.minLength)&&isCredentialContext(node,parent)){const ctxType=inferCredentialTypeFromContext(parent);const optionAllows=ctxType==="password"&&detectionOptions.detectPasswords||ctxType==="token"&&detectionOptions.detectTokens||ctxType==="database"&&detectionOptions.detectDatabaseStrings||ctxType==="apikey"&&detectionOptions.detectApiKeys||ctxType==="other";if(optionAllows){finalIsCredential=true;finalType=type||"Credential value"}}if(!finalIsCredential){return}if(isPublishableKey(value,parent)){return}let envVarName="API_KEY";if(parent&&parent.type==="Property"&&parent.key.type==="Identifier"){const keyName=parent.key.name;envVarName=keyName.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase().replace(/[^A-Z0-9_]/g,"_")}else if(parent&&parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){const varName=parent.id.name;envVarName=varName.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase().replace(/[^A-Z0-9_]/g,"_")}context.report({node,messageId:"useEnvironmentVariable",data:{credentialType:finalType,envVarName},suggest:[{messageId:"useEnvironmentVariable",data:{envVarName,credentialType:finalType},fix:fixer=>{return fixer.replaceText(node,`process.env.${envVarName} || '${value}'`)}},{messageId:"useSecretManager",data:{credentialType:finalType},fix:fixer=>{return fixer.replaceText(node,`await getSecret('${envVarName.toLowerCase()}')`)}}]})}return{Literal(node){checkStringLiteral(node,node.parent)},TemplateLiteral(node){if(node.expressions.length===0){const fullText=node.quasis.map(q=>q.value.raw).join("");const{isCredential,type,confidence}=looksLikeCredential(fullText,detectionOptions,compiledIgnorePatterns);if(isCredential&&!isTestFile&&confidence==="structural"){context.report({node,messageId:"useEnvironmentVariable",data:{credentialType:type,envVarName:"API_KEY"},suggest:[{messageId:"useEnvironmentVariable",data:{envVarName:"API_KEY",credentialType:type},fix:fixer=>{return fixer.replaceText(node,`process.env.API_KEY || \`${fullText}\``)}},{messageId:"useSecretManager",data:{credentialType:type},fix:fixer=>{return fixer.replaceText(node,`await getSecret('api_key')`)}}]})}}else{for(const quasi of node.quasis){if(quasi.value.raw){const{isCredential,type,confidence}=looksLikeCredential(quasi.value.raw,detectionOptions,compiledIgnorePatterns);if(isCredential&&!isTestFile&&confidence==="structural"){context.report({node:quasi,messageId:"useEnvironmentVariable",data:{credentialType:type,envVarName:"API_KEY"}})}}}}}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noHardcodedCredentials=void 0;exports.isNaturalWordString=isNaturalWordString;exports.looksRandom=looksRandom;exports.isSecretShaped=isSecretShaped;exports.isPlaceholderValue=isPlaceholderValue;exports.isPublishableKeyValue=isPublishableKeyValue;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const CREDENTIAL_PATTERNS={apiKey:/^(?:[A-Za-z0-9_-]{32,}|sk_[A-Za-z0-9_-]{32,}|pk_[A-Za-z0-9_-]{32,}|AKIA[0-9A-Z]{16})$/,jwtToken:/^eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,oauthToken:/^(?:ghp_|gho_|ghu_|ghs_|ghr_)[A-Za-z0-9]{36,}$/,awsAccessKey:/^AKIA[0-9A-Z]{16}$/,databaseString:/^(?:mysql|postgres|mongodb|redis):\/\/[^:]+:[^@]+@/,commonPassword:/^(?:password|admin|123456|qwerty|letmein|welcome|monkey|1234567890|12345678|password123|root|test|guest)$/i,secretKey:/^(?:[A-Za-z0-9+/]{32,}={0,2}|[A-Fa-f0-9]{32,})$/};const CREDENTIAL_VARIABLE_NAMES=new Set(["apikey","api_key","apiKey","secret","secretkey","secret_key","secretKey","clientsecret","client_secret","clientSecret","token","authtoken","auth_token","authToken","accesstoken","access_token","accessToken","refreshtoken","refresh_token","refreshToken","idtoken","id_token","idToken","password","passwd","pass","pwd","privatekey","private_key","privateKey","credentials","creds","authorization","auth","connectionstring","connection_string","connectionString","connectionuri","connectionURI","dburl","db_url","dbUrl","databaseurl","database_url","databaseUrl"]);const WORD_SEPARATORS=new Set(["_","-","."," "]);function shannonEntropy(value){const freq=new Map;for(const ch of value)freq.set(ch,(freq.get(ch)??0)+1);let entropy=0;for(const count of freq.values()){const p=count/value.length;entropy-=p*Math.log2(p)}return entropy}function charClasses(value){const classes={lower:false,upper:false,digit:false,symbol:false};for(const ch of value){if(WORD_SEPARATORS.has(ch))continue;if(ch>="a"&&ch<="z")classes.lower=true;else if(ch>="A"&&ch<="Z")classes.upper=true;else if(ch>="0"&&ch<="9")classes.digit=true;else classes.symbol=true}return classes}function classCount(classes){return Number(classes.lower)+Number(classes.upper)+Number(classes.digit)+Number(classes.symbol)}function isPronounceable(token){const lower=token.toLowerCase();if(!/[aeiouy]/.test(lower))return false;if(/[bcdfghjklmnpqrstvwxz]{4,}/.test(lower))return false;return true}function isNaturalWordString(value){if(!/^[A-Za-z][A-Za-z0-9_\-. ]*$/.test(value))return false;const digits=value.replace(/[^0-9]/g,"").length;if(digits>0&&(digits/value.length>.2||/[0-9]{4,}/.test(value)))return false;const tokens=value.replace(/([a-z])([A-Z])/g,"$1 $2").split(/[^A-Za-z]+/).filter(Boolean);const meaningful=tokens.filter(t=>t.length>=3);if(meaningful.length===0)return false;if(meaningful.every(isPronounceable))return true;if(/[0-9]/.test(value))return false;const waived=meaningful.filter(token=>!isPronounceable(token));if(waived.some(token=>token.length>4))return false;return waived.length*2<=meaningful.length}function hasSequentialRun(value,min=5){let run=1;for(let i=1;i<value.length;i++){run=value.charCodeAt(i)===value.charCodeAt(i-1)+1?run+1:1;if(run>=min)return true}return false}function looksRandom(value){if(value.length<20)return false;if(!/^[A-Za-z0-9]+$/.test(value))return false;const classes=charClasses(value);if(!classes.lower||!classes.upper||!classes.digit)return false;if(hasSequentialRun(value))return false;if(isNaturalWordString(value))return false;return shannonEntropy(value)>=3.5}const CONTEXT_FREE_RANDOM_LENGTH=32;function isUrlOrPath(value){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(value)){return!/^[^/]*\/\/[^/@]*:[^/@]*@/.test(value)}const rooted=value.replace(/^(?:<[A-Za-z_$][\w$]*>|\[[A-Za-z_$][\w$]*\])(?=\/)/,"");if(rooted!==value)return isUrlOrPath(rooted);if(!value.startsWith("/")||value.startsWith("//"))return false;const path=value.split(/[?#]/)[0];const segments=path.slice(1).split("/");if(!segments.every(segment=>/^[A-Za-z0-9._~%:@-]*$/.test(segment))){return false}const looksGenerated=segment=>/[a-z]/.test(segment)&&/[A-Z]/.test(segment)&&/[0-9]/.test(segment);if(segments.length===1){return!looksGenerated(segments[0])}return!segments.some(segment=>segment.length>=16&&looksGenerated(segment))}function echoesItsOwnSlotName(value,slotName){if(slotName==="")return false;const fold=text=>text.replace(/[-_.\s]/g,"").toLowerCase();return fold(value)===fold(slotName)}function isSecretShaped(value,minLength){if(value.length<minLength)return false;if(/\s/.test(value))return false;if(isUrlOrPath(value))return false;if(isNaturalWordString(value))return false;if(classCount(charClasses(value))>=2)return true;return value.length>=20&&shannonEntropy(value)>=3}const DEFAULT_PLACEHOLDER_WORDS=["changeme","change","replaceme","replace","yours","your","placeholder","example","sample","dummy","todo","tbd","redacted","notreal","xxx"];function isPlaceholderValue(value,words){const trimmed=value.trim();if(trimmed.length===0)return false;if(/^(?:<.*>|\{\{.*\}\}|\$\{.*\}|\[.*\])$/.test(trimmed))return true;const dunder=/^__(.+)__$/.exec(trimmed);if(dunder!==null){const inner=dunder[1];const candidate=inner.trim();return/^[^A-Za-z]*[A-Z]{3,}/.test(candidate)&&!looksRandom(candidate)}if(trimmed.length>=4&&new Set(trimmed).size===1)return true;const tokens=trimmed.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return tokens.some(token=>words.has(token))}function isPublishableKeyValue(value){if(/^pk_(?:live|test)_[A-Za-z0-9_-]{8,}$/.test(value))return true;if(/^phc_[A-Za-z0-9]{20,}$/.test(value))return true;if(/^https?:\/\/[A-Za-z0-9]+@[A-Za-z0-9.-]+(?::\d+)?\/\d+$/.test(value)){return true}if(/^0x[A-Fa-f0-9]{40}$/.test(value))return true;return false}const SECRET_SIDE_VALUE=/^(?:sk|rk)_(?:live|test)_|^sk-[A-Za-z0-9]|^gh[pousr]_|^ph[xs]_|^sntry[su]_|^xox[baprs]-|^AKIA[0-9A-Z]{16}$|^ey[A-Za-z0-9_-]+\.ey|-----BEGIN|^(?:mysql|postgres|mongodb|redis):\/\//;const SECRET_SIDE_SLOT=/secret|private|signing|password|passwd|serviceaccount|serverkey|adminkey|masterkey/;const PUBLISHABLE_VENDORS=[{vendor:"Bugsnag",packages:["bugsnag","bugsnag-js","bugsnag-build-reporter","bugsnag-sourcemaps"],scopes:["@bugsnag"],named:/bugsnag/,slots:/^(?:bugsnag)?(?:notifier)?(?:api)?key$/},{vendor:"Sentry",scopes:["@sentry"],named:/sentry/,slots:/^(?:sentry)?dsn$/},{vendor:"PostHog",packages:["posthog-js","posthog-node"],named:/posthog/,slots:/^(?:posthog)?(?:project)?(?:api)?key$/},{vendor:"Segment",packages:["analytics-node"],scopes:["@segment"],named:/segment/,slots:/^(?:segment)?write(?:key|token)$/},{vendor:"Amplitude",packages:["amplitude-js"],scopes:["@amplitude"],named:/amplitude/,slots:/^(?:amplitude)?(?:api)?key$/},{vendor:"Mixpanel",packages:["mixpanel","mixpanel-browser"],named:/mixpanel/,slots:/^(?:mixpanel)?(?:project)?token$/},{vendor:"Firebase",packages:["firebase"],scopes:["@firebase"],named:/firebase/,slots:/^(?:firebase)?(?:web)?apikey$/}];const VENDOR_PROBES=PUBLISHABLE_VENDORS.map(entry=>({entry,loadsSdk:(0,eslint_devkit_2.createModuleEvidence)({packages:entry.packages,scopes:entry.scopes})}));function slotNameOf(parent){if(parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){return parent.id.name.toLowerCase()}if(parent.type==="Property"){const key=parent.key;if(key.type==="Identifier")return key.name.toLowerCase();return String(key.value).toLowerCase()}if(parent.type==="AssignmentExpression"){const left=parent.left;if(left.type==="MemberExpression"){const named=(0,eslint_devkit_1.propertyName)(left);if(named!==null)return named.toLowerCase()}}return""}function looksLikeCredential(value,options,ignorePatterns){const NONE={isCredential:false,type:"",confidence:"ambiguous"};if(ignorePatterns.some(pattern=>pattern.test(value)))return NONE;for(const customPattern of options.customPatterns){try{const regex=new RegExp(customPattern.pattern);if(regex.test(value)){return{isCredential:true,type:customPattern.type,confidence:"structural"}}}catch{continue}}if(options.detectPasswords&&CREDENTIAL_PATTERNS.commonPassword.test(value)){return{isCredential:true,type:"Common password",confidence:"ambiguous"}}if(options.detectDatabaseStrings&&CREDENTIAL_PATTERNS.databaseString.test(value)){return{isCredential:true,type:"Database connection string",confidence:"structural"}}if(value.length<options.minLength)return NONE;if(options.detectTokens&&CREDENTIAL_PATTERNS.jwtToken.test(value)){return{isCredential:true,type:"JWT token",confidence:"structural"}}if(options.detectTokens&&CREDENTIAL_PATTERNS.oauthToken.test(value)){return{isCredential:true,type:"OAuth token",confidence:"structural"}}if(options.detectApiKeys&&CREDENTIAL_PATTERNS.awsAccessKey.test(value)){return{isCredential:true,type:"AWS access key",confidence:"structural"}}if(options.detectApiKeys&&/^(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9_-]{16,}$/.test(value)){return{isCredential:true,type:"API key",confidence:"structural"}}if(options.detectApiKeys&&looksRandom(value)){return{isCredential:true,type:"Secret key",confidence:value.length>=CONTEXT_FREE_RANDOM_LENGTH?"structural":"ambiguous"}}if(value.length>=32&&CREDENTIAL_PATTERNS.secretKey.test(value)&&!isNaturalWordString(value)){return{isCredential:true,type:"Secret key",confidence:"ambiguous"}}if(options.detectApiKeys&&/^[A-Za-z0-9_-]{32,}$/.test(value)&&!isNaturalWordString(value)){return{isCredential:true,type:"API key",confidence:"ambiguous"}}return NONE}exports.noHardcodedCredentials=(0,eslint_devkit_2.createRule)({name:"no-hardcoded-credentials",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-hardcoded-credentials.md",description:"Detects hardcoded passwords, API keys, tokens, and other sensitive credentials",cwe:"CWE-798",cvss:9.8,confidence:"medium"},fixable:"code",hasSuggestions:true,messages:{useEnvironmentVariable:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Hard-coded Credential",cwe:"CWE-798",description:"Hard-coded {{credentialType}} detected",severity:"CRITICAL",fix:"Use environment variable: process.env.{{envVarName}} or secret management service",documentationLink:"https://cwe.mitre.org/data/definitions/798.html"}),useSecretManager:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Use Secret Manager",cwe:"CWE-798",description:"Use secure secret management service",severity:"HIGH",fix:"Use AWS Secrets Manager, HashiCorp Vault, Azure Key Vault, or similar",documentationLink:"https://cwe.mitre.org/data/definitions/798.html"})},schema:[{type:"object",properties:{credentialWords:{type:"array",items:{type:"string"},default:[...CREDENTIAL_VARIABLE_NAMES],description:"Variable and property names this project uses for a credential. REPLACES the default list."},ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Regex patterns to ignore"},allowInTests:{type:"boolean",default:true,description:"Allow credentials in test files"},minLength:{type:"number",default:8,description:"Minimum length for credential detection"},detectApiKeys:{type:"boolean",default:true,description:"Detect API keys"},detectPasswords:{type:"boolean",default:true,description:"Detect passwords"},detectTokens:{type:"boolean",default:true,description:"Detect tokens"},detectDatabaseStrings:{type:"boolean",default:true,description:"Detect database connection strings"},customPatterns:{type:"array",items:{type:"object",properties:{type:{type:"string",description:'The type of credential (e.g., "API key", "token")'},pattern:{type:"string",description:"Regex pattern to match"}},required:["type","pattern"],additionalProperties:false},default:[],description:"Custom credential patterns to detect"},allowPlaceholders:{type:"boolean",default:true,description:"Skip self-evident placeholder values (`<your-secret-here>`, `changeme`, `xxxxxxxx`)"},placeholderWords:{type:"array",items:{type:"string"},default:DEFAULT_PLACEHOLDER_WORDS,description:"Words that mark a value as a self-evident stand-in rather than a secret, matched as a WHOLE token inside the value and never as a substring. Replaces the built-in list. Read only when `allowPlaceholders` is true."},additionalPlaceholderWords:{type:"array",items:{type:"string"},default:[],description:"Extra placeholder words, on top of `placeholderWords`."}},additionalProperties:false}]},defaultOptions:[{ignorePatterns:[],allowInTests:true,minLength:8,detectApiKeys:true,detectPasswords:true,detectTokens:true,detectDatabaseStrings:true,customPatterns:[],allowPlaceholders:true,placeholderWords:DEFAULT_PLACEHOLDER_WORDS,additionalPlaceholderWords:[]}],create(context){const options=context.options[0]||{};const credentialWords=new Set((options.credentialWords??[...CREDENTIAL_VARIABLE_NAMES]).map(w=>w.toLowerCase()));const{ignorePatterns=[],allowInTests=true,minLength=8,detectApiKeys=true,detectPasswords=true,detectTokens=true,detectDatabaseStrings=true,customPatterns=[],allowPlaceholders=true,placeholderWords=DEFAULT_PLACEHOLDER_WORDS,additionalPlaceholderWords=[]}=options;const placeholderWordSet=new Set([...placeholderWords,...additionalPlaceholderWords]);const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_2.isTestFilePath)(filename);const compiledIgnorePatterns=(0,eslint_devkit_1.compileUserPatterns)(ignorePatterns);const detectionOptions={minLength,detectApiKeys,detectPasswords,detectTokens,detectDatabaseStrings,customPatterns};const LABEL_CONTEXT_NAMES=new Set(["type","name","id","placeholder","label","title","role","autocomplete","autoFocus","autocapitalize","inputmode","aria-label","aria-labelledby","aria-describedby","fieldName","fieldType","fieldLabel","inputType","inputName","displayName","columnName","paramName","i18nKey","translationKey","messageKey"]);function isLabelContext(node,parent){if(!parent)return false;if(parent.type==="ObjectExpression"){const grand=parent.parent;if(grand)return isLabelContext(node,grand);return false}if(parent.type==="ArrayExpression"){const grand=parent.parent;if(grand)return isLabelContext(node,grand);return false}if(parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){const n=parent.id.name.toLowerCase();if(LABEL_CONTEXT_NAMES.has(n)||n==="labels"||n.endsWith("label")||n.endsWith("labels")||n.endsWith("name")||n.endsWith("placeholder"))return true}if(parent.type==="AssignmentExpression"&&parent.right===node){const left=parent.left;if(left.type==="MemberExpression"){const slot=(0,eslint_devkit_1.propertyName)(left);if(slot!==null&&LABEL_CONTEXT_NAMES.has(slot))return true}}if(parent.type==="Property"&&parent.value===node){const key=parent.key;const keyText=key.type==="Identifier"?key.name:(0,eslint_devkit_1.staticString)(key)!==null?(0,eslint_devkit_1.staticString)(key):null;if(keyText!==null&&node.type==="Literal"&&typeof node.value==="string"){const keyTokens=keyText.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase().split(/[^A-Z0-9]+/).filter(Boolean);if(keyTokens.includes(node.value.toUpperCase()))return true}if(key.type==="Identifier"&&LABEL_CONTEXT_NAMES.has(key.name))return true;if(key.type==="Literal"&&typeof key.value==="string"){if(LABEL_CONTEXT_NAMES.has(key.value))return true}const obj=parent.parent;if(obj?.type==="ObjectExpression"){const grand=obj.parent;if(grand)return isLabelContext(node,grand)}}if(parent.type==="CallExpression"&&parent.callee.type==="MemberExpression"&&parent.callee.property.type==="Identifier"){const callee=parent.callee;const methodName=callee.property.name;if(methodName==="setAttribute"||methodName==="getAttribute"){const args=parent.arguments;if(args[1]===node)return true}}if(parent.type==="JSXAttribute")return true;return false}function inferCredentialTypeFromContext(parent){const name=slotNameOf(parent);if(/(?:^|[_-])(password|passwd|pass|pwd)$/.test(name))return"password";if(/(?:^|[_-])(token|authtoken|auth_token|accesstoken|access_token|refreshtoken|refresh_token|idtoken|id_token)$/.test(name))return"token";if(/(?:^|[_-])(dburl|db_url|databaseurl|database_url|connectionstring|connection_string|connectionuri)$/.test(name))return"database";if(/(?:^|[_-])(apikey|api_key|secretkey|secret_key|privatekey|private_key|secret|key|clientsecret|client_secret)$/.test(name))return"apikey";return"other"}function isCredentialContext(node,parent){if(!parent)return false;const matches=name=>{const lower=name.toLowerCase();if(lower==="key"||lower==="keys"){return node.type==="Literal"&&typeof node.value==="string"&&looksRandom(node.value)}const singular=lower.endsWith("s")?lower.slice(0,-1):lower;if(credentialWords.has(lower)||credentialWords.has(singular))return true;return[...credentialWords].some(word=>lower.endsWith(word)||lower.endsWith(`${word}s`))};if(parent.type==="ArrayExpression"){const grand=parent.parent;if(grand)return isCredentialContext(node,grand);return false}if(parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){if(matches(parent.id.name))return true}if(parent.type==="AssignmentExpression"&&parent.right===node){const left=parent.left;if(left.type==="MemberExpression"){const slot=(0,eslint_devkit_1.propertyName)(left);if(slot!==null&&matches(slot))return true}if(left.type==="Identifier"){if(matches(left.name))return true}}if(parent.type==="Property"&&parent.value===node){const key=parent.key;if(key.type==="Identifier"&&matches(key.name))return true;if(key.type==="Literal"&&typeof key.value==="string"){if(matches(key.value))return true}}return false}let loadedVendors=null;function vendorsInFile(){if(loadedVendors===null){const found=new Set;for(const{entry,loadsSdk}of VENDOR_PROBES){if(loadsSdk(context.sourceCode.ast))found.add(entry.vendor)}loadedVendors=found}return loadedVendors}function isPublishableKey(value,parent){if(SECRET_SIDE_VALUE.test(value))return false;if(isPublishableKeyValue(value))return true;const slot=slotNameOf(parent);if(slot===""||SECRET_SIDE_SLOT.test(slot))return false;for(const{entry}of VENDOR_PROBES){if(!entry.named.test(slot)&&!vendorsInFile().has(entry.vendor)){continue}if(entry.slots.test(slot))return true}return false}function checkStringLiteral(node,parent){if(typeof node.value!=="string"){return}const value=node.value;if(isTestFile){return}if(parent?.type==="LogicalExpression"&&parent.operator==="||"&&parent.right===node){const left=parent.left;if(left.type==="MemberExpression"&&left.object.type==="MemberExpression"&&left.object.object.type==="Identifier"&&left.object.object.name==="process"&&(0,eslint_devkit_1.propertyName)(left.object)==="env"){return}}if(isLabelContext(node,parent)){return}const{isCredential,type,confidence}=looksLikeCredential(value,detectionOptions,compiledIgnorePatterns);let finalIsCredential=isCredential;let finalType=type;if(isCredential&&confidence==="ambiguous"&&!isCredentialContext(node,parent)){finalIsCredential=false}const echoesSlot=confidence!=="structural"&&parent!==void 0&&echoesItsOwnSlotName(value,slotNameOf(parent));if(echoesSlot){finalIsCredential=false}const isPlaceholder=allowPlaceholders&&isPlaceholderValue(value,placeholderWordSet);if(isPlaceholder&&confidence!=="structural"){finalIsCredential=false}if(!finalIsCredential&&!isPlaceholder&&!echoesSlot&&!compiledIgnorePatterns.some(pattern=>pattern.test(value))&&isSecretShaped(value,detectionOptions.minLength)&&isCredentialContext(node,parent)){const ctxType=inferCredentialTypeFromContext(parent);const optionAllows=ctxType==="password"&&detectionOptions.detectPasswords||ctxType==="token"&&detectionOptions.detectTokens||ctxType==="database"&&detectionOptions.detectDatabaseStrings||ctxType==="apikey"&&detectionOptions.detectApiKeys||ctxType==="other";if(optionAllows){finalIsCredential=true;finalType=type||"Credential value"}}if(!finalIsCredential){return}if(isPublishableKey(value,parent)){return}let envVarName="API_KEY";if(parent&&parent.type==="Property"&&parent.key.type==="Identifier"){const keyName=parent.key.name;envVarName=keyName.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase().replace(/[^A-Z0-9_]/g,"_")}else if(parent&&parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){const varName=parent.id.name;envVarName=varName.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase().replace(/[^A-Z0-9_]/g,"_")}context.report({node,messageId:"useEnvironmentVariable",data:{credentialType:finalType,envVarName},suggest:[{messageId:"useEnvironmentVariable",data:{envVarName,credentialType:finalType},fix:fixer=>{return fixer.replaceText(node,`process.env.${envVarName} || '${value}'`)}},{messageId:"useSecretManager",data:{credentialType:finalType},fix:fixer=>{return fixer.replaceText(node,`await getSecret('${envVarName.toLowerCase()}')`)}}]})}return{Literal(node){checkStringLiteral(node,node.parent)},TemplateLiteral(node){if(node.expressions.length===0){const fullText=node.quasis.map(q=>q.value.raw).join("");const{isCredential,type,confidence}=looksLikeCredential(fullText,detectionOptions,compiledIgnorePatterns);if(isCredential&&!isTestFile&&confidence==="structural"){context.report({node,messageId:"useEnvironmentVariable",data:{credentialType:type,envVarName:"API_KEY"},suggest:[{messageId:"useEnvironmentVariable",data:{envVarName:"API_KEY",credentialType:type},fix:fixer=>{return fixer.replaceText(node,`process.env.API_KEY || \`${fullText}\``)}},{messageId:"useSecretManager",data:{credentialType:type},fix:fixer=>{return fixer.replaceText(node,`await getSecret('api_key')`)}}]})}}else{for(const quasi of node.quasis){if(quasi.value.raw){const{isCredential,type,confidence}=looksLikeCredential(quasi.value.raw,detectionOptions,compiledIgnorePatterns);if(isCredential&&!isTestFile&&confidence==="structural"){context.report({node:quasi,messageId:"useEnvironmentVariable",data:{credentialType:type,envVarName:"API_KEY"}})}}}}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noImproperSanitization=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");exports.noImproperSanitization=(0,eslint_devkit_1.createRule)({name:"no-improper-sanitization",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-improper-sanitization.md",description:"Detects improper sanitization of user input",cwe:"CWE-116"},messages:{insufficientXssProtection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Insufficient XSS Protection",cwe:"CWE-79",description:"XSS protection is incomplete or missing",severity:"HIGH",fix:"Use comprehensive XSS prevention or trusted sanitization library",documentationLink:"https://owasp.org/www-community/attacks/xss/"}),incompleteHtmlEscaping:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Incomplete HTML Escaping",cwe:"CWE-116",description:"HTML escaping misses dangerous characters",severity:"MEDIUM",fix:`Escape all HTML special characters: & < > " '`,documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html"}),unsafeReplaceSanitization:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unescaped Markup In Output",cwe:"CWE-116",description:"A string reaching this sink carries unescaped markup",severity:"MEDIUM",fix:"Escape the value before it reaches the sink, or send it as text rather than markup",documentationLink:"https://cwe.mitre.org/data/definitions/116.html"})},schema:[{type:"object",properties:{safeSanitizers:{type:"array",items:{type:"string"},default:["DOMPurify.sanitize","he.encode","encodeURIComponent","encodeURI","escape"],description:"Sanitizer calls treated as sufficient"},dangerousChars:{type:"array",items:{type:"string"},default:["<",">",'"',"'","&"],description:"Characters a sanitizer is expected to handle"},contexts:{type:"array",items:{type:"string"},default:["html","url","sql","command","javascript","css"],description:"Output contexts checked for a context-appropriate sanitizer"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as sanitizers"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},defaultOptions:[{safeSanitizers:["DOMPurify.sanitize","he.encode","encodeURIComponent","encodeURI","escape"],dangerousChars:["<",">",'"',"'","&"],contexts:["html","url","sql","command","javascript","css"],trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{safeSanitizers=["DOMPurify.sanitize","he.encode","encodeURIComponent","encodeURI","escape"],dangerousChars=["<",">",'"',"'","&"],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const sourceCode=context.sourceCode;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const isSafeSanitizer=callText=>{return safeSanitizers.some(sanitizer=>callText.includes(sanitizer))};const isReplaceCall=node=>node?.type==="CallExpression"&&node.callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(node.callee)==="replace";const isMidChain=node=>{const parent=node.parent;const grandparent=parent?.parent;return isReplaceCall(grandparent)&&grandparent.callee===parent};const staticPattern=node=>{if(node?.type!=="Literal")return void 0;const withRegex=node;if(withRegex.regex)return withRegex.regex.pattern;return typeof node.value==="string"?node.value:void 0};const staticReplacement=node=>{if(node?.type==="Literal"){return typeof node.value==="string"?node.value:void 0}if(node?.type==="TemplateLiteral"&&node.expressions.length===0){return node.quasis.map(quasi=>quasi.value.cooked).join("")}return void 0};const replaceChain=terminal=>{const pairs=[];let current=terminal;while(isReplaceCall(current)){pairs.push({pattern:staticPattern(current.arguments[0]),replacement:staticReplacement(current.arguments[1])});current=current.callee.object}return pairs};const ENTITY=/&(?:amp|lt|gt|quot|apos|#x[0-9a-f]+|#\d+);/i;const isIncompleteReplaceSanitization=callExpression=>{const pairs=replaceChain(callExpression);const escapesTagChar=pairs.some(pair=>(pair.pattern==="<"||pair.pattern===">")&&pair.replacement!==void 0&&ENTITY.test(pair.replacement));if(!escapesTagChar)return false;const replacements=pairs.map(pair=>pair.replacement??"").join("");const hasQuoteEscaping=/"|'|�?39;|'/i.test(replacements);const hasAmpersandEscaping=/&/.test(replacements);return!(hasQuoteEscaping&&hasAmpersandEscaping)};const needsContextEncoding=outputNode=>{let current=outputNode;while(current){const text=sourceCode.getText(current).toLowerCase();if(text.includes("innerhtml")||text.includes("outerhtml")){return"html"}if(text.includes("href")||text.includes("src")||text.includes("url")){return"url"}if(text.includes("sql")||text.includes("query")||text.includes("execute")){return"sql"}if(text.includes("exec")||text.includes("spawn")||text.includes("command")){return"command"}current=current.parent}return null};return{CallExpression(node){const callee=node.callee;if(callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(callee)==="replace"){if(isMidChain(node)){return}if(isIncompleteReplaceSanitization(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"incompleteHtmlEscaping",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}},AssignmentExpression(node){const left=node.left;const right=node.right;if(left.type==="MemberExpression"&&left.property.type==="Identifier"){const propertyName=left.property.name.toLowerCase();if(["innerhtml","outerhtml","innertext","textcontent"].includes(propertyName)){const encodingContext=needsContextEncoding(node);if(encodingContext==="html"&&propertyName==="innerhtml"){const rightText=sourceCode.getText(right);if(!isSafeSanitizer(rightText)){const hasUserInput=rightText.includes("req.")||rightText.includes("body")||rightText.includes("query")||rightText.includes("input");if(hasUserInput){if(safetyChecker.isSafe(node,context)){return}context.report({node:right,messageId:"insufficientXssProtection",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}}},Literal(node){if(typeof node.value!=="string"){return}const directParent=node.parent;if(directParent?.type==="AssignmentExpression"&&directParent.right===node&&directParent.left.type==="MemberExpression"){const left=directParent.left;if(left.property.type==="Identifier"&&["innerHTML","outerHTML"].includes(left.property.name)){const literalValue=node.value;const hasDangerousMarkup=/<script[\s>]|<\/script>|\son\w+\s*=|javascript:/i.test(literalValue);if(!hasDangerousMarkup){return}}}const text=node.value;let current=node;let isInDangerousContext=false;while(current){if(current.type==="AssignmentExpression"){const left=current.left;if(left.type==="MemberExpression"&&left.property.type==="Identifier"&&["innerHTML","outerHTML"].includes(left.property.name)){isInDangerousContext=true;break}}else if(current.type==="CallExpression"){const callee=current.callee;if(callee.type==="MemberExpression"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),["write","send","json"])){isInDangerousContext=true;break}}current=current.parent}if(isInDangerousContext){const enclosingArgument=literal=>{let current2=literal;let parent=current2.parent;for(;;){if(parent?.type==="BinaryExpression"&&parent.operator==="+"){current2=parent}else if(parent?.type==="ArrayExpression"){current2=parent}else if(parent?.type==="Property"||parent?.type==="ObjectExpression"&¤t2.type==="Property"){current2=parent}else if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.TSSatisfiesExpression||parent?.type===eslint_devkit_1.AST_NODE_TYPES.TSAsExpression||parent?.type===eslint_devkit_1.AST_NODE_TYPES.TSNonNullExpression||parent?.type===eslint_devkit_1.AST_NODE_TYPES.TSTypeAssertion){current2=parent}else if(parent?.type==="MemberExpression"&&parent.object===current2&&(0,eslint_devkit_1.propertyName)(parent)==="join"){current2=parent}else if(parent?.type==="CallExpression"&&parent.callee===current2){current2=parent}else{break}parent=current2.parent}if(parent?.type==="CallExpression"&&parent.arguments.includes(current2)){return current2}return void 0};const sanitizerNames=new Set([...safeSanitizers,...trustedSanitizers,"escapeHtml","escapeHTML","htmlEscape"]);const calleeName=callee=>{if(callee.type==="Identifier")return callee.name;if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.property.type==="Identifier"){return`${callee.object.name}.${callee.property.name}`}return void 0};const isSafeText=expr=>{if(expr.type==="Literal"){if(expr.value===null||typeof expr.value==="number"||typeof expr.value==="boolean"||typeof expr.value==="bigint"){return true}return typeof expr.value==="string"}if(expr.type==="TemplateLiteral")return expr.expressions.length===0;if(expr.type==="BinaryExpression"&&expr.operator==="+"){return isSafeText(expr.left)&&isSafeText(expr.right)}if(expr.type==="ObjectExpression"){return expr.properties.every(property=>property.type==="Property"&&isSafeText(property.value))}if(expr.type===eslint_devkit_1.AST_NODE_TYPES.TSSatisfiesExpression||expr.type===eslint_devkit_1.AST_NODE_TYPES.TSAsExpression||expr.type===eslint_devkit_1.AST_NODE_TYPES.TSNonNullExpression||expr.type===eslint_devkit_1.AST_NODE_TYPES.TSTypeAssertion){return isSafeText(expr.expression)}if(expr.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){return expr.elements.every(element=>element===null||isSafeText(element))}if(expr.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(expr)==="length"){return true}if(expr.type==="CallExpression"){const callee=expr.callee;if(callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(callee)==="join"&&callee.object.type==="ArrayExpression"){return callee.object.elements.every(element=>element!==null&&isSafeText(element))}const name=calleeName(callee);return name!==void 0&&sanitizerNames.has(name)}return false};const argument=enclosingArgument(node);const isBareLiteral=argument!==void 0&&isSafeText(argument);const hasDangerousMarkup=/<script[\s>]|<\/script>|\son\w+\s*=|javascript:/i.test(text);if(isBareLiteral&&!hasDangerousMarkup){return}const hasDangerousChars=dangerousChars.some(char=>text.includes(char));const hasEscaping=text.includes("<")||text.includes(">")||text.includes(""")||text.includes("'")||text.includes("&");if(hasDangerousChars&&!hasEscaping){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"unsafeReplaceSanitization",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noImproperSanitization=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");exports.noImproperSanitization=(0,eslint_devkit_1.createRule)({name:"no-improper-sanitization",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-improper-sanitization.md",description:"Detects improper sanitization of user input",cwe:"CWE-116"},messages:{insufficientXssProtection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Insufficient XSS Protection",cwe:"CWE-79",description:"XSS protection is incomplete or missing",severity:"HIGH",fix:"Use comprehensive XSS prevention or trusted sanitization library",documentationLink:"https://owasp.org/www-community/attacks/xss/"}),incompleteHtmlEscaping:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Incomplete HTML Escaping",cwe:"CWE-116",description:"HTML escaping misses dangerous characters",severity:"MEDIUM",fix:`Escape all HTML special characters: & < > " '`,documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html"}),unsafeReplaceSanitization:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unescaped Markup In Output",cwe:"CWE-116",description:"A string reaching this sink carries unescaped markup",severity:"MEDIUM",fix:"Escape the value before it reaches the sink, or send it as text rather than markup",documentationLink:"https://cwe.mitre.org/data/definitions/116.html"})},schema:[{type:"object",properties:{safeSanitizers:{type:"array",items:{type:"string"},default:["DOMPurify.sanitize","he.encode","encodeURIComponent","encodeURI","escape"],description:"Sanitizer calls treated as sufficient"},dangerousChars:{type:"array",items:{type:"string"},default:["<",">",'"',"'","&"],description:"Characters a sanitizer is expected to handle"},contexts:{type:"array",items:{type:"string"},default:["html","url","sql","command","javascript","css"],description:"Output contexts checked for a context-appropriate sanitizer"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as sanitizers"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},defaultOptions:[{safeSanitizers:["DOMPurify.sanitize","he.encode","encodeURIComponent","encodeURI","escape"],dangerousChars:["<",">",'"',"'","&"],contexts:["html","url","sql","command","javascript","css"],trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{safeSanitizers=["DOMPurify.sanitize","he.encode","encodeURIComponent","encodeURI","escape"],dangerousChars=["<",">",'"',"'","&"],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const sourceCode=context.sourceCode;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const isSafeSanitizer=callText=>{return safeSanitizers.some(sanitizer=>callText.includes(sanitizer))};const isReplaceCall=node=>node?.type==="CallExpression"&&node.callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(node.callee)==="replace";const isMidChain=node=>{const parent=node.parent;const grandparent=parent?.parent;return isReplaceCall(grandparent)&&grandparent.callee===parent};const staticPattern=node=>{if(node?.type!=="Literal")return void 0;const withRegex=node;if(withRegex.regex)return withRegex.regex.pattern;return typeof node.value==="string"?node.value:void 0};const staticReplacement=node=>{if(node?.type==="Literal"){return typeof node.value==="string"?node.value:void 0}if(node?.type==="TemplateLiteral"&&node.expressions.length===0){return node.quasis.map(quasi=>quasi.value.cooked).join("")}return void 0};const replaceChain=terminal=>{const pairs=[];let current=terminal;while(isReplaceCall(current)){pairs.push({pattern:staticPattern(current.arguments[0]),replacement:staticReplacement(current.arguments[1])});current=current.callee.object}return pairs};const ENTITY=/&(?:amp|lt|gt|quot|apos|#x[0-9a-f]+|#\d+);/i;const isIncompleteReplaceSanitization=callExpression=>{const pairs=replaceChain(callExpression);const escapesTagChar=pairs.some(pair=>(pair.pattern==="<"||pair.pattern===">")&&pair.replacement!==void 0&&ENTITY.test(pair.replacement));if(!escapesTagChar)return false;const replacements=pairs.map(pair=>pair.replacement??"").join("");const hasQuoteEscaping=/"|'|�?39;|'/i.test(replacements);const hasAmpersandEscaping=/&/.test(replacements);return!(hasQuoteEscaping&&hasAmpersandEscaping)};const needsContextEncoding=outputNode=>{let current=outputNode;while(current){const text=sourceCode.getText(current).toLowerCase();if(text.includes("innerhtml")||text.includes("outerhtml")){return"html"}if(text.includes("href")||text.includes("src")||text.includes("url")){return"url"}if(text.includes("sql")||text.includes("query")||text.includes("execute")){return"sql"}if(text.includes("exec")||text.includes("spawn")||text.includes("command")){return"command"}current=current.parent}return null};return{CallExpression(node){const callee=node.callee;if(callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(callee)==="replace"){if(isMidChain(node)){return}if(isIncompleteReplaceSanitization(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"incompleteHtmlEscaping",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}},AssignmentExpression(node){const left=node.left;const right=node.right;if(left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const sink=((0,eslint_devkit_1.propertyName)(left)??"").toLowerCase();if(["innerhtml","outerhtml","innertext","textcontent"].includes(sink)){const encodingContext=needsContextEncoding(node);if(encodingContext==="html"&&sink==="innerhtml"){const rightText=sourceCode.getText(right);if(!isSafeSanitizer(rightText)){const hasUserInput=rightText.includes("req.")||rightText.includes("body")||rightText.includes("query")||rightText.includes("input");if(hasUserInput){if(safetyChecker.isSafe(node,context)){return}context.report({node:right,messageId:"insufficientXssProtection",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}}},Literal(node){if(typeof node.value!=="string"){return}const directParent=node.parent;if(directParent?.type==="AssignmentExpression"&&directParent.right===node&&directParent.left.type==="MemberExpression"){const left=directParent.left;if(["innerHTML","outerHTML"].includes((0,eslint_devkit_1.propertyName)(left)??"")){const literalValue=node.value;const hasDangerousMarkup=/<script[\s>]|<\/script>|\son\w+\s*=|javascript:/i.test(literalValue);if(!hasDangerousMarkup){return}}}const text=node.value;let current=node;let isInDangerousContext=false;while(current){if(current.type==="AssignmentExpression"){const left=current.left;if(left.type==="MemberExpression"&&["innerHTML","outerHTML"].includes((0,eslint_devkit_1.propertyName)(left)??"")){isInDangerousContext=true;break}}else if(current.type==="CallExpression"){const callee=current.callee;if(callee.type==="MemberExpression"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),["write","send","json"])){isInDangerousContext=true;break}}current=current.parent}if(isInDangerousContext){const enclosingArgument=literal=>{let current2=literal;let parent=current2.parent;for(;;){if(parent?.type==="BinaryExpression"&&parent.operator==="+"){current2=parent}else if(parent?.type==="ArrayExpression"){current2=parent}else if(parent?.type==="Property"||parent?.type==="ObjectExpression"&¤t2.type==="Property"){current2=parent}else if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.TSSatisfiesExpression||parent?.type===eslint_devkit_1.AST_NODE_TYPES.TSAsExpression||parent?.type===eslint_devkit_1.AST_NODE_TYPES.TSNonNullExpression||parent?.type===eslint_devkit_1.AST_NODE_TYPES.TSTypeAssertion){current2=parent}else if(parent?.type==="MemberExpression"&&parent.object===current2&&(0,eslint_devkit_1.propertyName)(parent)==="join"){current2=parent}else if(parent?.type==="CallExpression"&&parent.callee===current2){current2=parent}else{break}parent=current2.parent}if(parent?.type==="CallExpression"&&parent.arguments.includes(current2)){return current2}return void 0};const sanitizerNames=new Set([...safeSanitizers,...trustedSanitizers,"escapeHtml","escapeHTML","htmlEscape"]);const calleeName=callee=>{if(callee.type==="Identifier")return callee.name;if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.property.type==="Identifier"){return`${callee.object.name}.${callee.property.name}`}return void 0};const isSafeText=expr=>{if(expr.type==="Literal"){if(expr.value===null||typeof expr.value==="number"||typeof expr.value==="boolean"||typeof expr.value==="bigint"){return true}return typeof expr.value==="string"}if(expr.type==="TemplateLiteral")return expr.expressions.length===0;if(expr.type==="BinaryExpression"&&expr.operator==="+"){return isSafeText(expr.left)&&isSafeText(expr.right)}if(expr.type==="ObjectExpression"){return expr.properties.every(property=>property.type==="Property"&&isSafeText(property.value))}if(expr.type===eslint_devkit_1.AST_NODE_TYPES.TSSatisfiesExpression||expr.type===eslint_devkit_1.AST_NODE_TYPES.TSAsExpression||expr.type===eslint_devkit_1.AST_NODE_TYPES.TSNonNullExpression||expr.type===eslint_devkit_1.AST_NODE_TYPES.TSTypeAssertion){return isSafeText(expr.expression)}if(expr.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){return expr.elements.every(element=>element===null||isSafeText(element))}if(expr.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(expr)==="length"){return true}if(expr.type==="CallExpression"){const callee=expr.callee;if(callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(callee)==="join"&&callee.object.type==="ArrayExpression"){return callee.object.elements.every(element=>element!==null&&isSafeText(element))}const name=calleeName(callee);return name!==void 0&&sanitizerNames.has(name)}return false};const argument=enclosingArgument(node);const isBareLiteral=argument!==void 0&&isSafeText(argument);const hasDangerousMarkup=/<script[\s>]|<\/script>|\son\w+\s*=|javascript:/i.test(text);if(isBareLiteral&&!hasDangerousMarkup){return}const hasDangerousChars=dangerousChars.some(char=>text.includes(char));const hasEscaping=text.includes("<")||text.includes(">")||text.includes(""")||text.includes("'")||text.includes("&");if(hasDangerousChars&&!hasEscaping){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"unsafeReplaceSanitization",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noImproperTypeValidation=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");exports.noImproperTypeValidation=(0,eslint_devkit_1.createRule)({name:"no-improper-type-validation",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-improper-type-validation.md",description:"Detects improper type validation in user input handling",cwe:"CWE-1287"},messages:{unsafeTypeofCheck:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.WARNING,issueName:"Unsafe typeof Check",cwe:"CWE-1287",description:"typeof x === 'object' also matches null and arrays",severity:"MEDIUM",fix:'Use value != null && typeof value === "object" && !Array.isArray(value) \u2014 Not a finding if the value is already known non-null on this path',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof"}),unsafeInstanceofUsage:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.WARNING,issueName:"Unsafe instanceof Usage",cwe:"CWE-1287",description:"instanceof may fail across contexts",severity:"LOW",fix:"Use Array.isArray() or typeof checks \u2014 Not a finding if the value never crosses a realm boundary (no vm, iframe, or worker)",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof"}),looseEqualityTypeCheck:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.WARNING,issueName:"Loose Equality Type Check",cwe:"CWE-1287",description:"Loose equality may cause type confusion",severity:"LOW",fix:"Use strict equality (===) for type checking \u2014 Not a finding if both operands are already the same primitive type",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality"}),unreliableConstructorCheck:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.WARNING,issueName:"Unreliable Constructor Check",cwe:"CWE-1287",description:"constructor.name can be spoofed",severity:"MEDIUM",fix:"Use Object.prototype.toString.call() or duck typing \u2014 Not a finding if the value never came from parsed input",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor"})},schema:[{type:"object",properties:{allowInstanceofSameRealm:{type:"boolean",default:true,description:"Allow instanceof for same-realm objects"},checkLooseEquality:{type:"boolean",default:true,description:"Report loose == / != between operands of unprovable type. Set false to keep only the structural typeof/instanceof/constructor arms."},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as type validators"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},skipTestFiles:true,defaultOptions:[{allowInstanceofSameRealm:true,checkLooseEquality:true,trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{allowInstanceofSameRealm=true,checkLooseEquality=true,trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const sourceCode=context.sourceCode;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const isNullish=node=>node.type==="Literal"&&node.raw==="null"||node.type==="Identifier"&&node.name==="undefined";const sameExpression=(a,b)=>{if(a.type!==b.type)return false;if(a.type==="Identifier"&&b.type==="Identifier")return a.name===b.name;if(a.type==="ThisExpression")return true;if(a.type==="MemberExpression"&&b.type==="MemberExpression"){if(a.computed!==b.computed)return false;return sameExpression(a.object,b.object)&&sameExpression(a.property,b.property)}if(a.type==="Literal"&&b.type==="Literal")return a.raw===b.raw;return false};const hasNullGuard=(node,operand)=>{const excludesNullish=(expression,negated2)=>{if(sameExpression(expression,operand))return!negated2;if(expression.type==="UnaryExpression"&&expression.operator==="!"){return sameExpression(expression.argument,operand)&&negated2}if(expression.type!=="BinaryExpression")return false;const wanted=negated2?["===","=="]:["!==","!="];if(!wanted.includes(expression.operator))return false;if(isNullish(expression.right))return sameExpression(expression.left,operand);if(isNullish(expression.left))return sameExpression(expression.right,operand);return false};const negated=node.operator==="!=="||node.operator==="!=";const combinator=negated?"||":"&&";const guards=expression=>{if(expression.type==="LogicalExpression"&&expression.operator===combinator){return guards(expression.left)||guards(expression.right)}return excludesNullish(expression,negated)};let chain=node;while(chain.parent?.type==="LogicalExpression"&&chain.parent.operator===combinator){chain=chain.parent}return chain!==node&&guards(chain)};const primitiveTypeOf=(node,seen=new Set)=>{if(node.type==="Literal"){if(typeof node.value==="string")return"string";if(typeof node.value==="number")return"number";return void 0}if(node.type==="TemplateLiteral")return"string";if(node.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(node)==="length"){return"number"}if(node.type==="CallExpression"&&node.callee.type==="Identifier"){if(node.callee.name==="String")return"string";if(node.callee.name==="Number"||node.callee.name==="parseInt")return"number"}if(node.type!=="Identifier")return void 0;if(seen.has(node.name))return void 0;seen.add(node.name);for(let scope=sourceCode.getScope(node);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===node.name);if(!variable)continue;const writes=variable.references.filter(ref=>ref.isWrite()&&ref.writeExpr);if(writes.length===0)return void 0;const types=writes.map(ref=>primitiveTypeOf(ref.writeExpr,seen));return types.every(type=>type!==void 0&&type===types[0])?types[0]:void 0}return void 0};const typeofObjectOperand=node=>{if(!["===","!==","==","!="].includes(node.operator))return void 0;const{left,right}=node;if(left.type==="UnaryExpression"&&left.operator==="typeof"&&right.type==="Literal"&&right.value==="object"){return left.argument}return void 0};const report=(node,messageId)=>{if(safetyChecker.isSafe(node,context))return;context.report({node,messageId,data:{filePath:filename,line:String(node.loc.start.line)}})};return{BinaryExpression(node){const operand=typeofObjectOperand(node);if(operand){if(!hasNullGuard(node,operand))report(node.left,"unsafeTypeofCheck");return}if(node.operator==="instanceof"&&!allowInstanceofSameRealm){report(node,"unsafeInstanceofUsage");return}if(checkLooseEquality&&(node.operator==="=="||node.operator==="!=")){if(isNullish(node.left)||isNullish(node.right))return;const leftType=primitiveTypeOf(node.left);if(leftType!==void 0&&leftType===primitiveTypeOf(node.right))return;report(node,"looseEqualityTypeCheck")}},MemberExpression(node){if(
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noImproperTypeValidation=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");exports.noImproperTypeValidation=(0,eslint_devkit_1.createRule)({name:"no-improper-type-validation",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-improper-type-validation.md",description:"Detects improper type validation in user input handling",cwe:"CWE-1287"},messages:{unsafeTypeofCheck:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.WARNING,issueName:"Unsafe typeof Check",cwe:"CWE-1287",description:"typeof x === 'object' also matches null and arrays",severity:"MEDIUM",fix:'Use value != null && typeof value === "object" && !Array.isArray(value) \u2014 Not a finding if the value is already known non-null on this path',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof"}),unsafeInstanceofUsage:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.WARNING,issueName:"Unsafe instanceof Usage",cwe:"CWE-1287",description:"instanceof may fail across contexts",severity:"LOW",fix:"Use Array.isArray() or typeof checks \u2014 Not a finding if the value never crosses a realm boundary (no vm, iframe, or worker)",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof"}),looseEqualityTypeCheck:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.WARNING,issueName:"Loose Equality Type Check",cwe:"CWE-1287",description:"Loose equality may cause type confusion",severity:"LOW",fix:"Use strict equality (===) for type checking \u2014 Not a finding if both operands are already the same primitive type",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality"}),unreliableConstructorCheck:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.WARNING,issueName:"Unreliable Constructor Check",cwe:"CWE-1287",description:"constructor.name can be spoofed",severity:"MEDIUM",fix:"Use Object.prototype.toString.call() or duck typing \u2014 Not a finding if the value never came from parsed input",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor"})},schema:[{type:"object",properties:{allowInstanceofSameRealm:{type:"boolean",default:true,description:"Allow instanceof for same-realm objects"},checkLooseEquality:{type:"boolean",default:true,description:"Report loose == / != between operands of unprovable type. Set false to keep only the structural typeof/instanceof/constructor arms."},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as type validators"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},skipTestFiles:true,defaultOptions:[{allowInstanceofSameRealm:true,checkLooseEquality:true,trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{allowInstanceofSameRealm=true,checkLooseEquality=true,trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const sourceCode=context.sourceCode;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const isNullish=node=>node.type==="Literal"&&node.raw==="null"||node.type==="Identifier"&&node.name==="undefined";const sameExpression=(a,b)=>{if(a.type!==b.type)return false;if(a.type==="Identifier"&&b.type==="Identifier")return a.name===b.name;if(a.type==="ThisExpression")return true;if(a.type==="MemberExpression"&&b.type==="MemberExpression"){if(a.computed!==b.computed)return false;return sameExpression(a.object,b.object)&&sameExpression(a.property,b.property)}if(a.type==="Literal"&&b.type==="Literal")return a.raw===b.raw;return false};const hasNullGuard=(node,operand)=>{const excludesNullish=(expression,negated2)=>{if(sameExpression(expression,operand))return!negated2;if(expression.type==="UnaryExpression"&&expression.operator==="!"){return sameExpression(expression.argument,operand)&&negated2}if(expression.type!=="BinaryExpression")return false;const wanted=negated2?["===","=="]:["!==","!="];if(!wanted.includes(expression.operator))return false;if(isNullish(expression.right))return sameExpression(expression.left,operand);if(isNullish(expression.left))return sameExpression(expression.right,operand);return false};const negated=node.operator==="!=="||node.operator==="!=";const combinator=negated?"||":"&&";const guards=expression=>{if(expression.type==="LogicalExpression"&&expression.operator===combinator){return guards(expression.left)||guards(expression.right)}return excludesNullish(expression,negated)};let chain=node;while(chain.parent?.type==="LogicalExpression"&&chain.parent.operator===combinator){chain=chain.parent}return chain!==node&&guards(chain)};const primitiveTypeOf=(node,seen=new Set)=>{if(node.type==="Literal"){if(typeof node.value==="string")return"string";if(typeof node.value==="number")return"number";return void 0}if(node.type==="TemplateLiteral")return"string";if(node.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(node)==="length"){return"number"}if(node.type==="CallExpression"&&node.callee.type==="Identifier"){if(node.callee.name==="String")return"string";if(node.callee.name==="Number"||node.callee.name==="parseInt")return"number"}if(node.type!=="Identifier")return void 0;if(seen.has(node.name))return void 0;seen.add(node.name);for(let scope=sourceCode.getScope(node);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===node.name);if(!variable)continue;const writes=variable.references.filter(ref=>ref.isWrite()&&ref.writeExpr);if(writes.length===0)return void 0;const types=writes.map(ref=>primitiveTypeOf(ref.writeExpr,seen));return types.every(type=>type!==void 0&&type===types[0])?types[0]:void 0}return void 0};const typeofObjectOperand=node=>{if(!["===","!==","==","!="].includes(node.operator))return void 0;const{left,right}=node;if(left.type==="UnaryExpression"&&left.operator==="typeof"&&right.type==="Literal"&&right.value==="object"){return left.argument}return void 0};const report=(node,messageId)=>{if(safetyChecker.isSafe(node,context))return;context.report({node,messageId,data:{filePath:filename,line:String(node.loc.start.line)}})};return{BinaryExpression(node){const operand=typeofObjectOperand(node);if(operand){if(!hasNullGuard(node,operand))report(node.left,"unsafeTypeofCheck");return}if(node.operator==="instanceof"&&!allowInstanceofSameRealm){report(node,"unsafeInstanceofUsage");return}if(checkLooseEquality&&(node.operator==="=="||node.operator==="!=")){if(isNullish(node.left)||isNullish(node.right))return;const leftType=primitiveTypeOf(node.left);if(leftType!==void 0&&leftType===primitiveTypeOf(node.right))return;report(node,"looseEqualityTypeCheck")}},MemberExpression(node){if((0,eslint_devkit_1.propertyName)(node)!=="name")return;const inner=node.object;if(inner.type!=="MemberExpression"||(0,eslint_devkit_1.propertyName)(inner)!=="constructor"){return}if(node.parent?.type!=="BinaryExpression")return;report(node,"unreliableConstructorCheck")}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noLdapInjection=void 0;exports.containsDangerousLdapFilter=containsDangerousLdapFilter;exports.looksLikeLdapFilterGrammar=looksLikeLdapFilterGrammar;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");function containsDangerousLdapFilter(filterText){const dangerousPatterns=[/\*\)$/,/\|\)$/,/&\)$/,/!\)$/,/\*\|\*/,/\*&\*/,/\*!/];return dangerousPatterns.some(pattern=>pattern.test(filterText))}function looksLikeLdapFilterGrammar(staticText){return/\(\s*[A-Za-z][\w.;-]*\s*(?:[:~<>]?=)/.test(staticText)}const DEFAULT_LDAP_PACKAGES=["ldapjs","ldapts","ldapauth-fork","passport-ldapauth","ldap-authentication","ldap-escape","ldap-filter","activedirectory","activedirectory2","node-ldap"];const LDAP_SCOPES=new Set(["@ldapjs"]);const SEARCH_METHODS=new Set(["search","searchAsync","searchPaginated"]);const DEFAULT_REQUEST_ROOTS=["req","request","ctx","httpRequest"];const DEFAULT_LDAP_FUNCTIONS=["search","searchAsync","searchPaginated","bind","modify","modifyDN","add","del","delete","compare"];const DEFAULT_ESCAPE_FUNCTIONS=["escape.filterValue","escape.dnValue","filterValue","dnValue","filterEscape","dnEscape"];const DEFAULT_VALIDATION_FUNCTIONS=["validateLdapInput","sanitizeLdapFilter","cleanLdapValue","checkLdapFilter"];exports.noLdapInjection=(0,eslint_devkit_1.createRule)({name:"no-ldap-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-ldap-injection.md",description:"Detects LDAP injection vulnerabilities",cwe:"CWE-90"},messages:{ldapInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"LDAP Injection",cwe:"CWE-90",description:"LDAP injection vulnerability detected",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/90.html"}),unsafeLdapFilter:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe LDAP Filter",cwe:"CWE-90",description:"LDAP filter constructed with unsafe string operations",severity:"HIGH",fix:"Use ldap.escape.filterValue() to escape user input",documentationLink:"https://ldap.com/ldap-filters/"}),unescapedLdapInput:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unescaped LDAP Input",cwe:"CWE-90",description:"LDAP operation uses unescaped user input",severity:"MEDIUM",fix:"Escape all user input before LDAP operations",documentationLink:"https://cwe.mitre.org/data/definitions/90.html"}),dangerousLdapOperation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous LDAP Operation",cwe:"CWE-90",description:"LDAP operation allows dangerous filter patterns",severity:"HIGH",fix:"Validate LDAP filters and restrict allowed operations",documentationLink:"https://ldap.com/ldap-filters/"}),validateLdapInput:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Validate LDAP Input",description:"Validate LDAP input before processing",severity:"LOW",fix:"Validate input against allowed patterns",documentationLink:"https://cwe.mitre.org/data/definitions/90.html"})},schema:[{type:"object",properties:{ldapFunctions:{type:"array",items:{type:"string"},default:DEFAULT_LDAP_FUNCTIONS,description:"LDAP client methods treated as query sinks"},ldapEscapeFunctions:{type:"array",items:{type:"string"},default:DEFAULT_ESCAPE_FUNCTIONS,description:"Function names that escape LDAP filter or DN values"},ldapValidationFunctions:{type:"array",items:{type:"string"},default:DEFAULT_VALIDATION_FUNCTIONS,description:"Function names that count as LDAP input validation"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as LDAP sanitizers"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"},ldapPackages:{type:"array",items:{type:"string"},default:DEFAULT_LDAP_PACKAGES,description:"Package specifiers whose import opens the file gate. Nothing in a file is examined unless one of these is loaded. Replaces the built-in list."},additionalLdapPackages:{type:"array",items:{type:"string"},default:[],description:"Extra LDAP client packages, on top of `ldapPackages` \u2014 a house wrapper around ldapjs belongs here."},requestRoots:{type:"array",items:{type:"string"},default:DEFAULT_REQUEST_ROOTS,description:"Identifiers naming a framework request object, matched as the exact ROOT of a member chain \u2014 never as a substring of the printed expression. Replaces the built-in list."},additionalRequestRoots:{type:"array",items:{type:"string"},default:[],description:"Extra request-object root names, on top of `requestRoots`."}},additionalProperties:false}]},defaultOptions:[{ldapFunctions:DEFAULT_LDAP_FUNCTIONS,ldapEscapeFunctions:DEFAULT_ESCAPE_FUNCTIONS,ldapValidationFunctions:DEFAULT_VALIDATION_FUNCTIONS,trustedSanitizers:[],trustedAnnotations:[],strictMode:false,ldapPackages:DEFAULT_LDAP_PACKAGES,additionalLdapPackages:[],requestRoots:DEFAULT_REQUEST_ROOTS,additionalRequestRoots:[]}],create(context){const options=context.options[0]||{};const{ldapFunctions=DEFAULT_LDAP_FUNCTIONS,ldapEscapeFunctions=DEFAULT_ESCAPE_FUNCTIONS,ldapValidationFunctions=DEFAULT_VALIDATION_FUNCTIONS,trustedSanitizers=[],trustedAnnotations=[],strictMode=false,ldapPackages=DEFAULT_LDAP_PACKAGES,additionalLdapPackages=[],requestRoots=DEFAULT_REQUEST_ROOTS,additionalRequestRoots=[]}=options;const ldapPackageSet=new Set([...ldapPackages,...additionalLdapPackages]);const requestRootSet=new Set([...requestRoots,...additionalRequestRoots]);const fileImportsLdapClient=(0,eslint_devkit_1.createModuleEvidence)({packages:[...ldapPackageSet],scopes:[...LDAP_SCOPES]});const sourceCode=context.sourceCode;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const ldapLocals=new Set;let ldapInFile=false;const collectLdapLocals=program=>{const record=node=>{if(node?.type==="Identifier")ldapLocals.add(node.name);else if(node?.type==="ObjectPattern"){for(const property of node.properties){if(property.type==="Property")record(property.value)}}};const isLdapSource=raw=>typeof raw==="string"&&(ldapPackageSet.has(raw)||[...LDAP_SCOPES].some(scope=>raw.startsWith(`${scope}/`)));for(const statement of program.body){if(statement.type==="ImportDeclaration"&&isLdapSource(statement.source.value)){for(const specifier of statement.specifiers)record(specifier.local)}if(statement.type==="VariableDeclaration"){for(const declarator of statement.declarations){const init=declarator.init;if(init?.type==="CallExpression"&&init.callee.type==="Identifier"&&init.callee.name==="require"&&init.arguments[0]?.type==="Literal"&&isLdapSource(init.arguments[0].value)){record(declarator.id)}}}}};const unwrap=node=>{let current=node;while(current.type==="TSAsExpression"||current.type==="TSSatisfiesExpression"||current.type==="TSNonNullExpression"||current.type==="ChainExpression"){current=current.expression}return current};const writesOf=identifier=>{for(let scope=sourceCode.getScope(identifier);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===identifier.name);if(!variable)continue;return variable.references.filter(ref=>ref.isWrite()&&ref.writeExpr).map(ref=>ref.writeExpr)}return[]};const soleWriteOf=identifier=>{const writes=writesOf(identifier);return writes.length===1?writes[0]:void 0};const isLdapConstruction=node=>{const expression=unwrap(node);if(expression.type==="NewExpression"){const{callee:callee2}=expression;if(callee2.type==="Identifier")return ldapLocals.has(callee2.name);return callee2.type==="MemberExpression"&&callee2.object.type==="Identifier"&&ldapLocals.has(callee2.object.name)}if(expression.type!=="CallExpression")return false;const{callee}=expression;if(callee.type==="Identifier")return ldapLocals.has(callee.name);return callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&ldapLocals.has(callee.object.name)};const enclosingClassBody=node=>{for(let current=node;current;current=current.parent){if(current.type==="ClassBody")return current}return void 0};const isProvablyNotLdapReceiver=receiver=>{const expression=unwrap(receiver);if(expression.type==="ArrayExpression"||expression.type==="ObjectExpression"||expression.type==="Literal"){return true}if(expression.type==="NewExpression"||expression.type==="CallExpression"){return!isLdapConstruction(expression)}if(expression.type==="Identifier"){const writes=writesOf(expression);if(writes.length===0)return false;if(writes.some(isLdapConstruction))return false;return writes.every(write=>{const value=unwrap(write);return value.type==="NewExpression"||value.type==="CallExpression"||value.type==="ArrayExpression"||value.type==="ObjectExpression"||value.type==="Literal"})}const fieldName=(0,eslint_devkit_1.memberPropertyName)(expression);if(expression.type==="MemberExpression"&&expression.object.type==="ThisExpression"&&fieldName!==null){const body=enclosingClassBody(expression);if(!body)return false;const field=body.body.find(member=>member.type==="PropertyDefinition"&&!member.computed&&member.key.type==="Identifier"&&member.key.name===fieldName);if(!field?.value)return false;return!isLdapConstruction(field.value)}return false};const isEscaped=node=>{const expression=unwrap(node);if(expression.type==="Identifier"){const write=soleWriteOf(expression);if(write&&write!==expression&&isEscapedAt(write))return true}return isEscapedAt(node)};function isEscapedAt(node){for(let current=node;current;current=current.parent){if(current.type!=="CallExpression")continue;const{callee}=current;const escapeMethod=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type==="MemberExpression"&&escapeMethod!==null){if(ldapEscapeFunctions.some(escapeFunc=>escapeFunc===escapeMethod||escapeFunc.endsWith(`.${escapeMethod}`))){return true}}if(callee.type==="Identifier"&&(ldapValidationFunctions.includes(callee.name)||ldapEscapeFunctions.includes(callee.name))){return true}}return false}const isStatic=node=>(0,eslint_devkit_1.isStaticExpression)({node,scope:sourceCode.getScope(node)});const dynamicParts=(node,seen=new Set)=>{const expression=unwrap(node);if(seen.has(expression))return null;seen.add(expression);if(expression.type==="TemplateLiteral"){return expression.expressions.filter(part=>!isStatic(part)&&!isEscaped(part))}if(expression.type==="BinaryExpression"&&expression.operator==="+"){const leaves=[];const flatten=n=>{const inner=unwrap(n);if(inner.type==="BinaryExpression"&&inner.operator==="+"){flatten(inner.left);flatten(inner.right)}else leaves.push(inner)};flatten(expression);const hasStringPart=leaves.some(leaf=>(0,eslint_devkit_1.staticString)(leaf)!==null||leaf.type==="TemplateLiteral");if(!hasStringPart)return null;return leaves.filter(leaf=>!isStatic(leaf)&&!isEscaped(leaf))}if(expression.type==="ConditionalExpression"){const consequent=dynamicParts(expression.consequent,seen);const alternate=dynamicParts(expression.alternate,seen);if(consequent===null&&alternate===null)return null;return[...consequent??[],...alternate??[]]}if(expression.type==="Identifier"){const write=soleWriteOf(expression);return write?dynamicParts(write,seen):null}return null};const isRequestValue=(node,seen=new Set)=>{const expression=unwrap(node);if(seen.has(expression))return false;seen.add(expression);if(expression.type==="Identifier"){const write=soleWriteOf(expression);return write?isRequestValue(write,seen):false}if(expression.type==="CallExpression"){if(isEscaped(expression))return false;return expression.arguments.some(argument=>argument.type!=="SpreadElement"&&isRequestValue(argument,seen))}if(expression.type!=="MemberExpression"||expression.computed)return false;return!isStatic(expression)&&isUntrustedRequestChain(expression)};function isUntrustedRequestChain(node){let current=node;while(current.type==="MemberExpression")current=current.object;if(current.type!=="Identifier")return false;if(requestRootSet.has(current.name))return true;for(let scope=sourceCode.getScope(current);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===current.name);if(!variable)continue;return variable.defs.some(def=>{if(def.type!=="Variable")return false;const init=def.node.init?unwrap(def.node.init):void 0;if(!init)return false;if(init.type==="Identifier")return requestRootSet.has(init.name);return init.type==="MemberExpression"&&isUntrustedRequestChain(init)})}return false}const filterOption=node=>{let expression=unwrap(node);if(expression.type==="Identifier"){const write=soleWriteOf(expression);if(!write)return void 0;expression=unwrap(write)}if(expression.type!=="ObjectExpression")return void 0;for(const property of expression.properties){if(property.type!=="Property")continue;const{key}=property;if(!property.computed&&key.type==="Identifier"&&key.name==="filter"){return property.value}if(key.type==="Literal"&&key.value==="filter")return property.value;if(property.computed&&key.type==="Identifier"){const keyWrite=soleWriteOf(key);if(keyWrite&&unwrap(keyWrite).type==="Literal"){const literal=unwrap(keyWrite);if(literal.value==="filter")return property.value}}}return void 0};const reported=new Set;const report=(node,messageId,data)=>{if(reported.has(node))return;if(safetyChecker.isSafe(node,context))return;reported.add(node);context.report({node,messageId,data:{filePath:filename,line:String(node.loc.start.line),...data}})};const staticSkeleton=(node,seen=new Set)=>{const expression=unwrap(node);if(seen.has(expression))return"";seen.add(expression);if(expression.type==="Literal"){return typeof expression.value==="string"?expression.value:""}if(expression.type==="TemplateLiteral"){return expression.quasis.map(quasi=>quasi.value.raw).join("\0")}if(expression.type==="BinaryExpression"&&expression.operator==="+"){return staticSkeleton(expression.left,seen)+"\0"+staticSkeleton(expression.right,seen)}if(expression.type==="ConditionalExpression"){return staticSkeleton(expression.consequent,seen)+"\0"+staticSkeleton(expression.alternate,seen)}if(expression.type==="Identifier"){const write=soleWriteOf(expression);return write?staticSkeleton(write,seen):""}return""};const originOf=node=>{let current=unwrap(node);for(let hops=0;current.type==="Identifier"&&hops<8;hops+=1){const write=soleWriteOf(current);if(!write)break;current=unwrap(write)}return current};const checkFilter=rawFilterNode=>{const filterNode=originOf(rawFilterNode);const parts=dynamicParts(filterNode);if(parts&&parts.length>0){report(filterNode,"unsafeLdapFilter",{});return}if(isRequestValue(filterNode)){report(filterNode,"unescapedLdapInput",{});return}if(containsDangerousLdapFilter(staticSkeleton(filterNode).split("\0").join(""))){report(filterNode,"dangerousLdapOperation",{})}};const checkDn=rawDnNode=>{const dnNode=originOf(rawDnNode);const parts=dynamicParts(dnNode);if(parts&&parts.length>0){report(dnNode,"ldapInjection",{severity:"HIGH",safeAlternative:"Use ldap.escape.dnValue() or build the DN from validated components"});return}if(isRequestValue(dnNode)){report(dnNode,"ldapInjection",{severity:"MEDIUM",safeAlternative:"Use proper LDAP escaping and validation"})}};const checkConstructedFilter=node=>{if(!looksLikeLdapFilterGrammar(staticSkeleton(node)))return;checkFilter(node)};return{Program(program){ldapInFile=fileImportsLdapClient(program);if(ldapInFile)collectLdapLocals(program)},VariableDeclarator(node){if(!ldapInFile||!node.init)return;checkConstructedFilter(node.init)},AssignmentExpression(node){if(!ldapInFile)return;checkConstructedFilter(node.right)},CallExpression(node){if(!ldapInFile)return;const callee=unwrap(node.callee);if(callee.type!=="MemberExpression")return;const method=(0,eslint_devkit_1.propertyName)(callee);if(method===null)return;if(!ldapFunctions.includes(method))return;if(isProvablyNotLdapReceiver(callee.object))return;const args=node.arguments.filter(argument=>argument.type!=="SpreadElement");if(args.length===0)return;checkDn(args[0]);if(args.length<2)return;if(SEARCH_METHODS.has(method)){const optionsFilter=filterOption(args[1]);checkFilter(optionsFilter??args[1]);return}checkConstructedFilter(args[1])}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noLdapInjection=void 0;exports.containsDangerousLdapFilter=containsDangerousLdapFilter;exports.looksLikeLdapFilterGrammar=looksLikeLdapFilterGrammar;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");function containsDangerousLdapFilter(filterText){const dangerousPatterns=[/\*\)$/,/\|\)$/,/&\)$/,/!\)$/,/\*\|\*/,/\*&\*/,/\*!/];return dangerousPatterns.some(pattern=>pattern.test(filterText))}function looksLikeLdapFilterGrammar(staticText){return/\(\s*[A-Za-z][\w.;-]*\s*(?:[:~<>]?=)/.test(staticText)}const DEFAULT_LDAP_PACKAGES=["ldapjs","ldapts","ldapauth-fork","passport-ldapauth","ldap-authentication","ldap-escape","ldap-filter","activedirectory","activedirectory2","node-ldap"];const LDAP_SCOPES=new Set(["@ldapjs"]);const SEARCH_METHODS=new Set(["search","searchAsync","searchPaginated"]);const DEFAULT_REQUEST_ROOTS=["req","request","ctx","httpRequest"];const DEFAULT_LDAP_FUNCTIONS=["search","searchAsync","searchPaginated","bind","modify","modifyDN","add","del","delete","compare"];const DEFAULT_ESCAPE_FUNCTIONS=["escape.filterValue","escape.dnValue","filterValue","dnValue","filterEscape","dnEscape"];const DEFAULT_VALIDATION_FUNCTIONS=["validateLdapInput","sanitizeLdapFilter","cleanLdapValue","checkLdapFilter"];exports.noLdapInjection=(0,eslint_devkit_1.createRule)({name:"no-ldap-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-ldap-injection.md",description:"Detects LDAP injection vulnerabilities",cwe:"CWE-90"},messages:{ldapInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"LDAP Injection",cwe:"CWE-90",description:"LDAP injection vulnerability detected",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/90.html"}),unsafeLdapFilter:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe LDAP Filter",cwe:"CWE-90",description:"LDAP filter constructed with unsafe string operations",severity:"HIGH",fix:"Use ldap.escape.filterValue() to escape user input",documentationLink:"https://ldap.com/ldap-filters/"}),unescapedLdapInput:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unescaped LDAP Input",cwe:"CWE-90",description:"LDAP operation uses unescaped user input",severity:"MEDIUM",fix:"Escape all user input before LDAP operations",documentationLink:"https://cwe.mitre.org/data/definitions/90.html"}),dangerousLdapOperation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous LDAP Operation",cwe:"CWE-90",description:"LDAP operation allows dangerous filter patterns",severity:"HIGH",fix:"Validate LDAP filters and restrict allowed operations",documentationLink:"https://ldap.com/ldap-filters/"}),validateLdapInput:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Validate LDAP Input",description:"Validate LDAP input before processing",severity:"LOW",fix:"Validate input against allowed patterns",documentationLink:"https://cwe.mitre.org/data/definitions/90.html"})},schema:[{type:"object",properties:{ldapFunctions:{type:"array",items:{type:"string"},default:DEFAULT_LDAP_FUNCTIONS,description:"LDAP client methods treated as query sinks"},ldapEscapeFunctions:{type:"array",items:{type:"string"},default:DEFAULT_ESCAPE_FUNCTIONS,description:"Function names that escape LDAP filter or DN values"},ldapValidationFunctions:{type:"array",items:{type:"string"},default:DEFAULT_VALIDATION_FUNCTIONS,description:"Function names that count as LDAP input validation"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as LDAP sanitizers"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"},ldapPackages:{type:"array",items:{type:"string"},default:DEFAULT_LDAP_PACKAGES,description:"Package specifiers whose import opens the file gate. Nothing in a file is examined unless one of these is loaded. Replaces the built-in list."},additionalLdapPackages:{type:"array",items:{type:"string"},default:[],description:"Extra LDAP client packages, on top of `ldapPackages` \u2014 a house wrapper around ldapjs belongs here."},requestRoots:{type:"array",items:{type:"string"},default:DEFAULT_REQUEST_ROOTS,description:"Identifiers naming a framework request object, matched as the exact ROOT of a member chain \u2014 never as a substring of the printed expression. Replaces the built-in list."},additionalRequestRoots:{type:"array",items:{type:"string"},default:[],description:"Extra request-object root names, on top of `requestRoots`."}},additionalProperties:false}]},defaultOptions:[{ldapFunctions:DEFAULT_LDAP_FUNCTIONS,ldapEscapeFunctions:DEFAULT_ESCAPE_FUNCTIONS,ldapValidationFunctions:DEFAULT_VALIDATION_FUNCTIONS,trustedSanitizers:[],trustedAnnotations:[],strictMode:false,ldapPackages:DEFAULT_LDAP_PACKAGES,additionalLdapPackages:[],requestRoots:DEFAULT_REQUEST_ROOTS,additionalRequestRoots:[]}],create(context){const options=context.options[0]||{};const{ldapFunctions=DEFAULT_LDAP_FUNCTIONS,ldapEscapeFunctions=DEFAULT_ESCAPE_FUNCTIONS,ldapValidationFunctions=DEFAULT_VALIDATION_FUNCTIONS,trustedSanitizers=[],trustedAnnotations=[],strictMode=false,ldapPackages=DEFAULT_LDAP_PACKAGES,additionalLdapPackages=[],requestRoots=DEFAULT_REQUEST_ROOTS,additionalRequestRoots=[]}=options;const ldapPackageSet=new Set([...ldapPackages,...additionalLdapPackages]);const requestRootSet=new Set([...requestRoots,...additionalRequestRoots]);const fileImportsLdapClient=(0,eslint_devkit_1.createModuleEvidence)({packages:[...ldapPackageSet],scopes:[...LDAP_SCOPES]});const sourceCode=context.sourceCode;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const ldapLocals=new Set;let ldapInFile=false;const collectLdapLocals=program=>{const record=node=>{if(node?.type==="Identifier")ldapLocals.add(node.name);else if(node?.type==="ObjectPattern"){for(const property of node.properties){if(property.type==="Property")record(property.value)}}};const isLdapSource=raw=>typeof raw==="string"&&(ldapPackageSet.has(raw)||[...LDAP_SCOPES].some(scope=>raw.startsWith(`${scope}/`)));for(const statement of program.body){if(statement.type==="ImportDeclaration"&&isLdapSource(statement.source.value)){for(const specifier of statement.specifiers)record(specifier.local)}if(statement.type==="VariableDeclaration"){for(const declarator of statement.declarations){const init=declarator.init;if(init?.type==="CallExpression"&&init.callee.type==="Identifier"&&init.callee.name==="require"&&init.arguments[0]?.type==="Literal"&&isLdapSource(init.arguments[0].value)){record(declarator.id)}}}}};const unwrap=node=>{let current=node;while(current.type==="TSAsExpression"||current.type==="TSSatisfiesExpression"||current.type==="TSNonNullExpression"||current.type==="ChainExpression"){current=current.expression}return current};const writesOf=identifier=>{for(let scope=sourceCode.getScope(identifier);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===identifier.name);if(!variable)continue;return variable.references.filter(ref=>ref.isWrite()&&ref.writeExpr).map(ref=>ref.writeExpr)}return[]};const soleWriteOf=identifier=>{const writes=writesOf(identifier);return writes.length===1?writes[0]:void 0};const isLdapConstruction=node=>{const expression=unwrap(node);if(expression.type==="NewExpression"){const{callee:callee2}=expression;if(callee2.type==="Identifier")return ldapLocals.has(callee2.name);return callee2.type==="MemberExpression"&&callee2.object.type==="Identifier"&&ldapLocals.has(callee2.object.name)}if(expression.type!=="CallExpression")return false;const{callee}=expression;if(callee.type==="Identifier")return ldapLocals.has(callee.name);return callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&ldapLocals.has(callee.object.name)};const enclosingClassBody=node=>{for(let current=node;current;current=current.parent){if(current.type==="ClassBody")return current}return void 0};const isProvablyNotLdapReceiver=receiver=>{const expression=unwrap(receiver);if(expression.type==="ArrayExpression"||expression.type==="ObjectExpression"||expression.type==="Literal"){return true}if(expression.type==="NewExpression"||expression.type==="CallExpression"){return!isLdapConstruction(expression)}if(expression.type==="Identifier"){const writes=writesOf(expression);if(writes.length===0)return false;if(writes.some(isLdapConstruction))return false;return writes.every(write=>{const value=unwrap(write);return value.type==="NewExpression"||value.type==="CallExpression"||value.type==="ArrayExpression"||value.type==="ObjectExpression"||value.type==="Literal"})}const fieldName=(0,eslint_devkit_1.memberPropertyName)(expression);if(expression.type==="MemberExpression"&&expression.object.type==="ThisExpression"&&fieldName!==null){const body=enclosingClassBody(expression);if(!body)return false;const field=body.body.find(member=>member.type==="PropertyDefinition"&&!member.computed&&member.key.type==="Identifier"&&member.key.name===fieldName);if(!field?.value)return false;return!isLdapConstruction(field.value)}return false};const isEscaped=node=>{const expression=unwrap(node);if(expression.type==="Identifier"){const write=soleWriteOf(expression);if(write&&write!==expression&&isEscapedAt(write))return true}return isEscapedAt(node)};function isEscapedAt(node){for(let current=node;current;current=current.parent){if(current.type!=="CallExpression")continue;const{callee}=current;const escapeMethod=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type==="MemberExpression"&&escapeMethod!==null){if(ldapEscapeFunctions.some(escapeFunc=>escapeFunc===escapeMethod||escapeFunc.endsWith(`.${escapeMethod}`))){return true}}if(callee.type==="Identifier"&&(ldapValidationFunctions.includes(callee.name)||ldapEscapeFunctions.includes(callee.name))){return true}}return false}const isStatic=node=>(0,eslint_devkit_1.isStaticExpression)({node,scope:sourceCode.getScope(node)});const dynamicParts=(node,seen=new Set)=>{const expression=unwrap(node);if(seen.has(expression))return null;seen.add(expression);if(expression.type==="TemplateLiteral"){return expression.expressions.filter(part=>!isStatic(part)&&!isEscaped(part))}if(expression.type==="BinaryExpression"&&expression.operator==="+"){const leaves=[];const flatten=n=>{const inner=unwrap(n);if(inner.type==="BinaryExpression"&&inner.operator==="+"){flatten(inner.left);flatten(inner.right)}else leaves.push(inner)};flatten(expression);const hasStringPart=leaves.some(leaf=>(0,eslint_devkit_1.staticString)(leaf)!==null||leaf.type==="TemplateLiteral");if(!hasStringPart)return null;return leaves.filter(leaf=>!isStatic(leaf)&&!isEscaped(leaf))}if(expression.type==="ConditionalExpression"){const consequent=dynamicParts(expression.consequent,seen);const alternate=dynamicParts(expression.alternate,seen);if(consequent===null&&alternate===null)return null;return[...consequent??[],...alternate??[]]}if(expression.type==="Identifier"){const write=soleWriteOf(expression);return write?dynamicParts(write,seen):null}return null};const isRequestValue=(node,seen=new Set)=>{const expression=unwrap(node);if(seen.has(expression))return false;seen.add(expression);if(expression.type==="Identifier"){const write=soleWriteOf(expression);return write?isRequestValue(write,seen):false}if(expression.type==="CallExpression"){if(isEscaped(expression))return false;return expression.arguments.some(argument=>argument.type!=="SpreadElement"&&isRequestValue(argument,seen))}if(expression.type!=="MemberExpression"||(0,eslint_devkit_1.propertyName)(expression)===null)return false;return!isStatic(expression)&&isUntrustedRequestChain(expression)};function isUntrustedRequestChain(node){let current=node;while(current.type==="MemberExpression"){if((0,eslint_devkit_1.propertyName)(current)===null)return false;current=current.object}if(current.type!=="Identifier")return false;if(requestRootSet.has(current.name))return true;for(let scope=sourceCode.getScope(current);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===current.name);if(!variable)continue;return variable.defs.some(def=>{if(def.type!=="Variable")return false;const init=def.node.init?unwrap(def.node.init):void 0;if(!init)return false;if(init.type==="Identifier")return requestRootSet.has(init.name);return init.type==="MemberExpression"&&isUntrustedRequestChain(init)})}return false}const filterOption=node=>{let expression=unwrap(node);if(expression.type==="Identifier"){const write=soleWriteOf(expression);if(!write)return void 0;expression=unwrap(write)}if(expression.type!=="ObjectExpression")return void 0;for(const property of expression.properties){if(property.type!=="Property")continue;const{key}=property;if(!property.computed&&key.type==="Identifier"&&key.name==="filter"){return property.value}if(key.type==="Literal"&&key.value==="filter")return property.value;if(property.computed&&key.type==="Identifier"){const keyWrite=soleWriteOf(key);if(keyWrite&&unwrap(keyWrite).type==="Literal"){const literal=unwrap(keyWrite);if(literal.value==="filter")return property.value}}}return void 0};const reported=new Set;const report=(node,messageId,data)=>{if(reported.has(node))return;if(safetyChecker.isSafe(node,context))return;reported.add(node);context.report({node,messageId,data:{filePath:filename,line:String(node.loc.start.line),...data}})};const staticSkeleton=(node,seen=new Set)=>{const expression=unwrap(node);if(seen.has(expression))return"";seen.add(expression);if(expression.type==="Literal"){return typeof expression.value==="string"?expression.value:""}if(expression.type==="TemplateLiteral"){return expression.quasis.map(quasi=>quasi.value.raw).join("\0")}if(expression.type==="BinaryExpression"&&expression.operator==="+"){return staticSkeleton(expression.left,seen)+"\0"+staticSkeleton(expression.right,seen)}if(expression.type==="ConditionalExpression"){return staticSkeleton(expression.consequent,seen)+"\0"+staticSkeleton(expression.alternate,seen)}if(expression.type==="Identifier"){const write=soleWriteOf(expression);return write?staticSkeleton(write,seen):""}return""};const originOf=node=>{let current=unwrap(node);for(let hops=0;current.type==="Identifier"&&hops<8;hops+=1){const write=soleWriteOf(current);if(!write)break;current=unwrap(write)}return current};const checkFilter=rawFilterNode=>{const filterNode=originOf(rawFilterNode);const parts=dynamicParts(filterNode);if(parts&&parts.length>0){report(filterNode,"unsafeLdapFilter",{});return}if(isRequestValue(filterNode)){report(filterNode,"unescapedLdapInput",{});return}if(containsDangerousLdapFilter(staticSkeleton(filterNode).split("\0").join(""))){report(filterNode,"dangerousLdapOperation",{})}};const checkDn=rawDnNode=>{const dnNode=originOf(rawDnNode);const parts=dynamicParts(dnNode);if(parts&&parts.length>0){report(dnNode,"ldapInjection",{severity:"HIGH",safeAlternative:"Use ldap.escape.dnValue() or build the DN from validated components"});return}if(isRequestValue(dnNode)){report(dnNode,"ldapInjection",{severity:"MEDIUM",safeAlternative:"Use proper LDAP escaping and validation"})}};const checkConstructedFilter=node=>{if(!looksLikeLdapFilterGrammar(staticSkeleton(node)))return;checkFilter(node)};return{Program(program){ldapInFile=fileImportsLdapClient(program);if(ldapInFile)collectLdapLocals(program)},VariableDeclarator(node){if(!ldapInFile||!node.init)return;checkConstructedFilter(node.init)},AssignmentExpression(node){if(!ldapInFile)return;checkConstructedFilter(node.right)},CallExpression(node){if(!ldapInFile)return;const callee=unwrap(node.callee);if(callee.type!=="MemberExpression")return;const method=(0,eslint_devkit_1.propertyName)(callee);if(method===null)return;if(!ldapFunctions.includes(method))return;if(isProvablyNotLdapReceiver(callee.object))return;const args=node.arguments.filter(argument=>argument.type!=="SpreadElement");if(args.length===0)return;checkDn(args[0]);if(args.length<2)return;if(SEARCH_METHODS.has(method)){const optionsFilter=filterOption(args[1]);checkFilter(optionsFilter??args[1]);return}checkConstructedFilter(args[1])}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPrivilegeEscalation=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const DEFAULT_ROLE_CHECK_PATTERNS=["hasRole","checkRole","isAdmin","isAuthorized","hasPermission","checkPermission","verifyRole","requireRole"];const DEFAULT_USER_INPUT_PATTERNS=[/\breq\.(body|query|params)\b/,/\brequest\.(body|query|params)\b/,/\buserInput\b/];const DEFAULT_PRIVILEGE_PROPERTIES=["role","permission","privilege","access"];const DEFAULT_PRIVILEGE_TERMS=["setRole","updateRole","elevate","grant role","grant permission","grant access","grant privilege","promote user","promote admin","revoke role","revoke permission","revoke access","revoke privilege"];const DEFAULT_BARE_PRIVILEGE_VERBS=["grant","promote","revoke"];function isPrivilegeOperationName(name,privilegeTerms,bareVerbs){if((0,eslint_devkit_1.nameHasAnyWord)(name,privilegeTerms)){return true}const words=(0,eslint_devkit_1.identifierWords)(name);return words.length===1&&bareVerbs.has(words[0])}function assignedPropertyName(member){if(!member.computed&&member.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return member.property.name}const staticText=(0,eslint_devkit_1.staticString)(member.property);if(staticText!==null){return staticText}return null}function forEachNode(root,visit){const pending=[root];while(pending.length>0){const node=pending.pop();visit(node);for(const[key,value]of Object.entries(node)){if(key==="parent")continue;const children=Array.isArray(value)?value:[value];for(const child of children){if(child!==null&&typeof child==="object"&&typeof child.type==="string"){pending.push(child)}}}}}function containsRoleCheck(root,roleCheckPatterns){let found=false;forEachNode(root,node=>{if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(0,eslint_devkit_1.nameHasAnyWord)(node.name,roleCheckPatterns)){found=true}});return found}function exitsUnconditionally(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement||node.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement){return true}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){return node.body.some(statement=>statement.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement||statement.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement)}return false}function isAfterRoleGuard(node,roleCheckPatterns){let current=node;while(current.parent){const parent=current.parent;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement||parent.type===eslint_devkit_1.AST_NODE_TYPES.Program){const body=parent.body;const index=body.indexOf(current);for(let i=0;i<index;i++){const statement=body[i];if(statement.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement&&exitsUnconditionally(statement.consequent)&&containsRoleCheck(statement.test,roleCheckPatterns)){return true}}}current=parent}return false}function matchesIgnorePattern(text,patterns){return(0,eslint_devkit_1.matchesAnyUserPattern)((0,eslint_devkit_1.compileUserPatterns)(patterns,"i"),text)}function containsUserInput(node,sourceCode,userInputPatterns){const text=sourceCode.getText(node);return userInputPatterns.some(pattern=>pattern.test(text))}function isInsideRoleCheck(node,roleCheckPatterns){let current=node;while(current){if(current.parent&¤t.parent.type==="IfStatement"){const ifStmt=current.parent;if(containsRoleCheck(ifStmt.test,roleCheckPatterns)){return true}}if(current.parent&¤t.parent.type==="ConditionalExpression"){const condExpr=current.parent;if(containsRoleCheck(condExpr.test,roleCheckPatterns)){return true}}if(current.parent&¤t.parent.type==="CallExpression"){const callExpr=current.parent;const callee=callExpr.callee;if(callee.type==="Identifier"){if((0,eslint_devkit_1.nameHasAnyWord)(callee.name,roleCheckPatterns)){return true}}const memberName=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type==="MemberExpression"&&memberName!==null){if((0,eslint_devkit_1.nameHasAnyWord)(memberName,roleCheckPatterns)){return true}}}if("parent"in current&¤t.parent){current=current.parent}else{break}}return false}exports.noPrivilegeEscalation=(0,eslint_devkit_2.createRule)({name:"no-privilege-escalation",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-privilege-escalation.md",description:"Detects potential privilege escalation vulnerabilities",cwe:"CWE-269",cvss:8.8},messages:{privilegeEscalation:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Privilege Escalation",cwe:"CWE-269",description:"Potential privilege escalation: {{issue}} - user input used without role validation",severity:"HIGH",fix:'Add role check before using user input: if (!hasRole(user, requiredRole)) throw new Error("Unauthorized");',documentationLink:"https://cwe.mitre.org/data/definitions/269.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow privilege escalation patterns in test files"},testFilePattern:{type:["string","null"],default:null,description:"Override which filenames `allowInTests` applies to. Null \u2014 the default \u2014 leaves it to the shared structural predicate."},roleCheckPatterns:{type:"array",items:{type:"string"},default:DEFAULT_ROLE_CHECK_PATTERNS,description:"Role check patterns to recognize"},userInputPatterns:{type:"array",items:{type:"string"},default:[],description:"Additional user input patterns to check (regex strings)"},ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Additional patterns to ignore"},privilegeProperties:{type:"array",items:{type:"string"},default:DEFAULT_PRIVILEGE_PROPERTIES,description:"Property names whose assignment is an authorisation decision, compared case-insensitively as an exact name. Replaces the built-in list."},additionalPrivilegeProperties:{type:"array",items:{type:"string"},default:[],description:"Extra privilege property names, on top of `privilegeProperties`."},privilegeTerms:{type:"array",items:{type:"string"},default:DEFAULT_PRIVILEGE_TERMS,description:"Privilege operations, matched as whole words or whole consecutive phrases of a callee name \u2014 never as a substring. Replaces the built-in list."},additionalPrivilegeTerms:{type:"array",items:{type:"string"},default:[],description:"Extra privilege operation terms, on top of `privilegeTerms`."},barePrivilegeVerbs:{type:"array",items:{type:"string"},default:DEFAULT_BARE_PRIVILEGE_VERBS,description:"Verbs that count only when they are the WHOLE callee name, because their ordinary English sense dominates otherwise. Replaces the built-in list."},additionalBarePrivilegeVerbs:{type:"array",items:{type:"string"},default:[],description:"Extra bare privilege verbs, on top of `barePrivilegeVerbs`."}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,roleCheckPatterns:DEFAULT_ROLE_CHECK_PATTERNS,userInputPatterns:[],ignorePatterns:[],privilegeProperties:DEFAULT_PRIVILEGE_PROPERTIES,additionalPrivilegeProperties:[],privilegeTerms:DEFAULT_PRIVILEGE_TERMS,additionalPrivilegeTerms:[],barePrivilegeVerbs:DEFAULT_BARE_PRIVILEGE_VERBS,additionalBarePrivilegeVerbs:[]}],create(context,[options={}]){const{allowInTests=false,testFilePattern,roleCheckPatterns=DEFAULT_ROLE_CHECK_PATTERNS,userInputPatterns:additionalUserInputPatterns=[],ignorePatterns=[],privilegeProperties=DEFAULT_PRIVILEGE_PROPERTIES,additionalPrivilegeProperties=[],privilegeTerms=DEFAULT_PRIVILEGE_TERMS,additionalPrivilegeTerms=[],barePrivilegeVerbs=DEFAULT_BARE_PRIVILEGE_VERBS,additionalBarePrivilegeVerbs=[]}=options;const privilegeProps=new Set([...privilegeProperties,...additionalPrivilegeProperties].map(name=>name.toLowerCase()));const privilegeOperationTerms=[...privilegeTerms,...additionalPrivilegeTerms];const bareVerbs=new Set([...barePrivilegeVerbs,...additionalBarePrivilegeVerbs]);const isPrivilegeOperationCallee=name=>isPrivilegeOperationName(name,privilegeOperationTerms,bareVerbs);const filename=context.filename;const isTestFile=allowInTests&&(testFilePattern==null?(0,eslint_devkit_2.isTestFilePath)(filename):(0,eslint_devkit_1.compileUserPattern)(testFilePattern).test(filename));const sourceCode=context.sourceCode;const userInputPatterns=[...DEFAULT_USER_INPUT_PATTERNS,...(0,eslint_devkit_1.compileUserPatterns)(additionalUserInputPatterns,"i")];function isRoleChecked(node){return isInsideRoleCheck(node,roleCheckPatterns)||isAfterRoleGuard(node,roleCheckPatterns)}function resolvesToUserInput(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const scope=sourceCode.getScope(node);const reference=scope.references.find(ref=>ref.identifier===node);for(const def of reference?.resolved?.defs??[]){let declarator=def.name;while(declarator&&declarator.type!==eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator){declarator=declarator.parent}if(declarator?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&declarator.init&&containsUserInput(declarator.init,sourceCode,userInputPatterns)){return true}}return false}function isUserControlled(node){return containsUserInput(node,sourceCode,userInputPatterns)||resolvesToUserInput(node)}function checkAssignmentExpression(node){if(isTestFile){return}if(node.left.type==="MemberExpression"){const propertyName=assignedPropertyName(node.left)?.toLowerCase();if(propertyName!==void 0&&privilegeProps.has(propertyName)){const text=sourceCode.getText(node);if(matchesIgnorePattern(text,ignorePatterns)){return}if(isUserControlled(node.right)){if(!isRoleChecked(node)){context.report({node,messageId:"privilegeEscalation",data:{issue:`Role assignment from user input: ${sourceCode.getText(node.left)} = ${sourceCode.getText(node.right)}`}})}}}}}function checkCallExpression(node){if(isTestFile){return}const callee=node.callee;let isPrivilegeOperation=false;let operationName="";if(callee.type==="Identifier"){if(isPrivilegeOperationCallee(callee.name)){isPrivilegeOperation=true;operationName=callee.name}}const method=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type==="MemberExpression"&&method!==null){if(isPrivilegeOperationCallee(method)){isPrivilegeOperation=true;operationName=method.toLowerCase()}}if(isPrivilegeOperation){const text=sourceCode.getText(node);if(matchesIgnorePattern(text,ignorePatterns)){return}for(const arg of node.arguments){if(isUserControlled(arg)){if(!isRoleChecked(node)){context.report({node,messageId:"privilegeEscalation",data:{issue:`Privilege operation (${operationName}) with user input without role validation`}});return}}}}}function checkObjectExpression(node){if(isTestFile)return;for(const prop of node.properties){if(prop.type==="Property"&&prop.key.type==="Identifier"){const keyName=prop.key.name.toLowerCase();if(privilegeProps.has(keyName)){const text=sourceCode.getText(prop);if(matchesIgnorePattern(text,ignorePatterns))continue;if(isUserControlled(prop.value)){if(!isRoleChecked(node)){context.report({node:prop,messageId:"privilegeEscalation",data:{issue:`Role assignment in object from user input: ${sourceCode.getText(prop)}`}})}}}}}}return{AssignmentExpression:checkAssignmentExpression,CallExpression:checkCallExpression,ObjectExpression:checkObjectExpression}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPrivilegeEscalation=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const DEFAULT_ROLE_CHECK_PATTERNS=["hasRole","checkRole","isAdmin","isAuthorized","hasPermission","checkPermission","verifyRole","requireRole"];const DEFAULT_USER_INPUT_PATTERNS=[/\breq\s*(?:\.\s*(?:body|query|params)(?![\w$])|\[\s*['"](?:body|query|params)['"]\s*\])/,/\brequest\s*(?:\.\s*(?:body|query|params)(?![\w$])|\[\s*['"](?:body|query|params)['"]\s*\])/,/\buserInput\b/];const DEFAULT_PRIVILEGE_PROPERTIES=["role","permission","privilege","access"];const DEFAULT_PRIVILEGE_TERMS=["setRole","updateRole","elevate","grant role","grant permission","grant access","grant privilege","promote user","promote admin","revoke role","revoke permission","revoke access","revoke privilege"];const DEFAULT_BARE_PRIVILEGE_VERBS=["grant","promote","revoke"];function isPrivilegeOperationName(name,privilegeTerms,bareVerbs){if((0,eslint_devkit_1.nameHasAnyWord)(name,privilegeTerms)){return true}const words=(0,eslint_devkit_1.identifierWords)(name);return words.length===1&&bareVerbs.has(words[0])}function assignedPropertyName(member){if(!member.computed&&member.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return member.property.name}const staticText=(0,eslint_devkit_1.staticString)(member.property);if(staticText!==null){return staticText}return null}function forEachNode(root,visit){const pending=[root];while(pending.length>0){const node=pending.pop();visit(node);for(const[key,value]of Object.entries(node)){if(key==="parent")continue;const children=Array.isArray(value)?value:[value];for(const child of children){if(child!==null&&typeof child==="object"&&typeof child.type==="string"){pending.push(child)}}}}}function containsRoleCheck(root,roleCheckPatterns){let found=false;forEachNode(root,node=>{if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(0,eslint_devkit_1.nameHasAnyWord)(node.name,roleCheckPatterns)){found=true}});return found}function exitsUnconditionally(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement||node.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement){return true}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){return node.body.some(statement=>statement.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement||statement.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement)}return false}function isAfterRoleGuard(node,roleCheckPatterns){let current=node;while(current.parent){const parent=current.parent;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement||parent.type===eslint_devkit_1.AST_NODE_TYPES.Program){const body=parent.body;const index=body.indexOf(current);for(let i=0;i<index;i++){const statement=body[i];if(statement.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement&&exitsUnconditionally(statement.consequent)&&containsRoleCheck(statement.test,roleCheckPatterns)){return true}}}current=parent}return false}function matchesIgnorePattern(text,patterns){return(0,eslint_devkit_1.matchesAnyUserPattern)((0,eslint_devkit_1.compileUserPatterns)(patterns,"i"),text)}function containsUserInput(node,sourceCode,userInputPatterns){const text=sourceCode.getText(node);return userInputPatterns.some(pattern=>pattern.test(text))}function isInsideRoleCheck(node,roleCheckPatterns){let current=node;while(current){if(current.parent&¤t.parent.type==="IfStatement"){const ifStmt=current.parent;if(containsRoleCheck(ifStmt.test,roleCheckPatterns)){return true}}if(current.parent&¤t.parent.type==="ConditionalExpression"){const condExpr=current.parent;if(containsRoleCheck(condExpr.test,roleCheckPatterns)){return true}}if(current.parent&¤t.parent.type==="CallExpression"){const callExpr=current.parent;const callee=callExpr.callee;if(callee.type==="Identifier"){if((0,eslint_devkit_1.nameHasAnyWord)(callee.name,roleCheckPatterns)){return true}}const memberName=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type==="MemberExpression"&&memberName!==null){if((0,eslint_devkit_1.nameHasAnyWord)(memberName,roleCheckPatterns)){return true}}}if("parent"in current&¤t.parent){current=current.parent}else{break}}return false}exports.noPrivilegeEscalation=(0,eslint_devkit_2.createRule)({name:"no-privilege-escalation",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-privilege-escalation.md",description:"Detects potential privilege escalation vulnerabilities",cwe:"CWE-269",cvss:8.8},messages:{privilegeEscalation:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Privilege Escalation",cwe:"CWE-269",description:"Potential privilege escalation: {{issue}} - user input used without role validation",severity:"HIGH",fix:'Add role check before using user input: if (!hasRole(user, requiredRole)) throw new Error("Unauthorized");',documentationLink:"https://cwe.mitre.org/data/definitions/269.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow privilege escalation patterns in test files"},testFilePattern:{type:["string","null"],default:null,description:"Override which filenames `allowInTests` applies to. Null \u2014 the default \u2014 leaves it to the shared structural predicate."},roleCheckPatterns:{type:"array",items:{type:"string"},default:DEFAULT_ROLE_CHECK_PATTERNS,description:"Role check patterns to recognize"},userInputPatterns:{type:"array",items:{type:"string"},default:[],description:"Additional user input patterns to check (regex strings)"},ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Additional patterns to ignore"},privilegeProperties:{type:"array",items:{type:"string"},default:DEFAULT_PRIVILEGE_PROPERTIES,description:"Property names whose assignment is an authorisation decision, compared case-insensitively as an exact name. Replaces the built-in list."},additionalPrivilegeProperties:{type:"array",items:{type:"string"},default:[],description:"Extra privilege property names, on top of `privilegeProperties`."},privilegeTerms:{type:"array",items:{type:"string"},default:DEFAULT_PRIVILEGE_TERMS,description:"Privilege operations, matched as whole words or whole consecutive phrases of a callee name \u2014 never as a substring. Replaces the built-in list."},additionalPrivilegeTerms:{type:"array",items:{type:"string"},default:[],description:"Extra privilege operation terms, on top of `privilegeTerms`."},barePrivilegeVerbs:{type:"array",items:{type:"string"},default:DEFAULT_BARE_PRIVILEGE_VERBS,description:"Verbs that count only when they are the WHOLE callee name, because their ordinary English sense dominates otherwise. Replaces the built-in list."},additionalBarePrivilegeVerbs:{type:"array",items:{type:"string"},default:[],description:"Extra bare privilege verbs, on top of `barePrivilegeVerbs`."}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,roleCheckPatterns:DEFAULT_ROLE_CHECK_PATTERNS,userInputPatterns:[],ignorePatterns:[],privilegeProperties:DEFAULT_PRIVILEGE_PROPERTIES,additionalPrivilegeProperties:[],privilegeTerms:DEFAULT_PRIVILEGE_TERMS,additionalPrivilegeTerms:[],barePrivilegeVerbs:DEFAULT_BARE_PRIVILEGE_VERBS,additionalBarePrivilegeVerbs:[]}],create(context,[options={}]){const{allowInTests=false,testFilePattern,roleCheckPatterns=DEFAULT_ROLE_CHECK_PATTERNS,userInputPatterns:additionalUserInputPatterns=[],ignorePatterns=[],privilegeProperties=DEFAULT_PRIVILEGE_PROPERTIES,additionalPrivilegeProperties=[],privilegeTerms=DEFAULT_PRIVILEGE_TERMS,additionalPrivilegeTerms=[],barePrivilegeVerbs=DEFAULT_BARE_PRIVILEGE_VERBS,additionalBarePrivilegeVerbs=[]}=options;const privilegeProps=new Set([...privilegeProperties,...additionalPrivilegeProperties].map(name=>name.toLowerCase()));const privilegeOperationTerms=[...privilegeTerms,...additionalPrivilegeTerms];const bareVerbs=new Set([...barePrivilegeVerbs,...additionalBarePrivilegeVerbs]);const isPrivilegeOperationCallee=name=>isPrivilegeOperationName(name,privilegeOperationTerms,bareVerbs);const filename=context.filename;const isTestFile=allowInTests&&(testFilePattern==null?(0,eslint_devkit_2.isTestFilePath)(filename):(0,eslint_devkit_1.compileUserPattern)(testFilePattern).test(filename));const sourceCode=context.sourceCode;const userInputPatterns=[...DEFAULT_USER_INPUT_PATTERNS,...(0,eslint_devkit_1.compileUserPatterns)(additionalUserInputPatterns,"i")];function isRoleChecked(node){return isInsideRoleCheck(node,roleCheckPatterns)||isAfterRoleGuard(node,roleCheckPatterns)}function resolvesToUserInput(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const scope=sourceCode.getScope(node);const reference=scope.references.find(ref=>ref.identifier===node);for(const def of reference?.resolved?.defs??[]){let declarator=def.name;while(declarator&&declarator.type!==eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator){declarator=declarator.parent}if(declarator?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&declarator.init&&containsUserInput(declarator.init,sourceCode,userInputPatterns)){return true}}return false}function isUserControlled(node){return containsUserInput(node,sourceCode,userInputPatterns)||resolvesToUserInput(node)}function checkAssignmentExpression(node){if(isTestFile){return}if(node.left.type==="MemberExpression"){const propertyName=assignedPropertyName(node.left)?.toLowerCase();if(propertyName!==void 0&&privilegeProps.has(propertyName)){const text=sourceCode.getText(node);if(matchesIgnorePattern(text,ignorePatterns)){return}if(isUserControlled(node.right)){if(!isRoleChecked(node)){context.report({node,messageId:"privilegeEscalation",data:{issue:`Role assignment from user input: ${sourceCode.getText(node.left)} = ${sourceCode.getText(node.right)}`}})}}}}}function checkCallExpression(node){if(isTestFile){return}const callee=node.callee;let isPrivilegeOperation=false;let operationName="";if(callee.type==="Identifier"){if(isPrivilegeOperationCallee(callee.name)){isPrivilegeOperation=true;operationName=callee.name}}const method=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type==="MemberExpression"&&method!==null){if(isPrivilegeOperationCallee(method)){isPrivilegeOperation=true;operationName=method.toLowerCase()}}if(isPrivilegeOperation){const text=sourceCode.getText(node);if(matchesIgnorePattern(text,ignorePatterns)){return}for(const arg of node.arguments){if(isUserControlled(arg)){if(!isRoleChecked(node)){context.report({node,messageId:"privilegeEscalation",data:{issue:`Privilege operation (${operationName}) with user input without role validation`}});return}}}}}function checkObjectExpression(node){if(isTestFile)return;for(const prop of node.properties){if(prop.type==="Property"&&prop.key.type==="Identifier"){const keyName=prop.key.name.toLowerCase();if(privilegeProps.has(keyName)){const text=sourceCode.getText(prop);if(matchesIgnorePattern(text,ignorePatterns))continue;if(isUserControlled(prop.value)){if(!isRoleChecked(node)){context.report({node:prop,messageId:"privilegeEscalation",data:{issue:`Role assignment in object from user input: ${sourceCode.getText(prop)}`}})}}}}}}return{AssignmentExpression:checkAssignmentExpression,CallExpression:checkCallExpression,ObjectExpression:checkObjectExpression}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSqlInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const NO_SUBSTITUTIONS=new Map;function substitutionFor(node,scope,substitutions){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return void 0;const variable=resolveVariable(node.name,scope);return variable===null?void 0:substitutions.get(variable)}function hasRawUnattributedPart(node,scope,substitutions){const parts=node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral?[...node.expressions]:[node.left,node.right];return parts.some(part=>{if(part.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;if(part.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||part.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return hasRawUnattributedPart(part,scope,substitutions)}const bound=substitutionFor(part,scope,substitutions);if(bound!==void 0){return bound.node!==null&&!(0,eslint_devkit_1.isStaticExpression)({node:bound.node,scope:bound.scope})}return!(0,eslint_devkit_1.isStaticExpression)({node:part,scope})})}const SQL_DRIVER_MODULES=new Set(["pg","pg-pool","pg-native","pg-cursor","pg-promise","pg-copy-streams","postgres","slonik","@vercel/postgres","@neondatabase/serverless","@electric-sql/pglite","mysql","mysql2","@planetscale/database","sqlite3","better-sqlite3","node:sqlite","bun:sqlite","@libsql/client","typeorm","@nestjs/typeorm","sequelize","sequelize-typescript","@nestjs/sequelize","knex","objection","drizzle-orm","@prisma/client","prisma","kysely","mssql","oracledb"]);function isSqlDriverSpecifier(specifier){if(specifier.startsWith(".")||specifier.startsWith("/"))return false;const parts=specifier.split("/");const root=specifier.startsWith("@")?parts.slice(0,2).join("/"):parts[0];return SQL_DRIVER_MODULES.has(root)}function stringLiteralValue(node){if(node!==void 0&&node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.value==="string"){return node.value}return null}const SQL_SINK_METHODS=["query","execute"];const TRANSPARENT_CALLS=["String"];const QUERY_TEXT_PROPERTIES=["text","sql"];function invokedMethodName(callee,scope){const named=(0,eslint_devkit_1.propertyName)(callee);if(named!==null)return named;if(callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const variable=resolveVariable(callee.property.name,scope);if(variable===null)return null;const init=singleAssignedInit(variable);return init===null?null:stringLiteralValue(init)}const SQL_STATEMENTS=[/^\s*select\b[\s\S]*\bfrom\b/i,/^\s*insert\s+into\b/i,/^\s*update\b[\s\S]*\bset\b/i,/^\s*delete\s+from\b/i,/^\s*replace\s+into\b/i,/^\s*merge\s+into\b/i];function staticText(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.quasis.map(q=>q.value.raw).join("")}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return`${staticText(node.left)}${staticText(node.right)}`}const literal=stringLiteralValue(node);return literal===null?"":literal}function looksLikeSqlStatement(nodes){const text=nodes.map(staticText).join("");return SQL_STATEMENTS.some(pattern=>pattern.test(text))}function isBuiltString(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.expressions.length>0}return node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"}const REQUEST_ROOTS=["req","request","ctx","event"];const REQUEST_PROPERTIES=["query","params","body","headers","cookies","url","path"];function resolveVariable(name,scope){for(let current=scope;current!==null;current=current.upper){const variable=current.set.get(name);if(variable!==void 0)return variable}return null}function singleAssignedInit(variable){const writes=variable.references.filter(ref=>ref.isWrite());if(writes.length!==1)return null;const def=variable.defs.find(d=>d.type==="Variable");if(def===void 0)return null;return def.node.init??null}function isParameterBinding(variable){return variable.defs.some(def=>def.type==="Parameter"&&!bindsADeclaredContract(def))}function bindsADeclaredContract(def){for(let node=def.name;node!==void 0;node=node.parent??void 0){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectPattern&&node.type!==eslint_devkit_1.AST_NODE_TYPES.ArrayPattern&&node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){continue}const annotation=node.typeAnnotation?.typeAnnotation;if(annotation?.type===eslint_devkit_1.AST_NODE_TYPES.TSTypeReference)return true}return false}function allWritesStatic(variable,scope){const writes=writeExpressions(variable);if(writes.length===0)return false;return writes.every(node=>(0,eslint_devkit_1.isStaticExpression)({node,scope}))}function writeExpressions(variable){const written=[];for(const reference of variable.references){const{writeExpr}=reference;if(reference.isWrite()&&writeExpr!==void 0&&writeExpr!==null){written.push(writeExpr)}}return written}function isLocallyConstructed(variable,scope){if(variable===null)return false;const init=singleAssignedInit(variable);if(init===null)return false;return init.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression||(0,eslint_devkit_1.isStaticExpression)({node:init,scope})}function isAmbientGlobal(name,scope){const variable=resolveVariable(name,scope);return variable===null||variable.defs.length===0}function attributedThroughCall(node,scope,attribution,depth){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&attribution.transparentCalls.has(node.callee.name)&&isAmbientGlobal(node.callee.name,scope)){for(const argument of node.arguments){if(argument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)continue;const found=attributedSource(argument,scope,attribution,depth+1);if(found!==null)return found}return null}const inlined=effectiveExpression(node,scope,attribution);if(inlined.nodes.length===1&&inlined.nodes[0]===node)return null;const inner={...attribution,substitutions:inlined.substitutions};for(const candidate of inlined.nodes){const found=attributedSource(candidate,inlined.scope,inner,depth+1);if(found!==null)return found}return null}function attributedSource(node,scope,attribution,depth=0){if(depth>5)return null;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return attributedSource(bare,scope,attribution,depth+1);if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){for(const expression of node.expressions){const found=attributedSource(expression,scope,attribution,depth+1);if(found!==null)return found}return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return attributedSource(node.left,scope,attribution,depth+1)??attributedSource(node.right,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){let root=node;const properties=[];while(root.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){if(root.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){properties.unshift(root.property.name)}root=root.object}if(root.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;if(isLocallyConstructed(resolveVariable(root.name,scope),scope))return null;if(!properties.some(property=>attribution.requestProperties.has(property))){return null}if(attribution.requestRoots.has(root.name)||attribution.trustRequestShape&&(0,eslint_devkit_1.readsRequestShape)(node,attribution.sourceCode)){return`${root.name}.${properties.join(".")}`}return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){return attributedSource(node.consequent,scope,attribution,depth+1)??attributedSource(node.alternate,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.LogicalExpression){return attributedSource(node.left,scope,attribution,depth+1)??attributedSource(node.right,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){return attributedThroughCall(node,scope,attribution,depth)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=resolveVariable(node.name,scope);if(variable===null)return null;const bound=attribution.substitutions.get(variable);if(bound!==void 0){return bound.node===null?null:attributedSource(bound.node,bound.scope,{...attribution,substitutions:NO_SUBSTITUTIONS},depth+1)}const writes=writeExpressions(variable);for(const write of writes){const found=attributedSource(write,scope,attribution,depth+1);if(found!==null)return found}if(attribution.untrustedParameters&&isParameterBinding(variable)&&!allWritesStatic(variable,scope)&&!isNarrowedByGuardClause(node.name,node,attribution.sourceCode)){return`${node.name} (a caller-supplied parameter)`}return null}return null}function isNarrowedByGuardClause(name,node,sourceCode){let fn=node;while(fn.parent!==void 0&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression){fn=fn.parent}const body=fn.body;if(body===void 0||body.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement)return false;for(const statement of body.body){if(statement.range[0]>=node.range[0])break;if(statement.type!==eslint_devkit_1.AST_NODE_TYPES.IfStatement)continue;const leaves=consequent=>{if(consequent.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement)return true;if(consequent.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)return true;if(consequent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){return consequent.body.some(inner=>inner.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement||inner.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)}return false};if(!leaves(statement.consequent))continue;const test=statement.test;if(test.type!==eslint_devkit_1.AST_NODE_TYPES.UnaryExpression||test.operator!=="!")continue;const call=test.argument;if(call.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)continue;if(call.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)continue;const method=call.callee.property;if(method.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||method.name!=="has"&&method.name!=="includes"){continue}const[checked]=call.arguments;if(checked?.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||checked.name!==name)continue;const receiver=call.callee.object;if(receiver.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)continue;let search=sourceCode.getScope(node);let declared;while(search!==null&&declared===void 0){declared=search.variables.find(v=>v.name===receiver.name);search=search.upper}const source=declared?.defs[0]?.node.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator?declared.defs[0].node.init:void 0;if(source===void 0||source===null)continue;const listOf=init=>{if(init.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression)return[...init.elements].filter(Boolean);if(init.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression&&init.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&init.callee.name==="Set"&&init.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){return[...init.arguments[0].elements].filter(Boolean)}return void 0};const members=listOf(source);if(members===void 0||members.length===0)continue;if(members.every(el=>el.type===eslint_devkit_1.AST_NODE_TYPES.Literal))return true}return false}function effectiveExpression(node,scope,attribution,depth=0){const unresolved={nodes:[node],scope,substitutions:NO_SUBSTITUTIONS};if(depth>5)return unresolved;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node){return effectiveExpression(bare,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression){return effectiveExpression(node.argument,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const joined=joinedArrayElements(node,scope);if(joined!==null){return{nodes:joined,scope,substitutions:NO_SUBSTITUTIONS}}return resolveBuilderCall(node,scope,attribution)??unresolved}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){const text=queryTextProperty(node,attribution.queryTextProperties);return text===null?unresolved:effectiveExpression(text,scope,attribution,depth+1)}if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return unresolved;const variable=resolveVariable(node.name,scope);if(variable===null)return unresolved;const writes=writeExpressions(variable);if(writes.length===0)return unresolved;if(writes.length===1){return effectiveExpression(writes[0],scope,attribution,depth+1)}return{nodes:writes,scope,substitutions:NO_SUBSTITUTIONS}}function resolveBuilderCall(node,scope,attribution){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const impl=resolveLocalFunction(node.callee.name,scope);if(impl===null)return null;const returned=returnedExpression(impl);if(returned===null||returned.type!==eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&returned.type!==eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){return null}const bindings=bindParameters(impl,node.arguments,scope,attribution.sourceCode);if(bindings===null)return null;return{nodes:[returned],scope:attribution.sourceCode.getScope(returned),substitutions:bindings}}function resolveLocalFunction(name,scope){const variable=resolveVariable(name,scope);if(variable===null)return null;const declared=variable.defs.find(def=>def.type==="FunctionName");if(declared!==void 0){return declared.node}const init=singleAssignedInit(variable);if(init!==null&&(init.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression)){return init}return null}function returnedExpression(impl){if(impl.body.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement)return impl.body;const[only]=impl.body.body;if(impl.body.body.length!==1||only?.type!==eslint_devkit_1.AST_NODE_TYPES.ReturnStatement){return null}return only.argument??null}function joinedArrayElements(node,scope){const{callee}=node;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return null}if((0,eslint_devkit_1.propertyName)(callee)!=="join"){return null}let receiver=callee.object;if(receiver.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=resolveVariable(receiver.name,scope);const init=variable===null?null:singleAssignedInit(variable);if(init===null)return null;receiver=init}if(receiver.type!==eslint_devkit_1.AST_NODE_TYPES.ArrayExpression)return null;const elements=[];for(const element of receiver.elements){if(element===null||element.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){continue}elements.push(element)}return elements}function queryTextProperty(node,names){for(const property of node.properties){if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property||property.computed)continue;const key=property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?property.key.name:stringLiteralValue(property.key);if(key!==null&&names.has(key))return property.value}return null}function bindParameters(impl,args,callerScope,sourceCode){if(args.some(a=>a.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement))return null;if(impl.params.some(p=>p.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier))return null;const bindings=new Map;sourceCode.getDeclaredVariables(impl).filter(variable=>isParameterBinding(variable)).forEach((variable,index)=>{bindings.set(variable,{node:args[index]??null,scope:callerScope})});return bindings}exports.noSqlInjection=(0,eslint_devkit_1.createRule)({name:"no-sql-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-sql-injection.md",description:"Prevent SQL injection when a query is built from attacker-controlled input and executed through a driver-agnostic handle",cwe:"CWE-89",cvss:9.8,confidence:"high"},messages:{sqlInjection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"SQL Injection Risk",cwe:"CWE-89",owasp:"A03:2021",cvss:9.8,description:'SQL statement built from "{{source}}" and executed. An attacker controls part of the statement text.',severity:"CRITICAL",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"high",fix:"Pass the value as a bound parameter (`$1` / `?`) instead of concatenating it into the statement.",documentationLink:"https://owasp.org/www-community/attacks/SQL_Injection"})},schema:[{type:"object",properties:{reportUnattributedInterpolation:{type:"boolean",default:false,description:"Report SQL built by interpolation even when the interpolated value cannot be traced to a request in this file (a property of `this`, a property of a non-request object, a helper return). Parameterise either way. Set false to report only attributable taint."},treatParametersAsUntrusted:{type:"boolean",default:true,description:"Treat a function parameter spliced into statement text as an untrusted inlet \u2014 nothing in this file constrains what a caller passes. Set false to report only values traceable to a request within the linted file."},requestRoots:{type:"array",items:{type:"string"},default:[...REQUEST_ROOTS],description:"Identifier roots that denote an inbound request. Matched exactly."},requestProperties:{type:"array",items:{type:"string"},default:[...REQUEST_PROPERTIES],description:"Request properties that carry caller-supplied data. Matched exactly."},sinkMethods:{type:"array",items:{type:"string"},default:[...SQL_SINK_METHODS],description:"Method names that execute a raw SQL string. Matched exactly against the called member name."},queryTextProperties:{type:"array",items:{type:"string"},default:[...QUERY_TEXT_PROPERTIES],description:"Properties of a driver query-config object that hold the statement text. Matched exactly."},transparentCalls:{type:"array",items:{type:"string"},default:[...TRANSPARENT_CALLS],description:"Ambient global calls that pass their argument through unchanged, so taint survives them. Matched exactly, and only when the file declares no binding of that name."}},additionalProperties:false}]},defaultOptions:[{reportUnattributedInterpolation:false,treatParametersAsUntrusted:true,requestRoots:REQUEST_ROOTS,requestProperties:REQUEST_PROPERTIES,sinkMethods:SQL_SINK_METHODS,transparentCalls:TRANSPARENT_CALLS,queryTextProperties:QUERY_TEXT_PROPERTIES}],create(context,[options={}]){const{reportUnattributedInterpolation=false,treatParametersAsUntrusted=true,requestRoots=REQUEST_ROOTS,requestProperties=REQUEST_PROPERTIES,sinkMethods=SQL_SINK_METHODS,transparentCalls=TRANSPARENT_CALLS,queryTextProperties=QUERY_TEXT_PROPERTIES}=options;const attribution={substitutions:NO_SUBSTITUTIONS,untrustedParameters:treatParametersAsUntrusted,requestRoots:new Set(requestRoots),trustRequestShape:requestRoots.length===REQUEST_ROOTS.length&&REQUEST_ROOTS.every((name,index)=>requestRoots[index]===name),requestProperties:new Set(requestProperties),transparentCalls:new Set(transparentCalls),queryTextProperties:new Set(queryTextProperties),sourceCode:context.sourceCode};const sinks=new Set(sinkMethods);const pending=[];let importsSqlDriver=false;const noteSpecifier=specifier=>{if(specifier!==null&&isSqlDriverSpecifier(specifier)){importsSqlDriver=true}};return{ImportDeclaration(node){noteSpecifier(node.source.value)},ImportExpression(node){noteSpecifier(stringLiteralValue(node.source))},TSImportEqualsDeclaration(node){if(node.moduleReference.type===eslint_devkit_1.AST_NODE_TYPES.TSExternalModuleReference){noteSpecifier(stringLiteralValue(node.moduleReference.expression))}},CallExpression(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="require"){noteSpecifier(stringLiteralValue(node.arguments[0]));return}if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;const callScope=context.sourceCode.getScope(node);const method=invokedMethodName(node.callee,callScope);if(method===null||!sinks.has(method))return;const[firstArgument]=node.arguments;if(firstArgument===void 0||firstArgument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){return}const{nodes,scope,substitutions}=effectiveExpression(firstArgument,callScope,attribution);const built=nodes.some(isBuiltString)||nodes.length>1&&nodes.some(n=>!(0,eslint_devkit_1.isStaticExpression)({node:n,scope}));if(!built)return;if(!looksLikeSqlStatement(nodes))return;const sinkAttribution={...attribution,substitutions};for(const candidate of nodes){const source=attributedSource(candidate,scope,sinkAttribution);if(source!==null){pending.push({node,source});return}}if(reportUnattributedInterpolation&&nodes.some(n=>(n.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral||n.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression)&&hasRawUnattributedPart(n,scope,substitutions))){pending.push({node,source:"a value this file cannot attribute"})}},"Program:exit"(){if(importsSqlDriver)return;for(const finding of pending){context.report({node:finding.node,messageId:"sqlInjection",data:{source:finding.source}})}}}}});exports.default=exports.noSqlInjection;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSqlInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const NO_SUBSTITUTIONS=new Map;function substitutionFor(node,scope,substitutions){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return void 0;const variable=resolveVariable(node.name,scope);return variable===null?void 0:substitutions.get(variable)}function hasRawUnattributedPart(node,scope,substitutions){const parts=node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral?[...node.expressions]:[node.left,node.right];return parts.some(part=>{if(part.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;if(part.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||part.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return hasRawUnattributedPart(part,scope,substitutions)}const bound=substitutionFor(part,scope,substitutions);if(bound!==void 0){return bound.node!==null&&!(0,eslint_devkit_1.isStaticExpression)({node:bound.node,scope:bound.scope})}return!(0,eslint_devkit_1.isStaticExpression)({node:part,scope})})}const SQL_DRIVER_MODULES=new Set(["pg","pg-pool","pg-native","pg-cursor","pg-promise","pg-copy-streams","postgres","slonik","@vercel/postgres","@neondatabase/serverless","@electric-sql/pglite","mysql","mysql2","@planetscale/database","sqlite3","better-sqlite3","node:sqlite","bun:sqlite","@libsql/client","typeorm","@nestjs/typeorm","sequelize","sequelize-typescript","@nestjs/sequelize","knex","objection","drizzle-orm","@prisma/client","prisma","kysely","mssql","oracledb"]);function isSqlDriverSpecifier(specifier){if(specifier.startsWith(".")||specifier.startsWith("/"))return false;const parts=specifier.split("/");const root=specifier.startsWith("@")?parts.slice(0,2).join("/"):parts[0];return SQL_DRIVER_MODULES.has(root)}function stringLiteralValue(node){if(node!==void 0&&node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.value==="string"){return node.value}return null}const SQL_SINK_METHODS=["query","execute"];const TRANSPARENT_CALLS=["String"];const QUERY_TEXT_PROPERTIES=["text","sql"];function invokedMethodName(callee,scope){const named=(0,eslint_devkit_1.propertyName)(callee);if(named!==null)return named;if(callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const variable=resolveVariable(callee.property.name,scope);if(variable===null)return null;const init=singleAssignedInit(variable);return init===null?null:stringLiteralValue(init)}const SQL_STATEMENTS=[/^\s*select\b[\s\S]*\bfrom\b/i,/^\s*insert\s+into\b/i,/^\s*update\b[\s\S]*\bset\b/i,/^\s*delete\s+from\b/i,/^\s*replace\s+into\b/i,/^\s*merge\s+into\b/i];function staticText(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.quasis.map(q=>q.value.raw).join("")}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return`${staticText(node.left)}${staticText(node.right)}`}const literal=stringLiteralValue(node);return literal===null?"":literal}function looksLikeSqlStatement(nodes){const text=nodes.map(staticText).join("");return SQL_STATEMENTS.some(pattern=>pattern.test(text))}function isBuiltString(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.expressions.length>0}return node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"}const REQUEST_ROOTS=["req","request","ctx","event"];const REQUEST_PROPERTIES=["query","params","body","headers","cookies","url","path"];function resolveVariable(name,scope){for(let current=scope;current!==null;current=current.upper){const variable=current.set.get(name);if(variable!==void 0)return variable}return null}function singleAssignedInit(variable){const writes=variable.references.filter(ref=>ref.isWrite());if(writes.length!==1)return null;const def=variable.defs.find(d=>d.type==="Variable");if(def===void 0)return null;return def.node.init??null}function isParameterBinding(variable){return variable.defs.some(def=>def.type==="Parameter"&&!bindsADeclaredContract(def))}function bindsADeclaredContract(def){for(let node=def.name;node!==void 0;node=node.parent??void 0){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectPattern&&node.type!==eslint_devkit_1.AST_NODE_TYPES.ArrayPattern&&node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){continue}const annotation=node.typeAnnotation?.typeAnnotation;if(annotation?.type===eslint_devkit_1.AST_NODE_TYPES.TSTypeReference)return true}return false}function allWritesStatic(variable,scope){const writes=writeExpressions(variable);if(writes.length===0)return false;return writes.every(node=>(0,eslint_devkit_1.isStaticExpression)({node,scope}))}function writeExpressions(variable){const written=[];for(const reference of variable.references){const{writeExpr}=reference;if(reference.isWrite()&&writeExpr!==void 0&&writeExpr!==null){written.push(writeExpr)}}return written}function isLocallyConstructed(variable,scope){if(variable===null)return false;const init=singleAssignedInit(variable);if(init===null)return false;return init.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression||(0,eslint_devkit_1.isStaticExpression)({node:init,scope})}function isAmbientGlobal(name,scope){const variable=resolveVariable(name,scope);return variable===null||variable.defs.length===0}function attributedThroughCall(node,scope,attribution,depth){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&attribution.transparentCalls.has(node.callee.name)&&isAmbientGlobal(node.callee.name,scope)){for(const argument of node.arguments){if(argument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)continue;const found=attributedSource(argument,scope,attribution,depth+1);if(found!==null)return found}return null}const inlined=effectiveExpression(node,scope,attribution);if(inlined.nodes.length===1&&inlined.nodes[0]===node)return null;const inner={...attribution,substitutions:inlined.substitutions};for(const candidate of inlined.nodes){const found=attributedSource(candidate,inlined.scope,inner,depth+1);if(found!==null)return found}return null}function attributedSource(node,scope,attribution,depth=0){if(depth>5)return null;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return attributedSource(bare,scope,attribution,depth+1);if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){for(const expression of node.expressions){const found=attributedSource(expression,scope,attribution,depth+1);if(found!==null)return found}return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return attributedSource(node.left,scope,attribution,depth+1)??attributedSource(node.right,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){let root=node;const properties=[];while(root.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const segment=(0,eslint_devkit_1.propertyName)(root);if(segment!==null){properties.unshift(segment)}root=root.object}if(root.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;if(isLocallyConstructed(resolveVariable(root.name,scope),scope))return null;if(!properties.some(property=>attribution.requestProperties.has(property))){return null}if(attribution.requestRoots.has(root.name)||attribution.trustRequestShape&&(0,eslint_devkit_1.readsRequestShape)(node,attribution.sourceCode)){return`${root.name}.${properties.join(".")}`}return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){return attributedSource(node.consequent,scope,attribution,depth+1)??attributedSource(node.alternate,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.LogicalExpression){return attributedSource(node.left,scope,attribution,depth+1)??attributedSource(node.right,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){return attributedThroughCall(node,scope,attribution,depth)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=resolveVariable(node.name,scope);if(variable===null)return null;const bound=attribution.substitutions.get(variable);if(bound!==void 0){return bound.node===null?null:attributedSource(bound.node,bound.scope,{...attribution,substitutions:NO_SUBSTITUTIONS},depth+1)}const writes=writeExpressions(variable);for(const write of writes){const found=attributedSource(write,scope,attribution,depth+1);if(found!==null)return found}if(attribution.untrustedParameters&&isParameterBinding(variable)&&!allWritesStatic(variable,scope)&&!isNarrowedByGuardClause(node.name,node,attribution.sourceCode)){return`${node.name} (a caller-supplied parameter)`}return null}return null}function isNarrowedByGuardClause(name,node,sourceCode){let fn=node;while(fn.parent!==void 0&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression){fn=fn.parent}const body=fn.body;if(body===void 0||body.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement)return false;for(const statement of body.body){if(statement.range[0]>=node.range[0])break;if(statement.type!==eslint_devkit_1.AST_NODE_TYPES.IfStatement)continue;const leaves=consequent=>{if(consequent.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement)return true;if(consequent.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)return true;if(consequent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){return consequent.body.some(inner=>inner.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement||inner.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)}return false};if(!leaves(statement.consequent))continue;const test=statement.test;if(test.type!==eslint_devkit_1.AST_NODE_TYPES.UnaryExpression||test.operator!=="!")continue;const call=test.argument;if(call.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)continue;if(call.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)continue;const method=call.callee.property;if(method.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||method.name!=="has"&&method.name!=="includes"){continue}const[checked]=call.arguments;if(checked?.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||checked.name!==name)continue;const receiver=call.callee.object;if(receiver.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)continue;let search=sourceCode.getScope(node);let declared;while(search!==null&&declared===void 0){declared=search.variables.find(v=>v.name===receiver.name);search=search.upper}const source=declared?.defs[0]?.node.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator?declared.defs[0].node.init:void 0;if(source===void 0||source===null)continue;const listOf=init=>{if(init.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression)return[...init.elements].filter(Boolean);if(init.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression&&init.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&init.callee.name==="Set"&&init.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){return[...init.arguments[0].elements].filter(Boolean)}return void 0};const members=listOf(source);if(members===void 0||members.length===0)continue;if(members.every(el=>el.type===eslint_devkit_1.AST_NODE_TYPES.Literal))return true}return false}function effectiveExpression(node,scope,attribution,depth=0){const unresolved={nodes:[node],scope,substitutions:NO_SUBSTITUTIONS};if(depth>5)return unresolved;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node){return effectiveExpression(bare,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression){return effectiveExpression(node.argument,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const joined=joinedArrayElements(node,scope);if(joined!==null){return{nodes:joined,scope,substitutions:NO_SUBSTITUTIONS}}return resolveBuilderCall(node,scope,attribution)??unresolved}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){const text=queryTextProperty(node,attribution.queryTextProperties);return text===null?unresolved:effectiveExpression(text,scope,attribution,depth+1)}if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return unresolved;const variable=resolveVariable(node.name,scope);if(variable===null)return unresolved;const writes=writeExpressions(variable);if(writes.length===0)return unresolved;if(writes.length===1){return effectiveExpression(writes[0],scope,attribution,depth+1)}return{nodes:writes,scope,substitutions:NO_SUBSTITUTIONS}}function resolveBuilderCall(node,scope,attribution){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const impl=resolveLocalFunction(node.callee.name,scope);if(impl===null)return null;const returned=returnedExpression(impl);if(returned===null||returned.type!==eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&returned.type!==eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){return null}const bindings=bindParameters(impl,node.arguments,scope,attribution.sourceCode);if(bindings===null)return null;return{nodes:[returned],scope:attribution.sourceCode.getScope(returned),substitutions:bindings}}function resolveLocalFunction(name,scope){const variable=resolveVariable(name,scope);if(variable===null)return null;const declared=variable.defs.find(def=>def.type==="FunctionName");if(declared!==void 0){return declared.node}const init=singleAssignedInit(variable);if(init!==null&&(init.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression)){return init}return null}function returnedExpression(impl){if(impl.body.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement)return impl.body;const[only]=impl.body.body;if(impl.body.body.length!==1||only?.type!==eslint_devkit_1.AST_NODE_TYPES.ReturnStatement){return null}return only.argument??null}function joinedArrayElements(node,scope){const{callee}=node;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return null}if((0,eslint_devkit_1.propertyName)(callee)!=="join"){return null}let receiver=callee.object;if(receiver.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=resolveVariable(receiver.name,scope);const init=variable===null?null:singleAssignedInit(variable);if(init===null)return null;receiver=init}if(receiver.type!==eslint_devkit_1.AST_NODE_TYPES.ArrayExpression)return null;const elements=[];for(const element of receiver.elements){if(element===null||element.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){continue}elements.push(element)}return elements}function queryTextProperty(node,names){for(const property of node.properties){if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property||property.computed)continue;const key=property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?property.key.name:stringLiteralValue(property.key);if(key!==null&&names.has(key))return property.value}return null}function bindParameters(impl,args,callerScope,sourceCode){if(args.some(a=>a.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement))return null;if(impl.params.some(p=>p.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier))return null;const bindings=new Map;sourceCode.getDeclaredVariables(impl).filter(variable=>isParameterBinding(variable)).forEach((variable,index)=>{bindings.set(variable,{node:args[index]??null,scope:callerScope})});return bindings}exports.noSqlInjection=(0,eslint_devkit_1.createRule)({name:"no-sql-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-sql-injection.md",description:"Prevent SQL injection when a query is built from attacker-controlled input and executed through a driver-agnostic handle",cwe:"CWE-89",cvss:9.8,confidence:"high"},messages:{sqlInjection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"SQL Injection Risk",cwe:"CWE-89",owasp:"A03:2021",cvss:9.8,description:'SQL statement built from "{{source}}" and executed. An attacker controls part of the statement text.',severity:"CRITICAL",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"high",fix:"Pass the value as a bound parameter (`$1` / `?`) instead of concatenating it into the statement.",documentationLink:"https://owasp.org/www-community/attacks/SQL_Injection"})},schema:[{type:"object",properties:{reportUnattributedInterpolation:{type:"boolean",default:false,description:"Report SQL built by interpolation even when the interpolated value cannot be traced to a request in this file (a property of `this`, a property of a non-request object, a helper return). Parameterise either way. Set false to report only attributable taint."},treatParametersAsUntrusted:{type:"boolean",default:true,description:"Treat a function parameter spliced into statement text as an untrusted inlet \u2014 nothing in this file constrains what a caller passes. Set false to report only values traceable to a request within the linted file."},requestRoots:{type:"array",items:{type:"string"},default:[...REQUEST_ROOTS],description:"Identifier roots that denote an inbound request. Matched exactly."},requestProperties:{type:"array",items:{type:"string"},default:[...REQUEST_PROPERTIES],description:"Request properties that carry caller-supplied data. Matched exactly."},sinkMethods:{type:"array",items:{type:"string"},default:[...SQL_SINK_METHODS],description:"Method names that execute a raw SQL string. Matched exactly against the called member name."},queryTextProperties:{type:"array",items:{type:"string"},default:[...QUERY_TEXT_PROPERTIES],description:"Properties of a driver query-config object that hold the statement text. Matched exactly."},transparentCalls:{type:"array",items:{type:"string"},default:[...TRANSPARENT_CALLS],description:"Ambient global calls that pass their argument through unchanged, so taint survives them. Matched exactly, and only when the file declares no binding of that name."}},additionalProperties:false}]},defaultOptions:[{reportUnattributedInterpolation:false,treatParametersAsUntrusted:true,requestRoots:REQUEST_ROOTS,requestProperties:REQUEST_PROPERTIES,sinkMethods:SQL_SINK_METHODS,transparentCalls:TRANSPARENT_CALLS,queryTextProperties:QUERY_TEXT_PROPERTIES}],create(context,[options={}]){const{reportUnattributedInterpolation=false,treatParametersAsUntrusted=true,requestRoots=REQUEST_ROOTS,requestProperties=REQUEST_PROPERTIES,sinkMethods=SQL_SINK_METHODS,transparentCalls=TRANSPARENT_CALLS,queryTextProperties=QUERY_TEXT_PROPERTIES}=options;const attribution={substitutions:NO_SUBSTITUTIONS,untrustedParameters:treatParametersAsUntrusted,requestRoots:new Set(requestRoots),trustRequestShape:requestRoots.length===REQUEST_ROOTS.length&&REQUEST_ROOTS.every((name,index)=>requestRoots[index]===name),requestProperties:new Set(requestProperties),transparentCalls:new Set(transparentCalls),queryTextProperties:new Set(queryTextProperties),sourceCode:context.sourceCode};const sinks=new Set(sinkMethods);const pending=[];let importsSqlDriver=false;const noteSpecifier=specifier=>{if(specifier!==null&&isSqlDriverSpecifier(specifier)){importsSqlDriver=true}};return{ImportDeclaration(node){noteSpecifier(node.source.value)},ImportExpression(node){noteSpecifier(stringLiteralValue(node.source))},TSImportEqualsDeclaration(node){if(node.moduleReference.type===eslint_devkit_1.AST_NODE_TYPES.TSExternalModuleReference){noteSpecifier(stringLiteralValue(node.moduleReference.expression))}},CallExpression(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="require"){noteSpecifier(stringLiteralValue(node.arguments[0]));return}if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;const callScope=context.sourceCode.getScope(node);const method=invokedMethodName(node.callee,callScope);if(method===null||!sinks.has(method))return;const[firstArgument]=node.arguments;if(firstArgument===void 0||firstArgument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){return}const{nodes,scope,substitutions}=effectiveExpression(firstArgument,callScope,attribution);const built=nodes.some(isBuiltString)||nodes.length>1&&nodes.some(n=>!(0,eslint_devkit_1.isStaticExpression)({node:n,scope}));if(!built)return;if(!looksLikeSqlStatement(nodes))return;const sinkAttribution={...attribution,substitutions};for(const candidate of nodes){const source=attributedSource(candidate,scope,sinkAttribution);if(source!==null){pending.push({node,source});return}}if(reportUnattributedInterpolation&&nodes.some(n=>(n.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral||n.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression)&&hasRawUnattributedPart(n,scope,substitutions))){pending.push({node,source:"a value this file cannot attribute"})}},"Program:exit"(){if(importsSqlDriver)return;for(const finding of pending){context.report({node:finding.node,messageId:"sqlInjection",data:{source:finding.source}})}}}}});exports.default=exports.noSqlInjection;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noTemplateInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const TEMPLATE_COMPILE_METHODS=new Set(["compile","precompile","create","parse","template"]);const TEMPLATE_RENDER_METHODS=new Set(["render","renderFile","renderString","renderToString","renderTemplate"]);const ALL_TEMPLATE_METHODS=new Set([...TEMPLATE_COMPILE_METHODS,...TEMPLATE_RENDER_METHODS]);const DEFAULT_TEMPLATE_ENGINES=["Handlebars","handlebars","ejs","pug","jade","mustache","Mustache","nunjucks","swig","dust","Dust","doT","consolidate"];const DEFAULT_REQUEST_ROOTS=["req","request","ctx","event","message"];const DEFAULT_REQUEST_PROPERTIES=["query","params","body","headers","url","path","cookies","data"];const READER_METHODS=new Set(["readFile","readFileSync","text","json","arrayBuffer","formData","blob"]);const DEFAULT_UNTRUSTED_NAME_WORDS=["user","untrusted","attacker","external","remote","client","payload","input"];function nameStatesUntrusted(name,vocabulary){const words=name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/);return words.some(word=>vocabulary.untrustedNameWords.has(word))}function untrustedSource(node,vocabulary,depth=0){if(depth>6)return null;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return untrustedSource(bare,vocabulary,depth+1);if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return nameStatesUntrusted(node.name,vocabulary)?node.name:null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){for(const expression of node.expressions){const found=untrustedSource(expression,vocabulary,depth+1);if(found!==null)return found}return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return untrustedSource(node.left,vocabulary,depth+1)??untrustedSource(node.right,vocabulary,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression){return untrustedSource(node.argument,vocabulary,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){let root=node;const properties=[];while(root.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noTemplateInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const TEMPLATE_COMPILE_METHODS=new Set(["compile","precompile","create","parse","template"]);const TEMPLATE_RENDER_METHODS=new Set(["render","renderFile","renderString","renderToString","renderTemplate"]);const ALL_TEMPLATE_METHODS=new Set([...TEMPLATE_COMPILE_METHODS,...TEMPLATE_RENDER_METHODS]);const DEFAULT_TEMPLATE_ENGINES=["Handlebars","handlebars","ejs","pug","jade","mustache","Mustache","nunjucks","swig","dust","Dust","doT","consolidate"];const DEFAULT_REQUEST_ROOTS=["req","request","ctx","event","message"];const DEFAULT_REQUEST_PROPERTIES=["query","params","body","headers","url","path","cookies","data"];const READER_METHODS=new Set(["readFile","readFileSync","text","json","arrayBuffer","formData","blob"]);const DEFAULT_UNTRUSTED_NAME_WORDS=["user","untrusted","attacker","external","remote","client","payload","input"];function nameStatesUntrusted(name,vocabulary){const words=name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/);return words.some(word=>vocabulary.untrustedNameWords.has(word))}function untrustedSource(node,vocabulary,depth=0){if(depth>6)return null;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return untrustedSource(bare,vocabulary,depth+1);if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return nameStatesUntrusted(node.name,vocabulary)?node.name:null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){for(const expression of node.expressions){const found=untrustedSource(expression,vocabulary,depth+1);if(found!==null)return found}return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return untrustedSource(node.left,vocabulary,depth+1)??untrustedSource(node.right,vocabulary,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression){return untrustedSource(node.argument,vocabulary,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){let root=node;const properties=[];while(root.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const segment=(0,eslint_devkit_1.propertyName)(root);if(segment!==null){properties.unshift(segment)}root=root.object}if(root.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const chain=[root.name,...properties].join(".");if(vocabulary.requestRoots.has(root.name)&&properties.some(property=>vocabulary.requestProperties.has(property))){return chain}if(root.name==="process"&&properties[0]==="argv")return"process.argv";return[root.name,...properties].some(part=>nameStatesUntrusted(part,vocabulary))?chain:null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),READER_METHODS)){return(0,eslint_devkit_1.propertyName)(callee)}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&READER_METHODS.has(callee.name)){return callee.name}for(const argument of node.arguments){if(argument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)continue;const found=untrustedSource(argument,vocabulary,depth+1);if(found!==null)return found}return null}return null}exports.noTemplateInjection=(0,eslint_devkit_1.createRule)({name:"no-template-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-template-injection.md",description:"Disallow dynamic strings as template arguments to server-side template engines (CWE-94)",cwe:"CWE-94",cvss:9.8},messages:{templateInjection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Template Injection (CWE-94)",cwe:"CWE-94",description:"{{engine}}.{{method}}() receives a dynamic string. An attacker who controls the template can execute arbitrary server-side code.",severity:"CRITICAL",fix:"Pass only string literals as templates. If the template must vary, load it from a trusted file system path, never from user input.",documentationLink:"https://portswigger.net/web-security/server-side-template-injection"})},schema:[{type:"object",properties:{templateEngines:{type:"array",items:{type:"string"},default:DEFAULT_TEMPLATE_ENGINES,description:"Receiver names that denote a server-side template engine, compared as an exact identifier name and never as a substring. Replaces the built-in list."},additionalTemplateEngines:{type:"array",items:{type:"string"},default:[],description:"Extra template-engine receiver names, on top of `templateEngines` \u2014 an alias import such as `hbs` belongs here."},requestRoots:{type:"array",items:{type:"string"},default:DEFAULT_REQUEST_ROOTS,description:"Identifier roots that denote an inbound request, matched as the exact ROOT of a member chain. Replaces the built-in list."},additionalRequestRoots:{type:"array",items:{type:"string"},default:[],description:"Extra request-object root names, on top of `requestRoots`."},requestProperties:{type:"array",items:{type:"string"},default:DEFAULT_REQUEST_PROPERTIES,description:"Request properties that carry caller-supplied data, matched as a whole segment of the member chain. Replaces the built-in list."},additionalRequestProperties:{type:"array",items:{type:"string"},default:[],description:"Extra request properties, on top of `requestProperties` \u2014 hapi's `request.payload` belongs here."},untrustedNameWords:{type:"array",items:{type:"string"},default:DEFAULT_UNTRUSTED_NAME_WORDS,description:"Words with which an author states a value came from outside, compared as a WHOLE word of the split identifier and never as a substring. Replaces the built-in list."},additionalUntrustedNameWords:{type:"array",items:{type:"string"},default:[],description:"Extra untrusted-provenance words, on top of `untrustedNameWords`."}},additionalProperties:false}]},defaultOptions:[{templateEngines:DEFAULT_TEMPLATE_ENGINES,additionalTemplateEngines:[],requestRoots:DEFAULT_REQUEST_ROOTS,additionalRequestRoots:[],requestProperties:DEFAULT_REQUEST_PROPERTIES,additionalRequestProperties:[],untrustedNameWords:DEFAULT_UNTRUSTED_NAME_WORDS,additionalUntrustedNameWords:[]}],create(context){const options=context.options[0]??{};const engines=new Set([...options.templateEngines??DEFAULT_TEMPLATE_ENGINES,...options.additionalTemplateEngines??[]]);const vocabulary={requestRoots:new Set([...options.requestRoots??DEFAULT_REQUEST_ROOTS,...options.additionalRequestRoots??[]]),requestProperties:new Set([...options.requestProperties??DEFAULT_REQUEST_PROPERTIES,...options.additionalRequestProperties??[]]),untrustedNameWords:new Set([...options.untrustedNameWords??DEFAULT_UNTRUSTED_NAME_WORDS,...options.additionalUntrustedNameWords??[]])};return{CallExpression(node){const{callee,arguments:args}=node;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;const{object}=callee;if(object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;const methodName=(0,eslint_devkit_1.propertyName)(callee);if(methodName===null)return;const engineName=object.name;if(!engines.has(engineName))return;if(!ALL_TEMPLATE_METHODS.has(methodName))return;const firstArg=args[0];if(!firstArg)return;if(firstArg.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof firstArg.value==="string")return;if(firstArg.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&firstArg.expressions.length===0)return;if(untrustedSource(firstArg,vocabulary)===null)return;context.report({node:firstArg,messageId:"templateInjection",data:{engine:engineName,method:methodName}})}}}});
|