s3-wire 0.2.0

An async, streaming S3-compatible client for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
//! Credential values and providers.

use std::env;
use std::fmt;
use std::sync::Arc;
use std::time::Duration;

use async_trait::async_trait;
use secrecy::{ExposeSecret, SecretString};
use time::OffsetDateTime;
use tokio::sync::Mutex;

use crate::error::{ErrorCategory, RetryClassification, S3Error};

#[cfg(feature = "aws-credentials")]
use aws_credential_types::provider::{ProvideCredentials as _, SharedCredentialsProvider};

/// AWS-compatible credentials and optional expiration.
///
/// Secret values are zeroized on drop. Its `Debug` implementation redacts all
/// credential material, including the access-key identifier.
#[derive(Clone)]
pub struct Credentials {
    access_key_id: SecretString,
    secret_access_key: SecretString,
    session_token: Option<SecretString>,
    expires_at: Option<OffsetDateTime>,
}

impl Credentials {
    /// Creates non-expiring credentials.
    pub fn new(
        access_key_id: impl Into<String>,
        secret_access_key: impl Into<String>,
        session_token: Option<String>,
    ) -> Result<Self, S3Error> {
        Self::with_expiration(access_key_id, secret_access_key, session_token, None)
    }

    /// Creates credentials with an optional expiration time.
    pub fn with_expiration(
        access_key_id: impl Into<String>,
        secret_access_key: impl Into<String>,
        session_token: Option<String>,
        expires_at: Option<OffsetDateTime>,
    ) -> Result<Self, S3Error> {
        let access_key_id = access_key_id.into();
        let secret_access_key = secret_access_key.into();
        if access_key_id.is_empty() {
            return Err(S3Error::configuration(
                "credential access key identifier must not be empty",
            ));
        }
        if secret_access_key.is_empty() {
            return Err(S3Error::configuration(
                "credential secret access key must not be empty",
            ));
        }
        if session_token.as_deref() == Some("") {
            return Err(S3Error::configuration(
                "credential session token must not be empty when present",
            ));
        }
        Ok(Self {
            access_key_id: access_key_id.into(),
            secret_access_key: secret_access_key.into(),
            session_token: session_token.map(Into::into),
            expires_at,
        })
    }

    /// Returns the access-key identifier for signing.
    pub fn access_key_id(&self) -> &str {
        self.access_key_id.expose_secret()
    }

    /// Returns the secret access key for signing.
    pub fn secret_access_key(&self) -> &SecretString {
        &self.secret_access_key
    }

    /// Returns the optional session token for signing.
    pub fn session_token(&self) -> Option<&SecretString> {
        self.session_token.as_ref()
    }

    /// Returns the credential expiration time, when supplied by the provider.
    pub fn expires_at(&self) -> Option<OffsetDateTime> {
        self.expires_at
    }

    /// Returns whether the credentials expire at or before `time`.
    pub fn expires_by(&self, time: OffsetDateTime) -> bool {
        self.expires_at.is_some_and(|expiration| expiration <= time)
    }
}

impl fmt::Debug for Credentials {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Credentials")
            .field("access_key_id", &"[REDACTED]")
            .field("secret_access_key", &"[REDACTED]")
            .field(
                "session_token",
                &self.session_token.as_ref().map(|_| "[REDACTED]"),
            )
            .field("expires_at", &self.expires_at)
            .finish()
    }
}

/// Asynchronous source of AWS-compatible credentials.
#[async_trait]
pub trait CredentialsProvider: Send + Sync {
    /// Resolves credentials for a request.
    async fn provide_credentials(&self) -> Result<Credentials, S3Error>;
}

/// Adapter for AWS's standard renewable credential provider chain.
///
/// This provider is available only with the `aws-credentials` feature so the
/// default `s3-wire` dependency graph remains small. The chain covers shared
/// profiles, environment credentials, web identity, ECS container credentials,
/// EC2 IMDSv2, credential processes, and assume-role profiles.
#[cfg(feature = "aws-credentials")]
#[derive(Clone)]
pub struct AwsDefaultCredentialsProvider {
    inner: SharedCredentialsProvider,
}

#[cfg(feature = "aws-credentials")]
impl AwsDefaultCredentialsProvider {
    /// Builds the standard AWS credential chain.
    pub async fn new() -> Self {
        let chain = aws_config::default_provider::credentials::DefaultCredentialsChain::builder()
            .build()
            .await;
        Self {
            inner: SharedCredentialsProvider::new(chain),
        }
    }

