Mental model
Forwarding a user's broad OAuth refresh token or a backend master "god API key" directly into agent tool schemas or container environments shatters least-privilege isolation cleanly on day one: any prompt-injected retrieval snippet or unhandled crash stack trace leaks unlimited cross-service authority! Delegated credentials replace static ambient secrets with an out-of-band credential broker (OAuth 2.0 Token Exchange RFC 8693) that down-scopes the verified human session (sub) plus acting agent identity (act) into an ephemeral, narrow-scoped, audience-bound (aud) and resource-locked token injected exclusively at trusted downstream HTTP/MCP proxies—ensuring zero raw secret bytes ever enter LLM prompt memory, trace logs, or persistent agent checkpoints.
Learning outcomes
- Architect OAuth 2.0 Token Exchange (
RFC 8693) pipelines preserving both authorizing user attribution (sub) and acting agent identity (act). - Enforce orthogonal confinement checks—
audtarget binding, narrow operation scope, explicitresource_idrestrictions, and sender constraints (DPoP/ mTLS)—so even compromised ephemeral tokens resist lateral replay. - Keep raw bearer tokens strictly isolated out of model instructions, tool JSON responses, error stack traces, and durable LangGraph checkpoints cleanly.
- Balance token-exchange latency (
10–30 ms) against strict blast-radius containment for multi-tenant AI agents.
Theory
Teams routinely assume setting a short 60-second TTL alone prevents delegated tool abuse. In reality, an unconstrained 60-second wildcard token accepted by both internal billing endpoints AND user CRM records (missing aud check), or carrying broad "calendar.*" write privileges when the operator asked to view one slot, lets a hijacked tool execution mutate dozens of unintended endpoints within milliseconds! Hardening delegated AI execution requires verifying four orthogonal claims simultaneously inside trusted token-broker and resource-server guards:
| Credential Pattern | Exposure to LLM Context / Logs | Blast Radius If Compromised | Forensic Attribution & Lateral Replay Defense |
|---|---|---|---|
| Raw User Token or Env Secret Inside Tool Container | Visible inside code dumps, error tracebacks, or model tool args | Full multi-service human account or entire platform takeover across long TTLs | Weak; attackers reuse extracted token cleanly from any host |
Static Shared Service Key (ai_service_bot) | Hidden behind proxy, yet unrestricted across tenants | Exposes all customer tenants if single executor endpoint compromised | Loses individual employee attribution (who approved write?) |
| RFC 8693 Audience-Bound Ephemeral Token + Proxy Injection | 0 secret bytes ever touch LLM context or persisted checkpoint state | Bounded strictly to 1 downstream service aud, 1 resource URI, minimal scope, 60–120 s TTL | Immutable sub + act audit trail plus sender-constrained DPoP / mTLS! |
Sender-Constrained Tokens (DPoP / mTLS) and Credential Redaction Hygiene
Enforcing aud checks stops Confused Deputy cross-service replay (e.g. presenting a calendar token cleanly to billing), while sender-constraining (OAuth DPoP RFC 9449 cryptographic proof-of-possession or mutual TLS client certificate binding cnf.jkt) prevents stolen bearer tokens leaked in debug memory dumps from working anywhere outside your authenticated egress proxy! Equally critical: configure structured loggers, LangGraph/DB checkpoint serializers, and error formatters to scrub Authorization, Cookie, and query secrets automatically so a downstream 401 traceback never dumps a live ephemeral token cleanly into observability buckets or LLM retry feedback loops!
pythonfrom dataclasses import dataclass@dataclass(frozen=True)class DelegatedAccessToken:sub_user_id: stract_agent_id: straud_service: strscopes: frozenset[str]resource_id: strexp_epoch: intdpop_thumbprint: strdef verify_delegated_tool_token(tok: DelegatedAccessToken,expected_service: str,required_scope: str,target_resource: str,caller_dpop_thumbprint: str,now_epoch: int,) -> tuple[bool, str]:"""Verify audience, operation scope, resource URI, DPoP proof, and expiration at API boundary."""if now_epoch >= tok.exp_epoch:return False, "token_expired"if tok.aud_service != expected_service:return False, f"audience_mismatch:{tok.aud_service}"if required_scope not in tok.scopes:return False, f"insufficient_scope:{required_scope}"if tok.resource_id != target_resource:return False, "resource_binding_mismatch"if tok.dpop_thumbprint != caller_dpop_thumbprint:return False, "dpop_sender_constraint_failed"return True, "authorized"
Alternatives and trade-offs
- Out-of-Band
RFC 8693Credential Broker + Edge Proxy Injection (DPoP/ mTLS): Gold-standard zero-trust multi-tenant architecture isolating LLM contexts completely from credentials while preserving exactsub+actcompliance auditability; introduces an identity-broker token exchange round-trip (10–30 msor safely cached per narrow action scope) and requires downstream microservices to validateaud/resource/sender proofs. - Scoped Proxy Service Keys With Request-Header User Assertion (
Signed Internal JWT): Simpler to retrofit onto legacy internal APIs lacking nativeRFC 8693IdP endpoints, provided the proxy still injects credentials exclusively out-of-band outside sandboxed containers and signs immutable caller attribution headers. - User-Prompted Secret Injection or Broad Sandbox Env Variables: Acceptable only for isolated personal single-user prototypes holding disposable sandbox tokens—completely unacceptable in enterprise or multi-tenant production systems.
Failure modes and misconceptions
- Equating Short Expiration (
TTL = 60 s) With Least Privilege: A broad 60-second token lackingaudor specificresource_idlimits still authorizes mass deletions across unrelated APIs inside one second of runtime execution. - Defining
api_keyFields Inside Model Tool Parameters: Allowing models to read or pass credentials as tool JSON arguments embeds secrets permanently inside LLM prompts, third-party vendor trace logs, and SQL checkpoints. Always inject secrets exclusively inside trusted outbound proxies after schema + policy verification! - Destroying Individual User Auditability Behind Shared Bot Accounts: Using one global
agent_adminservice credential hides whetheralice@company.comorbob@company.cominitiated a high-consequence change—failing SOC 2 / HIPAA access reviews cleanly unlesssubandactclaims propagate together. - Leaking Unmasked Proxy Headers Into Exception Telemetry or Agent Memory: Returning full verbose
httpxrequest debug payloads cleanly to an LLM retry prompt exposes freshAuthorization: Bearer ...values into untrusted model context! Strip credential headers cleanly inside telemetry middleware before error capture.
Decision scenario
Your enterprise workplace assistant needs permission to reschedule a single approved customer meeting (evt_9914) through your internal Calendar microservice while separate isolated tools query billing reports. Build an out-of-band RFC 8693 Credential Broker behind an outbound egress proxy: swap the user's verified session (sub) cleanly for a 90-second DPoP-bound token carrying aud = "calendar-api.internal", scope = "calendar.events.patch", resource_id = "evt_9914", and act = "assistant-scheduler"; enforce all five claim checks strictly inside the Calendar endpoint; ensure LLM tool parameters reference only logical handles ("evt_9914"); and strip all Authorization headers in telemetry middleware so zero token bytes reach prompts or logs.
Trade-offs
Brokered, audience-bound, sender-constrained delegated credentials dramatically tighten lateral-movement blast radii and eliminate context-window secret leakage across agentic tools, at the operational cost of operating an RFC 8693 token-exchange proxy, DPoP/mTLS validation hooks, and millisecond exchange hops per scoped action.