diff --git a/packages/core/src/project.test.ts b/packages/core/src/project.test.ts index c08704b..2d051e7 100644 --- a/packages/core/src/project.test.ts +++ b/packages/core/src/project.test.ts @@ -3,6 +3,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { ConfigSchema } from '@laqi/schema' import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { bodyHash } from './canonical-json' import { Project } from './project' let root: string @@ -520,3 +521,125 @@ describe('scaffoldResponses', () => { if (!result.ok) expect(result.code).toBe('not-found') }) }) + +/** Evidence that truthfully describes `body`. */ +const evidenceFor = (body: unknown) => ({ + seed: 9, + options: { arrayLength: 1 }, + bodyHash: bodyHash(body), +}) + +describe('applyGeneratedBody — the body and its evidence are one fact', () => { + const schema = { + name: 'User', + document: { $schema: 'https://json-schema.org/draft/2020-12/schema', type: 'object' }, + source: { kind: 'typescript-paste' as const }, + diagnostics: [], + } + const oldBody = [{ id: 1 }] + const newBody = [{ id: 2 }] + + /** A response laqi vouches for, so only the apply checks under test can refuse. */ + function seedGenerated(): { revision: string; before: string } { + writeMocks({ + 'GET /users': { + default: 'ok', + responses: { + ok: { status: 200, body: oldBody, schema, generation: evidenceFor(oldBody) }, + }, + }, + }) + const revision = unwrap(project.getResponseRevision('GET /users', 'ok')) + return { revision, before: readFileSync(join(root, 'laqi/api.json'), 'utf8') } + } + + function expectRefused(result: { ok: boolean; error?: string }, before: string, reason: RegExp) { + expect(result.ok).toBe(false) + expect(result.error).toMatch(reason) + // Byte for byte: a refused write must not even reformat the file. + expect(readFileSync(join(root, 'laqi/api.json'), 'utf8')).toBe(before) + } + + it('applies a body with matching evidence', () => { + const { revision } = seedGenerated() + + const result = project.applyGeneratedBody({ + id: 'GET /users', + body: newBody, + generation: evidenceFor(newBody), + revision, + }) + + expect(result.ok).toBe(true) + const stored = (readMocks()['GET /users'] as { responses: Record }).responses + expect(stored['ok']).toMatchObject({ body: newBody, generation: evidenceFor(newBody) }) + }) + + it('refuses a missing evidence key and leaves the stored response unchanged', () => { + const { revision, before } = seedGenerated() + + const result = project.applyGeneratedBody({ + id: 'GET /users', + body: newBody, + generation: undefined, + revision, + }) + + expectRefused(result, before, /evidence/i) + }) + + it('refuses a missing body key even with confirm unset, and leaves the stored response unchanged', () => { + const { revision, before } = seedGenerated() + + const result = project.applyGeneratedBody({ + id: 'GET /users', + body: undefined, + generation: evidenceFor(newBody), + revision, + }) + + expectRefused(result, before, /body/i) + }) + + it('refuses a body whose hash is not the evidence’s, and writes nothing', () => { + const { revision, before } = seedGenerated() + + const result = project.applyGeneratedBody({ + id: 'GET /users', + body: [{ id: 3, handWritten: true }], + generation: evidenceFor(newBody), + revision, + }) + + expectRefused(result, before, /bodyHash|hash/i) + }) + + it('refuses evidence that is not the GenerationEvidence shape', () => { + const { revision, before } = seedGenerated() + + const result = project.applyGeneratedBody({ + id: 'GET /users', + body: newBody, + generation: { seed: 'nine', bodyHash: 'not-a-hash' }, + revision, + }) + + expectRefused(result, before, /evidence/i) + }) + + it('stores a literal null body as null, distinct from removing the key', () => { + const { revision } = seedGenerated() + + const result = project.applyGeneratedBody({ + id: 'GET /users', + body: null, + generation: evidenceFor(null), + revision, + }) + + expect(result.ok).toBe(true) + const stored = (readMocks()['GET /users'] as { responses: Record }).responses + expect(stored['ok']).toHaveProperty('body', null) + expect(stored['ok']).toHaveProperty('generation', evidenceFor(null)) + }) +}) diff --git a/packages/core/src/project.ts b/packages/core/src/project.ts index f10bb28..256713c 100644 --- a/packages/core/src/project.ts +++ b/packages/core/src/project.ts @@ -1,4 +1,5 @@ import { join, resolve } from 'node:path' +import { bodyHash } from './canonical-json' import { loadMocks, type LoadedEndpoint, type LoadError } from './loader' import { resolveResponse } from './resolve' import { buildRouteTable } from './route-table' @@ -14,6 +15,7 @@ import { } from './writer' import { formatEndpointId, + GenerationEvidenceSchema, isHttpMethod, parseEndpointKey, suggestResponses, @@ -496,6 +498,12 @@ export class Project { * Refuses when the response changed since `revision` was read, or when the * body about to be overwritten is not one laqi vouches for — `confirm` * waives the second, never the first. + * + * Also refuses before touching the file when the pair is not one fact: a + * missing body or evidence, evidence that is not the evidence shape, or a + * body that is not the one the evidence hashes. `confirm` waives none of + * these, because they would let a caller write a body and have laqi vouch + * for it. A literal `null` body is a body; only `undefined` is absent. */ applyGeneratedBody(params: { id: string @@ -508,6 +516,22 @@ export class Project { const located = this.locate(params.id, params.response) if (!located.ok) return located + if (params.body === undefined) { + return fail('a generated body is required: send the body together with its evidence') + } + const evidence = GenerationEvidenceSchema.safeParse(params.generation) + if (!evidence.success) { + const why = params.generation === undefined ? 'missing' : 'malformed' + return fail( + `the generation evidence is ${why}: send the evidence that came back with the body (${evidence.error.issues.map((i) => i.message).join('; ')})`, + ) + } + if (bodyHash(params.body) !== evidence.data.bodyHash) { + return fail( + 'the body does not match the evidence: its hash is not evidence.bodyHash, so laqi will not vouch for it', + ) + } + const result = updateResponseInFile({ root: this.root, bounds: this.bounds(), @@ -516,7 +540,7 @@ export class Project { response: located.value.name, revision: params.revision, confirm: params.confirm, - patch: { body: params.body, generation: params.generation }, + patch: { body: params.body, generation: evidence.data }, }) if (result.ok) return ok({ revision: result.revision, file: located.value.file }) diff --git a/packages/mcp/src/server.ts b/packages/mcp/src/server.ts index f873ec1..1542d55 100644 --- a/packages/mcp/src/server.ts +++ b/packages/mcp/src/server.ts @@ -1,5 +1,6 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js' import { + GenerationEvidenceSchema, ResponseSchema, SourceRequestSchema, type EndpointDefinition, @@ -572,12 +573,17 @@ export function createMcpServer(options: { root: string; config: LaqiConfig }): { title: 'Write a generated body to a response', description: - 'Write a body produced by regenerate_response or generate_data, together with the evidence that reproduces it. Pass the revision that came back with the preview. This can be refused: if the response changed since then, or if the body being replaced is not one laqi generated (hand-written, or edited afterwards), the reply names the reason and the current revision. Show the person what would be overwritten, then retry with that revision and confirm: true.', + 'Write a body produced by regenerate_response or generate_data, together with the evidence that reproduces it. Both are required and must match. Pass the revision that came back with the preview. This can be refused: if the response changed since then, or if the body being replaced is not one laqi generated (hand-written, or edited afterwards), the reply names the reason and the current revision. Show the person what would be overwritten, then retry with that revision and confirm: true.', inputSchema: { endpointId: z.string().describe('Endpoint id, e.g. "GET /users/:id"'), response: z.string().optional().describe('Response name; defaults to the endpoint default'), - body: z.unknown().describe('The generated body, exactly as the preview returned it'), - generation: z.unknown().describe('The evidence the preview returned beside the body'), + body: z + .unknown() + .refine((body) => body !== undefined, 'body is required') + .describe('The generated body, exactly as the preview returned it'), + generation: GenerationEvidenceSchema.describe( + 'The evidence the preview returned beside the body', + ), revision: z.string().describe('The revision the preview was generated against'), confirm: z .boolean() diff --git a/packages/mcp/src/stdio.test.ts b/packages/mcp/src/stdio.test.ts index 63d1ca6..2067adc 100644 --- a/packages/mcp/src/stdio.test.ts +++ b/packages/mcp/src/stdio.test.ts @@ -543,6 +543,75 @@ describe('regenerating and applying a body over stdio', () => { expect((refused.json() as { conflict: string }).conflict).toBe('stale-revision') }, 60_000) + describe('a body and its evidence are one fact', () => { + function fileBytes(): string { + return readFileSync(join(root, 'laqi', 'api.json'), 'utf8') + } + + /** A fresh preview to apply, and the bytes on disk that a refusal must leave alone. */ + async function preview() { + const { revision } = await seed() + const next = await call('regenerate_response', { endpointId: 'GET /users', seed: 9 }) + const { preview: body, generation } = next.json() as Record + return { revision, body, generation, before: fileBytes() } + } + + it('refuses a missing generation and writes nothing', async () => { + const { revision, body, before } = await preview() + + const refused = await call('apply_generated_body', { + endpointId: 'GET /users', + body, + revision, + }) + + expect(refused.isError).toBe(true) + expect(fileBytes()).toBe(before) + }, 60_000) + + it('refuses a missing body, even with the response vouched for, and writes nothing', async () => { + const { revision, generation, before } = await preview() + + const refused = await call('apply_generated_body', { + endpointId: 'GET /users', + generation, + revision, + }) + + expect(refused.isError).toBe(true) + expect(fileBytes()).toBe(before) + }, 60_000) + + it('refuses a body that is not the one the evidence hashes, and writes nothing', async () => { + const { revision, generation, before } = await preview() + + const refused = await call('apply_generated_body', { + endpointId: 'GET /users', + body: [{ id: 1, title: 'hand-written', kind: 'task' }], + generation, + revision, + }) + + expect(refused.isError).toBe(true) + expect(refused.text).toContain('bodyHash') + expect(fileBytes()).toBe(before) + }, 60_000) + + it('refuses evidence that is not the GenerationEvidence shape', async () => { + const { revision, body, before } = await preview() + + const refused = await call('apply_generated_body', { + endpointId: 'GET /users', + body, + generation: { seed: 'nine', bodyHash: 'not-a-hash' }, + revision, + }) + + expect(refused.isError).toBe(true) + expect(fileBytes()).toBe(before) + }, 60_000) + }) + it('refuses to refresh a schema that came from a paste, and writes nothing', async () => { const { revision } = await seed() const before = readApiFile()['GET /users']?.responses['ok'] diff --git a/packages/server/src/control-plane-app.test.ts b/packages/server/src/control-plane-app.test.ts index a97639a..ae27db7 100644 --- a/packages/server/src/control-plane-app.test.ts +++ b/packages/server/src/control-plane-app.test.ts @@ -779,3 +779,54 @@ describe('generation routes', () => { expect((await app.request('/api/endpoints/GET%20%2Fnope/types')).status).toBe(404) }) }) + +describe('PUT /api/endpoints/:id/responses/:name/body — the body and its evidence travel together', () => { + const evidence = { seed: 1, options: { arrayLength: 1 }, bodyHash: 'a'.repeat(64) } + + async function put(payload: unknown) { + const applyGeneratedBody = vi.fn(() => ({ ok: true as const, revision: 'r2' })) + const app = createControlPlaneApp(makeRuntime({ applyGeneratedBody })) + const res = await app.request('/api/endpoints/GET%20%2Fusers/responses/ok/body', { + method: 'PUT', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(payload), + }) + return { res, applyGeneratedBody } + } + + it('rejects a request without the evidence key', async () => { + const { res, applyGeneratedBody } = await put({ body: [{ id: 1 }], revision: 'r1' }) + + expect(res.status).toBe(400) + expect(applyGeneratedBody).not.toHaveBeenCalled() + }) + + it('rejects a request without the body key', async () => { + const { res, applyGeneratedBody } = await put({ evidence, revision: 'r1' }) + + expect(res.status).toBe(400) + expect(applyGeneratedBody).not.toHaveBeenCalled() + }) + + it('rejects evidence that is not the GenerationEvidence shape', async () => { + const { res, applyGeneratedBody } = await put({ + body: [], + evidence: { seed: 'one' }, + revision: 'r1', + }) + + expect(res.status).toBe(400) + expect(applyGeneratedBody).not.toHaveBeenCalled() + }) + + it('passes a literal null body through as null', async () => { + const { res, applyGeneratedBody } = await put({ body: null, evidence, revision: 'r1' }) + + expect(res.status).toBe(200) + expect(applyGeneratedBody).toHaveBeenCalledWith( + 'GET /users', + 'ok', + expect.objectContaining({ body: null, evidence }), + ) + }) +}) diff --git a/packages/server/src/control-plane-app.ts b/packages/server/src/control-plane-app.ts index ddd3c52..f3081e3 100644 --- a/packages/server/src/control-plane-app.ts +++ b/packages/server/src/control-plane-app.ts @@ -1,6 +1,7 @@ import type { LaqiEvent, LoadedEndpoint, LoadError } from '@laqi/core' import { EndpointSchema, + GenerationEvidenceSchema, isHttpMethod, RESERVED_PREFIX, StateSchema, @@ -240,9 +241,11 @@ const RegenerateRequestSchema = z.object({ arrayLength: z.number().int().optional(), }) +// `z.unknown()` alone makes a key optional, so the body needs a refinement to +// be required. `null` is a body; only an absent key is refused. const ApplyBodyRequestSchema = z.object({ - body: z.unknown(), - evidence: z.unknown(), + body: z.unknown().refine((body) => body !== undefined, 'body is required'), + evidence: GenerationEvidenceSchema, revision: z.string().min(1), confirm: z.boolean().optional(), })