    /// Builds the standard AWS credential chain for a named shared profile.
    pub async fn for_profile(profile: &str) -> Result<Self, S3Error> {
        if profile.is_empty() {
            return Err(S3Error::configuration("AWS profile name must not be empty"));
        }
        let chain = aws_config::default_provider::credentials::DefaultCredentialsChain::builder()
            .profile_name(profile)
            .build()
            .await;
        Ok(Self {
            inner: SharedCredentialsProvider::new(chain),
        })
    }
}

#[cfg(feature = "aws-credentials")]
impl fmt::Debug for AwsDefaultCredentialsProvider {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("AwsDefaultCredentialsProvider")
            .field("inner", &"[REDACTED]")
            .finish()
    }
}

#[cfg(feature = "aws-credentials")]
#[async_trait]
impl CredentialsProvider for AwsDefaultCredentialsProvider {
    async fn provide_credentials(&self) -> Result<Credentials, S3Error> {
        let credentials = self.inner.provide_credentials().await.map_err(|error| {
            S3Error::new(
                ErrorCategory::Authentication,
                "AWS default credential chain did not resolve credentials",
                RetryClassification::Never,
            )
            .with_source(error)
        })?;
        Credentials::with_expiration(
            credentials.access_key_id(),
            credentials.secret_access_key(),
            credentials.session_token().map(ToOwned::to_owned),
            credentials.expiry().map(OffsetDateTime::from),
        )
    }
}

/// Resolves a signing region through AWS's standard environment, shared
/// profile, and IMDS region chain.
///
/// # Errors
///
/// Returns an error when the chain does not resolve a region.
#[cfg(feature = "aws-credentials")]
pub async fn resolve_default_aws_region() -> Result<String, S3Error> {
    aws_config::default_provider::region::DefaultRegionChain::builder()
        .build()
        .region()
        .await
        .map(|region| region.as_ref().to_owned())
        .ok_or_else(|| S3Error::configuration("AWS default region chain did not resolve a region"))
}

/// Resolves a signing region through AWS's standard chain for a named profile.
///
/// # Errors
///
/// Returns an error for an empty profile or when the chain does not resolve a
/// region.
#[cfg(feature = "aws-credentials")]
pub async fn resolve_aws_region_for_profile(profile: &str) -> Result<String, S3Error> {
    if profile.is_empty() {
        return Err(S3Error::configuration("AWS profile name must not be empty"));
    }
    aws_config::default_provider::region::DefaultRegionChain::builder()
        .profile_name(profile)
        .build()
        .region()
        .await
        .map(|region| region.as_ref().to_owned())
        .ok_or_else(|| S3Error::configuration("AWS profile did not resolve a region"))
}

/// Provider backed by an immutable credential value.
#[derive(Clone)]
pub struct StaticCredentialsProvider {
    credentials: Credentials,
}

impl StaticCredentialsProvider {
    /// Creates a static provider.
    pub fn new(credentials: Credentials) -> Self {
        Self { credentials }
    }
}

impl fmt::Debug for StaticCredentialsProvider {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("StaticCredentialsProvider")
            .field("credentials", &"[REDACTED]")
            .finish()
    }
}

#[async_trait]
impl CredentialsProvider for StaticCredentialsProvider {
    async fn provide_credentials(&self) -> Result<Credentials, S3Error> {
        Ok(self.credentials.clone())
    }
}

/// Provider for the conventional AWS credential environment variables.
#[derive(Clone, Copy, Debug, Default)]
pub struct EnvironmentCredentialsProvider;

impl EnvironmentCredentialsProvider {
    /// Creates an environment credential provider.
    pub const fn new() -> Self {
        Self
    }
}

#[async_trait]
impl CredentialsProvider for EnvironmentCredentialsProvider {
    async fn provide_credentials(&self) -> Result<Credentials, S3Error> {
        let access_key_id = read_required_env("AWS_ACCESS_KEY_ID")?;
        let secret_access_key = read_required_env("AWS_SECRET_ACCESS_KEY")?;
        let session_token = read_optional_env("AWS_SESSION_TOKEN")?;
        Credentials::new(access_key_id, secret_access_key, session_token)
    }
}

fn read_required_env(name: &'static str) -> Result<String, S3Error> {
    read_optional_env(name)?.ok_or_else(|| {
        S3Error::new(
            ErrorCategory::Authentication,
            format!("required credential environment variable {name} is not set"),
            RetryClassification::Never,
        )
    })
}

fn read_optional_env(name: &'static str) -> Result<Option<String>, S3Error> {
    env::var_os(name)
        .map(|value| {
            value.into_string().map_err(|_| {
                S3Error::new(
                    ErrorCategory::Authentication,
                    format!("credential environment variable {name} is not valid Unicode"),
                    RetryClassification::Never,
                )
            })
        })
        .transpose()
}

