rustfs-cli 0.1.30

A Rust S3 CLI client for S3-compatible object storage
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
//! Bucket Object Lock commands and shared WORM command output helpers.

use clap::{Args, Subcommand, ValueEnum};
use comfy_table::Table;
use rc_core::{
    AliasManager, BucketObjectLockConfiguration, DefaultRetention, ObjectRetention,
    ObjectStore as _, ParsedPath, RemotePath, RetentionDuration, RetentionMode, parse_path,
};
use rc_s3::S3Client;
use serde::Serialize;

use crate::exit_code::ExitCode;
use crate::output::{Formatter, OutputConfig, V3ErrorEnvelope, V3SuccessEnvelope};

const LOCK_CAPABILITY: &str = "object_lock";

/// Manage bucket Object Lock configuration.
#[derive(Args, Debug)]
pub struct LockArgs {
    #[command(subcommand)]
    pub command: LockCommands,
}

#[derive(Subcommand, Debug)]
pub enum LockCommands {
    /// Show bucket Object Lock and default retention configuration.
    Info(BucketLockArg),
    /// Set a bucket default retention rule.
    Set(SetBucketLockArgs),
    /// Clear the bucket default retention rule without disabling Object Lock.
    Clear(BucketLockArg),
}

#[derive(Args, Debug)]
pub struct BucketLockArg {
    /// Bucket path in alias/bucket form.
    pub path: String,
}

#[derive(Args, Debug)]
pub struct SetBucketLockArgs {
    /// Bucket path in alias/bucket form.
    pub path: String,
    /// Default retention mode.
    #[arg(long)]
    pub mode: RetentionModeArg,
    /// Positive default retention duration in days.
    #[arg(long, conflicts_with = "years", required_unless_present = "years")]
    pub days: Option<i32>,
    /// Positive default retention duration in years.
    #[arg(long, conflicts_with = "days", required_unless_present = "days")]
    pub years: Option<i32>,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
pub enum RetentionModeArg {
    Governance,
    Compliance,
}

impl From<RetentionModeArg> for RetentionMode {
    fn from(value: RetentionModeArg) -> Self {
        match value {
            RetentionModeArg::Governance => Self::Governance,
            RetentionModeArg::Compliance => Self::Compliance,
        }
    }
}

#[derive(Debug, Serialize)]
pub(crate) struct LocksData {
    operation: &'static str,
    changed: bool,
    items: Vec<LockStateOutput>,
}

impl LocksData {
    pub(crate) fn one(operation: &'static str, changed: bool, item: LockStateOutput) -> Self {
        Self {
            operation,
            changed,
            items: vec![item],
        }
    }
}

#[derive(Debug, Serialize)]
pub(crate) struct LockStateOutput {
    bucket: String,
    key: String,
    version_id: Option<String>,
    object_lock_enabled: bool,
    retention: Option<ObjectRetention>,
    legal_hold: Option<bool>,
    default_retention: Option<DefaultRetention>,
}

impl LockStateOutput {
    pub(crate) fn bucket(
        bucket: String,
        configuration: Option<BucketObjectLockConfiguration>,
    ) -> Self {
        let configuration = configuration.unwrap_or(BucketObjectLockConfiguration {
            enabled: false,
            default_retention: None,
        });
        Self {
            bucket,
            key: String::new(),
            version_id: None,
            object_lock_enabled: configuration.enabled,
            retention: None,
            legal_hold: None,
            default_retention: configuration.default_retention,
        }
    }

    pub(crate) fn retention(
        path: &RemotePath,
        version_id: Option<String>,
        retention: Option<ObjectRetention>,
    ) -> Self {
        Self {
            bucket: path.bucket.clone(),
            key: path.key.clone(),
            version_id,
            object_lock_enabled: true,
            retention,
            legal_hold: None,
            default_retention: None,
        }
    }

