Skip to content
Closed
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
8e8721e
fix(core): scrub secrets from shell-subprocess env, share scrub primi…
jadelike-wine Jul 9, 2026
2dc63e2
fix(core,desktop): narrow child-env scrub to daemon-only keys, share …
jadelike-wine Jul 9, 2026
3e9b546
fix(core): normalize Windows PATH before spawning tool subprocesses
jadelike-wine Jul 11, 2026
1530d8b
fix(desktop): strip cloud/provider credentials from untrusted sandbox…
jadelike-wine Jul 11, 2026
85ab7f9
Revert "fix(desktop): strip cloud/provider credentials from untrusted…
jadelike-wine Jul 11, 2026
283e492
Merge branch 'main' into main
wenshao Jul 12, 2026
1e0cd6f
fix(core): harden child env secret scrubbing
jadelike-wine Jul 13, 2026
23bca8e
fix(serve): preserve custom provider credentials
jadelike-wine Jul 13, 2026
65448c5
test(core): cover subprocess environment scrubbing
jadelike-wine Jul 13, 2026
bf75f7c
Merge branch 'main' into main
jadelike-wine Jul 14, 2026
0c4f816
merge(main): resolve conflicts for daemon credential sanitization (PR…
qwen-code-dev-bot Jul 14, 2026
c2b07f0
fix(serve): preserve daemon credential store
jadelike-wine Jul 14, 2026
7977941
merge(main): resolve conflicts for daemon credential sanitization (PR…
wenshao Jul 15, 2026
5212071
Merge branch 'main' into main
wenshao Jul 15, 2026
032050e
fix(serve): address wenshao review findings on credential store and t…
jadelike-wine Jul 18, 2026
961c3ed
merge: resolve conflicts between credential store and skill install e…
qwen-code-dev-bot Jul 18, 2026
0077f9d
merge: resolve conflicts between daemon secret sanitization and test …
qwen-code-dev-bot Jul 18, 2026
64a40cb
fix(serve): address credential scrub review findings
jadelike-wine Jul 19, 2026
2de8c5d
Merge remote-tracking branch 'origin/main'
jadelike-wine Jul 19, 2026
e0293d2
feat(cli,core): thread credentialStore through workspace MCP settings
jadelike-wine Jul 21, 2026
f041bb5
merge: resolve conflicts between daemon secret sanitization and works…
qwen-code-dev-bot Jul 25, 2026
7e2c89a
merge: resolve conflicts between daemon secret sanitization and proce…
qwen-code-dev-bot Jul 30, 2026
467b43e
chore(cli): merge main into daemon secret sanitization PR
qwen-code-dev-bot Aug 1, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions packages/acp-bridge/src/spawnChannel.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,18 +69,21 @@ describe('createSpawnChannelFactory env policy', () => {
const originalArgv1 = process.argv[1];
let originalSimple: string | undefined;
let originalServerToken: string | undefined;
let originalDaemonToken: string | undefined;
let originalCliEntry: string | undefined;
let originalRuntimeOnlyForTest: string | undefined;

beforeEach(() => {
mockSpawn.mockReset();
originalSimple = process.env['QWEN_CODE_SIMPLE'];
originalServerToken = process.env['QWEN_SERVER_TOKEN'];
originalDaemonToken = process.env['QWEN_DAEMON_TOKEN'];
originalCliEntry = process.env['QWEN_CLI_ENTRY'];
originalRuntimeOnlyForTest = process.env['RUNTIME_ONLY_FOR_TEST'];
process.argv[1] = '/tmp/qwen.js';
process.env['QWEN_CODE_SIMPLE'] = '1';
process.env['QWEN_SERVER_TOKEN'] = 'secret';
process.env['QWEN_DAEMON_TOKEN'] = 'daemon-secret';
});

afterEach(() => {
Expand All @@ -95,6 +98,11 @@ describe('createSpawnChannelFactory env policy', () => {
} else {
process.env['QWEN_SERVER_TOKEN'] = originalServerToken;
}
if (originalDaemonToken === undefined) {
delete process.env['QWEN_DAEMON_TOKEN'];
} else {
process.env['QWEN_DAEMON_TOKEN'] = originalDaemonToken;
}
if (originalCliEntry === undefined) {
delete process.env['QWEN_CLI_ENTRY'];
} else {
Expand All @@ -114,16 +122,38 @@ describe('createSpawnChannelFactory env policy', () => {
await factory('/tmp/project', {
QWEN_CODE_SIMPLE: '1',
QWEN_SERVER_TOKEN: 'override-secret',
QWEN_DAEMON_TOKEN: 'override-daemon-secret',
});

const spawnOptions = mockSpawn.mock.calls[0]?.[2] as
| { env?: NodeJS.ProcessEnv }
| undefined;
expect(spawnOptions?.env).not.toHaveProperty('QWEN_CODE_SIMPLE');
expect(spawnOptions?.env).not.toHaveProperty('QWEN_SERVER_TOKEN');
expect(spawnOptions?.env).not.toHaveProperty('QWEN_DAEMON_TOKEN');
expect(spawnOptions?.env?.['QWEN_CODE_NO_RELAUNCH']).toBe('true');
});

it('scrubs mixed-case daemon tokens on Windows', async () => {
const platformSpy = vi
.spyOn(process, 'platform', 'get')
.mockReturnValue('win32');
mockSpawn.mockReturnValue(createFakeChildProcess());
try {
const factory = createSpawnChannelFactory({
sourceEnv: { qwen_daemon_token: 'secret' },
});
await factory('/tmp/project', { Qwen_Daemon_Token: 'override-secret' });
const spawnOptions = mockSpawn.mock.calls[0]?.[2] as
| { env?: NodeJS.ProcessEnv }
| undefined;
expect(spawnOptions?.env).not.toHaveProperty('qwen_daemon_token');
expect(spawnOptions?.env).not.toHaveProperty('Qwen_Daemon_Token');
} finally {
platformSpy.mockRestore();
}
});

it('passes optional child args after --acp', async () => {
mockSpawn.mockReturnValue(createFakeChildProcess());

Expand Down
62 changes: 19 additions & 43 deletions packages/acp-bridge/src/spawnChannel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ import type { AcpChannelExitInfo, ChannelFactory } from './channel.js';
import { redactLogCredentials } from './logRedaction.js';
import { ndJsonStream, type NdJsonStreamHooks } from './ndJsonStream.js';
import { MissingCliEntryError } from './status.js';
import { scrubChildEnv } from '@qwen-code/qwen-code-core';

// Re-export so the public `@qwen-code/acp-bridge` surface (and the
// `spawnChannel.test.ts` canary) keep resolving now that the implementation
// lives in core and is shared with the shell-tool subprocess path.
export { scrubChildEnv };

let cachedMemoryArgs: string[] | undefined;
export function getAcpMemoryArgs(): string[] {
Expand Down Expand Up @@ -250,6 +256,8 @@ const KILL_HARD_DEADLINE_MS = 10_000;
* an authenticated client of its own daemon — an escalation the agent
* doesn't otherwise have.
*
* `QWEN_DAEMON_TOKEN`: the channel worker's bearer token for its daemon.
*
* `QWEN_CODE_SIMPLE`: an invocation-level bare-mode override. Letting a
* daemon or IDE environment leak it into per-session `qwen --acp`
* children silently disables skills in those children.
Expand All @@ -264,56 +272,24 @@ const KILL_HARD_DEADLINE_MS = 10_000;
* `AWS_*`, `GITHUB_TOKEN`, `CI_*`, `*_API_KEY`, `*_SECRET`, …).
* See the remote-sandbox plan for Stage 4+.
*
* Two-context note: this NARROW set is intentionally NOT the same as the
* shell-tool subprocess scrub. The ACP child is itself a `qwen` agent and
* MUST inherit provider API keys (`OPENAI_API_KEY`, etc.) to call models,
* so only daemon-internal secrets are stripped here. The shell-tool path
* (`shellExecutionService.ts`) passes the BROAD set from
Comment thread
jadelike-wine marked this conversation as resolved.
Resolved
* `collectSensitiveShellEnvKeys` because that subprocess is where the
* model's own commands run (incl. auto-allowed `printenv`/`env`) and must
* never inherit the daemon's secrets. Both share the same `scrubChildEnv`
* primitive from `@qwen-code/qwen-code-core` — do NOT unify the sets.
*
* Defined at module scope so the Set is allocated once at load.
*/
const SCRUBBED_CHILD_ENV_KEYS: ReadonlySet<string> = new Set([
'QWEN_SERVER_TOKEN',
'QWEN_DAEMON_TOKEN',
'QWEN_CODE_SIMPLE',
]);

/**
* Build the env passed to the `qwen --acp` child. Pure function, exported
* for unit-test access (the surrounding `defaultSpawnChannelFactory` is
* unit-test-hostile because it actually spawns Node). Behavior:
*
* 1. Start from a shallow clone of `source` (no aliasing into the
* daemon's `process.env`).
* 2. Delete every key listed in `scrubbed` (the daemon-internal
* child-env denylist; see the rationale on the constant).
* 3. Apply `overrides` per-handle. `undefined` value deletes the key
* (lets an embedded caller scrub a stale inherited var without
* mutating the daemon's global `process.env`). Anything else
* assigns. **`overrides` CANNOT re-introduce a scrubbed key** —
* defense-in-depth so an operator passing
* `{ QWEN_SERVER_TOKEN: 'x' }` in overrides can't smuggle the
* daemon's bearer token back into the child.
*
* Used by `defaultSpawnChannelFactory` above. The split mirrors the
* "scrub" comment block's structure 1:1; behavior is byte-identical to
* the pre-extraction inline implementation.
*/
export function scrubChildEnv(
source: NodeJS.ProcessEnv,
scrubbed: ReadonlySet<string>,
overrides?: Readonly<Record<string, string | undefined>>,
): NodeJS.ProcessEnv {
const childEnv: NodeJS.ProcessEnv = { ...source };
for (const key of scrubbed) {
delete childEnv[key];
}
if (overrides) {
for (const [key, value] of Object.entries(overrides)) {
if (scrubbed.has(key)) continue;
if (value === undefined) {
delete childEnv[key];
} else {
childEnv[key] = value;
}
}
}
return childEnv;
}

function killChild(child: ChildProcess): Promise<void> {
return new Promise<void>((resolve) => {
if (child.exitCode !== null || child.signalCode !== null) {
Expand Down
62 changes: 61 additions & 1 deletion packages/cli/src/serve/run-qwen-serve.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import * as fs from 'node:fs';
import { createServer } from 'node:http';
import * as https from 'node:https';
import type { AddressInfo } from 'node:net';
import { describe, it, expect, vi, afterEach } from 'vitest';
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';
import express from 'express';
import {
createLazyBridgeProxy,
Expand All @@ -20,6 +20,7 @@ import {
createDisabledChannelWorkerSupervisor,
resolveRuntimeStartupTimeoutMs,
runQwenServe,
scrubDaemonProcessEnv,
type RunHandle,
validatePolicyConfig,
waitForRuntimeStartingForShutdown,
Expand Down Expand Up @@ -6326,3 +6327,62 @@ describe('runQwenServe startup observability', () => {
}
});
});

describe('scrubDaemonProcessEnv', () => {
const SCRUB_KEYS = [
'QWEN_SERVER_TOKEN',
'QWEN_DAEMON_TOKEN',
'QWEN_CODE_SIMPLE',
'QWEN_CUSTOM_API_KEY_FOO',
'QWEN_CUSTOM_API_KEY_BAR',
] as const;
const saved: Record<string, string | undefined> = {};

beforeEach(() => {
for (const key of SCRUB_KEYS) {
saved[key] = process.env[key];
}
});

afterEach(() => {
for (const key of SCRUB_KEYS) {
const value = saved[key];
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
});

it('removes QWEN_SERVER_TOKEN from process.env', () => {
process.env['QWEN_SERVER_TOKEN'] = 'test-secret';
scrubDaemonProcessEnv();
expect(process.env['QWEN_SERVER_TOKEN']).toBeUndefined();
});

it('removes QWEN_DAEMON_TOKEN from process.env', () => {
process.env['QWEN_DAEMON_TOKEN'] = 'test-secret';
scrubDaemonProcessEnv();
expect(process.env['QWEN_DAEMON_TOKEN']).toBeUndefined();
});

it('removes QWEN_CODE_SIMPLE from process.env', () => {
process.env['QWEN_CODE_SIMPLE'] = '1';
scrubDaemonProcessEnv();
expect(process.env['QWEN_CODE_SIMPLE']).toBeUndefined();
});

it('removes QWEN_CUSTOM_API_KEY_* keys', () => {
process.env['QWEN_CUSTOM_API_KEY_FOO'] = 'secret-foo';
process.env['QWEN_CUSTOM_API_KEY_BAR'] = 'secret-bar';
scrubDaemonProcessEnv();
expect(process.env['QWEN_CUSTOM_API_KEY_FOO']).toBeUndefined();
expect(process.env['QWEN_CUSTOM_API_KEY_BAR']).toBeUndefined();
});

it('preserves unrelated keys', () => {
process.env['QWEN_SERVER_TOKEN'] = 'test-secret';
process.env['QWEN_CODE_SIMPLE'] = '1';
const pathBefore = process.env['PATH'];
scrubDaemonProcessEnv();
expect(process.env['PATH']).toBe(pathBefore);
});
});
56 changes: 53 additions & 3 deletions packages/cli/src/serve/run-qwen-serve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -741,6 +741,36 @@ export interface RunQwenServeDeps {
workspaceRegistrationStore?: WorkspaceRegistrationStore;
}

/**
* Regex matching env-var keys that must never appear in the daemon's
* OS-visible `process.env` after boot. On macOS a same-UID child can
* discover the daemon ancestor's PID via `process.ppid` and read its
* environment with `ps eww`; this pattern identifies the keys to
* strip before that exposure window opens.
*
* Mirrors the shell-tool denylist in `child-env-scrub.ts` — kept as a
* separate constant so the daemon's self-scrub policy is explicit and
* independently auditable.
*/
const DAEMON_SELF_SCRUB_PATTERN =
/^(?:QWEN_SERVER_TOKEN|QWEN_DAEMON_TOKEN|QWEN_CODE_SIMPLE|QWEN_CUSTOM_API_KEY_.+)$/;

/**
* Remove secret-bearing keys from the daemon's own `process.env` so
* they are not visible via OS process-inspection tools. Must be called
* AFTER all values have been read into local variables and BEFORE
* `daemonRuntimeBaseEnv` is snapshotted.
*/
export function scrubDaemonProcessEnv(): void {
for (const key of Object.keys(process.env)) {
const normalizedKey =
process.platform === 'win32' ? key.toUpperCase() : key;
if (DAEMON_SELF_SCRUB_PATTERN.test(normalizedKey)) {
delete process.env[key];
}
}
}

function shouldPreheatBridge(deps: RunQwenServeDeps): boolean {
if (deps.preheatBridge !== undefined) return deps.preheatBridge;
return process.env['VITEST_WORKER_ID'] === undefined;
Expand Down Expand Up @@ -1589,10 +1619,12 @@ export async function runQwenServe(
},
};
preResolveServeFastPathHomeEnvOverrides();
const daemonRuntimeBaseEnv: Readonly<NodeJS.ProcessEnv> = Object.freeze({
...process.env,
});

// Resolve the bearer token BEFORE scrubbing process.env — once read
// into the local variable the daemon uses it exclusively through
// closure (bearerAuth, createMutationGate, etc.) and never re-reads
// from the environment.
//
// Trim both sources. Common gotcha: `export QWEN_SERVER_TOKEN=$(cat
// token.txt)` keeps the file's trailing `\n` in the env value, so the
// hashed-then-compared token never matches what well-behaved clients
Expand All @@ -1604,6 +1636,24 @@ export async function runQwenServe(
typeof rawToken === 'string' && rawToken.trim().length > 0
? rawToken.trim()
: undefined;

// Remove secret-bearing keys from the daemon's own process.env so
// they are not visible via OS process-inspection tools. On macOS a
// same-UID child can discover the daemon ancestor's PID and read
// its environment with `ps eww`; the child's own env is already
// scrubbed by shellExecutionService but the daemon's was not.
// Also scrubs QWEN_CODE_SIMPLE (invocation-level override that
// would silently suppress skills in children) and QWEN_CUSTOM_API_KEY_*
// (user-configured keys that should not leak into workspace sessions).
scrubDaemonProcessEnv();
Comment thread
jadelike-wine marked this conversation as resolved.
Resolved
Comment thread
jadelike-wine marked this conversation as resolved.
Resolved

// Snapshot AFTER scrubbing — daemonRuntimeBaseEnv is clean by
// construction, so buildRuntimeEnvironment() never propagates
// daemon secrets into workspace session environments.
const daemonRuntimeBaseEnv: Readonly<NodeJS.ProcessEnv> = Object.freeze({
...process.env,
});

const sessionShellCommandEnabled =
optsIn.enableSessionShell === true && token !== undefined;
if (optsIn.enableSessionShell === true && token === undefined) {
Expand Down
23 changes: 15 additions & 8 deletions packages/core/src/hooks/hookRunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ import { PromptHookRunner } from './promptHookRunner.js';
import { AsyncHookRegistry, generateHookId } from './asyncHookRegistry.js';
import type { Config } from '../config/config.js';
import { getShellContextEnvVars } from '../utils/shellContextEnv.js';
import {
collectSensitiveShellEnvKeys,
scrubChildEnv,
} from '../utils/child-env-scrub.js';

const debugLogger = createDebugLogger('TRUSTED_HOOKS');

Expand Down Expand Up @@ -583,14 +587,17 @@ export class HookRunner {
shellConfig.shell,
);

const env = {
...process.env,
GEMINI_PROJECT_DIR: input.cwd,
CLAUDE_PROJECT_DIR: input.cwd, // For compatibility
QWEN_PROJECT_DIR: input.cwd, // For Qwen Code compatibility
...getShellContextEnvVars(),
...hookConfig.env,
};
const env = scrubChildEnv(
Comment thread
jadelike-wine marked this conversation as resolved.
Resolved
process.env,
collectSensitiveShellEnvKeys(process.env),
{
GEMINI_PROJECT_DIR: input.cwd,
CLAUDE_PROJECT_DIR: input.cwd, // For compatibility
QWEN_PROJECT_DIR: input.cwd, // For Qwen Code compatibility
...getShellContextEnvVars(),
...hookConfig.env,
},
);

const child = spawn(
shellConfig.executable,
Expand Down
Loading
Loading