aws-hit-breaks 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,14 @@
1
+ """
2
+ AWS Hit Breaks - Emergency cost control for AWS accounts.
3
+
4
+ A CLI tool that acts like a car's brakes for AWS accounts, allowing users to pause
5
+ all running processes and services to stop incurring costs without permanent deletion.
6
+ """
7
+
8
+ __version__ = "1.0.0"
9
+ __author__ = "AWS Break CLI Team"
10
+ __email__ = "support@aws-hit-breaks.com"
11
+
12
+ from aws_hit_breaks.core.exceptions import AWSBreakError
13
+
14
+ __all__ = ["AWSBreakError"]
@@ -0,0 +1 @@
1
+ """Authentication and IAM role management package."""
@@ -0,0 +1,317 @@
1
+ """IAM role authentication and STS assume role functionality."""
2
+
3
+ import boto3
4
+ from botocore.exceptions import ClientError, NoCredentialsError, BotoCoreError
5
+ from typing import Dict, Optional, Any
6
+ import logging
7
+ from datetime import datetime, timedelta, timezone
8
+
9
+ from aws_hit_breaks.core.config import Config, ConfigManager
10
+ from aws_hit_breaks.core.exceptions import AuthenticationError, ConfigurationError
11
+
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ class IAMRoleAuthenticator:
17
+ """Handles IAM role authentication using STS assume role."""
18
+
19
+ def __init__(self, config_manager: Optional[ConfigManager] = None):
20
+ """Initialize the IAM role authenticator.
21
+
22
+ Args:
23
+ config_manager: Optional configuration manager instance.
24
+ If None, creates a new one with default settings.
25
+ """
26
+ self.config_manager = config_manager or ConfigManager()
27
+ self._cached_credentials: Optional[Dict[str, Any]] = None
28
+ self._credentials_expiry: Optional[datetime] = None
29
+
30
+ def get_aws_session(self, region: Optional[str] = None) -> boto3.Session:
31
+ """Get an authenticated AWS session using the configured IAM role.
32
+
33
+ Args:
34
+ region: Optional AWS region. If None, uses default from config.
35
+
36
+ Returns:
37
+ Authenticated boto3 Session object.
38
+
39
+ Raises:
40
+ ConfigurationError: If no IAM role is configured.
41
+ AuthenticationError: If role assumption fails.
42
+ """
43
+ config = self._load_config()
44
+
45
+ # Use provided region or fall back to config default
46
+ session_region = region or config.default_region
47
+
48
+ # Get credentials (cached or fresh)
49
+ credentials = self._get_credentials(config.iam_role_arn)
50
+
51
+ # Create session with assumed role credentials
52
+ session = boto3.Session(
53
+ aws_access_key_id=credentials['AccessKeyId'],
54
+ aws_secret_access_key=credentials['SecretAccessKey'],
55
+ aws_session_token=credentials['SessionToken'],
56
+ region_name=session_region
57
+ )
58
+
59
+ return session
60
+
61
+ def get_aws_client(self, service_name: str, region: Optional[str] = None) -> Any:
62
+ """Get an authenticated AWS service client.
63
+
64
+ Args:
65
+ service_name: AWS service name (e.g., 'ec2', 'rds', 'ecs').
66
+ region: Optional AWS region. If None, uses default from config.
67
+
68
+ Returns:
69
+ Authenticated boto3 client for the specified service.
70
+
71
+ Raises:
72
+ ConfigurationError: If no IAM role is configured.
73
+ AuthenticationError: If role assumption fails.
74
+ """
75
+ session = self.get_aws_session(region)
76
+ return session.client(service_name)
77
+
78
+ def validate_role_access(self, role_arn: str) -> bool:
79
+ """Validate that the IAM role can be assumed successfully.
80
+
81
+ Args:
82
+ role_arn: IAM role ARN to validate.
83
+
84
+ Returns:
85
+ True if role can be assumed, False otherwise.
86
+ """
87
+ try:
88
+ # Try to assume the role
89
+ sts_client = boto3.client('sts')
90
+ response = sts_client.assume_role(
91
+ RoleArn=role_arn,
92
+ RoleSessionName='aws-hit-breaks-validation',
93
+ DurationSeconds=900 # 15 minutes minimum
94
+ )
95
+
96
+ # If we get here, the role assumption worked
97
+ logger.info(f"Successfully validated IAM role: {role_arn}")
98
+ return True
99
+
100
+ except ClientError as e:
101
+ error_code = e.response.get('Error', {}).get('Code', 'Unknown')
102
+ logger.warning(f"Failed to validate IAM role {role_arn}: {error_code} - {e}")
103
+ return False
104
+ except (NoCredentialsError, BotoCoreError) as e:
105
+ logger.warning(f"AWS credentials or configuration error: {e}")
106
+ return False
107
+
108
+ def get_caller_identity(self) -> Dict[str, Any]:
109
+ """Get the current caller identity information.
110
+
111
+ Returns:
112
+ Dictionary containing caller identity information.
113
+
114
+ Raises:
115
+ AuthenticationError: If unable to get caller identity.
116
+ """
117
+ try:
118
+ session = self.get_aws_session()
119
+ sts_client = session.client('sts')
120
+ return sts_client.get_caller_identity()
121
+ except Exception as e:
122
+ raise AuthenticationError(f"Failed to get caller identity: {e}")
123
+
124
+ def _load_config(self) -> Config:
125
+ """Load configuration and validate IAM role is configured.
126
+
127
+ Returns:
128
+ Configuration object.
129
+
130
+ Raises:
131
+ ConfigurationError: If no configuration exists or IAM role not configured.
132
+ """
133
+ config = self.config_manager.load_config()
134
+
135
+ if config is None:
136
+ raise ConfigurationError(
137
+ "No configuration found. Please run the setup process to configure your IAM role."
138
+ )
139
+
140
+ if not config.iam_role_arn:
141
+ raise ConfigurationError(
142
+ "No IAM role configured. Please run the setup process to configure your IAM role."
143
+ )
144
+
145
+ return config
146
+
147
+ def _get_credentials(self, role_arn: str) -> Dict[str, Any]:
148
+ """Get AWS credentials by assuming the specified IAM role.
149
+
150
+ Args:
151
+ role_arn: IAM role ARN to assume.
152
+
153
+ Returns:
154
+ Dictionary containing AWS credentials.
155
+
156
+ Raises:
157
+ AuthenticationError: If role assumption fails.
158
+ """
159
+ # Check if we have cached credentials that are still valid
160
+ if self._cached_credentials and self._credentials_expiry:
161
+ # Add 5 minute buffer before expiry (use timezone-aware comparison)
162
+ if datetime.now(timezone.utc) < (self._credentials_expiry - timedelta(minutes=5)):
163
+ logger.debug("Using cached AWS credentials")
164
+ return self._cached_credentials
165
+
166
+ try:
167
+ logger.info(f"Assuming IAM role: {role_arn}")
168
+
169
+ # Create STS client with current credentials
170
+ sts_client = boto3.client('sts')
171
+
172
+ # Assume the role
173
+ response = sts_client.assume_role(
174
+ RoleArn=role_arn,
175
+ RoleSessionName='aws-hit-breaks-session',
176
+ DurationSeconds=3600 # 1 hour
177
+ )
178
+
179
+ # Extract credentials
180
+ credentials = response['Credentials']
181
+
182
+ # Cache credentials and expiry time (keep timezone-aware)
183
+ self._cached_credentials = credentials
184
+ # AWS returns timezone-aware datetime, keep it that way for accurate comparison
185
+ self._credentials_expiry = credentials['Expiration'].astimezone(timezone.utc)
186
+
187
+ logger.info("Successfully assumed IAM role")
188
+ return credentials
189
+
190
+ except ClientError as e:
191
+ error_code = e.response.get('Error', {}).get('Code', 'Unknown')
192
+ error_message = e.response.get('Error', {}).get('Message', str(e))
193
+
194
+ if error_code == 'AccessDenied':
195
+ raise AuthenticationError(
196
+ f"Access denied when assuming role {role_arn}. "
197
+ "Please check that:\n"
198
+ "1. The role exists and is correctly configured\n"
199
+ "2. Your current AWS credentials have permission to assume this role\n"
200
+ "3. The role's trust policy allows your account/user to assume it"
201
+ )
202
+ elif error_code == 'InvalidUserID.NotFound':
203
+ raise AuthenticationError(
204
+ f"IAM role not found: {role_arn}. "
205
+ "Please check that the role ARN is correct and the role exists."
206
+ )
207
+ else:
208
+ raise AuthenticationError(
209
+ f"Failed to assume IAM role {role_arn}: {error_code} - {error_message}"
210
+ )
211
+
212
+ except NoCredentialsError:
213
+ raise AuthenticationError(
214
+ "No AWS credentials found. Please configure your AWS credentials using:\n"
215
+ "1. AWS CLI: aws configure\n"
216
+ "2. Environment variables: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY\n"
217
+ "3. IAM instance profile (if running on EC2)\n"
218
+ "4. AWS SSO: aws sso login"
219
+ )
220
+
221
+ except BotoCoreError as e:
222
+ raise AuthenticationError(f"AWS configuration error: {e}")
223
+
224
+ except Exception as e:
225
+ raise AuthenticationError(f"Unexpected error assuming IAM role: {e}")
226
+
227
+ def clear_cached_credentials(self) -> None:
228
+ """Clear any cached credentials to force fresh authentication."""
229
+ self._cached_credentials = None
230
+ self._credentials_expiry = None
231
+ logger.debug("Cleared cached AWS credentials")
232
+
233
+
234
+ def create_cloudformation_template() -> str:
235
+ """Generate CloudFormation template for creating the required IAM role.
236
+
237
+ Returns:
238
+ CloudFormation template as a YAML string.
239
+ """
240
+ template = """AWSTemplateFormatVersion: '2010-09-09'
241
+ Description: 'IAM role for AWS Hit Breaks CLI with minimal required permissions'
242
+
243
+ Parameters:
244
+ TrustedAccountId:
245
+ Type: String
246
+ Description: 'AWS Account ID that can assume this role (your account ID)'
247
+ Default: !Ref 'AWS::AccountId'
248
+
249
+ Resources:
250
+ AWSHitBreaksRole:
251
+ Type: AWS::IAM::Role
252
+ Properties:
253
+ RoleName: AWSHitBreaksRole
254
+ AssumeRolePolicyDocument:
255
+ Version: '2012-10-17'
256
+ Statement:
257
+ - Effect: Allow
258
+ Principal:
259
+ AWS: !Sub 'arn:aws:iam::${TrustedAccountId}:root'
260
+ Action: sts:AssumeRole
261
+ Condition:
262
+ StringEquals:
263
+ 'sts:ExternalId': 'aws-hit-breaks-cli'
264
+ Policies:
265
+ - PolicyName: AWSHitBreaksPolicy
266
+ PolicyDocument:
267
+ Version: '2012-10-17'
268
+ Statement:
269
+ - Effect: Allow
270
+ Action:
271
+ # EC2 permissions
272
+ - ec2:DescribeInstances
273
+ - ec2:DescribeInstanceStatus
274
+ - ec2:StopInstances
275
+ - ec2:StartInstances
276
+ # RDS permissions
277
+ - rds:DescribeDBInstances
278
+ - rds:DescribeDBClusters
279
+ - rds:StopDBInstance
280
+ - rds:StartDBInstance
281
+ - rds:StopDBCluster
282
+ - rds:StartDBCluster
283
+ # ECS permissions
284
+ - ecs:DescribeServices
285
+ - ecs:DescribeClusters
286
+ - ecs:ListServices
287
+ - ecs:UpdateService
288
+ # Auto Scaling permissions
289
+ - autoscaling:DescribeAutoScalingGroups
290
+ - autoscaling:SuspendProcesses
291
+ - autoscaling:ResumeProcesses
292
+ - autoscaling:SetDesiredCapacity
293
+ # Lambda permissions
294
+ - lambda:ListFunctions
295
+ - lambda:GetProvisionedConcurrencyConfig
296
+ - lambda:PutProvisionedConcurrencyConfig
297
+ - lambda:DeleteProvisionedConcurrencyConfig
298
+ # Pricing API permissions
299
+ - pricing:GetProducts
300
+ Resource: '*'
301
+
302
+ Outputs:
303
+ RoleArn:
304
+ Description: 'ARN of the created IAM role'
305
+ Value: !GetAtt AWSHitBreaksRole.Arn
306
+ Export:
307
+ Name: !Sub '${AWS::StackName}-RoleArn'
308
+
309
+ SetupInstructions:
310
+ Description: 'Instructions for configuring AWS Hit Breaks CLI'
311
+ Value: !Sub |
312
+ 1. Copy this role ARN: ${AWSHitBreaksRole.Arn}
313
+ 2. Run: aws-hit-breaks configure
314
+ 3. Paste the role ARN when prompted
315
+ """
316
+
317
+ return template
@@ -0,0 +1 @@
1
+ """CLI interface package for AWS Hit Breaks."""
@@ -0,0 +1,247 @@
1
+ """Interactive CLI flow for AWS Hit Breaks."""
2
+
3
+ import sys
4
+ from typing import Optional
5
+
6
+ from rich.console import Console
7
+ from rich.panel import Panel
8
+ from rich.text import Text
9
+
10
+ from aws_hit_breaks.core.config import Config, ConfigManager
11
+ from aws_hit_breaks.auth.iam_auth import IAMRoleAuthenticator, create_cloudformation_template
12
+ from aws_hit_breaks.core.exceptions import AWSBreakError, ConfigurationError, AuthenticationError, UserCancelled
13
+ from aws_hit_breaks.cli.keyboard import (
14
+ prompt_with_escape,
15
+ confirm_with_escape,
16
+ show_escape_hint,
17
+ escape_listener,
18
+ is_cancelled,
19
+ reset_cancel,
20
+ poll_escape,
21
+ )
22
+
23
+
24
+ class InteractiveFlow:
25
+ """Handles interactive CLI flows for AWS Hit Breaks."""
26
+
27
+ def __init__(self, console: Console, config_manager: ConfigManager, iam_manager: IAMRoleAuthenticator):
28
+ """Initialize interactive flow.
29
+
30
+ Args:
31
+ console: Rich console for output
32
+ config_manager: Configuration manager instance
33
+ iam_manager: IAM role authenticator instance
34
+ """
35
+ self.console = console
36
+ self.config_manager = config_manager
37
+ self.iam_manager = iam_manager
38
+
39
+ def _handle_cancellation(self, message: str = "Cancel and quit?") -> bool:
40
+ """Handle ESC key press with confirmation.
41
+
42
+ Args:
43
+ message: Confirmation message to display
44
+
45
+ Returns:
46
+ True if user confirmed cancellation, False to continue
47
+
48
+ Raises:
49
+ UserCancelled: If user confirms they want to quit
50
+ """
51
+ # Poll for ESC key press
52
+ poll_escape()
53
+
54
+ if is_cancelled():
55
+ self.console.print()
56
+ self.console.print("[yellow]ESC pressed - cancelling...[/yellow]")
57
+ try:
58
+ if confirm_with_escape(message, self.console, default=False):
59
+ raise UserCancelled("User cancelled operation")
60
+ else:
61
+ # User wants to continue, reset the flag
62
+ reset_cancel()
63
+ self.console.print("[green]Continuing...[/green]")
64
+ return False
65
+ except UserCancelled:
66
+ # User pressed ESC again during confirmation - treat as quit
67
+ raise
68
+ return False
69
+
70
+ def setup_iam_role(self) -> None:
71
+ """Guide user through IAM role setup process."""
72
+ self.console.print("I'll create an IAM role with minimal required permissions.")
73
+ self.console.print("This ensures your AWS account stays secure.")
74
+ self.console.print()
75
+ show_escape_hint(self.console)
76
+
77
+ # Ask user for setup method
78
+ self.console.print("Choose setup method:")
79
+ self.console.print("1. 📋 Copy CloudFormation template (recommended)")
80
+ self.console.print("2. 🔧 Manual IAM role creation")
81
+ self.console.print()
82
+
83
+ choice = prompt_with_escape("Select option", self.console, choices=["1", "2"], default="1")
84
+
85
+ if choice == "1":
86
+ self._setup_with_cloudformation()
87
+ else:
88
+ self._setup_manual()
89
+
90
+ def _setup_with_cloudformation(self) -> None:
91
+ """Setup using CloudFormation template."""
92
+ self.console.print()
93
+ self.console.print("📋 [bold]CloudFormation Template Setup[/bold]")
94
+ self.console.print("━" * 40)
95
+
96
+ # Generate and display CloudFormation template
97
+ template = create_cloudformation_template()
98
+
99
+ self.console.print("1. Copy the CloudFormation template below:")
100
+ self.console.print()
101
+
102
+ # Display template in a panel
103
+ template_panel = Panel(
104
+ template,
105
+ title="CloudFormation Template",
106
+ border_style="blue",
107
+ expand=False
108
+ )
109
+ self.console.print(template_panel)
110
+
111
+ self.console.print()
112
+ self.console.print("2. Deploy this template in your AWS account:")
113
+ self.console.print(" • Go to AWS CloudFormation console")
114
+ self.console.print(" • Create new stack")
115
+ self.console.print(" • Paste the template above")
116
+ self.console.print(" • Deploy with default parameters")
117
+ self.console.print()
118
+
119
+ # Wait for user to deploy
120
+ confirm_with_escape("Have you deployed the CloudFormation template?", self.console, default=False)
121
+
122
+ # Get role ARN from user
123
+ self._get_role_arn_from_user()
124
+
125
+ def _setup_manual(self) -> None:
126
+ """Setup with manual IAM role creation."""
127
+ self.console.print()
128
+ self.console.print("🔧 [bold]Manual IAM Role Setup[/bold]")
129
+ self.console.print("━" * 30)
130
+
131
+ self.console.print("1. Go to AWS IAM console")
132
+ self.console.print("2. Create a new IAM role")
133
+ self.console.print("3. Choose 'AWS account' as trusted entity")
134
+ self.console.print("4. Add the following permissions:")
135
+
136
+ permissions = [
137
+ "ec2:DescribeInstances", "ec2:StopInstances", "ec2:StartInstances",
138
+ "rds:DescribeDBInstances", "rds:StopDBInstance", "rds:StartDBInstance",
139
+ "ecs:DescribeServices", "ecs:UpdateService",
140
+ "autoscaling:DescribeAutoScalingGroups", "autoscaling:SuspendProcesses",
141
+ "pricing:GetProducts"
142
+ ]
143
+
144
+ for permission in permissions:
145
+ self.console.print(f" • {permission}")
146
+
147
+ self.console.print()
148
+ self.console.print("5. Name the role 'AWSHitBreaksRole'")
149
+ self.console.print("6. Copy the role ARN")
150
+ self.console.print()
151
+
152
+ # Get role ARN from user
153
+ self._get_role_arn_from_user()
154
+
155
+ def _get_role_arn_from_user(self) -> None:
156
+ """Get and validate role ARN from user input."""
157
+ while True:
158
+ role_arn = prompt_with_escape("Enter the IAM role ARN", self.console)
159
+
160
+ if not role_arn:
161
+ self.console.print("❌ [red]Role ARN cannot be empty[/red]")
162
+ continue
163
+
164
+ # Validate role ARN format
165
+ try:
166
+ config = Config(iam_role_arn=role_arn)
167
+ except ValueError as e:
168
+ self.console.print(f"❌ [red]{e}[/red]")
169
+ continue
170
+
171
+ # Test role access
172
+ self.console.print("🔍 Testing role access...")
173
+
174
+ if self.iam_manager.validate_role_access(role_arn):
175
+ # Save configuration
176
+ self.config_manager.save_config(config)
177
+ self.console.print("✅ [green]IAM role configured successfully![/green]")
178
+ self.console.print()
179
+ self.console.print("You can now run 'aws-hit-breaks' to start using the tool.")
180
+ break
181
+ else:
182
+ self.console.print("❌ [red]Unable to assume the specified role.[/red]")
183
+ self.console.print("Please check:")
184
+ self.console.print("• The role ARN is correct")
185
+ self.console.print("• The role exists in your account")
186
+ self.console.print("• Your AWS credentials have permission to assume the role")
187
+ self.console.print()
188
+
189
+ if not confirm_with_escape("Try a different role ARN?", self.console, default=True):
190
+ sys.exit(1)
191
+
192
+ def discover_and_pause(self, region: Optional[str], dry_run: bool) -> None:
193
+ """Main discover and pause flow."""
194
+ self.console.print("🚨 [bold red]AWS Hit Breaks - Emergency Cost Control[/bold red]")
195
+ self.console.print("━" * 50)
196
+ self.console.print()
197
+ show_escape_hint(self.console)
198
+
199
+ with escape_listener(self.console):
200
+ # Check for cancellation periodically
201
+ self._handle_cancellation()
202
+
203
+ # TODO: Implement service discovery and pause logic
204
+ # This will be implemented in later tasks
205
+ self.console.print("🔍 [yellow]Service discovery not yet implemented[/yellow]")
206
+ self.console.print("This will be available in the next implementation phase.")
207
+
208
+ # Check for cancellation after operations
209
+ self._handle_cancellation()
210
+
211
+ def resume_services(self, region: Optional[str], dry_run: bool) -> None:
212
+ """Resume previously paused services."""
213
+ self.console.print("🚨 [bold red]AWS Hit Breaks - Resume Services[/bold red]")
214
+ self.console.print("━" * 40)
215
+ self.console.print()
216
+ show_escape_hint(self.console)
217
+
218
+ with escape_listener(self.console):
219
+ # Check for cancellation periodically
220
+ self._handle_cancellation()
221
+
222
+ # TODO: Implement resume logic
223
+ # This will be implemented in later tasks
224
+ self.console.print("🔄 [yellow]Service resume not yet implemented[/yellow]")
225
+ self.console.print("This will be available in the next implementation phase.")
226
+
227
+ # Check for cancellation after operations
228
+ self._handle_cancellation()
229
+
230
+ def show_status(self, region: Optional[str]) -> None:
231
+ """Show current status of services and snapshots."""
232
+ self.console.print("🚨 [bold red]AWS Hit Breaks - Status[/bold red]")
233
+ self.console.print("━" * 30)
234
+ self.console.print()
235
+ show_escape_hint(self.console)
236
+
237
+ with escape_listener(self.console):
238
+ # Check for cancellation periodically
239
+ self._handle_cancellation()
240
+
241
+ # TODO: Implement status display
242
+ # This will be implemented in later tasks
243
+ self.console.print("📊 [yellow]Status display not yet implemented[/yellow]")
244
+ self.console.print("This will be available in the next implementation phase.")
245
+
246
+ # Check for cancellation after operations
247
+ self._handle_cancellation()