yup_oauth2/
application_default_credentials.rs

1use crate::client::SendRequest;
2use crate::error::Error;
3use crate::types::TokenInfo;
4use http_body_util::BodyExt;
5
6/// Provide options for the Application Default Credential Flow, mostly used for testing
7#[derive(Default, Clone, Debug)]
8pub struct ApplicationDefaultCredentialsFlowOpts {
9    /// Used as base to build the url during token request from GCP metadata server
10    pub metadata_url: Option<String>,
11}
12
13pub struct ApplicationDefaultCredentialsFlow {
14    metadata_url: String,
15}
16
17impl ApplicationDefaultCredentialsFlow {
18    pub(crate) fn new(opts: ApplicationDefaultCredentialsFlowOpts) -> Self {
19        let metadata_url = opts.metadata_url.unwrap_or_else(|| "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token".to_string());
20        ApplicationDefaultCredentialsFlow { metadata_url }
21    }
22
23    pub(crate) async fn token<T>(
24        &self,
25        hyper_client: &impl SendRequest,
26        scopes: &[T],
27    ) -> Result<TokenInfo, Error>
28    where
29        T: AsRef<str>,
30    {
31        let scope = crate::helper::join(scopes, ",");
32        let token_uri = format!("{}?scopes={}", self.metadata_url, scope);
33        let request = http::Request::get(token_uri)
34            .header("Metadata-Flavor", "Google")
35            .body(String::new()) // why body is needed?
36            .unwrap();
37        log::debug!("requesting token from metadata server: {:?}", request);
38        let (head, body) = hyper_client.request(request).await?.into_parts();
39        let body = body.collect().await?.to_bytes();
40        log::debug!("received response; head: {:?}, body: {:?}", head, body);
41        TokenInfo::from_json(&body)
42    }
43}
44
45// eof