FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Delegated Credentials for AI Tools

Use short-lived, audience-bound, least-privilege credentials without exposing secrets to model context.

Freshness: current•15 min read•Security, Safety, and Governance

Key Learning Outcomes

  • ✓Explain the operating model behind Delegated Credentials for AI Tools.
  • ✓Evaluate trade-offs and failure modes for Delegated Credentials for AI Tools.
  • ✓Apply Delegated Credentials for AI Tools to a production decision.
Full Technical Reference Document

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.

User Identity (sub) + Scoped Intent Check
RFC 8693 Broker Down-Scopes aud, Scope & Resource
Proxy Injects Short-Lived Token Outside Prompt
Resource API Verifies aud, Scope, act & DPoP
Zero Secrets Leak Into Model Logs or Context
Conceptual teaching model synthesized from:oauth-security-bcp,mcp-specification

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—aud target binding, narrow operation scope, explicit resource_id restrictions, 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 PatternExposure to LLM Context / LogsBlast Radius If CompromisedForensic Attribution & Lateral Replay Defense
Raw User Token or Env Secret Inside Tool ContainerVisible inside code dumps, error tracebacks, or model tool argsFull multi-service human account or entire platform takeover across long TTLsWeak; attackers reuse extracted token cleanly from any host
Static Shared Service Key (ai_service_bot)Hidden behind proxy, yet unrestricted across tenantsExposes all customer tenants if single executor endpoint compromisedLoses individual employee attribution (who approved write?)
RFC 8693 Audience-Bound Ephemeral Token + Proxy Injection0 secret bytes ever touch LLM context or persisted checkpoint stateBounded strictly to 1 downstream service aud, 1 resource URI, minimal scope, 60–120 s TTLImmutable 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!

python
from dataclasses import dataclass
​
@dataclass(frozen=True)
class DelegatedAccessToken:
sub_user_id: str
act_agent_id: str
aud_service: str
scopes: frozenset[str]
resource_id: str
exp_epoch: int
dpop_thumbprint: str
​
def 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 8693 Credential Broker + Edge Proxy Injection (DPoP / mTLS): Gold-standard zero-trust multi-tenant architecture isolating LLM contexts completely from credentials while preserving exact sub + act compliance auditability; introduces an identity-broker token exchange round-trip (10–30 ms or safely cached per narrow action scope) and requires downstream microservices to validate aud/resource/sender proofs.
  • Scoped Proxy Service Keys With Request-Header User Assertion (Signed Internal JWT): Simpler to retrofit onto legacy internal APIs lacking native RFC 8693 IdP 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

  1. Equating Short Expiration (TTL = 60 s) With Least Privilege: A broad 60-second token lacking aud or specific resource_id limits still authorizes mass deletions across unrelated APIs inside one second of runtime execution.
  2. Defining api_key Fields 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!
  3. Destroying Individual User Auditability Behind Shared Bot Accounts: Using one global agent_admin service credential hides whether alice@company.com or bob@company.com initiated a high-consequence change—failing SOC 2 / HIPAA access reviews cleanly unless sub and act claims propagate together.
  4. Leaking Unmasked Proxy Headers Into Exception Telemetry or Agent Memory: Returning full verbose httpx request debug payloads cleanly to an LLM retry prompt exposes fresh Authorization: Bearer ... values into untrusted model context! Strip credential headers cleanly inside telemetry middleware before error capture.
Reflect before revealing the guide

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.

Prerequisites & Related Concepts (3)

Private notes

0 words
Included In Free Course
Free · Verifiable Credential

FS-301Agentic Systems Engineer

Engineer bounded tool-using systems with explicit workflows state protocols evaluation observability security and human control.

27 concepts~29h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next