eslint-plugin-lambda-security 1.0.4 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +100 -248
  3. package/package.json +3 -12
  4. package/src/index.d.ts +58 -20
  5. package/src/index.js +70 -3
  6. package/src/rules/no-env-logging/index.d.ts +17 -1
  7. package/src/rules/no-env-logging/index.js +5 -0
  8. package/src/rules/no-error-swallowing/index.d.ts +24 -0
  9. package/src/rules/no-error-swallowing/index.js +197 -0
  10. package/src/rules/no-exposed-error-details/index.d.ts +22 -0
  11. package/src/rules/no-exposed-error-details/index.js +161 -0
  12. package/src/rules/no-hardcoded-credentials-sdk/index.d.ts +18 -1
  13. package/src/rules/no-hardcoded-credentials-sdk/index.js +5 -0
  14. package/src/rules/no-missing-authorization-check/index.d.ts +24 -0
  15. package/src/rules/no-missing-authorization-check/index.js +220 -0
  16. package/src/rules/no-overly-permissive-iam-policy/index.d.ts +22 -0
  17. package/src/rules/no-overly-permissive-iam-policy/index.js +139 -0
  18. package/src/rules/no-permissive-cors-middy/index.d.ts +18 -1
  19. package/src/rules/no-permissive-cors-middy/index.js +5 -0
  20. package/src/rules/no-permissive-cors-response/index.d.ts +18 -1
  21. package/src/rules/no-permissive-cors-response/index.js +5 -0
  22. package/src/rules/no-secrets-in-env/index.d.ts +18 -1
  23. package/src/rules/no-secrets-in-env/index.js +5 -0
  24. package/src/rules/no-unbounded-batch-processing/index.d.ts +24 -0
  25. package/src/rules/no-unbounded-batch-processing/index.js +170 -0
  26. package/src/rules/no-unvalidated-event-body/index.d.ts +24 -0
  27. package/src/rules/no-unvalidated-event-body/index.js +270 -0
  28. package/src/rules/no-user-controlled-requests/index.d.ts +22 -0
  29. package/src/rules/no-user-controlled-requests/index.js +267 -0
  30. package/src/rules/require-timeout-handling/index.d.ts +22 -0
  31. package/src/rules/require-timeout-handling/index.js +171 -0
