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
41 changes: 23 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,14 @@ The simplest way to use `reqsign` is with the default signers provided by each s

```rust
use anyhow::Result;
use reqsign::aws;
use reqsign::{aws, default_context};

#[tokio::main]
async fn main() -> Result<()> {
// Create a default signer for S3 in us-east-1
// This will automatically:
// - Load credentials from environment variables, config files, or IAM roles
// - Set up the default HTTP client and file reader
let signer = aws::default_signer("s3", "us-east-1");
// Create a default runtime context (HTTP client, file reader, OS env, command execution)
let ctx = default_context();
// Create a default signer for S3 in us-east-1 using the supplied context
let signer = aws::default_signer(ctx, "s3", "us-east-1");

// Build your request
let mut req = http::Request::builder()
Expand Down Expand Up @@ -100,15 +99,15 @@ async fn main() -> Result<()> {
You can also customize the default signers using the `with_*` methods:

```rust
use reqsign::aws;
use reqsign::{aws, default_context};
use reqsign_aws_v4::StaticCredentialProvider;

// Start with default signer and customize specific components
let signer = aws::default_signer("s3", "us-east-1")
let ctx = default_context();
let signer = aws::default_signer(ctx, "s3", "us-east-1")
.with_credential_provider(StaticCredentialProvider::new(
"my-access-key",
"my-secret-key",
None, // Optional session token
));
```

Expand All @@ -121,24 +120,28 @@ For server applications that already hold an OIDC assertion, see

```rust
use reqsign::aws::v4a::{SigningRegionSet, default_signer};
use reqsign::default_context;

let ctx = default_context();
let region_set = SigningRegionSet::new("us-east-1,us-west-2")?;
let signer = default_signer("s3", region_set);
let signer = default_signer(ctx, "s3", region_set);
# Ok::<(), reqsign_core::Error>(())
```

#### Azure Storage

```rust
use reqsign::azure;
use reqsign::{azure, default_context};

let ctx = default_context();

// Default signer for Azure Storage
let signer = azure::default_signer();
let signer = azure::default_signer(ctx.clone());

