rustfs-cli 0.1.20

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
//! encryption command - Manage bucket default encryption.
//!
//! Set, inspect, or clear bucket default encryption for a bucket path.

use clap::{Args, Subcommand, ValueEnum};
use rc_core::{AliasManager, BucketEncryption, ObjectStore as _};
use rc_s3::S3Client;
use serde::Serialize;

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

const ENCRYPTION_AFTER_HELP: &str = "\
Examples:
  rc bucket encryption set local/my-bucket --mode sse-s3
  rc bucket encryption set local/my-bucket --mode sse-kms --key-id alias/my-key
  rc bucket encryption info local/my-bucket
  rc bucket encryption clear local/my-bucket";

const SET_AFTER_HELP: &str = "\
Examples:
  rc bucket encryption set local/my-bucket --mode sse-s3
  rc bucket encryption set local/my-bucket --mode sse-kms --key-id alias/my-key";

const INFO_AFTER_HELP: &str = "\
Examples:
  rc bucket encryption info local/my-bucket";

const CLEAR_AFTER_HELP: &str = "\
Examples:
  rc bucket encryption clear local/my-bucket";

/// Manage bucket default encryption
#[derive(Args, Debug)]
#[command(after_help = ENCRYPTION_AFTER_HELP)]
pub struct EncryptionArgs {
    #[command(subcommand)]
    pub command: EncryptionCommands,
}

#[derive(Subcommand, Debug)]
pub enum EncryptionCommands {
    /// Set bucket default encryption
    Set(SetEncryptionArgs),

    /// Show bucket default encryption
    Info(InfoEncryptionArgs),

    /// Clear bucket default encryption
    Clear(ClearEncryptionArgs),
}

#[derive(Copy, Clone, Debug, Eq, PartialEq, ValueEnum)]
pub enum EncryptionMode {
    SseS3,
    SseKms,
}

#[derive(Args, Debug)]
#[command(after_help = SET_AFTER_HELP)]
pub struct SetEncryptionArgs {
    /// Path to the bucket (alias/bucket)
    pub path: String,

    /// Default encryption mode
    #[arg(long)]
    pub mode: EncryptionMode,

    /// KMS key id for sse-kms mode
    #[arg(long)]
    pub key_id: Option<String>,
}

#[derive(Args, Debug)]
pub struct BucketArg {
    /// Path to the bucket (alias/bucket)
    pub path: String,
}

#[derive(Args, Debug)]
#[command(after_help = INFO_AFTER_HELP)]
pub struct InfoEncryptionArgs {
    #[command(flatten)]
    pub bucket: BucketArg,
}

#[derive(Args, Debug)]
#[command(after_help = CLEAR_AFTER_HELP)]
pub struct ClearEncryptionArgs {
    #[command(flatten)]
    pub bucket: BucketArg,
}

#[derive(Debug, Serialize)]
struct BucketEncryptionOutput {
    bucket: String,
    status: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    mode: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    kms_key_id: Option<String>,
}

/// Execute the encryption command
pub async fn execute(args: EncryptionArgs, output_config: OutputConfig) -> ExitCode {
    match args.command {
        EncryptionCommands::Set(args) => execute_set(args, output_config).await,
        EncryptionCommands::Info(args) => execute_info(args, output_config).await,
        EncryptionCommands::Clear(args) => execute_clear(args, output_config).await,
    }
}

async fn execute_set(args: SetEncryptionArgs, output_config: OutputConfig) -> ExitCode {
    let formatter = Formatter::new(output_config);
    let (alias_name, bucket) = match parse_bucket_path(&args.path) {
        Ok(parts) => parts,
        Err(error) => {
            return formatter.fail_with_suggestion(
                ExitCode::UsageError,
                &error,
                "Use a bucket path in the form alias/bucket before retrying the encryption command.",
            );
        }
    };

    let encryption = match validate_set_encryption_args(&args, &formatter) {
        Ok(encryption) => encryption,
        Err(code) => return code,
    };

    let client = match setup_client(&alias_name, &bucket, &formatter).await {
        Ok(client) => client,
        Err(code) => return code,
    };

    match client
        .set_bucket_encryption(&bucket, encryption.clone())
        .await
    {
        Ok(()) => {
            let output = output_for_encryption(bucket, Some(encryption), "Not configured");
            if formatter.is_json() {
                formatter.json(&output);
            } else {
                formatter.println(&format!("Bucket: {}", output.bucket));
                formatter.println(&format!("Encryption: {}", output.status));
                if let Some(mode) = output.mode {
                    formatter.println(&format!("Mode: {mode}"));
                }
                if let Some(key_id) = output.kms_key_id {
                    formatter.println(&format!("KMS Key ID: {key_id}"));
                }
            }
            ExitCode::Success
        }
        Err(error) => formatter.fail(
            exit_code_from_error(&error),
            &format!("Failed to set bucket encryption: {error}"),
        ),
    }
}

