adk-auth
Access control and authentication for Rust Agent Development Kit (ADK-Rust).
Stability: Stable — follows semantic versioning, so breaking changes wait for the next major release. See STABILITY.md.
Overview
adk-auth provides access control for AI agents:
- Declarative scope-based security — tools declare required scopes, framework enforces automatically
- Role-based access control — define roles with allow/deny permissions, deny takes precedence
- Audit logging — every access decision to a JSONL file, PostgreSQL, OTLP, or a signed Merkle-tree log
- Credential brokers — audience-bound tokens for an agent's outbound calls
- Secret providers — AWS Secrets Manager, Azure Key Vault, and GCP Secret Manager
- SSO/OAuth — JWT validation with Google, Azure AD, Okta, Auth0, and generic OIDC providers
- Auth bridge — flow authenticated identity from HTTP requests into agent execution via
adk-server - Web Bot Auth — verify and sign RFC 9421 request signatures so automated clients have a verified identity
Installation
[]
= "3.0.0"
# With SSO/JWT validation
= { = "3.0.0", = ["sso"] }
# With auth bridge for adk-server identity flow (implies sso)
= { = "3.0.0", = ["auth-bridge"] }
# With the signed, Merkle-hashed audit log
= { = "3.0.0", = ["signed-audit"] }
# With Web Bot Auth request signatures
= { = "3.0.0", = ["web-bot-auth"] }
# With agent identity federation: AWS, Google Cloud and Microsoft Entra (implies sso)
= { = "3.0.0", = ["agent-federation"] }
Features
Core RBAC, scope-based security, and audit logging are always available with no feature flags.
| Feature | Description |
|---|---|
sso |
JWT/OIDC providers (Google, Azure AD, Okta, Auth0, generic OIDC) |
auth-bridge |
JwtRequestContextExtractor for adk-server identity flow (implies sso) |
token-exchange |
TokenExchangeBroker: RFC 8693 token exchange of the agent's credential, or of the subject's token with the agent as actor (on_behalf_of), for resource-scoped tokens |
signed-audit |
signed_audit::AuditLog: the signed, Merkle-hashed audit log, and signed_audit::verify |
web-bot-auth |
web_bot_auth: RFC 9421 Ed25519 request signatures, HttpSignatureVerifier, HttpSignatureSigner, key directories |
agent-federation |
federation: AgentTokenIssuer, an OIDC issuer for agents; exchanges of its tokens at AWS IAM, Amazon Bedrock AgentCore Identity, Google Cloud and Microsoft Entra Agent ID; InboundAgentVerifier for Entra and Google agent tokens (implies sso) |
postgres-audit |
PostgresAuditSink |
otlp-audit |
OtlpAuditSink |
aws-secrets |
secrets::AwsSecretProvider (AWS Secrets Manager) |
azure-keyvault |
secrets::AzureSecretProvider (Azure Key Vault) |
gcp-secrets |
secrets::GcpSecretProvider (GCP Secret Manager) |
Declarative Scope-Based Security
Tools declare what scopes they need. The framework enforces before execution — no imperative checks in your handlers:
use Arc;
use ;
use ;
use FunctionTool;
use ;
async
Pluggable resolvers:
| Resolver | Source |
|---|---|
ContextScopeResolver |
Delegates to ToolContext::user_scopes() (JWT claims, session state) |
StaticScopeResolver |
Fixed scopes — useful for testing |
Custom impl ScopeResolver |
Any async source (database, external IdP, etc.) |
For resolvers that call external services, cache the resolved scopes at the request or session layer to avoid repeated lookups during multi-tool runs.
Role-Based Access Control
use Arc;
use ;
use Tool;
Deny always takes precedence over allow, regardless of role assignment order. If a user has both an editor role (allow all tools) and a restricted role (deny code_exec), code_exec is denied.
You can also use the extension trait:
use Arc;
use ;
use Tool;
Combining RBAC + Scopes
Use RBAC for coarse tool/agent entitlement and scopes for request-level constraints:
use ;
use Tool;
SSO Integration
Enable with features = ["sso"]:
use ;
use ;
async
User ID Claim Selection
The ClaimsMapper builder controls which JWT claim becomes the user_id:
| Method | Claim | Fallback |
|---|---|---|
user_id_from_sub() (default) |
sub |
— |
user_id_from_email() |
email (only when email_verified == true) |
sub |
user_id_from_preferred_username() |
preferred_username |
sub |
user_id_from_claim("custom") |
Any custom claim | sub |
Providers
| Provider | Usage |
|---|---|
GoogleProvider::new(client_id) |
|
| Azure AD | AzureADProvider::new(tenant_id, client_id) or ::multi_tenant(client_id).with_allowed_tenants(["tenant-id"]) |
| Okta | OktaProvider::new(domain, client_id) or ::with_auth_server(domain, server_id, client_id) |
| Auth0 | Auth0Provider::new(domain, audience) |
| Generic OIDC | OidcProvider::from_discovery(issuer, client_id).await or ::new(issuer, client_id, jwks_uri) |
| Custom JWT | JwtValidator::builder().issuer(iss).audience(aud).jwks_uri(uri).build()? |
Every validator requires the exp, iss, and aud claims: a token without one fails with TokenError::MissingClaim. JwtValidatorBuilder::build fails without an audience; for an issuer whose tokens carry no aud claim, without_audience() opts out, and the validator then refuses any token that carries an audience and still requires iss.
JwtValidatorBuilder::algorithm(JwtAlgorithm::ES256) adds an allowed signature algorithm; with none, the validator accepts RS256 only. JwtAlgorithm is ADK-owned and lists only the RSA and EC algorithms a JWKS can verify, and "PS256".parse::<JwtAlgorithm>() reads one from configuration.
AzureADProvider::multi_tenant() accepts tokens from any tenant targeting the configured audience unless you restrict it with with_allowed_tenants(...). It requires the iss claim but does not check its value.
OidcProvider::from_discovery() rejects discovery documents whose issuer does not match the requested issuer URL.
All providers implement the TokenValidator trait — you can implement it for any custom identity provider.
Auth Bridge
Enable with features = ["auth-bridge"] to validate Bearer tokens directly into adk-server request contexts:
use JwtRequestContextExtractor;
use ;
Pass it to ServerConfig::with_request_context(Arc::new(extractor)).
The extractor maps:
user_idfrom the configuredClaimsMapperscopesfrom JWTscope(space-delimited string) andscp(array) claims, deduplicatedmetadataincluding issuer, subject, email, tenant ID, and hosted domain when present
Audit Logging
use ;
Each line is one AuditEvent; optional fields such as session_id, agent_id, and on_behalf_of appear when set:
Implement the AuditSink trait for custom destinations (database, external service, etc.).
A protected or scoped tool refuses a call whose decision the sink fails to record
(AuditFailureMode::Block, the default); with_audit_failure_mode(AuditFailureMode::Warn)
logs the failure and continues instead. SsoAccessControl refuses such a grant with
SsoError::AuditFailed, and its builder takes the same mode through audit_failure_mode.
FileAuditSink::with_chaining and with_hmac_chaining write a hash chain that resumes
after a restart, and FileAuditSink::verify reports the first line whose prev_hash does
not match the line before it: an edit, insertion, or removal is caught at the next line,
while a change to the newest line and lines cut from the end leave no broken link.
Protected and scoped tools record the acting agent on every decision: agent_id,
on_behalf_of, and the principal's tenant (AuditEvent::with_acting_context).
The agent_id field of AuditFilter selects one agent's records.
Signed audit log (signed-audit)
signed_audit::AuditLog writes RFC 8785 records into an RFC 9162 Merkle tree per replica,
signs C2SP checkpoints with Ed25519 (Go sumdb/note compatible), rotates keys with a
dual-signed checkpoint, and publishes checkpoints to optional anchors. It is an AuditSink
and an AuditRecorder, so Runner::builder().audit_log(log) records every governed tool
decision, approval, kill-switch change, payment, and unknown outcome of a run in it.
Records live in an AuditLogStore (in memory, or adk-session SQLite, PostgreSQL, Redis,
MongoDB, Neo4j, or Firestore), and
signed_audit::verify or adk-rust audit verify detects flipped bytes, deletions,
reorders, forks, and the truncation of records that a supplied checkpoint covers. An export
cut together with its later checkpoints, or an empty one, verifies unless the anchored
checkpoints are passed as well (--checkpoints). See the
Audit Log guide.
Pseudonymous events
PseudonymousAuditSink wraps any AuditSink and rewrites each event before it is chained:
user and on_behalf_of become adk_core::subject::SubjectRegistry pseudonyms (visitors by
default, every subject after for_every_subject()), and ip_address is dropped. Erasing a
subject deletes its pseudonym, so the stored events stay chained and no longer name it.
Visitor Tokens
VisitorTokens signs a random adk_core::subject::VisitorId into
v1.{visitor id}.{expiry}.{HMAC-SHA256} with the first of its keys and verifies with every key,
so a site rotates keys without dropping visitors. A token proves the bearer was given the id; it
authenticates no one. set_cookie builds the __Host-adk_visitor cookie (Secure, HttpOnly,
SameSite=Lax) for a visitor who consented to being remembered.
Web Bot Auth (web-bot-auth)
web_bot_auth implements the IETF Web Bot Auth draft
(draft-ietf-webbotauth-httpsig-protocol-00) over HTTP Message Signatures (RFC 9421) with
Ed25519 keys. An automated client signs each request and names, in Signature-Agent, the
origin whose /.well-known/http-message-signatures-directory publishes its key; a site
verifies the signature against that directory instead of trusting a User-Agent claim.
| Type | Role |
|---|---|
HttpSignatureVerifier |
Verifies a request; returns VerifiedRequester with id = "wba:{directory origin}#{key thumbprint}", or None for an unsigned request |
HttpSignatureSigner |
Signs an http::Request or reqwest::Request with a site's key and Signature-Agent |
HttpKeyDirectorySource |
Fetches directories over HTTPS: public addresses only, no redirects, 5 s timeout, 64 KiB and 64 keys at most |
InMemoryKeyDirectorySource |
Directories from memory, for tests and out-of-band keys |
KeyDirectory |
Parses a directory, and builds the one a site publishes, with its possession proof |
Ed25519SigningKey |
Ed25519 key on aws-lc-rs; the seed is zeroized and never printed |
use Arc;
use ;
async
The verifier requires created, expires, keyid and tag="web-bot-auth", coverage of
@authority (or @target-uri) and the signature's Signature-Agent member, and accepts
created/expires within 60 s of clock skew. Directories are cached for their HTTP cache
lifetime, bounded to 60 s–24 h. The RFC 9421 test key is rejected unless
allow_test_keys(true). The verifier assigns no trust tier; that is the AWP edge's decision.
See the Web Bot Auth guide.
Credential Brokers
Each broker implements adk_core::CredentialBroker and mints a ScopedToken whose audience is
the requested resource (RFC 8707); ScopedToken::authorize_for refuses any other URL.
| Broker | Feature | Token source |
|---|---|---|
SecretCredentialBroker |
none | A SecretProvider secret bound to an exact (AgentId, resource) pair and its granted scopes |
TokenExchangeBroker |
token-exchange |
RFC 8693 exchange of the IdentitySource credential, or, with on_behalf_of(SubjectTokenSource), of the run's subject's token with the credential as actor_token; tokens are cached per subject, delegation chain, agent, resource, and scopes; optional RFC 7009 revocation |
federation::GoogleWorkloadIdentity |
agent-federation |
Google Cloud workload identity federation of the agent's own token; https resources on googleapis.com only |
federation::EntraAgentIdentity |
agent-federation |
Microsoft Entra Agent ID: the agent identity's token for the resource's .default scope |
See Agent Identity.
Agent Identity Federation (agent-federation)
federation federates an agent's AgentId with cloud identity systems. AgentTokenIssuer
publishes an OpenID Connect discovery document and JWK set and signs short-lived RS256 tokens
whose subject is the agent; each cloud trusts the issuer URL and fetches its keys itself.
| Type | Role |
|---|---|
AgentTokenIssuer |
Discovery document, JWK set, and tokens with iss, sub, aud, iat, nbf, exp (10 minutes by default, 1 hour at most) and jti |
AgentTokenSigner, RsaTokenSigner |
The signing key: a key service behind the trait, or a PKCS#8 RSA key on aws-lc-rs that is never printed |
AwsWebIdentity |
sts:AssumeRoleWithWebIdentity: temporary credentials of an IAM role |
AgentCoreIdentity |
bedrock-agentcore:GetWorkloadAccessTokenForJWT, signed with Signature Version 4 |
GoogleWorkloadIdentity |
Security Token Service exchange for a federated access token |
EntraAgentIdentity |
The blueprint and agent identity exchanges of Microsoft Entra Agent ID |
InboundAgentVerifier |
Validates an Entra or Google agent token and returns its AgentPrincipal; AgentClaimsProfile adds identity systems |
use Arc;
use ;
use AgentPrincipal;
async
See Agent Identity.
Changes in 3.0
| Change | Migration |
|---|---|
A guarded tool whose audit sink fails is refused with auth.audit_failed (AuditFailureMode::Block) |
with_audit_failure_mode(AuditFailureMode::Warn) keeps running when the sink is down |
AuditEvent gains agent_id and on_behalf_of |
Set them in struct literals |
AuditFailureMode moves to adk_core::audit_log and is re-exported here |
— |
| Signed audit log, credential brokers, token exchange, and Web Bot Auth are new | — |
PostgresAuditSink writes agent_id and on_behalf_of columns |
Call migrate() once before the first write; until then inserts fail and guarded tools are refused |
PostgresAuditSink uses SQLx 0.9 |
See SQLx compatibility below |
| HTTP requests to IdPs and token endpoints have connect and request timeouts | — |
The adk-server feature is removed |
Drop it: auth-bridge no longer needs adk-server |
The optional dependencies axum, base64, dashmap, jsonwebtoken, and reqwest are no longer features |
Enable the feature that uses them: sso, auth-bridge, signed-audit, token-exchange, or web-bot-auth |
See the 2.x to 3.0 migration guide and the changelog for the full list.
Error Types
| Type | When |
|---|---|
AccessDenied |
RBAC check fails (user lacks permission) |
AuthError |
Role not found, audit sink failure |
ScopeDenied |
Scope check fails (missing required scopes) |
TokenError |
JWT validation failure (expired, bad signature, missing claims) |
SsoError |
Token validation, access denied, or a grant the audit sink failed to record in SSO flow |
web_bot_auth::WebBotAuthError |
A Web Bot Auth signature is malformed, invalid, or unverifiable (is_unverified) |
Examples
Teaching examples live in the adk-playground repo.
Two standalone examples in this repository run adk-auth against local stand-ins, with no
identity provider:
| Example | What it exercises |
|---|---|
security_sessions_contracts |
JwtValidator over a local ES256 JWKS, SsoAccessControl with a failing audit sink, and JwtRequestContextExtractor in front of adk-server |
tools_hardening |
Request timeouts of JwksCache, OidcProvider::from_discovery, and TokenExchangeBroker, and single-flight token exchange |
Security Notes
- Prefer short-lived access tokens and rotate signing keys regularly.
- The JWKS cache refreshes hourly by default; lower the refresh interval with
JwksCache::with_refresh_interval()if your IdP rotates keys aggressively. - JWKS refreshes and OIDC discovery give up after 10 seconds, and
TokenExchangeBrokerrequests after 30 seconds, each with a 5-second connect timeout. OidcProvider::from_discovery()rejects discovery documents whoseissuerdoes not match the requested issuer URL.- Token revocation and blacklist checks are not built in. If you need immediate revocation, enforce it in a custom
TokenValidatoror request extractor. JwtAlgorithmhas no symmetric (HS256/HS384/HS512), EdDSA ornonevariant, so aJwtValidatorcannot be configured to accept them. A token whosealgis not in the allow-list, including an HS256 token keyed with the public JWK, is refused before its signature is checked.- A token with a
critheader naming an extension the validator does not implement is refused. - Every validator refuses a token without an
issoraudclaim.JwtValidatorBuilder::without_audience()is the only way to accept tokens that name no audience; pin an audience whenever the issuer sets one.
SQLx compatibility
ADK-Rust 3.0 SQL backends use SQLx 0.9. SQLx types appear in this crate's public
API — PostgresAuditSink::from_pool and PostgresAuditSink::pool — so an application that passes in its own pool must depend on
SQLx 0.9 too. Applications that let ADK open its own connections need no SQLx
dependency. The SQLx 0.9 migration guide
lists who is affected and what changed, and its
TLS behaviour section
covers PostgreSQL certificate verification.
License
Apache-2.0
Part of ADK-Rust
This crate is part of the ADK-Rust framework for building AI agents in Rust.