Skip to content

Commit ca72af3

Browse files
chrmartiCopilot
andcommitted
agentHost: recheck client forwarding after pending requests
Addresses the second review of the client forwarding: - Drops Git credentials a credential manager returns after forwarding was turned off, or after a session of the agent host turned sandboxing on, and copies no Git configuration a client returns after a session turned sandboxing on. - Closes forwarded connections when a session applies an enabled sandbox state, which changes its metadata without a configuration change. - Keeps automatic signing only when GnuPG with keys of its own, which it then uses instead of the client's agent, has the signing key. - Awaits the GPG key import before forwarding settles; connecting still does not wait for it. - Documents that turning the forwarding setting on applies to a Dev Container's next connection. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 9299c1a commit ca72af3

8 files changed

Lines changed: 73 additions & 24 deletions

File tree

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

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -134,14 +134,20 @@ export class AgentHostClientForwarding extends Disposable implements IAgentHostC
134134
}
135135

136136
async gitCredential(operation: ClientGitCredentialOperation, input: string): Promise<string> {
137-
return this._options.forwardCredentials() ? this._service.gitCredential(operation, input) : '';
137+
if (!this._options.forwardCredentials()) {
138+
return '';
139+
}
140+
const output = await this._service.gitCredential(operation, input);
141+
// Forwarding may have turned off while a credential manager signed in.
142+
return this._options.forwardCredentials() && !this._store.isDisposed ? output : '';
138143
}
139144

140145
async gpgKeys(): Promise<ClientGpgKeys> {
141146
return this._options.forwardCredentials() ? this._service.gpgKeys() : {};
142147
}
143148

144-
gitConfig(): Promise<ClientGitConfig> {
145-
return this._service.gitConfig(this._options.forwardCredentials(), this._options.folder);
149+
async gitConfig(): Promise<ClientGitConfig> {
150+
const gitConfig = await this._service.gitConfig(this._options.forwardCredentials(), this._options.folder);
151+
return this._options.forwardCredentials() || !gitConfig.gitGlobalConfig ? gitConfig : { user: gitConfig.user };
146152
}
147153
}

‎src/vs/platform/agentHost/node/agentHostClientForwarding.ts‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import { IAgentConfigurationService } from './agentConfigurationService.js';
2525
import { AgentHostStateManager, IAgentHostStateManager } from './agentHostStateManager.js';
2626
import { readChatSandboxStates, readSessionSandboxState } from '../common/meta/agentSandboxStateMeta.js';
2727
import { SessionConfigKey } from '../common/sessionConfigKeys.js';
28+
import { ActionType } from '../common/state/sessionActions.js';
2829
import { shellEscape } from './sshRemoteAgentHostHelpers.js';
2930

3031
/** Set to `1` by a launcher, e.g., for Dev Containers, to have the agent host forward what its clients offer. */
@@ -192,6 +193,12 @@ export class AgentHostClientForwardingService extends Disposable implements IAge
192193
};
193194
this._register(_configurationService.onDidSessionConfigChange(closeIfSandboxed));
194195
this._register(_configurationService.onDidChatConfigChange(closeIfSandboxed));
196+
// The sandbox state a session applies changes its metadata, without a configuration change.
197+
this._register(_stateManager.onDidEmitEnvelope(({ action }) => {
198+
if (action.type === ActionType.SessionMetaChanged) {
199+
closeIfSandboxed();
200+
}
201+
}));
195202
}
196203
}
197204

