Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions THREAT_MODEL.md
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,11 @@ callback. After a successful exchange, restarting with the initially configured
token may require a fresh authorized grant, or an application that manages and
persists its own exchange and supplies an access token.

Baidu Netdisk sends the client secret and single-use refresh token in the query
of its HTTPS token endpoint. The host must serialize each authorization's
exchanges and persist each replacement, including when the access credential
is unusable. Loss of the response before persistence may require reauthorization.

OneDrive follows Microsoft's client types: a public-client exchange sends no
client secret, while a confidential client sends its secret as an RFC 6749 form
field. Microsoft documents no environment variable or shared configuration
Expand Down
2 changes: 1 addition & 1 deletion reqsign/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ This crate provides a unified interface for signing HTTP requests across multipl

- **AWS**: Signature V4 for AWS services
- **Azure**: Azure Storage services
- **Baidu Netdisk**: Static access-token query signing
- **Baidu Netdisk**: Access-token query signing and single-use refresh-token rotation
- **Cloudflare**: Cloudflare API v4 requests with an API token, including KV and D1
- **Dropbox**: OAuth 2.0 bearer authentication
- **GitHub**: GitHub.com bearer tokens and anonymous public access
Expand Down
4 changes: 2 additions & 2 deletions reqsign/src/baidu_netdisk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ pub type DefaultSigner = Signer<Credential>;
///
/// The signer adds the form-encoded `access_token` query parameter to each
/// request and removes any existing `access_token` parameter first. Other
/// query parameters and all headers are preserved. OAuth refresh and token
/// persistence stay with the caller.
/// query parameters and all headers are preserved. For automatic renewal, pass
/// [`RefreshCredentialProvider`] and [`RequestSigner`] to [`Signer::new`].
///
/// # Example
///
Expand Down
8 changes: 8 additions & 0 deletions services/baidu-netdisk/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,19 @@ repository.workspace = true
rust-version.workspace = true

[dependencies]
asyncband = { workspace = true }
form_urlencoded = { workspace = true }
http = { workspace = true }
reqsign-core = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }

[target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies]
jiff = { workspace = true, features = ["js"] }

[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]
bytes = { workspace = true }
tempfile = { workspace = true }
tokio = { workspace = true, features = ["full"] }

[target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dev-dependencies]
Expand Down
25 changes: 10 additions & 15 deletions services/baidu-netdisk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ Baidu Netdisk Open Platform access-token credentials and request signing for
Reqsign.

Baidu Netdisk's xpan APIs authenticate requests with an `access_token` query
parameter. This crate holds the token, supplies it through a static provider,
and signs request heads by appending the form-encoded query parameter.
parameter. Supply a static access token or let the provider obtain one by
exchanging a refresh token.

## Usage

Expand Down Expand Up @@ -39,16 +39,11 @@ URLs and any logs that include the URI as secret-bearing material.

## Credentials

`StaticCredentialProvider` accepts a token that the caller already obtained
through Baidu's Open Platform authorization flow. This crate does not read an
environment variable, a well-known credential file, or an OAuth token endpoint.
It also does not implement OAuth refresh, single-use refresh-token rotation, or
token persistence; those stay with the caller.

