eslint-plugin-secure-coding 5.1.4 → 5.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +56 -59
- package/package.json +2 -2
- package/src/index.js +1 -1
- package/src/rules/detect-non-literal-regexp/index.js +1 -1
- package/src/rules/detect-object-injection/index.js +1 -1
- package/src/rules/detect-weak-password-validation/index.js +1 -1
- package/src/rules/no-directive-injection/index.js +1 -1
- package/src/rules/no-electron-security-issues/index.js +1 -1
- package/src/rules/no-format-string-injection/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-hardcoded-session-tokens/index.js +1 -1
- package/src/rules/no-insecure-comparison/index.js +1 -1
- package/src/rules/no-ldap-injection/index.js +1 -1
- package/src/rules/no-log-injection/index.js +1 -1
- package/src/rules/no-privilege-escalation/index.js +1 -1
- package/src/rules/no-sensitive-data-exposure/index.js +1 -1
- package/src/rules/no-sql-injection/index.js +1 -1
- package/src/rules/no-unlimited-resource-allocation/index.js +1 -1
- package/src/rules/no-unsafe-regex-construction/index.js +1 -1
- package/src/rules/no-xpath-injection/index.js +1 -1
- package/src/rules/no-xxe-injection/index.js +1 -1
- package/src/rules/require-backend-authorization/index.js +1 -1
- package/src/rules/require-secure-defaults/index.js +1 -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}if(member.property.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof member.property.value==="string"){return member.property.value}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}}if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){if((0,eslint_devkit_1.nameHasAnyWord)(callee.property.name,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}}if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){if(isPrivilegeOperationCallee(callee.property.name)){isPrivilegeOperation=true;operationName=callee.property.name.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\.(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}}if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){if((0,eslint_devkit_1.nameHasAnyWord)(callee.property.name,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}}if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){if(isPrivilegeOperationCallee(callee.property.name)){isPrivilegeOperation=true;operationName=callee.property.name.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.noSensitiveDataExposure=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");function literalCarriesSecret(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();return patterns.some(pattern=>{const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");return new RegExp(`\\b${flexPattern}\\b[ _-]{0,2}(?:[a-z0-9]{1,12}[ _-]{0,2})?[:=]\\s*\\S`,"i").test(normalized)&&/[:=]\s*\S+\s*$/.test(text)})}function literalLabelsValue(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();for(const pattern of patterns){const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");if(new RegExp(`\\b${flexPattern}\\b\\s*[:=]\\s*$`,"i").test(normalized)){return pattern}}return null}const DESCRIPTOR_SEGMENTS=["msg","message","error","err","label","prompt","hint","description","desc","regex","pattern","placeholder","warning","notice"];function identifierNamesSecret(name,patterns,descriptors){const matched=containsSensitiveData(name,patterns);if(!matched)return null;const last=name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).slice(-1).join("");return descriptors.has(last)?null:matched}function memberCarriesSecret(node,patterns,descriptors){const prop=node.property;const propName=node.computed?prop.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof prop.value==="string"?prop.value:null:prop.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?prop.name:null;const fromProp=propName?identifierNamesSecret(propName,patterns,descriptors):null;if(fromProp)return fromProp;if(propName&&(VALUE_FREE_PROPERTIES.has(propName)||DIAGNOSTIC_ACCESSORS.has(propName)))return null;return node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?identifierNamesSecret(node.object.name,patterns,descriptors):null}const VALUE_FREE_PROPERTIES=new Set(["length","size","byteLength","byteOffset"]);const DIAGNOSTIC_ACCESSORS=new Set(["message","stack","name","status","statusText"]);function isDiagnosticAccessor(node){const unwrapped=(0,eslint_devkit_1.unwrapTypeSyntax)(node);const value=unwrapped.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression?unwrapped.expression:unwrapped;return value.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!value.computed&&value.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&DIAGNOSTIC_ACCESSORS.has(value.property.name)}function containsSensitiveData(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();for(const pattern of patterns){const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");if(new RegExp(`\\b${flexPattern}\\b`,"i").test(normalized)){return pattern}}return null}exports.noSensitiveDataExposure=(0,eslint_devkit_2.createRule)({name:"no-sensitive-data-exposure",meta:{type:"suggestion",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-sensitive-data-exposure.md",description:"Detects PII/credentials in logs, responses, or error messages",cwe:"CWE-532",cvss:5.3},messages:{sensitiveDataExposure:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Sensitive data exposure",cwe:"CWE-532",description:"Sensitive data detected in {{context}}: {{dataType}}",severity:"HIGH",fix:"Redact or mask sensitive data before logging/exposing",documentationLink:"https://cwe.mitre.org/data/definitions/532.html"})},schema:[{type:"object",properties:{sensitivePatterns:{type:"array",items:{type:"string"},default:["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],description:"Sensitive data patterns"},checkConsoleLog:{type:"boolean",default:true,description:"Check console.log statements"},checkErrorMessages:{type:"boolean",default:true,description:"Check error messages"},descriptorSegments:{type:"array",items:{type:"string"},default:DESCRIPTOR_SEGMENTS,description:"Trailing name segments that describe a secret rather than hold one, so `apiKeyMsg` and `passwordError` are not reported. Compared as the whole FINAL segment of the name, never as a substring. Replaces the built-in list."},additionalDescriptorSegments:{type:"array",items:{type:"string"},default:[],description:"Extra descriptor segments, on top of `descriptorSegments`."}},additionalProperties:false}]},defaultOptions:[{sensitivePatterns:["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],checkConsoleLog:true,checkErrorMessages:true,descriptorSegments:DESCRIPTOR_SEGMENTS,additionalDescriptorSegments:[]}],create(context,[options={}]){const{sensitivePatterns=["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],checkConsoleLog=true,checkErrorMessages=true,descriptorSegments=DESCRIPTOR_SEGMENTS,additionalDescriptorSegments=[]}=options||{};const descriptors=new Set([...descriptorSegments,...additionalDescriptorSegments]);const LOGGER_RECEIVERS=new Set(["console","logger","log"]);const LOG_METHODS=new Set(["log","info","warn","error","debug","trace","fatal","verbose","silly"]);function isLoggerReceiver(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return LOGGER_RECEIVERS.has(node.name.toLowerCase())}return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!node.computed&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&LOGGER_RECEIVERS.has(node.property.name.toLowerCase())}function describeExposure(argument){const arg=(0,eslint_devkit_1.unwrapTypeSyntax)(argument);if(arg.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof arg.value==="string"){const pattern=literalCarriesSecret(arg.value,sensitivePatterns)?containsSensitiveData(arg.value,sensitivePatterns):null;return pattern?{node:arg,pattern}:null}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&arg.operator==="+"){if(arg.left.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof arg.left.value==="string"){const labelled=literalLabelsValue(arg.left.value,sensitivePatterns);if(labelled)return{node:arg.left,pattern:labelled}}else{const fromLeft=describeExposure(arg.left);if(fromLeft)return fromLeft}return namedValueExposure(arg.right)}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){const fromExpression=arg.expressions.map(e=>namedValueExposure(e)).find(m=>Boolean(m));if(fromExpression)return{node:arg,pattern:fromExpression.pattern};const INTERPOLATION="";const joined=arg.quasis.map(q=>q.value.cooked).join(INTERPOLATION);const allHolesAreDiagnostic=arg.expressions.every(isNonSecretHole);const fromText=arg.expressions.length>0&&!allHolesAreDiagnostic&&literalCarriesSecret(joined,sensitivePatterns)?containsSensitiveData(joined,sensitivePatterns):null;return fromText?{node:arg,pattern:fromText}:null}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){for(const property of arg.properties){if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property||property.computed)continue;const keyName=property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?property.key.name:property.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof property.key.value==="string"?property.key.value:null;const pattern=keyName?identifierNamesSecret(keyName,sensitivePatterns,descriptors):null;if(!pattern)continue;if((0,eslint_devkit_1.isStaticExpression)({node:property.value,scope:context.sourceCode.getScope(arg)})){continue}return{node:property,pattern}}return null}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){return describeExposure(arg.consequent)??describeExposure(arg.alternate)}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&arg.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&arg.callee.name==="String"&&arg.arguments.length===1&&arg.arguments[0].type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&!isShadowed("String",arg)){return describeExposure(arg.arguments[0])}return namedValueExposure(arg)}function isShadowed(name,node){const scope=context.sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===name);if(variable)return variable.defs.length>0}return false}function namedValueExposure(node,seen=new Set){const value=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(seen.has(value))return null;seen.add(value);if(value.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression){return namedValueExposure(value.expression,seen)}if(value.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const pattern=identifierNamesSecret(value.name,sensitivePatterns,descriptors);if(pattern)return{node:value,pattern};const init=resolveBindingInit(value);const viaBinding=init?namedValueExposure(init,seen):null;return viaBinding?{node:value,pattern:viaBinding.pattern}:null}if(value.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const pattern=memberCarriesSecret(value,sensitivePatterns,descriptors);return pattern?{node:value,pattern}:null}return null}function resolveBindingInit(node){const scope=context.sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===node.name);if(!variable)continue;if(variable.defs.length!==1)return null;const[def]=variable.defs;if(def.type!=="Variable"||!def.node.init)return null;return variable.references.filter(r=>r.isWrite()).length===1?def.node.init:null}return null}function isNonSecretHole(expression){if(!isDiagnosticAccessor(expression))return false;const unwrapped=(0,eslint_devkit_1.unwrapTypeSyntax)(expression);const member=unwrapped.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression?unwrapped.expression:unwrapped;if(member.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return true;const init=resolveBindingInit(member.object);if(init===null||init.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return true;const key=member.property.name;const assigned=init.properties.find(property=>property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&!property.computed&&(property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&property.key.name===key||property.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&property.key.value===key));if(!assigned)return true;return namedValueExposure(assigned.value)===null}function reportFirstExposure(argumentList,exposureContext){for(const argument of argumentList){const exposure=describeExposure(argument);if(exposure){context.report({node:exposure.node,messageId:"sensitiveDataExposure",data:{context:exposureContext,dataType:exposure.pattern}});return}}}function checkCallExpression(node){const isLoggingCall=(()=>{if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const property=node.callee.property;return!node.callee.computed&&property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&LOG_METHODS.has(property.name.toLowerCase())&&isLoggerReceiver(node.callee.object)}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const words=node.callee.name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/);return words.includes("log")||words.includes("logger")}return false})();if(isLoggingCall&&checkConsoleLog){reportFirstExposure(node.arguments,"logs")}}function checkNewExpression(node){if(!checkErrorMessages){return}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="Error"){reportFirstExposure(node.arguments,"error messages")}}return{CallExpression:checkCallExpression,NewExpression:checkNewExpression}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSensitiveDataExposure=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");function literalCarriesSecret(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();return patterns.some(pattern=>{const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");return new RegExp(`\\b${flexPattern}\\b[ _-]{0,2}(?:[a-z0-9]{1,12}[ _-]{0,2})?[:=]\\s*\\S`,"i").test(normalized)&&/[:=]\s*\S+\s*$/.test(text)})}function literalLabelsValue(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();for(const pattern of patterns){const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");if(new RegExp(`\\b${flexPattern}\\b\\s*[:=]\\s*$`,"i").test(normalized)){return pattern}}return null}const DESCRIPTOR_SEGMENTS=["msg","message","error","err","label","prompt","hint","description","desc","regex","pattern","placeholder","warning","notice"];function identifierNamesSecret(name,patterns,descriptors){const matched=containsSensitiveData(name,patterns);if(!matched)return null;const last=name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).slice(-1).join("");return descriptors.has(last)?null:matched}function memberCarriesSecret(node,patterns,descriptors){const prop=node.property;const propName=node.computed?(0,eslint_devkit_1.staticString)(prop)!==null?(0,eslint_devkit_1.staticString)(prop):null:prop.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?prop.name:null;const fromProp=propName?identifierNamesSecret(propName,patterns,descriptors):null;if(fromProp)return fromProp;if(propName&&(VALUE_FREE_PROPERTIES.has(propName)||DIAGNOSTIC_ACCESSORS.has(propName)))return null;return node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?identifierNamesSecret(node.object.name,patterns,descriptors):null}const VALUE_FREE_PROPERTIES=new Set(["length","size","byteLength","byteOffset"]);const DIAGNOSTIC_ACCESSORS=new Set(["message","stack","name","status","statusText"]);function isDiagnosticAccessor(node){const unwrapped=(0,eslint_devkit_1.unwrapTypeSyntax)(node);const value=unwrapped.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression?unwrapped.expression:unwrapped;return value.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!value.computed&&value.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&DIAGNOSTIC_ACCESSORS.has(value.property.name)}function containsSensitiveData(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();for(const pattern of patterns){const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");if(new RegExp(`\\b${flexPattern}\\b`,"i").test(normalized)){return pattern}}return null}exports.noSensitiveDataExposure=(0,eslint_devkit_2.createRule)({name:"no-sensitive-data-exposure",meta:{type:"suggestion",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-sensitive-data-exposure.md",description:"Detects PII/credentials in logs, responses, or error messages",cwe:"CWE-532",cvss:5.3},messages:{sensitiveDataExposure:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Sensitive data exposure",cwe:"CWE-532",description:"Sensitive data detected in {{context}}: {{dataType}}",severity:"HIGH",fix:"Redact or mask sensitive data before logging/exposing",documentationLink:"https://cwe.mitre.org/data/definitions/532.html"})},schema:[{type:"object",properties:{sensitivePatterns:{type:"array",items:{type:"string"},default:["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],description:"Sensitive data patterns"},checkConsoleLog:{type:"boolean",default:true,description:"Check console.log statements"},checkErrorMessages:{type:"boolean",default:true,description:"Check error messages"},descriptorSegments:{type:"array",items:{type:"string"},default:DESCRIPTOR_SEGMENTS,description:"Trailing name segments that describe a secret rather than hold one, so `apiKeyMsg` and `passwordError` are not reported. Compared as the whole FINAL segment of the name, never as a substring. Replaces the built-in list."},additionalDescriptorSegments:{type:"array",items:{type:"string"},default:[],description:"Extra descriptor segments, on top of `descriptorSegments`."}},additionalProperties:false}]},defaultOptions:[{sensitivePatterns:["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],checkConsoleLog:true,checkErrorMessages:true,descriptorSegments:DESCRIPTOR_SEGMENTS,additionalDescriptorSegments:[]}],create(context,[options={}]){const{sensitivePatterns=["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],checkConsoleLog=true,checkErrorMessages=true,descriptorSegments=DESCRIPTOR_SEGMENTS,additionalDescriptorSegments=[]}=options||{};const descriptors=new Set([...descriptorSegments,...additionalDescriptorSegments]);const LOGGER_RECEIVERS=new Set(["console","logger","log"]);const LOG_METHODS=new Set(["log","info","warn","error","debug","trace","fatal","verbose","silly"]);function isLoggerReceiver(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return LOGGER_RECEIVERS.has(node.name.toLowerCase())}return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!node.computed&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&LOGGER_RECEIVERS.has(node.property.name.toLowerCase())}function describeExposure(argument){const arg=(0,eslint_devkit_1.unwrapTypeSyntax)(argument);const staticText1=(0,eslint_devkit_1.staticString)(arg);if(staticText1!==null){const pattern=literalCarriesSecret(staticText1,sensitivePatterns)?containsSensitiveData(staticText1,sensitivePatterns):null;return pattern?{node:arg,pattern}:null}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&arg.operator==="+"){const staticText2=(0,eslint_devkit_1.staticString)(arg.left);if(staticText2!==null){const labelled=literalLabelsValue(staticText2,sensitivePatterns);if(labelled)return{node:arg.left,pattern:labelled}}else{const fromLeft=describeExposure(arg.left);if(fromLeft)return fromLeft}return namedValueExposure(arg.right)}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){const fromExpression=arg.expressions.map(e=>namedValueExposure(e)).find(m=>Boolean(m));if(fromExpression)return{node:arg,pattern:fromExpression.pattern};const INTERPOLATION="";const joined=arg.quasis.map(q=>q.value.cooked).join(INTERPOLATION);const allHolesAreDiagnostic=arg.expressions.every(isNonSecretHole);const fromText=arg.expressions.length>0&&!allHolesAreDiagnostic&&literalCarriesSecret(joined,sensitivePatterns)?containsSensitiveData(joined,sensitivePatterns):null;return fromText?{node:arg,pattern:fromText}:null}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){for(const property of arg.properties){if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property||property.computed)continue;const keyName=property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?property.key.name:property.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof property.key.value==="string"?property.key.value:null;const pattern=keyName?identifierNamesSecret(keyName,sensitivePatterns,descriptors):null;if(!pattern)continue;if((0,eslint_devkit_1.isStaticExpression)({node:property.value,scope:context.sourceCode.getScope(arg)})){continue}return{node:property,pattern}}return null}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){return describeExposure(arg.consequent)??describeExposure(arg.alternate)}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&arg.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&arg.callee.name==="String"&&arg.arguments.length===1&&arg.arguments[0].type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&!isShadowed("String",arg)){return describeExposure(arg.arguments[0])}return namedValueExposure(arg)}function isShadowed(name,node){const scope=context.sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===name);if(variable)return variable.defs.length>0}return false}function namedValueExposure(node,seen=new Set){const value=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(seen.has(value))return null;seen.add(value);if(value.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression){return namedValueExposure(value.expression,seen)}if(value.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const pattern=identifierNamesSecret(value.name,sensitivePatterns,descriptors);if(pattern)return{node:value,pattern};const init=resolveBindingInit(value);const viaBinding=init?namedValueExposure(init,seen):null;return viaBinding?{node:value,pattern:viaBinding.pattern}:null}if(value.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const pattern=memberCarriesSecret(value,sensitivePatterns,descriptors);return pattern?{node:value,pattern}:null}return null}function resolveBindingInit(node){const scope=context.sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===node.name);if(!variable)continue;if(variable.defs.length!==1)return null;const[def]=variable.defs;if(def.type!=="Variable"||!def.node.init)return null;return variable.references.filter(r=>r.isWrite()).length===1?def.node.init:null}return null}function isNonSecretHole(expression){if(!isDiagnosticAccessor(expression))return false;const unwrapped=(0,eslint_devkit_1.unwrapTypeSyntax)(expression);const member=unwrapped.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression?unwrapped.expression:unwrapped;if(member.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return true;const init=resolveBindingInit(member.object);if(init===null||init.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return true;const key=member.property.name;const assigned=init.properties.find(property=>property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&!property.computed&&(property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&property.key.name===key||property.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&property.key.value===key));if(!assigned)return true;return namedValueExposure(assigned.value)===null}function reportFirstExposure(argumentList,exposureContext){for(const argument of argumentList){const exposure=describeExposure(argument);if(exposure){context.report({node:exposure.node,messageId:"sensitiveDataExposure",data:{context:exposureContext,dataType:exposure.pattern}});return}}}function checkCallExpression(node){const isLoggingCall=(()=>{if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const property=node.callee.property;return!node.callee.computed&&property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&LOG_METHODS.has(property.name.toLowerCase())&&isLoggerReceiver(node.callee.object)}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const words=node.callee.name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/);return words.includes("log")||words.includes("logger")}return false})();if(isLoggingCall&&checkConsoleLog){reportFirstExposure(node.arguments,"logs")}}function checkNewExpression(node){if(!checkErrorMessages){return}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="Error"){reportFirstExposure(node.arguments,"error messages")}}return{CallExpression:checkCallExpression,NewExpression:checkNewExpression}}});
|
|
@@ -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){if(!callee.computed){return callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?callee.property.name:null}const direct=stringLiteralValue(callee.property);if(direct!==null)return direct;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&&attribution.requestRoots.has(root.name)&&properties.some(property=>attribution.requestProperties.has(property))&&!isLocallyConstructed(resolveVariable(root.name,scope),scope)){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||callee.computed){return null}if(callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||callee.property.name!=="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),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){if(!callee.computed){return callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?callee.property.name:null}const direct=stringLiteralValue(callee.property);if(direct!==null)return direct;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||callee.computed){return null}if(callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||callee.property.name!=="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.noUnlimitedResourceAllocation=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.noUnlimitedResourceAllocation=(0,eslint_devkit_1.createRule)({name:"no-unlimited-resource-allocation",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-unlimited-resource-allocation.md",description:"Detects unlimited resource allocation that could cause DoS",cwe:"CWE-770"},messages:{unlimitedBufferAllocation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unlimited Buffer Allocation",cwe:"CWE-770",description:"Buffer allocated without size limits",severity:"HIGH",fix:"Set maximum buffer size limits \u2014 Not a finding if the size is a constant, or already clamped before this line",documentationLink:"https://nodejs.org/api/buffer.html"}),unlimitedFileOperations:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unlimited File Operations",cwe:"CWE-770",description:"File operations without size limits",severity:"MEDIUM",fix:"Validate file size before operations \u2014 Not a finding if the decompressed bytes are counted against a ceiling downstream",documentationLink:"https://nodejs.org/api/fs.html"}),unlimitedMemoryAllocation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unlimited Memory Allocation",cwe:"CWE-770",description:"Memory allocated without limits",severity:"MEDIUM",fix:"Set memory allocation limits \u2014 Not a finding if the length comes from data the process already holds",documentationLink:"https://nodejs.org/api/buffer.html"}),userControlledResourceSize:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"User Controlled Resource Size",cwe:"CWE-770",description:"Resource size controlled by user input",severity:"HIGH",fix:"Validate and limit user-controlled resource sizes \u2014 Not a finding if the value is content rather than a byte count",documentationLink:"https://cwe.mitre.org/data/definitions/770.html"}),resourceAllocationInLoop:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Resource Allocation in Loop",cwe:"CWE-770",description:"Resource allocation inside loop without limits",severity:"HIGH",fix:"Move resource allocation outside loop or add iteration limits \u2014 Not a finding if the loop bound is a constant or a collection the process already holds",documentationLink:"https://cwe.mitre.org/data/definitions/770.html"})},schema:[{type:"object",properties:{maxResourceSize:{type:"number",minimum:1024,default:1048576,description:"Allocation size in bytes above which a call is reported"},userInputVariables:{type:"array",items:{type:"string"},default:["req","request","body","query","params","input","data"],description:"Variable names treated as user-controlled input"},safeResourceFunctions:{type:"array",items:{type:"string"},default:["validateSize","checkLimits","limitResource","safeAlloc"],description:"Function names that bound an allocation"},requireResourceValidation:{type:"boolean",default:true,description:"Require an explicit size check before allocating"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as resource 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:[{maxResourceSize:1048576,userInputVariables:["req","request","body","query","params","input","data"],safeResourceFunctions:["validateSize","checkLimits","limitResource","safeAlloc"],requireResourceValidation:true,trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{maxResourceSize=1048576,userInputVariables=["req","request","body","query","params","input","data"],safeResourceFunctions=["validateSize","checkLimits","limitResource","safeAlloc"],requireResourceValidation=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 REQUEST_SURFACE=new Set(["body","query","params","headers","cookies","url","originalUrl","rawBody","files","payload","searchParams"]);const requestRoots=new Set(userInputVariables.map(name=>name.toLowerCase()));const readsRequestSurface=node=>node?.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!node.computed&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&REQUEST_SURFACE.has(node.property.name);const initializerOf=id=>{const resolved=context.sourceCode.getScope(id).references.find(ref=>ref.identifier===id)?.resolved;const def=resolved?.defs[0];if(def?.type!=="Variable")return void 0;return def.node.init??void 0};const isInvokerControlled=(node,depth=0)=>{if(depth>12)return false;switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:{if(requestRoots.has(node.name.toLowerCase())&&readsRequestSurface(node.parent)){return true}const init=initializerOf(node);return init!==void 0&&isInvokerControlled(init,depth+1)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:return isInvokerControlled(node.object,depth+1)||node.computed&&isInvokerControlled(node.property,depth+1);case eslint_devkit_1.AST_NODE_TYPES.CallExpression:case eslint_devkit_1.AST_NODE_TYPES.NewExpression:return isInvokerControlled(node.callee,depth+1)||node.arguments.some(argument=>argument.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&isInvokerControlled(argument,depth+1));case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:case eslint_devkit_1.AST_NODE_TYPES.LogicalExpression:return isInvokerControlled(node.left,depth+1)||isInvokerControlled(node.right,depth+1);case eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression:return isInvokerControlled(node.consequent,depth+1)||isInvokerControlled(node.alternate,depth+1);case eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral:return node.expressions.some(e=>isInvokerControlled(e,depth+1));case eslint_devkit_1.AST_NODE_TYPES.AwaitExpression:case eslint_devkit_1.AST_NODE_TYPES.UnaryExpression:return isInvokerControlled(node.argument,depth+1);case eslint_devkit_1.AST_NODE_TYPES.TSAsExpression:case eslint_devkit_1.AST_NODE_TYPES.TSNonNullExpression:return isInvokerControlled(node.expression,depth+1);default:return false}};const isUserInput=expression=>isInvokerControlled(expression);const couldBeASize=node=>{switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Literal:return typeof node.value==="number";case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return["+","-","*","/","%","**","<<",">>"].includes(node.operator);case eslint_devkit_1.AST_NODE_TYPES.UnaryExpression:return node.operator==="+"||node.operator==="-"||node.operator==="~";case eslint_devkit_1.AST_NODE_TYPES.CallExpression:{const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return["Number","parseInt","parseFloat","BigInt"].includes(callee.name)}return callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="Math"}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:return!node.computed&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&["length","size","byteLength","count"].includes(node.property.name);case eslint_devkit_1.AST_NODE_TYPES.Identifier:{const init=initializerOf(node);return init!==void 0&&couldBeASize(init)}case eslint_devkit_1.AST_NODE_TYPES.LogicalExpression:return couldBeASize(node.left)||couldBeASize(node.right);case eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression:return couldBeASize(node.consequent)||couldBeASize(node.alternate);case eslint_devkit_1.AST_NODE_TYPES.TSAsExpression:case eslint_devkit_1.AST_NODE_TYPES.TSNonNullExpression:return couldBeASize(node.expression);default:return false}};const hasSizeValidation=node=>{const args=node.arguments;const sizeArg=args[0];const sizeText=sizeArg.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?`${sourceCode.getText(sizeArg)} ${sourceCode.getText(initializerOf(sizeArg))}`:sourceCode.getText(sizeArg);return sizeText.includes("Math.min(")||sizeText.includes("Math.max(")||sizeText.includes("Math.clamp(")||safeResourceFunctions.some(func=>sizeText.includes(func))};const estimateResourceSize=sizeExpression=>{if(sizeExpression.type==="Literal"&&typeof sizeExpression.value==="number"){return sizeExpression.value}if(sizeExpression.type==="BinaryExpression"){const left=estimateResourceSize(sizeExpression.left);const right=estimateResourceSize(sizeExpression.right);if(left!==null&&right!==null){switch(sizeExpression.operator){case"*":return left*right;case"+":return left+right;case"-":return left-right;case"/":return right!==0?left/right:null;default:return null}}}return null};const ARCHIVE_MODULES=/^(unzipper|tar|tar-stream|yauzl|adm-zip|node:zlib|zlib)$/;const archiveBindings=new Set(["zlib"]);const noteArchiveBinding=(local,source)=>{if(ARCHIVE_MODULES.test(source))archiveBindings.add(local)};const ALLOCATORS=new Set(["Buffer.alloc","Buffer.allocUnsafe","Buffer.allocUnsafeSlow","Buffer","Array","Map","Set","WeakMap","WeakSet"]);const enclosingLoop=node=>{let child=node;let current=node.parent;while(current!=null){switch(current.type){case eslint_devkit_1.AST_NODE_TYPES.ForStatement:return current.init===child?void 0:current;case eslint_devkit_1.AST_NODE_TYPES.ForOfStatement:case eslint_devkit_1.AST_NODE_TYPES.ForInStatement:return current.right===child?void 0:current;case eslint_devkit_1.AST_NODE_TYPES.WhileStatement:case eslint_devkit_1.AST_NODE_TYPES.DoWhileStatement:return current;default:break}child=current;current=current.parent}return void 0};const isAllocationInLoopBody=node=>{const callee=node.callee;let name;if(callee.type==="Identifier"){name=callee.name}else if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.property.type==="Identifier"){name=`${callee.object.name}.${callee.property.name}`}if(name===void 0||!ALLOCATORS.has(name))return false;const loop=enclosingLoop(node);if(loop===void 0)return false;const bound=loop.type===eslint_devkit_1.AST_NODE_TYPES.ForOfStatement||loop.type===eslint_devkit_1.AST_NODE_TYPES.ForInStatement?loop.right:loop.test??void 0;return bound!==void 0&&isInvokerControlled(bound)};return{ImportDeclaration(node){for(const spec of node.specifiers){if(spec.type==="ImportDefaultSpecifier"||spec.type==="ImportNamespaceSpecifier"){noteArchiveBinding(spec.local.name,String(node.source.value))}}},VariableDeclarator(node){if(node.id.type==="Identifier"&&node.init?.type==="CallExpression"&&node.init.callee.type==="Identifier"&&node.init.callee.name==="require"&&node.init.arguments[0]?.type==="Literal"){noteArchiveBinding(node.id.name,String(node.init.arguments[0].value))}},CallExpression(node){const callee=node.callee;const isBufferAlloc=callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="Buffer"&&callee.property.type==="Identifier"&&(callee.property.name==="alloc"||callee.property.name==="allocUnsafe");const isNewBuffer=callee.type==="NewExpression"&&callee.callee.type==="Identifier"&&callee.callee.name==="Buffer";if(isBufferAlloc||isNewBuffer){const args=node.arguments;if(args.length>0){const sizeArg=args[0];if(requireResourceValidation&&sizeArg.type!=="SpreadElement"&&isUserInput(sizeArg)&&!hasSizeValidation(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"userControlledResourceSize",data:{filePath:filename,line:String(node.loc.start.line)}});return}const estimatedSize=sizeArg.type==="SpreadElement"?null:estimateResourceSize(sizeArg);if(estimatedSize&&estimatedSize>maxResourceSize){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"unlimitedBufferAllocation",data:{filePath:filename,line:String(node.loc.start.line)}});return}}}if(callee.type==="Identifier"&&callee.name==="multer"){const args=node.arguments;if(args.length>0&&args[0].type==="ObjectExpression"){const props=args[0].properties;const hasValidLimits=props.some(prop=>{if(prop.type!=="Property"||prop.key.type!=="Identifier"){return false}if(prop.key.name==="fileSize")return true;if(prop.key.name==="limits"&&prop.value.type==="ObjectExpression"){return prop.value.properties.some(limitProp=>limitProp.type==="Property"&&limitProp.key.type==="Identifier"&&limitProp.key.name==="fileSize")}return false});if(!hasValidLimits){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"unlimitedFileOperations",data:{filePath:filename,line:String(node.loc.start.line)}})}}return}if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="fs"&&callee.property.type==="Identifier"&&["readFile","writeFile","readFileSync","writeFileSync"].includes(callee.property.name)){const args=node.arguments;if(args.length>0){const pathArg=args[0];if(pathArg.type!=="SpreadElement"&&(0,eslint_devkit_1.isStaticExpression)({node:pathArg,scope:context.sourceCode.getScope(pathArg)})){return}if(pathArg.type!=="SpreadElement"&&isUserInput(pathArg)){if(safetyChecker.isSafe(node,context)){return}context.report({node:pathArg,messageId:"unlimitedFileOperations",data:{filePath:filename,line:String(node.loc.start.line)}})}}}if(callee.type==="Identifier"&&callee.name==="Array"){const args=node.arguments;if(args.length===1){const sizeArg=args[0];if(sizeArg.type!=="SpreadElement"&&isUserInput(sizeArg)){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"unlimitedMemoryAllocation",data:{filePath:filename,line:String(node.loc.start.line)}})}}}const isDecompression=()=>{if(callee.type!=="MemberExpression")return false;const member=callee;const receiver=member.object.type==="Identifier"?member.object.name:"";if(!archiveBindings.has(receiver))return false;const method=member.property.type==="Identifier"?member.property.name:"";return/^(Extract|Parse|extract|createGunzip|createUnzip|createInflate|open)$/.test(method)};const hasDecompressionLimit=()=>node.arguments.some(argument=>argument.type==="ObjectExpression"&&argument.properties.some(property=>property.type==="Property"&&property.key.type==="Identifier"&&["maxOutputLength","maxSize","limit"].includes(property.key.name)));const countsOutputBytes=()=>{const scope=context.sourceCode.getScope(node).variableScope.block;const accumulators=new Set;const compared=new Set;const visit=current=>{if(current===null||typeof current!=="object")return;if(Array.isArray(current)){for(const item of current)visit(item);return}const candidate=current;if(typeof candidate.type!=="string")return;if(candidate.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&candidate.operator==="+="&&candidate.left.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&candidate.right.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!candidate.right.computed&&candidate.right.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(candidate.right.property.name==="length"||candidate.right.property.name==="byteLength")){accumulators.add(candidate.left.name)}if(candidate.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&[">",">=","<","<="].includes(candidate.operator)){for(const side of[candidate.left,candidate.right]){if(side.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)compared.add(side.name)}}for(const[key,value]of Object.entries(candidate)){if(key==="parent")continue;visit(value)}};visit(scope);return[...accumulators].some(name=>compared.has(name))};if(isDecompression()&&!hasDecompressionLimit()&&!countsOutputBytes()){context.report({node,messageId:"unlimitedFileOperations",data:{filePath:filename,line:String(node.loc.start.line)}})}if(isAllocationInLoopBody(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"resourceAllocationInLoop",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},NewExpression(node){const callee=node.callee;if(callee.type==="Identifier"&&callee.name==="Buffer"){const args=node.arguments;if(args.length>0){const sizeArg=args[0];const hasEncodingArgument=args.length>1;if(requireResourceValidation&&sizeArg.type!=="SpreadElement"&&!hasEncodingArgument&&couldBeASize(sizeArg)&&isUserInput(sizeArg)&&!hasSizeValidation(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"userControlledResourceSize",data:{filePath:filename,line:String(node.loc.start.line)}});return}const estimatedSize=sizeArg.type==="SpreadElement"?null:estimateResourceSize(sizeArg);if(estimatedSize&&estimatedSize>maxResourceSize){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"unlimitedBufferAllocation",data:{filePath:filename,line:String(node.loc.start.line)}});return}}}if(callee.type==="Identifier"&&callee.name==="Array"){const args=node.arguments;if(args.length===1){const sizeArg=args[0];if(sizeArg.type!=="SpreadElement"&&isUserInput(sizeArg)){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"unlimitedMemoryAllocation",data:{filePath:filename,line:String(node.loc.start.line)}})}}}if(isAllocationInLoopBody(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"resourceAllocationInLoop",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnlimitedResourceAllocation=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");const DEFAULT_SIZE_PROPERTIES=["length","size","byteLength","count"];const DEFAULT_LIMIT_OPTION_NAMES=["maxOutputLength","maxSize","limit"];exports.noUnlimitedResourceAllocation=(0,eslint_devkit_1.createRule)({name:"no-unlimited-resource-allocation",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-unlimited-resource-allocation.md",description:"Detects unlimited resource allocation that could cause DoS",cwe:"CWE-770"},messages:{unlimitedBufferAllocation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unlimited Buffer Allocation",cwe:"CWE-770",description:"Buffer allocated without size limits",severity:"HIGH",fix:"Set maximum buffer size limits \u2014 Not a finding if the size is a constant, or already clamped before this line",documentationLink:"https://nodejs.org/api/buffer.html"}),unlimitedFileOperations:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unlimited File Operations",cwe:"CWE-770",description:"File operations without size limits",severity:"MEDIUM",fix:"Validate file size before operations \u2014 Not a finding if the decompressed bytes are counted against a ceiling downstream",documentationLink:"https://nodejs.org/api/fs.html"}),unlimitedMemoryAllocation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unlimited Memory Allocation",cwe:"CWE-770",description:"Memory allocated without limits",severity:"MEDIUM",fix:"Set memory allocation limits \u2014 Not a finding if the length comes from data the process already holds",documentationLink:"https://nodejs.org/api/buffer.html"}),userControlledResourceSize:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"User Controlled Resource Size",cwe:"CWE-770",description:"Resource size controlled by user input",severity:"HIGH",fix:"Validate and limit user-controlled resource sizes \u2014 Not a finding if the value is content rather than a byte count",documentationLink:"https://cwe.mitre.org/data/definitions/770.html"}),resourceAllocationInLoop:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Resource Allocation in Loop",cwe:"CWE-770",description:"Resource allocation inside loop without limits",severity:"HIGH",fix:"Move resource allocation outside loop or add iteration limits \u2014 Not a finding if the loop bound is a constant or a collection the process already holds",documentationLink:"https://cwe.mitre.org/data/definitions/770.html"})},schema:[{type:"object",properties:{sizeProperties:{type:"array",items:{type:"string"},default:[...DEFAULT_SIZE_PROPERTIES],description:"Property names that carry a magnitude. Replaces the default."},limitOptionNames:{type:"array",items:{type:"string"},default:[...DEFAULT_LIMIT_OPTION_NAMES],description:"Option keys a library accepts to cap an operation. Replaces the default."},maxResourceSize:{type:"number",minimum:1024,default:1048576,description:"Allocation size in bytes above which a call is reported"},userInputVariables:{type:"array",items:{type:"string"},default:["req","request","body","query","params","input","data"],description:"Variable names treated as user-controlled input"},safeResourceFunctions:{type:"array",items:{type:"string"},default:["validateSize","checkLimits","limitResource","safeAlloc"],description:"Function names that bound an allocation"},requireResourceValidation:{type:"boolean",default:true,description:"Require an explicit size check before allocating"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as resource 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:[{maxResourceSize:1048576,userInputVariables:["req","request","body","query","params","input","data"],safeResourceFunctions:["validateSize","checkLimits","limitResource","safeAlloc"],requireResourceValidation:true,trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const sizeProperties=new Set(options.sizeProperties??DEFAULT_SIZE_PROPERTIES);const limitOptionNames=new Set(options.limitOptionNames??DEFAULT_LIMIT_OPTION_NAMES);const{maxResourceSize=1048576,userInputVariables=["req","request","body","query","params","input","data"],safeResourceFunctions=["validateSize","checkLimits","limitResource","safeAlloc"],requireResourceValidation=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 REQUEST_SURFACE=new Set(["body","query","params","headers","cookies","url","originalUrl","rawBody","files","payload","searchParams"]);const requestRoots=new Set(userInputVariables.map(name=>name.toLowerCase()));const readsRequestSurface=node=>node?.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!node.computed&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&REQUEST_SURFACE.has(node.property.name);const initializerOf=id=>{const resolved=context.sourceCode.getScope(id).references.find(ref=>ref.identifier===id)?.resolved;const def=resolved?.defs[0];if(def?.type!=="Variable")return void 0;return def.node.init??void 0};const isInvokerControlled=(node,depth=0)=>{if(depth>12)return false;switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:{if(requestRoots.has(node.name.toLowerCase())&&readsRequestSurface(node.parent)){return true}const init=initializerOf(node);return init!==void 0&&isInvokerControlled(init,depth+1)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:return isInvokerControlled(node.object,depth+1)||node.computed&&isInvokerControlled(node.property,depth+1);case eslint_devkit_1.AST_NODE_TYPES.CallExpression:case eslint_devkit_1.AST_NODE_TYPES.NewExpression:return isInvokerControlled(node.callee,depth+1)||node.arguments.some(argument=>argument.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&isInvokerControlled(argument,depth+1));case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:case eslint_devkit_1.AST_NODE_TYPES.LogicalExpression:return isInvokerControlled(node.left,depth+1)||isInvokerControlled(node.right,depth+1);case eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression:return isInvokerControlled(node.consequent,depth+1)||isInvokerControlled(node.alternate,depth+1);case eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral:return node.expressions.some(e=>isInvokerControlled(e,depth+1));case eslint_devkit_1.AST_NODE_TYPES.AwaitExpression:case eslint_devkit_1.AST_NODE_TYPES.UnaryExpression:return isInvokerControlled(node.argument,depth+1);case eslint_devkit_1.AST_NODE_TYPES.TSAsExpression:case eslint_devkit_1.AST_NODE_TYPES.TSNonNullExpression:return isInvokerControlled(node.expression,depth+1);default:return false}};const isUserInput=expression=>isInvokerControlled(expression);const couldBeASize=node=>{switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Literal:return typeof node.value==="number";case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return["+","-","*","/","%","**","<<",">>"].includes(node.operator);case eslint_devkit_1.AST_NODE_TYPES.UnaryExpression:return node.operator==="+"||node.operator==="-"||node.operator==="~";case eslint_devkit_1.AST_NODE_TYPES.CallExpression:{const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return["Number","parseInt","parseFloat","BigInt"].includes(callee.name)}return callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="Math"}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:return!node.computed&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&sizeProperties.has(node.property.name);case eslint_devkit_1.AST_NODE_TYPES.Identifier:{const init=initializerOf(node);return init!==void 0&&couldBeASize(init)}case eslint_devkit_1.AST_NODE_TYPES.LogicalExpression:return couldBeASize(node.left)||couldBeASize(node.right);case eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression:return couldBeASize(node.consequent)||couldBeASize(node.alternate);case eslint_devkit_1.AST_NODE_TYPES.TSAsExpression:case eslint_devkit_1.AST_NODE_TYPES.TSNonNullExpression:return couldBeASize(node.expression);default:return false}};const hasSizeValidation=node=>{const args=node.arguments;const sizeArg=args[0];const sizeText=sizeArg.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?`${sourceCode.getText(sizeArg)} ${sourceCode.getText(initializerOf(sizeArg))}`:sourceCode.getText(sizeArg);return sizeText.includes("Math.min(")||sizeText.includes("Math.max(")||sizeText.includes("Math.clamp(")||safeResourceFunctions.some(func=>sizeText.includes(func))};const estimateResourceSize=sizeExpression=>{if(sizeExpression.type==="Literal"&&typeof sizeExpression.value==="number"){return sizeExpression.value}if(sizeExpression.type==="BinaryExpression"){const left=estimateResourceSize(sizeExpression.left);const right=estimateResourceSize(sizeExpression.right);if(left!==null&&right!==null){switch(sizeExpression.operator){case"*":return left*right;case"+":return left+right;case"-":return left-right;case"/":return right!==0?left/right:null;default:return null}}}return null};const ARCHIVE_MODULES=/^(unzipper|tar|tar-stream|yauzl|adm-zip|node:zlib|zlib)$/;const archiveBindings=new Set(["zlib"]);const noteArchiveBinding=(local,source)=>{if(ARCHIVE_MODULES.test(source))archiveBindings.add(local)};const ALLOCATORS=new Set(["Buffer.alloc","Buffer.allocUnsafe","Buffer.allocUnsafeSlow","Buffer","Array","Map","Set","WeakMap","WeakSet"]);const enclosingLoop=node=>{let child=node;let current=node.parent;while(current!=null){switch(current.type){case eslint_devkit_1.AST_NODE_TYPES.ForStatement:return current.init===child?void 0:current;case eslint_devkit_1.AST_NODE_TYPES.ForOfStatement:case eslint_devkit_1.AST_NODE_TYPES.ForInStatement:return current.right===child?void 0:current;case eslint_devkit_1.AST_NODE_TYPES.WhileStatement:case eslint_devkit_1.AST_NODE_TYPES.DoWhileStatement:return current;default:break}child=current;current=current.parent}return void 0};const isAllocationInLoopBody=node=>{const callee=node.callee;let name;if(callee.type==="Identifier"){name=callee.name}else if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.property.type==="Identifier"){name=`${callee.object.name}.${callee.property.name}`}if(name===void 0||!ALLOCATORS.has(name))return false;const loop=enclosingLoop(node);if(loop===void 0)return false;const bound=loop.type===eslint_devkit_1.AST_NODE_TYPES.ForOfStatement||loop.type===eslint_devkit_1.AST_NODE_TYPES.ForInStatement?loop.right:loop.test??void 0;return bound!==void 0&&isInvokerControlled(bound)};return{ImportDeclaration(node){for(const spec of node.specifiers){if(spec.type==="ImportDefaultSpecifier"||spec.type==="ImportNamespaceSpecifier"){noteArchiveBinding(spec.local.name,String(node.source.value))}}},VariableDeclarator(node){if(node.id.type==="Identifier"&&node.init?.type==="CallExpression"&&node.init.callee.type==="Identifier"&&node.init.callee.name==="require"&&node.init.arguments[0]?.type==="Literal"){noteArchiveBinding(node.id.name,String(node.init.arguments[0].value))}},CallExpression(node){const callee=node.callee;const isBufferAlloc=callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="Buffer"&&callee.property.type==="Identifier"&&(callee.property.name==="alloc"||callee.property.name==="allocUnsafe");const isNewBuffer=callee.type==="NewExpression"&&callee.callee.type==="Identifier"&&callee.callee.name==="Buffer";if(isBufferAlloc||isNewBuffer){const args=node.arguments;if(args.length>0){const sizeArg=args[0];if(requireResourceValidation&&sizeArg.type!=="SpreadElement"&&isUserInput(sizeArg)&&!hasSizeValidation(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"userControlledResourceSize",data:{filePath:filename,line:String(node.loc.start.line)}});return}const estimatedSize=sizeArg.type==="SpreadElement"?null:estimateResourceSize(sizeArg);if(estimatedSize&&estimatedSize>maxResourceSize){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"unlimitedBufferAllocation",data:{filePath:filename,line:String(node.loc.start.line)}});return}}}if(callee.type==="Identifier"&&callee.name==="multer"){const args=node.arguments;if(args.length>0&&args[0].type==="ObjectExpression"){const props=args[0].properties;const hasValidLimits=props.some(prop=>{if(prop.type!=="Property"||prop.key.type!=="Identifier"){return false}if(prop.key.name==="fileSize")return true;if(prop.key.name==="limits"&&prop.value.type==="ObjectExpression"){return prop.value.properties.some(limitProp=>limitProp.type==="Property"&&limitProp.key.type==="Identifier"&&limitProp.key.name==="fileSize")}return false});if(!hasValidLimits){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"unlimitedFileOperations",data:{filePath:filename,line:String(node.loc.start.line)}})}}return}if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="fs"&&callee.property.type==="Identifier"&&["readFile","writeFile","readFileSync","writeFileSync"].includes(callee.property.name)){const args=node.arguments;if(args.length>0){const pathArg=args[0];if(pathArg.type!=="SpreadElement"&&(0,eslint_devkit_1.isStaticExpression)({node:pathArg,scope:context.sourceCode.getScope(pathArg)})){return}if(pathArg.type!=="SpreadElement"&&isUserInput(pathArg)){if(safetyChecker.isSafe(node,context)){return}context.report({node:pathArg,messageId:"unlimitedFileOperations",data:{filePath:filename,line:String(node.loc.start.line)}})}}}if(callee.type==="Identifier"&&callee.name==="Array"){const args=node.arguments;if(args.length===1){const sizeArg=args[0];if(sizeArg.type!=="SpreadElement"&&isUserInput(sizeArg)){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"unlimitedMemoryAllocation",data:{filePath:filename,line:String(node.loc.start.line)}})}}}const isDecompression=()=>{if(callee.type!=="MemberExpression")return false;const member=callee;const receiver=member.object.type==="Identifier"?member.object.name:"";if(!archiveBindings.has(receiver))return false;const method=member.property.type==="Identifier"?member.property.name:"";return/^(Extract|Parse|extract|createGunzip|createUnzip|createInflate|open)$/.test(method)};const hasDecompressionLimit=()=>node.arguments.some(argument=>argument.type==="ObjectExpression"&&argument.properties.some(property=>property.type==="Property"&&property.key.type==="Identifier"&&limitOptionNames.has(property.key.name)));const countsOutputBytes=()=>{const scope=context.sourceCode.getScope(node).variableScope.block;const accumulators=new Set;const compared=new Set;const visit=current=>{if(current===null||typeof current!=="object")return;if(Array.isArray(current)){for(const item of current)visit(item);return}const candidate=current;if(typeof candidate.type!=="string")return;if(candidate.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&candidate.operator==="+="&&candidate.left.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&candidate.right.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!candidate.right.computed&&candidate.right.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(candidate.right.property.name==="length"||candidate.right.property.name==="byteLength")){accumulators.add(candidate.left.name)}if(candidate.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&[">",">=","<","<="].includes(candidate.operator)){for(const side of[candidate.left,candidate.right]){if(side.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)compared.add(side.name)}}for(const[key,value]of Object.entries(candidate)){if(key==="parent")continue;visit(value)}};visit(scope);return[...accumulators].some(name=>compared.has(name))};if(isDecompression()&&!hasDecompressionLimit()&&!countsOutputBytes()){context.report({node,messageId:"unlimitedFileOperations",data:{filePath:filename,line:String(node.loc.start.line)}})}if(isAllocationInLoopBody(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"resourceAllocationInLoop",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},NewExpression(node){const callee=node.callee;if(callee.type==="Identifier"&&callee.name==="Buffer"){const args=node.arguments;if(args.length>0){const sizeArg=args[0];const hasEncodingArgument=args.length>1;if(requireResourceValidation&&sizeArg.type!=="SpreadElement"&&!hasEncodingArgument&&couldBeASize(sizeArg)&&isUserInput(sizeArg)&&!hasSizeValidation(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"userControlledResourceSize",data:{filePath:filename,line:String(node.loc.start.line)}});return}const estimatedSize=sizeArg.type==="SpreadElement"?null:estimateResourceSize(sizeArg);if(estimatedSize&&estimatedSize>maxResourceSize){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"unlimitedBufferAllocation",data:{filePath:filename,line:String(node.loc.start.line)}});return}}}if(callee.type==="Identifier"&&callee.name==="Array"){const args=node.arguments;if(args.length===1){const sizeArg=args[0];if(sizeArg.type!=="SpreadElement"&&isUserInput(sizeArg)){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"unlimitedMemoryAllocation",data:{filePath:filename,line:String(node.loc.start.line)}})}}}if(isAllocationInLoopBody(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"resourceAllocationInLoop",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeRegexConstruction=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const DEFAULT_TRUSTED_ESCAPING_FUNCTIONS=["escapeRegex","escapeRegExp","escapeStringRegexp","regexpEscape"];const INLINE_ESCAPE_SUFFIX='.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\\\$&")';function taintSource(node,scope,depth=0){if(depth>6)return null;const unwrapped=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(unwrapped!==node)return taintSource(unwrapped,scope,depth+1);if(node.type==="TemplateLiteral"){for(const expression of node.expressions){const found=taintSource(expression,scope,depth+1);if(found!==null)return found}return null}if(node.type==="BinaryExpression"&&node.operator==="+"){return taintSource(node.left,scope,depth+1)??taintSource(node.right,scope,depth+1)}if(node.type==="AwaitExpression"){return taintSource(node.argument,scope,depth+1)}if(node.type==="MemberExpression"){let root=node;const properties=[];while(root.type==="MemberExpression"){if(root.property.type==="Identifier")properties.unshift(root.property.name);root=root.object}if(root.type==="Identifier"){if(REQUEST_ROOTS.has(root.name)&&properties.some(p=>REQUEST_PROPERTIES.has(p))&&isInboundRequestBinding(root,scope)){return`${root.name}.${properties.join(".")}`}if(root.name==="process"&&properties[0]==="argv"){return"process.argv"}}return null}if(node.type==="CallExpression"){const callee=node.callee;if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){if(READER_METHODS.has(callee.property.name)){return callee.property.name}}if(callee.type==="Identifier"&&READER_METHODS.has(callee.name)){return callee.name}for(const arg of node.arguments){if(arg.type==="SpreadElement")continue;const found=taintSource(arg,scope,depth+1);if(found!==null)return found}return null}if(node.type==="Identifier"){const variable=lookupVariable(node.name,scope);if(!variable)return null;for(const reference of variable.references){if(!reference.isWrite()||!reference.writeExpr)continue;const found=taintSource(reference.writeExpr,scope,depth+1);if(found!==null)return found}return null}return null}function isInboundRequestBinding(root,scope){const variable=lookupVariable(root.name,scope);if(!variable||variable.defs.length===0)return true;return variable.defs.every(def=>def.type==="Parameter")}function lookupVariable(name,scope){for(let current=scope;current;current=current.upper){const found=current.variables.find(v=>v.name===name);if(found)return found}return void 0}const REQUEST_ROOTS=new Set(["req","request","ctx","event","message"]);const REQUEST_PROPERTIES=new Set(["query","params","body","headers","url","path","cookies","data"]);const READER_METHODS=new Set(["readFile","readFileSync","text","json","arrayBuffer","formData","blob"]);const MEMBER_ESCAPERS=new Set(["escapeRegExp","escapeRegex","escapeStringRegexp","regexpEscape"]);const ESCAPER_PACKAGES=new Set(["escape-string-regexp","lodash.escaperegexp","escape-regexp","regexp.escape"]);function isEscaperPackageBinding(callee,scope){const binding=(0,eslint_devkit_1.resolveModuleBinding)(callee,scope);if(binding&&ESCAPER_PACKAGES.has(binding.module))return true;return binding?.module==="lodash"&&binding.path.at(-1)==="escapeRegExp"}function isRegExpConstructor(callee,scope,depth=0){if(depth>4)return false;if(callee.type!=="Identifier")return false;if(callee.name==="RegExp"){const shadow=lookupVariable("RegExp",scope);return shadow===void 0||shadow.defs.length===0}const variable=lookupVariable(callee.name,scope);if(!variable)return false;const writes=variable.references.filter(ref=>ref.isWrite());return writes.length>0&&writes.every(ref=>{const written=ref.writeExpr;return written!=null&&isRegExpConstructor(written,scope,depth+1)})}function isTrustedMemberEscaper(callee){if(callee.type!=="MemberExpression"||callee.computed)return false;if(callee.property.type!=="Identifier")return false;if(callee.property.name==="escape"&&callee.object.type==="Identifier"&&callee.object.name==="RegExp"){return true}return MEMBER_ESCAPERS.has(callee.property.name)}function isEscaped(node,trustedFunctions,sourceCode,scope){if(node.type==="CallExpression"&&node.callee.type==="Identifier"){const functionName=node.callee.name;if(trustedFunctions.includes(functionName)){return true}}if(node.type==="CallExpression"&&isEscaperPackageBinding(node.callee,scope)){return true}if(node.type==="CallExpression"&&isTrustedMemberEscaper(node.callee)){return true}let current=node;let depth=0;const maxDepth=5;while(depth<maxDepth){const parent=sourceCode.getNodeByRangeIndex?.(current.range[0]-1)||current.parent;if(!parent)break;if(parent.type==="CallExpression"&&parent.callee.type==="Identifier"){const functionName=parent.callee.name;if(trustedFunctions.includes(functionName)){return true}}current=parent;depth++}return false}function isRegexClone(node){if(node.type==="MemberExpression"&&!node.computed&&node.property.type==="Identifier"&&node.property.name==="source"){return true}if(node.type==="BinaryExpression"&&node.operator==="+"){return isRegexClone(node.left)||isRegexClone(node.right)}return false}function hasDynamicFlags(node){if(node.arguments.length>1){const flagsNode=node.arguments[1];return!(flagsNode.type==="Literal"&&typeof flagsNode.value==="string")}return false}function extractPattern(node,sourceCode,trustedFunctions,scope){const patternNode=node.arguments.length>0?node.arguments[0]:null;if(!patternNode){return{patternNode:null,isUserInput:false,taintedBy:null,isEscaped:false}}const taintedBy=taintSource(patternNode,scope);const isUserInputValue=taintedBy!==null;const allTrustedFunctions=[...new Set([...DEFAULT_TRUSTED_ESCAPING_FUNCTIONS,...trustedFunctions])];const isEscapedValue=isEscaped(patternNode,allTrustedFunctions,sourceCode,scope);return{patternNode,isUserInput:isUserInputValue,taintedBy,isEscaped:isEscapedValue}}exports.noUnsafeRegexConstruction=(0,eslint_devkit_2.createRule)({name:"no-unsafe-regex-construction",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-unsafe-regex-construction.md",description:"Detects unsafe regex construction patterns (user input without escaping, dynamic flags)",cwe:"CWE-400",cvss:7.5},hasSuggestions:true,messages:{unsafeRegexConstruction:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unsafe regex construction",cwe:"CWE-400",description:"{{issue}}: {{details}}",severity:"HIGH",fix:"{{fix}}",documentationLink:"https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS"}),escapeUserInput:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Escape User Input",description:"Escape user input for regex",severity:"LOW",fix:'input.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\\\$&")',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping"})},schema:[{type:"object",properties:{allowLiterals:{type:"boolean",default:true,description:"Allow literal string patterns"},trustedEscapingFunctions:{type:"array",items:{type:"string"},default:[...DEFAULT_TRUSTED_ESCAPING_FUNCTIONS],description:"Trusted functions that escape input"},maxPatternLength:{type:"number",default:100,minimum:1,description:"Maximum pattern length for dynamic regex"}},additionalProperties:false}]},defaultOptions:[{allowLiterals:true,trustedEscapingFunctions:[...DEFAULT_TRUSTED_ESCAPING_FUNCTIONS],maxPatternLength:100}],create(context,[options={}]){const{allowLiterals=true,maxPatternLength=100,trustedEscapingFunctions=[...DEFAULT_TRUSTED_ESCAPING_FUNCTIONS]}=options;const sourceCode=context.sourceCode;function checkRegExpCall(node){if(!isRegExpConstructor(node.callee,sourceCode.getScope(node))){return}const{patternNode,isUserInput:isUserInputValue,isEscaped:isEscapedValue}=extractPattern(node,sourceCode,trustedEscapingFunctions,sourceCode.getScope(node));if(!patternNode){return}if(patternNode.type==="Literal"&&typeof patternNode.value==="string"){const patternLength=patternNode.value.length;if(patternLength>maxPatternLength){context.report({node:patternNode,messageId:"unsafeRegexConstruction",data:{issue:"Pattern too long",details:`Pattern length (${patternLength}) exceeds maximum (${maxPatternLength})`,fix:"Split into smaller patterns or validate length"}});return}if(!allowLiterals){context.report({node:patternNode,messageId:"unsafeRegexConstruction",data:{issue:"Literal regex pattern",details:"Literal regex patterns should be avoided for security. Use variables instead.",fix:"Use a variable or RegExp constructor with a string variable"}});return}}if(isUserInputValue&&!isEscapedValue){const patternText=context.sourceCode.getText(patternNode);context.report({node:patternNode,messageId:"unsafeRegexConstruction",data:{issue:"User input in regex without escaping",details:"User input in regex pattern can lead to ReDoS or injection attacks",fix:"Escape special characters before using in regex"},suggest:[{messageId:"escapeUserInput",fix:fixer=>fixer.replaceText(patternNode,`(${patternText})${INLINE_ESCAPE_SUFFIX}`)}]})}if(hasDynamicFlags(node)&&!isRegexClone(patternNode)){context.report({node,messageId:"unsafeRegexConstruction",data:{issue:"Dynamic regex flags",details:"Dynamic flags can lead to unexpected behavior or security issues",fix:"Use static flags instead of dynamic flags"}})}}return{CallExpression:checkRegExpCall,NewExpression:checkRegExpCall}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeRegexConstruction=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const DEFAULT_TRUSTED_ESCAPING_FUNCTIONS=["escapeRegex","escapeRegExp","escapeStringRegexp","regexpEscape"];const INLINE_ESCAPE_SUFFIX='.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\\\$&")';function taintSource(node,scope,requestRoots,depth=0){if(depth>6)return null;const unwrapped=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(unwrapped!==node)return taintSource(unwrapped,scope,requestRoots,depth+1);if(node.type==="TemplateLiteral"){for(const expression of node.expressions){const found=taintSource(expression,scope,requestRoots,depth+1);if(found!==null)return found}return null}if(node.type==="BinaryExpression"&&node.operator==="+"){return taintSource(node.left,scope,requestRoots,depth+1)??taintSource(node.right,scope,requestRoots,depth+1)}if(node.type==="AwaitExpression"){return taintSource(node.argument,scope,requestRoots,depth+1)}if(node.type==="MemberExpression"){let root=node;const properties=[];while(root.type==="MemberExpression"){if(root.property.type==="Identifier")properties.unshift(root.property.name);root=root.object}if(root.type==="Identifier"){if(requestRoots.has(root.name)&&properties.some(p=>REQUEST_PROPERTIES.has(p))&&isInboundRequestBinding(root,scope)){return`${root.name}.${properties.join(".")}`}if(root.name==="process"&&properties[0]==="argv"){return"process.argv"}}return null}if(node.type==="CallExpression"){const callee=node.callee;if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){if(READER_METHODS.has(callee.property.name)){return callee.property.name}}if(callee.type==="Identifier"&&READER_METHODS.has(callee.name)){return callee.name}for(const arg of node.arguments){if(arg.type==="SpreadElement")continue;const found=taintSource(arg,scope,requestRoots,depth+1);if(found!==null)return found}return null}if(node.type==="Identifier"){const variable=lookupVariable(node.name,scope);if(!variable)return null;for(const reference of variable.references){if(!reference.isWrite()||!reference.writeExpr)continue;const found=taintSource(reference.writeExpr,scope,requestRoots,depth+1);if(found!==null)return found}return null}return null}function isInboundRequestBinding(root,scope){const variable=lookupVariable(root.name,scope);if(!variable||variable.defs.length===0)return true;return variable.defs.every(def=>def.type==="Parameter")}function lookupVariable(name,scope){for(let current=scope;current;current=current.upper){const found=current.variables.find(v=>v.name===name);if(found)return found}return void 0}const DEFAULT_REQUEST_ROOT_NAMES=["req","request","ctx","event","message"];const REQUEST_PROPERTIES=new Set(["query","params","body","headers","url","path","cookies","data"]);const READER_METHODS=new Set(["readFile","readFileSync","text","json","arrayBuffer","formData","blob"]);const MEMBER_ESCAPERS=new Set(["escapeRegExp","escapeRegex","escapeStringRegexp","regexpEscape"]);const ESCAPER_PACKAGES=new Set(["escape-string-regexp","lodash.escaperegexp","escape-regexp","regexp.escape"]);function isEscaperPackageBinding(callee,scope){const binding=(0,eslint_devkit_1.resolveModuleBinding)(callee,scope);if(binding&&ESCAPER_PACKAGES.has(binding.module))return true;return binding?.module==="lodash"&&binding.path.at(-1)==="escapeRegExp"}function isRegExpConstructor(callee,scope,depth=0){if(depth>4)return false;if(callee.type!=="Identifier")return false;if(callee.name==="RegExp"){const shadow=lookupVariable("RegExp",scope);return shadow===void 0||shadow.defs.length===0}const variable=lookupVariable(callee.name,scope);if(!variable)return false;const writes=variable.references.filter(ref=>ref.isWrite());return writes.length>0&&writes.every(ref=>{const written=ref.writeExpr;return written!=null&&isRegExpConstructor(written,scope,depth+1)})}function isTrustedMemberEscaper(callee){if(callee.type!=="MemberExpression"||callee.computed)return false;if(callee.property.type!=="Identifier")return false;if(callee.property.name==="escape"&&callee.object.type==="Identifier"&&callee.object.name==="RegExp"){return true}return MEMBER_ESCAPERS.has(callee.property.name)}function isEscaped(node,trustedFunctions,sourceCode,scope){if(node.type==="CallExpression"&&node.callee.type==="Identifier"){const functionName=node.callee.name;if(trustedFunctions.includes(functionName)){return true}}if(node.type==="CallExpression"&&isEscaperPackageBinding(node.callee,scope)){return true}if(node.type==="CallExpression"&&isTrustedMemberEscaper(node.callee)){return true}let current=node;let depth=0;const maxDepth=5;while(depth<maxDepth){const parent=sourceCode.getNodeByRangeIndex?.(current.range[0]-1)||current.parent;if(!parent)break;if(parent.type==="CallExpression"&&parent.callee.type==="Identifier"){const functionName=parent.callee.name;if(trustedFunctions.includes(functionName)){return true}}current=parent;depth++}return false}function isRegexClone(node){if(node.type==="MemberExpression"&&!node.computed&&node.property.type==="Identifier"&&node.property.name==="source"){return true}if(node.type==="BinaryExpression"&&node.operator==="+"){return isRegexClone(node.left)||isRegexClone(node.right)}return false}function isSameObjectPair(pattern,flags){const root=node=>node.type==="MemberExpression"&&!node.computed&&node.object.type==="Identifier"&&node.property.type==="Identifier"?node.object.name:null;const a=root(pattern);return a!==null&&a===root(flags)}function hasDynamicFlags(node){if(node.arguments.length>1){const flagsNode=node.arguments[1];return!((0,eslint_devkit_1.staticString)(flagsNode)!==null)}return false}function extractPattern(node,sourceCode,trustedFunctions,scope,requestRoots){const patternNode=node.arguments.length>0?node.arguments[0]:null;if(!patternNode){return{patternNode:null,isUserInput:false,taintedBy:null,isEscaped:false}}const taintedBy=taintSource(patternNode,scope,requestRoots);const isUserInputValue=taintedBy!==null;const allTrustedFunctions=[...new Set([...DEFAULT_TRUSTED_ESCAPING_FUNCTIONS,...trustedFunctions])];const isEscapedValue=isEscaped(patternNode,allTrustedFunctions,sourceCode,scope);return{patternNode,isUserInput:isUserInputValue,taintedBy,isEscaped:isEscapedValue}}exports.noUnsafeRegexConstruction=(0,eslint_devkit_2.createRule)({name:"no-unsafe-regex-construction",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-unsafe-regex-construction.md",description:"Detects unsafe regex construction patterns (user input without escaping, dynamic flags)",cwe:"CWE-400",cvss:7.5},hasSuggestions:true,messages:{unsafeRegexConstruction:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unsafe regex construction",cwe:"CWE-400",description:"{{issue}}: {{details}}",severity:"HIGH",fix:"{{fix}}",documentationLink:"https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS"}),escapeUserInput:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Escape User Input",description:"Escape user input for regex",severity:"LOW",fix:'input.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\\\$&")',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping"})},schema:[{type:"object",properties:{requestRootNames:{type:"array",items:{type:"string"},default:[...DEFAULT_REQUEST_ROOT_NAMES],description:"Identifier names that select a candidate inbound request. Replaces the default."},allowLiterals:{type:"boolean",default:true,description:"Allow literal string patterns"},trustedEscapingFunctions:{type:"array",items:{type:"string"},default:[...DEFAULT_TRUSTED_ESCAPING_FUNCTIONS],description:"Trusted functions that escape input"},maxPatternLength:{type:"number",default:100,minimum:1,description:"Maximum pattern length for dynamic regex"}},additionalProperties:false}]},defaultOptions:[{allowLiterals:true,trustedEscapingFunctions:[...DEFAULT_TRUSTED_ESCAPING_FUNCTIONS],maxPatternLength:100}],create(context,[options={}]){const{allowLiterals=true,maxPatternLength=100,trustedEscapingFunctions=[...DEFAULT_TRUSTED_ESCAPING_FUNCTIONS]}=options;const sourceCode=context.sourceCode;const requestRoots=new Set(options.requestRootNames??DEFAULT_REQUEST_ROOT_NAMES);function checkRegExpCall(node){if(!isRegExpConstructor(node.callee,sourceCode.getScope(node))){return}const{patternNode,isUserInput:isUserInputValue,isEscaped:isEscapedValue}=extractPattern(node,sourceCode,trustedEscapingFunctions,sourceCode.getScope(node),requestRoots);if(!patternNode){return}if(patternNode.type==="Literal"&&typeof patternNode.value==="string"){const patternLength=patternNode.value.length;if(patternLength>maxPatternLength){context.report({node:patternNode,messageId:"unsafeRegexConstruction",data:{issue:"Pattern too long",details:`Pattern length (${patternLength}) exceeds maximum (${maxPatternLength})`,fix:"Split into smaller patterns or validate length"}});return}if(!allowLiterals){context.report({node:patternNode,messageId:"unsafeRegexConstruction",data:{issue:"Literal regex pattern",details:"Literal regex patterns should be avoided for security. Use variables instead.",fix:"Use a variable or RegExp constructor with a string variable"}});return}}if(isUserInputValue&&!isEscapedValue){const patternText=context.sourceCode.getText(patternNode);context.report({node:patternNode,messageId:"unsafeRegexConstruction",data:{issue:"User input in regex without escaping",details:"User input in regex pattern can lead to ReDoS or injection attacks",fix:"Escape special characters before using in regex"},suggest:[{messageId:"escapeUserInput",fix:fixer=>fixer.replaceText(patternNode,`(${patternText})${INLINE_ESCAPE_SUFFIX}`)}]})}if(hasDynamicFlags(node)&&!isRegexClone(patternNode)&&!isSameObjectPair(patternNode,node.arguments[1])){context.report({node,messageId:"unsafeRegexConstruction",data:{issue:"Dynamic regex flags",details:"Dynamic flags can lead to unexpected behavior or security issues",fix:"Use static flags instead of dynamic flags"}})}}return{CallExpression:checkRegExpCall,NewExpression:checkRegExpCall}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noXpathInjection=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");function literalTextOf(node){if(node.type==="Literal")return typeof node.value==="string"?node.value:"";if(node.type==="TemplateLiteral")return node.quasis.map(q=>q.value.raw).join(" ");if(node.type==="BinaryExpression"&&node.operator==="+"){return`${literalTextOf(node.left)} ${literalTextOf(node.right)}`}return""}const XPATH_AXIS="ancestor-or-self|ancestor|attribute|child|descendant-or-self|descendant|following-sibling|following|namespace|parent|preceding-sibling|preceding|self";const XPATH_SYNTAX=new RegExp(`\\/\\/(?=[A-Za-z_*@.])|\\/\\*(?![\\w.*/-])|\\[@(?=[A-Za-z_*])|\\b(?:${XPATH_AXIS})::|\\btext\\(\\)|\\bnode\\(\\)|\\bcontains\\(|\\bstarts-with\\(|\\blocal-name\\(|\\bposition\\(\\)|\\/[A-Za-z_*][\\w.-]*\\[`);function looksLikeXpath(text){return XPATH_SYNTAX.test(text.replace(/:\/\//g," "))}const XPATH_SYNTAX_UNAMBIGUOUS=new RegExp(`\\/\\/(?=[A-Za-z_*@.])|\\[@(?=[A-Za-z_*])|\\b(?:${XPATH_AXIS})::|\\btext\\(\\)|\\bnode\\(\\)|\\bcontains\\(|\\bstarts-with\\(|\\blocal-name\\(|\\bposition\\(\\)|\\/[A-Za-z_*][\\w.-]*\\[`);function isWildcardOnlyXpath(text){const cleaned=text.replace(/:\/\//g," ");return XPATH_SYNTAX.test(cleaned)&&!XPATH_SYNTAX_UNAMBIGUOUS.test(cleaned)}const DEFAULT_XPATH_PACKAGES=["xpath","xmldom-xpath","xpath.js","libxmljs","libxmljs2","@xmldom/xmldom"];function isXpathModuleExport(node,scope,xpathPackages){const binding=(0,eslint_devkit_1.resolveModuleBinding)(node,scope);return binding!==void 0&&xpathPackages.has(binding.module)}exports.noXpathInjection=(0,eslint_devkit_1.createRule)({name:"no-xpath-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-xpath-injection.md",description:"Detects XPath injection vulnerabilities",cwe:"CWE-643"},messages:{xpathInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"XPath Injection",cwe:"CWE-643",description:"XPath injection vulnerability detected",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/643.html"}),unsafeXpathConcatenation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe XPath Concatenation",cwe:"CWE-643",description:"Unsafe string concatenation in XPath expression",severity:"HIGH",fix:"Use parameterized XPath or escape user input",documentationLink:"https://owasp.org/www-community/attacks/XPATH_Injection"}),unvalidatedXpathInput:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unvalidated XPath Input",cwe:"CWE-643",description:"XPath query uses unvalidated user input",severity:"MEDIUM",fix:"Validate and sanitize XPath input before use",documentationLink:"https://owasp.org/www-community/attacks/XPATH_Injection"}),dangerousXpathExpression:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous XPath Expression",cwe:"CWE-643",description:"XPath expression allows dangerous operations",severity:"MEDIUM",fix:"Restrict XPath to safe patterns and validate expressions",documentationLink:"https://cwe.mitre.org/data/definitions/643.html"})},schema:[{type:"object",properties:{reportDangerousConstructs:{type:"boolean",default:false,description:"Also report constant XPath containing ordinary axis syntax (//, text(), .., /*). These are not vulnerabilities; a constant expression has nothing to inject into. Off by default because it reported essentially every XPath in existence at CVSS 9.8."},xpathFunctions:{type:"array",items:{type:"string"},default:["evaluate","selectSingleNode","selectNodes","xpath","select","select1"],description:"XPath evaluation methods treated as query sinks"},safeXpathConstructors:{type:"array",items:{type:"string"},default:["buildXPath","createXPath","safeXPath","xpathBuilder"],description:"Builders that produce a parameterized XPath expression"},xpathValidationFunctions:{type:"array",items:{type:"string"},default:["validateXPath","escapeXPath","sanitizeXPath","cleanXPath"],description:"Function names that escape or validate XPath input"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as XPath 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)"},xpathPackages:{type:"array",items:{type:"string"},default:DEFAULT_XPATH_PACKAGES,description:"Module specifiers whose exports evaluate an XPath expression, matched against a resolved import binding. Replaces the built-in list."},additionalXpathPackages:{type:"array",items:{type:"string"},default:[],description:"Extra XPath package specifiers, on top of `xpathPackages`."}},additionalProperties:false}]},defaultOptions:[{xpathPackages:DEFAULT_XPATH_PACKAGES,additionalXpathPackages:[],xpathFunctions:["evaluate","selectSingleNode","selectNodes","xpath","select","select1"],safeXpathConstructors:["buildXPath","createXPath","safeXPath","xpathBuilder"],xpathValidationFunctions:["validateXPath","escapeXPath","sanitizeXPath","cleanXPath"],trustedSanitizers:[],trustedAnnotations:["@xpath-safe"],strictMode:false}],create(context){const options=context.options[0]||{};const{reportDangerousConstructs=false,xpathPackages=DEFAULT_XPATH_PACKAGES,additionalXpathPackages=[],xpathFunctions=["evaluate","selectSingleNode","selectNodes","xpath","select","select1"],xpathValidationFunctions=["validateXPath","escapeXPath","sanitizeXPath","cleanXPath"],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const xpathPackageSet=new Set([...xpathPackages,...additionalXpathPackages]);const sourceCode=context.sourceCode;const filename=context.filename;let moduleEvaluatesXpath=false;const wildcardPending=[];const DOM_XPATH_MEMBERS=new Set(["evaluate","selectNodes","selectSingleNode","createExpression"]);const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const validatedVariables=new Set;function everyUseAvoidsSink(node){const declarator=node.parent;if(declarator?.type!==eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator||declarator.init!==node||declarator.id.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const[variable]=context.sourceCode.getDeclaredVariables(declarator);const reads=variable.references.filter(ref=>ref.isRead());if(reads.length===0)return false;return reads.every(ref=>!reachesXpathSink(ref.identifier))}function isXpathSinkCall(call){const callee=call.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return xpathFunctions.includes(callee.name)&&isXpathModuleExport(callee,sourceCode.getScope(callee),xpathPackageSet)}return callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&xpathFunctions.includes(callee.property.name)}function reachesXpathSink(node){const parent=node.parent;if(!parent)return false;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&parent.arguments[0]===node){return isXpathSinkCall(parent)}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const declared=parent.id;const resolved=sourceCode.getScope(node).references.find(r=>r.identifier.name===declared.name)?.resolved;return(resolved?.references??[]).some(ref=>{const refParent=ref.identifier.parent;return refParent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&refParent.arguments[0]===ref.identifier&&isXpathSinkCall(refParent)})}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||parent.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return reachesXpathSink(parent)}return false}const isXpathOperation=node=>{const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&xpathFunctions.includes(callee.property.name)){if(callee.property.name!=="select"){return true}const receiver=callee.object;return receiver.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&/xpath|xpth/i.test(receiver.name)||receiver.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&receiver.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&/xpath/i.test(receiver.property.name)}if(callee.type==="Identifier"&&xpathFunctions.includes(callee.name)&&isXpathModuleExport(callee,sourceCode.getScope(callee),xpathPackageSet)){return true}return false};const containsDangerousXpath=xpathText=>{if(!reportDangerousConstructs)return false;const dangerousPatterns=[/\.\./,/\/\*/,/\[.*\*\]/,/\/\//,/text\(\)/,/comment\(\)/,/processing-instruction\(\)/];return dangerousPatterns.some(pattern=>pattern.test(xpathText))};const isUntrustedXpathInput=inputNode=>{if(inputNode.type==="MemberExpression"){if(inputNode.object.type==="MemberExpression"&&inputNode.object.object.type==="Identifier"&&inputNode.object.object.name==="req"&&inputNode.object.property.type==="Identifier"&&["query","body","params","param"].includes(inputNode.object.property.name)){return true}if(inputNode.object.type==="Identifier"&&inputNode.object.name==="req"){return true}}if(inputNode.type!=="Identifier"){return false}const varName=inputNode.name.toLowerCase();if(["req","request","query","params","input","user","search"].some(keyword=>varName.includes(keyword))){return true}let current=inputNode;while(current){if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){const func=current;return func.params.some(param=>{if(param.type==="Identifier"){return param.name===inputNode.name}return false})}current=current.parent}return false};const isXpathInputValidated=inputNode=>{let current=inputNode;while(current){if(current.type==="CallExpression"&¤t.callee.type==="Identifier"&&xpathValidationFunctions.includes(current.callee.name)){return true}current=current.parent}return false};const hasSafeAnnotationOnStatement=node=>{let current=node;while(current){if(current.type==="VariableDeclaration"||current.type==="ExpressionStatement"||current.type==="FunctionDeclaration"){const comments=sourceCode.getCommentsBefore(current);for(const comment of comments){if(comment.type==="Block"&&comment.value.includes("@xpath-safe")){return true}}}current=current.parent}return false};const declarationReachesSink=declarator=>{const name=declarator.id.name;for(let scope=context.sourceCode.getScope(declarator.id);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===name);if(variable){return variable.references.some(ref=>reachesXpathSink(ref.identifier))}}return false};return{CallExpression(node){if(!isXpathOperation(node)){return}const args=node.arguments;if(args.length===0){return}const xpathArg=args[0];if(xpathArg.type==="Literal"&&typeof xpathArg.value==="string"){const xpathText=xpathArg.value;if(containsDangerousXpath(xpathText)){if((0,eslint_devkit_3.hasSafeAnnotation)(xpathArg,context,trustedAnnotations)||hasSafeAnnotationOnStatement(node)){return}context.report({node:xpathArg,messageId:"dangerousXpathExpression",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}else if(xpathArg.type==="Identifier"){if(isUntrustedXpathInput(xpathArg)&&!isXpathInputValidated(xpathArg)&&!(xpathArg.type==="Identifier"&&validatedVariables.has(xpathArg.name))){if((0,eslint_devkit_3.hasSafeAnnotation)(xpathArg,context,trustedAnnotations)||safetyChecker.isSafe(xpathArg,context)||hasSafeAnnotationOnStatement(node)){return}context.report({node:xpathArg,messageId:"unvalidatedXpathInput",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}},ImportDeclaration(node){if(xpathPackageSet.has(String(node.source.value))){moduleEvaluatesXpath=true}},"MemberExpression[computed=false] > Identifier.property"(node){if(DOM_XPATH_MEMBERS.has(node.name)){moduleEvaluatesXpath=true}},"Program:exit"(){if(!moduleEvaluatesXpath)return;for(const pending of wildcardPending){context.report({node:pending,messageId:"unsafeXpathConcatenation",data:{filePath:filename,line:String(pending.loc.start.line)}})}},TemplateLiteral(node){const staticText=literalTextOf(node);if(/https?:\/\//.test(staticText)||/^\s*\/api\//.test(staticText)){return}if(/^\s*\/home\//.test(staticText)||/^\s*\/usr\//.test(staticText)||/^\s*\/tmp\//.test(staticText)){return}if(/\[data-[\w-]+/.test(staticText)||/\[class=/.test(staticText)||/\[id=/.test(staticText)){return}if(/\?.*=/.test(staticText)&&!/\[@/.test(staticText)){return}if(!looksLikeXpath(staticText)){return}const wildcardOnly=isWildcardOnlyXpath(staticText);if(node.expressions.length>0){const hasUntrustedInterpolation=node.expressions.some(expr=>isUntrustedXpathInput(expr)&&!isXpathInputValidated(expr)&&!(expr.type==="Identifier"&&validatedVariables.has(expr.name)));if(hasUntrustedInterpolation){if(hasSafeAnnotationOnStatement(node)){return}if(wildcardOnly){wildcardPending.push(node);return}context.report({node,messageId:"unsafeXpathConcatenation",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}if(containsDangerousXpath(staticText)&&reachesXpathSink(node)){if(hasSafeAnnotationOnStatement(node)){return}context.report({node,messageId:"dangerousXpathExpression",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},BinaryExpression(node){if(node.operator!=="+"){return}if(!looksLikeXpath(literalTextOf(node))){return}const isInnerConcat=node.parent?.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.parent.operator==="+";if(isInnerConcat){return}const operands=[];(function flatten(n){if(n.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&n.operator==="+"){flatten(n.left);flatten(n.right);return}operands.push(n)})(node);const unvalidated=operand=>!isXpathInputValidated(operand)&&!(operand.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&validatedVariables.has(operand.name));const hasUntrusted=operands.some(operand=>isUntrustedXpathInput(operand)&&unvalidated(operand));const dynamicAtSink=reachesXpathSink(node)&&operands.some(operand=>!(0,eslint_devkit_1.isStaticExpression)({node:operand,scope:context.sourceCode.getScope(operand)})&&unvalidated(operand));if((hasUntrusted||dynamicAtSink)&&!everyUseAvoidsSink(node)){if(safetyChecker.isSafe(node,context)||hasSafeAnnotationOnStatement(node)){return}context.report({node,messageId:"xpathInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Use parameterized XPath construction with input validation"}})}},VariableDeclarator(node){const declLine=String(node.loc?.start.line??0);if(!node.init||node.id.type!=="Identifier"){return}const varName=node.id.name;if(node.init.type==="CallExpression"&&node.init.callee.type==="Identifier"&&(xpathValidationFunctions.includes(node.init.callee.name)||trustedSanitizers.includes(node.init.callee.name))){validatedVariables.add(varName)}const varNameLower=varName.toLowerCase();if(!varNameLower.includes("xpath")&&!varNameLower.includes("query")&&!varNameLower.includes("path")){return}if(node.init.type==="Literal"&&typeof node.init.value==="string"){if(looksLikeXpath(node.init.value)&&containsDangerousXpath(node.init.value)){if(safetyChecker.isSafe(node.init,context)||hasSafeAnnotationOnStatement(node)){return}context.report({node:node.init,messageId:"dangerousXpathExpression",data:{filePath:filename,line:declLine}})}}else if(isUntrustedXpathInput(node.init)&&declarationReachesSink(node)&&!isUntrustedXpathInput(node.id)){context.report({node:node.init,messageId:"xpathInjection",data:{filePath:filename,line:declLine,severity:"MEDIUM",safeAlternative:"Use safe XPath construction methods"}})}}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noXpathInjection=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");function literalTextOf(node){if(node.type==="Literal")return typeof node.value==="string"?node.value:"";if(node.type==="TemplateLiteral")return node.quasis.map(q=>q.value.raw).join(" ");if(node.type==="BinaryExpression"&&node.operator==="+"){return`${literalTextOf(node.left)} ${literalTextOf(node.right)}`}return""}const XPATH_AXIS="ancestor-or-self|ancestor|attribute|child|descendant-or-self|descendant|following-sibling|following|namespace|parent|preceding-sibling|preceding|self";const XPATH_SYNTAX=new RegExp(`\\/\\/(?=[A-Za-z_*@.])|\\/\\*(?![\\w.*/-])|\\[@(?=[A-Za-z_*])|\\b(?:${XPATH_AXIS})::|\\btext\\(\\)|\\bnode\\(\\)|\\bcontains\\(|\\bstarts-with\\(|\\blocal-name\\(|\\bposition\\(\\)|\\/[A-Za-z_*][\\w.-]*\\[`);function looksLikeXpath(text){return XPATH_SYNTAX.test(text.replace(/:\/\//g," "))}const XPATH_SYNTAX_UNAMBIGUOUS=new RegExp(`\\/\\/(?=[A-Za-z_*@.])|\\[@(?=[A-Za-z_*])|\\b(?:${XPATH_AXIS})::|\\btext\\(\\)|\\bnode\\(\\)|\\bcontains\\(|\\bstarts-with\\(|\\blocal-name\\(|\\bposition\\(\\)|\\/[A-Za-z_*][\\w.-]*\\[`);function isWildcardOnlyXpath(text){const cleaned=text.replace(/:\/\//g," ");return XPATH_SYNTAX.test(cleaned)&&!XPATH_SYNTAX_UNAMBIGUOUS.test(cleaned)}const DEFAULT_XPATH_PACKAGES=["xpath","xmldom-xpath","xpath.js","libxmljs","libxmljs2","@xmldom/xmldom"];function isXpathModuleExport(node,scope,xpathPackages){const binding=(0,eslint_devkit_1.resolveModuleBinding)(node,scope);return binding!==void 0&&xpathPackages.has(binding.module)}exports.noXpathInjection=(0,eslint_devkit_1.createRule)({name:"no-xpath-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-xpath-injection.md",description:"Detects XPath injection vulnerabilities",cwe:"CWE-643"},messages:{xpathInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"XPath Injection",cwe:"CWE-643",description:"XPath injection vulnerability detected",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/643.html"}),unsafeXpathConcatenation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe XPath Concatenation",cwe:"CWE-643",description:"Unsafe string concatenation in XPath expression",severity:"HIGH",fix:"Use parameterized XPath or escape user input",documentationLink:"https://owasp.org/www-community/attacks/XPATH_Injection"}),unvalidatedXpathInput:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unvalidated XPath Input",cwe:"CWE-643",description:"XPath query uses unvalidated user input",severity:"MEDIUM",fix:"Validate and sanitize XPath input before use",documentationLink:"https://owasp.org/www-community/attacks/XPATH_Injection"}),dangerousXpathExpression:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous XPath Expression",cwe:"CWE-643",description:"XPath expression allows dangerous operations",severity:"MEDIUM",fix:"Restrict XPath to safe patterns and validate expressions",documentationLink:"https://cwe.mitre.org/data/definitions/643.html"})},schema:[{type:"object",properties:{reportDangerousConstructs:{type:"boolean",default:false,description:"Also report constant XPath containing ordinary axis syntax (//, text(), .., /*). These are not vulnerabilities; a constant expression has nothing to inject into. Off by default because it reported essentially every XPath in existence at CVSS 9.8."},xpathFunctions:{type:"array",items:{type:"string"},default:["evaluate","selectSingleNode","selectNodes","xpath","select","select1"],description:"XPath evaluation methods treated as query sinks"},safeXpathConstructors:{type:"array",items:{type:"string"},default:["buildXPath","createXPath","safeXPath","xpathBuilder"],description:"Builders that produce a parameterized XPath expression"},xpathValidationFunctions:{type:"array",items:{type:"string"},default:["validateXPath","escapeXPath","sanitizeXPath","cleanXPath"],description:"Function names that escape or validate XPath input"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as XPath 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)"},xpathPackages:{type:"array",items:{type:"string"},default:DEFAULT_XPATH_PACKAGES,description:"Module specifiers whose exports evaluate an XPath expression, matched against a resolved import binding. Replaces the built-in list."},additionalXpathPackages:{type:"array",items:{type:"string"},default:[],description:"Extra XPath package specifiers, on top of `xpathPackages`."}},additionalProperties:false}]},defaultOptions:[{xpathPackages:DEFAULT_XPATH_PACKAGES,additionalXpathPackages:[],xpathFunctions:["evaluate","selectSingleNode","selectNodes","xpath","select","select1"],safeXpathConstructors:["buildXPath","createXPath","safeXPath","xpathBuilder"],xpathValidationFunctions:["validateXPath","escapeXPath","sanitizeXPath","cleanXPath"],trustedSanitizers:[],trustedAnnotations:["@xpath-safe"],strictMode:false}],create(context){const options=context.options[0]||{};const{reportDangerousConstructs=false,xpathPackages=DEFAULT_XPATH_PACKAGES,additionalXpathPackages=[],xpathFunctions=["evaluate","selectSingleNode","selectNodes","xpath","select","select1"],xpathValidationFunctions=["validateXPath","escapeXPath","sanitizeXPath","cleanXPath"],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const xpathPackageSet=new Set([...xpathPackages,...additionalXpathPackages]);const sourceCode=context.sourceCode;const filename=context.filename;let moduleEvaluatesXpath=false;const wildcardPending=[];const DOM_XPATH_MEMBERS=new Set(["evaluate","selectNodes","selectSingleNode","createExpression"]);const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const validatedVariables=new Set;function everyUseAvoidsSink(node){const declarator=node.parent;if(declarator?.type!==eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator||declarator.init!==node||declarator.id.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const[variable]=context.sourceCode.getDeclaredVariables(declarator);const reads=variable.references.filter(ref=>ref.isRead());if(reads.length===0)return false;return reads.every(ref=>!reachesXpathSink(ref.identifier))}function isXpathSinkCall(call){const callee=call.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return xpathFunctions.includes(callee.name)&&isXpathModuleExport(callee,sourceCode.getScope(callee),xpathPackageSet)}return callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&xpathFunctions.includes(callee.property.name)}function reachesXpathSink(node){const parent=node.parent;if(!parent)return false;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&parent.arguments[0]===node){return isXpathSinkCall(parent)}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const declared=parent.id;const resolved=sourceCode.getScope(node).references.find(r=>r.identifier.name===declared.name)?.resolved;return(resolved?.references??[]).some(ref=>{const refParent=ref.identifier.parent;return refParent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&refParent.arguments[0]===ref.identifier&&isXpathSinkCall(refParent)})}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||parent.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return reachesXpathSink(parent)}return false}const isXpathOperation=node=>{const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&xpathFunctions.includes(callee.property.name)){if(callee.property.name!=="select"){return true}const receiver=callee.object;return receiver.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&/xpath|xpth/i.test(receiver.name)||receiver.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&receiver.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&/xpath/i.test(receiver.property.name)}if(callee.type==="Identifier"&&xpathFunctions.includes(callee.name)&&isXpathModuleExport(callee,sourceCode.getScope(callee),xpathPackageSet)){return true}return false};const containsDangerousXpath=xpathText=>{if(!reportDangerousConstructs)return false;const dangerousPatterns=[/\.\./,/\/\*/,/\[.*\*\]/,/\/\//,/text\(\)/,/comment\(\)/,/processing-instruction\(\)/];return dangerousPatterns.some(pattern=>pattern.test(xpathText))};const isUntrustedXpathInput=inputNode=>{if(inputNode.type==="MemberExpression"){if(inputNode.object.type==="MemberExpression"&&inputNode.object.object.type==="Identifier"&&inputNode.object.object.name==="req"&&inputNode.object.property.type==="Identifier"&&["query","body","params","param"].includes(inputNode.object.property.name)){return true}if(inputNode.object.type==="Identifier"&&inputNode.object.name==="req"){return true}}if(inputNode.type!=="Identifier"){return false}const varName=inputNode.name.toLowerCase();if(["req","request","query","params","input","user","search"].some(keyword=>varName.includes(keyword))){return true}let current=inputNode;while(current){if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){const func=current;return func.params.some(param=>{if(param.type==="Identifier"){return param.name===inputNode.name}return false})}current=current.parent}return false};const isXpathInputValidated=inputNode=>{let current=inputNode;while(current){if(current.type==="CallExpression"&¤t.callee.type==="Identifier"&&xpathValidationFunctions.includes(current.callee.name)){return true}current=current.parent}return false};const hasSafeAnnotationOnStatement=node=>{let current=node;while(current){if(current.type==="VariableDeclaration"||current.type==="ExpressionStatement"||current.type==="FunctionDeclaration"){const comments=sourceCode.getCommentsBefore(current);for(const comment of comments){if(comment.type==="Block"&&comment.value.includes("@xpath-safe")){return true}}}current=current.parent}return false};const declarationReachesSink=declarator=>{const name=declarator.id.name;for(let scope=context.sourceCode.getScope(declarator.id);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===name);if(variable){return variable.references.some(ref=>reachesXpathSink(ref.identifier))}}return false};return{CallExpression(node){if(!isXpathOperation(node)){return}const args=node.arguments;if(args.length===0){return}const xpathArg=args[0];const staticText=xpathArg.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral?null:(0,eslint_devkit_1.staticString)(xpathArg);if(staticText!==null){const xpathText=staticText;if(containsDangerousXpath(xpathText)){if((0,eslint_devkit_3.hasSafeAnnotation)(xpathArg,context,trustedAnnotations)||hasSafeAnnotationOnStatement(node)){return}context.report({node:xpathArg,messageId:"dangerousXpathExpression",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}else if(xpathArg.type==="Identifier"){if(isUntrustedXpathInput(xpathArg)&&!isXpathInputValidated(xpathArg)&&!(xpathArg.type==="Identifier"&&validatedVariables.has(xpathArg.name))){if((0,eslint_devkit_3.hasSafeAnnotation)(xpathArg,context,trustedAnnotations)||safetyChecker.isSafe(xpathArg,context)||hasSafeAnnotationOnStatement(node)){return}context.report({node:xpathArg,messageId:"unvalidatedXpathInput",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}},ImportDeclaration(node){if(xpathPackageSet.has(String(node.source.value))){moduleEvaluatesXpath=true}},"MemberExpression[computed=false] > Identifier.property"(node){if(DOM_XPATH_MEMBERS.has(node.name)){moduleEvaluatesXpath=true}},"Program:exit"(){if(!moduleEvaluatesXpath)return;for(const pending of wildcardPending){context.report({node:pending,messageId:"unsafeXpathConcatenation",data:{filePath:filename,line:String(pending.loc.start.line)}})}},TemplateLiteral(node){const staticText=literalTextOf(node);if(/https?:\/\//.test(staticText)||/^\s*\/api\//.test(staticText)){return}if(/^\s*\/home\//.test(staticText)||/^\s*\/usr\//.test(staticText)||/^\s*\/tmp\//.test(staticText)){return}if(/\[data-[\w-]+/.test(staticText)||/\[class=/.test(staticText)||/\[id=/.test(staticText)){return}if(/\?.*=/.test(staticText)&&!/\[@/.test(staticText)){return}if(!looksLikeXpath(staticText)){return}const wildcardOnly=isWildcardOnlyXpath(staticText);if(node.expressions.length>0){const hasUntrustedInterpolation=node.expressions.some(expr=>isUntrustedXpathInput(expr)&&!isXpathInputValidated(expr)&&!(expr.type==="Identifier"&&validatedVariables.has(expr.name)));if(hasUntrustedInterpolation){if(hasSafeAnnotationOnStatement(node)){return}if(wildcardOnly){wildcardPending.push(node);return}context.report({node,messageId:"unsafeXpathConcatenation",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}if(containsDangerousXpath(staticText)&&reachesXpathSink(node)){if(hasSafeAnnotationOnStatement(node)){return}context.report({node,messageId:"dangerousXpathExpression",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},BinaryExpression(node){if(node.operator!=="+"){return}if(!looksLikeXpath(literalTextOf(node))){return}const isInnerConcat=node.parent?.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.parent.operator==="+";if(isInnerConcat){return}const operands=[];(function flatten(n){if(n.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&n.operator==="+"){flatten(n.left);flatten(n.right);return}operands.push(n)})(node);const unvalidated=operand=>!isXpathInputValidated(operand)&&!(operand.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&validatedVariables.has(operand.name));const hasUntrusted=operands.some(operand=>isUntrustedXpathInput(operand)&&unvalidated(operand));const dynamicAtSink=reachesXpathSink(node)&&operands.some(operand=>!(0,eslint_devkit_1.isStaticExpression)({node:operand,scope:context.sourceCode.getScope(operand)})&&unvalidated(operand));if((hasUntrusted||dynamicAtSink)&&!everyUseAvoidsSink(node)){if(safetyChecker.isSafe(node,context)||hasSafeAnnotationOnStatement(node)){return}context.report({node,messageId:"xpathInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Use parameterized XPath construction with input validation"}})}},VariableDeclarator(node){const declLine=String(node.loc?.start.line??0);if(!node.init||node.id.type!=="Identifier"){return}const varName=node.id.name;if(node.init.type==="CallExpression"&&node.init.callee.type==="Identifier"&&(xpathValidationFunctions.includes(node.init.callee.name)||trustedSanitizers.includes(node.init.callee.name))){validatedVariables.add(varName)}const varNameLower=varName.toLowerCase();if(!varNameLower.includes("xpath")&&!varNameLower.includes("query")&&!varNameLower.includes("path")){return}if(node.init.type==="Literal"&&typeof node.init.value==="string"){if(looksLikeXpath(node.init.value)&&containsDangerousXpath(node.init.value)){if(safetyChecker.isSafe(node.init,context)||hasSafeAnnotationOnStatement(node)){return}context.report({node:node.init,messageId:"dangerousXpathExpression",data:{filePath:filename,line:declLine}})}}else if(isUntrustedXpathInput(node.init)&&declarationReachesSink(node)&&!isUntrustedXpathInput(node.id)){context.report({node:node.init,messageId:"xpathInjection",data:{filePath:filename,line:declLine,severity:"MEDIUM",safeAlternative:"Use safe XPath construction methods"}})}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noXxeInjection=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");const DEFAULT_SAFE_PARSER_OPTIONS=["noent","resolveExternals","expandEntityReferences","entityResolver","processEntities","dtdload"];const DEFAULT_XML_VALIDATION_FUNCTIONS=["validateXml","sanitizeXml","cleanXml","parseXmlSafe"];const DEFAULT_XML_MODULES=["libxmljs","libxmljs2","xml2js","xml2json","fast-xml-parser","@xmldom/xmldom","xmldom","node-expat"];const PROVEN_NO_EXTERNAL_ENTITIES=["xml2js","fast-xml-parser","@xmldom/xmldom","xmldom"];const DEFAULT_XML_PARSE_METHODS=["parseFromString","parseString","parseStringPromise","parseXml","parseXmlAsync","parseXmlString","parseXML"];const DEFAULT_DANGEROUS_PARSER_OPTIONS=["resolveExternals","expandEntityReferences","noent","processEntities","dtdload"];const optionKey=prop=>{if(prop.type!==eslint_devkit_3.AST_NODE_TYPES.Property||prop.computed)return void 0;if(prop.key.type===eslint_devkit_3.AST_NODE_TYPES.Identifier)return prop.key.name;return prop.key.type===eslint_devkit_3.AST_NODE_TYPES.Literal&&typeof prop.key.value==="string"?prop.key.value:void 0};const hasDangerousParserOptions=(optionsNode,dangerousKeys)=>{if(optionsNode?.type!==eslint_devkit_3.AST_NODE_TYPES.ObjectExpression)return false;for(const prop of optionsNode.properties){const key=optionKey(prop);if(key===void 0||!dangerousKeys.has(key))continue;const{value}=prop;if(value.type===eslint_devkit_3.AST_NODE_TYPES.Literal&&value.value===true)return true}return false};const containsDangerousEntities=xmlText=>{return/<!ENTITY/i.test(xmlText)&&/SYSTEM\s+["']/i.test(xmlText)};exports.noXxeInjection=(0,eslint_devkit_1.createRule)({name:"no-xxe-injection",meta:{type:"problem",docs:{description:"Detect XML External Entity (XXE) injection vulnerabilities",url:"https://cwe.mitre.org/data/definitions/611.html",cwe:"CWE-611",cvss:9.1},messages:{xxeInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"XXE Injection",cwe:"CWE-611",description:"XML contains dangerous entity declarations",severity:"CRITICAL",fix:"Remove SYSTEM/PUBLIC entity declarations or use safe XML parser",documentationLink:"https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"}),unsafeXmlParser:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe XML Parser",cwe:"CWE-611",description:"Using unsafe XML parser without secure configuration",severity:"HIGH",fix:"Use libxmljs with noent: false or xmldom with entityResolver: null",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html"}),externalEntityEnabled:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"External Entity Processing",cwe:"CWE-611",description:"External entity processing is enabled",severity:"CRITICAL",fix:"Disable external entity processing",documentationLink:"https://cwe.mitre.org/data/definitions/611.html"}),untrustedXmlSource:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Untrusted XML Source",cwe:"CWE-611",description:"XML from untrusted source without validation",severity:"HIGH",fix:"Validate and sanitize XML input before parsing",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html"})},schema:[{type:"object",properties:{safeParserOptions:{type:"array",items:{type:"string"},default:DEFAULT_SAFE_PARSER_OPTIONS,description:"Parser option keys whose disabled value proves entity expansion is off"},xmlValidationFunctions:{type:"array",items:{type:"string"},default:DEFAULT_XML_VALIDATION_FUNCTIONS,description:"Function names that count as XML input validation"},xmlModules:{type:"array",items:{type:"string"},default:DEFAULT_XML_MODULES,description:"Module specifiers this rule treats as XML parsers, matched against a resolved import binding. Replaces the built-in list."},additionalXmlModules:{type:"array",items:{type:"string"},default:[],description:"Extra XML package specifiers, on top of `xmlModules`."},xmlParseMethods:{type:"array",items:{type:"string"},default:DEFAULT_XML_PARSE_METHODS,description:"Method names that only ever parse XML, matched as an exact method name whatever the receiver. Replaces the built-in list."},additionalXmlParseMethods:{type:"array",items:{type:"string"},default:[],description:"Extra XML-only parse method names, on top of `xmlParseMethods`."},dangerousParserOptions:{type:"array",items:{type:"string"},default:DEFAULT_DANGEROUS_PARSER_OPTIONS,description:"Parser option keys whose `true` value turns entity expansion ON. Replaces the built-in list."},entityIncapableModules:{type:"array",items:{type:"string"},default:PROVEN_NO_EXTERNAL_ENTITIES,description:"Packages proven unable to resolve an external entity, and therefore never reported for parsing untrusted input. Replaces the built-in list."},additionalDangerousParserOptions:{type:"array",items:{type:"string"},default:[],description:"Extra entity-expansion option keys, on top of `dangerousParserOptions`."}},additionalProperties:false}]},defaultOptions:[{safeParserOptions:DEFAULT_SAFE_PARSER_OPTIONS,xmlValidationFunctions:DEFAULT_XML_VALIDATION_FUNCTIONS,xmlModules:DEFAULT_XML_MODULES,additionalXmlModules:[],xmlParseMethods:DEFAULT_XML_PARSE_METHODS,additionalXmlParseMethods:[],dangerousParserOptions:DEFAULT_DANGEROUS_PARSER_OPTIONS,additionalDangerousParserOptions:[],entityIncapableModules:PROVEN_NO_EXTERNAL_ENTITIES}],create(context,[options]){const{safeParserOptions=DEFAULT_SAFE_PARSER_OPTIONS,xmlValidationFunctions=DEFAULT_XML_VALIDATION_FUNCTIONS,xmlModules=DEFAULT_XML_MODULES,additionalXmlModules=[],xmlParseMethods=DEFAULT_XML_PARSE_METHODS,additionalXmlParseMethods=[],dangerousParserOptions=DEFAULT_DANGEROUS_PARSER_OPTIONS,additionalDangerousParserOptions=[],entityIncapableModules=PROVEN_NO_EXTERNAL_ENTITIES}=options;const xmlPackages=new Set([...xmlModules,...additionalXmlModules]);const incapablePackages=new Set(entityIncapableModules);const parseMethods=new Set([...xmlParseMethods,...additionalXmlParseMethods]);const dangerousKeys=new Set([...dangerousParserOptions,...additionalDangerousParserOptions]);const filename=context.filename;const sourceCode=context.sourceCode;const isHtmlParse=node=>{const mime=node.arguments[1];return mime!==void 0&&mime.type===eslint_devkit_3.AST_NODE_TYPES.Literal&&typeof mime.value==="string"&&mime.value.toLowerCase().startsWith("text/html")};const reportData=node=>({filePath:filename,line:String(node.loc.start.line)});const resolvesToXmlModule=node=>{const binding=(0,eslint_devkit_1.resolveModuleBinding)(node,sourceCode.getScope(node));return binding!==void 0&&xmlPackages.has(binding.module)};const resolvesToEntityIncapableModule=node=>{const binding=(0,eslint_devkit_1.resolveModuleBinding)(node,sourceCode.getScope(node));return binding!==void 0&&incapablePackages.has(binding.module)};const constructionSite=callee=>{if(callee.type!==eslint_devkit_3.AST_NODE_TYPES.MemberExpression)return void 0;const receiver=callee.object;if(receiver.type===eslint_devkit_3.AST_NODE_TYPES.NewExpression)return receiver;if(receiver.type!==eslint_devkit_3.AST_NODE_TYPES.Identifier)return void 0;const variable=sourceCode.getScope(receiver).references.find(reference=>reference.identifier===receiver)?.resolved;const definition=variable?.defs[0];if(definition?.type!=="Variable")return void 0;if(variable.references.filter(reference=>reference.isWrite()).length!==1){return void 0}return definition.node.init?.type===eslint_devkit_3.AST_NODE_TYPES.NewExpression?definition.node.init:void 0};const isXmlParsingCall=node=>{const callee=node.callee;if(callee.type===eslint_devkit_3.AST_NODE_TYPES.MemberExpression&&!callee.computed&&callee.property.type===eslint_devkit_3.AST_NODE_TYPES.Identifier&&parseMethods.has(callee.property.name)){return true}if(hasDangerousParserOptions(node.arguments[1],dangerousKeys))return true;if(resolvesToXmlModule(callee))return true;const construction=constructionSite(callee);return construction!==void 0&&resolvesToXmlModule(construction.callee)};const hasSecureParserOptions=optionsNode=>{if(optionsNode?.type!==eslint_devkit_3.AST_NODE_TYPES.ObjectExpression)return false;for(const prop of optionsNode.properties){const key=optionKey(prop);if(key===void 0||!safeParserOptions.includes(key))continue;const{value}=prop;if(value.type!==eslint_devkit_3.AST_NODE_TYPES.Literal)continue;if(value.value===false||value.value===null)return true}return false};const isXmlInputValidated=xmlSource=>{let current=xmlSource;while(current){if(current.type===eslint_devkit_3.AST_NODE_TYPES.CallExpression&¤t.callee.type===eslint_devkit_3.AST_NODE_TYPES.Identifier&&xmlValidationFunctions.includes(current.callee.name)){return true}current=current.parent}return false};const isTrustedXmlSource=xmlSource=>(0,eslint_devkit_1.isStaticExpression)({node:xmlSource,scope:sourceCode.getScope(xmlSource)});return{CallExpression(node){if(!isXmlParsingCall(node))return;const xmlInput=node.arguments[0];if(!xmlInput)return;if(isHtmlParse(node))return;const callOptions=node.arguments[1];const construction=constructionSite(node.callee);const constructionOptions=construction?.arguments[0];if(hasDangerousParserOptions(callOptions,dangerousKeys)){context.report({node:callOptions,messageId:"externalEntityEnabled",data:reportData(node)});return}if(hasDangerousParserOptions(constructionOptions,dangerousKeys)){context.report({node:node.callee,messageId:"unsafeXmlParser",data:reportData(node)});return}if(hasSecureParserOptions(callOptions)||hasSecureParserOptions(constructionOptions)){return}if(isTrustedXmlSource(xmlInput)||isXmlInputValidated(xmlInput))return;if(resolvesToEntityIncapableModule(node.callee)||construction!==void 0&&resolvesToEntityIncapableModule(construction.callee)){return}context.report({node:xmlInput,messageId:"untrustedXmlSource",data:reportData(node)})},Literal(node){if(typeof node.value==="string"&&containsDangerousEntities(node.value)){context.report({node,messageId:"xxeInjection",data:reportData(node)})}},TemplateElement(node){if(containsDangerousEntities(node.value.raw)){context.report({node,messageId:"xxeInjection",data:reportData(node)})}}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noXxeInjection=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");const DEFAULT_SAFE_PARSER_OPTIONS=["noent","resolveExternals","expandEntityReferences","entityResolver","processEntities","dtdload"];const DEFAULT_XML_VALIDATION_FUNCTIONS=["validateXml","sanitizeXml","cleanXml","parseXmlSafe"];const DEFAULT_XML_MODULES=["libxmljs","libxmljs2","xml2js","xml2json","fast-xml-parser","@xmldom/xmldom","xmldom","node-expat"];const PROVEN_NO_EXTERNAL_ENTITIES=["xml2js","fast-xml-parser","@xmldom/xmldom","xmldom"];const DEFAULT_XML_PARSE_METHODS=["parseFromString","parseString","parseStringPromise","parseXml","parseXmlAsync","parseXmlString","parseXML"];const DEFAULT_DANGEROUS_PARSER_OPTIONS=["resolveExternals","expandEntityReferences","noent","processEntities","dtdload"];const optionKey=prop=>{if(prop.type!==eslint_devkit_3.AST_NODE_TYPES.Property||prop.computed)return void 0;if(prop.key.type===eslint_devkit_3.AST_NODE_TYPES.Identifier)return prop.key.name;return(0,eslint_devkit_1.staticString)(prop.key)??void 0};const hasDangerousParserOptions=(optionsNode,dangerousKeys)=>{if(optionsNode?.type!==eslint_devkit_3.AST_NODE_TYPES.ObjectExpression)return false;for(const prop of optionsNode.properties){const key=optionKey(prop);if(key===void 0||!dangerousKeys.has(key))continue;const{value}=prop;if(value.type===eslint_devkit_3.AST_NODE_TYPES.Literal&&value.value===true)return true}return false};const containsDangerousEntities=xmlText=>{return/<!ENTITY/i.test(xmlText)&&/SYSTEM\s+["']/i.test(xmlText)};exports.noXxeInjection=(0,eslint_devkit_1.createRule)({name:"no-xxe-injection",meta:{type:"problem",docs:{description:"Detect XML External Entity (XXE) injection vulnerabilities",url:"https://cwe.mitre.org/data/definitions/611.html",cwe:"CWE-611",cvss:9.1},messages:{xxeInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"XXE Injection",cwe:"CWE-611",description:"XML contains dangerous entity declarations",severity:"CRITICAL",fix:"Remove SYSTEM/PUBLIC entity declarations or use safe XML parser",documentationLink:"https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"}),unsafeXmlParser:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe XML Parser",cwe:"CWE-611",description:"Using unsafe XML parser without secure configuration",severity:"HIGH",fix:"Use libxmljs with noent: false or xmldom with entityResolver: null",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html"}),externalEntityEnabled:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"External Entity Processing",cwe:"CWE-611",description:"External entity processing is enabled",severity:"CRITICAL",fix:"Disable external entity processing",documentationLink:"https://cwe.mitre.org/data/definitions/611.html"}),untrustedXmlSource:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Untrusted XML Source",cwe:"CWE-611",description:"XML from untrusted source without validation",severity:"HIGH",fix:"Validate and sanitize XML input before parsing",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html"})},schema:[{type:"object",properties:{safeParserOptions:{type:"array",items:{type:"string"},default:DEFAULT_SAFE_PARSER_OPTIONS,description:"Parser option keys whose disabled value proves entity expansion is off"},xmlValidationFunctions:{type:"array",items:{type:"string"},default:DEFAULT_XML_VALIDATION_FUNCTIONS,description:"Function names that count as XML input validation"},xmlModules:{type:"array",items:{type:"string"},default:DEFAULT_XML_MODULES,description:"Module specifiers this rule treats as XML parsers, matched against a resolved import binding. Replaces the built-in list."},additionalXmlModules:{type:"array",items:{type:"string"},default:[],description:"Extra XML package specifiers, on top of `xmlModules`."},xmlParseMethods:{type:"array",items:{type:"string"},default:DEFAULT_XML_PARSE_METHODS,description:"Method names that only ever parse XML, matched as an exact method name whatever the receiver. Replaces the built-in list."},additionalXmlParseMethods:{type:"array",items:{type:"string"},default:[],description:"Extra XML-only parse method names, on top of `xmlParseMethods`."},dangerousParserOptions:{type:"array",items:{type:"string"},default:DEFAULT_DANGEROUS_PARSER_OPTIONS,description:"Parser option keys whose `true` value turns entity expansion ON. Replaces the built-in list."},entityIncapableModules:{type:"array",items:{type:"string"},default:PROVEN_NO_EXTERNAL_ENTITIES,description:"Packages proven unable to resolve an external entity, and therefore never reported for parsing untrusted input. Replaces the built-in list."},additionalDangerousParserOptions:{type:"array",items:{type:"string"},default:[],description:"Extra entity-expansion option keys, on top of `dangerousParserOptions`."}},additionalProperties:false}]},defaultOptions:[{safeParserOptions:DEFAULT_SAFE_PARSER_OPTIONS,xmlValidationFunctions:DEFAULT_XML_VALIDATION_FUNCTIONS,xmlModules:DEFAULT_XML_MODULES,additionalXmlModules:[],xmlParseMethods:DEFAULT_XML_PARSE_METHODS,additionalXmlParseMethods:[],dangerousParserOptions:DEFAULT_DANGEROUS_PARSER_OPTIONS,additionalDangerousParserOptions:[],entityIncapableModules:PROVEN_NO_EXTERNAL_ENTITIES}],create(context,[options]){const{safeParserOptions=DEFAULT_SAFE_PARSER_OPTIONS,xmlValidationFunctions=DEFAULT_XML_VALIDATION_FUNCTIONS,xmlModules=DEFAULT_XML_MODULES,additionalXmlModules=[],xmlParseMethods=DEFAULT_XML_PARSE_METHODS,additionalXmlParseMethods=[],dangerousParserOptions=DEFAULT_DANGEROUS_PARSER_OPTIONS,additionalDangerousParserOptions=[],entityIncapableModules=PROVEN_NO_EXTERNAL_ENTITIES}=options;const xmlPackages=new Set([...xmlModules,...additionalXmlModules]);const incapablePackages=new Set(entityIncapableModules);const parseMethods=new Set([...xmlParseMethods,...additionalXmlParseMethods]);const dangerousKeys=new Set([...dangerousParserOptions,...additionalDangerousParserOptions]);const filename=context.filename;const sourceCode=context.sourceCode;const isHtmlParse=node=>{const mime=node.arguments[1];return mime!==void 0&&mime.type===eslint_devkit_3.AST_NODE_TYPES.Literal&&typeof mime.value==="string"&&mime.value.toLowerCase().startsWith("text/html")};const reportData=node=>({filePath:filename,line:String(node.loc.start.line)});const resolvesToXmlModule=node=>{const binding=(0,eslint_devkit_1.resolveModuleBinding)(node,sourceCode.getScope(node));return binding!==void 0&&xmlPackages.has(binding.module)};const resolvesToEntityIncapableModule=node=>{const binding=(0,eslint_devkit_1.resolveModuleBinding)(node,sourceCode.getScope(node));return binding!==void 0&&incapablePackages.has(binding.module)};const constructionSite=callee=>{if(callee.type!==eslint_devkit_3.AST_NODE_TYPES.MemberExpression)return void 0;const receiver=callee.object;if(receiver.type===eslint_devkit_3.AST_NODE_TYPES.NewExpression)return receiver;if(receiver.type!==eslint_devkit_3.AST_NODE_TYPES.Identifier)return void 0;const variable=sourceCode.getScope(receiver).references.find(reference=>reference.identifier===receiver)?.resolved;const definition=variable?.defs[0];if(definition?.type!=="Variable")return void 0;if(variable.references.filter(reference=>reference.isWrite()).length!==1){return void 0}return definition.node.init?.type===eslint_devkit_3.AST_NODE_TYPES.NewExpression?definition.node.init:void 0};const isXmlParsingCall=node=>{const callee=node.callee;if(callee.type===eslint_devkit_3.AST_NODE_TYPES.MemberExpression&&!callee.computed&&callee.property.type===eslint_devkit_3.AST_NODE_TYPES.Identifier&&parseMethods.has(callee.property.name)){return true}if(hasDangerousParserOptions(node.arguments[1],dangerousKeys))return true;if(resolvesToXmlModule(callee))return true;const construction=constructionSite(callee);return construction!==void 0&&resolvesToXmlModule(construction.callee)};const hasSecureParserOptions=optionsNode=>{if(optionsNode?.type!==eslint_devkit_3.AST_NODE_TYPES.ObjectExpression)return false;for(const prop of optionsNode.properties){const key=optionKey(prop);if(key===void 0||!safeParserOptions.includes(key))continue;const{value}=prop;if(value.type!==eslint_devkit_3.AST_NODE_TYPES.Literal)continue;if(value.value===false||value.value===null)return true}return false};const isXmlInputValidated=xmlSource=>{let current=xmlSource;while(current){if(current.type===eslint_devkit_3.AST_NODE_TYPES.CallExpression&¤t.callee.type===eslint_devkit_3.AST_NODE_TYPES.Identifier&&xmlValidationFunctions.includes(current.callee.name)){return true}current=current.parent}return false};const isTrustedXmlSource=xmlSource=>(0,eslint_devkit_1.isStaticExpression)({node:xmlSource,scope:sourceCode.getScope(xmlSource)});return{CallExpression(node){if(!isXmlParsingCall(node))return;const xmlInput=node.arguments[0];if(!xmlInput)return;if(isHtmlParse(node))return;const callOptions=node.arguments[1];const construction=constructionSite(node.callee);const constructionOptions=construction?.arguments[0];if(hasDangerousParserOptions(callOptions,dangerousKeys)){context.report({node:callOptions,messageId:"externalEntityEnabled",data:reportData(node)});return}if(hasDangerousParserOptions(constructionOptions,dangerousKeys)){context.report({node:node.callee,messageId:"unsafeXmlParser",data:reportData(node)});return}if(hasSecureParserOptions(callOptions)||hasSecureParserOptions(constructionOptions)){return}if(isTrustedXmlSource(xmlInput)||isXmlInputValidated(xmlInput))return;if(resolvesToEntityIncapableModule(node.callee)||construction!==void 0&&resolvesToEntityIncapableModule(construction.callee)){return}context.report({node:xmlInput,messageId:"untrustedXmlSource",data:reportData(node)})},Literal(node){if(typeof node.value==="string"&&containsDangerousEntities(node.value)){context.report({node,messageId:"xxeInjection",data:reportData(node)})}},TemplateElement(node){if(containsDangerousEntities(node.value.raw)){context.report({node,messageId:"xxeInjection",data:reportData(node)})}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireBackendAuthorization=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_AUTH_PROPERTIES=["role","roles","isAdmin","isAuthenticated","isAuthorized","permissions","admin"];const DEFAULT_BROWSER_GLOBALS=["window","document","localStorage","sessionStorage","navigator"];const DEFAULT_SERVER_MODULES=["express","fastify","koa","@hapi/hapi","@nestjs/common","@nestjs/core","next/server","http","https","node:http","node:https"];const memberPropertyName=node=>{if(node.computed){return
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireBackendAuthorization=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_AUTH_PROPERTIES=["role","roles","isAdmin","isAuthenticated","isAuthorized","permissions","admin"];const DEFAULT_BROWSER_GLOBALS=["window","document","localStorage","sessionStorage","navigator"];const DEFAULT_SERVER_MODULES=["express","fastify","koa","@hapi/hapi","@nestjs/common","@nestjs/core","next/server","http","https","node:http","node:https"];const memberPropertyName=node=>{if(node.computed){return(0,eslint_devkit_1.staticString)(node.property)??void 0}return node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?node.property.name:void 0};exports.requireBackendAuthorization=(0,eslint_devkit_1.createRule)({name:"require-backend-authorization",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/require-backend-authorization.md",description:"Require server-side authorization checks",cwe:"CWE-602",cvss:6.5},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Client-Side Authorization",cwe:"CWE-602",description:"Authorization logic in client code - easily bypassed",severity:"CRITICAL",fix:"Move authorization checks to server-side API endpoints",documentationLink:"https://cwe.mitre.org/data/definitions/602.html"})},schema:[{type:"object",properties:{authProperties:{type:"array",items:{type:"string"},default:DEFAULT_AUTH_PROPERTIES,description:"Property names that hold an authorization claim, matched as an exact property name. Replaces the built-in list."},additionalAuthProperties:{type:"array",items:{type:"string"},default:[],description:"Extra claim property names, on top of `authProperties`."},browserGlobals:{type:"array",items:{type:"string"},default:DEFAULT_BROWSER_GLOBALS,description:"Globals whose unresolved reference proves the file runs in a browser. Replaces the built-in list."},additionalBrowserGlobals:{type:"array",items:{type:"string"},default:[],description:"Extra browser-only globals, on top of `browserGlobals`."},serverModules:{type:"array",items:{type:"string"},default:DEFAULT_SERVER_MODULES,description:"Module specifiers that can only load in a server process; importing one suppresses the finding. Replaces the built-in list."},additionalServerModules:{type:"array",items:{type:"string"},default:[],description:"Extra server-only module specifiers, on top of `serverModules`."}},additionalProperties:false}]},defaultOptions:[{authProperties:DEFAULT_AUTH_PROPERTIES,additionalAuthProperties:[],browserGlobals:DEFAULT_BROWSER_GLOBALS,additionalBrowserGlobals:[],serverModules:DEFAULT_SERVER_MODULES,additionalServerModules:[]}],create(context,[options={}]){const{authProperties=DEFAULT_AUTH_PROPERTIES,additionalAuthProperties=[],browserGlobals=DEFAULT_BROWSER_GLOBALS,additionalBrowserGlobals=[],serverModules=DEFAULT_SERVER_MODULES,additionalServerModules=[]}=options;const authNames=new Set([...authProperties,...additionalAuthProperties]);const browserNames=new Set([...browserGlobals,...additionalBrowserGlobals]);const serverSpecifiers=new Set([...serverModules,...additionalServerModules]);const sourceCode=context.sourceCode;const candidates=[];const claimBackedVariables=new Set;const indirectTests=[];let hasJsx=false;const noteIndirect=(test,node)=>{if(test.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)indirectTests.push({node,identifier:test})};const resolveReference=identifier=>{for(let scope=sourceCode.getScope(identifier);scope;scope=scope.upper){const reference=scope.references.find(entry=>entry.identifier===identifier);if(reference)return reference.resolved??void 0}return void 0};return{JSXElement(){hasJsx=true},JSXFragment(){hasJsx=true},MemberExpression(node){const property=memberPropertyName(node);if(property===void 0||!authNames.has(property))return;let current=node;for(let parent=node.parent;parent;current=parent,parent=parent.parent){if(parent.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement&&parent.test===current){candidates.push(parent);return}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.SwitchStatement&&parent.discriminant===current){candidates.push(parent);return}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.init===current){for(const variable of sourceCode.getDeclaredVariables(parent)){claimBackedVariables.add(variable)}return}}},IfStatement(node){noteIndirect(node.test,node)},SwitchStatement(node){noteIndirect(node.discriminant,node)},"Program:exit"(program){for(const{node,identifier}of indirectTests){const resolved=resolveReference(identifier);if(!resolved||!claimBackedVariables.has(resolved))continue;if(resolved.references.filter(reference=>reference.isWrite()).length!==1)continue;candidates.push(node)}if(candidates.length===0)return;const importsServerModule=program.body.some(statement=>statement.type===eslint_devkit_1.AST_NODE_TYPES.ImportDeclaration&&serverSpecifiers.has(String(statement.source.value)));if(importsServerModule)return;const hasUseClient=program.body.some(statement=>statement.type===eslint_devkit_1.AST_NODE_TYPES.ExpressionStatement&&statement.directive==="use client");const touchesBrowserGlobal=sourceCode.getScope(program).through.some(reference=>browserNames.has(reference.identifier.name));if(!hasUseClient&&!hasJsx&&!touchesBrowserGlobal)return;for(const node of candidates){context.report({node,messageId:"violationDetected"})}}}}});
|