@@ -0,0 +1,170 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) 2025 Ofri Peretz
4
+ * Licensed under the MIT License. Use of this source code is governed by the
5
+ * MIT license that can be found in the LICENSE file.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.noUnboundedBatchProcessing = void 0;
9
+ const eslint_devkit_1 = require("@interlace/eslint-devkit");
10
+ // Event sources with Records array
11
+ const BATCH_SOURCE_PROPERTIES = [
12
+ 'Records', // SQS, SNS, DynamoDB Streams, Kinesis, S3
13
+ 'records', // Some custom structures
14
+ 'items', // Custom batches
15
+ 'messages', // Custom message batches
16
+ ];
17
+ // Event parameter names
18
+ const EVENT_PARAM_NAMES = ['event', 'evt', 'e', 'request', 'req'];
19
+ exports.noUnboundedBatchProcessing = (0, eslint_devkit_1.createRule)({
20
+ name: 'no-unbounded-batch-processing',
21
+ meta: {
22
+ type: 'problem',
23
+ docs: {
24
+ description: 'Detects processing batch records without size validation',
25
+ },
26
+ hasSuggestions: true,
27
+ messages: {
28
+ unboundedBatch: (0, eslint_devkit_1.formatLLMMessage)({
29
+ icon: eslint_devkit_1.MessageIcons.WARNING,
30
+ issueName: 'Unbounded Batch Processing',
31
+ cwe: 'CWE-770',
32
+ cvss: 5.5,
33
+ description: 'Processing {{source}} without size check. Large batches may cause timeout or memory exhaustion.',
34
+ severity: 'MEDIUM',
35
+ fix: 'Validate batch size before processing: if (event.Records.length > MAX_BATCH) throw new Error("Batch too large")',
36
+ documentationLink: 'https://docs.aws.amazon.com/lambda/latest/dg/with-sqs.html',
37
+ }),
38
+ addBatchLimit: (0, eslint_devkit_1.formatLLMMessage)({
39
+ icon: eslint_devkit_1.MessageIcons.INFO,
40
+ issueName: 'Add Batch Size Limit',
41
+ description: 'Add a maximum batch size check before processing',
42
+ severity: 'LOW',
43
+ fix: 'const MAX_BATCH_SIZE = 10; const records = event.Records.slice(0, MAX_BATCH_SIZE);',
44
+ documentationLink: 'https://docs.aws.amazon.com/lambda/latest/dg/with-sqs.html',
45
+ }),
46
+ },
47
+ schema: [
48
+ {
49
+ type: 'object',
50
+ properties: {
51
+ allowInTests: {
52
+ type: 'boolean',
53
+ default: true,
54
+ },
55
+ maxBatchSize: {
56
+ type: 'number',
57
+ default: 100,
58
+ },
59
+ },
60
+ additionalProperties: false,
61
+ },
62
+ ],
63
+ },
64
+ defaultOptions: [{ allowInTests: true, maxBatchSize: 100 }],
65
+ create(context, [options = {}]) {
66
+ const { allowInTests = true } = options;
67
+ const filename = context.filename || context.getFilename();
68
+ const isTestFile = /\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);
69
+ if (allowInTests && isTestFile) {
70
+ return {};
71
+ }
72
+ // Track handler functions
73
+ let currentHandlerNode = null;
74
+ let hasBatchSizeCheck = false;
75
+ const batchAccessNodes = [];
76
+ const eventParamName = [];
77
+ function enterFunction(node) {
78
+ const hasEvent = node.params.some((p) => {
79
+ if (p.type === eslint_devkit_1.AST_NODE_TYPES.Identifier &&
80
+ EVENT_PARAM_NAMES.includes(p.name)) {
81
+ eventParamName.push(p.name);
82
+ return true;
83
+ }
84
+ return false;
85
+ });
86
+ if (hasEvent) {
87
+ currentHandlerNode = node;
88
+ hasBatchSizeCheck = false;
89
+ batchAccessNodes.length = 0;
90
+ }
91
+ }
92
+ function exitFunction(node) {
93
+ if (currentHandlerNode !== node)
94
+ return;
95
+ // Report if batch is processed without size check
96
+ if (!hasBatchSizeCheck) {
97
+ for (const { node: batchNode, source } of batchAccessNodes) {
98
+ context.report({
99
+ node: batchNode,
100
+ messageId: 'unboundedBatch',
101
+ data: { source },
102
+ suggest: [
103
+ {
104
+ messageId: 'addBatchLimit',
105
+ fix: () => null,
106
+ },
107
+ ],
108
+ });
109
+ }
110
+ }
111
+ currentHandlerNode = null;
112
+ eventParamName.length = 0;
113
+ }
114
+ return {
115
+ 'ArrowFunctionExpression, FunctionExpression, FunctionDeclaration'(node) {
116
+ enterFunction(node);
117
+ },
118
+ 'ArrowFunctionExpression:exit, FunctionExpression:exit, FunctionDeclaration:exit'(node) {
119
+ exitFunction(node);
120
+ },
121
+ // Detect event.Records access
122
+ MemberExpression(node) {
123
+ if (!currentHandlerNode)
124
+ return;
125
+ // event.Records
126
+ if (node.object.type === eslint_devkit_1.AST_NODE_TYPES.Identifier &&
127
+ eventParamName.includes(node.object.name) &&
128
+ node.property.type === eslint_devkit_1.AST_NODE_TYPES.Identifier &&
129
+ BATCH_SOURCE_PROPERTIES.includes(node.property.name)) {
130
+ batchAccessNodes.push({
131
+ node,
132
+ source: `${node.object.name}.${node.property.name}`,
133
+ });
134
+ }
135
+ // Check for .length access (indicates size check)
136
+ if (node.property.type === eslint_devkit_1.AST_NODE_TYPES.Identifier &&
137
+ node.property.name === 'length') {
138
+ // Check if this is Records.length
139
+ if (node.object.type === eslint_devkit_1.AST_NODE_TYPES.MemberExpression &&
140
+ node.object.property.type === eslint_devkit_1.AST_NODE_TYPES.Identifier &&
141
+ BATCH_SOURCE_PROPERTIES.includes(node.object.property.name)) {
142
+ hasBatchSizeCheck = true;
143
+ }
144
+ }
145
+ },
146
+ // Detect slice/splice (limiting)
147
+ CallExpression(node) {
148
+ if (!currentHandlerNode)
149
+ return;
150
+ if (node.callee.type === eslint_devkit_1.AST_NODE_TYPES.MemberExpression &&
151
+ node.callee.property.type === eslint_devkit_1.AST_NODE_TYPES.Identifier &&
152
+ ['slice', 'splice', 'take', 'chunk'].includes(node.callee.property.name)) {
153
+ hasBatchSizeCheck = true;
154
+ }
155
+ },
156
+ // Detect size comparisons
157
+ BinaryExpression(node) {
158
+ if (!currentHandlerNode)
159
+ return;
160
+ if (['<', '<=', '>', '>='].includes(node.operator)) {
161
+ const sourceCode = context.sourceCode || context.getSourceCode();
162
+ const text = sourceCode.getText(node);
163
+ if (/\.length|Records|records/.test(text)) {
164
+ hasBatchSizeCheck = true;
165
+ }
166
+ }
167
+ },
168
+ };
169
+ },
170
+ });
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Copyright (c) 2025 Ofri Peretz
3
+ * Licensed under the MIT License. Use of this source code is governed by the
4
+ * MIT license that can be found in the LICENSE file.
5
+ */
6
+ /**
7
+ * ESLint Rule: no-unvalidated-event-body
8
+ * Detects Lambda handlers using event body/params without validation
9
+ * CWE-20: Improper Input Validation
10
+ *
11
+ * @see https://cwe.mitre.org/data/definitions/20.html
12
+ * @see https://owasp.org/www-project-serverless-top-10/
13
+ */
14
+ import type { TSESLint } from '@interlace/eslint-devkit';
15
+ type MessageIds = 'unvalidatedInput' | 'useValidation';
16
+ export interface Options {
17
+ /** Allow in test files. Default: true */
18
+ allowInTests?: boolean;
19
+ /** Additional event properties to check. Default: [] */
20
+ additionalProperties?: string[];
21
+ }
22
+ type RuleOptions = [Options?];
23
+ export declare const noUnvalidatedEventBody: TSESLint.RuleModule<MessageIds, RuleOptions, unknown, TSESLint.RuleListener>;
24
+ export {};
@@ -0,0 +1,270 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) 2025 Ofri Peretz
4
+ * Licensed under the MIT License. Use of this source code is governed by the
5
+ * MIT license that can be found in the LICENSE file.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.noUnvalidatedEventBody = void 0;
9
+ const eslint_devkit_1 = require("@interlace/eslint-devkit");
10
+ // Properties on 'event' that contain untrusted user input
11
+ const DANGEROUS_EVENT_PROPERTIES = [
12
+ 'body',
13
+ 'queryStringParameters',
14
+ 'pathParameters',
15
+ 'multiValueQueryStringParameters',
16
+ 'headers',
17
+ 'multiValueHeaders',
18
+ 'rawPath',
19
+ 'rawQueryString',
20
+ ];
21
+ // Property accesses that indicate validation
22
+ const VALIDATION_INDICATORS = [
23
+ // Middy validators
24
+ 'validator',
25
+ 'httpJsonBodyParser',
26
+ '@middy/validator',
27
+ // Schema libraries
28
+ 'parse', // zod.parse()
29
+ 'validate', // joi.validate(), yup.validate()
30
+ 'parseAsync', // zod.parseAsync()
31
+ 'safeParse',
32
+ 'safeParseAsync',
33
+ 'assert', // superstruct.assert()
34
+ 'is', // superstruct.is()
35
+ ];
36
+ exports.noUnvalidatedEventBody = (0, eslint_devkit_1.createRule)({
37
+ name: 'no-unvalidated-event-body',
38
+ meta: {
39
+ type: 'problem',
40
+ docs: {
41
+ description: 'Detects Lambda handlers using event body/params without validation',
42
+ },
43
+ hasSuggestions: true,
44
+ messages: {
45
+ unvalidatedInput: (0, eslint_devkit_1.formatLLMMessage)({
46
+ icon: eslint_devkit_1.MessageIcons.SECURITY,
47
+ issueName: 'Unvalidated Event Input',
48
+ cwe: 'CWE-20',
49
+ cvss: 8.0,
50
+ description: 'Lambda handler uses {{property}} without validation. This can lead to injection attacks.',
51
+ severity: 'HIGH',
52
+ fix: 'Validate event input using Middy validator, Zod, or Joi before use',
53
+ documentationLink: 'https://owasp.org/www-project-serverless-top-10/',
54
+ }),
55
+ useValidation: (0, eslint_devkit_1.formatLLMMessage)({
56
+ icon: eslint_devkit_1.MessageIcons.INFO,
57
+ issueName: 'Add Input Validation',
58
+ description: 'Add input validation using Middy validator middleware or a schema library',
59
+ severity: 'LOW',
60
+ fix: "import { validator } from '@middy/validator'; middy(handler).use(validator({ inputSchema }))",
61
+ documentationLink: 'https://middy.js.org/docs/middlewares/validator',
62
+ }),
63
+ },
64
+ schema: [
65
+ {
66
+ type: 'object',
67
+ properties: {
68
+ allowInTests: {
69
+ type: 'boolean',
70
+ default: true,
71
+ description: 'Allow unvalidated input in test files',
72
+ },
73
+ additionalProperties: {
74
+ type: 'array',
75
+ items: { type: 'string' },
76
+ default: [],
77
+ description: 'Additional event properties to check',
78
+ },
79
+ },
80
+ additionalProperties: false,
81
+ },
82
+ ],
83
+ },
84
+ defaultOptions: [
85
+ {
86
+ allowInTests: true,
87
+ additionalProperties: [],
88
+ },
89
+ ],
90
+ create(context, [options = {}]) {
91
+ const { allowInTests = true, additionalProperties = [] } = options;
92
+ const filename = context.filename || context.getFilename();
93
+ const isTestFile = /\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);
94
+ if (allowInTests && isTestFile) {
95
+ return {};
96
+ }
97
+ const dangerousProperties = [
98
+ ...DANGEROUS_EVENT_PROPERTIES,
99
+ ...additionalProperties,
100
+ ];
101
+ // Track which variables have been validated
102
+ const validatedVariables = new Set();
103
+ // Track which event parameters we're monitoring
104
+ const eventParameters = new Set();
105
+ // Track if we're inside a handler that uses validation middleware
106
+ let hasValidationMiddleware = false;
107
+ /**
108
+ * Check if an expression indicates validation has occurred
109
+ */
110
+ function isValidationCall(node) {
111
+ if (node.type === eslint_devkit_1.AST_NODE_TYPES.CallExpression) {
112
+ // Check for schema.parse(x), schema.validate(x), etc.
113
+ if (node.callee.type === eslint_devkit_1.AST_NODE_TYPES.MemberExpression) {
114
+ const property = node.callee.property;
115
+ if (property.type === eslint_devkit_1.AST_NODE_TYPES.Identifier &&
116
+ VALIDATION_INDICATORS.includes(property.name)) {
117
+ return true;
118
+ }
119
+ }
120
+ // Check for direct function calls like validate(x)
121
+ if (node.callee.type === eslint_devkit_1.AST_NODE_TYPES.Identifier) {
122
+ if (VALIDATION_INDICATORS.includes(node.callee.name)) {
123
+ return true;
124
+ }
125
+ }
126
+ }
127
+ return false;
128
+ }
129
+ /**
130
+ * Check if this is an event parameter access (e.g., event.body)
131
+ */
132
+ function isEventPropertyAccess(node) {
133
+ if (node.object.type === eslint_devkit_1.AST_NODE_TYPES.Identifier &&
134
+ eventParameters.has(node.object.name) &&
135
+ node.property.type === eslint_devkit_1.AST_NODE_TYPES.Identifier &&
136
+ dangerousProperties.includes(node.property.name)) {
137
+ return {
138
+ eventName: node.object.name,
139
+ property: node.property.name,
140
+ };
141
+ }
142
+ return null;
143
+ }
144
+ /**
145
+ * Check if JSON.parse is being called on event property
146
+ */
147
+ function isJsonParseOfEventBody(node) {
148
+ if (node.callee.type === eslint_devkit_1.AST_NODE_TYPES.MemberExpression &&
149
+ node.callee.object.type === eslint_devkit_1.AST_NODE_TYPES.Identifier &&
150
+ node.callee.object.name === 'JSON' &&
151
+ node.callee.property.type === eslint_devkit_1.AST_NODE_TYPES.Identifier &&
152
+ node.callee.property.name === 'parse' &&
153
+ node.arguments.length > 0) {
154
+ const arg = node.arguments[0];
155
+ if (arg.type === eslint_devkit_1.AST_NODE_TYPES.MemberExpression) {
156
+ return isEventPropertyAccess(arg) !== null;
157
+ }
158
+ }
159
+ return false;
160
+ }
161
+ return {
162
+ // Track arrow function/function parameters named 'event'
163
+ 'ArrowFunctionExpression, FunctionExpression, FunctionDeclaration'(node) {
164
+ for (const param of node.params) {
165
+ if (param.type === eslint_devkit_1.AST_NODE_TYPES.Identifier) {
166
+ // Common Lambda handler parameter names
167
+ if (['event', 'evt', 'e', 'request', 'req'].includes(param.name)) {
168
+ eventParameters.add(param.name);
169
+ }
170
+ }
171
+ }
172
+ },
173
+ // Check for Middy with validation middleware
174
+ CallExpression(node) {
175
+ // Check for middy().use(validator(...))
176
+ if (node.callee.type === eslint_devkit_1.AST_NODE_TYPES.MemberExpression &&
177
+ node.callee.property.type === eslint_devkit_1.AST_NODE_TYPES.Identifier &&
178
+ node.callee.property.name === 'use') {
179
+ // Check if argument is validator call
180
+ for (const arg of node.arguments) {
181
+ if (arg.type === eslint_devkit_1.AST_NODE_TYPES.CallExpression &&
182
+ arg.callee.type === eslint_devkit_1.AST_NODE_TYPES.Identifier &&
183
+ ['validator', 'httpJsonBodyParser'].includes(arg.callee.name)) {
184
+ hasValidationMiddleware = true;
185
+ }
186
+ }
187
+ }
188
+ // Track validation calls that assign to variables
189
+ if (isValidationCall(node)) {
190
+ // If this is part of a variable assignment, mark that variable as validated
191
+ const parent = node.parent;
192
+ if (parent?.type === eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator &&
193
+ parent.id.type === eslint_devkit_1.AST_NODE_TYPES.Identifier) {
194
+ validatedVariables.add(parent.id.name);
195
+ }
196
+ }
197
+ },
198
+ // Check direct access to event properties without validation
199
+ MemberExpression(node) {
200
+ // Skip if validation middleware is present
201
+ if (hasValidationMiddleware)
202
+ return;
203
+ const eventAccess = isEventPropertyAccess(node);
204
+ if (!eventAccess)
205
+ return;
206
+ // Check if this is being validated
207
+ const parent = node.parent;
208
+ // Case: const data = schema.parse(event.body) - this is OK
209
+ if (parent?.type === eslint_devkit_1.AST_NODE_TYPES.CallExpression &&
210
+ isValidationCall(parent)) {
211
+ return;
212
+ }
213
+ // Case: const body = JSON.parse(event.body); schema.parse(body); - track this
214
+ if (parent?.type === eslint_devkit_1.AST_NODE_TYPES.CallExpression &&
215
+ isJsonParseOfEventBody(parent)) {
216
+ // We need to check if this variable is later validated
217
+ // For now, flag it as potentially dangerous
218
+ // A more sophisticated analysis would track variable flow
219
+ }
220
+ // Case: Direct use without validation - DANGER
221
+ // Check common safe patterns
222
+ // Safe: typeof event.body === 'string'
223
+ if (parent?.type === eslint_devkit_1.AST_NODE_TYPES.UnaryExpression &&
224
+ parent.operator === 'typeof') {
225
+ return;
226
+ }
227
+ // Safe: if (event.body) - null check
228
+ if (parent?.type === eslint_devkit_1.AST_NODE_TYPES.IfStatement ||
229
+ parent?.type === eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression) {
230
+ return;
231
+ }
232
+ // Safe: event.body?.prop - optional chain check
233
+ // If this node is event.body, and the parent is a MemberExpression with optional chaining
234
+ if (node.optional) {
235
+ return;
236
+ }
237
+ // Check if parent is using optional chaining on this node
238
+ // e.g., event.body?.name - the event.body node's parent is optional
239
+ if (parent?.type === eslint_devkit_1.AST_NODE_TYPES.MemberExpression &&
240
+ parent.optional) {
241
+ return;
242
+ }
243
+ // Also check ChainExpression wrapping
244
+ if (parent?.type === eslint_devkit_1.AST_NODE_TYPES.ChainExpression) {
245
+ return;
246
+ }
247
+ // Safe: Logging event input (detected by property access in console.log argument)
248
+ if (parent?.type === eslint_devkit_1.AST_NODE_TYPES.CallExpression &&
249
+ parent.callee.type === eslint_devkit_1.AST_NODE_TYPES.MemberExpression &&
250
+ parent.callee.object.type === eslint_devkit_1.AST_NODE_TYPES.Identifier &&
251
+ parent.callee.object.name === 'console') {
252
+ return;
253
+ }
254
+ context.report({
255
+ node,
256
+ messageId: 'unvalidatedInput',
257
+ data: {
258
+ property: `event.${eventAccess.property}`,
259
+ },
260
+ suggest: [
261
+ {
262
+ messageId: 'useValidation',
263
+ fix: () => null, // Complex fix requiring schema setup
264
+ },
265
+ ],
266
+ });
267
+ },
268
+ };
269
+ },
270
+ });
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Copyright (c) 2025 Ofri Peretz
3
+ * Licensed under the MIT License. Use of this source code is governed by the
4
+ * MIT license that can be found in the LICENSE file.
5
+ */
6
+ /**
7
+ * ESLint Rule: no-user-controlled-requests
8
+ * Detects HTTP requests with user-controlled URLs (SSRF)
9
+ * CWE-918: Server-Side Request Forgery (SSRF)
10
+ *
11
+ * @see https://cwe.mitre.org/data/definitions/918.html
12
+ * @see https://owasp.org/www-community/attacks/Server_Side_Request_Forgery
13
+ */
14
+ import type { TSESLint } from '@interlace/eslint-devkit';
15
+ type MessageIds = 'ssrfVulnerability' | 'useAllowlist';
16
+ export interface Options {
17
+ /** Allow in test files. Default: true */
18
+ allowInTests?: boolean;
19
+ }
20
+ type RuleOptions = [Options?];
21
+ export declare const noUserControlledRequests: TSESLint.RuleModule<MessageIds, RuleOptions, unknown, TSESLint.RuleListener>;
22
+ export {};