eslint-plugin-secure-coding 5.5.1 → 5.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/package.json +1 -1
- package/src/index.js +1 -1
- package/src/rules/detect-object-injection/index.js +1 -1
- package/src/rules/no-directive-injection/index.js +1 -1
- package/src/rules/no-format-string-injection/index.js +1 -1
- package/src/rules/no-hardcoded-credentials/index.js +1 -1
- package/src/rules/no-pii-in-logs/index.js +1 -1
- package/src/rules/no-sql-injection/index.js +1 -1
- package/src/rules/no-template-injection/index.js +1 -1
- package/src/rules/no-unchecked-loop-condition/index.js +1 -1
- package/src/rules/no-unlimited-resource-allocation/index.js +1 -1
- package/src/rules/no-unsafe-deserialization/index.js +1 -1
- package/src/rules/no-weak-password-recovery/index.js +1 -1
- package/src/rules/no-xpath-injection/index.js +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noHardcodedCredentials=void 0;exports.isNaturalWordString=isNaturalWordString;exports.looksRandom=looksRandom;exports.isStyleToken=isStyleToken;exports.isSecretShaped=isSecretShaped;exports.isPlaceholderValue=isPlaceholderValue;exports.isPublishableKeyValue=isPublishableKeyValue;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const CREDENTIAL_PATTERNS={apiKey:/^(?:[A-Za-z0-9_-]{32,}|sk_[A-Za-z0-9_-]{32,}|pk_[A-Za-z0-9_-]{32,}|AKIA[0-9A-Z]{16})$/,jwtToken:/^eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,oauthToken:/^(?:ghp_|gho_|ghu_|ghs_|ghr_)[A-Za-z0-9]{36,}$/,awsAccessKey:/^AKIA[0-9A-Z]{16}$/,databaseString:/^(?:mysql|postgres|mongodb|redis):\/\/[^:]+:[^@]+@/,commonPassword:/^(?:password|admin|123456|qwerty|letmein|welcome|monkey|1234567890|12345678|password123|root|test|guest)$/i,secretKey:/^(?:[A-Za-z0-9+/]{32,}={0,2}|[A-Fa-f0-9]{32,})$/};const CREDENTIAL_VARIABLE_NAMES=new Set(["apikey","api_key","apiKey","secret","secretkey","secret_key","secretKey","clientsecret","client_secret","clientSecret","token","authtoken","auth_token","authToken","accesstoken","access_token","accessToken","refreshtoken","refresh_token","refreshToken","idtoken","id_token","idToken","password","passwd","pass","pwd","privatekey","private_key","privateKey","credentials","creds","authorization","auth","connectionstring","connection_string","connectionString","connectionuri","connectionURI","dburl","db_url","dbUrl","databaseurl","database_url","databaseUrl"]);const WORD_SEPARATORS=new Set(["_","-","."," "]);function shannonEntropy(value){const freq=new Map;for(const ch of value)freq.set(ch,(freq.get(ch)??0)+1);let entropy=0;for(const count of freq.values()){const p=count/value.length;entropy-=p*Math.log2(p)}return entropy}function charClasses(value){const classes={lower:false,upper:false,digit:false,symbol:false};for(const ch of value){if(WORD_SEPARATORS.has(ch))continue;if(ch>="a"&&ch<="z")classes.lower=true;else if(ch>="A"&&ch<="Z")classes.upper=true;else if(ch>="0"&&ch<="9")classes.digit=true;else classes.symbol=true}return classes}function classCount(classes){return Number(classes.lower)+Number(classes.upper)+Number(classes.digit)+Number(classes.symbol)}function isPronounceable(token){const lower=token.toLowerCase();if(!/[aeiouy]/.test(lower))return false;if(/[bcdfghjklmnpqrstvwxz]{4,}/.test(lower))return false;return true}function isNaturalWordString(value){if(!/^[A-Za-z][A-Za-z0-9_\-. ]*$/.test(value))return false;const digits=value.replace(/[^0-9]/g,"").length;if(digits>0&&(digits/value.length>.2||/[0-9]{4,}/.test(value)))return false;const tokens=value.replace(/([a-z])([A-Z])/g,"$1 $2").split(/[^A-Za-z]+/).filter(Boolean);const meaningful=tokens.filter(t=>t.length>=3);if(meaningful.length===0)return false;if(meaningful.every(isPronounceable))return true;if(/[0-9]/.test(value))return false;const waived=meaningful.filter(token=>!isPronounceable(token));if(waived.some(token=>token.length>4))return false;return waived.length*2<=meaningful.length}function hasSequentialRun(value,min=5){let run=1;for(let i=1;i<value.length;i++){run=value.charCodeAt(i)===value.charCodeAt(i-1)+1?run+1:1;if(run>=min)return true}return false}function looksRandom(value){if(value.length<20)return false;if(!/^[A-Za-z0-9]+$/.test(value))return false;const classes=charClasses(value);if(!classes.lower||!classes.upper||!classes.digit)return false;if(hasSequentialRun(value))return false;if(isNaturalWordString(value))return false;return shannonEntropy(value)>=3.5}const CONTEXT_FREE_RANDOM_LENGTH=32;function isStyleToken(value){if(/\b(?:var|env)\(\s*--[\w-]+/.test(value))return true;if(/^--[a-z][\w-]*$/i.test(value))return true;if(/^[a-z][\w-]*-\[[^\]]+\]$/i.test(value))return true;return false}function isUrlOrPath(value){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(value)){return!/^[^/]*\/\/[^/@]*:[^/@]*@/.test(value)}const rooted=value.replace(/^(?:<[A-Za-z_$][\w$]*>|\[[A-Za-z_$][\w$]*\])(?=\/)/,"");if(rooted!==value)return isUrlOrPath(rooted);if(!value.startsWith("/")||value.startsWith("//"))return false;const path=value.split(/[?#]/)[0];const segments=path.slice(1).split("/");if(!segments.every(segment=>/^[A-Za-z0-9._~%:@-]*$/.test(segment))){return false}const looksGenerated=segment=>/[a-z]/.test(segment)&&/[A-Z]/.test(segment)&&/[0-9]/.test(segment);if(segments.length===1){return!looksGenerated(segments[0])}return!segments.some(segment=>segment.length>=16&&looksGenerated(segment))}function echoesItsOwnSlotName(value,slotName){if(slotName==="")return false;const fold=text=>text.replace(/[-_.\s]/g,"").toLowerCase();return fold(value)===fold(slotName)}function isSecretShaped(value,minLength){if(value.length<minLength)return false;if(/\s/.test(value))return false;if(isUrlOrPath(value))return false;if(isStyleToken(value))return false;if(isNaturalWordString(value))return false;if(classCount(charClasses(value))>=2)return true;return value.length>=20&&shannonEntropy(value)>=3}const DEFAULT_PLACEHOLDER_WORDS=["changeme","change","replaceme","replace","yours","your","placeholder","example","sample","dummy","todo","tbd","redacted","notreal","xxx"];function isPlaceholderValue(value,words){const trimmed=value.trim();if(trimmed.length===0)return false;if(/^(?:<.*>|\{\{.*\}\}|\$\{.*\}|\[.*\])$/.test(trimmed))return true;const dunder=/^__(.+)__$/.exec(trimmed);if(dunder!==null){const inner=dunder[1];const candidate=inner.trim();return/^[^A-Za-z]*[A-Z]{3,}/.test(candidate)&&!looksRandom(candidate)}if(trimmed.length>=4&&new Set(trimmed).size===1)return true;const tokens=trimmed.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return tokens.some(token=>words.has(token))}function isPublishableKeyValue(value){if(/^pk_(?:live|test)_[A-Za-z0-9_-]{8,}$/.test(value))return true;if(/^phc_[A-Za-z0-9]{20,}$/.test(value))return true;if(/^https?:\/\/[A-Za-z0-9]+@[A-Za-z0-9.-]+(?::\d+)?\/\d+$/.test(value)){return true}if(/^0x[A-Fa-f0-9]{40}$/.test(value))return true;return false}const SECRET_SIDE_VALUE=/^(?:sk|rk)_(?:live|test)_|^sk-[A-Za-z0-9]|^gh[pousr]_|^ph[xs]_|^sntry[su]_|^xox[baprs]-|^AKIA[0-9A-Z]{16}$|^ey[A-Za-z0-9_-]+\.ey|-----BEGIN|^(?:mysql|postgres|mongodb|redis):\/\//;const SECRET_SIDE_SLOT=/secret|private|signing|password|passwd|serviceaccount|serverkey|adminkey|masterkey/;const PUBLISHABLE_VENDORS=[{vendor:"Bugsnag",packages:["bugsnag","bugsnag-js","bugsnag-build-reporter","bugsnag-sourcemaps"],scopes:["@bugsnag"],named:/bugsnag/,slots:/^(?:bugsnag)?(?:notifier)?(?:api)?key$/},{vendor:"Sentry",scopes:["@sentry"],named:/sentry/,slots:/^(?:sentry)?dsn$/},{vendor:"PostHog",packages:["posthog-js","posthog-node"],named:/posthog/,slots:/^(?:posthog)?(?:project)?(?:api)?key$/},{vendor:"Segment",packages:["analytics-node"],scopes:["@segment"],named:/segment/,slots:/^(?:segment)?write(?:key|token)$/},{vendor:"Amplitude",packages:["amplitude-js"],scopes:["@amplitude"],named:/amplitude/,slots:/^(?:amplitude)?(?:api)?key$/},{vendor:"Mixpanel",packages:["mixpanel","mixpanel-browser"],named:/mixpanel/,slots:/^(?:mixpanel)?(?:project)?token$/},{vendor:"Firebase",packages:["firebase"],scopes:["@firebase"],named:/firebase/,slots:/^(?:firebase)?(?:web)?apikey$/}];const VENDOR_PROBES=PUBLISHABLE_VENDORS.map(entry=>({entry,loadsSdk:(0,eslint_devkit_2.createModuleEvidence)({packages:entry.packages,scopes:entry.scopes})}));function slotNameOf(parent){if(parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){return parent.id.name.toLowerCase()}if(parent.type==="Property"){const key=parent.key;if(key.type==="Identifier")return key.name.toLowerCase();return String(key.value).toLowerCase()}if(parent.type==="AssignmentExpression"){const left=parent.left;if(left.type==="MemberExpression"){const named=(0,eslint_devkit_1.propertyName)(left);if(named!==null)return named.toLowerCase()}}return""}function looksLikeCredential(value,options,ignorePatterns){const NONE={isCredential:false,type:"",confidence:"ambiguous"};if(ignorePatterns.some(pattern=>pattern.test(value)))return NONE;for(const customPattern of options.customPatterns){try{const regex=new RegExp(customPattern.pattern);if(regex.test(value)){return{isCredential:true,type:customPattern.type,confidence:"structural"}}}catch{continue}}if(options.detectPasswords&&CREDENTIAL_PATTERNS.commonPassword.test(value)){return{isCredential:true,type:"Common password",confidence:"ambiguous"}}if(options.detectDatabaseStrings&&CREDENTIAL_PATTERNS.databaseString.test(value)){return{isCredential:true,type:"Database connection string",confidence:"structural"}}if(value.length<options.minLength)return NONE;if(options.detectTokens&&CREDENTIAL_PATTERNS.jwtToken.test(value)){return{isCredential:true,type:"JWT token",confidence:"structural"}}if(options.detectTokens&&CREDENTIAL_PATTERNS.oauthToken.test(value)){return{isCredential:true,type:"OAuth token",confidence:"structural"}}if(options.detectApiKeys&&CREDENTIAL_PATTERNS.awsAccessKey.test(value)){return{isCredential:true,type:"AWS access key",confidence:"structural"}}if(options.detectApiKeys&&/^(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9_-]{16,}$/.test(value)){return{isCredential:true,type:"API key",confidence:"structural"}}if(options.detectApiKeys&&looksRandom(value)){return{isCredential:true,type:"Secret key",confidence:value.length>=CONTEXT_FREE_RANDOM_LENGTH?"structural":"ambiguous"}}if(value.length>=32&&CREDENTIAL_PATTERNS.secretKey.test(value)&&!isNaturalWordString(value)){return{isCredential:true,type:"Secret key",confidence:"ambiguous"}}if(options.detectApiKeys&&/^[A-Za-z0-9_-]{32,}$/.test(value)&&!isNaturalWordString(value)){return{isCredential:true,type:"API key",confidence:"ambiguous"}}return NONE}exports.noHardcodedCredentials=(0,eslint_devkit_2.createRule)({name:"no-hardcoded-credentials",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-hardcoded-credentials.md",description:"Detects hardcoded passwords, API keys, tokens, and other sensitive credentials",cwe:"CWE-798",cvss:9.8,confidence:"medium"},fixable:"code",hasSuggestions:true,messages:{useEnvironmentVariable:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Hard-coded Credential",cwe:"CWE-798",description:"Hard-coded {{credentialType}} detected",severity:"CRITICAL",fix:"Use environment variable: process.env.{{envVarName}} or secret management service",documentationLink:"https://cwe.mitre.org/data/definitions/798.html"}),useSecretManager:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Use Secret Manager",cwe:"CWE-798",description:"Use secure secret management service",severity:"HIGH",fix:"Use AWS Secrets Manager, HashiCorp Vault, Azure Key Vault, or similar",documentationLink:"https://cwe.mitre.org/data/definitions/798.html"})},schema:[{type:"object",properties:{credentialWords:{type:"array",items:{type:"string"},default:[...CREDENTIAL_VARIABLE_NAMES],description:"Variable and property names this project uses for a credential. REPLACES the default list."},ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Regex patterns to ignore"},allowInTests:{type:"boolean",default:true,description:"Allow credentials in test files"},minLength:{type:"number",default:8,description:"Minimum length for credential detection"},detectApiKeys:{type:"boolean",default:true,description:"Detect API keys"},detectPasswords:{type:"boolean",default:true,description:"Detect passwords"},detectTokens:{type:"boolean",default:true,description:"Detect tokens"},detectDatabaseStrings:{type:"boolean",default:true,description:"Detect database connection strings"},customPatterns:{type:"array",items:{type:"object",properties:{type:{type:"string",description:'The type of credential (e.g., "API key", "token")'},pattern:{type:"string",description:"Regex pattern to match"}},required:["type","pattern"],additionalProperties:false},default:[],description:"Custom credential patterns to detect"},allowPlaceholders:{type:"boolean",default:true,description:"Skip self-evident placeholder values (`<your-secret-here>`, `changeme`, `xxxxxxxx`)"},placeholderWords:{type:"array",items:{type:"string"},default:DEFAULT_PLACEHOLDER_WORDS,description:"Words that mark a value as a self-evident stand-in rather than a secret, matched as a WHOLE token inside the value and never as a substring. Replaces the built-in list. Read only when `allowPlaceholders` is true."},additionalPlaceholderWords:{type:"array",items:{type:"string"},default:[],description:"Extra placeholder words, on top of `placeholderWords`."}},additionalProperties:false}]},defaultOptions:[{ignorePatterns:[],allowInTests:true,minLength:8,detectApiKeys:true,detectPasswords:true,detectTokens:true,detectDatabaseStrings:true,customPatterns:[],allowPlaceholders:true,placeholderWords:DEFAULT_PLACEHOLDER_WORDS,additionalPlaceholderWords:[]}],createOnce(context){let credentialWords;let ignorePatterns;let allowInTests;let minLength;let detectApiKeys;let detectPasswords;let detectTokens;let detectDatabaseStrings;let customPatterns;let allowPlaceholders;let placeholderWords;let additionalPlaceholderWords;let placeholderWordSet;let isTestFile;let compiledIgnorePatterns;let detectionOptions;let LABEL_CONTEXT_NAMES;let loadedVendors;function isLabelContext(node,parent){if(!parent)return false;if(parent.type==="ObjectExpression"){const grand=parent.parent;if(grand)return isLabelContext(node,grand);return false}if(parent.type==="ArrayExpression"){const grand=parent.parent;if(grand)return isLabelContext(node,grand);return false}if(parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){const n=parent.id.name.toLowerCase();if(LABEL_CONTEXT_NAMES.has(n)||n==="labels"||n.endsWith("label")||n.endsWith("labels")||n.endsWith("name")||n.endsWith("placeholder"))return true}if(parent.type==="AssignmentExpression"&&parent.right===node){const left=parent.left;if(left.type==="MemberExpression"){const slot=(0,eslint_devkit_1.propertyName)(left);if(slot!==null&&LABEL_CONTEXT_NAMES.has(slot))return true}}if(parent.type==="Property"&&parent.value===node){const key=parent.key;const keyText=key.type==="Identifier"?key.name:(0,eslint_devkit_1.staticString)(key)!==null?(0,eslint_devkit_1.staticString)(key):null;if(keyText!==null&&node.type==="Literal"&&typeof node.value==="string"){const keyTokens=keyText.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase().split(/[^A-Z0-9]+/).filter(Boolean);if(keyTokens.includes(node.value.toUpperCase()))return true}if(key.type==="Identifier"&&LABEL_CONTEXT_NAMES.has(key.name))return true;if(key.type==="Literal"&&typeof key.value==="string"){if(LABEL_CONTEXT_NAMES.has(key.value))return true}const obj=parent.parent;if(obj?.type==="ObjectExpression"){const grand=obj.parent;if(grand)return isLabelContext(node,grand)}}if(parent.type==="CallExpression"&&parent.callee.type==="MemberExpression"&&parent.callee.property.type==="Identifier"){const callee=parent.callee;const methodName=callee.property.name;if(methodName==="setAttribute"||methodName==="getAttribute"){const args=parent.arguments;if(args[1]===node)return true}}if(parent.type==="JSXAttribute")return true;return false}function inferCredentialTypeFromContext(parent){const name=slotNameOf(parent);if(/(?:^|[_-])(password|passwd|pass|pwd)$/.test(name))return"password";if(/(?:^|[_-])(token|authtoken|auth_token|accesstoken|access_token|refreshtoken|refresh_token|idtoken|id_token)$/.test(name))return"token";if(/(?:^|[_-])(dburl|db_url|databaseurl|database_url|connectionstring|connection_string|connectionuri)$/.test(name))return"database";if(/(?:^|[_-])(apikey|api_key|secretkey|secret_key|privatekey|private_key|secret|key|clientsecret|client_secret)$/.test(name))return"apikey";return"other"}function isCredentialContext(node,parent){if(!parent)return false;const matches=name=>{const lower=name.toLowerCase();if(lower==="key"||lower==="keys"){return node.type==="Literal"&&typeof node.value==="string"&&looksRandom(node.value)}const singular=lower.endsWith("s")?lower.slice(0,-1):lower;if(credentialWords.has(lower)||credentialWords.has(singular))return true;return[...credentialWords].some(word=>lower.endsWith(word)||lower.endsWith(`${word}s`))};if(parent.type==="ArrayExpression"){const grand=parent.parent;if(grand)return isCredentialContext(node,grand);return false}if(parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){if(matches(parent.id.name))return true}if(parent.type==="AssignmentExpression"&&parent.right===node){const left=parent.left;if(left.type==="MemberExpression"){const slot=(0,eslint_devkit_1.propertyName)(left);if(slot!==null&&matches(slot))return true}if(left.type==="Identifier"){if(matches(left.name))return true}}if(parent.type==="Property"&&parent.value===node){const key=parent.key;if(key.type==="Identifier"&&matches(key.name))return true;if(key.type==="Literal"&&typeof key.value==="string"){if(matches(key.value))return true}}return false}function vendorsInFile(){if(loadedVendors===null){const found=new Set;for(const{entry,loadsSdk}of VENDOR_PROBES){if(loadsSdk(context.sourceCode.ast))found.add(entry.vendor)}loadedVendors=found}return loadedVendors}function isPublishableKey(value,parent){if(SECRET_SIDE_VALUE.test(value))return false;if(isPublishableKeyValue(value))return true;const slot=slotNameOf(parent);if(slot===""||SECRET_SIDE_SLOT.test(slot))return false;for(const{entry}of VENDOR_PROBES){if(!entry.named.test(slot)&&!vendorsInFile().has(entry.vendor)){continue}if(entry.slots.test(slot))return true}return false}function checkStringLiteral(node,parent){if(typeof node.value!=="string"){return}const value=node.value;if(isTestFile){return}if(parent?.type==="LogicalExpression"&&parent.operator==="||"&&parent.right===node){const left=parent.left;if(left.type==="MemberExpression"&&left.object.type==="MemberExpression"&&left.object.object.type==="Identifier"&&left.object.object.name==="process"&&(0,eslint_devkit_1.propertyName)(left.object)==="env"){return}}if(isLabelContext(node,parent)){return}const{isCredential,type,confidence}=looksLikeCredential(value,detectionOptions,compiledIgnorePatterns);let finalIsCredential=isCredential;let finalType=type;if(isCredential&&confidence==="ambiguous"&&!isCredentialContext(node,parent)){finalIsCredential=false}const echoesSlot=confidence!=="structural"&&parent!==void 0&&echoesItsOwnSlotName(value,slotNameOf(parent));if(echoesSlot){finalIsCredential=false}const isPlaceholder=allowPlaceholders&&isPlaceholderValue(value,placeholderWordSet);if(isPlaceholder&&confidence!=="structural"){finalIsCredential=false}if(!finalIsCredential&&!isPlaceholder&&!echoesSlot&&!compiledIgnorePatterns.some(pattern=>pattern.test(value))&&isSecretShaped(value,detectionOptions.minLength)&&isCredentialContext(node,parent)){const ctxType=inferCredentialTypeFromContext(parent);const optionAllows=ctxType==="password"&&detectionOptions.detectPasswords||ctxType==="token"&&detectionOptions.detectTokens||ctxType==="database"&&detectionOptions.detectDatabaseStrings||ctxType==="apikey"&&detectionOptions.detectApiKeys||ctxType==="other";if(optionAllows){finalIsCredential=true;finalType=type||"Credential value"}}if(!finalIsCredential){return}if(isPublishableKey(value,parent)){return}let envVarName="API_KEY";if(parent&&parent.type==="Property"&&parent.key.type==="Identifier"){const keyName=parent.key.name;envVarName=keyName.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase().replace(/[^A-Z0-9_]/g,"_")}else if(parent&&parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){const varName=parent.id.name;envVarName=varName.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase().replace(/[^A-Z0-9_]/g,"_")}context.report({node,messageId:"useEnvironmentVariable",data:{credentialType:finalType,envVarName},suggest:[{messageId:"useEnvironmentVariable",data:{envVarName,credentialType:finalType},fix:fixer=>{return fixer.replaceText(node,`process.env.${envVarName} || '${value}'`)}},{messageId:"useSecretManager",data:{credentialType:finalType},fix:fixer=>{return fixer.replaceText(node,`await getSecret('${envVarName.toLowerCase()}')`)}}]})}return{before(){const options=context.options[0]||{};credentialWords=new Set((options.credentialWords??[...CREDENTIAL_VARIABLE_NAMES]).map(w=>w.toLowerCase()));({ignorePatterns=[],allowInTests=true,minLength=8,detectApiKeys=true,detectPasswords=true,detectTokens=true,detectDatabaseStrings=true,customPatterns=[],allowPlaceholders=true,placeholderWords=DEFAULT_PLACEHOLDER_WORDS,additionalPlaceholderWords=[]}=options);placeholderWordSet=new Set([...placeholderWords,...additionalPlaceholderWords]);const filename=context.filename;isTestFile=allowInTests&&(0,eslint_devkit_2.isTestFilePath)(filename);compiledIgnorePatterns=(0,eslint_devkit_1.compileUserPatterns)(ignorePatterns);detectionOptions={minLength,detectApiKeys,detectPasswords,detectTokens,detectDatabaseStrings,customPatterns};LABEL_CONTEXT_NAMES=new Set(["type","name","id","placeholder","label","title","role","autocomplete","autoFocus","autocapitalize","inputmode","aria-label","aria-labelledby","aria-describedby","fieldName","fieldType","fieldLabel","inputType","inputName","displayName","columnName","paramName","i18nKey","translationKey","messageKey"]);loadedVendors=null},Literal(node){checkStringLiteral(node,node.parent)},TemplateLiteral(node){if(node.expressions.length===0){const fullText=node.quasis.map(q=>q.value.raw).join("");const{isCredential,type,confidence}=looksLikeCredential(fullText,detectionOptions,compiledIgnorePatterns);if(isCredential&&!isTestFile&&confidence==="structural"){context.report({node,messageId:"useEnvironmentVariable",data:{credentialType:type,envVarName:"API_KEY"},suggest:[{messageId:"useEnvironmentVariable",data:{envVarName:"API_KEY",credentialType:type},fix:fixer=>{return fixer.replaceText(node,`process.env.API_KEY || \`${fullText}\``)}},{messageId:"useSecretManager",data:{credentialType:type},fix:fixer=>{return fixer.replaceText(node,`await getSecret('api_key')`)}}]})}}else{for(const quasi of node.quasis){if(quasi.value.raw){const{isCredential,type,confidence}=looksLikeCredential(quasi.value.raw,detectionOptions,compiledIgnorePatterns);if(isCredential&&!isTestFile&&confidence==="structural"){context.report({node:quasi,messageId:"useEnvironmentVariable",data:{credentialType:type,envVarName:"API_KEY"}})}}}}}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noHardcodedCredentials=void 0;exports.isNaturalWordString=isNaturalWordString;exports.looksRandom=looksRandom;exports.isStyleToken=isStyleToken;exports.isSecretShaped=isSecretShaped;exports.isPlaceholderValue=isPlaceholderValue;exports.isPublishableKeyValue=isPublishableKeyValue;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const CREDENTIAL_PATTERNS={jwtToken:/^eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,oauthToken:/^(?:ghp_|gho_|ghu_|ghs_|ghr_)[A-Za-z0-9]{36,}$/,awsAccessKey:/^AKIA[0-9A-Z]{16}$/,databaseString:/^(?:mysql|postgres|mongodb|redis):\/\/[^:]+:[^@]+@/,commonPassword:/^(?:password|admin|123456|qwerty|letmein|welcome|monkey|1234567890|12345678|password123|root|test|guest)$/i,secretKey:/^[A-Za-z0-9+/]{32,}={0,2}$/};const CREDENTIAL_VARIABLE_NAMES=new Set(["apikey","api_key","apiKey","secret","secretkey","secret_key","secretKey","clientsecret","client_secret","clientSecret","token","authtoken","auth_token","authToken","accesstoken","access_token","accessToken","refreshtoken","refresh_token","refreshToken","idtoken","id_token","idToken","password","passwd","pass","pwd","privatekey","private_key","privateKey","credentials","creds","authorization","auth","connectionstring","connection_string","connectionString","connectionuri","connectionURI","dburl","db_url","dbUrl","databaseurl","database_url","databaseUrl"]);function shannonEntropy(value){const freq=new Map;for(const ch of value)freq.set(ch,(freq.get(ch)??0)+1);let entropy=0;for(const count of freq.values()){const p=count/value.length;entropy-=p*Math.log2(p)}return entropy}function charClasses(value){return{lower:/[a-z]/.test(value),upper:/[A-Z]/.test(value),digit:/[0-9]/.test(value),symbol:/[^A-Za-z0-9_\-. ]/.test(value)}}function classCount(classes){return Number(classes.lower)+Number(classes.upper)+Number(classes.digit)+Number(classes.symbol)}function isPronounceable(token){const lower=token.toLowerCase();if(!/[aeiouy]/.test(lower))return false;if(/[bcdfghjklmnpqrstvwxz]{4,}/.test(lower))return false;return true}function isNaturalWordString(value){if(!/^[A-Za-z][A-Za-z0-9_\-. ]*$/.test(value))return false;const digits=value.replace(/[^0-9]/g,"").length;if(digits/value.length>.2||/[0-9]{4,}/.test(value))return false;const meaningful=value.replace(/([a-z])([A-Z])/g,"$1 $2").split(/[^A-Za-z]+/).filter(t=>t.length>=3);if(meaningful.length===0)return false;if(meaningful.every(isPronounceable))return true;if(/[0-9]/.test(value))return false;const waived=meaningful.filter(token=>!isPronounceable(token));if(waived.some(token=>token.length>4))return false;return waived.length*2<=meaningful.length}function hasSequentialRun(value,min=5){let run=1;for(let i=1;i<value.length;i++){run=value.charCodeAt(i)===value.charCodeAt(i-1)+1?run+1:1;if(run>=min)return true}return false}function looksRandom(value){if(value.length<20)return false;if(!/^[A-Za-z0-9]+$/.test(value))return false;const classes=charClasses(value);if(!classes.lower||!classes.upper||!classes.digit)return false;if(hasSequentialRun(value))return false;if(isNaturalWordString(value))return false;return shannonEntropy(value)>=3.5}const CONTEXT_FREE_RANDOM_LENGTH=32;function isStyleToken(value){if(/\b(?:var|env)\(\s*--[\w-]+/.test(value))return true;if(/^--[a-z][\w-]*$/i.test(value))return true;if(/^[a-z][\w-]*-\[[^\]]+\]$/i.test(value))return true;return false}function isUrlOrPath(value){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(value)){return!/^[^/]*\/\/[^/@]*:[^/@]*@/.test(value)}const rooted=value.replace(/^(?:<[A-Za-z_$][\w$]*>|\[[A-Za-z_$][\w$]*\])(?=\/)/,"");if(rooted!==value)return isUrlOrPath(rooted);if(!value.startsWith("/")||value.startsWith("//"))return false;const path=value.split(/[?#]/)[0];const segments=path.slice(1).split("/");if(!segments.every(segment=>/^(?:[A-Za-z0-9._~%:@-]*|<[A-Za-z_$][\w$]*>|\[[A-Za-z_$][\w$]*\])$/.test(segment))){return false}const looksGenerated=segment=>/[a-z]/.test(segment)&&/[A-Z]/.test(segment)&&/[0-9]/.test(segment);if(segments.length===1){return!looksGenerated(segments[0])}return!segments.some(segment=>segment.length>=16&&looksGenerated(segment))}function echoesItsOwnSlotName(value,slotName){const fold=text=>text.replace(/[-_.\s]/g,"").toLowerCase();return fold(value)===fold(slotName)}function isSecretShaped(value,minLength){if(value.length<minLength)return false;if(/\s/.test(value))return false;if(isUrlOrPath(value))return false;if(isStyleToken(value))return false;if(isNaturalWordString(value))return false;if(classCount(charClasses(value))>=2)return true;return value.length>=20&&shannonEntropy(value)>=3}const DEFAULT_PLACEHOLDER_WORDS=["changeme","change","replaceme","replace","yours","your","placeholder","example","sample","dummy","todo","tbd","redacted","notreal","xxx"];function isPlaceholderValue(value,words){const trimmed=value.trim();if(/^(?:<.*>|\{\{.*\}\}|\$\{.*\}|\[.*\])$/.test(trimmed))return true;const dunder=/^__(.+)__$/.exec(trimmed);if(dunder!==null){const inner=dunder[1];const candidate=inner.trim();return/^[^A-Za-z]*[A-Z]{3,}/.test(candidate)&&!looksRandom(candidate)}if(trimmed.length>=4&&new Set(trimmed).size===1)return true;const tokens=trimmed.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return tokens.some(token=>words.has(token))}function isPublishableKeyValue(value){if(/^pk_(?:live|test)_[A-Za-z0-9_-]{8,}$/.test(value))return true;if(/^phc_[A-Za-z0-9]{20,}$/.test(value))return true;if(/^https?:\/\/[A-Za-z0-9]+@[A-Za-z0-9.-]+(?::\d+)?\/\d+$/.test(value)){return true}if(/^0x[A-Fa-f0-9]{40}$/.test(value))return true;return false}const SECRET_SIDE_VALUE=/^(?:sk|rk)_(?:live|test)_|^sk-[A-Za-z0-9]|^gh[pousr]_|^ph[xs]_|^sntry[su]_|^xox[baprs]-|^AKIA[0-9A-Z]{16}$|^ey[A-Za-z0-9_-]+\.ey|-----BEGIN|^(?:mysql|postgres|mongodb|redis):\/\//;const PUBLISHABLE_VENDORS=[{vendor:"Bugsnag",packages:["bugsnag","bugsnag-js","bugsnag-build-reporter","bugsnag-sourcemaps"],scopes:["@bugsnag"],named:/bugsnag/,slots:/^(?:bugsnag)?(?:notifier)?(?:api)?key$/},{vendor:"Sentry",scopes:["@sentry"],named:/sentry/,slots:/^(?:sentry)?dsn$/},{vendor:"PostHog",packages:["posthog-js","posthog-node"],named:/posthog/,slots:/^(?:posthog)?(?:project)?(?:api)?key$/},{vendor:"Segment",packages:["analytics-node"],scopes:["@segment"],named:/segment/,slots:/^(?:segment)?write(?:key|token)$/},{vendor:"Amplitude",packages:["amplitude-js"],scopes:["@amplitude"],named:/amplitude/,slots:/^(?:amplitude)?(?:api)?key$/},{vendor:"Mixpanel",packages:["mixpanel","mixpanel-browser"],named:/mixpanel/,slots:/^(?:mixpanel)?(?:project)?token$/},{vendor:"Firebase",packages:["firebase"],scopes:["@firebase"],named:/firebase/,slots:/^(?:firebase)?(?:web)?apikey$/}];const VENDOR_PROBES=PUBLISHABLE_VENDORS.map(entry=>({entry,loadsSdk:(0,eslint_devkit_2.createModuleEvidence)({packages:entry.packages,scopes:entry.scopes})}));function slotOf(parent){let slot=parent;while(slot?.type==="ArrayExpression")slot=slot.parent;return slot}function slotNameOf(parent){switch(parent.type){case"VariableDeclarator":return parent.id.type==="Identifier"?parent.id.name.toLowerCase():"";case"Property":{const named=(0,eslint_devkit_1.objectKeyName)(parent);return named===null?"":named.toLowerCase()}case"AssignmentExpression":{const left=parent.left;const named=left.type==="Identifier"?left.name:left.type==="MemberExpression"?(0,eslint_devkit_1.propertyName)(left):null;return named===null?"":named.toLowerCase()}default:return""}}function looksLikeCredential(value,options,ignorePatterns){const NONE={isCredential:false,type:"",confidence:"ambiguous"};if(ignorePatterns.some(pattern=>pattern.test(value)))return NONE;for(const customPattern of options.customPatterns){try{const regex=new RegExp(customPattern.pattern);if(regex.test(value)){return{isCredential:true,type:customPattern.type,confidence:"structural"}}}catch{}}if(options.detectPasswords&&CREDENTIAL_PATTERNS.commonPassword.test(value)){return{isCredential:true,type:"Common password",confidence:"ambiguous"}}if(options.detectDatabaseStrings&&CREDENTIAL_PATTERNS.databaseString.test(value)){return{isCredential:true,type:"Database connection string",confidence:"structural"}}if(value.length<options.minLength)return NONE;if(options.detectTokens&&CREDENTIAL_PATTERNS.jwtToken.test(value)){return{isCredential:true,type:"JWT token",confidence:"structural"}}if(options.detectTokens&&CREDENTIAL_PATTERNS.oauthToken.test(value)){return{isCredential:true,type:"OAuth token",confidence:"structural"}}if(options.detectApiKeys&&CREDENTIAL_PATTERNS.awsAccessKey.test(value)){return{isCredential:true,type:"AWS access key",confidence:"structural"}}if(options.detectApiKeys&&/^(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9_-]{16,}$/.test(value)){return{isCredential:true,type:"API key",confidence:"structural"}}if(options.detectApiKeys&&looksRandom(value)){return{isCredential:true,type:"Secret key",confidence:value.length>=CONTEXT_FREE_RANDOM_LENGTH?"structural":"ambiguous"}}if(CREDENTIAL_PATTERNS.secretKey.test(value)&&!isNaturalWordString(value)){return{isCredential:true,type:"Secret key",confidence:"ambiguous"}}if(options.detectApiKeys&&/^[A-Za-z0-9_-]{32,}$/.test(value)&&!isNaturalWordString(value)){return{isCredential:true,type:"API key",confidence:"ambiguous"}}return NONE}exports.noHardcodedCredentials=(0,eslint_devkit_2.createRule)({name:"no-hardcoded-credentials",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-hardcoded-credentials.md",description:"Detects hardcoded passwords, API keys, tokens, and other sensitive credentials",cwe:"CWE-798",cvss:9.8,confidence:"medium"},fixable:"code",hasSuggestions:true,messages:{useEnvironmentVariable:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Hard-coded Credential",cwe:"CWE-798",description:"Hard-coded {{credentialType}} detected",severity:"CRITICAL",fix:"Use environment variable: process.env.{{envVarName}} or secret management service",documentationLink:"https://cwe.mitre.org/data/definitions/798.html"}),useSecretManager:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Use Secret Manager",cwe:"CWE-798",description:"Use secure secret management service",severity:"HIGH",fix:"Use AWS Secrets Manager, HashiCorp Vault, Azure Key Vault, or similar",documentationLink:"https://cwe.mitre.org/data/definitions/798.html"})},schema:[{type:"object",properties:{credentialWords:{type:"array",items:{type:"string"},default:[...CREDENTIAL_VARIABLE_NAMES],description:"Variable and property names this project uses for a credential. REPLACES the default list."},ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Regex patterns to ignore"},allowInTests:{type:"boolean",default:true,description:"Allow credentials in test files"},minLength:{type:"number",default:8,description:"Minimum length for credential detection"},detectApiKeys:{type:"boolean",default:true,description:"Detect API keys"},detectPasswords:{type:"boolean",default:true,description:"Detect passwords"},detectTokens:{type:"boolean",default:true,description:"Detect tokens"},detectDatabaseStrings:{type:"boolean",default:true,description:"Detect database connection strings"},customPatterns:{type:"array",items:{type:"object",properties:{type:{type:"string",description:'The type of credential (e.g., "API key", "token")'},pattern:{type:"string",description:"Regex pattern to match"}},required:["type","pattern"],additionalProperties:false},default:[],description:"Custom credential patterns to detect"},allowPlaceholders:{type:"boolean",default:true,description:"Skip self-evident placeholder values (`<your-secret-here>`, `changeme`, `xxxxxxxx`)"},placeholderWords:{type:"array",items:{type:"string"},default:DEFAULT_PLACEHOLDER_WORDS,description:"Words that mark a value as a self-evident stand-in rather than a secret, matched as a WHOLE token inside the value and never as a substring. Replaces the built-in list. Read only when `allowPlaceholders` is true."},additionalPlaceholderWords:{type:"array",items:{type:"string"},default:[],description:"Extra placeholder words, on top of `placeholderWords`."}},additionalProperties:false}]},defaultOptions:[{ignorePatterns:[],allowInTests:true,minLength:8,detectApiKeys:true,detectPasswords:true,detectTokens:true,detectDatabaseStrings:true,customPatterns:[],allowPlaceholders:true,placeholderWords:DEFAULT_PLACEHOLDER_WORDS,additionalPlaceholderWords:[]}],createOnce(context){let credentialWords;let ignorePatterns;let allowInTests;let minLength;let detectApiKeys;let detectPasswords;let detectTokens;let detectDatabaseStrings;let customPatterns;let allowPlaceholders;let placeholderWords;let additionalPlaceholderWords;let placeholderWordSet;let isTestFile;let compiledIgnorePatterns;let detectionOptions;let loadedVendors;function isLabelContext(value,parent){if(parent?.type!=="Property")return false;const key=parent.key;const keyText=key.type==="Identifier"?key.name:(0,eslint_devkit_1.staticString)(key);if(keyText!==null&&keyText.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase().split(/[^A-Z0-9]+/).includes(value.toUpperCase())){return true}let container=parent.parent.parent;while(container?.type==="ArrayExpression"){container=container.parent}if(container?.type!=="VariableDeclarator"||container.id.type!=="Identifier"){return false}const name=container.id.name.toLowerCase();return name.endsWith("label")||name.endsWith("labels")||name.endsWith("name")||name.endsWith("placeholder")}function inferCredentialTypeFromContext(parent){const name=slotNameOf(slotOf(parent));if(/(?:^|[_-])(password|passwd|pass|pwd)s?$/.test(name))return"password";if(/(?:^|[_-])(token|authtoken|auth_token|accesstoken|access_token|refreshtoken|refresh_token|idtoken|id_token)s?$/.test(name))return"token";if(/(?:^|[_-])(dburl|db_url|databaseurl|database_url|connectionstring|connection_string|connectionuri)s?$/.test(name))return"database";if(/(?:^|[_-])(apikey|api_key|secretkey|secret_key|privatekey|private_key|secret|key|clientsecret|client_secret)s?$/.test(name))return"apikey";return"other"}function isCredentialContext(value,parent){const slot=slotOf(parent);if(slot===void 0)return false;const name=slotNameOf(slot);if(name==="key"||name==="keys")return looksRandom(value);return[...credentialWords].some(word=>name.endsWith(word)||name.endsWith(`${word}s`))}function vendorsInFile(){if(loadedVendors===null){const found=new Set;for(const{entry,loadsSdk}of VENDOR_PROBES){if(loadsSdk(context.sourceCode.ast))found.add(entry.vendor)}loadedVendors=found}return loadedVendors}function isPublishableKey(value,parent){if(SECRET_SIDE_VALUE.test(value))return false;if(isPublishableKeyValue(value))return true;const slot=slotNameOf(parent);for(const{entry}of VENDOR_PROBES){if(!entry.named.test(slot)&&!vendorsInFile().has(entry.vendor)){continue}if(entry.slots.test(slot))return true}return false}function checkStringLiteral(node,parent){if(typeof node.value!=="string"){return}const value=node.value;if(isTestFile){return}if(parent?.type==="LogicalExpression"&&parent.operator!=="&&"){const left=parent.left;if(left.type==="MemberExpression"&&left.object.type==="MemberExpression"&&left.object.object.type==="Identifier"&&left.object.object.name==="process"&&(0,eslint_devkit_1.propertyName)(left.object)==="env"){return}}const{isCredential,type,confidence}=looksLikeCredential(value,detectionOptions,compiledIgnorePatterns);if(confidence!=="structural"&&isLabelContext(value,parent)){return}let finalIsCredential=isCredential;let finalType=type;if(isCredential&&confidence==="ambiguous"&&!isCredentialContext(value,parent)){finalIsCredential=false}const echoesSlot=confidence!=="structural"&&parent!==void 0&&echoesItsOwnSlotName(value,slotNameOf(parent));if(echoesSlot){finalIsCredential=false}const isPlaceholder=allowPlaceholders&&isPlaceholderValue(value,placeholderWordSet);if(isPlaceholder&&confidence!=="structural"){finalIsCredential=false}if(!finalIsCredential&&!isPlaceholder&&!echoesSlot&&!compiledIgnorePatterns.some(pattern=>pattern.test(value))&&isSecretShaped(value,detectionOptions.minLength)&&isCredentialContext(value,parent)){const ctxType=inferCredentialTypeFromContext(parent);const optionAllows=ctxType==="password"&&detectionOptions.detectPasswords||ctxType==="token"&&detectionOptions.detectTokens||ctxType==="database"&&detectionOptions.detectDatabaseStrings||ctxType==="apikey"&&detectionOptions.detectApiKeys||ctxType==="other";if(optionAllows){finalIsCredential=true;finalType=type||"Credential value"}}if(!finalIsCredential){return}if(isPublishableKey(value,parent)){return}let envVarName="API_KEY";if(parent&&parent.type==="Property"&&parent.key.type==="Identifier"){const keyName=parent.key.name;envVarName=keyName.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase().replace(/[^A-Z0-9_]/g,"_")}else if(parent&&parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){const varName=parent.id.name;envVarName=varName.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase().replace(/[^A-Z0-9_]/g,"_")}context.report({node,messageId:"useEnvironmentVariable",data:{credentialType:finalType,envVarName},suggest:[{messageId:"useEnvironmentVariable",data:{envVarName,credentialType:finalType},fix:fixer=>{return fixer.replaceText(node,`process.env.${envVarName} || '${value}'`)}},{messageId:"useSecretManager",fix:fixer=>{return fixer.replaceText(node,`await getSecret('${envVarName.toLowerCase()}')`)}}]})}return{before(){const options=context.options[0]||{};credentialWords=new Set((options.credentialWords??[...CREDENTIAL_VARIABLE_NAMES]).map(w=>w.toLowerCase()));({ignorePatterns=[],allowInTests=true,minLength=8,detectApiKeys=true,detectPasswords=true,detectTokens=true,detectDatabaseStrings=true,customPatterns=[],allowPlaceholders=true,placeholderWords=DEFAULT_PLACEHOLDER_WORDS,additionalPlaceholderWords=[]}=options);placeholderWordSet=new Set([...placeholderWords,...additionalPlaceholderWords]);const filename=context.filename;isTestFile=allowInTests&&(0,eslint_devkit_2.isTestFilePath)(filename);compiledIgnorePatterns=(0,eslint_devkit_1.compileUserPatterns)(ignorePatterns);detectionOptions={minLength,detectApiKeys,detectPasswords,detectTokens,detectDatabaseStrings,customPatterns};loadedVendors=null},Literal(node){checkStringLiteral(node,node.parent)},TemplateLiteral(node){if(isTestFile)return;if(node.expressions.length===0){const fullText=node.quasis.map(q=>q.value.raw).join("");const{type,confidence}=looksLikeCredential(fullText,detectionOptions,compiledIgnorePatterns);if(confidence==="structural"){context.report({node,messageId:"useEnvironmentVariable",data:{credentialType:type,envVarName:"API_KEY"},suggest:[{messageId:"useEnvironmentVariable",data:{envVarName:"API_KEY",credentialType:type},fix:fixer=>{return fixer.replaceText(node,`process.env.API_KEY || \`${fullText}\``)}},{messageId:"useSecretManager",fix:fixer=>{return fixer.replaceText(node,`await getSecret('api_key')`)}}]})}}else{for(const quasi of node.quasis){const{type,confidence}=looksLikeCredential(quasi.value.raw,detectionOptions,compiledIgnorePatterns);if(confidence==="structural"){context.report({node:quasi,messageId:"useEnvironmentVariable",data:{credentialType:type,envVarName:"API_KEY"}})}}}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPiiInLogs=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_CONSOLE_METHODS=["log","error","warn","info"];const DEFAULT_PII_TERMS=["email","ssn","password","credit card","phone"];const DEFAULT_PII_LABELS=["email:","ssn:","password:","credit card:","creditcard:"];function collectLoggedValues(root){const found=[];const pending=[root];while(pending.length>0){const node=pending.pop();found.push(node);if(node.type===eslint_devkit_1.AST_NODE_TYPES.TSAsExpression){pending.push(node.expression)}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){pending.push(...node.expressions)}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){pending.push(node.left,node.right)}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){for(const property of node.properties){if(property.type===eslint_devkit_1.AST_NODE_TYPES.Property){pending.push(property.value)}}}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){pending.push(node.consequent,node.alternate)}}return found}function isPiiFieldAccess(node,piiTerms){const field=(0,eslint_devkit_1.memberPropertyName)(node);return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&field!==null&&(0,eslint_devkit_1.nameHasAnyWord)(field,piiTerms)}exports.noPiiInLogs=(0,eslint_devkit_1.createRule)({name:"no-pii-in-logs",meta:{interop:{runtimes:["eslint","oxlint"]},type:"suggestion",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-pii-in-logs.md",description:"Prevent PII (email, SSN, credit cards) in console logs",cwe:"CWE-359",cvss:5.3},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"violation Detected",cwe:"CWE-359",description:"Prevent PII (email, SSN, credit cards) in console logs detected - this is a security risk",severity:"HIGH",fix:"Review and apply secure practices",documentationLink:"https://cwe.mitre.org/data/definitions/359.html"})},schema:[{type:"object",properties:{consoleMethods:{type:"array",items:{type:"string"},default:DEFAULT_CONSOLE_METHODS,description:"`console` methods treated as a log sink, matched as an exact method name. Replaces the built-in list."},additionalConsoleMethods:{type:"array",items:{type:"string"},default:[],description:"Extra `console` methods, on top of `consoleMethods`."},piiTerms:{type:"array",items:{type:"string"},default:DEFAULT_PII_TERMS,description:'Field vocabulary, matched as WHOLE WORDS of an identifier \u2014 never as a substring. Multi-word terms such as "credit card" match consecutive segments. Replaces the built-in list.'},additionalPiiTerms:{type:"array",items:{type:"string"},default:[],description:"Extra PII field terms, on top of `piiTerms`."},piiLabels:{type:"array",items:{type:"string"},default:DEFAULT_PII_LABELS,description:"String literals that are EXACTLY a field label announcing the next argument. Compared case-insensitively after trimming. Replaces the built-in list."},additionalPiiLabels:{type:"array",items:{type:"string"},default:[],description:"Extra field labels, on top of `piiLabels`."}},additionalProperties:false}]},defaultOptions:[{consoleMethods:DEFAULT_CONSOLE_METHODS,additionalConsoleMethods:[],piiTerms:DEFAULT_PII_TERMS,additionalPiiTerms:[],piiLabels:DEFAULT_PII_LABELS,additionalPiiLabels:[]}],createOnce(context,currentOptions){let logMethods;let terms;let labels;let sourceCode;function report(node){context.report({node,messageId:"violationDetected"})}function isPiiBinding(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);const resolved=reference?.resolved;if(!resolved){return false}return resolved.defs.some(def=>{const declared=def.name;const parent=declared.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.Property&&parent.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return(0,eslint_devkit_1.nameHasAnyWord)(parent.key.name,terms)}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.init){return isPiiFieldAccess(parent.init,terms)}return false})}return{before(){const[options={}]=currentOptions();const{consoleMethods=DEFAULT_CONSOLE_METHODS,additionalConsoleMethods=[],piiTerms=DEFAULT_PII_TERMS,additionalPiiTerms=[],piiLabels=DEFAULT_PII_LABELS,additionalPiiLabels=[]}=options;logMethods=new Set([...consoleMethods,...additionalConsoleMethods]);terms=[...piiTerms,...additionalPiiTerms];labels=new Set([...piiLabels,...additionalPiiLabels].map(label=>label.trim().toLowerCase()));sourceCode=context.sourceCode},CallExpression(node){if(
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPiiInLogs=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_CONSOLE_METHODS=["log","error","warn","info"];const DEFAULT_PII_TERMS=["email","ssn","password","credit card","phone"];const DEFAULT_PII_LABELS=["email:","ssn:","password:","credit card:","creditcard:"];const DEFAULT_LOGGERS=["logger","log"];const LOGGER_METHODS=new Set(["trace","debug","verbose","info","log","warn","error","fatal"]);const DEFAULT_PII_RECORDS=["user","person","customer","account","applicant","patient"];const EMAIL_IN_TEXT=/[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}/;const SSN_IN_TEXT=/(?<!\d)\d{3}-\d{2}-\d{4}(?!\d)/;const CARD_IN_TEXT=/(?<![\d-])\d(?:[ -]?\d){12,18}(?![\d-])/g;function passesLuhn(digits){let sum=0;for(let i=0;i<digits.length;i++){let digit=Number(digits[digits.length-1-i]);if(i%2===1){digit*=2;if(digit>9)digit-=9}sum+=digit}return sum%10===0}function constantTextHasPii(node){const constant=(0,eslint_devkit_1.staticString)(node);let text;if(constant!==null){text=constant}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){text=node.quasis.map(quasi=>quasi.value.raw).join(" ")}else{return false}if(EMAIL_IN_TEXT.test(text)||SSN_IN_TEXT.test(text))return true;return[...text.matchAll(CARD_IN_TEXT)].some(match=>passesLuhn(match[0].replace(/[ -]/g,"")))}function stringifiedValue(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression||node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||node.callee.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||node.callee.object.name!=="JSON"||(0,eslint_devkit_1.propertyName)(node.callee)!=="stringify"){return null}const[value]=node.arguments;return value===void 0||value.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement?null:value}function collectLoggedValues(root){const found=[];const pending=[root];while(pending.length>0){const node=pending.pop();found.push(node);if(node.type===eslint_devkit_1.AST_NODE_TYPES.TSAsExpression){pending.push(node.expression)}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){pending.push(...node.expressions)}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){pending.push(node.left,node.right)}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){for(const property of node.properties){if(property.type===eslint_devkit_1.AST_NODE_TYPES.Property){pending.push(property.value)}}}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){pending.push(node.consequent,node.alternate)}else{const serialized=stringifiedValue(node);if(serialized!==null)pending.push(serialized)}}return found}function isPiiFieldAccess(node,piiTerms){const field=(0,eslint_devkit_1.memberPropertyName)(node);return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&field!==null&&(0,eslint_devkit_1.nameHasAnyWord)(field,piiTerms)}exports.noPiiInLogs=(0,eslint_devkit_1.createRule)({name:"no-pii-in-logs",meta:{interop:{runtimes:["eslint","oxlint"]},type:"suggestion",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-pii-in-logs.md",description:"Prevent PII (email, SSN, credit cards) in console logs",cwe:"CWE-359",cvss:5.3},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"violation Detected",cwe:"CWE-359",description:"Prevent PII (email, SSN, credit cards) in console logs detected - this is a security risk",severity:"HIGH",fix:"Review and apply secure practices",documentationLink:"https://cwe.mitre.org/data/definitions/359.html"})},schema:[{type:"object",properties:{consoleMethods:{type:"array",items:{type:"string"},default:DEFAULT_CONSOLE_METHODS,description:"`console` methods treated as a log sink, matched as an exact method name. Replaces the built-in list."},additionalConsoleMethods:{type:"array",items:{type:"string"},default:[],description:"Extra `console` methods, on top of `consoleMethods`."},piiTerms:{type:"array",items:{type:"string"},default:DEFAULT_PII_TERMS,description:'Field vocabulary, matched as WHOLE WORDS of an identifier \u2014 never as a substring. Multi-word terms such as "credit card" match consecutive segments. Replaces the built-in list.'},additionalPiiTerms:{type:"array",items:{type:"string"},default:[],description:"Extra PII field terms, on top of `piiTerms`."},piiLabels:{type:"array",items:{type:"string"},default:DEFAULT_PII_LABELS,description:"String literals that are EXACTLY a field label announcing the next argument. Compared case-insensitively after trimming. Replaces the built-in list."},additionalPiiLabels:{type:"array",items:{type:"string"},default:[],description:"Extra field labels, on top of `piiLabels`."},loggers:{type:"array",items:{type:"string"},default:DEFAULT_LOGGERS,description:"Receiver names that denote an application logger (`logger.info`, `this.logger.error`); every level method on one is a log sink. Replaces the built-in list."},additionalLoggers:{type:"array",items:{type:"string"},default:[],description:"Extra logger receiver names, on top of `loggers`."},piiRecords:{type:"array",items:{type:"string"},default:DEFAULT_PII_RECORDS,description:"Words naming a whole person record, matched as WHOLE WORDS of an identifier. `JSON.stringify` of one is reported. Replaces the built-in list."},additionalPiiRecords:{type:"array",items:{type:"string"},default:[],description:"Extra person-record words, on top of `piiRecords`."}},additionalProperties:false}]},defaultOptions:[{consoleMethods:DEFAULT_CONSOLE_METHODS,additionalConsoleMethods:[],piiTerms:DEFAULT_PII_TERMS,additionalPiiTerms:[],piiLabels:DEFAULT_PII_LABELS,additionalPiiLabels:[],loggers:DEFAULT_LOGGERS,additionalLoggers:[],piiRecords:DEFAULT_PII_RECORDS,additionalPiiRecords:[]}],createOnce(context,currentOptions){let logMethods;let terms;let labels;let loggerNames;let records;let sourceCode;function report(node){context.report({node,messageId:"violationDetected"})}function isPiiBinding(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);const resolved=reference?.resolved;if(!resolved){return false}return resolved.defs.some(def=>{const declared=def.name;const parent=declared.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.Property&&parent.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return(0,eslint_devkit_1.nameHasAnyWord)(parent.key.name,terms)}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.init){return isPiiFieldAccess(parent.init,terms)}return false})}function isLogSink(callee){if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;const method=(0,eslint_devkit_1.propertyName)(callee);const receiver=callee.object;if(receiver.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return receiver.name==="console"?(0,eslint_devkit_1.namesOneOf)(method,logMethods):loggerNames.has(receiver.name)&&(0,eslint_devkit_1.namesOneOf)(method,LOGGER_METHODS)}return receiver.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&loggerNames.has((0,eslint_devkit_1.propertyName)(receiver))&&(0,eslint_devkit_1.namesOneOf)(method,LOGGER_METHODS)}function isSerializedRecord(node){const serialized=stringifiedValue(node);return serialized?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(0,eslint_devkit_1.nameHasAnyWord)(serialized.name,records)}return{before(){const[options={}]=currentOptions();const{consoleMethods=DEFAULT_CONSOLE_METHODS,additionalConsoleMethods=[],piiTerms=DEFAULT_PII_TERMS,additionalPiiTerms=[],piiLabels=DEFAULT_PII_LABELS,additionalPiiLabels=[],loggers=DEFAULT_LOGGERS,additionalLoggers=[],piiRecords=DEFAULT_PII_RECORDS,additionalPiiRecords=[]}=options;loggerNames=new Set([...loggers,...additionalLoggers]);records=[...piiRecords,...additionalPiiRecords];logMethods=new Set([...consoleMethods,...additionalConsoleMethods]);terms=[...piiTerms,...additionalPiiTerms];labels=new Set([...piiLabels,...additionalPiiLabels].map(label=>label.trim().toLowerCase()));sourceCode=context.sourceCode},CallExpression(node){if(!isLogSink(node.callee)){return}for(const[index,arg]of node.arguments.entries()){if(arg.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof arg.value==="string"&&index<node.arguments.length-1&&labels.has(arg.value.trim().toLowerCase())){report(node);return}for(const value of collectLoggedValues(arg)){if(isPiiFieldAccess(value,terms)||isPiiBinding(value)||isSerializedRecord(value)||constantTextHasPii(value)){report(node);return}}}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSqlInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const NO_SUBSTITUTIONS=new Map;function substitutionFor(node,scope,substitutions){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return void 0;const variable=resolveVariable(node.name,scope);return variable===null?void 0:substitutions.get(variable)}function hasRawUnattributedPart(node,scope,substitutions){const parts=node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral?[...node.expressions]:[node.left,node.right];return parts.some(part=>{if(part.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;if(part.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||part.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return hasRawUnattributedPart(part,scope,substitutions)}const bound=substitutionFor(part,scope,substitutions);if(bound!==void 0){return bound.node!==null&&!(0,eslint_devkit_1.isStaticExpression)({node:bound.node,scope:bound.scope})}return!(0,eslint_devkit_1.isStaticExpression)({node:part,scope})})}const SQL_DRIVER_MODULES=new Set(["pg","pg-pool","pg-native","pg-cursor","pg-promise","pg-copy-streams","postgres","slonik","@vercel/postgres","@neondatabase/serverless","@electric-sql/pglite","mysql","mysql2","@planetscale/database","sqlite3","better-sqlite3","node:sqlite","bun:sqlite","@libsql/client","typeorm","@nestjs/typeorm","sequelize","sequelize-typescript","@nestjs/sequelize","knex","objection","drizzle-orm","@prisma/client","prisma","kysely","mssql","oracledb"]);function isSqlDriverSpecifier(specifier){if(specifier.startsWith(".")||specifier.startsWith("/"))return false;const parts=specifier.split("/");const root=specifier.startsWith("@")?parts.slice(0,2).join("/"):parts[0];return SQL_DRIVER_MODULES.has(root)}function stringLiteralValue(node){if(node!==void 0&&node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.value==="string"){return node.value}return null}const SQL_SINK_METHODS=["query","execute"];const TRANSPARENT_CALLS=["String"];const QUERY_TEXT_PROPERTIES=["text","sql"];function invokedMethodName(callee,scope){const named=(0,eslint_devkit_1.propertyName)(callee);if(named!==null)return named;if(callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const variable=resolveVariable(callee.property.name,scope);if(variable===null)return null;const init=singleAssignedInit(variable);return init===null?null:stringLiteralValue(init)}const SQL_STATEMENTS=[/^\s*select\b[\s\S]*\bfrom\b/i,/^\s*insert\s+into\b/i,/^\s*update\b[\s\S]*\bset\b/i,/^\s*delete\s+from\b/i,/^\s*replace\s+into\b/i,/^\s*merge\s+into\b/i];function staticText(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.quasis.map(q=>q.value.raw).join("")}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return`${staticText(node.left)}${staticText(node.right)}`}const literal=stringLiteralValue(node);return literal===null?"":literal}function looksLikeSqlStatement(nodes){const text=nodes.map(staticText).join("");return SQL_STATEMENTS.some(pattern=>pattern.test(text))}function isBuiltString(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.expressions.length>0}return node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"}const REQUEST_ROOTS=["req","request","ctx","event"];const REQUEST_PROPERTIES=["query","params","body","headers","cookies","url","path"];function resolveVariable(name,scope){for(let current=scope;current!==null;current=current.upper){const variable=current.set.get(name);if(variable!==void 0)return variable}return null}function singleAssignedInit(variable){const writes=variable.references.filter(ref=>ref.isWrite());if(writes.length!==1)return null;const def=variable.defs.find(d=>d.type==="Variable");if(def===void 0)return null;return def.node.init??null}function isParameterBinding(variable){return variable.defs.some(def=>def.type==="Parameter"&&!bindsADeclaredContract(def))}function bindsADeclaredContract(def){for(let node=def.name;node!==void 0;node=node.parent??void 0){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectPattern&&node.type!==eslint_devkit_1.AST_NODE_TYPES.ArrayPattern&&node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){continue}const annotation=node.typeAnnotation?.typeAnnotation;if(annotation?.type===eslint_devkit_1.AST_NODE_TYPES.TSTypeReference)return true}return false}function allWritesStatic(variable,scope){const writes=writeExpressions(variable);if(writes.length===0)return false;return writes.every(node=>(0,eslint_devkit_1.isStaticExpression)({node,scope}))}function writeExpressions(variable){const written=[];for(const reference of variable.references){const{writeExpr}=reference;if(reference.isWrite()&&writeExpr!==void 0&&writeExpr!==null){written.push(writeExpr)}}return written}function isLocallyConstructed(variable,scope){if(variable===null)return false;const init=singleAssignedInit(variable);if(init===null)return false;return init.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression||(0,eslint_devkit_1.isStaticExpression)({node:init,scope})}function isAmbientGlobal(name,scope){const variable=resolveVariable(name,scope);return variable===null||variable.defs.length===0}function attributedThroughCall(node,scope,attribution,depth){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&attribution.transparentCalls.has(node.callee.name)&&isAmbientGlobal(node.callee.name,scope)){for(const argument of node.arguments){if(argument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)continue;const found=attributedSource(argument,scope,attribution,depth+1);if(found!==null)return found}return null}const inlined=effectiveExpression(node,scope,attribution);if(inlined.nodes.length===1&&inlined.nodes[0]===node)return null;const inner={...attribution,substitutions:inlined.substitutions};for(const candidate of inlined.nodes){const found=attributedSource(candidate,inlined.scope,inner,depth+1);if(found!==null)return found}return null}function attributedSource(node,scope,attribution,depth=0){if(depth>5)return null;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return attributedSource(bare,scope,attribution,depth+1);if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){for(const expression of node.expressions){const found=attributedSource(expression,scope,attribution,depth+1);if(found!==null)return found}return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return attributedSource(node.left,scope,attribution,depth+1)??attributedSource(node.right,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){let root=node;const properties=[];while(root.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const segment=(0,eslint_devkit_1.propertyName)(root);if(segment!==null){properties.unshift(segment)}root=root.object}if(root.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;if(isLocallyConstructed(resolveVariable(root.name,scope),scope))return null;if(!properties.some(property=>attribution.requestProperties.has(property))){return null}if(attribution.requestRoots.has(root.name)||attribution.trustRequestShape&&(0,eslint_devkit_1.readsRequestShape)(node,attribution.sourceCode)){return`${root.name}.${properties.join(".")}`}return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){return attributedSource(node.consequent,scope,attribution,depth+1)??attributedSource(node.alternate,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.LogicalExpression){return attributedSource(node.left,scope,attribution,depth+1)??attributedSource(node.right,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){return attributedThroughCall(node,scope,attribution,depth)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=resolveVariable(node.name,scope);if(variable===null)return null;const bound=attribution.substitutions.get(variable);if(bound!==void 0){return bound.node===null?null:attributedSource(bound.node,bound.scope,{...attribution,substitutions:NO_SUBSTITUTIONS},depth+1)}const writes=writeExpressions(variable);for(const write of writes){const found=attributedSource(write,scope,attribution,depth+1);if(found!==null)return found}if(attribution.untrustedParameters&&isParameterBinding(variable)&&!allWritesStatic(variable,scope)&&!isNarrowedByGuardClause(node.name,node,attribution.sourceCode)){return`${node.name} (a caller-supplied parameter)`}return null}return null}function isNarrowedByGuardClause(name,node,sourceCode){let fn=node;while(fn.parent!==void 0&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression){fn=fn.parent}const body=fn.body;if(body===void 0||body.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement)return false;for(const statement of body.body){if(statement.range[0]>=node.range[0])break;if(statement.type!==eslint_devkit_1.AST_NODE_TYPES.IfStatement)continue;const leaves=consequent=>{if(consequent.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement)return true;if(consequent.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)return true;if(consequent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){return consequent.body.some(inner=>inner.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement||inner.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)}return false};if(!leaves(statement.consequent))continue;const test=statement.test;if(test.type!==eslint_devkit_1.AST_NODE_TYPES.UnaryExpression||test.operator!=="!")continue;const call=test.argument;if(call.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)continue;if(call.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)continue;const method=call.callee.property;if(method.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||method.name!=="has"&&method.name!=="includes"){continue}const[checked]=call.arguments;if(checked?.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||checked.name!==name)continue;const receiver=call.callee.object;if(receiver.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)continue;let search=sourceCode.getScope(node);let declared;while(search!==null&&declared===void 0){declared=search.variables.find(v=>v.name===receiver.name);search=search.upper}const source=declared?.defs[0]?.node.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator?declared.defs[0].node.init:void 0;if(source===void 0||source===null)continue;const listOf=init=>{if(init.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression)return[...init.elements].filter(Boolean);if(init.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression&&init.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&init.callee.name==="Set"&&init.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){return[...init.arguments[0].elements].filter(Boolean)}return void 0};const members=listOf(source);if(members===void 0||members.length===0)continue;if(members.every(el=>el.type===eslint_devkit_1.AST_NODE_TYPES.Literal))return true}return false}function effectiveExpression(node,scope,attribution,depth=0){const unresolved={nodes:[node],scope,substitutions:NO_SUBSTITUTIONS};if(depth>5)return unresolved;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node){return effectiveExpression(bare,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression){return effectiveExpression(node.argument,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const joined=joinedArrayElements(node,scope);if(joined!==null){return{nodes:joined,scope,substitutions:NO_SUBSTITUTIONS}}return resolveBuilderCall(node,scope,attribution)??unresolved}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){const text=queryTextProperty(node,attribution.queryTextProperties);return text===null?unresolved:effectiveExpression(text,scope,attribution,depth+1)}if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return unresolved;const variable=resolveVariable(node.name,scope);if(variable===null)return unresolved;const writes=writeExpressions(variable);if(writes.length===0)return unresolved;if(writes.length===1){return effectiveExpression(writes[0],scope,attribution,depth+1)}return{nodes:writes,scope,substitutions:NO_SUBSTITUTIONS}}function resolveBuilderCall(node,scope,attribution){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const impl=resolveLocalFunction(node.callee.name,scope);if(impl===null)return null;const returned=returnedExpression(impl);if(returned===null||returned.type!==eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&returned.type!==eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){return null}const bindings=bindParameters(impl,node.arguments,scope,attribution.sourceCode);if(bindings===null)return null;return{nodes:[returned],scope:attribution.sourceCode.getScope(returned),substitutions:bindings}}function resolveLocalFunction(name,scope){const variable=resolveVariable(name,scope);if(variable===null)return null;const declared=variable.defs.find(def=>def.type==="FunctionName");if(declared!==void 0){return declared.node}const init=singleAssignedInit(variable);if(init!==null&&(init.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression)){return init}return null}function returnedExpression(impl){if(impl.body.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement)return impl.body;const[only]=impl.body.body;if(impl.body.body.length!==1||only?.type!==eslint_devkit_1.AST_NODE_TYPES.ReturnStatement){return null}return only.argument??null}function joinedArrayElements(node,scope){const{callee}=node;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return null}if((0,eslint_devkit_1.propertyName)(callee)!=="join"){return null}let receiver=callee.object;if(receiver.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=resolveVariable(receiver.name,scope);const init=variable===null?null:singleAssignedInit(variable);if(init===null)return null;receiver=init}if(receiver.type!==eslint_devkit_1.AST_NODE_TYPES.ArrayExpression)return null;const elements=[];for(const element of receiver.elements){if(element===null||element.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){continue}elements.push(element)}return elements}function queryTextProperty(node,names){for(const property of node.properties){if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property||property.computed)continue;const key=property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?property.key.name:stringLiteralValue(property.key);if(key!==null&&names.has(key))return property.value}return null}function bindParameters(impl,args,callerScope,sourceCode){if(args.some(a=>a.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement))return null;if(impl.params.some(p=>p.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier))return null;const bindings=new Map;sourceCode.getDeclaredVariables(impl).filter(variable=>isParameterBinding(variable)).forEach((variable,index)=>{bindings.set(variable,{node:args[index]??null,scope:callerScope})});return bindings}exports.noSqlInjection=(0,eslint_devkit_1.createRule)({name:"no-sql-injection",meta:{interop:{runtimes:["eslint","oxlint"]},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}],createOnce(context,currentOptions){let reportUnattributedInterpolation;let treatParametersAsUntrusted;let requestRoots;let requestProperties;let sinkMethods;let transparentCalls;let queryTextProperties;let attribution;let sinks;let pending;let importsSqlDriver;const noteSpecifier=specifier=>{if(specifier!==null&&isSqlDriverSpecifier(specifier)){importsSqlDriver=true}};return{before(){const[options={}]=currentOptions();({reportUnattributedInterpolation=false,treatParametersAsUntrusted=true,requestRoots=REQUEST_ROOTS,requestProperties=REQUEST_PROPERTIES,sinkMethods=SQL_SINK_METHODS,transparentCalls=TRANSPARENT_CALLS,queryTextProperties=QUERY_TEXT_PROPERTIES}=options);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};sinks=new Set(sinkMethods);pending=[];importsSqlDriver=false},ImportDeclaration(node){noteSpecifier(node.source.value)},ImportExpression(node){noteSpecifier(stringLiteralValue(node.source))},TSImportEqualsDeclaration(node){if(node.moduleReference.type===eslint_devkit_1.AST_NODE_TYPES.TSExternalModuleReference){noteSpecifier(stringLiteralValue(node.moduleReference.expression))}},CallExpression(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="require"){noteSpecifier(stringLiteralValue(node.arguments[0]));return}if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;const callScope=context.sourceCode.getScope(node);const method=invokedMethodName(node.callee,callScope);if(method===null||!sinks.has(method))return;const[firstArgument]=node.arguments;if(firstArgument===void 0||firstArgument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){return}const{nodes,scope,substitutions}=effectiveExpression(firstArgument,callScope,attribution);const built=nodes.some(isBuiltString)||nodes.length>1&&nodes.some(n=>!(0,eslint_devkit_1.isStaticExpression)({node:n,scope}));if(!built)return;if(!looksLikeSqlStatement(nodes))return;const sinkAttribution={...attribution,substitutions};for(const candidate of nodes){const source=attributedSource(candidate,scope,sinkAttribution);if(source!==null){pending.push({node,source});return}}if(reportUnattributedInterpolation&&nodes.some(n=>(n.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral||n.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression)&&hasRawUnattributedPart(n,scope,substitutions))){pending.push({node,source:"a value this file cannot attribute"})}},"Program:exit"(){if(importsSqlDriver)return;for(const finding of pending){context.report({node:finding.node,messageId:"sqlInjection",data:{source:finding.source}})}}}}});exports.default=exports.noSqlInjection;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSqlInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const NO_SUBSTITUTIONS=new Map;function substitutionFor(node,scope,substitutions){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return void 0;const variable=resolveVariable(node.name,scope);return variable===null?void 0:substitutions.get(variable)}function hasRawUnattributedPart(node,scope,substitutions){const parts=node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral?[...node.expressions]:[node.left,node.right];return parts.some(part=>{if(part.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;if(part.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||part.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return hasRawUnattributedPart(part,scope,substitutions)}const bound=substitutionFor(part,scope,substitutions);if(bound!==void 0){return bound.node!==null&&!(0,eslint_devkit_1.isStaticExpression)({node:bound.node,scope:bound.scope})}return!(0,eslint_devkit_1.isStaticExpression)({node:part,scope})})}const SQL_DRIVER_MODULES=new Set(["pg","pg-pool","pg-native","pg-cursor","pg-promise","pg-copy-streams","postgres","slonik","@vercel/postgres","@neondatabase/serverless","@electric-sql/pglite","mysql","mysql2","@planetscale/database","sqlite3","better-sqlite3","node:sqlite","bun:sqlite","@libsql/client","typeorm","@nestjs/typeorm","sequelize","sequelize-typescript","@nestjs/sequelize","knex","objection","drizzle-orm","@prisma/client","prisma","kysely","mssql","oracledb"]);function isSqlDriverSpecifier(specifier){if(specifier.startsWith(".")||specifier.startsWith("/"))return false;const parts=specifier.split("/");const root=specifier.startsWith("@")?parts.slice(0,2).join("/"):parts[0];return SQL_DRIVER_MODULES.has(root)}function stringLiteralValue(node){if(node!==void 0&&node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.value==="string"){return node.value}return null}const SQL_SINK_METHODS=["query","execute"];const TRANSPARENT_CALLS=["String"];const QUERY_TEXT_PROPERTIES=["text","sql"];function invokedMethodName(callee,scope){const named=(0,eslint_devkit_1.propertyName)(callee);if(named!==null)return named;if(callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const variable=resolveVariable(callee.property.name,scope);if(variable===null)return null;const init=singleAssignedInit(variable);return init===null?null:stringLiteralValue(init)}const SQL_STATEMENTS=[/^\s*select\b[\s\S]*\bfrom\b/i,/^\s*insert\s+into\b/i,/^\s*update\b[\s\S]*\bset\b/i,/^\s*delete\s+from\b/i,/^\s*replace\s+into\b/i,/^\s*merge\s+into\b/i];function staticText(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.quasis.map(q=>q.value.raw).join("")}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return`${staticText(node.left)}${staticText(node.right)}`}const literal=stringLiteralValue(node);return literal===null?"":literal}function looksLikeSqlStatement(nodes){const text=nodes.map(staticText).join("");return SQL_STATEMENTS.some(pattern=>pattern.test(text))}function isBuiltString(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.expressions.length>0}return node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"}const REQUEST_ROOTS=["req","request","ctx","event"];const REQUEST_PROPERTIES=["query","params","body","headers","cookies","url","path"];function resolveVariable(name,scope){for(let current=scope;current!==null;current=current.upper){const variable=current.set.get(name);if(variable!==void 0)return variable}return null}function singleAssignedInit(variable){const writes=variable.references.filter(ref=>ref.isWrite());if(writes.length!==1)return null;const def=variable.defs.find(d=>d.type==="Variable");if(def===void 0)return null;return def.node.init??null}function isParameterBinding(variable){return variable.defs.some(def=>def.type==="Parameter"&&!bindsADeclaredContract(def))}function bindsADeclaredContract(def){for(let node=def.name;node!==void 0;node=node.parent??void 0){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectPattern&&node.type!==eslint_devkit_1.AST_NODE_TYPES.ArrayPattern&&node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){continue}const annotation=node.typeAnnotation?.typeAnnotation;if(annotation?.type===eslint_devkit_1.AST_NODE_TYPES.TSTypeReference)return true}return false}function allWritesStatic(variable,scope){const writes=writeExpressions(variable);if(writes.length===0)return false;return writes.every(node=>(0,eslint_devkit_1.isStaticExpression)({node,scope}))}function writeExpressions(variable){const written=[];for(const reference of variable.references){const{writeExpr}=reference;if(reference.isWrite()&&writeExpr!==void 0&&writeExpr!==null){written.push(writeExpr)}}return written}function isLocallyConstructed(variable,scope){if(variable===null)return false;const init=singleAssignedInit(variable);if(init===null)return false;return init.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression||(0,eslint_devkit_1.isStaticExpression)({node:init,scope})}function isAmbientGlobal(name,scope){const variable=resolveVariable(name,scope);return variable===null||variable.defs.length===0}function attributedThroughCall(node,scope,attribution,depth){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&attribution.transparentCalls.has(node.callee.name)&&isAmbientGlobal(node.callee.name,scope)){for(const argument of node.arguments){if(argument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)continue;const found=attributedSource(argument,scope,attribution,depth+1);if(found!==null)return found}return null}const inlined=effectiveExpression(node,scope,attribution);if(inlined.nodes.length===1&&inlined.nodes[0]===node)return null;const inner={...attribution,substitutions:inlined.substitutions};for(const candidate of inlined.nodes){const found=attributedSource(candidate,inlined.scope,inner,depth+1);if(found!==null)return found}return null}function attributedSource(node,scope,attribution,depth=0){if(depth>5)return null;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return attributedSource(bare,scope,attribution,depth+1);if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){for(const expression of node.expressions){const found=attributedSource(expression,scope,attribution,depth+1);if(found!==null)return found}return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return attributedSource(node.left,scope,attribution,depth+1)??attributedSource(node.right,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){let root=node;const properties=[];while(root.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const segment=(0,eslint_devkit_1.propertyName)(root);if(segment!==null){properties.unshift(segment)}root=root.object}if(root.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;if(isLocallyConstructed(resolveVariable(root.name,scope),scope))return null;if(!properties.some(property=>attribution.requestProperties.has(property))){return null}if(attribution.requestRoots.has(root.name)||attribution.trustRequestShape&&(0,eslint_devkit_1.readsRequestShape)(node,attribution.sourceCode)){return`${root.name}.${properties.join(".")}`}return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){return attributedSource(node.consequent,scope,attribution,depth+1)??attributedSource(node.alternate,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.LogicalExpression){return attributedSource(node.left,scope,attribution,depth+1)??attributedSource(node.right,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){return attributedThroughCall(node,scope,attribution,depth)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=resolveVariable(node.name,scope);if(variable===null)return null;const bound=attribution.substitutions.get(variable);if(bound!==void 0){return bound.node===null?null:attributedSource(bound.node,bound.scope,{...attribution,substitutions:NO_SUBSTITUTIONS},depth+1)}const writes=writeExpressions(variable);for(const write of writes){const found=attributedSource(write,scope,attribution,depth+1);if(found!==null)return found}if(attribution.untrustedParameters&&isParameterBinding(variable)&&!allWritesStatic(variable,scope)&&!isNarrowedByGuardClause(node.name,node,attribution.sourceCode)){return`${node.name} (a caller-supplied parameter)`}return null}return null}function isNarrowedByGuardClause(name,node,sourceCode){let fn=node;while(fn.parent!==void 0&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression){fn=fn.parent}const body=fn.body;if(body===void 0||body.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement)return false;for(const statement of body.body){if(statement.range[0]>=node.range[0])break;if(statement.type!==eslint_devkit_1.AST_NODE_TYPES.IfStatement)continue;const leaves=consequent=>{if(consequent.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement)return true;if(consequent.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)return true;if(consequent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){return consequent.body.some(inner=>inner.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement||inner.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)}return false};if(!leaves(statement.consequent))continue;const test=statement.test;if(test.type!==eslint_devkit_1.AST_NODE_TYPES.UnaryExpression||test.operator!=="!")continue;const call=test.argument;if(call.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)continue;if(call.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)continue;const method=call.callee.property;if(method.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||method.name!=="has"&&method.name!=="includes"){continue}const[checked]=call.arguments;if(checked?.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||checked.name!==name)continue;const receiver=call.callee.object;if(receiver.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)continue;let search=sourceCode.getScope(node);let declared;while(search!==null&&declared===void 0){declared=search.variables.find(v=>v.name===receiver.name);search=search.upper}const source=declared?.defs[0]?.node.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator?declared.defs[0].node.init:void 0;if(source===void 0||source===null)continue;const listOf=init=>{if(init.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression)return[...init.elements].filter(Boolean);if(init.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression&&init.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&init.callee.name==="Set"&&init.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){return[...init.arguments[0].elements].filter(Boolean)}return void 0};const members=listOf(source);if(members===void 0||members.length===0)continue;if(members.every(el=>el.type===eslint_devkit_1.AST_NODE_TYPES.Literal))return true}return false}function effectiveExpression(node,scope,attribution,depth=0){const unresolved={nodes:[node],scope,substitutions:NO_SUBSTITUTIONS};if(depth>5)return unresolved;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node){return effectiveExpression(bare,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression){return effectiveExpression(node.argument,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const joined=joinedArrayElements(node,scope);if(joined!==null){return{nodes:joined,scope,substitutions:NO_SUBSTITUTIONS}}return resolveBuilderCall(node,scope,attribution)??unresolved}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){const text=queryTextProperty(node,attribution.queryTextProperties);return text===null?unresolved:effectiveExpression(text,scope,attribution,depth+1)}if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return unresolved;const variable=resolveVariable(node.name,scope);if(variable===null)return unresolved;const writes=writeExpressions(variable);if(writes.length===0)return unresolved;if(writes.length===1){return effectiveExpression(writes[0],scope,attribution,depth+1)}return{nodes:writes,scope,substitutions:NO_SUBSTITUTIONS}}function resolveBuilderCall(node,scope,attribution){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const impl=resolveLocalFunction(node.callee.name,scope);if(impl===null)return null;const returned=returnedExpression(impl);if(returned===null||returned.type!==eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&returned.type!==eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){return null}const bindings=bindParameters(impl,node.arguments,scope,attribution.sourceCode);if(bindings===null)return null;return{nodes:[returned],scope:attribution.sourceCode.getScope(returned),substitutions:bindings}}function resolveLocalFunction(name,scope){const variable=resolveVariable(name,scope);if(variable===null)return null;const declared=variable.defs.find(def=>def.type==="FunctionName");if(declared!==void 0){return declared.node.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration?declared.node:null}const init=singleAssignedInit(variable);if(init!==null&&(init.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression)){return init}return null}function returnedExpression(impl){if(impl.body.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement)return impl.body;const[only]=impl.body.body;if(impl.body.body.length!==1||only?.type!==eslint_devkit_1.AST_NODE_TYPES.ReturnStatement){return null}return only.argument??null}function joinedArrayElements(node,scope){const{callee}=node;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return null}if((0,eslint_devkit_1.propertyName)(callee)!=="join"){return null}let receiver=callee.object;if(receiver.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=resolveVariable(receiver.name,scope);const init=variable===null?null:singleAssignedInit(variable);if(init===null)return null;receiver=init}if(receiver.type!==eslint_devkit_1.AST_NODE_TYPES.ArrayExpression)return null;const elements=[];for(const element of receiver.elements){if(element===null||element.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){continue}elements.push(element)}return elements}function queryTextProperty(node,names){for(const property of node.properties){if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property||property.computed)continue;const key=property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?property.key.name:stringLiteralValue(property.key);if(key!==null&&names.has(key))return property.value}return null}function bindParameters(impl,args,callerScope,sourceCode){if(args.some(a=>a.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement))return null;if(impl.params.some(p=>p.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier))return null;const bindings=new Map;sourceCode.getDeclaredVariables(impl).filter(variable=>isParameterBinding(variable)).forEach((variable,index)=>{bindings.set(variable,{node:args[index]??null,scope:callerScope})});return bindings}exports.noSqlInjection=(0,eslint_devkit_1.createRule)({name:"no-sql-injection",meta:{interop:{runtimes:["eslint","oxlint"]},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}],createOnce(context,currentOptions){let reportUnattributedInterpolation;let treatParametersAsUntrusted;let requestRoots;let requestProperties;let sinkMethods;let transparentCalls;let queryTextProperties;let attribution;let sinks;let pending;let importsSqlDriver;const noteSpecifier=specifier=>{if(specifier!==null&&isSqlDriverSpecifier(specifier)){importsSqlDriver=true}};return{before(){const[options={}]=currentOptions();({reportUnattributedInterpolation=false,treatParametersAsUntrusted=true,requestRoots=REQUEST_ROOTS,requestProperties=REQUEST_PROPERTIES,sinkMethods=SQL_SINK_METHODS,transparentCalls=TRANSPARENT_CALLS,queryTextProperties=QUERY_TEXT_PROPERTIES}=options);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};sinks=new Set(sinkMethods);pending=[];importsSqlDriver=false},ImportDeclaration(node){noteSpecifier(node.source.value)},ImportExpression(node){noteSpecifier(stringLiteralValue(node.source))},TSImportEqualsDeclaration(node){if(node.moduleReference.type===eslint_devkit_1.AST_NODE_TYPES.TSExternalModuleReference){noteSpecifier(stringLiteralValue(node.moduleReference.expression))}},CallExpression(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="require"){noteSpecifier(stringLiteralValue(node.arguments[0]));return}if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;const callScope=context.sourceCode.getScope(node);const method=invokedMethodName(node.callee,callScope);if(method===null||!sinks.has(method))return;const[firstArgument]=node.arguments;if(firstArgument===void 0||firstArgument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){return}const{nodes,scope,substitutions}=effectiveExpression(firstArgument,callScope,attribution);const built=nodes.some(isBuiltString)||nodes.length>1&&nodes.some(n=>!(0,eslint_devkit_1.isStaticExpression)({node:n,scope}));if(!built)return;if(!looksLikeSqlStatement(nodes))return;const sinkAttribution={...attribution,substitutions};for(const candidate of nodes){const source=attributedSource(candidate,scope,sinkAttribution);if(source!==null){pending.push({node,source});return}}if(reportUnattributedInterpolation&&nodes.some(n=>(n.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral||n.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression)&&hasRawUnattributedPart(n,scope,substitutions))){pending.push({node,source:"a value this file cannot attribute"})}},"Program:exit"(){if(importsSqlDriver)return;for(const finding of pending){context.report({node:finding.node,messageId:"sqlInjection",data:{source:finding.source}})}}}}});exports.default=exports.noSqlInjection;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noTemplateInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const TEMPLATE_COMPILE_METHODS=new Set(["compile","precompile","create","parse","template"]);const TEMPLATE_RENDER_METHODS=new Set(["render","renderFile","renderString","renderToString","renderTemplate"]);const ALL_TEMPLATE_METHODS=new Set([...TEMPLATE_COMPILE_METHODS,...TEMPLATE_RENDER_METHODS]);const DEFAULT_TEMPLATE_ENGINES=["Handlebars","handlebars","ejs","pug","jade","mustache","Mustache","nunjucks","swig","dust","Dust","doT","consolidate"];const DEFAULT_REQUEST_ROOTS=["req","request","ctx","event","message"];const DEFAULT_REQUEST_PROPERTIES=["query","params","body","headers","url","path","cookies","data"];const READER_METHODS=new Set(["readFile","readFileSync","text","json","arrayBuffer","formData","blob"]);const DEFAULT_UNTRUSTED_NAME_WORDS=["user","untrusted","attacker","external","remote","client","payload","input"];function nameStatesUntrusted(name,vocabulary){const words=name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/);return words.some(word=>vocabulary.untrustedNameWords.has(word))}function untrustedSource(node,vocabulary,depth=0){if(depth>6)return null;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return untrustedSource(bare,vocabulary,depth+1);if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return nameStatesUntrusted(node.name,vocabulary)?node.name:null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){for(const expression of node.expressions){const found=untrustedSource(expression,vocabulary,depth+1);if(found!==null)return found}return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return untrustedSource(node.left,vocabulary,depth+1)??untrustedSource(node.right,vocabulary,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression){return untrustedSource(node.argument,vocabulary,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.LogicalExpression){return node.operator==="&&"?untrustedSource(node.right,vocabulary,depth+1):untrustedSource(node.left,vocabulary,depth+1)??untrustedSource(node.right,vocabulary,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){return untrustedSource(node.consequent,vocabulary,depth+1)??untrustedSource(node.alternate,vocabulary,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){let root=node;const properties=[];while(root.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const segment=(0,eslint_devkit_1.propertyName)(root);if(segment!==null){properties.unshift(segment)}root=root.object}if(root.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const chain=[root.name,...properties].join(".");if(vocabulary.requestRoots.has(root.name)&&properties.some(property=>vocabulary.requestProperties.has(property))){return chain}if(root.name==="process"&&properties[0]==="argv")return"process.argv";return[root.name,...properties].some(part=>nameStatesUntrusted(part,vocabulary))?chain:null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),READER_METHODS)){return(0,eslint_devkit_1.propertyName)(callee)}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&READER_METHODS.has(callee.name)){return callee.name}for(const argument of node.arguments){if(argument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)continue;const found=untrustedSource(argument,vocabulary,depth+1);if(found!==null)return found}return null}return null}exports.noTemplateInjection=(0,eslint_devkit_1.createRule)({name:"no-template-injection",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-template-injection.md",description:"Disallow dynamic strings as template arguments to server-side template engines (CWE-94)",cwe:"CWE-94",cvss:9.8},messages:{templateInjection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Template Injection (CWE-94)",cwe:"CWE-94",description:"{{engine}}.{{method}}() receives a dynamic string. An attacker who controls the template can execute arbitrary server-side code.",severity:"CRITICAL",fix:"Pass only string literals as templates. If the template must vary, load it from a trusted file system path, never from user input.",documentationLink:"https://portswigger.net/web-security/server-side-template-injection"})},schema:[{type:"object",properties:{templateEngines:{type:"array",items:{type:"string"},default:DEFAULT_TEMPLATE_ENGINES,description:"Receiver names that denote a server-side template engine, compared as an exact identifier name and never as a substring. Replaces the built-in list."},additionalTemplateEngines:{type:"array",items:{type:"string"},default:[],description:"Extra template-engine receiver names, on top of `templateEngines` \u2014 an alias import such as `hbs` belongs here."},requestRoots:{type:"array",items:{type:"string"},default:DEFAULT_REQUEST_ROOTS,description:"Identifier roots that denote an inbound request, matched as the exact ROOT of a member chain. Replaces the built-in list."},additionalRequestRoots:{type:"array",items:{type:"string"},default:[],description:"Extra request-object root names, on top of `requestRoots`."},requestProperties:{type:"array",items:{type:"string"},default:DEFAULT_REQUEST_PROPERTIES,description:"Request properties that carry caller-supplied data, matched as a whole segment of the member chain. Replaces the built-in list."},additionalRequestProperties:{type:"array",items:{type:"string"},default:[],description:"Extra request properties, on top of `requestProperties` \u2014 hapi's `request.payload` belongs here."},untrustedNameWords:{type:"array",items:{type:"string"},default:DEFAULT_UNTRUSTED_NAME_WORDS,description:"Words with which an author states a value came from outside, compared as a WHOLE word of the split identifier and never as a substring. Replaces the built-in list."},additionalUntrustedNameWords:{type:"array",items:{type:"string"},default:[],description:"Extra untrusted-provenance words, on top of `untrustedNameWords`."}},additionalProperties:false}]},defaultOptions:[{templateEngines:DEFAULT_TEMPLATE_ENGINES,additionalTemplateEngines:[],requestRoots:DEFAULT_REQUEST_ROOTS,additionalRequestRoots:[],requestProperties:DEFAULT_REQUEST_PROPERTIES,additionalRequestProperties:[],untrustedNameWords:DEFAULT_UNTRUSTED_NAME_WORDS,additionalUntrustedNameWords:[]}],createOnce(context){let engines;let vocabulary;return{before(){const options=context.options[0]??{};engines=new Set([...options.templateEngines??DEFAULT_TEMPLATE_ENGINES,...options.additionalTemplateEngines??[]]);vocabulary={requestRoots:new Set([...options.requestRoots??DEFAULT_REQUEST_ROOTS,...options.additionalRequestRoots??[]]),requestProperties:new Set([...options.requestProperties??DEFAULT_REQUEST_PROPERTIES,...options.additionalRequestProperties??[]]),untrustedNameWords:new Set([...options.untrustedNameWords??DEFAULT_UNTRUSTED_NAME_WORDS,...options.additionalUntrustedNameWords??[]])}},CallExpression(node){const{callee,arguments:args}=node;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noTemplateInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const TEMPLATE_COMPILE_METHODS=new Set(["compile","precompile","create","parse","template"]);const TEMPLATE_RENDER_METHODS=new Set(["render","renderFile","renderString","renderToString","renderTemplate"]);const ALL_TEMPLATE_METHODS=new Set([...TEMPLATE_COMPILE_METHODS,...TEMPLATE_RENDER_METHODS]);const DEFAULT_TEMPLATE_ENGINES=["Handlebars","handlebars","ejs","pug","jade","mustache","Mustache","nunjucks","swig","dust","Dust","doT","consolidate"];const ENGINE_MODULES=new Set(["handlebars","ejs","pug","jade","mustache","nunjucks","swig","dustjs-linkedin","dot","consolidate"]);const TEMPLATE_UTILITY_MODULES=new Set(["lodash","lodash-es","underscore"]);function isEngineMethod(module,path){if(path.length!==1)return false;const[method]=path;if(TEMPLATE_UTILITY_MODULES.has(module))return method==="template";return ENGINE_MODULES.has(module)&&ALL_TEMPLATE_METHODS.has(method)}const DEFAULT_REQUEST_ROOTS=["req","request","ctx","event","message"];const DEFAULT_REQUEST_PROPERTIES=["query","params","body","headers","url","path","cookies","data"];const READER_METHODS=new Set(["readFile","readFileSync","text","json","arrayBuffer","formData","blob"]);const DEFAULT_UNTRUSTED_NAME_WORDS=["user","untrusted","attacker","external","remote","client","payload","input"];function nameStatesUntrusted(name,vocabulary){const words=name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/);return words.some(word=>vocabulary.untrustedNameWords.has(word))}function untrustedSource(node,vocabulary,depth=0){if(depth>6)return null;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return untrustedSource(bare,vocabulary,depth+1);if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return nameStatesUntrusted(node.name,vocabulary)?node.name:null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){for(const expression of node.expressions){const found=untrustedSource(expression,vocabulary,depth+1);if(found!==null)return found}return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return untrustedSource(node.left,vocabulary,depth+1)??untrustedSource(node.right,vocabulary,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression){return untrustedSource(node.argument,vocabulary,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.LogicalExpression){return node.operator==="&&"?untrustedSource(node.right,vocabulary,depth+1):untrustedSource(node.left,vocabulary,depth+1)??untrustedSource(node.right,vocabulary,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){return untrustedSource(node.consequent,vocabulary,depth+1)??untrustedSource(node.alternate,vocabulary,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){let root=node;const properties=[];while(root.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const segment=(0,eslint_devkit_1.propertyName)(root);if(segment!==null){properties.unshift(segment)}root=root.object}if(root.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const chain=[root.name,...properties].join(".");if(vocabulary.requestRoots.has(root.name)&&properties.some(property=>vocabulary.requestProperties.has(property))){return chain}if(root.name==="process"&&properties[0]==="argv")return"process.argv";return[root.name,...properties].some(part=>nameStatesUntrusted(part,vocabulary))?chain:null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),READER_METHODS)){return(0,eslint_devkit_1.propertyName)(callee)}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&READER_METHODS.has(callee.name)){return callee.name}for(const argument of node.arguments){if(argument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)continue;const found=untrustedSource(argument,vocabulary,depth+1);if(found!==null)return found}return null}return null}exports.noTemplateInjection=(0,eslint_devkit_1.createRule)({name:"no-template-injection",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-template-injection.md",description:"Disallow dynamic strings as template arguments to server-side template engines (CWE-94)",cwe:"CWE-94",cvss:9.8},messages:{templateInjection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Template Injection (CWE-94)",cwe:"CWE-94",description:"{{engine}}.{{method}}() receives a dynamic string. An attacker who controls the template can execute arbitrary server-side code.",severity:"CRITICAL",fix:"Pass only string literals as templates. If the template must vary, load it from a trusted file system path, never from user input.",documentationLink:"https://portswigger.net/web-security/server-side-template-injection"})},schema:[{type:"object",properties:{templateEngines:{type:"array",items:{type:"string"},default:DEFAULT_TEMPLATE_ENGINES,description:"Receiver names that denote a server-side template engine, compared as an exact identifier name and never as a substring. Replaces the built-in list."},additionalTemplateEngines:{type:"array",items:{type:"string"},default:[],description:"Extra template-engine receiver names, on top of `templateEngines` \u2014 an alias import such as `hbs` belongs here."},requestRoots:{type:"array",items:{type:"string"},default:DEFAULT_REQUEST_ROOTS,description:"Identifier roots that denote an inbound request, matched as the exact ROOT of a member chain. Replaces the built-in list."},additionalRequestRoots:{type:"array",items:{type:"string"},default:[],description:"Extra request-object root names, on top of `requestRoots`."},requestProperties:{type:"array",items:{type:"string"},default:DEFAULT_REQUEST_PROPERTIES,description:"Request properties that carry caller-supplied data, matched as a whole segment of the member chain. Replaces the built-in list."},additionalRequestProperties:{type:"array",items:{type:"string"},default:[],description:"Extra request properties, on top of `requestProperties` \u2014 hapi's `request.payload` belongs here."},untrustedNameWords:{type:"array",items:{type:"string"},default:DEFAULT_UNTRUSTED_NAME_WORDS,description:"Words with which an author states a value came from outside, compared as a WHOLE word of the split identifier and never as a substring. Replaces the built-in list."},additionalUntrustedNameWords:{type:"array",items:{type:"string"},default:[],description:"Extra untrusted-provenance words, on top of `untrustedNameWords`."}},additionalProperties:false}]},defaultOptions:[{templateEngines:DEFAULT_TEMPLATE_ENGINES,additionalTemplateEngines:[],requestRoots:DEFAULT_REQUEST_ROOTS,additionalRequestRoots:[],requestProperties:DEFAULT_REQUEST_PROPERTIES,additionalRequestProperties:[],untrustedNameWords:DEFAULT_UNTRUSTED_NAME_WORDS,additionalUntrustedNameWords:[]}],createOnce(context){let engines;let vocabulary;function engineCall(callee){const binding=(0,eslint_devkit_1.resolveModuleBinding)(callee,context.sourceCode.getScope(callee));if(binding!==void 0&&isEngineMethod(binding.module,binding.path)){return{engineName:callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?callee.object.name:binding.module,methodName:binding.path.join(".")}}if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return null;const{object}=callee;if(object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const methodName=(0,eslint_devkit_1.propertyName)(callee);if(methodName===null)return null;if(!engines.has(object.name))return null;if(!ALL_TEMPLATE_METHODS.has(methodName))return null;return{engineName:object.name,methodName}}return{before(){const options=context.options[0]??{};engines=new Set([...options.templateEngines??DEFAULT_TEMPLATE_ENGINES,...options.additionalTemplateEngines??[]]);vocabulary={requestRoots:new Set([...options.requestRoots??DEFAULT_REQUEST_ROOTS,...options.additionalRequestRoots??[]]),requestProperties:new Set([...options.requestProperties??DEFAULT_REQUEST_PROPERTIES,...options.additionalRequestProperties??[]]),untrustedNameWords:new Set([...options.untrustedNameWords??DEFAULT_UNTRUSTED_NAME_WORDS,...options.additionalUntrustedNameWords??[]])}},CallExpression(node){const{callee,arguments:args}=node;const target=engineCall(callee);if(target===null)return;const{engineName,methodName}=target;const firstArg=args[0];if(!firstArg)return;if(untrustedSource(firstArg,vocabulary)===null)return;context.report({node:firstArg,messageId:"templateInjection",data:{engine:engineName,method:methodName}})}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUncheckedLoopCondition=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.noUncheckedLoopCondition=(0,eslint_devkit_1.createRule)({name:"no-unchecked-loop-condition",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-unchecked-loop-condition.md",description:"Detects unchecked loop conditions that could cause DoS",cwe:"CWE-400"},messages:{uncheckedLoopCondition:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unchecked Loop Condition",cwe:"CWE-400",description:"Loop condition may cause DoS through excessive iterations",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),infiniteLoop:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Infinite Loop",cwe:"CWE-400",description:"Loop may run indefinitely",severity:"CRITICAL",fix:"Add termination condition or iteration limit",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),userControlledLoopBound:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"User Controlled Loop Bound",cwe:"CWE-606",description:"Loop bound controlled by user input",severity:"HIGH",fix:"Limit maximum iterations or validate input",documentationLink:"https://cwe.mitre.org/data/definitions/606.html"}),missingLoopTermination:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Loop Termination",cwe:"CWE-400",description:"Loop lacks clear termination condition",severity:"MEDIUM",fix:"Add explicit termination condition",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),largeLoopBound:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Large Loop Bound",cwe:"CWE-400",description:"Loop may iterate excessively",severity:"MEDIUM",fix:"Limit maximum iterations",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),unsafeRecursion:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Recursion",cwe:"CWE-674",description:"Recursive function may cause stack overflow",severity:"HIGH",fix:"Add recursion depth limit or use iterative approach",documentationLink:"https://cwe.mitre.org/data/definitions/674.html"})},schema:[{type:"object",properties:{maxStaticIterations:{type:"number",minimum:100,default:1e4,description:"Literal iteration count above which a loop is reported"},userInputVariables:{type:"array",items:{type:"string"},default:["req","request","body","query","params","input","data"],description:"Variable names treated as user-controlled input"},allowWhileTrueWithBreak:{type:"boolean",default:true,description:"Allow `while (true)` when the body contains a `break`"},maxRecursionDepth:{type:"number",minimum:1,default:10,description:"Recursion depth above which a call is reported"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as loop protectors"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},defaultOptions:[{maxStaticIterations:1e4,userInputVariables:["req","request","body","query","params","input","data"],allowWhileTrueWithBreak:true,maxRecursionDepth:10,trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],createOnce(context){let maxStaticIterations;let userInputVariables;let allowWhileTrueWithBreak;let maxRecursionDepth;let trustedSanitizers;let trustedAnnotations;let strictMode;let sourceCode;let filename;let safetyChecker;let functionCalls;let reportedRecursion;let currentFunctionStack;let taintedVariables;let REQUEST_OBJECTS;const isUserInput=varName=>{if(taintedVariables.has(varName)){return true}const lowerVarName=varName.toLowerCase();const isUsingDefaults=userInputVariables.length===7&&userInputVariables.includes("req")&&userInputVariables.includes("input");if(!isUsingDefaults){return userInputVariables.some(input=>lowerVarName===input.toLowerCase())}return REQUEST_OBJECTS.has(lowerVarName)};const checkIfCollectionIsValidated=(forOfNode,collection)=>{const guarded=collection;const validates=test=>{let sawArrayCheck=false;let sawLengthComparison=false;const walk=node=>{if(node.type==="CallExpression"&&node.callee.type==="MemberExpression"&&node.callee.object.type==="Identifier"&&node.callee.object.name==="Array"&&(0,eslint_devkit_1.propertyName)(node.callee)==="isArray"&&node.arguments.some(a=>a.type!=="SpreadElement"&&samePath(a,guarded))){sawArrayCheck=true}if(node.type==="BinaryExpression"&&["<","<=",">",">=","===","==","!==","!="].includes(node.operator)){for(const side of[node.left,node.right]){if(side.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(side)==="length"&&samePath(side.object,guarded)){sawLengthComparison=true}}}const walkIfNode=value=>{if(value&&typeof value==="object"&&"type"in value)walk(value)};for(const key of["left","right","argument","expression","test","object","callee"]){walkIfNode(node[key])}const args=node.arguments;if(Array.isArray(args)){for(const a of args)walkIfNode(a)}};walk(test);return sawArrayCheck&&sawLengthComparison};for(let current=forOfNode.parent;current;current=current.parent){if(current.type==="IfStatement"&&validates(current.test))return true;if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){break}}for(let current=forOfNode;current;current=current.parent){const parent=current.parent;if(parent?.type==="BlockStatement"||parent?.type==="Program"){const body=parent.body;const index=body.indexOf(current);for(const statement of body.slice(0,index)){if(statement.type==="IfStatement"&&validates(statement.test))return true}}if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){break}}return false};const resolveVariable=node=>{const scope=sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===node.name);if(variable)return variable}return null};const samePath=(left,right)=>{const a=(0,eslint_devkit_3.unwrapTypeSyntax)(left);const b=(0,eslint_devkit_3.unwrapTypeSyntax)(right);if(a.type==="Identifier"&&b.type==="Identifier"){const va=resolveVariable(a);const vb=resolveVariable(b);return va||vb?va===vb:a.name===b.name}if(a.type==="MemberExpression"&&b.type==="MemberExpression"){return(0,eslint_devkit_1.propertyName)(a)===(0,eslint_devkit_1.propertyName)(b)&&samePath(a.object,b.object)}return false};const isClamped=node=>{const expression=(0,eslint_devkit_3.unwrapTypeSyntax)(node);if(expression.type==="CallExpression"&&expression.callee.type==="MemberExpression"&&!expression.callee.computed&&expression.callee.object.type==="Identifier"&&expression.callee.object.name==="Math"&&expression.callee.property.type==="Identifier"&&["min","max"].includes(expression.callee.property.name)){return true}if(expression.type==="BinaryExpression"||expression.type==="LogicalExpression"){return isClamped(expression.left)||isClamped(expression.right)}if(expression.type==="ConditionalExpression"){return isClamped(expression.consequent)&&isClamped(expression.alternate)}return false};const involvesUserInput=expression=>{const checkExpression=raw=>{const node=(0,eslint_devkit_3.unwrapTypeSyntax)(raw);if(node.type==="MemberExpression"){if((0,eslint_devkit_1.propertyName)(node)==="length"){return false}const objectText=sourceCode.getText(node.object);if(isUserInput(objectText)){return true}return checkExpression(node.object)}if(node.type==="Identifier"){return isUserInput(node.name)}if(node.type==="CallExpression"){return checkExpression(node.callee)||node.arguments.filter(arg=>arg.type!=="SpreadElement").some(arg=>checkExpression(arg))}if(node.type==="LogicalExpression"){return node.operator==="&&"?checkExpression(node.right):checkExpression(node.left)||checkExpression(node.right)}if(node.type==="BinaryExpression"){return checkExpression(node.left)||checkExpression(node.right)}if(node.type==="UpdateExpression"){return checkExpression(node.argument)}if(node.type==="UnaryExpression"){return checkExpression(node.argument)}return false};return checkExpression(expression)};const hasBreakStatement=loopBody=>{let hasBreak=false;const visited=new Set;const checkNode=(node,depth=0)=>{if(depth>10||visited.has(node)){return}visited.add(node);if(node.type==="BreakStatement"){hasBreak=true;return}for(const key in node){const child=node[key];if(child&&typeof child==="object"){if("type"in child){checkNode(child,depth+1)}else if(Array.isArray(child)){child.forEach(item=>{if(item&&typeof item==="object"&&"type"in item){checkNode(item,depth+1)}})}}}};checkNode(loopBody);return hasBreak};const hasLoopExit=loopBody=>{let found=false;const innerLabels=new Set;const walk=(node,insideNestedBreakable)=>{if(found)return;switch(node.type){case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":return;case"BreakStatement":if(node.label===null){if(!insideNestedBreakable)found=true}else if(!innerLabels.has(node.label.name)){found=true}return;case"ReturnStatement":case"ThrowStatement":found=true;return;default:break}if(node.type==="LabeledStatement")innerLabels.add(node.label.name);const breakable=insideNestedBreakable||node.type==="ForStatement"||node.type==="ForInStatement"||node.type==="ForOfStatement"||node.type==="WhileStatement"||node.type==="DoWhileStatement"||node.type==="SwitchStatement";for(const key of Object.keys(node)){if(key==="parent")continue;const child=node[key];if(child===null||typeof child!=="object")continue;if(Array.isArray(child)){for(const item of child){if(item!==null&&typeof item==="object"&&"type"in item){walk(item,breakable)}}}else if("type"in child){walk(child,breakable)}}};walk(loopBody,false);return found};const isUnconditionalSelfCall=call=>{const BRANCHING=new Set(["IfStatement","ConditionalExpression","LogicalExpression","SwitchStatement","SwitchCase","ForStatement","ForInStatement","ForOfStatement","WhileStatement","DoWhileStatement","TryStatement","CatchClause"]);let child=call;for(let current=call.parent;current;child=current,current=current.parent){if(BRANCHING.has(current.type))return false;if(current.type==="BlockStatement"){const index=current.body.indexOf(child);const preceding=current.body.slice(0,index);if(preceding.some(statement=>statement.type==="IfStatement"&&exits(statement))){return false}}if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){return true}}return false};const exits=node=>{if(node.type==="ReturnStatement"||node.type==="ThrowStatement")return true;for(const key in node){const child=node[key];if(key==="parent"||!child||typeof child!=="object")continue;if("type"in child){if(exits(child))return true}else if(Array.isArray(child)){for(const item of child){if(item&&typeof item==="object"&&"type"in item&&exits(item))return true}}}return false};const estimateIterations=loop=>{const test=loop.test;if(test&&test.type==="BinaryExpression"){if(test.operator==="<"||test.operator==="<="||test.operator===">"||test.operator===">="){const right=test.right;if(right.type==="Literal"&&typeof right.value==="number"){return Math.abs(right.value)}}}return null};return{before(){const options=context.options[0]||{};({maxStaticIterations=1e4,userInputVariables=["req","request","body","query","params","input","data"],allowWhileTrueWithBreak=true,maxRecursionDepth=10,trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options);sourceCode=context.sourceCode;filename=context.filename;safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});functionCalls=new Map;reportedRecursion=new Set;currentFunctionStack=[];taintedVariables=new Set;REQUEST_OBJECTS=new Set(["req","request","ctx","context","event"])},VariableDeclaration(node){for(const declarator of node.declarations){if(declarator.id.type==="Identifier"&&declarator.init){const varName=declarator.id.name;const hasUserInput=involvesUserInput(declarator.init);const isSanitized=isClamped(declarator.init);if(hasUserInput&&!isSanitized){taintedVariables.add(varName)}}}},FunctionDeclaration(node){if(node.id){currentFunctionStack.push(node.id.name)}},"FunctionDeclaration:exit"(node){if(node.id&¤tFunctionStack[currentFunctionStack.length-1]===node.id.name){currentFunctionStack.pop()}},CallExpression(node){const callee=node.callee;if(callee.type==="Identifier"){const functionName=callee.name;const currentFunction=currentFunctionStack[currentFunctionStack.length-1];if(currentFunction&&functionName===currentFunction){const callCount=(functionCalls.get(functionName)||0)+1;functionCalls.set(functionName,callCount);if(!reportedRecursion.has(functionName)){if(callCount>maxRecursionDepth||isUnconditionalSelfCall(node)){if(safetyChecker.isSafe(node,context)){return}reportedRecursion.add(functionName);context.report({node,messageId:"unsafeRecursion",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}},WhileStatement(node){const test=node.test;if(test.type==="Literal"&&test.value===true){const hasBreak=hasBreakStatement(node.body);if(allowWhileTrueWithBreak&&hasBreak){return}context.report({node,messageId:"infiniteLoop",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(involvesUserInput(test)){if(safetyChecker.isSafe(node,context)){return}context.report({node:test,messageId:"userControlledLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}},ForStatement(node){if(!node.test&&!node.update){if(safetyChecker.isSafe(node,context)){return}if(allowWhileTrueWithBreak&&hasLoopExit(node.body)){return}context.report({node,messageId:"infiniteLoop",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(!node.test){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"missingLoopTermination",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(involvesUserInput(node.test)){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.test,messageId:"userControlledLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}const estimatedIterations=estimateIterations(node);if(estimatedIterations&&estimatedIterations>maxStaticIterations){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.test,messageId:"largeLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},DoWhileStatement(node){const test=node.test;if(involvesUserInput(test)){if(safetyChecker.isSafe(node,context)){return}context.report({node:test,messageId:"userControlledLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},ForInStatement(node){const right=node.right;if(involvesUserInput(right)){if(safetyChecker.isSafe(node,context)){return}context.report({node:right,messageId:"uncheckedLoopCondition",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"MEDIUM",safeAlternative:"Limit collection size or add iteration timeout"}})}},ForOfStatement(node){const right=node.right;if(involvesUserInput(right)){const isValidated=checkIfCollectionIsValidated(node,right);if(isValidated){return}if(safetyChecker.isSafe(node,context)){return}context.report({node:right,messageId:"uncheckedLoopCondition",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"MEDIUM",safeAlternative:"Limit collection size before iteration"}})}}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUncheckedLoopCondition=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.noUncheckedLoopCondition=(0,eslint_devkit_1.createRule)({name:"no-unchecked-loop-condition",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-unchecked-loop-condition.md",description:"Detects unchecked loop conditions that could cause DoS",cwe:"CWE-400"},messages:{uncheckedLoopCondition:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unchecked Loop Condition",cwe:"CWE-400",description:"Loop condition may cause DoS through excessive iterations",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),infiniteLoop:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Infinite Loop",cwe:"CWE-400",description:"Loop may run indefinitely",severity:"CRITICAL",fix:"Add termination condition or iteration limit",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),userControlledLoopBound:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"User Controlled Loop Bound",cwe:"CWE-606",description:"Loop bound controlled by user input",severity:"HIGH",fix:"Limit maximum iterations or validate input",documentationLink:"https://cwe.mitre.org/data/definitions/606.html"}),missingLoopTermination:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Loop Termination",cwe:"CWE-400",description:"Loop lacks clear termination condition",severity:"MEDIUM",fix:"Add explicit termination condition",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),largeLoopBound:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Large Loop Bound",cwe:"CWE-400",description:"Loop may iterate excessively",severity:"MEDIUM",fix:"Limit maximum iterations",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),unsafeRecursion:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Recursion",cwe:"CWE-674",description:"Recursive function may cause stack overflow",severity:"HIGH",fix:"Add recursion depth limit or use iterative approach",documentationLink:"https://cwe.mitre.org/data/definitions/674.html"})},schema:[{type:"object",properties:{maxStaticIterations:{type:"number",minimum:100,default:1e4,description:"Literal iteration count above which a loop is reported"},userInputVariables:{type:"array",items:{type:"string"},default:["req","request","body","query","params","input","data"],description:"Variable names treated as user-controlled input"},allowWhileTrueWithBreak:{type:"boolean",default:true,description:"Allow an infinite-loop form (`while (true)`, `while (1)`, `do \u2026 while (true)`, `for (;;)`) whose body leaves it: a `break` of that loop, a `return` or a `throw`"},maxRecursionDepth:{type:"number",minimum:1,default:10,description:"Recursion depth above which a call is reported"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as loop protectors"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},defaultOptions:[{maxStaticIterations:1e4,userInputVariables:["req","request","body","query","params","input","data"],allowWhileTrueWithBreak:true,maxRecursionDepth:10,trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],createOnce(context){let maxStaticIterations;let userInputVariables;let allowWhileTrueWithBreak;let maxRecursionDepth;let trustedSanitizers;let trustedAnnotations;let strictMode;let sourceCode;let filename;let safetyChecker;let functionCalls;let reportedRecursion;let currentFunctionStack;let taintedVariables;let REQUEST_OBJECTS;const isUserInput=varName=>{if(taintedVariables.has(varName)){return true}const lowerVarName=varName.toLowerCase();const isUsingDefaults=userInputVariables.length===7&&userInputVariables.includes("req")&&userInputVariables.includes("input");if(!isUsingDefaults){return userInputVariables.some(input=>lowerVarName===input.toLowerCase())}return REQUEST_OBJECTS.has(lowerVarName)};const checkIfCollectionIsValidated=(forOfNode,collection)=>{const guarded=collection;const validates=test=>{let sawArrayCheck=false;let sawLengthComparison=false;const walk=node=>{if(node.type==="CallExpression"&&node.callee.type==="MemberExpression"&&node.callee.object.type==="Identifier"&&node.callee.object.name==="Array"&&(0,eslint_devkit_1.propertyName)(node.callee)==="isArray"&&node.arguments.some(a=>a.type!=="SpreadElement"&&samePath(a,guarded))){sawArrayCheck=true}if(node.type==="BinaryExpression"&&["<","<=",">",">=","===","==","!==","!="].includes(node.operator)){for(const side of[node.left,node.right]){if(side.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(side)==="length"&&samePath(side.object,guarded)){sawLengthComparison=true}}}const walkIfNode=value=>{if(value&&typeof value==="object"&&"type"in value)walk(value)};for(const key of["left","right","argument","expression","test","object","callee"]){walkIfNode(node[key])}const args=node.arguments;if(Array.isArray(args)){for(const a of args)walkIfNode(a)}};walk(test);return sawArrayCheck&&sawLengthComparison};for(let current=forOfNode.parent;current;current=current.parent){if(current.type==="IfStatement"&&validates(current.test))return true;if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){break}}for(let current=forOfNode;current;current=current.parent){if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){break}const parent=current.parent;if(parent?.type==="BlockStatement"||parent?.type==="Program"){const body=parent.body;const index=body.indexOf(current);for(const statement of body.slice(0,index)){if(statement.type==="IfStatement"&&validates(statement.test))return true}}}return false};const resolveVariable=node=>{const scope=sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===node.name);if(variable)return variable}return null};const samePath=(left,right)=>{const a=(0,eslint_devkit_3.unwrapTypeSyntax)(left);const b=(0,eslint_devkit_3.unwrapTypeSyntax)(right);if(a.type==="Identifier"&&b.type==="Identifier"){const va=resolveVariable(a);const vb=resolveVariable(b);return va||vb?va===vb:a.name===b.name}if(a.type==="MemberExpression"&&b.type==="MemberExpression"){return(0,eslint_devkit_1.propertyName)(a)===(0,eslint_devkit_1.propertyName)(b)&&samePath(a.object,b.object)}return false};const isClamped=node=>{const expression=(0,eslint_devkit_3.unwrapTypeSyntax)(node);if(expression.type==="CallExpression"&&expression.callee.type==="MemberExpression"&&!expression.callee.computed&&expression.callee.object.type==="Identifier"&&expression.callee.object.name==="Math"&&expression.callee.property.type==="Identifier"&&["min","max"].includes(expression.callee.property.name)){return true}if(expression.type==="BinaryExpression"||expression.type==="LogicalExpression"){const bounded=side=>isClamped(side)||!involvesUserInput(side);return bounded(expression.left)&&bounded(expression.right)}return false};const involvesUserInput=expression=>{const checkExpression=raw=>{const node=(0,eslint_devkit_3.unwrapTypeSyntax)(raw);if(node.type==="MemberExpression"){if((0,eslint_devkit_1.propertyName)(node)==="length"){return false}return checkExpression(node.object)}if(node.type==="Identifier"){return isUserInput(node.name)}if(node.type==="CallExpression"){return checkExpression(node.callee)||node.arguments.filter(arg=>arg.type!=="SpreadElement").some(arg=>checkExpression(arg))}if(node.type==="LogicalExpression"){return node.operator==="&&"?checkExpression(node.right):checkExpression(node.left)||checkExpression(node.right)}if(node.type==="BinaryExpression"){return checkExpression(node.left)||checkExpression(node.right)}if(node.type==="UpdateExpression"){return checkExpression(node.argument)}if(node.type==="UnaryExpression"){return checkExpression(node.argument)}return false};return checkExpression(expression)};const hasLoopExit=loopBody=>{let found=false;const innerLabels=new Set;const walk=(node,insideNestedBreakable)=>{if(found)return;switch(node.type){case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":return;case"BreakStatement":if(node.label===null){if(!insideNestedBreakable)found=true}else if(!innerLabels.has(node.label.name)){found=true}return;case"ReturnStatement":case"ThrowStatement":found=true;return;default:break}if(node.type==="LabeledStatement")innerLabels.add(node.label.name);const breakable=insideNestedBreakable||node.type==="ForStatement"||node.type==="ForInStatement"||node.type==="ForOfStatement"||node.type==="WhileStatement"||node.type==="DoWhileStatement"||node.type==="SwitchStatement";for(const key of Object.keys(node)){if(key==="parent")continue;const child=node[key];if(child===null||typeof child!=="object")continue;if(Array.isArray(child)){for(const item of child){if(item!==null&&typeof item==="object"&&"type"in item){walk(item,breakable)}}}else if("type"in child){walk(child,breakable)}}};walk(loopBody,false);return found};const isUnconditionalSelfCall=call=>{const BRANCHING=new Set(["IfStatement","ConditionalExpression","LogicalExpression","SwitchStatement","SwitchCase","ForStatement","ForInStatement","ForOfStatement","WhileStatement","DoWhileStatement","TryStatement","CatchClause"]);for(let child=call,current=call.parent;;child=current,current=current.parent){if(BRANCHING.has(current.type))return false;if(current.type==="BlockStatement"){const index=current.body.indexOf(child);const preceding=current.body.slice(0,index);if(preceding.some(statement=>statement.type==="IfStatement"&&exits(statement))){return false}}if(current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){return false}if(current.type==="FunctionDeclaration")return true}};const exits=node=>{if(node.type==="ReturnStatement"||node.type==="ThrowStatement")return true;for(const key in node){const child=node[key];if(key==="parent"||!child||typeof child!=="object")continue;if("type"in child){if(exits(child))return true}else if(Array.isArray(child)){for(const item of child){if(item&&typeof item==="object"&&"type"in item&&exits(item))return true}}}return false};const estimateIterations=test=>{if(test.type==="BinaryExpression"){if(test.operator==="<"||test.operator==="<="||test.operator===">"||test.operator===">="){const right=test.right;if(right.type==="Literal"&&typeof right.value==="number"){return Math.abs(right.value)}}}return null};const checkInfiniteLoop=node=>{if(safetyChecker.isSafe(node,context)){return}if(allowWhileTrueWithBreak&&hasLoopExit(node.body)){return}context.report({node,messageId:"infiniteLoop",data:{filePath:filename,line:String(node.loc?.start.line??0)}})};const isConstantlyTrue=test=>test.type==="Literal"&&Boolean(test.value);const checkLargeBound=(node,test)=>{const estimatedIterations=estimateIterations(test);if(estimatedIterations&&estimatedIterations>maxStaticIterations){if(safetyChecker.isSafe(node,context)){return}context.report({node:test,messageId:"largeLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}};return{before(){const options=context.options[0]||{};({maxStaticIterations=1e4,userInputVariables=["req","request","body","query","params","input","data"],allowWhileTrueWithBreak=true,maxRecursionDepth=10,trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options);sourceCode=context.sourceCode;filename=context.filename;safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});functionCalls=new Map;reportedRecursion=new Set;currentFunctionStack=[];taintedVariables=new Set;REQUEST_OBJECTS=new Set(["req","request","ctx","context","event"])},VariableDeclaration(node){for(const declarator of node.declarations){if(declarator.id.type==="Identifier"&&declarator.init){const varName=declarator.id.name;const hasUserInput=involvesUserInput(declarator.init);const isSanitized=isClamped(declarator.init);if(hasUserInput&&!isSanitized){taintedVariables.add(varName)}}}},FunctionDeclaration(node){if(node.id){currentFunctionStack.push(node.id.name)}},"FunctionDeclaration:exit"(node){if(node.id&¤tFunctionStack[currentFunctionStack.length-1]===node.id.name){currentFunctionStack.pop()}},CallExpression(node){const callee=node.callee;if(callee.type==="Identifier"){const functionName=callee.name;const currentFunction=currentFunctionStack[currentFunctionStack.length-1];if(currentFunction&&functionName===currentFunction){const callCount=(functionCalls.get(functionName)||0)+1;functionCalls.set(functionName,callCount);if(!reportedRecursion.has(functionName)){if(callCount>maxRecursionDepth||isUnconditionalSelfCall(node)){if(safetyChecker.isSafe(node,context)){return}reportedRecursion.add(functionName);context.report({node,messageId:"unsafeRecursion",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}},WhileStatement(node){const test=node.test;if(isConstantlyTrue(test)){checkInfiniteLoop(node);return}if(involvesUserInput(test)){if(safetyChecker.isSafe(node,context)){return}context.report({node:test,messageId:"userControlledLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}checkLargeBound(node,test)},ForStatement(node){if(!node.test&&!node.update){checkInfiniteLoop(node);return}if(!node.test){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"missingLoopTermination",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(involvesUserInput(node.test)){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.test,messageId:"userControlledLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}checkLargeBound(node,node.test)},DoWhileStatement(node){const test=node.test;if(isConstantlyTrue(test)){checkInfiniteLoop(node);return}if(involvesUserInput(test)){if(safetyChecker.isSafe(node,context)){return}context.report({node:test,messageId:"userControlledLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},ForInStatement(node){const right=node.right;if(involvesUserInput(right)){if(safetyChecker.isSafe(node,context)){return}context.report({node:right,messageId:"uncheckedLoopCondition",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"MEDIUM",safeAlternative:"Limit collection size or add iteration timeout"}})}},ForOfStatement(node){const right=node.right;if(involvesUserInput(right)){const isValidated=checkIfCollectionIsValidated(node,right);if(isValidated){return}if(safetyChecker.isSafe(node,context)){return}context.report({node:right,messageId:"uncheckedLoopCondition",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"MEDIUM",safeAlternative:"Limit collection size before iteration"}})}}}}});
|
|
@@ -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");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:{interop:{runtimes:["eslint","oxlint"]},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}],createOnce(context){let sizeProperties;let limitOptionNames;let maxResourceSize;let userInputVariables;let safeResourceFunctions;let requireResourceValidation;let trustedSanitizers;let trustedAnnotations;let strictMode;let sourceCode;let filename;let safetyChecker;let REQUEST_SURFACE;let requestRoots;const ARCHIVE_MODULES=/^(unzipper|tar|tar-stream|yauzl|adm-zip|node:zlib|zlib)$/;let archiveBindings;let ALLOCATORS;const readsRequestSurface=node=>node?.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node),REQUEST_SURFACE);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(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node),sizeProperties);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 noteArchiveBinding=(local,source)=>{if(ARCHIVE_MODULES.test(source))archiveBindings.add(local)};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;const member=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type==="Identifier"){name=callee.name}else if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&member!==null){name=`${callee.object.name}.${member}`}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{before(){const options=context.options[0]||{};sizeProperties=new Set(options.sizeProperties??DEFAULT_SIZE_PROPERTIES);limitOptionNames=new Set(options.limitOptionNames??DEFAULT_LIMIT_OPTION_NAMES);({maxResourceSize=1048576,userInputVariables=["req","request","body","query","params","input","data"],safeResourceFunctions=["validateSize","checkLimits","limitResource","safeAlloc"],requireResourceValidation=true,trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options);sourceCode=context.sourceCode;filename=context.filename;safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});REQUEST_SURFACE=new Set(["body","query","params","headers","cookies","url","originalUrl","rawBody","files","payload","searchParams"]);requestRoots=new Set(userInputVariables.map(name=>name.toLowerCase()));archiveBindings=new Set(["zlib"]);ALLOCATORS=new Set(["Buffer.alloc","Buffer.allocUnsafe","Buffer.allocUnsafeSlow","Buffer","Array","Map","Set","WeakMap","WeakSet"])},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"&&((0,eslint_devkit_1.propertyName)(callee)==="alloc"||(0,eslint_devkit_1.propertyName)(callee)==="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"&&["readFile","writeFile","readFileSync","writeFileSync"].includes((0,eslint_devkit_1.propertyName)(callee)??"")){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=(0,eslint_devkit_1.propertyName)(member)??"";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&&((0,eslint_devkit_1.propertyName)(candidate.right)==="length"||(0,eslint_devkit_1.propertyName)(candidate.right)==="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"];const BYTE_BUFFER_CONSTRUCTORS=new Set(["ArrayBuffer","SharedArrayBuffer"]);exports.noUnlimitedResourceAllocation=(0,eslint_devkit_1.createRule)({name:"no-unlimited-resource-allocation",meta:{interop:{runtimes:["eslint","oxlint"]},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}],createOnce(context){let sizeProperties;let limitOptionNames;let maxResourceSize;let userInputVariables;let safeResourceFunctions;let requireResourceValidation;let trustedSanitizers;let trustedAnnotations;let strictMode;let sourceCode;let safetyChecker;let REQUEST_SURFACE;let requestRoots;const ARCHIVE_MODULES=/^(unzipper|tar|tar-stream|yauzl|adm-zip|node:zlib|zlib)$/;let archiveBindings;let ALLOCATORS;const readsRequestSurface=node=>node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node),REQUEST_SURFACE);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=>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(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node),sizeProperties);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 testsUpperBound=(test,name)=>{if(test.type===eslint_devkit_1.AST_NODE_TYPES.LogicalExpression){return testsUpperBound(test.left,name)||testsUpperBound(test.right,name)}if(test.type!==eslint_devkit_1.AST_NODE_TYPES.BinaryExpression)return false;const isName=side=>side.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&side.name===name;return(test.operator===">"||test.operator===">=")&&isName(test.left)||(test.operator==="<"||test.operator==="<=")&&isName(test.right)};const alwaysExits=statement=>{const last=statement.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement?statement.body.at(-1):statement;return last?.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement||last?.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement};const hasUpperBoundGuard=node=>{const[sizeArg]=node.arguments;if(sizeArg.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;for(let child=node,parent=node.parent;parent;child=parent,parent=parent.parent){if(parent.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement&&parent.type!==eslint_devkit_1.AST_NODE_TYPES.Program){continue}const statements=parent.body;if(statements.slice(0,statements.indexOf(child)).some(statement=>statement.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement&&testsUpperBound(statement.test,sizeArg.name)&&alwaysExits(statement.consequent))){return true}}return false};const isBounded=node=>hasSizeValidation(node)||hasUpperBoundGuard(node);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 noteArchiveBinding=(local,source)=>{if(ARCHIVE_MODULES.test(source))archiveBindings.add(local)};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;const member=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type==="Identifier"){name=callee.name}else if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&member!==null){name=`${callee.object.name}.${member}`}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)};const checkArrayLength=node=>{const args=node.arguments;if(args.length!==1)return;const sizeArg=args[0];if(sizeArg.type==="SpreadElement")return;const unbounded=isUserInput(sizeArg)&&!isBounded(node);const estimatedSize=estimateResourceSize(sizeArg);if(!unbounded&&(estimatedSize===null||estimatedSize<=maxResourceSize)){return}if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"unlimitedMemoryAllocation"})};return{before(){const options=context.options[0]||{};sizeProperties=new Set(options.sizeProperties??DEFAULT_SIZE_PROPERTIES);limitOptionNames=new Set(options.limitOptionNames??DEFAULT_LIMIT_OPTION_NAMES);({maxResourceSize=1048576,userInputVariables=["req","request","body","query","params","input","data"],safeResourceFunctions=["validateSize","checkLimits","limitResource","safeAlloc"],requireResourceValidation=true,trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options);sourceCode=context.sourceCode;safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});REQUEST_SURFACE=new Set(["body","query","params","headers","cookies","url","originalUrl","rawBody","files","payload","searchParams"]);requestRoots=new Set(userInputVariables.map(name=>name.toLowerCase()));archiveBindings=new Set(["zlib"]);ALLOCATORS=new Set(["Buffer.alloc","Buffer.allocUnsafe","Buffer.allocUnsafeSlow","Buffer","Array","Map","Set","WeakMap","WeakSet"])},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"&&((0,eslint_devkit_1.propertyName)(callee)==="alloc"||(0,eslint_devkit_1.propertyName)(callee)==="allocUnsafe");if(isBufferAlloc){const args=node.arguments;if(args.length>0){const sizeArg=args[0];if(requireResourceValidation&&sizeArg.type!=="SpreadElement"&&isUserInput(sizeArg)&&!isBounded(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"userControlledResourceSize"});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"});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"})}}return}if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="fs"&&["readFile","writeFile","readFileSync","writeFileSync"].includes((0,eslint_devkit_1.propertyName)(callee)??"")){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"})}}}if(callee.type==="Identifier"&&callee.name==="Array"){checkArrayLength(node)}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=(0,eslint_devkit_1.propertyName)(member)??"";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(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&&((0,eslint_devkit_1.propertyName)(candidate.right)==="length"||(0,eslint_devkit_1.propertyName)(candidate.right)==="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"})}if(isAllocationInLoopBody(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"resourceAllocationInLoop"})}},NewExpression(node){const callee=node.callee;if(callee.type==="Identifier"&&(callee.name==="Buffer"||BYTE_BUFFER_CONSTRUCTORS.has(callee.name))){const reservesBytes=BYTE_BUFFER_CONSTRUCTORS.has(callee.name);const args=node.arguments;if(args.length>0){const sizeArg=args[0];const hasEncodingArgument=args.length>1;if(requireResourceValidation&&sizeArg.type!=="SpreadElement"&&(reservesBytes||!hasEncodingArgument&&couldBeASize(sizeArg))&&isUserInput(sizeArg)&&!isBounded(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"userControlledResourceSize"});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"});return}}}if(callee.type==="Identifier"&&callee.name==="Array"){checkArrayLength(node)}if(isAllocationInLoopBody(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"resourceAllocationInLoop"})}}}}});
|