s3util-rs 1.4.0

Tools for managing Amazon S3 objects and buckets
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
use crate::config::args::value_parser::url;
use crate::config::{CLITimeoutConfig, ClientConfig, RetryConfig, TracingConfig};
use crate::types::{AccessKeys, ClientConfigLocation, S3Credentials};
use aws_sdk_s3::types::RequestPayer;
use aws_smithy_types::checksum_config::RequestChecksumCalculation;
use clap::Parser;
use clap::builder::NonEmptyStringValueParser;
use clap_verbosity_flag::{Verbosity, WarnLevel};
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::Arc;
use tokio::sync::Semaphore;

use super::common::{
    DEFAULT_ACCELERATE, DEFAULT_AWS_MAX_ATTEMPTS, DEFAULT_AWS_SDK_TRACING,
    DEFAULT_DISABLE_COLOR_TRACING, DEFAULT_DISABLE_STALLED_STREAM_PROTECTION,
    DEFAULT_FORCE_PATH_STYLE, DEFAULT_INITIAL_BACKOFF_MILLISECONDS, DEFAULT_JSON_TRACING,
    DEFAULT_REQUEST_PAYER, DEFAULT_SPAN_EVENTS_TRACING,
};

const DEFAULT_TARGET_NO_SIGN_REQUEST: bool = false;

#[derive(Parser, Clone, Debug)]
pub struct CommonClientArgs {
    // === Tracing / Logging ===
    /// Show trace as json format.
    #[arg(long, env, default_value_t = DEFAULT_JSON_TRACING, help_heading = "Tracing/Logging")]
    pub json_tracing: bool,

    /// Enable aws sdk tracing.
    #[arg(long, env, default_value_t = DEFAULT_AWS_SDK_TRACING, help_heading = "Tracing/Logging")]
    pub aws_sdk_tracing: bool,

    /// Show span event tracing.
    #[arg(long, env, default_value_t = DEFAULT_SPAN_EVENTS_TRACING, help_heading = "Tracing/Logging")]
    pub span_events_tracing: bool,

    /// Disable ANSI terminal colors.
    #[arg(long, env, default_value_t = DEFAULT_DISABLE_COLOR_TRACING, help_heading = "Tracing/Logging")]
    pub disable_color_tracing: bool,

    #[command(flatten)]
    pub verbosity: Verbosity<WarnLevel>,

    // === AWS Configuration ===
    /// Location of the file that the AWS CLI uses to store configuration profiles
    #[arg(long, env, value_name = "FILE", help_heading = "AWS Configuration")]
    pub aws_config_file: Option<PathBuf>,

    /// Location of the file that the AWS CLI uses to store access keys
    #[arg(long, env, value_name = "FILE", help_heading = "AWS Configuration")]
    pub aws_shared_credentials_file: Option<PathBuf>,

    /// Target AWS CLI profile
    #[arg(long, env, conflicts_with_all = ["target_access_key", "target_secret_access_key", "target_session_token"], help_heading = "AWS Configuration")]
    pub target_profile: Option<String>,

    /// Target access key
    #[arg(long, env, conflicts_with_all = ["target_profile"], requires = "target_secret_access_key", help_heading = "AWS Configuration")]
    pub target_access_key: Option<String>,

    /// Target secret access key
    #[arg(long, env, conflicts_with_all = ["target_profile"], requires = "target_access_key", help_heading = "AWS Configuration")]
    pub target_secret_access_key: Option<String>,

    /// Target session token
    #[arg(long, env, conflicts_with_all = ["target_profile"], requires = "target_access_key", help_heading = "AWS Configuration")]
    pub target_session_token: Option<String>,

    /// AWS region for the target
    #[arg(long, env, value_parser = NonEmptyStringValueParser::new(), help_heading = "AWS Configuration")]
    pub target_region: Option<String>,

    /// Custom S3-compatible endpoint URL (e.g. MinIO, Wasabi)
    #[arg(long, env, value_parser = url::check_scheme, help_heading = "AWS Configuration")]
    pub target_endpoint_url: Option<String>,

    /// Use path-style access (required by some S3-compatible services)
    #[arg(long, env, default_value_t = DEFAULT_FORCE_PATH_STYLE, help_heading = "AWS Configuration")]
    pub target_force_path_style: bool,

    /// Enable S3 Transfer Acceleration
    #[arg(long, env, default_value_t = DEFAULT_ACCELERATE, help_heading = "AWS Configuration")]
    pub target_accelerate: bool,

    /// Enable requester-pays for the target bucket
    #[arg(long, env, default_value_t = DEFAULT_REQUEST_PAYER, help_heading = "AWS Configuration")]
    pub target_request_payer: bool,

