|
| 1 | +/** @vitest-environment node */ |
| 2 | +import { beforeEach, describe, expect, it, vi } from 'vitest' |
| 3 | + |
| 4 | +const mocks = vi.hoisted(() => ({ scoped: vi.fn(), decrypt: vi.fn() })) |
| 5 | +vi.mock('@/lib/core/security/encryption', () => ({ decryptSecret: mocks.decrypt })) |
| 6 | +vi.mock('@/lib/mothership/agent-cli/scoped-transport', () => ({ |
| 7 | + createScopedCliTransport: () => mocks.scoped, |
| 8 | +})) |
| 9 | +vi.mock('@/lib/mothership/application/workspace-target', () => ({ |
| 10 | + resolveInvocationWorkspace: async (owner: { userId: string }, workspaceId?: string) => ({ |
| 11 | + workspaceId: workspaceId ?? 'workspace', |
| 12 | + userId: owner.userId, |
| 13 | + }), |
| 14 | +})) |
| 15 | +vi.mock('@/lib/execution/remote-sandbox/session-files', () => ({ |
| 16 | + SESSION_SANDBOX_HOME: '/home/user', |
| 17 | + readSessionSandboxFile: vi.fn(), |
| 18 | + writeSessionSandboxFile: vi.fn(), |
| 19 | +})) |
| 20 | +vi.mock('@/lib/execution/remote-sandbox/session-file-snapshot', () => ({ |
| 21 | + openSessionFileSnapshot: vi.fn(), |
| 22 | +})) |
| 23 | + |
| 24 | +import { V2_ROUTES } from '@/lib/api/server/routes/v2-route-table.generated' |
| 25 | +import { |
| 26 | + createTableReadTransport, |
| 27 | + TABLE_ROUTES_WITHOUT_ROW_DATA, |
| 28 | +} from '@/lib/mothership/agent-cli/table-read-transport' |
| 29 | +import { inspectToolResultForCopilot } from '@/lib/mothership/request/tools/resolved-secret-result' |
| 30 | +import { executeSimCli } from '@/lib/mothership/tools/handlers/sim-cli' |
| 31 | +import { reportTableRowDelivery } from '@/lib/table/application/row-delivery-observer' |
| 32 | +import { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry' |
| 33 | + |
| 34 | +const SECRET = 'PRIVATE_TABLE_CELL_CANARY_FOR_LOCAL_TEST' |
| 35 | +const scope = { userId: 'reader', workspaceId: 'workspace' } |
| 36 | +const endpoint = 'https://sim.test' |
| 37 | +const rowUrl = `${endpoint}/api/v2/tables/table/rows/row?workspaceId=workspace` |
| 38 | +const rowBody = { data: { id: 'row', data: { token: SECRET } } } |
| 39 | + |
| 40 | +function registry() { |
| 41 | + return new ResolvedSecretTraceRegistry([], scope) |
| 42 | +} |
| 43 | + |
| 44 | +function secretProvenance() { |
| 45 | + const source = new ResolvedSecretTraceRegistry( |
| 46 | + [{ name: 'TABLE_SECRET', plaintext: SECRET, encryptedValue: 'fixture-ciphertext' }], |
| 47 | + scope |
| 48 | + ) |
| 49 | + source.recordResolved('TABLE_SECRET', SECRET, { propagated: true }) |
| 50 | + return source.exportProvenance() |
| 51 | +} |
| 52 | + |
| 53 | +/** Stands in for a v2 table route whose use case reports the rows it returns. */ |
| 54 | +async function deliveringRoute() { |
| 55 | + await reportTableRowDelivery(secretProvenance(), [{ col_token: SECRET }]) |
| 56 | + return Response.json(rowBody) |
| 57 | +} |
| 58 | + |
| 59 | +function projected(output: string, trace: ResolvedSecretTraceRegistry) { |
| 60 | + return JSON.stringify(inspectToolResultForCopilot({ success: true, output }, trace, 'sim_cli')) |
| 61 | +} |
| 62 | + |
| 63 | +describe('table provenance at the CLI and model-result boundary', () => { |
| 64 | + beforeEach(() => { |
| 65 | + vi.clearAllMocks() |
| 66 | + mocks.decrypt.mockResolvedValue({ decrypted: SECRET }) |
| 67 | + }) |
| 68 | + |
| 69 | + it('activates reported row provenance so the model projection redacts the cell', async () => { |
| 70 | + const trace = registry() |
| 71 | + const inner = vi.fn(deliveringRoute) |
| 72 | + const response = await createTableReadTransport({ |
| 73 | + endpoint, |
| 74 | + transport: inner, |
| 75 | + registry: trace, |
| 76 | + })(rowUrl) |
| 77 | + |
| 78 | + expect(response.status).toBe(200) |
| 79 | + const output = await response.text() |
| 80 | + expect(output).toBe(JSON.stringify(rowBody)) |
| 81 | + expect(trace.isPermanentlyIncomplete()).toBe(false) |
| 82 | + expect(projected(output, trace)).not.toContain(SECRET) |
| 83 | + }) |
| 84 | + |
| 85 | + it('withholds a row-bearing result that reported no provenance', async () => { |
| 86 | + const trace = registry() |
| 87 | + const response = await createTableReadTransport({ |
| 88 | + endpoint, |
| 89 | + transport: async () => Response.json(rowBody), |
| 90 | + registry: trace, |
| 91 | + })(rowUrl) |
| 92 | + |
| 93 | + expect(response.status).toBe(200) |
| 94 | + expect(trace.isPermanentlyIncomplete()).toBe(true) |
| 95 | + expect(projected(await response.text(), trace)).not.toContain(SECRET) |
| 96 | + }) |
| 97 | + |
| 98 | + it('withholds a result whose run state carries error text without provenance', async () => { |
| 99 | + const trace = registry() |
| 100 | + const response = await createTableReadTransport({ |
| 101 | + endpoint, |
| 102 | + transport: async () => { |
| 103 | + await reportTableRowDelivery(secretProvenance(), [{ col_token: SECRET }], { |
| 104 | + unprovenancedErrorText: true, |
| 105 | + }) |
| 106 | + return Response.json(rowBody) |
| 107 | + }, |
| 108 | + registry: trace, |
| 109 | + })(rowUrl) |
| 110 | + |
| 111 | + expect(response.status).toBe(200) |
| 112 | + expect(trace.isPermanentlyIncomplete()).toBe(true) |
| 113 | + expect(trace.getIncompletenessDiagnostics()?.reasons).toEqual([ |
| 114 | + 'table-run-state-provenance-unavailable', |
| 115 | + ]) |
| 116 | + }) |
| 117 | + |
| 118 | + it('keeps a delivered result without run-state error text complete', async () => { |
| 119 | + const trace = registry() |
| 120 | + await createTableReadTransport({ |
| 121 | + endpoint, |
| 122 | + transport: async () => { |
| 123 | + await reportTableRowDelivery(secretProvenance(), [{ col_token: SECRET }], { |
| 124 | + unprovenancedErrorText: false, |
| 125 | + }) |
| 126 | + return Response.json(rowBody) |
| 127 | + }, |
| 128 | + registry: trace, |
| 129 | + })(rowUrl) |
| 130 | + |
| 131 | + expect(trace.isPermanentlyIncomplete()).toBe(false) |
| 132 | + }) |
| 133 | + |
| 134 | + it.each(['GET', 'HEAD'])( |
| 135 | + 'refuses to return a table export download link (%s)', |
| 136 | + async (method) => { |
| 137 | + const trace = registry() |
| 138 | + const inner = vi.fn(async () => |
| 139 | + Response.json({ data: { url: 'https://signed.test/export.csv' } }) |
| 140 | + ) |
| 141 | + const response = await createTableReadTransport({ |
| 142 | + endpoint, |
| 143 | + transport: inner, |
| 144 | + registry: trace, |
| 145 | + })(`${endpoint}/api/v2/tables/table/exports/export/download?workspaceId=workspace`, { |
| 146 | + method, |
| 147 | + }) |
| 148 | + |
| 149 | + expect(response.status).toBe(403) |
| 150 | + expect(await response.text()).not.toContain('signed.test') |
| 151 | + expect(inner).not.toHaveBeenCalled() |
| 152 | + expect(trace.isPermanentlyIncomplete()).toBe(false) |
| 153 | + } |
| 154 | + ) |
| 155 | + |
| 156 | + it('ignores provenance that detached work reports after the call settles', async () => { |
| 157 | + const trace = registry() |
| 158 | + let release!: () => void |
| 159 | + const released = new Promise<void>((resolve) => { |
| 160 | + release = resolve |
| 161 | + }) |
| 162 | + let detached: Promise<void> | undefined |
| 163 | + await createTableReadTransport({ |
| 164 | + endpoint, |
| 165 | + transport: async () => { |
| 166 | + detached = released.then(() => |
| 167 | + reportTableRowDelivery(secretProvenance(), [{ col_token: SECRET }]) |
| 168 | + ) |
| 169 | + return Response.json({ error: { message: 'Row not found' } }, { status: 404 }) |
| 170 | + }, |
| 171 | + registry: trace, |
| 172 | + })(rowUrl) |
| 173 | + |
| 174 | + release() |
| 175 | + await detached |
| 176 | + expect(projected(JSON.stringify(rowBody), trace)).toContain(SECRET) |
| 177 | + }) |
| 178 | + |
| 179 | + it('refuses row reads without a registry instead of returning plaintext', async () => { |
| 180 | + const inner = vi.fn(deliveringRoute) |
| 181 | + const response = await createTableReadTransport({ endpoint, transport: inner })(rowUrl) |
| 182 | + |
| 183 | + expect(response.status).toBe(503) |
| 184 | + expect(await response.text()).not.toContain(SECRET) |
| 185 | + expect(inner).not.toHaveBeenCalled() |
| 186 | + }) |
| 187 | + |
| 188 | + it('keeps a failed row read from poisoning the turn', async () => { |
| 189 | + const trace = registry() |
| 190 | + const response = await createTableReadTransport({ |
| 191 | + endpoint, |
| 192 | + transport: async () => |
| 193 | + Response.json({ error: { message: 'Row not found' } }, { status: 404 }), |
| 194 | + registry: trace, |
| 195 | + })(rowUrl) |
| 196 | + |
| 197 | + expect(response.status).toBe(404) |
| 198 | + expect(trace.isPermanentlyIncomplete()).toBe(false) |
| 199 | + }) |
| 200 | + |
| 201 | + it.each([ |
| 202 | + ['GET', `${endpoint}/api/v2/files/file?workspaceId=workspace`], |
| 203 | + ['GET', `${endpoint}/api/v2/tables/table?workspaceId=workspace`], |
| 204 | + ['POST', `${endpoint}/api/v2/tables/table/rows/search`], |
| 205 | + ['DELETE', `${endpoint}/api/v2/tables/table/rows/row?workspaceId=workspace`], |
| 206 | + ['GET', 'https://elsewhere.test/api/v2/tables/table/rows/row'], |
| 207 | + ])('passes %s %s through untouched without a registry', async (method, url) => { |
| 208 | + const upstream = Response.json({ data: { ok: true } }) |
| 209 | + const inner = vi.fn(async () => upstream) |
| 210 | + const response = await createTableReadTransport({ endpoint, transport: inner })(url, { |
| 211 | + method, |
| 212 | + }) |
| 213 | + |
| 214 | + expect(response).toBe(upstream) |
| 215 | + expect(inner).toHaveBeenCalledWith(url, { method }) |
| 216 | + }) |
| 217 | + |
| 218 | + it('composes into the sim_cli stack so a table read through the real CLI is redacted', async () => { |
| 219 | + mocks.scoped.mockImplementation(deliveringRoute) |
| 220 | + const trace = registry() |
| 221 | + const result = await executeSimCli( |
| 222 | + { |
| 223 | + request: { |
| 224 | + invocation: { |
| 225 | + kind: 'cli', |
| 226 | + argv: ['tables', 'rows', 'get', 'table', 'row'], |
| 227 | + }, |
| 228 | + }, |
| 229 | + }, |
| 230 | + { |
| 231 | + userId: 'reader', |
| 232 | + workspaceId: 'workspace', |
| 233 | + workflowId: '', |
| 234 | + chatId: 'chat', |
| 235 | + resolvedSecretTraceRegistry: trace, |
| 236 | + } |
| 237 | + ) |
| 238 | + |
| 239 | + expect(mocks.scoped).toHaveBeenCalled() |
| 240 | + expect(new URL(String(mocks.scoped.mock.calls[0]?.[0])).pathname).toBe( |
| 241 | + '/api/v2/tables/table/rows/row' |
| 242 | + ) |
| 243 | + expect(JSON.stringify(result.output)).toContain(SECRET) |
| 244 | + expect(trace.isPermanentlyIncomplete()).toBe(false) |
| 245 | + expect(JSON.stringify(inspectToolResultForCopilot(result, trace, 'sim_cli'))).not.toContain( |
| 246 | + SECRET |
| 247 | + ) |
| 248 | + }) |
| 249 | + |
| 250 | + /** |
| 251 | + * Every v2 table route is either declared row-free or must deliver provenance. |
| 252 | + * A new route lands in the row-bearing set by default — its results are withheld |
| 253 | + * until its use case reports delivery — and this list forces that to be a decision. |
| 254 | + */ |
| 255 | + it('classifies every v2 table route', async () => { |
| 256 | + const methods = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] as const |
| 257 | + const declared = new Set<string>() |
| 258 | + for (const route of V2_ROUTES) { |
| 259 | + if (route.pattern !== '/api/v2/tables' && !route.pattern.startsWith('/api/v2/tables/')) |
| 260 | + continue |
| 261 | + const module = await route.load() |
| 262 | + for (const method of methods) { |
| 263 | + if (typeof Reflect.get(module, method) === 'function') |
| 264 | + declared.add(`${method} ${route.pattern}`) |
| 265 | + } |
| 266 | + } |
| 267 | + |
| 268 | + expect([...TABLE_ROUTES_WITHOUT_ROW_DATA].filter((key) => !declared.has(key))).toEqual([]) |
| 269 | + expect([...declared].filter((key) => !TABLE_ROUTES_WITHOUT_ROW_DATA.has(key)).sort()).toEqual([ |
| 270 | + 'GET /api/v2/tables/{tableId}/exports/{exportId}/download', |
| 271 | + 'GET /api/v2/tables/{tableId}/rows', |
| 272 | + 'GET /api/v2/tables/{tableId}/rows/{rowId}', |
| 273 | + 'GET /api/v2/tables/{tableId}/rows/{rowId}/enrichment/{groupId}', |
| 274 | + 'PATCH /api/v2/tables/{tableId}/rows/{rowId}', |
| 275 | + 'POST /api/v2/tables/{tableId}/query', |
| 276 | + 'POST /api/v2/tables/{tableId}/rows', |
| 277 | + 'POST /api/v2/tables/{tableId}/rows/upsert', |
| 278 | + ]) |
| 279 | + }, 60_000) |
| 280 | +}) |
0 commit comments