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 2297b87ad0 refactor(services/seafile): Use Reqsign for account
authentication and API signing (#9449)
2297b87ad0 is described below
commit 2297b87ad01496123ce744d5a958bb05ae906b7a
Author: Xuanwo <[email protected]>
AuthorDate: Tue Dec 1 02:49:11 2026 +0800
refactor(services/seafile): Use Reqsign for account authentication and API
signing (#9449)
refactor(services/seafile): migrate authentication to Reqsign
Use Reqsign for account credentials and API signing while keeping library
discovery and signer state scoped to the OpenDAL transport. Preserve Seafile
login diagnostics, error kinds, and retryability without exposing account
exchange payloads.
---
core/Cargo.lock | 18 ++
core/services/seafile/Cargo.toml | 6 +-
core/services/seafile/src/backend.rs | 83 ++++--
core/services/seafile/src/config.rs | 5 +-
core/services/seafile/src/core.rs | 548 ++++++++++++++++++++++++-----------
core/services/seafile/src/docs.md | 11 +-
core/services/seafile/src/lib.rs | 5 +
7 files changed, 478 insertions(+), 198 deletions(-)
diff --git a/core/Cargo.lock b/core/Cargo.lock
index c671f5c527..31ecbdee8a 100644
--- a/core/Cargo.lock
+++ b/core/Cargo.lock
@@ -8463,6 +8463,8 @@ dependencies = [
"http 1.5.0",
"log",
"opendal-core",
+ "reqsign-core",
+ "reqsign-seafile",
"serde",
"serde_json",
"tokio",
@@ -10312,6 +10314,22 @@ dependencies = [
"serde_json",
]
+[[package]]
+name = "reqsign-seafile"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a1c7b12b00df31702ee64f3b23d4390fe9181036a6ac2dfd540371662bca0b7d"
+dependencies = [
+ "bytes",
+ "form_urlencoded",
+ "http 1.5.0",
+ "log",
+ "reqsign-core",
+ "rust-ini",
+ "serde",
+ "serde_json",
+]
+
[[package]]
name = "reqsign-tencent-cos"
version = "4.0.0"
diff --git a/core/services/seafile/Cargo.toml b/core/services/seafile/Cargo.toml
index b74fc7c4fa..b5fb072e7a 100644
--- a/core/services/seafile/Cargo.toml
+++ b/core/services/seafile/Cargo.toml
@@ -32,12 +32,16 @@ version = { workspace = true }
all-features = true
[dependencies]
-opendal-core = { path = "../../core", version = "0.59.5", default-features =
false }
+opendal-core = { path = "../../core", version = "0.59.5", default-features =
false, features = [
+ "reqsign",
+] }
asyncband = { workspace = true, features = ["once-cell"] }
bytes = { workspace = true }
http = { workspace = true }
log = { workspace = true }
+reqsign-core = { version = "4.0.0", default-features = false }
+reqsign-seafile = { version = "1.0.0", default-features = false }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
diff --git a/core/services/seafile/src/backend.rs
b/core/services/seafile/src/backend.rs
index fdf1169f0b..37b667553d 100644
--- a/core/services/seafile/src/backend.rs
+++ b/core/services/seafile/src/backend.rs
@@ -18,12 +18,16 @@
use std::fmt::Debug;
use std::sync::Arc;
-use asyncband::once::OnceCell;
use log::debug;
+use reqsign_core::ProvideCredential;
+use reqsign_core::ProvideCredentialDyn;
+use reqsign_seafile::AccountTokenCredentialProvider;
+use reqsign_seafile::Credential;
use super::SEAFILE_SCHEME;
use super::config::SeafileConfig;
use super::core::SeafileCore;
+use super::core::SeafileCredentialProvider;
use super::core::parse_dir_detail;
use super::core::parse_file_detail;
use super::deleter::SeafileDeleter;
@@ -39,6 +43,7 @@ use opendal_core::*;
#[derive(Default)]
pub struct SeafileBuilder {
pub(super) config: SeafileConfig,
+ pub(super) credential_provider: Option<Arc<dyn
ProvideCredentialDyn<Credential = Credential>>>,
}
impl Debug for SeafileBuilder {
@@ -76,9 +81,9 @@ impl SeafileBuilder {
self
}
- /// username of this backend.
+ /// Set the account username, for example `[email protected]`.
///
- /// It is required. e.g. `[email protected]`
+ /// Required when using the built-in account login.
pub fn username(mut self, username: &str) -> Self {
self.config.username = if username.is_empty() {
None
@@ -89,9 +94,9 @@ impl SeafileBuilder {
self
}
- /// password of this backend.
+ /// Set the account password.
///
- /// It is required. e.g. `asecret`
+ /// Required when using the built-in account login.
pub fn password(mut self, password: &str) -> Self {
self.config.password = if password.is_empty() {
None
@@ -102,6 +107,22 @@ impl SeafileBuilder {
self
}
+ /// Use a Reqsign credential provider in place of the built-in account
login.
+ ///
+ /// The provider must supply an account token that can list the configured
+ /// library. The endpoint and repository name are still required. Username
+ /// and password are ignored when a provider is set.
+ ///
+ /// Use [`crate::reqsign_seafile::StaticCredentialProvider`] to supply an
+ /// existing account token.
+ pub fn credential_provider(
+ mut self,
+ provider: impl ProvideCredential<Credential = Credential> + 'static,
+ ) -> Self {
+ self.credential_provider = Some(Arc::new(provider));
+ self
+ }
+
/// Set repo name of this backend.
///
/// It is required. e.g. `myrepo`
@@ -131,26 +152,33 @@ impl Builder for SeafileBuilder {
debug!("backend use repo_name {}", self.config.repo_name);
- let endpoint = match &self.config.endpoint {
- Some(endpoint) => Ok(endpoint.clone()),
- None => Err(Error::new(ErrorKind::ConfigInvalid, "endpoint is
empty")
+ let endpoint = self.config.endpoint.ok_or_else(|| {
+ Error::new(ErrorKind::ConfigInvalid, "endpoint is empty")
.with_operation("Builder::build")
- .with_context("service", SEAFILE_SCHEME)),
- }?;
-
- let username = match &self.config.username {
- Some(username) => Ok(username.clone()),
- None => Err(Error::new(ErrorKind::ConfigInvalid, "username is
empty")
- .with_operation("Builder::build")
- .with_context("service", SEAFILE_SCHEME)),
- }?;
-
- let password = match &self.config.password {
- Some(password) => Ok(password.clone()),
- None => Err(Error::new(ErrorKind::ConfigInvalid, "password is
empty")
- .with_operation("Builder::build")
- .with_context("service", SEAFILE_SCHEME)),
- }?;
+ .with_context("service", SEAFILE_SCHEME)
+ })?;
+ let endpoint = endpoint.trim_end_matches('/').to_string();
+
+ let credential_provider = match self.credential_provider {
+ Some(provider) => SeafileCredentialProvider::Custom(provider),
+ None => {
+ let username = self.config.username.ok_or_else(|| {
+ Error::new(ErrorKind::ConfigInvalid, "username is empty")
+ .with_operation("Builder::build")
+ .with_context("service", SEAFILE_SCHEME)
+ })?;
+ let password = self.config.password.ok_or_else(|| {
+ Error::new(ErrorKind::ConfigInvalid, "password is empty")
+ .with_operation("Builder::build")
+ .with_context("service", SEAFILE_SCHEME)
+ })?;
+
SeafileCredentialProvider::Account(AccountTokenCredentialProvider::new(
+ endpoint.clone(),
+ username,
+ password,
+ ))
+ }
+ };
Ok(SeafileBackend {
core: Arc::new(SeafileCore {
@@ -174,10 +202,9 @@ impl Builder for SeafileBuilder {
},
root,
endpoint,
- username,
- password,
- repo_name: self.config.repo_name.clone(),
- auth_info: Arc::new(OnceCell::new()),
+ repo_name: self.config.repo_name,
+ credential_provider,
+ auth_info: HttpTransportCache::new(),
}),
})
}
diff --git a/core/services/seafile/src/config.rs
b/core/services/seafile/src/config.rs
index 57e9b85e5f..476fb3c550 100644
--- a/core/services/seafile/src/config.rs
+++ b/core/services/seafile/src/config.rs
@@ -88,7 +88,10 @@ impl opendal_core::Configurator for SeafileConfig {
}
fn into_builder(self) -> Self::Builder {
- SeafileBuilder { config: self }
+ SeafileBuilder {
+ config: self,
+ ..Default::default()
+ }
}
}
diff --git a/core/services/seafile/src/core.rs
b/core/services/seafile/src/core.rs
index dced27943a..7a36bdbd0d 100644
--- a/core/services/seafile/src/core.rs
+++ b/core/services/seafile/src/core.rs
@@ -25,29 +25,37 @@ use http::Request;
use http::Response;
use http::StatusCode;
use http::header;
+use reqsign_core::HttpSend;
+use reqsign_core::ProvideCredentialDyn;
+use reqsign_core::Signer;
+use reqsign_seafile::AccountTokenCredentialProvider;
+use reqsign_seafile::Credential;
+use reqsign_seafile::RequestSigner;
use serde::Deserialize;
use opendal_core::raw::*;
use opendal_core::*;
/// Core of [seafile](https://www.seafile.com) services support.
-#[derive(Clone)]
pub struct SeafileCore {
pub info: ServiceInfo,
pub capability: Capability,
- /// The root of this core.
pub root: String,
- /// The endpoint of this backend.
pub endpoint: String,
- /// The username of this backend.
- pub username: String,
- /// The password id of this backend.
- pub password: String,
- /// The repo name of this backend.
pub repo_name: String,
+ pub(super) credential_provider: SeafileCredentialProvider,
+ pub(super) auth_info: HttpTransportCache<Arc<OnceCell<AuthInfo>>>,
+}
- /// Authentication and library information published after both requests
succeed.
- pub auth_info: Arc<OnceCell<AuthInfo>>,
+pub(super) enum SeafileCredentialProvider {
+ Account(AccountTokenCredentialProvider),
+ Custom(Arc<dyn ProvideCredentialDyn<Credential = Credential>>),
+}
+
+#[derive(Clone)]
+pub(super) struct AuthInfo {
+ repo_id: String,
+ signer: Signer<Credential>,
}
impl Debug for SeafileCore {
@@ -55,104 +63,82 @@ impl Debug for SeafileCore {
f.debug_struct("SeafileCore")
.field("root", &self.root)
.field("endpoint", &self.endpoint)
- .field("username", &self.username)
.field("repo_name", &self.repo_name)
.finish_non_exhaustive()
}
}
impl SeafileCore {
- #[inline]
- pub async fn send(
- &self,
- ctx: &OperationContext,
- req: Request<Buffer>,
- ) -> Result<Response<Buffer>> {
- ctx.http_transport().send(req).await
- }
-
- /// Initialize authentication and library information, retrying incomplete
attempts.
- pub async fn get_auth_info(&self, ctx: &OperationContext) ->
Result<AuthInfo> {
- let auth_info = self
+ async fn get_auth_info(&self, ctx: &OperationContext) -> Result<AuthInfo> {
+ let auth_cell = self
.auth_info
+ .get_or_init(ctx.http_transport(), |_| Arc::new(OnceCell::new()));
+ let auth_info = auth_cell
.get_or_try_init(async || {
- let body = format!(
- "username={}&password={}",
- percent_encode_path(&self.username),
- percent_encode_path(&self.password)
- );
- let req = Request::post(format!("{}/api2/auth-token/",
self.endpoint))
- .header(header::CONTENT_TYPE,
"application/x-www-form-urlencoded")
- .body(Buffer::from(Bytes::from(body)))
- .map_err(new_request_build_error)?;
-
- let resp = ctx.http_transport().send(req).await?;
- let status = resp.status();
-
- let token = match status {
- StatusCode::OK => {
- let resp_body = resp.into_body();
- let auth_response: AuthTokenResponse =
- serde_json::from_reader(resp_body.reader())
- .map_err(new_json_deserialize_error)?;
- auth_response.token
- }
- _ => {
- return Err(parse_error(
- ErrorContext::new(ServiceOperation("AuthToken")),
- resp,
- ));
- }
+ // A failed or cancelled lookup must discard the signer's
cached token.
+ let transport =
WeakHttpTransporter::downgrade(ctx.http_transport());
+ let sign_ctx = reqsign_context();
+ let signer = match &self.credential_provider {
+ SeafileCredentialProvider::Account(provider) =>
Signer::new(
+
sign_ctx.with_http_send(AccountTokenTransport(transport)),
+ provider.clone(),
+ RequestSigner,
+ ),
+ SeafileCredentialProvider::Custom(provider) => Signer::new(
+ sign_ctx.with_http_send(transport),
+ provider.clone(),
+ RequestSigner,
+ ),
};
- let url = format!("{}/api2/repos", self.endpoint);
-
- let req = Request::get(url)
- .header(header::AUTHORIZATION, format!("Token {token}"))
+ let req = Request::get(format!("{}/api2/repos", self.endpoint))
.body(Buffer::new())
.map_err(new_request_build_error)?;
-
- let resp = ctx.http_transport().send(req).await?;
-
- let status = resp.status();
-
- let mut repo_id = String::new();
- match status {
- StatusCode::OK => {
- let resp_body = resp.into_body();
- let list_library_response: Vec<ListLibraryResponse> =
- serde_json::from_reader(resp_body.reader())
- .map_err(new_json_deserialize_error)?;
-
- for library in list_library_response {
- if library.name == self.repo_name {
- repo_id = library.id;
- break;
- }
- }
-
- // repo not found
- if repo_id.is_empty() {
- return Err(Error::new(
- ErrorKind::NotFound,
- format!("repo {} not found", self.repo_name),
- ));
- }
- }
- _ => {
- return Err(parse_error(
-
ErrorContext::new(ServiceOperation("ListRepositories")),
- resp,
- ));
- }
+ let resp = send_api(ctx, &signer, req).await?;
+ if resp.status() != StatusCode::OK {
+ return Err(parse_error(
+
ErrorContext::new(ServiceOperation("ListRepositories")),
+ resp,
+ ));
}
- Ok(AuthInfo { repo_id, token })
+
+ let libraries: Vec<ListLibraryResponse> =
+ serde_json::from_reader(resp.into_body().reader())
+ .map_err(new_json_deserialize_error)?;
+ let repo_id = libraries
+ .into_iter()
+ .find(|library| library.name == self.repo_name)
+ .map(|library| library.id)
+ .filter(|id| !id.is_empty())
+ .ok_or_else(|| {
+ Error::new(
+ ErrorKind::NotFound,
+ format!("repo {} not found", self.repo_name),
+ )
+ })?;
+
+ Ok(AuthInfo { repo_id, signer })
})
.await?;
Ok(auth_info.clone())
}
}
+async fn send_api(
+ ctx: &OperationContext,
+ signer: &Signer<Credential>,
+ req: Request<Buffer>,
+) -> Result<Response<Buffer>> {
+ let (mut parts, body) = req.into_parts();
+ signer
+ .sign(&mut parts, None)
+ .await
+ .map_err(map_sign_error)?;
+ ctx.http_transport()
+ .send(Request::from_parts(parts, body))
+ .await
+}
+
impl SeafileCore {
/// get upload url
async fn get_upload_url(&self, ctx: &OperationContext) -> Result<String> {
@@ -164,13 +150,12 @@ impl SeafileCore {
));
let req = req
- .header(header::AUTHORIZATION, format!("Token {}",
auth_info.token))
.extension(Operation::Write)
.extension(ServiceOperation("GetUploadLink"))
.body(Buffer::new())
.map_err(new_request_build_error)?;
- let resp = self.send(ctx, req).await?;
+ let resp = send_api(ctx, &auth_info.signer, req).await?;
let status = resp.status();
match status {
@@ -223,7 +208,7 @@ impl SeafileCore {
let req = multipart.apply(req)?;
- self.send(ctx, req).await
+ ctx.http_transport().send(req).await
}
pub async fn create_dir(&self, ctx: &OperationContext, path: &str) ->
Result<()> {
@@ -243,14 +228,13 @@ impl SeafileCore {
));
let req = req
- .header(header::AUTHORIZATION, format!("Token {}",
auth_info.token))
.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
.extension(Operation::CreateDir)
.extension(ServiceOperation("Mkdir"))
.body(body)
.map_err(new_request_build_error)?;
- let resp = self.send(ctx, req).await?;
+ let resp = send_api(ctx, &auth_info.signer, req).await?;
match resp.status() {
StatusCode::OK | StatusCode::CREATED => Ok(()),
@@ -274,13 +258,12 @@ impl SeafileCore {
));
let req = req
- .header(header::AUTHORIZATION, format!("Token {}",
auth_info.token))
.extension(Operation::Read)
.extension(ServiceOperation("GetDownloadLink"))
.body(Buffer::new())
.map_err(new_request_build_error)?;
- let resp = self.send(ctx, req).await?;
+ let resp = send_api(ctx, &auth_info.signer, req).await?;
let status = resp.status();
match status {
@@ -332,13 +315,12 @@ impl SeafileCore {
));
let req = req
- .header(header::AUTHORIZATION, format!("Token {}",
auth_info.token))
.extension(Operation::Stat)
.extension(ServiceOperation("GetFileDetail"))
.body(Buffer::new())
.map_err(new_request_build_error)?;
- let resp = self.send(ctx, req).await?;
+ let resp = send_api(ctx, &auth_info.signer, req).await?;
let status = resp.status();
match status {
@@ -368,13 +350,12 @@ impl SeafileCore {
));
let req = req
- .header(header::AUTHORIZATION, format!("Token {}",
auth_info.token))
.extension(Operation::Stat)
.extension(ServiceOperation("GetDirDetail"))
.body(Buffer::new())
.map_err(new_request_build_error)?;
- let resp = self.send(ctx, req).await?;
+ let resp = send_api(ctx, &auth_info.signer, req).await?;
let status = resp.status();
match status {
@@ -413,13 +394,12 @@ impl SeafileCore {
let req = Request::delete(url);
let req = req
- .header(header::AUTHORIZATION, format!("Token {}",
auth_info.token))
.extension(Operation::Delete)
.extension(ServiceOperation("Delete"))
.body(Buffer::new())
.map_err(new_request_build_error)?;
- let resp = self.send(ctx, req).await?;
+ let resp = send_api(ctx, &auth_info.signer, req).await?;
let status = resp.status();
@@ -447,13 +427,12 @@ impl SeafileCore {
let req = Request::get(url);
let req = req
- .header(header::AUTHORIZATION, format!("Token {}",
auth_info.token))
.extension(Operation::List)
.extension(ServiceOperation("ListDir"))
.body(Buffer::new())
.map_err(new_request_build_error)?;
- let resp = self.send(ctx, req).await?;
+ let resp = send_api(ctx, &auth_info.signer, req).await?;
match resp.status() {
StatusCode::OK => {
@@ -478,11 +457,6 @@ impl SeafileCore {
}
}
-#[derive(Deserialize)]
-pub struct AuthTokenResponse {
- pub token: String,
-}
-
#[derive(Deserialize)]
pub struct FileDetail {
pub last_modified: String,
@@ -509,14 +483,6 @@ pub fn parse_file_detail(file_detail: FileDetail) ->
Result<Metadata> {
Ok(md.build())
}
-#[derive(Clone)]
-pub struct AuthInfo {
- /// The repo id of this auth info.
- pub repo_id: String,
- /// The token of this auth info,
- pub token: String,
-}
-
#[derive(Deserialize)]
pub struct ListLibraryResponse {
pub name: String,
@@ -546,45 +512,115 @@ struct SeafileError {
/// Context needed to classify an error from this service.
#[derive(Clone, Copy, Debug)]
-pub(crate) struct ErrorContext {
- service_operation: ServiceOperation,
+pub(crate) enum ErrorContext {
+ AuthToken,
+ Operation(ServiceOperation),
}
impl ErrorContext {
pub(crate) const fn new(service_operation: ServiceOperation) -> Self {
- Self { service_operation }
+ Self::Operation(service_operation)
}
}
+// Reqsign's provider does not expose non-200 responses to the caller. Parse
+// them here so the signer's error retains OpenDAL's account exchange
diagnostics.
+#[derive(Debug)]
+struct AccountTokenTransport(WeakHttpTransporter);
+
+impl HttpSend for AccountTokenTransport {
+ async fn http_send(&self, req: Request<Bytes>) ->
reqsign_core::Result<Response<Bytes>> {
+ let resp = self.0.http_send(req).await?;
+ let status = resp.status();
+ if status == StatusCode::OK {
+ return Ok(resp);
+ }
+
+ let error = parse_error(ErrorContext::AuthToken,
resp.map(Buffer::from));
+ Err(
+ reqsign_core::Error::unexpected(format!("Seafile AuthToken
returned HTTP {status}"))
+ .set_retryable(error.is_temporary())
+ .with_source(error),
+ )
+ }
+}
+
+fn map_sign_error(err: reqsign_core::Error) -> Error {
+ let source = std::error::Error::source(&err).and_then(|source|
source.downcast_ref::<Error>());
+ let (kind, message) = if let Some(source) = source {
+ (source.kind(), source.message())
+ } else if err.kind() == reqsign_core::ErrorKind::PermissionDenied {
+ (ErrorKind::PermissionDenied, "signing Seafile API request")
+ } else {
+ return new_request_sign_error(err.into());
+ };
+ Error::new(kind, message)
+ .with_temporary(err.is_retryable())
+ .with_persistent(source.is_some_and(Error::is_persistent))
+ .set_source(err)
+}
+
/// Parse an error response using its service request context.
pub(crate) fn parse_error(ctx: ErrorContext, resp: Response<Buffer>) -> Error {
let (parts, body) = resp.into_parts();
- let bs = body.to_bytes();
-
+ let body = body.to_bytes();
let (kind, retryable) = match parts.status.as_u16() {
403 => (ErrorKind::PermissionDenied, false),
404 => (ErrorKind::NotFound, false),
416 => (ErrorKind::RangeNotSatisfied, false),
- // Seafile reports a transient backend failure as a 5xx, including its
own 520;
- // retrying is the documented recovery, so mark these temporary.
+ // Seafile documents retries for transient backend failures, including
its own 520.
500 | 502 | 503 | 504 | 520 => (ErrorKind::Unexpected, true),
_ => (ErrorKind::Unexpected, false),
};
- let (message, _seafile_err) = serde_json::from_reader::<_,
SeafileError>(bs.clone().reader())
- .map(|seafile_err| (format!("{seafile_err:?}"), Some(seafile_err)))
- .unwrap_or_else(|_| (String::from_utf8_lossy(&bs).into_owned(), None));
-
- let mut err = Error::new(kind, message);
+ let error = match ctx {
+ ErrorContext::AuthToken => {
+ Error::new(kind, account_token_error_message(&parts.headers,
&body))
+ .with_context("service_operation", "AuthToken")
+ .with_context("status", parts.status)
+ }
+ ErrorContext::Operation(operation) => {
+ let message = serde_json::from_slice::<SeafileError>(&body)
+ .map(|seafile_error| format!("{seafile_error:?}"))
+ .unwrap_or_else(|_|
String::from_utf8_lossy(&body).into_owned());
+ let error = Error::new(kind,
message).with_context("service_operation", operation.0);
+ with_error_response_context(error, parts)
+ }
+ };
+ error.with_temporary(retryable)
+}
- err = err.with_context("service_operation", ctx.service_operation.0);
- err = with_error_response_context(err, parts);
+fn account_token_error_message(headers: &http::HeaderMap, body: &[u8]) ->
&'static str {
+ if headers.contains_key("x-seafile-otp") {
+ return "Seafile requires two-factor authentication for account login";
+ }
- if retryable {
- err = err.set_temporary();
+ #[derive(Deserialize)]
+ struct AccountTokenError {
+ error_msg: Option<String>,
+ #[serde(default)]
+ non_field_errors: Vec<String>,
}
- err
+ // A login failure can echo credentials in its body or carry session
headers.
+ // Use only fixed Seafile diagnostics for this endpoint.
+ let fallback = "Seafile account token exchange failed";
+ let Ok(error) = serde_json::from_slice::<AccountTokenError>(body) else {
+ return fallback;
+ };
+ [
+ "Unable to login with provided credentials.",
+ "User account is disabled.",
+ ]
+ .into_iter()
+ .find(|message| {
+ error.error_msg.as_deref() == Some(*message)
+ || error
+ .non_field_errors
+ .iter()
+ .any(|detail| detail == *message)
+ })
+ .unwrap_or(fallback)
}
#[cfg(test)]
@@ -611,80 +647,108 @@ mod tests {
assert!(!err.is_temporary());
}
+ type AuthResponse = (&'static str, Option<&'static str>, &'static str);
+
#[derive(Clone)]
struct AuthTransport {
- responses: Arc<Mutex<VecDeque<(&'static str, &'static str)>>>,
+ responses: Arc<Mutex<VecDeque<AuthResponse>>>,
repositories: Arc<Semaphore>,
+ status: StatusCode,
+ headers: http::HeaderMap,
}
impl AuthTransport {
- fn new(responses: &[(&'static str, &'static str)]) -> Self {
+ fn new(responses: &[AuthResponse]) -> Self {
Self {
responses:
Arc::new(Mutex::new(responses.iter().copied().collect())),
repositories: Arc::new(Semaphore::new(0)),
+ status: StatusCode::OK,
+ headers: http::HeaderMap::new(),
}
}
+
+ fn context(&self) -> OperationContext {
+
OperationContext::new().with_http_transport(HttpTransporter::new(self.clone()))
+ }
}
impl HttpTransport for AuthTransport {
async fn fetch(&self, req: Request<Buffer>) ->
Result<Response<HttpBody>> {
- let (path, body) =
self.responses.lock().await.pop_front().unwrap();
+ let (path, authorization, body) =
self.responses.lock().await.pop_front().unwrap();
assert_eq!(req.uri().path(), path);
+ let header = req.headers().get(header::AUTHORIZATION);
+ assert_eq!(header.map(|value| value.to_str().unwrap()),
authorization);
if path == "/api2/repos" {
drop(self.repositories.acquire(1).await);
}
- Ok(Response::builder()
+ let mut response = Response::builder()
+ .status(self.status)
.body(HttpBody::new(
futures::stream::iter([Ok(Buffer::from(Bytes::from_static(body.as_bytes())))]),
Some(body.len() as u64),
))
- .unwrap())
+ .unwrap();
+ response.headers_mut().clone_from(&self.headers);
+ Ok(response)
}
}
- fn auth_core(transport: AuthTransport) -> (SeafileCore, OperationContext) {
- let core = SeafileCore {
+ fn auth_core() -> SeafileCore {
+ let endpoint = "http://example.com";
+ SeafileCore {
info: ServiceInfo::new("seafile", "/", ""),
capability: Capability::default(),
root: "/".to_string(),
- endpoint: "http://example.com".to_string(),
- username: "user".to_string(),
- password: "password".to_string(),
+ endpoint: endpoint.to_string(),
repo_name: "test".to_string(),
- auth_info: Arc::new(OnceCell::new()),
- };
- let ctx =
OperationContext::new().with_http_transport(HttpTransporter::new(transport));
- (core, ctx)
+ credential_provider: SeafileCredentialProvider::Account(
+ AccountTokenCredentialProvider::new(endpoint, "user",
"example-secret"),
+ ),
+ auth_info: HttpTransportCache::new(),
+ }
}
#[tokio::test]
async fn test_auth_info_retries_after_missing_repository() {
let transport = AuthTransport::new(&[
- ("/api2/auth-token/", r#"{"token":"first"}"#),
- ("/api2/repos", "[]"),
- ("/api2/auth-token/", r#"{"token":"second"}"#),
- ("/api2/repos", r#"[{"name":"test","id":"repo-id"}]"#),
+ ("/api2/auth-token/", None, r#"{"token":"first"}"#),
+ ("/api2/repos", Some("Token first"), "[]"),
+ ("/api2/auth-token/", None, r#"{"token":"second"}"#),
+ (
+ "/api2/repos",
+ Some("Token second"),
+ r#"[{"name":"test","id":"repo-id"}]"#,
+ ),
]);
transport.repositories.release(1);
- let (core, ctx) = auth_core(transport.clone());
+ let core = auth_core();
+ let ctx = transport.context();
let err = core.get_auth_info(&ctx).await.err().unwrap();
assert_eq!(err.kind(), ErrorKind::NotFound);
let auth = core.get_auth_info(&ctx).await.unwrap();
assert_eq!(auth.repo_id, "repo-id");
- assert_eq!(auth.token, "second");
assert!(transport.responses.lock().await.is_empty());
}
#[tokio::test]
async fn test_auth_info_retries_after_initialization_is_cancelled() {
let transport = AuthTransport::new(&[
- ("/api2/auth-token/", r#"{"token":"first"}"#),
- ("/api2/repos", r#"[{"name":"test","id":"repo-id"}]"#),
- ("/api2/auth-token/", r#"{"token":"second"}"#),
- ("/api2/repos", r#"[{"name":"test","id":"repo-id"}]"#),
+ ("/api2/auth-token/", None, r#"{"token":"first"}"#),
+ (
+ "/api2/repos",
+ Some("Token first"),
+ r#"[{"name":"test","id":"repo-id"}]"#,
+ ),
+ ("/api2/auth-token/", None, r#"{"token":"second"}"#),
+ (
+ "/api2/repos",
+ Some("Token second"),
+ r#"[{"name":"test","id":"repo-id"}]"#,
+ ),
]);
- let (core, ctx) = auth_core(transport.clone());
+ let core = auth_core();
+ let ctx = transport.context();
let mut first = Box::pin(core.get_auth_info(&ctx));
let mut cx = Context::from_waker(Waker::noop());
assert!(first.as_mut().poll(&mut cx).is_pending());
@@ -693,19 +757,25 @@ mod tests {
transport.repositories.release(1);
let auth = core.get_auth_info(&ctx).await.unwrap();
assert_eq!(auth.repo_id, "repo-id");
- assert_eq!(auth.token, "second");
assert!(transport.responses.lock().await.is_empty());
}
#[tokio::test]
async fn test_auth_info_shares_complete_initialization() {
let transport = AuthTransport::new(&[
- ("/api2/auth-token/", r#"{"token":"shared"}"#),
- ("/api2/repos", r#"[{"name":"test","id":"repo-id"}]"#),
+ ("/api2/auth-token/", None, r#"{"token":"shared"}"#),
+ (
+ "/api2/repos",
+ Some("Token shared"),
+ r#"[{"name":"test","id":"repo-id"}]"#,
+ ),
+ ("/api2/repos/repo-id/dir/", Some("Token shared"), "[]"),
]);
- let (core, ctx) = auth_core(transport.clone());
+ let core = auth_core();
+ let ctx = transport.context();
+ let cloned_ctx = ctx.clone();
let mut first = Box::pin(core.get_auth_info(&ctx));
- let mut second = Box::pin(core.get_auth_info(&ctx));
+ let mut second = Box::pin(core.get_auth_info(&cloned_ctx));
let mut cancelled = Box::pin(core.get_auth_info(&ctx));
let mut cx = Context::from_waker(Waker::noop());
assert!(first.as_mut().poll(&mut cx).is_pending());
@@ -716,13 +786,157 @@ mod tests {
transport.repositories.release(1);
let (first, second) = tokio::join!(first, second);
for auth in [first, second, core.get_auth_info(&ctx).await] {
- let auth = auth.unwrap();
- assert_eq!(auth.repo_id, "repo-id");
- assert_eq!(auth.token, "shared");
+ assert_eq!(auth.unwrap().repo_id, "repo-id");
}
+ core.list(&cloned_ctx, "/").await.unwrap();
assert!(transport.responses.lock().await.is_empty());
}
+ #[tokio::test]
+ async fn test_auth_info_isolated_by_transport() {
+ let first = AuthTransport::new(&[
+ ("/api2/auth-token/", None, r#"{"token":"first"}"#),
+ (
+ "/api2/repos",
+ Some("Token first"),
+ r#"[{"name":"test","id":"first-repo"}]"#,
+ ),
+ ("/api2/repos/first-repo/dir/", Some("Token first"), "[]"),
+ ("/api2/repos/first-repo/dir/", Some("Token first"), "[]"),
+ ]);
+ let second = AuthTransport::new(&[
+ ("/api2/auth-token/", None, r#"{"token":"second"}"#),
+ (
+ "/api2/repos",
+ Some("Token second"),
+ r#"[{"name":"test","id":"second-repo"}]"#,
+ ),
+ ("/api2/repos/second-repo/dir/", Some("Token second"), "[]"),
+ ]);
+ first.repositories.release(1);
+ second.repositories.release(1);
+ let core = auth_core();
+ let first_ctx = first.context();
+ let second_ctx = second.context();
+
+ core.list(&first_ctx, "/").await.unwrap();
+ core.list(&second_ctx, "/").await.unwrap();
+ core.list(&first_ctx, "/").await.unwrap();
+ assert!(first.responses.lock().await.is_empty());
+ assert!(second.responses.lock().await.is_empty());
+ }
+
+ #[tokio::test]
+ async fn test_account_exchange_errors() {
+ let core = auth_core();
+ for (status, kind, retryable, body, otp_required, expected) in [
+ (
+ StatusCode::BAD_REQUEST,
+ ErrorKind::Unexpected,
+ false,
+ r#"{"non_field_errors":["Unable to login with provided
credentials."],"token":"body-canary"}"#,
+ false,
+ "Unable to login with provided credentials.",
+ ),
+ (
+ StatusCode::BAD_REQUEST,
+ ErrorKind::Unexpected,
+ false,
+ "",
+ true,
+ "Seafile requires two-factor authentication for account login",
+ ),
+ (
+ StatusCode::FORBIDDEN,
+ ErrorKind::PermissionDenied,
+ false,
+ r#"{"error_msg":"User account is disabled."}"#,
+ false,
+ "User account is disabled.",
+ ),
+ (
+ StatusCode::NOT_FOUND,
+ ErrorKind::NotFound,
+ false,
+ "<html>body-canary</html>",
+ false,
+ "Seafile account token exchange failed",
+ ),
+ (
+ StatusCode::SERVICE_UNAVAILABLE,
+ ErrorKind::Unexpected,
+ true,
+ r#"{"error_msg":"body-canary"}"#,
+ false,
+ "Seafile account token exchange failed",
+ ),
+ (
+ StatusCode::from_u16(520).unwrap(),
+ ErrorKind::Unexpected,
+ true,
+ "",
+ false,
+ "Seafile account token exchange failed",
+ ),
+ ] {
+ let mut transport = AuthTransport::new(&[("/api2/auth-token/",
None, body)]);
+ transport.status = status;
+ let value = header::HeaderValue::from_static("header-canary");
+ transport.headers.insert("x-seafile-s2fa", value.clone());
+ if otp_required {
+ transport.headers.insert("x-seafile-otp", value);
+ }
+ let err = core
+ .get_auth_info(&transport.context())
+ .await
+ .err()
+ .unwrap();
+ assert_eq!(err.kind(), kind);
+ assert_eq!(err.is_temporary(), retryable);
+ assert_eq!(err.message(), expected);
+ let display = err.to_string();
+ assert!(display.contains(expected));
+ assert!(display.contains(status.as_str()));
+ assert!(display.contains("AuthToken"));
+ for diagnostic in [display, format!("{err:?}"),
format!("{err:#?}")] {
+ assert!(!diagnostic.contains("body-canary"));
+ assert!(!diagnostic.contains("header-canary"));
+ }
+ assert!(transport.responses.lock().await.is_empty());
+ }
+ }
+
+ #[tokio::test]
+ async fn test_login_preserves_transport_error() {
+ struct FailedLoginTransport {
+ temporary: bool,
+ }
+
+ impl HttpTransport for FailedLoginTransport {
+ async fn fetch(&self, req: Request<Buffer>) ->
Result<Response<HttpBody>> {
+ assert_eq!(req.uri().path(), "/api2/auth-token/");
+ Err(
+ Error::new(ErrorKind::RateLimited, "fixture transport is
throttled")
+ .with_temporary(self.temporary)
+ .with_persistent(!self.temporary)
+ .set_source(std::io::Error::other("fixture transport
cause")),
+ )
+ }
+ }
+
+ let core = auth_core();
+ for temporary in [true, false] {
+ let transport = HttpTransporter::new(FailedLoginTransport {
temporary });
+ let ctx = OperationContext::new().with_http_transport(transport);
+ let err = core.get_auth_info(&ctx).await.err().unwrap();
+ assert_eq!(err.kind(), ErrorKind::RateLimited);
+ assert_eq!(err.message(), "fixture transport is throttled");
+ assert_eq!(err.is_temporary(), temporary);
+ assert_eq!(err.is_persistent(), !temporary);
+ assert!(format!("{err:?}").contains("fixture transport cause"));
+ }
+ }
+
#[tokio::test]
async fn test_parse_error() {
let err_res = vec![
diff --git a/core/services/seafile/src/docs.md
b/core/services/seafile/src/docs.md
index f8d89ad650..57bbc19c98 100644
--- a/core/services/seafile/src/docs.md
+++ b/core/services/seafile/src/docs.md
@@ -21,7 +21,16 @@ Use [`crate::SeafileConfig`] for serializable configuration
and this builder's
methods for direct construction. The field and method documentation defines
accepted values, defaults, and environment interaction.
-Authentication and library lookup are initialized together on first use.
Failed or cancelled initialization can be retried by a subsequent operation;
successful initialization is shared by an operator and its clones.
+The service logs in with the configured username and password by default. Use
+[`Seafile::credential_provider`](crate::Seafile::credential_provider) to supply
+an account token through Reqsign. The service finds the library by its exact
+name and returns [`opendal_core::ErrorKind::NotFound`] if the account cannot
see
+that library.
+
+The service initializes authentication and library lookup together on first use
+of each HTTP transport. A later operation can retry failed or cancelled
+initialization. Operators that share the same transport and service instance
+also share successful initialization.
## Example
diff --git a/core/services/seafile/src/lib.rs b/core/services/seafile/src/lib.rs
index e61b3363ba..30a959cfd0 100644
--- a/core/services/seafile/src/lib.rs
+++ b/core/services/seafile/src/lib.rs
@@ -43,3 +43,8 @@ mod writer;
pub use backend::SeafileBuilder as Seafile;
pub use config::SeafileConfig;
+
+/// Reqsign types for use with [`Seafile::credential_provider`].
+/// Implement providers against this re-export and
[`opendal_core::reqsign_core`]
+/// so their types match those used by this service.
+pub use reqsign_seafile;