rustfs-cli 0.1.12

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
//! Service account management commands
//!
//! Commands for managing service accounts: list, create, info, remove.

use clap::Subcommand;
use serde::Serialize;

use super::get_admin_client;
use crate::exit_code::ExitCode;
use crate::output::Formatter;
use rc_core::admin::{AdminApi, CreateServiceAccountRequest, ServiceAccount};

const DEFAULT_SERVICE_ACCOUNT_EXPIRY: &str = "9999-12-31T23:59:59Z";

/// Service account management subcommands
#[derive(Subcommand, Debug)]
pub enum ServiceAccountCommands {
    /// List service accounts
    #[command(name = "ls", alias = "list")]
    List(ListArgs),

    /// Create a new service account
    Create(CreateArgs),

    /// Get service account information
    Info(InfoArgs),

    /// Remove a service account
    #[command(name = "rm", alias = "remove")]
    Remove(RemoveArgs),
}

#[derive(clap::Args, Debug)]
pub struct ListArgs {
    /// Alias name of the server
    pub alias: String,

    /// Filter by parent user
    #[arg(long)]
    pub user: Option<String>,
}

#[derive(clap::Args, Debug)]
pub struct CreateArgs {
    /// Alias name of the server
    pub alias: String,

    /// Access key for the service account
    pub access_key: String,

    /// Secret key for the service account
    pub secret_key: String,

    /// Optional name for the service account
    #[arg(long)]
    pub name: Option<String>,

    /// Optional description
    #[arg(long)]
    pub description: Option<String>,

    /// Optional policy document (JSON file path)
    #[arg(long)]
    pub policy: Option<String>,

    /// Optional expiration time (ISO 8601 format)
    #[arg(long)]
    pub expiry: Option<String>,
}

#[derive(clap::Args, Debug)]
pub struct InfoArgs {
    /// Alias name of the server
    pub alias: String,

    /// Access key of the service account
    pub access_key: String,
}

#[derive(clap::Args, Debug)]
pub struct RemoveArgs {
    /// Alias name of the server
    pub alias: String,

    /// Access key of the service account to remove
    pub access_key: String,
}

/// JSON output for service account list
#[derive(Serialize)]
struct ServiceAccountListOutput {
    accounts: Vec<ServiceAccountInfo>,
}

/// JSON representation of a service account
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct ServiceAccountInfo {
    access_key: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    secret_key: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    parent_user: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    account_status: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    expiration: Option<String>,
}

impl From<ServiceAccount> for ServiceAccountInfo {
    fn from(sa: ServiceAccount) -> Self {
        Self {
            access_key: sa.access_key,
            secret_key: sa.secret_key,
            parent_user: sa.parent_user,
            account_status: sa.account_status,
            expiration: sa.expiration,
        }
    }
}

/// JSON output for service account create
#[derive(Serialize)]
struct ServiceAccountCreateOutput {
    success: bool,
    access_key: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    secret_key: Option<String>,
    message: String,
}

/// JSON output for service account operations
#[derive(Serialize)]
struct ServiceAccountOperationOutput {
    success: bool,
    access_key: String,
    message: String,
}

/// Execute a service account subcommand
pub async fn execute(cmd: ServiceAccountCommands, formatter: &Formatter) -> ExitCode {
    match cmd {
        ServiceAccountCommands::List(args) => execute_list(args, formatter).await,
        ServiceAccountCommands::Create(args) => execute_create(args, formatter).await,
        ServiceAccountCommands::Info(args) => execute_info(args, formatter).await,
        ServiceAccountCommands::Remove(args) => execute_remove(args, formatter).await,
    }
}

async fn execute_list(args: ListArgs, formatter: &Formatter) -> ExitCode {
    let client = match get_admin_client(&args.alias, formatter) {
        Ok(c) => c,
        Err(code) => return code,
    };

    match client.list_service_accounts(args.user.as_deref()).await {
        Ok(accounts) => {
            if formatter.is_json() {
                let output = ServiceAccountListOutput {
                    accounts: accounts.into_iter().map(ServiceAccountInfo::from).collect(),
                };
                formatter.json(&output);
            } else if accounts.is_empty() {
                formatter.println("No service accounts found.");
            } else {
                for sa in accounts {
                    let styled_key = formatter.style_name(&sa.access_key);
                    let parent = sa
                        .parent_user
                        .map(|p| format!(" (parent: {})", p))
                        .unwrap_or_default();
                    let status = sa
                        .account_status
                        .map(|s| format!(" [{}]", s))
                        .unwrap_or_default();
                    formatter.println(&format!("  {styled_key}{parent}{status}"));
                }
            }
            ExitCode::Success
        }
        Err(e) => {
            formatter.error(&format!("Failed to list service accounts: {e}"));
            ExitCode::GeneralError
        }
    }
}

