Skip to content
84 changes: 84 additions & 0 deletions packages/core/src/extension/extension-git-client.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/

import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import * as fs from 'node:fs/promises';
import * as os from 'node:os';
import * as path from 'node:path';
import { simpleGit } from 'simple-git';
import { createExtensionGitClient } from './extension-git-client.js';

describe('createExtensionGitClient', () => {
let tempDir: string;

beforeEach(async () => {
tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'extension-git-client-'));
});

afterEach(async () => {
vi.unstubAllEnvs();
await fs.rm(tempDir, { recursive: true, force: true });
});

it('runs authenticated Git commands with pinned network config', async () => {
let spawned = false;
const git = createExtensionGitClient(simpleGit, {
baseDir: tempDir,
networkPolicy: 'public',
networkConfig: [
'http.curloptResolve=git.example.com:443:8.8.8.8',
'http.followRedirects=false',
'http.proxy=',
'protocol.allow=never',
'protocol.https.allow=always',
],
authentication: {
source: 'https://git.example.com/owner/repo.git',
credential: { username: 'user', password: 'token' },
},
});
git.outputHandler(() => {
spawned = true;
});

await expect(git.version()).resolves.toBeDefined();
expect(spawned).toBe(true);
});

it('runs authenticated Git commands without pinned network config', async () => {
let spawned = false;
const git = createExtensionGitClient(simpleGit, {
baseDir: tempDir,
authentication: {
source: 'https://git.example.com/owner/repo.git',
credential: { username: 'user', password: 'token' },
},
});
git.outputHandler(() => {
spawned = true;
});

await expect(git.version()).resolves.toBeDefined();
expect(spawned).toBe(true);
});

it('does not inherit Git config count for anonymous public commands', async () => {
vi.stubEnv('GIT_CONFIG_COUNT', '1');
vi.stubEnv('GIT_CONFIG_KEY_0', 'http.extraHeader');
vi.stubEnv('GIT_CONFIG_VALUE_0', 'Authorization: Basic external');
let spawned = false;
const git = createExtensionGitClient(simpleGit, {
baseDir: tempDir,
networkPolicy: 'public',
});
git.outputHandler(() => {
spawned = true;
});

await expect(git.version()).resolves.toBeDefined();
expect(spawned).toBe(true);
});
});
81 changes: 81 additions & 0 deletions packages/core/src/extension/extension-git-client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/

import * as os from 'node:os';
import type { SimpleGit, SimpleGitFactory } from 'simple-git';
import type { ExtensionInstallMetadata } from '../config/config.js';
import type { GitCredential } from './extension-git-credentials.js';

interface ExtensionGitAuthentication {
source: string;
credential: GitCredential;
}

interface ExtensionGitClientOptions {
baseDir: string;
signal?: AbortSignal;
networkPolicy?: ExtensionInstallMetadata['networkPolicy'];
networkConfig?: string[];
authentication?: ExtensionGitAuthentication;
}

