|
| 1 | +use async_trait::async_trait; |
| 2 | +use std::{collections::HashMap, sync::RwLock}; |
| 3 | +use time::{format_description::well_known::Iso8601, OffsetDateTime}; |
| 4 | + |
| 5 | +use hyper::header; |
| 6 | +use serde::{de, Deserialize, Deserializer, Serialize}; |
| 7 | + |
| 8 | +use crate::{ |
| 9 | + authentication_manager::ServiceAccount, gcloud_authorized_user::DEFAULT_TOKEN_DURATION, |
| 10 | + types::HyperClient, util::HyperExt, Error, Token, |
| 11 | +}; |
| 12 | + |
| 13 | +// This credential uses the `source_credentials` to get a token |
| 14 | +// and then uses that token to get a token impersonating the service |
| 15 | +// account specified by `service_account_impersonation_url`. |
| 16 | +// refresh logic https://github.com/golang/oauth2/blob/a835fc4358f6852f50c4c5c33fddcd1adade5b0a/google/internal/externalaccount/impersonate.go#L57 |
| 17 | +// |
| 18 | +// In practice, the api currently referred to by `service_account_impersonation_url` is |
| 19 | +// https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateAccessToken |
| 20 | +pub(crate) struct ImpersonatedServiceAccount { |
| 21 | + service_account_impersonation_url: String, |
| 22 | + source_credentials: Box<dyn ServiceAccount>, |
| 23 | + delegates: Vec<String>, |
| 24 | + tokens: RwLock<HashMap<Vec<String>, Token>>, |
| 25 | +} |
| 26 | + |
| 27 | +impl ImpersonatedServiceAccount { |
| 28 | + pub(crate) fn new( |
| 29 | + source_credentials: Box<dyn ServiceAccount>, |
| 30 | + service_account_impersonation_url: String, |
| 31 | + delegates: Vec<String>, |
| 32 | + ) -> Self { |
| 33 | + Self { |
| 34 | + service_account_impersonation_url, |
| 35 | + source_credentials, |
| 36 | + delegates, |
| 37 | + tokens: RwLock::new(HashMap::new()), |
| 38 | + } |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +impl std::fmt::Debug for ImpersonatedServiceAccount { |
| 43 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 44 | + f.debug_struct("ImpersonatedServiceAccount") |
| 45 | + .field( |
| 46 | + "service_account_impersonation_url", |
| 47 | + &self.service_account_impersonation_url, |
| 48 | + ) |
| 49 | + .field("source_credentials", &"Box<dyn ServiceAccount>") |
| 50 | + .field("delegates", &self.delegates) |
| 51 | + .finish() |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +// This is the impersonation token described by this documentation |
| 56 | +// https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateAccessToken |
| 57 | +#[derive(Deserialize)] |
| 58 | +#[serde(rename_all = "camelCase")] |
| 59 | +struct ImpersonationTokenResponse { |
| 60 | + access_token: String, |
| 61 | + #[serde(deserialize_with = "deserialize_rfc3339")] |
| 62 | + expire_time: OffsetDateTime, |
| 63 | +} |
| 64 | + |
| 65 | +fn deserialize_rfc3339<'de, D>(deserializer: D) -> Result<OffsetDateTime, D::Error> |
| 66 | +where |
| 67 | + D: Deserializer<'de>, |
| 68 | +{ |
| 69 | + // First try to deserialize seconds |
| 70 | + let time_str: String = Deserialize::deserialize(deserializer)?; |
| 71 | + |
| 72 | + OffsetDateTime::parse(&time_str, &Iso8601::PARSING).map_err(de::Error::custom) |
| 73 | +} |
| 74 | + |
| 75 | +impl From<ImpersonationTokenResponse> for Token { |
| 76 | + fn from(value: ImpersonationTokenResponse) -> Self { |
| 77 | + Token::new(value.access_token, value.expire_time) |
| 78 | + } |
| 79 | +} |
| 80 | + |
| 81 | +#[cfg(test)] |
| 82 | +mod tests { |
| 83 | + use super::*; |
| 84 | + |
| 85 | + #[test] |
| 86 | + fn test_deserialize_impersonation_token() { |
| 87 | + let resp_body = "{\n \"accessToken\": \"secret_token\",\n \"expireTime\": \"2023-08-18T04:09:45Z\"\n}"; |
| 88 | + let token: ImpersonationTokenResponse = |
| 89 | + serde_json::from_str(resp_body).expect("Failed to parse token"); |
| 90 | + assert_eq!(token.access_token, "secret_token"); |
| 91 | + } |
| 92 | +} |
| 93 | + |
| 94 | +#[async_trait] |
| 95 | +impl ServiceAccount for ImpersonatedServiceAccount { |
| 96 | + async fn project_id(&self, hc: &HyperClient) -> Result<String, Error> { |
| 97 | + self.source_credentials.project_id(hc).await |
| 98 | + } |
| 99 | + |
| 100 | + fn get_token(&self, scopes: &[&str]) -> Option<Token> { |
| 101 | + let key: Vec<_> = scopes.iter().map(|x| x.to_string()).collect(); |
| 102 | + self.tokens.read().unwrap().get(&key).cloned() |
| 103 | + } |
| 104 | + |
| 105 | + async fn refresh_token(&self, client: &HyperClient, scopes: &[&str]) -> Result<Token, Error> { |
| 106 | + let source_token = self |
| 107 | + .source_credentials |
| 108 | + .refresh_token(client, scopes) |
| 109 | + .await?; |
| 110 | + |
| 111 | + // Then we do a request to get the impersonated token |
| 112 | + let lifetime_seconds = DEFAULT_TOKEN_DURATION.whole_seconds(); |
| 113 | + #[derive(Serialize, Clone)] |
| 114 | + // Format from https://github.com/golang/oauth2/blob/a835fc4358f6852f50c4c5c33fddcd1adade5b0a/google/internal/externalaccount/impersonate.go#L21 |
| 115 | + struct AccessTokenRequest { |
| 116 | + lifetime: String, |
| 117 | + #[serde(skip_serializing_if = "Vec::is_empty")] |
| 118 | + scope: Vec<String>, |
| 119 | + #[serde(skip_serializing_if = "Vec::is_empty")] |
| 120 | + delegates: Vec<String>, |
| 121 | + } |
| 122 | + |
| 123 | + let request = AccessTokenRequest { |
| 124 | + lifetime: format!("{lifetime_seconds}s"), |
| 125 | + scope: scopes.iter().map(|s| s.to_string()).collect(), |
| 126 | + delegates: self.delegates.clone(), |
| 127 | + }; |
| 128 | + let rqbody = |
| 129 | + serde_json::to_string(&request).expect("access token request failed to serialize"); |
| 130 | + |
| 131 | + let token_uri = self.service_account_impersonation_url.as_str(); |
| 132 | + |
| 133 | + let mut retries = 0; |
| 134 | + let response = loop { |
| 135 | + // We assume bearer tokens only. In the referenced code, other token types are possible |
| 136 | + // https://github.com/golang/oauth2/blob/a835fc4358f6852f50c4c5c33fddcd1adade5b0a/token.go#L84 |
| 137 | + let request = hyper::Request::post(token_uri) |
| 138 | + .header( |
| 139 | + header::AUTHORIZATION, |
| 140 | + format!("Bearer {}", source_token.as_str()), |
| 141 | + ) |
| 142 | + .header(header::CONTENT_TYPE, "application/json") |
| 143 | + .body(hyper::Body::from(rqbody.clone())) |
| 144 | + .unwrap(); |
| 145 | + |
| 146 | + tracing::debug!("requesting impersonation token from service account: {request:?}"); |
| 147 | + let err = match client.request(request).await { |
| 148 | + // Early return when the request succeeds |
| 149 | + Ok(response) => break response, |
| 150 | + Err(err) => err, |
| 151 | + }; |
| 152 | + |
| 153 | + tracing::warn!( |
| 154 | + "Failed to refresh impersonation token with service token endpoint {token_uri}: {err}, trying again..." |
| 155 | + ); |
| 156 | + retries += 1; |
| 157 | + if retries >= RETRY_COUNT { |
| 158 | + return Err(Error::OAuthConnectionError(err)); |
| 159 | + } |
| 160 | + }; |
| 161 | + |
| 162 | + let token_response: ImpersonationTokenResponse = response.deserialize().await?; |
| 163 | + let token: Token = token_response.into(); |
| 164 | + |
| 165 | + let key = scopes.iter().map(|x| (*x).to_string()).collect(); |
| 166 | + self.tokens.write().unwrap().insert(key, token.clone()); |
| 167 | + |
| 168 | + Ok(token) |
| 169 | + } |
| 170 | +} |
| 171 | + |
| 172 | +/// How many times to attempt to fetch a token from the set credentials token endpoint. |
| 173 | +const RETRY_COUNT: u8 = 5; |
0 commit comments