|
| 1 | +/** |
| 2 | + * @vitest-environment node |
| 3 | + */ |
| 4 | +import { beforeEach, describe, expect, it, vi } from 'vitest' |
| 5 | + |
| 6 | +const { mockResolveHostAddresses, mockConnectionPool, mockConnect } = vi.hoisted(() => { |
| 7 | + const connect = vi.fn().mockResolvedValue(undefined) |
| 8 | + const pool = vi.fn(function ConnectionPool(this: Record<string, unknown>) { |
| 9 | + this.connect = connect |
| 10 | + }) |
| 11 | + return { |
| 12 | + mockResolveHostAddresses: vi.fn(), |
| 13 | + mockConnectionPool: pool, |
| 14 | + mockConnect: connect, |
| 15 | + } |
| 16 | +}) |
| 17 | + |
| 18 | +vi.mock('mssql', () => ({ |
| 19 | + default: { ConnectionPool: mockConnectionPool }, |
| 20 | + ConnectionPool: mockConnectionPool, |
| 21 | +})) |
| 22 | + |
| 23 | +/** |
| 24 | + * Only DNS is stubbed. The SSRF guard and the shared WHERE screens stay real, so |
| 25 | + * these tests exercise the same masking behavior production does — which is the |
| 26 | + * point, since the bypasses below are a property of that masker. |
| 27 | + */ |
| 28 | +vi.mock('@sim/security/dns', () => ({ |
| 29 | + resolveHostAddresses: mockResolveHostAddresses, |
| 30 | + preferIpv4: (addresses: string[]) => addresses[0], |
| 31 | +})) |
| 32 | + |
| 33 | +import { |
| 34 | + buildDeleteQuery, |
| 35 | + buildInsertQuery, |
| 36 | + buildUpdateQuery, |
| 37 | + createMSSQLConnection, |
| 38 | + executeQuery, |
| 39 | + type MSSQLConnectionConfig, |
| 40 | + validateReadOnlyQuery, |
| 41 | +} from '@/app/api/tools/mssql/utils' |
| 42 | + |
| 43 | +function makeConfig(overrides: Partial<MSSQLConnectionConfig> = {}): MSSQLConnectionConfig { |
| 44 | + return { |
| 45 | + host: 'db.example.com', |
| 46 | + port: 1433, |
| 47 | + database: 'app', |
| 48 | + username: 'app', |
| 49 | + password: 'secret', |
| 50 | + encrypt: 'enabled', |
| 51 | + trustServerCertificate: 'disabled', |
| 52 | + connectionTimeout: 15000, |
| 53 | + ...overrides, |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +describe('validateReadOnlyQuery', () => { |
| 58 | + it('accepts an ordinary SELECT and a leading CTE', () => { |
| 59 | + expect(validateReadOnlyQuery('SELECT TOP (10) * FROM dbo.users').isValid).toBe(true) |
| 60 | + expect( |
| 61 | + validateReadOnlyQuery('WITH t AS (SELECT id FROM dbo.users) SELECT * FROM t').isValid |
| 62 | + ).toBe(true) |
| 63 | + }) |
| 64 | + |
| 65 | + it('accepts a SELECT whose literal contains a doubled quote', () => { |
| 66 | + expect(validateReadOnlyQuery("SELECT * FROM dbo.users WHERE name = 'O''Brien'").isValid).toBe( |
| 67 | + true |
| 68 | + ) |
| 69 | + }) |
| 70 | + |
| 71 | + it.each([ |
| 72 | + ['a bare mutation', 'DELETE FROM dbo.users'], |
| 73 | + ['a semicolon batch', 'SELECT 1; DROP TABLE dbo.users'], |
| 74 | + ['a semicolon-less batch', 'SELECT 1 DELETE FROM dbo.users'], |
| 75 | + ['a CTE-led mutation', 'WITH t AS (SELECT id FROM dbo.users) DELETE FROM t'], |
| 76 | + ['a comment', 'SELECT 1 -- DELETE FROM dbo.users'], |
| 77 | + ['a stored procedure', 'SELECT 1 FROM dbo.t WHERE x = 1 xp_cmdshell'], |
| 78 | + ])('rejects %s', (_label, query) => { |
| 79 | + expect(validateReadOnlyQuery(query).isValid).toBe(false) |
| 80 | + }) |
| 81 | + |
| 82 | + /** |
| 83 | + * The shared masker treats `\` as a literal escape because it was written for |
| 84 | + * the MySQL dialect. T-SQL has no backslash escape, so the server closes the |
| 85 | + * literal at the quote the masker swallowed and runs the remainder as code — |
| 86 | + * with an even quote count, so a parity check alone does not catch it. |
| 87 | + */ |
| 88 | + it('rejects a backslash-escaped quote that would hide a mutation from the keyword screen', () => { |
| 89 | + const smuggled = String.raw`SELECT * FROM dbo.t WHERE a='x\' DELETE FROM dbo.t WHERE b='y'` |
| 90 | + |
| 91 | + const result = validateReadOnlyQuery(smuggled) |
| 92 | + |
| 93 | + expect(result.isValid).toBe(false) |
| 94 | + expect(result.error).toMatch(/backslash before a quote/) |
| 95 | + }) |
| 96 | + |
| 97 | + it('rejects a quote inside a bracketed identifier', () => { |
| 98 | + expect(validateReadOnlyQuery(`SELECT * FROM dbo.t WHERE [a"] = 1 OR 1=1`).isValid).toBe(false) |
| 99 | + expect(validateReadOnlyQuery(`SELECT * FROM dbo.t WHERE [a'] = 1 OR 1=1`).isValid).toBe(false) |
| 100 | + }) |
| 101 | + |
| 102 | + it('rejects an unpaired quote', () => { |
| 103 | + expect(validateReadOnlyQuery(`SELECT * FROM dbo.t WHERE a = 'x`).isValid).toBe(false) |
| 104 | + }) |
| 105 | +}) |
| 106 | + |
| 107 | +describe('buildUpdateQuery / buildDeleteQuery WHERE screening', () => { |
| 108 | + it('builds a parameterized statement for an ordinary condition', () => { |
| 109 | + const { query, values } = buildUpdateQuery('dbo.users', { name: 'Jane' }, 'id = 1') |
| 110 | + |
| 111 | + expect(query).toBe('UPDATE [dbo].[users] SET [name] = @param1 WHERE id = 1') |
| 112 | + expect(values).toEqual(['Jane']) |
| 113 | + }) |
| 114 | + |
| 115 | + /** |
| 116 | + * Same masker desynchronisation as above, reached through the mutation path: |
| 117 | + * an even quote count, no semicolon, and the tautology invisible to every |
| 118 | + * screen that runs over masked text. |
| 119 | + */ |
| 120 | + it('rejects a backslash-escaped quote that would hide a tautology', () => { |
| 121 | + const smuggled = String.raw`id = 'a\' OR 1=1 OR 2>1 AND b = 'x'` |
| 122 | + |
| 123 | + expect(() => buildDeleteQuery('dbo.users', smuggled)).toThrow(/backslash before a quote/) |
| 124 | + expect(() => buildUpdateQuery('dbo.users', { a: 1 }, smuggled)).toThrow( |
| 125 | + /backslash before a quote/ |
| 126 | + ) |
| 127 | + }) |
| 128 | + |
| 129 | + it('rejects a quote hidden inside a bracketed identifier', () => { |
| 130 | + expect(() => buildDeleteQuery('dbo.users', `[a"] = 1 OR 1=1`)).toThrow(/bracketed identifier/) |
| 131 | + }) |
| 132 | + |
| 133 | + it.each([ |
| 134 | + ['a semicolon-less batch', "id = 1 DBCC SHRINKDATABASE('app')"], |
| 135 | + ['an appended SELECT', 'id = 1 SELECT secret FROM dbo.credentials'], |
| 136 | + ['a catalog probe', 'id = 1 AND EXISTS (sys.objects)'], |
| 137 | + ['a stored procedure', 'id = 1 AND xp_cmdshell'], |
| 138 | + ])('rejects %s', (_label, where) => { |
| 139 | + expect(() => buildDeleteQuery('dbo.users', where)).toThrow() |
| 140 | + }) |
| 141 | +}) |
| 142 | + |
| 143 | +describe('identifier handling', () => { |
| 144 | + it('bracket-quotes every part of a qualified name and binds values', () => { |
| 145 | + const { query, values } = buildInsertQuery('dbo.users', { name: 'Jane', age: 30 }) |
| 146 | + |
| 147 | + expect(query).toBe('INSERT INTO [dbo].[users] ([name], [age]) VALUES (@param1, @param2)') |
| 148 | + expect(values).toEqual(['Jane', 30]) |
| 149 | + }) |
| 150 | + |
| 151 | + it('rejects an identifier that is not a plain word', () => { |
| 152 | + expect(() => buildInsertQuery('users; DROP TABLE x', { a: 1 })).toThrow(/Invalid identifier/) |
| 153 | + expect(() => buildInsertQuery('users', { 'a b': 1 })).toThrow(/Invalid identifier/) |
| 154 | + }) |
| 155 | + |
| 156 | + it('cannot be escaped by pre-closing a bracket', () => { |
| 157 | + expect(() => buildInsertQuery('users] DROP TABLE x --[', { a: 1 })).toThrow( |
| 158 | + /Invalid identifier/ |
| 159 | + ) |
| 160 | + }) |
| 161 | +}) |
| 162 | + |
| 163 | +describe('executeQuery parameter binding', () => { |
| 164 | + function makePool(recordset: unknown[] = [], rowsAffected: number[] = [0]) { |
| 165 | + const input = vi.fn() |
| 166 | + const query = vi.fn().mockResolvedValue({ recordset, rowsAffected }) |
| 167 | + return { |
| 168 | + pool: { request: () => ({ input, query }) } as never, |
| 169 | + input, |
| 170 | + query, |
| 171 | + } |
| 172 | + } |
| 173 | + |
| 174 | + it('binds every value positionally, never interpolating it', async () => { |
| 175 | + const { pool, input, query } = makePool() |
| 176 | + |
| 177 | + await executeQuery(pool, 'INSERT INTO [dbo].[t] ([a]) VALUES (@param1)', ["'; DROP TABLE t --"]) |
| 178 | + |
| 179 | + expect(query).toHaveBeenCalledWith('INSERT INTO [dbo].[t] ([a]) VALUES (@param1)') |
| 180 | + expect(input).toHaveBeenCalledWith('param1', "'; DROP TABLE t --") |
| 181 | + }) |
| 182 | + |
| 183 | + /** |
| 184 | + * node-mssql infers NVarChar for an unrecognised object and tedious then |
| 185 | + * rejects it with a bare `Invalid string.`, so a nested JSON value has to be |
| 186 | + * serialized before it reaches the driver. |
| 187 | + */ |
| 188 | + it('serializes nested objects and arrays, passing scalars and Dates through', async () => { |
| 189 | + const { pool, input } = makePool() |
| 190 | + const when = new Date('2020-01-01T00:00:00Z') |
| 191 | + |
| 192 | + await executeQuery(pool, 'INSERT INTO [dbo].[t] VALUES (@param1, @param2, @param3, @param4)', [ |
| 193 | + { nested: true }, |
| 194 | + ['a', 'b'], |
| 195 | + when, |
| 196 | + 42, |
| 197 | + ]) |
| 198 | + |
| 199 | + expect(input).toHaveBeenNthCalledWith(1, 'param1', '{"nested":true}') |
| 200 | + expect(input).toHaveBeenNthCalledWith(2, 'param2', '["a","b"]') |
| 201 | + expect(input).toHaveBeenNthCalledWith(3, 'param3', when) |
| 202 | + expect(input).toHaveBeenNthCalledWith(4, 'param4', 42) |
| 203 | + }) |
| 204 | + |
| 205 | + it('reports affected rows when the statement returns no recordset', async () => { |
| 206 | + const { pool } = makePool([], [3]) |
| 207 | + |
| 208 | + await expect( |
| 209 | + executeQuery(pool, 'DELETE FROM [dbo].[t] WHERE id = @param1', [1]) |
| 210 | + ).resolves.toEqual({ rows: [], rowCount: 3 }) |
| 211 | + }) |
| 212 | +}) |
| 213 | + |
| 214 | +describe('createMSSQLConnection DNS pinning', () => { |
| 215 | + beforeEach(() => { |
| 216 | + vi.clearAllMocks() |
| 217 | + mockConnect.mockResolvedValue(undefined) |
| 218 | + mockResolveHostAddresses.mockResolvedValue({ |
| 219 | + addresses: ['93.184.216.34'], |
| 220 | + preferred: '93.184.216.34', |
| 221 | + }) |
| 222 | + }) |
| 223 | + |
| 224 | + it('never opens a connection when the host cannot be resolved (no SSRF window)', async () => { |
| 225 | + mockResolveHostAddresses.mockRejectedValue(new Error('ENOTFOUND')) |
| 226 | + |
| 227 | + await expect( |
| 228 | + createMSSQLConnection(makeConfig({ host: 'rebind.attacker.example' })) |
| 229 | + ).rejects.toThrow(/could not be resolved/) |
| 230 | + expect(mockConnectionPool).not.toHaveBeenCalled() |
| 231 | + }) |
| 232 | + |
| 233 | + it('keeps the hostname as `server` so TLS SNI and certificate validation still apply', async () => { |
| 234 | + await createMSSQLConnection(makeConfig({ host: 'rebind.attacker.example' })) |
| 235 | + |
| 236 | + expect(mockResolveHostAddresses).toHaveBeenCalledWith('rebind.attacker.example') |
| 237 | + const config = mockConnectionPool.mock.calls[0][0] |
| 238 | + expect(config.server).toBe('rebind.attacker.example') |
| 239 | + }) |
| 240 | + |
| 241 | + it('routes the socket through a connector bound to the validated IP, not the hostname', async () => { |
| 242 | + await createMSSQLConnection(makeConfig({ host: 'rebind.attacker.example' })) |
| 243 | + |
| 244 | + const config = mockConnectionPool.mock.calls[0][0] |
| 245 | + expect(typeof config.options.connector).toBe('function') |
| 246 | + expect(config.options.instanceName).toBeUndefined() |
| 247 | + }) |
| 248 | + |
| 249 | + it('maps the string toggles onto driver booleans without coercing "disabled" to true', async () => { |
| 250 | + await createMSSQLConnection( |
| 251 | + makeConfig({ encrypt: 'disabled', trustServerCertificate: 'enabled' }) |
| 252 | + ) |
| 253 | + |
| 254 | + const config = mockConnectionPool.mock.calls[0][0] |
| 255 | + expect(config.options.encrypt).toBe(false) |
| 256 | + expect(config.options.trustServerCertificate).toBe(true) |
| 257 | + }) |
| 258 | +}) |
0 commit comments