    pub(crate) fn legal_hold(path: &RemotePath, version_id: Option<String>, enabled: bool) -> Self {
        Self {
            bucket: path.bucket.clone(),
            key: path.key.clone(),
            version_id,
            object_lock_enabled: true,
            retention: None,
            legal_hold: Some(enabled),
            default_retention: None,
        }
    }
}

pub async fn execute(args: LockArgs, output_config: OutputConfig) -> ExitCode {
    match args.command {
        LockCommands::Info(args) => execute_info(args, output_config).await,
        LockCommands::Set(args) => execute_set(args, output_config).await,
        LockCommands::Clear(args) => execute_clear(args, output_config).await,
    }
}

async fn execute_info(args: BucketLockArg, output_config: OutputConfig) -> ExitCode {
    let formatter = Formatter::new(output_config);
    let path = match parse_bucket_path(&args.path) {
        Ok(path) => path,
        Err(error) => return fail_lock(&formatter, ExitCode::UsageError, &error, LOCK_CAPABILITY),
    };
    let client = match setup_client(&path.alias, &formatter, LOCK_CAPABILITY).await {
        Ok(client) => client,
        Err(code) => return code,
    };
    match client
        .get_bucket_object_lock_configuration(&path.bucket)
        .await
    {
        Ok(configuration) => emit_lock_output(
            &formatter,
            LocksData {
                operation: "bucket_lock_info",
                changed: false,
                items: vec![LockStateOutput::bucket(path.bucket, configuration)],
            },
        ),
        Err(error) => fail_core_lock(
            &formatter,
            &error,
            "Failed to get bucket Object Lock configuration",
            LOCK_CAPABILITY,
        ),
    }
}

async fn execute_set(args: SetBucketLockArgs, output_config: OutputConfig) -> ExitCode {
    let formatter = Formatter::new(output_config);
    let path = match parse_bucket_path(&args.path) {
        Ok(path) => path,
        Err(error) => return fail_lock(&formatter, ExitCode::UsageError, &error, LOCK_CAPABILITY),
    };
    let duration = match parse_bucket_duration(args.days, args.years) {
        Ok(duration) => duration,
        Err(error) => return fail_lock(&formatter, ExitCode::UsageError, &error, LOCK_CAPABILITY),
    };
    let client = match setup_client(&path.alias, &formatter, LOCK_CAPABILITY).await {
        Ok(client) => client,
        Err(code) => return code,
    };
    let existing = match client
        .get_bucket_object_lock_configuration(&path.bucket)
        .await
    {
        Ok(Some(configuration)) if configuration.enabled => configuration,
        Ok(_) => {
            return fail_lock(
                &formatter,
                ExitCode::Conflict,
                "Object Lock must be enabled when the bucket is created before its default retention can be updated",
                LOCK_CAPABILITY,
            );
        }
        Err(error) => {
            return fail_core_lock(
                &formatter,
                &error,
                "Failed to inspect bucket Object Lock configuration",
                LOCK_CAPABILITY,
            );
        }
    };
    let requested = BucketObjectLockConfiguration {
        enabled: existing.enabled,
        default_retention: Some(DefaultRetention {
            mode: args.mode.into(),
            duration,
        }),
    };
    if let Err(error) = client
        .put_bucket_object_lock_configuration(&path.bucket, requested)
        .await
    {
        return fail_core_lock(
            &formatter,
            &error,
            "Failed to set bucket Object Lock configuration",
            LOCK_CAPABILITY,
        );
    }
    emit_bucket_round_trip(&client, &formatter, path.bucket, "bucket_lock_set").await
}

async fn execute_clear(args: BucketLockArg, output_config: OutputConfig) -> ExitCode {
    let formatter = Formatter::new(output_config);
    let path = match parse_bucket_path(&args.path) {
        Ok(path) => path,
        Err(error) => return fail_lock(&formatter, ExitCode::UsageError, &error, LOCK_CAPABILITY),
    };
    let client = match setup_client(&path.alias, &formatter, LOCK_CAPABILITY).await {
        Ok(client) => client,
        Err(code) => return code,
    };
    let existing = match client
        .get_bucket_object_lock_configuration(&path.bucket)
        .await
    {
        Ok(Some(configuration)) if configuration.enabled => configuration,
        Ok(_) => {
            return fail_lock(
                &formatter,
                ExitCode::Conflict,
                "Object Lock is not enabled for this bucket",
                LOCK_CAPABILITY,
            );
        }
        Err(error) => {
            return fail_core_lock(
                &formatter,
                &error,
                "Failed to inspect bucket Object Lock configuration",
                LOCK_CAPABILITY,
            );
        }
    };
    let requested = BucketObjectLockConfiguration {
        enabled: existing.enabled,
        default_retention: None,
    };
    if let Err(error) = client
        .put_bucket_object_lock_configuration(&path.bucket, requested)
        .await
    {
        return fail_core_lock(
            &formatter,
            &error,
            "Failed to clear bucket default retention",
            LOCK_CAPABILITY,
        );
    }
    emit_bucket_round_trip(&client, &formatter, path.bucket, "bucket_lock_clear").await
}

async fn emit_bucket_round_trip(
    client: &S3Client,
    formatter: &Formatter,
    bucket: String,
    operation: &'static str,
) -> ExitCode {
    match client.get_bucket_object_lock_configuration(&bucket).await {
        Ok(configuration) => emit_lock_output(
            formatter,
            LocksData {
                operation,
                changed: true,
                items: vec![LockStateOutput::bucket(bucket, configuration)],
            },
        ),
        Err(error) => fail_core_lock(
            formatter,
            &error,
            "Bucket Object Lock changed, but the updated configuration could not be read back",
            LOCK_CAPABILITY,
        ),
    }
}

fn parse_bucket_duration(
    days: Option<i32>,
    years: Option<i32>,
) -> Result<RetentionDuration, String> {
    match (days, years) {
        (Some(days), None) => RetentionDuration::days(days).map_err(|error| error.to_string()),
        (None, Some(years)) => RetentionDuration::years(years).map_err(|error| error.to_string()),
        (Some(_), Some(_)) => Err("Specify only one of --days or --years".to_string()),
        (None, None) => Err("Specify exactly one of --days or --years".to_string()),
    }
}

pub(crate) fn parse_bucket_path(value: &str) -> Result<RemotePath, String> {
    match parse_path(value).map_err(|error| error.to_string())? {
        ParsedPath::Remote(path) if path.key.is_empty() => Ok(path),
        _ => Err("Bucket path must use the form alias/bucket".to_string()),
    }
}

pub(crate) async fn setup_client(
    alias_name: &str,
    formatter: &Formatter,
    capability: &str,
) -> Result<S3Client, ExitCode> {
    let manager = AliasManager::new()
        .map_err(|error| fail_core_lock(formatter, &error, "Failed to load aliases", capability))?;
    let alias = manager.get(alias_name).map_err(|error| {
        fail_core_lock(formatter, &error, "Failed to resolve alias", capability)
    })?;
    S3Client::new(alias).await.map_err(|error| {
        fail_core_lock(formatter, &error, "Failed to create S3 client", capability)
    })
}

pub(crate) fn emit_lock_output(formatter: &Formatter, data: LocksData) -> ExitCode {
    if formatter.is_json() {
        formatter.json(&V3SuccessEnvelope::locks(&data));
    } else {
        formatter.println(&render_lock_table(&data.items, formatter));
    }
    ExitCode::Success
}

fn render_lock_table(items: &[LockStateOutput], formatter: &Formatter) -> String {
    let mut table = Table::new();
    table.set_header([
        "BUCKET",
        "OBJECT",
        "VERSION",
        "LOCK",
        "RETENTION",
        "RETAIN UNTIL",
        "LEGAL HOLD",
        "DEFAULT",
    ]);
    for item in items {
        let bucket = formatter.sanitize_text(&item.bucket);
        let key = formatter.sanitize_text(&item.key);
        let version_id = item
            .version_id
            .as_deref()
            .map(|value| formatter.sanitize_text(value));
        let (mode, retain_until) = item
            .retention
            .as_ref()
            .map(|retention| {
                (
                    retention.mode.to_string().to_ascii_uppercase(),
                    retention.retain_until.to_string(),
                )
            })
            .unwrap_or_else(|| ("-".to_string(), "-".to_string()));
        let legal_hold = match item.legal_hold {
            Some(true) => "ON",
            Some(false) => "OFF",
            None => "-",
        };
        let default = item
            .default_retention
            .as_ref()
            .map(|retention| {
                format!(
                    "{} {} {}",
                    retention.mode.to_string().to_ascii_uppercase(),
                    retention.duration.value,
                    retention.duration.unit
                )
            })
            .unwrap_or_else(|| "-".to_string());
        table.add_row([
            bucket.as_str(),
            if key.is_empty() { "-" } else { key.as_str() },
            version_id.as_deref().unwrap_or("-"),
            if item.object_lock_enabled {
                "ENABLED"
            } else {
                "DISABLED"
            },
            mode.as_str(),
            retain_until.as_str(),
            legal_hold,
            default.as_str(),
        ]);
    }
    table.to_string()
}

pub(crate) fn fail_core_lock(
    formatter: &Formatter,
    error: &rc_core::Error,
    context: &str,
    capability: &str,
) -> ExitCode {
    let code = ExitCode::from_i32(error.exit_code()).unwrap_or(ExitCode::GeneralError);
    fail_lock(formatter, code, &format!("{context}: {error}"), capability)
}

pub(crate) fn fail_lock(
    formatter: &Formatter,
    code: ExitCode,
    message: &str,
    capability: &str,
) -> ExitCode {
    if formatter.is_json() {
        formatter.json_error(&V3ErrorEnvelope::locks(code, message, Some(capability)));
        code
    } else {
        formatter.fail(code, message)
    }
}

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

    #[test]
    fn bucket_duration_requires_one_positive_unit() {
        assert_eq!(
            parse_bucket_duration(Some(30), None)
                .expect("valid days")
                .unit,
            rc_core::RetentionDurationUnit::Days
        );
        assert!(parse_bucket_duration(Some(1), Some(1)).is_err());
        assert!(parse_bucket_duration(None, None).is_err());
        assert!(parse_bucket_duration(Some(0), None).is_err());
    }

    #[test]
    fn bucket_paths_cannot_select_objects() {
        assert!(parse_bucket_path("local/bucket").is_ok());
        assert!(parse_bucket_path("local/bucket/key").is_err());
    }
}