From 71dd54a145e5c08f55b66d7126c944267590051f Mon Sep 17 00:00:00 2001 From: Kevin J Gao <32936811+gaokevin1@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:20:34 -0800 Subject: [PATCH 1/2] fix(resources): authenticate token exchange and key cache per user Resource token exchange posted to /oauth2/v1/token without client auth. Descope serves agentic token exchange only on the inbound-apps server (/oauth2/v1/apps/token, per /v1/apps/ discovery) and requires the exchanging client to authenticate; that client becomes act.sub. - Send the exchange to /oauth2/v1/apps/token with client_id/client_secret from the configured provider (ClientCredentialsProvider, or CibaProvider with a secret) - Fail fast, before any request or approval prompt, when the provider has no confidential client to authenticate the exchange - Key the Resource token cache by a SHA-256 of act_as_user_token so a shared client never serves one user's token to another (or to the agent) - Acquire and refresh ClientCredentialsProvider tokens on /oauth2/v1/apps/token, the Agentic Client token endpoint - Same changes in Python and TypeScript Co-Authored-By: Claude Opus 5.5 --- python/descope_agent_auth/_endpoints.py | 10 +-- python/descope_agent_auth/client.py | 1 + python/descope_agent_auth/providers/base.py | 12 +++- python/descope_agent_auth/providers/ciba.py | 8 ++- .../providers/client_credentials.py | 13 +++- python/descope_agent_auth/vault/resources.py | 46 ++++++++++--- python/tests/test_exchange.py | 65 ++++++++++++++++++- python/tests/test_providers.py | 5 +- python/tests/test_user_scoped.py | 17 +++-- typescript/src/client.ts | 1 + typescript/src/endpoints.ts | 10 +-- typescript/src/exchange.test.ts | 3 +- typescript/src/providers.test.ts | 16 +++-- typescript/src/providers/base.ts | 12 ++++ typescript/src/providers/ciba.ts | 6 ++ typescript/src/providers/clientCredentials.ts | 13 +++- typescript/src/resources.test.ts | 55 +++++++++++++++- typescript/src/runtime.ts | 11 +++- typescript/src/tokenStorage.test.ts | 2 +- typescript/src/userScoped.test.ts | 24 +++---- typescript/src/vault/resources.ts | 43 +++++++++--- 21 files changed, 300 insertions(+), 73 deletions(-) diff --git a/python/descope_agent_auth/_endpoints.py b/python/descope_agent_auth/_endpoints.py index ae78b37..33e2601 100644 --- a/python/descope_agent_auth/_endpoints.py +++ b/python/descope_agent_auth/_endpoints.py @@ -8,7 +8,6 @@ discovery document (``//.well-known/openid-configuration``) before relying on them: - DEVICE_AUTHORIZATION path - - RESOURCE token endpoint shape These are isolated as named constants precisely so confirming/overriding them is a one-line change, not a refactor. """ @@ -17,12 +16,13 @@ # --- Phase 1: OAuth2 / OIDC (acquisition) ----------------------------------- -# Used for client_credentials, refresh_token and device_code grants. +# Used for refresh_token (default), device_code and jwt-bearer grants. OAUTH2_TOKEN = "/oauth2/v1/token" -# Token endpoint for an agent that authenticates as an inbound app client rather -# than through the project OIDC server. CIBA polls and refreshes -# here (or the /apps/{projectId}/token variant) because OAUTH2_TOKEN does not serve it. +# Token endpoint of the inbound-apps authorization server (the token_endpoint in +# /v1/apps//.well-known/openid-configuration). Agentic Clients are inbound +# apps, so client_credentials, CIBA and the Resource token-exchange (which requires +# client authentication) all go here. OAUTH2_APPS_TOKEN = "/oauth2/v1/apps/token" # UNVERIFIED -- confirm via discovery (device_authorization_endpoint). diff --git a/python/descope_agent_auth/client.py b/python/descope_agent_auth/client.py index b141ac3..c5f5099 100644 --- a/python/descope_agent_auth/client.py +++ b/python/descope_agent_auth/client.py @@ -98,6 +98,7 @@ def __init__( self.resources = ResourcesClient( http=self._http, get_credential=self.get_credential, + get_client_auth=self.credential.token_exchange_client_auth, store=self.store, mode=self.mode, approval_gate=self._run_approval, diff --git a/python/descope_agent_auth/providers/base.py b/python/descope_agent_auth/providers/base.py index 9c47060..6b2d892 100644 --- a/python/descope_agent_auth/providers/base.py +++ b/python/descope_agent_auth/providers/base.py @@ -16,7 +16,7 @@ import json import time from abc import ABC, abstractmethod -from typing import Optional +from typing import Dict, Optional from .._async import maybe_await from .._endpoints import GRANT_REFRESH_TOKEN, OAUTH2_TOKEN @@ -141,6 +141,16 @@ def _refresh_client_auth(self) -> dict: """Extra form fields / client auth needed for refresh. Override as needed.""" return {} + def token_exchange_client_auth(self) -> Optional[Dict[str, str]]: + """Form fields that authenticate this agent as a confidential client. + + Descope's token-exchange grant requires the exchanging client to + authenticate (it becomes ``act.sub`` on the minted token). Providers that + hold a client secret return ``client_id`` + ``client_secret``; the rest + return ``None`` and cannot mint Resource tokens. + """ + return None + # -- persistence -------------------------------------------------------- async def _save(self, cred: Credential) -> None: diff --git a/python/descope_agent_auth/providers/ciba.py b/python/descope_agent_auth/providers/ciba.py index bc495df..ef99ff0 100644 --- a/python/descope_agent_auth/providers/ciba.py +++ b/python/descope_agent_auth/providers/ciba.py @@ -19,7 +19,7 @@ import asyncio import json import time -from typing import List, Optional +from typing import Dict, List, Optional from .._endpoints import CIBA_AUTHENTICATE, GRANT_CIBA, OAUTH2_APPS_TOKEN from ..errors import ( @@ -171,6 +171,12 @@ def _refresh_client_auth(self) -> dict: out["client_secret"] = self._client_secret return out + def token_exchange_client_auth(self) -> Optional[Dict[str, str]]: + # Only a confidential CIBA client can authenticate a token exchange. + if not self._client_secret: + return None + return {"client_id": self._client_id, "client_secret": self._client_secret} + def _rejected_details_reason(body: Optional[dict]) -> Optional[str]: # With strict OAuth errors off, Descope sends only its legacy envelope: diff --git a/python/descope_agent_auth/providers/client_credentials.py b/python/descope_agent_auth/providers/client_credentials.py index 46804bd..0a8c21a 100644 --- a/python/descope_agent_auth/providers/client_credentials.py +++ b/python/descope_agent_auth/providers/client_credentials.py @@ -8,9 +8,9 @@ from __future__ import annotations import base64 -from typing import List, Optional +from typing import Dict, List, Optional -from .._endpoints import GRANT_CLIENT_CREDENTIALS, OAUTH2_TOKEN +from .._endpoints import GRANT_CLIENT_CREDENTIALS, OAUTH2_APPS_TOKEN from ..errors import CredentialAcquisitionFailed from ..types import Credential, CredentialKind from .base import CredentialProvider, _err, token_response_to_credential @@ -18,6 +18,8 @@ class ClientCredentialsProvider(CredentialProvider): kind = CredentialKind.AGENT_TOKEN + # Agentic Clients are inbound apps: acquire and refresh on the inbound-apps server. + refresh_endpoint = OAUTH2_APPS_TOKEN def __init__( self, @@ -39,8 +41,10 @@ async def _acquire(self) -> Credential: data = {"grant_type": GRANT_CLIENT_CREDENTIALS} if self._scopes: data["scope"] = " ".join(self._scopes) + # Agentic Clients are inbound apps, served by the /v1/apps/ + # authorization server, whose token endpoint is /oauth2/v1/apps/token. resp = await self.http.post_form( - OAUTH2_TOKEN, data=data, headers={"Authorization": self._basic_auth()} + OAUTH2_APPS_TOKEN, data=data, headers={"Authorization": self._basic_auth()} ) if not resp.ok: raise CredentialAcquisitionFailed( @@ -56,3 +60,6 @@ def _refresh_client_auth(self) -> dict: # client_credentials tokens are re-acquired, not refresh-token rotated; # base.get_credential falls back to _acquire when there is no refresh token. return {} + + def token_exchange_client_auth(self) -> Optional[Dict[str, str]]: + return {"client_id": self._client_id, "client_secret": self._client_secret} diff --git a/python/descope_agent_auth/vault/resources.py b/python/descope_agent_auth/vault/resources.py index 67fd64e..376384d 100644 --- a/python/descope_agent_auth/vault/resources.py +++ b/python/descope_agent_auth/vault/resources.py @@ -10,19 +10,22 @@ agent identity (Client ID/Secret via any phase-1 provider). It does not apply to a Management Key. -NOTE: the exact token-exchange parameters (``resource`` vs ``audience``, whether -client auth is also required) should be confirmed against the Descope API -reference; the grant + endpoint are pinned in ``_endpoints``. +The exchange goes to the inbound-apps token endpoint (``/oauth2/v1/apps/token``, +per the ``/v1/apps/`` discovery document) and must be authenticated by +a confidential client (``client_id`` + ``client_secret``). That client is recorded +as ``act.sub`` on the minted token, so the downstream API can see which agent is +acting for the user. """ from __future__ import annotations +import hashlib import json import time -from typing import Any, Awaitable, Callable, List, Optional +from typing import Any, Awaitable, Callable, Dict, List, Optional from .._async import maybe_await -from .._endpoints import GRANT_TOKEN_EXCHANGE, OAUTH2_TOKEN, TOKEN_TYPE_ACCESS_TOKEN +from .._endpoints import GRANT_TOKEN_EXCHANGE, OAUTH2_APPS_TOKEN, TOKEN_TYPE_ACCESS_TOKEN from .._http import HttpClient from ..errors import AgentAuthError, PolicyDenied, TokenExchangeFailed from ..store.base import TokenStore @@ -30,11 +33,21 @@ def _cache_key( - resource: str, scopes: Optional[List[str]], audience: Optional[List[str]] + resource: str, + scopes: Optional[List[str]], + audience: Optional[List[str]], + act_as_user_token: Optional[str] = None, ) -> str: scope_part = ",".join(sorted(scopes)) if scopes else "" aud_part = ",".join(sorted(audience)) if audience else "" - return f"vault:resource:{resource}:{aud_part}:{scope_part}" + # A user-scoped token belongs to that user only: key it by a digest of the + # subject token so one shared client never serves user A's token to user B + # (or to the agent itself). The raw token never lands in a store key. + if act_as_user_token: + subject_part = "user:" + hashlib.sha256(act_as_user_token.encode("utf-8")).hexdigest() + else: + subject_part = "agent" + return f"vault:resource:{subject_part}:{resource}:{aud_part}:{scope_part}" def _err(body: Optional[dict]) -> Optional[str]: @@ -49,6 +62,7 @@ def __init__( *, http: HttpClient, get_credential: Callable[[], Awaitable[Credential]], + get_client_auth: Callable[[], Optional[Dict[str, str]]], store: TokenStore, mode: Mode, approval_gate: Optional[Callable[[ApprovalRequest], Awaitable[None]]] = None, @@ -57,6 +71,7 @@ def __init__( ) -> None: self._http = http self._get_credential = get_credential + self._get_client_auth = get_client_auth self._store = store self._mode = mode self._approval_gate = approval_gate @@ -93,6 +108,18 @@ async def get_token( "raw token fetch is disabled in execute mode; the token stays vaulted." ) + # Descope rejects unauthenticated token-exchange requests, and the + # authenticating client is what lands in act.sub. Fail before any network + # call (or approval prompt) when the provider has no client secret to offer. + client_auth = self._get_client_auth() + if not client_auth: + raise AgentAuthError( + "Resource tokens use the token-exchange grant, which Descope only serves " + "to an authenticated agent client. Configure the client with " + "ClientCredentialsProvider(client_id=..., client_secret=...) and pass " + "act_as_user_token=... to act for a user." + ) + if require_approval is not None: if self._approval_gate is None: raise AgentAuthError( @@ -101,7 +128,7 @@ async def get_token( ) await self._approval_gate(require_approval) - cache_key = _cache_key(resource, scopes, audience) + cache_key = _cache_key(resource, scopes, audience, act_as_user_token) if self._cache_tokens and not force_refresh: cached = await self._cache_get(cache_key) if cached is not None: @@ -127,6 +154,7 @@ async def get_token( "subject_token": subject_token, "subject_token_type": TOKEN_TYPE_ACCESS_TOKEN, "resource": resource, + **client_auth, } if scopes: data["scope"] = " ".join(scopes) @@ -134,7 +162,7 @@ async def get_token( # RFC 8693 audience; sent as repeated form params when multi-valued. data["audience"] = audience - resp = await self._http.post_form(OAUTH2_TOKEN, data=data) + resp = await self._http.post_form(OAUTH2_APPS_TOKEN, data=data) if resp.status_code in (401, 403): raise PolicyDenied( f"policy denied for resource '{resource}' " diff --git a/python/tests/test_exchange.py b/python/tests/test_exchange.py index 5ba5f2d..eaee2ca 100644 --- a/python/tests/test_exchange.py +++ b/python/tests/test_exchange.py @@ -5,6 +5,7 @@ from unittest.mock import AsyncMock, patch from descope_agent_auth import ( + AccessTokenProvider, ClientCredentialsProvider, ManagementKeyProvider, ) @@ -323,12 +324,74 @@ def test_token_exchange_returns_resource_token(self, mock_request): self.assertEqual(tok.access_token, "resource_at") self.assertEqual(tok.scopes, ["read"]) args, kwargs = mock_request.call_args # the token-exchange call - self.assertEqual(args[1], "/oauth2/v1/token") + # Token-exchange is served only by the inbound-apps authorization server. + self.assertEqual(args[1], "/oauth2/v1/apps/token") self.assertEqual( kwargs["data"]["grant_type"], "urn:ietf:params:oauth:grant-type:token-exchange" ) self.assertEqual(kwargs["data"]["resource"], "urn:my-api") self.assertEqual(kwargs["data"]["subject_token"], "agent_at") + # Descope requires the exchanging client to authenticate; it becomes act.sub. + self.assertEqual(kwargs["data"]["client_id"], "cid") + self.assertEqual(kwargs["data"]["client_secret"], "s") + + @patch("httpx.AsyncClient.request", new_callable=AsyncMock) + def test_user_scoped_exchange_authenticates_the_agent_client(self, mock_request): + mock_request.return_value = make_response({"access_token": "resource_at"}) + client = self._agent_client() + + client.resources.get_token(resource="urn:my-api", act_as_user_token="user_jwt") + + args, kwargs = mock_request.call_args + self.assertEqual(args[1], "/oauth2/v1/apps/token") + self.assertEqual(kwargs["data"]["subject_token"], "user_jwt") + self.assertEqual(kwargs["data"]["client_id"], "cid") + self.assertEqual(kwargs["data"]["client_secret"], "s") + + @patch("httpx.AsyncClient.request", new_callable=AsyncMock) + def test_user_scoped_tokens_are_not_shared_across_users(self, mock_request): + # One shared agent client serving two users must never hand user A's + # Resource token to user B from the cache. + mock_request.side_effect = [ + make_response({"access_token": "alice_resource_at", "expires_in": 3600}), + make_response({"access_token": "bob_resource_at", "expires_in": 3600}), + ] + client = self._agent_client() + + alice = client.resources.get_token(resource="urn:my-api", act_as_user_token="alice_jwt") + bob = client.resources.get_token(resource="urn:my-api", act_as_user_token="bob_jwt") + alice_again = client.resources.get_token( + resource="urn:my-api", act_as_user_token="alice_jwt" + ) + + self.assertEqual(alice.access_token, "alice_resource_at") + self.assertEqual(bob.access_token, "bob_resource_at") + self.assertEqual(alice_again.access_token, "alice_resource_at") # cached per user + self.assertEqual(mock_request.call_count, 2) + + @patch("httpx.AsyncClient.request", new_callable=AsyncMock) + def test_user_scoped_token_is_not_served_to_the_agent_itself(self, mock_request): + mock_request.side_effect = [ + make_response({"access_token": "alice_resource_at", "expires_in": 3600}), + make_response({"access_token": "agent_at", "expires_in": 3600}), # phase 1 + make_response({"access_token": "agent_resource_at", "expires_in": 3600}), + ] + client = self._agent_client() + + client.resources.get_token(resource="urn:my-api", act_as_user_token="alice_jwt") + own = client.resources.get_token(resource="urn:my-api") + + self.assertEqual(own.access_token, "agent_resource_at") + + @patch("httpx.AsyncClient.request", new_callable=AsyncMock) + def test_exchange_without_confidential_client_is_rejected(self, mock_request): + # A bare user token has no client to authenticate the exchange, and + # Descope rejects unauthenticated token-exchange requests. + client = self.make_client(AccessTokenProvider(access_token="user_jwt")) + with self.assertRaises(AgentAuthError) as ctx: + client.resources.get_token(resource="urn:my-api") + self.assertIn("ClientCredentialsProvider", str(ctx.exception)) + mock_request.assert_not_called() @patch("httpx.AsyncClient.request", new_callable=AsyncMock) def test_resource_token_sends_audience(self, mock_request): diff --git a/python/tests/test_providers.py b/python/tests/test_providers.py index 7f95292..3f4911f 100644 --- a/python/tests/test_providers.py +++ b/python/tests/test_providers.py @@ -37,8 +37,11 @@ def test_happy_path_uses_basic_auth(self, mock_request): self.assertFalse(cred.is_privileged) self.assertFalse(cred.is_expired()) # Authorization header is HTTP Basic. - _, kwargs = mock_request.call_args + args, kwargs = mock_request.call_args self.assertTrue(kwargs["headers"]["Authorization"].startswith("Basic ")) + # Agentic Clients are inbound apps: their token endpoint (per the + # /v1/apps/ discovery document) is /oauth2/v1/apps/token. + self.assertEqual(args[1], "/oauth2/v1/apps/token") @patch("httpx.AsyncClient.request", new_callable=AsyncMock) def test_caches_until_expiry(self, mock_request): diff --git a/python/tests/test_user_scoped.py b/python/tests/test_user_scoped.py index c268a33..7a14d7e 100644 --- a/python/tests/test_user_scoped.py +++ b/python/tests/test_user_scoped.py @@ -8,6 +8,7 @@ AccessTokenProvider, ClientCredentialsProvider, ) +from descope_agent_auth.errors import AgentAuthError from . import common from .common import PROJECT_ID, make_response, token_obj @@ -41,17 +42,15 @@ def test_connection_fetch_is_user_scoped(self, mock_request): self.assertEqual(kwargs["headers"]["Authorization"], f"Bearer {PROJECT_ID}:user_jwt") @patch("httpx.AsyncClient.request", new_callable=AsyncMock) - def test_resource_token_exchange_uses_user_subject(self, mock_request): - mock_request.return_value = make_response( - {"access_token": "resource_at", "expires_in": 3600, "scope": "read"} - ) + def test_resource_token_exchange_needs_an_agent_client(self, mock_request): + # Descope only exchanges for an authenticated (confidential) client, so a + # bare user token can't mint Resource tokens on its own. Use a shared + # ClientCredentialsProvider client with act_as_user_token instead. client = self.make_client(AccessTokenProvider(access_token="user_jwt")) - tok = client.resources.get_token(resource="urn:my-api", scopes=["read"]) - - self.assertEqual(tok.access_token, "resource_at") - _, kwargs = mock_request.call_args - self.assertEqual(kwargs["data"]["subject_token"], "user_jwt") + with self.assertRaises(AgentAuthError): + client.resources.get_token(resource="urn:my-api", scopes=["read"]) + mock_request.assert_not_called() class TestActAsUserTokenOverride(common.AgentAuthTest): diff --git a/typescript/src/client.ts b/typescript/src/client.ts index ed58f69..0f6bcb7 100644 --- a/typescript/src/client.ts +++ b/typescript/src/client.ts @@ -109,6 +109,7 @@ export class AgentAuthClient { this.resources = new ResourcesClient({ http: this.http, getCredential: () => this.getCredential(), + getClientAuth: () => this.credential.tokenExchangeClientAuth(), store: this.store, mode: this.mode, approvalGate: (request) => this.runApproval(request), diff --git a/typescript/src/endpoints.ts b/typescript/src/endpoints.ts index a7936b9..7da3059 100644 --- a/typescript/src/endpoints.ts +++ b/typescript/src/endpoints.ts @@ -9,18 +9,18 @@ * discovery document (`//.well-known/openid-configuration`) before * relying on them: * - DEVICE_AUTHORIZATION path - * - RESOURCE token endpoint shape */ // --- Phase 1: OAuth2 / OIDC (acquisition) ----------------------------------- -/** client_credentials, refresh_token, device_code. */ +/** refresh_token (default), device_code, jwt-bearer. */ export const OAUTH2_TOKEN = '/oauth2/v1/token'; /** - * Token endpoint for an agent that authenticates as an inbound app client. CIBA polls - * and refreshes here (or the /apps/{projectId}/token variant) because OAUTH2_TOKEN - * does not serve it. + * Token endpoint of the inbound-apps authorization server (the `token_endpoint` in + * `/v1/apps//.well-known/openid-configuration`). Agentic Clients are + * inbound apps, so client_credentials, CIBA and the Resource token-exchange (which + * requires client authentication) all go here. */ export const OAUTH2_APPS_TOKEN = '/oauth2/v1/apps/token'; diff --git a/typescript/src/exchange.test.ts b/typescript/src/exchange.test.ts index 77928a9..ed75123 100644 --- a/typescript/src/exchange.test.ts +++ b/typescript/src/exchange.test.ts @@ -4,7 +4,8 @@ import { BASE_URL, PROJECT_ID, makeClient, tokenObj } from './testutils'; import { ClientCredentialsProvider, ManagementKeyProvider } from './providers'; import { AgentAuthError, PolicyDenied, TokenExchangeFailed } from './errors'; -const TOKEN_PATH = '/oauth2/v1/token'; +// Agent client_credentials is served by the inbound-apps server. +const TOKEN_PATH = '/oauth2/v1/apps/token'; const USER_LATEST = '/v1/mgmt/outbound/app/user/token/latest'; const USER_SCOPED = '/v1/mgmt/outbound/app/user/token'; const TENANT_LATEST = '/v1/mgmt/outbound/app/tenant/token/latest'; diff --git a/typescript/src/providers.test.ts b/typescript/src/providers.test.ts index 47a3765..3eaa42a 100644 --- a/typescript/src/providers.test.ts +++ b/typescript/src/providers.test.ts @@ -38,6 +38,8 @@ afterAll(() => { nock.enableNetConnect(); }); +// Agentic Clients are inbound apps: their token endpoint (per the /v1/apps/ +// discovery document) is /oauth2/v1/apps/token, the same one CIBA uses. describe('ClientCredentialsProvider', () => { it('acquires a token (happy path) with Basic auth', async () => { let authHeader: string | undefined; @@ -49,7 +51,7 @@ describe('ClientCredentialsProvider', () => { }, }, }) - .post(TOKEN_PATH) + .post(CIBA_TOKEN_PATH) .reply(200, { access_token: 'agent_at', expires_in: 3600 }); const client = makeClient( @@ -63,7 +65,7 @@ describe('ClientCredentialsProvider', () => { it('caches the credential until expiry', async () => { const scope = nock(BASE_URL) - .post(TOKEN_PATH) + .post(CIBA_TOKEN_PATH) .reply(200, { access_token: 'agent_at', expires_in: 3600 }); const client = makeClient( new ClientCredentialsProvider({ clientId: 'cid', clientSecret: 's' }), @@ -74,7 +76,7 @@ describe('ClientCredentialsProvider', () => { }); it('raises CredentialAcquisitionFailed on bad credentials', async () => { - nock(BASE_URL).post(TOKEN_PATH).reply(401, { error: 'invalid_client' }); + nock(BASE_URL).post(CIBA_TOKEN_PATH).reply(401, { error: 'invalid_client' }); const client = makeClient( new ClientCredentialsProvider({ clientId: 'cid', clientSecret: 'bad' }), ); @@ -84,9 +86,9 @@ describe('ClientCredentialsProvider', () => { it('uses the refresh_token grant when one is held and the token expired', async () => { let refreshBody: any; nock(BASE_URL) - .post(TOKEN_PATH) + .post(CIBA_TOKEN_PATH) .reply(200, { access_token: 'first', expires_in: -10, refresh_token: 'r1' }) - .post(TOKEN_PATH, (body) => { + .post(CIBA_TOKEN_PATH, (body) => { refreshBody = body; return true; }) @@ -101,9 +103,9 @@ describe('ClientCredentialsProvider', () => { it('re-acquires when the cached credential is expired', async () => { nock(BASE_URL) - .post(TOKEN_PATH) + .post(CIBA_TOKEN_PATH) .reply(200, { access_token: 'first', expires_in: -10 }) - .post(TOKEN_PATH) + .post(CIBA_TOKEN_PATH) .reply(200, { access_token: 'second', expires_in: 3600 }); const client = makeClient( new ClientCredentialsProvider({ clientId: 'cid', clientSecret: 's' }), diff --git a/typescript/src/providers/base.ts b/typescript/src/providers/base.ts index 28c5c9b..711c556 100644 --- a/typescript/src/providers/base.ts +++ b/typescript/src/providers/base.ts @@ -156,6 +156,18 @@ export abstract class CredentialProvider { return {}; } + /** + * Form fields that authenticate this agent as a confidential client. + * + * Descope's token-exchange grant requires the exchanging client to authenticate + * (it becomes `act.sub` on the minted token). Providers that hold a client secret + * return `client_id` + `client_secret`; the rest return `undefined` and cannot + * mint Resource tokens. + */ + tokenExchangeClientAuth(): Record | undefined { + return undefined; + } + // -- persistence -------------------------------------------------------- private async save(cred: Credential): Promise { diff --git a/typescript/src/providers/ciba.ts b/typescript/src/providers/ciba.ts index 685d4ca..cedc50e 100644 --- a/typescript/src/providers/ciba.ts +++ b/typescript/src/providers/ciba.ts @@ -200,4 +200,10 @@ export class CibaProvider extends CredentialProvider { if (this.clientSecret) out.client_secret = this.clientSecret; return out; } + + tokenExchangeClientAuth(): Record | undefined { + // Only a confidential CIBA client can authenticate a token exchange. + if (!this.clientSecret) return undefined; + return { client_id: this.clientId, client_secret: this.clientSecret }; + } } diff --git a/typescript/src/providers/clientCredentials.ts b/typescript/src/providers/clientCredentials.ts index 6a39d8d..314eb04 100644 --- a/typescript/src/providers/clientCredentials.ts +++ b/typescript/src/providers/clientCredentials.ts @@ -6,7 +6,7 @@ * authenticating as itself. */ -import { GRANT_CLIENT_CREDENTIALS, OAUTH2_TOKEN } from '../endpoints'; +import { GRANT_CLIENT_CREDENTIALS, OAUTH2_APPS_TOKEN } from '../endpoints'; import { CredentialAcquisitionFailed } from '../errors'; import { base64 } from '../runtime'; import { Credential } from '../types'; @@ -21,6 +21,9 @@ export interface ClientCredentialsOptions { export class ClientCredentialsProvider extends CredentialProvider { readonly kind = 'agent_token'; + // Agentic Clients are inbound apps: acquire and refresh on the inbound-apps server. + protected readonly refreshEndpoint = OAUTH2_APPS_TOKEN; + private readonly clientId: string; private readonly clientSecret: string; @@ -41,7 +44,9 @@ export class ClientCredentialsProvider extends CredentialProvider { protected async acquire(): Promise { const data: Record = { grant_type: GRANT_CLIENT_CREDENTIALS }; if (this.scopes.length) data.scope = this.scopes.join(' '); - const resp = await this.requireHttp().postForm(OAUTH2_TOKEN, data, { + // Agentic Clients are inbound apps, served by the /v1/apps/ + // authorization server, whose token endpoint is /oauth2/v1/apps/token. + const resp = await this.requireHttp().postForm(OAUTH2_APPS_TOKEN, data, { Authorization: this.basicAuth(), }); if (!resp.ok) { @@ -56,4 +61,8 @@ export class ClientCredentialsProvider extends CredentialProvider { protected storageKey(): string { return `cred:client_credentials:${this.projectId}:${this.clientId}`; } + + tokenExchangeClientAuth(): Record { + return { client_id: this.clientId, client_secret: this.clientSecret }; + } } diff --git a/typescript/src/resources.test.ts b/typescript/src/resources.test.ts index 3ed12a4..85fd161 100644 --- a/typescript/src/resources.test.ts +++ b/typescript/src/resources.test.ts @@ -3,7 +3,8 @@ import { BASE_URL, makeClient } from './testutils'; import { ClientCredentialsProvider, ManagementKeyProvider } from './providers'; import { AgentAuthError, PolicyDenied } from './errors'; -const TOKEN_PATH = '/oauth2/v1/token'; +// Agent client_credentials and token-exchange are both served by the inbound-apps server. +const TOKEN_PATH = '/oauth2/v1/apps/token'; const silentLogger = { debug: () => {}, warn: () => {} }; beforeAll(() => nock.disableNetConnect()); @@ -41,6 +42,58 @@ describe('ResourcesClient.getToken (token-exchange)', () => { expect(body.grant_type).toBe('urn:ietf:params:oauth:grant-type:token-exchange'); expect(body.resource).toBe('urn:my-api'); expect(body.subject_token).toBe('agent_at'); + // Descope requires the exchanging client to authenticate; it becomes act.sub. + expect(body.client_id).toBe('cid'); + expect(body.client_secret).toBe('s'); + }); + + it('authenticates the agent client on a user-scoped exchange', async () => { + let body: any; + nock(BASE_URL) + .post(TOKEN_PATH, (b) => { + body = b; + return true; + }) + .reply(200, { access_token: 'resource_at', expires_in: 3600 }); + + await makeClient( + new ClientCredentialsProvider({ clientId: 'cid', clientSecret: 's' }), + ).resources.getToken({ resource: 'urn:my-api', actAsUserToken: 'user_jwt' }); + + expect(body.subject_token).toBe('user_jwt'); + expect(body.client_id).toBe('cid'); + expect(body.client_secret).toBe('s'); + }); + + it('never serves one user’s token to another user (or the agent) from cache', async () => { + const minted: string[] = ['alice_resource_at', 'bob_resource_at', 'agent_at', 'agent_res_at']; + const scope = nock(BASE_URL) + .post(TOKEN_PATH) + .times(minted.length) + .reply(() => [200, { access_token: minted.shift(), expires_in: 3600 }]); + const client = makeClient( + new ClientCredentialsProvider({ clientId: 'cid', clientSecret: 's' }), + ); + + const alice = await client.resources.getToken({ + resource: 'urn:my-api', + actAsUserToken: 'alice_jwt', + }); + const bob = await client.resources.getToken({ + resource: 'urn:my-api', + actAsUserToken: 'bob_jwt', + }); + const aliceAgain = await client.resources.getToken({ + resource: 'urn:my-api', + actAsUserToken: 'alice_jwt', + }); + const own = await client.resources.getToken({ resource: 'urn:my-api' }); + + expect(alice.accessToken).toBe('alice_resource_at'); + expect(bob.accessToken).toBe('bob_resource_at'); + expect(aliceAgain.accessToken).toBe('alice_resource_at'); // cached per user + expect(own.accessToken).toBe('agent_res_at'); + expect(scope.isDone()).toBe(true); }); it('sends the audience claim (repeated params) on the token exchange', async () => { diff --git a/typescript/src/runtime.ts b/typescript/src/runtime.ts index 3ce1a79..a936f0f 100644 --- a/typescript/src/runtime.ts +++ b/typescript/src/runtime.ts @@ -47,9 +47,14 @@ export async function randomUrlToken(byteLength = 32): Promise { return toBase64Url(bytes); } -/** The SHA-256 PKCE code_challenge for a given verifier. */ -export async function sha256UrlChallenge(verifier: string): Promise { +/** Base64url SHA-256 digest of a UTF-8 string. */ +export async function sha256Base64Url(input: string): Promise { const c = await webCrypto(); - const digest = await c.subtle.digest('SHA-256', textEncoder.encode(verifier)); + const digest = await c.subtle.digest('SHA-256', textEncoder.encode(input)); return toBase64Url(new Uint8Array(digest)); } + +/** The SHA-256 PKCE code_challenge for a given verifier. */ +export async function sha256UrlChallenge(verifier: string): Promise { + return sha256Base64Url(verifier); +} diff --git a/typescript/src/tokenStorage.test.ts b/typescript/src/tokenStorage.test.ts index 687cf15..4050985 100644 --- a/typescript/src/tokenStorage.test.ts +++ b/typescript/src/tokenStorage.test.ts @@ -28,7 +28,7 @@ afterAll(() => nock.enableNetConnect()); describe('phase-1 credential persistence', () => { it('persists the credential and reuses it across instances (restart)', async () => { - nock(BASE_URL).post(TOKEN_PATH).reply(200, { access_token: 'agent_at', expires_in: 3600 }); + nock(BASE_URL).post(CIBA_TOKEN_PATH).reply(200, { access_token: 'agent_at', expires_in: 3600 }); const store = new MemoryTokenStore(); const first = client( diff --git a/typescript/src/userScoped.test.ts b/typescript/src/userScoped.test.ts index d746b8b..1e08cb6 100644 --- a/typescript/src/userScoped.test.ts +++ b/typescript/src/userScoped.test.ts @@ -3,7 +3,8 @@ import { BASE_URL, PROJECT_ID, makeClient, tokenObj } from './testutils'; import { AccessTokenProvider, ClientCredentialsProvider } from './providers'; const USER_LATEST = '/v1/mgmt/outbound/app/user/token/latest'; -const TOKEN_PATH = '/oauth2/v1/token'; +// Agent client_credentials and token-exchange are both served by the inbound-apps server. +const TOKEN_PATH = '/oauth2/v1/apps/token'; beforeAll(() => nock.disableNetConnect()); afterEach(() => nock.cleanAll()); @@ -34,21 +35,14 @@ describe('AccessTokenProvider (bring-your-own user token)', () => { expect(auth).toBe(`Bearer ${PROJECT_ID}:user_jwt`); }); - it('uses the user token as the token-exchange subject for resources', async () => { - let body: any; - nock(BASE_URL) - .post(TOKEN_PATH, (b) => { - body = b; - return true; - }) - .reply(200, { access_token: 'resource_at', expires_in: 3600, scope: 'read' }); - - const tok = await makeClient( - new AccessTokenProvider({ accessToken: 'user_jwt' }), - ).resources.getToken({ resource: 'urn:my-api', scopes: ['read'] }); + it('cannot mint Resource tokens without an agent client to authenticate the exchange', async () => { + // Descope only exchanges for an authenticated (confidential) client. Use a + // shared ClientCredentialsProvider client with actAsUserToken instead. + const client = makeClient(new AccessTokenProvider({ accessToken: 'user_jwt' })); - expect(tok.accessToken).toBe('resource_at'); - expect(body.subject_token).toBe('user_jwt'); + await expect( + client.resources.getToken({ resource: 'urn:my-api', scopes: ['read'] }), + ).rejects.toThrow(/ClientCredentialsProvider/); }); }); diff --git a/typescript/src/vault/resources.ts b/typescript/src/vault/resources.ts index ae00918..62156c2 100644 --- a/typescript/src/vault/resources.ts +++ b/typescript/src/vault/resources.ts @@ -11,12 +11,15 @@ * identity (Client ID/Secret via any phase-1 provider). It does not apply to a * Management Key. * - * NOTE: the exact token-exchange parameters (`resource` vs `audience`, whether - * client auth is also required) should be confirmed against the Descope API - * reference; the grant + endpoint are pinned in `endpoints`. + * The exchange goes to the inbound-apps token endpoint (`/oauth2/v1/apps/token`, + * per the `/v1/apps/` discovery document) and must be authenticated by a + * confidential client (`client_id` + `client_secret`). That client is recorded as + * `act.sub` on the minted token, so the downstream API can see which agent is + * acting for the user. */ -import { GRANT_TOKEN_EXCHANGE, OAUTH2_TOKEN, TOKEN_TYPE_ACCESS_TOKEN } from '../endpoints'; +import { GRANT_TOKEN_EXCHANGE, OAUTH2_APPS_TOKEN, TOKEN_TYPE_ACCESS_TOKEN } from '../endpoints'; +import { sha256Base64Url } from '../runtime'; import { AgentAuthError, PolicyDenied, TokenExchangeFailed } from '../errors'; import { HttpClient } from '../httpClient'; import { TokenStore } from '../store/base'; @@ -37,6 +40,8 @@ export interface GetResourceTokenArgs { export interface ResourcesClientDeps { http: HttpClient; getCredential: () => Promise; + /** Confidential-client auth for the exchange (`client_id` + `client_secret`), if any. */ + getClientAuth: () => Record | undefined; store: TokenStore; mode: Mode; approvalGate?: ApprovalGate; @@ -45,10 +50,19 @@ export interface ResourcesClientDeps { cacheTokens?: boolean; } -const cacheKey = (resource: string, scopes?: string[], audience?: string[]): string => { +const cacheKey = async ( + resource: string, + scopes?: string[], + audience?: string[], + actAsUserToken?: string, +): Promise => { const scopePart = scopes && scopes.length ? [...scopes].sort().join(',') : ''; const audPart = audience && audience.length ? [...audience].sort().join(',') : ''; - return `vault:resource:${resource}:${audPart}:${scopePart}`; + // A user-scoped token belongs to that user only: key it by a digest of the + // subject token so one shared client never serves user A's token to user B (or + // to the agent itself). The raw token never lands in a store key. + const subjectPart = actAsUserToken ? `user:${await sha256Base64Url(actAsUserToken)}` : 'agent'; + return `vault:resource:${subjectPart}:${resource}:${audPart}:${scopePart}`; }; const errMsg = (body: any): string | undefined => @@ -71,6 +85,18 @@ export class ResourcesClient { ); } + // Descope rejects unauthenticated token-exchange requests, and the + // authenticating client is what lands in act.sub. Fail before any network call + // (or approval prompt) when the provider has no client secret to offer. + const clientAuth = this.deps.getClientAuth(); + if (!clientAuth) { + throw new AgentAuthError( + 'Resource tokens use the token-exchange grant, which Descope only serves to an ' + + 'authenticated agent client. Configure the client with new ClientCredentialsProvider(' + + '{ clientId, clientSecret }) and pass actAsUserToken to act for a user.', + ); + } + if (args.requireApproval) { if (!this.deps.approvalGate) { throw new AgentAuthError( @@ -81,7 +107,7 @@ export class ResourcesClient { await this.deps.approvalGate(args.requireApproval); } - const key = cacheKey(args.resource, args.scopes, args.audience); + const key = await cacheKey(args.resource, args.scopes, args.audience, args.actAsUserToken); if (this.cacheTokens && !args.forceRefresh) { const cached = await this.cacheGet(key); if (cached) return cached; @@ -109,11 +135,12 @@ export class ResourcesClient { subject_token: subjectToken, subject_token_type: TOKEN_TYPE_ACCESS_TOKEN, resource: args.resource, + ...clientAuth, }; if (args.scopes && args.scopes.length) data.scope = args.scopes.join(' '); if (args.audience && args.audience.length) data.audience = args.audience; - const resp = await this.deps.http.postForm(OAUTH2_TOKEN, data); + const resp = await this.deps.http.postForm(OAUTH2_APPS_TOKEN, data); if (resp.statusCode === 401 || resp.statusCode === 403) { throw new PolicyDenied( `policy denied for resource '${args.resource}' ` + From ad1c7118e4731f83afe713d8516630732bb43a5a Mon Sep 17 00:00:00 2001 From: Kevin J Gao <32936811+gaokevin1@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:43:26 -0800 Subject: [PATCH 2/2] fix(resources): key Resource cache by client and subject; redact exchange tokens Address review on #47: - Key the Resource token cache by the authenticating client_id (act.sub) plus a SHA-256 of the subject token actually exchanged (the user's act_as_user_token or the phase-1 credential). The constant "agent" bucket let two clients, or two CIBA login_hints, share a token on a shared TokenStore. The subject is now resolved before the cache lookup. - Redact subject_token, actor_token and client_assertion in debug logs; a user's JWT on the act_as_user_token path was logged in clear text. - Docs: Resource tokens need a ClientCredentialsProvider client with act_as_user_token per call; AccessTokenProvider raises AgentAuthError. Updated README, AGENTS.md, quickstart and the AccessTokenProvider docstrings. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 9 ++- README.md | 23 ++++++-- docs/quickstart.md | 32 +++++++---- python/descope_agent_auth/_http.py | 4 ++ .../providers/access_token.py | 10 ++-- python/descope_agent_auth/vault/resources.py | 40 +++++++------ python/tests/test_exchange.py | 45 +++++++++++++++ python/tests/test_redaction.py | 16 ++++++ typescript/src/httpClient.ts | 4 ++ typescript/src/providers/accessToken.ts | 9 ++- typescript/src/redaction.test.ts | 13 +++++ typescript/src/resources.test.ts | 57 +++++++++++++++++++ typescript/src/vault/resources.ts | 40 ++++++++----- 13 files changed, 245 insertions(+), 57 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index adfe210..f28a3ed 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -110,9 +110,12 @@ One shared client, many users? Don't bind the client to one user — pass the us token per call instead: `get_token(..., act_as_user_token=user_jwt)` / `getToken({ ..., actAsUserToken: userJwt })`. -A user-scoped Resource token is the same idea: -`client.resources.get_token(resource="urn:my-api", scopes=["read"])` (the user is the -subject) or `resources.getToken({ resource: 'urn:my-api', actAsUserToken: userJwt })`. +A user-scoped Resource token always takes the per-call form, on a client built with +`ClientCredentialsProvider` (Descope only serves token exchange to an authenticated +confidential client, which becomes `act.sub`; an `AccessTokenProvider` client raises +`AgentAuthError`): +`agent.resources.get_token(resource="urn:my-api", scopes=["read"], act_as_user_token=user_jwt)` / +`agent.resources.getToken({ resource: 'urn:my-api', scopes: ['read'], actAsUserToken: userJwt })`. --- diff --git a/README.md b/README.md index 1ae3af7..a3d4954 100644 --- a/README.md +++ b/README.md @@ -225,13 +225,19 @@ or CIBA), or use a management key: ```python from descope_agent_auth import AccessTokenProvider -# Bind the client to the user's token: +# Bind the client to the user's token (Connection tokens): client = AgentAuthClient(project_id="P2...", credential=AccessTokenProvider(access_token=user_jwt)) gh = client.connections.get_token(connection="github", identifier=user_id) -res = client.resources.get_token(resource="urn:my-api", scopes=["read"]) -# Or pass the user token per call on a shared client: -gh = client.connections.get_token(connection="github", identifier=user_id, act_as_user_token=user_jwt) +# Or pass the user token per call on a shared agent client. Resource tokens need +# this form: the token exchange must be authenticated by a confidential client, +# which Descope records as the actor (act.sub). +agent = AgentAuthClient( + project_id="P2...", + credential=ClientCredentialsProvider(client_id="...", client_secret="..."), +) +gh = agent.connections.get_token(connection="github", identifier=user_id, act_as_user_token=user_jwt) +res = agent.resources.get_token(resource="urn:my-api", scopes=["read"], act_as_user_token=user_jwt) ``` ```ts @@ -240,8 +246,13 @@ import { AccessTokenProvider } from '@descope/agent-auth'; const client = new AgentAuthClient({ projectId: 'P2...', credential: new AccessTokenProvider({ accessToken: userJwt }) }); await client.connections.getToken({ connection: 'github', identifier: userId }); -// or per call on a shared client: -await client.connections.getToken({ connection: 'github', identifier: userId, actAsUserToken: userJwt }); +// or per call on a shared agent client (required for Resource tokens): +const agent = new AgentAuthClient({ + projectId: 'P2...', + credential: new ClientCredentialsProvider({ clientId: '...', clientSecret: '...' }), +}); +await agent.connections.getToken({ connection: 'github', identifier: userId, actAsUserToken: userJwt }); +await agent.resources.getToken({ resource: 'urn:my-api', scopes: ['read'], actAsUserToken: userJwt }); ``` **Management key (trusted backend, no user token).** Reads **any** user's token by diff --git a/docs/quickstart.md b/docs/quickstart.md index 4780202..3d6e520 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -197,30 +197,42 @@ const repos = await listRepos('user@example.com'); ### User-scoped access -To act as a specific user — and to mint user-scoped Resource tokens — present that -user's Descope access token. Configure the client with `AccessTokenProvider`, or pass -`act_as_user_token` / `actAsUserToken` per call on a shared client: +To act as a specific user, present that user's Descope access token. For Connection +tokens, configure the client with `AccessTokenProvider`, or pass `act_as_user_token` / +`actAsUserToken` per call on a shared client. User-scoped **Resource** tokens always +use the per-call form on a `ClientCredentialsProvider` client: Descope only serves +token exchange to an authenticated confidential client, and records it as the actor +(`act.sub`). An `AccessTokenProvider` client raises `AgentAuthError` there. ```python -from descope_agent_auth import AccessTokenProvider +from descope_agent_auth import AccessTokenProvider, ClientCredentialsProvider # A — client bound to the user's token: client = AgentAuthClient(project_id="P2...", credential=AccessTokenProvider(access_token=user_jwt)) gh = client.connections.get_token(connection="github", identifier=user_id) -# B — one shared client, user token per call: -gh = client.connections.get_token(connection="github", identifier=user_id, act_as_user_token=user_jwt) -res = client.resources.get_token(resource="urn:my-api", act_as_user_token=user_jwt) +# B — one shared agent client, user token per call: +agent = AgentAuthClient( + project_id="P2...", + credential=ClientCredentialsProvider(client_id="...", client_secret="..."), +) +gh = agent.connections.get_token(connection="github", identifier=user_id, act_as_user_token=user_jwt) +res = agent.resources.get_token(resource="urn:my-api", act_as_user_token=user_jwt) ``` ```ts -import { AccessTokenProvider } from '@descope/agent-auth'; +import { AccessTokenProvider, ClientCredentialsProvider } from '@descope/agent-auth'; const client = new AgentAuthClient({ projectId: 'P2...', credential: new AccessTokenProvider({ accessToken: userJwt }) }); await client.connections.getToken({ connection: 'github', identifier: userId }); -// or per call on a shared client: -await client.connections.getToken({ connection: 'github', identifier: userId, actAsUserToken: userJwt }); +// or per call on a shared agent client: +const agent = new AgentAuthClient({ + projectId: 'P2...', + credential: new ClientCredentialsProvider({ clientId: '...', clientSecret: '...' }), +}); +await agent.connections.getToken({ connection: 'github', identifier: userId, actAsUserToken: userJwt }); +await agent.resources.getToken({ resource: 'urn:my-api', actAsUserToken: userJwt }); ``` ### Management key (trusted backend, no user token) diff --git a/python/descope_agent_auth/_http.py b/python/descope_agent_auth/_http.py index 71ec894..838bf30 100644 --- a/python/descope_agent_auth/_http.py +++ b/python/descope_agent_auth/_http.py @@ -32,6 +32,10 @@ "device_code", "auth_req_id", "assertion", + "client_assertion", + # RFC 8693 token exchange: the user's (or agent's) token being exchanged. + "subject_token", + "actor_token", # Not a credential, but carries the transaction (amounts, account numbers). "authorization_details", } diff --git a/python/descope_agent_auth/providers/access_token.py b/python/descope_agent_auth/providers/access_token.py index 56bd51a..37348b0 100644 --- a/python/descope_agent_auth/providers/access_token.py +++ b/python/descope_agent_auth/providers/access_token.py @@ -10,12 +10,14 @@ project_id="P2...", credential=AccessTokenProvider(access_token=user_jwt), ) - # user-scoped: vault fetch + token-exchange both run as this user + # user-scoped: the vault fetch runs as this user gh = client.connections.get_token(connection="github", identifier=user_id) -For a single shared (autonomous) client serving many users, prefer the per-call -``act_as_user_token=`` override on ``connections.get_token`` / ``resources.get_token`` -instead of constructing a client per user. +This provider holds no client secret, so it cannot authenticate a token exchange: +``resources.get_token`` raises ``AgentAuthError`` on such a client. For user-scoped +Resource tokens, and for a single shared client serving many users, build the client +with ``ClientCredentialsProvider`` and pass ``act_as_user_token=`` per call on +``connections.get_token`` / ``resources.get_token``. """ from __future__ import annotations diff --git a/python/descope_agent_auth/vault/resources.py b/python/descope_agent_auth/vault/resources.py index 376384d..953a11e 100644 --- a/python/descope_agent_auth/vault/resources.py +++ b/python/descope_agent_auth/vault/resources.py @@ -36,18 +36,19 @@ def _cache_key( resource: str, scopes: Optional[List[str]], audience: Optional[List[str]], - act_as_user_token: Optional[str] = None, + *, + client_id: str, + subject_token: str, ) -> str: scope_part = ",".join(sorted(scopes)) if scopes else "" aud_part = ",".join(sorted(audience)) if audience else "" - # A user-scoped token belongs to that user only: key it by a digest of the - # subject token so one shared client never serves user A's token to user B - # (or to the agent itself). The raw token never lands in a store key. - if act_as_user_token: - subject_part = "user:" + hashlib.sha256(act_as_user_token.encode("utf-8")).hexdigest() - else: - subject_part = "agent" - return f"vault:resource:{subject_part}:{resource}:{aud_part}:{scope_part}" + # A Resource token belongs to one (actor, subject) pair: the client that + # authenticates the exchange (act.sub) and the token being exchanged (a + # user's token, or the phase-1 credential, which can itself be user-bound, + # e.g. CIBA). Key by both so a shared TokenStore never serves one client's or + # one user's token to another. Only a digest of the subject lands in the key. + subject_part = hashlib.sha256(subject_token.encode("utf-8")).hexdigest() + return f"vault:resource:{client_id}:{subject_part}:{resource}:{aud_part}:{scope_part}" def _err(body: Optional[dict]) -> Optional[str]: @@ -128,15 +129,10 @@ async def get_token( ) await self._approval_gate(require_approval) - cache_key = _cache_key(resource, scopes, audience, act_as_user_token) - if self._cache_tokens and not force_refresh: - cached = await self._cache_get(cache_key) - if cached is not None: - return cached - # The subject is either an explicit user token (user-scoped) or the # client's own credential. A Management Key is not an OAuth token, so it - # cannot be the subject of a token-exchange. + # cannot be the subject of a token-exchange. Resolve it before the cache + # lookup: the cache key is bound to the subject actually exchanged. if act_as_user_token: subject_token = act_as_user_token else: @@ -149,6 +145,18 @@ async def get_token( ) subject_token = cred.token + cache_key = _cache_key( + resource, + scopes, + audience, + client_id=client_auth.get("client_id", ""), + subject_token=subject_token, + ) + if self._cache_tokens and not force_refresh: + cached = await self._cache_get(cache_key) + if cached is not None: + return cached + data: dict = { "grant_type": GRANT_TOKEN_EXCHANGE, "subject_token": subject_token, diff --git a/python/tests/test_exchange.py b/python/tests/test_exchange.py index eaee2ca..3495507 100644 --- a/python/tests/test_exchange.py +++ b/python/tests/test_exchange.py @@ -16,6 +16,8 @@ TokenExchangeFailed, ) +from descope_agent_auth.store.memory import MemoryTokenStore + from . import common from .common import PROJECT_ID, make_response, token_obj @@ -383,6 +385,49 @@ def test_user_scoped_token_is_not_served_to_the_agent_itself(self, mock_request) self.assertEqual(own.access_token, "agent_resource_at") + @patch("httpx.AsyncClient.request", new_callable=AsyncMock) + def test_shared_store_does_not_mix_agent_clients_for_one_user(self, mock_request): + # Two agentic clients on one shared store, acting for the same user, must + # each get a token minted with themselves as act.sub. + mock_request.side_effect = [ + make_response({"access_token": "a_resource_at", "expires_in": 3600}), + make_response({"access_token": "b_resource_at", "expires_in": 3600}), + ] + store = MemoryTokenStore() + a = self.make_client(ClientCredentialsProvider(client_id="a", client_secret="s"), store=store) + b = self.make_client(ClientCredentialsProvider(client_id="b", client_secret="s"), store=store) + + tok_a = a.resources.get_token(resource="urn:my-api", act_as_user_token="alice_jwt") + tok_b = b.resources.get_token(resource="urn:my-api", act_as_user_token="alice_jwt") + + self.assertEqual(tok_a.access_token, "a_resource_at") + self.assertEqual(tok_b.access_token, "b_resource_at") + self.assertEqual(mock_request.call_args.kwargs["data"]["client_id"], "b") + + @patch("httpx.AsyncClient.request", new_callable=AsyncMock) + def test_shared_store_does_not_mix_agent_own_tokens(self, mock_request): + # Without act_as_user_token the subject is each client's own phase-1 + # credential; a shared store must not serve one client's Resource token + # to another client. + mock_request.side_effect = [ + make_response({"access_token": "a_agent_at", "expires_in": 3600}), # a phase 1 + make_response({"access_token": "a_resource_at", "expires_in": 3600}), + make_response({"access_token": "b_agent_at", "expires_in": 3600}), # b phase 1 + make_response({"access_token": "b_resource_at", "expires_in": 3600}), + ] + store = MemoryTokenStore() + a = self.make_client(ClientCredentialsProvider(client_id="a", client_secret="s"), store=store) + b = self.make_client(ClientCredentialsProvider(client_id="b", client_secret="s"), store=store) + + tok_a = a.resources.get_token(resource="urn:my-api") + tok_b = b.resources.get_token(resource="urn:my-api") + tok_a_again = a.resources.get_token(resource="urn:my-api") + + self.assertEqual(tok_a.access_token, "a_resource_at") + self.assertEqual(tok_b.access_token, "b_resource_at") + self.assertEqual(tok_a_again.access_token, "a_resource_at") # still cached + self.assertEqual(mock_request.call_count, 4) + @patch("httpx.AsyncClient.request", new_callable=AsyncMock) def test_exchange_without_confidential_client_is_rejected(self, mock_request): # A bare user token has no client to authenticate the exchange, and diff --git a/python/tests/test_redaction.py b/python/tests/test_redaction.py index 3130985..ed079de 100644 --- a/python/tests/test_redaction.py +++ b/python/tests/test_redaction.py @@ -17,6 +17,22 @@ def test_masks_sensitive_keys(self): self.assertEqual(masked["client_id"], "cid") # not sensitive self.assertEqual(masked["scope"], "read") + def test_masks_token_exchange_tokens(self): + masked = _redact( + { + "subject_token": "user.jwt", + "actor_token": "agent.jwt", + "client_assertion": "signed.jwt", + "subject_token_type": "urn:ietf:params:oauth:token-type:access_token", + } + ) + self.assertEqual(masked["subject_token"], _REDACTED) + self.assertEqual(masked["actor_token"], _REDACTED) + self.assertEqual(masked["client_assertion"], _REDACTED) + self.assertEqual( + masked["subject_token_type"], "urn:ietf:params:oauth:token-type:access_token" + ) + def test_masks_authorization_details(self): masked = _redact( {"authorization_details": '[{"type":"payment_initiation","amount":"15.00"}]'} diff --git a/typescript/src/httpClient.ts b/typescript/src/httpClient.ts index 43df51b..7d40900 100644 --- a/typescript/src/httpClient.ts +++ b/typescript/src/httpClient.ts @@ -24,6 +24,10 @@ const SENSITIVE_KEYS = new Set([ 'device_code', 'auth_req_id', 'assertion', + 'client_assertion', + // RFC 8693 token exchange: the user's (or agent's) token being exchanged. + 'subject_token', + 'actor_token', // Not a credential, but carries the transaction (amounts, account numbers). 'authorization_details', ]); diff --git a/typescript/src/providers/accessToken.ts b/typescript/src/providers/accessToken.ts index 7b5c496..31d878b 100644 --- a/typescript/src/providers/accessToken.ts +++ b/typescript/src/providers/accessToken.ts @@ -11,11 +11,14 @@ * projectId: 'P2...', * credential: new AccessTokenProvider({ accessToken: userJwt }), * }); - * // user-scoped: vault fetch + token-exchange both run as this user + * // user-scoped: the vault fetch runs as this user * const gh = await client.connections.getToken({ connection: 'github', identifier: userId }); * - * For a single shared (autonomous) client serving many users, prefer the per-call - * `actAsUserToken` override on `connections.getToken` / `resources.getToken`. + * This provider holds no client secret, so it cannot authenticate a token exchange: + * `resources.getToken` throws `AgentAuthError` on such a client. For user-scoped + * Resource tokens, and for a single shared client serving many users, build the + * client with `ClientCredentialsProvider` and pass `actAsUserToken` per call on + * `connections.getToken` / `resources.getToken`. */ import { Credential } from '../types'; diff --git a/typescript/src/redaction.test.ts b/typescript/src/redaction.test.ts index 8dd03c6..ad943af 100644 --- a/typescript/src/redaction.test.ts +++ b/typescript/src/redaction.test.ts @@ -16,6 +16,19 @@ describe('redact (log masking)', () => { expect(masked.scope).toBe('read'); }); + it('masks token-exchange tokens', () => { + const masked = redact({ + subject_token: 'user.jwt', + actor_token: 'agent.jwt', + client_assertion: 'signed.jwt', + subject_token_type: 'urn:ietf:params:oauth:token-type:access_token', + }); + expect(masked.subject_token).toBe(REDACTED); + expect(masked.actor_token).toBe(REDACTED); + expect(masked.client_assertion).toBe(REDACTED); + expect(masked.subject_token_type).toBe('urn:ietf:params:oauth:token-type:access_token'); + }); + it('masks authorization_details (transaction data)', () => { const masked = redact({ authorization_details: '[{"type":"payment_initiation"}]' }); expect(masked.authorization_details).toBe(REDACTED); diff --git a/typescript/src/resources.test.ts b/typescript/src/resources.test.ts index 85fd161..8768408 100644 --- a/typescript/src/resources.test.ts +++ b/typescript/src/resources.test.ts @@ -2,6 +2,7 @@ import nock from 'nock'; import { BASE_URL, makeClient } from './testutils'; import { ClientCredentialsProvider, ManagementKeyProvider } from './providers'; import { AgentAuthError, PolicyDenied } from './errors'; +import { MemoryTokenStore } from './store'; // Agent client_credentials and token-exchange are both served by the inbound-apps server. const TOKEN_PATH = '/oauth2/v1/apps/token'; @@ -96,6 +97,62 @@ describe('ResourcesClient.getToken (token-exchange)', () => { expect(scope.isDone()).toBe(true); }); + it('never mixes two agent clients on a shared store (same user)', async () => { + const bodies: any[] = []; + const minted = ['a_resource_at', 'b_resource_at']; + nock(BASE_URL) + .post(TOKEN_PATH, (b) => { + bodies.push(b); + return true; + }) + .times(2) + .reply(() => [200, { access_token: minted.shift(), expires_in: 3600 }]); + const store = new MemoryTokenStore(); + const a = makeClient(new ClientCredentialsProvider({ clientId: 'a', clientSecret: 's' }), { + store, + }); + const b = makeClient(new ClientCredentialsProvider({ clientId: 'b', clientSecret: 's' }), { + store, + }); + + const tokA = await a.resources.getToken({ + resource: 'urn:my-api', + actAsUserToken: 'alice_jwt', + }); + const tokB = await b.resources.getToken({ + resource: 'urn:my-api', + actAsUserToken: 'alice_jwt', + }); + + expect(tokA.accessToken).toBe('a_resource_at'); + expect(tokB.accessToken).toBe('b_resource_at'); + expect(bodies[1].client_id).toBe('b'); + }); + + it('never mixes two agent clients’ own tokens on a shared store', async () => { + const minted = ['a_agent_at', 'a_resource_at', 'b_agent_at', 'b_resource_at']; + const scope = nock(BASE_URL) + .post(TOKEN_PATH) + .times(minted.length) + .reply(() => [200, { access_token: minted.shift(), expires_in: 3600 }]); + const store = new MemoryTokenStore(); + const a = makeClient(new ClientCredentialsProvider({ clientId: 'a', clientSecret: 's' }), { + store, + }); + const b = makeClient(new ClientCredentialsProvider({ clientId: 'b', clientSecret: 's' }), { + store, + }); + + const tokA = await a.resources.getToken({ resource: 'urn:my-api' }); + const tokB = await b.resources.getToken({ resource: 'urn:my-api' }); + const tokAAgain = await a.resources.getToken({ resource: 'urn:my-api' }); + + expect(tokA.accessToken).toBe('a_resource_at'); + expect(tokB.accessToken).toBe('b_resource_at'); + expect(tokAAgain.accessToken).toBe('a_resource_at'); // still cached + expect(scope.isDone()).toBe(true); + }); + it('sends the audience claim (repeated params) on the token exchange', async () => { const client = agentClient(); let body: any; diff --git a/typescript/src/vault/resources.ts b/typescript/src/vault/resources.ts index 62156c2..37c41b4 100644 --- a/typescript/src/vault/resources.ts +++ b/typescript/src/vault/resources.ts @@ -52,17 +52,20 @@ export interface ResourcesClientDeps { const cacheKey = async ( resource: string, - scopes?: string[], - audience?: string[], - actAsUserToken?: string, + scopes: string[] | undefined, + audience: string[] | undefined, + clientId: string, + subjectToken: string, ): Promise => { const scopePart = scopes && scopes.length ? [...scopes].sort().join(',') : ''; const audPart = audience && audience.length ? [...audience].sort().join(',') : ''; - // A user-scoped token belongs to that user only: key it by a digest of the - // subject token so one shared client never serves user A's token to user B (or - // to the agent itself). The raw token never lands in a store key. - const subjectPart = actAsUserToken ? `user:${await sha256Base64Url(actAsUserToken)}` : 'agent'; - return `vault:resource:${subjectPart}:${resource}:${audPart}:${scopePart}`; + // A Resource token belongs to one (actor, subject) pair: the client that + // authenticates the exchange (act.sub) and the token being exchanged (a user's + // token, or the phase-1 credential, which can itself be user-bound, e.g. CIBA). + // Key by both so a shared TokenStore never serves one client's or one user's + // token to another. Only a digest of the subject lands in the key. + const subjectPart = await sha256Base64Url(subjectToken); + return `vault:resource:${clientId}:${subjectPart}:${resource}:${audPart}:${scopePart}`; }; const errMsg = (body: any): string | undefined => @@ -107,15 +110,10 @@ export class ResourcesClient { await this.deps.approvalGate(args.requireApproval); } - const key = await cacheKey(args.resource, args.scopes, args.audience, args.actAsUserToken); - if (this.cacheTokens && !args.forceRefresh) { - const cached = await this.cacheGet(key); - if (cached) return cached; - } - // The subject is either an explicit user token (user-scoped) or the client's // own credential. A Management Key is not an OAuth token, so it cannot be the - // subject of a token-exchange. + // subject of a token-exchange. Resolve it before the cache lookup: the cache + // key is bound to the subject actually exchanged. let subjectToken: string; if (args.actAsUserToken) { subjectToken = args.actAsUserToken; @@ -130,6 +128,18 @@ export class ResourcesClient { subjectToken = cred.token; } + const key = await cacheKey( + args.resource, + args.scopes, + args.audience, + clientAuth.client_id ?? '', + subjectToken, + ); + if (this.cacheTokens && !args.forceRefresh) { + const cached = await this.cacheGet(key); + if (cached) return cached; + } + const data: Record = { grant_type: GRANT_TOKEN_EXCHANGE, subject_token: subjectToken,