This is an automated email from the ASF dual-hosted git repository.

Xuanwo pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/opendal.git


The following commit(s) were added to refs/heads/main by this push:
     new 516644ec3f fix(services/gcs,gcs-grpc): reject invalid base64 
credential and use typed scope builders (#8901)
516644ec3f is described below

commit 516644ec3fbb257e920b3b22609a18e363081a28
Author: Xuanwo <[email protected]>
AuthorDate: Tue Nov 24 00:55:44 2026 +0800

    fix(services/gcs,gcs-grpc): reject invalid base64 credential and use typed 
scope builders (#8901)
---
 core/services/gcs-grpc/src/backend.rs | 320 +++++++++++++++++++++++++++++----
 core/services/gcs/src/backend.rs      | 325 ++++++++++++++++++++++++++++++----
 2 files changed, 579 insertions(+), 66 deletions(-)

diff --git a/core/services/gcs-grpc/src/backend.rs 
b/core/services/gcs-grpc/src/backend.rs
index 931e32c06f..fc0d031c36 100644
--- a/core/services/gcs-grpc/src/backend.rs
+++ b/core/services/gcs-grpc/src/backend.rs
@@ -19,12 +19,12 @@ use std::fmt::Debug;
 use std::sync::Arc;
 
 use log::debug;
-use reqsign_core::Env as _;
-use reqsign_core::{Context, OsEnv, ProvideCredential, ProvideCredentialChain, 
Signer, StaticEnv};
+use reqsign_core::{Context, OsEnv, ProvideCredential, ProvideCredentialChain, 
Signer};
 use reqsign_file_read_tokio::TokioFileRead;
 use reqsign_google::{
-    Credential, DefaultCredentialProvider, FileCredentialProvider, 
RequestSigner,
-    StaticCredentialProvider, TokenCredentialProvider, 
VmMetadataCredentialProvider,
+    Credential, DefaultCredentialProvider, EnvCredentialProvider, 
FileCredentialProvider,
+    RequestSigner, StaticCredentialProvider, TokenCredentialProvider, 
VmMetadataCredentialProvider,
+    WellKnownCredentialProvider,
 };
 use tonic::transport::{ClientTlsConfig, Endpoint};
 
@@ -156,10 +156,8 @@ impl GcsGrpcBuilder {
     }
 }
 
-impl Builder for GcsGrpcBuilder {
-    type Config = GcsGrpcConfig;
-
-    fn build(self) -> Result<impl Service> {
+impl GcsGrpcBuilder {
+    fn build_backend(self) -> Result<GcsGrpcBackend> {
         debug!("backend build started: {self:?}");
         let root = normalize_root(&self.config.root.unwrap_or_default());
         if self.config.bucket.is_empty() {
@@ -182,40 +180,37 @@ impl Builder for GcsGrpcBuilder {
             .clone()
             .unwrap_or_else(|| DEFAULT_GCS_SCOPE.to_string());
 
-        let os_env = OsEnv;
-        let mut envs = os_env.vars();
-        envs.insert("GOOGLE_SCOPE".to_string(), scope.clone());
-        let ctx = Context::new()
-            .with_file_read(TokioFileRead)
-            .with_env(StaticEnv {
-                home_dir: os_env.home_dir(),
-                envs,
-            });
+        let ctx = Context::new().with_file_read(TokioFileRead).with_env(OsEnv);
 
         let mut default_credential = DefaultCredentialProvider::builder();
         if self.config.disable_config_load {
             default_credential = default_credential.no_env().no_well_known();
+        } else {
+            default_credential = default_credential
+                .env(EnvCredentialProvider::new().with_scope(&scope))
+                
.well_known(WellKnownCredentialProvider::new().with_scope(&scope));
         }
-        if self.config.disable_vm_metadata || 
self.config.service_account.is_some() {
+        if self.config.disable_vm_metadata {
             default_credential = default_credential.no_vm_metadata();
+        } else {
+            let mut vm_metadata = 
VmMetadataCredentialProvider::new().with_scope(&scope);
+            if let Some(service_account) = 
self.config.service_account.as_deref() {
+                vm_metadata = 
vm_metadata.with_service_account(service_account);
+            }
+            default_credential = default_credential.vm_metadata(vm_metadata);
         }
         let mut credential_chain = 
ProvideCredentialChain::new().push(default_credential.build());
-        if !self.config.disable_vm_metadata
-            && let Some(service_account) = 
self.config.service_account.as_deref()
-        {
-            credential_chain = credential_chain.push(
-                VmMetadataCredentialProvider::new()
-                    .with_scope(&scope)
-                    .with_service_account(service_account),
-            );
-        }
         if let Some(path) = self.config.credential_path.as_deref() {
             credential_chain =
                 
credential_chain.push_front(FileCredentialProvider::new(path).with_scope(&scope));
         }
-        if let Some(content) = self.config.credential.as_deref()
-            && let Ok(provider) = 
StaticCredentialProvider::from_base64(content)
-        {
+        if let Some(content) = self.config.credential.as_deref() {
+            let provider = 
StaticCredentialProvider::from_base64(content).map_err(|err| {
+                Error::new(ErrorKind::ConfigInvalid, "invalid base64 
credential")
+                    .with_operation("Builder::build")
+                    .with_context("service", GCS_GRPC_SCHEME)
+                    .set_source(err)
+            })?;
             credential_chain = 
credential_chain.push_front(provider.with_scope(&scope));
         }
         if let Some(token) = self.config.token.as_deref() {
@@ -275,6 +270,14 @@ impl Builder for GcsGrpcBuilder {
     }
 }
 
+impl Builder for GcsGrpcBuilder {
+    type Config = GcsGrpcConfig;
+
+    fn build(self) -> Result<impl Service> {
+        self.build_backend()
+    }
+}
+
 fn build_endpoint(endpoint: &str) -> Result<Endpoint> {
     let mut endpoint_builder = 
Endpoint::from_shared(endpoint.to_string()).map_err(|err| {
         Error::new(ErrorKind::ConfigInvalid, "invalid GCS gRPC 
endpoint").set_source(err)
@@ -438,8 +441,73 @@ impl Service for GcsGrpcBackend {
 }
 #[cfg(test)]
 mod tests {
+    use std::collections::HashMap;
+    use std::sync::Mutex;
+
+    use bytes::Bytes;
+    use futures::executor::block_on;
+    use http::header::AUTHORIZATION;
+    use reqsign_core::{FileRead, HttpSend, StaticEnv};
+
     use super::*;
 
+    const TEST_SCOPE: &str = 
"https://www.googleapis.com/auth/devstorage.read_only";;
+    const IMPERSONATED_ADC_JSON: &[u8] = br#"{
+        "type": "impersonated_service_account",
+        "service_account_impersonation_url": 
"https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/target%40example.com:generateAccessToken";,
+        "source_credentials": {
+            "client_id": "client-id",
+            "client_secret": "client-secret",
+            "refresh_token": "refresh-token"
+        }
+    }"#;
+
+    #[derive(Clone, Debug, Default)]
+    struct MockFileRead {
+        files: HashMap<String, Vec<u8>>,
+        paths: Arc<Mutex<Vec<String>>>,
+    }
+
+    impl FileRead for MockFileRead {
+        async fn file_read(&self, path: &str) -> reqsign_core::Result<Vec<u8>> 
{
+            self.paths.lock().unwrap().push(path.to_string());
+            self.files.get(path).cloned().ok_or_else(|| {
+                reqsign_core::Error::config_invalid(format!("file not found: 
{path}"))
+            })
+        }
+    }
+
+    #[derive(Clone, Debug, Default)]
+    struct MockHttpSend {
+        requests: Arc<Mutex<Vec<(String, String)>>>,
+    }
+
+    impl HttpSend for MockHttpSend {
+        async fn http_send(
+            &self,
+            req: http::Request<Bytes>,
+        ) -> reqsign_core::Result<http::Response<Bytes>> {
+            let uri = req.uri().to_string();
+            let body = String::from_utf8_lossy(req.body()).into_owned();
+            self.requests.lock().unwrap().push((uri.clone(), body));
+
+            let response_body = if uri.contains("/computeMetadata/v1/") {
+                r#"{"access_token":"vm-token","expires_in":3600}"#
+            } else if uri == "https://oauth2.googleapis.com/token"; {
+                r#"{"access_token":"source-token","expires_in":3600}"#
+            } else if uri.contains(":generateAccessToken") {
+                
r#"{"accessToken":"impersonated-token","expireTime":"2100-01-01T00:00:00Z"}"#
+            } else {
+                panic!("unexpected request uri: {uri}");
+            };
+
+            Ok(http::Response::builder()
+                .status(http::StatusCode::OK)
+                .body(Bytes::from_static(response_body.as_bytes()))
+                .unwrap())
+        }
+    }
+
     #[test]
     fn builder_does_not_require_a_tokio_runtime() {
         GcsGrpcBuilder::default()
@@ -454,4 +522,196 @@ mod tests {
         assert!(build_endpoint("HTTPS://storage.googleapis.com").is_ok());
         assert!(build_endpoint("ftp://storage.googleapis.com";).is_err());
     }
+
+    #[test]
+    fn invalid_base64_credential_returns_config_invalid() {
+        for invalid in ["not-valid-base64!!!", "//4="] {
+            let err = GcsGrpcBuilder::default()
+                .bucket("example-bucket")
+                .credential(invalid)
+                .disable_config_load()
+                .disable_vm_metadata()
+                .build()
+                .expect_err("invalid base64 credential must fail build");
+            assert_eq!(err.kind(), ErrorKind::ConfigInvalid);
+        }
+
+        assert!(
+            GcsGrpcBuilder::default()
+                .bucket("example-bucket")
+                .credential("")
+                .disable_config_load()
+                .disable_vm_metadata()
+                .build()
+                .is_ok()
+        );
+    }
+
+    #[test]
+    fn vm_metadata_wires_scope_and_service_account_without_static_env() {
+        let backend = GcsGrpcBuilder::default()
+            .bucket("example-bucket")
+            .scope(TEST_SCOPE)
+            .service_account("[email protected]")
+            .disable_config_load()
+            .build_backend()
+            .unwrap();
+
+        assert_eq!(
+            backend.core.sign_ctx.env_var("GOOGLE_SCOPE"),
+            std::env::var("GOOGLE_SCOPE").ok()
+        );
+
+        let http = MockHttpSend::default();
+        let ctx = Context::new()
+            .with_env(StaticEnv::default())
+            .with_http_send(http.clone());
+        let (mut parts, ()) = 
http::Request::get("https://storage.googleapis.com";)
+            .body(())
+            .unwrap()
+            .into_parts();
+
+        block_on(
+            backend
+                .core
+                .signer
+                .clone()
+                .with_context(ctx)
+                .sign(&mut parts, None),
+        )
+        .unwrap();
+
+        assert_eq!(
+            parts
+                .headers
+                .get(AUTHORIZATION)
+                .and_then(|v| v.to_str().ok()),
+            Some("Bearer vm-token")
+        );
+        let requests = http.requests.lock().unwrap();
+        assert_eq!(requests.len(), 1);
+        assert_eq!(
+            requests[0].0,
+            format!(
+                
"http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/[email protected]/token?scopes={TEST_SCOPE}";
+            )
+        );
+    }
+
+    #[test]
+    fn env_and_well_known_providers_wire_scope_directly() {
+        for (env_key, env_value, expected_path) in [
+            (
+                "GOOGLE_APPLICATION_CREDENTIALS",
+                "/adc/env.json",
+                "/adc/env.json",
+            ),
+            (
+                "HOME",
+                "/adc-home",
+                
"/adc-home/.config/gcloud/application_default_credentials.json",
+            ),
+        ] {
+            let backend = GcsGrpcBuilder::default()
+                .bucket("example-bucket")
+                .scope(TEST_SCOPE)
+                .disable_vm_metadata()
+                .build_backend()
+                .unwrap();
+
+            let file_read = MockFileRead {
+                files: HashMap::from([(expected_path.to_string(), 
IMPERSONATED_ADC_JSON.to_vec())]),
+                paths: Arc::default(),
+            };
+            let http = MockHttpSend::default();
+            let ctx = Context::new()
+                .with_env(StaticEnv {
+                    home_dir: None,
+                    envs: HashMap::from([(env_key.to_string(), 
env_value.to_string())]),
+                })
+                .with_file_read(file_read.clone())
+                .with_http_send(http.clone());
+            let (mut parts, ()) = 
http::Request::get("https://storage.googleapis.com";)
+                .body(())
+                .unwrap()
+                .into_parts();
+
+            block_on(
+                backend
+                    .core
+                    .signer
+                    .clone()
+                    .with_context(ctx)
+                    .sign(&mut parts, None),
+            )
+            .unwrap();
+
+            assert_eq!(
+                parts
+                    .headers
+                    .get(AUTHORIZATION)
+                    .and_then(|v| v.to_str().ok()),
+                Some("Bearer impersonated-token")
+            );
+            assert_eq!(file_read.paths.lock().unwrap().as_slice(), 
&[expected_path]);
+            let requests = http.requests.lock().unwrap();
+            assert_eq!(requests.len(), 2);
+            let body: serde_json::Value = 
serde_json::from_str(&requests[1].1).unwrap();
+            assert_eq!(body["scope"], serde_json::json!([TEST_SCOPE]));
+        }
+    }
+
+    #[test]
+    fn disable_config_load_and_disable_vm_metadata_skip_default_providers() {
+        let backend = GcsGrpcBuilder::default()
+            .bucket("example-bucket")
+            .scope(TEST_SCOPE)
+            .service_account("[email protected]")
+            .disable_config_load()
+            .disable_vm_metadata()
+            .build_backend()
+            .unwrap();
+
+        let file_read = MockFileRead {
+            files: HashMap::from([
+                ("/adc/env.json".to_string(), IMPERSONATED_ADC_JSON.to_vec()),
+                (
+                    
"/adc-home/.config/gcloud/application_default_credentials.json".to_string(),
+                    IMPERSONATED_ADC_JSON.to_vec(),
+                ),
+            ]),
+            paths: Arc::default(),
+        };
+        let http = MockHttpSend::default();
+        let ctx = Context::new()
+            .with_env(StaticEnv {
+                home_dir: None,
+                envs: HashMap::from([
+                    (
+                        "GOOGLE_APPLICATION_CREDENTIALS".to_string(),
+                        "/adc/env.json".to_string(),
+                    ),
+                    ("HOME".to_string(), "/adc-home".to_string()),
+                ]),
+            })
+            .with_file_read(file_read.clone())
+            .with_http_send(http.clone());
+        let (mut parts, ()) = 
http::Request::get("https://storage.googleapis.com";)
+            .body(())
+            .unwrap()
+            .into_parts();
+
+        let err = block_on(
+            backend
+                .core
+                .signer
+                .clone()
+                .with_context(ctx)
+                .sign(&mut parts, None),
+        )
+        .unwrap_err();
+        assert_eq!(err.kind(), reqsign_core::ErrorKind::CredentialInvalid);
+        assert!(file_read.paths.lock().unwrap().is_empty());
+        assert!(http.requests.lock().unwrap().is_empty());
+    }
 }
diff --git a/core/services/gcs/src/backend.rs b/core/services/gcs/src/backend.rs
index 59edad7495..cad6b434af 100644
--- a/core/services/gcs/src/backend.rs
+++ b/core/services/gcs/src/backend.rs
@@ -20,20 +20,20 @@ use std::sync::Arc;
 
 use log::debug;
 use reqsign_core::Context;
-use reqsign_core::Env as _;
 use reqsign_core::OsEnv;
 use reqsign_core::ProvideCredential;
 use reqsign_core::ProvideCredentialChain;
 use reqsign_core::Signer;
-use reqsign_core::StaticEnv;
 use reqsign_file_read_tokio::TokioFileRead;
 use reqsign_google::Credential;
 use reqsign_google::DefaultCredentialProvider;
+use reqsign_google::EnvCredentialProvider;
 use reqsign_google::FileCredentialProvider;
 use reqsign_google::RequestSigner;
 use reqsign_google::StaticCredentialProvider;
 use reqsign_google::TokenCredentialProvider;
 use reqsign_google::VmMetadataCredentialProvider;
+use reqsign_google::WellKnownCredentialProvider;
 
 use super::GCS_SCHEME;
 use super::composer::GcsComposer;
@@ -248,10 +248,8 @@ impl GcsBuilder {
     }
 }
 
-impl Builder for GcsBuilder {
-    type Config = GcsConfig;
-
-    fn build(self) -> Result<impl Service> {
+impl GcsBuilder {
+    fn build_backend(self) -> Result<GcsBackend> {
         debug!("backend build started: {self:?}");
 
         #[allow(deprecated)]
@@ -285,51 +283,41 @@ impl Builder for GcsBuilder {
             .clone()
             .unwrap_or_else(|| DEFAULT_GCS_SCOPE.to_string());
 
-        let os_env = OsEnv;
-        let mut envs = os_env.vars();
-        envs.insert("GOOGLE_SCOPE".to_string(), scope.clone());
-
-        let ctx = Context::new()
-            .with_file_read(TokioFileRead)
-            .with_env(StaticEnv {
-                home_dir: os_env.home_dir(),
-                envs,
-            });
+        let ctx = Context::new().with_file_read(TokioFileRead).with_env(OsEnv);
 
         let mut default_credential = DefaultCredentialProvider::builder();
-        #[cfg(target_arch = "wasm32")]
-        {
-            default_credential = default_credential.no_env().no_well_known();
-        }
-
-        if self.config.disable_config_load {
+        if self.config.disable_config_load || cfg!(target_arch = "wasm32") {
             default_credential = default_credential.no_env().no_well_known();
+        } else {
+            default_credential = default_credential
+                .env(EnvCredentialProvider::new().with_scope(&scope))
+                
.well_known(WellKnownCredentialProvider::new().with_scope(&scope));
         }
 
-        if self.config.disable_vm_metadata || 
self.config.service_account.is_some() {
+        if self.config.disable_vm_metadata {
             default_credential = default_credential.no_vm_metadata();
+        } else {
+            let mut vm_metadata = 
VmMetadataCredentialProvider::new().with_scope(&scope);
+            if let Some(service_account) = 
self.config.service_account.as_deref() {
+                vm_metadata = 
vm_metadata.with_service_account(service_account);
+            }
+            default_credential = default_credential.vm_metadata(vm_metadata);
         }
 
         let mut credential_chain = 
ProvideCredentialChain::new().push(default_credential.build());
 
-        if !self.config.disable_vm_metadata
-            && let Some(service_account) = 
self.config.service_account.as_deref()
-        {
-            credential_chain = credential_chain.push(
-                VmMetadataCredentialProvider::new()
-                    .with_scope(&scope)
-                    .with_service_account(service_account),
-            );
-        }
-
         if let Some(path) = self.config.credential_path.as_deref() {
             credential_chain =
                 
credential_chain.push_front(FileCredentialProvider::new(path).with_scope(&scope));
         }
 
-        if let Some(content) = self.config.credential.as_deref()
-            && let Ok(provider) = 
StaticCredentialProvider::from_base64(content)
-        {
+        if let Some(content) = self.config.credential.as_deref() {
+            let provider = 
StaticCredentialProvider::from_base64(content).map_err(|err| {
+                Error::new(ErrorKind::ConfigInvalid, "invalid base64 
credential")
+                    .with_operation("Builder::build")
+                    .with_context("service", GCS_SCHEME)
+                    .set_source(err)
+            })?;
             credential_chain = 
credential_chain.push_front(provider.with_scope(&scope));
         }
 
@@ -453,6 +441,14 @@ impl Builder for GcsBuilder {
     }
 }
 
+impl Builder for GcsBuilder {
+    type Config = GcsConfig;
+
+    fn build(self) -> Result<impl Service> {
+        self.build_backend()
+    }
+}
+
 /// GCS storage backend
 #[derive(Clone, Debug)]
 pub struct GcsBackend {
@@ -640,8 +636,72 @@ impl Service for GcsBackend {
 
 #[cfg(test)]
 mod tests {
+    use std::collections::HashMap;
+    use std::sync::Mutex;
+
+    use bytes::Bytes;
+    use http::header::AUTHORIZATION;
+    use reqsign_core::{FileRead, HttpSend, StaticEnv};
+
     use super::*;
 
+    const TEST_SCOPE: &str = 
"https://www.googleapis.com/auth/devstorage.read_only";;
+    const IMPERSONATED_ADC_JSON: &[u8] = br#"{
+        "type": "impersonated_service_account",
+        "service_account_impersonation_url": 
"https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/target%40example.com:generateAccessToken";,
+        "source_credentials": {
+            "client_id": "client-id",
+            "client_secret": "client-secret",
+            "refresh_token": "refresh-token"
+        }
+    }"#;
+
+    #[derive(Clone, Debug, Default)]
+    struct MockFileRead {
+        files: HashMap<String, Vec<u8>>,
+        paths: Arc<Mutex<Vec<String>>>,
+    }
+
+    impl FileRead for MockFileRead {
+        async fn file_read(&self, path: &str) -> reqsign_core::Result<Vec<u8>> 
{
+            self.paths.lock().unwrap().push(path.to_string());
+            self.files.get(path).cloned().ok_or_else(|| {
+                reqsign_core::Error::config_invalid(format!("file not found: 
{path}"))
+            })
+        }
+    }
+
+    #[derive(Clone, Debug, Default)]
+    struct MockHttpSend {
+        requests: Arc<Mutex<Vec<(String, String)>>>,
+    }
+
+    impl HttpSend for MockHttpSend {
+        async fn http_send(
+            &self,
+            req: http::Request<Bytes>,
+        ) -> reqsign_core::Result<http::Response<Bytes>> {
+            let uri = req.uri().to_string();
+            let body = String::from_utf8_lossy(req.body()).into_owned();
+            self.requests.lock().unwrap().push((uri.clone(), body));
+
+            let response_body = if uri.contains("/computeMetadata/v1/") {
+                r#"{"access_token":"vm-token","expires_in":3600}"#
+            } else if uri == "https://oauth2.googleapis.com/token"; {
+                r#"{"access_token":"source-token","expires_in":3600}"#
+            } else if uri.contains(":generateAccessToken") {
+                
r#"{"accessToken":"impersonated-token","expireTime":"2100-01-01T00:00:00Z"}"#
+            } else {
+                panic!("unexpected request uri: {uri}");
+            };
+
+            Ok(http::Response::builder()
+                .status(http::StatusCode::OK)
+                .body(Bytes::from_static(response_body.as_bytes()))
+                .unwrap())
+        }
+    }
+
     #[test]
     fn test_capability_supports_versioned_operations() {
         let backend = GcsBuilder::default()
@@ -658,4 +718,197 @@ mod tests {
         assert!(capability.copy_with_source_version);
         assert!(capability.delete_with_version);
     }
+
+    #[test]
+    fn test_invalid_base64_credential_returns_config_invalid() {
+        for invalid in ["not-valid-base64!!!", "//4="] {
+            let err = GcsBuilder::default()
+                .bucket("example-bucket")
+                .credential(invalid)
+                .disable_config_load()
+                .disable_vm_metadata()
+                .build()
+                .expect_err("invalid base64 credential must fail build");
+            assert_eq!(err.kind(), ErrorKind::ConfigInvalid);
+        }
+
+        assert!(
+            GcsBuilder::default()
+                .bucket("example-bucket")
+                .credential("")
+                .disable_config_load()
+                .disable_vm_metadata()
+                .build()
+                .is_ok()
+        );
+    }
+
+    #[tokio::test]
+    async fn 
test_vm_metadata_wires_scope_and_service_account_without_static_env() {
+        let backend = GcsBuilder::default()
+            .bucket("example-bucket")
+            .scope(TEST_SCOPE)
+            .service_account("[email protected]")
+            .disable_config_load()
+            .build_backend()
+            .unwrap();
+
+        assert_eq!(
+            backend.core.sign_ctx.env_var("GOOGLE_SCOPE"),
+            std::env::var("GOOGLE_SCOPE").ok()
+        );
+
+        let http = MockHttpSend::default();
+        let ctx = Context::new()
+            .with_env(StaticEnv::default())
+            .with_http_send(http.clone());
+        let (mut parts, ()) =
+            
http::Request::get("https://storage.googleapis.com/example-bucket/obj";)
+                .body(())
+                .unwrap()
+                .into_parts();
+
+        backend
+            .core
+            .signer
+            .clone()
+            .with_context(ctx)
+            .sign(&mut parts, None)
+            .await
+            .unwrap();
+
+        assert_eq!(
+            parts
+                .headers
+                .get(AUTHORIZATION)
+                .and_then(|v| v.to_str().ok()),
+            Some("Bearer vm-token")
+        );
+        let requests = http.requests.lock().unwrap();
+        assert_eq!(requests.len(), 1);
+        assert_eq!(
+            requests[0].0,
+            format!(
+                
"http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/[email protected]/token?scopes={TEST_SCOPE}";
+            )
+        );
+    }
+
+    #[cfg(not(target_arch = "wasm32"))]
+    #[tokio::test]
+    async fn test_env_and_well_known_providers_wire_scope_directly() {
+        for (env_key, env_value, expected_path) in [
+            (
+                "GOOGLE_APPLICATION_CREDENTIALS",
+                "/adc/env.json",
+                "/adc/env.json",
+            ),
+            (
+                "HOME",
+                "/adc-home",
+                
"/adc-home/.config/gcloud/application_default_credentials.json",
+            ),
+        ] {
+            let backend = GcsBuilder::default()
+                .bucket("example-bucket")
+                .scope(TEST_SCOPE)
+                .disable_vm_metadata()
+                .build_backend()
+                .unwrap();
+
+            let file_read = MockFileRead {
+                files: HashMap::from([(expected_path.to_string(), 
IMPERSONATED_ADC_JSON.to_vec())]),
+                paths: Arc::default(),
+            };
+            let http = MockHttpSend::default();
+            let ctx = Context::new()
+                .with_env(StaticEnv {
+                    home_dir: None,
+                    envs: HashMap::from([(env_key.to_string(), 
env_value.to_string())]),
+                })
+                .with_file_read(file_read.clone())
+                .with_http_send(http.clone());
+            let (mut parts, ()) =
+                
http::Request::get("https://storage.googleapis.com/example-bucket/obj";)
+                    .body(())
+                    .unwrap()
+                    .into_parts();
+
+            backend
+                .core
+                .signer
+                .clone()
+                .with_context(ctx)
+                .sign(&mut parts, None)
+                .await
+                .unwrap();
+
+            assert_eq!(
+                parts
+                    .headers
+                    .get(AUTHORIZATION)
+                    .and_then(|v| v.to_str().ok()),
+                Some("Bearer impersonated-token")
+            );
+            assert_eq!(file_read.paths.lock().unwrap().as_slice(), 
&[expected_path]);
+            let requests = http.requests.lock().unwrap();
+            assert_eq!(requests.len(), 2);
+            let body: serde_json::Value = 
serde_json::from_str(&requests[1].1).unwrap();
+            assert_eq!(body["scope"], serde_json::json!([TEST_SCOPE]));
+        }
+    }
+
+    #[tokio::test]
+    async fn 
test_disable_config_load_and_disable_vm_metadata_skip_default_providers() {
+        let backend = GcsBuilder::default()
+            .bucket("example-bucket")
+            .scope(TEST_SCOPE)
+            .service_account("[email protected]")
+            .disable_config_load()
+            .disable_vm_metadata()
+            .build_backend()
+            .unwrap();
+
+        let file_read = MockFileRead {
+            files: HashMap::from([
+                ("/adc/env.json".to_string(), IMPERSONATED_ADC_JSON.to_vec()),
+                (
+                    
"/adc-home/.config/gcloud/application_default_credentials.json".to_string(),
+                    IMPERSONATED_ADC_JSON.to_vec(),
+                ),
+            ]),
+            paths: Arc::default(),
+        };
+        let http = MockHttpSend::default();
+        let ctx = Context::new()
+            .with_env(StaticEnv {
+                home_dir: None,
+                envs: HashMap::from([
+                    (
+                        "GOOGLE_APPLICATION_CREDENTIALS".to_string(),
+                        "/adc/env.json".to_string(),
+                    ),
+                    ("HOME".to_string(), "/adc-home".to_string()),
+                ]),
+            })
+            .with_file_read(file_read.clone())
+            .with_http_send(http.clone());
+        let (mut parts, ()) =
+            
http::Request::get("https://storage.googleapis.com/example-bucket/obj";)
+                .body(())
+                .unwrap()
+                .into_parts();
+
+        let err = backend
+            .core
+            .signer
+            .clone()
+            .with_context(ctx)
+            .sign(&mut parts, None)
+            .await
+            .unwrap_err();
+        assert_eq!(err.kind(), reqsign_core::ErrorKind::CredentialInvalid);
+        assert!(file_read.paths.lock().unwrap().is_empty());
+        assert!(http.requests.lock().unwrap().is_empty());
+    }
 }

Reply via email to