fn validate_set_encryption_args(
    args: &SetEncryptionArgs,
    formatter: &Formatter,
) -> Result<BucketEncryption, ExitCode> {
    match (args.mode, args.key_id.as_deref()) {
        (EncryptionMode::SseS3, None) => Ok(BucketEncryption::SseS3),
        (EncryptionMode::SseS3, Some(_)) => Err(formatter.fail(
            ExitCode::UsageError,
            "--key-id is only valid with --mode sse-kms",
        )),
        (EncryptionMode::SseKms, Some(key_id)) => Ok(BucketEncryption::SseKms {
            key_id: Some(key_id.to_string()),
        }),
        (EncryptionMode::SseKms, None) => Err(formatter.fail(
            ExitCode::UsageError,
            "--key-id is required with --mode sse-kms",
        )),
    }
}

async fn execute_info(args: InfoEncryptionArgs, output_config: OutputConfig) -> ExitCode {
    let formatter = Formatter::new(output_config);
    let (alias_name, bucket) = match parse_bucket_path(&args.bucket.path) {
        Ok(parts) => parts,
        Err(error) => {
            return formatter.fail_with_suggestion(
                ExitCode::UsageError,
                &error,
                "Use a bucket path in the form alias/bucket before retrying the encryption command.",
            );
        }
    };

    let client = match setup_client(&alias_name, &bucket, &formatter).await {
        Ok(client) => client,
        Err(code) => return code,
    };

    match client.get_bucket_encryption(&bucket).await {
        Ok(encryption) => {
            let output = output_for_encryption(bucket, encryption, "Not configured");
            if formatter.is_json() {
                formatter.json(&output);
            } else {
                formatter.println(&format!("Bucket: {}", output.bucket));
                formatter.println(&format!("Encryption: {}", output.status));
                if let Some(mode) = output.mode {
                    formatter.println(&format!("Mode: {mode}"));
                }
                if let Some(key_id) = output.kms_key_id {
                    formatter.println(&format!("KMS Key ID: {key_id}"));
                }
            }
            ExitCode::Success
        }
        Err(error) => formatter.fail(
            exit_code_from_error(&error),
            &format!("Failed to get bucket encryption: {error}"),
        ),
    }
}

async fn execute_clear(args: ClearEncryptionArgs, output_config: OutputConfig) -> ExitCode {
    let formatter = Formatter::new(output_config);
    let (alias_name, bucket) = match parse_bucket_path(&args.bucket.path) {
        Ok(parts) => parts,
        Err(error) => {
            return formatter.fail_with_suggestion(
                ExitCode::UsageError,
                &error,
                "Use a bucket path in the form alias/bucket before retrying the encryption command.",
            );
        }
    };

    let client = match setup_client(&alias_name, &bucket, &formatter).await {
        Ok(client) => client,
        Err(code) => return code,
    };

    match client.delete_bucket_encryption(&bucket).await {
        Ok(()) => {
            if formatter.is_json() {
                formatter.json(&BucketEncryptionOutput {
                    bucket,
                    status: "Cleared".to_string(),
                    mode: None,
                    kms_key_id: None,
                });
            } else {
                formatter.success("Bucket encryption configuration cleared successfully.");
            }
            ExitCode::Success
        }
        Err(error) => formatter.fail(
            exit_code_from_error(&error),
            &format!("Failed to clear bucket encryption: {error}"),
        ),
    }
}

async fn setup_client(
    alias_name: &str,
    bucket: &str,
    formatter: &Formatter,
) -> Result<S3Client, ExitCode> {
    let alias_manager = match AliasManager::new() {
        Ok(manager) => manager,
        Err(error) => {
            return Err(formatter.fail(
                ExitCode::GeneralError,
                &format!("Failed to load aliases: {error}"),
            ));
        }
    };

    let alias = match alias_manager.get(alias_name) {
        Ok(alias) => alias,
        Err(_) => {
            return Err(formatter.fail_with_suggestion(
                ExitCode::NotFound,
                &format!("Alias '{alias_name}' not found"),
                "Run `rc alias list` to inspect configured aliases or add one with `rc alias set ...`.",
            ));
        }
    };

    let client = match S3Client::new(alias).await {
        Ok(client) => client,
        Err(error) => {
            return Err(formatter.fail(
                ExitCode::NetworkError,
                &format!("Failed to create S3 client: {error}"),
            ));
        }
    };

    match client.bucket_exists(bucket).await {
        Ok(true) => {}
        Ok(false) => {
            return Err(formatter.fail_with_suggestion(
                ExitCode::NotFound,
                &format!("Bucket '{bucket}' does not exist"),
                "Check the bucket path and retry the encryption command.",
            ));
        }
        Err(error) => {
            return Err(formatter.fail(
                ExitCode::NetworkError,
                &format!("Failed to check bucket: {error}"),
            ));
        }
    }

    Ok(client)
}

