iam-policy-validator 1.3.1__py3-none-any.whl → 1.5.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.
Files changed (41) hide show
  1. {iam_policy_validator-1.3.1.dist-info → iam_policy_validator-1.5.0.dist-info}/METADATA +164 -19
  2. iam_policy_validator-1.5.0.dist-info/RECORD +67 -0
  3. iam_validator/__version__.py +1 -1
  4. iam_validator/checks/__init__.py +15 -3
  5. iam_validator/checks/action_condition_enforcement.py +1 -6
  6. iam_validator/checks/condition_key_validation.py +21 -1
  7. iam_validator/checks/full_wildcard.py +67 -0
  8. iam_validator/checks/policy_size.py +1 -0
  9. iam_validator/checks/policy_type_validation.py +299 -0
  10. iam_validator/checks/principal_validation.py +776 -0
  11. iam_validator/checks/sensitive_action.py +178 -0
  12. iam_validator/checks/service_wildcard.py +105 -0
  13. iam_validator/checks/sid_uniqueness.py +45 -7
  14. iam_validator/checks/utils/sensitive_action_matcher.py +39 -31
  15. iam_validator/checks/wildcard_action.py +62 -0
  16. iam_validator/checks/wildcard_resource.py +131 -0
  17. iam_validator/commands/download_services.py +3 -8
  18. iam_validator/commands/post_to_pr.py +7 -0
  19. iam_validator/commands/validate.py +204 -16
  20. iam_validator/core/aws_fetcher.py +25 -12
  21. iam_validator/core/check_registry.py +25 -21
  22. iam_validator/core/config/__init__.py +83 -0
  23. iam_validator/core/config/aws_api.py +35 -0
  24. iam_validator/core/config/condition_requirements.py +535 -0
  25. iam_validator/core/config/defaults.py +390 -0
  26. iam_validator/core/config/principal_requirements.py +421 -0
  27. iam_validator/core/config/sensitive_actions.py +133 -0
  28. iam_validator/core/config/service_principals.py +95 -0
  29. iam_validator/core/config/wildcards.py +124 -0
  30. iam_validator/core/config_loader.py +29 -9
  31. iam_validator/core/formatters/enhanced.py +11 -5
  32. iam_validator/core/formatters/sarif.py +78 -14
  33. iam_validator/core/models.py +13 -3
  34. iam_validator/core/policy_checks.py +39 -6
  35. iam_validator/core/pr_commenter.py +30 -9
  36. iam_policy_validator-1.3.1.dist-info/RECORD +0 -54
  37. iam_validator/checks/security_best_practices.py +0 -535
  38. iam_validator/core/defaults.py +0 -366
  39. {iam_policy_validator-1.3.1.dist-info → iam_policy_validator-1.5.0.dist-info}/WHEEL +0 -0
  40. {iam_policy_validator-1.3.1.dist-info → iam_policy_validator-1.5.0.dist-info}/entry_points.txt +0 -0
  41. {iam_policy_validator-1.3.1.dist-info → iam_policy_validator-1.5.0.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,390 @@
1
+ """
2
+ Default configuration for IAM Policy Validator.
3
+
4
+ This module contains the default configuration that is used when no user
5
+ configuration file is provided. User configuration files will override
6
+ these defaults.
7
+
8
+ This configuration uses Python-native data structures (imported from
9
+ iam_validator.core.config) for optimal performance and PyPI packaging.
10
+
11
+ Benefits of code-first approach:
12
+ - Zero parsing overhead (no YAML/JSON parsing)
13
+ - Compiled to .pyc for faster imports
14
+ - Better IDE support and type hints
15
+ - No data files to manage in PyPI package
16
+ - 5-10x faster than YAML parsing
17
+ """
18
+
19
+ from iam_validator.core.config.condition_requirements import get_default_requirements
20
+ from iam_validator.core.config.principal_requirements import (
21
+ get_default_principal_requirements,
22
+ )
23
+ from iam_validator.core.config.service_principals import DEFAULT_SERVICE_PRINCIPALS
24
+ from iam_validator.core.config.wildcards import (
25
+ DEFAULT_ALLOWED_WILDCARDS,
26
+ DEFAULT_SERVICE_WILDCARDS,
27
+ )
28
+
29
+ # ============================================================================
30
+ # SEVERITY LEVELS
31
+ # ============================================================================
32
+ # The validator uses two types of severity levels:
33
+ #
34
+ # 1. IAM VALIDITY SEVERITIES (for AWS IAM policy correctness):
35
+ # - error: Policy violates AWS IAM rules (invalid actions, ARNs, etc.)
36
+ # - warning: Policy may have IAM-related issues but is technically valid
37
+ # - info: Informational messages about the policy structure
38
+ #
39
+ # 2. SECURITY SEVERITIES (for security best practices):
40
+ # - critical: Critical security risk (e.g., wildcard action + resource)
41
+ # - high: High security risk (e.g., missing required conditions)
42
+ # - medium: Medium security risk (e.g., overly permissive wildcards)
43
+ # - low: Low security risk (e.g., minor best practice violations)
44
+ #
45
+ # Use 'error' for policy validity issues, and 'critical/high/medium/low' for
46
+ # security best practices. This distinction helps separate "broken policies"
47
+ # from "insecure but valid policies".
48
+ # ============================================================================
49
+
50
+ # ============================================================================
51
+ # DEFAULT CONFIGURATION
52
+ # ============================================================================
53
+ DEFAULT_CONFIG = {
54
+ # ========================================================================
55
+ # Global Settings
56
+ # ========================================================================
57
+ "settings": {
58
+ # Stop validation on first error
59
+ "fail_fast": False,
60
+ # Maximum number of concurrent policy validations
61
+ "max_concurrent": 10,
62
+ # Enable/disable ALL built-in checks (set to False when using AWS Access Analyzer)
63
+ "enable_builtin_checks": True,
64
+ # Enable parallel execution of checks for better performance
65
+ "parallel_execution": True,
66
+ # Path to directory containing pre-downloaded AWS service definitions
67
+ # Set to a directory path to use offline validation, or None to use AWS API
68
+ "aws_services_dir": None,
69
+ # Cache AWS service definitions locally (persists between runs)
70
+ "cache_enabled": True,
71
+ # Cache TTL in hours (default: 168 = 7 days)
72
+ "cache_ttl_hours": 168,
73
+ # Severity levels that cause validation to fail
74
+ # IAM Validity: error, warning, info
75
+ # Security: critical, high, medium, low
76
+ "fail_on_severity": ["error", "critical", "high"],
77
+ },
78
+ # ========================================================================
79
+ # AWS IAM Validation Checks
80
+ # These validate that policies conform to AWS IAM requirements
81
+ # ========================================================================
82
+ # Validate Statement ID (Sid) uniqueness as per AWS IAM requirements
83
+ # AWS requires:
84
+ # - Sids must be unique within the policy (duplicate_sid error)
85
+ # - Sids must contain only alphanumeric characters, hyphens, and underscores
86
+ # - No spaces or special characters allowed
87
+ "sid_uniqueness": {
88
+ "enabled": True,
89
+ "severity": "error", # IAM validity error
90
+ "description": "Validates that Statement IDs (Sids) are unique and follow AWS naming requirements",
91
+ },
92
+ # Validate policy size against AWS limits
93
+ # Policy type determines which AWS limit to enforce:
94
+ # - managed: 6144 characters (excluding whitespace)
95
+ # - inline_user: 2048 characters
96
+ # - inline_group: 5120 characters
97
+ # - inline_role: 10240 characters
98
+ "policy_size": {
99
+ "enabled": True,
100
+ "severity": "error", # IAM validity error
101
+ "description": "Validates that IAM policies don't exceed AWS size limits",
102
+ "policy_type": "managed", # Change based on your policy type
103
+ },
104
+ # Validate IAM actions against AWS service definitions
105
+ # Uses AWS Service Authorization Reference to validate action names
106
+ # Catches typos like "s3:GetObjekt" or non-existent actions
107
+ "action_validation": {
108
+ "enabled": True,
109
+ "severity": "error", # IAM validity error
110
+ "description": "Validates that actions exist in AWS services",
111
+ },
112
+ # Validate condition keys for actions against AWS service definitions
113
+ # Ensures condition keys are valid for the specified actions
114
+ # Examples:
115
+ # ✅ s3:GetObject with s3:prefix condition
116
+ # ❌ s3:GetObject with ec2:InstanceType condition (invalid)
117
+ "condition_key_validation": {
118
+ "enabled": True,
119
+ "severity": "error", # IAM validity error
120
+ "description": "Validates condition keys against AWS service definitions for specified actions",
121
+ # Validate aws:* global condition keys against known list
122
+ "validate_aws_global_keys": True,
123
+ # Warn when global condition keys (aws:*) are used with actions that have action-specific keys
124
+ # While global condition keys can be used across all AWS services, they may not be available
125
+ # in every request context. This warning helps ensure proper validation.
126
+ # Set to False to disable warnings for global condition keys
127
+ "warn_on_global_condition_keys": True,
128
+ },
129
+ # Validate resource ARN formats
130
+ # Ensures ARNs follow the correct format:
131
+ # arn:partition:service:region:account-id:resource-type/resource-id
132
+ # Pattern allows wildcards (*) in region and account fields
133
+ "resource_validation": {
134
+ "enabled": True,
135
+ "severity": "error", # IAM validity error
136
+ "description": "Validates ARN format for resources",
137
+ "arn_pattern": "^arn:(aws|aws-cn|aws-us-gov|aws-eusc|aws-iso|aws-iso-b|aws-iso-e|aws-iso-f):[a-z0-9\\-]+:[a-z0-9\\-*]*:[0-9*]*:.+$",
138
+ },
139
+ # ========================================================================
140
+ # Principal Validation (Resource Policies)
141
+ # ========================================================================
142
+ # Validates Principal elements in resource-based policies
143
+ # (S3 buckets, SNS topics, SQS queues, etc.)
144
+ # Only runs when --policy-type RESOURCE_POLICY is specified
145
+ #
146
+ # See: iam_validator/core/config/service_principals.py for defaults
147
+ "principal_validation": {
148
+ "enabled": True,
149
+ "severity": "high", # Security issue, not IAM validity error
150
+ "description": "Validates Principal elements in resource policies for security best practices",
151
+ # blocked_principals: Principals that should NEVER be allowed (deny list)
152
+ # Default: ["*"] blocks public access to everyone
153
+ # Examples:
154
+ # ["*"] - Block public access
155
+ # ["*", "arn:aws:iam::*:root"] - Block public + all AWS accounts
156
+ "blocked_principals": ["*"],
157
+ # allowed_principals: When set, ONLY these principals are allowed (whitelist mode)
158
+ # Leave empty to allow all except blocked principals
159
+ # Examples:
160
+ # [] - Allow all (except blocked)
161
+ # ["arn:aws:iam::123456789012:root"] - Only allow specific account
162
+ # ["arn:aws:iam::*:role/OrgAccessRole"] - Allow specific role in any account
163
+ "allowed_principals": [],
164
+ # require_conditions_for: Principals that MUST have specific IAM conditions
165
+ # Format: {principal_pattern: [required_condition_keys]}
166
+ # Default: Public access (*) must specify source to limit scope
167
+ # Examples:
168
+ # "*": ["aws:SourceArn"] - Public access must specify source ARN
169
+ # "arn:aws:iam::*:root": ["aws:PrincipalOrgID"] - Cross-account must be from org
170
+ "require_conditions_for": {
171
+ "*": [
172
+ "aws:SourceArn",
173
+ "aws:SourceAccount",
174
+ "aws:SourceVpce",
175
+ "aws:SourceIp",
176
+ "aws:SourceOrgID",
177
+ "aws:SourceOrgPaths",
178
+ ],
179
+ },
180
+ # principal_condition_requirements: Advanced condition requirements for principals
181
+ # Similar to action_condition_enforcement but for principals
182
+ # Supports all_of/any_of/none_of logic with rich metadata
183
+ # Default: 2 critical requirements enabled (public_access, prevent_insecure_transport)
184
+ # See: iam_validator/core/config/principal_requirements.py
185
+ # To customize requirements, use Python API:
186
+ # from iam_validator.core.config import get_principal_requirements_by_names
187
+ # requirements = get_principal_requirements_by_names(['public_access', 'cross_account_org'])
188
+ # To disable: set to empty list []
189
+ "principal_condition_requirements": get_default_principal_requirements(),
190
+ # allowed_service_principals: AWS service principals that are always allowed
191
+ # Default: 16 common AWS services (cloudfront, s3, lambda, logs, etc.)
192
+ # These are typically safe as AWS services need access to resources
193
+ # See: iam_validator/core/config/service_principals.py
194
+ "allowed_service_principals": list(DEFAULT_SERVICE_PRINCIPALS),
195
+ },
196
+ # Validate resource constraints for actions
197
+ # Ensures that actions without required resource types (account-level operations)
198
+ # use Resource: "*" as they cannot target specific resources
199
+ # Example: iam:ListUsers cannot target a specific user, must use "*"
200
+ "action_resource_constraint": {
201
+ "enabled": True,
202
+ "severity": "error", # IAM validity error
203
+ "description": "Validates that actions without required resource types use Resource: '*'",
204
+ },
205
+ # ========================================================================
206
+ # Security Best Practices Checks
207
+ # ========================================================================
208
+ # Individual checks for security anti-patterns
209
+ #
210
+ # Configuration Fields Reference:
211
+ # - description: Technical description of what the check does (internal/docs)
212
+ # - message: Error/warning shown to users when issue is detected
213
+ # - suggestion: Guidance on how to fix or mitigate the issue
214
+ # - example: Concrete code example showing before/after or proper usage
215
+ #
216
+ # Field Progression: detect (description) → alert (message) → advise (suggestion) → demonstrate (example)
217
+ #
218
+ # For detailed explanation of these fields and how to customize them,
219
+ # see: docs/configuration.md#customizing-messages
220
+ #
221
+ # See: iam_validator/core/config/wildcards.py for allowed wildcards
222
+ # See: iam_validator/core/config/sensitive_actions.py for sensitive actions
223
+ # ========================================================================
224
+ # Check for wildcard actions (Action: "*")
225
+ # Flags statements that allow all actions
226
+ "wildcard_action": {
227
+ "enabled": True,
228
+ "severity": "medium", # Security issue
229
+ "description": "Checks for wildcard actions (*)",
230
+ "message": "Statement allows all actions (*)",
231
+ "suggestion": "Replace wildcard with specific actions needed for your use case",
232
+ "example": (
233
+ "Replace:\n"
234
+ ' "Action": ["*"]\n'
235
+ "\n"
236
+ "With specific actions:\n"
237
+ ' "Action": ["s3:GetObject", "s3:PutObject", "s3:ListBucket"]\n'
238
+ ),
239
+ },
240
+ # Check for wildcard resources (Resource: "*")
241
+ # Flags statements that apply to all resources
242
+ # Exception: Allowed if ALL actions are in allowed_wildcards list
243
+ "wildcard_resource": {
244
+ "enabled": True,
245
+ "severity": "medium", # Security issue
246
+ "description": "Checks for wildcard resources (*)",
247
+ # Allowed wildcard patterns for actions that can be used with Resource: "*"
248
+ # Default: 25 read-only patterns (Describe*, List*, Get*)
249
+ # See: iam_validator/core/config/wildcards.py
250
+ "allowed_wildcards": list(DEFAULT_ALLOWED_WILDCARDS),
251
+ "message": "Statement applies to all resources (*)",
252
+ "suggestion": "Replace wildcard with specific resource ARNs",
253
+ "example": (
254
+ "Replace:\n"
255
+ ' "Resource": "*"\n'
256
+ "\n"
257
+ "With specific ARNs:\n"
258
+ ' "Resource": [\n'
259
+ ' "arn:aws:service:region:account-id:resource-type/resource-id",\n'
260
+ ' "arn:aws:service:region:account-id:resource-type/*"\n'
261
+ " ]\n"
262
+ ),
263
+ },
264
+ # Check for BOTH Action: "*" AND Resource: "*" (CRITICAL)
265
+ # This grants full administrative access (AdministratorAccess equivalent)
266
+ "full_wildcard": {
267
+ "enabled": True,
268
+ "severity": "critical", # CRITICAL security risk
269
+ "description": "Checks for both action and resource wildcards together (critical risk)",
270
+ "message": "Statement allows all actions on all resources - CRITICAL SECURITY RISK",
271
+ "suggestion": (
272
+ "This grants full administrative access. Replace both wildcards with specific actions "
273
+ "and resources to follow least-privilege principle"
274
+ ),
275
+ "example": (
276
+ "Replace:\n"
277
+ ' "Action": "*",\n'
278
+ ' "Resource": "*"\n'
279
+ "\n"
280
+ "With specific values:\n"
281
+ ' "Action": [\n'
282
+ ' "s3:GetObject",\n'
283
+ ' "s3:PutObject"\n'
284
+ " ],\n"
285
+ ' "Resource": [\n'
286
+ ' "arn:aws:s3:::my-bucket/*"\n'
287
+ " ]\n"
288
+ ),
289
+ },
290
+ # Check for service-level wildcards (e.g., "iam:*", "s3:*", "ec2:*")
291
+ # These grant ALL permissions for a service (often too permissive)
292
+ # Exception: Some services like logs, cloudwatch are typically safe
293
+ #
294
+ # Template placeholders supported in message/suggestion/example:
295
+ # - {action}: The wildcard action found (e.g., "s3:*")
296
+ # - {service}: The service name (e.g., "s3")
297
+ "service_wildcard": {
298
+ "enabled": True,
299
+ "severity": "high", # Security issue
300
+ "description": "Checks for service-level wildcards (e.g., 'iam:*', 's3:*')",
301
+ # Services that are allowed to use wildcards (default: logs, cloudwatch, xray)
302
+ # See: iam_validator/core/config/wildcards.py
303
+ "allowed_services": list(DEFAULT_SERVICE_WILDCARDS),
304
+ },
305
+ # Check for sensitive actions without IAM conditions
306
+ # Sensitive actions: IAM changes, secrets access, destructive operations
307
+ # Default: 79 actions across 8 categories
308
+ # Categories: iam_identity, secrets_credentials, compute_containers,
309
+ # database_storage, s3_backup, network_security,
310
+ # access_logging, account_organization
311
+ #
312
+ # Scans at BOTH statement-level AND policy-level for security patterns
313
+ # See: iam_validator/core/config/sensitive_actions.py
314
+ # Python API: get_actions_by_categories(['iam_identity', 'secrets_credentials'])
315
+ #
316
+ # Template placeholders supported:
317
+ # - message_single uses {action}: Single action name (e.g., "iam:CreateRole")
318
+ # - message_multiple uses {actions}: Comma-separated list (e.g., "iam:CreateRole', 'iam:PutUserPolicy")
319
+ # - suggestion and example support both {action} and {actions}
320
+ "sensitive_action": {
321
+ "enabled": True,
322
+ "severity": "medium", # Security issue
323
+ "description": "Checks for sensitive actions without conditions",
324
+ # Custom message templates (support {action} and {actions} placeholders)
325
+ "message_single": "Sensitive action '{action}' should have conditions to limit when it can be used",
326
+ "message_multiple": "Sensitive actions '{actions}' should have conditions to limit when they can be used",
327
+ "suggestion": (
328
+ "Add IAM conditions to limit when this action can be used.\n"
329
+ "Consider: ABAC (ResourceTag OR RequestTag matching ${aws:PrincipalTag}), "
330
+ "IP restrictions (aws:SourceIp), MFA requirements (aws:MultiFactorAuthPresent), "
331
+ "or time-based restrictions (aws:CurrentTime)\n"
332
+ ),
333
+ "example": (
334
+ '"Condition": {\n'
335
+ ' "StringEquals": {\n'
336
+ ' "aws:ResourceTag/owner": "${aws:PrincipalTag/owner}"\n'
337
+ " }\n"
338
+ "}\n"
339
+ ),
340
+ },
341
+ # ========================================================================
342
+ # Action Condition Enforcement
343
+ # ========================================================================
344
+ # Enforce specific IAM condition requirements for actions
345
+ # Examples: iam:PassRole must specify iam:PassedToService,
346
+ # S3 writes must require MFA, EC2 launches must use tags
347
+ #
348
+ # Default: 5 enabled requirements out of 13 available
349
+ # Available requirements:
350
+ # Default (enabled):
351
+ # - iam_pass_role: Requires iam:PassedToService
352
+ # - iam_permissions_boundary: Requires permissions boundary
353
+ # - s3_org_id: Requires organization ID for S3 writes
354
+ # - source_ip_restrictions: Restricts to corporate IPs
355
+ # - s3_secure_transport: Prevents insecure transport
356
+ # Optional (disabled by default):
357
+ # - s3_destructive_mfa: Requires MFA for S3 deletes
358
+ # - s3_require_https: Requires HTTPS for all S3 operations
359
+ # - ec2_vpc_restriction: Restricts EC2 to specific VPCs
360
+ # - ec2_tag_requirements: ABAC tag requirements for EC2
361
+ # - rds_tag_requirements: Tag requirements for RDS
362
+ # - s3_bucket_tag_requirements: Tag requirements for S3 buckets
363
+ # - forbidden_actions: Flags forbidden actions
364
+ # - prevent_public_ip: Prevents 0.0.0.0/0 IP ranges
365
+ #
366
+ # See: iam_validator/core/config/condition_requirements.py
367
+ # Python API:
368
+ # from iam_validator.core.config import get_requirements_by_names
369
+ # requirements = get_requirements_by_names(['iam_pass_role', 's3_destructive_mfa'])
370
+ "action_condition_enforcement": {
371
+ "enabled": True,
372
+ "severity": "high", # Default severity (can be overridden per-requirement)
373
+ "description": "Enforces conditions (MFA, IP, tags, etc.) for specific actions (supports all_of/any_of)",
374
+ # Load 5 default requirements from Python module
375
+ # Returns a deep copy to prevent mutation of the originals
376
+ "action_condition_requirements": get_default_requirements(),
377
+ },
378
+ }
379
+
380
+
381
+ def get_default_config() -> dict:
382
+ """
383
+ Get a deep copy of the default configuration.
384
+
385
+ Returns:
386
+ A deep copy of the default configuration dictionary
387
+ """
388
+ import copy
389
+
390
+ return copy.deepcopy(DEFAULT_CONFIG)