@@ -345,7 +352,9 @@ export class AgentHostClientForwardingService extends Disposable implements IAge
345352
try {
346353
// Without a client, Git asks its other helpers or the user.
347354
const output = client ? await client.client.gitCredential(content.operation, content.input) : '';
348-
response.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({ output }));
355+
// A session may have turned sandboxing on, or the client left, while a credential manager signed in.
356+
const allowed = !!client && this._clients.includes(client) && !this._store.isDisposed && !this._hasSandboxedSession();
357+
response.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({ output: allowed ? output : '' }));
349358
} catch (error) {
350359
this._logService.warn('[AgentHostClientForwarding] Git credential request failed', error);
351360
response.writeHead(502).end();
@@ -383,7 +392,12 @@ export class AgentHostClientForwardingService extends Disposable implements IAge
383392
// A sandboxed session gets only the identity, also where it shares the agent host with others.
384393
const offersConfig = description.gitConfig && !this._hasSandboxedSession();
385394
const agents = { sshAgent: description.sshAgent, gpgAgent: description.gpgAgent && !isWindows };
386-
await applyClientGitConfig(this._getGitConfigTarget(), offersConfig, agents, () => registered.client.gitConfig(), message => this._logService.info(`[AgentHostClientForwarding] ${message}`));
395+
const requestGitConfig = async (): Promise<ClientGitConfig> => {
396+
const gitConfig = await registered.client.gitConfig();
397+
// Also when a session turned sandboxing on while the client answered.
398+
return offersConfig && this._hasSandboxedSession() ? { user: gitConfig.user } : gitConfig;
399+
};
400+
await applyClientGitConfig(this._getGitConfigTarget(), offersConfig, agents, requestGitConfig, message => this._logService.info(`[AgentHostClientForwarding] ${message}`));
387401
} catch (error) {
388402
this._logService.warn('[AgentHostClientForwarding] Failed to apply the client\'s Git configuration', error);
389403
}
@@ -414,7 +428,8 @@ export class AgentHostClientForwardingService extends Disposable implements IAge
414428
if (plan.keyboxdSocket) {
415429
await this._listen('keyboxd', plan.keyboxdSocket, createServer(socket => this._forwardAgent(socket, 'keyboxd')));
416430
}
417-
// Only now, as importing would otherwise start an agent of its own. Not awaited, as only signing needs the keys.
431+
// Only now, as importing would otherwise start an agent of its own. Awaited, so the keys are there once settled, though
432+
// connecting does not wait for it.
418433
if ((plan.importKeys || plan.importOwnertrust) && !this._gpgImport) {
419434
const gpgImport = this._gpgImport = this._importGpgKeys(plan).catch(error => {
420435
this._logService.warn('[AgentHostClientForwarding] Failed to import GPG keys', error);
@@ -423,6 +438,7 @@ export class AgentHostClientForwardingService extends Disposable implements IAge
423438
this._gpgImport = undefined;
424439
}
425440
});
441+
await gpgImport;
426442
}
427443
}
428444

‎src/vs/platform/agentHost/node/clientGitConfig.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -259,14 +259,16 @@ export async function applyClientGitConfig(
259259
async function getSigningSupport(target: IClientGitConfigTarget, agents: IClientGitSigningAgents): Promise<IGitSigningSupport> {
260260
const homedir = parseGpgDirs((await target.run('gpgconf', ['--list-dirs']))?.stdout ?? '', isWindows).homedir;
261261
const ownKeys = !!homedir && (await readdir(join(homedir, 'private-keys-v1.d')).catch(() => [])).length > 0;
262-
return { sshAgent: agents.sshAgent, gpgSigning: !!homedir && (ownKeys || agents.gpgAgent) };
262+
return { sshAgent: agents.sshAgent, gpgSigning: !!homedir && (ownKeys || agents.gpgAgent), gpgOwnKeys: ownKeys };
263263
}
264264

265265
interface IGitSigningSupport {
266266
/** Whether the client's SSH agent is forwarded. */
267267
readonly sshAgent: boolean;
268268
/** Whether GPG signing can work, with the client's agent or the agent host's own keys. */
269269
readonly gpgSigning: boolean;
270+
/** Whether GnuPG has private keys of its own, in which case it uses them rather than the client's agent. */
271+
readonly gpgOwnKeys: boolean;
270272
}
271273

272274
/** Settings that run a program, which cannot work without it. */
@@ -340,6 +342,10 @@ async function removeUnavailableSigning(target: IClientGitConfigTarget, files: r
340342
// A private key file signs without an agent.
341343
available = await stat(path).then(stats => stats.isFile(), () => false) && (signing.sshAgent || !key.endsWith('.pub'));
342344
}
345+
} else if (available && format === 'openpgp' && signing.gpgOwnKeys) {
346+
// Git signs with the configured key, else one for the committer's email, which must then be one of its own.
347+
const key = await value('user.signingkey') || await value('user.email');
348+
available = !key || (await target.run(getCommandName(program), ['--list-secret-keys', '--with-colons', '--', key]))?.code === 0;
343349
} else if (available) {
344350
available = signing.gpgSigning;
345351
}

