Skip to content

Commit f5575bd

Browse files
authored
fix(mongodb): connect to exactly the validated host (#10473)
* fix(mongodb): connect to exactly the validated host validateDatabaseHost now refuses anything but a single hostname or IP literal before resolving it, so a seed list, userinfo, port, path or options can no longer pass the address check while the driver connects elsewhere. The MongoDB client builds its connection string from the validated host and port only, passes credentials, authSource and TLS as driver options, sets directConnection so server-advertised members are never followed, and validates the port and database name. * fix(mongodb): measure the database name limit in bytes
1 parent 689f8a8 commit f5575bd

6 files changed

Lines changed: 189 additions & 57 deletions

File tree

‎apps/sim/lib/core/security/input-validation.server.test.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ vi.mock('@sim/security/dns', () => ({
1414
import { EgressRefusedError } from '@/lib/core/network/transport.server'
1515
import {
1616
secureFetchWithValidation,
17+
validateDatabaseHost,
1718
validateUrlWithDNS,
1819
} from '@/lib/core/security/input-validation.server'
1920

@@ -170,3 +171,42 @@ describe('validateUrlWithDNS address classification', () => {
170171
expect(egressWarn).not.toHaveBeenCalled()
171172
})
172173
})
174+
175+
describe('validateDatabaseHost host shape', () => {
176+
it.each([
177+
['a seed list behind a public name', 'db.example.com,127.0.0.1'],
178+
['a seed list with a port', '127.0.0.1:6379,db.example.com'],
179+
['userinfo before an internal address', 'a@127.0.0.1'],
180+
['a path and options', 'db.example.com/admin?directConnection=false'],
181+
['a fragment', 'db.example.com#127.0.0.1'],
182+
['a port suffix', 'db.example.com:27017'],
183+
['a bracketed name', '[db.example.com]'],
184+
['an IPv6 zone id', 'fe80::1%eth0'],
185+
['surrounding whitespace', ' db.example.com'],
186+
])('refuses %s before resolving it', async (_case, host) => {
187+
// A wildcard zone answers any name, so the resolver alone cannot catch these.
188+
mockResolve.mockReset()
189+
mockResolve.mockResolvedValue(resolved(['93.184.216.34']))
190+
191+
const result = await validateDatabaseHost(host)
192+
193+
expect(result.isValid).toBe(false)
194+
expect(result.error).toContain('single hostname or IP address')
195+
expect(mockResolve).not.toHaveBeenCalled()
196+
})
197+
198+
it.each([
199+
['a DNS name', 'db.example.com'],
200+
['a service name with underscores', 'mongo_primary'],
201+
['a trailing-dot name', 'db.example.com.'],
202+
['a public IPv4 literal', '93.184.216.34'],
203+
['a bare IPv6 literal', '2606:4700::1111'],
204+
['a bracketed IPv6 literal', '[2606:4700::1111]'],
205+
])('accepts %s', async (_case, host) => {
206+
mockResolve.mockResolvedValue(resolved(['93.184.216.34']))
207+
208+
const result = await validateDatabaseHost(host)
209+
210+
expect(result.isValid).toBe(true)
211+
})
212+
})

‎apps/sim/lib/core/security/input-validation.server.ts‎

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import dns from 'node:dns/promises'
2+
import { isIP } from 'node:net'
23
import { Readable } from 'node:stream'
34
import zlib from 'node:zlib'
45
import http from 'http'
@@ -144,13 +145,34 @@ export async function validateAndPinProxyUrl(
144145
return { isValid: true, pinnedProxyUrl: parsed.toString() }
145146
}
146147

148+
/**
149+
* One DNS name: dot-separated labels of letters, digits, `-`, and `_` (Docker
150+
* and K8s service names carry underscores), with an optional trailing dot.
151+
*/
152+
const DATABASE_HOSTNAME_PATTERN =
153+
/^(?=.{1,253}\.?$)[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9_])?(?:\.[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9_])?)*\.?$/
154+
155+
/**
156+
* True when `host` names exactly one host: a DNS name, an IPv4 literal, or an
157+
* IPv6 literal (bracketed or bare, no zone id). Connection strings give `,`,
158+
* `/`, `@`, `?`, `#`, and `:` structural meaning, so a value carrying any of
159+
* them could name hosts, ports, or options the address check never judged.
160+
*/
161+
function isSingleDatabaseHost(host: string): boolean {
162+
const bare = host.startsWith('[') && host.endsWith(']') ? host.slice(1, -1) : host
163+
if (bare.includes(':')) return isIP(bare) === 6 && !bare.includes('%')
164+
return bare === host && DATABASE_HOSTNAME_PATTERN.test(host)
165+
}
166+
147167
/**
148168
* Validates a database hostname by resolving DNS and checking the resolved IP
149169
* against private/reserved ranges to prevent SSRF via database connections.
150170
*
151-
* Permissive about hostname format, so a legitimate database host is not
152-
* rejected on shape alone — Docker and K8s service names carry underscores that
153-
* a strict RFC check would refuse. Only the address is judged.
171+
* The value must be exactly one hostname or IP literal (see
172+
* {@link isSingleDatabaseHost}); a port, credentials, path, query, or second
173+
* host is refused before any lookup, because drivers that build a connection
174+
* string from it would otherwise connect to hosts this check never saw.
175+
* Underscores are accepted for Docker and K8s service names.
154176
*
155177
* Self-hosted operators reach a database on their private network (e.g. a
156178
* Docker/Swarm service name that resolves to an internal IP) by naming it in the
@@ -176,6 +198,13 @@ export async function validateDatabaseHost(
176198
return { isValid: false, error: `${paramName} is required` }
177199
}
178200

201+
if (!isSingleDatabaseHost(host.toLowerCase())) {
202+
return {
203+
isValid: false,
204+
error: `${paramName} must be a single hostname or IP address, without a port, credentials, path, or options`,
205+
}
206+
}
207+
179208
const cleanHost = unwrapIpv6Brackets(host.toLowerCase())
180209

181210
let asUrl: URL
Lines changed: 72 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,18 @@
1-
import {
2-
inputValidationMock,
3-
inputValidationMockFns,
4-
} from '@sim/testing/mocks/input-validation.mock'
1+
import { MongoClient } from 'mongodb'
52
import { beforeEach, describe, expect, it, vi } from 'vitest'
63

7-
const { mockClient, mockMongoClient } = vi.hoisted(() => {
8-
const client = {
9-
close: vi.fn().mockResolvedValue(undefined),
10-
connect: vi.fn(),
11-
}
12-
return {
13-
mockClient: client,
14-
mockMongoClient: vi.fn(function MockMongoClient() {
15-
return client
16-
}),
17-
}
18-
})
19-
20-
vi.mock('mongodb', () => ({ MongoClient: mockMongoClient }))
4+
const { mockResolve } = vi.hoisted(() => ({
5+
mockResolve: vi.fn(),
6+
}))
217

22-
vi.mock('@/lib/core/security/input-validation.server', () => inputValidationMock)
8+
vi.mock('@sim/security/dns', () => ({
9+
resolveHostAddresses: mockResolve,
10+
preferIpv4: (addresses: string[]) =>
11+
addresses.find((address) => address.includes('.')) ?? addresses[0],
12+
}))
2313

2414
import { createMongodbClient, type MongodbConnectionConfig } from '@/lib/internal/mongodb/client'
2515

26-
const { mockCreatePinnedLookup, mockValidateDatabaseHost } = inputValidationMockFns
27-
2816
const CONNECTION_CONFIG: MongodbConnectionConfig = {
2917
host: 'db.example.com',
3018
port: 27017,
@@ -36,33 +24,79 @@ const CONNECTION_CONFIG: MongodbConnectionConfig = {
3624
}
3725

3826
describe('MongoDB client', () => {
27+
let connect: ReturnType<typeof vi.spyOn>
28+
let close: ReturnType<typeof vi.spyOn>
29+
3930
beforeEach(() => {
40-
mockClient.close.mockResolvedValue(undefined)
41-
mockClient.connect.mockResolvedValue(mockClient)
42-
mockValidateDatabaseHost.mockResolvedValue({
43-
isValid: true,
44-
resolvedIP: '93.184.216.34',
45-
originalHostname: 'db.example.com',
31+
// A wildcard DNS zone answers any name, including one shaped like a seed list.
32+
mockResolve.mockResolvedValue({ addresses: ['93.184.216.34'], preferred: '93.184.216.34' })
33+
connect = vi.spyOn(MongoClient.prototype, 'connect').mockImplementation(async function (
34+
this: MongoClient
35+
) {
36+
return this
4637
})
47-
mockCreatePinnedLookup.mockReturnValue('pinned-lookup')
38+
close = vi.spyOn(MongoClient.prototype, 'close').mockResolvedValue(undefined)
4839
})
4940

50-
it('does not construct a client when DNS validation fails', async () => {
51-
mockValidateDatabaseHost.mockResolvedValue({
52-
isValid: false,
53-
error: 'host resolves to a blocked IP address',
54-
})
41+
it('connects to exactly the validated host, without following advertised members', async () => {
42+
const client = await createMongodbClient(CONNECTION_CONFIG)
43+
44+
expect(client.options.hosts.map(String)).toEqual(['db.example.com:27017'])
45+
expect(client.options.directConnection).toBe(true)
46+
expect(client.options.proxyHost).toBeUndefined()
47+
expect(client.options.loadBalanced).toBe(false)
48+
expect(client.options.tls).toBe(true)
49+
expect(client.options.credentials?.username).toBe('user@example.com')
50+
expect(client.options.credentials?.password).toBe('p@ss word')
51+
expect(client.options.credentials?.source).toBe('admin')
52+
})
53+
54+
it('authenticates against the database when no auth source is given', async () => {
55+
const client = await createMongodbClient({ ...CONNECTION_CONFIG, authSource: '' })
56+
57+
expect(client.options.credentials?.source).toBe('application')
58+
})
5559

56-
await expect(createMongodbClient(CONNECTION_CONFIG)).rejects.toThrow(
57-
'host resolves to a blocked IP address'
60+
it.each([
61+
['a seed list naming an internal address', '127.0.0.1:6379,db.example.com'],
62+
['a path and options after the host', 'db.example.com/admin?directConnection=false'],
63+
])('refuses %s as the host', async (_case, host) => {
64+
await expect(createMongodbClient({ ...CONNECTION_CONFIG, host })).rejects.toThrow(
65+
'host must be a single hostname or IP address'
5866
)
59-
expect(mockMongoClient).not.toHaveBeenCalled()
67+
expect(connect).not.toHaveBeenCalled()
68+
})
69+
70+
it.each([
71+
['connection-string options', 'db?directConnection=false&proxyHost=127.0.0.1&proxyPort=1080'],
72+
['a path separator', 'app/other'],
73+
['a dot', 'app.other'],
74+
['more than 63 bytes in fewer characters', 'é'.repeat(32)],
75+
])('refuses a database name carrying %s', async (_case, database) => {
76+
await expect(createMongodbClient({ ...CONNECTION_CONFIG, database })).rejects.toThrow(
77+
'database must be'
78+
)
79+
expect(connect).not.toHaveBeenCalled()
80+
})
81+
82+
it.each([0, 27017.5, 70000])('refuses port %s', async (port) => {
83+
await expect(createMongodbClient({ ...CONNECTION_CONFIG, port })).rejects.toThrow(
84+
'port must be an integer'
85+
)
86+
expect(connect).not.toHaveBeenCalled()
87+
})
88+
89+
it('does not connect when the host resolves to a private address', async () => {
90+
mockResolve.mockResolvedValue({ addresses: ['10.0.0.5'], preferred: '10.0.0.5' })
91+
92+
await expect(createMongodbClient(CONNECTION_CONFIG)).rejects.toThrow('private or reserved')
93+
expect(connect).not.toHaveBeenCalled()
6094
})
6195

6296
it('closes a partially connected client when connection fails', async () => {
63-
mockClient.connect.mockRejectedValue(new Error('handshake failed'))
97+
connect.mockRejectedValue(new Error('handshake failed'))
6498

6599
await expect(createMongodbClient(CONNECTION_CONFIG)).rejects.toThrow('handshake failed')
66-
expect(mockClient.close).toHaveBeenCalledOnce()
100+
expect(close).toHaveBeenCalledOnce()
67101
})
68102
})

‎apps/sim/lib/internal/mongodb/client.ts‎

Lines changed: 43 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { isIP } from 'node:net'
2+
import { unwrapIpv6Brackets } from '@sim/security/ssrf'
13
import { MongoClient } from 'mongodb'
24
import {
35
createPinnedLookup,
@@ -14,38 +16,65 @@ export interface MongodbConnectionConfig {
1416
ssl?: 'disabled' | 'required' | 'preferred'
1517
}
1618

19+
/**
20+
* MongoDB's database-name rules: 1–63 bytes, none of `/\. "$*<>:|?` or NUL.
21+
* The driver itself only refuses a few of these, so check the full set up front.
22+
*/
23+
const INVALID_DATABASE_NAME_CHARACTERS = /[/\\. "$*<>:|?\0]/
24+
25+
function assertValidDatabaseName(database: string): void {
26+
if (
27+
database.length === 0 ||
28+
Buffer.byteLength(database, 'utf8') > 63 ||
29+
INVALID_DATABASE_NAME_CHARACTERS.test(database)
30+
) {
31+
throw new Error(
32+
'database must be 1-63 bytes and cannot contain /, \\, ., spaces, ", $, *, <, >, :, |, or ?'
33+
)
34+
}
35+
}
36+
37+
/**
38+
* Connects to exactly the validated host. Only the host and port enter the
39+
* connection string, both checked first; every other setting goes through the
40+
* options object so no field can add hosts or connection-string options, and
41+
* `directConnection` keeps the driver from following hosts a server advertises.
42+
*/
1743
export async function createMongodbClient(
1844
config: MongodbConnectionConfig,
1945
signal?: AbortSignal
2046
): Promise<MongoClient> {
2147
signal?.throwIfAborted()
48+
if (!Number.isInteger(config.port) || config.port < 1 || config.port > 65535) {
49+
throw new Error('port must be an integer between 1 and 65535')
50+
}
51+
assertValidDatabaseName(config.database)
52+
2253
const hostValidation = await validateDatabaseHost(config.host, 'host')
2354
signal?.throwIfAborted()
2455

2556
if (!hostValidation.isValid) {
2657
throw new Error(hostValidation.error)
2758
}
2859

60+
const host = unwrapIpv6Brackets(config.host)
61+
const uriHost = isIP(host) === 6 ? `[${host}]` : host
2962
const credentials =
3063
config.username && config.password
31-
? `${encodeURIComponent(config.username)}:${encodeURIComponent(config.password)}@`
32-
: ''
33-
const queryParams = new URLSearchParams()
34-
35-
if (config.authSource) {
36-
queryParams.append('authSource', config.authSource)
37-
}
38-
if (config.ssl === 'required') {
39-
queryParams.append('ssl', 'true')
40-
}
64+
? {
65+
auth: { username: config.username, password: config.password },
66+
authSource: config.authSource || config.database,
67+
}
68+
: {}
4169

42-
const queryString = queryParams.toString()
43-
const uri = `mongodb://${credentials}${config.host}:${config.port}/${config.database}${queryString ? `?${queryString}` : ''}`
44-
const client = new MongoClient(uri, {
70+
const client = new MongoClient(`mongodb://${uriHost}:${config.port}/`, {
71+
...credentials,
72+
directConnection: true,
73+
...(config.ssl === 'required' ? { tls: true } : {}),
4574
connectTimeoutMS: 10000,
4675
socketTimeoutMS: 10000,
4776
maxPoolSize: 1,
48-
lookup: createPinnedLookup(hostValidation.resolvedIP ?? config.host),
77+
lookup: createPinnedLookup(hostValidation.resolvedIP ?? host),
4978
})
5079
let rejectAbort: ((reason: unknown) => void) | undefined
5180
const abortPromise = signal

‎apps/sim/lib/internal/sftp/client.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ export async function createSftpConnection(config: SftpConnectionConfig): Promis
9090
}
9191
config.signal?.throwIfAborted()
9292

93-
const hostValidation = await validateDatabaseHost(host, 'host')
93+
const hostValidation = await validateDatabaseHost(host.trim(), 'host')
9494
config.signal?.throwIfAborted()
9595
if (!hostValidation.isValid) throw new Error(hostValidation.error)
9696

‎apps/sim/lib/internal/ssh/client.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ export async function createSSHConnection(
111111
throw new Error('Host is required. Please provide a valid hostname or IP address.')
112112
}
113113

114-
const hostValidation = await validateDatabaseHost(host, 'host')
114+
const hostValidation = await validateDatabaseHost(host.trim(), 'host')
115115
signal?.throwIfAborted()
116116
if (!hostValidation.isValid) {
117117
throw new Error(hostValidation.error)

0 commit comments

Comments
 (0)