/// Expiration-aware provider that coalesces concurrent refresh requests.
///
/// A refresh is performed while holding a Tokio mutex. Concurrent callers wait for
/// that single refresh and then consume the same cached result, preventing refresh
/// storms. If an early refresh fails, credentials that have not actually expired are
/// returned until a later call can retry.
pub struct CachedCredentialsProvider {
    provider: Arc<dyn CredentialsProvider>,
    refresh_before: Duration,
    cached: Mutex<Option<Credentials>>,
}

impl CachedCredentialsProvider {
    /// Wraps a provider and refreshes expiring credentials one minute early.
    pub fn new(provider: Arc<dyn CredentialsProvider>) -> Self {
        Self::with_refresh_before(provider, Duration::from_secs(60))
    }

    /// Wraps a provider with a custom early-refresh window.
    pub fn with_refresh_before(
        provider: Arc<dyn CredentialsProvider>,
        refresh_before: Duration,
    ) -> Self {
        Self {
            provider,
            refresh_before,
            cached: Mutex::new(None),
        }
    }

    fn refresh_deadline(&self, now: OffsetDateTime) -> OffsetDateTime {
        let refresh_before =
            time::Duration::try_from(self.refresh_before).unwrap_or(time::Duration::MAX);
        now.saturating_add(refresh_before)
    }

    /// Clears the current cache entry so the next request refreshes it.
    pub async fn invalidate(&self) {
        *self.cached.lock().await = None;
    }
}

impl fmt::Debug for CachedCredentialsProvider {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CachedCredentialsProvider")
            .field("provider", &"[REDACTED]")
            .field("refresh_before", &self.refresh_before)
            .field("cached", &"[REDACTED]")
            .finish()
    }
}

#[async_trait]
impl CredentialsProvider for CachedCredentialsProvider {
    async fn provide_credentials(&self) -> Result<Credentials, S3Error> {
        let mut cached = self.cached.lock().await;
        let now = OffsetDateTime::now_utc();
        if let Some(credentials) = cached.as_ref()
            && !credentials.expires_by(self.refresh_deadline(now))
        {
            return Ok(credentials.clone());
        }

        match self.provider.provide_credentials().await {
            Ok(credentials) => {
                *cached = Some(credentials.clone());
                Ok(credentials)
            }
            Err(refresh_error) => {
                if let Some(credentials) = cached.as_ref()
                    && !credentials.expires_by(now)
                {
                    return Ok(credentials.clone());
                }
                Err(refresh_error)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use std::sync::atomic::{AtomicUsize, Ordering};

    use futures_util::future::join_all;
    use proptest::prelude::*;

    use super::*;

    struct CountingProvider {
        calls: AtomicUsize,
    }

    #[async_trait]
    impl CredentialsProvider for CountingProvider {
        async fn provide_credentials(&self) -> Result<Credentials, S3Error> {
            self.calls.fetch_add(1, Ordering::SeqCst);
            tokio::task::yield_now().await;
            Credentials::new(
                "visible-access-id",
                "visible-secret",
                Some("visible-token".into()),
            )
        }
    }

    #[test]
    fn debug_redacts_all_credential_material() {
        let credentials = Credentials::new(
            "visible-access-id",
            "visible-secret",
            Some("visible-token".into()),
        )
        .unwrap();
        let debug = format!("{credentials:?}");
        assert!(!debug.contains("visible-access-id"));
        assert!(!debug.contains("visible-secret"));
        assert!(!debug.contains("visible-token"));
    }

    proptest! {
        #[test]
        fn arbitrary_credential_values_are_redacted(
            suffix in "[A-Za-z0-9]{12,32}"
        ) {
            let access = format!("ACCESS-{suffix}");
            let secret = format!("SECRET-{suffix}");
            let token = format!("TOKEN-{suffix}");
            let credentials = Credentials::new(
                access.clone(),
                secret.clone(),
                Some(token.clone()),
            ).unwrap();
            let debug = format!("{credentials:?}");
            prop_assert!(!debug.contains(&access));
            prop_assert!(!debug.contains(&secret));
            prop_assert!(!debug.contains(&token));
        }
    }

    #[tokio::test]
    async fn concurrent_cache_misses_share_one_refresh() {
        let provider = Arc::new(CountingProvider {
            calls: AtomicUsize::new(0),
        });
        let cached = Arc::new(CachedCredentialsProvider::new(provider.clone()));
        let requests = (0..32).map(|_| {
            let cached = cached.clone();
            async move { cached.provide_credentials().await.unwrap() }
        });

        let results = join_all(requests).await;
        assert_eq!(results.len(), 32);
        assert_eq!(provider.calls.load(Ordering::SeqCst), 1);
    }
}