Skip to main content

lance_io/object_store/providers/
gcp.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright The Lance Authors
3
4use std::{collections::HashMap, str::FromStr, sync::Arc, time::Duration};
5
6use object_store::list::PaginatedListStore;
7use object_store::{
8    ClientOptions, CredentialProvider, ObjectStore as OSObjectStore, Result as ObjectStoreResult,
9    client::{HttpClient, HttpConnector, HttpRequestBody, ReqwestConnector},
10};
11use opendal::{Operator, services::Gcs};
12use reqsign_core::{Context as ReqsignContext, HttpSend, OsEnv, ProvideCredential};
13use reqsign_file_read_tokio::TokioFileRead;
14use reqsign_google::{Credential as ReqsignCredential, FileCredentialProvider};
15use tokio::sync::RwLock;
16
17use object_store::{
18    RetryConfig, StaticCredentialProvider,
19    gcp::{GcpCredential, GoogleCloudStorage, GoogleCloudStorageBuilder, GoogleConfigKey},
20};
21use url::Url;
22
23use crate::object_store::opendal_store::OpendalStore;
24use crate::object_store::{
25    DEFAULT_CLOUD_BLOCK_SIZE, DEFAULT_CLOUD_IO_PARALLELISM, DEFAULT_MAX_IOP_SIZE, ObjectStore,
26    ObjectStoreParams, ObjectStoreProvider, StorageOptions, StorageOptionsAccessor,
27    dynamic_credentials::build_dynamic_credential_provider,
28    throttle::{AimdThrottleConfig, AimdThrottleState, cloud_http_connector, with_throttling},
29};
30use lance_core::error::{Error, Result};
31use lance_core::utils::parse::str_is_truthy;
32#[derive(Default, Debug)]
33pub struct GcsStoreProvider;
34
35#[derive(Debug)]
36struct ObjectStoreHttpSend {
37    client: HttpClient,
38}
39
40impl HttpSend for ObjectStoreHttpSend {
41    async fn http_send(
42        &self,
43        request: http::Request<bytes::Bytes>,
44    ) -> reqsign_core::Result<http::Response<bytes::Bytes>> {
45        let (parts, body) = request.into_parts();
46        let request = http::Request::from_parts(parts, HttpRequestBody::from(body));
47        let response = self.client.execute(request).await.map_err(|source| {
48            reqsign_core::Error::unexpected("failed to send Google workload identity HTTP request")
49                .with_source(source)
50        })?;
51        let (parts, body) = response.into_parts();
52        let body = body.bytes().await.map_err(|source| {
53            reqsign_core::Error::unexpected("failed to read Google workload identity HTTP response")
54                .with_source(source)
55        })?;
56        Ok(http::Response::from_parts(parts, body))
57    }
58}
59
60#[derive(Debug)]
61struct WorkloadIdentityCredentialProvider {
62    provider: FileCredentialProvider,
63    context: ReqsignContext,
64    cached_credential: RwLock<Option<ReqsignCredential>>,
65}
66
67impl WorkloadIdentityCredentialProvider {
68    fn new(application_credentials_path: String, http_client: HttpClient) -> Self {
69        let context = ReqsignContext::new()
70            .with_file_read(TokioFileRead)
71            .with_http_send(ObjectStoreHttpSend {
72                client: http_client,
73            })
74            .with_env(OsEnv);
75        Self {
76            provider: FileCredentialProvider::new(application_credentials_path),
77            context,
78            cached_credential: RwLock::new(None),
79        }
80    }
81}
82
83fn usable_gcp_credential(credential: &ReqsignCredential) -> Option<GcpCredential> {
84    credential
85        .token
86        .as_ref()
87        .filter(|_| credential.has_valid_token())
88        .map(|token| GcpCredential {
89            bearer: token.access_token.clone(),
90        })
91}
92
93fn workload_identity_error(
94    source: impl std::error::Error + Send + Sync + 'static,
95) -> object_store::Error {
96    object_store::Error::Generic {
97        store: "GCS workload identity credentials",
98        source: Box::new(source),
99    }
100}
101
102#[async_trait::async_trait]
103impl CredentialProvider for WorkloadIdentityCredentialProvider {
104    type Credential = GcpCredential;
105
106    async fn get_credential(&self) -> ObjectStoreResult<Arc<Self::Credential>> {
107        if let Some(credential) = self
108            .cached_credential
109            .read()
110            .await
111            .as_ref()
112            .and_then(usable_gcp_credential)
113        {
114            return Ok(Arc::new(credential));
115        }
116
117        let mut cached_credential = self.cached_credential.write().await;
118        if let Some(credential) = cached_credential.as_ref().and_then(usable_gcp_credential) {
119            return Ok(Arc::new(credential));
120        }
121
122        let credential = self
123            .provider
124            .provide_credential(&self.context)
125            .await
126            .map_err(workload_identity_error)?
127            .ok_or_else(|| {
128                workload_identity_error(std::io::Error::other(
129                    "application credentials did not provide a Google access token",
130                ))
131            })?;
132        let gcp_credential = usable_gcp_credential(&credential).ok_or_else(|| {
133            workload_identity_error(std::io::Error::other(
134                "application credentials provided an expired or unusable Google access token",
135            ))
136        })?;
137        *cached_credential = Some(credential);
138        Ok(Arc::new(gcp_credential))
139    }
140}
141
142#[derive(serde::Deserialize)]
143struct ApplicationCredentialKind {
144    #[serde(rename = "type")]
145    credential_type: String,
146}
147
148struct GcsClientOptions {
149    object_requests: ClientOptions,
150    credential_requests: ClientOptions,
151}
152
153fn gcs_client_options(storage_options: &StorageOptions) -> Result<GcsClientOptions> {
154    let mut object_requests = storage_options.client_options()?;
155    // headers.* options are scoped to object requests and may contain secrets. Credential
156    // exchanges can target unrelated identity endpoints, so only share typed client settings.
157    let mut credential_requests = object_requests
158        .clone()
159        .with_default_headers(Default::default());
160    for (key, value) in storage_options.as_gcs_options() {
161        if let GoogleConfigKey::Client(key) = key {
162            object_requests = object_requests.with_config(key, value.clone());
163            credential_requests = credential_requests.with_config(key, value);
164        }
165    }
166    Ok(GcsClientOptions {
167        object_requests,
168        credential_requests,
169    })
170}
171
172fn workload_identity_credential_provider(
173    storage_options: &StorageOptions,
174    client_options: &ClientOptions,
175) -> Result<Option<Arc<dyn CredentialProvider<Credential = GcpCredential>>>> {
176    let gcs_options = storage_options.as_gcs_options();
177    if gcs_options.contains_key(&GoogleConfigKey::ServiceAccount)
178        || gcs_options.contains_key(&GoogleConfigKey::ServiceAccountKey)
179    {
180        return Ok(None);
181    }
182
183    let Some(application_credentials_path) =
184        gcs_options.get(&GoogleConfigKey::ApplicationCredentials)
185    else {
186        return Ok(None);
187    };
188    let Ok(contents) = std::fs::read(application_credentials_path) else {
189        return Ok(None);
190    };
191    let Ok(credential_kind) = serde_json::from_slice::<ApplicationCredentialKind>(&contents) else {
192        return Ok(None);
193    };
194    if credential_kind.credential_type != "external_account" {
195        return Ok(None);
196    }
197
198    let http_client = ReqwestConnector::default().connect(client_options)?;
199    Ok(Some(Arc::new(WorkloadIdentityCredentialProvider::new(
200        application_credentials_path.clone(),
201        http_client,
202    ))))
203}
204
205impl GcsStoreProvider {
206    async fn build_opendal_gcs_store(
207        &self,
208        base_path: &Url,
209        storage_options: &StorageOptions,
210    ) -> Result<Arc<dyn OSObjectStore>> {
211        let bucket = base_path
212            .host_str()
213            .ok_or_else(|| Error::invalid_input("GCS URL must contain bucket name"))?
214            .to_string();
215
216        let prefix = base_path.path().trim_start_matches('/').to_string();
217
218        // Start with all storage options as the config map
219        // OpenDAL will handle environment variables through its default credentials chain
220        let mut config_map: HashMap<String, String> = storage_options.0.clone();
221
222        // Set required OpenDAL configuration
223        config_map.insert("bucket".to_string(), bucket);
224
225        if !prefix.is_empty() {
226            config_map.insert("root".to_string(), format!("/{}", prefix));
227        }
228
229        let operator = Operator::from_iter::<Gcs>(config_map)
230            .map_err(|e| Error::invalid_input(format!("Failed to create GCS operator: {:?}", e)))?;
231
232        Ok(Arc::new(OpendalStore::new(operator)) as Arc<dyn OSObjectStore>)
233    }
234
235    async fn build_google_cloud_store(
236        &self,
237        base_path: &Url,
238        storage_options: &StorageOptions,
239        accessor: Option<Arc<StorageOptionsAccessor>>,
240        throttle_state: Option<&AimdThrottleState>,
241        // Concrete rather than `dyn`, so the caller keeps the handle a paginated listing
242        // needs: `PaginatedListStore` is a separate trait from `ObjectStore`.
243    ) -> Result<Arc<GoogleCloudStorage>> {
244        // Use a low retry count since the AIMD throttle layer handles
245        // throttle recovery with its own retry loop.
246        let retry_config = RetryConfig {
247            backoff: Default::default(),
248            max_retries: storage_options.client_max_retries(),
249            retry_timeout: Duration::from_secs(storage_options.client_retry_timeout()),
250        };
251
252        let client_options = gcs_client_options(storage_options)?;
253
254        let mut builder = GoogleCloudStorageBuilder::new()
255            .with_url(base_path.as_ref())
256            .with_retry(retry_config)
257            .with_client_options(client_options.object_requests.clone());
258        for (key, value) in storage_options.as_gcs_options() {
259            builder = builder.with_config(key, value);
260        }
261
262        if let Some(credentials) =
263            build_dynamic_credential_provider::<GcpCredential>(accessor).await?
264        {
265            builder = builder.with_credentials(credentials);
266        } else if let Some(storage_token) = storage_options.get("google_storage_token") {
267            let credential = GcpCredential {
268                bearer: storage_token.clone(),
269            };
270            let credential_provider = Arc::new(StaticCredentialProvider::new(credential)) as _;
271            builder = builder.with_credentials(credential_provider);
272        } else if let Some(credential_provider) = workload_identity_credential_provider(
273            storage_options,
274            &client_options.credential_requests,
275        )? {
276            // object_store cannot exchange external-account ADC files, while reqsign supports
277            // the workload identity format emitted by google-github-actions/auth.
278            builder = builder.with_credentials(credential_provider);
279        }
280
281        let store_prefix =
282            self.calculate_object_store_prefix(base_path, Some(&storage_options.0))?;
283        builder = builder.with_http_connector(cloud_http_connector(throttle_state, store_prefix));
284
285        Ok(Arc::new(builder.build()?))
286    }
287}
288
289#[async_trait::async_trait]
290impl ObjectStoreProvider for GcsStoreProvider {
291    async fn new_store(&self, base_path: Url, params: &ObjectStoreParams) -> Result<ObjectStore> {
292        let block_size = params.block_size.unwrap_or(DEFAULT_CLOUD_BLOCK_SIZE);
293        let mut storage_options =
294            StorageOptions::new(params.storage_options().cloned().unwrap_or_default());
295        storage_options.with_env_gcs();
296        let download_retry_count = storage_options.download_retry_count();
297
298        let use_opendal = storage_options
299            .0
300            .get("use_opendal")
301            .map(|v| str_is_truthy(v.as_str()))
302            .unwrap_or(false);
303
304        let accessor = params.get_accessor();
305
306        let throttle_config = AimdThrottleConfig::from_storage_options(params.storage_options())?;
307        let throttle_state = if throttle_config.is_disabled() {
308            None
309        } else {
310            Some(AimdThrottleState::new(throttle_config)?)
311        };
312
313        let (inner, paginated_lister) = if use_opendal {
314            // OpenDAL GCS intentionally uses static/environment-backed configuration only.
315            // Namespace-vended dynamic credentials are supported on the native object_store path.
316            // Listed in full: no paginated lister covers OpenDAL yet.
317            (
318                self.build_opendal_gcs_store(&base_path, &storage_options)
319                    .await?,
320                None,
321            )
322        } else {
323            let store = self
324                .build_google_cloud_store(
325                    &base_path,
326                    &storage_options,
327                    accessor,
328                    throttle_state.as_ref(),
329                )
330                .await?;
331            (
332                store.clone() as Arc<dyn OSObjectStore>,
333                Some(store as Arc<dyn PaginatedListStore>),
334            )
335        };
336        let (inner, paginated_lister) =
337            with_throttling(throttle_state, !use_opendal, inner, paginated_lister);
338
339        Ok(ObjectStore {
340            inner,
341            local_dir_operations: None,
342            scheme: String::from("gs"),
343            block_size,
344            max_iop_size: *DEFAULT_MAX_IOP_SIZE,
345            use_constant_size_upload_parts: false,
346            list_is_lexically_ordered: true,
347            io_parallelism: DEFAULT_CLOUD_IO_PARALLELISM,
348            download_retry_count,
349            io_tracker: Default::default(),
350            store_prefix: self
351                .calculate_object_store_prefix(&base_path, params.storage_options())?,
352            paginated_lister,
353        })
354    }
355}
356
357impl StorageOptions {
358    /// Add values from the environment to storage options
359    pub fn with_env_gcs(&mut self) {
360        for (os_key, os_value) in std::env::vars_os() {
361            if let (Some(key), Some(value)) = (os_key.to_str(), os_value.to_str()) {
362                let lowercase_key = key.to_ascii_lowercase();
363                let token_key = "google_storage_token";
364
365                if let Ok(config_key) = GoogleConfigKey::from_str(&lowercase_key) {
366                    if !self.0.contains_key(config_key.as_ref()) {
367                        self.0
368                            .insert(config_key.as_ref().to_string(), value.to_string());
369                    }
370                }
371                // Check for GOOGLE_STORAGE_TOKEN until GoogleConfigKey supports storage token
372                else if lowercase_key == token_key && !self.0.contains_key(token_key) {
373                    self.0.insert(token_key.to_string(), value.to_string());
374                }
375            }
376        }
377    }
378
379    /// Subset of options relevant for gcs storage
380    pub fn as_gcs_options(&self) -> HashMap<GoogleConfigKey, String> {
381        self.0
382            .iter()
383            .filter_map(|(key, value)| {
384                let gcs_key = GoogleConfigKey::from_str(&key.to_ascii_lowercase()).ok()?;
385                Some((gcs_key, value.clone()))
386            })
387            .collect()
388    }
389}
390
391#[cfg(test)]
392mod tests {
393    use super::*;
394    use std::{collections::HashMap, fs, sync::Arc};
395
396    use crate::object_store::test_utils::StaticMockStorageOptionsProvider;
397    use crate::object_store::{ObjectStoreParams, StorageOptionsAccessor};
398    use tempfile::TempDir;
399    use wiremock::{
400        Mock, MockServer, ResponseTemplate,
401        matchers::{method, path},
402    };
403
404    fn external_account_storage_options(
405        temp_dir: &TempDir,
406        token_url: String,
407    ) -> HashMap<String, String> {
408        let subject_token_path = temp_dir.path().join("oidc-token");
409        fs::write(&subject_token_path, "github-oidc-token").unwrap();
410        let application_credentials_path = temp_dir.path().join("credentials.json");
411        fs::write(
412            &application_credentials_path,
413            serde_json::to_vec(&serde_json::json!({
414                "type": "external_account",
415                "audience": "test-audience",
416                "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
417                "token_url": token_url,
418                "credential_source": {
419                    "file": subject_token_path.to_string_lossy(),
420                    "format": { "type": "text" }
421                }
422            }))
423            .unwrap(),
424        )
425        .unwrap();
426
427        HashMap::from([
428            (
429                "google_application_credentials".to_string(),
430                application_credentials_path.to_string_lossy().into_owned(),
431            ),
432            ("allow_http".to_string(), "true".to_string()),
433        ])
434    }
435
436    #[test]
437    fn test_gcs_store_path() {
438        let provider = GcsStoreProvider;
439
440        let url = Url::parse("gs://bucket/path/to/file").unwrap();
441        let path = provider.extract_path(&url).unwrap();
442        let expected_path = object_store::path::Path::from("path/to/file");
443        assert_eq!(path, expected_path);
444    }
445
446    #[tokio::test]
447    async fn test_use_opendal_flag() {
448        let provider = GcsStoreProvider;
449        let url = Url::parse("gs://test-bucket/path").unwrap();
450        let params_with_flag = ObjectStoreParams {
451            storage_options_accessor: Some(Arc::new(StorageOptionsAccessor::with_static_options(
452                HashMap::from([
453                    ("use_opendal".to_string(), "true".to_string()),
454                    (
455                        "service_account".to_string(),
456                        "test@example.iam.gserviceaccount.com".to_string(),
457                    ),
458                ]),
459            ))),
460            ..Default::default()
461        };
462
463        let store = provider
464            .new_store(url.clone(), &params_with_flag)
465            .await
466            .unwrap();
467        assert_eq!(store.scheme, "gs");
468    }
469
470    #[tokio::test]
471    async fn test_dynamic_gcp_credentials_provider() {
472        let accessor = Arc::new(StorageOptionsAccessor::with_provider(Arc::new(
473            StaticMockStorageOptionsProvider {
474                options: HashMap::from([(
475                    "google_storage_token".to_string(),
476                    "gcp-token".to_string(),
477                )]),
478            },
479        )));
480
481        let credentials = build_dynamic_credential_provider::<GcpCredential>(Some(accessor))
482            .await
483            .expect("dynamic gcp credentials should build")
484            .expect("expected credential provider")
485            .get_credential()
486            .await
487            .expect("expected gcp credential");
488
489        assert_eq!(credentials.bearer, "gcp-token");
490    }
491
492    #[tokio::test]
493    async fn test_external_account_application_credentials() {
494        let mock_server = MockServer::start().await;
495        Mock::given(method("POST"))
496            .and(path("/token"))
497            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
498                "access_token": "federated-token",
499                "expires_in": 3600
500            })))
501            .expect(1)
502            .mount(&mock_server)
503            .await;
504
505        let temp_dir = tempfile::tempdir().unwrap();
506        let mut storage_options =
507            external_account_storage_options(&temp_dir, format!("{}/token", mock_server.uri()));
508        storage_options.insert(
509            "headers.Authorization".to_string(),
510            "Bearer storage-secret".to_string(),
511        );
512        let params = ObjectStoreParams {
513            storage_options_accessor: Some(Arc::new(StorageOptionsAccessor::with_static_options(
514                storage_options.clone(),
515            ))),
516            ..Default::default()
517        };
518
519        let store = GcsStoreProvider
520            .new_store(Url::parse("gs://test-bucket/path").unwrap(), &params)
521            .await
522            .expect("external account credentials should build a GCS store");
523        assert_eq!(store.scheme, "gs");
524
525        let storage_options = StorageOptions::new(storage_options);
526        let client_options = gcs_client_options(&storage_options).unwrap();
527        let credential_provider = workload_identity_credential_provider(
528            &storage_options,
529            &client_options.credential_requests,
530        )
531        .expect("external account credential provider should build")
532        .expect("external account credentials should select the reqsign provider");
533        for _ in 0..2 {
534            let credential = credential_provider
535                .get_credential()
536                .await
537                .expect("workload identity token exchange should succeed");
538            assert_eq!(credential.bearer, "federated-token");
539        }
540        mock_server.verify().await;
541        let requests = mock_server.received_requests().await.unwrap();
542        assert!(!requests[0].headers.contains_key("authorization"));
543    }
544
545    #[tokio::test]
546    async fn test_external_account_respects_client_timeout() {
547        let mock_server = MockServer::start().await;
548        Mock::given(method("POST"))
549            .and(path("/token"))
550            .respond_with(
551                ResponseTemplate::new(200)
552                    .set_delay(Duration::from_secs(1))
553                    .set_body_json(serde_json::json!({
554                        "access_token": "federated-token",
555                        "expires_in": 3600
556                    })),
557            )
558            .expect(1)
559            .mount(&mock_server)
560            .await;
561
562        let temp_dir = tempfile::tempdir().unwrap();
563        let mut storage_options =
564            external_account_storage_options(&temp_dir, format!("{}/token", mock_server.uri()));
565        storage_options.insert("timeout".to_string(), "50ms".to_string());
566        let storage_options = StorageOptions::new(storage_options);
567        let client_options = gcs_client_options(&storage_options).unwrap();
568        let credential_provider = workload_identity_credential_provider(
569            &storage_options,
570            &client_options.credential_requests,
571        )
572        .expect("external account credential provider should build")
573        .expect("external account credentials should select the reqsign provider");
574
575        let credential_result = tokio::time::timeout(
576            Duration::from_millis(200),
577            credential_provider.get_credential(),
578        )
579        .await
580        .expect("configured client timeout should bound the credential exchange");
581        let error = credential_result.expect_err("the delayed token exchange should time out");
582        assert!(matches!(&error, object_store::Error::Generic { .. }));
583        assert!(
584            error
585                .to_string()
586                .contains("failed to send Google workload identity HTTP request"),
587            "unexpected error: {error}"
588        );
589        mock_server.verify().await;
590    }
591}