eslint-plugin-lambda-security 1.3.4 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/src/index.js +1 -1
- package/src/rules/no-env-logging/index.js +1 -1
- package/src/rules/no-error-swallowing/index.js +1 -1
- package/src/rules/no-exposed-debug-endpoints/index.js +1 -1
- package/src/rules/no-exposed-error-details/index.js +1 -1
- package/src/rules/no-hardcoded-credentials-sdk/index.js +1 -1
- package/src/rules/no-missing-authorization-check/index.js +1 -1
- package/src/rules/no-overly-permissive-iam-policy/index.js +1 -1
- package/src/rules/no-permissive-cors-middy/index.js +1 -1
- package/src/rules/no-permissive-cors-response/index.js +1 -1
- package/src/rules/no-secrets-in-env/index.js +1 -1
- package/src/rules/no-unbounded-batch-processing/index.js +1 -1
- package/src/rules/no-unvalidated-event-body/index.js +1 -1
- package/src/rules/no-user-controlled-requests/index.js +1 -1
- package/src/rules/require-timeout-handling/index.js +1 -1
- package/src/utils/lambda-evidence.js +1 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "eslint-plugin-lambda-security",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"description": "ESLint plugin for AWS Lambda security — detects overly permissive IAM policies and CORS, unvalidated event bodies, secrets in env vars, and leaked error details.",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -71,7 +71,7 @@
|
|
|
71
71
|
"node": ">=18.0.0"
|
|
72
72
|
},
|
|
73
73
|
"dependencies": {
|
|
74
|
-
"@interlace/eslint-devkit": "^1.
|
|
74
|
+
"@interlace/eslint-devkit": "^1.12.0"
|
|
75
75
|
},
|
|
76
76
|
"peerDependencies": {
|
|
77
77
|
"eslint": "^8.40.0 || ^9.0.0 || ^10.0.0",
|
package/src/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.configs=exports.plugin=exports.rules=void 0;exports.rules={get"no-hardcoded-credentials-sdk"(){return require("./rules/no-hardcoded-credentials-sdk").noHardcodedCredentialsSdk},get"no-permissive-cors-response"(){return require("./rules/no-permissive-cors-response").noPermissiveCorsResponse},get"no-permissive-cors-middy"(){return require("./rules/no-permissive-cors-middy").noPermissiveCorsMidly},get"no-secrets-in-env"(){return require("./rules/no-secrets-in-env").noSecretsInEnv},get"no-env-logging"(){return require("./rules/no-env-logging").noEnvLogging},get"no-unvalidated-event-body"(){return require("./rules/no-unvalidated-event-body").noUnvalidatedEventBody},get"no-missing-authorization-check"(){return require("./rules/no-missing-authorization-check").noMissingAuthorizationCheck},get"no-overly-permissive-iam-policy"(){return require("./rules/no-overly-permissive-iam-policy").noOverlyPermissiveIamPolicy},get"no-error-swallowing"(){return require("./rules/no-error-swallowing").noErrorSwallowing},get"require-timeout-handling"(){return require("./rules/require-timeout-handling").requireTimeoutHandling},get"no-unbounded-batch-processing"(){return require("./rules/no-unbounded-batch-processing").noUnboundedBatchProcessing},get"no-user-controlled-requests"(){return require("./rules/no-user-controlled-requests").noUserControlledRequests},get"no-exposed-error-details"(){return require("./rules/no-exposed-error-details").noExposedErrorDetails},get"no-exposed-debug-endpoints"(){return require("./rules/no-exposed-debug-endpoints").noExposedDebugEndpoints}};exports.plugin={meta:{name:"eslint-plugin-lambda-security",version:"
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.configs=exports.plugin=exports.rules=void 0;exports.rules={get"no-hardcoded-credentials-sdk"(){return require("./rules/no-hardcoded-credentials-sdk").noHardcodedCredentialsSdk},get"no-permissive-cors-response"(){return require("./rules/no-permissive-cors-response").noPermissiveCorsResponse},get"no-permissive-cors-middy"(){return require("./rules/no-permissive-cors-middy").noPermissiveCorsMidly},get"no-secrets-in-env"(){return require("./rules/no-secrets-in-env").noSecretsInEnv},get"no-env-logging"(){return require("./rules/no-env-logging").noEnvLogging},get"no-unvalidated-event-body"(){return require("./rules/no-unvalidated-event-body").noUnvalidatedEventBody},get"no-missing-authorization-check"(){return require("./rules/no-missing-authorization-check").noMissingAuthorizationCheck},get"no-overly-permissive-iam-policy"(){return require("./rules/no-overly-permissive-iam-policy").noOverlyPermissiveIamPolicy},get"no-error-swallowing"(){return require("./rules/no-error-swallowing").noErrorSwallowing},get"require-timeout-handling"(){return require("./rules/require-timeout-handling").requireTimeoutHandling},get"no-unbounded-batch-processing"(){return require("./rules/no-unbounded-batch-processing").noUnboundedBatchProcessing},get"no-user-controlled-requests"(){return require("./rules/no-user-controlled-requests").noUserControlledRequests},get"no-exposed-error-details"(){return require("./rules/no-exposed-error-details").noExposedErrorDetails},get"no-exposed-debug-endpoints"(){return require("./rules/no-exposed-debug-endpoints").noExposedDebugEndpoints}};exports.plugin={meta:{name:"eslint-plugin-lambda-security",version:"2.0.0"},rules:exports.rules};exports.configs={recommended:{plugins:{"lambda-security":exports.plugin},rules:{"lambda-security/no-hardcoded-credentials-sdk":"error","lambda-security/no-permissive-cors-response":"error","lambda-security/no-permissive-cors-middy":"error","lambda-security/no-secrets-in-env":"error","lambda-security/no-user-controlled-requests":"error","lambda-security/no-overly-permissive-iam-policy":"error","lambda-security/no-unvalidated-event-body":"warn","lambda-security/no-missing-authorization-check":"warn","lambda-security/no-exposed-error-details":"warn","lambda-security/no-exposed-debug-endpoints":"error","lambda-security/no-env-logging":"warn","lambda-security/no-error-swallowing":"warn","lambda-security/require-timeout-handling":"warn","lambda-security/no-unbounded-batch-processing":"warn"}},strict:{plugins:{"lambda-security":exports.plugin},rules:{"lambda-security/no-hardcoded-credentials-sdk":"error","lambda-security/no-permissive-cors-response":"error","lambda-security/no-permissive-cors-middy":"error","lambda-security/no-secrets-in-env":"error","lambda-security/no-env-logging":"error","lambda-security/no-unvalidated-event-body":"error","lambda-security/no-missing-authorization-check":"error","lambda-security/no-overly-permissive-iam-policy":"error","lambda-security/no-error-swallowing":"error","lambda-security/require-timeout-handling":"error","lambda-security/no-unbounded-batch-processing":"error","lambda-security/no-user-controlled-requests":"error","lambda-security/no-exposed-error-details":"error","lambda-security/no-exposed-debug-endpoints":"error"}}};exports.default=exports.plugin;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noEnvLogging=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const LOGGING_FUNCTIONS=new Set(["log","info","warn","error","debug","trace"]);exports.noEnvLogging=(0,eslint_devkit_1.createRule)({name:"no-env-logging",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-lambda-security/docs/rules/no-env-logging.md",description:"Detects logging of process.env which may expose secrets",cwe:"CWE-532",cvss:5.3},hasSuggestions:true,messages:{envLogging:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Environment Variable Logging",cwe:"CWE-532",description:"Logging process.env may expose secrets (API keys, passwords, tokens)",severity:"HIGH",fix:"Remove process.env from log statements or log specific non-sensitive values",documentationLink:"https://cwe.mitre.org/data/definitions/532.html"}),removeEnvLogging:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Remove Env Logging",description:"Remove environment variable logging",severity:"LOW",fix:'Log specific values instead: console.log("Region:", process.env.AWS_REGION)',documentationLink:"https://cwe.mitre.org/data/definitions/532.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true}},additionalProperties:false}]},defaultOptions:[{allowInTests:true}],create(context,[options={}]){const{allowInTests=true}=options;const filename=context.filename;const isTestFile=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}const sourceCode=context.sourceCode;function isProcessEnv(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.object.name==="process"&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.property.name==="env"){return true}return false}function containsProcessEnv(node){const text=sourceCode.getText(node);return text.includes("process.env")}function isLoggingCall(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const obj=node.callee.object;const prop=node.callee.property;if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const methodName=prop.name;if(!LOGGING_FUNCTIONS.has(methodName))return false;if(obj.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&obj.name==="console"){return true}if(obj.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&/log(ger)?/i.test(obj.name)){return true}}return false}return{CallExpression(node){if(!isLoggingCall(node))return;for(const arg of node.arguments){if(isProcessEnv(arg)){context.report({node:arg,messageId:"envLogging",suggest:[{messageId:"removeEnvLogging",fix:()=>null}]})}else if(containsProcessEnv(arg)){const text=sourceCode.getText(arg);if(/process\.env\s*[,)\]]/.test(text)||/JSON\.stringify\s*\(\s*process\.env\s*\)/.test(text)){context.report({node:arg,messageId:"envLogging",suggest:[{messageId:"removeEnvLogging",fix:()=>null}]})}}}}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noEnvLogging=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const lambda_evidence_1=require("../../utils/lambda-evidence");const LOGGING_FUNCTIONS=new Set(["log","info","warn","error","debug","trace"]);exports.noEnvLogging=(0,eslint_devkit_1.createRule)({name:"no-env-logging",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-lambda-security/docs/rules/no-env-logging.md",description:"Detects logging of process.env which may expose secrets",cwe:"CWE-532",cvss:5.3},hasSuggestions:true,messages:{envLogging:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Environment Variable Logging",cwe:"CWE-532",description:"Logging process.env may expose secrets (API keys, passwords, tokens)",severity:"HIGH",fix:"Remove process.env from log statements or log specific non-sensitive values",documentationLink:"https://cwe.mitre.org/data/definitions/532.html"}),removeEnvLogging:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Remove Env Logging",description:"Remove environment variable logging",severity:"LOW",fix:'Log specific values instead: console.log("Region:", process.env.AWS_REGION)',documentationLink:"https://cwe.mitre.org/data/definitions/532.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true}},additionalProperties:false}]},defaultOptions:[{allowInTests:true}],create(context,[options={}]){if(!(0,lambda_evidence_1.fileIsLambda)(context.sourceCode.ast))return{};const{allowInTests=true}=options;const filename=context.filename;const isTestFile=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}const sourceCode=context.sourceCode;function isProcessEnv(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.object.name==="process"&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.property.name==="env"){return true}return false}function containsProcessEnv(node){const text=sourceCode.getText(node);return text.includes("process.env")}function isLoggingCall(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const obj=node.callee.object;const prop=node.callee.property;if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const methodName=prop.name;if(!LOGGING_FUNCTIONS.has(methodName))return false;if(obj.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&obj.name==="console"){return true}if(obj.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&/log(ger)?/i.test(obj.name)){return true}}return false}return{CallExpression(node){if(!isLoggingCall(node))return;for(const arg of node.arguments){if(isProcessEnv(arg)){context.report({node:arg,messageId:"envLogging",suggest:[{messageId:"removeEnvLogging",fix:()=>null}]})}else if(containsProcessEnv(arg)){const text=sourceCode.getText(arg);if(/process\.env\s*[,)\]]/.test(text)||/JSON\.stringify\s*\(\s*process\.env\s*\)/.test(text)){context.report({node:arg,messageId:"envLogging",suggest:[{messageId:"removeEnvLogging",fix:()=>null}]})}}}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noErrorSwallowing=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.noErrorSwallowing=(0,eslint_devkit_1.createRule)({name:"no-error-swallowing",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-lambda-security/docs/rules/no-error-swallowing.md",description:"Detects empty catch blocks and missing error logging in Lambda handlers",cwe:"CWE-390",cvss:5},hasSuggestions:true,messages:{emptyCatchBlock:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.WARNING,issueName:"Error Swallowing",cwe:"CWE-390",cvss:5,description:"Catch block swallows error without logging. Security incidents may go undetected.",severity:"MEDIUM",fix:'Log the error with context: console.error("Operation failed", { error, awsRequestId: context.awsRequestId })',documentationLink:"https://cwe.mitre.org/data/definitions/390.html"}),addErrorLogging:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Add Error Logging",description:"Log errors with context for security monitoring",severity:"LOW",fix:'console.error("Error:", error); // or use structured logger',documentationLink:"https://docs.aws.amazon.com/lambda/latest/dg/nodejs-logging.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true},allowWithComment:{type:"boolean",default:true,description:"Allow an empty catch block that carries an explanatory comment"}},additionalProperties:false}]},defaultOptions:[{allowInTests:true,allowWithComment:true}],create(context,[options={}]){const{allowInTests=true,allowWithComment=true}=options;const filename=context.filename;const isTestFile=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}const LOGGER_OBJECTS=/^(console|logger|log|winston|pino|bunyan|sentry|Sentry)$/;const LOGGER_METHODS=/^(log|error|warn|info|debug|captureException|captureMessage)$/;const LOGGING_FUNCTIONS=/^(log|report|capture|track|record|notify)\w*$/i;const FORWARDING_CALLBACKS=/^(next|reject|callback|cb|done|fail|emit)$/;const RESPONSE_OBJECTS=/^(res|response|reply|ctx)$/;const RESPONSE_METHODS=/^(status|sendStatus|json|send|end|writeHead|render|redirect)$/;function mentions(nodes,name){const stack=[...nodes];while(stack.length>0){const node=stack.pop();if(!node||typeof node.type!=="string")continue;if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.name===name)return true;for(const key of Object.keys(node)){if(key==="parent")continue;const value=node[key];if(Array.isArray(value))stack.push(...value);else if(value&&typeof value==="object")stack.push(value)}}return false}function rootName(node){let current=node;while(current.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression)current=current.object;return current.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?current.name:void 0}function memberNames(node){const names=[];let current=node;while(current.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){if(current.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){names.unshift(current.property.name)}current=current.object}return names}function classifyCall(call,caughtName){const callee=call.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(FORWARDING_CALLBACKS.test(callee.name)){return caughtName!==void 0&&mentions(call.arguments,caughtName)?"forward":void 0}if(LOGGING_FUNCTIONS.test(callee.name))return"log";return void 0}if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return void 0;const names=memberNames(callee);const method=names.at(-1)??"";if(names.length>1&&LOGGER_OBJECTS.test(names.at(-2)??"")&&LOGGER_METHODS.test(method)){return"log"}const root=rootName(callee);if(root===void 0)return void 0;if(LOGGER_OBJECTS.test(root)&&LOGGER_METHODS.test(method))return"log";if(RESPONSE_OBJECTS.test(root)&&names.some(n=>RESPONSE_METHODS.test(n))){return"respond"}return void 0}function analyze(block,caughtName){const result={logs:false,forwards:false,responds:false};const seen=new Set;const visit=node=>{if(!node||typeof node.type!=="string"||seen.has(node))return;seen.add(node);if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const kind=classifyCall(node,caughtName);if(kind==="log")result.logs=true;else if(kind==="forward")result.forwards=true;else if(kind==="respond")result.responds=true}for(const key of Object.keys(node)){if(key==="parent")continue;const value=node[key];if(Array.isArray(value)){for(const item of value)visit(item)}else if(value&&typeof value==="object"){visit(value)}}};visit(block);return result}function hasIntentionalComment(node){if(!allowWithComment)return false;const sourceCode=context.sourceCode;const comments=sourceCode.getCommentsInside(node.body);return comments.some(comment=>/intentional|expected|ignore|suppress|handled|silent/i.test(comment.value))}function hasThrow(block){return block.body.some(stmt=>stmt.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement)}function returnsFallback(block){return block.body.some(stmt=>{if(stmt.type!==eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)return false;const value=stmt.argument;if(value===null)return false;if(value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&value.value===null)return false;if(value.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&value.name==="undefined"){return false}if(value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&value.value===true)return false;if(value.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){const status=value.properties.find(p=>p.type===eslint_devkit_1.AST_NODE_TYPES.Property&&p.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&/^(statusCode|status|ok|allowed|authorized)$/.test(p.key.name));if(status){const literal=status.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal?status.value.value:void 0;if(literal===true)return false;const code=Number(literal);if(code>=200&&code<300)return false}}return true})}return{CatchClause(node){const body=node.body;if(body.body.length===0){if(!hasIntentionalComment(node)){context.report({node,messageId:"emptyCatchBlock",suggest:[{messageId:"addErrorLogging",fix:fixer=>{const errorParam=node.param?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?node.param.name:"error";return fixer.replaceText(body,`{ console.error('Error:', ${errorParam}); }`)}}]})}return}if(hasThrow(body)){return}const caughtName=node.param?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?node.param.name:void 0;const{logs,forwards,responds}=analyze(body,caughtName);if(logs||forwards||responds||returnsFallback(body)){return}if(!hasIntentionalComment(node)){context.report({node,messageId:"emptyCatchBlock"})}}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noErrorSwallowing=void 0;const lambda_evidence_1=require("../../utils/lambda-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");exports.noErrorSwallowing=(0,eslint_devkit_1.createRule)({name:"no-error-swallowing",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-lambda-security/docs/rules/no-error-swallowing.md",description:"Detects empty catch blocks and missing error logging in Lambda handlers",cwe:"CWE-390",cvss:5},hasSuggestions:true,messages:{emptyCatchBlock:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.WARNING,issueName:"Error Swallowing",cwe:"CWE-390",cvss:5,description:"Catch block swallows error without logging. Security incidents may go undetected.",severity:"MEDIUM",fix:'Log the error with context: console.error("Operation failed", { error, awsRequestId: context.awsRequestId })',documentationLink:"https://cwe.mitre.org/data/definitions/390.html"}),addErrorLogging:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Add Error Logging",description:"Log errors with context for security monitoring",severity:"LOW",fix:'console.error("Error:", error); // or use structured logger',documentationLink:"https://docs.aws.amazon.com/lambda/latest/dg/nodejs-logging.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true},allowWithComment:{type:"boolean",default:true,description:"Allow an empty catch block that carries an explanatory comment"}},additionalProperties:false}]},defaultOptions:[{allowInTests:true,allowWithComment:true}],create(context,[options={}]){if(!(0,lambda_evidence_1.fileIsLambda)(context.sourceCode.ast))return{};const{allowInTests=true,allowWithComment=true}=options;const filename=context.filename;const isTestFile=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}const LOGGER_OBJECTS=/^(console|logger|log|winston|pino|bunyan|sentry|Sentry)$/;const LOGGER_METHODS=/^(log|error|warn|info|debug|captureException|captureMessage)$/;const LOGGING_FUNCTIONS=/^(log|report|capture|track|record|notify)\w*$/i;const FORWARDING_CALLBACKS=/^(next|reject|callback|cb|done|fail|emit)$/;const RESPONSE_OBJECTS=/^(res|response|reply|ctx)$/;const RESPONSE_METHODS=/^(status|sendStatus|json|send|end|writeHead|render|redirect)$/;function mentions(nodes,name){const stack=[...nodes];while(stack.length>0){const node=stack.pop();if(!node||typeof node.type!=="string")continue;if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.name===name)return true;for(const key of Object.keys(node)){if(key==="parent")continue;const value=node[key];if(Array.isArray(value))stack.push(...value);else if(value&&typeof value==="object")stack.push(value)}}return false}function rootName(node){let current=node;while(current.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression)current=current.object;return current.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?current.name:void 0}function memberNames(node){const names=[];let current=node;while(current.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){if(current.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){names.unshift(current.property.name)}current=current.object}return names}function classifyCall(call,caughtName){const callee=call.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(FORWARDING_CALLBACKS.test(callee.name)){return caughtName!==void 0&&mentions(call.arguments,caughtName)?"forward":void 0}if(LOGGING_FUNCTIONS.test(callee.name))return"log";return void 0}if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return void 0;const names=memberNames(callee);const method=names.at(-1)??"";if(names.length>1&&LOGGER_OBJECTS.test(names.at(-2)??"")&&LOGGER_METHODS.test(method)){return"log"}const root=rootName(callee);if(root===void 0)return void 0;if(LOGGER_OBJECTS.test(root)&&LOGGER_METHODS.test(method))return"log";if(RESPONSE_OBJECTS.test(root)&&names.some(n=>RESPONSE_METHODS.test(n))){return"respond"}return void 0}function analyze(block,caughtName){const result={logs:false,forwards:false,responds:false};const seen=new Set;const visit=node=>{if(!node||typeof node.type!=="string"||seen.has(node))return;seen.add(node);if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const kind=classifyCall(node,caughtName);if(kind==="log")result.logs=true;else if(kind==="forward")result.forwards=true;else if(kind==="respond")result.responds=true}for(const key of Object.keys(node)){if(key==="parent")continue;const value=node[key];if(Array.isArray(value)){for(const item of value)visit(item)}else if(value&&typeof value==="object"){visit(value)}}};visit(block);return result}function hasIntentionalComment(node){if(!allowWithComment)return false;const sourceCode=context.sourceCode;const comments=sourceCode.getCommentsInside(node.body);return comments.some(comment=>/intentional|expected|ignore|suppress|handled|silent/i.test(comment.value))}function hasThrow(block){return block.body.some(stmt=>stmt.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement)}function returnsFallback(block){return block.body.some(stmt=>{if(stmt.type!==eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)return false;const value=stmt.argument;if(value===null)return false;if(value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&value.value===null)return false;if(value.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&value.name==="undefined"){return false}if(value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&value.value===true)return false;if(value.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){const status=value.properties.find(p=>p.type===eslint_devkit_1.AST_NODE_TYPES.Property&&p.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&/^(statusCode|status|ok|allowed|authorized)$/.test(p.key.name));if(status){const literal=status.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal?status.value.value:void 0;if(literal===true)return false;const code=Number(literal);if(code>=200&&code<300)return false}}return true})}return{CatchClause(node){const body=node.body;if(body.body.length===0){if(!hasIntentionalComment(node)){context.report({node,messageId:"emptyCatchBlock",suggest:[{messageId:"addErrorLogging",fix:fixer=>{const errorParam=node.param?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?node.param.name:"error";return fixer.replaceText(body,`{ console.error('Error:', ${errorParam}); }`)}}]})}return}if(hasThrow(body)){return}const caughtName=node.param?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?node.param.name:void 0;const{logs,forwards,responds}=analyze(body,caughtName);if(logs||forwards||responds||returnsFallback(body)){return}if(!hasIntentionalComment(node)){context.report({node,messageId:"emptyCatchBlock"})}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noExposedDebugEndpoints=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_DEBUG_PATHS=["/debug","/__debug__","/admin","/_admin","/test","/health"];exports.noExposedDebugEndpoints=(0,eslint_devkit_1.createRule)({name:"no-exposed-debug-endpoints",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-lambda-security/docs/rules/no-exposed-debug-endpoints.md",description:"Detect debug endpoints without auth in AWS Lambda handlers",cwe:"CWE-489",cvss:7.5},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Exposed Debug Endpoint",cwe:"CWE-489",description:"Debug endpoint exposed without authentication",severity:"HIGH",fix:"Remove debug endpoints from production or add authentication",documentationLink:"https://cwe.mitre.org/data/definitions/489.html"})},schema:[{type:"object",properties:{endpoints:{type:"array",items:{type:"string"},description:"Custom list of debug/admin endpoints to flag"},ignoreFiles:{type:"array",items:{type:"string"},description:"List of files or patterns to ignore"}},additionalProperties:false}]},defaultOptions:[{}],create(context){const options=context.options[0]||{};const debugPaths=options.endpoints||DEFAULT_DEBUG_PATHS;const ignoreFiles=options.ignoreFiles||[];const filename=context.filename;if(ignoreFiles.some(pattern=>filename.includes(pattern))){return{}}function report(node){context.report({node,messageId:"violationDetected"})}return{Property(node){if(node.key.type==="Identifier"&&node.key.name==="path"&&node.value.type==="Literal"&&typeof node.value.value==="string"){const path=node.value.value.toLowerCase();if(debugPaths.some(dp=>path.includes(dp.toLowerCase()))){let parent=node.parent;while(parent){if(parent.type==="Property"&&parent.key.type==="Identifier"&&["http","httpApi"].includes(parent.key.name)){report(node.value);return}parent=parent.parent}}}},BinaryExpression(node){if(node.operator==="==="||node.operator==="=="||node.operator==="!=="||node.operator==="!="){const checkNode=side=>{if(side.type==="Literal"&&typeof side.value==="string"){const val=side.value.toLowerCase();if(debugPaths.some(dp=>val.includes(dp.toLowerCase()))){const other=side===node.left?node.right:node.left;if(other.type==="MemberExpression"&&other.object.type==="Identifier"&&(other.object.name==="event"||other.object.name==="evt")&&other.property.type==="Identifier"&&["path","rawPath","resource","routeKey"].includes(other.property.name)){report(side)}}}};checkNode(node.left);checkNode(node.right)}},Literal(node){if(typeof node.value==="string"){const path=node.value.toLowerCase();if(debugPaths.some(dp=>path===dp.toLowerCase())){const parent=node.parent;if(parent&&parent.type==="BinaryExpression"&&(parent.left===node||parent.right===node)){const other=parent.left===node?parent.right:parent.left;if(other.type==="MemberExpression"&&other.object.type==="Identifier"&&(other.object.name==="event"||other.object.name==="evt")){return}}if(parent&&parent.type==="Property"&&parent.key.type==="Identifier"&&parent.key.name==="path"){return}report(node)}}}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noExposedDebugEndpoints=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const lambda_evidence_1=require("../../utils/lambda-evidence");const DEFAULT_DEBUG_PATHS=["/debug","/__debug__","/admin","/_admin","/test","/health"];exports.noExposedDebugEndpoints=(0,eslint_devkit_1.createRule)({name:"no-exposed-debug-endpoints",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-lambda-security/docs/rules/no-exposed-debug-endpoints.md",description:"Detect debug endpoints without auth in AWS Lambda handlers",cwe:"CWE-489",cvss:7.5},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Exposed Debug Endpoint",cwe:"CWE-489",description:"Debug endpoint exposed without authentication",severity:"HIGH",fix:"Remove debug endpoints from production or add authentication",documentationLink:"https://cwe.mitre.org/data/definitions/489.html"})},schema:[{type:"object",properties:{endpoints:{type:"array",items:{type:"string"},description:"Custom list of debug/admin endpoints to flag"},ignoreFiles:{type:"array",items:{type:"string"},description:"List of files or patterns to ignore"}},additionalProperties:false}]},defaultOptions:[{}],create(context){if(!(0,lambda_evidence_1.fileIsLambda)(context.sourceCode.ast))return{};const options=context.options[0]||{};const debugPaths=options.endpoints||DEFAULT_DEBUG_PATHS;const ignoreFiles=options.ignoreFiles||[];const filename=context.filename;if(ignoreFiles.some(pattern=>filename.includes(pattern))){return{}}function report(node){context.report({node,messageId:"violationDetected"})}return{Property(node){if(node.key.type==="Identifier"&&node.key.name==="path"&&node.value.type==="Literal"&&typeof node.value.value==="string"){const path=node.value.value.toLowerCase();if(debugPaths.some(dp=>path.includes(dp.toLowerCase()))){let parent=node.parent;while(parent){if(parent.type==="Property"&&parent.key.type==="Identifier"&&["http","httpApi"].includes(parent.key.name)){report(node.value);return}parent=parent.parent}}}},BinaryExpression(node){if(node.operator==="==="||node.operator==="=="||node.operator==="!=="||node.operator==="!="){const checkNode=side=>{if(side.type==="Literal"&&typeof side.value==="string"){const val=side.value.toLowerCase();if(debugPaths.some(dp=>val.includes(dp.toLowerCase()))){const other=side===node.left?node.right:node.left;if(other.type==="MemberExpression"&&other.object.type==="Identifier"&&(other.object.name==="event"||other.object.name==="evt")&&other.property.type==="Identifier"&&["path","rawPath","resource","routeKey"].includes(other.property.name)){report(side)}}}};checkNode(node.left);checkNode(node.right)}},Literal(node){if(typeof node.value==="string"){const path=node.value.toLowerCase();if(debugPaths.some(dp=>path===dp.toLowerCase())){const parent=node.parent;if(parent&&parent.type==="BinaryExpression"&&(parent.left===node||parent.right===node)){const other=parent.left===node?parent.right:parent.left;if(other.type==="MemberExpression"&&other.object.type==="Identifier"&&(other.object.name==="event"||other.object.name==="evt")){return}}if(parent&&parent.type==="Property"&&parent.key.type==="Identifier"&&parent.key.name==="path"){return}report(node)}}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noExposedErrorDetails=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const SENSITIVE_ERROR_PROPERTIES=new Set(["stack","stackTrace","trace","cause","__dirname","__filename","path","hostname","config","env"]);exports.noExposedErrorDetails=(0,eslint_devkit_1.createRule)({name:"no-exposed-error-details",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-lambda-security/docs/rules/no-exposed-error-details.md",description:"Detects Lambda handlers exposing internal error details in responses",cwe:"CWE-209",cvss:4.3},hasSuggestions:true,messages:{exposedErrorDetails:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Exposed Error Details",cwe:"CWE-209",cvss:4.3,description:"Response exposes {{property}} which may leak internal paths, configs, or stack traces.",severity:"MEDIUM",fix:"Return generic error message. Log detailed errors server-side: console.error(error)",documentationLink:"https://cwe.mitre.org/data/definitions/209.html"}),sanitizeError:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Sanitize Error Response",description:"Return a generic error message without internal details",severity:"LOW",fix:'return { statusCode: 500, body: JSON.stringify({ message: "Internal server error" }) }',documentationLink:"https://owasp.org/www-community/Improper_Error_Handling"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true}},additionalProperties:false}]},defaultOptions:[{allowInTests:true}],create(context,[options={}]){const{allowInTests=true}=options;const filename=context.filename;const isTestFile=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}let insideApiResponse=false;function isApiResponse(node){return node.properties.some(prop=>prop.type===eslint_devkit_1.AST_NODE_TYPES.Property&&prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&["statusCode","body","headers"].includes(prop.key.name))}function getSensitiveProperty(node){if(node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(SENSITIVE_ERROR_PROPERTIES.has(node.property.name)){return node.property.name}}return null}return{ReturnStatement(node){if(node.argument?.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression&&isApiResponse(node.argument)){insideApiResponse=true}},"ReturnStatement:exit"(){insideApiResponse=false},MemberExpression(node){if(!insideApiResponse)return;const sensitiveProperty=getSensitiveProperty(node);if(sensitiveProperty){const parent=node.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.Property||parent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){context.report({node,messageId:"exposedErrorDetails",data:{property:sensitiveProperty},suggest:[{messageId:"sanitizeError",fix:()=>null}]})}}},CallExpression(node){if(!insideApiResponse)return;if(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"&&node.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.property.name==="stringify"){const arg=node.arguments[0];if(arg?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(/error|err|e|exception/i.test(arg.name)){context.report({node,messageId:"exposedErrorDetails",data:{property:"error object"},suggest:[{messageId:"sanitizeError",fix:()=>null}]})}}}}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noExposedErrorDetails=void 0;const lambda_evidence_1=require("../../utils/lambda-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");const SENSITIVE_ERROR_PROPERTIES=new Set(["stack","stackTrace","trace","cause","__dirname","__filename","path","hostname","config","env"]);exports.noExposedErrorDetails=(0,eslint_devkit_1.createRule)({name:"no-exposed-error-details",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-lambda-security/docs/rules/no-exposed-error-details.md",description:"Detects Lambda handlers exposing internal error details in responses",cwe:"CWE-209",cvss:4.3},hasSuggestions:true,messages:{exposedErrorDetails:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Exposed Error Details",cwe:"CWE-209",cvss:4.3,description:"Response exposes {{property}} which may leak internal paths, configs, or stack traces.",severity:"MEDIUM",fix:"Return generic error message. Log detailed errors server-side: console.error(error)",documentationLink:"https://cwe.mitre.org/data/definitions/209.html"}),sanitizeError:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Sanitize Error Response",description:"Return a generic error message without internal details",severity:"LOW",fix:'return { statusCode: 500, body: JSON.stringify({ message: "Internal server error" }) }',documentationLink:"https://owasp.org/www-community/Improper_Error_Handling"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true}},additionalProperties:false}]},defaultOptions:[{allowInTests:true}],create(context,[options={}]){if(!(0,lambda_evidence_1.fileIsLambda)(context.sourceCode.ast))return{};const{allowInTests=true}=options;const filename=context.filename;const isTestFile=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}let insideApiResponse=false;function isApiResponse(node){return node.properties.some(prop=>prop.type===eslint_devkit_1.AST_NODE_TYPES.Property&&prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&["statusCode","body","headers"].includes(prop.key.name))}function getSensitiveProperty(node){if(node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(SENSITIVE_ERROR_PROPERTIES.has(node.property.name)){return node.property.name}}return null}return{ReturnStatement(node){if(node.argument?.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression&&isApiResponse(node.argument)){insideApiResponse=true}},"ReturnStatement:exit"(){insideApiResponse=false},MemberExpression(node){if(!insideApiResponse)return;const sensitiveProperty=getSensitiveProperty(node);if(sensitiveProperty){const parent=node.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.Property||parent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){context.report({node,messageId:"exposedErrorDetails",data:{property:sensitiveProperty},suggest:[{messageId:"sanitizeError",fix:()=>null}]})}}},CallExpression(node){if(!insideApiResponse)return;if(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"&&node.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.property.name==="stringify"){const arg=node.arguments[0];if(arg?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(/error|err|e|exception/i.test(arg.name)){context.report({node,messageId:"exposedErrorDetails",data:{property:"error object"},suggest:[{messageId:"sanitizeError",fix:()=>null}]})}}}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noHardcodedCredentialsSdk=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const AWS_ACCESS_KEY_PATTERNS=[/^AKIA[0-9A-Z]{16}$/,/^ASIA[0-9A-Z]{16}$/,/^AIDA[0-9A-Z]{16}$/];const CREDENTIAL_PROPERTY_NAMES=["accessKeyId","secretAccessKey","sessionToken","awsAccessKeyId","awsSecretAccessKey"];const AWS_SDK_V3_CLIENTS=new Set(["S3Client","DynamoDBClient","LambdaClient","SQSClient","SNSClient","SecretsManagerClient","KMSClient","STSClient","IAMClient","EC2Client","ECSClient","CloudWatchClient","CloudWatchLogsClient","APIGatewayClient","CognitoIdentityClient","CognitoIdentityProviderClient","EventBridgeClient","StepFunctionsClient","RDSClient","ElastiCacheClient"]);exports.noHardcodedCredentialsSdk=(0,eslint_devkit_1.createRule)({name:"no-hardcoded-credentials-sdk",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-lambda-security/docs/rules/no-hardcoded-credentials-sdk.md",description:"Detects hardcoded AWS credentials in SDK client configurations",cwe:"CWE-798",cvss:9.8},hasSuggestions:true,messages:{hardcodedCredentials:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Hardcoded AWS Credentials",cwe:"CWE-798",description:"Hardcoded AWS credentials detected in {{clientName}} config: {{property}}",severity:"CRITICAL",fix:"Use credential provider chain: new {{clientName}}({ credentials: fromNodeProviderChain() })",documentationLink:"https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html"}),useCredentialProvider:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Credential Provider",description:"Use AWS credential provider chain instead of hardcoded credentials",severity:"LOW",fix:'import { fromNodeProviderChain } from "@aws-sdk/credential-providers"',documentationLink:"https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true,description:"Allow hardcoded credentials in test files"}},additionalProperties:false}]},defaultOptions:[{allowInTests:true}],create(context,[options={}]){const{allowInTests=true}=options;const filename=context.filename;const isTestFile=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}function looksLikeAwsAccessKey(value){return AWS_ACCESS_KEY_PATTERNS.some(pattern=>pattern.test(value))}function isCredentialProperty(name){return CREDENTIAL_PROPERTY_NAMES.some(credProp=>name.toLowerCase()===credProp.toLowerCase())}function getAwsClientName(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const name=node.callee.name;if(AWS_SDK_V3_CLIENTS.has(name)){return name}if(name.endsWith("Client")&&/^(S3|DynamoDB|Lambda|SQS|SNS|Secrets|KMS|STS|IAM|EC2|ECS|CloudWatch|APIGateway|Cognito|EventBridge|StepFunctions|RDS|ElastiCache|SSM|Athena|Glue|Kinesis|Firehose|Rekognition|Textract|Comprehend|Polly|Lex|Bedrock|My|Custom|AWS)/i.test(name)){return name}}return null}function checkCredentialsObject(obj,clientName){for(const prop of obj.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&prop.key.name==="credentials"&&prop.value.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){checkCredentialsInner(prop.value,clientName)}if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&isCredentialProperty(prop.key.name)){if(prop.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof prop.value.value==="string"){reportHardcodedCredential(prop,clientName,prop.key.name)}}}}function checkCredentialsInner(obj,clientName){for(const prop of obj.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&isCredentialProperty(prop.key.name)){if(prop.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof prop.value.value==="string"){const value=prop.value.value;const keyName=prop.key.name.toLowerCase();if(keyName==="accesskeyid"){if(looksLikeAwsAccessKey(value)){reportHardcodedCredential(prop,clientName,prop.key.name)}}else if(keyName==="secretaccesskey"){if(value.length>=20){reportHardcodedCredential(prop,clientName,prop.key.name)}}else if(keyName==="sessiontoken"){if(value.length>=15){reportHardcodedCredential(prop,clientName,prop.key.name)}}}else if(prop.value.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){reportHardcodedCredential(prop,clientName,prop.key.name)}}}}function reportHardcodedCredential(node,clientName,propertyName){context.report({node,messageId:"hardcodedCredentials",data:{clientName,property:propertyName},suggest:[{messageId:"useCredentialProvider",fix:()=>null}]})}return{NewExpression(node){const clientName=getAwsClientName(node);if(!clientName)return;if(node.arguments.length>0&&node.arguments[0].type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){checkCredentialsObject(node.arguments[0],clientName)}},VariableDeclarator(node){if(node.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.id.name.toLowerCase().includes("credential")&&node.init?.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){checkCredentialsInner(node.init,"AWSClient")}}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noHardcodedCredentialsSdk=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const lambda_evidence_1=require("../../utils/lambda-evidence");const AWS_ACCESS_KEY_PATTERNS=[/^AKIA[0-9A-Z]{16}$/,/^ASIA[0-9A-Z]{16}$/,/^AIDA[0-9A-Z]{16}$/];const CREDENTIAL_PROPERTY_NAMES=["accessKeyId","secretAccessKey","sessionToken","awsAccessKeyId","awsSecretAccessKey"];const AWS_SDK_V3_CLIENTS=new Set(["S3Client","DynamoDBClient","LambdaClient","SQSClient","SNSClient","SecretsManagerClient","KMSClient","STSClient","IAMClient","EC2Client","ECSClient","CloudWatchClient","CloudWatchLogsClient","APIGatewayClient","CognitoIdentityClient","CognitoIdentityProviderClient","EventBridgeClient","StepFunctionsClient","RDSClient","ElastiCacheClient"]);exports.noHardcodedCredentialsSdk=(0,eslint_devkit_1.createRule)({name:"no-hardcoded-credentials-sdk",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-lambda-security/docs/rules/no-hardcoded-credentials-sdk.md",description:"Detects hardcoded AWS credentials in SDK client configurations",cwe:"CWE-798",cvss:9.8},hasSuggestions:true,messages:{hardcodedCredentials:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Hardcoded AWS Credentials",cwe:"CWE-798",description:"Hardcoded AWS credentials detected in {{clientName}} config: {{property}}",severity:"CRITICAL",fix:"Use credential provider chain: new {{clientName}}({ credentials: fromNodeProviderChain() })",documentationLink:"https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html"}),useCredentialProvider:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Credential Provider",description:"Use AWS credential provider chain instead of hardcoded credentials",severity:"LOW",fix:'import { fromNodeProviderChain } from "@aws-sdk/credential-providers"',documentationLink:"https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true,description:"Allow hardcoded credentials in test files"}},additionalProperties:false}]},defaultOptions:[{allowInTests:true}],create(context,[options={}]){if(!(0,lambda_evidence_1.fileIsLambda)(context.sourceCode.ast))return{};const{allowInTests=true}=options;const filename=context.filename;const isTestFile=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}function looksLikeAwsAccessKey(value){return AWS_ACCESS_KEY_PATTERNS.some(pattern=>pattern.test(value))}function isCredentialProperty(name){return CREDENTIAL_PROPERTY_NAMES.some(credProp=>name.toLowerCase()===credProp.toLowerCase())}function getAwsClientName(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const name=node.callee.name;if(AWS_SDK_V3_CLIENTS.has(name)){return name}if(name.endsWith("Client")&&/^(S3|DynamoDB|Lambda|SQS|SNS|Secrets|KMS|STS|IAM|EC2|ECS|CloudWatch|APIGateway|Cognito|EventBridge|StepFunctions|RDS|ElastiCache|SSM|Athena|Glue|Kinesis|Firehose|Rekognition|Textract|Comprehend|Polly|Lex|Bedrock|My|Custom|AWS)/i.test(name)){return name}}return null}function checkCredentialsObject(obj,clientName){for(const prop of obj.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&prop.key.name==="credentials"&&prop.value.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){checkCredentialsInner(prop.value,clientName)}if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&isCredentialProperty(prop.key.name)){if(prop.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof prop.value.value==="string"){reportHardcodedCredential(prop,clientName,prop.key.name)}}}}function checkCredentialsInner(obj,clientName){for(const prop of obj.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&isCredentialProperty(prop.key.name)){if(prop.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof prop.value.value==="string"){const value=prop.value.value;const keyName=prop.key.name.toLowerCase();if(keyName==="accesskeyid"){if(looksLikeAwsAccessKey(value)){reportHardcodedCredential(prop,clientName,prop.key.name)}}else if(keyName==="secretaccesskey"){if(value.length>=20){reportHardcodedCredential(prop,clientName,prop.key.name)}}else if(keyName==="sessiontoken"){if(value.length>=15){reportHardcodedCredential(prop,clientName,prop.key.name)}}}else if(prop.value.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){reportHardcodedCredential(prop,clientName,prop.key.name)}}}}function reportHardcodedCredential(node,clientName,propertyName){context.report({node,messageId:"hardcodedCredentials",data:{clientName,property:propertyName},suggest:[{messageId:"useCredentialProvider",fix:()=>null}]})}return{NewExpression(node){const clientName=getAwsClientName(node);if(!clientName)return;if(node.arguments.length>0&&node.arguments[0].type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){checkCredentialsObject(node.arguments[0],clientName)}},VariableDeclarator(node){if(node.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.id.name.toLowerCase().includes("credential")&&node.init?.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){checkCredentialsInner(node.init,"AWSClient")}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noMissingAuthorizationCheck=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const AUTHORIZATION_CHECK_PATTERNS=["requestContext.authorizer","requestContext.identity","Authorization","authorization","claims","principalId","isAdmin","isAuthenticated","userId","sub","scope","permissions"];const SENSITIVE_OPERATIONS=new Set(["query","put","delete","update","insert","remove","create","send","invoke","putObject","deleteObject","getObject","putItem","deleteItem","updateItem","getItem"]);const EVENT_PARAM_NAMES=new Set(["event","evt","e","request","req"]);exports.noMissingAuthorizationCheck=(0,eslint_devkit_1.createRule)({name:"no-missing-authorization-check",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-lambda-security/docs/rules/no-missing-authorization-check.md",description:"Detects Lambda handlers without authorization checks",cwe:"CWE-862",cvss:7.5},hasSuggestions:true,messages:{missingAuthCheck:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing Authorization Check",cwe:"CWE-862",cvss:7.5,description:"Lambda handler performs {{operation}} operation without authorization check. Users may access resources without proper permissions.",severity:"HIGH",fix:"Add authorization check: const claims = event.requestContext.authorizer?.claims; if (!claims?.sub) { return { statusCode: 401 } }",documentationLink:"https://cwe.mitre.org/data/definitions/862.html"}),addAuthCheck:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Add Authorization Check",description:"Check event.requestContext.authorizer for API Gateway or implement custom JWT validation",severity:"LOW",fix:"const userId = event.requestContext.authorizer?.claims?.sub; if (!userId) throw new Error('Unauthorized');",documentationLink:"https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-jwt-authorizer.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true,description:"Allow missing auth in test files"},handlerPatterns:{type:"array",items:{type:"string"},description:"Handler file patterns to check"}},additionalProperties:false}]},defaultOptions:[{allowInTests:true,handlerPatterns:[]}],create(context,[options={}]){const{allowInTests=true}=options;const filename=context.filename;const isTestFile=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}let currentFunctionNode=null;let hasAuthCheck=false;let hasEventParameter=false;const sensitiveOperations=[];function enterFunction(node){const hasEvent=node.params.some(param=>param.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&EVENT_PARAM_NAMES.has(param.name));if(hasEvent){currentFunctionNode=node;hasAuthCheck=false;hasEventParameter=true;sensitiveOperations.length=0}}function exitFunction(node){if(currentFunctionNode!==node)return;if(hasEventParameter&&!hasAuthCheck){for(const{node:opNode,operation}of sensitiveOperations){context.report({node:opNode,messageId:"missingAuthCheck",data:{operation},suggest:[{messageId:"addAuthCheck",fix:()=>null}]})}}currentFunctionNode=null;hasEventParameter=false}function isAuthorizationAccess(node){const sourceCode=context.sourceCode;const text=sourceCode.getText(node);return AUTHORIZATION_CHECK_PATTERNS.some(pattern=>text.includes(pattern)||text.toLowerCase().includes(pattern.toLowerCase()))}function getSensitiveOperationName(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const property=node.callee.property;if(property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(SENSITIVE_OPERATIONS.has(property.name)){return property.name}}}return null}return{"ArrowFunctionExpression, FunctionExpression, FunctionDeclaration"(node){enterFunction(node)},"ArrowFunctionExpression:exit"(node){exitFunction(node)},"FunctionExpression:exit"(node){exitFunction(node)},"FunctionDeclaration:exit"(node){exitFunction(node)},MemberExpression(node){if(!currentFunctionNode)return;if(isAuthorizationAccess(node)){hasAuthCheck=true}},CallExpression(node){if(!currentFunctionNode)return;const operation=getSensitiveOperationName(node);if(operation){sensitiveOperations.push({node,operation})}},ReturnStatement(node){if(!currentFunctionNode)return;if(node.argument?.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){for(const prop of node.argument.properties){if(prop.type===eslint_devkit_1.AST_NODE_TYPES.Property&&prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&prop.key.name==="statusCode"&&prop.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&(prop.value.value===401||prop.value.value===403)){hasAuthCheck=true}}}}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noMissingAuthorizationCheck=void 0;const lambda_evidence_1=require("../../utils/lambda-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");const AUTHORIZATION_CHECK_PATTERNS=["requestContext.authorizer","requestContext.identity","Authorization","authorization","claims","principalId","isAdmin","isAuthenticated","userId","sub","scope","permissions"];const SENSITIVE_OPERATIONS=new Set(["query","put","delete","update","insert","remove","create","send","invoke","putObject","deleteObject","getObject","putItem","deleteItem","updateItem","getItem"]);const EVENT_PARAM_NAMES=new Set(["event","evt","e","request","req"]);exports.noMissingAuthorizationCheck=(0,eslint_devkit_1.createRule)({name:"no-missing-authorization-check",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-lambda-security/docs/rules/no-missing-authorization-check.md",description:"Detects Lambda handlers without authorization checks",cwe:"CWE-862",cvss:7.5},hasSuggestions:true,messages:{missingAuthCheck:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing Authorization Check",cwe:"CWE-862",cvss:7.5,description:"Lambda handler performs {{operation}} operation without authorization check. Users may access resources without proper permissions.",severity:"HIGH",fix:"Add authorization check: const claims = event.requestContext.authorizer?.claims; if (!claims?.sub) { return { statusCode: 401 } }",documentationLink:"https://cwe.mitre.org/data/definitions/862.html"}),addAuthCheck:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Add Authorization Check",description:"Check event.requestContext.authorizer for API Gateway or implement custom JWT validation",severity:"LOW",fix:"const userId = event.requestContext.authorizer?.claims?.sub; if (!userId) throw new Error('Unauthorized');",documentationLink:"https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-jwt-authorizer.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true,description:"Allow missing auth in test files"},handlerPatterns:{type:"array",items:{type:"string"},description:"Handler file patterns to check"}},additionalProperties:false}]},defaultOptions:[{allowInTests:true,handlerPatterns:[]}],create(context,[options={}]){if(!(0,lambda_evidence_1.fileIsLambda)(context.sourceCode.ast))return{};const{allowInTests=true}=options;const filename=context.filename;const isTestFile=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}let currentFunctionNode=null;let hasAuthCheck=false;let hasEventParameter=false;const sensitiveOperations=[];function enterFunction(node){const hasEvent=node.params.some(param=>param.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&EVENT_PARAM_NAMES.has(param.name));if(hasEvent){currentFunctionNode=node;hasAuthCheck=false;hasEventParameter=true;sensitiveOperations.length=0}}function exitFunction(node){if(currentFunctionNode!==node)return;if(hasEventParameter&&!hasAuthCheck){for(const{node:opNode,operation}of sensitiveOperations){context.report({node:opNode,messageId:"missingAuthCheck",data:{operation},suggest:[{messageId:"addAuthCheck",fix:()=>null}]})}}currentFunctionNode=null;hasEventParameter=false}function isAuthorizationAccess(node){const sourceCode=context.sourceCode;const text=sourceCode.getText(node);return AUTHORIZATION_CHECK_PATTERNS.some(pattern=>text.includes(pattern)||text.toLowerCase().includes(pattern.toLowerCase()))}function getSensitiveOperationName(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const property=node.callee.property;if(property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(SENSITIVE_OPERATIONS.has(property.name)){return property.name}}}return null}return{"ArrowFunctionExpression, FunctionExpression, FunctionDeclaration"(node){enterFunction(node)},"ArrowFunctionExpression:exit"(node){exitFunction(node)},"FunctionExpression:exit"(node){exitFunction(node)},"FunctionDeclaration:exit"(node){exitFunction(node)},MemberExpression(node){if(!currentFunctionNode)return;if(isAuthorizationAccess(node)){hasAuthCheck=true}},CallExpression(node){if(!currentFunctionNode)return;const operation=getSensitiveOperationName(node);if(operation){sensitiveOperations.push({node,operation})}},ReturnStatement(node){if(!currentFunctionNode)return;if(node.argument?.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){for(const prop of node.argument.properties){if(prop.type===eslint_devkit_1.AST_NODE_TYPES.Property&&prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&prop.key.name==="statusCode"&&prop.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&(prop.value.value===401||prop.value.value===403)){hasAuthCheck=true}}}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noOverlyPermissiveIamPolicy=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const POLICY_PROPERTIES=new Set(["Resource","Action","Principal"]);const DANGEROUS_WILDCARDS=new Set(["*","arn:aws:*","arn:*:*:*:*:*"]);exports.noOverlyPermissiveIamPolicy=(0,eslint_devkit_1.createRule)({name:"no-overly-permissive-iam-policy",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-lambda-security/docs/rules/no-overly-permissive-iam-policy.md",description:"Detects IAM policies with overly broad permissions (wildcards)",cwe:"CWE-732",cvss:6.5},hasSuggestions:true,messages:{permissivePolicy:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Overly Permissive IAM Policy",cwe:"CWE-732",cvss:6.5,description:'IAM policy has wildcard {{property}}: "{{value}}". Violates principle of least privilege.',severity:"HIGH",fix:'Restrict {{property}} to specific resources/actions. Example: "arn:aws:s3:::my-bucket/*" instead of "*"',documentationLink:"https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege"}),useLeastPrivilege:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Apply Least Privilege",description:"Restrict permissions to specific resources and actions",severity:"LOW",fix:'Replace "*" with specific ARNs and action names',documentationLink:"https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true}},additionalProperties:false}]},defaultOptions:[{allowInTests:true}],create(context,[options={}]){const{allowInTests=true}=options;const filename=context.filename;const isTestFile=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}function isDangerousWildcard(value){return DANGEROUS_WILDCARDS.has(value)||value.endsWith("*")&&value.includes(":*:")}function checkPolicyProperty(node,propertyName){const value=node.value;if(value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof value.value==="string"){if(isDangerousWildcard(value.value)){context.report({node,messageId:"permissivePolicy",data:{property:propertyName,value:value.value},suggest:[{messageId:"useLeastPrivilege",fix:()=>null}]})}}if(value.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){for(const element of value.elements){if(element?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof element.value==="string"){if(isDangerousWildcard(element.value)){context.report({node:element,messageId:"permissivePolicy",data:{property:propertyName,value:element.value},suggest:[{messageId:"useLeastPrivilege",fix:()=>null}]})}}}}}return{Property(node){if(node.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const keyName=node.key.name;if(POLICY_PROPERTIES.has(keyName)){checkPolicyProperty(node,keyName)}}if(node.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.key.value==="string"){const keyName=node.key.value;if(POLICY_PROPERTIES.has(keyName)){checkPolicyProperty(node,keyName)}}}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noOverlyPermissiveIamPolicy=void 0;const lambda_evidence_1=require("../../utils/lambda-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");const POLICY_PROPERTIES=new Set(["Resource","Action","Principal"]);const DANGEROUS_WILDCARDS=new Set(["*","arn:aws:*","arn:*:*:*:*:*"]);exports.noOverlyPermissiveIamPolicy=(0,eslint_devkit_1.createRule)({name:"no-overly-permissive-iam-policy",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-lambda-security/docs/rules/no-overly-permissive-iam-policy.md",description:"Detects IAM policies with overly broad permissions (wildcards)",cwe:"CWE-732",cvss:6.5},hasSuggestions:true,messages:{permissivePolicy:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Overly Permissive IAM Policy",cwe:"CWE-732",cvss:6.5,description:'IAM policy has wildcard {{property}}: "{{value}}". Violates principle of least privilege.',severity:"HIGH",fix:'Restrict {{property}} to specific resources/actions. Example: "arn:aws:s3:::my-bucket/*" instead of "*"',documentationLink:"https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege"}),useLeastPrivilege:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Apply Least Privilege",description:"Restrict permissions to specific resources and actions",severity:"LOW",fix:'Replace "*" with specific ARNs and action names',documentationLink:"https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true}},additionalProperties:false}]},defaultOptions:[{allowInTests:true}],create(context,[options={}]){if(!(0,lambda_evidence_1.fileIsLambda)(context.sourceCode.ast))return{};const{allowInTests=true}=options;const filename=context.filename;const isTestFile=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}function isDangerousWildcard(value){return DANGEROUS_WILDCARDS.has(value)||value.endsWith("*")&&value.includes(":*:")}function checkPolicyProperty(node,propertyName){const value=node.value;if(value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof value.value==="string"){if(isDangerousWildcard(value.value)){context.report({node,messageId:"permissivePolicy",data:{property:propertyName,value:value.value},suggest:[{messageId:"useLeastPrivilege",fix:()=>null}]})}}if(value.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){for(const element of value.elements){if(element?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof element.value==="string"){if(isDangerousWildcard(element.value)){context.report({node:element,messageId:"permissivePolicy",data:{property:propertyName,value:element.value},suggest:[{messageId:"useLeastPrivilege",fix:()=>null}]})}}}}}return{Property(node){if(node.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const keyName=node.key.name;if(POLICY_PROPERTIES.has(keyName)){checkPolicyProperty(node,keyName)}}if(node.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.key.value==="string"){const keyName=node.key.value;if(POLICY_PROPERTIES.has(keyName)){checkPolicyProperty(node,keyName)}}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPermissiveCorsMidly=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.noPermissiveCorsMidly=(0,eslint_devkit_1.createRule)({name:"no-permissive-cors-middy",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-lambda-security/docs/rules/no-permissive-cors-middy.md",description:"Detects @middy/http-cors middleware with permissive origin (*)",cwe:"CWE-942",cvss:7.5},hasSuggestions:true,messages:{permissiveCors:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Permissive CORS in Middy",cwe:"CWE-942",description:"Wildcard CORS origin in @middy/http-cors allows any domain",severity:"HIGH",fix:'Use specific origins: httpCors({ origins: ["https://your-domain.com"] })',documentationLink:"https://middy.js.org/docs/middlewares/http-cors"}),useSpecificOrigins:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Specific Origins",description:"Configure allowed origins in httpCors middleware",severity:"LOW",fix:'httpCors({ origins: ["https://allowed-domain.com"] })',documentationLink:"https://middy.js.org/docs/middlewares/http-cors"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true}},additionalProperties:false}]},defaultOptions:[{allowInTests:true}],create(context,[options={}]){const{allowInTests=true}=options;const filename=context.filename;const isTestFile=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}function isCorsMiddlewareCall(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const name=node.callee.name.toLowerCase();return name==="httpcors"||name==="cors"}return false}function checkCorsOptions(node,optionsObj){for(const prop of optionsObj.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const keyName=prop.key.name.toLowerCase();if(keyName==="origin"||keyName==="origins"){if(prop.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&prop.value.value==="*"){context.report({node:prop,messageId:"permissiveCors",suggest:[{messageId:"useSpecificOrigins",fix:()=>null}]})}else if(prop.value.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){for(const element of prop.value.elements){if(element?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&element.value==="*"){context.report({node:element,messageId:"permissiveCors",suggest:[{messageId:"useSpecificOrigins",fix:()=>null}]})}}}}}}}return{CallExpression(node){if(!isCorsMiddlewareCall(node))return;if(node.arguments.length===0){context.report({node,messageId:"permissiveCors",suggest:[{messageId:"useSpecificOrigins",fix:()=>null}]});return}if(node.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){checkCorsOptions(node,node.arguments[0])}}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPermissiveCorsMidly=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const lambda_evidence_1=require("../../utils/lambda-evidence");exports.noPermissiveCorsMidly=(0,eslint_devkit_1.createRule)({name:"no-permissive-cors-middy",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-lambda-security/docs/rules/no-permissive-cors-middy.md",description:"Detects @middy/http-cors middleware with permissive origin (*)",cwe:"CWE-942",cvss:7.5},hasSuggestions:true,messages:{permissiveCors:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Permissive CORS in Middy",cwe:"CWE-942",description:"Wildcard CORS origin in @middy/http-cors allows any domain",severity:"HIGH",fix:'Use specific origins: httpCors({ origins: ["https://your-domain.com"] })',documentationLink:"https://middy.js.org/docs/middlewares/http-cors"}),useSpecificOrigins:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Specific Origins",description:"Configure allowed origins in httpCors middleware",severity:"LOW",fix:'httpCors({ origins: ["https://allowed-domain.com"] })',documentationLink:"https://middy.js.org/docs/middlewares/http-cors"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true}},additionalProperties:false}]},defaultOptions:[{allowInTests:true}],create(context,[options={}]){if(!(0,lambda_evidence_1.fileIsLambda)(context.sourceCode.ast))return{};const{allowInTests=true}=options;const filename=context.filename;const isTestFile=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}function isCorsMiddlewareCall(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const name=node.callee.name.toLowerCase();return name==="httpcors"||name==="cors"}return false}function checkCorsOptions(node,optionsObj){for(const prop of optionsObj.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const keyName=prop.key.name.toLowerCase();if(keyName==="origin"||keyName==="origins"){if(prop.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&prop.value.value==="*"){context.report({node:prop,messageId:"permissiveCors",suggest:[{messageId:"useSpecificOrigins",fix:()=>null}]})}else if(prop.value.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){for(const element of prop.value.elements){if(element?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&element.value==="*"){context.report({node:element,messageId:"permissiveCors",suggest:[{messageId:"useSpecificOrigins",fix:()=>null}]})}}}}}}}return{CallExpression(node){if(!isCorsMiddlewareCall(node))return;if(node.arguments.length===0){context.report({node,messageId:"permissiveCors",suggest:[{messageId:"useSpecificOrigins",fix:()=>null}]});return}if(node.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){checkCorsOptions(node,node.arguments[0])}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPermissiveCorsResponse=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.noPermissiveCorsResponse=(0,eslint_devkit_1.createRule)({name:"no-permissive-cors-response",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-lambda-security/docs/rules/no-permissive-cors-response.md",description:"Detects permissive CORS (Access-Control-Allow-Origin: *) in Lambda response headers",cwe:"CWE-942",cvss:7.5},fixable:"code",messages:{permissiveCors:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Permissive CORS in Lambda Response",cwe:"CWE-942",description:"Wildcard CORS origin (*) allows any domain to access this Lambda function",severity:"HIGH",fix:'Use specific origins: headers: { "Access-Control-Allow-Origin": "https://your-domain.com" }',documentationLink:"https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html"}),useSpecificOrigin:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Specific Origin",description:"Specify allowed origins instead of wildcard",severity:"LOW",fix:'Replace "*" with specific domain(s)',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true,description:"Allow permissive CORS in test files"}},additionalProperties:false}]},defaultOptions:[{allowInTests:true}],create(context,[options={}]){const{allowInTests=true}=options;const filename=context.filename;const isTestFile=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}function isLambdaResponse(obj){const propNames=obj.properties.filter(p=>p.type===eslint_devkit_1.AST_NODE_TYPES.Property).map(p=>p.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?p.key.name:"");return propNames.includes("statusCode")||propNames.includes("body")}function checkHeadersObject(obj){for(const prop of obj.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;let headerName="";if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){headerName=prop.key.name}else if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof prop.key.value==="string"){headerName=prop.key.value}if(headerName.toLowerCase()==="access-control-allow-origin"){if(prop.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&prop.value.value==="*"){context.report({node:prop,messageId:"permissiveCors",fix:fixer=>{return fixer.replaceText(prop.value,'"https://your-domain.com"')}})}}}}function checkResponseObject(obj){if(!isLambdaResponse(obj))return;for(const prop of obj.properties){if(prop.type===eslint_devkit_1.AST_NODE_TYPES.Property&&prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&prop.key.name==="headers"&&prop.value.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){checkHeadersObject(prop.value)}}}return{ReturnStatement(node){if(node.argument?.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){checkResponseObject(node.argument)}},ArrowFunctionExpression(node){if(node.body.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){checkResponseObject(node.body)}},VariableDeclarator(node){if(node.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.id.name.toLowerCase().includes("response")&&node.init?.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){checkResponseObject(node.init)}}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPermissiveCorsResponse=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const lambda_evidence_1=require("../../utils/lambda-evidence");exports.noPermissiveCorsResponse=(0,eslint_devkit_1.createRule)({name:"no-permissive-cors-response",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-lambda-security/docs/rules/no-permissive-cors-response.md",description:"Detects permissive CORS (Access-Control-Allow-Origin: *) in Lambda response headers",cwe:"CWE-942",cvss:7.5},fixable:"code",messages:{permissiveCors:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Permissive CORS in Lambda Response",cwe:"CWE-942",description:"Wildcard CORS origin (*) allows any domain to access this Lambda function",severity:"HIGH",fix:'Use specific origins: headers: { "Access-Control-Allow-Origin": "https://your-domain.com" }',documentationLink:"https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html"}),useSpecificOrigin:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Specific Origin",description:"Specify allowed origins instead of wildcard",severity:"LOW",fix:'Replace "*" with specific domain(s)',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true,description:"Allow permissive CORS in test files"}},additionalProperties:false}]},defaultOptions:[{allowInTests:true}],create(context,[options={}]){if(!(0,lambda_evidence_1.fileIsLambda)(context.sourceCode.ast))return{};const{allowInTests=true}=options;const filename=context.filename;const isTestFile=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}function isLambdaResponse(obj){const propNames=obj.properties.filter(p=>p.type===eslint_devkit_1.AST_NODE_TYPES.Property).map(p=>p.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?p.key.name:"");return propNames.includes("statusCode")||propNames.includes("body")}function checkHeadersObject(obj){for(const prop of obj.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;let headerName="";if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){headerName=prop.key.name}else if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof prop.key.value==="string"){headerName=prop.key.value}if(headerName.toLowerCase()==="access-control-allow-origin"){if(prop.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&prop.value.value==="*"){context.report({node:prop,messageId:"permissiveCors",fix:fixer=>{return fixer.replaceText(prop.value,'"https://your-domain.com"')}})}}}}function checkResponseObject(obj){if(!isLambdaResponse(obj))return;for(const prop of obj.properties){if(prop.type===eslint_devkit_1.AST_NODE_TYPES.Property&&prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&prop.key.name==="headers"&&prop.value.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){checkHeadersObject(prop.value)}}}return{ReturnStatement(node){if(node.argument?.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){checkResponseObject(node.argument)}},ArrowFunctionExpression(node){if(node.body.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){checkResponseObject(node.body)}},VariableDeclarator(node){if(node.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.id.name.toLowerCase().includes("response")&&node.init?.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){checkResponseObject(node.init)}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSecretsInEnv=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const SECRET_PATTERNS=[/password/i,/secret/i,/api[_-]?key/i,/api[_-]?token/i,/auth[_-]?token/i,/access[_-]?token/i,/private[_-]?key/i,/encryption[_-]?key/i,/db[_-]?pass/i,/database[_-]?password/i,/jwt[_-]?secret/i,/signing[_-]?key/i,/client[_-]?secret/i,/aws[_-]?secret/i];exports.noSecretsInEnv=(0,eslint_devkit_1.createRule)({name:"no-secrets-in-env",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-lambda-security/docs/rules/no-secrets-in-env.md",description:"Detects secrets directly assigned to environment variables",cwe:"CWE-798",cvss:9.8},hasSuggestions:true,messages:{secretsInEnv:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Secret in Environment Variable",cwe:"CWE-798",description:'Secret "{{varName}}" should not be hardcoded in environment variables',severity:"CRITICAL",fix:'Use AWS Secrets Manager: const secret = await secretsClient.send(new GetSecretValueCommand({ SecretId: "{{varName}}" }))',documentationLink:"https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html"}),useSecretsManager:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Secrets Manager",description:"Store secrets in AWS Secrets Manager instead of env vars",severity:"LOW",fix:'import { SecretsManagerClient, GetSecretValueCommand } from "@aws-sdk/client-secrets-manager"',documentationLink:"https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true},additionalPatterns:{type:"array",items:{type:"string"},default:[],description:"Extra environment-variable name patterns to treat as secrets"}},additionalProperties:false}]},defaultOptions:[{allowInTests:true,additionalPatterns:[]}],create(context,[options={}]){const{allowInTests=true,additionalPatterns=[]}=options;const filename=context.filename;const isTestFile=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}const allPatterns=[...SECRET_PATTERNS,...additionalPatterns.map(p=>new RegExp(p,"i"))];function isSecretName(name){return allPatterns.some(pattern=>pattern.test(name))}function isHardcodedSecretValue(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.value==="string"){return node.value.length>5}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.quasis.some(quasi=>quasi.value.raw.length>5)}return false}return{AssignmentExpression(node){if(node.left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.left.object.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.left.object.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.left.object.object.name==="process"&&node.left.object.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.left.object.property.name==="env"){let envVarName="";if(node.left.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){envVarName=node.left.property.name}else if(node.left.property.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.left.property.value==="string"){envVarName=node.left.property.value}if(isSecretName(envVarName)&&isHardcodedSecretValue(node.right)){context.report({node,messageId:"secretsInEnv",data:{varName:envVarName},suggest:[{messageId:"useSecretsManager",fix:()=>null}]})}}},Property(node){let propName="";if(node.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){propName=node.key.name}else if(node.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.key.value==="string"){propName=node.key.value}if(isSecretName(propName)&&isHardcodedSecretValue(node.value)){let parent=node.parent;while(parent){if(parent.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){parent=parent.parent;continue}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&/env|config|settings/i.test(parent.id.name)){context.report({node,messageId:"secretsInEnv",data:{varName:propName},suggest:[{messageId:"useSecretsManager",fix:()=>null}]});break}break}}}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSecretsInEnv=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const lambda_evidence_1=require("../../utils/lambda-evidence");const SECRET_PATTERNS=[/password/i,/secret/i,/api[_-]?key/i,/api[_-]?token/i,/auth[_-]?token/i,/access[_-]?token/i,/private[_-]?key/i,/encryption[_-]?key/i,/db[_-]?pass/i,/database[_-]?password/i,/jwt[_-]?secret/i,/signing[_-]?key/i,/client[_-]?secret/i,/aws[_-]?secret/i];exports.noSecretsInEnv=(0,eslint_devkit_1.createRule)({name:"no-secrets-in-env",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-lambda-security/docs/rules/no-secrets-in-env.md",description:"Detects secrets directly assigned to environment variables",cwe:"CWE-798",cvss:9.8},hasSuggestions:true,messages:{secretsInEnv:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Secret in Environment Variable",cwe:"CWE-798",description:'Secret "{{varName}}" should not be hardcoded in environment variables',severity:"CRITICAL",fix:'Use AWS Secrets Manager: const secret = await secretsClient.send(new GetSecretValueCommand({ SecretId: "{{varName}}" }))',documentationLink:"https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html"}),useSecretsManager:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Secrets Manager",description:"Store secrets in AWS Secrets Manager instead of env vars",severity:"LOW",fix:'import { SecretsManagerClient, GetSecretValueCommand } from "@aws-sdk/client-secrets-manager"',documentationLink:"https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true},additionalPatterns:{type:"array",items:{type:"string"},default:[],description:"Extra environment-variable name patterns to treat as secrets"}},additionalProperties:false}]},defaultOptions:[{allowInTests:true,additionalPatterns:[]}],create(context,[options={}]){if(!(0,lambda_evidence_1.fileIsLambda)(context.sourceCode.ast))return{};const{allowInTests=true,additionalPatterns=[]}=options;const filename=context.filename;const isTestFile=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}const allPatterns=[...SECRET_PATTERNS,...additionalPatterns.map(p=>new RegExp(p,"i"))];function isSecretName(name){return allPatterns.some(pattern=>pattern.test(name))}function isHardcodedSecretValue(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.value==="string"){return node.value.length>5}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.quasis.some(quasi=>quasi.value.raw.length>5)}return false}return{AssignmentExpression(node){if(node.left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.left.object.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.left.object.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.left.object.object.name==="process"&&node.left.object.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.left.object.property.name==="env"){let envVarName="";if(node.left.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){envVarName=node.left.property.name}else if(node.left.property.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.left.property.value==="string"){envVarName=node.left.property.value}if(isSecretName(envVarName)&&isHardcodedSecretValue(node.right)){context.report({node,messageId:"secretsInEnv",data:{varName:envVarName},suggest:[{messageId:"useSecretsManager",fix:()=>null}]})}}},Property(node){let propName="";if(node.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){propName=node.key.name}else if(node.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.key.value==="string"){propName=node.key.value}if(isSecretName(propName)&&isHardcodedSecretValue(node.value)){let parent=node.parent;while(parent){if(parent.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){parent=parent.parent;continue}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&/env|config|settings/i.test(parent.id.name)){context.report({node,messageId:"secretsInEnv",data:{varName:propName},suggest:[{messageId:"useSecretsManager",fix:()=>null}]});break}break}}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnboundedBatchProcessing=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const BATCH_SOURCE_PROPERTIES=new Set(["Records","records","items","messages"]);const EVENT_PARAM_NAMES=new Set(["event","evt","e","request","req"]);exports.noUnboundedBatchProcessing=(0,eslint_devkit_1.createRule)({name:"no-unbounded-batch-processing",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-lambda-security/docs/rules/no-unbounded-batch-processing.md",description:"Detects processing batch records without size validation",cwe:"CWE-770",cvss:5.5},hasSuggestions:true,messages:{unboundedBatch:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.WARNING,issueName:"Unbounded Batch Processing",cwe:"CWE-770",cvss:5.5,description:"Processing {{source}} without size check. Large batches may cause timeout or memory exhaustion.",severity:"MEDIUM",fix:'Validate batch size before processing: if (event.Records.length > MAX_BATCH) throw new Error("Batch too large")',documentationLink:"https://docs.aws.amazon.com/lambda/latest/dg/with-sqs.html"}),addBatchLimit:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Add Batch Size Limit",description:"Add a maximum batch size check before processing",severity:"LOW",fix:"const MAX_BATCH_SIZE = 10; const records = event.Records.slice(0, MAX_BATCH_SIZE);",documentationLink:"https://docs.aws.amazon.com/lambda/latest/dg/with-sqs.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true},maxBatchSize:{type:"number",default:100,description:"Batch size above which processing must be explicitly bounded"}},additionalProperties:false}]},defaultOptions:[{allowInTests:true,maxBatchSize:100}],create(context,[options={}]){const{allowInTests=true}=options;const filename=context.filename;const isTestFile=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}let currentHandlerNode=null;let hasBatchSizeCheck=false;const batchAccessNodes=[];const eventParamName=[];function enterFunction(node){const hasEvent=node.params.some(p=>{if(p.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&EVENT_PARAM_NAMES.has(p.name)){eventParamName.push(p.name);return true}return false});if(hasEvent){currentHandlerNode=node;hasBatchSizeCheck=false;batchAccessNodes.length=0}}function exitFunction(node){if(currentHandlerNode!==node)return;if(!hasBatchSizeCheck){for(const{node:batchNode,source}of batchAccessNodes){context.report({node:batchNode,messageId:"unboundedBatch",data:{source},suggest:[{messageId:"addBatchLimit",fix:()=>null}]})}}currentHandlerNode=null;eventParamName.length=0}return{"ArrowFunctionExpression, FunctionExpression, FunctionDeclaration"(node){enterFunction(node)},"ArrowFunctionExpression:exit"(node){exitFunction(node)},"FunctionExpression:exit"(node){exitFunction(node)},"FunctionDeclaration:exit"(node){exitFunction(node)},MemberExpression(node){if(!currentHandlerNode)return;if(node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&eventParamName.includes(node.object.name)&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&BATCH_SOURCE_PROPERTIES.has(node.property.name)){batchAccessNodes.push({node,source:`${node.object.name}.${node.property.name}`})}if(node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.property.name==="length"){if(node.object.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.object.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&BATCH_SOURCE_PROPERTIES.has(node.object.property.name)){hasBatchSizeCheck=true}}},CallExpression(node){if(!currentHandlerNode)return;if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&["slice","splice","take","chunk"].includes(node.callee.property.name)){hasBatchSizeCheck=true}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&["slice","splice","take","chunk"].includes(node.callee.name)){hasBatchSizeCheck=true}},BinaryExpression(node){if(!currentHandlerNode)return;if(["<","<=",">",">="].includes(node.operator)){const sourceCode=context.sourceCode;const text=sourceCode.getText(node);if(/\.length|Records|records/.test(text)){hasBatchSizeCheck=true}}}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnboundedBatchProcessing=void 0;const lambda_evidence_1=require("../../utils/lambda-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");const BATCH_SOURCE_PROPERTIES=new Set(["Records","records","items","messages"]);const EVENT_PARAM_NAMES=new Set(["event","evt","e","request","req"]);exports.noUnboundedBatchProcessing=(0,eslint_devkit_1.createRule)({name:"no-unbounded-batch-processing",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-lambda-security/docs/rules/no-unbounded-batch-processing.md",description:"Detects processing batch records without size validation",cwe:"CWE-770",cvss:5.5},hasSuggestions:true,messages:{unboundedBatch:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.WARNING,issueName:"Unbounded Batch Processing",cwe:"CWE-770",cvss:5.5,description:"Processing {{source}} without size check. Large batches may cause timeout or memory exhaustion.",severity:"MEDIUM",fix:'Validate batch size before processing: if (event.Records.length > MAX_BATCH) throw new Error("Batch too large")',documentationLink:"https://docs.aws.amazon.com/lambda/latest/dg/with-sqs.html"}),addBatchLimit:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Add Batch Size Limit",description:"Add a maximum batch size check before processing",severity:"LOW",fix:"const MAX_BATCH_SIZE = 10; const records = event.Records.slice(0, MAX_BATCH_SIZE);",documentationLink:"https://docs.aws.amazon.com/lambda/latest/dg/with-sqs.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true},maxBatchSize:{type:"number",default:100,description:"Batch size above which processing must be explicitly bounded"}},additionalProperties:false}]},defaultOptions:[{allowInTests:true,maxBatchSize:100}],create(context,[options={}]){if(!(0,lambda_evidence_1.fileIsLambda)(context.sourceCode.ast))return{};const{allowInTests=true}=options;const filename=context.filename;const isTestFile=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}let currentHandlerNode=null;let hasBatchSizeCheck=false;const batchAccessNodes=[];const eventParamName=[];function enterFunction(node){const hasEvent=node.params.some(p=>{if(p.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&EVENT_PARAM_NAMES.has(p.name)){eventParamName.push(p.name);return true}return false});if(hasEvent){currentHandlerNode=node;hasBatchSizeCheck=false;batchAccessNodes.length=0}}function exitFunction(node){if(currentHandlerNode!==node)return;if(!hasBatchSizeCheck){for(const{node:batchNode,source}of batchAccessNodes){context.report({node:batchNode,messageId:"unboundedBatch",data:{source},suggest:[{messageId:"addBatchLimit",fix:()=>null}]})}}currentHandlerNode=null;eventParamName.length=0}return{"ArrowFunctionExpression, FunctionExpression, FunctionDeclaration"(node){enterFunction(node)},"ArrowFunctionExpression:exit"(node){exitFunction(node)},"FunctionExpression:exit"(node){exitFunction(node)},"FunctionDeclaration:exit"(node){exitFunction(node)},MemberExpression(node){if(!currentHandlerNode)return;if(node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&eventParamName.includes(node.object.name)&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&BATCH_SOURCE_PROPERTIES.has(node.property.name)){batchAccessNodes.push({node,source:`${node.object.name}.${node.property.name}`})}if(node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.property.name==="length"){if(node.object.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.object.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&BATCH_SOURCE_PROPERTIES.has(node.object.property.name)){hasBatchSizeCheck=true}}},CallExpression(node){if(!currentHandlerNode)return;if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&["slice","splice","take","chunk"].includes(node.callee.property.name)){hasBatchSizeCheck=true}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&["slice","splice","take","chunk"].includes(node.callee.name)){hasBatchSizeCheck=true}},BinaryExpression(node){if(!currentHandlerNode)return;if(["<","<=",">",">="].includes(node.operator)){const sourceCode=context.sourceCode;const text=sourceCode.getText(node);if(/\.length|Records|records/.test(text)){hasBatchSizeCheck=true}}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnvalidatedEventBody=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const DANGEROUS_EVENT_PROPERTIES=["body","queryStringParameters","pathParameters","multiValueQueryStringParameters","headers","multiValueHeaders","rawPath","rawQueryString"];const VALIDATION_INDICATORS=new Set(["validator","httpJsonBodyParser","@middy/validator","parse","validate","parseAsync","safeParse","safeParseAsync","assert","is"]);exports.noUnvalidatedEventBody=(0,eslint_devkit_1.createRule)({name:"no-unvalidated-event-body",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-lambda-security/docs/rules/no-unvalidated-event-body.md",description:"Detects Lambda handlers using event body/params without validation",cwe:"CWE-20",cvss:8},hasSuggestions:true,messages:{unvalidatedInput:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unvalidated Event Input",cwe:"CWE-20",cvss:8,description:"Lambda handler uses {{property}} without validation. This can lead to injection attacks.",severity:"HIGH",fix:"Validate event input using Middy validator, Zod, or Joi before use",documentationLink:"https://owasp.org/www-project-serverless-top-10/"}),useValidation:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Add Input Validation",description:"Add input validation using Middy validator middleware or a schema library",severity:"LOW",fix:"import { validator } from '@middy/validator'; middy(handler).use(validator({ inputSchema }))",documentationLink:"https://middy.js.org/docs/middlewares/validator"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true,description:"Allow unvalidated input in test files"},additionalProperties:{type:"array",items:{type:"string"},default:[],description:"Additional event properties to check"}},additionalProperties:false}]},defaultOptions:[{allowInTests:true,additionalProperties:[]}],create(context,[options={}]){const{allowInTests=true,additionalProperties=[]}=options;const filename=context.filename;const isTestFile=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}const dangerousProperties=new Set([...DANGEROUS_EVENT_PROPERTIES,...additionalProperties]);const validatedVariables=new Set;const eventParameters=new Set;let hasValidationMiddleware=false;function isValidationCall(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const property=node.callee.property;if(property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&VALIDATION_INDICATORS.has(property.name)){return true}}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(VALIDATION_INDICATORS.has(node.callee.name)){return true}}}return false}function isEventPropertyAccess(node){if(node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&eventParameters.has(node.object.name)&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&dangerousProperties.has(node.property.name)){return{eventName:node.object.name,property:node.property.name}}return null}function semanticParent(node){let current=node;let parent=current.parent;while(parent&&(parent.type===eslint_devkit_1.AST_NODE_TYPES.LogicalExpression||parent.type===eslint_devkit_1.AST_NODE_TYPES.TSAsExpression||parent.type===eslint_devkit_1.AST_NODE_TYPES.TSNonNullExpression)){current=parent;parent=current.parent}return parent}const sourceCode=context.sourceCode;const fileImportsLambda=sourceCode.ast.body.some(n=>{if(n.type!==eslint_devkit_1.AST_NODE_TYPES.ImportDeclaration)return false;const src=String(n.source.value);return src==="aws-lambda"||src.startsWith("@aws-sdk/")||src.startsWith("@middy/")||src==="@aws-cdk/aws-lambda"});function isExportedAsHandler(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration&&node.id?.name==="handler"){return true}const parent=node.parent;if(!parent)return false;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&parent.id.name==="handler"){return true}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression){const left=parent.left;if(left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&left.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&left.property.name==="handler"){return true}}return false}function isLambdaSignature(params,node){if(params.length<1)return false;const first=params[0];if(first.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const second=params[1];const hasContextSibling=second?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(second.name==="context"||second.name==="callback");const looksLikeExpress=second?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(first.name==="req"&&second.name==="res"||first.name==="request"&&second.name==="response");if(looksLikeExpress)return false;const isEventName=first.name==="event"||first.name==="evt";if(isEventName&&hasContextSibling)return true;if(isEventName&&fileImportsLambda)return true;if(isExportedAsHandler(node)){const allowedHandlerParam=["event","evt","e","request","req"];if(allowedHandlerParam.includes(first.name))return true}return false}return{"ArrowFunctionExpression, FunctionExpression, FunctionDeclaration"(node){if(!isLambdaSignature(node.params,node))return;const first=node.params[0];eventParameters.add(first.name)},CallExpression(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.property.name==="use"){for(const arg of node.arguments){if(arg.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&arg.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&["validator","httpJsonBodyParser"].includes(arg.callee.name)){hasValidationMiddleware=true}}}if(isValidationCall(node)){const parent=node.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){validatedVariables.add(parent.id.name)}}},MemberExpression(node){if(hasValidationMiddleware)return;const eventAccess=isEventPropertyAccess(node);if(!eventAccess)return;const parent=semanticParent(node);if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&isValidationCall(parent)){return}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.UnaryExpression&&parent.operator==="typeof"){return}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement||parent?.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){return}if(node.optional){return}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&parent.optional){return}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression){return}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&parent.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&parent.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&parent.callee.object.name==="console"){return}context.report({node,messageId:"unvalidatedInput",data:{property:`event.${eventAccess.property}`},suggest:[{messageId:"useValidation",fix:()=>null}]})}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnvalidatedEventBody=void 0;const lambda_evidence_1=require("../../utils/lambda-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");const DANGEROUS_EVENT_PROPERTIES=["body","queryStringParameters","pathParameters","multiValueQueryStringParameters","headers","multiValueHeaders","rawPath","rawQueryString"];const VALIDATION_INDICATORS=new Set(["validator","httpJsonBodyParser","@middy/validator","parse","validate","parseAsync","safeParse","safeParseAsync","assert","is"]);exports.noUnvalidatedEventBody=(0,eslint_devkit_1.createRule)({name:"no-unvalidated-event-body",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-lambda-security/docs/rules/no-unvalidated-event-body.md",description:"Detects Lambda handlers using event body/params without validation",cwe:"CWE-20",cvss:8},hasSuggestions:true,messages:{unvalidatedInput:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unvalidated Event Input",cwe:"CWE-20",cvss:8,description:"Lambda handler uses {{property}} without validation. This can lead to injection attacks.",severity:"HIGH",fix:"Validate event input using Middy validator, Zod, or Joi before use",documentationLink:"https://owasp.org/www-project-serverless-top-10/"}),useValidation:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Add Input Validation",description:"Add input validation using Middy validator middleware or a schema library",severity:"LOW",fix:"import { validator } from '@middy/validator'; middy(handler).use(validator({ inputSchema }))",documentationLink:"https://middy.js.org/docs/middlewares/validator"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true,description:"Allow unvalidated input in test files"},additionalProperties:{type:"array",items:{type:"string"},default:[],description:"Additional event properties to check"}},additionalProperties:false}]},defaultOptions:[{allowInTests:true,additionalProperties:[]}],create(context,[options={}]){if(!(0,lambda_evidence_1.fileIsLambda)(context.sourceCode.ast))return{};const{allowInTests=true,additionalProperties=[]}=options;const filename=context.filename;const isTestFile=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}const dangerousProperties=new Set([...DANGEROUS_EVENT_PROPERTIES,...additionalProperties]);const validatedVariables=new Set;const eventParameters=new Set;let hasValidationMiddleware=false;function isValidationCall(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const property=node.callee.property;if(property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&VALIDATION_INDICATORS.has(property.name)){return true}}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(VALIDATION_INDICATORS.has(node.callee.name)){return true}}}return false}function isEventPropertyAccess(node){if(node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&eventParameters.has(node.object.name)&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&dangerousProperties.has(node.property.name)){return{eventName:node.object.name,property:node.property.name}}return null}function semanticParent(node){let current=node;let parent=current.parent;while(parent&&(parent.type===eslint_devkit_1.AST_NODE_TYPES.LogicalExpression||parent.type===eslint_devkit_1.AST_NODE_TYPES.TSAsExpression||parent.type===eslint_devkit_1.AST_NODE_TYPES.TSNonNullExpression)){current=parent;parent=current.parent}return parent}const sourceCode=context.sourceCode;const fileImportsLambda=sourceCode.ast.body.some(n=>{if(n.type!==eslint_devkit_1.AST_NODE_TYPES.ImportDeclaration)return false;const src=String(n.source.value);return src==="aws-lambda"||src.startsWith("@aws-sdk/")||src.startsWith("@middy/")||src==="@aws-cdk/aws-lambda"});function isExportedAsHandler(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration&&node.id?.name==="handler"){return true}const parent=node.parent;if(!parent)return false;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&parent.id.name==="handler"){return true}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression){const left=parent.left;if(left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&left.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&left.property.name==="handler"){return true}}return false}function isLambdaSignature(params,node){if(params.length<1)return false;const first=params[0];if(first.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const second=params[1];const hasContextSibling=second?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(second.name==="context"||second.name==="callback");const looksLikeExpress=second?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(first.name==="req"&&second.name==="res"||first.name==="request"&&second.name==="response");if(looksLikeExpress)return false;const isEventName=first.name==="event"||first.name==="evt";if(isEventName&&hasContextSibling)return true;if(isEventName&&fileImportsLambda)return true;if(isExportedAsHandler(node)){const allowedHandlerParam=["event","evt","e","request","req"];if(allowedHandlerParam.includes(first.name))return true}return false}return{"ArrowFunctionExpression, FunctionExpression, FunctionDeclaration"(node){if(!isLambdaSignature(node.params,node))return;const first=node.params[0];eventParameters.add(first.name)},CallExpression(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.property.name==="use"){for(const arg of node.arguments){if(arg.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&arg.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&["validator","httpJsonBodyParser"].includes(arg.callee.name)){hasValidationMiddleware=true}}}if(isValidationCall(node)){const parent=node.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){validatedVariables.add(parent.id.name)}}},MemberExpression(node){if(hasValidationMiddleware)return;const eventAccess=isEventPropertyAccess(node);if(!eventAccess)return;const parent=semanticParent(node);if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&isValidationCall(parent)){return}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.UnaryExpression&&parent.operator==="typeof"){return}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement||parent?.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){return}if(node.optional){return}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&parent.optional){return}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression){return}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&parent.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&parent.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&parent.callee.object.name==="console"){return}context.report({node,messageId:"unvalidatedInput",data:{property:`event.${eventAccess.property}`},suggest:[{messageId:"useValidation",fix:()=>null}]})}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUserControlledRequests=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const HTTP_CLIENT_METHODS=new Set(["fetch","request","get","post","put","delete","patch","axios","got","nodeFetch","superagent"]);const HTTP_CLIENT_OBJECTS=new Set(["http","https","axios","got","request"]);const USER_INPUT_PROPERTIES=new Set(["body","queryStringParameters","pathParameters","multiValueQueryStringParameters","headers","rawPath","rawQueryString"]);const EVENT_PARAM_NAMES=new Set(["event","evt","e","request","req"]);exports.noUserControlledRequests=(0,eslint_devkit_1.createRule)({name:"no-user-controlled-requests",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-lambda-security/docs/rules/no-user-controlled-requests.md",description:"Detects HTTP requests with user-controlled URLs (SSRF vulnerability)",cwe:"CWE-918",cvss:9.1},hasSuggestions:true,messages:{ssrfVulnerability:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Server-Side Request Forgery (SSRF)",cwe:"CWE-918",cvss:9.1,description:"HTTP request URL contains user-controlled input from {{source}}. Attackers can access internal services or exfiltrate data.",severity:"CRITICAL",fix:"Validate URL against allowlist before making request. Never use user input directly in URLs.",documentationLink:"https://owasp.org/www-community/attacks/Server_Side_Request_Forgery"}),useAllowlist:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use URL Allowlist",description:"Implement an allowlist for permitted URL domains/hosts",severity:"LOW",fix:"const ALLOWED_HOSTS = ['api.trusted.com']; if (!ALLOWED_HOSTS.includes(new URL(url).host)) throw new Error('Invalid URL')",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true,description:"Allow user-controlled URLs in test files"}},additionalProperties:false}]},defaultOptions:[{allowInTests:true}],create(context,[options={}]){const{allowInTests=true}=options;const filename=context.filename;const isTestFile=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}const eventParameters=new Set;const taintedVariables=new Map;function isEventParameter(name){return eventParameters.has(name)}function getEventInputSource(node){if(node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&isEventParameter(node.object.name)&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&USER_INPUT_PROPERTIES.has(node.property.name)){return`event.${node.property.name}`}if(node.object.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.object.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&isEventParameter(node.object.object.name)&&node.object.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&USER_INPUT_PROPERTIES.has(node.object.property.name)){return`event.${node.object.property.name}.${node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?node.property.name:"[...]"}`}return null}function getTaintSource(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const source=getEventInputSource(node);if(source)return source}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const source=taintedVariables.get(node.name);if(source)return source}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){for(const expr of node.expressions){const source=getTaintSource(expr);if(source)return source}}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){const leftSource=getTaintSource(node.left);if(leftSource)return leftSource;const rightSource=getTaintSource(node.right);if(rightSource)return rightSource}return null}function isHttpClientCall(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&HTTP_CLIENT_METHODS.has(node.callee.name)){return true}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&HTTP_CLIENT_OBJECTS.has(node.callee.object.name)){return true}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&["get","post","put","delete","patch","request"].includes(node.callee.property.name)){return true}return false}function checkUrlArgument(node){if(node.arguments.length===0)return null;const urlArg=node.arguments[0];const source=getTaintSource(urlArg);if(source){return{tainted:true,source}}if(urlArg.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){for(const prop of urlArg.properties){if(prop.type===eslint_devkit_1.AST_NODE_TYPES.Property&&prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&["url","uri","href","baseURL"].includes(prop.key.name)){const propSource=getTaintSource(prop.value);if(propSource){return{tainted:true,source:propSource}}}}}return null}return{"ArrowFunctionExpression, FunctionExpression, FunctionDeclaration"(node){for(const param of node.params){if(param.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(EVENT_PARAM_NAMES.has(param.name)){eventParameters.add(param.name)}}}},VariableDeclarator(node){if(node.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.init){const source=getTaintSource(node.init);if(source){taintedVariables.set(node.id.name,source)}}},AssignmentExpression(node){if(node.left.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const source=getTaintSource(node.right);if(source){taintedVariables.set(node.left.name,source)}}},CallExpression(node){if(!isHttpClientCall(node))return;const result=checkUrlArgument(node);if(result?.tainted){context.report({node,messageId:"ssrfVulnerability",data:{source:result.source},suggest:[{messageId:"useAllowlist",fix:()=>null}]})}}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUserControlledRequests=void 0;const lambda_evidence_1=require("../../utils/lambda-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");const HTTP_CLIENT_METHODS=new Set(["fetch","request","get","post","put","delete","patch","axios","got","nodeFetch","superagent"]);const HTTP_CLIENT_OBJECTS=new Set(["http","https","axios","got","request"]);const USER_INPUT_PROPERTIES=new Set(["body","queryStringParameters","pathParameters","multiValueQueryStringParameters","headers","rawPath","rawQueryString"]);const EVENT_PARAM_NAMES=new Set(["event","evt","e","request","req"]);exports.noUserControlledRequests=(0,eslint_devkit_1.createRule)({name:"no-user-controlled-requests",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-lambda-security/docs/rules/no-user-controlled-requests.md",description:"Detects HTTP requests with user-controlled URLs (SSRF vulnerability)",cwe:"CWE-918",cvss:9.1},hasSuggestions:true,messages:{ssrfVulnerability:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Server-Side Request Forgery (SSRF)",cwe:"CWE-918",cvss:9.1,description:"HTTP request URL contains user-controlled input from {{source}}. Attackers can access internal services or exfiltrate data.",severity:"CRITICAL",fix:"Validate URL against allowlist before making request. Never use user input directly in URLs.",documentationLink:"https://owasp.org/www-community/attacks/Server_Side_Request_Forgery"}),useAllowlist:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use URL Allowlist",description:"Implement an allowlist for permitted URL domains/hosts",severity:"LOW",fix:"const ALLOWED_HOSTS = ['api.trusted.com']; if (!ALLOWED_HOSTS.includes(new URL(url).host)) throw new Error('Invalid URL')",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true,description:"Allow user-controlled URLs in test files"}},additionalProperties:false}]},defaultOptions:[{allowInTests:true}],create(context,[options={}]){if(!(0,lambda_evidence_1.fileIsLambda)(context.sourceCode.ast))return{};const{allowInTests=true}=options;const filename=context.filename;const isTestFile=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}const eventParameters=new Set;const taintedVariables=new Map;function isEventParameter(name){return eventParameters.has(name)}function getEventInputSource(node){if(node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&isEventParameter(node.object.name)&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&USER_INPUT_PROPERTIES.has(node.property.name)){return`event.${node.property.name}`}if(node.object.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.object.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&isEventParameter(node.object.object.name)&&node.object.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&USER_INPUT_PROPERTIES.has(node.object.property.name)){return`event.${node.object.property.name}.${node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?node.property.name:"[...]"}`}return null}function getTaintSource(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const source=getEventInputSource(node);if(source)return source}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const source=taintedVariables.get(node.name);if(source)return source}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){for(const expr of node.expressions){const source=getTaintSource(expr);if(source)return source}}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){const leftSource=getTaintSource(node.left);if(leftSource)return leftSource;const rightSource=getTaintSource(node.right);if(rightSource)return rightSource}return null}function isHttpClientCall(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&HTTP_CLIENT_METHODS.has(node.callee.name)){return true}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&HTTP_CLIENT_OBJECTS.has(node.callee.object.name)){return true}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&["get","post","put","delete","patch","request"].includes(node.callee.property.name)){return true}return false}function checkUrlArgument(node){if(node.arguments.length===0)return null;const urlArg=node.arguments[0];const source=getTaintSource(urlArg);if(source){return{tainted:true,source}}if(urlArg.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){for(const prop of urlArg.properties){if(prop.type===eslint_devkit_1.AST_NODE_TYPES.Property&&prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&["url","uri","href","baseURL"].includes(prop.key.name)){const propSource=getTaintSource(prop.value);if(propSource){return{tainted:true,source:propSource}}}}}return null}return{"ArrowFunctionExpression, FunctionExpression, FunctionDeclaration"(node){for(const param of node.params){if(param.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(EVENT_PARAM_NAMES.has(param.name)){eventParameters.add(param.name)}}}},VariableDeclarator(node){if(node.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.init){const source=getTaintSource(node.init);if(source){taintedVariables.set(node.id.name,source)}}},AssignmentExpression(node){if(node.left.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const source=getTaintSource(node.right);if(source){taintedVariables.set(node.left.name,source)}}},CallExpression(node){if(!isHttpClientCall(node))return;const result=checkUrlArgument(node);if(result?.tainted){context.report({node,messageId:"ssrfVulnerability",data:{source:result.source},suggest:[{messageId:"useAllowlist",fix:()=>null}]})}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireTimeoutHandling=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const CONTEXT_PARAM_NAMES=new Set(["context","ctx","lambdaContext"]);const EVENT_PARAM_NAMES=new Set(["event","evt","e","request","req"]);const EXTERNAL_CALL_PATTERNS=new Set(["fetch","axios","got","request","send","invoke","query","execute","connect","promise","wait"]);exports.requireTimeoutHandling=(0,eslint_devkit_1.createRule)({name:"require-timeout-handling",meta:{type:"suggestion",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-lambda-security/docs/rules/require-timeout-handling.md",description:"Warns when Lambda handlers with external calls lack timeout handling",cwe:"CWE-400",cvss:6},hasSuggestions:true,messages:{missingTimeoutHandling:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.WARNING,issueName:"Missing Timeout Handling",cwe:"CWE-400",cvss:6,description:"Lambda handler makes external calls without timeout handling. Function may timeout without cleanup.",severity:"MEDIUM",fix:"Use context.getRemainingTimeInMillis() to check available time before external calls, or use AbortController",documentationLink:"https://docs.aws.amazon.com/lambda/latest/dg/nodejs-context.html"}),addTimeoutCheck:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Add Timeout Check",description:"Check remaining time before making external calls to prevent timeouts",severity:"LOW",fix:"const remainingTime = context.getRemainingTimeInMillis(); if (remainingTime < 5000) { return { statusCode: 503 } }",documentationLink:"https://docs.aws.amazon.com/lambda/latest/dg/nodejs-context.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true}},additionalProperties:false}]},defaultOptions:[{allowInTests:true}],create(context,[options={}]){const{allowInTests=true}=options;const filename=context.filename;const isTestFile=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}let currentHandlerNode=null;let hasTimeoutCheck=false;let hasExternalCalls=false;let hasContextParam=false;function enterFunction(node){const params=node.params;const hasEvent=params.some(p=>p.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&EVENT_PARAM_NAMES.has(p.name));const hasContext=params.some(p=>p.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&CONTEXT_PARAM_NAMES.has(p.name));if(hasEvent){currentHandlerNode=node;hasTimeoutCheck=false;hasExternalCalls=false;hasContextParam=hasContext}}function exitFunction(node){if(currentHandlerNode!==node)return;if(hasExternalCalls&&!hasTimeoutCheck&&hasContextParam){context.report({node,messageId:"missingTimeoutHandling",suggest:[{messageId:"addTimeoutCheck",fix:()=>null}]})}currentHandlerNode=null}return{"ArrowFunctionExpression, FunctionExpression, FunctionDeclaration"(node){enterFunction(node)},"ArrowFunctionExpression:exit"(node){exitFunction(node)},"FunctionExpression:exit"(node){exitFunction(node)},"FunctionDeclaration:exit"(node){exitFunction(node)},MemberExpression(node){if(!currentHandlerNode)return;if(node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.property.name==="getRemainingTimeInMillis"){hasTimeoutCheck=true}},NewExpression(node){if(!currentHandlerNode)return;if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="AbortController"){hasTimeoutCheck=true}},CallExpression(node){if(!currentHandlerNode)return;if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(EXTERNAL_CALL_PATTERNS.has(node.callee.name)){hasExternalCalls=true}}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const property=node.callee.property;if(property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&EXTERNAL_CALL_PATTERNS.has(property.name)){hasExternalCalls=true}}if(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==="Promise"&&node.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.property.name==="race"){hasTimeoutCheck=true}}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireTimeoutHandling=void 0;const lambda_evidence_1=require("../../utils/lambda-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");const CONTEXT_PARAM_NAMES=new Set(["context","ctx","lambdaContext"]);const EVENT_PARAM_NAMES=new Set(["event","evt","e","request","req"]);const EXTERNAL_CALL_PATTERNS=new Set(["fetch","axios","got","request","send","invoke","query","execute","connect","promise","wait"]);exports.requireTimeoutHandling=(0,eslint_devkit_1.createRule)({name:"require-timeout-handling",meta:{type:"suggestion",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-lambda-security/docs/rules/require-timeout-handling.md",description:"Warns when Lambda handlers with external calls lack timeout handling",cwe:"CWE-400",cvss:6},hasSuggestions:true,messages:{missingTimeoutHandling:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.WARNING,issueName:"Missing Timeout Handling",cwe:"CWE-400",cvss:6,description:"Lambda handler makes external calls without timeout handling. Function may timeout without cleanup.",severity:"MEDIUM",fix:"Use context.getRemainingTimeInMillis() to check available time before external calls, or use AbortController",documentationLink:"https://docs.aws.amazon.com/lambda/latest/dg/nodejs-context.html"}),addTimeoutCheck:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Add Timeout Check",description:"Check remaining time before making external calls to prevent timeouts",severity:"LOW",fix:"const remainingTime = context.getRemainingTimeInMillis(); if (remainingTime < 5000) { return { statusCode: 503 } }",documentationLink:"https://docs.aws.amazon.com/lambda/latest/dg/nodejs-context.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true}},additionalProperties:false}]},defaultOptions:[{allowInTests:true}],create(context,[options={}]){if(!(0,lambda_evidence_1.fileIsLambda)(context.sourceCode.ast))return{};const{allowInTests=true}=options;const filename=context.filename;const isTestFile=/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(allowInTests&&isTestFile){return{}}let currentHandlerNode=null;let hasTimeoutCheck=false;let hasExternalCalls=false;let hasContextParam=false;function enterFunction(node){const params=node.params;const hasEvent=params.some(p=>p.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&EVENT_PARAM_NAMES.has(p.name));const hasContext=params.some(p=>p.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&CONTEXT_PARAM_NAMES.has(p.name));if(hasEvent){currentHandlerNode=node;hasTimeoutCheck=false;hasExternalCalls=false;hasContextParam=hasContext}}function exitFunction(node){if(currentHandlerNode!==node)return;if(hasExternalCalls&&!hasTimeoutCheck&&hasContextParam){context.report({node,messageId:"missingTimeoutHandling",suggest:[{messageId:"addTimeoutCheck",fix:()=>null}]})}currentHandlerNode=null}return{"ArrowFunctionExpression, FunctionExpression, FunctionDeclaration"(node){enterFunction(node)},"ArrowFunctionExpression:exit"(node){exitFunction(node)},"FunctionExpression:exit"(node){exitFunction(node)},"FunctionDeclaration:exit"(node){exitFunction(node)},MemberExpression(node){if(!currentHandlerNode)return;if(node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.property.name==="getRemainingTimeInMillis"){hasTimeoutCheck=true}},NewExpression(node){if(!currentHandlerNode)return;if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="AbortController"){hasTimeoutCheck=true}},CallExpression(node){if(!currentHandlerNode)return;if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(EXTERNAL_CALL_PATTERNS.has(node.callee.name)){hasExternalCalls=true}}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const property=node.callee.property;if(property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&EXTERNAL_CALL_PATTERNS.has(property.name)){hasExternalCalls=true}}if(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==="Promise"&&node.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.property.name==="race"){hasTimeoutCheck=true}}}}});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.fileIsLambda=fileIsLambda;const eslint_devkit_1=require("@interlace/eslint-devkit");const AWS_PACKAGES=new Set(["aws-lambda","aws-sdk","aws-xray-sdk","aws-xray-sdk-core","serverless","@aws-lambda-powertools/logger","@aws-lambda-powertools/tracer","@aws-lambda-powertools/metrics"]);const AWS_PREFIXES=["@aws-sdk/","@middy/","serverless-","@aws-lambda-powertools/"];const HANDLER_PARAMS=["event","context","callback"];function normalizeSpecifier(specifier){if(specifier.startsWith("npm:"))return specifier.slice(4);const deno=/^https?:\/\/deno\.land\/x\/([^@/]+)/.exec(specifier);if(deno)return deno[1];return specifier}function isAwsSpecifier(specifier){specifier=normalizeSpecifier(specifier);if(specifier.startsWith(".")||specifier.startsWith("/"))return false;if(AWS_PACKAGES.has(specifier))return true;const parts=specifier.split("/");const root=specifier.startsWith("@")?parts.slice(0,2).join("/"):parts[0];if(AWS_PACKAGES.has(root))return true;return AWS_PREFIXES.some(prefix=>specifier.startsWith(prefix))}function isImportEqualsLoad(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.TSImportEqualsDeclaration&&node.moduleReference.type===eslint_devkit_1.AST_NODE_TYPES.TSExternalModuleReference&&node.moduleReference.expression.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.moduleReference.expression.value==="string"&&isAwsSpecifier(node.moduleReference.expression.value)}function isAwsDynamicLoad(node,requireIsShadowed){const argument=node.type===eslint_devkit_1.AST_NODE_TYPES.ImportExpression?node.source:!requireIsShadowed&&node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="require"?node.arguments[0]:void 0;return argument?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof argument.value==="string"&&isAwsSpecifier(argument.value)}function namesHandler(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return node.name==="handler";if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.property.name==="handler"}return false}function declaresHandler(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&namesHandler(node.left)){return true}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ExportNamedDeclaration){if(node.specifiers.some(s=>namesHandler(s.exported)))return true;const decl=node.declaration;if(decl?.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration&&decl.id){return decl.id.name==="handler"}if(decl?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclaration){return decl.declarations.some(d=>d.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&d.id.name==="handler")}}return false}function hasHandlerSignature(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration&&node.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression&&node.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression){return false}const params=node.params;if(params.length<2)return false;return HANDLER_PARAMS.slice(0,params.length).every((expected,i)=>params[i].type===eslint_devkit_1.AST_NODE_TYPES.Identifier&¶ms[i].name===expected)}function bindsRequire(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||node.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||node.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression){return node.params.some(p=>p.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&p.name==="require")}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Program||node.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){return node.body.some(stmt=>stmt.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclaration&&stmt.declarations.some(d=>d.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&d.id.name==="require"))}return false}const cache=new WeakMap;function fileIsLambda(ast){const cached=cache.get(ast);if(cached!==void 0)return cached;const result=computeIsLambda(ast);cache.set(ast,result);return result}function computeIsLambda(ast){let found=false;const visit=(node,requireIsShadowed)=>{if((node.type===eslint_devkit_1.AST_NODE_TYPES.ImportDeclaration||node.type===eslint_devkit_1.AST_NODE_TYPES.ExportNamedDeclaration||node.type===eslint_devkit_1.AST_NODE_TYPES.ExportAllDeclaration)&&node.source?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.source.value==="string"&&isAwsSpecifier(node.source.value)){found=true;return}if(isImportEqualsLoad(node)||isAwsDynamicLoad(node,requireIsShadowed)||declaresHandler(node)||hasHandlerSignature(node)){found=true;return}const shadowedHere=requireIsShadowed||bindsRequire(node);for(const key of Object.keys(node)){if(key==="parent")continue;const value=node[key];if(Array.isArray(value)){for(const child of value){if(child&&typeof child.type==="string"){visit(child,shadowedHere);if(found)return}}}else if(value&&typeof value==="object"&&typeof value.type==="string"){visit(value,shadowedHere);if(found)return}}};visit(ast,false);return found}
|