eslint-plugin-postgresql-security 1.5.0 → 1.5.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 (100) hide show
  1. package/README.md +5 -5
  2. package/package.json +9 -23
  3. package/src/constants.js +4 -0
  4. package/src/index.d.ts +17 -0
  5. package/src/index.js +75 -0
  6. package/src/oxlint.d.ts +17 -0
  7. package/src/oxlint.js +3 -0
  8. package/{dist/src → src}/rules/check-query-params/index.js +2 -13
  9. package/{dist/src → src}/rules/no-batch-insert-loop/index.js +1 -14
  10. package/{dist/src → src}/rules/no-floating-query/index.js +1 -16
  11. package/{dist/src → src}/rules/no-hardcoded-credentials/index.js +1 -10
  12. package/{dist/src → src}/rules/no-insecure-ssl/index.js +0 -6
  13. package/{dist/src → src}/rules/no-missing-client-release/index.js +0 -17
  14. package/{dist/src → src}/rules/no-select-all/index.js +0 -13
  15. package/{dist/src → src}/rules/no-transaction-on-pool/index.js +0 -12
  16. package/{dist/src → src}/rules/no-unsafe-copy-from/index.js +2 -28
  17. package/{dist/src → src}/rules/no-unsafe-query/index.js +0 -26
  18. package/{dist/src → src}/rules/no-unsafe-search-path/index.js +0 -43
  19. package/{dist/src → src}/rules/prefer-pool-query/index.js +3 -20
  20. package/{dist/src → src}/rules/prevent-double-release/index.js +0 -75
  21. package/src/types/index.js +2 -0
  22. package/CHANGELOG.md +0 -150
  23. package/dist/AGENTS.md +0 -118
  24. package/dist/CHANGELOG.md +0 -150
  25. package/dist/LICENSE +0 -23
  26. package/dist/README.md +0 -169
  27. package/dist/package.json +0 -99
  28. package/dist/src/constants.d.ts +0 -6
  29. package/dist/src/constants.js +0 -13
  30. package/dist/src/index.d.ts +0 -26
  31. package/dist/src/index.js +0 -116
  32. package/dist/src/oxlint.d.ts +0 -20
  33. package/dist/src/oxlint.js +0 -21
  34. package/dist/src/rules/check-query-params/index.d.ts +0 -8
  35. package/dist/src/rules/no-batch-insert-loop/index.d.ts +0 -8
  36. package/dist/src/rules/no-floating-query/index.d.ts +0 -8
  37. package/dist/src/rules/no-hardcoded-credentials/index.d.ts +0 -8
  38. package/dist/src/rules/no-insecure-ssl/index.d.ts +0 -8
  39. package/dist/src/rules/no-missing-client-release/index.d.ts +0 -8
  40. package/dist/src/rules/no-select-all/index.d.ts +0 -8
  41. package/dist/src/rules/no-transaction-on-pool/index.d.ts +0 -8
  42. package/dist/src/rules/no-unsafe-copy-from/index.d.ts +0 -10
  43. package/dist/src/rules/no-unsafe-query/index.d.ts +0 -8
  44. package/dist/src/rules/no-unsafe-search-path/index.d.ts +0 -8
  45. package/dist/src/rules/prefer-pool-query/index.d.ts +0 -8
  46. package/dist/src/rules/prevent-double-release/index.d.ts +0 -8
  47. package/dist/src/types/index.js +0 -7
  48. package/src/__compatibility__/pg-interface.spec.ts +0 -495
  49. package/src/constants.ts +0 -11
  50. package/src/index.spec.ts +0 -14
  51. package/src/index.test.ts +0 -59
  52. package/src/index.ts +0 -130
  53. package/src/oxlint.spec.ts +0 -70
  54. package/src/oxlint.ts +0 -23
  55. package/src/rules/check-query-params/check-query-params.test.ts +0 -68
  56. package/src/rules/check-query-params/index.spec.ts +0 -117
  57. package/src/rules/check-query-params/index.ts +0 -106
  58. package/src/rules/no-batch-insert-loop/index.spec.ts +0 -105
  59. package/src/rules/no-batch-insert-loop/index.ts +0 -105
  60. package/src/rules/no-batch-insert-loop/no-batch-insert-loop.test.ts +0 -68
  61. package/src/rules/no-floating-query/index.spec.ts +0 -112
  62. package/src/rules/no-floating-query/index.ts +0 -81
  63. package/src/rules/no-floating-query/no-floating-query.test.ts +0 -68
  64. package/src/rules/no-hardcoded-credentials/index.spec.ts +0 -38
  65. package/src/rules/no-hardcoded-credentials/index.ts +0 -93
  66. package/src/rules/no-hardcoded-credentials/no-hardcoded-credentials.test.ts +0 -68
  67. package/src/rules/no-insecure-ssl/index.spec.ts +0 -40
  68. package/src/rules/no-insecure-ssl/index.ts +0 -81
  69. package/src/rules/no-insecure-ssl/no-insecure-ssl.test.ts +0 -68
  70. package/src/rules/no-missing-client-release/coverage-gaps.spec.ts +0 -42
  71. package/src/rules/no-missing-client-release/index.spec.ts +0 -52
  72. package/src/rules/no-missing-client-release/index.ts +0 -100
  73. package/src/rules/no-missing-client-release/no-missing-client-release.test.ts +0 -68
  74. package/src/rules/no-select-all/index.spec.ts +0 -44
  75. package/src/rules/no-select-all/index.ts +0 -92
  76. package/src/rules/no-select-all/no-select-all.test.ts +0 -68
  77. package/src/rules/no-transaction-on-pool/index.spec.ts +0 -36
  78. package/src/rules/no-transaction-on-pool/index.ts +0 -85
  79. package/src/rules/no-transaction-on-pool/no-transaction-on-pool.test.ts +0 -68
  80. package/src/rules/no-unsafe-copy-from/coverage-gaps.spec.ts +0 -76
  81. package/src/rules/no-unsafe-copy-from/index.spec.ts +0 -274
  82. package/src/rules/no-unsafe-copy-from/index.ts +0 -226
  83. package/src/rules/no-unsafe-copy-from/no-unsafe-copy-from.test.ts +0 -78
  84. package/src/rules/no-unsafe-query/coverage-gaps.spec.ts +0 -61
  85. package/src/rules/no-unsafe-query/index.spec.ts +0 -103
  86. package/src/rules/no-unsafe-query/index.ts +0 -149
  87. package/src/rules/no-unsafe-query/no-unsafe-query.test.ts +0 -73
  88. package/src/rules/no-unsafe-search-path/index.spec.ts +0 -46
  89. package/src/rules/no-unsafe-search-path/index.ts +0 -164
  90. package/src/rules/no-unsafe-search-path/no-unsafe-search-path.test.ts +0 -68
  91. package/src/rules/prefer-pool-query/coverage-gaps.spec.ts +0 -76
  92. package/src/rules/prefer-pool-query/index.spec.ts +0 -97
  93. package/src/rules/prefer-pool-query/index.ts +0 -118
  94. package/src/rules/prefer-pool-query/prefer-pool-query.test.ts +0 -68
  95. package/src/rules/prevent-double-release/coverage-gaps.spec.ts +0 -538
  96. package/src/rules/prevent-double-release/index.spec.ts +0 -824
  97. package/src/rules/prevent-double-release/index.ts +0 -534
  98. package/src/rules/prevent-double-release/prevent-double-release.test.ts +0 -70
  99. package/src/types/index.ts +0 -58
  100. /package/{dist/src → src}/types/index.d.ts +0 -0
