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.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 new file mode 100644 index 00000000000..267c8e28b67 --- /dev/null +++ b/apps/sim/lib/internal/neo4j/client.test.ts @@ -0,0 +1,28 @@ +import { + inputValidationMock, + inputValidationMockFns, +} from '@sim/testing/mocks/input-validation.mock' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@/lib/core/security/input-validation.server', () => inputValidationMock) + +import { openNeo4jConnection } from '@/lib/internal/neo4j/client' + +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', + }) + 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 89ae5de8e40..3fccb24cc53 100644 --- a/apps/sim/lib/internal/neo4j/client.ts +++ b/apps/sim/lib/internal/neo4j/client.ts @@ -1,49 +1,193 @@ +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() + 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) 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 + if (signal?.aborted) { + await relay?.close() + signal.throwIfAborted() + } + + 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 && error instanceof neo4j.Neo4jError) { + error.message = `${CONNECT_FAILURE_PREFIX} Caused by: ${relayFailure.message}` + error.cause = relayFailure + } 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) } }