Skip to content

Commit 9813b23

Browse files
feat: add Session Transfer Token support for CTE impersonation via session transfer (#139)
* feat: add Session Transfer Token (STT) support for CTE impersonation via session transfer Adds the initiator surface for Impersonation via Session Transfer on top of Custom Token Exchange: - request_session_transfer_token: mints an STT against the urn:{domain}:session_transfer audience. The actor is auto-sourced from the agent session's ID token (verified via JWKS, refreshed when expired) and overridable via an explicit actor_token; a blank actor_token is rejected, and no usable actor fails client-side with ACTOR_UNAVAILABLE before any network call. - build_session_transfer_redirect: builds the URL-encoded redirect that hands the STT to the target app's login URL (organization forwarded when present). - SessionTransferTokenResult model and the ACTOR_UNAVAILABLE / SETACTOR_REQUIRED / SESSION_TRANSFER_DISABLED error codes. - Developer guide (examples/CustomTokenExchange.md) + README pointer, and a Session Transfer Token test section covering actor resolution, the refresh path, stateless minting, error cases, and the redirect builder. Target-side redemption needs no new SDK code: start_interactive_login already forwards session_transfer_token to /authorize. * fix: address STT review feedback on PR #139 - Validate the redirect target URL in build_session_transfer_redirect: require an absolute https URL (http allowed only for localhost/loopback), via a reusable URL.validate_https_redirect_target helper. Prevents leaking the single-use STT to an untrusted host. - Surface issued_token_type exactly as the server returned it instead of defaulting to the STT URN, so a non-STT response is not mislabelled. - Validate subject_token/subject_token_type up front, before any session read or network. - Narrow the swallowed exceptions in actor resolution: the refresh catches only ApiError/AccessTokenError and _is_id_token_usable only token-verification errors, so infrastructure failures propagate instead of being masked as ACTOR_UNAVAILABLE. - Source the refresh domain from the session (resolver-safe) and reject an actor sourced from a session on a different domain in resolver mode. - Note the aud==client_id assumption in _is_id_token_usable. - Add tests for redirect validation, issued_token_type passthrough, up-front subject validation, and the actor-resolution paths. * fix: reject fragment in STT redirect target and cover the server-error path - validate_https_redirect_target now rejects a target_login_url with a fragment: appending the query after a fragment would place the STT inside the fragment, silently dropping the single-use token before it reaches the target's login handler. - Add a test asserting a server 400 on the STT exchange surfaces as CustomTokenExchangeError carrying the server's error/error_description. --------- Co-authored-by: nandan-bhat <167290944+nandan-bhat@users.noreply.github.com>
1 parent f6b54e8 commit 9813b23

7 files changed

Lines changed: 737 additions & 4 deletions

File tree

README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,11 @@ response = await auth0.custom_token_exchange(
147147
print(response.access_token)
148148
```
149149

150+
Building on token exchange, the SDK also supports:
151+
152+
- **[Delegation and Impersonation](examples/CustomTokenExchange.md#3-actor-tokens-delegation)** - exchange with an `actor_token` so the issued tokens record who is acting on whose behalf (the `act` claim).
153+
- **[Impersonation via Session Transfer (STT)](examples/CustomTokenExchange.md#8-impersonation-via-session-transfer-stt)** - mint a Session Transfer Token to log an agent into a target app as a customer, via `request_session_transfer_token()` and `build_session_transfer_redirect()`.
154+
150155
For more details and examples, see [examples/CustomTokenExchange.md](examples/CustomTokenExchange.md).
151156

152157
### 5. Multiple Custom Domains (MCD)

examples/CustomTokenExchange.md

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,92 @@ Use standard URNs when possible:
179179
"urn:company:legacy-token"
180180
```
181181

182+
## 8. Impersonation via Session Transfer (STT)
183+
184+
Custom Token Exchange can also mint a **Session Transfer Token (STT)** instead of an API access token. An STT lets an initiator app (for example a support console) log an agent into a target web app **as** a customer, with the agent recorded in the `act` claim - so a support engineer can reproduce a customer's exact experience without their password.
185+
186+
This is a two-role, two-hop flow:
187+
188+
- **Initiator** (the agent's app) mints the STT and redirects with it. This is where the new SDK methods live.
189+
- **Target** (the customer's app) forwards the STT to `/authorize` on a normal interactive login, which establishes the impersonated session.
190+
191+
The STT is opaque, single-use, and short-lived (~60s). The SDK requests it and helps build the redirect - it never decodes or stores it.
192+
193+
### Initiator: request an STT and build the redirect
194+
195+
```python
196+
from auth0_server_python.auth_server.server_client import ServerClient
197+
from auth0_server_python.error import CustomTokenExchangeError
198+
199+
# Mint the STT. The audience (urn:{domain}:session_transfer), grant type, and the actor are
200+
# set by the SDK - the actor is sourced from the logged-in agent's session.
201+
result = await auth0.request_session_transfer_token(
202+
subject_token=subject_token, # your proof of which customer to impersonate
203+
subject_token_type="urn:acme:customer-subject",
204+
organization=None, # optional; forwarded to the redirect
205+
store_options={"request": request, "response": None},
206+
)
207+
208+
# result.session_transfer_token is the opaque, one-shot STT (~60s). Never store it.
209+
redirect_url = auth0.build_session_transfer_redirect(
210+
"https://customer-app.example.com/auth/login", result, organization=None
211+
)
212+
return RedirectResponse(redirect_url) # your framework performs the redirect
213+
```
214+
215+
`SessionTransferTokenResult` carries `session_transfer_token`, `issued_token_type` (the session-transfer URN - the field to branch on), `expires_in`, and an informational `token_type` (`N_A`). There is no `act` on this result; `act` appears later, on the target session.
216+
217+
> **NOTE**: An actor is mandatory - an STT is only issued when the Action set one. By default the SDK sources the actor from the logged-in agent's session ID token, refreshing it when expired. If the agent is not logged in (no usable session ID token and none can be refreshed), the call fails client-side with `ACTOR_UNAVAILABLE` before any network request.
218+
219+
> **NOTE**: To use your own actor token instead of the session, pass `actor_token` (and optionally `actor_token_type`, which defaults to the ID token URN). An explicit `actor_token` takes precedence and the session is not read at all. It must be an **unexpired, asymmetrically-signed JWT** (RS256 or PS256) - an Auth0 session ID token satisfies this; an HS256 or expired token is rejected by the server.
220+
>
221+
> ```python
222+
> result = await auth0.request_session_transfer_token(
223+
> subject_token=subject_token,
224+
> subject_token_type="urn:acme:customer-subject",
225+
> actor_token=agent_id_token, # explicit override - session is not used
226+
> store_options={"request": request, "response": None},
227+
> )
228+
> ```
229+
230+
### Target: forward the STT to `/authorize`
231+
232+
On the target, the STT rides through your normal login. `start_interactive_login` forwards arbitrary authorization parameters to `/authorize`, so your login route just passes `session_transfer_token` (and `organization`, when the STT was issued in an org context) straight through:
233+
234+
```python
235+
from auth0_server_python.auth_types import StartInteractiveLoginOptions
236+
237+
url = await auth0.start_interactive_login(
238+
StartInteractiveLoginOptions(authorization_params={
239+
"session_transfer_token": request.query_params["session_transfer_token"],
240+
# "organization": org, # when the STT was issued in an org context
241+
}),
242+
store_options={"request": request, "response": None},
243+
)
244+
return RedirectResponse(url)
245+
```
246+
247+
After the callback completes, read the acting party off the session user - the same way as the [Actor Tokens (Delegation)](#3-actor-tokens-delegation) section above:
248+
249+
```python
250+
session = await auth0.get_session(store_options={"request": request, "response": None})
251+
act = (session or {}).get("user", {}).get("act")
252+
if act:
253+
print(f"Impersonated by: {act['sub']}") # drive an impersonation banner, etc.
254+
```
255+
256+
> **NOTE**: Both clients need one-time configuration through the Auth0 Dashboard or Management API. The issuing (initiator) client must be allowed to create session transfer tokens. The redeeming (target) client must be allowed to accept delegated-access sessions and to receive the token as a query parameter. See the [Auth0 documentation](https://auth0.com/docs/authenticate/custom-token-exchange) for the exact client settings.
257+
258+
> **NOTE**: `build_session_transfer_redirect` attaches a single-use credential to `target_login_url`, so that URL must be a trusted, app-controlled value - never one derived from untrusted input (such as a user-supplied `returnTo`), which could leak the token to an attacker host.
259+
260+
> **NOTE**: The impersonation session is hard-capped at 2 hours and cannot mint a refresh token (`offline_access` is dropped when an actor is present). To continue past that, re-run the flow.
261+
262+
### STT error codes
263+
264+
- `ACTOR_UNAVAILABLE`: no usable actor token (client-side; raised before any network call)
265+
- `SETACTOR_REQUIRED`: an STT was requested but the Action did not call `setActor` (server 400)
266+
- `SESSION_TRANSFER_DISABLED`: the session-transfer feature is not enabled for the tenant/client (server 400)
267+
182268
## Additional Resources
183269

184270
- [Auth0 Custom Token Exchange Documentation](https://auth0.com/docs/authenticate/custom-token-exchange)

src/auth0_server_python/auth_server/server_client.py

Lines changed: 214 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
PasskeySignupChallengeResponse,
4242
PasskeyTokenResponse,
4343
PasskeyUserProfile,
44+
SessionTransferTokenResult,
4445
StartInteractiveLoginOptions,
4546
StateData,
4647
TokenExchangeResponse,
@@ -86,6 +87,12 @@
8687
INTERNAL_AUTHORIZE_PARAMS = ["client_id", "response_type",
8788
"code_challenge", "code_challenge_method", "state", "nonce", "scope"]
8889

90+
# issued_token_type URN for a Session Transfer Token (STT).
91+
SESSION_TRANSFER_TOKEN_TYPE = "urn:auth0:params:oauth:token-type:session_transfer_token"
92+
93+
# actor_token_type URN when the actor is sourced from the agent session's ID token.
94+
ID_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:id_token"
95+
8996

9097
class ServerClient(Generic[TStoreOptions]):
9198
"""
@@ -2635,6 +2642,213 @@ async def login_with_custom_token_exchange(
26352642
e
26362643
)
26372644

2645+
# ============================================================================
2646+
# SESSION TRANSFER TOKEN (STT)
2647+
# Impersonation via Session Transfer, built on Custom Token Exchange.
2648+
# ============================================================================
2649+
2650+
async def _is_id_token_usable(self, token: str, store_options: Optional[dict[str, Any]]) -> bool:
2651+
"""
2652+
Verifies the agent session's ID token (signature + expiry) before using it as an actor.
2653+
2654+
Full verification against JWKS - the same path the login callback uses - so an expired
2655+
or tampered token is rejected client-side rather than sent to the server as a dud.
2656+
"""
2657+
if not token:
2658+
return False
2659+
domain = await self._resolve_current_domain(store_options)
2660+
metadata = await self._get_oidc_metadata_cached(domain)
2661+
jwks = await self._get_jwks_cached(domain, metadata)
2662+
try:
2663+
# aud is the client_id for a standard Auth0 ID token.
2664+
await self._verify_and_decode_jwt(token, jwks, audience=self._client_id)
2665+
return True
2666+
except (jwt.PyJWTError, ValueError):
2667+
# Only token-level failures mean "unusable"; infra errors (JWKS fetch, domain
2668+
# resolution) propagate above rather than being masked as ACTOR_UNAVAILABLE.
2669+
return False
2670+
2671+
async def _resolve_actor_token(
2672+
self,
2673+
actor_token: Optional[str],
2674+
actor_token_type: Optional[str],
2675+
store_options: Optional[dict[str, Any]]
2676+
) -> tuple[str, str]:
2677+
"""
2678+
Resolves the (actor_token, actor_token_type) pair for a session transfer request.
2679+
2680+
Raises:
2681+
CustomTokenExchangeError(ACTOR_UNAVAILABLE): if no usable actor can be resolved.
2682+
"""
2683+
# Explicit actor wins; a passed-but-blank value is a bug, not a fallback signal.
2684+
if actor_token is not None:
2685+
if not actor_token.strip():
2686+
raise CustomTokenExchangeError(
2687+
CustomTokenExchangeErrorCode.INVALID_TOKEN_FORMAT,
2688+
"actor_token cannot be empty or whitespace-only"
2689+
)
2690+
return actor_token, (actor_token_type or ID_TOKEN_TYPE)
2691+
2692+
# Otherwise source it from the agent's session ID token.
2693+
state_data = await self._state_store.get(self._state_identifier, store_options)
2694+
if state_data and hasattr(state_data, "dict") and callable(state_data.dict):
2695+
state_data = state_data.dict()
2696+
state_data = state_data or {}
2697+
2698+
# In resolver mode, don't source the actor from a session on a different domain.
2699+
if self._domain_resolver:
2700+
session_domain = self._get_session_domain(state_data)
2701+
current_domain = await self._resolve_current_domain(store_options)
2702+
if not session_domain or self._normalize_url(session_domain) != self._normalize_url(current_domain):
2703+
raise CustomTokenExchangeError(
2704+
CustomTokenExchangeErrorCode.ACTOR_UNAVAILABLE,
2705+
"No usable actor token: the agent session is on a different domain."
2706+
)
2707+
2708+
session_id_token = state_data.get("id_token")
2709+
2710+
# Refresh a stale (or missing) ID token when the agent session has a refresh token.
2711+
if not await self._is_id_token_usable(session_id_token, store_options) and state_data.get("refresh_token"):
2712+
refresh_domain = self._get_session_domain(state_data) or await self._resolve_current_domain(store_options)
2713+
try:
2714+
refreshed = await self.get_token_by_refresh_token({
2715+
"refresh_token": state_data["refresh_token"],
2716+
"domain": refresh_domain,
2717+
})
2718+
except (ApiError, AccessTokenError):
2719+
# A genuine refresh failure means no usable actor; unexpected errors propagate.
2720+
refreshed = None
2721+
if refreshed:
2722+
updated_state_data = State.update_state_data(
2723+
self.DEFAULT_AUDIENCE_STATE_KEY, state_data, refreshed)
2724+
await self._state_store.set(self._state_identifier, updated_state_data, options=store_options)
2725+
session_id_token = refreshed.get("id_token") or session_id_token
2726+
2727+
if await self._is_id_token_usable(session_id_token, store_options):
2728+
return session_id_token, ID_TOKEN_TYPE
2729+
2730+
raise CustomTokenExchangeError(
2731+
CustomTokenExchangeErrorCode.ACTOR_UNAVAILABLE,
2732+
"No usable actor token: pass actor_token or ensure the agent has a valid session."
2733+
)
2734+
2735+
async def request_session_transfer_token(
2736+
self,
2737+
subject_token: str,
2738+
subject_token_type: str,
2739+
actor_token: Optional[str] = None,
2740+
actor_token_type: Optional[str] = None,
2741+
scope: Optional[str] = None,
2742+
organization: Optional[str] = None,
2743+
store_options: Optional[dict[str, Any]] = None
2744+
) -> SessionTransferTokenResult:
2745+
"""
2746+
Requests a Session Transfer Token (STT) for impersonation via session transfer.
2747+
2748+
Performs a custom token exchange against the session_transfer audience. The returned
2749+
STT is opaque and single-use; hand it to build_session_transfer_redirect and do not
2750+
decode or store it. The act claim is not on this result.
2751+
2752+
Args:
2753+
subject_token: Your proof of which customer to impersonate (validated by your Action)
2754+
subject_token_type: The subject token type URI routing to your CTE Profile
2755+
actor_token: The acting party's token; optional. Defaults to the agent session's ID token
2756+
actor_token_type: Type URI of the actor token; defaults to the ID token URN
2757+
scope: Space-delimited list of scopes (optional)
2758+
organization: Organization identifier (optional)
2759+
store_options: Optional options used to read the agent session and resolve the domain
2760+
2761+
Returns:
2762+
SessionTransferTokenResult containing the STT and its metadata
2763+
2764+
Raises:
2765+
CustomTokenExchangeError: If no actor can be resolved or the exchange fails
2766+
"""
2767+
try:
2768+
# Validate the subject up front - before any session read/refresh/network.
2769+
if not subject_token or not subject_token.strip():
2770+
raise CustomTokenExchangeError(
2771+
CustomTokenExchangeErrorCode.INVALID_TOKEN_FORMAT,
2772+
"subject_token cannot be empty or whitespace-only"
2773+
)
2774+
if not subject_token_type or not subject_token_type.strip():
2775+
raise CustomTokenExchangeError(
2776+
CustomTokenExchangeErrorCode.INVALID_TOKEN_FORMAT,
2777+
"subject_token_type cannot be empty or whitespace-only"
2778+
)
2779+
2780+
actor_token, actor_token_type = await self._resolve_actor_token(
2781+
actor_token, actor_token_type, store_options)
2782+
2783+
# Build the session_transfer audience from the resolved request domain.
2784+
domain = await self._resolve_current_domain(store_options)
2785+
audience = f"urn:{domain}:session_transfer"
2786+
2787+
options = CustomTokenExchangeOptions(
2788+
subject_token=subject_token,
2789+
subject_token_type=subject_token_type,
2790+
audience=audience,
2791+
scope=scope,
2792+
actor_token=actor_token,
2793+
actor_token_type=actor_token_type,
2794+
organization=organization,
2795+
)
2796+
2797+
response = await self.custom_token_exchange(options, store_options)
2798+
2799+
return SessionTransferTokenResult(
2800+
session_transfer_token=response.access_token,
2801+
# Return the server's value as-is; don't default to the STT URN, or a non-STT
2802+
# response would be mislabelled as an STT.
2803+
issued_token_type=response.issued_token_type or "",
2804+
expires_in=response.expires_in,
2805+
token_type=response.token_type,
2806+
scope=response.scope,
2807+
)
2808+
except (CustomTokenExchangeError, ApiError):
2809+
raise
2810+
except Exception as e:
2811+
raise CustomTokenExchangeError(
2812+
CustomTokenExchangeErrorCode.TOKEN_EXCHANGE_FAILED,
2813+
f"Session transfer token request failed: {str(e)}",
2814+
e
2815+
)
2816+
2817+
def build_session_transfer_redirect(
2818+
self,
2819+
target_login_url: str,
2820+
result: SessionTransferTokenResult,
2821+
organization: Optional[str] = None
2822+
) -> str:
2823+
"""
2824+
Builds the redirect URL that hands the STT to the target app's login URL.
2825+
2826+
target_login_url must be a trusted, app-controlled absolute https URL (http is allowed
2827+
only for localhost/loopback) - the STT is a single-use credential and must not leak to an
2828+
untrusted host.
2829+
2830+
Args:
2831+
target_login_url: The target app's login URL (absolute, https)
2832+
result: The SessionTransferTokenResult from request_session_transfer_token
2833+
organization: Organization identifier to forward (optional)
2834+
2835+
Returns:
2836+
A URL string with session_transfer_token (and organization) as query parameters
2837+
2838+
Raises:
2839+
MissingRequiredArgumentError: If target_login_url is missing or blank
2840+
InvalidArgumentError: If target_login_url is not an absolute https URL, or organization is blank
2841+
"""
2842+
URL.validate_https_redirect_target(target_login_url, "target_login_url")
2843+
2844+
params = {"session_transfer_token": result.session_transfer_token}
2845+
if organization is not None:
2846+
if not organization.strip():
2847+
raise InvalidArgumentError("organization", "organization must not be blank")
2848+
params["organization"] = organization
2849+
2850+
return URL.build_url(target_login_url, params)
2851+
26382852
# ============================================================================
26392853
# MFA (Multi-Factor Authentication)
26402854
# ============================================================================

src/auth0_server_python/auth_types/__init__.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -397,6 +397,24 @@ class LoginWithCustomTokenExchangeResult(BaseModel):
397397
authorization_details: Optional[list[AuthorizationDetails]] = None
398398

399399

400+
class SessionTransferTokenResult(BaseModel):
401+
"""
402+
Response from a session transfer token (STT) request.
403+
404+
Attributes:
405+
session_transfer_token: The opaque, single-use session transfer token
406+
issued_token_type: Format of issued token (the session-transfer URN)
407+
expires_in: Token lifetime in seconds
408+
token_type: Token type as returned by the server (typically "N_A")
409+
scope: Granted scopes (if returned)
410+
"""
411+
session_transfer_token: str
412+
issued_token_type: str
413+
expires_in: int
414+
token_type: Optional[str] = None
415+
scope: Optional[str] = None
416+
417+
400418
# =============================================================================
401419
# Connected Accounts Types
402420
# =============================================================================

src/auth0_server_python/error/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,9 @@ class CustomTokenExchangeErrorCode:
254254
MISSING_ACTOR_TOKEN = "missing_actor_token"
255255
TOKEN_EXCHANGE_FAILED = "token_exchange_failed"
256256
INVALID_RESPONSE = "invalid_response"
257+
ACTOR_UNAVAILABLE = "actor_unavailable"
258+
SETACTOR_REQUIRED = "setactor_required"
259+
SESSION_TRANSFER_DISABLED = "session_transfer_disabled"
257260

258261

259262
# =============================================================================

0 commit comments

Comments
 (0)