From 3f9255074af9433fde3c2c9d6bd65dc295128918 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 28 Nov 2026 04:24:00 -0800 Subject: [PATCH 1/3] fix(neo4j): connect TLS sessions to the validated address --- apps/sim/lib/internal/neo4j/client.test.ts | 146 +++++++++++++++ apps/sim/lib/internal/neo4j/client.ts | 170 ++++++++++++++++-- .../sim/lib/internal/neo4j/operations.test.ts | 6 +- apps/sim/lib/internal/neo4j/operations.ts | 14 +- 4 files changed, 310 insertions(+), 26 deletions(-) create mode 100644 apps/sim/lib/internal/neo4j/client.test.ts diff --git a/apps/sim/lib/internal/neo4j/client.test.ts b/apps/sim/lib/internal/neo4j/client.test.ts new file mode 100644 index 00000000000..80ec7792fe8 --- /dev/null +++ b/apps/sim/lib/internal/neo4j/client.test.ts @@ -0,0 +1,146 @@ +import { execFile } from 'node:child_process' +import { mkdtempSync, readFileSync, rmSync } from 'node:fs' +import type { AddressInfo, Socket } from 'node:net' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { + createServer as createTlsServer, + getCACertificates, + setDefaultCACertificates, +} from 'node:tls' +import { promisify } from 'node:util' +import { + inputValidationMock, + inputValidationMockFns, +} from '@sim/testing/mocks/input-validation.mock' +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@/lib/core/security/input-validation.server', () => inputValidationMock) + +import { openNeo4jConnection } from '@/lib/internal/neo4j/client' + +/** `.invalid` never resolves, so only a connection pinned to the validated IP can reach the server. */ +const DATABASE_HOST = 'neo4j.invalid' +const BOLT_MAGIC = '6060b017' + +interface TlsDatabase { + port: number + /** SNI and first application bytes of every TLS session that completed. */ + sessions: Array<{ servername: string | false; firstBytes: string }> + close: () => Promise +} + +const certificateDirectory = mkdtempSync(join(tmpdir(), 'neo4j-tls-')) +const certificates: Record = {} +const defaultCertificates = getCACertificates('default') + +async function issueCertificate(name: string) { + const certPath = join(certificateDirectory, `${name}.crt`) + const keyPath = join(certificateDirectory, `${name}.key`) + await promisify(execFile)('openssl', [ + 'req', + '-x509', + '-newkey', + 'rsa:2048', + '-sha256', + '-nodes', + '-keyout', + keyPath, + '-out', + certPath, + '-days', + '2', + '-subj', + `/CN=${name}`, + '-addext', + `subjectAltName=DNS:${name}`, + ]) + certificates[name] = { cert: readFileSync(certPath, 'utf8'), key: readFileSync(keyPath, 'utf8') } +} + +/** A TLS listener that records the session, then hangs up: enough to see what the driver sent. */ +async function startTlsDatabase(certificateName: string): Promise { + const sessions: TlsDatabase['sessions'] = [] + const sockets = new Set() + const server = createTlsServer(certificates[certificateName], (socket) => { + socket.once('data', (chunk: Buffer) => { + sessions.push({ + servername: socket.servername, + firstBytes: chunk.subarray(0, 4).toString('hex'), + }) + socket.destroy() + }) + }) + server.on('connection', (socket) => { + sockets.add(socket) + socket.on('close', () => sockets.delete(socket)) + }) + server.on('tlsClientError', () => {}) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + return { + port: (server.address() as AddressInfo).port, + sessions, + close: () => + new Promise((resolve) => { + for (const socket of sockets) socket.destroy() + server.close(() => resolve()) + }), + } +} + +describe('openNeo4jConnection with encryption enabled', () => { + beforeAll(async () => { + await issueCertificate(DATABASE_HOST) + await issueCertificate('other.invalid') + setDefaultCACertificates([ + ...defaultCertificates, + certificates[DATABASE_HOST].cert, + certificates['other.invalid'].cert, + ]) + }) + + afterAll(() => { + setDefaultCACertificates(defaultCertificates) + rmSync(certificateDirectory, { recursive: true, force: true }) + }) + + beforeEach(() => { + inputValidationMockFns.mockValidateDatabaseHost.mockResolvedValue({ + isValid: true, + resolvedIP: '127.0.0.1', + originalHostname: DATABASE_HOST, + }) + }) + + const open = (port: number) => + openNeo4jConnection({ + host: DATABASE_HOST, + port, + database: 'neo4j', + username: 'neo4j', + password: 'secret', + encryption: 'enabled', + }) + + it('carries Bolt over TLS to the validated IP with the hostname as SNI', async () => { + const database = await startTlsDatabase(DATABASE_HOST) + try { + await expect(open(database.port)).rejects.toThrow() + expect(database.sessions[0]).toEqual({ servername: DATABASE_HOST, firstBytes: BOLT_MAGIC }) + } finally { + await database.close() + } + }) + + it('refuses a certificate issued for another hostname before sending any Bolt bytes', async () => { + const database = await startTlsDatabase('other.invalid') + try { + await expect(open(database.port)).rejects.toThrow( + /Failed to connect to server.*Caused by: Hostname\/IP does not match certificate's altnames/ + ) + expect(database.sessions).toEqual([]) + } finally { + await database.close() + } + }) +}) diff --git a/apps/sim/lib/internal/neo4j/client.ts b/apps/sim/lib/internal/neo4j/client.ts index 89ae5de8e40..c82090cdbc8 100644 --- a/apps/sim/lib/internal/neo4j/client.ts +++ b/apps/sim/lib/internal/neo4j/client.ts @@ -1,49 +1,185 @@ +import { createServer as createTcpServer, isIP, type Socket } from 'node:net' +import { checkServerIdentity, connect as connectTls } from 'node:tls' import neo4j, { type Driver } from 'neo4j-driver' import { validateDatabaseHost } from '@/lib/core/security/input-validation.server' import type { Neo4jConnectionConfig } from '@/tools/neo4j/types' +const CONNECTION_TIMEOUT_MS = 10_000 +/** The driver pools one connection; the rest of the budget covers reconnects after a drop. */ +const MAX_RELAYED_CONNECTIONS = 4 +const CONNECT_FAILURE_PREFIX = + 'Failed to connect to server. Please ensure that your database is listening on the correct host and port and that you have compatible encryption settings both on Neo4j server and driver.' + +/** An open Neo4j driver and everything that must be released with it. */ +export interface Neo4jConnection { + driver: Driver + close: () => Promise +} + +interface PinnedTlsRelay { + port: number + failure: () => Error | undefined + close: () => Promise +} + function isAuraHost(host: string): boolean { return host === 'databases.neo4j.io' || host.endsWith('.databases.neo4j.io') } -export async function createNeo4jDriver( +/** + * Accepts the driver's plaintext Bolt on loopback and carries it over TLS to the already + * validated `address`, sending `serverName` as SNI and verifying the certificate against it. + * + * The driver's direct `bolt+s` channel connects by name, so the host would be resolved again + * after validation (DNS rebinding), and neo4j-driver has no supported way to pin the address + * while keeping hostname verification. The relay owns TLS instead, against the pinned IP. + */ +async function startPinnedTlsRelay(target: { + address: string + port: number + serverName: string +}): Promise { + const sockets = new Set() + let accepted = 0 + let lastFailure: Error | undefined + let closePromise: Promise | undefined + + const server = createTcpServer((client) => { + accepted += 1 + sockets.add(client) + client.once('close', () => sockets.delete(client)) + if (accepted > MAX_RELAYED_CONNECTIONS) { + client.destroy() + return + } + + const upstream = connectTls({ + host: target.address, + port: target.port, + servername: isIP(target.serverName) ? undefined : target.serverName, + checkServerIdentity: (_name, certificate) => + checkServerIdentity(target.serverName, certificate), + rejectUnauthorized: true, + }) + sockets.add(upstream) + upstream.setNoDelay(true) + upstream.setTimeout(CONNECTION_TIMEOUT_MS) + + const finish = () => { + sockets.delete(upstream) + client.destroy() + upstream.destroy() + } + upstream.once('secureConnect', () => { + upstream.setTimeout(0) + client.pipe(upstream) + upstream.pipe(client) + }) + upstream.once('timeout', () => { + lastFailure = new Error(`Failed to establish connection in ${CONNECTION_TIMEOUT_MS}ms`) + finish() + }) + upstream.once('error', (error) => { + lastFailure = error + finish() + }) + upstream.once('close', finish) + client.once('error', finish) + client.once('close', finish) + }) + + await new Promise((resolve, reject) => { + server.once('error', reject) + server.listen(0, '127.0.0.1', () => { + server.removeListener('error', reject) + resolve() + }) + }) + + const address = server.address() + if (!address || typeof address === 'string') { + server.close() + throw new Error('Neo4j TLS relay did not bind a TCP port') + } + + return { + port: address.port, + failure: () => lastFailure, + close: () => { + closePromise ??= new Promise((resolve) => { + for (const socket of sockets) socket.destroy() + server.close(() => resolve()) + }) + return closePromise + }, + } +} + +/** + * Opens a verified Neo4j driver for a validated host. + * + * - Encryption off: plain `bolt` straight to the validated IP. + * - Encryption on: plain `bolt` to {@link startPinnedTlsRelay}, which reaches the validated IP + * over TLS with SNI and certificate hostname verification against the configured host. + * - Aura (`*.databases.neo4j.io`): the driver's own `neo4j+s` routing, by name. Those hosts and + * the routing table they return are operated by Neo4j, not chosen by the caller. + */ +export async function openNeo4jConnection( config: Neo4jConnectionConfig, signal?: AbortSignal -): Promise { +): Promise { signal?.throwIfAborted() const hostValidation = await validateDatabaseHost(config.host, 'host') signal?.throwIfAborted() if (!hostValidation.isValid) throw new Error(hostValidation.error) const aura = isAuraHost(config.host) - const protocol = aura ? 'neo4j+s' : config.encryption === 'enabled' ? 'bolt+s' : 'bolt' - const usePinnedIp = !protocol.endsWith('+s') const resolvedHost = hostValidation.resolvedIP ?? config.host - const uriHost = usePinnedIp - ? resolvedHost.includes(':') - ? `[${resolvedHost}]` - : resolvedHost - : config.host - const uri = `${protocol}://${uriHost}:${config.port}` + const relay = + !aura && config.encryption === 'enabled' + ? await startPinnedTlsRelay({ + address: resolvedHost, + port: config.port, + serverName: config.host.replace(/^\[|\]$/g, ''), + }) + : undefined + + let uri: string + if (aura) { + uri = `neo4j+s://${config.host}:${config.port}` + } else if (relay) { + uri = `bolt://127.0.0.1:${relay.port}` + } else { + uri = `bolt://${resolvedHost.includes(':') ? `[${resolvedHost}]` : resolvedHost}:${config.port}` + } const driverConfig: Exclude[2], undefined> = { maxConnectionPoolSize: 1, - connectionTimeout: 10_000, - } - if (!protocol.endsWith('+s')) { - driverConfig.encrypted = config.encryption === 'enabled' ? 'ENCRYPTION_ON' : 'ENCRYPTION_OFF' + connectionTimeout: CONNECTION_TIMEOUT_MS, } + if (!aura) driverConfig.encrypted = 'ENCRYPTION_OFF' const driver = neo4j.driver(uri, neo4j.auth.basic(config.username, config.password), driverConfig) + const close = async () => { + try { + await driver.close() + } finally { + await relay?.close() + } + } const abort = () => { - void driver.close() + void close() } signal?.addEventListener('abort', abort, { once: true }) try { await driver.verifyConnectivity() signal?.throwIfAborted() - return driver + return { driver, close } } catch (error) { - await driver.close().catch(() => undefined) + await close().catch(() => undefined) + const relayFailure = relay?.failure() + if (relayFailure && !signal?.aborted) { + throw new Error(`${CONNECT_FAILURE_PREFIX} Caused by: ${relayFailure.message}`) + } throw error } finally { signal?.removeEventListener('abort', abort) diff --git a/apps/sim/lib/internal/neo4j/operations.test.ts b/apps/sim/lib/internal/neo4j/operations.test.ts index 54c7b104f06..34e24d73aaa 100644 --- a/apps/sim/lib/internal/neo4j/operations.test.ts +++ b/apps/sim/lib/internal/neo4j/operations.test.ts @@ -8,7 +8,7 @@ const mocks = vi.hoisted(() => ({ })) vi.mock('@/lib/internal/neo4j/client', () => ({ - createNeo4jDriver: mocks.createDriver, + openNeo4jConnection: mocks.createDriver, })) import { isPayloadSizeLimitError } from '@/lib/core/utils/stream-limits' @@ -69,7 +69,9 @@ describe('Neo4j operations', () => { mocks.sessionClose.mockResolvedValue(undefined) mocks.driverClose.mockResolvedValue(undefined) mocks.createDriver.mockResolvedValue({ - session: vi.fn().mockReturnValue({ run: mocks.run, close: mocks.sessionClose }), + driver: { + session: vi.fn().mockReturnValue({ run: mocks.run, close: mocks.sessionClose }), + }, close: mocks.driverClose, }) }) diff --git a/apps/sim/lib/internal/neo4j/operations.ts b/apps/sim/lib/internal/neo4j/operations.ts index 0e644a1e653..23cff8d2a60 100644 --- a/apps/sim/lib/internal/neo4j/operations.ts +++ b/apps/sim/lib/internal/neo4j/operations.ts @@ -9,7 +9,7 @@ import type { Neo4jQueryRequest, Neo4jUpdateRequest, } from '@/lib/api/contracts/tools/databases/neo4j' -import { createNeo4jDriver } from '@/lib/internal/neo4j/client' +import { openNeo4jConnection } from '@/lib/internal/neo4j/client' import { convertNeo4jValue } from '@/lib/internal/neo4j/values' import { createResponseRowsBudget } from '@/lib/internal/tool-operations/response-limits' import type { Neo4jNodeSchema, Neo4jRelationshipSchema } from '@/tools/neo4j/types' @@ -150,8 +150,8 @@ function statementResponse( async function executeStatement(input: StatementInput, kind: StatementKind, signal?: AbortSignal) { signal?.throwIfAborted() validateCypherQuery(input.cypherQuery) - const driver = await createNeo4jDriver({ ...input, port: Number(input.port) }, signal) - const session = driver.session({ database: input.database }) + const connection = await openNeo4jConnection({ ...input, port: Number(input.port) }, signal) + const session = connection.driver.session({ database: input.database }) const unbindAbort = bindSessionAbort(session, signal) try { const result = await readResult(session.run(input.cypherQuery, input.parameters ?? {}), kind) @@ -160,7 +160,7 @@ async function executeStatement(input: StatementInput, kind: StatementKind, sign } finally { unbindAbort() await session.close().catch(() => undefined) - await driver.close().catch(() => undefined) + await connection.close().catch(() => undefined) } } @@ -188,8 +188,8 @@ export async function executeNeo4jIntrospection( signal?: AbortSignal ) { signal?.throwIfAborted() - const driver = await createNeo4jDriver({ ...input, port: Number(input.port) }, signal) - const session = driver.session({ database: input.database }) + const connection = await openNeo4jConnection({ ...input, port: Number(input.port) }, signal) + const session = connection.driver.session({ database: input.database }) const unbindAbort = bindSessionAbort(session, signal) try { const labelsResult = await session.run( @@ -298,6 +298,6 @@ export async function executeNeo4jIntrospection( } finally { unbindAbort() await session.close().catch(() => undefined) - await driver.close().catch(() => undefined) + await connection.close().catch(() => undefined) } } From 4dda30172cb4063679518a41a2355413efe3a977 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 28 Nov 2026 04:37:14 -0800 Subject: [PATCH 2/3] fix(neo4j): bound the port and honour aborts during relay setup --- apps/sim/lib/api/contracts/tools/databases/neo4j.ts | 6 +++++- apps/sim/lib/internal/neo4j/client.test.ts | 8 ++++++-- apps/sim/lib/internal/neo4j/client.ts | 7 +++++++ 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/apps/sim/lib/api/contracts/tools/databases/neo4j.ts b/apps/sim/lib/api/contracts/tools/databases/neo4j.ts index 5077dc21abe..0d8f41bb028 100644 --- a/apps/sim/lib/api/contracts/tools/databases/neo4j.ts +++ b/apps/sim/lib/api/contracts/tools/databases/neo4j.ts @@ -12,7 +12,11 @@ import { export const neo4jConnectionBodySchema = z.object({ host: z.string().min(1, 'Host is required'), - port: z.coerce.number().int().positive('Port must be a positive integer'), + port: z.coerce + .number() + .int() + .min(1, 'Port must be between 1 and 65535') + .max(65_535, 'Port must be between 1 and 65535'), database: z.string().min(1, 'Database name is required'), username: z.string().min(1, 'Username is required'), password: z.string().min(1, 'Password is required'), diff --git a/apps/sim/lib/internal/neo4j/client.test.ts b/apps/sim/lib/internal/neo4j/client.test.ts index 80ec7792fe8..ab35de65a9d 100644 --- a/apps/sim/lib/internal/neo4j/client.test.ts +++ b/apps/sim/lib/internal/neo4j/client.test.ts @@ -26,7 +26,7 @@ const BOLT_MAGIC = '6060b017' interface TlsDatabase { port: number /** SNI and first application bytes of every TLS session that completed. */ - sessions: Array<{ servername: string | false; firstBytes: string }> + sessions: Array<{ servername: string | undefined; firstBytes: string }> close: () => Promise } @@ -65,7 +65,7 @@ async function startTlsDatabase(certificateName: string): Promise { const server = createTlsServer(certificates[certificateName], (socket) => { socket.once('data', (chunk: Buffer) => { sessions.push({ - servername: socket.servername, + servername: socket.servername || undefined, firstBytes: chunk.subarray(0, 4).toString('hex'), }) socket.destroy() @@ -143,4 +143,8 @@ describe('openNeo4jConnection with encryption enabled', () => { await database.close() } }) + + it('rejects an out-of-range port instead of throwing from the relay', async () => { + await expect(open(65_536)).rejects.toThrow('Port must be an integer between 1 and 65535') + }) }) diff --git a/apps/sim/lib/internal/neo4j/client.ts b/apps/sim/lib/internal/neo4j/client.ts index c82090cdbc8..bf75e618c03 100644 --- a/apps/sim/lib/internal/neo4j/client.ts +++ b/apps/sim/lib/internal/neo4j/client.ts @@ -129,6 +129,9 @@ export async function openNeo4jConnection( signal?: AbortSignal ): Promise { signal?.throwIfAborted() + if (!Number.isInteger(config.port) || config.port < 1 || config.port > 65_535) { + throw new Error('Port must be an integer between 1 and 65535') + } const hostValidation = await validateDatabaseHost(config.host, 'host') signal?.throwIfAborted() if (!hostValidation.isValid) throw new Error(hostValidation.error) @@ -143,6 +146,10 @@ export async function openNeo4jConnection( serverName: config.host.replace(/^\[|\]$/g, ''), }) : undefined + if (signal?.aborted) { + await relay?.close() + signal.throwIfAborted() + } let uri: string if (aura) { From 949d4bb678c84c0a77c4c6913b30793d66c2e90c Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 28 Nov 2026 05:15:52 -0800 Subject: [PATCH 3/3] fix(neo4j): keep the driver error on relay failures and move socket tests to integration --- .../lib/internal/neo4j/client.integration.ts | 156 ++++++++++++++++++ apps/sim/lib/internal/neo4j/client.test.ts | 148 ++--------------- apps/sim/lib/internal/neo4j/client.ts | 5 +- 3 files changed, 172 insertions(+), 137 deletions(-) create mode 100644 apps/sim/lib/internal/neo4j/client.integration.ts diff --git a/apps/sim/lib/internal/neo4j/client.integration.ts b/apps/sim/lib/internal/neo4j/client.integration.ts new file mode 100644 index 00000000000..1a898e5f725 --- /dev/null +++ b/apps/sim/lib/internal/neo4j/client.integration.ts @@ -0,0 +1,156 @@ +/** + * Encrypted connections against a real loopback TLS listener: what reaches the wire (address, + * SNI, first Bolt bytes) is only observable on a socket. + */ +import { execFile } from 'node:child_process' +import { mkdtempSync, readFileSync, rmSync } from 'node:fs' +import type { AddressInfo, Socket } from 'node:net' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { + createServer as createTlsServer, + getCACertificates, + setDefaultCACertificates, +} from 'node:tls' +import { promisify } from 'node:util' +import { + inputValidationMock, + inputValidationMockFns, +} from '@sim/testing/mocks/input-validation.mock' +import { Neo4jError } from 'neo4j-driver' +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@/lib/core/security/input-validation.server', () => inputValidationMock) + +import { openNeo4jConnection } from '@/lib/internal/neo4j/client' + +/** `.invalid` never resolves, so only a connection pinned to the validated IP can reach the server. */ +const DATABASE_HOST = 'neo4j.invalid' +const BOLT_MAGIC = '6060b017' + +interface TlsDatabase { + port: number + /** SNI and first application bytes of every TLS session that completed. */ + sessions: Array<{ servername: string | undefined; firstBytes: string }> + close: () => Promise +} + +const certificateDirectory = mkdtempSync(join(tmpdir(), 'neo4j-tls-')) +const certificates: Record = {} +const defaultCertificates = getCACertificates('default') + +async function issueCertificate(name: string) { + const certPath = join(certificateDirectory, `${name}.crt`) + const keyPath = join(certificateDirectory, `${name}.key`) + await promisify(execFile)('openssl', [ + 'req', + '-x509', + '-newkey', + 'rsa:2048', + '-sha256', + '-nodes', + '-keyout', + keyPath, + '-out', + certPath, + '-days', + '2', + '-subj', + `/CN=${name}`, + '-addext', + `subjectAltName=DNS:${name}`, + ]) + certificates[name] = { cert: readFileSync(certPath, 'utf8'), key: readFileSync(keyPath, 'utf8') } +} + +/** A TLS listener that records the session, then hangs up: enough to see what the driver sent. */ +async function startTlsDatabase(certificateName: string): Promise { + const sessions: TlsDatabase['sessions'] = [] + const sockets = new Set() + const server = createTlsServer(certificates[certificateName], (socket) => { + socket.once('data', (chunk: Buffer) => { + sessions.push({ + servername: socket.servername || undefined, + firstBytes: chunk.subarray(0, 4).toString('hex'), + }) + socket.destroy() + }) + }) + server.on('connection', (socket) => { + sockets.add(socket) + socket.on('close', () => sockets.delete(socket)) + }) + server.on('tlsClientError', () => {}) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + return { + port: (server.address() as AddressInfo).port, + sessions, + close: () => + new Promise((resolve) => { + for (const socket of sockets) socket.destroy() + server.close(() => resolve()) + }), + } +} + +describe('openNeo4jConnection with encryption enabled', () => { + beforeAll(async () => { + await issueCertificate(DATABASE_HOST) + await issueCertificate('other.invalid') + setDefaultCACertificates([ + ...defaultCertificates, + certificates[DATABASE_HOST].cert, + certificates['other.invalid'].cert, + ]) + }) + + afterAll(() => { + setDefaultCACertificates(defaultCertificates) + rmSync(certificateDirectory, { recursive: true, force: true }) + }) + + beforeEach(() => { + inputValidationMockFns.mockValidateDatabaseHost.mockResolvedValue({ + isValid: true, + resolvedIP: '127.0.0.1', + originalHostname: DATABASE_HOST, + }) + }) + + const open = (port: number) => + openNeo4jConnection({ + host: DATABASE_HOST, + port, + database: 'neo4j', + username: 'neo4j', + password: 'secret', + encryption: 'enabled', + }) + + it('carries Bolt over TLS to the validated IP with the hostname as SNI', async () => { + const database = await startTlsDatabase(DATABASE_HOST) + try { + await expect(open(database.port)).rejects.toThrow() + expect(database.sessions[0]).toEqual({ servername: DATABASE_HOST, firstBytes: BOLT_MAGIC }) + } finally { + await database.close() + } + }) + + it('refuses a certificate issued for another hostname before sending any Bolt bytes', async () => { + const database = await startTlsDatabase('other.invalid') + try { + const error = await open(database.port).catch((caught: unknown) => caught) + expect(error).toBeInstanceOf(Neo4jError) + expect(error).toMatchObject({ + code: 'ServiceUnavailable', + message: expect.stringMatching( + /Failed to connect to server.*Caused by: Hostname\/IP does not match certificate's altnames/ + ), + }) + expect(database.sessions).toEqual([]) + } finally { + await database.close() + } + }) +}) diff --git a/apps/sim/lib/internal/neo4j/client.test.ts b/apps/sim/lib/internal/neo4j/client.test.ts index ab35de65a9d..267c8e28b67 100644 --- a/apps/sim/lib/internal/neo4j/client.test.ts +++ b/apps/sim/lib/internal/neo4j/client.test.ts @@ -1,150 +1,28 @@ -import { execFile } from 'node:child_process' -import { mkdtempSync, readFileSync, rmSync } from 'node:fs' -import type { AddressInfo, Socket } from 'node:net' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { - createServer as createTlsServer, - getCACertificates, - setDefaultCACertificates, -} from 'node:tls' -import { promisify } from 'node:util' import { inputValidationMock, inputValidationMockFns, } from '@sim/testing/mocks/input-validation.mock' -import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' +import { describe, expect, it, vi } from 'vitest' vi.mock('@/lib/core/security/input-validation.server', () => inputValidationMock) import { openNeo4jConnection } from '@/lib/internal/neo4j/client' -/** `.invalid` never resolves, so only a connection pinned to the validated IP can reach the server. */ -const DATABASE_HOST = 'neo4j.invalid' -const BOLT_MAGIC = '6060b017' - -interface TlsDatabase { - port: number - /** SNI and first application bytes of every TLS session that completed. */ - sessions: Array<{ servername: string | undefined; firstBytes: string }> - close: () => Promise -} - -const certificateDirectory = mkdtempSync(join(tmpdir(), 'neo4j-tls-')) -const certificates: Record = {} -const defaultCertificates = getCACertificates('default') - -async function issueCertificate(name: string) { - const certPath = join(certificateDirectory, `${name}.crt`) - const keyPath = join(certificateDirectory, `${name}.key`) - await promisify(execFile)('openssl', [ - 'req', - '-x509', - '-newkey', - 'rsa:2048', - '-sha256', - '-nodes', - '-keyout', - keyPath, - '-out', - certPath, - '-days', - '2', - '-subj', - `/CN=${name}`, - '-addext', - `subjectAltName=DNS:${name}`, - ]) - certificates[name] = { cert: readFileSync(certPath, 'utf8'), key: readFileSync(keyPath, 'utf8') } -} - -/** A TLS listener that records the session, then hangs up: enough to see what the driver sent. */ -async function startTlsDatabase(certificateName: string): Promise { - const sessions: TlsDatabase['sessions'] = [] - const sockets = new Set() - const server = createTlsServer(certificates[certificateName], (socket) => { - socket.once('data', (chunk: Buffer) => { - sessions.push({ - servername: socket.servername || undefined, - firstBytes: chunk.subarray(0, 4).toString('hex'), - }) - socket.destroy() - }) - }) - server.on('connection', (socket) => { - sockets.add(socket) - socket.on('close', () => sockets.delete(socket)) - }) - server.on('tlsClientError', () => {}) - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - return { - port: (server.address() as AddressInfo).port, - sessions, - close: () => - new Promise((resolve) => { - for (const socket of sockets) socket.destroy() - server.close(() => resolve()) - }), - } -} - -describe('openNeo4jConnection with encryption enabled', () => { - beforeAll(async () => { - await issueCertificate(DATABASE_HOST) - await issueCertificate('other.invalid') - setDefaultCACertificates([ - ...defaultCertificates, - certificates[DATABASE_HOST].cert, - certificates['other.invalid'].cert, - ]) - }) - - afterAll(() => { - setDefaultCACertificates(defaultCertificates) - rmSync(certificateDirectory, { recursive: true, force: true }) - }) - - beforeEach(() => { +describe('openNeo4jConnection', () => { + it('rejects an out-of-range port instead of throwing from the relay', async () => { inputValidationMockFns.mockValidateDatabaseHost.mockResolvedValue({ isValid: true, resolvedIP: '127.0.0.1', - originalHostname: DATABASE_HOST, - }) - }) - - const open = (port: number) => - openNeo4jConnection({ - host: DATABASE_HOST, - port, - database: 'neo4j', - username: 'neo4j', - password: 'secret', - encryption: 'enabled', }) - - it('carries Bolt over TLS to the validated IP with the hostname as SNI', async () => { - const database = await startTlsDatabase(DATABASE_HOST) - try { - await expect(open(database.port)).rejects.toThrow() - expect(database.sessions[0]).toEqual({ servername: DATABASE_HOST, firstBytes: BOLT_MAGIC }) - } finally { - await database.close() - } - }) - - it('refuses a certificate issued for another hostname before sending any Bolt bytes', async () => { - const database = await startTlsDatabase('other.invalid') - try { - await expect(open(database.port)).rejects.toThrow( - /Failed to connect to server.*Caused by: Hostname\/IP does not match certificate's altnames/ - ) - expect(database.sessions).toEqual([]) - } finally { - await database.close() - } - }) - - it('rejects an out-of-range port instead of throwing from the relay', async () => { - await expect(open(65_536)).rejects.toThrow('Port must be an integer between 1 and 65535') + await expect( + openNeo4jConnection({ + host: 'neo4j.invalid', + port: 65_536, + database: 'neo4j', + username: 'neo4j', + password: 'secret', + encryption: 'enabled', + }) + ).rejects.toThrow('Port must be an integer between 1 and 65535') }) }) diff --git a/apps/sim/lib/internal/neo4j/client.ts b/apps/sim/lib/internal/neo4j/client.ts index bf75e618c03..3fccb24cc53 100644 --- a/apps/sim/lib/internal/neo4j/client.ts +++ b/apps/sim/lib/internal/neo4j/client.ts @@ -184,8 +184,9 @@ export async function openNeo4jConnection( } catch (error) { await close().catch(() => undefined) const relayFailure = relay?.failure() - if (relayFailure && !signal?.aborted) { - throw new Error(`${CONNECT_FAILURE_PREFIX} Caused by: ${relayFailure.message}`) + if (relayFailure && !signal?.aborted && error instanceof neo4j.Neo4jError) { + error.message = `${CONNECT_FAILURE_PREFIX} Caused by: ${relayFailure.message}` + error.cause = relayFailure } throw error } finally {