An empty token is rejected before it enters the signer's credential cache. The
token has no tracked expiry in this crate, so it is reused for the lifetime of
the `Signer`. Replace the credential provider or create a new signer to use a
different token.
Supply an access token with `StaticCredentialProvider`. For application-managed
renewal, call `exchange_refresh_token` and save the replacement before using
the access credential. For automatic renewal, give `RefreshCredentialProvider`
a callback that saves each replacement.
See the [Baidu Netdisk refresh example](https://reqsign.apache.org/docs/providers/baidu-netdisk/#credentials).

## Request ownership

Expand All @@ -62,9 +57,9 @@ leaving stale authentication parameters.
Query authentication has no separate presign lifetime here, so signing rejects
`expires_in`. Do not forward a signed request to an unrelated host.

`Debug` output for credentials and the static provider never contains the
token. On `wasm32-unknown-unknown`, static credentials and query signing need no
JavaScript clock.
`Debug` output for credentials and providers never contains the
token. On `wasm32-unknown-unknown`, signing with a static token needs no clock.
Refreshing and signing with an expiring credential use the host clock.

## License

Expand Down
24 changes: 21 additions & 3 deletions services/baidu-netdisk/src/credential.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@
// under the License.

use reqsign_core::SigningCredential;
use reqsign_core::time::Timestamp;
use std::fmt::{self, Debug, Formatter};
use std::time::Duration;

/// An access token for the Baidu Netdisk Open Platform.
///
Expand All @@ -27,13 +29,15 @@ use std::fmt::{self, Debug, Formatter};
#[derive(Clone)]
pub struct Credential {
access_token: String,
expires_at: Option<Timestamp>,
}

impl Credential {
/// Create a credential from an access token.
pub fn new(access_token: impl Into<String>) -> Self {
Self {
access_token: access_token.into(),
expires_at: None,
}
}

Expand All @@ -42,8 +46,15 @@ impl Credential {
&self.access_token
}

pub(crate) fn is_valid_token(token: &str) -> bool {
!token.is_empty()
/// Set the absolute expiration of this access token.
pub fn with_expires_at(mut self, expires_at: Timestamp) -> Self {
self.expires_at = Some(expires_at);
self
}

/// Return the absolute expiration, if known.
pub fn expires_at(&self) -> Option<Timestamp> {
self.expires_at
}
}

Expand All @@ -55,6 +66,13 @@ impl Debug for Credential {

impl SigningCredential for Credential {
fn is_valid(&self) -> bool {
Self::is_valid_token(&self.access_token)
!self.access_token.is_empty()
&& self
.expires_at
.is_none_or(|expiry| expiry > Timestamp::now() + Duration::from_secs(120))
}

fn is_valid_at(&self, timestamp: Timestamp) -> bool {
!self.access_token.is_empty() && self.expires_at.is_none_or(|expiry| expiry > timestamp)
}
}
29 changes: 13 additions & 16 deletions services/baidu-netdisk/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,22 +18,16 @@
//! Baidu Netdisk Open Platform access-token credentials and request signing.
//!
//! Baidu Netdisk's xpan APIs authenticate requests with an `access_token`
//! query parameter. [`Credential`] holds the token,
//! [`StaticCredentialProvider`] supplies an explicitly configured token, and
//! [`RequestSigner`] adds the form-encoded parameter to the request URI.
//! query parameter. [`RequestSigner`] adds the form-encoded token to the URI.
//!
//! ## Credential discovery
//!
//! This crate does not read an environment variable, well-known credential
//! file, or OAuth token endpoint for Baidu Netdisk. The caller obtains an
//! access token through Baidu's Open Platform authorization flow and supplies
//! it explicitly. OAuth refresh, single-use refresh-token rotation, and token
//! persistence stay with the caller and are not part of this crate.
//!
//! The token is a secret. `Debug` output for [`Credential`] and
//! [`StaticCredentialProvider`] never contains it. A token without an expiry
//! is reused for the lifetime of the [`reqsign_core::Signer`]. Replacing the
//! signer's credential provider starts a new cache.
//! [`StaticCredentialProvider`] supplies an explicit access token with no
//! tracked expiry. [`RefreshCredentialProvider`] exchanges an AppKey,
//! SecretKey, and single-use refresh token at Baidu's token endpoint. The
//! [`reqsign_core::Signer`] caches the resulting access token and refreshes
//! it on demand within two minutes of expiry. The provider calls a required
//! save callback for each rotation. Hosts managing their own storage can call
//! [`exchange_refresh_token`] directly and persist the replacement before
//! using the returned access credential.
//!
//! ## Request ownership
//!
Expand Down Expand Up @@ -82,8 +76,11 @@
mod credential;
pub use credential::Credential;

mod refresh;
pub use refresh::{RefreshTokenResponse, exchange_refresh_token};

mod provide_credential;
pub use provide_credential::StaticCredentialProvider;
pub use provide_credential::{RefreshCredentialProvider, StaticCredentialProvider};

mod sign_request;
pub use sign_request::RequestSigner;
3 changes: 3 additions & 0 deletions services/baidu-netdisk/src/provide_credential/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,8 @@
// specific language governing permissions and limitations
// under the License.

mod refresh;
pub use refresh::RefreshCredentialProvider;

mod static_provider;
pub use static_provider::StaticCredentialProvider;
114 changes: 114 additions & 0 deletions services/baidu-netdisk/src/provide_credential/refresh.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

use asyncband::mutex::Mutex;
use reqsign_core::time::Timestamp;
use reqsign_core::{Context, Error, ProvideCredential, Result, SigningCredential};
use std::fmt;
use std::mem;
use std::sync::Arc;

use crate::refresh::validate_grant;
use crate::{Credential, RefreshTokenResponse, exchange_refresh_token};

type SaveRefreshToken = dyn Fn(&str) -> Result<()> + Send + Sync;

enum State {
Ready(String),
PendingSave(RefreshTokenResponse),
Spent,
}

/// Renews a Baidu Netdisk access token and hands each rotation to its owner.
/// Provider clones serialize both the exchange and the save callback.
#[derive(Clone)]
pub struct RefreshCredentialProvider {
client_id: String,
client_secret: String,
state: Arc<Mutex<State>>,
save_refresh_token: Arc<SaveRefreshToken>,
}

impl fmt::Debug for RefreshCredentialProvider {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RefreshCredentialProvider")
.finish_non_exhaustive()
}
}

impl RefreshCredentialProvider {
/// Create a provider from the AppKey, SecretKey, current refresh token and a save callback.
///
/// The callback must durably replace the saved refresh token before returning success.
/// If saving fails, the next call retries saving the same replacement before any new
/// exchange. Use one provider per authorization. Callers with asynchronous storage
/// can use [`exchange_refresh_token`] directly.
pub fn new(
client_id: impl Into<String>,
client_secret: impl Into<String>,
refresh_token: impl Into<String>,
save_refresh_token: impl Fn(&str) -> Result<()> + Send + Sync + 'static,
) -> Result<Self> {
let client_id = client_id.into();
let client_secret = client_secret.into();
let refresh_token = refresh_token.into();
validate_grant(&client_id, &client_secret, &refresh_token)?;
Ok(Self {
client_id,
client_secret,
state: Arc::new(Mutex::new(State::Ready(refresh_token))),
save_refresh_token: Arc::new(save_refresh_token),
})
}
}

impl ProvideCredential for RefreshCredentialProvider {
type Credential = Credential;

async fn provide_credential(&self, ctx: &Context) -> Result<Option<Credential>> {
let mut state = self.state.lock().await;
// Leave the token spent if the exchange is cancelled after dispatch.
let rotation = match mem::replace(&mut *state, State::Spent) {
State::Ready(token) => {
exchange_refresh_token(ctx, &self.client_id, &self.client_secret, &token).await?
}
State::PendingSave(rotation) => rotation,
State::Spent => {
return Err(Error::credential_invalid(
"Baidu Netdisk refresh token has already been used; reauthorization required",
));
}
};
if let Err(err) = (self.save_refresh_token)(&rotation.refresh_token) {
*state = State::PendingSave(rotation);
return Err(Error::new(
err.kind(),
"failed to save rotated Baidu Netdisk refresh token",
)
.set_retryable(err.is_retryable()));
}
*state = State::Ready(rotation.refresh_token);
let credential = rotation.credential?;
// A retry of the save may finish long after the exchange.
if !credential.is_valid_at(Timestamp::now()) {
return Err(Error::credential_invalid(
"Baidu Netdisk access token expired before persistence completed",
));
}
Ok(Some(credential))
}
}
Loading
Loading