package/src/index.ts DELETED
@@ -1,130 +0,0 @@
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
- /**
8
- * eslint-plugin-postgresql-security
9
- *
10
- * ESLint plugin with security and best practices rules for the pg Node.js driver.
11
- *
12
- * @see https://github.com/ofri-peretz/eslint/tree/main/packages/eslint-plugin-postgresql-security
13
- */
14
-
15
- import { TSESLint } from '@interlace/eslint-devkit';
16
-
17
- import { noUnsafeQuery } from './rules/no-unsafe-query';
18
- import { noInsecureSsl } from './rules/no-insecure-ssl';
19
- import { noHardcodedCredentials } from './rules/no-hardcoded-credentials';
20
- import { checkQueryParams } from './rules/check-query-params';
21
- import { noMissingClientRelease } from './rules/no-missing-client-release';
22
- import { noTransactionOnPool } from './rules/no-transaction-on-pool';
23
- import { noFloatingQuery } from './rules/no-floating-query';
24
- import { noSelectAll } from './rules/no-select-all';
25
- import { preferPoolQuery } from './rules/prefer-pool-query';
26
- import { noBatchInsertLoop } from './rules/no-batch-insert-loop';
27
- import { noUnsafeSearchPath } from './rules/no-unsafe-search-path';
28
- import { noUnsafeCopyFrom } from './rules/no-unsafe-copy-from';
29
- import { preventDoubleRelease } from './rules/prevent-double-release';
30
-
31
- /**
32
- * Collection of all rules
33
- */
34
- export const rules: Record<string, TSESLint.RuleModule<string, readonly unknown[]>> = {
35
- 'no-unsafe-query': noUnsafeQuery,
36
- 'no-insecure-ssl': noInsecureSsl,
37
- 'no-hardcoded-credentials': noHardcodedCredentials,
38
- 'check-query-params': checkQueryParams,
39
- 'no-missing-client-release': noMissingClientRelease,
40
- 'no-transaction-on-pool': noTransactionOnPool,
41
- 'no-floating-query': noFloatingQuery,
42
- 'no-select-all': noSelectAll,
43
- 'prefer-pool-query': preferPoolQuery,
44
- 'no-batch-insert-loop': noBatchInsertLoop,
45
- 'no-unsafe-search-path': noUnsafeSearchPath,
46
- 'no-unsafe-copy-from': noUnsafeCopyFrom,
47
- 'prevent-double-release': preventDoubleRelease,
48
- };
49
-
50
- /**
51
- * ESLint Plugin object
52
- */
53
- export const plugin: TSESLint.FlatConfig.Plugin = {
54
- meta: {
55
- name: 'eslint-plugin-postgresql-security',
56
- version: '1.4.9',
57
- },
58
- rules,
59
- } satisfies TSESLint.FlatConfig.Plugin;
60
-
61
- /**
62
- * Preset configurations
63
- */
64
- export const configs: Record<string, TSESLint.FlatConfig.Config> = {
65
- /**
66
- * Flagship preset — exactly the rule(s) from this plugin that appear in
67
- * the ecosystem-wide flagship list (`.agent/flagship-rules.md`). Use this
68
- * when you want the highest-signal subset shippable in CI gates without
69
- * the noise of `recommended`.
70
- */
71
- flagship: {
72
- plugins: { 'pg': plugin },
73
- rules: {
74
- 'pg/no-unsafe-query': 'error',
75
- },
76
- } satisfies TSESLint.FlatConfig.Config,
77
-
78
- /**
79
- * Recommended preset - balanced security for most projects
80
- */
81
- recommended: {
82
- plugins: {
83
- 'pg': plugin,
84
- },
85
- rules: {
86
- // Security rules (errors)
87
- 'pg/no-unsafe-query': 'error',
88
- 'pg/no-insecure-ssl': 'error',
89
- 'pg/no-hardcoded-credentials': 'error',
90
- 'pg/no-unsafe-search-path': 'error',
91
- 'pg/no-unsafe-copy-from': 'error',
92
- 'pg/no-transaction-on-pool': 'error',
93
- // Resource management (errors)
94
- 'pg/no-missing-client-release': 'error',
95
- 'pg/prevent-double-release': 'error',
96
- 'pg/no-floating-query': 'error',
97
- // Quality (warnings)
98
- 'pg/check-query-params': 'warn',
99
- 'pg/no-select-all': 'warn',
100
- 'pg/prefer-pool-query': 'warn',
101
- 'pg/no-batch-insert-loop': 'warn',
102
- },
103
- } satisfies TSESLint.FlatConfig.Config,
104
-
105
- /**
106
- * Strict preset - all rules as errors
107
- */
108
- strict: {
109
- plugins: {
110
- 'pg': plugin,
111
- },
112
- rules: {
113
- 'pg/no-unsafe-query': 'error',
114
- 'pg/no-insecure-ssl': 'error',
115
- 'pg/no-hardcoded-credentials': 'error',
116
- 'pg/no-unsafe-search-path': 'error',
117
- 'pg/no-unsafe-copy-from': 'error',
118
- 'pg/no-transaction-on-pool': 'error',
119
- 'pg/no-missing-client-release': 'error',
120
- 'pg/prevent-double-release': 'error',
121
- 'pg/no-floating-query': 'error',
122
- 'pg/check-query-params': 'error',
123
- 'pg/no-select-all': 'error',
124
- 'pg/prefer-pool-query': 'error',
125
- 'pg/no-batch-insert-loop': 'error',
126
- },
127
- } satisfies TSESLint.FlatConfig.Config,
128
- };
129
-
130
- export default plugin;
@@ -1,70 +0,0 @@
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
- import { describe, it, expect } from 'vitest';
8
- import * as fs from 'node:fs';
9
- import * as path from 'node:path';
10
- import { plugin as mainPlugin } from './index';
11
- import * as typeExports from './types';
12
-
13
- type Plugin = typeof mainPlugin;
14
-
15
- /**
16
- * Smoke tests for the `./oxlint` sub-export.
17
- *
18
- * Runtime shape: `oxlint.ts` uses `export = plugin`, which compiles to
19
- * `module.exports = plugin`. From an ESM dynamic `import('./oxlint')` view,
20
- * Node's CJS interop surfaces that value at `.default`. From oxlint's
21
- * `require('eslint-plugin-postgresql-security/oxlint')` view, it sits at the top of
22
- * `module.exports` — the `{ meta, rules }` shape oxlint's JS plugin loader
23
- * expects.
24
- */
25
- describe('eslint-plugin-postgresql-security/oxlint sub-export', () => {
26
- it('declares the ./oxlint sub-export in package.json', () => {
27
- const pkgJson = JSON.parse(
28
- fs.readFileSync(path.resolve(__dirname, '..', 'package.json'), 'utf8'),
29
- );
30
- expect(pkgJson.exports['./oxlint']).toEqual({
31
- types: './src/oxlint.d.ts',
32
- default: './src/oxlint.js',
33
- });
34
- });
35
-
36
- it('re-exports the plugin object (meta + rules at top level)', async () => {
37
- const oxlintModule = await import('./oxlint.js');
38
- const oxlintPlugin = (oxlintModule as unknown as { default: Plugin })
39
- .default;
40
- expect(oxlintPlugin).toBeDefined();
41
- expect(oxlintPlugin.meta?.name).toBe('eslint-plugin-postgresql-security');
42
- expect(oxlintPlugin.rules).toBeDefined();
43
- });
44
-
45
- it('exposes the same rule names as the main entry (no rules dropped)', async () => {
46
- const oxlintModule = await import('./oxlint.js');
47
- const oxlintPlugin = (oxlintModule as unknown as { default: Plugin })
48
- .default;
49
- expect(Object.keys(oxlintPlugin.rules || {}).toSorted()).toEqual(
50
- Object.keys(mainPlugin.rules || {}).toSorted(),
51
- );
52
- });
53
-
54
- it('exposes the same rule references (pass-through, not a copy)', async () => {
55
- const oxlintModule = await import('./oxlint.js');
56
- const oxlintPlugin = (oxlintModule as unknown as { default: Plugin })
57
- .default;
58
- for (const ruleName of Object.keys(mainPlugin.rules || {})) {
59
- expect(oxlintPlugin.rules?.[ruleName]).toBe(
60
- (mainPlugin.rules as Record<string, unknown>)[ruleName],
61
- );
62
- }
63
- });
64
- });
65
-
66
- describe('types sub-export', () => {
67
- it('is a type-only module with no runtime exports', () => {
68
- expect(Object.keys(typeExports)).toEqual([]);
69
- });
70
- });
package/src/oxlint.ts DELETED
@@ -1,23 +0,0 @@
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
- /**
8
- * oxlint sub-export.
9
- *
10
- * Consumers wire oxlint to this entry via:
11
- * { "jsPlugins": ["eslint-plugin-postgresql-security/oxlint"] }
12
- *
13
- * oxlint's JS plugin loader does `require('eslint-plugin-postgresql-security/oxlint')` and reads
14
- * `.rules` off the result. The compiled output of `export = plugin` is
15
- * `module.exports = plugin`, which gives oxlint the plugin object directly
16
- * (`{ meta, rules }`) — no wrapper, no `.default` indirection.
17
- *
18
- * Generated by scripts/generate-oxlint-shims.mjs. Do not edit by hand.
19
- */
20
-
21
- import { plugin } from './index';
22
-
23
- export = plugin;
@@ -1,68 +0,0 @@
1
- /**
2
- * Tests for check-query-params
3
- * CWE-20 — Ensure the number of query parameters matches the arguments array.
4
- *
5
- * Generated by: node scripts/generate-rule-tests.mjs
6
- * Standard: Engineering Standards §5 (side-by-side), §6 (≥5 valid + ≥5 invalid), §8 (RuleTester at describe level)
7
- */
8
- import { RuleTester } from '@typescript-eslint/rule-tester';
9
- import { describe, it, afterAll } from 'vitest';
10
- import parser from '@typescript-eslint/parser';
11
- import { checkQueryParams } from './index';
12
-
13
- RuleTester.afterAll = afterAll;
14
- RuleTester.it = it;
15
- RuleTester.itOnly = it.only;
16
- RuleTester.describe = describe;
17
-
18
- const ruleTester = new RuleTester({
19
- languageOptions: {
20
- parser,
21
- ecmaVersion: 2022,
22
- sourceType: 'module',
23
- parserOptions: { ecmaFeatures: { jsx: true } },
24
- },
25
- });
26
-
27
- describe('check-query-params', () => {
28
- describe('Valid Code', () => {
29
- ruleTester.run('valid - safe patterns', checkQueryParams, {
30
- valid: [
31
- // Unrelated code should not trigger
32
- {
33
- code: `const x = 1;`,
34
- },
35
- // Array operations are safe
36
- {
37
- code: `const arr = [1, 2, 3];`,
38
- },
39
- // Non-targeted method calls are safe
40
- {
41
- code: `obj.safeMethod();`,
42
- },
43
- // Environment variable usage is safe (padding case 4)
44
- {
45
- code: `const safe3 = process.env.DB_HOST;`,
46
- },
47
- // Environment variable usage is safe (padding case 5)
48
- {
49
- code: `const safe4 = process.env.DB_HOST;`,
50
- },
51
- ],
52
- invalid: [],
53
- });
54
- });
55
-
56
- describe('Invalid Code', () => {
57
- ruleTester.run('invalid - dangerous patterns', checkQueryParams, {
58
- valid: [],
59
- invalid: [
60
- // Triggers parameterCountMismatch
61
- {
62
- code: `client.query('SELECT * FROM users WHERE id = $1 AND name = $2', [userId])`,
63
- errors: [{ messageId: 'parameterCountMismatch' }],
64
- },
65
- ],
66
- });
67
- });
68
- });
@@ -1,117 +0,0 @@
1
- import { RuleTester } from '@typescript-eslint/rule-tester';
2
- import * as parser from '@typescript-eslint/parser';
3
- import { checkQueryParams } from './index';
4
-
5
- const ruleTester = new RuleTester({
6
- languageOptions: {
7
- parser,
8
- },
9
- });
10
-
11
- ruleTester.run('check-query-params', checkQueryParams, {
12
- valid: [
13
- // Basic valid cases
14
- {
15
- code: "client.query('SELECT * FROM users WHERE id = $1', [1])",
16
- name: 'Basic parameterized query with 1 arg',
17
- },
18
- {
19
- code: "pool.query('INSERT INTO users(name, email) VALUES($1, $2)', ['name', 'email'])",
20
- name: 'Insert with 2 parameters',
21
- },
22
- // Ignored cases (coverage)
23
- {
24
- code: "client.otherMethod('SELECT 1', [])", // Not .query
25
- name: 'Ignored: Not a .query method call',
26
- },
27
- {
28
- code: "otherFunc('SELECT 1', [])", // Not MemberExpression
29
- name: 'Ignored: Not a member expression call',
30
- },
31
- {
32
- code: "client.query('SELECT 1', dynamicValues)", // Dynamic values array (can't check count)
33
- name: 'Ignored: Dynamic values array',
34
- },
35
- {
36
- code: "client.query('SELECT 1')",
37
- name: 'Query with no parameters and no args array',
38
- },
39
- {
40
- code: "client.query('SELECT 1', [])",
41
- name: 'Query with no parameters and empty args array',
42
- },
43
- // Gaps in parameters (PG requires array length to cover the max index)
44
- {
45
- code: "client.query('SELECT $1, $3', [1, 2, 3])",
46
- name: 'Gaps in parameter indices ($1, $3), array has 3 elements',
47
- },
48
- // Edge cases: Strings and Comments
49
- {
50
- code: "client.query(\"SELECT '$1'\", [])",
51
- name: 'String literal containing $1 should be ignored',
52
- },
53
- {
54
- code: "client.query('SELECT 1 -- $1', [])",
55
- name: 'Line comment containing $1 should be ignored',
56
- },
57
- {
58
- code: "client.query('SELECT 1 /* $1 */', [])",
59
- name: 'Block comment containing $1 should be ignored',
60
- },
61
- {
62
- code: "client.query('SELECT \"$1\"', [])",
63
- name: 'Quoted identifier "$1" (unlikely but valid SQL identifier) - technically NOT a param',
64
- // Note: $1 inside double quotes is an identifier, not a parameter.
65
- // Our regex might match it if we don't strip double quotes?
66
- // Postgres treats "$1" as a column name "1" or similar? No, "$1" is identifier.
67
- // Real param is unquoted $1.
68
- // Current rule strips single quotes. Does NOT strip double quotes.
69
- // If we strip double quotes, we avoid FP here.
70
- // Let's assume for now we might have FP on "$1" if we don't handle it.
71
- // But typically people don't name columns "$1".
72
- // Let's see if this fails.
73
- },
74
- // Multiline
75
- {
76
- code: `
77
- client.query('SELECT * FROM users WHERE id = $1', [1])
78
- `,
79
- name: 'Multiline code formatted query',
80
- },
81
- {
82
- code: "client.query(`SELECT * FROM users WHERE id = $1`, [1])",
83
- name: 'Template literal (static) with $1',
84
- },
85
- ],
86
- invalid: [
87
- // Missing arguments
88
- {
89
- code: "client.query('SELECT * FROM users WHERE id = $1', [])",
90
- name: 'Missing argument (provided 0, needed 1)',
91
- errors: [{ messageId: 'parameterCountMismatch', data: { expected: '1', actual: '0' } }],
92
- },
93
- {
94
- code: "pool.query('INSERT INTO users VALUES($1, $2)', [1])",
95
- name: 'Missing argument (provided 1, needed 2)',
96
- errors: [{ messageId: 'parameterCountMismatch', data: { expected: '2', actual: '1' } }],
97
- },
98
- // Gaps handling
99
- {
100
- code: "client.query('SELECT $3', [1, 2])",
101
- name: 'Highest index is $3, but only 2 args provided',
102
- errors: [{ messageId: 'parameterCountMismatch', data: { expected: '3', actual: '2' } }],
103
- },
104
- // Double digits
105
- {
106
- code: "client.query('SELECT $10', [1,2,3,4,5,6,7,8,9])",
107
- name: 'Highest index is $10, provided 9 args',
108
- errors: [{ messageId: 'parameterCountMismatch', data: { expected: '10', actual: '9' } }],
109
- },
110
- // Multiple occurrences
111
- {
112
- code: "client.query('SELECT $1, $1', [])",
113
- name: 'Repeated $1 still requires at least 1 arg',
114
- errors: [{ messageId: 'parameterCountMismatch', data: { expected: '1', actual: '0' } }],
115
- },
116
- ],
117
- });
@@ -1,106 +0,0 @@
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
- import { TSESLint, AST_NODE_TYPES, TSESTree, formatLLMMessage, MessageIcons } from '@interlace/eslint-devkit';
8
- import { CheckQueryParamsOptions } from '../../types';
9
-
10
- // Pre-compiled regex patterns for performance
11
- const SINGLE_QUOTE_REGEX = /'(?:[^']|'')*'/g;
12
- const DOUBLE_QUOTE_REGEX = /"(?:[^"]|"")*"/g;
13
- const LINE_COMMENT_REGEX = /--.*/g;
14
- const BLOCK_COMMENT_REGEX = /\/\*[\s\S]*?\*\//g;
15
- const PARAM_REGEX = /\$\d+/g;
16
-
17
- export const checkQueryParams: TSESLint.RuleModule<
18
- 'parameterCountMismatch',
19
- CheckQueryParamsOptions
20
- > = {
21
- meta: {
22
- type: 'problem',
23
- docs: {
24
- description: 'Ensure the number of query parameters matches the arguments array.',
25
- url: 'https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-postgresql-security/docs/rules/check-query-params.md',
26
- cwe: 'CWE-20',
27
- cvss: 7.5,
28
- },
29
- messages: {
30
- parameterCountMismatch: formatLLMMessage({
31
- icon: MessageIcons.QUALITY,
32
- issueName: 'Parameter Count Mismatch',
33
- description: 'Query parameter count mismatch detected.',
34
- severity: 'HIGH',
35
- cwe: 'CWE-20',
36
- effort: 'low',
37
- fix: 'Ensure the number of arguments matches the number of placeholders ($1, $2, etc.).',
38
- documentationLink: 'https://node-postgres.com/features/queries',
39
- }),
40
- },
41
- schema: [],
42
- },
43
- defaultOptions: [],
44
- create(context) {
45
- return {
46
- CallExpression(node: TSESTree.CallExpression) {
47
- if (
48
- node.callee.type !== AST_NODE_TYPES.MemberExpression ||
49
- node.callee.property.type !== AST_NODE_TYPES.Identifier ||
50
- node.callee.property.name !== 'query'
51
- ) {
52
- return;
53
- }
54
-
55
- const args = node.arguments;
56
- if (args.length < 2) return;
57
-
58
- const queryArg = args[0];
59
- const valuesArg = args[1];
60
-
61
- if (queryArg.type !== AST_NODE_TYPES.Literal || typeof queryArg.value !== 'string') {
62
- return; // Can't statically analyze dynamic queries
63
- }
64
-
65
- if (valuesArg.type !== AST_NODE_TYPES.ArrayExpression) {
66
- return; // Can't statically count dynamic arrays
67
- }
68
-
69
- const queryText = queryArg.value;
70
-
71
- // Remove strings, quoted identifiers, and comments to avoid false positives
72
- const cleanText = queryText
73
- .replace(SINGLE_QUOTE_REGEX, '')
74
- .replace(DOUBLE_QUOTE_REGEX, '')
75
- .replace(LINE_COMMENT_REGEX, '')
76
- .replace(BLOCK_COMMENT_REGEX, '');
77
-
78
- const matches = cleanText.match(PARAM_REGEX);
79
-
80
- let maxParamIndex = 0;
81
- if (matches) {
82
- const indices = matches.map(m => parseInt(m.substring(1), 10));
83
- maxParamIndex = Math.max(0, ...indices);
84
- }
85
-
86
- // PG allows gaps, but essentially the highest index determines needed array length.
87
- // Actually, strictly speaking, if you use $2, you should provide at least 2 args.
88
- // But commonly, people mean "number of unique placeholders".
89
- // Let's enforce that array length >= max param index.
90
-
91
- const providedArgCount = valuesArg.elements.length;
92
-
93
- if (providedArgCount < maxParamIndex) {
94
- context.report({
95
- node: valuesArg,
96
- messageId: 'parameterCountMismatch',
97
- data: {
98
- expected: maxParamIndex.toString(),
99
- actual: providedArgCount.toString(),
100
- },
101
- });
102
- }
103
- },
104
- };
105
- },
106
- };
@@ -1,105 +0,0 @@
1
- import { RuleTester } from '@typescript-eslint/rule-tester';
2
- import * as parser from '@typescript-eslint/parser';
3
- import { noBatchInsertLoop } from './index';
4
-
5
- const ruleTester = new RuleTester({
6
- languageOptions: {
7
- parser,
8
- },
9
- });
10
-
11
- ruleTester.run('no-batch-insert-loop', noBatchInsertLoop, {
12
- valid: [
13
- `
14
- async function insert() {
15
- await client.query('INSERT INTO users ...');
16
- }
17
- `,
18
- `
19
- async function update() {
20
- // Bulk update
21
- await client.query('UPDATE users SET ... WHERE id = ANY($1)', [ids]);
22
- }
23
- `,
24
- // Non-loop functions (coverage)
25
- "function foo() { client.query('INSERT'); }",
26
- "const bar = () => client.query('UPDATE');",
27
- "class C { method() { client.query('INSERT'); } }",
28
- "client.query()", // Empty args
29
- "client.query(123)", // Non-string literal
30
- "items.map(item => client.query('SELECT 1'))", // Map but SELECT (ignored)
31
- `
32
- // SELECT inside loop is acceptable for this rule (targeted at mutations)
33
- for (const id of ids) {
34
- await client.query('SELECT * FROM items WHERE id = $1', [id]);
35
- }
36
- `,
37
- // Coverage: Line 92 - function boundary break (function NOT inside CallExpression parent)
38
- `
39
- const handler = async () => {
40
- await client.query('INSERT INTO items VALUES (1)');
41
- };
42
- `,
43
- // Line 92: FunctionExpression in object property (parent is Property, not CallExpression)
44
- `
45
- const obj = {
46
- handler: async function() {
47
- await client.query('INSERT INTO items VALUES (1)');
48
- }
49
- };
50
- `,
51
- // Line 92: ArrowFunction as function parameter (parent IS CallExpression, so won't break)
52
- // Need to ensure the parent is NOT map/forEach/reduce/filter to trigger break
53
- `
54
- setTimeout(async () => {
55
- await client.query('INSERT INTO items VALUES (1)');
56
- }, 1000);
57
- `
58
- ],
59
- invalid: [
60
- {
61
- code: `
62
- for (const item of items) {
63
- await client.query('INSERT INTO items VALUES ($1)', [item]);
64
- }
65
- `,
66
- errors: [{ messageId: 'noBatchInsertLoop' }],
67
- },
68
- {
69
- code: `
70
- items.forEach(async item => {
71
- await pool.query('UPDATE items SET val = $1 WHERE id = $2', [item.val, item.id]);
72
- });
73
- `,
74
- errors: [{ messageId: 'noBatchInsertLoop' }],
75
- },
76
- {
77
- code: `
78
- while(condition) {
79
- client.query('INSERT ...');
80
- }
81
- `,
82
- errors: [{ messageId: 'noBatchInsertLoop' }],
83
- },
84
- // Line 72: filter callback with INSERT
85
- {
86
- code: `
87
- items.filter(item => {
88
- client.query('INSERT INTO items VALUES (1)');
89
- return item.valid;
90
- });
91
- `,
92
- errors: [{ messageId: 'noBatchInsertLoop' }],
93
- },
94
- // Line 72: reduce callback with INSERT
95
- {
96
- code: `
97
- items.reduce((acc, item) => {
98
- client.query('INSERT INTO items VALUES (1)');
99
- return acc;
100
- }, []);
101
- `,
102
- errors: [{ messageId: 'noBatchInsertLoop' }],
103
- }
104
- ],
105
- });