|
| 1 | +import { generateJWT } from "@trigger.dev/core/v3/jwt"; |
| 2 | +import { beforeEach, describe, expect, it, vi } from "vitest"; |
| 3 | + |
| 4 | +/** |
| 5 | + * The query API is read-only, and the grammar is what enforces it. A parser test alone would |
| 6 | + * stay green if the route ever compiled agent SQL somewhere else, so these drive the real route |
| 7 | + * with a real signed environment JWT and stub only the ClickHouse client. A write must be |
| 8 | + * refused before anything reaches ClickHouse. |
| 9 | + */ |
| 10 | + |
| 11 | +const ENVIRONMENT_ID = "env_1234"; |
| 12 | +const API_KEY = "tr_dev_abcdefghijklmnop"; |
| 13 | + |
| 14 | +const environment = { |
| 15 | + id: ENVIRONMENT_ID, |
| 16 | + type: "DEVELOPMENT", |
| 17 | + slug: "dev", |
| 18 | + branchName: null, |
| 19 | + apiKey: API_KEY, |
| 20 | + organizationId: "org_1", |
| 21 | + projectId: "proj_1", |
| 22 | + archivedAt: null, |
| 23 | + concurrencyLimitBurstFactor: { toNumber: () => 1 }, |
| 24 | + maximumConcurrencyLimit: 10, |
| 25 | + project: { id: "proj_1", externalRef: "proj_ref", deletedAt: null }, |
| 26 | + organization: { id: "org_1" }, |
| 27 | + orgMember: null, |
| 28 | + parentEnvironment: null, |
| 29 | +}; |
| 30 | + |
| 31 | +const mocks = vi.hoisted(() => ({ |
| 32 | + runtimeEnvironmentFindFirst: vi.fn(), |
| 33 | + queryWithStats: vi.fn(), |
| 34 | + customerQueryCreate: vi.fn(), |
| 35 | +})); |
| 36 | + |
| 37 | +vi.mock("~/db.server", () => { |
| 38 | + const client = { |
| 39 | + runtimeEnvironment: { |
| 40 | + findFirst: mocks.runtimeEnvironmentFindFirst, |
| 41 | + findMany: async () => [], |
| 42 | + }, |
| 43 | + revokedApiKey: { findMany: async () => [], findFirst: async () => null }, |
| 44 | + project: { findMany: async () => [] }, |
| 45 | + customerQuery: { findFirst: async () => null, create: mocks.customerQueryCreate }, |
| 46 | + }; |
| 47 | + return { prisma: client, $replica: client }; |
| 48 | +}); |
| 49 | +vi.mock("~/env.server", () => ({ |
| 50 | + env: { |
| 51 | + SESSION_SECRET: "test-session-secret", |
| 52 | + QUERY_CLICKHOUSE_MAX_EXECUTION_TIME: "30", |
| 53 | + QUERY_CLICKHOUSE_MAX_MEMORY_USAGE: 1000000, |
| 54 | + QUERY_CLICKHOUSE_MAX_AST_ELEMENTS: 50000, |
| 55 | + QUERY_CLICKHOUSE_MAX_EXPANDED_AST_ELEMENTS: 500000, |
| 56 | + QUERY_CLICKHOUSE_MAX_BYTES_BEFORE_EXTERNAL_GROUP_BY: 1000000, |
| 57 | + QUERY_CLICKHOUSE_MAX_RETURNED_ROWS: 1000, |
| 58 | + }, |
| 59 | +})); |
| 60 | +vi.mock("~/services/clickhouse/clickhouseFactoryInstance.server", () => ({ |
| 61 | + clickhouseFactory: { |
| 62 | + getClickhouseForOrganization: async () => ({ |
| 63 | + reader: { queryWithStats: mocks.queryWithStats }, |
| 64 | + }), |
| 65 | + }, |
| 66 | +})); |
| 67 | +vi.mock("~/services/platform.v3.server", () => ({ getLimit: async () => 30 })); |
| 68 | +vi.mock("~/services/queryConcurrencyLimiter.server", () => ({ |
| 69 | + queryConcurrencyLimiter: { |
| 70 | + acquire: async () => ({ success: true }), |
| 71 | + release: async () => {}, |
| 72 | + }, |
| 73 | + DEFAULT_ORG_CONCURRENCY_LIMIT: 10, |
| 74 | + GLOBAL_CONCURRENCY_LIMIT: 100, |
| 75 | +})); |
| 76 | +vi.mock("~/services/logger.server", () => ({ |
| 77 | + logger: { debug: vi.fn(), error: vi.fn(), warn: vi.fn(), info: vi.fn() }, |
| 78 | +})); |
| 79 | +vi.mock("~/v3/services/worker/workerGroupTokenService.server", () => ({ |
| 80 | + WorkerGroupTokenService: class {}, |
| 81 | +})); |
| 82 | +vi.mock("~/v3/services/common.server", () => ({ ServiceValidationError: class extends Error {} })); |
| 83 | +vi.mock("@internal/run-engine", () => ({ EngineServiceValidationError: class extends Error {} })); |
| 84 | + |
| 85 | +import { action } from "~/routes/api.v1.query"; |
| 86 | +import { executeQuery } from "~/services/queryService.server"; |
| 87 | + |
| 88 | +/** The claims the env-JWT exchange mints (api.v1.projects.$projectRef.$env.jwt.ts). */ |
| 89 | +function mintEnvJwt(scopes: string[]) { |
| 90 | + return generateJWT({ |
| 91 | + secretKey: API_KEY, |
| 92 | + payload: { |
| 93 | + sub: ENVIRONMENT_ID, |
| 94 | + pub: true, |
| 95 | + scopes, |
| 96 | + act: { sub: "usr_1", client: "dashboard-agent" }, |
| 97 | + }, |
| 98 | + expirationTime: "1h", |
| 99 | + }); |
| 100 | +} |
| 101 | + |
| 102 | +async function runQuery(query: string): Promise<{ status: number; body: any }> { |
| 103 | + const jwt = await mintEnvJwt(["read:query"]); |
| 104 | + const response = await action({ |
| 105 | + request: new Request("https://api.trigger.dev/api/v1/query", { |
| 106 | + method: "POST", |
| 107 | + headers: { Authorization: `Bearer ${jwt}`, "Content-Type": "application/json" }, |
| 108 | + body: JSON.stringify({ query }), |
| 109 | + }), |
| 110 | + params: {}, |
| 111 | + context: {}, |
| 112 | + } as any); |
| 113 | + return { status: response.status, body: await response.json() }; |
| 114 | +} |
| 115 | + |
| 116 | +describe("the query API route", () => { |
| 117 | + beforeEach(() => { |
| 118 | + vi.clearAllMocks(); |
| 119 | + mocks.runtimeEnvironmentFindFirst.mockResolvedValue(environment); |
| 120 | + mocks.customerQueryCreate.mockResolvedValue({ id: "cq_1" }); |
| 121 | + mocks.queryWithStats.mockReturnValue(async () => [null, { rows: [], stats: {} }]); |
| 122 | + }); |
| 123 | + |
| 124 | + // Pins the seam the two refusals assert against: a read really does reach ClickHouse here, |
| 125 | + // so `not.toHaveBeenCalled()` below means refused, not unreachable. |
| 126 | + it("runs a read against ClickHouse", async () => { |
| 127 | + const result = await runQuery("SELECT count() FROM runs"); |
| 128 | + |
| 129 | + expect(result.status).toBe(200); |
| 130 | + expect(mocks.queryWithStats).toHaveBeenCalled(); |
| 131 | + }); |
| 132 | + |
| 133 | + it("refuses a write smuggled in as a second statement", async () => { |
| 134 | + const result = await runQuery("SELECT 1 FROM runs; DROP TABLE runs"); |
| 135 | + |
| 136 | + expect(result.status).toBe(400); |
| 137 | + expect(mocks.queryWithStats).not.toHaveBeenCalled(); |
| 138 | + }); |
| 139 | + |
| 140 | + it("refuses a mutating statement", async () => { |
| 141 | + const result = await runQuery("INSERT INTO runs (task_identifier) VALUES ('x')"); |
| 142 | + |
| 143 | + expect(result.status).toBe(400); |
| 144 | + expect(mocks.queryWithStats).not.toHaveBeenCalled(); |
| 145 | + }); |
| 146 | +}); |
| 147 | + |
| 148 | +describe("the query service", () => { |
| 149 | + beforeEach(() => { |
| 150 | + vi.clearAllMocks(); |
| 151 | + mocks.queryWithStats.mockReturnValue(async () => [null, { rows: [], stats: {} }]); |
| 152 | + }); |
| 153 | + |
| 154 | + it("keeps ClickHouse read-only when a caller overrides the settings", async () => { |
| 155 | + await executeQuery({ |
| 156 | + name: "test-query", |
| 157 | + query: "SELECT count() FROM runs", |
| 158 | + scope: "environment", |
| 159 | + organizationId: "org_1", |
| 160 | + projectId: "proj_1", |
| 161 | + environmentId: ENVIRONMENT_ID, |
| 162 | + clickhouseSettings: { readonly: "0" }, |
| 163 | + } as any); |
| 164 | + |
| 165 | + expect(mocks.queryWithStats).toHaveBeenCalled(); |
| 166 | + expect(mocks.queryWithStats.mock.calls[0][0].settings.readonly).toBe("1"); |
| 167 | + }); |
| 168 | +}); |
0 commit comments