fn parse_bucket_path(path: &str) -> Result<(String, String), String> {
    if path.is_empty() {
        return Err("Bucket path must be in format alias/bucket".to_string());
    }

    let parts: Vec<&str> = path.splitn(2, '/').collect();
    if parts.len() < 2 || parts[0].is_empty() || parts[1].is_empty() {
        return Err("Bucket path must be in format alias/bucket".to_string());
    }

    let bucket = parts[1].trim_end_matches('/');
    if bucket.is_empty() || bucket.contains('/') {
        return Err("Bucket path must be in format alias/bucket".to_string());
    }

    Ok((parts[0].to_string(), bucket.to_string()))
}

fn output_for_encryption(
    bucket: String,
    encryption: Option<BucketEncryption>,
    empty_status: &str,
) -> BucketEncryptionOutput {
    match encryption {
        Some(BucketEncryption::SseS3) => BucketEncryptionOutput {
            bucket,
            status: "Configured".to_string(),
            mode: Some("SSE-S3".to_string()),
            kms_key_id: None,
        },
        Some(BucketEncryption::SseKms { key_id }) => BucketEncryptionOutput {
            bucket,
            status: "Configured".to_string(),
            mode: Some("SSE-KMS".to_string()),
            kms_key_id: key_id,
        },
        None => BucketEncryptionOutput {
            bucket,
            status: empty_status.to_string(),
            mode: None,
            kms_key_id: None,
        },
    }
}

fn exit_code_from_error(error: &rc_core::Error) -> ExitCode {
    ExitCode::from_i32(error.exit_code()).unwrap_or(ExitCode::GeneralError)
}

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

    #[test]
    fn parse_bucket_path_rejects_object_paths() {
        assert!(parse_bucket_path("local/bucket/object.txt").is_err());
    }

    #[tokio::test]
    async fn execute_set_kms_without_key_id_returns_usage_error() {
        let args = EncryptionArgs {
            command: EncryptionCommands::Set(SetEncryptionArgs {
                path: "local/my-bucket".to_string(),
                mode: EncryptionMode::SseKms,
                key_id: None,
            }),
        };

        let code = execute(args, OutputConfig::default()).await;
        assert_eq!(code, ExitCode::UsageError);
    }

    #[tokio::test]
    async fn execute_set_invalid_bucket_path_returns_usage_error() {
        let args = EncryptionArgs {
            command: EncryptionCommands::Set(SetEncryptionArgs {
                path: "local/my-bucket/object.txt".to_string(),
                mode: EncryptionMode::SseS3,
                key_id: None,
            }),
        };

        let code = execute(args, OutputConfig::default()).await;
        assert_eq!(code, ExitCode::UsageError);
    }

    #[tokio::test]
    async fn execute_set_sse_s3_with_key_id_returns_usage_error() {
        let args = EncryptionArgs {
            command: EncryptionCommands::Set(SetEncryptionArgs {
                path: "local/my-bucket".to_string(),
                mode: EncryptionMode::SseS3,
                key_id: Some("kms-key".to_string()),
            }),
        };

        let code = execute(args, OutputConfig::default()).await;
        assert_eq!(code, ExitCode::UsageError);
    }

    #[tokio::test]
    async fn execute_info_invalid_bucket_path_returns_usage_error() {
        let args = EncryptionArgs {
            command: EncryptionCommands::Info(InfoEncryptionArgs {
                bucket: BucketArg {
                    path: "local/my-bucket/object.txt".to_string(),
                },
            }),
        };

        let code = execute(args, OutputConfig::default()).await;
        assert_eq!(code, ExitCode::UsageError);
    }

    #[tokio::test]
    async fn execute_clear_invalid_bucket_path_returns_usage_error() {
        let args = EncryptionArgs {
            command: EncryptionCommands::Clear(ClearEncryptionArgs {
                bucket: BucketArg {
                    path: "local/my-bucket/object.txt".to_string(),
                },
            }),
        };

        let code = execute(args, OutputConfig::default()).await;
        assert_eq!(code, ExitCode::UsageError);
    }
}