Skip to content

Commit 7b1e534

Browse files
committed
feat(database-tools): run PostgreSQL, MySQL, and SQL Server tools on a saved connection
Every PostgreSQL, MySQL, and SQL Server tool now declares an optional service-account credential policy (required: false), so its inline connection fields keep working unchanged and a saved connection can stand in for them. The executor authorizes the selected credential and passes it through trusted context; the family's operation handler, wrapped by withSavedDatabaseConnection, reads the stored connection bound to the run's owner and replaces every connection field before parsing. The providers resolve inside the operation, like AWS, so they join OPERATION_RESOLVED_CREDENTIAL_PROVIDERS. A real-Postgres integration test saves a connection (SELECT 1 through the guarded path), refuses one the server rejects, runs a query on the saved connection whatever fields the call carries, and refuses it to another workspace and once revoked.
1 parent 3c2cbfe commit 7b1e534

24 files changed

Lines changed: 279 additions & 9 deletions
Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
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+
})

‎apps/sim/lib/internal/mssql/execute-tool.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { getErrorMessage } from '@sim/utils/errors'
22
import type { z } from 'zod'
3+
import { withSavedDatabaseConnection } from '@/lib/credentials/database-connections/server'
34
import {
45
executeMssqlDelete,
56
executeMssqlInsert,
@@ -18,6 +19,7 @@ import {
1819
mssqlUpdateInputSchema,
1920
} from '@/lib/internal/mssql/schema'
2021
import type { InternalToolOperationHandler } from '@/lib/internal/tool-operations/types'
22+
import { MSSQL_SERVICE_ACCOUNT_PROVIDER_ID } from '@/lib/oauth/types'
2123

2224
async function executeOperation<TInput>(
2325
schema: z.ZodType<TInput>,
@@ -50,7 +52,7 @@ async function executeOperation<TInput>(
5052
}
5153
}
5254

53-
export const executeMssqlTool: InternalToolOperationHandler = async ({ toolId, input, signal }) => {
55+
const runMssqlTool: InternalToolOperationHandler = async ({ toolId, input, signal }) => {
5456
signal?.throwIfAborted()
5557

5658
switch (toolId) {
@@ -109,3 +111,9 @@ export const executeMssqlTool: InternalToolOperationHandler = async ({ toolId, i
109111
)
110112
}
111113
}
114+
115+
/** Runs a SQL Server tool on its inline connection, or on the saved connection the executor authorized. */
116+
export const executeMssqlTool = withSavedDatabaseConnection(
117+
MSSQL_SERVICE_ACCOUNT_PROVIDER_ID,
118+
runMssqlTool
119+
)

‎apps/sim/lib/internal/mysql/execute-tool.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { getErrorMessage } from '@sim/utils/errors'
22
import type { z } from 'zod'
3+
import { withSavedDatabaseConnection } from '@/lib/credentials/database-connections/server'
34
import {
45
executeMysqlDelete,
56
executeMysqlInsert,
@@ -18,6 +19,7 @@ import {
1819
mysqlUpdateInputSchema,
1920
} from '@/lib/internal/mysql/schema'
2021
import type { InternalToolOperationHandler } from '@/lib/internal/tool-operations/types'
22+
import { MYSQL_SERVICE_ACCOUNT_PROVIDER_ID } from '@/lib/oauth/types'
2123

2224
async function executeOperation<TInput>(
2325
schema: z.ZodType<TInput>,
@@ -50,7 +52,7 @@ async function executeOperation<TInput>(
5052
}
5153
}
5254

53-
export const executeMysqlTool: InternalToolOperationHandler = async ({ toolId, input, signal }) => {
55+
const runMysqlTool: InternalToolOperationHandler = async ({ toolId, input, signal }) => {
5456
signal?.throwIfAborted()
5557

5658
switch (toolId) {
@@ -106,3 +108,9 @@ export const executeMysqlTool: InternalToolOperationHandler = async ({ toolId, i
106108
return Response.json({ error: `Unsupported MySQL tool: ${toolId}` }, { status: 500 })
107109
}
108110
}
111+
112+
/** Runs a MySQL tool on its inline connection, or on the saved connection the executor authorized. */
113+
export const executeMysqlTool = withSavedDatabaseConnection(
114+
MYSQL_SERVICE_ACCOUNT_PROVIDER_ID,
115+
runMysqlTool
116+
)

‎apps/sim/lib/internal/postgresql/execute-tool.ts‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { getErrorMessage } from '@sim/utils/errors'
22
import type { z } from 'zod'
3+
import { withSavedDatabaseConnection } from '@/lib/credentials/database-connections/server'
34
import {
45
executePostgresqlDelete,
56
executePostgresqlInsert,
@@ -18,6 +19,7 @@ import {
1819
postgresqlUpdateInputSchema,
1920
} from '@/lib/internal/postgresql/schema'
2021
import type { InternalToolOperationHandler } from '@/lib/internal/tool-operations/types'
22+
import { POSTGRESQL_SERVICE_ACCOUNT_PROVIDER_ID } from '@/lib/oauth/types'
2123

2224
async function executeOperation<TInput>(
2325
schema: z.ZodType<TInput>,
@@ -50,11 +52,7 @@ async function executeOperation<TInput>(
5052
}
5153
}
5254

53-
export const executePostgresqlTool: InternalToolOperationHandler = async ({
54-
toolId,
55-
input,
56-
signal,
57-
}) => {
55+
const runPostgresqlTool: InternalToolOperationHandler = async ({ toolId, input, signal }) => {
5856
signal?.throwIfAborted()
5957

6058
switch (toolId) {
@@ -110,3 +108,9 @@ export const executePostgresqlTool: InternalToolOperationHandler = async ({
110108
return Response.json({ error: `Unsupported PostgreSQL tool: ${toolId}` }, { status: 500 })
111109
}
112110
}
111+
112+
/** Runs a PostgreSQL tool on its inline connection, or on the saved connection the executor authorized. */
113+
export const executePostgresqlTool = withSavedDatabaseConnection(
114+
POSTGRESQL_SERVICE_ACCOUNT_PROVIDER_ID,
115+
runPostgresqlTool
116+
)

‎apps/sim/tools/generated/tool-metadata.ts‎

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

‎apps/sim/tools/mssql/delete.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
import type { MSSQLDeleteParams, MSSQLDeleteResponse } from '@/tools/mssql/types'
2+
import { MSSQL_CREDENTIAL_OAUTH } from '@/tools/shared/saved-credentials'
23
import type { InternalToolConfig } from '@/tools/types'
34

45
export const deleteTool: InternalToolConfig<MSSQLDeleteParams, MSSQLDeleteResponse> = {
56
id: 'mssql_delete',
67
name: 'Microsoft SQL Server Delete',
78
description: 'Delete rows from a Microsoft SQL Server table',
89
version: '1.0',
10+
oauth: MSSQL_CREDENTIAL_OAUTH,
911

1012
params: {
1113
host: {

‎apps/sim/tools/mssql/execute.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
import type { MSSQLExecuteParams, MSSQLExecuteResponse } from '@/tools/mssql/types'
2+
import { MSSQL_CREDENTIAL_OAUTH } from '@/tools/shared/saved-credentials'
23
import type { InternalToolConfig } from '@/tools/types'
34

45
export const executeTool: InternalToolConfig<MSSQLExecuteParams, MSSQLExecuteResponse> = {
56
id: 'mssql_execute',
67
name: 'Microsoft SQL Server Execute',
78
description: 'Execute a raw T-SQL statement on a Microsoft SQL Server database',
89
version: '1.0',
10+
oauth: MSSQL_CREDENTIAL_OAUTH,
911

1012
params: {
1113
host: {

‎apps/sim/tools/mssql/insert.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
import type { MSSQLInsertParams, MSSQLInsertResponse } from '@/tools/mssql/types'
2+
import { MSSQL_CREDENTIAL_OAUTH } from '@/tools/shared/saved-credentials'
23
import type { InternalToolConfig } from '@/tools/types'
34

45
export const insertTool: InternalToolConfig<MSSQLInsertParams, MSSQLInsertResponse> = {
56
id: 'mssql_insert',
67
name: 'Microsoft SQL Server Insert',
78
description: 'Insert data into a Microsoft SQL Server table',
89
version: '1.0',
10+
oauth: MSSQL_CREDENTIAL_OAUTH,
911

1012
params: {
1113
host: {

‎apps/sim/tools/mssql/introspect.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {
33
type MSSQLIntrospectParams,
44
type MSSQLIntrospectResponse,
55
} from '@/tools/mssql/types'
6+
import { MSSQL_CREDENTIAL_OAUTH } from '@/tools/shared/saved-credentials'
67
import type { InternalToolConfig } from '@/tools/types'
78

89
export const introspectTool: InternalToolConfig<MSSQLIntrospectParams, MSSQLIntrospectResponse> = {
@@ -11,6 +12,7 @@ export const introspectTool: InternalToolConfig<MSSQLIntrospectParams, MSSQLIntr
1112
description:
1213
'Introspect a Microsoft SQL Server schema to retrieve table structures, columns, keys, and indexes. Results only cover objects the login can see, so a low-privilege account returns a partial schema rather than an error',
1314
version: '1.0',
15+
oauth: MSSQL_CREDENTIAL_OAUTH,
1416

1517
params: {
1618
host: {

‎apps/sim/tools/mssql/query.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
import type { MSSQLQueryParams, MSSQLQueryResponse } from '@/tools/mssql/types'
2+
import { MSSQL_CREDENTIAL_OAUTH } from '@/tools/shared/saved-credentials'
23
import type { InternalToolConfig } from '@/tools/types'
34

45
export const queryTool: InternalToolConfig<MSSQLQueryParams, MSSQLQueryResponse> = {
56
id: 'mssql_query',
67
name: 'Microsoft SQL Server Query',
78
description: 'Execute a SELECT query on a Microsoft SQL Server database',
89
version: '1.0',
10+
oauth: MSSQL_CREDENTIAL_OAUTH,
911

1012
params: {
1113
host: {

0 commit comments

Comments
 (0)