You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@opendal.apache.org by xu...@apache.org on 2026/03/18 11:08:25 UTC
(opendal-reqsign) branch main updated: refactor(aws-v4): migrate default credential builder (#713)
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-reqsign.git
The following commit(s) were added to refs/heads/main by this push:
new 9fd8cdb refactor(aws-v4): migrate default credential builder (#713)
9fd8cdb is described below
commit 9fd8cdb4cf6df8e5a04d1a65025e93de0673bd89
Author: Xuanwo <gi...@xuanwo.io>
AuthorDate: Wed Mar 18 19:08:21 2026 +0800
refactor(aws-v4): migrate default credential builder (#713)
This updates `services/aws-v4` to the `DefaultCredentialProvider` slot
API defined in `docs/default-credential-provider-api.md`. The builder
now exposes slot and no-slot methods only, and `build()` only pushes
configured `Some(...)` slots without fallback re-enabling.
The aws-v4 README was refreshed to the current public API, and the crate
tests now cover both `process(...)` and `no_process()` so the removal
semantics are exercised directly in this service.
---
services/aws-v4/README.md | 180 +++-------
services/aws-v4/src/lib.rs | 12 +
services/aws-v4/src/provide_credential/default.rs | 408 ++++++++++++----------
3 files changed, 293 insertions(+), 307 deletions(-)
diff --git a/services/aws-v4/README.md b/services/aws-v4/README.md
index 79a8994..007f519 100644
--- a/services/aws-v4/README.md
+++ b/services/aws-v4/README.md
@@ -1,145 +1,75 @@
# reqsign-aws-v4
-AWS SigV4 signing implementation for reqsign.
-
----
-
-This crate provides AWS Signature Version 4 (SigV4) signing capabilities for authenticating requests to AWS services like S3, DynamoDB, Lambda, and more.
+AWS SigV4 signing implementation for `reqsign`.
## Quick Start
-```rust
-use reqsign_aws_v4::{Builder, Config, DefaultLoader};
-use reqsign_core::{Context, Signer};
-
-// Create context and signer
-let ctx = Context::default();
-let config = Config::default().from_env().from_profile();
-let loader = DefaultLoader::new(config);
-let builder = Builder::new("s3", "us-east-1");
-let signer = Signer::new(ctx, loader, builder);
-
-// Sign requests
-let mut req = http::Request::get("https://s3.amazonaws.com/mybucket/mykey")
- .body(())
- .unwrap()
- .into_parts()
- .0;
-
-signer.sign(&mut req, None).await?;
+```rust,no_run
+use reqsign_aws_v4::{DefaultCredentialProvider, RequestSigner};
+use reqsign_core::{Context, OsEnv, Signer};
+use reqsign_file_read_tokio::TokioFileRead;
+use reqsign_http_send_reqwest::ReqwestHttpSend;
+
+#[tokio::main]
+async fn main() -> anyhow::Result<()> {
+ let ctx = Context::new()
+ .with_file_read(TokioFileRead)
+ .with_http_send(ReqwestHttpSend::default())
+ .with_env(OsEnv);
+
+ let signer = Signer::new(
+ ctx,
+ DefaultCredentialProvider::new(),
+ RequestSigner::new("s3", "us-east-1"),
+ );
+
+ let mut req = http::Request::get("https://s3.amazonaws.com/mybucket/mykey")
+ .body(())
+ .unwrap()
+ .into_parts()
+ .0;
+
+ signer.sign(&mut req, None).await?;
+ Ok(())
+}
```
-## Features
-
-- **Complete SigV4 Implementation**: Full AWS Signature Version 4 support
-- **Multiple Credential Sources**: Environment, files, IAM roles, and more
-- **Service Agnostic**: Works with any AWS service using SigV4
-- **Async Support**: Built for modern async Rust applications
-
-## Credential Sources
-
-This crate supports loading credentials from:
-
-1. **Environment Variables**
- ```bash
- export AWS_ACCESS_KEY_ID=your_access_key
- export AWS_SECRET_ACCESS_KEY=your_secret_key
- export AWS_SESSION_TOKEN=your_session_token # Optional
- ```
-
-2. **Credential File** (`~/.aws/credentials`)
- ```ini
- [default]
- aws_access_key_id = your_access_key
- aws_secret_access_key = your_secret_key
-
- [production]
- aws_access_key_id = prod_access_key
- aws_secret_access_key = prod_secret_key
- ```
+## Default Credential Chain
-3. **IAM Roles** (EC2, ECS, Lambda)
- - Automatically detected and used when running on AWS infrastructure
+`DefaultCredentialProvider::new()` builds the documented AWS default chain:
-4. **AssumeRole with STS**
- ```rust
- let config = Config::default()
- .role_arn("arn:aws:iam::123456789012:role/MyRole")
- .role_session_name("my-session");
- ```
+1. `env`
+2. `profile`
+3. `sso`
+4. `web_identity`
+5. `process`
+6. `ecs`
+7. `imds`
-5. **Web Identity Tokens** (EKS/Kubernetes)
- - Automatically detected in EKS environments
+On `wasm32`, the non-portable `sso` and `process` slots are not available.
-## Supported Services
+## Customize Slots
-Works with any AWS service using SigV4:
+Use `DefaultCredentialProvider::builder()` to replace or remove individual slots.
+Each slot is represented by `Option<T>` internally: `slot(provider)` enables it,
+`no_slot()` removes it, and `build()` only pushes `Some(...)` slots into the
+chain.
-- **Storage**: S3, EBS, EFS
-- **Database**: DynamoDB, RDS, DocumentDB
-- **Compute**: EC2, Lambda, ECS
-- **Messaging**: SQS, SNS, EventBridge
-- **Analytics**: Kinesis, Athena, EMR
-- And many more...
+```rust,no_run
+use reqsign_aws_v4::{DefaultCredentialProvider, ProfileCredentialProvider};
-## Examples
-
-### S3 Operations
-
-```rust
-// List buckets
-let req = http::Request::get("https://s3.amazonaws.com/")
- .header("x-amz-content-sha256", EMPTY_STRING_SHA256)
- .body(())?;
-
-// Get object
-let req = http::Request::get("https://bucket.s3.amazonaws.com/key")
- .header("x-amz-content-sha256", EMPTY_STRING_SHA256)
- .body(())?;
+let provider = DefaultCredentialProvider::builder()
+ .no_env()
+ .profile(ProfileCredentialProvider::new().with_profile("production"))
+ .no_imds()
+ .build();
```
-### DynamoDB Operations
+For advanced composition, use `DefaultCredentialProvider::with_chain(...)` or
+prepend a higher-priority source with `DefaultCredentialProvider::push_front(...)`.
-```rust
-// List tables
-let req = http::Request::post("https://dynamodb.us-east-1.amazonaws.com/")
- .header("x-amz-target", "DynamoDB_20120810.ListTables")
- .header("content-type", "application/x-amz-json-1.0")
- .body(json!({}))?;
-```
+## Examples
-Check out more examples:
- [S3 signing example](examples/s3_sign.rs)
- [DynamoDB signing example](examples/dynamodb_sign.rs)
-
-## Advanced Configuration
-
-### Custom Profile
-
-```rust
-let config = Config::default()
- .profile("production")
- .from_profile();
-```
-
-### Assume Role
-
-```rust
-let config = Config::default()
- .role_arn("arn:aws:iam::123456789012:role/MyRole")
- .external_id("unique-external-id")
- .duration_seconds(3600);
-```
-
-### Direct Credentials
-
-```rust
-let config = Config::default()
- .access_key_id("AKIAIOSFODNN7EXAMPLE")
- .secret_access_key("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY")
- .session_token("optional-session-token");
-```
-
-## License
-
-Licensed under [Apache License, Version 2.0](./LICENSE).
\ No newline at end of file
+- [S3 Express signing example](examples/s3_express_sign.rs)
diff --git a/services/aws-v4/src/lib.rs b/services/aws-v4/src/lib.rs
index 9d3eb26..4179ed9 100644
--- a/services/aws-v4/src/lib.rs
+++ b/services/aws-v4/src/lib.rs
@@ -100,6 +100,18 @@
//! .with_profile("production"));
//! ```
//!
+//! ### Customizing DefaultCredentialProvider Slots
+//!
+//! ```no_run
+//! use reqsign_aws_v4::{DefaultCredentialProvider, ProfileCredentialProvider};
+//!
+//! let provider = DefaultCredentialProvider::builder()
+//! .no_env()
+//! .profile(ProfileCredentialProvider::new().with_profile("production"))
+//! .no_imds()
+//! .build();
+//! ```
+//!
//! ### Custom Credential Provider
//!
//! You can create custom credential providers by implementing the `ProvideCredential` trait:
diff --git a/services/aws-v4/src/provide_credential/default.rs b/services/aws-v4/src/provide_credential/default.rs
index adde860..1bff7ff 100644
--- a/services/aws-v4/src/provide_credential/default.rs
+++ b/services/aws-v4/src/provide_credential/default.rs
@@ -86,190 +86,127 @@ impl DefaultCredentialProvider {
/// Builder for `DefaultCredentialProvider`.
///
-/// Use `configure_*` to customize provider behavior and `disable_*(bool)` to
-/// include or exclude providers from the default chain. Call `build()` to
-/// construct the provider.
-#[derive(Default)]
+/// Use `slot(provider)` to override a default slot and `no_slot()` to remove it
+/// from the default chain. Call `build()` to construct the provider.
pub struct DefaultCredentialProviderBuilder {
env: Option<EnvCredentialProvider>,
profile: Option<ProfileCredentialProvider>,
#[cfg(not(target_arch = "wasm32"))]
sso: Option<SSOCredentialProvider>,
- assume_role: Option<AssumeRoleWithWebIdentityCredentialProvider>,
+ web_identity: Option<AssumeRoleWithWebIdentityCredentialProvider>,
#[cfg(not(target_arch = "wasm32"))]
process: Option<ProcessCredentialProvider>,
ecs: Option<ECSCredentialProvider>,
imds: Option<IMDSv2CredentialProvider>,
}
+impl Default for DefaultCredentialProviderBuilder {
+ fn default() -> Self {
+ Self {
+ env: Some(EnvCredentialProvider::new()),
+ profile: Some(ProfileCredentialProvider::default()),
+ #[cfg(not(target_arch = "wasm32"))]
+ sso: Some(SSOCredentialProvider::default()),
+ web_identity: Some(AssumeRoleWithWebIdentityCredentialProvider::default()),
+ #[cfg(not(target_arch = "wasm32"))]
+ process: Some(ProcessCredentialProvider::default()),
+ ecs: Some(ECSCredentialProvider::default()),
+ imds: Some(IMDSv2CredentialProvider::default()),
+ }
+ }
+}
+
impl DefaultCredentialProviderBuilder {
/// Create a new builder with default state.
pub fn new() -> Self {
Self::default()
}
- /// Configure the environment credential provider.
- pub fn configure_env<F>(mut self, f: F) -> Self
- where
- F: FnOnce(EnvCredentialProvider) -> EnvCredentialProvider,
- {
- let p = self.env.take().unwrap_or_default();
- self.env = Some(f(p));
+ /// Override the environment credential provider slot.
+ pub fn env(mut self, provider: EnvCredentialProvider) -> Self {
+ self.env = Some(provider);
self
}
- /// Disable (true) or ensure enabled (false) the environment provider.
- pub fn disable_env(mut self, disable: bool) -> Self {
- if disable {
- self.env = None;
- } else if self.env.is_none() {
- self.env = Some(EnvCredentialProvider::new());
- }
+ /// Remove the environment credential provider from the chain.
+ pub fn no_env(mut self) -> Self {
+ self.env = None;
self
}
- /// Configure the profile credential provider.
- pub fn configure_profile<F>(mut self, f: F) -> Self
- where
- F: FnOnce(ProfileCredentialProvider) -> ProfileCredentialProvider,
- {
- let p = self.profile.take().unwrap_or_default();
- self.profile = Some(f(p));
+ /// Override the profile credential provider slot.
+ pub fn profile(mut self, provider: ProfileCredentialProvider) -> Self {
+ self.profile = Some(provider);
self
}
- /// Disable (true) or ensure enabled (false) the profile provider.
- pub fn disable_profile(mut self, disable: bool) -> Self {
- if disable {
- self.profile = None;
- } else if self.profile.is_none() {
- self.profile = Some(ProfileCredentialProvider::new());
- }
+ /// Remove the profile credential provider from the chain.
+ pub fn no_profile(mut self) -> Self {
+ self.profile = None;
self
}
- /// Configure the SSO credential provider.
- ///
- /// This customizes how AWS SSO (IAM Identity Center) credentials are
- /// discovered and exchanged from local SSO caches. Typical use cases
- /// include setting an alternative endpoint for testing, or overriding the
- /// profile-derived values. This method is only available for non-wasm32
- /// targets where process and filesystem access is supported.
+ /// Override the SSO credential provider slot.
#[cfg(not(target_arch = "wasm32"))]
- pub fn configure_sso<F>(mut self, f: F) -> Self
- where
- F: FnOnce(SSOCredentialProvider) -> SSOCredentialProvider,
- {
- let p = self.sso.take().unwrap_or_default();
- self.sso = Some(f(p));
+ pub fn sso(mut self, provider: SSOCredentialProvider) -> Self {
+ self.sso = Some(provider);
self
}
- /// Disable (true) or ensure enabled (false) the SSO provider.
- ///
- /// Use this to explicitly remove SSO from the default credential
- /// resolution chain (disable = true) or ensure it participates (disable = false).
- /// This is useful in controlled environments (e.g., CI) or when SSO is
- /// not configured. Only available on non-wasm32 targets.
+ /// Remove the SSO credential provider from the chain.
#[cfg(not(target_arch = "wasm32"))]
- pub fn disable_sso(mut self, disable: bool) -> Self {
- if disable {
- self.sso = None;
- } else if self.sso.is_none() {
- self.sso = Some(SSOCredentialProvider::new());
- }
+ pub fn no_sso(mut self) -> Self {
+ self.sso = None;
self
}
- /// Configure the web-identity assume-role credential provider.
- pub fn configure_assume_role<F>(mut self, f: F) -> Self
- where
- F: FnOnce(
- AssumeRoleWithWebIdentityCredentialProvider,
- ) -> AssumeRoleWithWebIdentityCredentialProvider,
- {
- let p = self.assume_role.take().unwrap_or_default();
- self.assume_role = Some(f(p));
+ /// Override the web-identity credential provider slot.
+ pub fn web_identity(mut self, provider: AssumeRoleWithWebIdentityCredentialProvider) -> Self {
+ self.web_identity = Some(provider);
self
}
- /// Disable (true) or ensure enabled (false) the assume role provider.
- pub fn disable_assume_role(mut self, disable: bool) -> Self {
- if disable {
- self.assume_role = None;
- } else if self.assume_role.is_none() {
- self.assume_role = Some(AssumeRoleWithWebIdentityCredentialProvider::new());
- }
+ /// Remove the web-identity credential provider from the chain.
+ pub fn no_web_identity(mut self) -> Self {
+ self.web_identity = None;
self
}
- /// Configure the external process credential provider.
- ///
- /// This allows overriding the profile-derived command used to obtain
- /// credentials via `credential_process`. Only available on non-wasm32
- /// targets.
+ /// Override the external process credential provider slot.
#[cfg(not(target_arch = "wasm32"))]
- pub fn configure_process<F>(mut self, f: F) -> Self
- where
- F: FnOnce(ProcessCredentialProvider) -> ProcessCredentialProvider,
- {
- let p = self.process.take().unwrap_or_default();
- self.process = Some(f(p));
+ pub fn process(mut self, provider: ProcessCredentialProvider) -> Self {
+ self.process = Some(provider);
self
}
- /// Disable (true) or ensure enabled (false) the process provider.
- ///
- /// Use this to explicitly remove the external process credential source
- /// (disable = true) or ensure it participates (disable = false). This is
- /// only meaningful on non-wasm32 targets.
+ /// Remove the external process credential provider from the chain.
#[cfg(not(target_arch = "wasm32"))]
- pub fn disable_process(mut self, disable: bool) -> Self {
- if disable {
- self.process = None;
- } else if self.process.is_none() {
- self.process = Some(ProcessCredentialProvider::new());
- }
+ pub fn no_process(mut self) -> Self {
+ self.process = None;
self
}
- /// Configure the ECS (container/task) credential provider.
- pub fn configure_ecs<F>(mut self, f: F) -> Self
- where
- F: FnOnce(ECSCredentialProvider) -> ECSCredentialProvider,
- {
- let p = self.ecs.take().unwrap_or_default();
- self.ecs = Some(f(p));
+ /// Override the ECS credential provider slot.
+ pub fn ecs(mut self, provider: ECSCredentialProvider) -> Self {
+ self.ecs = Some(provider);
self
}
- /// Disable (true) or ensure enabled (false) the ECS provider.
- pub fn disable_ecs(mut self, disable: bool) -> Self {
- if disable {
- self.ecs = None;
- } else if self.ecs.is_none() {
- self.ecs = Some(ECSCredentialProvider::new());
- }
+ /// Remove the ECS credential provider from the chain.
+ pub fn no_ecs(mut self) -> Self {
+ self.ecs = None;
self
}
- /// Configure the EC2 IMDSv2 credential provider.
- pub fn configure_imds<F>(mut self, f: F) -> Self
- where
- F: FnOnce(IMDSv2CredentialProvider) -> IMDSv2CredentialProvider,
- {
- let p = self.imds.take().unwrap_or_default();
- self.imds = Some(f(p));
+ /// Override the EC2 IMDSv2 credential provider slot.
+ pub fn imds(mut self, provider: IMDSv2CredentialProvider) -> Self {
+ self.imds = Some(provider);
self
}
- /// Disable (true) or ensure enabled (false) the IMDSv2 provider.
- pub fn disable_imds(mut self, disable: bool) -> Self {
- if disable {
- self.imds = None;
- } else if self.imds.is_none() {
- self.imds = Some(IMDSv2CredentialProvider::new());
- }
+ /// Remove the EC2 IMDSv2 credential provider from the chain.
+ pub fn no_imds(mut self) -> Self {
+ self.imds = None;
self
}
@@ -279,50 +216,36 @@ impl DefaultCredentialProviderBuilder {
if let Some(p) = self.env {
chain = chain.push(p);
- } else {
- chain = chain.push(EnvCredentialProvider::new());
}
if let Some(p) = self.profile {
chain = chain.push(p);
- } else {
- chain = chain.push(ProfileCredentialProvider::new());
}
#[cfg(not(target_arch = "wasm32"))]
{
if let Some(p) = self.sso {
chain = chain.push(p);
- } else {
- chain = chain.push(SSOCredentialProvider::new());
}
}
- if let Some(p) = self.assume_role {
+ if let Some(p) = self.web_identity {
chain = chain.push(p);
- } else {
- chain = chain.push(AssumeRoleWithWebIdentityCredentialProvider::new());
}
#[cfg(not(target_arch = "wasm32"))]
{
if let Some(p) = self.process {
chain = chain.push(p);
- } else {
- chain = chain.push(ProcessCredentialProvider::new());
}
}
if let Some(p) = self.ecs {
chain = chain.push(p);
- } else {
- chain = chain.push(ECSCredentialProvider::new());
}
if let Some(p) = self.imds {
chain = chain.push(p);
- } else {
- chain = chain.push(IMDSv2CredentialProvider::new());
}
DefaultCredentialProvider::with_chain(chain)
@@ -342,6 +265,8 @@ mod tests {
use crate::constants::{
AWS_ACCESS_KEY_ID, AWS_CONFIG_FILE, AWS_SECRET_ACCESS_KEY, AWS_SHARED_CREDENTIALS_FILE,
};
+ #[cfg(not(target_arch = "wasm32"))]
+ use reqsign_command_execute_tokio::TokioCommandExecute;
use reqsign_core::{OsEnv, StaticEnv};
use reqsign_file_read_tokio::TokioFileRead;
use reqsign_http_send_reqwest::ReqwestHttpSend;
@@ -361,7 +286,17 @@ mod tests {
envs: HashMap::new(),
});
- let l = DefaultCredentialProvider::new();
+ let builder = DefaultCredentialProvider::builder()
+ .no_profile()
+ .no_web_identity()
+ .no_ecs()
+ .no_imds();
+ #[cfg(not(target_arch = "wasm32"))]
+ let builder = builder.no_sso().no_process();
+ #[cfg(target_arch = "wasm32")]
+ let builder = builder;
+
+ let l = builder.build();
let x = l.provide_credential(&ctx).await.expect("load must succeed");
assert!(x.is_none());
}
@@ -393,6 +328,45 @@ mod tests {
assert_eq!("secret_access_key", x.secret_access_key);
}
+ #[tokio::test]
+ async fn test_default_credential_provider_no_env_removes_slot() {
+ let _ = env_logger::builder().is_test(true).try_init();
+
+ let ctx = Context::new()
+ .with_file_read(TokioFileRead)
+ .with_http_send(ReqwestHttpSend::default())
+ .with_env(OsEnv);
+ let ctx = ctx.with_env(StaticEnv {
+ home_dir: None,
+ envs: HashMap::from_iter([
+ (AWS_ACCESS_KEY_ID.to_string(), "access_key_id".to_string()),
+ (
+ AWS_SECRET_ACCESS_KEY.to_string(),
+ "secret_access_key".to_string(),
+ ),
+ ]),
+ });
+
+ let builder = DefaultCredentialProvider::builder()
+ .no_env()
+ .no_profile()
+ .no_imds()
+ .no_ecs()
+ .no_web_identity();
+ #[cfg(not(target_arch = "wasm32"))]
+ let builder = builder.no_sso().no_process();
+ #[cfg(target_arch = "wasm32")]
+ let builder = builder;
+
+ let provider = builder.build();
+
+ let cred = provider
+ .provide_credential(&ctx)
+ .await
+ .expect("load must succeed");
+ assert!(cred.is_none());
+ }
+
#[tokio::test]
async fn test_credential_profile_loader_from_config() {
let _ = env_logger::builder().is_test(true).try_init();
@@ -508,7 +482,7 @@ mod tests {
}
#[tokio::test]
- async fn test_default_credential_provider_configure_imds() {
+ async fn test_default_credential_provider_no_profile_removes_slot() {
let _ = env_logger::builder().is_test(true).try_init();
let ctx = Context::new()
@@ -517,31 +491,40 @@ mod tests {
.with_env(OsEnv);
let ctx = ctx.with_env(StaticEnv {
home_dir: None,
- envs: HashMap::new(),
+ envs: HashMap::from_iter([
+ (
+ AWS_CONFIG_FILE.to_string(),
+ format!(
+ "{}/testdata/default_config",
+ env::current_dir()
+ .expect("current_dir must exist")
+ .to_string_lossy()
+ ),
+ ),
+ (
+ AWS_SHARED_CREDENTIALS_FILE.to_string(),
+ format!(
+ "{}/testdata/not_exist",
+ env::current_dir()
+ .expect("current_dir must exist")
+ .to_string_lossy()
+ ),
+ ),
+ ]),
});
- // Build a custom chain with IMDS disabled
- let mut chain = ProvideCredentialChain::new()
- .push(EnvCredentialProvider::new())
- .push(ProfileCredentialProvider::new());
-
+ let builder = DefaultCredentialProvider::builder()
+ .no_profile()
+ .no_imds()
+ .no_ecs()
+ .no_web_identity();
#[cfg(not(target_arch = "wasm32"))]
- {
- chain = chain.push(SSOCredentialProvider::new());
- }
-
- chain = chain.push(AssumeRoleWithWebIdentityCredentialProvider::new());
-
- #[cfg(not(target_arch = "wasm32"))]
- {
- chain = chain.push(ProcessCredentialProvider::new());
- }
+ let builder = builder.no_sso().no_process();
+ #[cfg(target_arch = "wasm32")]
+ let builder = builder;
- chain = chain.push(ECSCredentialProvider::new());
+ let provider = builder.build();
- let provider = DefaultCredentialProvider::with_chain(chain);
-
- // Even though IMDS is the last provider, it should return None when disabled
let cred = provider
.provide_credential(&ctx)
.await
@@ -550,7 +533,7 @@ mod tests {
}
#[tokio::test]
- async fn test_default_credential_provider_configure_profile() {
+ async fn test_default_credential_provider_custom_profile_slot() {
let _ = env_logger::builder().is_test(true).try_init();
let ctx = Context::new()
@@ -570,37 +553,98 @@ mod tests {
.to_string_lossy()
);
- let mut chain = ProvideCredentialChain::new().push(EnvCredentialProvider::new());
+ let provider = DefaultCredentialProvider::builder()
+ .profile(ProfileCredentialProvider::new().with_config_file(custom_config))
+ .build();
- chain = chain.push(ProfileCredentialProvider::new().with_config_file(custom_config));
+ let cred = provider
+ .provide_credential(&ctx)
+ .await
+ .expect("load must succeed");
+ let cred = cred.expect("credential should exist");
+ assert_eq!("config_access_key_id", cred.access_key_id);
+ assert_eq!("config_secret_access_key", cred.secret_access_key);
+ }
- #[cfg(not(target_arch = "wasm32"))]
- {
- chain = chain.push(SSOCredentialProvider::new());
- }
+ #[cfg(not(target_arch = "wasm32"))]
+ #[tokio::test]
+ async fn test_default_credential_provider_custom_process_slot() {
+ let _ = env_logger::builder().is_test(true).try_init();
- chain = chain.push(AssumeRoleWithWebIdentityCredentialProvider::new());
+ let ctx = Context::new()
+ .with_file_read(TokioFileRead)
+ .with_http_send(ReqwestHttpSend::default())
+ .with_command_execute(TokioCommandExecute)
+ .with_env(OsEnv);
+ let ctx = ctx.with_env(StaticEnv {
+ home_dir: None,
+ envs: HashMap::new(),
+ });
- #[cfg(not(target_arch = "wasm32"))]
- {
- chain = chain.push(ProcessCredentialProvider::new());
- }
+ let helper = format!(
+ "{}/tests/mocks/credential_process_helper.py",
+ env::current_dir()
+ .expect("current_dir must exist")
+ .to_string_lossy()
+ );
- chain = chain
- .push(ECSCredentialProvider::new())
- .push(IMDSv2CredentialProvider::new());
+ let provider = DefaultCredentialProvider::builder()
+ .no_env()
+ .no_profile()
+ .no_sso()
+ .no_web_identity()
+ .no_ecs()
+ .no_imds()
+ .process(ProcessCredentialProvider::new().with_command(format!("python3 {helper}")))
+ .build();
- let provider = DefaultCredentialProvider::with_chain(chain);
+ let cred = provider
+ .provide_credential(&ctx)
+ .await
+ .expect("load must succeed")
+ .expect("credential should exist");
+ assert_eq!("ASIAPROCESSEXAMPLE", cred.access_key_id);
+ assert_eq!("process/secret/key/EXAMPLE", cred.secret_access_key);
+ }
+
+ #[cfg(not(target_arch = "wasm32"))]
+ #[tokio::test]
+ async fn test_default_credential_provider_no_process_removes_slot() {
+ let _ = env_logger::builder().is_test(true).try_init();
+
+ let ctx = Context::new()
+ .with_file_read(TokioFileRead)
+ .with_http_send(ReqwestHttpSend::default())
+ .with_command_execute(TokioCommandExecute)
+ .with_env(OsEnv);
+ let ctx = ctx.with_env(StaticEnv {
+ home_dir: None,
+ envs: HashMap::new(),
+ });
+
+ let helper = format!(
+ "{}/tests/mocks/credential_process_helper.py",
+ env::current_dir()
+ .expect("current_dir must exist")
+ .to_string_lossy()
+ );
+
+ let provider = DefaultCredentialProvider::builder()
+ .no_env()
+ .no_profile()
+ .no_sso()
+ .no_web_identity()
+ .no_ecs()
+ .no_imds()
+ .process(ProcessCredentialProvider::new().with_command(format!("python3 {helper}")))
+ .no_process()
+ .build();
- // Should load from the custom config
let cred = provider
.provide_credential(&ctx)
.await
.expect("load must succeed");
- // The testdata/default_config has credentials
- let cred = cred.expect("credential should exist");
- assert_eq!("config_access_key_id", cred.access_key_id);
- assert_eq!("config_secret_access_key", cred.secret_access_key);
+ assert!(cred.is_none());
}
/// AWS_SHARED_CREDENTIALS_FILE should be taken first.