aws-assume-role 1.3.1

Simple CLI tool to easily switch between AWS IAM roles across different accounts
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
# ๐Ÿ—๏ธ Architecture Guide

Comprehensive technical architecture documentation for AWS Assume Role CLI.

## ๐ŸŽฏ System Overview

AWS Assume Role CLI is a cross-platform command-line tool built in Rust that simplifies AWS role assumption. It is designed for performance, security, and ease of use.

**Core Components**:
- **Core Binary**: A high-performance, statically-linked Rust CLI (`awsr`).
- **Universal Shell Wrapper**: A single bash script (`aws-assume-role-bash.sh`) for seamless integration with bash-compatible shells (Bash, Zsh, Git Bash).
- **AWS SDK for Rust**: Direct integration with AWS services for robust and secure credential handling, replacing the previous dependency on the AWS CLI.
- **CI/CD Pipeline**: An automated testing and distribution pipeline using GitHub Actions.

## ๐Ÿ“Š Architecture Diagram

```mermaid
graph TD
    subgraph "User Interface Layer"
        A["Shell (Bash, Zsh, Git Bash)"] -->|source| B(aws-assume-role-bash.sh)
        B -->|alias 'awsr'| C{Core Binary (aws-assume-role)}
        D["Direct Usage"] --> C
    end

    subgraph "CLI Application Layer (clap)"
        C --> E{Command Parser}
        E -->|assume| F[Assume Role Logic]
        E -->|list| G[List Roles Logic]
        E -->|configure| H[Configuration Logic]
        E -->|--help/--version| I[Help & Version]
    end

    subgraph "Business Logic Layer (Rust)"
        F --> J{AWS SDK Integration}
        G --> K{Configuration Management}
        H --> K
    end

    subgraph "Infrastructure Layer"
        J -- "STS::AssumeRole" --> L(AWS Services via SDK)
        K -- "Read/Write" --> M(File System: config.json)
    end
```

## ๐Ÿงฉ Core Components

### **1. CLI Layer (`src/cli/mod.rs`)**

**Purpose**: Command-line interface and user interaction

**Responsibilities**:
- Parse command-line arguments using `clap`
- Validate user input and provide helpful error messages
- Format output for different shells and use cases
- Coordinate between different modules

**Key Patterns**:
```rust
// Command structure from 'clap'
#[derive(Parser)]
#[command(name = "aws-assume-role", version, about)]
pub struct Cli {
    #[command(subcommand)]
    pub command: Commands,
}

#[derive(Subcommand)]
pub enum Commands {
    Assume { role: String, duration: Option<u32> },
    List,
    Configure,
}
```

**Integration Points**:
- Calls AWS layer for role operations
- Uses Config layer for settings management
- Handles Error layer for user-friendly messages

### **2. AWS Layer (`src/aws/mod.rs`)**

**Purpose**: Direct AWS service integration using the AWS SDK for Rust.

**Responsibilities**:
- Natively assume IAM roles using the `aws-sdk-sts` crate.
- Load AWS configuration and credentials from standard sources (e.g., `~/.aws/config`, environment variables) using `aws-config`.
- Handle credential caching and session management securely.
- Provide a robust, type-safe abstraction over the AWS STS `AssumeRole` API call.

**Key Patterns**:
```rust
// Using the AWS SDK for Rust for STS operations
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_sts::Client as StsClient;

pub async fn assume_role(role_arn: &str, duration: i32) -> Result<aws_sdk_sts::types::Credentials, Box<dyn std::error::Error>> {
    let region_provider = RegionProviderChain::default_provider().or_else("us-east-1");
    let config = aws_config::from_env().region(region_provider).load().await;
    let client = StsClient::new(&config);

    let response = client
        .assume_role()
        .role_arn(role_arn)
        .role_session_name("aws-assume-role-session")
        .duration_seconds(duration)
        .send()
        .await?;

    Ok(response.credentials.unwrap())
}
```

**Architectural Shift**: This layer represents a critical architectural change from the previous version, which shelled out to the AWS CLI. By using the official AWS SDK, we gain:
- **Performance**: No overhead from starting an external process.
- **Security**: No risk of command injection and better handling of credentials.
- **Reliability**: Type-safe interaction with the AWS API, reducing parsing errors.
- **No AWS CLI Dependency**: The tool is now fully self-contained.

**Integration Points**:
- Requires AWS CLI v2 to be installed
- Reads AWS configuration and credentials
- Integrates with Config layer for role definitions

### **3. Configuration Layer (`src/config/mod.rs`)**

**Purpose**: Configuration file management and user preferences

**Responsibilities**:
- Load and save configuration files
- Manage role definitions and user preferences
- Handle cross-platform file paths
- Provide default values and validation

