Skip to content

Commit 89e9ae9

Browse files
chrmartiCopilot
andauthored
agentHost: Look up Basic proxy credentials from the client (#346967)
* agentHost: Look up Basic proxy credentials from the client A standalone Agent Host on a network it shares with the client, such as WSL, can now ask that client for Basic proxy credentials with the vscode/lookupProxyBasicCredentials reverse request over the vscode.clientProxy capability. The client only answers for proxies it resolved for the host, and the host uses the credentials for its own proxied requests. This keeps the credentials off the host's disk. The AHP log redacts the password. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * agentHost: Match Basic proxy credentials to the proxy endpoint The client only returns Basic credentials for the host and port of a proxy it points the agent host at, and only for http.proxy while that is set, because the native lookup returns its credentials for any proxy on the first attempt. The agent host passes the client the proxy's origin, keeping the scheme that decides the default port. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * agentHost: Rename the Basic proxy lookup to lookupProxyBasicAuthorization Aligns it with lookupProxyKerberosAuthorization, as IRequestService pairs lookupAuthorization with lookupKerberosAuthorization. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * agentHost: Match Basic proxy credentials to a credential-bearing environment proxy When http.proxy is unset, the native lookup returns the credentials of a proxy in HTTPS_PROXY or HTTP_PROXY for any proxy on the first attempt. Only that proxy's endpoint now qualifies for Basic lookups, like http.proxy. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 7cadbfc commit 89e9ae9

16 files changed

Lines changed: 446 additions & 69 deletions

‎src/vs/platform/agentHost/browser/agentHostClientProxy.ts‎

Lines changed: 127 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -4,32 +4,46 @@
44
*--------------------------------------------------------------------------------------------*/
55

66
import { Event } from '../../../base/common/event.js';
7+
import { IProcessEnvironment, isWindows } from '../../../base/common/platform.js';
8+
import { URI } from '../../../base/common/uri.js';
79
import { IConfigurationService } from '../../configuration/common/configuration.js';
810
import { IDefaultAccountService } from '../../defaultAccount/common/defaultAccount.js';
911
import { GITHUB_DOT_COM_COPILOT_API_BASE_URI } from '../../github/common/githubEndpoints.js';
1012
import { ILogService } from '../../log/common/log.js';
11-
import { IRequestService } from '../../request/common/request.js';
13+
import { Credentials, IRequestService } from '../../request/common/request.js';
1214
import type { IAgentHostClientProxyProvider } from '../common/clientProxyProtocol.js';
1315
import { AgentHostProxyConfigKey } from '../common/agentHostSchema.js';
1416
import { AgentHostSystemProxyEnabledSettingId } from '../common/agentService.js';
1517

1618
/** Settings that change how this client resolves proxies for the agent host. */
1719
const clientProxySettings = ['http.useLocalProxyConfiguration', 'http.proxy', 'http.noProxy', 'http.proxySupport'];
1820

21+
/** A proxy's hostname, as a URL formats it, and its port, defaulted for its scheme. */
22+
interface IProxyEndpoint {
23+
readonly hostname: string;
24+
readonly port: number;
25+
}
26+
1927
/**
2028
* Serves an agent host that shares this client's network, such as one in WSL or a local container, the way a remote
2129
* extension host with `useHostProxy` uses the local proxy configuration: proxies resolve through this client unless
22-
* `http.useLocalProxyConfiguration` is off, and the agent host can fall back to this client's Kerberos tickets.
30+
* `http.useLocalProxyConfiguration` is off, and the agent host can fall back to this client's Kerberos tickets and
31+
* proxy credentials.
2332
*/
2433
export class AgentHostClientProxy implements IAgentHostClientProxyProvider {
2534

26-
/** Hosts of the proxies this client resolved for the agent host or for GitHub Copilot. */
27-
private readonly _resolvedProxyHosts = new Set<string>();
28-
/** Hosts of the proxies this client declined tickets for, to log each once. */
29-
private readonly _declinedProxyHosts = new Set<string>();
35+
/** The proxies this client resolved for the agent host or for GitHub Copilot, by endpoint. */
36+
private readonly _resolvedProxies = new Map<string, IProxyEndpoint>();
37+
/** The lookups and hosts of the proxies this client declined, to log each once. */
38+
private readonly _declinedLookups = new Set<string>();
3039

40+
/**
41+
* @param _environment This client's environment, which it inherits from the main process that the native credential
42+
* lookup reads its environment proxy in.
43+
*/
3144
constructor(
3245
private readonly _isEnabled: () => boolean,
46+
private readonly _environment: IProcessEnvironment,
3347
@IConfigurationService private readonly _configurationService: IConfigurationService,
3448
@IRequestService private readonly _requestService: IRequestService,
3549
@IDefaultAccountService private readonly _defaultAccountService: IDefaultAccountService,
@@ -49,83 +63,158 @@ export class AgentHostClientProxy implements IAgentHostClientProxyProvider {
4963
return undefined;
5064
}
5165
const proxy = await this._requestService.resolveProxy(url);
52-
for (const host of getResolvedProxyHosts(proxy)) {
53-
this._resolvedProxyHosts.add(host);
54-
}
66+
this._rememberProxies(getResolvedProxies(proxy));
5567
return proxy;
5668
}
5769

5870
async lookupKerberosAuthorization(proxyUrl: string): Promise<string | undefined> {
5971
if (!await this._isAgentHostProxy(proxyUrl)) {
60-
const host = getUrlHost(proxyUrl) ?? 'an invalid URL';
61-
if (!this._declinedProxyHosts.has(host)) {
62-
this._declinedProxyHosts.add(host);
63-
this._logService.info(`[AgentHostClientProxy] Declined Kerberos lookup for ${host}: not a proxy this client points the agent host at`);
64-
}
72+
this._logDeclined('Kerberos', proxyUrl);
6573
return undefined;
6674
}
6775
return this._requestService.lookupKerberosAuthorization(proxyUrl);
6876
}
6977

7078
/**
71-
* Tickets are only issued for proxies this client points the agent host at: its `http.proxy` setting, the proxies
72-
* it resolved for the agent host, or the system proxy for GitHub Copilot, which also covers a proxy an earlier window
73-
* resolved. A configured `http.proxyKerberosServicePrincipal` limits tickets to that principal instead. Both settings
74-
* are read as the native request service issuing the tickets reads them, so remote settings cannot widen access.
79+
* Unlike Kerberos tickets, Basic credentials are reusable secrets that the native lookup returns for any proxy, such
80+
* as the ones in `http.proxy` or `HTTPS_PROXY`, so they only go to the endpoints of proxies this client points the
81+
* agent host at.
82+
*/
83+
async lookupBasicAuthorization(proxyUrl: string, realm: string | undefined, attempt: number): Promise<Credentials | undefined> {
84+
if (this._configurationService.getValue<boolean>('http.useLocalProxyConfiguration') === false) {
85+
return undefined;
86+
}
87+
const proxy = getProxyEndpoint(proxyUrl);
88+
if (!proxy || !await this._isResolvedProxy(proxy, true)) {
89+
this._logDeclined('Basic credentials', proxyUrl);
90+
return undefined;
91+
}
92+
return this._requestService.lookupAuthorization({
93+
isProxy: true,
94+
scheme: 'basic',
95+
host: proxy.hostname,
96+
// Like Electron, with the default port, which keys the credentials its login dialog stores.
97+
port: proxy.port,
98+
realm: realm ?? '',
99+
attempt,
100+
});
101+
}
102+
103+
private _logDeclined(lookup: string, proxyUrl: string): void {
104+
const host = getProxyEndpoint(proxyUrl)?.hostname ?? 'an invalid URL';
105+
const key = `${lookup} ${host}`;
106+
if (!this._declinedLookups.has(key)) {
107+
this._declinedLookups.add(key);
108+
this._logService.info(`[AgentHostClientProxy] Declined ${lookup} lookup for ${host}: not a proxy this client points the agent host at`);
109+
}
110+
}
111+
112+
/**
113+
* Tickets are only issued for proxies this client points the agent host at (see {@link _isResolvedProxy}). A
114+
* configured `http.proxyKerberosServicePrincipal` limits tickets to that principal instead. It is read as the native
115+
* request service issuing the tickets reads it, so remote settings cannot widen access.
75116
*/
76117
private async _isAgentHostProxy(proxyUrl: string): Promise<boolean> {
77118
if (this._getLocalValue<string>(AgentHostProxyConfigKey.ProxyKerberosServicePrincipal)?.trim()) {
78119
return true;
79120
}
80-
const host = getUrlHost(proxyUrl);
81-
return !!host && (this._resolvedProxyHosts.has(host) || (await this._resolveCopilotProxyHosts()).includes(host));
121+
const proxy = getProxyEndpoint(proxyUrl);
122+
return !!proxy && this._isResolvedProxy(proxy, false);
123+
}
124+
125+
/**
126+
* Whether `proxy` is a proxy this client points the agent host at: its `http.proxy` setting, the proxies it
127+
* resolved for the agent host, or the system proxy for GitHub Copilot, which also covers a proxy an earlier window
128+
* resolved. `http.proxy` is read as the native request service reads it, so remote settings cannot widen access.
129+
*
130+
* With `matchEndpoint`, the port must match too, and while the native lookup returns the credentials of a proxy for
131+
* any proxy on the first attempt (see {@link _getCredentialsProxy}), only that proxy can qualify, even when another
132+
* was resolved before.
133+
*/
134+
private async _isResolvedProxy(proxy: IProxyEndpoint, matchEndpoint: boolean): Promise<boolean> {
135+
const matches = (candidate: IProxyEndpoint) => candidate.hostname === proxy.hostname && (!matchEndpoint || candidate.port === proxy.port);
136+
const credentialsProxy = matchEndpoint ? this._getCredentialsProxy() : undefined;
137+
if (credentialsProxy !== undefined) {
138+
const endpoint = getProxyEndpoint(credentialsProxy);
139+
if (!endpoint || !matches(endpoint)) {
140+
return false;
141+
}
142+
}
143+
return [...this._resolvedProxies.values()].some(matches) || (await this._resolveCopilotProxies()).some(matches);
82144
}
83145

84-
private async _resolveCopilotProxyHosts(): Promise<string[]> {
85-
// The agent host receives the client's `http.proxy` setting under the same key.
86-
const configuredProxy = this._getLocalValue<string>(AgentHostProxyConfigKey.Proxy)?.trim();
146+
/**
147+
* The proxy whose credentials, if any, the native lookup returns for any proxy on the first attempt: `http.proxy`,
148+
* or else a proxy with credentials in the main process's environment.
149+
*/
150+
private _getCredentialsProxy(): string | undefined {
151+
const configuredProxy = this._getConfiguredProxy();
87152
if (configuredProxy) {
88-
const host = getUrlHost(configuredProxy);
89-
return host ? [host] : [];
153+
return configuredProxy;
154+
}
155+
const environmentProxy = getEnvironmentProxy(this._environment);
156+
return environmentProxy && URI.parse(environmentProxy).authority.includes('@') ? environmentProxy : undefined;
157+
}
158+
159+
private async _resolveCopilotProxies(): Promise<IProxyEndpoint[]> {
160+
const configuredProxy = this._getConfiguredProxy();
161+
if (configuredProxy) {
162+
const proxy = getProxyEndpoint(configuredProxy);
163+
return proxy ? [proxy] : [];
90164
}
91165
if (this._configurationService.getValue<boolean>(AgentHostSystemProxyEnabledSettingId) === false) {
92166
return [];
93167
}
94168
const apiUrl = this._defaultAccountService.currentDefaultAccount?.entitlementsData?.endpoints?.api || GITHUB_DOT_COM_COPILOT_API_BASE_URI;
95169
try {
96-
const hosts = getResolvedProxyHosts(await this._requestService.resolveProxy(apiUrl));
170+
const proxies = getResolvedProxies(await this._requestService.resolveProxy(apiUrl));
97171
// Remembered like the proxies resolved for the agent host, so that later lookups for them resolve nothing.
98-
for (const host of hosts) {
99-
this._resolvedProxyHosts.add(host);
100-
}
101-
return hosts;
172+
this._rememberProxies(proxies);
173+
return proxies;
102174
} catch (error) {
103175
this._logService.debug('[AgentHostClientProxy] Failed to resolve the GitHub Copilot proxy', error);
104176
return [];
105177
}
106178
}
107179

180+
private _rememberProxies(proxies: readonly IProxyEndpoint[]): void {
181+
for (const proxy of proxies) {
182+
this._resolvedProxies.set(`${proxy.hostname} ${proxy.port}`, proxy);
183+
}
184+
}
185+
186+
/** The agent host receives the client's `http.proxy` setting under the same key. */
187+
private _getConfiguredProxy(): string | undefined {
188+
return this._getLocalValue<string>(AgentHostProxyConfigKey.Proxy)?.trim() || undefined;
189+
}
190+
108191
/** The local user or default value, the layers the native request service reads for Kerberos tickets. */
109192
private _getLocalValue<T>(key: string): T | undefined {
110193
const { userLocalValue, defaultValue } = this._configurationService.inspect<T>(key);
111194
return userLocalValue ?? defaultValue;
112195
}
113196
}
114197

115-
function getUrlHost(url: string): string | undefined {
198+
function getProxyEndpoint(url: string): IProxyEndpoint | undefined {
116199
try {
117-
const { hostname } = new URL(url);
118-
return hostname ? hostname.replace(/^\[(.*)\]$/, '$1').toLowerCase() : undefined;
200+
const { protocol, hostname, port } = new URL(url);
201+
return hostname ? { hostname, port: Number(port) || (protocol === 'https:' ? 443 : 80) } : undefined;
119202
} catch {
120203
return undefined;
121204
}
122205
}
123206

124-
/** Hosts of the HTTP proxies in a PAC-style result such as `PROXY proxy:8080; DIRECT`. */
125-
function getResolvedProxyHosts(resolvedProxy: string | undefined): string[] {
207+
/** The environment's proxy, read like the native lookup reads it from the main process, which ignores case on Windows. */
208+
function getEnvironmentProxy(environment: IProcessEnvironment): string | undefined {
209+
const read = (name: string) => environment[isWindows ? Object.keys(environment).find(key => key.toUpperCase() === name.toUpperCase()) ?? name : name];
210+
return (read('https_proxy') || read('HTTPS_PROXY') || read('http_proxy') || read('HTTP_PROXY') || '').trim() || undefined;
211+
}
212+
213+
/** The HTTP proxies in a PAC-style result such as `PROXY proxy:8080; DIRECT`. */
214+
function getResolvedProxies(resolvedProxy: string | undefined): IProxyEndpoint[] {
126215
return (resolvedProxy ?? '').split(';').flatMap(entry => {
127-
const address = /^\s*(?:PROXY|HTTPS?)\s+(?<address>\S+)\s*$/i.exec(entry)?.groups?.address;
128-
const host = address && getUrlHost(`http://${address}`);
129-
return host ? [host] : [];
216+
const groups = /^\s*(?<type>PROXY|HTTPS?)\s+(?<address>\S+)\s*$/i.exec(entry)?.groups;
217+
const proxy = groups && getProxyEndpoint(`${groups.type.toUpperCase() === 'HTTPS' ? 'https' : 'http'}://${groups.address}`);
218+
return proxy ? [proxy] : [];
130219
});
131220
}

‎src/vs/platform/agentHost/browser/agentHostProtocolClient.ts‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,11 @@ import { AgentHostChannelError, AgentHostChannelErrorCode, reportAgentHostChanne
3737
import { AgentHostTcpBudget, AgentHostTcpConnection, agentHostTcpReceiveLimits, type IAgentHostTcpConnection } from '../common/agentHostTcpConnection.js';
3838
import { LoadClientCertificatesExtensionMethod, type IAgentHostClientCertificatesProvider } from '../common/clientCertificatesProtocol.js';
3939
import { AgentHostClientCertificatesCapabilityMetaKey } from '../common/meta/agentHostClientCertificatesMeta.js';
40-
import { ClientProxyChangedExtensionMethod, LookupClientProxyKerberosAuthorizationExtensionMethod, lookupClientProxyKerberosAuthorizationParamsValidator, ResolveClientProxyExtensionMethod, resolveClientProxyParamsValidator, type IAgentHostClientProxyProvider } from '../common/clientProxyProtocol.js';
40+
import { ClientProxyChangedExtensionMethod, LookupClientProxyBasicAuthorizationExtensionMethod, lookupClientProxyBasicAuthorizationParamsValidator, LookupClientProxyKerberosAuthorizationExtensionMethod, lookupClientProxyKerberosAuthorizationParamsValidator, ResolveClientProxyExtensionMethod, resolveClientProxyParamsValidator, type IAgentHostClientProxyProvider } from '../common/clientProxyProtocol.js';
4141
import { AgentHostClientProxyCapabilityMetaKey, servesAgentHostClientProxy } from '../common/meta/agentHostClientProxyMeta.js';
4242
import { localize } from '../../../nls.js';
4343
import { ILogService } from '../../log/common/log.js';
44+
import type { Credentials } from '../../request/common/request.js';
4445
import { FileSystemProviderErrorCode, toFileSystemProviderErrorCode } from '../../files/common/files.js';
4546
import { ConfigurationTarget, ConfigurationTargetToString, IConfigurationService } from '../../configuration/common/configuration.js';
4647
import { AgentPolicyError, type AgentExtensionMode, type AgentExtensionSource, type AgentExtensionStatus, IAgentCreateChatRequestOptions, IAgentCreateChatWorkspace, IAgentCreateSessionConfig, type IAgentExtensionInventory, IAgentResolveSessionConfigParams, IAgentSessionConfigCompletionsParams, IAgentSessionMetadata, AuthenticateParams, AuthenticateResult, IMcpNotification } from '../common/agent.js';
@@ -3435,6 +3436,26 @@ export class AgentHostProtocolClient extends Disposable implements IAgentConnect
34353436
sendResult({ authorization } satisfies IAgentHostExtensionServerCommandMap[typeof LookupClientProxyKerberosAuthorizationExtensionMethod]['result']);
34363437
return;
34373438
}
3439+
case LookupClientProxyBasicAuthorizationExtensionMethod: {
3440+
if (!this._clientProxy?.isEnabled()) {
3441+
throw new Error('This client does not provide proxy credentials for this agent host');
3442+
}
3443+
const { proxyUrl, realm, attempt } = lookupClientProxyBasicAuthorizationParamsValidator.validateOrThrow(params);
3444+
if (!isHttpUrl(proxyUrl)) {
3445+
throw new Error('Unsupported proxy URL');
3446+
}
3447+
if (!Number.isSafeInteger(attempt) || attempt < 1) {
3448+
throw new Error('Unsupported attempt');
3449+
}
3450+
let credentials: Credentials | undefined;
3451+
try {
3452+
credentials = await this._clientProxy.lookupBasicAuthorization(proxyUrl, realm, attempt);
3453+
} catch {
3454+
throw new Error('Proxy credential lookup failed');
3455+
}
3456+
sendResult((credentials ? { username: credentials.username, password: credentials.password } : {}) satisfies IAgentHostExtensionServerCommandMap[typeof LookupClientProxyBasicAuthorizationExtensionMethod]['result']);
3457+
return;
3458+
}
34383459
case ClientArtifactIntegrationExtensionMethod: {
34393460
const server = this._servedArtifactIntegrations;
34403461
if (!server || !isArtifactIntegrationRequest(params)) {

‎src/vs/platform/agentHost/common/agentHostExtensionProtocol.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
import { ValidatorBase, vArray, vBoolean, vEnum, vObj, vOptionalProp, vString, type ValidationError, type ValidatorType } from '../../../base/common/validation.js';
77
import { LoadClientCertificatesExtensionMethod, loadClientCertificatesResultValidator } from './clientCertificatesProtocol.js';
8-
import { ClientProxyChangedExtensionMethod, LookupClientProxyKerberosAuthorizationExtensionMethod, lookupClientProxyKerberosAuthorizationParamsValidator, lookupClientProxyKerberosAuthorizationResultValidator, ResolveClientProxyExtensionMethod, resolveClientProxyParamsValidator, resolveClientProxyResultValidator } from './clientProxyProtocol.js';
8+
import { ClientProxyChangedExtensionMethod, LookupClientProxyBasicAuthorizationExtensionMethod, lookupClientProxyBasicAuthorizationParamsValidator, lookupClientProxyBasicAuthorizationResultValidator, LookupClientProxyKerberosAuthorizationExtensionMethod, lookupClientProxyKerberosAuthorizationParamsValidator, lookupClientProxyKerberosAuthorizationResultValidator, ResolveClientProxyExtensionMethod, resolveClientProxyParamsValidator, resolveClientProxyResultValidator } from './clientProxyProtocol.js';
99
import type { IJSONSchema } from '../../../base/common/jsonSchema.js';
1010
import type { IDevContainerAgentHostConnectResult } from './devContainerAgentHost.js';
1111
import type { AgentExtensionMode, AgentExtensionSource, AgentExtensionStatus } from './agent.js';
@@ -423,6 +423,10 @@ export interface IAgentHostExtensionServerCommandMap {
423423
params: ValidatorType<typeof lookupClientProxyKerberosAuthorizationParamsValidator>;
424424
result: ValidatorType<typeof lookupClientProxyKerberosAuthorizationResultValidator>;
425425
};
426+
[LookupClientProxyBasicAuthorizationExtensionMethod]: {
427+
params: ValidatorType<typeof lookupClientProxyBasicAuthorizationParamsValidator>;
428+
result: ValidatorType<typeof lookupClientProxyBasicAuthorizationResultValidator>;
429+
};
426430
[RequestAgentHostWorkspaceTrustExtensionMethod]: {
427431
params: IAgentHostWorkspaceTrustRequest;
428432
result: { trusted: boolean };

‎src/vs/platform/agentHost/common/ahpJsonlLogger.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -440,6 +440,9 @@ function _ahpReplacer(this: unknown, _key: string, value: unknown): unknown {
440440
if (typeof value.authorization === 'string') {
441441
return { ...value, authorization: '<redacted>' };
442442
}
443+
if (typeof value.password === 'string') {
444+
return { ...value, password: '<redacted>' };
445+
}
443446
// Assisted permissions feedback is restricted telemetry, wherever a confirmation carries it.
444447
const redactedMeta = isRecord(value._meta) ? redactAgentPermissionFeedback(value._meta, REDACTED_PERMISSION_FEEDBACK) : undefined;
445448
if (redactedMeta) {

0 commit comments

Comments
 (0)