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 30155fb750 fix(services/tos): wire disable_config_load and strip Host 
after signing (#8900)
30155fb750 is described below

commit 30155fb75099a5418e691a03127c366aa666dcec
Author: Xuanwo <[email protected]>
AuthorDate: Tue Nov 24 02:20:58 2026 +0800

    fix(services/tos): wire disable_config_load and strip Host after signing 
(#8900)
    
    TosConfig::disable_config_load was exposed but never read: TosBuilder had
    no setter and build() always pushed EnvCredentialProvider into the chain.
    Add TosBuilder::disable_config_load() and build the credential chain from
    DefaultCredentialProvider, removing the env slot when config load is
    disabled. Explicit access_key_id/secret_access_key/security_token keep
    working because the static provider is still pushed to the front.
    
    TosCore::send signed the request but forwarded the Host header, unlike
    sign_query and fetch. Remove Host after signing so the HTTP client sets
    the authority for the negotiated protocol.
    
    Add unit tests that resolve credentials against reqsign_core::StaticEnv
    and record request headers through a mock HttpTransport. Correct the
    disable_config_load docs to name the environment variables that reqsign
    actually reads.
---
 .../OpenDAL/ServiceConfig/TosServiceConfig.cs      |   2 +-
 .../java/org/apache/opendal/ServiceConfig.java     |   2 +-
 bindings/python/python/opendal/config.py           |   2 +-
 core/services/tos/src/backend.rs                   | 127 ++++++++++++++++++++-
 core/services/tos/src/config.rs                    |   3 +-
 core/services/tos/src/core.rs                      |  72 ++++++++++++
 website/data/services.json                         |  12 +-
 7 files changed, 207 insertions(+), 13 deletions(-)

diff --git a/bindings/dotnet/OpenDAL/ServiceConfig/TosServiceConfig.cs 
b/bindings/dotnet/OpenDAL/ServiceConfig/TosServiceConfig.cs
index affdc96f12..70109bb76e 100644
--- a/bindings/dotnet/OpenDAL/ServiceConfig/TosServiceConfig.cs
+++ b/bindings/dotnet/OpenDAL/ServiceConfig/TosServiceConfig.cs
@@ -37,7 +37,7 @@ namespace OpenDAL.ServiceConfig
         /// </summary>
         public string? Bucket { get; init; }
         /// <summary>
-        /// Disable config load so that opendal will not load config from 
environment. For examples: - envs like `TOS_ACCESS_KEY_ID`
+        /// Disable config load so that opendal will not load config from 
environment. For examples: - envs like `VOLCENGINE_ACCESS_KEY_ID`
         /// </summary>
         public bool? DisableConfigLoad { get; init; }
         /// <summary>
diff --git a/bindings/java/src/main/java/org/apache/opendal/ServiceConfig.java 
b/bindings/java/src/main/java/org/apache/opendal/ServiceConfig.java
index 82d1fe0b5f..f58e80ad86 100644
--- a/bindings/java/src/main/java/org/apache/opendal/ServiceConfig.java
+++ b/bindings/java/src/main/java/org/apache/opendal/ServiceConfig.java
@@ -3913,7 +3913,7 @@ public interface ServiceConfig {
          * environment.</p>
          * <p>For examples:</p>
          * <ul>
-         * <li>envs like <code>TOS_ACCESS_KEY_ID</code></li>
+         * <li>envs like <code>VOLCENGINE_ACCESS_KEY_ID</code></li>
          * </ul>
          */
         public final Boolean disableConfigLoad;
diff --git a/bindings/python/python/opendal/config.py 
b/bindings/python/python/opendal/config.py
index 6b3da3f37a..bfb7fbe970 100644
--- a/bindings/python/python/opendal/config.py
+++ b/bindings/python/python/opendal/config.py
@@ -953,7 +953,7 @@ class TosConfig(TypedDict):
     bucket: Required[str]
     """bucket name of this backend.  required."""
     disable_config_load: NotRequired[bool]
-    """Disable config load so that opendal will not load config from 
environment.  For examples: - envs like `TOS_ACCESS_KEY_ID`"""
+    """Disable config load so that opendal will not load config from 
environment.  For examples:  - envs like `VOLCENGINE_ACCESS_KEY_ID`"""
     endpoint: NotRequired[str]
     """endpoint of this backend.  Endpoint must be full uri, e.g. - TOS: 
`https://tos-cn-beijing.volces.com` - TOS with region: 
`https://tos-{region}.volces.com`  If user inputs endpoint without scheme like 
"tos-cn-beijing.volces.com", we will prepend "https://"; before it."""
     region: NotRequired[str]
diff --git a/core/services/tos/src/backend.rs b/core/services/tos/src/backend.rs
index 3ef547b1c8..f20f00f61b 100644
--- a/core/services/tos/src/backend.rs
+++ b/core/services/tos/src/backend.rs
@@ -34,9 +34,9 @@ use http::StatusCode;
 use opendal_core::OperationContext;
 use opendal_core::raw::*;
 use opendal_core::{Buffer, Builder, Capability, Error, ErrorKind, Result};
-use reqsign_core::{Context, OsEnv, ProvideCredentialChain, Signer};
+use reqsign_core::{Context, OsEnv, Signer};
 use reqsign_file_read_tokio::TokioFileRead;
-use reqsign_volcengine_tos::{EnvCredentialProvider, RequestSigner, 
StaticCredentialProvider};
+use reqsign_volcengine_tos::{DefaultCredentialProvider, RequestSigner, 
StaticCredentialProvider};
 
 const TOS_SCHEME: &str = "tos";
 
@@ -126,6 +126,17 @@ impl TosBuilder {
         self
     }
 
+    /// Disable config load so that opendal will not load config from
+    /// environment.
+    ///
+    /// For examples:
+    ///
+    /// - envs like `VOLCENGINE_ACCESS_KEY_ID`
+    pub fn disable_config_load(mut self) -> Self {
+        self.config.disable_config_load = true;
+        self
+    }
+
     /// Skip signature will skip loading credentials and signing requests.
     pub fn skip_signature(mut self) -> Self {
         self.config.skip_signature = true;
@@ -153,7 +164,11 @@ impl Builder for TosBuilder {
 
         let ctx = Context::new().with_file_read(TokioFileRead).with_env(OsEnv);
 
-        let mut provider = 
ProvideCredentialChain::new().push(EnvCredentialProvider::new());
+        let mut provider = DefaultCredentialProvider::builder();
+        if config.disable_config_load {
+            provider = provider.no_env();
+        }
+        let mut provider = provider.build();
 
         if let (Some(ak), Some(sk)) = (&config.access_key_id, 
&config.secret_access_key) {
             let static_provider = if let Some(token) = 
config.security_token.as_deref() {
@@ -450,3 +465,109 @@ impl Service for TosBackend {
         )))
     }
 }
+
+#[cfg(test)]
+mod tests {
+    use std::collections::HashMap;
+    use std::future::Future;
+    use std::task::Context as TaskContext;
+    use std::task::Poll;
+    use std::task::Waker;
+
+    use reqsign_core::StaticEnv;
+
+    use super::*;
+
+    /// Poll a future once; these futures resolve without an external runtime.
+    fn poll_once<F: Future>(future: F) -> F::Output {
+        let mut future = std::pin::pin!(future);
+        let mut cx = TaskContext::from_waker(Waker::noop());
+        match future.as_mut().poll(&mut cx) {
+            Poll::Ready(output) => output,
+            Poll::Pending => panic!("future requires an external async 
runtime"),
+        }
+    }
+
+    fn build_core(builder: TosBuilder) -> Arc<TosCore> {
+        let backend = builder.build().expect("build must succeed");
+        let backend = (&backend as &dyn std::any::Any)
+            .downcast_ref::<TosBackend>()
+            .expect("build must return TosBackend");
+        backend.core.clone()
+    }
+
+    /// Sign a request with a static environment so tests never read the 
process env.
+    fn sign_with_env(
+        core: &TosCore,
+        envs: HashMap<String, String>,
+    ) -> reqsign_core::Result<http::request::Parts> {
+        let signer = core
+            .signer
+            .clone()
+            .with_context(Context::new().with_env(StaticEnv {
+                home_dir: None,
+                envs,
+            }));
+
+        let req = core
+            .tos_put_object_request("test", None, &OpWrite::default(), 
Buffer::new())
+            .expect("request must be valid");
+        let (mut parts, _) = req.into_parts();
+        poll_once(signer.sign(&mut parts, None))?;
+        Ok(parts)
+    }
+
+    fn env_credentials() -> HashMap<String, String> {
+        HashMap::from([
+            ("VOLCENGINE_ACCESS_KEY_ID".to_string(), "env-ak".to_string()),
+            (
+                "VOLCENGINE_SECRET_ACCESS_KEY".to_string(),
+                "env-sk".to_string(),
+            ),
+        ])
+    }
+
+    fn authorization(parts: &http::request::Parts) -> &str {
+        parts.headers[http::header::AUTHORIZATION]
+            .to_str()
+            .expect("authorization must be valid header value")
+    }
+
+    #[test]
+    fn test_disable_config_load_controls_env_credentials() {
+        let core = build_core(
+            TosBuilder::default()
+                .bucket("test-bucket")
+                .disable_config_load(),
+        );
+        assert!(
+            sign_with_env(&core, env_credentials()).is_err(),
+            "environment credentials must be ignored when config load is 
disabled"
+        );
+
+        let core = build_core(TosBuilder::default().bucket("test-bucket"));
+        let parts = sign_with_env(&core, env_credentials())
+            .expect("environment credentials must be loaded by default");
+        assert!(authorization(&parts).contains("Credential=env-ak/"));
+    }
+
+    #[test]
+    fn test_disable_config_load_keeps_static_credentials() {
+        let core = build_core(
+            TosBuilder::default()
+                .bucket("test-bucket")
+                .access_key_id("static-ak")
+                .secret_access_key("static-sk")
+                .security_token("static-token")
+                .disable_config_load(),
+        );
+
+        let parts = sign_with_env(&core, env_credentials())
+            .expect("explicit static credentials must still be used");
+        assert!(authorization(&parts).contains("Credential=static-ak/"));
+        assert_eq!(
+            parts.headers["x-tos-security-token"], "static-token",
+            "security token must be applied"
+        );
+    }
+}
diff --git a/core/services/tos/src/config.rs b/core/services/tos/src/config.rs
index c12451faa4..72da2caef0 100644
--- a/core/services/tos/src/config.rs
+++ b/core/services/tos/src/config.rs
@@ -82,7 +82,8 @@ pub struct TosConfig {
     /// environment.
     ///
     /// For examples:
-    /// - envs like `TOS_ACCESS_KEY_ID`
+    ///
+    /// - envs like `VOLCENGINE_ACCESS_KEY_ID`
     pub disable_config_load: bool,
     /// Skip signature will skip loading credentials and signing requests.
     pub skip_signature: bool,
diff --git a/core/services/tos/src/core.rs b/core/services/tos/src/core.rs
index 6b89a5f03c..62e3cb79e1 100644
--- a/core/services/tos/src/core.rs
+++ b/core/services/tos/src/core.rs
@@ -133,6 +133,8 @@ impl TosCore {
                 .sign(&mut parts, None)
                 .await
                 .map_err(|e| new_request_sign_error(e.into()))?;
+
+            parts.headers.remove(HOST);
         }
 
         parts.headers.insert(
@@ -1173,6 +1175,11 @@ pub fn parse_tos_error_code(code: &str) -> 
Option<(ErrorKind, bool)> {
 
 #[cfg(test)]
 mod tests {
+    use std::future::Future;
+    use std::task::Context as TaskContext;
+    use std::task::Poll;
+    use std::task::Waker;
+
     use super::*;
 
     #[test]
@@ -1238,6 +1245,71 @@ mod tests {
         let out: TosError = de::from_reader(bs.reader()).expect("must 
success");
         assert_eq!(out, TosError::default());
     }
+
+    /// Poll a future once; these futures resolve without an external runtime.
+    fn poll_once<F: Future>(future: F) -> F::Output {
+        let mut future = std::pin::pin!(future);
+        let mut cx = TaskContext::from_waker(Waker::noop());
+        match future.as_mut().poll(&mut cx) {
+            Poll::Ready(output) => output,
+            Poll::Pending => panic!("future requires an external async 
runtime"),
+        }
+    }
+
+    fn build_core() -> std::sync::Arc<TosCore> {
+        let backend = crate::Tos::default()
+            .bucket("test-bucket")
+            .access_key_id("test-ak")
+            .secret_access_key("test-sk")
+            .build()
+            .expect("build must succeed");
+        let backend = (&backend as &dyn std::any::Any)
+            .downcast_ref::<crate::backend::TosBackend>()
+            .expect("build must return TosBackend");
+        backend.core.clone()
+    }
+
+    #[derive(Clone, Default)]
+    struct RecordingTransport {
+        headers: std::sync::Arc<std::sync::Mutex<Vec<http::HeaderMap>>>,
+    }
+
+    impl HttpTransport for RecordingTransport {
+        async fn fetch(&self, req: Request<Buffer>) -> 
Result<Response<HttpBody>> {
+            self.headers.lock().unwrap().push(req.headers().clone());
+            // The test only inspects request headers, so it stops before a 
response
+            // body would require a stream implementation.
+            Err(Error::new(
+                ErrorKind::Unexpected,
+                "request recorded by test transport",
+            ))
+        }
+    }
+
+    #[test]
+    fn test_send_removes_host_header_after_signing() {
+        let transport = RecordingTransport::default();
+        let ctx =
+            
OperationContext::new().with_http_transport(HttpTransporter::new(transport.clone()));
+        let core = build_core();
+        let req = core
+            .tos_put_object_request("test", None, &OpWrite::default(), 
Buffer::new())
+            .expect("request must be valid");
+
+        // The recording transport stops after capturing the request headers.
+        assert!(poll_once(core.send(&ctx, req)).is_err());
+
+        let headers = transport.headers.lock().unwrap();
+        assert_eq!(headers.len(), 1);
+        assert!(
+            headers[0].contains_key(http::header::AUTHORIZATION),
+            "request must be signed before it is sent"
+        );
+        assert!(
+            !headers[0].contains_key(HOST),
+            "Host header must be removed after signing"
+        );
+    }
 }
 
 mod utils {
diff --git a/website/data/services.json b/website/data/services.json
index 4b3d7dc373..7b757f725a 100644
--- a/website/data/services.json
+++ b/website/data/services.json
@@ -5224,7 +5224,7 @@
           "type": "bool",
           "required": false,
           "group": "General",
-          "comments": "Disable config load so that opendal will not load 
config from\nenvironment.\n\nFor examples:\n- envs like `TOS_ACCESS_KEY_ID`"
+          "comments": "Disable config load so that opendal will not load 
config from\nenvironment.\n\nFor examples:\n\n- envs like 
`VOLCENGINE_ACCESS_KEY_ID`"
         },
         {
           "name": "skip_signature",
@@ -5239,31 +5239,31 @@
           "binding": "rust",
           "language": "rust",
           "minimal": "use opendal::Operator;\n\nlet operator = 
Operator::via_iter(\"tos\", [\n    (\"bucket\".to_string(), 
\"...\".to_string()),\n])?;",
-          "full": "use opendal::Operator;\n\nlet operator = 
Operator::via_iter(\"tos\", [\n    // root of this backend.\n    //\n    // All 
operations will happen under this root.\n    //\n    // default to `/` if not 
set.\n    // (\"root\".to_string(), \"...\".to_string()),\n\n    // bucket name 
of this backend.\n    //\n    // required.\n    (\"bucket\".to_string(), 
\"...\".to_string()),\n\n    // endpoint of this backend.\n    //\n    // 
Endpoint must be full uri, e.g.\n    // - TOS:  [...]
+          "full": "use opendal::Operator;\n\nlet operator = 
Operator::via_iter(\"tos\", [\n    // root of this backend.\n    //\n    // All 
operations will happen under this root.\n    //\n    // default to `/` if not 
set.\n    // (\"root\".to_string(), \"...\".to_string()),\n\n    // bucket name 
of this backend.\n    //\n    // required.\n    (\"bucket\".to_string(), 
\"...\".to_string()),\n\n    // endpoint of this backend.\n    //\n    // 
Endpoint must be full uri, e.g.\n    // - TOS:  [...]
         },
         {
           "binding": "java",
           "language": "java",
           "minimal": "import java.util.HashMap;\nimport java.util.Map;\nimport 
org.apache.opendal.Operator;\n\nMap<String, String> config = new 
HashMap<>();\nconfig.put(\"bucket\", \"...\");\nOperator operator = 
Operator.of(\"tos\", config);",
-          "full": "import java.util.HashMap;\nimport java.util.Map;\nimport 
org.apache.opendal.Operator;\n\nMap<String, String> config = new 
HashMap<>();\n// root of this backend.\n//\n// All operations will happen under 
this root.\n//\n// default to `/` if not set.\n// config.put(\"root\", 
\"...\");\n\n// bucket name of this backend.\n//\n// 
required.\nconfig.put(\"bucket\", \"...\");\n\n// endpoint of this 
backend.\n//\n// Endpoint must be full uri, e.g.\n// - TOS: 
`https://tos-cn-beij [...]
+          "full": "import java.util.HashMap;\nimport java.util.Map;\nimport 
org.apache.opendal.Operator;\n\nMap<String, String> config = new 
HashMap<>();\n// root of this backend.\n//\n// All operations will happen under 
this root.\n//\n// default to `/` if not set.\n// config.put(\"root\", 
\"...\");\n\n// bucket name of this backend.\n//\n// 
required.\nconfig.put(\"bucket\", \"...\");\n\n// endpoint of this 
backend.\n//\n// Endpoint must be full uri, e.g.\n// - TOS: 
`https://tos-cn-beij [...]
         },
         {
           "binding": "python",
           "language": "python",
           "minimal": "import opendal\n\noperator = opendal.Operator(\n    
\"tos\",\n    bucket=\"...\",\n)",
-          "full": "import opendal\n\noperator = opendal.Operator(\n    
\"tos\",\n    # root of this backend.\n    #\n    # All operations will happen 
under this root.\n    #\n    # default to `/` if not set.\n    # 
root=\"...\",\n\n    # bucket name of this backend.\n    #\n    # required.\n   
 bucket=\"...\",\n\n    # endpoint of this backend.\n    #\n    # Endpoint must 
be full uri, e.g.\n    # - TOS: `https://tos-cn-beijing.volces.com`\n    # - 
TOS with region: `https://tos-{region}.v [...]
+          "full": "import opendal\n\noperator = opendal.Operator(\n    
\"tos\",\n    # root of this backend.\n    #\n    # All operations will happen 
under this root.\n    #\n    # default to `/` if not set.\n    # 
root=\"...\",\n\n    # bucket name of this backend.\n    #\n    # required.\n   
 bucket=\"...\",\n\n    # endpoint of this backend.\n    #\n    # Endpoint must 
be full uri, e.g.\n    # - TOS: `https://tos-cn-beijing.volces.com`\n    # - 
TOS with region: `https://tos-{region}.v [...]
         },
         {
           "binding": "nodejs",
           "language": "javascript",
           "minimal": "import { Operator } from \"opendal\";\n\nconst operator 
= new Operator(\"tos\", {\n  bucket: \"...\",\n});",
-          "full": "import { Operator } from \"opendal\";\n\nconst operator = 
new Operator(\"tos\", {\n  // root of this backend.\n  //\n  // All operations 
will happen under this root.\n  //\n  // default to `/` if not set.\n  // root: 
\"...\",\n\n  // bucket name of this backend.\n  //\n  // required.\n  bucket: 
\"...\",\n\n  // endpoint of this backend.\n  //\n  // Endpoint must be full 
uri, e.g.\n  // - TOS: `https://tos-cn-beijing.volces.com`\n  // - TOS with 
region: `https://tos-{re [...]
+          "full": "import { Operator } from \"opendal\";\n\nconst operator = 
new Operator(\"tos\", {\n  // root of this backend.\n  //\n  // All operations 
will happen under this root.\n  //\n  // default to `/` if not set.\n  // root: 
\"...\",\n\n  // bucket name of this backend.\n  //\n  // required.\n  bucket: 
\"...\",\n\n  // endpoint of this backend.\n  //\n  // Endpoint must be full 
uri, e.g.\n  // - TOS: `https://tos-cn-beijing.volces.com`\n  // - TOS with 
region: `https://tos-{re [...]
         },
         {
           "binding": "go",
           "language": "go",
           "minimal": "import 
(\n\t\"github.com/apache/opendal-go-services/tos\"\n\topendal 
\"github.com/apache/opendal/bindings/go\"\n)\n\noperator, err := 
opendal.NewOperator(tos.Scheme, opendal.OperatorOptions{\n\t\"bucket\": 
\"...\",\n})",
-          "full": "import 
(\n\t\"github.com/apache/opendal-go-services/tos\"\n\topendal 
\"github.com/apache/opendal/bindings/go\"\n)\n\noperator, err := 
opendal.NewOperator(tos.Scheme, opendal.OperatorOptions{\n\t// root of this 
backend.\n\t//\n\t// All operations will happen under this root.\n\t//\n\t// 
default to `/` if not set.\n\t// \"root\": \"...\",\n\n\t// bucket name of this 
backend.\n\t//\n\t// required.\n\t\"bucket\": \"...\",\n\n\t// endpoint of this 
backend.\n\t//\n\t// Endpo [...]
+          "full": "import 
(\n\t\"github.com/apache/opendal-go-services/tos\"\n\topendal 
\"github.com/apache/opendal/bindings/go\"\n)\n\noperator, err := 
opendal.NewOperator(tos.Scheme, opendal.OperatorOptions{\n\t// root of this 
backend.\n\t//\n\t// All operations will happen under this root.\n\t//\n\t// 
default to `/` if not set.\n\t// \"root\": \"...\",\n\n\t// bucket name of this 
backend.\n\t//\n\t// required.\n\t\"bucket\": \"...\",\n\n\t// endpoint of this 
backend.\n\t//\n\t// Endpo [...]
         }
       ]
     },

Reply via email to