export function createExtensionGitClient(
simpleGit: SimpleGitFactory,
{
baseDir,
signal,
networkPolicy,
networkConfig = [],
authentication,
}: ExtensionGitClientOptions,
): SimpleGit {
const restrictEnvironment =
networkPolicy === 'public' || authentication !== undefined;
const hasNetworkConfig = networkConfig.length > 0;
const git = simpleGit(baseDir, {
...(signal ? { abort: signal } : {}),
...(hasNetworkConfig ? { config: networkConfig } : {}),
...(restrictEnvironment || hasNetworkConfig
? {
unsafe: {
...(restrictEnvironment ? { allowUnsafeConfigPaths: true } : {}),
...(hasNetworkConfig ? { allowUnsafeProtocolOverride: true } : {}),
...(authentication ? { allowUnsafeConfigEnvCount: true } : {}),
},
}
: {}),
});
if (!restrictEnvironment) return git;

const environment: Record<string, string> = {
GIT_CONFIG_NOSYSTEM: '1',
GIT_CONFIG_GLOBAL: os.devNull,
Comment thread
callmeYe marked this conversation as resolved.
Resolved
};
for (const key of [
'PATH',
'Path',
'SystemRoot',
'SYSTEMROOT',
'WINDIR',
'TEMP',
'TMP',
'TMPDIR',
]) {
const value = process.env[key];
if (value !== undefined) environment[key] = value;
}
if (authentication) {
const value = Buffer.from(
`${authentication.credential.username}:${authentication.credential.password}`,
'utf8',
).toString('base64');
environment['GIT_CONFIG_COUNT'] = '1';
environment['GIT_CONFIG_KEY_0'] =
`http.${authentication.source}.extraHeader`;
Comment thread
callmeYe marked this conversation as resolved.
Resolved
environment['GIT_CONFIG_VALUE_0'] = `Authorization: Basic ${value}`;
}
return git.env(environment);
}
30 changes: 30 additions & 0 deletions packages/core/src/extension/github.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,16 @@ describe('git extension helpers', () => {
'--depth',
'1',
]);
expect(simpleGit).toHaveBeenLastCalledWith(
'/dest',
expect.objectContaining({
unsafe: {
allowUnsafeConfigPaths: true,
allowUnsafeProtocolOverride: true,
allowUnsafeConfigEnvCount: true,
},
}),
);
expect(mockGit.env).toHaveBeenCalledWith(
expect.objectContaining({
GIT_CONFIG_COUNT: '1',
Expand Down Expand Up @@ -450,6 +460,16 @@ describe('git extension helpers', () => {
'./',
expect.any(Array),
);
expect(simpleGit).toHaveBeenLastCalledWith(
'/dest',
expect.objectContaining({
unsafe: {
allowUnsafeConfigPaths: true,
allowUnsafeProtocolOverride: true,
allowUnsafeConfigEnvCount: true,
},
}),
);
expect(mockGit.env).toHaveBeenCalledWith(
expect.objectContaining({
GIT_CONFIG_VALUE_0: `Authorization: Basic ${Buffer.from(
Expand Down Expand Up @@ -1503,6 +1523,16 @@ describe('git extension helpers', () => {

expect(result).toBe(ExtensionUpdateState.UPDATE_AVAILABLE);
expect(mockGit.listRemote).toHaveBeenCalledWith([source, 'HEAD']);
expect(simpleGit).toHaveBeenLastCalledWith(
extensionPath,
expect.objectContaining({
unsafe: {
allowUnsafeConfigPaths: true,
allowUnsafeProtocolOverride: true,
allowUnsafeConfigEnvCount: true,
},
}),
);
expect(mockGit.env).toHaveBeenLastCalledWith(
expect.objectContaining({
GIT_CONFIG_KEY_0: `http.${source}.extraHeader`,
Expand Down
84 changes: 15 additions & 69 deletions packages/core/src/extension/github.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
* SPDX-License-Identifier: Apache-2.0
*/

import type { SimpleGit } from 'simple-git';
import { getErrorMessage } from '../utils/errors.js';
import * as crypto from 'node:crypto';
import * as os from 'node:os';
Expand Down Expand Up @@ -43,6 +42,7 @@ import {
resolveStoredGitCredential,
type GitCredential,
} from './extension-git-credentials.js';
import { createExtensionGitClient } from './extension-git-client.js';

const debugLogger = createDebugLogger('EXT_GITHUB');
const SUPPORTED_ARCHIVE_EXTENSIONS = ['.tar.gz', '.zip'] as const;
Expand Down Expand Up @@ -214,42 +214,6 @@ function createPinnedGitConfig(curlResolve: string): string[] {
];
}

function restrictGitEnvironment(
git: SimpleGit,
networkPolicy?: ExtensionInstallMetadata['networkPolicy'],
authentication?: { source: string; credential: GitCredential },
): SimpleGit {
if (networkPolicy !== 'public' && !authentication) return git;
const environment: Record<string, string> = {
GIT_CONFIG_NOSYSTEM: '1',
GIT_CONFIG_GLOBAL: os.devNull,
};
for (const key of [
'PATH',
'Path',
'SystemRoot',
'SYSTEMROOT',
'WINDIR',
'TEMP',
'TMP',
'TMPDIR',
]) {
const value = process.env[key];
if (value !== undefined) environment[key] = value;
}
if (authentication) {
const value = Buffer.from(
`${authentication.credential.username}:${authentication.credential.password}`,
'utf8',
).toString('base64');
environment['GIT_CONFIG_COUNT'] = '1';
environment['GIT_CONFIG_KEY_0'] =
`http.${authentication.source}.extraHeader`;
environment['GIT_CONFIG_VALUE_0'] = `Authorization: Basic ${value}`;
}
return git.env(environment);
}

/**
* Clones a Git repository to a specified local path.
* @param installMetadata The metadata for the extension to install.
Expand Down Expand Up @@ -284,24 +248,15 @@ export async function cloneFromGit(
}
const effectiveCredential =
credential ?? getGitHubCredential(installMetadata.source);
const git = restrictGitEnvironment(
simpleGit(destination, {
...(signal ? { abort: signal } : {}),
...(networkConfig.length > 0
? {
config: networkConfig,
unsafe: {
allowUnsafeConfigPaths: true,
allowUnsafeProtocolOverride: true,
},
}
: {}),
}),
installMetadata.networkPolicy,
effectiveCredential
const git = createExtensionGitClient(simpleGit, {
baseDir: destination,
signal,
networkPolicy: installMetadata.networkPolicy,
networkConfig,
authentication: effectiveCredential
? { source: installMetadata.source, credential: effectiveCredential }
: undefined,
);
});
signal?.throwIfAborted();
// On Windows, symlinks require elevated privileges by default, so we
// disable them to avoid "Permission denied" errors during checkout.
Expand Down Expand Up @@ -787,24 +742,15 @@ export async function checkForExtensionUpdate(
signal?.throwIfAborted();
const effectiveCredential =
storedCredential ?? getGitHubCredential(remoteUrl);
const git = restrictGitEnvironment(
simpleGit(extension.path, {
...(signal ? { abort: signal } : {}),
...(networkConfig.length > 0
? {
config: networkConfig,
unsafe: {
allowUnsafeConfigPaths: true,
allowUnsafeProtocolOverride: true,
},
}
: {}),
}),
installMetadata.networkPolicy,
effectiveCredential
const git = createExtensionGitClient(simpleGit, {
baseDir: extension.path,
signal,
networkPolicy: installMetadata.networkPolicy,
networkConfig,
authentication: effectiveCredential
? { source: remoteUrl, credential: effectiveCredential }
: undefined,
);
});
const refToCheck = installMetadata.ref || 'HEAD';
const refPatterns = installMetadata.ref
? [refToCheck, `${refToCheck}^{}`]
Expand Down
Loading