‎src/vs/platform/agentHost/node/serviceBootstrapping.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,9 +57,9 @@ The same clients, and remote-editor connections under the same `useHostProxy` ga
5757

5858
The Copilot runtime gets proxies from the Agent Host through the SDK's network callbacks rather than proxy environment variables, which would also apply to the tools it runs. The runtime resolves each request's proxy with the `network.resolveProxy` callback, which applies the Agent Host's proxy precedence above and passes on the full PAC-style list, so the runtime can fail over to the fallback proxies a client resolves. When none of `http.noProxy`, `http.proxy`, the proxy environment variables or a connected client decides, for example while no client is connected, or when system proxy discovery is disabled, the callback gives no answer, and the runtime resolves that proxy itself from the environment and the operating system's settings. A PAC-style answer cannot carry credentials, so the callback answers an `http.proxy` setting with credentials without them, and gives no answer for a proxy environment variable with credentials: the runtime inherits the proxy environment variables of the Agent Host unchanged and uses that one itself. The runtime gets Kerberos tokens through the `network.authenticateNegotiate` callback: this machine's ticket for exactly the principal the runtime requests, else one from a client sharing its network. It gets Basic proxy credentials through the `network.authenticateBasic` callback: on the first challenge for the proxy of an `http.proxy` setting with credentials, those of the setting, like the Agent Host's own requests, and after the proxy rejects them, those of the setting again only when they changed since; otherwise from a local renderer, which serves those of the `http.proxy` setting until the proxy rejects them, then its stored credentials or its proxy login dialog, else from a client sharing its network under the restrictions above. Each runtime keeps the credentials it was answered until the proxy rejects them, so after a rejection, the Agent Host first answers a client's current credentials, which a login dialog for another runtime may already have replaced, and asks the client for others only when the proxy rejected those: when the password changes, the runtimes of the local and a WSL Agent Host share one login dialog. Credentials are not written to the runtime's environment or disk. Clients connecting or leaving, or `http.proxy` and `http.noProxy` changing, don't restart the runtime.
5959

