|
| 1 | +/** |
| 2 | + * A saved PostgreSQL connection end to end against a real server: saving |
| 3 | + * proves the login with SELECT 1 through the PostgreSQL tools' own guarded |
| 4 | + * connection path, and a run reads the stored connection inside the tool |
| 5 | + * operation, bound to the run's workspace, whatever connection fields the |
| 6 | + * call carries. |
| 7 | + */ |
| 8 | + |
| 9 | +import { db } from '@sim/db' |
| 10 | +import { credential, permissions, user, workspace } from '@sim/db/schema' |
| 11 | +import { readTestDatabaseUrl } from '@sim/db/testing/test-infrastructure' |
| 12 | +import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' |
| 13 | +import { posthogServerMock } from '@sim/testing/mocks/posthog-server.mock' |
| 14 | +import { generateId } from '@sim/utils/id' |
| 15 | +import { eq, inArray } from 'drizzle-orm' |
| 16 | +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' |
| 17 | + |
| 18 | +vi.mock('@/lib/posthog/server', () => posthogServerMock) |
| 19 | + |
| 20 | +import { env } from '@/lib/core/config/env' |
| 21 | +import { createCredentialRecord } from '@/lib/credentials/orchestration/credential-create' |
| 22 | +import { executePostgresqlTool } from '@/lib/internal/postgresql/execute-tool' |
| 23 | +import { POSTGRESQL_SERVICE_ACCOUNT_PROVIDER_ID } from '@/lib/oauth/types' |
| 24 | + |
| 25 | +const databaseUrl = new URL(readTestDatabaseUrl()) |
| 26 | +const connection = { |
| 27 | + host: '127.0.0.1', |
| 28 | + port: Number(databaseUrl.port || 5432), |
| 29 | + database: databaseUrl.pathname.slice(1), |
| 30 | + username: decodeURIComponent(databaseUrl.username), |
| 31 | + // The disposable server trusts loopback logins, so any non-empty password is accepted. |
| 32 | + password: decodeURIComponent(databaseUrl.password) || 'unused-under-trust-auth', |
| 33 | + ssl: 'disabled', |
| 34 | +} |
| 35 | +const userId = generateId() |
| 36 | +const workspaceId = generateId() |
| 37 | +const otherWorkspaceId = generateId() |
| 38 | + |
| 39 | +function save(displayName: string, serviceAccountJson: string) { |
| 40 | + return createCredentialRecord( |
| 41 | + { |
| 42 | + workspaceId, |
| 43 | + type: 'service_account', |
| 44 | + userId, |
| 45 | + providerId: POSTGRESQL_SERVICE_ACCOUNT_PROVIDER_ID, |
| 46 | + displayName, |
| 47 | + serviceAccountJson, |
| 48 | + }, |
| 49 | + { authorizeWorkspace: true } |
| 50 | + ) |
| 51 | +} |
| 52 | + |
| 53 | +function run(credentialId: string, runWorkspaceId: string) { |
| 54 | + return executePostgresqlTool({ |
| 55 | + toolId: 'postgresql_query', |
| 56 | + input: { |
| 57 | + host: 'unreachable.invalid', |
| 58 | + port: 1, |
| 59 | + database: 'other', |
| 60 | + username: 'other', |
| 61 | + password: 'inline', |
| 62 | + ssl: 'required', |
| 63 | + query: 'SELECT current_user AS who, current_database() AS db', |
| 64 | + }, |
| 65 | + headers: new Headers(), |
| 66 | + context: { |
| 67 | + workflowId: generateId(), |
| 68 | + workspaceId: runWorkspaceId, |
| 69 | + authorizedServiceAccountCredential: { credentialId, service: 'postgresql' }, |
| 70 | + }, |
| 71 | + requestId: generateId(), |
| 72 | + }) |
| 73 | +} |
| 74 | + |
| 75 | +describe('saved PostgreSQL connection', () => { |
| 76 | + let credentialId: string |
| 77 | + |
| 78 | + beforeAll(async () => { |
| 79 | + Object.assign(env, { EGRESS_ALLOWED_HOSTS: '127.0.0.1' }) |
| 80 | + const now = new Date() |
| 81 | + await db.insert(user).values({ |
| 82 | + id: userId, |
| 83 | + name: 'Database connection fixture', |
| 84 | + email: `${userId}@database-connection.test`, |
| 85 | + emailVerified: true, |
| 86 | + createdAt: now, |
| 87 | + updatedAt: now, |
| 88 | + }) |
| 89 | + for (const id of [workspaceId, otherWorkspaceId]) { |
| 90 | + await insertWorkspaceFixture(db, { |
| 91 | + id, |
| 92 | + name: 'Database connection fixture', |
| 93 | + ownerId: userId, |
| 94 | + billedAccountUserId: userId, |
| 95 | + }) |
| 96 | + await db.insert(permissions).values({ |
| 97 | + id: generateId(), |
| 98 | + userId, |
| 99 | + entityType: 'workspace', |
| 100 | + entityId: id, |
| 101 | + permissionType: 'admin', |
| 102 | + }) |
| 103 | + } |
| 104 | + }, 60_000) |
| 105 | + |
| 106 | + afterAll(async () => { |
| 107 | + await db.delete(credential).where(eq(credential.workspaceId, workspaceId)) |
| 108 | + await deleteWorkspaceFixture(db, inArray(workspace.id, [workspaceId, otherWorkspaceId])) |
| 109 | + await db.delete(user).where(eq(user.id, userId)) |
| 110 | + }) |
| 111 | + |
| 112 | + it('saves a connection the server accepts', async () => { |
| 113 | + const result = await save('Primary database', JSON.stringify(connection)) |
| 114 | + |
| 115 | + expect(result).toMatchObject({ success: true }) |
| 116 | + const [row] = await db |
| 117 | + .select() |
| 118 | + .from(credential) |
| 119 | + .where(eq(credential.displayName, 'Primary database')) |
| 120 | + expect(row).toMatchObject({ |
| 121 | + type: 'service_account', |
| 122 | + providerId: POSTGRESQL_SERVICE_ACCOUNT_PROVIDER_ID, |
| 123 | + workspaceId, |
| 124 | + }) |
| 125 | + expect(row.encryptedServiceAccountKey).not.toContain(connection.password) |
| 126 | + credentialId = row.id |
| 127 | + }) |
| 128 | + |
| 129 | + it('refuses to save a connection the server rejects', async () => { |
| 130 | + const result = await save( |
| 131 | + 'Missing database', |
| 132 | + JSON.stringify({ ...connection, database: `${connection.database}_missing` }) |
| 133 | + ) |
| 134 | + |
| 135 | + expect(result).toMatchObject({ success: false }) |
| 136 | + const rows = await db |
| 137 | + .select({ id: credential.id }) |
| 138 | + .from(credential) |
| 139 | + .where(eq(credential.displayName, 'Missing database')) |
| 140 | + expect(rows).toHaveLength(0) |
| 141 | + }) |
| 142 | + |
| 143 | + it('runs on the saved connection whatever connection fields the call carries', async () => { |
| 144 | + const response = await run(credentialId, workspaceId) |
| 145 | + |
| 146 | + expect(response.status).toBe(200) |
| 147 | + expect(await response.json()).toMatchObject({ |
| 148 | + rows: [{ who: connection.username, db: connection.database }], |
| 149 | + }) |
| 150 | + }) |
| 151 | + |
| 152 | + it('refuses the connection to a run in another workspace', async () => { |
| 153 | + const response = await run(credentialId, otherWorkspaceId) |
| 154 | + |
| 155 | + expect(response.status).toBe(403) |
| 156 | + }) |
| 157 | + |
| 158 | + it('refuses a revoked connection', async () => { |
| 159 | + await db |
| 160 | + .update(credential) |
| 161 | + .set({ revokedAt: new Date() }) |
| 162 | + .where(eq(credential.id, credentialId)) |
| 163 | + |
| 164 | + const response = await run(credentialId, workspaceId) |
| 165 | + |
| 166 | + expect(response.status).toBe(403) |
| 167 | + }) |
| 168 | +}) |
0 commit comments