google_cloud_auth/credentials/
api_key_credentials.rs1use crate::credentials::dynamic::CredentialsProvider;
24use crate::credentials::{CacheableResource, Credentials, Result};
25use crate::headers_util::build_cacheable_api_key_headers;
26use crate::token::{CachedTokenProvider, Token, TokenProvider};
27use crate::token_cache::TokenCache;
28use http::{Extensions, HeaderMap};
29use std::sync::Arc;
30
31struct ApiKeyTokenProvider {
32 api_key: String,
33}
34
35impl std::fmt::Debug for ApiKeyTokenProvider {
36 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37 f.debug_struct("ApiKeyCredentials")
38 .field("api_key", &"[censored]")
39 .finish()
40 }
41}
42
43#[async_trait::async_trait]
44impl TokenProvider for ApiKeyTokenProvider {
45 async fn token(&self) -> Result<Token> {
46 Ok(Token {
47 token: self.api_key.clone(),
48 token_type: String::new(),
49 expires_at: None,
50 metadata: None,
51 })
52 }
53}
54
55#[derive(Debug)]
56struct ApiKeyCredentials<T>
57where
58 T: CachedTokenProvider,
59{
60 token_provider: T,
61 quota_project_id: Option<String>,
62}
63
64#[derive(Debug)]
76pub struct Builder {
77 api_key: String,
78 quota_project_id: Option<String>,
79}
80
81impl Builder {
82 pub fn new<T: Into<String>>(api_key: T) -> Self {
93 Self {
94 api_key: api_key.into(),
95 quota_project_id: None,
96 }
97 }
98
99 pub fn with_quota_project_id<T: Into<String>>(mut self, quota_project_id: T) -> Self {
117 self.quota_project_id = Some(quota_project_id.into());
118 self
119 }
120
121 fn build_token_provider(self) -> ApiKeyTokenProvider {
122 ApiKeyTokenProvider {
123 api_key: self.api_key,
124 }
125 }
126
127 pub fn build(self) -> Credentials {
129 let quota_project_id = self.quota_project_id.clone();
130
131 Credentials {
132 inner: Arc::new(ApiKeyCredentials {
133 token_provider: TokenCache::new(self.build_token_provider()),
134 quota_project_id,
135 }),
136 }
137 }
138}
139
140#[async_trait::async_trait]
141impl<T> CredentialsProvider for ApiKeyCredentials<T>
142where
143 T: CachedTokenProvider,
144{
145 async fn headers(&self, extensions: Extensions) -> Result<CacheableResource<HeaderMap>> {
146 let cached_token = self.token_provider.token(extensions).await?;
147 build_cacheable_api_key_headers(&cached_token, &self.quota_project_id)
148 }
149}
150
151#[cfg(test)]
152mod tests {
153 use super::*;
154 use crate::credentials::QUOTA_PROJECT_KEY;
155 use crate::credentials::tests::get_headers_from_cache;
156 use http::HeaderValue;
157 use scoped_env::ScopedEnv;
158
159 const API_KEY_HEADER_KEY: &str = "x-goog-api-key";
160 type TestResult = std::result::Result<(), Box<dyn std::error::Error>>;
161
162 #[test]
163 fn debug_token_provider() {
164 let expected = Builder::new("test-api-key").build_token_provider();
165
166 let fmt = format!("{expected:?}");
167 assert!(!fmt.contains("super-secret-api-key"), "{fmt}");
168 }
169
170 #[tokio::test]
171 async fn api_key_credentials_token_provider() {
172 let tp = Builder::new("test-api-key").build_token_provider();
173 assert_eq!(
174 tp.token().await.unwrap(),
175 Token {
176 token: "test-api-key".to_string(),
177 token_type: String::new(),
178 expires_at: None,
179 metadata: None,
180 }
181 );
182 }
183
184 #[tokio::test]
185 #[serial_test::serial]
186 async fn create_api_key_credentials_basic() -> TestResult {
187 let _e = ScopedEnv::remove("GOOGLE_CLOUD_QUOTA_PROJECT");
188
189 let creds = Builder::new("test-api-key").build();
190 let headers = get_headers_from_cache(creds.headers(Extensions::new()).await.unwrap())?;
191 let value = headers.get(API_KEY_HEADER_KEY).unwrap();
192
193 assert_eq!(headers.len(), 1, "{headers:?}");
194 assert_eq!(value, HeaderValue::from_static("test-api-key"));
195 assert!(value.is_sensitive());
196 Ok(())
197 }
198
199 #[tokio::test]
200 #[serial_test::serial]
201 async fn create_api_key_credentials_with_options() -> TestResult {
202 let _e = ScopedEnv::remove("GOOGLE_CLOUD_QUOTA_PROJECT");
203
204 let creds = Builder::new("test-api-key")
205 .with_quota_project_id("qp-option")
206 .build();
207 let headers = get_headers_from_cache(creds.headers(Extensions::new()).await.unwrap())?;
208 let api_key = headers.get(API_KEY_HEADER_KEY).unwrap();
209 let quota_project = headers.get(QUOTA_PROJECT_KEY).unwrap();
210
211 assert_eq!(headers.len(), 2, "{headers:?}");
212 assert_eq!(api_key, HeaderValue::from_static("test-api-key"));
213 assert!(api_key.is_sensitive());
214 assert_eq!(quota_project, HeaderValue::from_static("qp-option"));
215 assert!(!quota_project.is_sensitive());
216 Ok(())
217 }
218
219 #[tokio::test]
220 #[serial_test::serial]
221 async fn create_api_key_credentials_basic_with_extensions() -> TestResult {
222 let _e = ScopedEnv::remove("GOOGLE_CLOUD_QUOTA_PROJECT");
223
224 let creds = Builder::new("test-api-key").build();
225 let mut extensions = Extensions::new();
226 let cached_headers = creds.headers(extensions.clone()).await?;
227 let (headers, entity_tag) = match cached_headers {
228 CacheableResource::New { entity_tag, data } => (data, entity_tag),
229 CacheableResource::NotModified => unreachable!("expecting new headers"),
230 };
231 let value = headers.get(API_KEY_HEADER_KEY).unwrap();
232
233 assert_eq!(headers.len(), 1, "{headers:?}");
234 assert_eq!(value, HeaderValue::from_static("test-api-key"));
235 assert!(value.is_sensitive());
236 extensions.insert(entity_tag);
237
238 let cached_headers = creds.headers(extensions).await?;
239
240 match cached_headers {
241 CacheableResource::New { .. } => unreachable!("expecting new headers"),
242 CacheableResource::NotModified => CacheableResource::<HeaderMap>::NotModified,
243 };
244
245 Ok(())
246 }
247}