60-
An Agent Host its launcher starts with `VSCODE_AGENT_HOST_CLIENT_FORWARDING=1`, as the Dev Container launcher does, forwards what clients advertising the optional `vscode.clientForwarding` capability offer to the processes it starts, such as the Copilot runtime and terminals, like the Dev Containers extension forwards them into a container: the client machine's Git configuration and identity, Git credentials, SSH agent and GPG agent. Only such an Agent Host confirms the capability in its initialize result. Processes get their environment when they start, so it is set up once, when the Agent Host starts: the Agent Host listens on sockets in an owner-only folder, points `SSH_AUTH_SOCK` to its SSH socket, and appends a credential helper to the configuration Git reads from the environment after its files, `GIT_CONFIG_COUNT` or, before Git 2.31, `GIT_CONFIG_PARAMETERS`, so the configured helpers come first and a reset of the helper list in a file does not remove it. It asks each client what it offers with `vscode/forwarding/describe`; the newest client offering something serves it. A connection to the SSH socket goes to that client's agent, else to the agent the Agent Host had, else gets the answers of an agent without keys. The Git helper runs with the Agent Host's Node.js and gets credentials from that client through `vscode/forwarding/gitCredential`, which runs `git credential fill`, `approve` or `reject` in the client machine's shell environment; without a client or an answer, Git continues with its other helpers. For each connection to an agent, the Agent Host opens a client connection with `vscode/forwarding/open`; both sides then send the connection's data and closing as `vscode/forwarding/data` and `vscode/forwarding/close` notifications, which have no flow control, as agents exchange small messages. On Linux and macOS, while a client offers its GPG agent and unless GnuPG there has private keys of its own, the Agent Host listens on GnuPG's standard agent socket and, when the client uses `keyboxd`, on its `keyboxd` socket, enabling `keyboxd` without existing keyrings, and imports the client's public keys, certificates and owner trust from `vscode/forwarding/gpgKeys` once it listens, so no agent of its own starts; after a failed import, the next client retries it. All its processes share this environment, so while one of the Agent Host's sessions has terminal sandboxing on, it forwards none of its clients' agents and credentials: it closes open connections, its SSH socket answers as an agent without keys and the Git helper without credentials. Its protocol debug logs redact forwarded agent data, credentials and Git configuration.
60+
An Agent Host its launcher starts with `VSCODE_AGENT_HOST_CLIENT_FORWARDING=1`, as the Dev Container launcher does, forwards what clients advertising the optional `vscode.clientForwarding` capability offer to the processes it starts, such as the Copilot runtime and terminals, like the Dev Containers extension forwards them into a container: the client machine's Git configuration and identity, Git credentials, SSH agent and GPG agent. Only such an Agent Host confirms the capability in its initialize result. Processes get their environment when they start, so it is set up once, when the Agent Host starts: the Agent Host listens on sockets in an owner-only folder, points `SSH_AUTH_SOCK` to its SSH socket, and appends a credential helper to the configuration Git reads from the environment after its files, `GIT_CONFIG_COUNT` or, before Git 2.31, `GIT_CONFIG_PARAMETERS`, so the configured helpers come first and a reset of the helper list in a file does not remove it. It asks each client what it offers with `vscode/forwarding/describe`; the newest client offering something serves it. A connection to the SSH socket goes to that client's agent, else to the agent the Agent Host had, else gets the answers of an agent without keys. The Git helper runs with the Agent Host's Node.js and gets credentials from that client through `vscode/forwarding/gitCredential`, which runs `git credential fill`, `approve` or `reject` in the client machine's shell environment; without a client or an answer, Git continues with its other helpers. For each connection to an agent, the Agent Host opens a client connection with `vscode/forwarding/open`; both sides then send the connection's data and closing as `vscode/forwarding/data` and `vscode/forwarding/close` notifications, which have no flow control, as agents exchange small messages. On Linux and macOS, while a client offers its GPG agent and unless GnuPG there has private keys of its own, the Agent Host listens on GnuPG's standard agent socket and, when the client uses `keyboxd`, on its `keyboxd` socket, enabling `keyboxd` without existing keyrings, and imports the client's public keys, certificates and owner trust from `vscode/forwarding/gpgKeys` once it listens, so no agent of its own starts; after a failed import, the next client retries it. All its processes share this environment, so while one of the Agent Host's sessions has terminal sandboxing on, it forwards none of its clients' agents and credentials: it closes open connections, its SSH socket answers as an agent without keys and the Git helper without credentials, also for a request that was pending when sandboxing turned on. Its protocol debug logs redact forwarded agent data, credentials and Git configuration.
6161

