Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/vs/platform/agentHost/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. 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.
- **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.
Expand Down
2 changes: 2 additions & 0 deletions src/vs/platform/agentHost/common/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>;
}
Expand Down
16 changes: 13 additions & 3 deletions src/vs/platform/agentHost/common/ahpJsonlLogger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,16 @@ function stringifyAhpLogEntryTruncated(value: unknown, maxStringLength: number):
});
}

/** Returns an `authenticate` request with its access token and ID Token redacted, or `undefined` when there is nothing to redact. */
function redactAuthenticationRequest(message: Record<string, unknown>): Record<string, unknown> | undefined {
const params = message.params;
if (message.method !== 'authenticate' || !isRecord(params)) {
return undefined;
}
const secrets = ['token', 'idToken'].filter(field => params[field] !== undefined && params[field] !== '<redacted>' && params[field] !== '[REDACTED]');
return secrets.length ? { ...message, params: { ...params, ...Object.fromEntries(secrets.map(field => [field, '<redacted>'])) } } : undefined;
}

/**
* JSON.stringify replacer that converts URI values to their canonical string
* form. `URI.prototype.toJSON()` runs before this replacer is invoked and
Expand Down Expand Up @@ -455,9 +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: '<redacted>' } };
}
if (value.method === 'authenticate' && isRecord(value.params) && value.params.token !== undefined
&& value.params.token !== '<redacted>' && value.params.token !== '[REDACTED]') {
return { ...value, params: { ...value.params, token: '<redacted>' } };
const redactedAuthentication = redactAuthenticationRequest(value);
if (redactedAuthentication) {
return redactedAuthentication;
}
if (value.method === RegisterGitHubEnvironmentExtensionMethod && isRecord(value.params) && value.params.credential !== undefined
&& value.params.credential !== '<redacted>') {
Expand Down
2 changes: 1 addition & 1 deletion src/vs/platform/agentHost/common/state/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand Down
16 changes: 12 additions & 4 deletions src/vs/platform/agentHost/node/agentHostAuthenticationService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down Expand Up @@ -96,6 +98,12 @@ interface ILocalCredentialsOptions {
readonly onDidChange: Event<void>;
}

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>): boolean {
return result.status === 'fulfilled' && result.value;
}
Expand Down Expand Up @@ -183,9 +191,8 @@ export class AgentHostAuthenticationService extends Disposable implements IAgent
}

async authenticate(params: AuthenticateParams, providers: Iterable<IAgent>, scope?: IAgentHostAuthenticationScope, clientId?: string): Promise<AuthenticateResult> {
if (params.accountId !== undefined && (typeof params.accountId !== 'string' || params.accountId.length === 0)) {
throw new ProtocolError(JsonRpcErrorCodes.InvalidParams, 'accountId must be a nonempty string');
}
assertOptionalNonemptyString(params.accountId, 'accountId');
assertOptionalNonemptyString(params.idToken, 'idToken');
const providerList = [...providers];
if (scope) {
const resources = [
Expand Down Expand Up @@ -303,7 +310,7 @@ 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 } : {}),
});
}
Expand Down Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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 {
Expand Down Expand Up @@ -65,10 +68,10 @@ 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(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 ?? [])) {
Expand Down Expand Up @@ -291,9 +294,38 @@ function resolveEntraIdentity(request: Extract<EntraTokenProviderArgs, { kind: '
if (request.reason === 'forceInteractive') {
return undefined;
}
// TODO: Replace the return below with this one once the SDK includes github/copilot-agent-runtime#34048, which requires the tenant; the runtime before it rejects the field.
// return authority.tenantId ? { kind: 'identity', accountId: authority.accountId, tenantId: authority.tenantId } : undefined;
return { kind: 'identity', accountId: authority.accountId };
}

/** The host's Microsoft account after a discovery credential is accepted: the first account is kept, and its tenant is learned once. */
export function acceptEntraDiscoveryCredential(authority: IEntraAuthority | undefined, credential: Pick<IAgentHostAuthCredential, 'accountId' | 'idToken'> | 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;
Expand Down
6 changes: 6 additions & 0 deletions src/vs/platform/agentHost/test/common/ahpJsonlLogger.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -487,6 +487,12 @@ suite('AhpJsonlLogger', () => {
})).params.token), ['<redacted>', '[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: '<redacted>', idToken: '<redacted>' }, { token: '[REDACTED]', idToken: '<redacted>' }]);
});

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());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 => {
Expand All @@ -1911,14 +1911,14 @@ 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 },
});
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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();
Expand Down Expand Up @@ -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<IAgent>() {
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();
Expand Down
Loading