gcloud_auth/
project.rs

1use google_cloud_metadata::on_gce;
2
3use crate::credentials::CredentialsFile;
4use crate::idtoken::id_token_source_from_credentials;
5use crate::misc::EMPTY;
6use crate::token_source::authorized_user_token_source::UserAccountTokenSource;
7use crate::token_source::compute_identity_source::ComputeIdentitySource;
8use crate::token_source::compute_token_source::ComputeTokenSource;
9use crate::token_source::reuse_token_source::ReuseTokenSource;
10use crate::token_source::service_account_token_source::OAuth2ServiceAccountTokenSource;
11use crate::token_source::service_account_token_source::ServiceAccountTokenSource;
12use crate::token_source::TokenSource;
13use crate::{credentials, error};
14
15pub(crate) const SERVICE_ACCOUNT_KEY: &str = "service_account";
16const USER_CREDENTIALS_KEY: &str = "authorized_user";
17#[cfg(feature = "external-account")]
18const EXTERNAL_ACCOUNT_KEY: &str = "external_account";
19
20#[derive(Debug, Clone, Default)]
21pub struct Config<'a> {
22    audience: Option<&'a str>,
23    scopes: Option<&'a [&'a str]>,
24    sub: Option<&'a str>,
25    use_id_token: bool,
26}
27
28impl<'a> Config<'a> {
29    pub fn scopes_to_string(&self, sep: &str) -> String {
30        match self.scopes {
31            Some(s) => s.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(sep),
32            None => EMPTY.to_string(),
33        }
34    }
35
36    pub fn with_audience(mut self, value: &'a str) -> Self {
37        self.audience = Some(value);
38        self
39    }
40
41    pub fn with_scopes(mut self, value: &'a [&'a str]) -> Self {
42        self.scopes = Some(value);
43        self
44    }
45
46    pub fn with_sub(mut self, value: &'a str) -> Self {
47        self.sub = Some(value);
48        self
49    }
50
51    pub fn with_use_id_token(mut self, value: bool) -> Self {
52        self.use_id_token = value;
53        self
54    }
55}
56
57#[derive(Clone)]
58pub struct ProjectInfo {
59    pub project_id: Option<String>,
60}
61
62#[derive(Clone)]
63pub enum Project {
64    FromFile(Box<CredentialsFile>),
65    FromMetadataServer(ProjectInfo),
66}
67
68// Possible sensitive info in debug messages
69impl std::fmt::Debug for Project {
70    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71        match self {
72            Project::FromFile(_) => write!(f, "Project::FromFile"),
73            Project::FromMetadataServer(_) => write!(f, "Project::FromMetadataServer"),
74        }
75    }
76}
77
78impl Project {
79    pub fn project_id(&self) -> Option<&String> {
80        match self {
81            Self::FromFile(file) => file.project_id.as_ref(),
82            Self::FromMetadataServer(info) => info.project_id.as_ref(),
83        }
84    }
85}
86
87/// project() returns the project credentials or project info from metadata server.
88pub async fn project() -> Result<Project, error::Error> {
89    let credentials = credentials::CredentialsFile::new().await;
90    match credentials {
91        Ok(credentials) => Ok(Project::FromFile(Box::new(credentials))),
92        Err(e) => {
93            if on_gce().await {
94                let project_id = google_cloud_metadata::project_id().await;
95                Ok(Project::FromMetadataServer(ProjectInfo {
96                    project_id: if project_id.is_empty() { None } else { Some(project_id) },
97                }))
98            } else {
99                Err(e)
100            }
101        }
102    }
103}
104
105/// Creates token source using provided credentials file
106pub async fn create_token_source_from_credentials(
107    credentials: &CredentialsFile,
108    config: &Config<'_>,
109) -> Result<Box<dyn TokenSource>, error::Error> {
110    let ts = credentials_from_json_with_params(credentials, config).await?;
111    let token = ts.token().await?;
112    Ok(Box::new(ReuseTokenSource::new(ts, token)))
113}
114
115/// create_token_source_from_project creates the token source.
116pub async fn create_token_source_from_project(
117    project: &Project,
118    config: Config<'_>,
119) -> Result<Box<dyn TokenSource>, error::Error> {
120    match project {
121        Project::FromFile(file) => {
122            if config.use_id_token {
123                id_token_source_from_credentials(&Default::default(), file, config.audience.unwrap_or_default()).await
124            } else {
125                create_token_source_from_credentials(file, &config).await
126            }
127        }
128        Project::FromMetadataServer(_) => {
129            if config.use_id_token {
130                let ts = ComputeIdentitySource::new(config.audience.unwrap_or_default())?;
131                let token = ts.token().await?;
132                Ok(Box::new(ReuseTokenSource::new(Box::new(ts), token)))
133            } else {
134                if config.scopes.is_none() {
135                    return Err(error::Error::ScopeOrAudienceRequired);
136                }
137                let ts = ComputeTokenSource::new(config.scopes_to_string(",").as_str())?;
138                let token = ts.token().await?;
139                Ok(Box::new(ReuseTokenSource::new(Box::new(ts), token)))
140            }
141        }
142    }
143}
144
145/// create_token_source creates the token source
146/// use [DefaultTokenSourceProvider](crate::token::DefaultTokenSourceProvider) or impl [TokenSourceProvider](google_cloud_token::TokenSourceProvider) instead.
147#[deprecated(note = "Use DefaultTokenSourceProvider instead")]
148pub async fn create_token_source(config: Config<'_>) -> Result<Box<dyn TokenSource>, error::Error> {
149    let project = project().await?;
150    create_token_source_from_project(&project, config).await
151}
152
153async fn credentials_from_json_with_params(
154    credentials: &CredentialsFile,
155    config: &Config<'_>,
156) -> Result<Box<dyn TokenSource>, error::Error> {
157    match credentials.tp.as_str() {
158        SERVICE_ACCOUNT_KEY => {
159            match config.audience {
160                None => {
161                    if config.scopes.is_none() {
162                        return Err(error::Error::ScopeOrAudienceRequired);
163                    }
164
165                    // use Standard OAuth 2.0 Flow
166                    let source = OAuth2ServiceAccountTokenSource::new(
167                        credentials,
168                        config.scopes_to_string(" ").as_str(),
169                        config.sub,
170                    )?;
171                    Ok(Box::new(source))
172                }
173                Some(audience) => {
174                    // use self-signed JWT.
175                    let source = ServiceAccountTokenSource::new(credentials, audience)?;
176                    Ok(Box::new(source))
177                }
178            }
179        }
180        USER_CREDENTIALS_KEY => Ok(Box::new(UserAccountTokenSource::new(credentials)?)),
181        #[cfg(feature = "external-account")]
182        EXTERNAL_ACCOUNT_KEY => {
183            let ts = crate::token_source::external_account_source::ExternalAccountTokenSource::new(
184                config.scopes_to_string(" "),
185                credentials.clone(),
186            )
187            .await?;
188            if let Some(impersonation_url) = &credentials.service_account_impersonation_url {
189                let url = impersonation_url.clone();
190                let mut scopes = config.scopes.map(|v| v.to_vec()).unwrap_or(vec![]);
191                scopes.push("https://www.googleapis.com/auth/cloud-platform");
192                let scopes = scopes.iter().map(|e| e.to_string()).collect();
193                let lifetime = credentials
194                    .service_account_impersonation
195                    .clone()
196                    .map(|v| v.token_lifetime_seconds);
197                let ts = crate::token_source::impersonate_token_source::ImpersonateTokenSource::new(
198                    url,
199                    vec![],
200                    scopes,
201                    lifetime,
202                    Box::new(ts),
203                );
204                Ok(Box::new(ts))
205            } else {
206                Ok(Box::new(ts))
207            }
208        }
209        _ => Err(error::Error::UnsupportedAccountType(credentials.tp.to_string())),
210    }
211}