    /// Do not sign the request. If this argument is specified, credentials will not be loaded
    #[arg(
        long,
        env,
        default_value_t = DEFAULT_TARGET_NO_SIGN_REQUEST,
        conflicts_with_all = [
            "target_profile",
            "target_access_key",
            "target_secret_access_key",
            "target_session_token",
            "target_request_payer",
        ],
        help_heading = "AWS Configuration"
    )]
    pub target_no_sign_request: bool,

    /// Disable stalled stream protection
    #[arg(long, env, default_value_t = DEFAULT_DISABLE_STALLED_STREAM_PROTECTION, help_heading = "AWS Configuration")]
    pub disable_stalled_stream_protection: bool,

    // === Retry Options ===
    /// Maximum retry attempts for AWS SDK operations
    #[arg(long, env, default_value_t = DEFAULT_AWS_MAX_ATTEMPTS, help_heading = "Retry Options")]
    pub aws_max_attempts: u32,

    /// Initial backoff in milliseconds for retries
    #[arg(long, env, default_value_t = DEFAULT_INITIAL_BACKOFF_MILLISECONDS, help_heading = "Retry Options")]
    pub initial_backoff_milliseconds: u64,

    // === Timeout Options ===
    /// Overall operation timeout in milliseconds
    #[arg(long, env, help_heading = "Timeout Options")]
    pub operation_timeout_milliseconds: Option<u64>,

    /// Per-attempt operation timeout in milliseconds
    #[arg(long, env, help_heading = "Timeout Options")]
    pub operation_attempt_timeout_milliseconds: Option<u64>,

    /// Connection timeout in milliseconds
    #[arg(long, env, help_heading = "Timeout Options")]
    pub connect_timeout_milliseconds: Option<u64>,

    /// Read timeout in milliseconds
    #[arg(long, env, help_heading = "Timeout Options")]
    pub read_timeout_milliseconds: Option<u64>,

    // === Advanced ===
    #[arg(
        long,
        env,
        value_name = "SHELL",
        value_parser = clap_complete::shells::Shell::from_str,
        help_heading = "Advanced",
        long_help = r#"Generate a auto completions script.
Valid choices: bash, fish, zsh, powershell, elvish."#
    )]
    pub auto_complete_shell: Option<clap_complete::shells::Shell>,
}

impl CommonClientArgs {
    /// Translate the parsed flags into the existing `ClientConfig` used by
    /// `storage::s3::client_builder`. Single endpoint (target), so no source/target
    /// dichotomy. The parallel-upload semaphore is unused by thin-wrapper commands
    /// but must be present because `ClientConfig` requires it.
    pub fn build_client_config(&self) -> ClientConfig {
        let credential = if self.target_no_sign_request {
            S3Credentials::NoSignRequest
        } else if let Some(profile) = self.target_profile.clone() {
            S3Credentials::Profile(profile)
        } else if let Some(access_key) = self.target_access_key.clone() {
            S3Credentials::Credentials {
                access_keys: AccessKeys {
                    access_key,
                    secret_access_key: self.target_secret_access_key.clone().expect(
                        "clap requires --target-secret-access-key alongside --target-access-key",
                    ),
                    session_token: self.target_session_token.clone(),
                },
            }
        } else {
            S3Credentials::FromEnvironment
        };

        let request_payer = if self.target_request_payer {
            Some(RequestPayer::Requester)
        } else {
            None
        };

        ClientConfig {
            client_config_location: ClientConfigLocation {
                aws_config_file: self.aws_config_file.clone(),
                aws_shared_credentials_file: self.aws_shared_credentials_file.clone(),
            },
            credential,
            region: self.target_region.clone(),
            endpoint_url: self.target_endpoint_url.clone(),
            force_path_style: self.target_force_path_style,
            accelerate: self.target_accelerate,
            request_payer,
            retry_config: RetryConfig {
                aws_max_attempts: self.aws_max_attempts,
                initial_backoff_milliseconds: self.initial_backoff_milliseconds,
            },
            cli_timeout_config: CLITimeoutConfig {
                operation_timeout_milliseconds: self.operation_timeout_milliseconds,
                operation_attempt_timeout_milliseconds: self.operation_attempt_timeout_milliseconds,
                connect_timeout_milliseconds: self.connect_timeout_milliseconds,
                read_timeout_milliseconds: self.read_timeout_milliseconds,
            },
            disable_stalled_stream_protection: self.disable_stalled_stream_protection,
            request_checksum_calculation: RequestChecksumCalculation::WhenRequired,
            // Thin-wrapper commands don't multipart-upload, but ClientConfig
            // demands a semaphore. A 1-permit semaphore is harmless.
            parallel_upload_semaphore: Arc::new(Semaphore::new(1)),
        }
    }

