eslint-plugin-postgresql-security 1.5.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.
Files changed (95) hide show
  1. package/CHANGELOG.md +150 -0
  2. package/LICENSE +23 -0
  3. package/README.md +169 -0
  4. package/dist/AGENTS.md +118 -0
  5. package/dist/CHANGELOG.md +150 -0
  6. package/dist/LICENSE +23 -0
  7. package/dist/README.md +169 -0
  8. package/dist/package.json +99 -0
  9. package/dist/src/constants.d.ts +6 -0
  10. package/dist/src/constants.js +13 -0
  11. package/dist/src/index.d.ts +26 -0
  12. package/dist/src/index.js +116 -0
  13. package/dist/src/oxlint.d.ts +20 -0
  14. package/dist/src/oxlint.js +21 -0
  15. package/dist/src/rules/check-query-params/index.d.ts +8 -0
  16. package/dist/src/rules/check-query-params/index.js +90 -0
  17. package/dist/src/rules/no-batch-insert-loop/index.d.ts +8 -0
  18. package/dist/src/rules/no-batch-insert-loop/index.js +90 -0
  19. package/dist/src/rules/no-floating-query/index.d.ts +8 -0
  20. package/dist/src/rules/no-floating-query/index.js +74 -0
  21. package/dist/src/rules/no-hardcoded-credentials/index.d.ts +8 -0
  22. package/dist/src/rules/no-hardcoded-credentials/index.js +86 -0
  23. package/dist/src/rules/no-insecure-ssl/index.d.ts +8 -0
  24. package/dist/src/rules/no-insecure-ssl/index.js +66 -0
  25. package/dist/src/rules/no-missing-client-release/index.d.ts +8 -0
  26. package/dist/src/rules/no-missing-client-release/index.js +85 -0
  27. package/dist/src/rules/no-select-all/index.d.ts +8 -0
  28. package/dist/src/rules/no-select-all/index.js +79 -0
  29. package/dist/src/rules/no-transaction-on-pool/index.d.ts +8 -0
  30. package/dist/src/rules/no-transaction-on-pool/index.js +71 -0
  31. package/dist/src/rules/no-unsafe-copy-from/index.d.ts +10 -0
  32. package/dist/src/rules/no-unsafe-copy-from/index.js +205 -0
  33. package/dist/src/rules/no-unsafe-query/index.d.ts +8 -0
  34. package/dist/src/rules/no-unsafe-query/index.js +132 -0
  35. package/dist/src/rules/no-unsafe-search-path/index.d.ts +8 -0
  36. package/dist/src/rules/no-unsafe-search-path/index.js +144 -0
  37. package/dist/src/rules/prefer-pool-query/index.d.ts +8 -0
  38. package/dist/src/rules/prefer-pool-query/index.js +104 -0
  39. package/dist/src/rules/prevent-double-release/index.d.ts +8 -0
  40. package/dist/src/rules/prevent-double-release/index.js +456 -0
  41. package/dist/src/types/index.d.ts +54 -0
  42. package/dist/src/types/index.js +7 -0
  43. package/package.json +99 -0
  44. package/src/__compatibility__/pg-interface.spec.ts +495 -0
  45. package/src/constants.ts +11 -0
  46. package/src/index.spec.ts +14 -0
  47. package/src/index.test.ts +59 -0
  48. package/src/index.ts +130 -0
  49. package/src/oxlint.spec.ts +70 -0
  50. package/src/oxlint.ts +23 -0
  51. package/src/rules/check-query-params/check-query-params.test.ts +68 -0
  52. package/src/rules/check-query-params/index.spec.ts +117 -0
  53. package/src/rules/check-query-params/index.ts +106 -0
  54. package/src/rules/no-batch-insert-loop/index.spec.ts +105 -0
  55. package/src/rules/no-batch-insert-loop/index.ts +105 -0
  56. package/src/rules/no-batch-insert-loop/no-batch-insert-loop.test.ts +68 -0
  57. package/src/rules/no-floating-query/index.spec.ts +112 -0
  58. package/src/rules/no-floating-query/index.ts +81 -0
  59. package/src/rules/no-floating-query/no-floating-query.test.ts +68 -0
  60. package/src/rules/no-hardcoded-credentials/index.spec.ts +38 -0
  61. package/src/rules/no-hardcoded-credentials/index.ts +93 -0
  62. package/src/rules/no-hardcoded-credentials/no-hardcoded-credentials.test.ts +68 -0
  63. package/src/rules/no-insecure-ssl/index.spec.ts +40 -0
  64. package/src/rules/no-insecure-ssl/index.ts +81 -0
  65. package/src/rules/no-insecure-ssl/no-insecure-ssl.test.ts +68 -0
  66. package/src/rules/no-missing-client-release/coverage-gaps.spec.ts +42 -0
  67. package/src/rules/no-missing-client-release/index.spec.ts +52 -0
  68. package/src/rules/no-missing-client-release/index.ts +100 -0
  69. package/src/rules/no-missing-client-release/no-missing-client-release.test.ts +68 -0
  70. package/src/rules/no-select-all/index.spec.ts +44 -0
  71. package/src/rules/no-select-all/index.ts +92 -0
  72. package/src/rules/no-select-all/no-select-all.test.ts +68 -0
  73. package/src/rules/no-transaction-on-pool/index.spec.ts +36 -0
  74. package/src/rules/no-transaction-on-pool/index.ts +85 -0
  75. package/src/rules/no-transaction-on-pool/no-transaction-on-pool.test.ts +68 -0
  76. package/src/rules/no-unsafe-copy-from/coverage-gaps.spec.ts +76 -0
  77. package/src/rules/no-unsafe-copy-from/index.spec.ts +274 -0
  78. package/src/rules/no-unsafe-copy-from/index.ts +226 -0
  79. package/src/rules/no-unsafe-copy-from/no-unsafe-copy-from.test.ts +78 -0
  80. package/src/rules/no-unsafe-query/coverage-gaps.spec.ts +61 -0
  81. package/src/rules/no-unsafe-query/index.spec.ts +103 -0
  82. package/src/rules/no-unsafe-query/index.ts +149 -0
  83. package/src/rules/no-unsafe-query/no-unsafe-query.test.ts +73 -0
  84. package/src/rules/no-unsafe-search-path/index.spec.ts +46 -0
  85. package/src/rules/no-unsafe-search-path/index.ts +164 -0
  86. package/src/rules/no-unsafe-search-path/no-unsafe-search-path.test.ts +68 -0
  87. package/src/rules/prefer-pool-query/coverage-gaps.spec.ts +76 -0
  88. package/src/rules/prefer-pool-query/index.spec.ts +97 -0
  89. package/src/rules/prefer-pool-query/index.ts +118 -0
  90. package/src/rules/prefer-pool-query/prefer-pool-query.test.ts +68 -0
  91. package/src/rules/prevent-double-release/coverage-gaps.spec.ts +538 -0
  92. package/src/rules/prevent-double-release/index.spec.ts +824 -0
  93. package/src/rules/prevent-double-release/index.ts +534 -0
  94. package/src/rules/prevent-double-release/prevent-double-release.test.ts +70 -0
  95. package/src/types/index.ts +58 -0
