@berthojoris/mcp-mysql-server 1.43.2 → 1.44.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/CHANGELOG.md +57 -6
- package/DOCUMENTATIONS.md +40 -38
- package/README.md +26 -7
- package/bin/mcp-mysql.js +168 -168
- package/dist/cache/queryCache.js +1 -1
- package/dist/config/config.js +2 -1
- package/dist/config/featureConfig.d.ts +5 -0
- package/dist/config/featureConfig.js +26 -12
- package/dist/db/connection.d.ts +8 -1
- package/dist/db/connection.js +19 -14
- package/dist/index.js +0 -10
- package/dist/mcp-server.js +45 -305
- package/dist/security/securityLayer.d.ts +33 -5
- package/dist/security/securityLayer.js +211 -58
- package/dist/tools/aiTools.js +1 -1
- package/dist/tools/dataExportTools.js +8 -0
- package/dist/tools/queryTools.d.ts +1 -1
- package/dist/tools/queryTools.js +6 -7
- package/dist/tools/toolArgumentValidation.js +22 -22
- package/dist/tools/toolRegistry.d.ts +1 -1
- package/dist/tools/toolRegistry.js +7 -1
- package/dist/tools/transactionTools.js +1 -1
- package/manifest.json +5 -5
- package/package.json +86 -78
- package/dist/auth/authService.d.ts +0 -29
- package/dist/auth/authService.js +0 -114
- package/dist/tools/backupRestoreTools.d.ts +0 -18
- package/dist/tools/backupRestoreTools.js +0 -70
- package/dist/tools/documentationGeneratorTools.d.ts +0 -145
- package/dist/tools/documentationGeneratorTools.js +0 -820
- package/dist/tools/forecastingTools.d.ts +0 -36
- package/dist/tools/forecastingTools.js +0 -256
- package/dist/tools/functionTools.d.ts +0 -87
- package/dist/tools/functionTools.js +0 -358
- package/dist/tools/indexRecommendationTools.d.ts +0 -50
- package/dist/tools/indexRecommendationTools.js +0 -451
- package/dist/tools/intelligentQueryTools.d.ts +0 -94
- package/dist/tools/intelligentQueryTools.js +0 -713
- package/dist/tools/performanceTools.d.ts +0 -76
- package/dist/tools/performanceTools.js +0 -505
- package/dist/tools/processTools.d.ts +0 -61
- package/dist/tools/processTools.js +0 -181
- package/dist/tools/queryVisualizationTools.d.ts +0 -22
- package/dist/tools/queryVisualizationTools.js +0 -155
- package/dist/tools/schemaDesignTools.d.ts +0 -67
- package/dist/tools/schemaDesignTools.js +0 -359
- package/dist/tools/schemaPatternTools.d.ts +0 -19
- package/dist/tools/schemaPatternTools.js +0 -253
- package/dist/tools/schemaVersioningTools.d.ts +0 -138
- package/dist/tools/schemaVersioningTools.js +0 -1008
- package/dist/tools/securityAuditTools.d.ts +0 -39
- package/dist/tools/securityAuditTools.js +0 -319
- package/dist/tools/smartDiscoveryTools.d.ts +0 -163
- package/dist/tools/smartDiscoveryTools.js +0 -750
- package/dist/tools/testDataTools.d.ts +0 -26
- package/dist/tools/testDataTools.js +0 -325
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { FeatureConfig } from "../config/featureConfig
|
|
2
|
-
import { MaskingLayer } from "./maskingLayer
|
|
1
|
+
import { FeatureConfig } from "../config/featureConfig";
|
|
2
|
+
import { MaskingLayer } from "./maskingLayer";
|
|
3
3
|
export declare class SecurityLayer {
|
|
4
4
|
private ajv;
|
|
5
5
|
private readonly dangerousKeywords;
|
|
@@ -14,8 +14,17 @@ export declare class SecurityLayer {
|
|
|
14
14
|
isToolEnabled(toolName: string): boolean;
|
|
15
15
|
/**
|
|
16
16
|
* Check if a query is a read-only information query (SHOW, DESCRIBE, EXPLAIN, etc.)
|
|
17
|
+
* Note: EXPLAIN ANALYZE is handled separately by validateQuery because MySQL
|
|
18
|
+
* executes the wrapped statement, so it is authorized as the inner statement type.
|
|
17
19
|
*/
|
|
18
20
|
private isInformationQuery;
|
|
21
|
+
/**
|
|
22
|
+
* Authorize the SQL operation separately from the enclosing tool.
|
|
23
|
+
*/
|
|
24
|
+
validateQueryPermissions(queryType: string): {
|
|
25
|
+
valid: boolean;
|
|
26
|
+
error?: string;
|
|
27
|
+
};
|
|
19
28
|
/**
|
|
20
29
|
* Validate input against a JSON schema
|
|
21
30
|
*/
|
|
@@ -33,13 +42,32 @@ export declare class SecurityLayer {
|
|
|
33
42
|
/**
|
|
34
43
|
* Enhanced SQL query validation for security issues
|
|
35
44
|
* @param query - The SQL query to validate
|
|
36
|
-
* @param
|
|
45
|
+
* @param allowAdvancedQueries - Allows advanced SELECT features, never dangerous operations
|
|
37
46
|
*/
|
|
38
|
-
validateQuery(query: string,
|
|
47
|
+
validateQuery(query: string, allowAdvancedQueries?: boolean): {
|
|
39
48
|
valid: boolean;
|
|
40
49
|
error?: string;
|
|
41
50
|
queryType?: string;
|
|
42
51
|
};
|
|
52
|
+
/**
|
|
53
|
+
* Blank out the contents of string literals and quoted identifiers so that
|
|
54
|
+
* comment, statement-separator, and keyword checks only see SQL syntax.
|
|
55
|
+
* Strings become '' and identifiers become `` (or their bare content when
|
|
56
|
+
* keepIdentifiers is set). Returns null when the query cannot be lexed
|
|
57
|
+
* unambiguously: an unterminated quote, or a backslash inside a literal,
|
|
58
|
+
* whose meaning depends on the NO_BACKSLASH_ESCAPES sql_mode.
|
|
59
|
+
*/
|
|
60
|
+
private maskQuotedContent;
|
|
61
|
+
/**
|
|
62
|
+
* Return the main statement that follows the CTE definitions of a WITH
|
|
63
|
+
* clause, the statement itself when it has no WITH clause, or null when the
|
|
64
|
+
* WITH clause cannot be parsed.
|
|
65
|
+
*/
|
|
66
|
+
private resolveCteMainStatement;
|
|
67
|
+
/**
|
|
68
|
+
* Index of the parenthesis closing the one at position 0, or -1 if unbalanced.
|
|
69
|
+
*/
|
|
70
|
+
private findClosingParen;
|
|
43
71
|
/**
|
|
44
72
|
* Enhanced comment detection to prevent bypass techniques
|
|
45
73
|
*/
|
|
@@ -71,7 +99,7 @@ export declare class SecurityLayer {
|
|
|
71
99
|
/**
|
|
72
100
|
* Check if a query is a read-only SELECT query or information query (SHOW, DESCRIBE, etc.)
|
|
73
101
|
*/
|
|
74
|
-
isReadOnlyQuery(query: string,
|
|
102
|
+
isReadOnlyQuery(query: string, allowAdvancedQueries?: boolean): boolean;
|
|
75
103
|
/**
|
|
76
104
|
* Check if a query contains dangerous operations
|
|
77
105
|
*/
|
|
@@ -5,14 +5,14 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.SecurityLayer = void 0;
|
|
7
7
|
const ajv_1 = __importDefault(require("ajv"));
|
|
8
|
-
const
|
|
9
|
-
const
|
|
8
|
+
const featureConfig_1 = require("../config/featureConfig");
|
|
9
|
+
const maskingLayer_1 = require("./maskingLayer");
|
|
10
10
|
class SecurityLayer {
|
|
11
11
|
constructor(featureConfig) {
|
|
12
12
|
this.ajv = new ajv_1.default();
|
|
13
|
-
this.featureConfig = featureConfig || new
|
|
13
|
+
this.featureConfig = featureConfig || new featureConfig_1.FeatureConfig();
|
|
14
14
|
// Masking is intentionally not configurable via environment variables.
|
|
15
|
-
this.masking = new
|
|
15
|
+
this.masking = new maskingLayer_1.MaskingLayer("none");
|
|
16
16
|
// Define dangerous SQL keywords that should ALWAYS be blocked (critical security threats)
|
|
17
17
|
// These are blocked even with 'execute' permission
|
|
18
18
|
// Note: Avoid blocking common table/column names like "user" or "password"
|
|
@@ -45,11 +45,39 @@ class SecurityLayer {
|
|
|
45
45
|
}
|
|
46
46
|
/**
|
|
47
47
|
* Check if a query is a read-only information query (SHOW, DESCRIBE, EXPLAIN, etc.)
|
|
48
|
+
* Note: EXPLAIN ANALYZE is handled separately by validateQuery because MySQL
|
|
49
|
+
* executes the wrapped statement, so it is authorized as the inner statement type.
|
|
48
50
|
*/
|
|
49
51
|
isInformationQuery(query) {
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
52
|
+
return /^(SHOW|DESCRIBE|DESC|EXPLAIN|HELP)\b/i.test(query.trim());
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Authorize the SQL operation separately from the enclosing tool.
|
|
56
|
+
*/
|
|
57
|
+
validateQueryPermissions(queryType) {
|
|
58
|
+
if (this.ddlOperations.includes(queryType)) {
|
|
59
|
+
return this.featureConfig.isToolEnabled("executeDdl")
|
|
60
|
+
? { valid: true }
|
|
61
|
+
: { valid: false, error: this.featureConfig.getPermissionError("executeDdl") };
|
|
62
|
+
}
|
|
63
|
+
const requiredPermissions = {
|
|
64
|
+
SELECT: [featureConfig_1.ToolCategory.READ],
|
|
65
|
+
INSERT: [featureConfig_1.ToolCategory.CREATE, featureConfig_1.ToolCategory.EXECUTE],
|
|
66
|
+
UPDATE: [featureConfig_1.ToolCategory.UPDATE, featureConfig_1.ToolCategory.EXECUTE],
|
|
67
|
+
DELETE: [featureConfig_1.ToolCategory.DELETE],
|
|
68
|
+
INFORMATION: [featureConfig_1.ToolCategory.LIST, featureConfig_1.ToolCategory.READ],
|
|
69
|
+
};
|
|
70
|
+
const permissions = requiredPermissions[queryType];
|
|
71
|
+
if (!permissions) {
|
|
72
|
+
return { valid: false, error: "Query type not allowed" };
|
|
73
|
+
}
|
|
74
|
+
if (!permissions.some((permission) => this.featureConfig.isCategoryEnabled(permission))) {
|
|
75
|
+
return {
|
|
76
|
+
valid: false,
|
|
77
|
+
error: `Permission denied: ${queryType} requires ${permissions.map((permission) => `'${permission}'`).join(" or ")} permission.`,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
return { valid: true };
|
|
53
81
|
}
|
|
54
82
|
/**
|
|
55
83
|
* Validate input against a JSON schema
|
|
@@ -132,9 +160,9 @@ class SecurityLayer {
|
|
|
132
160
|
/**
|
|
133
161
|
* Enhanced SQL query validation for security issues
|
|
134
162
|
* @param query - The SQL query to validate
|
|
135
|
-
* @param
|
|
163
|
+
* @param allowAdvancedQueries - Allows advanced SELECT features, never dangerous operations
|
|
136
164
|
*/
|
|
137
|
-
validateQuery(query,
|
|
165
|
+
validateQuery(query, allowAdvancedQueries = false) {
|
|
138
166
|
if (!query || typeof query !== "string") {
|
|
139
167
|
return { valid: false, error: "Query must be a non-empty string" };
|
|
140
168
|
}
|
|
@@ -155,21 +183,41 @@ class SecurityLayer {
|
|
|
155
183
|
}
|
|
156
184
|
// Remove trailing semicolon for analysis
|
|
157
185
|
const cleanQuery = trimmedQuery.replace(/;$/, "");
|
|
158
|
-
|
|
159
|
-
if (
|
|
160
|
-
return
|
|
186
|
+
const dangerousCheck = this.detectDangerousKeywords(cleanQuery, allowAdvancedQueries);
|
|
187
|
+
if (!dangerousCheck.valid) {
|
|
188
|
+
return dangerousCheck;
|
|
189
|
+
}
|
|
190
|
+
// MySQL 8.0.18+ actually executes the statement wrapped by EXPLAIN ANALYZE,
|
|
191
|
+
// including multi-table UPDATE/DELETE. Such queries are authorized as the
|
|
192
|
+
// inner statement instead of being treated as read-only information queries.
|
|
193
|
+
const explainAnalyzeMatch = cleanQuery.match(/^(?:EXPLAIN|DESCRIBE|DESC)\s+ANALYZE\s+(?:FORMAT\s*=\s*TREE\s+)?(.+)$/is);
|
|
194
|
+
// Information queries still require permission and mandatory safety checks.
|
|
195
|
+
if (!explainAnalyzeMatch && this.isInformationQuery(trimmedQuery)) {
|
|
196
|
+
const permissionCheck = this.validateQueryPermissions("INFORMATION");
|
|
197
|
+
return permissionCheck.valid
|
|
198
|
+
? { valid: true, queryType: "INFORMATION" }
|
|
199
|
+
: permissionCheck;
|
|
161
200
|
}
|
|
162
|
-
// Enhanced query type detection with better parsing
|
|
163
|
-
|
|
201
|
+
// Enhanced query type detection with better parsing.
|
|
202
|
+
// EXPLAIN ANALYZE is classified by the inner statement it executes.
|
|
203
|
+
const statement = explainAnalyzeMatch ? explainAnalyzeMatch[1].trim() : cleanQuery;
|
|
204
|
+
// A WITH clause is authorized as the main statement that follows its CTEs.
|
|
205
|
+
const mainStatement = this.resolveCteMainStatement(statement);
|
|
206
|
+
if (mainStatement === null) {
|
|
207
|
+
return { valid: false, error: "Unable to parse WITH clause. Query type not allowed" };
|
|
208
|
+
}
|
|
209
|
+
const queryTypeResult = this.detectQueryType(mainStatement);
|
|
164
210
|
if (!queryTypeResult.valid) {
|
|
165
211
|
return queryTypeResult;
|
|
166
212
|
}
|
|
167
|
-
//
|
|
168
|
-
if (!
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
}
|
|
213
|
+
// CTEs are as expressive as derived tables, which also require execute permission.
|
|
214
|
+
if (!allowAdvancedQueries && /^WITH\b/.test(statement)) {
|
|
215
|
+
return {
|
|
216
|
+
valid: false,
|
|
217
|
+
error: "Common table expressions (WITH) not allowed without 'execute' permission",
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
if (!allowAdvancedQueries) {
|
|
173
221
|
// Additional checks for specific query types
|
|
174
222
|
if (queryTypeResult.queryType === "SELECT") {
|
|
175
223
|
const selectCheck = this.validateSelectQuery(cleanQuery);
|
|
@@ -180,10 +228,128 @@ class SecurityLayer {
|
|
|
180
228
|
}
|
|
181
229
|
return { valid: true, queryType: queryTypeResult.queryType };
|
|
182
230
|
}
|
|
231
|
+
/**
|
|
232
|
+
* Blank out the contents of string literals and quoted identifiers so that
|
|
233
|
+
* comment, statement-separator, and keyword checks only see SQL syntax.
|
|
234
|
+
* Strings become '' and identifiers become `` (or their bare content when
|
|
235
|
+
* keepIdentifiers is set). Returns null when the query cannot be lexed
|
|
236
|
+
* unambiguously: an unterminated quote, or a backslash inside a literal,
|
|
237
|
+
* whose meaning depends on the NO_BACKSLASH_ESCAPES sql_mode.
|
|
238
|
+
*/
|
|
239
|
+
maskQuotedContent(query, keepIdentifiers = false) {
|
|
240
|
+
let result = "";
|
|
241
|
+
let i = 0;
|
|
242
|
+
while (i < query.length) {
|
|
243
|
+
const quote = query[i];
|
|
244
|
+
if (quote !== "'" && quote !== '"' && quote !== "`") {
|
|
245
|
+
result += quote;
|
|
246
|
+
i++;
|
|
247
|
+
continue;
|
|
248
|
+
}
|
|
249
|
+
let content = "";
|
|
250
|
+
let j = i + 1;
|
|
251
|
+
let closed = false;
|
|
252
|
+
while (j < query.length) {
|
|
253
|
+
if (query[j] === quote) {
|
|
254
|
+
// A doubled quote is an escaped quote in both sql_modes
|
|
255
|
+
if (query[j + 1] === quote) {
|
|
256
|
+
content += quote + quote;
|
|
257
|
+
j += 2;
|
|
258
|
+
continue;
|
|
259
|
+
}
|
|
260
|
+
closed = true;
|
|
261
|
+
break;
|
|
262
|
+
}
|
|
263
|
+
if (query[j] === "\\" && quote !== "`") {
|
|
264
|
+
return null;
|
|
265
|
+
}
|
|
266
|
+
content += query[j];
|
|
267
|
+
j++;
|
|
268
|
+
}
|
|
269
|
+
if (!closed) {
|
|
270
|
+
return null;
|
|
271
|
+
}
|
|
272
|
+
if (quote === "`") {
|
|
273
|
+
result += keepIdentifiers ? content : "``";
|
|
274
|
+
}
|
|
275
|
+
else {
|
|
276
|
+
result += quote + quote;
|
|
277
|
+
}
|
|
278
|
+
i = j + 1;
|
|
279
|
+
}
|
|
280
|
+
return result;
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Return the main statement that follows the CTE definitions of a WITH
|
|
284
|
+
* clause, the statement itself when it has no WITH clause, or null when the
|
|
285
|
+
* WITH clause cannot be parsed.
|
|
286
|
+
*/
|
|
287
|
+
resolveCteMainStatement(statement) {
|
|
288
|
+
if (!/^WITH\b/i.test(statement)) {
|
|
289
|
+
return statement;
|
|
290
|
+
}
|
|
291
|
+
const masked = this.maskQuotedContent(statement);
|
|
292
|
+
if (masked === null) {
|
|
293
|
+
return null;
|
|
294
|
+
}
|
|
295
|
+
let rest = masked.replace(/^WITH\s+(?:RECURSIVE\s+)?/i, "");
|
|
296
|
+
while (true) {
|
|
297
|
+
const nameMatch = rest.match(/^(?:``|[A-Z0-9_$]+)\s*/i);
|
|
298
|
+
if (!nameMatch) {
|
|
299
|
+
return null;
|
|
300
|
+
}
|
|
301
|
+
rest = rest.slice(nameMatch[0].length);
|
|
302
|
+
// Optional column list
|
|
303
|
+
if (rest.startsWith("(")) {
|
|
304
|
+
const end = this.findClosingParen(rest);
|
|
305
|
+
if (end < 0) {
|
|
306
|
+
return null;
|
|
307
|
+
}
|
|
308
|
+
rest = rest.slice(end + 1).trimStart();
|
|
309
|
+
}
|
|
310
|
+
const asMatch = rest.match(/^AS\s*/i);
|
|
311
|
+
if (!asMatch) {
|
|
312
|
+
return null;
|
|
313
|
+
}
|
|
314
|
+
rest = rest.slice(asMatch[0].length);
|
|
315
|
+
if (!rest.startsWith("(")) {
|
|
316
|
+
return null;
|
|
317
|
+
}
|
|
318
|
+
const end = this.findClosingParen(rest);
|
|
319
|
+
if (end < 0) {
|
|
320
|
+
return null;
|
|
321
|
+
}
|
|
322
|
+
rest = rest.slice(end + 1).trimStart();
|
|
323
|
+
if (!rest.startsWith(",")) {
|
|
324
|
+
return rest;
|
|
325
|
+
}
|
|
326
|
+
rest = rest.slice(1).trimStart();
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* Index of the parenthesis closing the one at position 0, or -1 if unbalanced.
|
|
331
|
+
*/
|
|
332
|
+
findClosingParen(text) {
|
|
333
|
+
let depth = 0;
|
|
334
|
+
for (let i = 0; i < text.length; i++) {
|
|
335
|
+
if (text[i] === "(") {
|
|
336
|
+
depth++;
|
|
337
|
+
}
|
|
338
|
+
else if (text[i] === ")") {
|
|
339
|
+
depth--;
|
|
340
|
+
if (depth === 0) {
|
|
341
|
+
return i;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
return -1;
|
|
346
|
+
}
|
|
183
347
|
/**
|
|
184
348
|
* Enhanced comment detection to prevent bypass techniques
|
|
185
349
|
*/
|
|
186
|
-
detectComments(
|
|
350
|
+
detectComments(rawQuery) {
|
|
351
|
+
// Quoted content is data, not syntax; fall back to the raw text if ambiguous
|
|
352
|
+
const query = this.maskQuotedContent(rawQuery) ?? rawQuery;
|
|
187
353
|
// Check for various comment types and bypass attempts
|
|
188
354
|
const commentPatterns = [
|
|
189
355
|
/\/\*[\s\S]*?\*\//g, // Multi-line comments
|
|
@@ -226,15 +392,15 @@ class SecurityLayer {
|
|
|
226
392
|
* Enhanced multiple statement detection
|
|
227
393
|
*/
|
|
228
394
|
detectMultipleStatements(query) {
|
|
229
|
-
// Remove
|
|
230
|
-
const queryWithoutStrings =
|
|
395
|
+
// Remove quoted content to avoid false positives; fall back to the raw text if ambiguous
|
|
396
|
+
const queryWithoutStrings = this.maskQuotedContent(query) ?? query;
|
|
231
397
|
// Check for multiple semicolons not at the end
|
|
232
398
|
const semicolonMatches = queryWithoutStrings.match(/;/g);
|
|
233
399
|
if (semicolonMatches && semicolonMatches.length > 1) {
|
|
234
400
|
return { valid: false, error: "Multiple statements not allowed" };
|
|
235
401
|
}
|
|
236
402
|
// Check for semicolon not at the very end (after trimming)
|
|
237
|
-
const trimmedQuery =
|
|
403
|
+
const trimmedQuery = queryWithoutStrings.trim();
|
|
238
404
|
if (trimmedQuery.includes(';') && !trimmedQuery.endsWith(';')) {
|
|
239
405
|
return { valid: false, error: "Multiple statements not allowed" };
|
|
240
406
|
}
|
|
@@ -264,23 +430,9 @@ class SecurityLayer {
|
|
|
264
430
|
];
|
|
265
431
|
for (const { type, pattern } of queryTypePatterns) {
|
|
266
432
|
if (pattern.test(cleanQuery)) {
|
|
267
|
-
|
|
268
|
-
if (
|
|
269
|
-
|
|
270
|
-
return {
|
|
271
|
-
valid: false,
|
|
272
|
-
error: `DDL operation '${type}' requires 'ddl' permission. Add 'ddl' to your permissions configuration.`,
|
|
273
|
-
};
|
|
274
|
-
}
|
|
275
|
-
}
|
|
276
|
-
// DELETE requires explicit delete permission (execute alone is not sufficient)
|
|
277
|
-
if (type === "DELETE") {
|
|
278
|
-
if (!this.featureConfig.isCategoryEnabled(featureConfig_js_1.ToolCategory.DELETE)) {
|
|
279
|
-
return {
|
|
280
|
-
valid: false,
|
|
281
|
-
error: "DELETE operation requires 'delete' permission. Add 'delete' to your permissions configuration, or use delete_record / bulk_delete.",
|
|
282
|
-
};
|
|
283
|
-
}
|
|
433
|
+
const permissionCheck = this.validateQueryPermissions(type);
|
|
434
|
+
if (!permissionCheck.valid) {
|
|
435
|
+
return permissionCheck;
|
|
284
436
|
}
|
|
285
437
|
return { valid: true, queryType: type };
|
|
286
438
|
}
|
|
@@ -290,16 +442,17 @@ class SecurityLayer {
|
|
|
290
442
|
/**
|
|
291
443
|
* Enhanced dangerous keyword detection
|
|
292
444
|
*/
|
|
293
|
-
detectDangerousKeywords(cleanQuery) {
|
|
294
|
-
// Remove string literals to avoid false positives
|
|
295
|
-
|
|
445
|
+
detectDangerousKeywords(cleanQuery, allowAdvancedQueries) {
|
|
446
|
+
// Remove string literals to avoid false positives, and unwrap quoted
|
|
447
|
+
// identifiers so `mysql`.`user` is still detected
|
|
448
|
+
const queryWithoutStrings = this.maskQuotedContent(cleanQuery, true) ?? cleanQuery.replace(/`/g, "");
|
|
296
449
|
for (const keyword of this.dangerousKeywords) {
|
|
297
450
|
// Enhanced regex with word boundaries and case insensitivity
|
|
298
451
|
const keywordRegex = new RegExp(`\\b${keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`, 'i');
|
|
299
452
|
if (keywordRegex.test(queryWithoutStrings)) {
|
|
300
453
|
return {
|
|
301
454
|
valid: false,
|
|
302
|
-
error: `Dangerous keyword detected: ${keyword}. This
|
|
455
|
+
error: `Dangerous keyword detected: ${keyword}. This operation is not allowed.`,
|
|
303
456
|
};
|
|
304
457
|
}
|
|
305
458
|
}
|
|
@@ -307,7 +460,6 @@ class SecurityLayer {
|
|
|
307
460
|
const dangerousPatterns = [
|
|
308
461
|
/\b(LOAD_FILE|INTO\s+OUTFILE|INTO\s+DUMPFILE)\b/i,
|
|
309
462
|
/\b(GRANT|REVOKE|CREATE\s+USER|DROP\s+USER|ALTER\s+USER|SET\s+PASSWORD|RENAME\s+USER)\b/i,
|
|
310
|
-
/\b(INFORMATION_SCHEMA\.|MYSQL\.|PERFORMANCE_SCHEMA\.|SYS\.)\b/i,
|
|
311
463
|
/\b(SLEEP|BENCHMARK|GET_LOCK|RELEASE_LOCK)\b/i,
|
|
312
464
|
/\b(PREPARE|EXECUTE|DEALLOCATE\s+PREPARE)\b/i,
|
|
313
465
|
/\b(LOAD\s+DATA|SELECT\s+.*\s+INTO\s+OUTFILE|SELECT\s+.*\s+INTO\s+DUMPFILE)\b/i,
|
|
@@ -320,18 +472,24 @@ class SecurityLayer {
|
|
|
320
472
|
if (pattern.test(queryWithoutStrings)) {
|
|
321
473
|
return {
|
|
322
474
|
valid: false,
|
|
323
|
-
error: "Dangerous operation detected. This
|
|
475
|
+
error: "Dangerous operation detected. This operation is not allowed.",
|
|
324
476
|
};
|
|
325
477
|
}
|
|
326
478
|
}
|
|
479
|
+
if (!allowAdvancedQueries && /\b(INFORMATION_SCHEMA\.|MYSQL\.|PERFORMANCE_SCHEMA\.|SYS\.)\b/i.test(queryWithoutStrings)) {
|
|
480
|
+
return {
|
|
481
|
+
valid: false,
|
|
482
|
+
error: "System schema queries require 'execute' permission.",
|
|
483
|
+
};
|
|
484
|
+
}
|
|
327
485
|
return { valid: true };
|
|
328
486
|
}
|
|
329
487
|
/**
|
|
330
488
|
* Enhanced SELECT query validation
|
|
331
489
|
*/
|
|
332
490
|
validateSelectQuery(cleanQuery) {
|
|
333
|
-
// Remove
|
|
334
|
-
const queryWithoutStrings =
|
|
491
|
+
// Remove quoted content to avoid false positives
|
|
492
|
+
const queryWithoutStrings = this.maskQuotedContent(cleanQuery) ?? cleanQuery;
|
|
335
493
|
// Check for UNION attacks
|
|
336
494
|
if (/\bUNION\b/i.test(queryWithoutStrings)) {
|
|
337
495
|
return {
|
|
@@ -413,14 +571,9 @@ class SecurityLayer {
|
|
|
413
571
|
/**
|
|
414
572
|
* Check if a query is a read-only SELECT query or information query (SHOW, DESCRIBE, etc.)
|
|
415
573
|
*/
|
|
416
|
-
isReadOnlyQuery(query,
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
return true;
|
|
420
|
-
}
|
|
421
|
-
// Check if it's a SELECT query
|
|
422
|
-
const validation = this.validateQuery(query, bypassDangerousCheck);
|
|
423
|
-
return validation.valid && validation.queryType === "SELECT";
|
|
574
|
+
isReadOnlyQuery(query, allowAdvancedQueries = false) {
|
|
575
|
+
const validation = this.validateQuery(query, allowAdvancedQueries);
|
|
576
|
+
return validation.valid && (validation.queryType === "SELECT" || validation.queryType === "INFORMATION");
|
|
424
577
|
}
|
|
425
578
|
/**
|
|
426
579
|
* Check if a query contains dangerous operations
|
|
@@ -433,7 +586,7 @@ class SecurityLayer {
|
|
|
433
586
|
* Check if execute permission is enabled
|
|
434
587
|
*/
|
|
435
588
|
hasExecutePermission() {
|
|
436
|
-
return this.featureConfig.isCategoryEnabled(
|
|
589
|
+
return this.featureConfig.isCategoryEnabled(featureConfig_1.ToolCategory.EXECUTE);
|
|
437
590
|
}
|
|
438
591
|
/**
|
|
439
592
|
* Escape identifier for safe use in SQL queries
|
package/dist/tools/aiTools.js
CHANGED
|
@@ -40,7 +40,7 @@ class AiTools {
|
|
|
40
40
|
// 2. Validate query generally (security check)
|
|
41
41
|
// We assume this tool is used by an agent who might have 'read' permissions at least.
|
|
42
42
|
// If the query is unsafe (e.g. injection), we return that.
|
|
43
|
-
const validation = this.security.validateQuery(query,
|
|
43
|
+
const validation = this.security.validateQuery(query, this.security.hasExecutePermission());
|
|
44
44
|
if (!validation.valid) {
|
|
45
45
|
return {
|
|
46
46
|
status: "error",
|
|
@@ -94,6 +94,10 @@ class DataExportTools {
|
|
|
94
94
|
*/
|
|
95
95
|
async exportTableToCSV(params) {
|
|
96
96
|
try {
|
|
97
|
+
const readPermission = this.security.validateQueryPermissions("SELECT");
|
|
98
|
+
if (!readPermission.valid) {
|
|
99
|
+
return { status: "error", error: readPermission.error };
|
|
100
|
+
}
|
|
97
101
|
const { table_name, filters = [], pagination, sorting, include_headers = true, } = params;
|
|
98
102
|
// Validate table name
|
|
99
103
|
const tableValidation = this.security.validateIdentifier(table_name);
|
|
@@ -224,6 +228,10 @@ class DataExportTools {
|
|
|
224
228
|
}
|
|
225
229
|
async exportQueryToCSV(queryParams) {
|
|
226
230
|
try {
|
|
231
|
+
const readPermission = this.security.validateQueryPermissions("SELECT");
|
|
232
|
+
if (!readPermission.valid) {
|
|
233
|
+
return { status: "error", error: readPermission.error };
|
|
234
|
+
}
|
|
227
235
|
const { query, params = [], include_headers = true, } = queryParams;
|
|
228
236
|
const queryValidation = this.security.validateQuery(query, this.security.hasExecutePermission());
|
|
229
237
|
if (!queryValidation.valid) {
|
|
@@ -35,7 +35,7 @@ export declare class QueryTools {
|
|
|
35
35
|
/**
|
|
36
36
|
* Execute write operations (INSERT, UPDATE) with validation.
|
|
37
37
|
* DELETE requires the separate delete permission and is validated in the security layer.
|
|
38
|
-
*
|
|
38
|
+
* DDL and information queries must use their dedicated tools.
|
|
39
39
|
*/
|
|
40
40
|
executeWriteQuery(queryParams: {
|
|
41
41
|
query: string;
|
package/dist/tools/queryTools.js
CHANGED
|
@@ -27,10 +27,10 @@ class QueryTools {
|
|
|
27
27
|
error: `Query validation failed: ${queryValidationResult.errors?.join(', ') || 'Invalid query parameters'}`,
|
|
28
28
|
};
|
|
29
29
|
}
|
|
30
|
-
//
|
|
30
|
+
// Execute permission allows advanced SELECT features, not dangerous operations.
|
|
31
31
|
const hasExecutePermission = this.security.hasExecutePermission();
|
|
32
32
|
// Validate query using security layer
|
|
33
|
-
//
|
|
33
|
+
// Mandatory safety checks apply regardless of execute permission.
|
|
34
34
|
const securityQueryValidation = this.security.validateQuery(query, hasExecutePermission);
|
|
35
35
|
if (!securityQueryValidation.valid) {
|
|
36
36
|
return {
|
|
@@ -120,7 +120,7 @@ class QueryTools {
|
|
|
120
120
|
/**
|
|
121
121
|
* Execute write operations (INSERT, UPDATE) with validation.
|
|
122
122
|
* DELETE requires the separate delete permission and is validated in the security layer.
|
|
123
|
-
*
|
|
123
|
+
* DDL and information queries must use their dedicated tools.
|
|
124
124
|
*/
|
|
125
125
|
async executeWriteQuery(queryParams) {
|
|
126
126
|
try {
|
|
@@ -134,7 +134,7 @@ class QueryTools {
|
|
|
134
134
|
};
|
|
135
135
|
}
|
|
136
136
|
// Validate query using security layer
|
|
137
|
-
//
|
|
137
|
+
// Execute permission does not bypass mandatory safety restrictions.
|
|
138
138
|
const securityQueryValidation = this.security.validateQuery(query, true);
|
|
139
139
|
if (!securityQueryValidation.valid) {
|
|
140
140
|
return {
|
|
@@ -142,11 +142,10 @@ class QueryTools {
|
|
|
142
142
|
error: `Query validation failed: ${securityQueryValidation.error}`,
|
|
143
143
|
};
|
|
144
144
|
}
|
|
145
|
-
|
|
146
|
-
if (securityQueryValidation.queryType === "SELECT") {
|
|
145
|
+
if (!["INSERT", "UPDATE", "DELETE"].includes(securityQueryValidation.queryType || "")) {
|
|
147
146
|
return {
|
|
148
147
|
status: "error",
|
|
149
|
-
error: "
|
|
148
|
+
error: "Only INSERT, UPDATE, and DELETE are allowed with execute_write_query. Use run_select_query for SELECT and execute_ddl for schema changes.",
|
|
150
149
|
};
|
|
151
150
|
}
|
|
152
151
|
// Validate parameters
|