Skip to content
Open
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
9 changes: 6 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 })`.

---

Expand Down
23 changes: 17 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
32 changes: 22 additions & 10 deletions docs/quickstart.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
10 changes: 5 additions & 5 deletions python/descope_agent_auth/_endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
discovery document (``/<project_id>/.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.
"""
Expand All @@ -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/<project_id>/.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).
Expand Down
4 changes: 4 additions & 0 deletions python/descope_agent_auth/_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
}
Expand Down Expand Up @@ -141,7 +145,7 @@
self._log.debug(
"descope request %s %s body=%s headers=%s (attempt %d)",
method,
path,

Check failure

Code scanning / CodeQL

Clear-text logging of sensitive information High

This expression logs
sensitive data (password)
as clear text.
This expression logs sensitive data (password) as clear text.
_redact(json or data),
_redact(headers),
attempt,
Expand All @@ -166,7 +170,7 @@
parsed = resp.json()
except ValueError:
parsed = None
self._log.debug("descope response %s %s -> %d", method, path, resp.status_code)

Check failure

Code scanning / CodeQL

Clear-text logging of sensitive information High

This expression logs
sensitive data (password)
as clear text.
This expression logs sensitive data (password) as clear text.
return HttpResponse(status_code=resp.status_code, json=parsed, text=resp.text)

# Only reached if all attempts raised transport errors.
Expand Down
1 change: 1 addition & 0 deletions python/descope_agent_auth/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
10 changes: 6 additions & 4 deletions python/descope_agent_auth/providers/access_token.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 11 additions & 1 deletion python/descope_agent_auth/providers/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
8 changes: 7 additions & 1 deletion python/descope_agent_auth/providers/ciba.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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:
Expand Down
13 changes: 10 additions & 3 deletions python/descope_agent_auth/providers/client_credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,18 @@
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


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,
Expand All @@ -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/<projectId>
# 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(
Expand All @@ -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}
Loading
Loading