async fn execute_create(args: CreateArgs, formatter: &Formatter) -> ExitCode {
    let client = match get_admin_client(&args.alias, formatter) {
        Ok(c) => c,
        Err(code) => return code,
    };

    // Read policy if provided
    let policy = if let Some(policy_path) = &args.policy {
        match std::fs::read_to_string(policy_path) {
            Ok(content) => Some(content),
            Err(e) => {
                formatter.error(&format!(
                    "Failed to read policy file '{}': {e}",
                    policy_path
                ));
                return ExitCode::UsageError;
            }
        }
    } else {
        None
    };

    let request = build_create_service_account_request(&args, policy);
    let create_result = match client.create_service_account(request.clone()).await {
        Ok(sa) => Ok(sa),
        Err(e) if should_retry_with_default_expiry(&args, &e) => {
            let mut retry_request = request;
            retry_request.expiry = Some(DEFAULT_SERVICE_ACCOUNT_EXPIRY.to_string());
            client.create_service_account(retry_request).await
        }
        Err(e) => Err(e),
    };

    match create_result {
        Ok(sa) => {
            if formatter.is_json() {
                let output = ServiceAccountCreateOutput {
                    success: true,
                    access_key: sa.access_key.clone(),
                    secret_key: sa.secret_key.clone(),
                    message: "Service account created successfully".to_string(),
                };
                formatter.json(&output);
            } else {
                let styled_key = formatter.style_name(&sa.access_key);
                formatter.success("Service account created successfully.");
                formatter.println(&format!("Access Key: {styled_key}"));
                if let Some(secret) = &sa.secret_key {
                    formatter.println(&format!("Secret Key: {secret}"));
                    formatter.println("");
                    formatter
                        .warning("Make sure to save the secret key, it cannot be retrieved later!");
                }
            }
            ExitCode::Success
        }
        Err(e) => {
            formatter.error(&format!("Failed to create service account: {e}"));
            ExitCode::GeneralError
        }
    }
}

fn build_create_service_account_request(
    args: &CreateArgs,
    policy: Option<String>,
) -> CreateServiceAccountRequest {
    CreateServiceAccountRequest {
        policy,
        expiry: args.expiry.clone(),
        // Keep existing CLI UX where positional ACCESS_KEY is enough.
        name: args.name.clone().or_else(|| Some(args.access_key.clone())),
        description: args.description.clone(),
        access_key: args.access_key.clone(),
        secret_key: args.secret_key.clone(),
    }
}

fn should_retry_with_default_expiry(args: &CreateArgs, error: &rc_core::Error) -> bool {
    if args.expiry.is_some() {
        return false;
    }

    let text = error.to_string();
    text.contains("missing field `expiration`") || text.contains("InvalidExpiration")
}

async fn execute_info(args: InfoArgs, formatter: &Formatter) -> ExitCode {
    let client = match get_admin_client(&args.alias, formatter) {
        Ok(c) => c,
        Err(code) => return code,
    };

    match client.get_service_account(&args.access_key).await {
        Ok(sa) => {
            if formatter.is_json() {
                formatter.json(&ServiceAccountInfo::from(sa));
            } else {
                let styled_key = formatter.style_name(&sa.access_key);
                formatter.println(&format!("Access Key:  {styled_key}"));

                if let Some(parent) = &sa.parent_user {
                    formatter.println(&format!("Parent User: {parent}"));
                }

                if let Some(status) = &sa.account_status {
                    formatter.println(&format!("Status:      {status}"));
                }

                if let Some(expiry) = &sa.expiration {
                    formatter.println(&format!("Expiration:  {expiry}"));
                }

                if let Some(policy) = &sa.policy {
                    formatter.println("");
                    formatter.println("Policy:");
                    formatter.println(policy);
                }
            }
            ExitCode::Success
        }
        Err(rc_core::Error::NotFound(_)) => {
            formatter.error(&format!("Service account '{}' not found", args.access_key));
            ExitCode::NotFound
        }
        Err(e) => {
            formatter.error(&format!("Failed to get service account info: {e}"));
            ExitCode::GeneralError
        }
    }
}

