From fb8037728feb2a21162ee0f9fe015a33a2de027c Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <176368005+LikC1606@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:47:21 +0800 Subject: [PATCH] Keep generic CLI provider keys out of research sandboxes The non-sealed cli research launch spread the whole host environment into bwrap, so any inherited provider key was readable from the agent's shell and /proc environ. - Add an optional researchProvider binding to cli.json; the host relay keeps the real key and the sandbox gets a disposable capability plus a relay /v1 base. Client paths are forwarded relative to the configured base. - Strip secret-named inherited variables, sealedRole keys and copies of the key; fail closed (math_cli_provider_relay_unsupported) for any other inherited credential that has a value. - Require web cli providers to declare a matching researchProvider. - Bind the Qwen and Aider presets; Aider no longer inherits ANTHROPIC_API_KEY. Gemini fails closed when GEMINI_API_KEY is set. Co-Authored-By: Claude Opus 5.5 --- apps/web/config.ts | 4 +++ apps/web/harness.ts | 3 ++ docs/generic-cli.md | 9 ++++++ resources/cli-harnesses/README.md | 2 +- resources/cli-harnesses/aider/cli.json | 3 +- resources/cli-harnesses/qwen/cli.json | 1 + src/runtime/cliConfiguration.ts | 8 ++++++ src/runtime/cliSession.ts | 9 ++++-- src/runtime/researchCredentialRelay.ts | 40 ++++++++++++++++++++++++++ tests/cliConfiguration.test.ts | 5 ++++ tests/cliSession.test.ts | 29 +++++++++++++++++++ tests/fixtures/cliProtocolPeer.cjs | 14 +++++++++ tests/genericCliSolver.test.ts | 10 +++++-- tests/researchCredentialRelay.test.ts | 33 ++++++++++++++++++++- tests/webHarness.test.ts | 8 ++++-- tests/webServer.test.ts | 3 +- 16 files changed, 170 insertions(+), 11 deletions(-) diff --git a/apps/web/config.ts b/apps/web/config.ts index 2c98ee60..82a7a225 100644 --- a/apps/web/config.ts +++ b/apps/web/config.ts @@ -23,6 +23,10 @@ const providerSchema = z.object({ if (provider.harness === 'cli' ? !provider.execution?.cli : provider.execution?.cli || provider.execution?.files || provider.execution?.apiKeyEnvironment || provider.execution?.baseUrlEnvironment) ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'CLI launch configuration requires a CLI provider.' }); + const research = provider.execution?.cli?.researchProvider; + if (provider.execution?.cli && (research?.apiKeyEnvironment !== (provider.execution.apiKeyEnvironment ?? 'OPENAI_API_KEY') || + research.baseUrlEnvironment !== (provider.execution.baseUrlEnvironment ?? 'OPENAI_BASE_URL'))) + ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'CLI providers must declare researchProvider for their key and base URL variables.' }); for (const name of Object.keys(provider.execution?.files ?? {})) if (path.isAbsolute(name) || name.split(/[\\/]/u).some(part => !part || part === '..' || part === '.') || name === 'cli.json') ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'CLI configuration file paths must be relative ordinary files.' }); for (const name of [provider.execution?.apiKeyEnvironment, provider.execution?.baseUrlEnvironment].filter(Boolean)) diff --git a/apps/web/harness.ts b/apps/web/harness.ts index 21066c60..b0bc4776 100644 --- a/apps/web/harness.ts +++ b/apps/web/harness.ts @@ -68,6 +68,9 @@ export function prepareWebNativeProfile(profile: string, provider: WebWorkerProv if (!actual.inheritEnvironment.includes(key) || !actual.inheritEnvironment.includes(base) || Object.hasOwn(actual.environment, key) || Object.hasOwn(actual.environment, base)) throw new Error('web_cli_provider_environment_unbound'); + // The BYOK key reaches the native client only through the host research relay. + if (actual.researchProvider?.apiKeyEnvironment !== key || actual.researchProvider.baseUrlEnvironment !== base) + throw new Error('web_cli_research_provider_unbound'); if (!actual.efforts.includes(input.effort)) throw new Error('math_cli_effort_unsupported'); return; } diff --git a/docs/generic-cli.md b/docs/generic-cli.md index ed05c64c..2835d22f 100644 --- a/docs/generic-cli.md +++ b/docs/generic-cli.md @@ -81,6 +81,15 @@ Configured terminal failure classes are `authentication`, `context`, `rate-limit `environment` maps explicit native environment values, for example `"HOME": "{profile}/home"`. `inheritEnvironment` lists existing process variables needed by that command, for example an API key or endpoint. CLI-only inherited values are excluded from host Lean environment records. Credentials should enter through `inheritEnvironment`, not literal config or argv values. Non-secret inherited values participate in the launch identity; recognized credential names may rotate. Runtime-owned environment names are reserved. +Research sessions keep native network access, so the provider key never enters the sandbox. Declare the native client's provider variables with `researchProvider`: + +```json +"inheritEnvironment": ["OPENAI_API_KEY", "OPENAI_BASE_URL"], +"researchProvider": { "wireApi": "chat-completions", "apiKeyEnvironment": "OPENAI_API_KEY", "baseUrlEnvironment": "OPENAI_BASE_URL" } +``` + +Both names must be listed in `inheritEnvironment` and absent from `environment`. The host keeps the real key in a loopback relay. Inside the sandbox the key variable holds a disposable capability and the base variable holds the relay's `/v1` endpoint. The relay forwards only the wire API's request paths, relative to the base the client was configured with: `/responses`, `/chat/completions`, or Anthropic `/messages` and `/messages/count_tokens` (with or without a leading `/v1`). An unset base variable uses the provider's public endpoint. The upstream base must be HTTPS, or HTTP to a loopback/private host. Inherited variables whose names look like credentials (`API_KEY`, `TOKEN`, `SECRET`, `PASSWORD`, `CREDENTIAL`, `PRIVATE_KEY`) are always removed. If one of them has a value and is not the declared `researchProvider` key, the session fails with `math_cli_provider_relay_unsupported` instead of projecting it. A `sealedRole` provider key is never passed to research sessions. Declare a credential with an unusual name through `researchProvider`, since name matching cannot recognize it. + `configurationFiles` lists existing relative files under the profile whose bytes must remain frozen, such as native settings. The host pins these files, `cli.json`, executable path/bytes and non-secret inherited environment before dispatch, source freezing and resume. Session/cache files can grow. Put every native settings file that affects execution in this list and disable undesired native project/global discovery in the native configuration. Execution requires Linux bubblewrap. The host root is read-only; the proof worktree and dedicated profile are writable. HOME defaults to the dedicated profile, XDG state stays there, temporary files stay in the worktree, protected roots and host socket directories are masked, and research networking remains available. The host waits for confirmed process shutdown before freezing source. A valid completion file may stop the process early; it is a handoff for independent verification, never proof acceptance. diff --git a/resources/cli-harnesses/README.md b/resources/cli-harnesses/README.md index 0124ab9c..2193b9b1 100644 --- a/resources/cli-harnesses/README.md +++ b/resources/cli-harnesses/README.md @@ -22,7 +22,7 @@ bun bin/math.ts run --harness cli --harness-profile DEDICATED_PROFILE \ --output RESULT_FILE --build-manifest BUILD_MANIFEST ``` -Supply credentials using the names in `inheritEnvironment`. Keep them out of profile files and args. HOME defaults to the dedicated profile. Gemini additionally sets `GEMINI_CLI_HOME` to a private home root; the native CLI appends `.gemini`. Qwen sets `QWEN_HOME` to a private settings/session directory. Explicit system settings paths prevent fallback to host system paths; Gemini may ignore these profile files when its privileged settings ownership checks fail. Do not interpret that as those files taking effect. +Supply credentials using the names in `inheritEnvironment`. Keep them out of profile files and args. Qwen and Aider declare `researchProvider`, so the host relay holds the OpenAI-compatible key and the native process sees only a disposable capability. Aider's profile relays only its OpenAI-compatible provider; it no longer inherits `ANTHROPIC_API_KEY`. Gemini's native API has no host relay yet: a research session with `GEMINI_API_KEY` set fails with `math_cli_provider_relay_unsupported` rather than exposing the key. HOME defaults to the dedicated profile. Gemini additionally sets `GEMINI_CLI_HOME` to a private home root; the native CLI appends `.gemini`. Qwen sets `QWEN_HOME` to a private settings/session directory. Explicit system settings paths prevent fallback to host system paths; Gemini may ignore these profile files when its privileged settings ownership checks fail. Do not interpret that as those files taking effect. Gemini and Qwen retain `usage.completeness: "partial"`: the local probes establish event mapping and continuity, not complete accounting for every provider/tool/background combination. With a finite token budget the host stops subsequent dispatches after an incomplete turn. Cached counters are already part of input totals. Gemini headless resume was measured at 40/5 then 40/5 tokens; Qwen at 40/5 then 80/10. Neither preset claims a latest individual request size. diff --git a/resources/cli-harnesses/aider/cli.json b/resources/cli-harnesses/aider/cli.json index 9c7ea4bd..c5e4cb1e 100644 --- a/resources/cli-harnesses/aider/cli.json +++ b/resources/cli-harnesses/aider/cli.json @@ -7,6 +7,7 @@ "output": {"format": "text"}, "efforts": ["none"], "environment": {"NO_COLOR": "1"}, - "inheritEnvironment": ["OPENAI_API_KEY", "OPENAI_API_BASE", "ANTHROPIC_API_KEY"], + "inheritEnvironment": ["OPENAI_API_KEY", "OPENAI_API_BASE"], + "researchProvider": {"wireApi": "chat-completions", "apiKeyEnvironment": "OPENAI_API_KEY", "baseUrlEnvironment": "OPENAI_API_BASE"}, "configurationFiles": ["aider.conf.yml", "empty.env"] } diff --git a/resources/cli-harnesses/qwen/cli.json b/resources/cli-harnesses/qwen/cli.json index ccbb3f8b..02363c41 100644 --- a/resources/cli-harnesses/qwen/cli.json +++ b/resources/cli-harnesses/qwen/cli.json @@ -37,5 +37,6 @@ "NO_COLOR": "1" }, "inheritEnvironment": ["OPENAI_API_KEY", "OPENAI_BASE_URL"], + "researchProvider": {"wireApi": "chat-completions", "apiKeyEnvironment": "OPENAI_API_KEY", "baseUrlEnvironment": "OPENAI_BASE_URL"}, "configurationFiles": ["qwen-home/settings.json", "system-defaults.json", "system-settings.json"] } diff --git a/src/runtime/cliConfiguration.ts b/src/runtime/cliConfiguration.ts index 22b78ad3..8bca7a60 100644 --- a/src/runtime/cliConfiguration.ts +++ b/src/runtime/cliConfiguration.ts @@ -47,6 +47,9 @@ export const cliConfigurationSchema = z.object({ client: z.object({ baseUrlEnvironment: environmentName, apiKeyEnvironment: environmentName }).strict(), profileFiles: z.record(argument).default({}), runtime: sealedRuntime.optional() }).strict().optional(), + /** Research sessions: the native client's provider variables. The host relay keeps the real key. */ + researchProvider: z.object({ wireApi: sealedRoleProviderSchema.shape.wireApi, + apiKeyEnvironment: environmentName, baseUrlEnvironment: environmentName }).strict().optional(), }).strict(); export type CliConfiguration = z.infer; @@ -94,6 +97,11 @@ export function readCliConfiguration(profile: string): CliConfiguration { throw new Error('math_cli_runtime_environment_reserved'); if (config.inheritEnvironment.some(name => /^(?:HOME|PATH|ELAN_HOME|LAKE_HOME|LEAN_.+)$/u.test(name))) throw new Error('math_cli_runtime_environment_reserved'); + const research = config.researchProvider; + if (research && (research.apiKeyEnvironment === research.baseUrlEnvironment || + [research.apiKeyEnvironment, research.baseUrlEnvironment].some(name => + !config.inheritEnvironment.includes(name) || Object.hasOwn(config.environment, name)))) + throw new Error('math_cli_research_provider_binding_invalid'); for (const name of config.configurationFiles) { const selected = path.resolve(profile, name); if (path.isAbsolute(name) || !isMathPathWithin(profile, selected) || selected === profile || diff --git a/src/runtime/cliSession.ts b/src/runtime/cliSession.ts index 2aa7b4ef..f0bf481b 100644 --- a/src/runtime/cliSession.ts +++ b/src/runtime/cliSession.ts @@ -13,6 +13,7 @@ import { cliFieldMatches, cliFieldValue, expandCliTemplate, readCliConfiguration import type { MathAgentFailureDiagnostic } from './failureDiagnostic'; import { prepareHarnessProcess } from './harnessProcess'; import { planMathAgentSession } from './agentSessionPlan'; +import { prepareCliResearchRelay } from './researchCredentialRelay'; import { prepareSealedHarness, sealedRolePath, sealedRoleText } from './sealedHarness'; type Json = Record; @@ -49,6 +50,9 @@ export async function createCliMathSession(options: MathAgentOptions): Promise [name, expandCliTemplate(value, sealedValues)])) }) : undefined; + // Research keeps native network, so inherited provider keys stay in a host relay. + const research = sealed ? undefined : await prepareCliResearchRelay({ configuration, + environment: options.environment ?? process.env, model: options.model, signal: options.signal }); let resume = configuration.session.mode !== 'fresh' && Boolean(options.threadId), closed = false; let child: ChildProcess | undefined, closing: Promise | undefined; let active: { interrupt: () => void } | undefined; @@ -101,9 +105,10 @@ export async function createCliMathSession(options: MathAgentOptions): Promise expandCliTemplate(argument, values)); const invocation = sealed ? sealed.launch(arguments_) : prepareHarnessProcess({ ...options, environment: { - ...(options.environment ?? process.env), HOME: options.profile, + ...research!.environment, HOME: options.profile, ...Object.fromEntries(Object.entries(configuration.environment).map(([key, value]) => [key, expandCliTemplate(value, values)])), } }, options.executable, arguments_); + research?.relay?.assertNotProjected([...Object.values(invocation.env ?? {}), ...invocation.args]); isolationReceipt = sealed?.receipt ?? ('isolationReceipt' in invocation ? invocation.isolationReceipt as Json : undefined); let owned: ChildProcess; try { owned = child = spawn(invocation.command, invocation.args, { cwd: workspace, env: invocation.env, @@ -245,7 +250,7 @@ export async function createCliMathSession(options: MathAgentOptions): Promise = { + responses: ['/responses'], 'chat-completions': ['/chat/completions'], + 'anthropic-messages': ['/messages', '/messages/count_tokens', '/v1/messages', '/v1/messages/count_tokens'] + .flatMap(route => [route, route + '?beta=true']), +}; +const cliDefaultBase: Record = { responses: 'https://api.openai.com/v1', + 'chat-completions': 'https://api.openai.com/v1', 'anthropic-messages': 'https://api.anthropic.com' }; + +/** Generic CLI research launch. Inherited credentials never enter the sandbox: the declared + * `researchProvider` key is held by a host relay and the client base points at that relay, which + * forwards the client's base-relative path unchanged. Any other inherited credential, or one without + * a declared wire API, fails closed instead of being projected. */ +export async function prepareCliResearchRelay(input: { configuration: Pick; environment: NodeJS.ProcessEnv; model: string; + signal?: AbortSignal }): Promise<{ environment: NodeJS.ProcessEnv; relay?: ResearchCredentialRelay }> { + const { configuration } = input, env = input.environment, binding = configuration.researchProvider; + const inherited = configuration.inheritEnvironment.filter(name => secretName.test(name)); + const credentialNames = new Set([...inherited, ...(binding ? [binding.apiKeyEnvironment] : []), + // The sealed-role host key is loaded for formalization only; research never receives it. + ...(configuration.sealedRole ? [configuration.sealedRole.provider.apiKeyEnvironment] : [])]); + const sandbox: NodeJS.ProcessEnv = { ...env }; + for (const name of credentialNames) delete sandbox[name]; + if ([...credentialNames].some(name => env[name] && name !== binding?.apiKeyEnvironment && + configuration.inheritEnvironment.includes(name))) throw new Error('math_cli_provider_relay_unsupported'); + const credential = binding && env[binding.apiKeyEnvironment]; + if (!binding || !credential) return { environment: sandbox }; + for (const [name, value] of Object.entries(sandbox)) if (value?.includes(credential)) delete sandbox[name]; + const base = researchUpstreamBase(env[binding.baseUrlEnvironment] || cliDefaultBase[binding.wireApi]); + const routes = Object.fromEntries(cliRelativeRoutes[binding.wireApi].map(route => ['/v1' + route, base + route.replace(/\?.*$/u, '')])); + const relay = await startRelay(researchRelayProtocol({ wireApi: binding.wireApi, routes, + upstreamAuthHeader: binding.wireApi === 'anthropic-messages' ? 'x-api-key' : 'authorization' }), credential, input.model, input.signal); + sandbox[binding.apiKeyEnvironment] = relay.apiKey; sandbox[binding.baseUrlEnvironment] = 'http://' + relay.httpHost + '/v1'; + const selected = custody(relay, credential, sandbox); + try { selected.assertNotProjected(Object.values(sandbox)); } catch (error) { await relay.close(); throw error; } + return { environment: sandbox, relay: selected }; +} diff --git a/tests/cliConfiguration.test.ts b/tests/cliConfiguration.test.ts index 461c3f39..74116b42 100644 --- a/tests/cliConfiguration.test.ts +++ b/tests/cliConfiguration.test.ts @@ -40,6 +40,11 @@ describe('declarative headless CLI configuration', () => { [{ inheritEnvironment: ['PATH'] }, 'math_cli_runtime_environment_reserved'], [{ environment: { THEOREMOS_PRIVATE: 'override' } }, 'math_cli_runtime_environment_reserved'], [{ configurationFiles: ['../outside.json'] }, 'math_cli_configuration_path_invalid'], + [{ researchProvider: { wireApi: 'responses', apiKeyEnvironment: 'KEY', baseUrlEnvironment: 'BASE' } }, 'math_cli_research_provider_binding_invalid'], + [{ inheritEnvironment: ['KEY'], environment: { BASE: 'x' }, researchProvider: { wireApi: 'responses', apiKeyEnvironment: 'KEY', + baseUrlEnvironment: 'BASE' } }, 'math_cli_research_provider_binding_invalid'], + [{ inheritEnvironment: ['KEY'], researchProvider: { wireApi: 'responses', apiKeyEnvironment: 'KEY', baseUrlEnvironment: 'KEY' } }, + 'math_cli_research_provider_binding_invalid'], ])('rejects an unusable launch contract %j', (overrides, reason) => { const f = fixture(overrides); expect(() => readCliConfiguration(f.profile)).toThrow(reason); }); diff --git a/tests/cliSession.test.ts b/tests/cliSession.test.ts index 54cdd3b0..41e58767 100644 --- a/tests/cliSession.test.ts +++ b/tests/cliSession.test.ts @@ -1,4 +1,6 @@ import fs from 'node:fs'; +import http from 'node:http'; +import { once } from 'node:events'; import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { createCliMathSession } from '../src/runtime/cliSession'; @@ -87,6 +89,33 @@ describe('configured headless CLI sessions with isolated local children', () => } }); + it('keeps inherited provider keys in a host relay and fails closed for credentials it cannot relay', async () => { + const marker = 'sk-cli-host-marker-7731', seen: { url?: string; authorization?: string }[] = []; + const upstream = http.createServer((request, response) => { + seen.push({ url: request.url, authorization: request.headers.authorization }); request.resume(); + request.on('end', () => { response.setHeader('content-type', 'application/json'); response.end('{"id":"chat_fixture"}'); }); + }); + upstream.listen(0, '127.0.0.1'); await once(upstream, 'listening'); + try { + const base = `http://127.0.0.1:${(upstream.address() as { port: number }).port}/v1`; + configuration.inheritEnvironment = ['OPENAI_API_KEY', 'OPENAI_BASE_URL', 'OTHER_TOKEN']; + configuration.researchProvider = { wireApi: 'chat-completions', apiKeyEnvironment: 'OPENAI_API_KEY', baseUrlEnvironment: 'OPENAI_BASE_URL' }; + scenario('provider-relay'); + const environment = { ...options.environment, OPENAI_API_KEY: marker, OPENAI_BASE_URL: base, COPIED_KEY: 'copy-' + marker }; + const session = await open({ ...options, environment }); + expect(await session.run('Check provider custody.', 'relay-turn', workspace, vi.fn())).toBe('completed'); + const peer = JSON.parse(fs.readFileSync(path.join(profile, 'cli-peer-provider.json'), 'utf8')); + expect(peer.environ).not.toContain(marker); expect(peer.alias).toBeUndefined(); + expect(peer.key).toMatch(/^[0-9a-f]{64}$/u); expect(peer.base).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/v1$/u); + expect(peer.result).toEqual({ status: 200, body: '{"id":"chat_fixture"}' }); + expect(seen).toEqual([{ url: '/v1/chat/completions', authorization: 'Bearer ' + marker }]); + await expect(open({ ...options, environment: { ...environment, OTHER_TOKEN: 'other-secret' } })) + .rejects.toThrow('math_cli_provider_relay_unsupported'); + delete configuration.researchProvider; + await expect(open({ ...options, environment })).rejects.toThrow('math_cli_provider_relay_unsupported'); + } finally { await new Promise(resolve => upstream.close(() => resolve())); } + }); + it('reads a configured JSON document after natural exit', async () => { configuration.output = structured('json'); configuration.args = (configuration.args as string[]).map(value => value === 'jsonl' ? 'json' : value); diff --git a/tests/fixtures/cliProtocolPeer.cjs b/tests/fixtures/cliProtocolPeer.cjs index db53bfce..6d2f8d55 100644 --- a/tests/fixtures/cliProtocolPeer.cjs +++ b/tests/fixtures/cliProtocolPeer.cjs @@ -39,6 +39,20 @@ process.stdin.on('end', () => { fs.writeFileSync(path.join(process.cwd(), 'owned.txt'), 'owned'); fs.writeFileSync(path.join(profile, 'cli-peer-isolation.json'), JSON.stringify(result)); } + if (scenario === 'provider-relay') { + // Records what a sandboxed command can see, then calls its configured provider like a native client. + const seen = { key: process.env.OPENAI_API_KEY, base: process.env.OPENAI_BASE_URL, alias: process.env.COPIED_KEY, + other: process.env.OTHER_TOKEN, environ: fs.readFileSync('/proc/self/environ', 'utf8') }; + fetch(seen.base + '/chat/completions', { method: 'POST', headers: { authorization: 'Bearer ' + seen.key, + 'content-type': 'application/json' }, body: JSON.stringify({ model: 'fixture/model', messages: [] }) }) + .then(async response => ({ status: response.status, body: await response.text() }), error => ({ error: String(error) })) + .then(result => { + fs.writeFileSync(path.join(profile, 'cli-peer-provider.json'), JSON.stringify({ ...seen, result })); + send({ kind: 'final', session: { id: returnedId }, result: { text: 'relay checked' }, + stats: { input: 11, output: 5, cached: 2, reasoning: 1, context: 9 } }); + }); + return; + } if (scenario.startsWith('failure-')) { send({ kind: 'failure', reason: scenario.slice('failure-'.length), message: 'private provider secret' }); process.exitCode = Number(argument('--failure-exit-code') || '0'); diff --git a/tests/genericCliSolver.test.ts b/tests/genericCliSolver.test.ts index 57d2fe5c..45fac283 100644 --- a/tests/genericCliSolver.test.ts +++ b/tests/genericCliSolver.test.ts @@ -129,11 +129,15 @@ describe('generic CLI through the shared Skill solver', () => { expect(state().tokenBudget!.usageComplete).toBe(false); expect(state().check?.passed).not.toBe(true); }, 60_000); - it('passes explicit CLI credentials only to the native process and never saves them in host environments', async () => { + it('relays explicit CLI credentials for the native process and never saves them in host environments', async () => { vi.stubEnv('RESEARCH_CREDENTIAL', 'fixture-private-value'); vi.stubEnv('RESEARCH_ENDPOINT', 'http://127.0.0.1:1'); - config.inheritEnvironment = ['RESEARCH_CREDENTIAL', 'RESEARCH_ENDPOINT']; write(); + config.inheritEnvironment = ['RESEARCH_CREDENTIAL', 'RESEARCH_ENDPOINT']; + config.researchProvider = { wireApi: 'chat-completions', apiKeyEnvironment: 'RESEARCH_CREDENTIAL', baseUrlEnvironment: 'RESEARCH_ENDPOINT' }; + write(); expect(await runSolver([...args, '--max-turns', '1'], root)).toBe(4); - expect(invocations()[0]).toMatchObject({ credential: 'fixture-private-value', endpoint: 'http://127.0.0.1:1' }); + // The native process holds only the relay capability and endpoint; the host keeps the real value. + expect(invocations()[0].credential).toMatch(/^[0-9a-f]{64}$/u); + expect(invocations()[0].endpoint).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/v1$/u); const saved = fs.readFileSync(output + '.runtime/environment-solver.json', 'utf8'); expect(saved).not.toContain('RESEARCH_CREDENTIAL'); expect(saved).not.toContain('fixture-private-value'); expect(saved).not.toContain('RESEARCH_ENDPOINT'); diff --git a/tests/researchCredentialRelay.test.ts b/tests/researchCredentialRelay.test.ts index 4aad78ca..eebc7cb8 100644 --- a/tests/researchCredentialRelay.test.ts +++ b/tests/researchCredentialRelay.test.ts @@ -1,7 +1,7 @@ import http from 'node:http'; import { once } from 'node:events'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { prepareClaudeResearchRelay, prepareOpenCodeResearchRelay, researchUpstreamBase, +import { prepareClaudeResearchRelay, prepareCliResearchRelay, prepareOpenCodeResearchRelay, researchUpstreamBase, type ResearchCredentialRelay } from '../src/runtime/researchCredentialRelay'; const MARKER = 'sk-host-research-marker-5521'; @@ -143,4 +143,35 @@ describe('research credential relay', () => { options: { apiKey: '{env:COMPAT_KEY}' } }, model: 'compat/m', environment: { COMPAT_KEY: MARKER } })) .rejects.toThrow('math_opencode_provider_endpoint_unavailable'); }); + + it('relays a declared CLI provider and forwards the client path relative to its base', async () => { + const configuration = { inheritEnvironment: ['FIXTURE_KEY', 'FIXTURE_BASE'], sealedRole: { provider: { wireApi: 'responses' as const, + baseUrl: 'https://sealed.example.test/v1', apiKeyEnvironment: 'SEALED_HOST_KEY' }, client: { baseUrlEnvironment: 'A', apiKeyEnvironment: 'B' }, + profileFiles: {} }, researchProvider: { wireApi: 'anthropic-messages' as const, apiKeyEnvironment: 'FIXTURE_KEY', baseUrlEnvironment: 'FIXTURE_BASE' } }; + const prepared = await prepareCliResearchRelay({ configuration, model: 'm', environment: { PATH: '/bin', FIXTURE_KEY: MARKER, + FIXTURE_BASE: upstream, SEALED_HOST_KEY: 'sealed-only', ALIAS: MARKER } }); + const relay = keep(prepared.relay)!, env = prepared.environment; + expect(env).toEqual({ PATH: '/bin', FIXTURE_KEY: relay.relay.apiKey, FIXTURE_BASE: 'http://' + relay.relay.httpHost + '/v1' }); + const headers = { 'x-api-key': env.FIXTURE_KEY!, 'anthropic-version': '2023-06-01' }; + // A root-style Anthropic base appends /v1/messages; a /v1-style base appends /messages. + expect((await post(env.FIXTURE_BASE + '/v1/messages?beta=true', headers)).status).toBe(200); + expect((await post(env.FIXTURE_BASE + '/messages/count_tokens', headers)).status).toBe(200); + expect((await post(env.FIXTURE_BASE + '/chat/completions', headers)).status).toBe(404); + expect(seen.map(request => [request.url, request.headers['x-api-key']])).toEqual([['/v1/messages', MARKER], ['/messages/count_tokens', MARKER]]); + }); + + it('strips CLI credentials it does not relay and refuses inherited ones', async () => { + const binding = { wireApi: 'chat-completions' as const, apiKeyEnvironment: 'OPENAI_API_KEY', baseUrlEnvironment: 'OPENAI_BASE_URL' }; + expect(await prepareCliResearchRelay({ configuration: { inheritEnvironment: ['OPENAI_API_KEY', 'OPENAI_BASE_URL'], researchProvider: binding }, + model: 'm', environment: { PATH: '/bin', OPENAI_BASE_URL: upstream } })).toEqual({ environment: { PATH: '/bin', OPENAI_BASE_URL: upstream } }); + expect(await prepareCliResearchRelay({ configuration: { inheritEnvironment: ['RESEARCH_ENDPOINT'] }, model: 'm', + environment: { RESEARCH_ENDPOINT: upstream } })).toEqual({ environment: { RESEARCH_ENDPOINT: upstream } }); + for (const configuration of [{ inheritEnvironment: ['GEMINI_API_KEY'] }, + { inheritEnvironment: ['OPENAI_API_KEY', 'OPENAI_BASE_URL', 'HF_TOKEN'], researchProvider: binding }]) + await expect(prepareCliResearchRelay({ configuration, model: 'm', environment: { GEMINI_API_KEY: MARKER, OPENAI_API_KEY: MARKER, + HF_TOKEN: 'hf' } })).rejects.toThrow('math_cli_provider_relay_unsupported'); + await expect(prepareCliResearchRelay({ configuration: { inheritEnvironment: ['OPENAI_API_KEY', 'OPENAI_BASE_URL'], researchProvider: binding }, + model: 'm', environment: { OPENAI_API_KEY: MARKER, OPENAI_BASE_URL: 'http://example.com/v1' } })) + .rejects.toThrow('math_research_provider_endpoint_invalid'); + }); }); diff --git a/tests/webHarness.test.ts b/tests/webHarness.test.ts index bd926e24..93df8dd5 100644 --- a/tests/webHarness.test.ts +++ b/tests/webHarness.test.ts @@ -38,7 +38,8 @@ function fixture(harness: 'claude-code' | 'opencode' | 'cli') { harness, execution: { executable, ...(harness === 'cli' ? { cli: cliConfigurationSchema.parse({ schema: 'theorem-os.cli-harness.v1', executable, args: ['--model', '{model}', '--effort', '{effort}', '--profile', '{profile}', '--format', 'jsonl'], - inheritEnvironment: ['OPENAI_API_KEY', 'OPENAI_BASE_URL'], efforts: ['high'], output: { format: 'jsonl', + inheritEnvironment: ['OPENAI_API_KEY', 'OPENAI_BASE_URL'], researchProvider: { wireApi: 'responses', + apiKeyEnvironment: 'OPENAI_API_KEY', baseUrlEnvironment: 'OPENAI_BASE_URL' }, efforts: ['high'], output: { format: 'jsonl', text: { field: '/result/text', when: { field: '/kind', value: 'final' } }, usage: { when: { field: '/kind', value: 'final' }, inputTokens: '/stats/input', outputTokens: '/stats/output', cachedInputTokens: '/stats/cached', reasoningOutputTokens: '/stats/reasoning', completeness: 'complete' }, @@ -165,7 +166,10 @@ describe('Web server-selected harnesses', () => { for (const execution of [{ ...f.provider.execution, files: { '../outside': 'forbidden' } }, { ...f.provider.execution, apiKeyEnvironment: 'HOME' }, { ...f.provider.execution, cli: undefined }]) expect(() => configure({ ...f.provider, execution })).toThrow(); - const bad = { ...f.provider, execution: { ...f.provider.execution, cli: { ...f.provider.execution!.cli!, inheritEnvironment: [] } } }; + const bad = { ...f.provider, execution: { ...f.provider.execution, cli: { ...f.provider.execution!.cli!, inheritEnvironment: [], researchProvider: undefined } } }; expect(() => prepareWebNativeProfile(path.join(f.root, 'bad-profile'), bad, input())).toThrow('web_cli_provider_environment_unbound'); + const unrelayed = { ...f.provider, execution: { ...f.provider.execution, cli: { ...f.provider.execution!.cli!, researchProvider: undefined } } }; + expect(() => configure(unrelayed)).toThrow(); + expect(() => prepareWebNativeProfile(path.join(f.root, 'unrelayed-profile'), unrelayed, input())).toThrow('web_cli_research_provider_unbound'); }); }); diff --git a/tests/webServer.test.ts b/tests/webServer.test.ts index 7ace7d04..1e4538d0 100644 --- a/tests/webServer.test.ts +++ b/tests/webServer.test.ts @@ -228,7 +228,8 @@ describe('web HTTP boundary with disposable local servers and no model calls', ( it('accepts no-effort execution only for an operator CLI that declares it', async () => { config.providers.push({ id: 'generic-cli', name: 'Generic CLI', baseUrl: 'https://models.example.test/v1', harness: 'cli', execution: { cli: { schema: 'theorem-os.cli-harness.v1', executable: '/opt/operator-cli', args: ['--model', '{model}'], - inheritEnvironment: ['OPENAI_API_KEY', 'OPENAI_BASE_URL'], efforts: ['none'], output: { format: 'text' } } } }); + inheritEnvironment: ['OPENAI_API_KEY', 'OPENAI_BASE_URL'], researchProvider: { wireApi: 'chat-completions', + apiKeyEnvironment: 'OPENAI_API_KEY', baseUrlEnvironment: 'OPENAI_BASE_URL' }, efforts: ['none'], output: { format: 'text' } } } }); const client = await session(); expect(client.session.providers.find(item => item.id === 'generic-cli')?.efforts).toEqual(['none']); const submitted = { ...input(), providerId: 'generic-cli', effort: 'none', requestId: 'generic-no-effort' };