gadk_session/toolauth/tool.rs
1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! The auth config a tool requests a credential with: [`Config`], the key it names its
17//! credential by
18//! ([`Config::key`]), its secret-free copy ([`Config::without_secrets`]), the arguments of an
19//! `adk_request_credential` call ([`ToolArguments`]) and that call's name
20//! ([`REQUEST_CREDENTIAL_FUNCTION_CALL_NAME`]).
21
22use serde::de::Error as _;
23use serde::{Deserialize, Deserializer, Serialize, Serializer};
24use serde_json::value::RawValue;
25use sha2::{Digest, Sha256};
26
27use super::Extra;
28use super::credential::Credential;
29use super::model_json::{
30 GoJson, GoMarshal, ObjectWriter, decode_object, extra_eq, go_string, serialize_go,
31};
32use super::schemes::Scheme;
33
34/// The name of the function call ADK sends to the client to ask the end user for a credential
35/// (the `adk_request_credential` call). ADK Web and adk-python recognize the
36/// request by this exact name.
37pub const REQUEST_CREDENTIAL_FUNCTION_CALL_NAME: &str = "adk_request_credential";
38
39/// `Config`'s JSON field names, in struct order.
40const CONFIG_ALIASES: &[&str] = &[
41 "authScheme",
42 "rawAuthCredential",
43 "exchangedAuthCredential",
44 "credentialKey",
45];
46
47/// `ToolArguments`' JSON field names, in struct order.
48const TOOL_ARGUMENTS_ALIASES: &[&str] = &["functionCallId", "authConfig"];
49
50/// What a tool needs in order to get a credential: how the resource
51/// authenticates, the credential the tool was configured with, and the credential the flow
52/// produces. ADK sends it to the client in an `adk_request_credential` call, and the client
53/// fills `exchanged_auth_credential` in and sends it back.
54///
55/// It reads and writes adk-python's `AuthConfig` JSON: each field under its camelCase name,
56/// read under that name or its snake_case Python name (camelCase wins when both are present),
57/// and unknown keys kept in `extra`. `credentialKey` is always written, as [`Config::key`].
58#[derive(Clone, Default)]
59pub struct Config {
60 /// How the resource authenticates. Required on decode.
61 pub auth_scheme: Scheme,
62 /// The credential the tool was configured with, such as an OAuth2 client ID and secret. A
63 /// scheme that needs no exchange, such as an API key, may leave it `None`.
64 pub raw_auth_credential: Option<Credential>,
65 /// Filled in by ADK and the client together. For OAuth2 and OpenID Connect, ADK adds the
66 /// authorization URI and state, and the client adds the auth response.
67 pub exchanged_auth_credential: Option<Credential>,
68 /// Names the credential in a credential service. Serialized as [`Config::key`].
69 pub credential_key: String,
70 /// JSON keys that match no field, each as the raw text it arrived as.
71 pub extra: Extra,
72}
73
74impl Config {
75 /// The key that names this config's credential in a credential service.
76 ///
77 /// It is `credential_key` when that is set. Otherwise it is the first non-empty string
78 /// under `credential_key` or `credentialKey` among the unknown keys of
79 /// `raw_auth_credential`, then of `auth_scheme`, which is where adk-python's `AuthConfig`
80 /// looks. Otherwise it is derived the way adk-python's `get_credential_key` derives it:
81 /// `adk_<type>_<digest>_` followed, when there is a raw credential, by
82 /// `<authType>_<digest>`. Each digest covers the JSON of the scheme or the credential
83 /// without its own unknown keys. The OAuth2 fields that change during a flow (`auth_uri`,
84 /// `state`, `auth_response_uri`, `auth_code`, `access_token`, `refresh_token`,
85 /// `expires_at`, `expires_in` and `redirect_uri`) are left out, so the key stays put while
86 /// the flow runs.
87 ///
88 /// Every field of [`Scheme`] counts towards the key, whatever its type, but the scheme's
89 /// `extra` does not. A custom scheme's own fields are in `extra`, so two schemes of one
90 /// custom type that differ only there get the same key; set `credential_key` to tell them
91 /// apart.
92 ///
93 /// `key` trusts the config it is called on. A config a client sends back in an
94 /// `adk_request_credential` response can carry any `credentialKey`, so take only its
95 /// `exchanged_auth_credential` and store the credential under the key of the config ADK
96 /// sent, as adk-python's `store_auth_response` does.
97 ///
98 /// Infallible: `extra` holds only valid JSON text, so nothing in it can fail to encode.
99 pub fn key(&self) -> String {
100 if !self.credential_key.is_empty() {
101 return self.credential_key.clone();
102 }
103 let cred_extra = self.raw_auth_credential.as_ref().map(|c| &c.extra);
104 for extra in [cred_extra, Some(&self.auth_scheme.extra)]
105 .into_iter()
106 .flatten()
107 {
108 for name in ["credential_key", "credentialKey"] {
109 if let Some(k) = extra_string(extra, name)
110 && !k.is_empty()
111 {
112 return k;
113 }
114 }
115 }
116
117 let scheme = Scheme {
118 extra: Extra::new(),
119 ..self.auth_scheme.clone()
120 };
121 let mut key = format!("adk_{}_{}_", scheme.r#type.as_str(), digest(&scheme));
122 let Some(raw) = &self.raw_auth_credential else {
123 return key;
124 };
125 let mut cred = Credential {
126 extra: Extra::new(),
127 ..raw.clone()
128 };
129 if let Some(o) = cred.oauth2.as_mut() {
130 o.auth_uri = String::new();
131 o.state = String::new();
132 o.auth_response_uri = String::new();
133 o.auth_code = String::new();
134 o.access_token = String::new();
135 o.refresh_token = String::new();
136 o.redirect_uri = String::new();
137 o.expires_at = 0;
138 o.expires_in = 0;
139 }
140 key.push_str(cred.auth_type.as_str());
141 key.push('_');
142 key.push_str(&digest(&cred));
143 key
144 }
145
146 /// A deep copy of the config without the secrets the agent was configured with, for
147 /// sending to the client and keeping in the session.
148 ///
149 /// In both `raw_auth_credential` and `exchanged_auth_credential` it drops the API key, the
150 /// OAuth2 client secret, the HTTP password, token and additional headers, and a service
151 /// account's private key and key ID. That is adk-python's `_without_configured_secrets`,
152 /// which leaves the service account key in. Everything else, the PKCE code verifier
153 /// included, is kept. The copy carries this config's [`Config::key`] in `credential_key`,
154 /// since its stripped content would derive a different one.
155 ///
156 /// The copy shares nothing with `self`: `Clone` copies every map, list and extra value.
157 /// Infallible, because [`Config::key`] is.
158 pub fn without_secrets(&self) -> Config {
159 let mut out = self.clone();
160 out.credential_key = self.key();
161 for cred in [
162 out.raw_auth_credential.as_mut(),
163 out.exchanged_auth_credential.as_mut(),
164 ]
165 .into_iter()
166 .flatten()
167 {
168 cred.api_key = String::new();
169 if let Some(o) = cred.oauth2.as_mut() {
170 o.client_secret = String::new();
171 }
172 if let Some(h) = cred.http.as_mut() {
173 h.credentials.password = String::new();
174 h.credentials.token = String::new();
175 h.additional_headers = None;
176 }
177 if let Some(sa) = cred.service_account.as_mut()
178 && let Some(key) = sa.service_account_credential.as_mut()
179 {
180 key.private_key = String::new();
181 key.private_key_id = String::new();
182 }
183 }
184 out
185 }
186
187 /// Decodes a [`Config`] with `authScheme` required.
188 pub(crate) fn decode(raw: &RawValue) -> Result<Config, String> {
189 let mut d = decode_object(raw, "Config", CONFIG_ALIASES, true, &["authScheme"])?;
190 let auth_scheme = d
191 .take::<Scheme>("authScheme", "Config", "Scheme")?
192 .unwrap_or_default();
193 let raw_auth_credential = d
194 .take::<Option<Credential>>("rawAuthCredential", "Config", "Credential")?
195 .flatten();
196 let exchanged_auth_credential = d
197 .take::<Option<Credential>>("exchangedAuthCredential", "Config", "Credential")?
198 .flatten();
199 let credential_key = d
200 .take::<Option<String>>("credentialKey", "Config", "String")?
201 .flatten()
202 .unwrap_or_default();
203 Ok(Config {
204 auth_scheme,
205 raw_auth_credential,
206 exchanged_auth_credential,
207 credential_key,
208 extra: d.extra,
209 })
210 }
211}
212
213/// Equality of every field, with extras compared as JSON trees.
214impl PartialEq for Config {
215 fn eq(&self, other: &Self) -> bool {
216 self.auth_scheme == other.auth_scheme
217 && self.raw_auth_credential == other.raw_auth_credential
218 && self.exchanged_auth_credential == other.exchanged_auth_credential
219 && self.credential_key == other.credential_key
220 && extra_eq(&self.extra, &other.extra)
221 }
222}
223
224/// Encodes the fields in struct order with `credentialKey` written as
225/// [`Config::key`], then the extras that name no field.
226impl GoMarshal for Config {
227 fn go_marshal(&self) -> String {
228 let mut w = ObjectWriter::new();
229 w.field("authScheme", &self.auth_scheme.go_marshal());
230 if let Some(cred) = &self.raw_auth_credential {
231 w.field("rawAuthCredential", &cred.go_marshal());
232 }
233 if let Some(cred) = &self.exchanged_auth_credential {
234 w.field("exchangedAuthCredential", &cred.go_marshal());
235 }
236 let key = self.key();
237 if !key.is_empty() {
238 w.field("credentialKey", &go_string(&key));
239 }
240 w.finish(&self.extra, CONFIG_ALIASES, true)
241 }
242}
243
244impl Serialize for Config {
245 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
246 serialize_go(self, serializer)
247 }
248}
249
250impl<'de> Deserialize<'de> for Config {
251 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
252 let raw = Box::<RawValue>::deserialize(deserializer)?;
253 Config::decode(&raw).map_err(D::Error::custom)
254 }
255}
256
257/// The arguments of an `adk_request_credential` call: the ID of the tool
258/// call that needs the credential, and its config.
259#[derive(Clone, Default)]
260pub struct ToolArguments {
261 /// The ID of the function call that needs the credential. Required on decode.
262 pub function_call_id: String,
263 /// The config the credential is requested with. Required on decode.
264 pub auth_config: Config,
265 /// JSON keys that match no field, each as the raw text it arrived as.
266 pub extra: Extra,
267}
268
269impl ToolArguments {
270 /// Decodes [`ToolArguments`] with `functionCallId` and `authConfig` required.
271 fn decode(raw: &RawValue) -> Result<ToolArguments, String> {
272 let mut d = decode_object(
273 raw,
274 "ToolArguments",
275 TOOL_ARGUMENTS_ALIASES,
276 true,
277 &["functionCallId", "authConfig"],
278 )?;
279 let function_call_id = d
280 .take::<String>("functionCallId", "ToolArguments", "String")?
281 .unwrap_or_default();
282 let auth_config = d
283 .take::<Config>("authConfig", "ToolArguments", "Config")?
284 .unwrap_or_default();
285 Ok(ToolArguments {
286 function_call_id,
287 auth_config,
288 extra: d.extra,
289 })
290 }
291}
292
293/// Equality of every field, with extras compared as JSON trees.
294impl PartialEq for ToolArguments {
295 fn eq(&self, other: &Self) -> bool {
296 self.function_call_id == other.function_call_id
297 && self.auth_config == other.auth_config
298 && extra_eq(&self.extra, &other.extra)
299 }
300}
301
302/// Encodes the fields in struct order, then the extras that name no
303/// field.
304impl GoMarshal for ToolArguments {
305 fn go_marshal(&self) -> String {
306 let mut w = ObjectWriter::new();
307 w.field("functionCallId", &go_string(&self.function_call_id));
308 w.field("authConfig", &self.auth_config.go_marshal());
309 w.finish(&self.extra, TOOL_ARGUMENTS_ALIASES, true)
310 }
311}
312
313impl Serialize for ToolArguments {
314 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
315 serialize_go(self, serializer)
316 }
317}
318
319impl<'de> Deserialize<'de> for ToolArguments {
320 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
321 let raw = Box::<RawValue>::deserialize(deserializer)?;
322 ToolArguments::decode(&raw).map_err(D::Error::custom)
323 }
324}
325
326/// The value under `name` in `extra` when it is a JSON string;
327/// any other JSON value is ignored.
328fn extra_string(extra: &Extra, name: &str) -> Option<String> {
329 match GoJson::from_raw(extra.get(name)?) {
330 GoJson::String(s) => Some(s),
331 _ => None,
332 }
333}
334
335/// The first 16 hex digits of the SHA-256 of `v`'s JSON in canonical form.
336fn digest<T: GoMarshal>(v: &T) -> String {
337 digest_text(&v.go_marshal())
338}
339
340/// Computes the digest of the encoded text `marshaled`:
341/// 1. decode `marshaled` keeping each number's literal text;
342/// 2. re-encode it compactly with keys sorted bytewise, `&` `<` `>` and non-ASCII raw, and only
343/// U+2028/U+2029 escaped, which is the JSON
344/// Python's `json.dumps(sort_keys=True, ensure_ascii=False, separators=(",", ":"))` writes
345/// except for those two escapes and for numbers written as they arrived;
346/// 3. SHA-256 it (no trailing newline is written);
347/// 4. keep the first 8 bytes as lowercase hex.
348///
349/// `marshaled` is a model's `go_marshal()` output, which always parses. Should it ever not,
350/// the text is hashed as is, so the key stays infallible without a panic.
351fn digest_text(marshaled: &str) -> String {
352 let canonical = match GoJson::parse(marshaled) {
353 Ok(tree) => tree.encode(false),
354 Err(_) => marshaled.to_owned(),
355 };
356 let sum = Sha256::digest(canonical.as_bytes());
357 hex_prefix(sum.as_slice())
358}
359
360/// The first 8 bytes as 16 lowercase hex digits.
361fn hex_prefix(sum: &[u8]) -> String {
362 const DIGITS: &[u8; 16] = b"0123456789abcdef";
363 let mut out = String::with_capacity(16);
364 for b in sum.iter().take(8) {
365 out.push(char::from(DIGITS[usize::from(b >> 4)]));
366 out.push(char::from(DIGITS[usize::from(b & 0x0f)]));
367 }
368 out
369}
370
371#[cfg(test)]
372mod tests {
373 use super::*;
374
375 // Every expected digest below was computed with Go's own digest body
376 // (json.NewDecoder + UseNumber, json.NewEncoder + SetEscapeHTML(false), TrimSuffix "\n",
377 // sha256, hex of sum[:8]) on the same input text.
378
379 #[test]
380 fn digest_sorts_keys() {
381 // Go's Scheme field order in, sorted keys out: the "API key scheme" vector's digest.
382 assert_eq!(
383 digest_text(r#"{"type":"apiKey","in":"header","name":"X-Api-Key"}"#),
384 "12037b6b68d3604d"
385 );
386 assert_eq!(
387 digest_text(r#"{"in":"header","name":"X-Api-Key","type":"apiKey"}"#),
388 "12037b6b68d3604d"
389 );
390 }
391
392 #[test]
393 fn digest_undoes_html_escaping_and_writes_non_ascii_raw() {
394 // json.Marshal writes < & > as \u003c \u0026 \u003e; the canonical form writes them
395 // raw, and é raw: {"a":"<&>","b":"é"}.
396 assert_eq!(
397 digest_text(r#"{"b":"é","a":"\u003c\u0026\u003e"}"#),
398 "67cc612da7899777"
399 );
400 assert_eq!(digest_text(r#"{"a":"<&>","b":"é"}"#), "67cc612da7899777");
401 }
402
403 #[test]
404 fn digest_escapes_line_and_paragraph_separators() {
405 // A raw U+2028 is hashed as the six characters `\u2028`, as Go's encoder writes it.
406 assert_eq!(digest_text("{\"a\":\"\u{2028}\"}"), "952a2834102e2573");
407 assert_eq!(digest_text(r#"{"a":"\u2028"}"#), "952a2834102e2573");
408 }
409
410 #[test]
411 fn digest_keeps_number_text() {
412 // 12345678901234567890 is past i64 and loses digits as an f64; 1e3 is not rewritten
413 // as 1000 or 1000.0.
414 assert_eq!(
415 digest_text(r#"{"x":12345678901234567890}"#),
416 "80c05588fb76e5cf"
417 );
418 assert_eq!(digest_text(r#"{"x":1e3}"#), "b4d5049d8c391b49");
419 }
420
421 #[test]
422 fn hex_prefix_takes_eight_bytes_lowercase() {
423 let sum = [0x00, 0x0f, 0xf0, 0xff, 0x12, 0x34, 0xab, 0xcd, 0xee, 0x01];
424 assert_eq!(hex_prefix(&sum), "000ff0ff1234abcd");
425 }
426}