// With custom credentials
use reqsign_azure_storage::StaticCredentialProvider;
let signer = azure::default_signer()
.with_credential_provider(StaticCredentialProvider::new(
let signer = azure::default_signer(ctx)
.with_credential_provider(StaticCredentialProvider::new_shared_key(
"account-name",
"account-key",
));
Expand All @@ -147,19 +150,21 @@ let signer = azure::default_signer()
#### Google Cloud

```rust
use reqsign::google;
use reqsign::{default_context, google};

// Default signer for Google Cloud Storage
let signer = google::default_signer("storage.googleapis.com");
let ctx = default_context();
let signer = google::default_signer(ctx, "storage.googleapis.com");
```

#### Aliyun OSS

```rust
use reqsign::aliyun;
use reqsign::{aliyun, default_context};

// Default signer for Aliyun OSS
let signer = aliyun::default_signer("mybucket");
let ctx = default_context();
let signer = aliyun::default_signer(ctx, "mybucket");
```

## Features
Expand Down
86 changes: 80 additions & 6 deletions core/src/signer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,10 @@ impl<K: SigningCredential> Signer<K> {
}
}

/// Replace the context while keeping the credential provider, request signer,
/// and shared credential cache.
/// Replace the context and create an isolated empty credential cache.
pub fn with_context(mut self, ctx: Context) -> Self {
self.ctx = ctx;
self.credential = Arc::new(Mutex::new(None));
self
}

Expand All @@ -83,7 +83,8 @@ impl<K: SigningCredential> Signer<K> {
self
}

/// Replace the request signer while keeping context and credential provider.
/// Replace only the request signer, retaining the context, credential provider,
/// and shared credential cache.
pub fn with_request_signer(mut self, signer: impl SignRequest<Credential = K>) -> Self {
self.builder = Arc::new(signer);
self
Expand Down Expand Up @@ -180,12 +181,12 @@ impl<K: SigningCredential> Signer<K> {
mod tests {
use super::*;
use crate::time::Timestamp;
use crate::{ErrorKind, ProvideCredential, SignRequest};
use crate::{ErrorKind, ProvideCredential, SignRequest, StaticEnv};
use asyncband::oneshot;
use futures::future::{join_all, pending};
use futures::poll;
use http::{HeaderValue, Method, Request, Version};
use std::collections::VecDeque;
use std::collections::{HashMap, VecDeque};
use std::sync::Mutex as StdMutex;
use std::sync::atomic::{AtomicUsize, Ordering};

Expand Down Expand Up @@ -868,14 +869,87 @@ mod tests {
let with_provider = signer.clone().with_credential_provider(StaticProvider);

assert!(Arc::ptr_eq(&signer.credential, &clone.credential));
assert!(Arc::ptr_eq(&signer.credential, &with_context.credential));
assert!(!Arc::ptr_eq(&signer.credential, &with_context.credential));
assert!(Arc::ptr_eq(
&signer.credential,
&with_request_signer.credential
));
assert!(!Arc::ptr_eq(&signer.credential, &with_provider.credential));
}

#[test]
fn with_context_isolates_credential_cache() {
#[derive(Debug)]
struct EnvGenerationProvider {
calls: Arc<AtomicUsize>,
base: Timestamp,
}

impl ProvideCredential for EnvGenerationProvider {
type Credential = ExpiringCredential;

async fn provide_credential(&self, ctx: &Context) -> Result<Option<Self::Credential>> {
self.calls.fetch_add(1, Ordering::SeqCst);
let generation = ctx
.env_var("GENERATION")
.expect("generation env must be set")
.parse::<u8>()
.expect("generation env must be u8");
Ok(Some(ExpiringCredential {
generation,
fresh: true,
expires_at: self.base + Duration::from_secs(60),
required_until: self.base + Duration::from_secs(10),
}))
}
}

fn context_with_generation(generation: u8) -> Context {
Context::new().with_env(StaticEnv {
home_dir: None,
envs: HashMap::from([("GENERATION".to_string(), generation.to_string())]),
})
}

futures::executor::block_on(async {
let base = Timestamp::from_second(975).expect("timestamp must be valid");
let calls = Arc::new(AtomicUsize::new(0));
let signer_a = Signer::new(
context_with_generation(1),
EnvGenerationProvider {
calls: calls.clone(),
base,
},
OperationSigner,
);

let mut req_a = request_parts();
signer_a
.sign(&mut req_a, None)
.await
.expect("initial sign under context 1 must succeed");
assert_eq!(req_a.headers["x-credential-generation"], "1");
assert_eq!(calls.load(Ordering::SeqCst), 1);

let signer_b = signer_a.clone().with_context(context_with_generation(2));
let mut req_b = request_parts();
signer_b
.sign(&mut req_b, None)
.await
.expect("sign after with_context must reload under context 2");
assert_eq!(req_b.headers["x-credential-generation"], "2");
assert_eq!(calls.load(Ordering::SeqCst), 2);

let mut req_a_again = request_parts();
signer_a
.sign(&mut req_a_again, None)
.await
.expect("original signer must retain its isolated cache");
assert_eq!(req_a_again.headers["x-credential-generation"], "1");
assert_eq!(calls.load(Ordering::SeqCst), 2);
});
}

#[test]
fn cancelled_refresh_releases_lock_and_waiter_retries() {
futures::executor::block_on(async {
Expand Down
2 changes: 1 addition & 1 deletion docs/caller-provided-subject-tokens.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ credential chain.

Create a new provider and signer for each independently authenticated request
identity. Cloned signers share their exchanged-credential cache, while
`Signer::with_credential_provider` creates a new empty cache.
`Signer::with_context` and `Signer::with_credential_provider` create a new empty cache.

```rust
use reqsign::{Context, Signer, time::Timestamp};
Expand Down
35 changes: 17 additions & 18 deletions reqsign/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,15 +59,14 @@ The easiest way to get started is using the default signers provided for each se

```rust,ignore
use anyhow::Result;
use reqsign::aws;
use reqsign::{aws, default_context};

#[tokio::main]
async fn main() -> Result<()> {
// Create a default signer for AWS S3 in us-east-1
// This will automatically:
// - Set up HTTP client and file reader
// - Load credentials from environment, config files, or instance metadata
let signer = aws::default_signer("s3", "us-east-1");
// Create a default runtime context (HTTP client, file reader, OS env, command execution)
let ctx = default_context();
// Create a default signer for AWS S3 in us-east-1 using the supplied context
let signer = aws::default_signer(ctx, "s3", "us-east-1");

// Build and sign a request
let mut req = http::Request::builder()
Expand Down Expand Up @@ -136,14 +135,12 @@ You can customize the default signers using the `with_*` methods:
use reqsign::aws;
use reqsign::aws::StaticCredentialProvider;

// Start with default signer and customize components
let signer = aws::default_signer("s3", "us-east-1")
// Pass a custom context directly and customize components as needed
let signer = aws::default_signer(my_custom_context, "s3", "us-east-1")
.with_credential_provider(StaticCredentialProvider::new(
"my-access-key",
"my-secret-key",
None, // Optional session token
))
.with_context(my_custom_context);
));
```

For server applications that already hold an OIDC assertion, see
Expand All @@ -152,33 +149,35 @@ For server applications that already hold an OIDC assertion, see
### Examples for Other Services

```rust,ignore
let ctx = reqsign::default_context();

// Azure Storage
use reqsign::azure;
let signer = azure::default_signer();
let signer = azure::default_signer(ctx.clone());

// Google Cloud
use reqsign::google;
let signer = google::default_signer("storage.googleapis.com");
let signer = google::default_signer(ctx.clone(), "storage.googleapis.com");

// Aliyun OSS
use reqsign::aliyun;
let signer = aliyun::default_signer("mybucket");
let signer = aliyun::default_signer(ctx.clone(), "mybucket");

// Huawei Cloud OBS
use reqsign::huaweicloud;
let signer = huaweicloud::default_signer("mybucket");
let signer = huaweicloud::default_signer(ctx.clone(), "mybucket");

// OpenStack Keystone
use reqsign::openstack;
let signer = openstack::default_signer();
let signer = openstack::default_signer(ctx.clone());

// Tencent COS
use reqsign::tencent;
let signer = tencent::default_signer();
let signer = tencent::default_signer(ctx.clone());

// Oracle Cloud
use reqsign::oracle;
let signer = oracle::default_signer();
let signer = oracle::default_signer(ctx);
```

## Feature Flags
Expand Down
5 changes: 3 additions & 2 deletions reqsign/examples/aws.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,10 @@ use anyhow::Result;
#[tokio::main]
async fn main() -> Result<()> {
// ANCHOR: quickstart
use reqsign::aws;
use reqsign::{aws, default_context};
// Create a default signer for S3 in us-east-1
let signer = aws::default_signer("s3", "us-east-1");
let ctx = default_context();
let signer = aws::default_signer(ctx, "s3", "us-east-1");

// Build a request
let mut req = http::Request::builder()
Expand Down
5 changes: 3 additions & 2 deletions reqsign/examples/azure.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,10 @@ use anyhow::Result;
#[tokio::main]
async fn main() -> Result<()> {
// ANCHOR: quickstart
use reqsign::azure;
use reqsign::{azure, default_context};
// Create a default signer for Azure Storage
let signer = azure::default_signer();
let ctx = default_context();
let signer = azure::default_signer(ctx);

// Build a request
let mut req = http::Request::builder()
Expand Down
5 changes: 3 additions & 2 deletions reqsign/examples/google.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,10 @@ use anyhow::Result;
#[tokio::main]
async fn main() -> Result<()> {
// ANCHOR: quickstart
use reqsign::google;
use reqsign::{default_context, google};
// Create a default signer for Google Cloud Storage
let signer = google::default_signer("storage.googleapis.com");
let ctx = default_context();
let signer = google::default_signer(ctx, "storage.googleapis.com");

// Build a request
let mut req = http::Request::builder()
Expand Down
5 changes: 3 additions & 2 deletions reqsign/examples/presign.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,13 @@
// specific language governing permissions and limitations
// under the License.

use reqsign::aws;
use reqsign::{aws, default_context};
use std::time::Duration;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
let signer = aws::default_signer("s3", "us-east-1");
let ctx = default_context();
let signer = aws::default_signer(ctx, "s3", "us-east-1");
let mut req = http::Request::get("https://s3.amazonaws.com/my-bucket/report.csv")
.body(())?
.into_parts()
Expand Down
4 changes: 3 additions & 1 deletion reqsign/examples/s3_express_sign.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use reqsign::aws::{
self, DefaultCredentialProvider, S3ExpressSessionGrant, S3ExpressSessionMode,
S3ExpressSessionProvider,
};
use reqsign::default_context;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
Expand All @@ -28,7 +29,8 @@ async fn main() -> anyhow::Result<()> {
)
.with_region("us-west-2")
.with_grant(S3ExpressSessionGrant::new(S3ExpressSessionMode::ReadOnly));
let signer = aws::default_signer("s3express", "us-west-2").with_credential_provider(provider);
let signer = aws::default_signer(default_context(), "s3express", "us-west-2")
.with_credential_provider(provider);
let mut req = http::Request::get(
"https://my-bucket--usw2-az1--x-s3.s3express-usw2-az1.us-west-2.amazonaws.com/object",
)
Expand Down
Loading
Loading