From a249dda0f83b0255bb7f8fba463400fad16a0430 Mon Sep 17 00:00:00 2001 From: Tyler Leonhardt Date: Wed, 25 Nov 2026 14:28:07 -0800 Subject: [PATCH 1/4] agentHost: forward the authentication ID token and learn the tenant Forward the Microsoft session's ID token on authenticate, using the optional idToken field from microsoft/agent-host-protocol#631. The host keeps it with the accepted credential, replays it, and redacts it from AHP logs. The Entra bridge reads the unverified tid claim from the first ID token sent for the account and keeps it with the account. Nothing is handed to the runtime yet: the identity result that carries the tenant is left as a TODO until the SDK accepts it. Sync the protocol copy with idToken as a targeted backport on the current pin. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/vs/platform/agentHost/AGENTS.md | 2 + src/vs/platform/agentHost/common/agent.ts | 2 + .../agentHost/common/ahpJsonlLogger.ts | 17 +++++-- .../platform/agentHost/common/state/AGENTS.md | 2 +- .../common/state/protocol/common/commands.ts | 9 ++++ .../node/agentHostAuthenticationService.ts | 8 ++++ .../copilot/copilotEntraAuthentication.ts | 42 +++++++++++++--- .../test/common/ahpJsonlLogger.test.ts | 6 +++ .../node/copilotEntraAuthentication.test.ts | 48 ++++++++++++++++++- .../agentSessions/agentHost/agentHostAuth.ts | 4 ++ .../copilotEntraAuthentication.test.ts | 8 ++++ 11 files changed, 137 insertions(+), 11 deletions(-) diff --git a/src/vs/platform/agentHost/AGENTS.md b/src/vs/platform/agentHost/AGENTS.md index 88f4b4ad4a0cf0..867561042ef463 100644 --- a/src/vs/platform/agentHost/AGENTS.md +++ b/src/vs/platform/agentHost/AGENTS.md @@ -815,6 +815,8 @@ Applies only when the host started with `copilotM365EnabledAtStartup` on. Easy t - **GitHub and Microsoft are advertised as optional.** A user needs one of them, not both, so each is `required: false`. That only stops a client from blocking on one of them; a session still cannot run without a credential. - **The host is bound to one Microsoft account.** It knows the account only by the `authenticate.accountId` of the first accepted credential: a client does not send a display name and the host does not give the runtime one. It rejects a token with a different ID instead of switching. The ID is compared as given across clients, so every client must send the same value for the same account; this keeps the host consistent and does not isolate clients from each other. +- **Identity claims come from the ID Token.** A client may send `authenticate.idToken` with a credential; the host keeps it with the accepted token, replays it, and returns it from `getAuthCredential`. Read claims such as the tenant from it, never from the access token, which only its resource can read, or from `accountId`, which is opaque. A client that sends none leaves the host without those claims. +- **The tenant is learned once and kept with the account.** The bridge reads the unverified `tid` claim from the first ID Token sent with a discovery credential for the account, and keeps it even when a later credential arrives without one. The runtime is not given it yet. - **The SDK's token callback never waits.** It returns the stored token or `unavailable`, which means "no token right now", not "this user has no access". - **A client disconnecting is not a sign-out.** Tokens the host accepted survive the last client leaving. As with GitHub, any client can withdraw them: the host then advertises the missing credential, unless a GitHub credential is there to return to, so a client that is still signed in can re-supply it, and restarts the runtime once running turns finish. - **Clients may re-send a challenged token.** The host refuses the token the runtime most recently rejected for a resource, but it does not remember earlier ones. diff --git a/src/vs/platform/agentHost/common/agent.ts b/src/vs/platform/agentHost/common/agent.ts index e7ee55480149a4..1764f8fcdd3c0e 100644 --- a/src/vs/platform/agentHost/common/agent.ts +++ b/src/vs/platform/agentHost/common/agent.ts @@ -838,6 +838,8 @@ export interface AuthenticateParams { readonly target?: AuthenticateTarget; /** Unverified client-local account selection, stable across token renewals. */ readonly accountId?: string; + /** The OpenID Connect ID Token issued with `token`. Its claims are unverified, and it is never a bearer credential. */ + readonly idToken?: string; /** Optional client metadata. Hosts must remain usable when it is absent. */ readonly _meta?: Record; } diff --git a/src/vs/platform/agentHost/common/ahpJsonlLogger.ts b/src/vs/platform/agentHost/common/ahpJsonlLogger.ts index 53995ad9388a40..898f7cdf1e6a9a 100644 --- a/src/vs/platform/agentHost/common/ahpJsonlLogger.ts +++ b/src/vs/platform/agentHost/common/ahpJsonlLogger.ts @@ -428,6 +428,15 @@ function stringifyAhpLogEntryTruncated(value: unknown, maxStringLength: number): }); } +/** Replaces the access token and ID Token of `authenticate` params, or returns `undefined` when neither needs it. */ +function redactAuthenticationParams(params: Record): Record | undefined { + const hasToken = params.token !== undefined && params.token !== '' && params.token !== '[REDACTED]'; + const hasIdToken = params.idToken !== undefined && params.idToken !== ''; + return hasToken || hasIdToken + ? { ...params, ...(hasToken ? { token: '' } : {}), ...(hasIdToken ? { idToken: '' } : {}) } + : undefined; +} + /** * JSON.stringify replacer that converts URI values to their canonical string * form. `URI.prototype.toJSON()` runs before this replacer is invoked and @@ -455,9 +464,11 @@ function _ahpReplacer(this: unknown, _key: string, value: unknown): unknown { if (isRecord(value.result) && Array.isArray(value.result.certificates)) { return { ...value, result: { ...value.result, certificates: '' } }; } - if (value.method === 'authenticate' && isRecord(value.params) && value.params.token !== undefined - && value.params.token !== '' && value.params.token !== '[REDACTED]') { - return { ...value, params: { ...value.params, token: '' } }; + if (value.method === 'authenticate' && isRecord(value.params)) { + const redacted = redactAuthenticationParams(value.params); + if (redacted) { + return { ...value, params: redacted }; + } } if (value.method === RegisterGitHubEnvironmentExtensionMethod && isRecord(value.params) && value.params.credential !== undefined && value.params.credential !== '') { diff --git a/src/vs/platform/agentHost/common/state/AGENTS.md b/src/vs/platform/agentHost/common/state/AGENTS.md index 226b3fded16cf8..7bc59cd4e07719 100644 --- a/src/vs/platform/agentHost/common/state/AGENTS.md +++ b/src/vs/platform/agentHost/common/state/AGENTS.md @@ -29,7 +29,7 @@ The generated protocol includes the Changesets model: ### Current targeted backports -The generated copy uses the `.ahp-version` source commit `d7a5579b` plus targeted source backports for MCP-served skills and optional `AuthenticateParams.accountId`. The account field matches the merged [microsoft/agent-host-protocol#583](https://github.com/microsoft/agent-host-protocol/pull/583) at `eea267f02b9b031aebe6abea12a4e80927da2493`. Preserve these deltas when syncing until the recorded pin includes them. The older `CreateChatParams.title`, deprecated `SessionChatSummary.archived`, and `ChatIsReadChanged` compatibility deltas are already present in this pin. +The generated copy uses the `.ahp-version` source commit `1928cd4e` plus one targeted source backport: optional `AuthenticateParams.idToken`. The field matches the merged [microsoft/agent-host-protocol#631](https://github.com/microsoft/agent-host-protocol/pull/631) at `c6388ccce7c78066f8f9982fcaef0e62bd20bd01`. Preserve this delta when syncing until the recorded pin includes it. The older `CreateChatParams.title`, deprecated `SessionChatSummary.archived`, and `ChatIsReadChanged` compatibility deltas are already present in this pin. For a narrow sync, set `AHP_PROTOCOL_REPO` to an isolated protocol source worktree at the recorded pin with those source backports applied, then run the normal sync script. Do not copy unrelated upstream changes or edit generated files to recover the existing deltas. diff --git a/src/vs/platform/agentHost/common/state/protocol/common/commands.ts b/src/vs/platform/agentHost/common/state/protocol/common/commands.ts index 0b895d79c6e967..affeea8fe91992 100644 --- a/src/vs/platform/agentHost/common/state/protocol/common/commands.ts +++ b/src/vs/platform/agentHost/common/state/protocol/common/commands.ts @@ -1554,6 +1554,15 @@ export interface AuthenticateParams extends BaseParams { * @minLength 1 */ accountId?: string; + /** + * Optional OpenID Connect ID Token issued with `token`, forwarded unchanged + * (`id_token` in an OpenID Connect token response). Lets the host read + * identity claims that the opaque access token and `accountId` do not expose. + * see {@link /specification/authentication#id-tokens | ID tokens}. + * + * @minLength 1 + */ + idToken?: string; } /** diff --git a/src/vs/platform/agentHost/node/agentHostAuthenticationService.ts b/src/vs/platform/agentHost/node/agentHostAuthenticationService.ts index 1c67aeee951833..f45b5468ee9eb2 100644 --- a/src/vs/platform/agentHost/node/agentHostAuthenticationService.ts +++ b/src/vs/platform/agentHost/node/agentHostAuthenticationService.ts @@ -28,6 +28,8 @@ export interface IAgentHostAuthCredential { readonly token: string; readonly scopes: readonly string[]; readonly accountId?: string; + /** The ID Token the client sent with this token, for reading identity claims the access token keeps opaque. */ + readonly idToken?: string; readonly expiresAt: number | undefined; } @@ -172,6 +174,7 @@ export class AgentHostAuthenticationService extends Disposable implements IAgent resource: credential.resource, token: credential.token, scopes: normalizeAuthenticationScopes(credential.scopes ?? metadata.scopes_supported), expiresAt, accountId: credential.accountId, + ...(credential.idToken !== undefined ? { idToken: credential.idToken } : {}), }); } this._hostExecutionCredentials = stored; @@ -186,6 +189,9 @@ export class AgentHostAuthenticationService extends Disposable implements IAgent if (params.accountId !== undefined && (typeof params.accountId !== 'string' || params.accountId.length === 0)) { throw new ProtocolError(JsonRpcErrorCodes.InvalidParams, 'accountId must be a nonempty string'); } + if (params.idToken !== undefined && (typeof params.idToken !== 'string' || params.idToken.length === 0)) { + throw new ProtocolError(JsonRpcErrorCodes.InvalidParams, 'idToken must be a nonempty string'); + } const providerList = [...providers]; if (scope) { const resources = [ @@ -305,6 +311,7 @@ export class AgentHostAuthenticationService extends Disposable implements IAgent this._tokens.set(key, { resource: params.resource, scopes, token: params.token, expiresAt, accountId: params.accountId, clientId, ...selection, ...(params.target ? { target: params.target } : {}), + ...(params.idToken !== undefined ? { idToken: params.idToken } : {}), }); } if (!params.target && this.useLocalCredentials) { @@ -366,6 +373,7 @@ export class AgentHostAuthenticationService extends Disposable implements IAgent resource: stored.resource, scopes: stored.scopes, token: stored.token, expiresIn, ...(stored.target ? { target: stored.target } : {}), ...(stored.accountId !== undefined ? { accountId: stored.accountId } : {}), + ...(stored.idToken !== undefined ? { idToken: stored.idToken } : {}), }; if (!stored.target && protectedResources.has(stored.resource)) { try { diff --git a/src/vs/platform/agentHost/node/copilot/copilotEntraAuthentication.ts b/src/vs/platform/agentHost/node/copilot/copilotEntraAuthentication.ts index 1265a5b87e2efd..7a87e9d5630752 100644 --- a/src/vs/platform/agentHost/node/copilot/copilotEntraAuthentication.ts +++ b/src/vs/platform/agentHost/node/copilot/copilotEntraAuthentication.ts @@ -9,6 +9,7 @@ import { CancellationToken } from '../../../../base/common/cancellation.js'; import { isExpired } from '../../../../base/common/date.js'; import { Emitter } from '../../../../base/common/event.js'; import { Disposable, toDisposable } from '../../../../base/common/lifecycle.js'; +import { getClaimsFromJWT } from '../../../../base/common/oauth.js'; import { derived, observableValue, transaction, type IReader } from '../../../../base/common/observable.js'; import type { AuthenticateParams } from '../../common/agent.js'; import { copilotEntraAuthorizationServer, copilotEntraClientId, copilotEntraDiscoveryResource, copilotEntraResources } from '../../common/copilotEntraAuthentication.js'; @@ -17,7 +18,7 @@ import { AhpErrorCodes, ProtocolError } from '../../common/state/sessionProtocol import type { ProtectedResourceMetadata } from '../../common/state/protocol/state.js'; import { IAgentHostAuthenticationService, type IAgentHostAuthCredential } from '../agentHostAuthenticationService.js'; -interface IEntraAuthority { +export interface IEntraAuthority { /** * The `authenticate.accountId` of the first accepted discovery credential. Unlike the per-client GitHub * comparison, it is compared as given across clients and Microsoft resources, because one Microsoft account @@ -26,6 +27,8 @@ interface IEntraAuthority { * and is not a boundary between clients, which share these credentials and can replace them. */ readonly accountId: string; + /** The unverified `tid` claim of the first ID Token a client sent for the account. */ + readonly tenantId: string | undefined; } interface IEntraTokenChallenge { @@ -65,11 +68,9 @@ export class CopilotEntraAuthentication extends Disposable { })); if (this._authenticationService.onDidAuthenticate) { this._register(this._authenticationService.onDidAuthenticate(request => { - if (request.resource === copilotEntraDiscoveryResource && !this._authority.get()) { - const accountId = this._authenticationService.getAuthCredential({ resource: copilotEntraDiscoveryResource, scopes: copilotEntraDiscoveryMetadata.scopes_supported })?.accountId; - if (accountId) { - this._authority.set({ accountId }, undefined); - } + if (request.resource === copilotEntraDiscoveryResource) { + const credential = this._authenticationService.getAuthCredential({ resource: copilotEntraDiscoveryResource, scopes: copilotEntraDiscoveryMetadata.scopes_supported }); + this._authority.set(acceptEntraDiscoveryCredential(this._authority.get(), credential), undefined); } if (this.getCredential(request.resource, request.scopes ?? [])) { this._requirements.set(this._requirements.get().filter(requirement => requirement.resource.resource !== request.resource), undefined); @@ -291,9 +292,38 @@ function resolveEntraIdentity(request: Extract | undefined): IEntraAuthority | undefined { + if (!credential?.accountId) { + return authority; + } + if (!authority) { + return { accountId: credential.accountId, tenantId: readTenantId(credential.idToken) }; + } + if (authority.tenantId || authority.accountId !== credential.accountId) { + return authority; + } + const tenantId = readTenantId(credential.idToken); + return tenantId ? { ...authority, tenantId } : authority; +} + +function readTenantId(idToken: string | undefined): string | undefined { + if (!idToken) { + return undefined; + } + try { + const { tid } = getClaimsFromJWT(idToken); + return typeof tid === 'string' && tid.trim() ? tid : undefined; + } catch { + return undefined; + } +} + export function copilotEntraResourceForRequest(request: EntraTokenProviderArgs): ProtectedResourceMetadata | undefined { if (request.kind === 'identity') { return copilotEntraDiscoveryMetadata; diff --git a/src/vs/platform/agentHost/test/common/ahpJsonlLogger.test.ts b/src/vs/platform/agentHost/test/common/ahpJsonlLogger.test.ts index e6a128573e4ec6..3d107e29849249 100644 --- a/src/vs/platform/agentHost/test/common/ahpJsonlLogger.test.ts +++ b/src/vs/platform/agentHost/test/common/ahpJsonlLogger.test.ts @@ -487,6 +487,12 @@ suite('AhpJsonlLogger', () => { })).params.token), ['', '[REDACTED]']); }); + test('redacts an authentication ID token, also when the access token was redacted upstream', () => { + assert.deepStrictEqual(['private-token', '[REDACTED]'].map(token => JSON.parse(stringifyAhpLogEntry({ + method: 'authenticate', params: { token, idToken: 'private-id-token' }, + })).params), [{ token: '', idToken: '' }, { token: '[REDACTED]', idToken: '' }]); + }); + test('coalesces synchronously queued log calls into a single write', async () => { const fileService = store.add(new FileService(new NullLogService())); const provider = store.add(new RecordingInMemoryFileSystemProvider()); diff --git a/src/vs/platform/agentHost/test/node/copilotEntraAuthentication.test.ts b/src/vs/platform/agentHost/test/node/copilotEntraAuthentication.test.ts index 9a123da924c1f1..4d10344ccdcf60 100644 --- a/src/vs/platform/agentHost/test/node/copilotEntraAuthentication.test.ts +++ b/src/vs/platform/agentHost/test/node/copilotEntraAuthentication.test.ts @@ -6,6 +6,7 @@ import assert from 'assert'; import type { EntraTokenProvider, EntraTokenProviderArgs } from '@microsoft/copilot-sdk'; import { DeferredPromise, timeout } from '../../../../base/common/async.js'; +import { encodeBase64, VSBuffer } from '../../../../base/common/buffer.js'; import { CancellationToken, CancellationTokenSource } from '../../../../base/common/cancellation.js'; import { autorun } from '../../../../base/common/observable.js'; import { mock } from '../../../../base/test/common/mock.js'; @@ -17,7 +18,7 @@ import { copilotEntraAuthorizationServer, copilotEntraClientId, copilotEntraDisc import { AuthRequiredReason } from '../../common/state/sessionActions.js'; import { AuthenticateTargetKind } from '../../common/state/sessionProtocol.js'; import { AgentHostAuthenticationService } from '../../node/agentHostAuthenticationService.js'; -import { CopilotEntraAuthentication, copilotEntraDiscoveryMetadata } from '../../node/copilot/copilotEntraAuthentication.js'; +import { acceptEntraDiscoveryCredential, CopilotEntraAuthentication, copilotEntraDiscoveryMetadata } from '../../node/copilot/copilotEntraAuthentication.js'; suite('Copilot Entra authentication', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); @@ -160,6 +161,51 @@ suite('Copilot Entra authentication', () => { assert.deepStrictEqual(replayed, [{ accountId: 'selected', metadata: undefined }]); }); + test('the discovery credential keeps its ID token for the host and through replay', async () => { + const f = fixture(); + await f.acquire(identity); + await assert.rejects(f.authenticate({ ...f.credential(), idToken: '' }), /idToken must be a nonempty string/); + await f.authenticate({ ...f.credential(), idToken: 'synthetic-id-token' }); + const replayed: (string | undefined)[] = []; + await f.authentication.replay(new class extends mock() { + override getProtectedResources() { return []; } + override async handleAuthenticationToken(params: AuthenticateParams) { + replayed.push(params.idToken); + return true; + } + }()); + assert.deepStrictEqual({ + stored: f.authentication.getAuthCredential({ resource: copilotEntraDiscoveryResource, scopes: ['User.Read'] })?.idToken, + replayed, + }, { stored: 'synthetic-id-token', replayed: ['synthetic-id-token'] }); + }); + + test('the first discovery credential fixes the account, and its tenant is learned once from an ID token', () => { + const idToken = (claims: unknown) => `${encodeBase64(VSBuffer.fromString('{}'))}.${encodeBase64(VSBuffer.fromString(JSON.stringify(claims)))}.signature`; + const tenant = { accountId: 'selected', idToken: idToken({ tid: 'tenant' }) }; + const withoutTenant = { accountId: 'selected', tenantId: undefined }; + const withTenant = { accountId: 'selected', tenantId: 'tenant' }; + assert.deepStrictEqual({ + first: acceptEntraDiscoveryCredential(undefined, tenant), + unreadable: [undefined, 'not-a-jwt', idToken({}), idToken({ tid: ' ' }), idToken({ tid: 7 }), idToken(null)] + .map(idToken => acceptEntraDiscoveryCredential(undefined, { accountId: 'selected', idToken })), + learnedLater: acceptEntraDiscoveryCredential(withoutTenant, tenant), + kept: [ + acceptEntraDiscoveryCredential(withTenant, { accountId: 'selected', idToken: idToken({ tid: 'other-tenant' }) }), + acceptEntraDiscoveryCredential(withTenant, { accountId: 'selected' }), + acceptEntraDiscoveryCredential(withoutTenant, { accountId: 'other', idToken: tenant.idToken }), + acceptEntraDiscoveryCredential(withTenant, undefined), + ], + noAccount: acceptEntraDiscoveryCredential(undefined, { idToken: tenant.idToken }), + }, { + first: withTenant, + unreadable: new Array(6).fill(withoutTenant), + learnedLater: withTenant, + kept: [withTenant, withTenant, withoutTenant, withTenant], + noAccount: undefined, + }); + }); + for (const audience of [copilotEntraEmuAudience, copilotEntraM365Audience]) { test(`returns unavailable without revocation, then consumes a later credential for ${audience}`, async () => { const f = fixture(); diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostAuth.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostAuth.ts index 7f8e240e1583f2..dbc7e095ce2627 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostAuth.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostAuth.ts @@ -721,6 +721,8 @@ export interface IAgentHostAuthenticateRequest { /** The access token's remaining lifetime in seconds, when known. */ readonly expiresIn?: number; readonly accountId?: string; + /** The ID Token the provider issued with the access token, forwarded unchanged. */ + readonly idToken?: string; readonly _meta?: Record; } @@ -749,6 +751,7 @@ interface IForwardedAuthenticationSession { readonly id?: string; readonly account?: AuthenticationSession['account']; readonly authorizationServer?: URI; + readonly idToken?: string; } function resolveAuthenticationOptions(accessor: ServicesAccessor, options: IAgentHostAuthenticationOptions): IResolvedAgentHostAuthenticationOptions { @@ -825,6 +828,7 @@ export function toAuthenticateRequest( token: session?.accessToken ?? '', ...(expiresAfter !== undefined && Number.isInteger(expiresAfter) && expiresAfter > 0 ? { expiresIn: Math.ceil(expiresAfter / 1000) } : {}), ...(accountId !== undefined ? { accountId } : {}), + ...(session?.idToken ? { idToken: session.idToken } : {}), ...(entitlement ? { _meta: agentEntitlementHintMeta(entitlement) } : {}), }; } diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/copilotEntraAuthentication.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/copilotEntraAuthentication.test.ts index e62d0d15eee083..e601edfb297f06 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/copilotEntraAuthentication.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/copilotEntraAuthentication.test.ts @@ -122,6 +122,14 @@ suite('Agent Host Microsoft credential acquisition', () => { }); }); + test('forwards the ID token of a session that has one', async () => { + const f = fixture(); + f.authentication.sessions = [{ ...selected, idToken: 'synthetic-id-token' }]; + assert.deepStrictEqual(await f.resolve(), { + resource: resource.resource, scopes: ['User.Read'], token: selected.accessToken, accountId: '["microsoft","selected",null]', idToken: 'synthetic-id-token', + }); + }); + test('does not substitute another account or its display label for a missing default identity', async () => { const f = fixture(); const credentials = []; From c694a7ae8197707972a827f42fc73e6b3936c687 Mon Sep 17 00:00:00 2001 From: Tyler Leonhardt Date: Wed, 25 Nov 2026 14:47:00 -0800 Subject: [PATCH 2/4] agentHost: keep the ID token off sealed connections and track the accepted credential Drop the ID token wherever the access token is sealed, since only the token can be sealed and a relay would otherwise read its claims. Learn the tenant from the discovery credential that was just accepted, not from an older credential stored under the advertised scopes. Include the ID token in the client's forwarded-credential key, so one that becomes available for an unchanged access token still reaches the host. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/vs/platform/agentHost/AGENTS.md | 2 +- .../agentHost/browser/agentHostProtocolClient.ts | 9 +++++++-- .../node/copilot/copilotEntraAuthentication.ts | 6 ++++-- .../agentHostProtocolClient.test.ts | 16 ++++++++++++++++ .../agentSessions/agentHost/agentHostAuth.ts | 8 ++++---- .../copilotEntraAuthentication.test.ts | 13 +++++++++++++ 6 files changed, 45 insertions(+), 9 deletions(-) diff --git a/src/vs/platform/agentHost/AGENTS.md b/src/vs/platform/agentHost/AGENTS.md index 867561042ef463..b1b738694e9816 100644 --- a/src/vs/platform/agentHost/AGENTS.md +++ b/src/vs/platform/agentHost/AGENTS.md @@ -815,7 +815,7 @@ Applies only when the host started with `copilotM365EnabledAtStartup` on. Easy t - **GitHub and Microsoft are advertised as optional.** A user needs one of them, not both, so each is `required: false`. That only stops a client from blocking on one of them; a session still cannot run without a credential. - **The host is bound to one Microsoft account.** It knows the account only by the `authenticate.accountId` of the first accepted credential: a client does not send a display name and the host does not give the runtime one. It rejects a token with a different ID instead of switching. The ID is compared as given across clients, so every client must send the same value for the same account; this keeps the host consistent and does not isolate clients from each other. -- **Identity claims come from the ID Token.** A client may send `authenticate.idToken` with a credential; the host keeps it with the accepted token, replays it, and returns it from `getAuthCredential`. Read claims such as the tenant from it, never from the access token, which only its resource can read, or from `accountId`, which is opaque. A client that sends none leaves the host without those claims. +- **Identity claims come from the ID Token.** A client may send `authenticate.idToken` with a credential; the host keeps it with the accepted token, replays it, and returns it from `getAuthCredential`. Read claims such as the tenant from it, never from the access token, which only its resource can read, or from `accountId`, which is opaque. A client that sends none leaves the host without those claims, and VS Code sends none on a connection that seals the token, because only the token can be sealed. - **The tenant is learned once and kept with the account.** The bridge reads the unverified `tid` claim from the first ID Token sent with a discovery credential for the account, and keeps it even when a later credential arrives without one. The runtime is not given it yet. - **The SDK's token callback never waits.** It returns the stored token or `unavailable`, which means "no token right now", not "this user has no access". - **A client disconnecting is not a sign-out.** Tokens the host accepted survive the last client leaving. As with GitHub, any client can withdraw them: the host then advertises the missing credential, unless a GitHub credential is there to return to, so a client that is still signed in can re-supply it, and restarts the runtime once running turns finish. diff --git a/src/vs/platform/agentHost/browser/agentHostProtocolClient.ts b/src/vs/platform/agentHost/browser/agentHostProtocolClient.ts index 4af0c49dc82c6c..963f695e15cd0f 100644 --- a/src/vs/platform/agentHost/browser/agentHostProtocolClient.ts +++ b/src/vs/platform/agentHost/browser/agentHostProtocolClient.ts @@ -2796,9 +2796,14 @@ export class AgentHostProtocolClient extends Disposable implements IAgentConnect } private _encryptAuthentication(params: CommandMap['authenticate']['params']): CommandMap['authenticate']['params'] | Promise { - if (!params.token || params.token.startsWith('copilot-sealed.')) { + if (!params.token) { return params; } + // Only the token can be sealed, so the ID Token is dropped wherever the token is sealed. + const { idToken: _idToken, ...sealable } = params; + if (params.token.startsWith('copilot-sealed.')) { + return sealable; + } try { const value = this.rootState.value; const root = value instanceof Error ? undefined : value; @@ -2814,7 +2819,7 @@ export class AgentHostProtocolClient extends Disposable implements IAgentConnect if (this._isWebPubSubRelay() && !this._trustedAuthenticationTokenSealer) { throw new Error('Relay credentials must be sealed using an independently trusted recipient key.'); } - return this._sealAuthentication(params, encryption); + return this._sealAuthentication(sealable, encryption); } catch (error) { throw new AuthenticationEncryptionError(getErrorMessage(error)); } diff --git a/src/vs/platform/agentHost/node/copilot/copilotEntraAuthentication.ts b/src/vs/platform/agentHost/node/copilot/copilotEntraAuthentication.ts index 7a87e9d5630752..bfb610672e1178 100644 --- a/src/vs/platform/agentHost/node/copilot/copilotEntraAuthentication.ts +++ b/src/vs/platform/agentHost/node/copilot/copilotEntraAuthentication.ts @@ -69,8 +69,10 @@ export class CopilotEntraAuthentication extends Disposable { if (this._authenticationService.onDidAuthenticate) { this._register(this._authenticationService.onDidAuthenticate(request => { if (request.resource === copilotEntraDiscoveryResource) { - const credential = this._authenticationService.getAuthCredential({ resource: copilotEntraDiscoveryResource, scopes: copilotEntraDiscoveryMetadata.scopes_supported }); - this._authority.set(acceptEntraDiscoveryCredential(this._authority.get(), credential), undefined); + const credential = this._authenticationService.getAuthCredential(request); + if (credential && copilotEntraDiscoveryMetadata.scopes_supported?.every(scope => credential.scopes.includes(scope))) { + this._authority.set(acceptEntraDiscoveryCredential(this._authority.get(), credential), undefined); + } } if (this.getCredential(request.resource, request.scopes ?? [])) { this._requirements.set(this._requirements.get().filter(requirement => requirement.resource.resource !== request.resource), undefined); diff --git a/src/vs/platform/agentHost/test/electron-browser/agentHostProtocolClient.test.ts b/src/vs/platform/agentHost/test/electron-browser/agentHostProtocolClient.test.ts index f5cf9d48e99334..add6b40b64af39 100644 --- a/src/vs/platform/agentHost/test/electron-browser/agentHostProtocolClient.test.ts +++ b/src/vs/platform/agentHost/test/electron-browser/agentHostProtocolClient.test.ts @@ -1923,6 +1923,22 @@ suite('AgentHostProtocolClient', () => { }); }); + test('omits the ID token wherever the token is sealed, and sends it on an unencrypted connection', async () => { + const sealing = createClient(); + disposables.add(sealing.client.registerAuthenticationTokenSealer(async request => `copilot-sealed.v1.${request.key.key_id}.ciphertext`)); + await initialize(sealing.client, sealing.transport); + const sealed = await acknowledgeAuthentication(sealing.transport, sealing.client.authenticate({ resource, token: 'provider-token', idToken: 'id-token' })); + const alreadySealed = await acknowledgeAuthentication(sealing.transport, sealing.client.authenticate({ resource, token: 'copilot-sealed.v1.external.ciphertext', idToken: 'id-token' })); + const direct = createClient(); + await initialize(direct.client, direct.transport, { 'copilot.encryptionKeys': [] }, {}); + const unencrypted = await acknowledgeAuthentication(direct.transport, direct.client.authenticate({ resource, token: 'provider-token', idToken: 'id-token' })); + assert.deepStrictEqual({ sealed, alreadySealed, unencrypted }, { + sealed: { channel: ROOT_STATE_URI, resource, token: 'copilot-sealed.v1.auth-token.ciphertext', scopes: undefined }, + alreadySealed: { channel: ROOT_STATE_URI, resource, token: 'copilot-sealed.v1.external.ciphertext', scopes: undefined }, + unencrypted: { channel: ROOT_STATE_URI, resource, token: 'provider-token', scopes: undefined, idToken: 'id-token' }, + }); + }); + test('preserves already sealed credentials and the empty revocation sentinel', async () => { const { client, transport } = createClient(); disposables.add(client.registerAuthenticationTokenSealer(async () => { throw new Error('Must not encrypt twice'); })); diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostAuth.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostAuth.ts index dbc7e095ce2627..26a1d8e7b15fc4 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostAuth.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostAuth.ts @@ -110,8 +110,8 @@ export class AgentHostAuthTokenCache { * Forwards a token once per resource/scope/target combination. Same-token callers share * and await an in-flight authentication. */ - async authenticate(resource: string, scopes: readonly string[] | undefined, token: string, authenticate: () => Promise, accountId?: string, entitlement?: IAgentEntitlementHint, target?: AuthenticateTarget, identity?: IForwardedAuthenticationIdentity): Promise { - const credentialKey = JSON.stringify([token, accountId, entitlement?.trackingId, entitlement?.sku]); + async authenticate(resource: string, scopes: readonly string[] | undefined, token: string, authenticate: () => Promise, accountId?: string, entitlement?: IAgentEntitlementHint, target?: AuthenticateTarget, identity?: IForwardedAuthenticationIdentity, idToken?: string): Promise { + const credentialKey = JSON.stringify([token, accountId, entitlement?.trackingId, entitlement?.sku, idToken]); const key = this._key(resource, scopes, target); const globalGeneration = this._globalGeneration; const keyGeneration = this._keyGenerations.get(key) ?? 0; @@ -134,7 +134,7 @@ export class AgentHostAuthTokenCache { if (!this._isCurrentGeneration(key, globalGeneration, keyGeneration)) { throw new CancellationError(); } - return this.authenticate(resource, scopes, token, authenticate, accountId, entitlement, target, identity); + return this.authenticate(resource, scopes, token, authenticate, accountId, entitlement, target, identity, idToken); } if (this._completedTokens.get(key)?.credentialKey === credentialKey) { @@ -805,7 +805,7 @@ async function forwardAuthenticationToken( }; if (options.authTokenCache) { const identity = session?.id && session.account ? { sessionId: session.id, accountId: session.account.id } : undefined; - return options.authTokenCache.authenticate(resource, scopes ?? [], token, () => options.authenticate(request), request.accountId, readAgentEntitlementHint(request), options.target, identity); + return options.authTokenCache.authenticate(resource, scopes ?? [], token, () => options.authenticate(request), request.accountId, readAgentEntitlementHint(request), options.target, identity, request.idToken); } assertAuthenticationAccepted(await options.authenticate(request)); return true; diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/copilotEntraAuthentication.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/copilotEntraAuthentication.test.ts index e601edfb297f06..514a54c581ca68 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/copilotEntraAuthentication.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/copilotEntraAuthentication.test.ts @@ -515,6 +515,19 @@ suite('Agent Host Microsoft credential acquisition', () => { assert.deepStrictEqual({ tokens: forwarded.map(request => request.token), prompts: f.authentication.created }, { tokens: [selected.accessToken], prompts: [] }); }); + test('an ID token that becomes available is forwarded once for an unchanged access token', async () => { + const f = fixture(); + const forwarded: IAgentHostAuthenticateRequest[] = []; + const options = { logPrefix: '[test]', authTokenCache: new AgentHostAuthTokenCache(), authenticate: async (request: IAgentHostAuthenticateRequest) => { forwarded.push(request); } }; + const forward = () => f.instantiation.invokeFunction(authenticateProtectedResources, + [{ provider: 'copilotcli', displayName: 'Copilot', description: '', models: [], protectedResources: [resource] }], options); + await forward(); + f.authentication.sessions = [{ ...selected, idToken: 'synthetic-id-token' }]; + await forward(); + await forward(); + assert.deepStrictEqual(forwarded.map(request => [request.token, request.idToken]), [[selected.accessToken, undefined], [selected.accessToken, 'synthetic-id-token']]); + }); + test('repeated challenges never prompt for a Microsoft credential and accept a later silent replacement', async () => { const f = fixture(); const forwarded: IAgentHostAuthenticateRequest[] = []; From 860d9ef9739871dc5bd224f7627279aad93749f9 Mon Sep 17 00:00:00 2001 From: Tyler Leonhardt Date: Wed, 25 Nov 2026 15:14:47 -0800 Subject: [PATCH 3/4] agentHost: send the ID token on relayed connections too Stop dropping the ID token where the access token is sealed. An optional field that is silently omitted on one kind of connection is hard to notice, and the relay already carries the session's content in clear; the ID token is identity, not access. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/vs/platform/agentHost/AGENTS.md | 2 +- .../browser/agentHostProtocolClient.ts | 9 ++------ .../agentHostProtocolClient.test.ts | 22 +++---------------- 3 files changed, 6 insertions(+), 27 deletions(-) diff --git a/src/vs/platform/agentHost/AGENTS.md b/src/vs/platform/agentHost/AGENTS.md index b1b738694e9816..c563c48d4e16ee 100644 --- a/src/vs/platform/agentHost/AGENTS.md +++ b/src/vs/platform/agentHost/AGENTS.md @@ -815,7 +815,7 @@ Applies only when the host started with `copilotM365EnabledAtStartup` on. Easy t - **GitHub and Microsoft are advertised as optional.** A user needs one of them, not both, so each is `required: false`. That only stops a client from blocking on one of them; a session still cannot run without a credential. - **The host is bound to one Microsoft account.** It knows the account only by the `authenticate.accountId` of the first accepted credential: a client does not send a display name and the host does not give the runtime one. It rejects a token with a different ID instead of switching. The ID is compared as given across clients, so every client must send the same value for the same account; this keeps the host consistent and does not isolate clients from each other. -- **Identity claims come from the ID Token.** A client may send `authenticate.idToken` with a credential; the host keeps it with the accepted token, replays it, and returns it from `getAuthCredential`. Read claims such as the tenant from it, never from the access token, which only its resource can read, or from `accountId`, which is opaque. A client that sends none leaves the host without those claims, and VS Code sends none on a connection that seals the token, because only the token can be sealed. +- **Identity claims come from the ID Token.** A client may send `authenticate.idToken` with a credential; the host keeps it with the accepted token, replays it, and returns it from `getAuthCredential`. Read claims such as the tenant from it, never from the access token, which only its resource can read, or from `accountId`, which is opaque. A client that sends none leaves the host without those claims. On a relayed connection only `token` is sealed; the ID Token crosses the relay in clear, like the session's content. - **The tenant is learned once and kept with the account.** The bridge reads the unverified `tid` claim from the first ID Token sent with a discovery credential for the account, and keeps it even when a later credential arrives without one. The runtime is not given it yet. - **The SDK's token callback never waits.** It returns the stored token or `unavailable`, which means "no token right now", not "this user has no access". - **A client disconnecting is not a sign-out.** Tokens the host accepted survive the last client leaving. As with GitHub, any client can withdraw them: the host then advertises the missing credential, unless a GitHub credential is there to return to, so a client that is still signed in can re-supply it, and restarts the runtime once running turns finish. diff --git a/src/vs/platform/agentHost/browser/agentHostProtocolClient.ts b/src/vs/platform/agentHost/browser/agentHostProtocolClient.ts index 963f695e15cd0f..4af0c49dc82c6c 100644 --- a/src/vs/platform/agentHost/browser/agentHostProtocolClient.ts +++ b/src/vs/platform/agentHost/browser/agentHostProtocolClient.ts @@ -2796,14 +2796,9 @@ export class AgentHostProtocolClient extends Disposable implements IAgentConnect } private _encryptAuthentication(params: CommandMap['authenticate']['params']): CommandMap['authenticate']['params'] | Promise { - if (!params.token) { + if (!params.token || params.token.startsWith('copilot-sealed.')) { return params; } - // Only the token can be sealed, so the ID Token is dropped wherever the token is sealed. - const { idToken: _idToken, ...sealable } = params; - if (params.token.startsWith('copilot-sealed.')) { - return sealable; - } try { const value = this.rootState.value; const root = value instanceof Error ? undefined : value; @@ -2819,7 +2814,7 @@ export class AgentHostProtocolClient extends Disposable implements IAgentConnect if (this._isWebPubSubRelay() && !this._trustedAuthenticationTokenSealer) { throw new Error('Relay credentials must be sealed using an independently trusted recipient key.'); } - return this._sealAuthentication(sealable, encryption); + return this._sealAuthentication(params, encryption); } catch (error) { throw new AuthenticationEncryptionError(getErrorMessage(error)); } diff --git a/src/vs/platform/agentHost/test/electron-browser/agentHostProtocolClient.test.ts b/src/vs/platform/agentHost/test/electron-browser/agentHostProtocolClient.test.ts index add6b40b64af39..5c9689b455ed4a 100644 --- a/src/vs/platform/agentHost/test/electron-browser/agentHostProtocolClient.test.ts +++ b/src/vs/platform/agentHost/test/electron-browser/agentHostProtocolClient.test.ts @@ -1902,7 +1902,7 @@ suite('AgentHostProtocolClient', () => { return request.params as AuthenticateParams; } - test('seals provider and targeted MCP credentials with separate keys without changing scopes or addressing', async () => { + test('seals provider and targeted MCP credentials with separate keys without changing scopes, addressing or the ID token', async () => { const { client, transport } = createClient(); const sealed: IMissionControlCredentialSealingRequest[] = []; disposables.add(client.registerAuthenticationTokenSealer(async request => { @@ -1911,34 +1911,18 @@ suite('AgentHostProtocolClient', () => { })); await initialize(client, transport); const target = { kind: AuthenticateTargetKind.McpServer, session: 'opaque-session://tenant/id', customizationId: 'server/one' }; - const provider = await acknowledgeAuthentication(transport, client.authenticate({ resource, token: 'provider-token', scopes: ['write', 'read'], expiresIn: 300 })); + const provider = await acknowledgeAuthentication(transport, client.authenticate({ resource, token: 'provider-token', scopes: ['write', 'read'], expiresIn: 300, idToken: 'id-token' })); const mcp = await acknowledgeAuthentication(transport, client.authenticate({ resource, token: 'mcp-token', scopes: ['read'], target })); assert.deepStrictEqual({ sealed: sealed.map(request => [request.token, request.resource, request.key.use, request.challenge]), provider, mcp, }, { sealed: [['provider-token', resource, 'auth-token', challenge], ['mcp-token', resource, 'mcp-auth-token', challenge]], - provider: { channel: ROOT_STATE_URI, resource, token: 'copilot-sealed.v1.auth-token.ciphertext', scopes: ['read', 'write'], expiresIn: 300 }, + provider: { channel: ROOT_STATE_URI, resource, token: 'copilot-sealed.v1.auth-token.ciphertext', scopes: ['read', 'write'], expiresIn: 300, idToken: 'id-token' }, mcp: { channel: ROOT_STATE_URI, resource, token: 'copilot-sealed.v1.mcp-auth-token.ciphertext', scopes: ['read'], target }, }); }); - test('omits the ID token wherever the token is sealed, and sends it on an unencrypted connection', async () => { - const sealing = createClient(); - disposables.add(sealing.client.registerAuthenticationTokenSealer(async request => `copilot-sealed.v1.${request.key.key_id}.ciphertext`)); - await initialize(sealing.client, sealing.transport); - const sealed = await acknowledgeAuthentication(sealing.transport, sealing.client.authenticate({ resource, token: 'provider-token', idToken: 'id-token' })); - const alreadySealed = await acknowledgeAuthentication(sealing.transport, sealing.client.authenticate({ resource, token: 'copilot-sealed.v1.external.ciphertext', idToken: 'id-token' })); - const direct = createClient(); - await initialize(direct.client, direct.transport, { 'copilot.encryptionKeys': [] }, {}); - const unencrypted = await acknowledgeAuthentication(direct.transport, direct.client.authenticate({ resource, token: 'provider-token', idToken: 'id-token' })); - assert.deepStrictEqual({ sealed, alreadySealed, unencrypted }, { - sealed: { channel: ROOT_STATE_URI, resource, token: 'copilot-sealed.v1.auth-token.ciphertext', scopes: undefined }, - alreadySealed: { channel: ROOT_STATE_URI, resource, token: 'copilot-sealed.v1.external.ciphertext', scopes: undefined }, - unencrypted: { channel: ROOT_STATE_URI, resource, token: 'provider-token', scopes: undefined, idToken: 'id-token' }, - }); - }); - test('preserves already sealed credentials and the empty revocation sentinel', async () => { const { client, transport } = createClient(); disposables.add(client.registerAuthenticationTokenSealer(async () => { throw new Error('Must not encrypt twice'); })); From 56bbc769f120becc10e8f6e6123e697e12d76adf Mon Sep 17 00:00:00 2001 From: Tyler Leonhardt Date: Wed, 25 Nov 2026 16:16:01 -0800 Subject: [PATCH 4/4] agentHost: simplify ID token handling after review Move authenticate redaction into one function so the log replacer does not grow, share the nonempty-string check between accountId and idToken, and store the ID token the same way as the account ID. Stop storing the ID token on host execution credentials, where nothing can read it, and keep the authority type private to the bridge. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../agentHost/common/ahpJsonlLogger.ts | 23 +++++++++---------- .../node/agentHostAuthenticationService.ts | 18 +++++++-------- .../copilot/copilotEntraAuthentication.ts | 2 +- 3 files changed, 21 insertions(+), 22 deletions(-) diff --git a/src/vs/platform/agentHost/common/ahpJsonlLogger.ts b/src/vs/platform/agentHost/common/ahpJsonlLogger.ts index 898f7cdf1e6a9a..85c5e2440a68b1 100644 --- a/src/vs/platform/agentHost/common/ahpJsonlLogger.ts +++ b/src/vs/platform/agentHost/common/ahpJsonlLogger.ts @@ -428,13 +428,14 @@ function stringifyAhpLogEntryTruncated(value: unknown, maxStringLength: number): }); } -/** Replaces the access token and ID Token of `authenticate` params, or returns `undefined` when neither needs it. */ -function redactAuthenticationParams(params: Record): Record | undefined { - const hasToken = params.token !== undefined && params.token !== '' && params.token !== '[REDACTED]'; - const hasIdToken = params.idToken !== undefined && params.idToken !== ''; - return hasToken || hasIdToken - ? { ...params, ...(hasToken ? { token: '' } : {}), ...(hasIdToken ? { idToken: '' } : {}) } - : undefined; +/** Returns an `authenticate` request with its access token and ID Token redacted, or `undefined` when there is nothing to redact. */ +function redactAuthenticationRequest(message: Record): Record | undefined { + const params = message.params; + if (message.method !== 'authenticate' || !isRecord(params)) { + return undefined; + } + const secrets = ['token', 'idToken'].filter(field => params[field] !== undefined && params[field] !== '' && params[field] !== '[REDACTED]'); + return secrets.length ? { ...message, params: { ...params, ...Object.fromEntries(secrets.map(field => [field, ''])) } } : undefined; } /** @@ -464,11 +465,9 @@ function _ahpReplacer(this: unknown, _key: string, value: unknown): unknown { if (isRecord(value.result) && Array.isArray(value.result.certificates)) { return { ...value, result: { ...value.result, certificates: '' } }; } - if (value.method === 'authenticate' && isRecord(value.params)) { - const redacted = redactAuthenticationParams(value.params); - if (redacted) { - return { ...value, params: redacted }; - } + const redactedAuthentication = redactAuthenticationRequest(value); + if (redactedAuthentication) { + return redactedAuthentication; } if (value.method === RegisterGitHubEnvironmentExtensionMethod && isRecord(value.params) && value.params.credential !== undefined && value.params.credential !== '') { diff --git a/src/vs/platform/agentHost/node/agentHostAuthenticationService.ts b/src/vs/platform/agentHost/node/agentHostAuthenticationService.ts index f45b5468ee9eb2..42a781b73dd932 100644 --- a/src/vs/platform/agentHost/node/agentHostAuthenticationService.ts +++ b/src/vs/platform/agentHost/node/agentHostAuthenticationService.ts @@ -98,6 +98,12 @@ interface ILocalCredentialsOptions { readonly onDidChange: Event; } +function assertOptionalNonemptyString(value: unknown, name: string): void { + if (value !== undefined && (typeof value !== 'string' || value.length === 0)) { + throw new ProtocolError(JsonRpcErrorCodes.InvalidParams, `${name} must be a nonempty string`); + } +} + function isAccepted(result: PromiseSettledResult): boolean { return result.status === 'fulfilled' && result.value; } @@ -174,7 +180,6 @@ export class AgentHostAuthenticationService extends Disposable implements IAgent resource: credential.resource, token: credential.token, scopes: normalizeAuthenticationScopes(credential.scopes ?? metadata.scopes_supported), expiresAt, accountId: credential.accountId, - ...(credential.idToken !== undefined ? { idToken: credential.idToken } : {}), }); } this._hostExecutionCredentials = stored; @@ -186,12 +191,8 @@ export class AgentHostAuthenticationService extends Disposable implements IAgent } async authenticate(params: AuthenticateParams, providers: Iterable, scope?: IAgentHostAuthenticationScope, clientId?: string): Promise { - if (params.accountId !== undefined && (typeof params.accountId !== 'string' || params.accountId.length === 0)) { - throw new ProtocolError(JsonRpcErrorCodes.InvalidParams, 'accountId must be a nonempty string'); - } - if (params.idToken !== undefined && (typeof params.idToken !== 'string' || params.idToken.length === 0)) { - throw new ProtocolError(JsonRpcErrorCodes.InvalidParams, 'idToken must be a nonempty string'); - } + assertOptionalNonemptyString(params.accountId, 'accountId'); + assertOptionalNonemptyString(params.idToken, 'idToken'); const providerList = [...providers]; if (scope) { const resources = [ @@ -309,9 +310,8 @@ export class AgentHostAuthenticationService extends Disposable implements IAgent const selection = { lastAccountId, unhintedAccountId }; this._accountSelectionHistory.set(selectionKey, selection); this._tokens.set(key, { - resource: params.resource, scopes, token: params.token, expiresAt, accountId: params.accountId, + resource: params.resource, scopes, token: params.token, expiresAt, accountId: params.accountId, idToken: params.idToken, clientId, ...selection, ...(params.target ? { target: params.target } : {}), - ...(params.idToken !== undefined ? { idToken: params.idToken } : {}), }); } if (!params.target && this.useLocalCredentials) { diff --git a/src/vs/platform/agentHost/node/copilot/copilotEntraAuthentication.ts b/src/vs/platform/agentHost/node/copilot/copilotEntraAuthentication.ts index bfb610672e1178..36d0279e0d5b5b 100644 --- a/src/vs/platform/agentHost/node/copilot/copilotEntraAuthentication.ts +++ b/src/vs/platform/agentHost/node/copilot/copilotEntraAuthentication.ts @@ -18,7 +18,7 @@ import { AhpErrorCodes, ProtocolError } from '../../common/state/sessionProtocol import type { ProtectedResourceMetadata } from '../../common/state/protocol/state.js'; import { IAgentHostAuthenticationService, type IAgentHostAuthCredential } from '../agentHostAuthenticationService.js'; -export interface IEntraAuthority { +interface IEntraAuthority { /** * The `authenticate.accountId` of the first accepted discovery credential. Unlike the per-client GitHub * comparison, it is compared as given across clients and Microsoft resources, because one Microsoft account