eslint-plugin-lambda-security 1.0.1 → 1.0.3

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