a2a_protocol_client/token_provider/
exchange.rs1use std::fmt;
34use std::time::Duration;
35
36use base64::Engine;
37use base64::engine::general_purpose::STANDARD;
38use http_body_util::Full;
39use hyper::body::Bytes;
40
41use super::{
42 DEFAULT_TOKEN_REQUEST_TIMEOUT, MAX_TOKEN_RESPONSE_SIZE, TokenEndpointAuthStyle,
43 TokenHttpClient, build_token_http_client, check_endpoint_reachable, check_endpoint_secure,
44 encode_form, form_urlencode, token_error,
45};
46use crate::error::{ClientError, ClientResult};
47
48pub const TOKEN_EXCHANGE_GRANT: &str = "urn:ietf:params:oauth:grant-type:token-exchange";
50
51pub const ACCESS_TOKEN_TYPE: &str = "urn:ietf:params:oauth:token-type:access_token";
53
54pub const JWT_TOKEN_TYPE: &str = "urn:ietf:params:oauth:token-type:jwt";
56
57#[derive(Clone)]
59#[non_exhaustive]
60pub struct ExchangeRequest {
61 pub subject_token: String,
63 pub subject_token_type: String,
65 pub actor_token: Option<(String, String)>,
69 pub audience: Vec<String>,
71 pub resource: Vec<String>,
73 pub scopes: Vec<String>,
75 pub requested_token_type: Option<String>,
77}
78
79impl ExchangeRequest {
80 #[must_use]
82 pub fn new(subject_token: impl Into<String>) -> Self {
83 Self {
84 subject_token: subject_token.into(),
85 subject_token_type: ACCESS_TOKEN_TYPE.to_owned(),
86 actor_token: None,
87 audience: Vec::new(),
88 resource: Vec::new(),
89 scopes: Vec::new(),
90 requested_token_type: None,
91 }
92 }
93
94 #[must_use]
96 pub fn with_subject_token_type(mut self, token_type: impl Into<String>) -> Self {
97 self.subject_token_type = token_type.into();
98 self
99 }
100
101 #[must_use]
103 pub fn with_actor_token(
104 mut self,
105 token: impl Into<String>,
106 token_type: impl Into<String>,
107 ) -> Self {
108 self.actor_token = Some((token.into(), token_type.into()));
109 self
110 }
111
112 #[must_use]
114 pub fn with_audience(mut self, audience: impl Into<String>) -> Self {
115 self.audience.push(audience.into());
116 self
117 }
118
119 #[must_use]
121 pub fn with_resource(mut self, resource: impl Into<String>) -> Self {
122 self.resource.push(resource.into());
123 self
124 }
125
126 #[must_use]
128 pub fn with_scopes<I, S>(mut self, scopes: I) -> Self
129 where
130 I: IntoIterator<Item = S>,
131 S: Into<String>,
132 {
133 self.scopes = scopes.into_iter().map(Into::into).collect();
134 self
135 }
136
137 #[must_use]
139 pub fn with_requested_token_type(mut self, token_type: impl Into<String>) -> Self {
140 self.requested_token_type = Some(token_type.into());
141 self
142 }
143
144 fn form(&self) -> Vec<(String, String)> {
146 let mut form = vec![("grant_type".to_owned(), TOKEN_EXCHANGE_GRANT.to_owned())];
147 for r in &self.resource {
148 form.push(("resource".to_owned(), r.clone()));
149 }
150 for a in &self.audience {
151 form.push(("audience".to_owned(), a.clone()));
152 }
153 if !self.scopes.is_empty() {
154 form.push(("scope".to_owned(), self.scopes.join(" ")));
155 }
156 if let Some(t) = &self.requested_token_type {
157 form.push(("requested_token_type".to_owned(), t.clone()));
158 }
159 form.push(("subject_token".to_owned(), self.subject_token.clone()));
160 form.push((
161 "subject_token_type".to_owned(),
162 self.subject_token_type.clone(),
163 ));
164 if let Some((token, token_type)) = &self.actor_token {
165 form.push(("actor_token".to_owned(), token.clone()));
166 form.push(("actor_token_type".to_owned(), token_type.clone()));
167 }
168 form
169 }
170}
171
172impl fmt::Debug for ExchangeRequest {
173 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174 f.debug_struct("ExchangeRequest")
175 .field("subject_token", &"<redacted>")
176 .field("subject_token_type", &self.subject_token_type)
177 .field(
178 "actor_token",
179 &self.actor_token.as_ref().map(|_| "<redacted>"),
180 )
181 .field("audience", &self.audience)
182 .field("resource", &self.resource)
183 .field("scopes", &self.scopes)
184 .finish_non_exhaustive()
185 }
186}
187
188#[derive(Clone, serde::Deserialize)]
190#[non_exhaustive]
191pub struct ExchangedToken {
192 pub access_token: String,
194 pub issued_token_type: String,
196 pub token_type: String,
199 #[serde(default)]
201 pub expires_in: Option<u64>,
202 #[serde(default)]
204 pub scope: Option<String>,
205}
206
207impl ExchangedToken {
208 #[must_use]
210 pub fn lifetime(&self) -> Option<Duration> {
211 self.expires_in.map(Duration::from_secs)
212 }
213}
214
215impl fmt::Debug for ExchangedToken {
216 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
217 f.debug_struct("ExchangedToken")
218 .field("access_token", &"<redacted>")
219 .field("issued_token_type", &self.issued_token_type)
220 .field("token_type", &self.token_type)
221 .field("expires_in", &self.expires_in)
222 .field("scope", &self.scope)
223 .finish()
224 }
225}
226
227pub struct TokenExchange {
231 token_url: String,
232 client_id: String,
233 client_secret: zeroize::Zeroizing<String>,
234 auth_style: TokenEndpointAuthStyle,
235 request_timeout: Duration,
236 allow_insecure: bool,
237 client: TokenHttpClient,
238}
239
240impl fmt::Debug for TokenExchange {
241 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
242 f.debug_struct("TokenExchange")
243 .field("token_url", &self.token_url)
244 .field("client_id", &self.client_id)
245 .field("client_secret", &"<redacted>")
246 .field("auth_style", &self.auth_style)
247 .finish_non_exhaustive()
248 }
249}
250
251impl TokenExchange {
252 #[must_use]
254 pub fn new(
255 token_url: impl Into<String>,
256 client_id: impl Into<String>,
257 client_secret: impl Into<String>,
258 ) -> Self {
259 Self {
260 token_url: token_url.into(),
261 client_id: client_id.into(),
262 client_secret: zeroize::Zeroizing::new(client_secret.into()),
263 auth_style: TokenEndpointAuthStyle::Basic,
264 request_timeout: DEFAULT_TOKEN_REQUEST_TIMEOUT,
265 allow_insecure: false,
266 client: build_token_http_client(),
267 }
268 }
269
270 #[cfg(feature = "tls-rustls")]
276 #[must_use]
277 pub fn with_tls_config(mut self, tls: rustls::ClientConfig) -> Self {
278 self.client = super::token_http_client_with(tls);
279 self
280 }
281
282 #[must_use]
287 pub const fn allow_insecure_token_endpoint(mut self) -> Self {
288 self.allow_insecure = true;
289 self
290 }
291
292 #[must_use]
295 pub const fn with_auth_style(mut self, style: TokenEndpointAuthStyle) -> Self {
296 self.auth_style = style;
297 self
298 }
299
300 #[must_use]
303 pub const fn with_request_timeout(mut self, timeout: Duration) -> Self {
304 self.request_timeout = timeout;
305 self
306 }
307
308 pub async fn exchange(&self, request: &ExchangeRequest) -> ClientResult<ExchangedToken> {
317 check_endpoint_secure(&self.token_url, "token endpoint", self.allow_insecure)?;
318 check_endpoint_reachable(
319 cfg!(feature = "tls-rustls"),
320 &self.token_url,
321 "token endpoint",
322 )?;
323 let deadline = tokio::time::Instant::now() + self.request_timeout;
324 let resp = tokio::time::timeout_at(deadline, self.client.request(self.build(request)?))
325 .await
326 .map_err(|_| ClientError::Timeout("token exchange timed out".into()))?
327 .map_err(|e| {
328 ClientError::HttpClient(format!(
329 "token exchange failed: {}",
330 crate::error::chain(&e)
331 ))
332 })?;
333 let status = resp.status();
334 let body = crate::transport::collect_response_limited(
335 resp,
336 MAX_TOKEN_RESPONSE_SIZE,
337 deadline.saturating_duration_since(tokio::time::Instant::now()),
338 )
339 .await?;
340 if !status.is_success() {
341 return Err(token_error(status, &body));
342 }
343 serde_json::from_slice(&body).map_err(|e| {
344 ClientError::Transport(format!("token exchange returned an unusable response: {e}"))
345 })
346 }
347
348 fn build(&self, request: &ExchangeRequest) -> ClientResult<hyper::Request<Full<Bytes>>> {
349 let mut form = request.form();
350 if self.auth_style == TokenEndpointAuthStyle::Post {
351 form.push(("client_id".to_owned(), self.client_id.clone()));
352 form.push(("client_secret".to_owned(), (*self.client_secret).clone()));
353 }
354 let mut builder = hyper::Request::builder()
355 .method(hyper::Method::POST)
356 .uri(&self.token_url)
357 .header("content-type", "application/x-www-form-urlencoded")
358 .header("accept", "application/json");
359 if self.auth_style == TokenEndpointAuthStyle::Basic {
360 let credentials = format!(
361 "{}:{}",
362 form_urlencode(&self.client_id),
363 form_urlencode(&self.client_secret)
364 );
365 builder = builder.header(
366 "authorization",
367 format!("Basic {}", STANDARD.encode(credentials)),
368 );
369 }
370 builder
371 .body(Full::new(Bytes::from(encode_form(&form))))
372 .map_err(|e| ClientError::Transport(format!("token exchange build failed: {e}")))
373 }
374}
375
376#[cfg(test)]
377mod tests;