    /// Build a `TracingConfig` from verbosity + tracing flags. Returns `None`
    /// when verbosity is below Error so the global tracing subscriber is not
    /// installed (matches cp/mv `-qqq` behaviour).
    pub fn build_tracing_config(&self) -> Option<TracingConfig> {
        self.verbosity
            .log_level()
            .map(|tracing_level| TracingConfig {
                tracing_level,
                json_tracing: self.json_tracing,
                aws_sdk_tracing: self.aws_sdk_tracing,
                span_events_tracing: self.span_events_tracing,
                disable_color_tracing: self.disable_color_tracing,
            })
    }

    /// Same as [`build_tracing_config`], but with `dry_run` forcing the level
    /// to at least `Info` so the "[dry-run]" message is visible at the default
    /// `WarnLevel`. Levels already above info (debug/trace) are left
    /// unchanged. When `dry_run` is false, behaves identically to
    /// `build_tracing_config`.
    ///
    /// [`build_tracing_config`]: Self::build_tracing_config
    pub fn build_tracing_config_dry_run(&self, dry_run: bool) -> Option<TracingConfig> {
        if !dry_run {
            return self.build_tracing_config();
        }
        let tracing_level = self
            .verbosity
            .log_level()
            .map_or(log::Level::Info, |l| l.max(log::Level::Info));
        Some(TracingConfig {
            tracing_level,
            json_tracing: self.json_tracing,
            aws_sdk_tracing: self.aws_sdk_tracing,
            span_events_tracing: self.span_events_tracing,
            disable_color_tracing: self.disable_color_tracing,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use clap::Parser;

    #[derive(Parser, Debug)]
    struct TestCli {
        #[command(flatten)]
        common: CommonClientArgs,
    }

    #[test]
    fn parses_with_no_flags() {
        let cli = TestCli::try_parse_from(["test"]).unwrap();
        assert!(cli.common.target_region.is_none());
        assert_eq!(cli.common.aws_max_attempts, DEFAULT_AWS_MAX_ATTEMPTS);
        assert!(!cli.common.json_tracing);
    }

    #[test]
    fn target_access_key_requires_secret() {
        let res = TestCli::try_parse_from(["test", "--target-access-key", "AKIA"]);
        assert!(res.is_err(), "must require --target-secret-access-key");
    }

    #[test]
    fn target_no_sign_request_conflicts_with_profile() {
        let res = TestCli::try_parse_from([
            "test",
            "--target-no-sign-request",
            "--target-profile",
            "default",
        ]);
        assert!(res.is_err(), "no-sign-request must conflict with profile");
    }

    #[test]
    fn target_region_rejects_empty() {
        let res = TestCli::try_parse_from(["test", "--target-region", ""]);
        assert!(res.is_err(), "empty region must be rejected");
    }

    #[test]
    fn build_client_config_uses_environment_credentials_by_default() {
        let cli = TestCli::try_parse_from(["test"]).unwrap();
        let cfg = cli.common.build_client_config();
        assert!(matches!(
            cfg.credential,
            crate::types::S3Credentials::FromEnvironment
        ));
        assert_eq!(cfg.retry_config.aws_max_attempts, DEFAULT_AWS_MAX_ATTEMPTS);
        assert!(!cfg.disable_stalled_stream_protection);
    }

    #[test]
    fn build_client_config_uses_no_sign_request_when_set() {
        let cli = TestCli::try_parse_from(["test", "--target-no-sign-request"]).unwrap();
        let cfg = cli.common.build_client_config();
        assert!(matches!(
            cfg.credential,
            crate::types::S3Credentials::NoSignRequest
        ));
    }

    #[test]
    fn build_client_config_uses_explicit_keys() {
        let cli = TestCli::try_parse_from([
            "test",
            "--target-access-key",
            "AKIA",
            "--target-secret-access-key",
            "secret",
        ])
        .unwrap();
        let cfg = cli.common.build_client_config();
        assert!(matches!(
            cfg.credential,
            crate::types::S3Credentials::Credentials { .. }
        ));
    }

    #[test]
    fn build_client_config_uses_profile_when_set() {
        let cli = TestCli::try_parse_from(["test", "--target-profile", "prod"]).unwrap();
        let cfg = cli.common.build_client_config();
        match cfg.credential {
            crate::types::S3Credentials::Profile(name) => assert_eq!(name, "prod"),
            other => panic!("expected Profile, got {other:?}"),
        }
    }

    #[test]
    fn build_client_config_propagates_request_payer_and_accelerate() {
        let cli =
            TestCli::try_parse_from(["test", "--target-request-payer", "--target-accelerate"])
                .unwrap();
        let cfg = cli.common.build_client_config();
        assert_eq!(
            cfg.request_payer,
            Some(aws_sdk_s3::types::RequestPayer::Requester)
        );
        assert!(cfg.accelerate);
    }

    #[test]
    fn build_tracing_config_returns_some_at_default_verbosity() {
        let cli = TestCli::try_parse_from(["test"]).unwrap();
        let cfg = cli.common.build_tracing_config();
        assert!(cfg.is_some());
        let cfg = cfg.unwrap();
        assert_eq!(cfg.tracing_level, log::Level::Warn);
        assert!(!cfg.json_tracing);
    }

    #[test]
    fn build_tracing_config_returns_none_when_silenced() {
        let cli = TestCli::try_parse_from(["test", "-qqq"]).unwrap();
        let cfg = cli.common.build_tracing_config();
        assert!(cfg.is_none(), "expected None when verbosity below Error");
    }

    #[test]
    fn build_tracing_config_propagates_flags() {
        let cli = TestCli::try_parse_from([
            "test",
            "--json-tracing",
            "--aws-sdk-tracing",
            "--span-events-tracing",
            "--disable-color-tracing",
        ])
        .unwrap();
        let cfg = cli.common.build_tracing_config().unwrap();
        assert!(cfg.json_tracing);
        assert!(cfg.aws_sdk_tracing);
        assert!(cfg.span_events_tracing);
        assert!(cfg.disable_color_tracing);
    }

    #[test]
    fn build_tracing_config_dry_run_false_matches_normal() {
        let cli = TestCli::try_parse_from(["test"]).unwrap();
        let normal = cli.common.build_tracing_config();
        let dry = cli.common.build_tracing_config_dry_run(false);
        assert_eq!(
            normal.map(|c| c.tracing_level),
            dry.map(|c| c.tracing_level)
        );
    }

    #[test]
    fn build_tracing_config_dry_run_false_returns_none_when_silenced() {
        let cli = TestCli::try_parse_from(["test", "-qqq"]).unwrap();
        let cfg = cli.common.build_tracing_config_dry_run(false);
        assert!(cfg.is_none());
    }

    #[test]
    fn build_tracing_config_dry_run_bumps_default_warn_to_info() {
        let cli = TestCli::try_parse_from(["test"]).unwrap();
        let cfg = cli.common.build_tracing_config_dry_run(true).unwrap();
        assert_eq!(cfg.tracing_level, log::Level::Info);
    }

    #[test]
    fn build_tracing_config_dry_run_keeps_explicit_info() {
        let cli = TestCli::try_parse_from(["test", "-v"]).unwrap();
        let cfg = cli.common.build_tracing_config_dry_run(true).unwrap();
        assert_eq!(cfg.tracing_level, log::Level::Info);
    }

    #[test]
    fn build_tracing_config_dry_run_preserves_debug() {
        let cli = TestCli::try_parse_from(["test", "-vv"]).unwrap();
        let cfg = cli.common.build_tracing_config_dry_run(true).unwrap();
        assert_eq!(
            cfg.tracing_level,
            log::Level::Debug,
            "debug must not be downgraded to info"
        );
    }

    #[test]
    fn build_tracing_config_dry_run_preserves_trace() {
        let cli = TestCli::try_parse_from(["test", "-vvv"]).unwrap();
        let cfg = cli.common.build_tracing_config_dry_run(true).unwrap();
        assert_eq!(
            cfg.tracing_level,
            log::Level::Trace,
            "trace must not be downgraded to info"
        );
    }

    #[test]
    fn build_tracing_config_dry_run_bumps_error_to_info() {
        let cli = TestCli::try_parse_from(["test", "-q"]).unwrap();
        let cfg = cli.common.build_tracing_config_dry_run(true).unwrap();
        assert_eq!(cfg.tracing_level, log::Level::Info);
    }

    #[test]
    fn build_tracing_config_dry_run_bumps_silenced_to_info() {
        // -qqq normally returns None; with dry_run we override that to Info
        // so the [dry-run] message stays visible.
        let cli = TestCli::try_parse_from(["test", "-qqq"]).unwrap();
        let cfg = cli.common.build_tracing_config_dry_run(true);
        assert!(cfg.is_some(), "dry-run must override -qqq silencing");
        assert_eq!(cfg.unwrap().tracing_level, log::Level::Info);
    }

    #[test]
    fn build_tracing_config_dry_run_propagates_format_flags() {
        let cli = TestCli::try_parse_from([
            "test",
            "--json-tracing",
            "--aws-sdk-tracing",
            "--span-events-tracing",
            "--disable-color-tracing",
            "-qqq",
        ])
        .unwrap();
        let cfg = cli.common.build_tracing_config_dry_run(true).unwrap();
        assert!(cfg.json_tracing);
        assert!(cfg.aws_sdk_tracing);
        assert!(cfg.span_events_tracing);
        assert!(cfg.disable_color_tracing);
        assert_eq!(cfg.tracing_level, log::Level::Info);
    }
}