**Key Patterns**:
```rust
// Configuration structure
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Config {
    pub roles: HashMap<String, RoleConfig>,
    pub default_duration: u32,
    pub default_region: Option<String>,
}

// Cross-platform path handling
pub fn get_config_path() -> PathBuf {
    // Check both HOME and USERPROFILE for cross-platform support
    if let Ok(home) = env::var("HOME") {
        return PathBuf::from(home).join(".aws-assume-role");
    }
    if let Ok(userprofile) = env::var("USERPROFILE") {
        return PathBuf::from(userprofile).join(".aws-assume-role");
    }
    dirs::home_dir().unwrap_or_default().join(".aws-assume-role")
}
```

**Integration Points**:
- Used by CLI layer for role lookups
- Integrates with AWS layer for credential storage
- Handles Error layer for configuration issues

### **4. Error Layer (`src/error/mod.rs`)**

**Purpose**: Structured error handling and user-friendly messages

**Responsibilities**:
- Define error types for different failure modes
- Provide actionable error messages
- Chain errors with context preservation
- Enable debugging while maintaining user experience

**Key Patterns**:
```rust
// Structured error types using thiserror
#[derive(Error, Debug)]
pub enum CliError {
    #[error("AWS CLI not found. Please install AWS CLI v2")]
    AwsCliNotFound,
    
    #[error("Failed to assume role '{role}': {source}")]
    AssumeRoleFailed { 
        role: String, 
        #[source] source: Box<dyn std::error::Error> 
    },
    
    #[error("Configuration error: {0}")]
    ConfigError(String),
}
```

**Integration Points**:
- Used by all layers for consistent error handling
- Provides user-friendly messages in CLI layer
- Preserves technical details for debugging

## ๐Ÿ”„ Data Flow

### **Typical Role Assumption Flow**

```mermaid
graph TD
    A[User runs 'awsr assume <role>'] --> B{CLI Parser};
    B --> C{Config Layer: Look up Role ARN};
    C --> D{AWS Layer: Call assume_role()};
    D --> E{AWS SDK for Rust: STS Client};
    E -- "AssumeRole API Call" --> F[AWS STS Service];
    F -- "Temporary Credentials" --> E;
    E --> D;
    D -- "Credentials Result" --> B;
    B --> G[Output Layer: Format as shell exports];
    G --> H[User sources output to set ENV VARS];
```

### **Configuration Management Flow**

```mermaid
graph TD
    A[User runs 'awsr configure'] --> B{CLI Parser};
    B --> C{Prompt for Role Details};
    C --> D{Config Layer: Read config.json};
    D --> E{Update/Add Role Definition};
    E --> F{Config Layer: Write to config.json};
```

## ๐Ÿ—๏ธ Design Patterns

### **1. Cross-Platform Compatibility**