async fn execute_remove(args: RemoveArgs, formatter: &Formatter) -> ExitCode {
    let client = match get_admin_client(&args.alias, formatter) {
        Ok(c) => c,
        Err(code) => return code,
    };

    match client.delete_service_account(&args.access_key).await {
        Ok(()) => {
            if formatter.is_json() {
                let output = ServiceAccountOperationOutput {
                    success: true,
                    access_key: args.access_key.clone(),
                    message: format!("Service account '{}' removed successfully", args.access_key),
                };
                formatter.json(&output);
            } else {
                let styled_key = formatter.style_name(&args.access_key);
                formatter.success(&format!(
                    "Service account '{styled_key}' removed successfully."
                ));
            }
            ExitCode::Success
        }
        Err(rc_core::Error::NotFound(_)) => {
            formatter.error(&format!("Service account '{}' not found", args.access_key));
            ExitCode::NotFound
        }
        Err(e) => {
            formatter.error(&format!("Failed to remove service account: {e}"));
            ExitCode::GeneralError
        }
    }
}

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

    #[test]
    fn test_service_account_info_from() {
        let sa = ServiceAccount {
            access_key: "AKIAIOSFODNN7EXAMPLE".to_string(),
            secret_key: Some("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY".to_string()),
            parent_user: Some("admin".to_string()),
            policy: None,
            account_status: Some("on".to_string()),
            expiration: None,
            name: None,
            description: None,
            implied_policy: None,
        };

        let info = ServiceAccountInfo::from(sa);
        assert_eq!(info.access_key, "AKIAIOSFODNN7EXAMPLE");
        assert!(info.secret_key.is_some());
        assert_eq!(info.parent_user, Some("admin".to_string()));
    }

    #[test]
    fn test_build_create_request_uses_access_key_as_default_name() {
        let args = CreateArgs {
            alias: "local".to_string(),
            access_key: "AKIAIOSFODNN7EXAMPLE".to_string(),
            secret_key: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY".to_string(),
            name: None,
            description: None,
            policy: None,
            expiry: None,
        };

        let request = build_create_service_account_request(&args, None);
        assert_eq!(request.name.as_deref(), Some("AKIAIOSFODNN7EXAMPLE"));
        assert!(request.expiry.is_none());
    }

    #[test]
    fn test_build_create_request_keeps_explicit_name() {
        let args = CreateArgs {
            alias: "local".to_string(),
            access_key: "AKIAIOSFODNN7EXAMPLE".to_string(),
            secret_key: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY".to_string(),
            name: Some("manual-name".to_string()),
            description: Some("demo".to_string()),
            policy: None,
            expiry: Some("2030-01-01T00:00:00Z".to_string()),
        };

        let request = build_create_service_account_request(&args, Some("{\"x\":1}".to_string()));
        assert_eq!(request.name.as_deref(), Some("manual-name"));
        assert_eq!(request.description.as_deref(), Some("demo"));
        assert_eq!(request.expiry.as_deref(), Some("2030-01-01T00:00:00Z"));
        assert_eq!(request.policy.as_deref(), Some("{\"x\":1}"));
    }

    #[test]
    fn test_should_retry_with_default_expiry_for_missing_field_error() {
        let args = CreateArgs {
            alias: "local".to_string(),
            access_key: "AKIAIOSFODNN7EXAMPLE".to_string(),
            secret_key: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY".to_string(),
            name: None,
            description: None,
            policy: None,
            expiry: None,
        };
        let error = rc_core::Error::InvalidPath("missing field `expiration`".to_string());
        assert!(should_retry_with_default_expiry(&args, &error));
    }

    #[test]
    fn test_should_not_retry_with_default_expiry_when_expiry_is_explicit() {
        let args = CreateArgs {
            alias: "local".to_string(),
            access_key: "AKIAIOSFODNN7EXAMPLE".to_string(),
            secret_key: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY".to_string(),
            name: None,
            description: None,
            policy: None,
            expiry: Some("2030-01-01T00:00:00Z".to_string()),
        };
        let error = rc_core::Error::InvalidPath("missing field `expiration`".to_string());
        assert!(!should_retry_with_default_expiry(&args, &error));
    }
}