62-
With `vscode/forwarding/gitConfig`, the Agent Host gets the Git identity the client uses for the workspace folder, following its conditional includes, and, from clients that offer it while none of its sessions is sandboxed, their global Git configuration and the files in their home folder that settings name, such as allowed signers. Like the Dev Containers extension, it copies the client's `~/.gitconfig` only where it has none or one with only `[filter]`, `[safe]` or `[user]` sections, and only once, marking the copy with a comment, and the client's XDG configuration only where it has none. It then removes from the copied files what cannot work there: editors and programs it lacks, a TLS backend, except on Windows, whose Git supports several, credential helpers whose commands it lacks (with their URL's reset of the helper list), and commit and tag signing that neither an agent the client forwards nor a key of its own supports. It sets the client's identity where it has none, and after copying, where the copy's differs because of the client folder's conditional includes or adds a second value. It asks the client only when there is something to do. It answers `initialize` once its environment is in place, waiting at most 10 seconds for its own startup but not for clients: the Git configuration follows in the background. Relay connections never forward.
62+
With `vscode/forwarding/gitConfig`, the Agent Host gets the Git identity the client uses for the workspace folder, following its conditional includes, and, from clients that offer it while none of its sessions is sandboxed, also when the client answers, their global Git configuration and the files in their home folder that settings name, such as allowed signers. Like the Dev Containers extension, it copies the client's `~/.gitconfig` only where it has none or one with only `[filter]`, `[safe]` or `[user]` sections, and only once, marking the copy with a comment, and the client's XDG configuration only where it has none. It then removes from the copied files what cannot work there: editors and programs it lacks, a TLS backend, except on Windows, whose Git supports several, credential helpers whose commands it lacks (with their URL's reset of the helper list), and commit and tag signing that neither an agent the client forwards nor a key of its own supports; GnuPG with keys of its own does not use the client's agent, so the signing key must then be one of them. It sets the client's identity where it has none, and after copying, where the copy's differs because of the client folder's conditional includes or adds a second value. It asks the client only when there is something to do. It answers `initialize` once its environment is in place, waiting at most 10 seconds for its own startup but not for clients: the Git configuration follows in the background. Relay connections never forward.
6363

6464
The foundation loads persisted session storage identities before constructing `SessionDataService` or any provider. The orchestrator and per-session storage boundaries share that codec and retain foundation ownership.
6565

‎src/vs/platform/agentHost/test/browser/agentHostClientForwarding.test.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import type { IAgentHostClientForwardingMainService } from '../../common/agentHo
1313
suite('AgentHostClientForwarding', () => {
1414
const store = ensureNoDisposablesAreLeakedInTestSuite();
1515

16-
test('turning forwarding off closes open agent connections and then forwards only the identity', async () => {
16+
test('turning forwarding off drops a pending credential, closes open agent connections and then forwards only the identity', async () => {
1717
const onDidChangeForwardCredentials = store.add(new Emitter<void>());
1818
const calls: string[] = [];
1919
const service: IAgentHostClientForwardingMainService = {
@@ -28,7 +28,11 @@ suite('AgentHostClientForwarding', () => {
2828
close: async () => {
2929
calls.push('close');
3030
},
31-
gitCredential: async () => 'password=secret\n',
31+
gitCredential: async () => {
32+
// Turned off while a credential manager signs in.
33+
forward = false;
34+
return 'password=secret\n';
35+
},
3236
gpgKeys: async () => ({ ownertrust: 'dHJ1c3Q=' }),
3337
gitConfig: async full => ({ user: { name: full ? 'With configuration' : 'Identity only' } }),
3438
};
@@ -42,9 +46,10 @@ suite('AgentHostClientForwarding', () => {
4246
connection.dispose();
4347
}));
4448

45-
forward = false;
49+
const pendingGitCredential = await forwarding.gitCredential('get', 'host=example.com\n');
4650
onDidChangeForwardCredentials.fire();
4751
assert.deepStrictEqual({
52+
pendingGitCredential,
4853
closed,
4954
calls,
5055
describe: await forwarding.describe(),
@@ -53,6 +58,7 @@ suite('AgentHostClientForwarding', () => {
5358
gpgKeys: await forwarding.gpgKeys(),
5459
gitConfig: await forwarding.gitConfig(),
5560
}, {
61+
pendingGitCredential: '',
5662
closed: true,
5763
calls: ['open ssh-agent', 'close'],
5864
describe: { gitConfig: false, gitCredentials: false, sshAgent: false, gpgAgent: false, keyboxd: false },

0 commit comments

Comments
 (0)