**Challenge**: Different operating systems have different conventions for:
- Environment variables (`HOME` vs `USERPROFILE`)
- File paths (Unix `/` vs Windows `\`)
- Shell integration (Bash vs PowerShell vs CMD)

**Solution**: Environment variable checking with fallbacks
```rust
pub fn get_config_path() -> PathBuf {
    // Production: Use both environment variables for cross-platform support
    if let Ok(home) = env::var("HOME") {
        return PathBuf::from(home).join(".aws-assume-role");
    }
    if let Ok(userprofile) = env::var("USERPROFILE") {
        return PathBuf::from(userprofile).join(".aws-assume-role");
    }
    
    // Fallback to dirs crate
    dirs::home_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join(".aws-assume-role")
}
```

### **2. Shell Integration Strategy**

**Challenge**: Different shells require different syntax for:
- Environment variable export
- Function definition
- Error handling

**Solution**: Shell-specific wrapper scripts
```bash
# Bash/Zsh wrapper
awsr() {
    local output
    output=$(command awsr "$@" 2>&1)
    local exit_code=$?
    
    if [ $exit_code -eq 0 ] && [[ "$1" == "assume" ]]; then
        eval "$output"
    else
        echo "$output"
    fi
    
    return $exit_code
}
```

### **3. Error Handling Strategy**

**Challenge**: Provide actionable error messages while preserving technical details

**Solution**: Layered error types with context
```rust
// High-level user errors
#[derive(Error, Debug)]
pub enum CliError {
    #[error("AWS CLI not found. Please install AWS CLI v2")]
    AwsCliNotFound,
}

// Detailed technical errors preserved in source chain
impl From<std::io::Error> for CliError {
    fn from(err: std::io::Error) -> Self {
        CliError::IoError { source: err }
    }
}
```

### **4. Configuration Management**

**Challenge**: Flexible configuration with sensible defaults

**Solution**: Layered configuration resolution
```rust
// 1. Built-in defaults
// 2. User configuration file
// 3. Command-line arguments
// 4. Environment variables (highest priority)

pub fn resolve_config(cli_args: &CliArgs) -> Config {
    let mut config = Config::default();
    config.merge_from_file();
    config.merge_from_env();
    config.merge_from_args(cli_args);
    config
}
```

## ๐Ÿงช Testing Architecture

### **Test Structure (60 Total Tests)**

```
Testing Framework:
โ”œโ”€โ”€ Unit Tests (23 tests)
โ”‚   โ”œโ”€โ”€ Configuration module tests
โ”‚   โ”œโ”€โ”€ Error handling tests
โ”‚   โ”œโ”€โ”€ AWS integration tests
โ”‚   โ””โ”€โ”€ CLI parsing tests
โ”œโ”€โ”€ Integration Tests (14 tests)
โ”‚   โ”œโ”€โ”€ End-to-end CLI functionality
โ”‚   โ”œโ”€โ”€ Cross-platform compatibility
โ”‚   โ”œโ”€โ”€ Configuration workflows
โ”‚   โ””โ”€โ”€ Error scenarios
โ””โ”€โ”€ Additional Tests (23 tests)
    โ”œโ”€โ”€ Performance benchmarks
    โ”œโ”€โ”€ Cross-platform utilities
    โ””โ”€โ”€ Serialization helpers
```

### **Test Isolation Patterns**

**Environment Variable Testing**:
```rust
#[test]
#[serial_test::serial]  // Prevent race conditions
fn test_cross_platform_config() {
    // Store original values
    let original_home = env::var("HOME").ok();
    let original_userprofile = env::var("USERPROFILE").ok();
    
    // Test logic with isolated environment
    
    // Restore original values
    restore_env_vars(original_home, original_userprofile);
}
```

**File System Testing**:
```rust
#[test]
fn test_config_operations() {
    let temp_dir = TempDir::new().unwrap();
    env::set_var("HOME", temp_dir.path());
    
    // Test config operations in isolation
    
    // Automatic cleanup on test completion
}
```

## ๐Ÿš€ Performance Considerations

### **Optimization Strategies**

**1. Minimal Dependencies**
- Use lightweight crates where possible
- Avoid heavy runtime dependencies
- Prefer standard library when sufficient

**2. Efficient AWS CLI Integration**
- Cache AWS CLI path discovery
- Reuse process handles when possible
- Parse JSON responses efficiently

**3. Fast Startup Time**
- Lazy initialization of expensive operations
- Minimal work in main() function
- Defer AWS CLI calls until needed

### **Benchmarking Framework**

```rust
// Performance benchmarks in benches/performance.rs
#[bench]
fn bench_config_load(b: &mut Bencher) {
    b.iter(|| {
        // Benchmark configuration loading
    });
}

#[bench]
fn bench_role_assumption(b: &mut Bencher) {
    b.iter(|| {
        // Benchmark end-to-end role assumption
    });
}
```

## ๐Ÿ”’ Security Architecture

### **Security Principles**

**1. Credential Isolation**
- Never log sensitive credentials
- Use secure temporary file handling
- Clear credentials from memory when possible

**2. Input Validation**
- Validate all user inputs
- Sanitize shell command construction
- Prevent command injection attacks

**3. Dependency Security**
- Regular security audits (`cargo audit`)
- Minimal dependency surface
- Use well-maintained crates

### **Secure Coding Patterns**

```rust
// Secure command construction
fn build_aws_command(role_arn: &str) -> Command {
    let mut cmd = Command::new("aws");
    cmd.arg("sts")
       .arg("assume-role")
       .arg("--role-arn")
       .arg(role_arn);  // Properly escaped argument
    cmd
}

// Secure temporary file handling
fn write_temp_credentials(creds: &Credentials) -> Result<PathBuf> {
    let mut temp_file = NamedTempFile::new()?;
    temp_file.write_all(creds.to_json().as_bytes())?;
    Ok(temp_file.into_temp_path().to_path_buf())
}
```

## ๐Ÿ“ฆ Distribution Architecture

### **Multi-Platform Build Strategy**

```
Build Targets:
โ”œโ”€โ”€ x86_64-unknown-linux-gnu     # Linux
โ”œโ”€โ”€ x86_64-pc-windows-gnu        # Windows
โ”œโ”€โ”€ x86_64-apple-darwin          # macOS Intel
โ””โ”€โ”€ aarch64-apple-darwin         # macOS Apple Silicon
```

### **Package Distribution**

```
Distribution Channels:
โ”œโ”€โ”€ Cargo (crates.io)            # Rust package manager
โ”œโ”€โ”€ Homebrew (macOS/Linux)       # Popular package manager
โ”œโ”€โ”€ APT (Debian/Ubuntu)          # Linux package manager
โ”œโ”€โ”€ DNF/YUM (Fedora/RHEL)        # Linux package manager
โ”œโ”€โ”€ GitHub Releases              # Direct download
โ””โ”€โ”€ Docker Images                # Container distribution
```

### **Release Automation**

```
CI/CD Pipeline:
โ”œโ”€โ”€ Code Quality Gates
โ”‚   โ”œโ”€โ”€ Formatting check
โ”‚   โ”œโ”€โ”€ Clippy linting
โ”‚   โ”œโ”€โ”€ Security audit
โ”‚   โ””โ”€โ”€ Test suite (60 tests)
โ”œโ”€โ”€ Multi-Platform Builds
โ”‚   โ”œโ”€โ”€ Linux x86_64
โ”‚   โ”œโ”€โ”€ Windows x86_64
โ”‚   โ””โ”€โ”€ macOS universal
โ””โ”€โ”€ Automated Distribution
    โ”œโ”€โ”€ GitHub release creation
    โ”œโ”€โ”€ Package manager updates
    โ””โ”€โ”€ Container image publishing
```

## ๐Ÿ”ง Development Architecture

### **Development Workflow**

```
Development Process:
โ”œโ”€โ”€ Feature Development
โ”‚   โ”œโ”€ feature/* branches
โ”‚   โ”œโ”€ Comprehensive testing
โ”‚   โ””โ”€ Code review process
โ”œโ”€โ”€ Quality Assurance
โ”‚   โ”œโ”€ Mandatory formatting
โ”‚   โ”œโ”€ Zero clippy warnings
โ”‚   โ””โ”€ Cross-platform testing
โ””โ”€โ”€ Release Management
    โ”œโ”€ Semantic versioning
    โ”œโ”€ Automated changelog
    โ””โ”€ Multi-channel distribution
```

### **Code Organization**

```
Source Structure:
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ main.rs              # Entry point
โ”‚   โ”œโ”€โ”€ lib.rs               # Library interface
โ”‚   โ”œโ”€โ”€ cli/mod.rs           # CLI handling
โ”‚   โ”œโ”€โ”€ aws/mod.rs           # AWS integration
โ”‚   โ”œโ”€โ”€ config/mod.rs        # Configuration
โ”‚   โ””โ”€โ”€ error/mod.rs         # Error handling
โ”œโ”€โ”€ tests/                   # Test suite
โ”œโ”€โ”€ benches/                 # Performance tests
โ””โ”€โ”€ releases/                # Distribution artifacts
```

## ๐Ÿ“š Technology Stack

### **Core Technologies**

| Component | Technology | Purpose |
|-----------|------------|---------|
| **Language** | Rust 1.70+ | Performance, safety, cross-platform |
| **CLI Framework** | clap 4.x | Argument parsing and help generation |
| **Error Handling** | thiserror | Structured error types |
| **Serialization** | serde + serde_json | Configuration and AWS response parsing |
| **Testing** | cargo test + assert_cmd | Comprehensive test framework |
| **Cross-Platform** | dirs crate | Platform-specific directory handling |

### **Development Tools**

| Tool | Purpose |
|------|---------|
| **rustfmt** | Code formatting (enforced) |
| **clippy** | Linting and best practices |
| **cargo-audit** | Security vulnerability scanning |
| **criterion** | Performance benchmarking |
| **tarpaulin** | Code coverage analysis |

### **Infrastructure**

| Component | Technology |
|-----------|------------|
| **CI/CD** | GitHub Actions |
| **Package Hosting** | Multiple (Cargo, Homebrew, APT, COPR) |
| **Container Registry** | GitHub Container Registry |
| **Documentation** | Markdown + GitHub Pages |

## ๐ŸŽฏ Future Architecture Considerations

### **Planned Enhancements**

1. **Native AWS SDK Integration**: Reduce dependency on AWS CLI
2. **Configuration UI**: Web-based configuration management
3. **Plugin Architecture**: Extensible functionality
4. **Enhanced Shell Integration**: More shell-specific features

### **Scalability Considerations**

1. **Multi-Account Support**: Enhanced organization support
2. **Caching Layer**: Improve performance for repeated operations
3. **Audit Logging**: Comprehensive usage tracking
4. **Configuration Sync**: Cloud-based configuration sharing

This architecture provides a solid foundation for a reliable, cross-platform AWS role assumption tool while maintaining simplicity and performance.