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 7df7776b07 refactor(services/aliyun-drive): sign API requests with 
Reqsign (#9441)
7df7776b07 is described below

commit 7df7776b07eb73233659e1f7dbcfd19702b106a1
Author: Xuanwo <[email protected]>
AuthorDate: Mon Nov 30 23:40:39 2026 +0800

    refactor(services/aliyun-drive): sign API requests with Reqsign (#9441)
    
    Keep the token exchange and cache in the service to preserve grant rotation 
across transports and the existing exchange errors. Use the published Reqsign 
signer for first-party API bearer headers.
---
 core/Cargo.lock                           | 17 ++++++++
 core/services/aliyun-drive/Cargo.toml     |  2 +
 core/services/aliyun-drive/src/backend.rs | 12 +++---
 core/services/aliyun-drive/src/core.rs    | 70 ++++++++++++++++++-------------
 4 files changed, 65 insertions(+), 36 deletions(-)

diff --git a/core/Cargo.lock b/core/Cargo.lock
index 282b9bde86..48d7ac4c63 100644
--- a/core/Cargo.lock
+++ b/core/Cargo.lock
@@ -7637,6 +7637,8 @@ dependencies = [
  "http 1.5.0",
  "log",
  "opendal-core",
+ "reqsign-aliyun-drive",
+ "reqsign-core",
  "serde",
  "serde_json",
  "tokio",
@@ -10047,6 +10049,21 @@ version = "0.8.12"
 source = "registry+https://github.com/rust-lang/crates.io-index";
 checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
 
+[[package]]
+name = "reqsign-aliyun-drive"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index";
+checksum = "efc3f8fa0b86464d283337d142bd721706f40a64058c40deb094634405868c14"
+dependencies = [
+ "asyncband 0.8.0",
+ "bytes",
+ "http 1.5.0",
+ "jiff 1.0.3",
+ "reqsign-core",
+ "serde",
+ "serde_json",
+]
+
 [[package]]
 name = "reqsign-aliyun-oss"
 version = "4.0.0"
diff --git a/core/services/aliyun-drive/Cargo.toml 
b/core/services/aliyun-drive/Cargo.toml
index 483b1156dc..c9d9be56af 100644
--- a/core/services/aliyun-drive/Cargo.toml
+++ b/core/services/aliyun-drive/Cargo.toml
@@ -37,6 +37,8 @@ bytes = { workspace = true }
 http = { workspace = true }
 log = { workspace = true }
 opendal-core = { path = "../../core", version = "0.59.5", default-features = 
false }
+reqsign-aliyun-drive = { version = "1.0.0", default-features = false }
+reqsign-core = { version = "4.0.0", default-features = false }
 serde = { workspace = true, features = ["derive"] }
 serde_json = { workspace = true }
 
diff --git a/core/services/aliyun-drive/src/backend.rs 
b/core/services/aliyun-drive/src/backend.rs
index 6fc5381d16..1b1f8f6188 100644
--- a/core/services/aliyun-drive/src/backend.rs
+++ b/core/services/aliyun-drive/src/backend.rs
@@ -105,9 +105,9 @@ impl Builder for AliyunDriveBuilder {
         let root = 
normalize_root(&self.config.root.clone().unwrap_or_default());
         debug!("backend use root {}", root);
 
-        let sign = match self.config.access_token.clone() {
+        let auth = match self.config.access_token.clone() {
             Some(access_token) if !access_token.is_empty() => {
-                AliyunDriveSign::Access(access_token)
+                AliyunDriveAuth::Access(access_token)
             }
             _ => match (
                 self.config.client_id.clone(),
@@ -116,7 +116,7 @@ impl Builder for AliyunDriveBuilder {
             ) {
                 (Some(client_id), Some(client_secret), Some(refresh_token)) if
                 !client_id.is_empty() && !client_secret.is_empty() && 
!refresh_token.is_empty() => {
-                    AliyunDriveSign::Refresh(client_id, client_secret, 
refresh_token, None, 0)
+                    AliyunDriveAuth::Refresh(client_id, client_secret, 
refresh_token, None, 0)
                 }
                 _ => return Err(Error::new(
                     ErrorKind::ConfigInvalid,
@@ -168,10 +168,10 @@ impl Builder for AliyunDriveBuilder {
                 endpoint: "https://openapi.alipan.com".to_string(),
                 root,
                 drive_type,
-                signer: Arc::new(Mutex::new(AliyunDriveSigner {
+                session: Mutex::new(AliyunDriveSession {
                     drive_id: None,
-                    sign,
-                })),
+                    auth,
+                }),
                 dir_lock: Arc::new(Mutex::new(())),
             }),
         })
diff --git a/core/services/aliyun-drive/src/core.rs 
b/core/services/aliyun-drive/src/core.rs
index a8b836384e..dae40be447 100644
--- a/core/services/aliyun-drive/src/core.rs
+++ b/core/services/aliyun-drive/src/core.rs
@@ -17,6 +17,7 @@
 
 use std::fmt::Debug;
 use std::sync::Arc;
+use std::sync::LazyLock;
 
 use asyncband::mutex::Mutex;
 use bytes::Buf;
@@ -25,6 +26,10 @@ use http::Request;
 use http::Response;
 use http::header;
 use http::header::HeaderValue;
+use reqsign_aliyun_drive::Credential;
+use reqsign_aliyun_drive::RequestSigner;
+use reqsign_core::Context;
+use reqsign_core::SignRequest;
 use serde::Deserialize;
 use serde::Serialize;
 
@@ -47,15 +52,15 @@ pub enum DriveType {
     Resource,
 }
 
-/// Available Aliyun Drive Signer Set
-pub enum AliyunDriveSign {
+pub(super) enum AliyunDriveAuth {
     Refresh(String, String, String, Option<String>, i64),
     Access(String),
 }
 
-pub struct AliyunDriveSigner {
-    pub drive_id: Option<String>,
-    pub sign: AliyunDriveSign,
+// Keep the refresh cache across transport changes and preserve the token 
endpoint's OpenDAL errors.
+pub(super) struct AliyunDriveSession {
+    pub(super) drive_id: Option<String>,
+    pub(super) auth: AliyunDriveAuth,
 }
 
 pub struct AliyunDriveCore {
@@ -66,7 +71,7 @@ pub struct AliyunDriveCore {
     pub root: String,
     pub drive_type: DriveType,
 
-    pub signer: Arc<Mutex<AliyunDriveSigner>>,
+    pub(super) session: Mutex<AliyunDriveSession>,
     pub dir_lock: Arc<Mutex<()>>,
 }
 
@@ -84,7 +89,7 @@ impl AliyunDriveCore {
         &self,
         ctx: &OperationContext,
         mut req: Request<Buffer>,
-        token: Option<&str>,
+        token: Option<String>,
     ) -> Result<Response<Buffer>> {
         // AliyunDrive raise NullPointerException if you haven't set a 
user-agent.
         req.headers_mut().insert(
@@ -99,11 +104,16 @@ impl AliyunDriveCore {
             );
         }
         if let Some(token) = token {
-            req.headers_mut().insert(
-                header::AUTHORIZATION,
-                HeaderValue::from_str(&format_authorization_by_bearer(token)?)
-                    .expect("access token must be valid header value"),
-            );
+            static SIGNING_CONTEXT: LazyLock<Context> = 
LazyLock::new(Context::new);
+
+            let credential =
+                Credential::new(token).map_err(|err| 
new_request_sign_error(err.into()))?;
+            let (mut parts, body) = req.into_parts();
+            RequestSigner
+                .sign_request(&SIGNING_CONTEXT, &mut parts, Some(&credential), 
None)
+                .await
+                .map_err(|err| new_request_sign_error(err.into()))?;
+            req = Request::from_parts(parts, body);
         }
         ctx.http_transport().send(req).await
     }
@@ -135,7 +145,7 @@ impl AliyunDriveCore {
         Ok(res.into_body())
     }
 
-    async fn get_drive_id(&self, ctx: &OperationContext, token: Option<&str>) 
-> Result<Buffer> {
+    async fn get_drive_id(&self, ctx: &OperationContext, token: 
Option<String>) -> Result<Buffer> {
         let req = Request::post(format!("{}/adrive/v1.0/user/getDriveInfo", 
self.endpoint))
             .body(Buffer::new())
             .map_err(new_request_build_error)?;
@@ -153,10 +163,10 @@ impl AliyunDriveCore {
         &self,
         ctx: &OperationContext,
     ) -> Result<(Option<String>, String)> {
-        let mut signer = self.signer.lock().await;
-        let token = match &mut signer.sign {
-            AliyunDriveSign::Access(access_token) => 
Some(access_token.clone()),
-            AliyunDriveSign::Refresh(
+        let mut session = self.session.lock().await;
+        let token = match &mut session.auth {
+            AliyunDriveAuth::Access(access_token) => 
Some(access_token.clone()),
+            AliyunDriveAuth::Refresh(
                 client_id,
                 client_secret,
                 refresh_token,
@@ -177,8 +187,8 @@ impl AliyunDriveCore {
                 access_token.clone()
             }
         };
-        let Some(drive_id) = &signer.drive_id else {
-            let res = self.get_drive_id(ctx, token.as_deref()).await?;
+        let Some(drive_id) = &session.drive_id else {
+            let res = self.get_drive_id(ctx, token.clone()).await?;
             let output: DriveInfoResponse =
                 
serde_json::from_reader(res.reader()).map_err(new_json_deserialize_error)?;
             let drive_id = match self.drive_type {
@@ -186,7 +196,7 @@ impl AliyunDriveCore {
                 DriveType::Backup => 
output.backup_drive_id.unwrap_or(output.default_drive_id),
                 DriveType::Resource => 
output.resource_drive_id.unwrap_or(output.default_drive_id),
             };
-            signer.drive_id = Some(drive_id.clone());
+            session.drive_id = Some(drive_id.clone());
             return Ok((token, drive_id));
         };
         Ok((token, drive_id.clone()))
@@ -222,7 +232,7 @@ impl AliyunDriveCore {
             .extension(ServiceOperation("GetFileByPath"))
             .body(Buffer::from(body))
             .map_err(new_request_build_error)?;
-        let res = self.send(ctx, req, token.as_deref()).await?;
+        let res = self.send(ctx, req, token).await?;
         if !res.status().is_success() {
             return Err(parse_error(
                 ErrorContext::new(ServiceOperation("GetFileByPath")),
@@ -298,7 +308,7 @@ impl AliyunDriveCore {
             .extension(ServiceOperation("CreateFile"))
             .body(Buffer::from(body))
             .map_err(new_request_build_error)?;
-        let res = self.send(ctx, req, token.as_deref()).await?;
+        let res = self.send(ctx, req, token).await?;
         if !res.status().is_success() {
             return Err(parse_error(
                 ErrorContext::new(ServiceOperation("CreateFile")),
@@ -337,7 +347,7 @@ impl AliyunDriveCore {
         .body(Buffer::from(body))
         .map_err(new_request_build_error)?;
 
-        let res = self.send(ctx, req, token.as_deref()).await?;
+        let res = self.send(ctx, req, token).await?;
         if !res.status().is_success() {
             return Err(parse_error(
                 ErrorContext::new(ServiceOperation("GetDownloadUrl")),
@@ -387,7 +397,7 @@ impl AliyunDriveCore {
             .extension(ServiceOperation("MoveFile"))
             .body(Buffer::from(body))
             .map_err(new_request_build_error)?;
-        let res = self.send(ctx, req, token.as_deref()).await?;
+        let res = self.send(ctx, req, token).await?;
         if !res.status().is_success() {
             return Err(parse_error(
                 ErrorContext::new(ServiceOperation("MoveFile")),
@@ -416,7 +426,7 @@ impl AliyunDriveCore {
             .extension(ServiceOperation("UpdateFile"))
             .body(Buffer::from(body))
             .map_err(new_request_build_error)?;
-        let res = self.send(ctx, req, token.as_deref()).await?;
+        let res = self.send(ctx, req, token).await?;
         if !res.status().is_success() {
             return Err(parse_error(
                 ErrorContext::new(ServiceOperation("UpdateFile")),
@@ -446,7 +456,7 @@ impl AliyunDriveCore {
             .extension(ServiceOperation("CopyFile"))
             .body(Buffer::from(body))
             .map_err(new_request_build_error)?;
-        let res = self.send(ctx, req, token.as_deref()).await?;
+        let res = self.send(ctx, req, token).await?;
         if !res.status().is_success() {
             return Err(parse_error(
                 ErrorContext::new(ServiceOperation("CopyFile")),
@@ -468,7 +478,7 @@ impl AliyunDriveCore {
             .extension(ServiceOperation("DeleteFile"))
             .body(Buffer::from(body))
             .map_err(new_request_build_error)?;
-        let res = self.send(ctx, req, token.as_deref()).await?;
+        let res = self.send(ctx, req, token).await?;
         if !res.status().is_success() {
             return Err(parse_error(
                 ErrorContext::new(ServiceOperation("DeleteFile")),
@@ -498,7 +508,7 @@ impl AliyunDriveCore {
             .extension(ServiceOperation("ListFiles"))
             .body(Buffer::from(body))
             .map_err(new_request_build_error)?;
-        let res = self.send(ctx, req, token.as_deref()).await?;
+        let res = self.send(ctx, req, token).await?;
         if !res.status().is_success() {
             return Err(parse_error(
                 ErrorContext::new(ServiceOperation("ListFiles")),
@@ -526,7 +536,7 @@ impl AliyunDriveCore {
             .extension(ServiceOperation("CompleteUpload"))
             .body(Buffer::from(body))
             .map_err(new_request_build_error)?;
-        let res = self.send(ctx, req, token.as_deref()).await?;
+        let res = self.send(ctx, req, token).await?;
         if !res.status().is_success() {
             return Err(parse_error(
                 ErrorContext::new(ServiceOperation("CompleteUpload")),
@@ -564,7 +574,7 @@ impl AliyunDriveCore {
         .body(Buffer::from(body))
         .map_err(new_request_build_error)?;
 
-        let res = self.send(ctx, req, token.as_deref()).await?;
+        let res = self.send(ctx, req, token).await?;
         if !res.status().is_success() {
             return Err(parse_error(
                 ErrorContext::new(ServiceOperation("GetUploadUrl")),

Reply via email to