@@ -0,0 +1,205 @@
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.noUnsafeCopyFrom = void 0;
9
+ const eslint_devkit_1 = require("@interlace/eslint-devkit");
10
+ // Pre-compiled regex patterns for performance
11
+ const COPY_FROM_REGEX = /\bCOPY\b.*\bFROM\b/i;
12
+ const STDIN_REGEX = /\bFROM\s+STDIN\b/i;
13
+ // Extract file path from COPY FROM 'path' pattern
14
+ const FILE_PATH_REGEX = /FROM\s+['"]([^'"]+)['"]/i;
15
+ // Helper to check for COPY FROM (but not COPY FROM STDIN)
16
+ const hasCopyFrom = (str) => COPY_FROM_REGEX.test(str) && !STDIN_REGEX.test(str);
17
+ // Extract file path from COPY statement
18
+ const extractFilePath = (str) => {
19
+ const match = FILE_PATH_REGEX.exec(str);
20
+ return match ? match[1] : null;
21
+ };
22
+ exports.noUnsafeCopyFrom = {
23
+ meta: {
24
+ type: 'problem',
25
+ docs: {
26
+ description: 'Prevent unsafe COPY FROM usage with dynamic file paths, which can lead to arbitrary file read/RCE.',
27
+ url: 'https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-postgresql-security/docs/rules/no-unsafe-copy-from.md',
28
+ cwe: 'CWE-73',
29
+ cvss: 9.5,
30
+ },
31
+ messages: {
32
+ dynamicPath: (0, eslint_devkit_1.formatLLMMessage)({
33
+ icon: eslint_devkit_1.MessageIcons.SECURITY,
34
+ issueName: 'COPY FROM Injection',
35
+ description: 'Dynamic file path in COPY FROM detected - potential arbitrary file read.',
36
+ severity: 'CRITICAL',
37
+ cwe: 'CWE-73',
38
+ owasp: 'A03:2021',
39
+ compliance: ['SOC2', 'PCI-DSS'],
40
+ effort: 'low',
41
+ fix: 'Never use user input in COPY FROM paths. Use COPY FROM STDIN for user data.',
42
+ documentationLink: 'https://www.postgresql.org/docs/current/sql-copy.html',
43
+ }),
44
+ hardcodedPath: (0, eslint_devkit_1.formatLLMMessage)({
45
+ icon: eslint_devkit_1.MessageIcons.WARNING,
46
+ issueName: 'Server-side COPY FROM',
47
+ description: 'Hardcoded file path in COPY FROM - server-side file access.',
48
+ severity: 'MEDIUM',
49
+ cwe: 'CWE-73',
50
+ effort: 'low',
51
+ fix: 'Prefer COPY FROM STDIN for application code. Use allowHardcodedPaths option if this is an admin script.',
52
+ documentationLink: 'https://www.postgresql.org/docs/current/sql-copy.html',
53
+ }),
54
+ unverifiablePath: (0, eslint_devkit_1.formatLLMMessage)({
55
+ icon: eslint_devkit_1.MessageIcons.WARNING,
56
+ issueName: 'Unverifiable COPY FROM',
57
+ description: 'Cannot statically verify COPY FROM source - potential injection risk.',
58
+ severity: 'MEDIUM',
59
+ cwe: 'CWE-73',
60
+ effort: 'medium',
61
+ fix: 'Ensure the query source does not contain user input, or refactor to use COPY FROM STDIN.',
62
+ documentationLink: 'https://www.postgresql.org/docs/current/sql-copy.html',
63
+ }),
64
+ },
65
+ schema: [
66
+ {
67
+ type: 'object',
68
+ properties: {
69
+ allowHardcodedPaths: {
70
+ type: 'boolean',
71
+ description: 'Allow hardcoded file paths (for admin/migration scripts)',
72
+ },
73
+ allowedPaths: {
74
+ type: 'array',
75
+ items: { type: 'string' },
76
+ description: 'List of allowed file path patterns (regex strings)',
77
+ },
78
+ },
79
+ additionalProperties: false,
80
+ },
81
+ ],
82
+ },
83
+ defaultOptions: [{}],
84
+ create(context) {
85
+ const options = context.options[0] ?? {};
86
+ const allowHardcodedPaths = options.allowHardcodedPaths ?? false;
87
+ const allowedPaths = (options.allowedPaths ?? []).map((p) => new RegExp(p));
88
+ // Check if a file path matches any allowed pattern
89
+ const isPathAllowed = (filePath) => {
90
+ return allowedPaths.some((pattern) => pattern.test(filePath));
91
+ };
92
+ return {
93
+ CallExpression(node) {
94
+ if (node.callee.type !== eslint_devkit_1.AST_NODE_TYPES.MemberExpression ||
95
+ node.callee.property.type !== eslint_devkit_1.AST_NODE_TYPES.Identifier ||
96
+ node.callee.property.name !== 'query') {
97
+ return;
98
+ }
99
+ const args = node.arguments;
100
+ if (args.length === 0)
101
+ return;
102
+ const queryArg = args[0];
103
+ // Case 1: Literal string - can fully analyze
104
+ if (queryArg.type === eslint_devkit_1.AST_NODE_TYPES.Literal && typeof queryArg.value === 'string') {
105
+ if (hasCopyFrom(queryArg.value)) {
106
+ const filePath = extractFilePath(queryArg.value);
107
+ // Check if path is in allowlist
108
+ if (filePath && isPathAllowed(filePath)) {
109
+ return; // Explicitly allowed
110
+ }
111
+ // Hardcoded path - report as medium severity (or skip if allowed)
112
+ if (allowHardcodedPaths) {
113
+ return; // User opted to allow hardcoded paths
114
+ }
115
+ context.report({
116
+ node: queryArg,
117
+ messageId: 'hardcodedPath',
118
+ });
119
+ }
120
+ return;
121
+ }
122
+ // Case 2: Template literal - check for dynamic expressions
123
+ if (queryArg.type === eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral) {
124
+ const staticText = queryArg.quasis.map(q => q.value.raw).join(' ');
125
+ if (hasCopyFrom(staticText)) {
126
+ // Has expressions = dynamic = CRITICAL
127
+ if (queryArg.expressions.length > 0) {
128
+ context.report({
129
+ node: queryArg,
130
+ messageId: 'dynamicPath',
131
+ });
132
+ }
133
+ else {
134
+ // No expressions = effectively a static string
135
+ const filePath = extractFilePath(staticText);
136
+ if (filePath && isPathAllowed(filePath)) {
137
+ return;
138
+ }
139
+ if (!allowHardcodedPaths) {
140
+ context.report({
141
+ node: queryArg,
142
+ messageId: 'hardcodedPath',
143
+ });
144
+ }
145
+ }
146
+ }
147
+ return;
148
+ }
149
+ // Case 3: Binary expression (string concatenation)
150
+ if (queryArg.type === eslint_devkit_1.AST_NODE_TYPES.BinaryExpression) {
151
+ const parts = [];
152
+ let hasDynamicPart = false;
153
+ const stack = [queryArg];
154
+ for (let curr = stack.pop(); curr !== undefined; curr = stack.pop()) {
155
+ if (curr.type === eslint_devkit_1.AST_NODE_TYPES.BinaryExpression && curr.operator === '+') {
156
+ stack.push(curr.right);
157
+ stack.push(curr.left);
158
+ }
159
+ else if (curr.type === eslint_devkit_1.AST_NODE_TYPES.Literal && typeof curr.value === 'string') {
160
+ parts.push(curr.value);
161
+ }
162
+ else {
163
+ // Non-literal part = dynamic
164
+ hasDynamicPart = true;
165
+ }
166
+ }
167
+ const staticText = parts.join(' ');
168
+ if (hasCopyFrom(staticText)) {
169
+ if (hasDynamicPart) {
170
+ context.report({
171
+ node: queryArg,
172
+ messageId: 'dynamicPath',
173
+ });
174
+ }
175
+ else {
176
+ // All literals - treat as hardcoded
177
+ const filePath = extractFilePath(staticText);
178
+ if (filePath && isPathAllowed(filePath)) {
179
+ return;
180
+ }
181
+ if (!allowHardcodedPaths) {
182
+ context.report({
183
+ node: queryArg,
184
+ messageId: 'hardcodedPath',
185
+ });
186
+ }
187
+ }
188
+ }
189
+ return;
190
+ }
191
+ // Case 4: Identifier or CallExpression - cannot verify statically
192
+ if (queryArg.type === eslint_devkit_1.AST_NODE_TYPES.Identifier ||
193
+ queryArg.type === eslint_devkit_1.AST_NODE_TYPES.CallExpression) {
194
+ // We can't see what's in the variable/function - flag as unverifiable
195
+ // This catches: client.query(sqlQuery) or client.query(buildQuery())
196
+ // We report as medium severity since we can't confirm it's COPY FROM
197
+ // Actually, we can't even confirm it's COPY FROM, so let's not report
198
+ // unless we want to be very aggressive. For now, skip these.
199
+ // The user would need to ensure the source is safe.
200
+ return;
201
+ }
202
+ },
203
+ };
204
+ },
205
+ };
@@ -0,0 +1,8 @@
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
+ import { TSESLint } from '@interlace/eslint-devkit';
7
+ import { NoUnsafeQueryOptions } from '../../types';
8
+ export declare const noUnsafeQuery: TSESLint.RuleModule<'noUnsafeQuery' | 'unsafeTemplateLiteral', NoUnsafeQueryOptions>;
@@ -0,0 +1,132 @@
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.noUnsafeQuery = void 0;
9
+ const eslint_devkit_1 = require("@interlace/eslint-devkit");
10
+ /**
11
+ * Check if a node contains unsafe string construction (concatenation or interpolation)
12
+ */
13
+ function isUnsafeStringConstruction(node) {
14
+ // Direct concatenation: "SELECT..." + var
15
+ if (node.type === eslint_devkit_1.AST_NODE_TYPES.BinaryExpression && node.operator === '+') {
16
+ return 'concat';
17
+ }
18
+ // Template literal with expressions: `SELECT...${var}`
19
+ if (node.type === eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral && node.expressions.length > 0) {
20
+ return 'template';
21
+ }
22
+ return false;
23
+ }
24
+ exports.noUnsafeQuery = {
25
+ meta: {
26
+ type: 'problem',
27
+ // CWE / CVSS lifted to meta.docs (Interlace extension) so
28
+ // @interlace/eslint-formatter renders them inline. Previously these
29
+ // values lived only inside the `messages` factory below, where the
30
+ // whole-run formatter cannot see them. See docs/META_HYGIENE.md for
31
+ // the fleet-wide audit and tracker P1 #5 for the rollout plan.
32
+ docs: {
33
+ description: 'Prevent SQL injection by disallowing string concatenation or unsafe template literals in queries.',
34
+ url: 'https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-postgresql-security/docs/rules/no-unsafe-query.md',
35
+ // CWE / CVSS surfaces in the formatter (devkit augments RuleMetaDataDocs).
36
+ cwe: 'CWE-89',
37
+ cvss: 9.8,
38
+ confidence: 'high',
39
+ },
40
+ messages: {
41
+ noUnsafeQuery: (0, eslint_devkit_1.formatLLMMessage)({
42
+ icon: eslint_devkit_1.MessageIcons.SECURITY,
43
+ issueName: 'SQL Injection Risk',
44
+ description: 'Unsafe SQL query detected. Variable interpolation found.',
45
+ severity: 'CRITICAL',
46
+ cwe: 'CWE-89',
47
+ owasp: 'A03:2021',
48
+ compliance: ['SOC2', 'PCI-DSS', 'NIST-CSF'],
49
+ effort: 'high',
50
+ fix: 'Use parameterized queries ($1, $2) instead of string concatenation.',
51
+ documentationLink: 'https://node-postgres.com/features/queries#parameterized-queries',
52
+ }),
53
+ unsafeTemplateLiteral: (0, eslint_devkit_1.formatLLMMessage)({
54
+ icon: eslint_devkit_1.MessageIcons.SECURITY,
55
+ issueName: 'SQL Injection Risk',
56
+ description: 'Unsafe SQL query construction detected (template literal).',
57
+ severity: 'CRITICAL',
58
+ fix: 'Use parameterized queries ($1, $2) instead of interpolating values.',
59
+ documentationLink: 'https://owasp.org/www-community/attacks/SQL_Injection',
60
+ }),
61
+ },
62
+ schema: [],
63
+ },
64
+ defaultOptions: [],
65
+ create(context) {
66
+ // Track variables tainted by unsafe string construction
67
+ const taintedVariables = new Map();
68
+ return {
69
+ // Track variable declarations with unsafe init:
70
+ // const query = "SELECT..." + userId;
71
+ // const query = `SELECT...${email}`;
72
+ VariableDeclarator(node) {
73
+ if (node.id.type === eslint_devkit_1.AST_NODE_TYPES.Identifier &&
74
+ node.init) {
75
+ const unsafe = isUnsafeStringConstruction(node.init);
76
+ if (unsafe) {
77
+ taintedVariables.set(node.id.name, unsafe);
78
+ }
79
+ }
80
+ },
81
+ // Track augmented assignment: query += " AND ..." + var
82
+ // or: query += `...${var}`
83
+ AssignmentExpression(node) {
84
+ if (node.operator === '+=' &&
85
+ node.left.type === eslint_devkit_1.AST_NODE_TYPES.Identifier) {
86
+ const unsafe = isUnsafeStringConstruction(node.right);
87
+ if (unsafe) {
88
+ taintedVariables.set(node.left.name, unsafe);
89
+ }
90
+ }
91
+ },
92
+ CallExpression(node) {
93
+ // Check if the method being called is 'query'
94
+ if (node.callee.type !== eslint_devkit_1.AST_NODE_TYPES.MemberExpression ||
95
+ node.callee.property.type !== eslint_devkit_1.AST_NODE_TYPES.Identifier ||
96
+ node.callee.property.name !== 'query') {
97
+ return;
98
+ }
99
+ const args = node.arguments;
100
+ if (args.length === 0)
101
+ return;
102
+ const queryArg = args[0];
103
+ // 1. Check for String Concatenation: query('SELECT * FROM users WHERE id = ' + id)
104
+ if (queryArg.type === eslint_devkit_1.AST_NODE_TYPES.BinaryExpression && queryArg.operator === '+') {
105
+ context.report({
106
+ node: queryArg,
107
+ messageId: 'noUnsafeQuery',
108
+ });
109
+ return;
110
+ }
111
+ // 2. Check for Template Literals with Expressions: query(`SELECT * FROM users WHERE id = ${id}`)
112
+ if (queryArg.type === eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral && queryArg.expressions.length > 0) {
113
+ context.report({
114
+ node: queryArg,
115
+ messageId: 'unsafeTemplateLiteral',
116
+ });
117
+ return;
118
+ }
119
+ // 3. Check for tainted variables: const q = "..." + var; db.query(q)
120
+ if (queryArg.type === eslint_devkit_1.AST_NODE_TYPES.Identifier) {
121
+ const taint = taintedVariables.get(queryArg.name);
122
+ if (taint) {
123
+ context.report({
124
+ node: queryArg,
125
+ messageId: taint === 'template' ? 'unsafeTemplateLiteral' : 'noUnsafeQuery',
126
+ });
127
+ }
128
+ }
129
+ },
130
+ };
131
+ },
132
+ };
@@ -0,0 +1,8 @@
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
+ import { TSESLint } from '@interlace/eslint-devkit';
7
+ import { NoUnsafeSearchPathOptions } from '../../types';
8
+ export declare const noUnsafeSearchPath: TSESLint.RuleModule<'noUnsafeSearchPath', NoUnsafeSearchPathOptions>;
@@ -0,0 +1,144 @@
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.noUnsafeSearchPath = void 0;
9
+ const eslint_devkit_1 = require("@interlace/eslint-devkit");
10
+ // Pre-compiled pattern check for search_path
11
+ const hasSearchPath = (str) => str.toLowerCase().includes('set search_path');
12
+ exports.noUnsafeSearchPath = {
13
+ meta: {
14
+ type: 'problem',
15
+ docs: {
16
+ description: 'Prevent unsafe SET search_path usage with dynamic values, which can lead to schema hijacking.',
17
+ url: 'https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-postgresql-security/docs/rules/no-unsafe-search-path.md',
18
+ cwe: 'CWE-426',
19
+ cvss: 7.5,
20
+ },
21
+ messages: {
22
+ noUnsafeSearchPath: (0, eslint_devkit_1.formatLLMMessage)({
23
+ icon: eslint_devkit_1.MessageIcons.SECURITY,
24
+ issueName: 'Schema Hijacking Risk',
25
+ description: 'Unsafe "SET search_path" detected.',
26
+ severity: 'CRITICAL',
27
+ cwe: 'CWE-426',
28
+ owasp: 'A05:2021',
29
+ compliance: ['SOC2', 'PCI-DSS'],
30
+ effort: 'low',
31
+ fix: 'Do not use dynamic values for search_path. Use static strings or strict validation.',
32
+ documentationLink: 'https://www.postgresql.org/docs/current/ddl-schemas.html#DDL-SCHEMAS-PATH',
33
+ }),
34
+ },
35
+ schema: [],
36
+ },
37
+ defaultOptions: [],
38
+ create(context) {
39
+ return {
40
+ CallExpression(node) {
41
+ if (node.callee.type !== eslint_devkit_1.AST_NODE_TYPES.MemberExpression ||
42
+ node.callee.property.type !== eslint_devkit_1.AST_NODE_TYPES.Identifier ||
43
+ node.callee.property.name !== 'query') {
44
+ return;
45
+ }
46
+ const args = node.arguments;
47
+ if (args.length === 0)
48
+ return;
49
+ const queryArg = args[0];
50
+ // 1. Literal Check: "SET search_path = " + variable
51
+ if (queryArg.type === eslint_devkit_1.AST_NODE_TYPES.BinaryExpression && queryArg.operator === '+') {
52
+ // We need to check if the left or right side contains "SET search_path"
53
+ // This requires a bit of deep traversal if it's a chain, but let's check simple cases first.
54
+ // Or, we can just check if *any* part of the expression is a string literal containing "SET search_path"
55
+ // A simpler approach for BinaryExpression:
56
+ // If it isn't a Literal, it's dynamic. If we can prove it contains "SET search_path", flag it.
57
+ // But statically analyzing the concatenated string is hard.
58
+ // However, we ALREADY forbid string concatenation in queries via `no-unsafe-query`.
59
+ // So this rule specifically should target WHERE `no-unsafe-query` might miss (e.g. valid syntax but unsafe LOGIC),
60
+ // OR reinforce it.
61
+ // Actually `no-unsafe-query` blocks `query('SET search_path = ' + val)`.
62
+ // But what about `query('SET search_path = $1', [val])`?
63
+ // PostgreSQL DOES NOT allow parameters for `SET search_path`. It must be a literal identifier.
64
+ // usages like `SET search_path TO $1` throw syntax error in PG.
65
+ // So users MUST use string interpolation or literal.
66
+ // `no-unsafe-query` will block the string interpolation/concatenation.
67
+ // So the only "safe" way usually is `query('SET search_path = public')`.
68
+ // Wait, if `no-unsafe-query` blocks all dynamic queries, then `no-unsafe-search-path` is redundant?
69
+ // Not quite. `no-unsafe-query` allows template literals without expressions.
70
+ // It blocks concatenation.
71
+ // But sometimes people disable `no-unsafe-query` or use helpers.
72
+ // Also, `pg-format` usage: `format('SET search_path = %I', val)`.
73
+ // This IS safe from SQLi in general, but for `search_path`, allows changing to ARBITRARY schema.
74
+ // If attacker controls `val`, they can point to `hack_public` schema.
75
+ // So we want to ensure `search_path` is HARDCODED or strictly validated.
76
+ // Let's detect `SET search_path` in any string literal part of the arg.
77
+ // If we find it, and the argument is NOT a pure String Literal (i.e. it involves vars/functions), WARN.
78
+ }
79
+ if (queryArg.type === eslint_devkit_1.AST_NODE_TYPES.Literal) {
80
+ if (typeof queryArg.value === 'string' && hasSearchPath(queryArg.value)) {
81
+ // Safe: Literal string "SET search_path = public"
82
+ return;
83
+ }
84
+ }
85
+ // If it's a TemplateLiteral
86
+ if (queryArg.type === eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral) {
87
+ // Check quasis
88
+ const rawText = queryArg.quasis.map(q => q.value.raw).join(' ');
89
+ if (hasSearchPath(rawText)) {
90
+ if (queryArg.expressions.length > 0) {
91
+ context.report({
92
+ node: queryArg,
93
+ messageId: 'noUnsafeSearchPath',
94
+ });
95
+ }
96
+ }
97
+ return;
98
+ }
99
+ // If it's a BinaryExpression (concat)
100
+ if (queryArg.type === eslint_devkit_1.AST_NODE_TYPES.BinaryExpression) {
101
+ // We can't easily reconstruction the full string.
102
+ // But if we detect "search_path" in any literal part, and it's being concatenated, flag it.
103
+ // This is a simplified visitor for the binary expression tree
104
+ const parts = [];
105
+ const stack = [queryArg];
106
+ for (let curr = stack.pop(); curr !== undefined; curr = stack.pop()) {
107
+ if (curr.type === eslint_devkit_1.AST_NODE_TYPES.BinaryExpression && curr.operator === '+') {
108
+ stack.push(curr.right);
109
+ stack.push(curr.left);
110
+ }
111
+ else if (curr.type === eslint_devkit_1.AST_NODE_TYPES.Literal && typeof curr.value === 'string') {
112
+ parts.push(curr.value);
113
+ }
114
+ }
115
+ const combined = parts.join(' ');
116
+ if (hasSearchPath(combined)) {
117
+ context.report({
118
+ node: queryArg,
119
+ messageId: 'noUnsafeSearchPath',
120
+ });
121
+ }
122
+ return;
123
+ }
124
+ // CallExpression (e.g. pg-format)
125
+ // format('SET search_path = %I', schema) -> This is arguably unsafe if schema is user-controlled.
126
+ if (queryArg.type === eslint_devkit_1.AST_NODE_TYPES.CallExpression) {
127
+ if (queryArg.arguments.length > 0 &&
128
+ queryArg.arguments[0].type === eslint_devkit_1.AST_NODE_TYPES.Literal &&
129
+ typeof queryArg.arguments[0].value === 'string' &&
130
+ hasSearchPath(queryArg.arguments[0].value)) {
131
+ // Fix: If all arguments are Literals, assume it is safe.
132
+ const allLiterals = queryArg.arguments.every(arg => arg.type === eslint_devkit_1.AST_NODE_TYPES.Literal);
133
+ if (allLiterals)
134
+ return;
135
+ context.report({
136
+ node: queryArg,
137
+ messageId: 'noUnsafeSearchPath',
138
+ });
139
+ }
140
+ }
141
+ },
142
+ };
143
+ },
144
+ };
@@ -0,0 +1,8 @@
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
+ import { TSESLint } from '@interlace/eslint-devkit';
7
+ import { PreferPoolQueryOptions } from '../../types';
8
+ export declare const preferPoolQuery: TSESLint.RuleModule<'preferPoolQuery', PreferPoolQueryOptions>;
@@ -0,0 +1,104 @@
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.preferPoolQuery = void 0;
9
+ const eslint_devkit_1 = require("@interlace/eslint-devkit");
10
+ exports.preferPoolQuery = {
11
+ meta: {
12
+ type: 'suggestion',
13
+ docs: {
14
+ description: 'Prefer pool.query() over client.query() for single-shot queries.',
15
+ url: 'https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-postgresql-security/docs/rules/prefer-pool-query.md',
16
+ },
17
+ messages: {
18
+ preferPoolQuery: (0, eslint_devkit_1.formatLLMMessage)({
19
+ icon: eslint_devkit_1.MessageIcons.PERFORMANCE,
20
+ issueName: 'Prefer Pool Query',
21
+ description: 'Single-shot queries should use pool.query() directly.',
22
+ severity: 'MEDIUM',
23
+ cwe: 'CWE-400',
24
+ effort: 'low',
25
+ fix: 'Use pool.query(...) instead of manual client checkout/release for simple queries.',
26
+ documentationLink: 'https://node-postgres.com/features/pooling',
27
+ }),
28
+ },
29
+ schema: [],
30
+ },
31
+ defaultOptions: [],
32
+ create(context) {
33
+ return {
34
+ VariableDeclarator(node) {
35
+ // Look for: const client = await pool.connect()
36
+ // And ensure it is used for exactly one query, then released.
37
+ // This is complex for a perfect check, but we can look for basic patterns.
38
+ if (!node.init ||
39
+ node.init.type !== eslint_devkit_1.AST_NODE_TYPES.AwaitExpression ||
40
+ node.init.argument.type !== eslint_devkit_1.AST_NODE_TYPES.CallExpression ||
41
+ node.init.argument.callee.type !== eslint_devkit_1.AST_NODE_TYPES.MemberExpression ||
42
+ node.init.argument.callee.property.type !== eslint_devkit_1.AST_NODE_TYPES.Identifier ||
43
+ node.init.argument.callee.property.name !== 'connect') {
44
+ return;
45
+ }
46
+ const variable = context.sourceCode.getDeclaredVariables(node)[0];
47
+ if (!variable)
48
+ return;
49
+ const references = variable.references;
50
+ // Count meaningful usages
51
+ // 1. Definition (init)
52
+ // 2. usage in query
53
+ // 3. usage in release
54
+ // roughly 3 refs total? (maybe 2 if release is forgot, but that is handled by other rule)
55
+ // If we have just: connect, query, release.
56
+ // And NO transactions (BEGIN/COMMIT).
57
+ let queryCallCount = 0;
58
+ let releaseCallCount = 0;
59
+ let otherUsageCount = 0;
60
+ for (const ref of references) {
61
+ if (ref.isWrite())
62
+ continue; // definition
63
+ const id = ref.identifier;
64
+ // Check for member access
65
+ if (id.parent?.type === eslint_devkit_1.AST_NODE_TYPES.MemberExpression &&
66
+ id.parent.object === id &&
67
+ id.parent.property.type === eslint_devkit_1.AST_NODE_TYPES.Identifier) {
68
+ const method = id.parent.property.name;
69
+ if (method === 'query') {
70
+ queryCallCount++;
71
+ // Check if it is a transaction command
72
+ if (id.parent.parent?.type === eslint_devkit_1.AST_NODE_TYPES.CallExpression) {
73
+ const call = id.parent.parent;
74
+ if (call.arguments.length > 0 &&
75
+ call.arguments[0].type === eslint_devkit_1.AST_NODE_TYPES.Literal &&
76
+ typeof call.arguments[0].value === 'string') {
77
+ const q = call.arguments[0].value.toUpperCase().trim();
78
+ if (q.startsWith('BEGIN') || q.startsWith('COMMIT') || q.startsWith('ROLLBACK')) {
79
+ return; // It's a transaction, keep manual control
80
+ }
81
+ }
82
+ }
83
+ }
84
+ else if (method === 'release') {
85
+ releaseCallCount++;
86
+ }
87
+ else {
88
+ otherUsageCount++;
89
+ }
90
+ }
91
+ else {
92
+ otherUsageCount++; // usage as value (passing to func?)
93
+ }
94
+ }
95
+ if (queryCallCount === 1 && releaseCallCount === 1 && otherUsageCount === 0) {
96
+ context.report({
97
+ node,
98
+ messageId: 'preferPoolQuery',
99
+ });
100
+ }
101
+ },
102
+ };
103
+ },
104
+ };
@@ -0,0 +1,8 @@
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
+ import { TSESLint } from '@interlace/eslint-devkit';
7
+ import { PreventDoubleReleaseOptions } from '../../types';
8
+ export declare const preventDoubleRelease: TSESLint.RuleModule<'doubleRelease' | 'doubleReleaseCallback', PreventDoubleReleaseOptions>;