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 afef5ad6c7 refactor(services/github): use Reqsign for GitHub 
authentication (#9437)
afef5ad6c7 is described below

commit afef5ad6c72c5e4d560556759c250506d8a412c7
Author: Xuanwo <[email protected]>
AuthorDate: Mon Nov 30 22:09:56 2026 +0800

    refactor(services/github): use Reqsign for GitHub authentication (#9437)
    
    refactor(services/github): sign requests with reqsign
---
 core/Cargo.lock                     | 12 ++++++
 core/services/github/Cargo.toml     |  2 +
 core/services/github/src/backend.rs | 20 +++++++--
 core/services/github/src/core.rs    | 82 +++++++++++++------------------------
 4 files changed, 60 insertions(+), 56 deletions(-)

diff --git a/core/Cargo.lock b/core/Cargo.lock
index 08d6a63f38..250f65d723 100644
--- a/core/Cargo.lock
+++ b/core/Cargo.lock
@@ -8020,6 +8020,8 @@ dependencies = [
  "http 1.5.0",
  "log",
  "opendal-core",
+ "reqsign-core",
+ "reqsign-github",
  "serde",
  "serde_json",
  "tokio",
@@ -10159,6 +10161,16 @@ dependencies = [
  "tokio",
 ]
 
+[[package]]
+name = "reqsign-github"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index";
+checksum = "45e92c073a233ebb9f55a768f8b43cffaa1cc6b0622be40aa126b5817cdcda45"
+dependencies = [
+ "http 1.5.0",
+ "reqsign-core",
+]
+
 [[package]]
 name = "reqsign-google"
 version = "4.0.0"
diff --git a/core/services/github/Cargo.toml b/core/services/github/Cargo.toml
index ee95b7e32b..fd50ee90b0 100644
--- a/core/services/github/Cargo.toml
+++ b/core/services/github/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-core = { version = "4.0.0", default-features = false }
+reqsign-github = { version = "1.0.0", default-features = false }
 serde = { workspace = true, features = ["derive"] }
 serde_json = { workspace = true }
 
diff --git a/core/services/github/src/backend.rs 
b/core/services/github/src/backend.rs
index 8e520259fd..25e5b80e92 100644
--- a/core/services/github/src/backend.rs
+++ b/core/services/github/src/backend.rs
@@ -21,6 +21,8 @@ use std::sync::Arc;
 use bytes::Buf;
 use http::StatusCode;
 use log::debug;
+use reqsign_core::Context;
+use reqsign_github::Credential;
 
 use super::GITHUB_SCHEME;
 use super::config::GithubConfig;
@@ -64,9 +66,10 @@ impl GithubBuilder {
         self
     }
 
-    /// Github access_token.
+    /// Set the optional GitHub access token.
     ///
-    /// required.
+    /// Pass the raw token as visible ASCII without whitespace. An empty input
+    /// leaves the current token setting unchanged.
     pub fn token(mut self, token: &str) -> Self {
         if !token.is_empty() {
             self.config.token = Some(token.to_string());
@@ -117,6 +120,16 @@ impl Builder for GithubBuilder {
 
         debug!("backend use repo {}", self.config.repo);
 
+        let credential = match self.config.token {
+            Some(token) => Credential::new(token).map_err(|err| {
+                Error::new(ErrorKind::ConfigInvalid, "invalid GitHub token")
+                    .with_operation("Builder::build")
+                    .with_context("service", GITHUB_SCHEME)
+                    .set_source(err)
+            })?,
+            None => Credential::anonymous(),
+        };
+
         Ok(GithubBackend {
             core: Arc::new(GithubCore {
                 info: ServiceInfo::new(GITHUB_SCHEME, &root, ""),
@@ -143,7 +156,8 @@ impl Builder for GithubBuilder {
                     ..Default::default()
                 },
                 root,
-                token: self.config.token.clone(),
+                credential,
+                sign_context: Context::new(),
                 owner: self.config.owner.clone(),
                 repo: self.config.repo.clone(),
             }),
diff --git a/core/services/github/src/core.rs b/core/services/github/src/core.rs
index bfa9f91faa..5c3baa8733 100644
--- a/core/services/github/src/core.rs
+++ b/core/services/github/src/core.rs
@@ -25,7 +25,8 @@ use http::Request;
 use http::Response;
 use http::StatusCode;
 use http::header;
-use http::request;
+use reqsign_core::{Context, SignRequest};
+use reqsign_github::{Credential, RequestSigner};
 use serde::Deserialize;
 use serde::Serialize;
 
@@ -39,8 +40,8 @@ pub struct GithubCore {
     pub capability: Capability,
     /// The root of this core.
     pub root: String,
-    /// Github access_token.
-    pub token: Option<String>,
+    pub(super) credential: Credential,
+    pub(super) sign_context: Context,
     /// Github repo owner.
     pub owner: String,
     /// Github repo name.
@@ -58,36 +59,30 @@ impl Debug for GithubCore {
 }
 
 impl GithubCore {
-    #[inline]
-    pub async fn send(
-        &self,
-        ctx: &OperationContext,
-        req: Request<Buffer>,
-    ) -> Result<Response<Buffer>> {
-        ctx.http_transport().send(req).await
+    async fn sign(&self, req: Request<Buffer>) -> Result<Request<Buffer>> {
+        let (mut parts, body) = req.into_parts();
+        parts.headers.insert(
+            header::USER_AGENT,
+            build_header_value(&format!("opendal-{VERSION}"))?,
+        );
+        parts.headers.insert(
+            "x-github-api-version",
+            header::HeaderValue::from_static("2022-11-28"),
+        );
+        RequestSigner
+            .sign_request(&self.sign_context, &mut parts, 
Some(&self.credential), None)
+            .await
+            .map_err(|err| new_request_sign_error(err.into()))?;
+        Ok(Request::from_parts(parts, body))
     }
 
-    pub fn sign(&self, req: request::Builder) -> Result<request::Builder> {
-        let mut req = req
-            .header(header::USER_AGENT, format!("opendal-{VERSION}"))
-            .header("X-GitHub-Api-Version", "2022-11-28");
-
-        // Github access_token is optional.
-        if let Some(token) = &self.token {
-            req = req.header(
-                header::AUTHORIZATION,
-                format_authorization_by_bearer(token)?,
-            )
-        }
-
-        Ok(req)
+    async fn send(&self, ctx: &OperationContext, req: Request<Buffer>) -> 
Result<Response<Buffer>> {
+        let req = self.sign(req).await?;
+        ctx.http_transport().send(req).await
     }
-}
 
-impl GithubCore {
     pub async fn get_file_sha(&self, ctx: &OperationContext, path: &str) -> 
Result<Option<String>> {
-        // if the token is not set, we should not try to get the sha of the 
file.
-        if self.token.is_none() {
+        if self.credential.is_anonymous() {
             return Err(Error::new(
                 ErrorKind::PermissionDenied,
                 "Github access_token is not set",
@@ -126,11 +121,7 @@ impl GithubCore {
 
         let req = req
             .extension(Operation::Stat)
-            .extension(ServiceOperation("GetRepositoryContent"));
-
-        let req = self.sign(req)?;
-
-        let req = req
+            .extension(ServiceOperation("GetRepositoryContent"))
             .header("Accept", "application/vnd.github.object+json")
             .body(Buffer::new())
             .map_err(new_request_build_error)?;
@@ -156,13 +147,9 @@ impl GithubCore {
 
         let req = Request::get(url);
 
-        let req = req
-            .extension(Operation::Read)
-            .extension(ServiceOperation("GetRepositoryContent"));
-
-        let req = self.sign(req)?;
-
         let mut req = req
+            .extension(Operation::Read)
+            .extension(ServiceOperation("GetRepositoryContent"))
             .header(header::ACCEPT, "application/vnd.github.raw+json")
             .header(header::RANGE, range.to_header());
 
@@ -171,6 +158,7 @@ impl GithubCore {
         }
 
         let req = req.body(Buffer::new()).map_err(new_request_build_error)?;
+        let req = self.sign(req).await?;
 
         ctx.http_transport().fetch(req).await
     }
@@ -198,8 +186,6 @@ impl GithubCore {
             .extension(Operation::Write)
             .extension(ServiceOperation("CreateOrUpdateFileContents"));
 
-        let req = self.sign(req)?;
-
         let mut req_body = CreateOrUpdateContentsRequest {
             message: format!("Write {} at {} via opendal", path, 
Timestamp::now()),
             content: 
base64::engine::general_purpose::STANDARD.encode(bs.to_bytes()),
@@ -252,8 +238,6 @@ impl GithubCore {
             .extension(Operation::Delete)
             .extension(ServiceOperation("DeleteFile"));
 
-        let req = self.sign(req)?;
-
         let req_body = DeleteContentsRequest {
             message: format!("Delete {} at {} via opendal", path, 
Timestamp::now()),
             sha,
@@ -300,11 +284,7 @@ impl GithubCore {
 
         let req = req
             .extension(Operation::List)
-            .extension(ServiceOperation("GetRepositoryContent"));
-
-        let req = self.sign(req)?;
-
-        let req = req
+            .extension(ServiceOperation("GetRepositoryContent"))
             .header("Accept", "application/vnd.github.object+json")
             .body(Buffer::new())
             .map_err(new_request_build_error)?;
@@ -339,11 +319,7 @@ impl GithubCore {
 
         let req = req
             .extension(Operation::List)
-            .extension(ServiceOperation("GetTree"));
-
-        let req = self.sign(req)?;
-
-        let req = req
+            .extension(ServiceOperation("GetTree"))
             .header("Accept", "application/vnd.github.object+json")
             .body(Buffer::new())
             .map_err(new_request_build_error)?;

Reply via email to