From 1979011e432a5bb269c51eb6ec05feba896961d4 Mon Sep 17 00:00:00 2001 From: Facetomyself <[GIT_EMAIL]> Date: Fri, 27 Nov 2026 18:39:08 +0800 Subject: [PATCH 1/3] =?UTF-8?q?test(headless):=20=E9=AA=8C=E8=AF=81?= =?UTF-8?q?=E5=81=9C=E6=AD=A2=E6=96=AD=E6=B5=81=E4=B8=8E=E8=B7=A8=E5=8D=8F?= =?UTF-8?q?=E8=AE=AE=E9=87=8D=E5=BB=BA=E7=BB=AD=E8=81=8A=20/=20verify=20st?= =?UTF-8?q?op=20disconnects=20and=20conversation=20continuity?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/desktop/test/headless-compose-probe.mjs | 171 +++++++++++++------ 1 file changed, 123 insertions(+), 48 deletions(-) diff --git a/apps/desktop/test/headless-compose-probe.mjs b/apps/desktop/test/headless-compose-probe.mjs index 6f97adb0..0a0467db 100644 --- a/apps/desktop/test/headless-compose-probe.mjs +++ b/apps/desktop/test/headless-compose-probe.mjs @@ -1,83 +1,158 @@ // Runs inside the shipping container before and after `docker compose up --force-recreate`. -// Only the fixed, local fixture below is accepted; this check never contacts a real provider. +// Only the fixed, local fixture below is accepted; redirects are disabled. import assert from 'node:assert/strict' import { randomUUID } from 'node:crypto' import { once } from 'node:events' import { createServer } from 'node:http' +import { isDeepStrictEqual } from 'node:util' + +const { DEVA_ORIGIN: origin, DEVA_WEB_TOKEN: token, DEVA_SMOKE_SESSION: existing, DEVA_SMOKE_AFTER_REVOKE: revokeFlag, + DEVA_MODEL_PROTOCOL: protocol = 'openai', DEVA_SMOKE_EXPECT_PROTOCOL: expected } = process.env +const host = '127.0.0.1', port = 18795, model = 'deva-compose-fixture' +const sidPattern = /^web_[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/u +assert.ok(process.env.DEVA_MODEL === model && process.env.DEVA_MODEL_BASE_URL === `http://${host}:${port}/v1` && + !process.env.DEVA_MODEL_API_KEY, 'fixture model required') +assert.ok(/^http:\/\/127\.0\.0\.1:\d+$/u.test(origin) && /^[A-Za-z0-9_-]{32,128}$/u.test(token), 'loopback origin and owner token required') +assert.ok((expected ?? 'openai') === protocol && (protocol === 'openai' || protocol === (existing ? 'anthropic' : 'responses')), + 'fixture protocol does not match probe stage') +assert.ok(!existing || sidPattern.test(existing), 'invalid session ID') +const afterRevoke = revokeFlag === '1', shouldStop = protocol === 'responses' +assert.ok(revokeFlag === undefined || (afterRevoke && existing && expected === 'openai'), 'revoked stage requires a session and explicit OpenAI expectation') -const { DEVA_ORIGIN: origin, DEVA_WEB_TOKEN: token, DEVA_SMOKE_SESSION: existing } = process.env -assert.equal(process.env.DEVA_MODEL, 'deva-compose-fixture') -assert.equal(process.env.DEVA_MODEL_BASE_URL, 'http://127.0.0.1:18795/v1') -assert.ok(/^http:\/\/127\.0\.0\.1:\d+$/u.test(origin) && !process.env.DEVA_MODEL_API_KEY) -const protocol = process.env.DEVA_MODEL_PROTOCOL ?? 'openai' -assert.equal(protocol, process.env.DEVA_SMOKE_EXPECT_PROTOCOL ?? 'openai') -assert.ok(['openai', 'responses', 'anthropic'].includes(protocol)) -const prompt = existing ? 'continue after restart' : 'hello from compose' const attachment = { name: 'reading-notes.md', text: 'A short note.\r\n谢谢。' } const first = [{ role: 'user', text: 'hello from compose', attachment }, { role: 'assistant', text: 'fixture reply' }] -const sent = existing ? { role: 'user', text: prompt } : first[0] +const interrupted = [...first, { role: 'user', text: 'start a synthetic reply for Stop' }, { role: 'assistant', text: 'visible partial reply' }] +const followUp = { role: 'user', text: 'continue after restart' } +const continued = [...interrupted, followUp, { role: 'assistant', text: 'fixture continuation reply' }] +const revoked = [...continued, { role: 'user', text: 'continue after synthetic document revocation' }, { role: 'assistant', text: 'fixture reply after revoke' }] +const [initial, completed] = afterRevoke ? [continued, revoked] : protocol === 'anthropic' ? [interrupted, continued] + : existing ? [first, [...first, followUp, first[1]]] : [[], first] +const turns = shouldStop ? [completed, interrupted] : [completed] +const title = 'Saved reading notes' +const route = { openai: '/v1/chat/completions', responses: '/v1/responses', anthropic: '/v1/messages' }[protocol] const parts = m => m.attachment ? [`[附件文件] ${m.attachment.name}\n\`\`\`\n${m.attachment.text}\n\`\`\``, m.text] : [m.text] -let cookie, calls = 0 +const wire = m => ({ role: m.role, content: protocol === 'openai' ? parts(m).join('\n') : parts(m).map(text => ({ + type: protocol === 'anthropic' ? 'text' : m.role === 'assistant' ? 'output_text' : 'input_text', text +})) }) +// Fixed diagnostics, even if an unexpected response contains private values. +const equal = (actual, expected, label) => assert.ok(isDeepStrictEqual(actual, expected), label) +const parse = text => { try { return JSON.parse(text) } catch { throw new Error('invalid probe JSON') } } +let cookie, calls = 0, held const fixture = createServer(async (req, res) => { try { - assert.equal(req.method, 'POST'); calls++ - assert.equal(req.url, { openai: '/v1/chat/completions', responses: '/v1/responses', anthropic: '/v1/messages' }[protocol]) + const turn = turns[calls++] + assert.ok(req.method === 'POST' && req.url === route, 'fixture route mismatch') + assert.ok(turn, 'extra provider request') const chunks = []; for await (const chunk of req) chunks.push(chunk) - const body = JSON.parse(Buffer.concat(chunks)), history = [...(existing ? first : []), sent] - assert.equal(body.model, process.env.DEVA_MODEL); assert.equal(body.stream, true); assert.ok(!body.tools) + const body = parse(Buffer.concat(chunks)), reply = turn.at(-1).text + assert.ok(body.model === model && body.stream === true && !Object.hasOwn(body, 'tools'), 'fixture model request mismatch') + equal(shouldStop ? body.input : body.messages, turn.slice(0, -1).map(wire), 'provider fixture history mismatch') res.writeHead(200, { 'Content-Type': 'text/event-stream' }) const frame = (type, fields = {}) => res.write(`event: ${type}\ndata: ${JSON.stringify({ type, ...fields })}\n\n`) if (protocol === 'responses') { - assert.equal(body.store, false); assert.ok(!body.previous_response_id) - assert.deepEqual(body.input, history.map(m => ({ role: m.role, content: parts(m).map(text => ({ type: m.role === 'assistant' ? 'output_text' : 'input_text', text })) }))) - frame('response.output_text.delta', { delta: 'fixture reply' }) + assert.ok(body.store === false && !Object.hasOwn(body, 'previous_response_id'), 'Responses must be stateless') + if (turn === interrupted) held = { response: res, socket: req.socket } + frame('response.output_text.delta', { delta: reply }) + if (turn === interrupted) return // Only Stop closes this wire; the fixture never sends a terminal or EOF. frame('response.completed', { response: { id: 'resp_probe', status: 'completed' } }) } else if (protocol === 'anthropic') { - assert.equal(req.headers['anthropic-version'], '2023-06-01') - assert.deepEqual(body.messages, history.map(m => ({ role: m.role, content: parts(m).map(text => ({ type: 'text', text })) }))) + equal(req.headers['anthropic-version'], '2023-06-01', 'Anthropic version mismatch') frame('message_start', { message: { id: 'msg_probe', role: 'assistant', content: [] } }) frame('content_block_start', { index: 0, content_block: { type: 'text', text: '' } }) - frame('content_block_delta', { index: 0, delta: { type: 'text_delta', text: 'fixture reply' } }) + frame('content_block_delta', { index: 0, delta: { type: 'text_delta', text: reply } }) frame('content_block_stop', { index: 0 }); frame('message_delta', { delta: { stop_reason: 'end_turn' } }); frame('message_stop') } else { - assert.deepEqual(body.messages, history.map(m => ({ role: m.role, content: parts(m).join('\n') }))) - res.write('data: {"choices":[{"delta":{"content":"fixture reply"},"finish_reason":"stop"}]}\n\ndata: [DONE]\n\n') + const choice = (delta, finish_reason) => res.write(`data: ${JSON.stringify({ choices: [{ index: 0, delta, finish_reason }] })}\n\n`) + choice({ content: reply }, null); choice({}, 'stop'); res.write('data: [DONE]\n\n') } res.end() } catch (err) { console.error(err.message); res.destroy() } }) -async function api(path, body) { +async function api(path, body, signal = AbortSignal.timeout(10_000)) { const res = await fetch(`${origin}/api/${path}`, { method: body ? 'POST' : 'GET', headers: { ...(cookie && { Cookie: cookie }), ...(body && { Origin: origin, 'Content-Type': 'application/json' }) - }, body: body && JSON.stringify(body), signal: AbortSignal.timeout(10000) }) + }, body: body && JSON.stringify(body), signal, redirect: 'error' }) assert.ok(res.ok, `${path} returned ${res.status}`); return res } +const json = async (...args) => parse(await (await api(...args)).text()) +async function* ndjson(res) { + assert.ok(/^application\/x-ndjson\b/u.test(res.headers.get('content-type')), 'expected NDJSON') + let tail = '' + for await (const chunk of res.body.pipeThrough(new TextDecoderStream())) { + const lines = (tail + chunk).split('\n'); tail = lines.pop() + for (const line of lines) yield parse(line) + } + assert.ok(!tail, 'incomplete NDJSON frame') +} +const delta = text => ({ type: 'delta', text }), done = reason => ({ type: 'done', reason }) +async function finish(events, ...expected) { + const received = []; for await (const event of events) received.push(event) + equal(received, expected, 'unexpected turn frames or terminal reason') +} +function saved(view, history) { + equal(view.messages, history, 'saved history mismatch') + equal(view.active, null, 'expected no active turn') +} try { - await once(fixture.listen(18795, '127.0.0.1'), 'listening') - const login = await api('login', { token }); cookie = login.headers.get('set-cookie').split(';')[0]; await login.json() - const sid = existing || (await (await api('sessions', {})).json()).id - assert.match(sid, /^web_[a-f0-9-]{36}$/u) - const path = `sessions/${sid}`, title = 'Saved reading notes' - let view = await (await api(path)).json() - assert.deepEqual(view.messages, existing ? first : []) + await once(fixture.listen(port, host), 'listening', { signal: AbortSignal.timeout(10_000) }) + const login = await api('login', { token }); cookie = login.headers.get('set-cookie')?.split(';', 1)[0] + assert.ok(/^deva_web=[A-Za-z0-9_-]+$/u.test(cookie), 'missing owner session cookie') + equal(parse(await login.text()), { ok: true }, 'login acknowledgement mismatch') + const sid = existing || (await json('sessions', {})).id + assert.ok(typeof sid === 'string' && sidPattern.test(sid), 'invalid session ID') + const path = `sessions/${sid}` + const send = async (view, { text, attachment }, turnId = randomUUID(), signal) => + ndjson(await api(`${path}/turns`, { text, revision: view.revision, turnId, attachment }, signal)) + let view = await json(path) + saved(view, initial) if (existing) { - assert.deepEqual((await (await api('sessions/archived')).json()).sessions, [{ id: sid, title, archived: true }]) - assert.deepEqual((await (await api('sessions')).json()).sessions, []) - view = await (await api(`${path}/archive`, { archived: false, revision: view.revision })).json() - assert.equal(view.title, title); assert.deepEqual(view.messages, first) + assert.ok(view.title === title, 'saved title was not reloaded') + const index = await json('sessions') + if (afterRevoke) { + assert.ok(!view.archived && !Object.hasOwn(index, 'projectDocs'), 'expected restored chat without the document viewer') + equal(index.sessions, [{ id: sid, title }], 'active list mismatch after revoke') + } else { + assert.ok(view.archived === true, 'archive was not reloaded') + equal((await json('sessions/archived')).sessions, [{ id: sid, title, archived: true }], 'archived list mismatch') + equal(index.sessions, [], 'active list mismatch') + view = await json(`${path}/archive`, { archived: false, revision: view.revision }) + assert.ok(!view.archived && view.title === title, 'restore changed the title or archive state') + saved(view, initial) + } + } + equal(calls, 0, 'session setup contacted the fixture') + await finish(await send(view, completed.at(-2)), delta(completed.at(-1).text), done('complete')) + equal(calls, 1, 'complete turn provider call count mismatch') + view = await json(path); saved(view, completed) + if (existing) assert.ok(!view.archived && view.title === title, 'continuation changed the title or archive state') + if (shouldStop) { + const turnId = randomUUID(), streamDeadline = AbortSignal.timeout(10_000) + const events = await send(view, interrupted.at(-2), turnId, streamDeadline) + equal(await events.next(), { value: delta(interrupted.at(-1).text), done: false }, 'missing visible partial before Stop') + const active = await json(path, undefined, streamDeadline) + equal(active.active, turnId, 'second turn is not active') + equal(active.messages, interrupted.slice(0, -1), 'live history mismatch') + const { response, socket } = held ?? {} + assert.ok(socket && !socket.destroyed && !response.writableEnded, 'upstream was not open before Stop') + const stopDeadline = AbortSignal.timeout(3_000) + const [, ack] = await Promise.all([ + once(socket, 'close', { signal: stopDeadline }), json(`${path}/stop`, { turnId }, stopDeadline) + ]) + equal(ack, { ok: true }, 'Stop acknowledgement mismatch') + assert.ok(socket.destroyed && !response.writableEnded && !streamDeadline.aborted && !stopDeadline.aborted, + 'upstream did not close on Stop before fixture EOF or probe deadlines') + await finish(events, done('stopped')) + assert.ok(!streamDeadline.aborted, 'turn stream deadline elapsed') + view = await json(path); saved(view, interrupted) } - assert.equal(calls, 0) - const stream = await api(`${path}/turns`, { text: prompt, revision: view.revision, turnId: randomUUID(), ...(!existing && { attachment }) }) - const events = (await stream.text()).trim().split('\n').map(line => JSON.parse(line)) - assert.deepEqual(events, [{ type: 'delta', text: 'fixture reply' }, { type: 'done', reason: 'complete' }]) - assert.equal(calls, 1) - const saved = await (await api(path)).json() - assert.deepEqual(saved.messages, [...view.messages, sent, { role: 'assistant', text: 'fixture reply' }]) if (!existing) { - const renamed = await (await api(`${path}/title`, { title, revision: saved.revision })).json() - const archived = await (await api(`${path}/archive`, { archived: true, revision: renamed.revision })).json() - assert.ok(archived.archived); assert.deepEqual(archived.messages, first) + const renamed = await json(`${path}/title`, { title, revision: view.revision }) + const archived = await json(`${path}/archive`, { archived: true, revision: renamed.revision }) + assert.ok(archived.archived === true && archived.title === title, 'archive or title did not persist') + saved(archived, turns.at(-1)) } - assert.equal(calls, 1) + equal(calls, turns.length, 'final provider call count mismatch') console.log(sid) -} finally { fixture.closeAllConnections(); await new Promise(resolve => fixture.close(resolve)) } +} finally { + const closed = new Promise(resolve => fixture.close(resolve)); fixture.closeAllConnections(); await closed +} From 8547051692de410bccd8778bb8bf32636a1b0960 Mon Sep 17 00:00:00 2001 From: Facetomyself <[GIT_EMAIL]> Date: Fri, 27 Nov 2026 18:39:08 +0800 Subject: [PATCH 2/3] =?UTF-8?q?test(compose):=20=E6=A0=B8=E5=AF=B9?= =?UTF-8?q?=E5=8E=9F=E7=94=9F=E9=95=9C=E5=83=8F=E8=AF=81=E6=8D=AE=E4=B8=8E?= =?UTF-8?q?=E9=AA=8C=E6=94=B6=E8=B5=84=E6=BA=90=E5=BD=92=E5=B1=9E=20/=20va?= =?UTF-8?q?lidate=20native=20image=20evidence=20and=20test=20resource=20ow?= =?UTF-8?q?nership?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../test/compose-acceptance-evidence.mjs | 164 ++++++++++++++++++ .../test/compose-acceptance-evidence.test.mjs | 139 +++++++++++++++ apps/desktop/test/compose-acceptance-host.mjs | 155 +++++++++++++++++ .../test/compose-acceptance-host.test.mjs | 109 ++++++++++++ .../test/compose-acceptance-lifecycle.mjs | 63 +++++++ .../compose-acceptance-lifecycle.test.mjs | 67 +++++++ .../test/headless-compose-default.test.mjs | 14 +- 7 files changed, 707 insertions(+), 4 deletions(-) create mode 100644 apps/desktop/test/compose-acceptance-evidence.mjs create mode 100644 apps/desktop/test/compose-acceptance-evidence.test.mjs create mode 100644 apps/desktop/test/compose-acceptance-host.mjs create mode 100644 apps/desktop/test/compose-acceptance-host.test.mjs create mode 100644 apps/desktop/test/compose-acceptance-lifecycle.mjs create mode 100644 apps/desktop/test/compose-acceptance-lifecycle.test.mjs diff --git a/apps/desktop/test/compose-acceptance-evidence.mjs b/apps/desktop/test/compose-acceptance-evidence.mjs new file mode 100644 index 00000000..bfed9347 --- /dev/null +++ b/apps/desktop/test/compose-acceptance-evidence.mjs @@ -0,0 +1,164 @@ +import { posix } from 'node:path' +import { isDeepStrictEqual } from 'node:util' + +const containerIdPattern = /^[a-f0-9]{64}$/ +const imageIdPattern = /^sha256:[a-f0-9]{64}$/ +const projectPattern = /^deva-accept-[a-f0-9]{24}$/ +const volumePattern = /^deva-accept-[a-f0-9]{24}_deva-data$/ +const nodePattern = /^v22\.(?:0|[1-9]\d{0,2})\.(?:0|[1-9]\d{0,2})$/ +const enginePattern = /^\d{1,3}\.\d{1,3}\.\d{1,4}(?:[-+][a-zA-Z0-9]+(?:[.+~-][a-zA-Z0-9]+)*)?$/ +const snapshotTarget = '/run/deva-project-docs/snapshot.json' +const matches = (pattern, value) => typeof value === 'string' && pattern.test(value) +const x86 = value => value === 'amd64' || value === 'x86_64' +const record = value => value !== null && typeof value === 'object' && !Array.isArray(value) +const emptyList = value => value == null || (Array.isArray(value) && value.length === 0) +const emptyMap = value => value == null || (record(value) && Object.keys(value).length === 0) +const onlyKeys = (value, allowed) => record(value) && Object.keys(value).every(key => allowed.includes(key)) +const unsetOr = (value, expected) => value === undefined || value === expected +const exactListValue = (value, expected) => Array.isArray(value) && value.length === 1 && expected.includes(value[0]) +const noNewPrivileges = ['no-new-privileges:true', 'no-new-privileges=true'] +const validPort = value => Number.isInteger(value) && value > 0 && value <= 65535 +const absolute = value => typeof value === 'string' && posix.isAbsolute(value) && posix.normalize(value) === value && + !value.endsWith('/') && !/[\x00-\x1f\x7f]/.test(value) +const privateSource = value => absolute(value) && posix.dirname(value) !== '/' + +function requireEvidence(condition, reason) { + if (!condition) throw new Error(reason) +} + +export function checkEngine(info) { + const { OSType, Architecture, ServerVersion } = info ?? {} + requireEvidence(OSType === 'linux', 'engine.os') + requireEvidence(x86(Architecture), 'engine.architecture') + requireEvidence(matches(enginePattern, ServerVersion) && ServerVersion.length <= 64, 'engine.version') + return ServerVersion +} + +const planServiceKeys = ['build', 'cap_drop', 'command', 'entrypoint', 'environment', 'networks', 'ports', + 'read_only', 'restart', 'security_opt', 'volumes', 'privileged'] +const planEnvironmentKeys = ['DEVA_HOST', 'DEVA_PORT', 'DEVA_ORIGIN', 'DEVA_WEB_TOKEN', 'DEVA_MODEL_PROTOCOL', + 'DEVA_MODEL_BASE_URL', 'DEVA_MODEL', 'DEVA_MODEL_API_KEY'] + +export function checkPlan(plan, options) { + const { project, port, work, snapshotFile, granted } = options ?? {} + requireEvidence(matches(projectPattern, project) && validPort(port) && absolute(work) && + typeof granted === 'boolean' && (!granted || privateSource(snapshotFile)), 'plan.inputs') + requireEvidence(onlyKeys(plan, ['name', 'services', 'networks', 'volumes']) && plan.name === project && + onlyKeys(plan.services, ['deva']) && onlyKeys(plan.services.deva, planServiceKeys), 'plan.services') + const service = plan.services.deva + const { build, environment: env } = service + requireEvidence(onlyKeys(build, ['context', 'dockerfile']) && build.context === work && + (unsetOr(build.dockerfile, 'Dockerfile') || build.dockerfile === posix.join(work, 'Dockerfile')), 'plan.build') + const envKeys = granted ? [...planEnvironmentKeys, 'DEVA_PROJECT_DOCS_SHA256'] : planEnvironmentKeys + requireEvidence(onlyKeys(env, envKeys) && envKeys.every(key => typeof env[key] === 'string') && + (!granted || matches(containerIdPattern, env.DEVA_PROJECT_DOCS_SHA256)), 'plan.environment') + requireEvidence(service.read_only === true && unsetOr(service.privileged, false) && service.restart === 'unless-stopped' && + exactListValue(service.cap_drop, ['ALL']) && exactListValue(service.security_opt, noNewPrivileges) && + service.command == null && service.entrypoint == null, 'plan.runtime') + + const network = plan.networks?.default, attached = service.networks + requireEvidence(onlyKeys(plan.networks, ['default']) && onlyKeys(network, ['name', 'driver', 'external', 'ipam']) && + network.name === `${project}_default` && unsetOr(network.driver, 'bridge') && unsetOr(network.external, false) && + emptyMap(network.ipam) && (attached === undefined || (onlyKeys(attached, ['default']) && + Object.hasOwn(attached, 'default') && emptyMap(attached.default))), 'plan.network') + const volume = plan.volumes?.['deva-data'] + requireEvidence(onlyKeys(plan.volumes, ['deva-data']) && onlyKeys(volume, ['name', 'driver', 'external', 'driver_opts']) && + volume.name === `${project}_deva-data` && unsetOr(volume.driver, 'local') && unsetOr(volume.external, false) && + emptyMap(volume.driver_opts), 'plan.volume') + + const publication = service.ports?.[0] + requireEvidence(Array.isArray(service.ports) && service.ports.length === 1 && + onlyKeys(publication, ['host_ip', 'target', 'published', 'protocol', 'mode']) && publication.host_ip === '127.0.0.1' && + publication.target === port && [String(port), port].includes(publication.published) && + unsetOr(publication.protocol, 'tcp') && unsetOr(publication.mode, 'ingress'), 'plan.ports') + const mounts = service.volumes + requireEvidence(Array.isArray(mounts) && mounts.length === (granted ? 2 : 1), 'plan.mounts') + const data = mounts.find(mount => mount?.target === '/data') + requireEvidence(onlyKeys(data, ['type', 'source', 'target', 'volume', 'read_only']) && data.type === 'volume' && + data.source === 'deva-data' && emptyMap(data.volume) && unsetOr(data.read_only, false), 'plan.mounts') + if (granted) { + const bind = mounts.find(mount => mount?.target === snapshotTarget) + requireEvidence(onlyKeys(bind, ['type', 'source', 'target', 'bind', 'read_only']) && bind.type === 'bind' && + bind.source === snapshotFile && bind.read_only === true && onlyKeys(bind.bind, ['propagation', 'create_host_path']) && + bind.bind.propagation === 'rprivate' && unsetOr(bind.bind.create_host_path, false), 'plan.snapshot') + } +} + +// A config-only contrast: Compose v2.36 omits false; v5.7 omits true. Absence by itself proves neither. +export function sourceCreationControl(yaml) { + const declaration = /^([ \t]*create_host_path:[ \t]*)false[ \t]*$/gmu + requireEvidence(typeof yaml === 'string' && [...yaml.matchAll(declaration)].length === 1, 'plan.source-control') + return yaml.replace(declaration, '$1true') +} +export function checkSourceCreationControl(plan, control) { + const leaf = p => p?.services?.deva?.volumes?.find(v => v?.type === 'bind' && v.target === snapshotTarget)?.bind + const a = leaf(plan), b = leaf(control) + requireEvidence(record(a) && record(b) && unsetOr(a.create_host_path, false) && unsetOr(b.create_host_path, true) && + a.create_host_path !== b.create_host_path, 'plan.source-control') + const adjusted = structuredClone(control), test = leaf(adjusted) + if (Object.hasOwn(a, 'create_host_path')) test.create_host_path = a.create_host_path + else delete test.create_host_path + requireEvidence(isDeepStrictEqual(plan, adjusted), 'plan.source-control') +} + +function exactPort(bindings, port, allowUnpublished = false) { + if (!record(bindings)) return false + const key = `${port}/tcp` + const rows = bindings[key] + // Docker may include unbound image EXPOSE entries with null or empty bindings. + return Object.keys(bindings).every(name => name === key || (allowUnpublished && emptyList(bindings[name]))) && + Array.isArray(rows) && rows.length === 1 && rows[0]?.HostIp === '127.0.0.1' && rows[0]?.HostPort === String(port) +} + +export function checkStage(evidence) { + const { container, image, node, project, port, snapshotFile, granted } = evidence ?? {} + requireEvidence(matches(projectPattern, project), 'stage.project') + requireEvidence(record(container) && matches(containerIdPattern, container.Id), 'stage.container-id') + requireEvidence(record(image) && matches(imageIdPattern, image.Id) && container.Image === image.Id, 'stage.image') + requireEvidence(image.Os === 'linux' && x86(image.Architecture) && + (container.Platform === undefined || container.Platform === 'linux'), 'stage.platform') + requireEvidence(node?.os === 'linux' && node.arch === 'x64' && node.uid === 1000 && + matches(nodePattern, node.version), 'stage.node') + const { State: state, HostConfig: host, Config: config, NetworkSettings: network, Mounts: mounts } = container + const health = state?.Health + requireEvidence(state?.Running === true && state.Status === 'running' && !state.Paused && !state.Restarting && + health?.Status === 'healthy' && health.FailingStreak === 0 && Array.isArray(health.Log) && + health.Log.at(-1)?.ExitCode === 0, 'stage.health') + requireEvidence(config?.Labels?.['com.docker.compose.project'] === project && + config.Labels['com.docker.compose.service'] === 'deva', 'stage.labels') + requireEvidence(host?.ReadonlyRootfs === true && host.Privileged === false && emptyList(host.CapAdd) && + exactListValue(host.CapDrop, ['ALL']) && exactListValue(host.SecurityOpt, noNewPrivileges), 'stage.hardening') + requireEvidence(emptyList(host.Devices) && emptyList(host.DeviceRequests) && + emptyList(host.DeviceCgroupRules), 'stage.devices') + const networkName = `${project}_default`, attached = network?.Networks + requireEvidence(host.NetworkMode === networkName && (attached === undefined || + (onlyKeys(attached, [networkName]) && Object.hasOwn(attached, networkName))), 'stage.network') + requireEvidence(validPort(port) && !host.PublishAllPorts && + exactPort(network?.Ports, port, true) && + (host.PortBindings === undefined || exactPort(host.PortBindings, port)), 'stage.ports') + + requireEvidence(typeof granted === 'boolean' && emptyMap(host.Tmpfs) && emptyList(host.VolumesFrom) && + Array.isArray(mounts) && mounts.length === (granted ? 2 : 1), 'stage.mounts') + const volumeName = `${project}_deva-data` + const volume = mounts.find(mount => mount?.Destination === '/data') + requireEvidence(volume?.Type === 'volume' && volume.Name === volumeName && volume.RW === true && + (volume.Driver === undefined || volume.Driver === 'local'), 'stage.volume') + if (granted) { + const bind = mounts.find(mount => mount?.Destination === snapshotTarget) + // The caller creates and checks the private source on disk; inspect proves the exact leaf was mounted. + requireEvidence(privateSource(snapshotFile) && bind?.Type === 'bind' && bind.Source === snapshotFile && + bind.RW === false && unsetOr(bind.Propagation, 'rprivate'), 'stage.snapshot') + } + return { containerId: container.Id, imageId: image.Id, volumeName, nodeVersion: node.version } +} + +export function checkContinuity(stages) { + requireEvidence(Array.isArray(stages) && stages.length === 3 && Array.from(stages).every(stage => + record(stage) && matches(containerIdPattern, stage.containerId) && matches(imageIdPattern, stage.imageId) && + matches(volumePattern, stage.volumeName) && matches(nodePattern, stage.nodeVersion)), 'continuity.stages') + const [first, ...rest] = stages + requireEvidence(new Set(stages.map(stage => stage.containerId)).size === 3, 'continuity.containers') + requireEvidence(rest.every(stage => stage.imageId === first.imageId), 'continuity.image') + requireEvidence(rest.every(stage => stage.volumeName === first.volumeName), 'continuity.volume') + requireEvidence(rest.every(stage => stage.nodeVersion === first.nodeVersion), 'continuity.node') +} diff --git a/apps/desktop/test/compose-acceptance-evidence.test.mjs b/apps/desktop/test/compose-acceptance-evidence.test.mjs new file mode 100644 index 00000000..d8557cb4 --- /dev/null +++ b/apps/desktop/test/compose-acceptance-evidence.test.mjs @@ -0,0 +1,139 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { checkContinuity, checkEngine, checkPlan, checkSourceCreationControl, checkStage, sourceCreationControl } from './compose-acceptance-evidence.mjs' + +const project = `deva-accept-${'a'.repeat(24)}`, port = 18787, tcp = `${port}/tcp` +const volumeName = `${project}_deva-data`, imageId = `sha256:${'d'.repeat(64)}` +const snapshotFile = '/private-fixture/synthetic-snapshot.json', nodeVersion = 'v22.21.1' +const engine = { OSType: 'linux', Architecture: 'x86_64', ServerVersion: '27.5.1' } +const work = '/private-fixture/checkout', networkName = `${project}_default` + +function planFixture(granted = false) { + const environment = { DEVA_HOST: '0.0.0.0', DEVA_PORT: String(port), DEVA_ORIGIN: `http://127.0.0.1:${port}`, + DEVA_WEB_TOKEN: 'synthetic', DEVA_MODEL_PROTOCOL: 'openai', DEVA_MODEL_BASE_URL: 'http://192.0.2.1:1234/v1', + DEVA_MODEL: 'fixture', DEVA_MODEL_API_KEY: '' } + const volumes = [{ type: 'volume', source: 'deva-data', target: '/data', volume: {} }] + if (granted) { + environment.DEVA_PROJECT_DOCS_SHA256 = 'b'.repeat(64) + volumes.push({ type: 'bind', source: snapshotFile, target: '/run/deva-project-docs/snapshot.json', read_only: true, + bind: { propagation: 'rprivate', create_host_path: false } }) + } + return { name: project, networks: { default: { name: networkName, ipam: {} } }, + volumes: { 'deva-data': { name: volumeName } }, services: { deva: { + build: { context: work, dockerfile: 'Dockerfile' }, command: null, entrypoint: null, environment, + networks: { default: null }, ports: [{ host_ip: '127.0.0.1', target: port, published: String(port), + mode: 'ingress', protocol: 'tcp' }], volumes, read_only: true, restart: 'unless-stopped', + cap_drop: ['ALL'], security_opt: ['no-new-privileges:true'] } } } +} +function fixture(id = 'a', granted = false) { + const bindings = () => ({ [tcp]: [{ HostIp: '127.0.0.1', HostPort: String(port) }] }) + const container = { Id: id.repeat(64), Image: imageId, Platform: 'linux', + State: { Status: 'running', Running: true, Health: { Status: 'healthy', FailingStreak: 0, + Log: [{ ExitCode: 0, Output: 'synthetic private probe output' }] } }, + Config: { Labels: { 'com.docker.compose.project': project, 'com.docker.compose.service': 'deva' }, + Env: ['DEVA_WEB_TOKEN=synthetic-private-credential'] }, + HostConfig: { ReadonlyRootfs: true, Privileged: false, CapDrop: ['ALL'], CapAdd: null, + SecurityOpt: ['no-new-privileges:true'], Devices: [], DeviceRequests: null, NetworkMode: networkName, + PortBindings: bindings(), PublishAllPorts: false }, + NetworkSettings: { Ports: { ...bindings(), '8787/tcp': null, '9797/tcp': [] }, Networks: { [networkName]: {} } }, + Mounts: [{ Type: 'volume', Name: volumeName, Driver: 'local', Destination: '/data', RW: true }] } + if (granted) container.Mounts.push({ Type: 'bind', Destination: '/run/deva-project-docs/snapshot.json', + Source: snapshotFile, RW: false, Propagation: 'rprivate' }) + return { container, image: { Id: imageId, Os: 'linux', Architecture: 'amd64' }, + node: { os: 'linux', arch: 'x64', uid: 1000, version: nodeVersion }, project, port, snapshotFile, granted } +} + +const fails = (fn, message) => assert.throws(fn, { name: 'Error', message }) + +test('preflight accepts the current Compose plan shapes, including harmless omissions', () => { + for (const granted of [false, true]) { + const plan = planFixture(granted), options = { project, port, work, snapshotFile, granted } + assert.equal(checkPlan(plan, options), undefined) + delete plan.services.deva.command + delete plan.services.deva.build.dockerfile + delete plan.networks.default.ipam + assert.equal(checkPlan(plan, options), undefined) + } +}) + +for (const [name, reason, mutate, granted = false] of [ + ['extra service', 'services', plan => { plan.services.other = plan.services.deva }], + ['external service image', 'services', (_, service) => { service.image = 'other:stable' }], + ['host IPC', 'services', (_, service) => { service.ipc = 'host' }], + ['alternate command', 'runtime', (_, service) => { service.command = ['node', '-e', '0'] }], + ['alternate build context', 'build', (_, service) => { service.build.context = '/private-fixture/other' }], + ['build secrets', 'build', (_, service) => { service.build.secrets = ['synthetic'] }], + ['external network', 'network', plan => { plan.networks.default.external = true }], + ['driver-bound data volume', 'volume', plan => { plan.volumes['deva-data'].driver_opts = { type: 'none', o: 'bind' } }], + ['wildcard port', 'ports', (_, service) => { service.ports[0].host_ip = '0.0.0.0' }], + ['host mount', 'mounts', (_, service) => { service.volumes.push({ type: 'bind', source: '/private-fixture/other' }) }], + ['auto-created snapshot source', 'snapshot', (_, service) => { service.volumes[1].bind.create_host_path = true }, true], +]) test(`preflight rejects ${name} with a constant code`, () => { + const plan = planFixture(granted) + mutate(plan, plan.services.deva) + fails(() => checkPlan(plan, { project, port, work, snapshotFile, granted }), `plan.${reason}`) +}) + +test('bind auto-creation needs an explicit false source and a meaningful config-only contrast', () => { + assert.equal(sourceCreationControl('bind:\n create_host_path: false\n'), 'bind:\n create_host_path: true\n') + for (const ambiguous of ['# create_host_path: false', 'create_host_path: true', 'create_host_path: false\ncreate_host_path: false']) { + fails(() => sourceCreationControl(ambiguous), 'plan.source-control') + } + const pair = (value, source = snapshotFile) => ({ services: { deva: { volumes: [{ type: 'bind', source, + target: '/run/deva-project-docs/snapshot.json', bind: { propagation: 'rprivate', ...(value === undefined ? {} : { create_host_path: value }) } }] } } }) + for (const [a, b] of [[false, true], [undefined, true], [false, undefined]]) checkSourceCreationControl(pair(a), pair(b)) + for (const [a, b] of [[undefined, undefined], [true, undefined], [false, false]]) fails(() => checkSourceCreationControl(pair(a), pair(b)), 'plan.source-control') + fails(() => checkSourceCreationControl(pair(false), pair(true, '/changed/leaf')), 'plan.source-control') +}) + +test('engine evidence yields a bounded Linux x86-64 server version', () => { + assert.equal(checkEngine(engine), '27.5.1') + assert.equal(checkEngine({ ...engine, Architecture: 'amd64', ServerVersion: '26.1.3+dfsg1' }), '26.1.3+dfsg1') + fails(() => checkEngine({ ...engine, OSType: 'windows' }), 'engine.os') + fails(() => checkEngine({ ...engine, Architecture: 'arm64' }), 'engine.architecture') + for (const version of ['27.5.1\n', '27.5.1 private=/path', `27.5.1+${'a'.repeat(64)}`]) { + fails(() => checkEngine({ ...engine, ServerVersion: version }), 'engine.version') + } +}) + +test('default, enabled and revoked fixtures produce only qualified receipt fields', () => { + const stages = [fixture(), fixture('b', true), fixture('c')].map(checkStage) + assert.deepEqual(stages[1], { containerId: 'b'.repeat(64), imageId, volumeName, nodeVersion }) + assert.equal(checkContinuity(stages), undefined) +}) + +for (const [name, reason, mutate, granted = false] of [ + ['short ID', 'container-id', e => { e.container.Id = 'deadbeef' }], + ['swapped inspected image', 'image', e => { e.image.Id = `sha256:${'e'.repeat(64)}` }], + ['foreign image architecture', 'platform', e => { e.image.Architecture = 'arm64' }], + ['foreign Node architecture', 'node', e => { e.node.arch = 'arm64' }], + ['root Node process', 'node', e => { e.node.uid = 0 }], + ['wrong Node release', 'node', e => { e.node.version = 'v24.1.0' }], + ['fake health status', 'health', e => { e.container.State.Health = { Status: 'healthy' } }], + ['writable root', 'hardening', e => { e.container.HostConfig.ReadonlyRootfs = false }], + ['extra capability', 'hardening', e => { e.container.HostConfig.CapAdd = ['SYS_ADMIN'] }], + ['missing no-new-privileges', 'hardening', e => { e.container.HostConfig.SecurityOpt = [] }], + ['extra device', 'devices', e => { e.container.HostConfig.Devices = [{ PathOnHost: '/private/device' }] }], + ['host network', 'network', e => { e.container.HostConfig.NetworkMode = 'host' }], + ['extra attached network', 'network', e => { e.container.NetworkSettings.Networks.other = {} }], + ['wildcard port', 'ports', e => { e.container.NetworkSettings.Ports[tcp][0].HostIp = '0.0.0.0' }], + ['second published port', 'ports', e => { e.container.NetworkSettings.Ports['8787/tcp'] = e.container.NetworkSettings.Ports[tcp] }], + ['extra mount in a disabled stage', 'mounts', e => { e.container.Mounts.push({ Type: 'bind' }) }], + ['swapped volume', 'volume', e => { e.container.Mounts[0].Name = 'other-volume' }], + ['writable snapshot', 'snapshot', e => { e.container.Mounts[1].RW = true }, true], + ['shared snapshot', 'snapshot', e => { e.container.Mounts[1].Propagation = 'rshared' }, true], + ['different snapshot', 'snapshot', e => { e.container.Mounts[1].Source = '/private-fixture/withheld.json' }, true], +]) test(`stage rejects ${name} with a constant code`, () => { + const evidence = fixture('a', granted) + mutate(evidence) + fails(() => checkStage(evidence), `stage.${reason}`) +}) + +test('continuity rejects missing, duplicate or changed stage evidence', () => { + const [a, b, c] = [fixture(), fixture('b', true), fixture('c')].map(checkStage) + fails(() => checkContinuity([a, b]), 'continuity.stages') + fails(() => checkContinuity([a, b, a]), 'continuity.containers') + fails(() => checkContinuity([a, b, { ...c, imageId: `sha256:${'e'.repeat(64)}` }]), 'continuity.image') + fails(() => checkContinuity([a, b, { ...c, volumeName: `deva-accept-${'e'.repeat(24)}_deva-data` }]), 'continuity.volume') + fails(() => checkContinuity([a, b, { ...c, nodeVersion: 'v22.21.2' }]), 'continuity.node') +}) diff --git a/apps/desktop/test/compose-acceptance-host.mjs b/apps/desktop/test/compose-acceptance-host.mjs new file mode 100644 index 00000000..acf17302 --- /dev/null +++ b/apps/desktop/test/compose-acceptance-host.mjs @@ -0,0 +1,155 @@ +import { execFileSync } from 'node:child_process' +import { chmodSync, lstatSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs' +import os from 'node:os' +import path from 'node:path' + +const RUNNER = 'apps/desktop/test/verify-native-compose.mjs' +const INPUTS = ['.dockerignore', '.npmrc', 'Dockerfile', 'compose.yaml', 'compose.project-docs.yaml', + 'package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml', 'apps/desktop/package.json', + 'apps/desktop/vite.headless.config.ts', 'apps/desktop/test/headless-compose-probe.mjs', + 'apps/desktop/test/headless-compose-docs-probe.mjs'] +const PREFIX = 'deva-native-compose-' +const SNAPSHOT = String.raw`{"version":1,"project":"发布手册","documents":[{"name":"入门.md","text":"首次使用:先阅读版本说明。\n"}]}` + '\n' +const CLI_OPTIONS = { stdio: ['pipe', 'pipe', 'pipe'], timeout: 30_000, maxBuffer: 64 * 1024 * 1024 } + +export function requireNativeHost(platform = process.platform, arch = process.arch, machine = os.machine()) { + if (platform !== 'linux' || arch !== 'x64' || machine !== 'x86_64') throw new Error('native_linux_amd64_required') +} + +export function commandEnv(env = process.env) { + const result = { LANG: 'C', COMPOSE_DISABLE_ENV_FILE: '1' } + // Pin relative paths to the caller's cwd without collapsing symlink-sensitive `..` segments. + const absolute = (value) => path.isAbsolute(value) ? value : value ? `${process.cwd()}${path.sep}${value}` : process.cwd() + for (const key of ['PATH', 'HOME', 'XDG_RUNTIME_DIR', 'DOCKER_CONFIG']) { + if (!Object.hasOwn(env, key) || typeof env[key] !== 'string' || env[key] === '') continue + result[key] = key === 'PATH' ? env[key].split(path.delimiter).map(absolute).join(path.delimiter) : absolute(env[key]) + } + return result +} + +function socketUrl(host) { + const socket = typeof host === 'string' && host.startsWith('unix://') && host.slice('unix://'.length) + if (!socket || !socket.startsWith('/') || socket.endsWith('/') || /[\s\p{Cc}\\?#%]/u.test(socket) || + socket.split('/').some((part, i, parts) => part === '..' || (part === '.' && i === parts.length - 1))) { + throw new Error('native_compose_local_unix_endpoint_required') + } + return `unix://${path.posix.normalize(socket)}` +} + +export function localDockerEndpoint(env = process.env) { + const { DOCKER_HOST: host, DOCKER_CONTEXT: context } = env + if (host && context) throw new Error('native_compose_docker_context_ambiguous') + if (host) return socketUrl(host) + let endpoint + try { + // This command reads CLI metadata only. With no explicit name it inspects the selected context. + const args = ['context', 'inspect', '--format', '{{json .Endpoints.docker.Host}}'] + if (context) args.push('--', context) + endpoint = JSON.parse(execFileSync('docker', args, { ...CLI_OPTIONS, env: commandEnv(env), encoding: 'utf8' })) + } catch { + throw new Error('native_compose_docker_context_inspection_failed') + } + return socketUrl(endpoint) +} + +function exportTree(git, sha, work) { + // Use Git's object store directly: archive attributes, checkout filters and symlinks never affect the export. + const listing = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }) + .decode(git(['ls-tree', '-rz', '--full-tree', sha, '--', ...INPUTS, 'apps/desktop'])) + let runnerTracked = false + const entries = listing.split('\0').filter(Boolean).flatMap((entry) => { + const match = /^(\d+) (\w+) ([0-9a-f]+)\t([^]+)$/u.exec(entry) + if (!match) throw new Error('native_compose_invalid_source_tree') + const [, mode, type, oid, file] = match + const regular = type === 'blob' && ['100644', '100755'].includes(mode) + if (file === RUNNER) runnerTracked = regular + if (!INPUTS.includes(file) && !file.startsWith('apps/desktop/src/') && + !/^apps\/desktop\/tsconfig[^/]*\.json$/u.test(file) && file !== 'apps/desktop/src') return [] + const parts = file.split('/') + if (parts.some((part) => /^(?:\.git$|\.env|node_modules$)|\.(?:pem|key)$/iu.test(part))) return [] + if (!regular || file === 'apps/desktop/src' || parts.some((part) => + !part || part === '.' || part === '..' || part.includes('\\'))) throw new Error('native_compose_invalid_source_tree') + return [{ oid, file, mode }] + }) + if (!runnerTracked) throw new Error('native_compose_runner_must_be_tracked') + const blobs = git(['cat-file', '--batch'], entries.map(({ oid }) => `${oid}\n`).join('')) + let offset = 0 + for (const { oid, file, mode } of entries) { + const headerEnd = blobs.indexOf(10, offset) + const header = headerEnd >= 0 && /^([0-9a-f]+) blob (\d+)$/u.exec(blobs.toString('ascii', offset, headerEnd)) + const end = header && headerEnd + 1 + Number(header[2]) + if (!header || header[1] !== oid || blobs[end] !== 10) throw new Error('native_compose_invalid_source_blob') + const target = path.join(work, file) + mkdirSync(path.dirname(target), { recursive: true }) + writeFileSync(target, blobs.subarray(headerEnd + 1, end), { flag: 'wx', mode: mode === '100755' ? 0o555 : 0o444 }) + offset = end + 1 + } + if (offset !== blobs.length) throw new Error('native_compose_invalid_source_blob') +} + +export function prepareSource(root) { + try { + return stageSource(root) + } catch (error) { + // Child-process and filesystem diagnostics can carry operator paths or data. + const code = /^native_compose_[a-z_]+$/u.test(error?.message) ? error.message : 'native_compose_source_preparation_failed' + throw new Error(code) + } +} + +function stageSource(root) { + const repo = realpathSync(root) + // A missing object in a partial clone must fail locally, including with older Git versions. + const env = { ...commandEnv(), GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null', + GIT_NO_LAZY_FETCH: '1', GIT_ALLOW_PROTOCOL: '' } + const git = (args, input) => execFileSync('git', ['--no-replace-objects', '--no-optional-locks', + '-c', 'core.fsmonitor=false', '-c', 'core.ignoreStat=false', '-c', 'core.fileMode=true', ...args], + { ...CLI_OPTIONS, cwd: repo, env, input }) + const top = git(['rev-parse', '--show-toplevel']).toString('utf8').replace(/\n$/u, '') + if (realpathSync(top) !== repo) throw new Error('native_compose_repository_root_required') + const sha = git(['rev-parse', '--verify', 'HEAD^{commit}']).toString('ascii').trim() + if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(sha)) throw new Error('native_compose_commit_required') + // Lowercase tags and S are assume-unchanged and skip-worktree; neither can establish a clean checkout. + if (git(['ls-files', '-vz']).toString('utf8').split('\0').some((entry) => /^[a-zS] /u.test(entry)) || + git(['status', '--porcelain=v1', '--untracked-files=no', '--ignore-submodules=none']).length) { + throw new Error('native_compose_clean_tracked_checkout_required') + } + + // Ignore ambient TMPDIR; this project must live outside the checkout, even if TMPDIR points inside it. + const tmp = realpathSync('/tmp') + const relative = path.relative(repo, tmp) + if (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)) { + throw new Error('native_compose_staging_outside_repository_required') + } + const dir = mkdtempSync(path.join(tmp, PREFIX)) + const identity = lstatSync(dir, { bigint: true }) + const uid = BigInt(process.getuid()) + let disposed = false + function checkStage() { + try { + const current = lstatSync(dir, { bigint: true }) + if (path.dirname(dir) === tmp && path.basename(dir).startsWith(PREFIX) && current.isDirectory() && + current.dev === identity.dev && current.ino === identity.ino && current.uid === uid && + (current.mode & 0o777n) === 0o700n && realpathSync(dir) === dir) return + } catch { /* A missing or inaccessible directory cannot establish identity. */ } + throw new Error('native_compose_staging_identity_changed') + } + function dispose() { + if (disposed) return + checkStage() + try { rmSync(dir, { recursive: true }) } catch { throw new Error('native_compose_staging_cleanup_failed') } + disposed = true + } + const work = path.join(dir, 'work'), snapshotFile = path.join(dir, 'snapshot.json') + try { + checkStage() + mkdirSync(work, { mode: 0o700 }) + exportTree(git, sha, work) + writeFileSync(snapshotFile, SNAPSHOT, { flag: 'wx', mode: 0o444 }) + chmodSync(snapshotFile, 0o444) // Readable by the container UID even when the operator has a restrictive umask. + return { sha, dir, work, snapshotFile, dispose } + } catch (error) { + try { dispose() } catch { throw new Error('native_compose_staging_cleanup_failed') } + throw error + } +} diff --git a/apps/desktop/test/compose-acceptance-host.test.mjs b/apps/desktop/test/compose-acceptance-host.test.mjs new file mode 100644 index 00000000..9b8896af --- /dev/null +++ b/apps/desktop/test/compose-acceptance-host.test.mjs @@ -0,0 +1,109 @@ +import assert from 'node:assert/strict' +import { execFileSync } from 'node:child_process' +import { createHash } from 'node:crypto' +import fs from 'node:fs' +import { syncBuiltinESMExports } from 'node:module' +import path from 'node:path' +import test from 'node:test' +import { commandEnv, localDockerEndpoint, prepareSource, requireNativeHost } from './compose-acceptance-host.mjs' + +const desktop = 'apps/desktop', runner = `${desktop}/test/verify-native-compose.mjs`, src = `${desktop}/src` +const included = ['Dockerfile', 'compose.yaml', `${src}/fixed`, `${desktop}/tsconfig.node.json`, + `${desktop}/test/headless-compose-probe.mjs`, `${desktop}/test/headless-compose-docs-probe.mjs`] +const excluded = ['.env', `${src}/.env.local`, `${src}/test.pem`, `${src}/test.key`, + 'remote-deployment.yaml', `${desktop}/test/unrelated-fixture`] +const temp = fs.realpathSync('/tmp') +function verifyDir(dir, identity) { + const st = fs.lstatSync(dir) + assert.ok(path.dirname(dir) === temp && fs.realpathSync(dir) === dir && st.isDirectory() && + st.dev === identity.dev && st.ino === identity.ino && st.uid === process.getuid() && (st.mode & 0o777) === 0o700) +} +function repository(t, trackRunner = true) { + const root = fs.mkdtempSync(path.join(temp, 'compose-host-test-')), identity = fs.lstatSync(root) + t.after(() => { verifyDir(root, identity); fs.rmSync(root, { recursive: true }) }) + const env = { ...commandEnv(), GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null' } + const git = (...args) => execFileSync('git', ['-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.test', + '-c', 'core.hooksPath=/dev/null', ...args], { cwd: root, env, stdio: ['ignore', 'pipe', 'pipe'] }).toString().trim() + const put = (file, contents = file) => { + const target = path.join(root, file) + fs.mkdirSync(path.dirname(target), { recursive: true }); fs.writeFileSync(target, contents) + } + git('init', '-q') + for (const file of [...included, ...excluded]) put(file) + put('.gitignore', '*.local\n'); put('.gitattributes', 'Dockerfile export-ignore\n') + if (trackRunner) put(runner) + git('add', '--force', `${src}/.env.local`) + git('add', '--all'); git('commit', '-qm', 'synthetic fixture') + return { root, git, put } +} + +test('native architecture, explicit local Unix endpoints, and the child environment allowlist', () => { + requireNativeHost('linux', 'x64', 'x86_64') + for (const args of [['darwin', 'x64', 'x86_64'], ['linux', 'arm64', 'aarch64'], ['linux', 'x64', 'aarch64']]) { + assert.throws(() => requireNativeHost(...args), { message: 'native_linux_amd64_required' }) + } + assert.equal(localDockerEndpoint({ DOCKER_HOST: 'unix:////run/user/1000/./docker.sock' }), 'unix:///run/user/1000/docker.sock') + for (const DOCKER_HOST of ['ssh://docker.example', 'tcp://127.0.0.1:2375', 'npipe:////./pipe/docker_engine', + 'unix://host/run/docker.sock', 'unix:///run/../docker.sock', 'unix:///run/docker.sock?ignored', 'unix:///']) { + assert.throws(() => localDockerEndpoint({ DOCKER_HOST }), /native_compose_local_unix_endpoint_required/u) + } + assert.throws(() => localDockerEndpoint({ DOCKER_HOST: 'unix:///run/docker.sock', DOCKER_CONTEXT: 'default' }), /ambiguous/u) + assert.throws(() => localDockerEndpoint({ PATH: '/dev/null', DOCKER_CONTEXT: 'missing' }), /inspection_failed/u) + const vars = { PATH: '/bin', HOME: '/home/test', DOCKER_CONFIG: '/conf', XDG_RUNTIME_DIR: '/run/user/1000' } + assert.deepEqual(commandEnv({ ...vars, LANG: 'fr', DOCKER_HOST: 'tcp://other', DOCKER_CONTEXT: 'other', + DOCKER_DEFAULT_PLATFORM: 'linux/arm64', DEVA_WEB_TOKEN: 'private', COMPOSE_FILE: 'remote.yaml', + COMPOSE_PROJECT_NAME: 'deployed', COMPOSE_ENV_FILES: '.env', GITHUB_TOKEN: 'private', TMPDIR: '/checkout' }), + { ...vars, LANG: 'C', COMPOSE_DISABLE_ENV_FILE: '1' }) + const cwd = process.cwd() + assert.deepEqual(commandEnv({ PATH: 'bin::/usr/bin', HOME: 'home', XDG_RUNTIME_DIR: 'run', DOCKER_CONFIG: 'link/../config' }), + { PATH: `${cwd}/bin:${cwd}:/usr/bin`, HOME: `${cwd}/home`, XDG_RUNTIME_DIR: `${cwd}/run`, DOCKER_CONFIG: `${cwd}/link/../config`, + LANG: 'C', COMPOSE_DISABLE_ENV_FILE: '1' }) +}) + +test('stage exact checked-in bytes and fixture outside checkout/context; replacement cleanup fails closed', (t) => { + const { root, git, put } = repository(t) + put(`${src}/untracked`); put(`${src}/ignored.local`) + const prior = process.env.TMPDIR + process.env.TMPDIR = root + let stage + try { stage = prepareSource(root) } finally { if (prior === undefined) delete process.env.TMPDIR; else process.env.TMPDIR = prior } + const { sha, dir, work, snapshotFile, dispose } = stage + t.after(dispose) + assert.equal(sha, git('rev-parse', 'HEAD')) + assert.equal(path.dirname(dir), path.dirname(root)); assert.equal(fs.statSync(dir).mode & 0o777, 0o700) + for (const file of included) assert.equal(fs.readFileSync(path.join(work, file), 'utf8'), file) + for (const file of [...excluded, '.git', `${src}/ignored.local`, `${src}/untracked`, runner]) { + assert.equal(fs.existsSync(path.join(work, file)), false, file) + } + assert.equal(path.dirname(snapshotFile), dir); assert.notEqual(path.dirname(snapshotFile), work) + assert.equal(fs.statSync(snapshotFile).mode & 0o777, 0o444) + assert.equal(createHash('sha256').update(fs.readFileSync(snapshotFile)).digest('hex'), + '17abef945c4669dcd7d6162cd1dd65084490d4249b1b6c6b9b8bf477ba0879f5') + const moved = `${dir}.moved`, identity = fs.lstatSync(dir) + verifyDir(dir, identity); assert.equal(path.dirname(moved), temp); assert.ok(!fs.existsSync(moved)) + fs.renameSync(dir, moved); fs.mkdirSync(dir, { mode: 0o700 }); const replacement = fs.lstatSync(dir) + try { assert.throws(dispose, /staging_identity_changed/u); assert.ok(fs.existsSync(dir)) } + finally { + verifyDir(dir, replacement); fs.rmdirSync(dir); verifyDir(moved, identity) + assert.ok(!fs.existsSync(dir)); fs.renameSync(moved, dir) + } + dispose(); dispose(); assert.equal(fs.existsSync(dir), false) + git('update-index', '--assume-unchanged', 'Dockerfile'); put('Dockerfile', 'dirty') + assert.throws(() => prepareSource(root), /clean_tracked_checkout_required/u) +}) + +test('missing tracked runner and failed staging leave no extracted project', (t) => { + const untracked = repository(t, false) + untracked.put(runner) + assert.throws(() => prepareSource(untracked.root), /runner_must_be_tracked/u) + const { root } = repository(t) + let stage + const writeFile = t.mock.method(fs, 'writeFileSync', (file) => { + stage = path.dirname(path.dirname(file)) + throw new Error('synthetic write failure with private data') + }) + syncBuiltinESMExports() + try { assert.throws(() => prepareSource(root), { message: 'native_compose_source_preparation_failed' }) } + finally { writeFile.mock.restore(); syncBuiltinESMExports() } + assert.ok(stage); assert.equal(fs.existsSync(stage), false) +}) diff --git a/apps/desktop/test/compose-acceptance-lifecycle.mjs b/apps/desktop/test/compose-acceptance-lifecycle.mjs new file mode 100644 index 00000000..627e8219 --- /dev/null +++ b/apps/desktop/test/compose-acceptance-lifecycle.mjs @@ -0,0 +1,63 @@ +import { request } from 'node:http' + +const need = (condition, reason) => { if (!condition) throw Error(reason) } +const lines = s => s ? s.split('\n') : [] + +// Only inspect and clean this invocation's pre-checked random namespace, never a developer's Compose project. +async function resources(docker, project, cleanup = false) { + need(/^deva-accept-[a-f0-9]{24}$/u.test(project), 'invalid_test_project') + const opt = { cleanup }, tag = `${project}-deva:latest`, volume = `${project}_deva-data`, network = `${project}_default` + const named = async (type, name) => lines(await docker([type, 'ls', '--filter', `name=${name}`, '--format', '{{.Name}}'], opt)).includes(name) + return { tag, volume, network, hasVolume: await named('volume', volume), hasNetwork: await named('network', network), + image: await docker(['image', 'ls', '-q', '--no-trunc', tag], opt), containers: lines(await docker(['container', 'ls', '-aq', '--no-trunc', + '--filter', `label=com.docker.compose.project=${project}`], opt)) } +} +const empty = r => !r.hasVolume && !r.hasNetwork && !r.image && !r.containers.length +export async function checkUnused(docker, project) { need(empty(await resources(docker, project)), 'project_collision') } +export async function teardown(docker, compose, project, work, knownImage) { + const r = await resources(docker, project, true), opt = { cleanup: true } + const labels = async (type, id, field = '.Labels') => JSON.parse(await docker([type, 'inspect', '--format', `{{json ${field}}}`, id], opt)) ?? {} + for (const id of r.containers) { + const l = await labels('container', id, '.Config.Labels') + need(l['com.docker.compose.project'] === project && l['com.docker.compose.service'] === 'deva' && + l['com.docker.compose.project.working_dir'] === work, 'cleanup_owner_unconfirmed') + } + for (const [type, present, name, key] of [['volume', r.hasVolume, r.volume, 'deva-data'], ['network', r.hasNetwork, r.network, 'default']]) { + if (present) { const l = await labels(type, name); need(l['com.docker.compose.project'] === project && l[`com.docker.compose.${type}`] === key, 'cleanup_owner_unconfirmed') } + } + if (r.hasVolume || r.hasNetwork || r.containers.length) await compose(false, ['down', '--volumes', '--timeout', '10'], { ...opt, timeout: 80_000, quiet: true }) + if (r.image) { + const current = await docker(['image', 'inspect', '--format', '{{.Id}}', r.tag], opt) + const l = await labels('image', r.tag, '.Config.Labels') + need(current === r.image && (current === knownImage || (l['com.docker.compose.project'] === project && l['com.docker.compose.service'] === 'deva')), 'cleanup_image_unconfirmed') + await docker(['image', 'rm', r.tag], { ...opt, quiet: true }) // Untag exactly our name; never prune the shared build cache. + } + need(empty(await resources(docker, project, true)), 'cleanup_incomplete') +} + +export async function publishedLogin(origin, token, previous, granted, signal) { + function api(path, expected, { cookie, login } = {}) { + // Direct IPv4 loopback, no redirect or environment proxy. Even the synthetic token stays local. + return new Promise((resolve, reject) => { + const req = request({ hostname: '127.0.0.1', port: new URL(origin).port, path, family: 4, agent: false, + method: login ? 'POST' : 'GET', signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(5000)]) : AbortSignal.timeout(5000), + headers: { ...(cookie && { Cookie: cookie }), ...(login && { Origin: origin, 'Content-Type': 'application/json' }) } }, async res => { + try { + need(res.statusCode === expected, 'published_http_status'); const chunks = []; let size = 0 + for await (const chunk of res) { size += chunk.length; need(size <= 16_384, 'published_response_limit'); chunks.push(chunk) } + resolve({ data: JSON.parse(Buffer.concat(chunks).toString('utf8')), headers: res.headers }) + } catch (error) { res.destroy(); reject(error) } + }) + req.on('error', () => reject(Error('published_http_unavailable'))); req.end(login ? JSON.stringify({ token }) : undefined) + }) + } + need((await api('/healthz', 200)).data.ok === true, 'published_health_failed') + need((await api('/api/sessions', 401, { cookie: previous })).data.error === 'auth', 'old_login_not_rejected') + const { headers, data } = await api('/api/login', 200, { login: true }) + const cookie = headers['set-cookie']?.length === 1 && headers['set-cookie'][0].split(';', 1)[0] + need(data.ok === true && /^deva_web=[A-Za-z0-9_-]{43}$/u.test(cookie ?? '') && cookie !== previous, 'published_login_failed') + const index = (await api('/api/sessions', 200, { cookie })).data + need(index.model === 'deva-compose-fixture' && Array.isArray(index.sessions) && + (granted ? index.projectDocs === true : !Object.hasOwn(index, 'projectDocs')), 'published_grant_disagrees') + return cookie // Only held between recreations; never part of a receipt or a CLI argument. +} diff --git a/apps/desktop/test/compose-acceptance-lifecycle.test.mjs b/apps/desktop/test/compose-acceptance-lifecycle.test.mjs new file mode 100644 index 00000000..f872774d --- /dev/null +++ b/apps/desktop/test/compose-acceptance-lifecycle.test.mjs @@ -0,0 +1,67 @@ +import assert from 'node:assert/strict' +import { randomBytes } from 'node:crypto' +import { once } from 'node:events' +import { createServer } from 'node:http' +import test from 'node:test' +import { checkUnused, publishedLogin, teardown } from './compose-acceptance-lifecycle.mjs' + +const project = `deva-accept-${'2'.repeat(24)}`, work = '/synthetic/work', image = `sha256:${'3'.repeat(64)}` +// Command recorder for the cleanup boundary only. It cannot build, run, or issue an acceptance receipt. +function registry(foreign) { + const container = '4'.repeat(64), volume = `${project}_deva-data`, network = `${project}_default`, tag = `${project}-deva:latest` + let objects = true, tagged = true + const changed = [] + async function docker([type, op, ...args]) { + if (op === 'ls') return ({ container: objects ? container : '', network: objects ? network : '', volume: objects ? volume : '', image: tagged ? image : '' })[type] + if (op === 'inspect') { + if (args.includes('{{.Id}}')) return foreign === 'image' ? `sha256:${'5'.repeat(64)}` : image + return JSON.stringify({ 'com.docker.compose.project': type === foreign ? 'unrelated' : project, 'com.docker.compose.volume': 'deva-data', + 'com.docker.compose.network': 'default', 'com.docker.compose.service': 'deva', 'com.docker.compose.project.working_dir': work }) + } + assert.deepEqual([type, op, ...args], ['image', 'rm', tag]); changed.push(tag); tagged = false; return '' + } + async function compose(granted, args, options) { + assert.ok(!granted && options.cleanup); assert.deepEqual(args, ['down', '--volumes', '--timeout', '10']) + changed.push('test-project-down'); objects = false + } + return { docker, compose, changed, tag } +} + +test('cleanup refuses foreign resources, and only removes the exact checked image tag', async () => { + for (const owner of ['container', 'network', 'volume', 'image', undefined]) { + const r = registry(owner) + await assert.rejects(() => checkUnused(r.docker, project), { message: 'project_collision' }) + await assert.rejects(() => teardown(r.docker, r.compose, 'main', work, image), { message: 'invalid_test_project' }) + if (owner) { + await assert.rejects(() => teardown(r.docker, r.compose, project, work, image), + { message: owner === 'image' ? 'cleanup_image_unconfirmed' : 'cleanup_owner_unconfirmed' }) + assert.deepEqual(r.changed, owner === 'image' ? ['test-project-down'] : []) + } else { + await teardown(r.docker, r.compose, project, work, image); assert.deepEqual(r.changed, ['test-project-down', r.tag]) + await checkUnused(r.docker, project) + } + } +}) + +test('host-side login crosses real loopback HTTP and rejects reuse of the previous cookie', async () => { + const token = randomBytes(32).toString('hex'); let cookie = '', granted = false, origin + const server = createServer(async (req, res) => { + if (req.url === '/healthz') return res.end('{"ok":true}') + if (req.method === 'POST' && req.url === '/api/login') { + let raw = ''; for await (const chunk of req) raw += chunk + if (req.headers.origin !== origin || JSON.parse(raw).token !== token) return res.writeHead(403).end('{}') + cookie = `deva_web=${randomBytes(32).toString('base64url')}` + return res.writeHead(200, { 'Set-Cookie': cookie + '; HttpOnly' }).end('{"ok":true}') + } + if (!cookie || req.headers.cookie !== cookie) return res.writeHead(401).end('{"error":"auth"}') + res.end(JSON.stringify({ model: 'deva-compose-fixture', sessions: [], ...(granted && { projectDocs: true }) })) + }) + await once(server.listen(0, '127.0.0.1'), 'listening'); origin = `http://127.0.0.1:${server.address().port}` + try { + const first = await publishedLogin(origin, token, undefined, false); assert.equal(first, cookie) + await assert.rejects(() => publishedLogin(origin, token, first, true), { message: 'published_http_status' }) + cookie = ''; granted = true + const second = await publishedLogin(origin, token, first, true); assert.notEqual(second, first) + cookie = ''; granted = false; assert.equal(await publishedLogin(origin, token, second, false), cookie) + } finally { const done = once(server, 'close'); server.close(); server.closeAllConnections(); await done } +}) diff --git a/apps/desktop/test/headless-compose-default.test.mjs b/apps/desktop/test/headless-compose-default.test.mjs index e99a68f7..5e177554 100644 --- a/apps/desktop/test/headless-compose-default.test.mjs +++ b/apps/desktop/test/headless-compose-default.test.mjs @@ -1,8 +1,10 @@ import assert from 'node:assert/strict' import { execFileSync } from 'node:child_process' import { randomBytes } from 'node:crypto' +import { readFileSync } from 'node:fs' import test from 'node:test' import { fileURLToPath } from 'node:url' +import { checkSourceCreationControl, sourceCreationControl } from './compose-acceptance-evidence.mjs' // Render only the named manifests without reading a deployment's .env or connecting to an engine. const base = fileURLToPath(new URL('../../../compose.yaml', import.meta.url)) @@ -10,10 +12,10 @@ const overlay = fileURLToPath(new URL('../../../compose.project-docs.yaml', impo const source = '/unused-deva-test/selected.json', digest = 'a'.repeat(64) const env = { PATH: process.env.PATH, DOCKER_HOST: 'unix:///dev/null', COMPOSE_DISABLE_ENV_FILE: '1', DEVA_WEB_TOKEN: randomBytes(32).toString('hex'), DEVA_MODEL: 'fixture', DEVA_MODEL_BASE_URL: 'https://example.invalid/v1' } -function render(files, extra) { +function render(files, extra, input) { return JSON.parse(execFileSync('docker', ['compose', '--env-file', '/dev/null', ...files.flatMap(file => ['-f', file]), '-p', 'deva-default-check', 'config', '--format', 'json'], { - encoding: 'utf8', timeout: 10000, env: { ...env, ...extra }, stdio: ['ignore', 'pipe', 'pipe'] + encoding: 'utf8', input, timeout: 10000, env: { ...env, ...extra }, stdio: ['pipe', 'pipe', 'pipe'] })) } @@ -43,8 +45,12 @@ test('only the explicit overlay passes a digest and one read-only leaf bind', () } const plain = render([base], both), enabled = render(files, both) const service = enabled.services.deva - assert.deepEqual(service.volumes, [...plain.services.deva.volumes, { type: 'bind', source, - target: '/run/deva-project-docs/snapshot.json', read_only: true, bind: { create_host_path: false, propagation: 'rprivate' } }]) + const leaf = { type: 'bind', source, target: '/run/deva-project-docs/snapshot.json', read_only: true } + // Verify the effect of changing the actual declaration, even on a CLI that omits one boolean default. + const control = render([base, '-'], both, sourceCreationControl(readFileSync(overlay, 'utf8'))) + checkSourceCreationControl(enabled, control) + const normalized = service.volumes.map(v => v.type === 'bind' ? { ...v, bind: { create_host_path: false, ...v.bind } } : v) + assert.deepEqual(normalized, [...plain.services.deva.volumes, { ...leaf, bind: { create_host_path: false, propagation: 'rprivate' } }]) assert.deepEqual(service.environment, { ...plain.services.deva.environment, DEVA_PROJECT_DOCS_SHA256: digest }) // The optional grant must not otherwise widen the runtime configuration. assert.deepEqual({ ...service, volumes: plain.services.deva.volumes, environment: plain.services.deva.environment }, plain.services.deva) From fb6c68caa9cbca9e56de31ed37c52a35b11bee72 Mon Sep 17 00:00:00 2001 From: Facetomyself <[GIT_EMAIL]> Date: Fri, 27 Nov 2026 18:39:09 +0800 Subject: [PATCH 3/3] =?UTF-8?q?ci(headless):=20=E5=85=B1=E7=94=A8=E5=8F=AF?= =?UTF-8?q?=E7=8B=AC=E7=AB=8B=E8=BF=90=E8=A1=8C=E7=9A=84=E5=8E=9F=E7=94=9F?= =?UTF-8?q?=E5=AE=B9=E5=99=A8=E9=AA=8C=E6=94=B6=E5=85=A5=E5=8F=A3=20/=20sh?= =?UTF-8?q?are=20one=20native=20Compose=20acceptance=20command?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/ci.yml | 62 ++----- apps/desktop/src/headless/README.md | 19 ++ .../test/native-compose-entry.test.mjs | 29 +++ apps/desktop/test/verify-native-compose.mjs | 172 ++++++++++++++++++ 4 files changed, 235 insertions(+), 47 deletions(-) create mode 100644 apps/desktop/test/native-compose-entry.test.mjs create mode 100644 apps/desktop/test/verify-native-compose.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 69a851f3..5e927bc9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,50 +43,18 @@ jobs: - run: pnpm --filter @deva/desktop build:headless && node --test apps/desktop/test/{headless-chat,project-docs-mount}.test.mjs - - name: Verify native amd64 Compose chat continuity and optional document grant then revocation - timeout-minutes: 12 - env: - DEVA_PORT: '18794' - DEVA_ORIGIN: http://127.0.0.1:18794 - DEVA_MODEL_BASE_URL: http://127.0.0.1:18795/v1 - DEVA_MODEL: deva-compose-fixture - DEVA_MODEL_PROTOCOL: responses - run: | - set -eu - test "$(uname -m)" = x86_64 - node --test apps/desktop/test/headless-compose-default.test.mjs - export COMPOSE_PROJECT_NAME="deva-test-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" - DEVA_WEB_TOKEN=$(openssl rand -hex 32); export DEVA_WEB_TOKEN - # Private synthetic input stays outside the checkout/build context. The digest is fixed separately. - stage=$(mktemp -d "${RUNNER_TEMP:?}/deva-docs-XXXXXXXX") - export DEVA_PROJECT_DOCS_FILE="$stage/reviewed.json" - cleanup() { - docker compose -f compose.yaml down --volumes - test "$(realpath "$stage")" = "$stage" && test "$(dirname "$stage")" = "$RUNNER_TEMP" - if test -f "$stage/reviewed.json"; then test "$(realpath "$stage/reviewed.json")" = "$stage/reviewed.json" && unlink "$stage/reviewed.json"; fi - rmdir "$stage" - } - trap cleanup EXIT - printf '%s\n' '{"version":1,"project":"发布手册","documents":[{"name":"入门.md","text":"首次使用:先阅读版本说明。\n"}]}' > "$DEVA_PROJECT_DOCS_FILE" - chmod 0444 "$DEVA_PROJECT_DOCS_FILE" - export DEVA_PROJECT_DOCS_SHA256=17abef945c4669dcd7d6162cd1dd65084490d4249b1b6c6b9b8bf477ba0879f5 - with_docs() { docker compose -f compose.yaml -f compose.project-docs.yaml "$@"; } - docker compose up --build --wait --wait-timeout 90 - curl -fsS "$DEVA_ORIGIN/healthz" - first=$(docker compose ps -q deva) - sid=$(docker compose exec -T -e DEVA_SMOKE_EXPECT_PROTOCOL=responses deva node --input-type=module < apps/desktop/test/headless-compose-probe.mjs) - export DEVA_MODEL_PROTOCOL=anthropic - with_docs up --no-build --force-recreate --wait --wait-timeout 90 - second=$(with_docs ps -q deva) - test -n "$first" && test -n "$second" && test "$first" != "$second" - test "$(docker inspect -f '{{range .Mounts}}{{if eq .Destination "/run/deva-project-docs/snapshot.json"}}{{.Type}}:{{.RW}}{{end}}{{end}}' "$second")" = bind:false - test "$(with_docs exec -T deva id -u)" = 1000 - doc=$(with_docs exec -T -e DEVA_SMOKE_SESSION="$sid" deva node --input-type=module < apps/desktop/test/headless-compose-docs-probe.mjs) - with_docs exec -T -e DEVA_SMOKE_EXPECT_PROTOCOL=anthropic -e DEVA_SMOKE_SESSION="$sid" deva node --input-type=module < apps/desktop/test/headless-compose-probe.mjs - with_docs stop deva - test "$(docker inspect -f '{{.State.Running}}' "$second")" = false - unset DEVA_PROJECT_DOCS_FILE DEVA_PROJECT_DOCS_SHA256 - docker compose -f compose.yaml up --no-build --force-recreate --wait --wait-timeout 90 - third=$(docker compose ps -q deva) - test -n "$third" && test "$third" != "$second" - docker compose exec -T -e DEVA_SMOKE_SESSION="$sid" -e DEVA_REVOKED_DOC="$doc" deva node --input-type=module < apps/desktop/test/headless-compose-docs-probe.mjs + - name: Check manifest isolation and qualification guards + run: node --test apps/desktop/test/{headless-compose-default,compose-acceptance-host,compose-acceptance-evidence,compose-acceptance-lifecycle,native-compose-entry}.test.mjs + + - name: Qualify the native amd64 Compose image and verify cleanup + timeout-minutes: 20 + shell: bash + run: node apps/desktop/test/verify-native-compose.mjs | tee "$RUNNER_TEMP/deva-native-amd64.json" + + - name: Save the successful native image receipt + uses: actions/upload-artifact@v4 + with: + name: deva-native-amd64-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/deva-native-amd64.json + if-no-files-found: error + retention-days: 14 diff --git a/apps/desktop/src/headless/README.md b/apps/desktop/src/headless/README.md index bd4a45f9..76f786ac 100644 --- a/apps/desktop/src/headless/README.md +++ b/apps/desktop/src/headless/README.md @@ -96,6 +96,25 @@ docker compose -f compose.yaml -f compose.project-docs.yaml stop deva && 换版亦先停旧服务,用新文件、新的已审核摘要重新发布。仅替换或删除宿主原文件不会改变正在运行的快照。重新登录后旧文档 ID 失效,关闭资料时原有聊天仍可续聊。更多授权边界与验收条件见[只读资料设计](./project-docs-design.md)。 +## 原生 amd64 Docker 成品验收 + +这是验收已提交版本的命令,不是日常部署命令。在**原生 x86-64 Linux** 上检出要验证的提交,使用 Node 22 或更新版本、Git、可访问的本地 Docker Engine 和 Compose v2+。无需安装项目依赖、提供模型密钥或复用正在运行的 Deva 实例。 + +```bash +# 只读检查架构、本地引擎和 Compose。成功也不代表容器已经运行。 +node apps/desktop/test/verify-native-compose.mjs --preflight +# 实际构建和启动三次,清理完成后向标准输出写一条 JSON 回执。 +node apps/desktop/test/verify-native-compose.mjs +``` + +[验收程序](../../test/verify-native-compose.mjs)从 Git 提交对象导出构建所需文件,使用一次性项目名、独立数据卷和动态宿主回环端口。它不会使用工作目录的 `.env`、未提交的文件、原有服务令牌或外部模型。首次构建仍需能获取基础镜像与锁定的依赖。不同 Compose 版本会省略不同的布尔默认值;程序在启动前用当前 CLI 对照渲染 `create_host_path` 的两个取值,只有原始的禁止自动创建配置用于实际运行。运行顺序是: + +1. 基础实例用 Responses 协议完成含附件的第一轮;第二轮模型夹具只发一段文字,保持连接。在用户接口确认这段文字后发出 Stop,验证真实上游 TCP 连接在夹具主动结束前断开,并保存部分回复。 +2. 用同一镜像和数据卷重建,改用 Anthropic 协议并授权一份只读快照;旧登录须失效,新登录可打开合成文档。模型实际收到的续聊历史须含原附件和刚刚停止的文字。 +3. 停止已授权实例,撤下挂载,再用基础配置重建。旧文档 ID 返回 `404`;在原会话上用默认的 OpenAI Chat Completions 协议再发一条消息,须收到实际回复。三次启动均须从宿主发布的回环端口验证健康和登录,且容器 ID 各异、镜像 ID 一致、使用原命名卷。 + +**通过标准是退出码为 `0` 且回执为 `kind: deva-native-compose-v1`、`status: passed` 和 `cleanup: verified`。** 回执记录实际检出的 Git 提交、镜像内容 ID、三个容器 ID 与引擎版本,不含令牌、Cookie、文档 ID 或正文。程序只清理本次已核对归属的容器、网络、卷、镜像标签和暂存目录,不清空共享构建缓存。失败会在标准错误报告阶段与原因;预检、ARM64 运行、模拟输入测试、仅解析 Compose 配置都不是成品回执。CI 使用同一命令,只上传成功回执。 + ## 从源码验证 ```bash diff --git a/apps/desktop/test/native-compose-entry.test.mjs b/apps/desktop/test/native-compose-entry.test.mjs new file mode 100644 index 00000000..dfbcdcbd --- /dev/null +++ b/apps/desktop/test/native-compose-entry.test.mjs @@ -0,0 +1,29 @@ +import assert from 'node:assert/strict' +import { spawnSync } from 'node:child_process' +import { machine } from 'node:os' +import test from 'node:test' +import { fileURLToPath } from 'node:url' + +const runner = fileURLToPath(new URL('./verify-native-compose.mjs', import.meta.url)) +// Deliberately unusable CLI path: help, bad arguments, wrong arch and remote endpoints must never reach Docker. +const env = { HOME: '/unused', PATH: '/unused-acceptance-path', DOCKER_HOST: 'ssh://example.invalid', + DEVA_WEB_TOKEN: 'private-test-marker', COMPOSE_PROJECT_NAME: 'unrelated-operator-project' } +const invoke = args => spawnSync(process.execPath, [runner, ...args], { encoding: 'utf8', timeout: 5000, env }) +test('operator help and argument errors cannot produce a successful native receipt', () => { + const help = invoke(['--help']); assert.equal(help.status, 0); assert.equal(help.stderr, '') + assert.match(help.stdout, /^Usage: .*verify-native-compose\.mjs /u); assert.ok(!help.stdout.includes('"status":"passed"')) + for (const args of [['--platform', 'linux/amd64'], ['--preflight', '--skip-engine']]) { + const invalid = invoke(args); assert.equal(invalid.status, 2); assert.equal(invalid.stdout, '') + assert.deepEqual(JSON.parse(invalid.stderr), { status: 'failed', phase: 'arguments', reason: 'invalid_arguments' }) + } +}) + +test('a foreign host or remote context fails before an engine command or receipt', () => { + const native = process.platform === 'linux' && process.arch === 'x64' && machine() === 'x86_64' + const expected = native ? { phase: 'local_engine', reason: 'native_compose_local_unix_endpoint_required' } : + { phase: 'native_host', reason: 'native_linux_amd64_required' } + for (const args of [[], ['--preflight']]) { + const denied = invoke(args); assert.equal(denied.status, 1); assert.equal(denied.stdout, '') + assert.deepEqual(JSON.parse(denied.stderr), { status: 'failed', ...expected }) + } +}) diff --git a/apps/desktop/test/verify-native-compose.mjs b/apps/desktop/test/verify-native-compose.mjs new file mode 100644 index 00000000..445c7eec --- /dev/null +++ b/apps/desktop/test/verify-native-compose.mjs @@ -0,0 +1,172 @@ +// Run from a clean Git checkout. Only a successful real run prints an acceptance receipt on stdout. +import { spawn } from 'node:child_process' +import { randomBytes } from 'node:crypto' +import { readFileSync } from 'node:fs' +import { createServer } from 'node:net' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { commandEnv, localDockerEndpoint, prepareSource, requireNativeHost } from './compose-acceptance-host.mjs' +import { checkUnused, publishedLogin, teardown } from './compose-acceptance-lifecycle.mjs' +import { checkContinuity, checkEngine, checkPlan, checkSourceCreationControl, checkStage, sourceCreationControl } from './compose-acceptance-evidence.mjs' + +const root = fileURLToPath(new URL('../../../', import.meta.url)) +const approved = '17abef945c4669dcd7d6162cd1dd65084490d4249b1b6c6b9b8bf477ba0879f5' +const sidPattern = /^web_[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/u +const chatProbe = 'headless-compose-probe.mjs', docsProbe = 'headless-compose-docs-probe.mjs' +const sequence = [['base', 'responses'], ['granted', 'anthropic'], ['revoked', 'openai']] +const interrupted = new AbortController() +const stop = () => interrupted.abort() +let phase = 'arguments', cleanupProblem, failedProject +const need = (condition, reason) => { if (!condition) throw Error(reason) } +const reason = e => /^[a-z][a-z0-9_.-]{1,70}$/u.test(e?.message ?? '') ? e.message : 'verification_failed' + +// Do not forward command output/errors: even a private Docker config or a failed inspect can include credentials. +function dockerClient(endpoint, baseEnv) { + return (args, { env = {}, cwd, input, quiet = false, cleanup = false, timeout = 30_000 } = {}) => new Promise((resolve, reject) => { + if (!cleanup && interrupted.signal.aborted) return reject(Error('interrupted')) + const child = spawn('docker', ['--host', endpoint, ...args], { cwd, detached: true, + env: { ...baseEnv, DOCKER_HOST: endpoint, ...env }, stdio: ['pipe', quiet ? 'ignore' : 'pipe', 'pipe'] }) + const chunks = []; let size = 0, problem, hint, finished = false + child.stderr.on('data', chunk => { + const message = chunk.toString('utf8') + if (/permission denied while trying to connect|connect: permission denied/iu.test(message)) hint = 'engine_permission_denied' + else if (/cannot connect to the docker daemon|error during connect/iu.test(message)) hint ??= 'engine_connection_failed' + else if (/port is already allocated|address already in use/iu.test(message)) hint ??= 'port_unavailable' + else if (/container .*unhealthy/iu.test(message)) hint ??= 'container_unhealthy' + }) + function cancel(why) { + problem ??= why + if (child.pid && !finished) { try { process.kill(-child.pid, 'SIGKILL') } catch (e) { if (e.code !== 'ESRCH') problem = 'docker_client_stop_failed' } } + } + // Compose/Buildx are child CLI plugins. Stop our entire private client group before cleanup starts. + const abort = () => cancel('interrupted'), timer = setTimeout(() => cancel('docker_command_timeout'), timeout).unref() + if (!cleanup) { interrupted.signal.addEventListener('abort', abort, { once: true }); if (interrupted.signal.aborted) abort() } + child.on('error', error => { problem ??= error.code === 'ENOENT' ? 'docker_cli_missing' : 'docker_command_failed' }) + child.stdin.on('error', () => { if (input) problem ??= 'probe_input_failed' }); child.stdin.end(input) + child.stdout?.on('data', chunk => { + size += chunk.length + if (size <= 4 * 1024 * 1024) chunks.push(chunk) + else cancel('docker_output_limit') + }) + child.once('close', code => { + finished = true; clearTimeout(timer); interrupted.signal.removeEventListener('abort', abort) + if (problem || code !== 0) reject(Object.assign(Error(problem ?? hint ?? 'docker_command_failed'), { dockerExit: code })) + else resolve(Buffer.concat(chunks).toString('utf8').trim()) + }) + }) +} + +async function freePort() { + const socket = createServer() + await new Promise((yes, no) => { socket.once('error', no); socket.listen(0, '127.0.0.1', yes) }) + const { port } = socket.address(); await new Promise((yes, no) => socket.close(e => e ? no(e) : yes())) + return port === 18795 ? freePort() : port // The provider uses this port *inside* the container. +} + +async function acceptance(docker, source, project) { + const port = await freePort(), token = randomBytes(32).toString('hex'), origin = `http://127.0.0.1:${port}` + const env = { DEVA_WEB_TOKEN: token, DEVA_MODEL_API_KEY: '', DEVA_BIND: '127.0.0.1', DEVA_PORT: String(port), DEVA_ORIGIN: origin, + DEVA_MODEL: 'deva-compose-fixture', DEVA_MODEL_BASE_URL: 'http://127.0.0.1:18795/v1', DEVA_MODEL_PROTOCOL: 'responses' } + const compose = (grant, args, opt = {}) => docker(['compose', '--env-file', '/dev/null', '--project-directory', source.work, '-p', project, + '-f', join(source.work, 'compose.yaml'), ...(grant ? ['-f', opt.input ? '-' : join(source.work, 'compose.project-docs.yaml')] : []), ...args], + { ...opt, cwd: source.work, env: { ...env, ...(grant && { DEVA_PROJECT_DOCS_FILE: source.snapshotFile, DEVA_PROJECT_DOCS_SHA256: approved }) } }) + const probe = (file, id, vars) => docker(['exec', '-i', ...Object.entries(vars).flatMap(([k, v]) => ['-e', `${k}=${v}`]), id, + 'node', '--input-type=module'], { input: readFileSync(join(source.work, 'apps/desktop/test', file)), timeout: 45_000 }) + const protocolFor = protocol => { if (protocol === 'openai') delete env.DEVA_MODEL_PROTOCOL; else env.DEVA_MODEL_PROTOCOL = protocol } + const stages = []; let id, sid, oldDoc, cookie, volumeCreated, mutation = false, originalFailure + try { + phase = 'rendered_plan' + for (const [label, protocol] of sequence) { + const grant = label === 'granted'; protocolFor(protocol) + const rendered = JSON.parse(await compose(grant, ['config', '--format', 'json'])) + checkPlan(rendered, { project, port, work: source.work, snapshotFile: source.snapshotFile, granted: grant }) + if (grant) { + const input = sourceCreationControl(readFileSync(join(source.work, 'compose.project-docs.yaml'), 'utf8')) + const control = JSON.parse(await compose(true, ['config', '--format', 'json'], { input })) // Render only; never start this variant. + checkSourceCreationControl(rendered, control) + } + const { DEVA_BIND: _publishOnly, ...settings } = env + const expected = { ...settings, DEVA_HOST: '0.0.0.0', DEVA_MODEL_PROTOCOL: protocol, ...(grant && { DEVA_PROJECT_DOCS_SHA256: approved }) } + const actual = rendered.services.deva.environment + need(Object.keys(actual).length === Object.keys(expected).length && Object.entries(expected).every(([k, v]) => actual[k] === v), 'unexpected_service_environment') + need([`${project}-deva`, `${project}-deva:latest`].includes(await compose(grant, ['config', '--images'])), 'unexpected_image_tag') + } + phase = 'isolation'; await checkUnused(docker, project) + for (const [i, [label, protocol]] of sequence.entries()) { + const grant = label === 'granted'; phase = `${label}_start`; protocolFor(protocol) + console.error(`deva-compose: ${phase}`); mutation = true + await compose(grant, ['up', i ? '--no-build' : '--build', ...(i ? ['--force-recreate'] : []), '-d', '--wait', '--wait-timeout', '100'], + { quiet: true, timeout: i ? 150_000 : 600_000 }) + phase = `${label}_identity` + id = await compose(grant, ['ps', '-q', 'deva']); need(/^[a-f0-9]{12,64}$/u.test(id), 'missing_test_container') + const [container] = JSON.parse(await docker(['container', 'inspect', id])) + need(container?.Config?.Labels?.['com.docker.compose.project'] === project && container.Config.Labels['com.docker.compose.project.working_dir'] === source.work, 'unexpected_container') + const [Os, Architecture, Id] = (await docker(['image', 'inspect', '--format', '{{.Os}} {{.Architecture}} {{.Id}}', container.Image])).split(' ') + const node = JSON.parse(await docker(['exec', id, 'node', '-p', 'JSON.stringify({os:process.platform,arch:process.arch,uid:process.getuid(),version:process.version})'])) + const stage = checkStage({ container, image: { Os, Architecture, Id }, node, project, port, snapshotFile: source.snapshotFile, granted: grant }) + const [vol] = JSON.parse(await docker(['volume', 'inspect', stage.volumeName])) + need(vol.Driver === 'local' && !Object.keys(vol.Options ?? {}).length && vol.Labels?.['com.docker.compose.project'] === project && + vol.Labels?.['com.docker.compose.volume'] === 'deva-data' && !!vol.CreatedAt && (!volumeCreated || vol.CreatedAt === volumeCreated), 'volume_identity_failed') + volumeCreated = vol.CreatedAt; stages.push(stage) + phase = `${label}_published_http`; cookie = await publishedLogin(origin, token, cookie, grant, interrupted.signal) + phase = `${label}_workflow` + if (grant) { + oldDoc = await probe(docsProbe, id, { DEVA_SMOKE_SESSION: sid }) + need(/^[a-f0-9]{32}\/[a-f0-9]{32}$/u.test(oldDoc), 'published_document_probe_failed') + } else if (i === 2) { + need(await probe(docsProbe, id, { DEVA_SMOKE_SESSION: sid, DEVA_REVOKED_DOC: oldDoc }) === '', 'revocation_probe_failed') + } + const result = await probe(chatProbe, id, { DEVA_SMOKE_EXPECT_PROTOCOL: protocol, ...(sid && { DEVA_SMOKE_SESSION: sid }), + ...(i === 2 && { DEVA_SMOKE_AFTER_REVOKE: '1' }) }) + need(sidPattern.test(result) && (!sid || result === sid), 'conversation_probe_failed'); sid = result + if (grant) { + await compose(true, ['stop', '--timeout', '15', 'deva'], { quiet: true }) + need(await docker(['container', 'inspect', '--format', '{{.State.Running}}', id]) === 'false', 'old_reader_still_running') + } + } + checkContinuity(stages) + return { image: stages[0].imageId, node: stages[0].nodeVersion, containers: stages.map(s => s.containerId), + checks: ['published_loopback_health_and_login', 'complete_response', 'stop_closed_provider_socket', 'partial_preserved_across_recreation', + 'anthropic_continuation_with_attachment', 'read_only_snapshot', 'old_login_and_document_revoked', 'default_openai_turn_after_revocation', 'same_named_volume'] } + } catch (error) { originalFailure = error; throw error } finally { + if (mutation) { + try { await teardown(docker, compose, project, source.work, stages[0]?.imageId) } + catch (error) { + cleanupProblem = reason(error); failedProject = project + if (!originalFailure) { phase = 'cleanup'; throw Error('cleanup_unconfirmed') } + } + } + } +} + +async function main(args) { + if (args.length === 1 && ['-h', '--help'].includes(args[0])) { + console.log('Usage: node apps/desktop/test/verify-native-compose.mjs [--preflight]\nRequires native Linux x86-64, Node 22+, Git, Docker Engine and Compose.\n--preflight checks the local environment only. A full run builds, recreates and removes a private synthetic project, printing JSON only after cleanup.'); return + } + need(!args.length || (args.length === 1 && args[0] === '--preflight'), 'invalid_arguments') + phase = 'native_host'; requireNativeHost(); need(Number(process.versions.node.split('.')[0]) >= 22, 'node_22_required') + phase = 'local_engine'; const docker = dockerClient(localDockerEndpoint(), { ...commandEnv(), BUILDX_BUILDER: 'default' }) + const [OSType, Architecture, ServerVersion] = (await docker(['info', '--format', '{{.OSType}} {{.Architecture}} {{.ServerVersion}}'])).split(' ') + const engine = checkEngine({ OSType, Architecture, ServerVersion }), compose = await docker(['compose', 'version', '--short']) + need(/^v?[2-9]\d*\.\d+\.\d+(?:[-+][\w.-]+)?$/u.test(compose), 'invalid_compose_version') + if (args.length) { console.log(JSON.stringify({ kind: 'preflight', platform: 'linux/amd64', engine, compose, containersRun: false })); return } + phase = 'source'; const project = `deva-accept-${randomBytes(12).toString('hex')}`, source = prepareSource(root) + let result, originalFailure + try { result = await acceptance(docker, source, project) } + catch (error) { originalFailure = error; throw error } finally { + try { source.dispose() } catch { + cleanupProblem ??= 'staging_cleanup_failed' + if (!originalFailure) { phase = 'cleanup'; throw Error('cleanup_unconfirmed') } + } + } + phase = 'finished'; need(!interrupted.signal.aborted, 'interrupted') + console.log(JSON.stringify({ kind: 'deva-native-compose-v1', status: 'passed', commit: source.sha, platform: 'linux/amd64', engine, compose, + ...result, cleanup: 'verified', completedAt: new Date().toISOString() })) +} +process.once('SIGINT', stop); process.once('SIGTERM', stop) +try { await main(process.argv.slice(2)) } +catch (error) { + console.error(JSON.stringify({ status: 'failed', phase, reason: reason(error), ...(Number.isInteger(error?.dockerExit) && { dockerExit: error.dockerExit }), + ...(cleanupProblem && { cleanup: cleanupProblem, project: failedProject }) })) + process.exitCode = phase === 'arguments' ? 2 : 1 +} finally { process.off('SIGINT', stop); process.off('SIGTERM', stop) }