adk_auth/secrets/authorizing.rs
1//! Per-tool authorization for secret access.
2//!
3//! A tool holding a context can name any secret, and a
4//! [`SecretProvider`](super::provider::SecretProvider) receives only
5//! that name. Policy therefore collapses to whatever the backing cloud credentials can
6//! read, and nothing distinguishes a weather tool asking for its own API key from the
7//! same tool asking for a payment credential.
8//!
9//! [`AuthorizingSecretService`] closes that at the ADK layer: a declarative grant per
10//! tool decides before the provider is called, and every decision is recorded without
11//! the secret value.
12
13use std::collections::HashMap;
14use std::sync::Arc;
15
16use adk_core::{AdkError, Result, SecretRequest, SecretService};
17use async_trait::async_trait;
18
19/// What a single tool may read.
20#[derive(Debug, Clone, Default, PartialEq, Eq)]
21pub struct SecretGrant {
22 /// Secret names allowed verbatim.
23 names: Vec<String>,
24 /// Name prefixes allowed, for namespaced secrets such as `billing/`.
25 prefixes: Vec<String>,
26}
27
28impl SecretGrant {
29 /// A grant that allows nothing.
30 pub fn none() -> Self {
31 Self::default()
32 }
33
34 /// Allow an exact secret name.
35 #[must_use]
36 pub fn name(mut self, name: impl Into<String>) -> Self {
37 self.names.push(name.into());
38 self
39 }
40
41 /// Allow every name beginning with `prefix`.
42 ///
43 /// Use this for a namespace the tool owns. A prefix is a blunt instrument: prefer
44 /// exact names where the set is known.
45 #[must_use]
46 pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
47 self.prefixes.push(prefix.into());
48 self
49 }
50
51 /// Whether this grant covers `name`.
52 fn allows(&self, name: &str) -> bool {
53 self.names.iter().any(|allowed| allowed == name)
54 || self.prefixes.iter().any(|prefix| name.starts_with(prefix.as_str()))
55 }
56}
57
58/// Records secret access decisions.
59///
60/// Implementations must not receive or log secret values — only the decision and the
61/// identity around it.
62pub trait SecretAuditSink: Send + Sync {
63 /// Called once per decision, before the provider is consulted on an allow.
64 fn record(&self, decision: SecretAccessDecision<'_>);
65}
66
67/// A single allow or deny, carrying no secret value.
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub struct SecretAccessDecision<'a> {
70 /// Whether access was permitted.
71 pub allowed: bool,
72 /// The secret name requested.
73 pub name: &'a str,
74 /// The requesting tool, when the access came from one.
75 pub tool_name: Option<&'a str>,
76 /// The user the run belongs to.
77 pub user_id: Option<&'a str>,
78 /// The invocation the access happened in.
79 pub invocation_id: Option<&'a str>,
80 /// Why the decision went the way it did.
81 pub reason: &'static str,
82}
83
84/// Wraps a [`SecretService`] with declarative per-tool grants and an audit record.
85///
86/// A request whose tool has no grant, or whose grant does not cover the name, is
87/// refused **before** the inner service is called, so a denied name never reaches the
88/// provider.
89///
90/// # Example
91///
92/// ```rust
93/// use std::sync::Arc;
94///
95/// use adk_auth::secrets::{AuthorizingSecretService, SecretGrant};
96/// use adk_core::{SecretRequest, SecretService};
97///
98/// /// The backing store, such as a cloud secret manager.
99/// struct Vault;
100///
101/// #[async_trait::async_trait]
102/// impl SecretService for Vault {
103/// async fn get_secret(&self, name: &str) -> adk_core::Result<String> {
104/// Ok(format!("value of {name}"))
105/// }
106/// }
107///
108/// # #[tokio::main(flavor = "current_thread")]
109/// # async fn main() -> adk_core::Result<()> {
110/// let service = AuthorizingSecretService::new(Arc::new(Vault))
111/// .grant("weather_lookup", SecretGrant::none().name("weather-api-key"))
112/// .grant("charge_card", SecretGrant::none().prefix("billing/"));
113///
114/// let own_key = SecretRequest::new("weather-api-key").with_tool_name("weather_lookup");
115/// assert_eq!(service.get_secret_for(&own_key).await?, "value of weather-api-key");
116///
117/// let other_tools_key = SecretRequest::new("billing/card-key").with_tool_name("weather_lookup");
118/// assert!(service.get_secret_for(&other_tools_key).await.unwrap_err().is_unauthorized());
119/// # Ok(())
120/// # }
121/// ```
122pub struct AuthorizingSecretService {
123 inner: Arc<dyn SecretService>,
124 grants: HashMap<String, SecretGrant>,
125 /// What an access with no tool identity may read.
126 untooled: SecretGrant,
127 audit: Option<Arc<dyn SecretAuditSink>>,
128}
129
130impl AuthorizingSecretService {
131 /// Wrap `inner`, denying everything until grants are added.
132 pub fn new(inner: Arc<dyn SecretService>) -> Self {
133 Self { inner, grants: HashMap::new(), untooled: SecretGrant::none(), audit: None }
134 }
135
136 /// Grant `tool_name` access to the secrets described by `grant`.
137 #[must_use]
138 pub fn grant(mut self, tool_name: impl Into<String>, grant: SecretGrant) -> Self {
139 self.grants.insert(tool_name.into(), grant);
140 self
141 }
142
143 /// Grant access for requests that carry no tool identity.
144 ///
145 /// These are accesses made by the agent itself rather than by a dispatched tool.
146 /// They are denied by default, because a request with no identity cannot be
147 /// attributed.
148 #[must_use]
149 pub fn grant_untooled(mut self, grant: SecretGrant) -> Self {
150 self.untooled = grant;
151 self
152 }
153
154 /// Record every decision to `sink`.
155 #[must_use]
156 pub fn with_audit_sink(mut self, sink: Arc<dyn SecretAuditSink>) -> Self {
157 self.audit = Some(sink);
158 self
159 }
160
161 /// Decide whether `request` is permitted, and why.
162 fn decide(&self, request: &SecretRequest) -> (bool, &'static str) {
163 match &request.tool_name {
164 Some(tool_name) => match self.grants.get(tool_name) {
165 Some(grant) if grant.allows(&request.name) => (true, "granted to tool"),
166 Some(_) => (false, "secret not in the tool's grant"),
167 None => (false, "no grant for tool"),
168 },
169 None => {
170 if self.untooled.allows(&request.name) {
171 (true, "granted without tool identity")
172 } else {
173 (false, "no grant for a request without tool identity")
174 }
175 }
176 }
177 }
178
179 fn record(&self, request: &SecretRequest, allowed: bool, reason: &'static str) {
180 let decision = SecretAccessDecision {
181 allowed,
182 name: &request.name,
183 tool_name: request.tool_name.as_deref(),
184 user_id: request.user_id.as_deref(),
185 invocation_id: request.invocation_id.as_deref(),
186 reason,
187 };
188 if allowed {
189 tracing::info!(
190 secret.name = %decision.name,
191 tool.name = decision.tool_name.unwrap_or("<none>"),
192 user.id = decision.user_id.unwrap_or("<unknown>"),
193 invocation.id = decision.invocation_id.unwrap_or("<unknown>"),
194 decision.reason = reason,
195 "secret access allowed"
196 );
197 } else {
198 tracing::warn!(
199 secret.name = %decision.name,
200 tool.name = decision.tool_name.unwrap_or("<none>"),
201 user.id = decision.user_id.unwrap_or("<unknown>"),
202 invocation.id = decision.invocation_id.unwrap_or("<unknown>"),
203 decision.reason = reason,
204 "secret access denied"
205 );
206 }
207 if let Some(sink) = &self.audit {
208 sink.record(decision);
209 }
210 }
211}
212
213impl std::fmt::Debug for AuthorizingSecretService {
214 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
215 f.debug_struct("AuthorizingSecretService")
216 .field("granted_tools", &self.grants.keys().collect::<Vec<_>>())
217 .field("audited", &self.audit.is_some())
218 .finish()
219 }
220}
221
222#[async_trait]
223impl SecretService for AuthorizingSecretService {
224 /// Denies unconditionally.
225 ///
226 /// # Errors
227 ///
228 /// A bare name carries no identity, so there is nothing to authorize against.
229 /// Callers reach this service through
230 /// [`SecretService::get_secret_for`], which the framework uses.
231 async fn get_secret(&self, name: &str) -> Result<String> {
232 let request = SecretRequest::new(name);
233 self.record(&request, false, "no identity supplied");
234 Err(AdkError::unauthorized(
235 adk_core::ErrorComponent::Tool,
236 "secret.no_identity",
237 format!("secret '{name}' was requested without identity, so it cannot be authorized"),
238 ))
239 }
240
241 async fn get_secret_for(&self, request: &SecretRequest) -> Result<String> {
242 let (allowed, reason) = self.decide(request);
243 self.record(request, allowed, reason);
244 if !allowed {
245 // The provider is never consulted, so a denied name is not even looked up.
246 return Err(AdkError::unauthorized(
247 adk_core::ErrorComponent::Tool,
248 "secret.access_denied",
249 format!(
250 "tool {} is not permitted to read secret '{}': {reason}",
251 request.tool_name.as_deref().unwrap_or("<none>"),
252 request.name
253 ),
254 ));
255 }
256 self.inner.get_secret_for(request).await
257 }
258}