Skip to content
Closed
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
c018d25
fix(hooks): never follow redirects in HTTP hooks
wenshao Aug 2, 2026
cb6ec7c
fix(settings): strip allowedHttpHookUrls from workspace scope
wenshao Aug 2, 2026
38754ef
fix(hooks): never resolve Qwen-internal secrets in env interpolation
wenshao Aug 2, 2026
6d61cf6
fix(hooks): gate project frontmatter hooks on folder trust
wenshao Aug 2, 2026
aed434a
fix(core): apply the internal-secrets denylist to the core envVarReso…
wenshao Aug 2, 2026
5813462
Merge branch 'main' into fix/hooks-security
qwen-code-dev-bot Aug 2, 2026
50b7f86
fix(hooks): case-insensitive secret denylist, narrow fast-path import…
qwen-code-ci-bot Aug 2, 2026
1353d0b
fix(hooks): meaningful casing tests, single env resolver, workspace-s…
qwen-code-ci-bot Aug 2, 2026
e3accbe
fix(hooks): case-insensitive child-env sanitize, denylist-first resol…
qwen-code-ci-bot Aug 3, 2026
9569dbf
fix(core): channel-config secret denylist, skill allowedTools trust g…
qwen-code-ci-bot Aug 3, 2026
832f82b
fix(hooks): throw on internal-secret channel refs, sanitize redirect …
qwen-code-ci-bot Aug 3, 2026
e83f5e1
fix(hooks): event-scoped redirect warnings, merged systemMessages (#8…
qwen-code-ci-bot Aug 3, 2026
199aaee
fix(cli): warn when skill allowedTools trust gate fires in slash-comm…
qwen-code-ci-bot Aug 3, 2026
0f9e98e
fix(core): apply skill side effects when folder trust is granted mid-…
qwen-code-ci-bot Aug 3, 2026
fb7b426
fix(core): honor skill side-effect deferral contract, pin invariants …
qwen-code-ci-bot Aug 4, 2026
6c44667
Merge branch 'main' into fix/hooks-security
qwen-code-dev-bot Aug 4, 2026
b10ec55
fix(cli): remap core envVarResolver subpath in dev loader (#8396)
qwen-code-dev-bot Aug 4, 2026
935ae7e
Merge branch 'main' into fix/hooks-security
qwen-code-dev-bot Aug 4, 2026
502a8aa
fix(hooks): workspace whitelist may only narrow; trust session subage…
qwen-code-dev-bot Aug 4, 2026
846ec2d
fix(hooks): roll back once-hook slot when a 3xx is never delivered (#…
qwen-code-dev-bot Aug 4, 2026
edb11de
fix(hooks): fail closed and scan linearly when narrowing workspace ho…
qwen-code-dev-bot Aug 4, 2026
817e1dc
fix(hooks): harden hook whitelist narrowing and one-shot warning deli…
qwen-code-dev-bot Aug 5, 2026
90002cb
fix(hooks): close home-root trust bypass and non-ASCII pattern diverg…
qwen-code-dev-bot Aug 5, 2026
f36390e
Merge branch 'main' into fix/hooks-security
qwen-code-dev-bot Aug 5, 2026
eedd924
fix(hooks): make home-root trust gates immune to per-agent root rebin…
qwen-code-dev-bot Aug 5, 2026
dce013c
Merge branch 'main' into fix/hooks-security
wenshao Aug 6, 2026
3ef677f
chore(hooks): merge main into fix/hooks-security
qwen-code-dev-bot Aug 6, 2026
d4a76b9
chore(hooks): merge main into fix/hooks-security
qwen-code-dev-bot Aug 13, 2026
ccf1a7a
Merge branch 'main' into fix/hooks-security
wenshao Aug 15, 2026
ad00d83
Merge branch 'main' into fix/hooks-security
wenshao Aug 17, 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
31 changes: 27 additions & 4 deletions packages/cli/src/config/settings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3264,7 +3264,7 @@ describe('Settings Loading and Merging', () => {
expect(settings.merged.security?.allowPrivateNetworkHooks).toBe(true);
});

it('should strip security.allowPrivateNetworkHooks from workspace scope even when trusted', () => {
it('should strip security.allowPrivateNetworkHooks and security.allowedHttpHookUrls from workspace scope even when trusted', () => {
(mockFsExistsSync as Mock).mockReturnValue(true);
const workspaceSettingsContent = {
security: {
Expand All @@ -3282,13 +3282,36 @@ describe('Settings Loading and Merging', () => {
);

const settings = loadSettings(MOCK_WORKSPACE_DIR);
// The flag is ignored from workspace scope...
// Both hook-security overrides are ignored from workspace scope:
// a repository must not self-grant an SSRF relaxation nor replace
// the user's hook-payload whitelist.
expect(
settings.merged.security?.allowPrivateNetworkHooks,
).toBeUndefined();
// ...but other workspace security settings still merge.
expect(settings.merged.security?.allowedHttpHookUrls).toBeUndefined();
});

it('should honor security.allowedHttpHookUrls from user scope', () => {
(mockFsExistsSync as Mock).mockReturnValue(true);
(fs.readFileSync as Mock).mockImplementation(
(p: fs.PathOrFileDescriptor) => {
if (p === USER_SETTINGS_PATH)
return JSON.stringify({
security: { allowedHttpHookUrls: ['https://hooks.corp.com/*'] },
});
if (p === MOCK_WORKSPACE_SETTINGS_PATH)
return JSON.stringify({
security: { allowedHttpHookUrls: ['*'] },
});
return '{}';
},
);

const settings = loadSettings(MOCK_WORKSPACE_DIR);
// The workspace's self-granted "*" is stripped; the user's
// whitelist survives.
expect(settings.merged.security?.allowedHttpHookUrls).toEqual([
'https://hooks.example.com/*',
'https://hooks.corp.com/*',
]);
});

Expand Down
27 changes: 19 additions & 8 deletions packages/cli/src/config/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -400,17 +400,28 @@ function tagMcpServerScope(

/**
* `security.allowPrivateNetworkHooks` relaxes SSRF protection for HTTP hooks,
* so it must never be honored from Workspace scope — otherwise a malicious
* repository could self-grant the bypass and point hooks at link-local or
* private infrastructure. Strip it from workspace settings before merging.
* and `security.allowedHttpHookUrls` replaces the user's whitelist of where
* HTTP hooks may POST agent data. Neither may be honored from Workspace
* scope — otherwise a malicious repository could self-grant the bypass
* (point hooks at link-local or private infrastructure) or widen the
* whitelist to exfiltrate hook payloads past the user's configured
* boundary. Strip both from workspace settings before merging.
* Returns a shallow copy — never mutates input.
*/
function stripWorkspacePrivateNetworkHooks(settings: Settings): Settings {
if (settings.security?.allowPrivateNetworkHooks === undefined) {
function stripWorkspaceHookSecurityOverrides(settings: Settings): Settings {
const { allowPrivateNetworkHooks, allowedHttpHookUrls } =
settings.security ?? {};
if (
allowPrivateNetworkHooks === undefined &&
allowedHttpHookUrls === undefined
) {
return settings;
}
const { allowPrivateNetworkHooks: _stripped, ...restSecurity } =
settings.security;
const {
allowPrivateNetworkHooks: _strippedFlag,
allowedHttpHookUrls: _strippedUrls,
...restSecurity
} = settings.security!;
return { ...settings, security: restSecurity };
}

Expand All @@ -423,7 +434,7 @@ function mergeSettings(
): Settings {
const safeWorkspace = isTrusted
? tagMcpServerScope(
stripWorkspacePrivateNetworkHooks(workspace),
stripWorkspaceHookSecurityOverrides(workspace),
'workspace',
)
: ({} as Settings);
Expand Down
12 changes: 11 additions & 1 deletion packages/cli/src/utils/envVarResolver.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,20 @@ describe('resolveEnvVarsInString', () => {

it('should leave undefined variables unchanged', () => {
const result = resolveEnvVarsInString('Value is $UNDEFINED_VAR');

expect(result).toBe('Value is $UNDEFINED_VAR');
});

it('should never resolve Qwen-internal secrets from process.env', () => {
process.env['QWEN_SERVER_TOKEN'] = 'daemon-secret';

const result = resolveEnvVarsInString(
'curl https://x/t=$QWEN_SERVER_TOKEN',
);

expect(result).toBe('curl https://x/t=$QWEN_SERVER_TOKEN');
expect(result).not.toContain('daemon-secret');
});

it('should leave undefined variables with braces unchanged', () => {
const result = resolveEnvVarsInString('Value is ${UNDEFINED_VAR}');

Expand Down
12 changes: 12 additions & 0 deletions packages/cli/src/utils/envVarResolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,20 @@
* SPDX-License-Identifier: Apache-2.0
*/

import { INTERNAL_SECRET_ENV_VARS } from '@qwen-code/qwen-code-core';

/**
* Resolves environment variables in a string.
* Replaces $VAR_NAME and ${VAR_NAME} with their corresponding environment variable values.
* If the environment variable is not defined, the original placeholder is preserved.
*
* Qwen-internal secrets (INTERNAL_SECRET_ENV_VARS — daemon tokens, private
* capabilities) are never resolved from `process.env`: settings files can
* come from a repository, and a resolved value is baked into hook commands,
* URLs, or MCP configs before child-env sanitization ever applies. Leaving
* the placeholder unresolved is safe — spawned children get a sanitized
* environment without those variables.
*
* @param value - The string that may contain environment variable placeholders
* @returns The string with environment variables resolved
*
Expand All @@ -27,6 +36,9 @@ export function resolveEnvVarsInString(
if (customEnv && typeof customEnv[varName] === 'string') {
return customEnv[varName];
}
if (INTERNAL_SECRET_ENV_VARS.includes(varName)) {
return match;
}
if (process && process.env && typeof process.env[varName] === 'string') {
return process.env[varName]!;
}
Expand Down
9 changes: 9 additions & 0 deletions packages/core/src/hooks/envInterpolator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,15 @@ describe('envInterpolator', () => {
expect(result).toBe('');
});

it('should never interpolate Qwen-internal secrets, even when whitelisted', () => {
process.env['QWEN_SERVER_TOKEN'] = 'daemon-secret';
const result = interpolateEnvVars('token=$QWEN_SERVER_TOKEN', [
'QWEN_SERVER_TOKEN',
]);
expect(result).toBe('token=');
expect(result).not.toContain('daemon-secret');
});

it('should handle empty whitelist', () => {
const result = interpolateEnvVars('$MY_TOKEN', []);
expect(result).toBe('');
Expand Down
9 changes: 9 additions & 0 deletions packages/core/src/hooks/envInterpolator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
* Provides secure interpolation with whitelist-based access control.
*/

import { INTERNAL_SECRET_ENV_VARS } from '../utils/sanitize-child-env.js';

/**
* Strip CR, LF, and NUL bytes from a header value to prevent HTTP header
* injection (CRLF injection) via env var values or hook-configured header
Expand Down Expand Up @@ -65,6 +67,13 @@ export function interpolateEnvVars(
if (!isSafeVarName(varName)) {
return '';
}
// Qwen-internal secrets (daemon tokens, private capabilities) are
// never interpolated, even when a hook config names them in
// allowedEnvVars — the whitelist is repo-controlled, the values
// leave the process over the network.
if (INTERNAL_SECRET_ENV_VARS.includes(varName)) {
return '';
}
if (allowedVars.includes(varName)) {
return process.env[varName] || '';
}
Expand Down
30 changes: 30 additions & 0 deletions packages/core/src/hooks/httpHookRunner.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,36 @@ describe('HttpHookRunner', () => {
expect(mockFetch).toHaveBeenCalledTimes(1); // Still 1
});

it('should not follow redirects — 3xx is a non-blocking error and the target is never contacted', async () => {
mockFetch.mockResolvedValueOnce({
ok: false,
status: 302,
headers: new Headers({
location: 'http://169.254.169.254/latest/meta-data',
}),
json: async () => ({}),
});

const config = createMockConfig();
const input = createMockInput();

const result = await httpRunner.execute(
config,
HookEventName.PreToolUse,
input,
);

// Non-2xx (incl. 3xx) is a non-blocking error per spec
expect(result.success).toBe(true);
expect(result.output?.continue).toBe(true);
// Exactly one request: the redirect target is never fetched
expect(mockFetch).toHaveBeenCalledTimes(1);
expect(mockFetch).toHaveBeenCalledWith(
'https://api.example.com/hook',
expect.objectContaining({ redirect: 'manual' }),
);
});

it('should parse JSON response with hook output', async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
Expand Down
5 changes: 5 additions & 0 deletions packages/core/src/hooks/httpHookRunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,11 @@ export class HttpHookRunner {
},
body,
signal: combinedSignal,
// Never follow redirects: the whitelist and DNS-level SSRF
// checks above cover only this URL, and a 307/308 would re-send
// the hook payload to an unvalidated target. A 3xx response
// falls into the non-2xx branch below (non-blocking error).
redirect: 'manual',
});

cleanup();
Expand Down
56 changes: 56 additions & 0 deletions packages/core/src/subagents/subagent-manager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2572,6 +2572,62 @@ bad`);
expect(unregisterSpy).toHaveBeenCalledTimes(1);
});

it('does not register hooks for a project-level subagent in an untrusted folder', async () => {
const addAgentHooksSpy = vi.fn().mockReturnValue(vi.fn());
vi.spyOn(mockConfig, 'getHookSystem').mockReturnValue({
getRegistry: () => ({ addAgentHooks: addAgentHooksSpy }),
} as unknown as ReturnType<Config['getHookSystem']>);
vi.spyOn(mockConfig, 'isTrustedFolder').mockReturnValue(false);

const result = await manager.createAgentHeadless(
{
...baseConfig,
level: 'project',
hooks: {
PreToolUse: [
{
matcher: 'Bash',
hooks: [{ type: 'command', command: 'echo' }],
},
],
},
},
mockConfig,
);

expect(addAgentHooksSpy).not.toHaveBeenCalled();
// The agent itself is still created — only the hooks are gated.
expect(result).toHaveProperty('subagent');
await result.dispose();
});

it('registers hooks for a project-level subagent in a trusted folder', async () => {
const addAgentHooksSpy = vi.fn().mockReturnValue(vi.fn());
vi.spyOn(mockConfig, 'getHookSystem').mockReturnValue({
getRegistry: () => ({ addAgentHooks: addAgentHooksSpy }),
} as unknown as ReturnType<Config['getHookSystem']>);
vi.spyOn(mockConfig, 'isTrustedFolder').mockReturnValue(true);

const result = await manager.createAgentHeadless(
{
...baseConfig,
level: 'project',
hooks: {
PreToolUse: [
{
matcher: 'Bash',
hooks: [{ type: 'command', command: 'echo' }],
},
],
},
},
mockConfig,
);

expect(addAgentHooksSpy).toHaveBeenCalledTimes(1);
await result.dispose();
});

it('dispose unregisters even when execute() never runs (early-exit leak fix)', async () => {
// Caller pattern:
// const { subagent, dispose } = await createAgentHeadless(...);
Expand Down
10 changes: 9 additions & 1 deletion packages/core/src/subagents/subagent-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -924,7 +924,15 @@ export class SubagentManager {
const hookSystem = runtimeContext.getHookSystem();
const hookRegistry = hookSystem?.getRegistry();
if (config.hooks && Object.keys(config.hooks).length > 0) {
if (hookRegistry) {
if (config.level === 'project' && !runtimeContext.isTrustedFolder()) {
// Project agents load from <repo>/.qwen/agents/ regardless of
// trust (read-only use is fine), but their hooks are repo-supplied
// code execution — the same gate Config.getProjectHooks() applies
// to settings-file hooks.
debugLogger.warn(
`Subagent "${config.name}" declares hooks but the folder is not trusted; ignoring per-agent hooks.`,
);
} else if (hookRegistry) {
const agentScope = `agent:${config.name}:${randomUUID()}`;
unregisterAgentHooks = hookRegistry.addAgentHooks(
config.hooks as { [K in HookEventName]?: HookDefinition[] },
Expand Down
Loading
Loading