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
use crate::{
error::{ErrorData, Result},
BindingTarget, PermissionContext,
};
use alien_core::PermissionSet;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value as JsonValue};
/// AWS IAM statement for CloudFormation templates
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "PascalCase")]
pub struct AwsCloudFormationIamStatement {
/// Statement ID
pub sid: String,
/// Effect (Allow/Deny)
pub effect: String,
/// List of IAM actions (can be CloudFormation intrinsic functions)
pub action: Vec<JsonValue>,
/// List of resource ARNs (can be CloudFormation intrinsic functions)
pub resource: Vec<JsonValue>,
/// Optional conditions (can contain CloudFormation intrinsic functions)
#[serde(skip_serializing_if = "Option::is_none")]
pub condition: Option<IndexMap<String, IndexMap<String, JsonValue>>>,
}
/// AWS IAM policy document for CloudFormation templates
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "PascalCase")]
pub struct AwsCloudFormationIamPolicy {
/// Policy version
pub version: String,
/// List of policy statements
pub statement: Vec<AwsCloudFormationIamStatement>,
}
/// AWS CloudFormation permissions generator for IAM policy documents
pub struct AwsCloudFormationPermissionsGenerator;
impl AwsCloudFormationPermissionsGenerator {
/// Create a new AWS CloudFormation permissions generator
pub fn new() -> Self {
Self
}
/// Generate a CloudFormation-compatible IAM policy document from a permission set and binding target
///
/// Takes a PermissionSet and where to bind it, produces AWS IAM policy documents
/// that can be embedded in CloudFormation templates with intrinsic functions.
pub fn generate_policy(
&self,
permission_set: &PermissionSet,
binding_target: BindingTarget,
context: &PermissionContext,
) -> Result<AwsCloudFormationIamPolicy> {
let aws_platform_permissions = permission_set.platforms.aws.as_ref().ok_or_else(|| {
alien_error::AlienError::new(ErrorData::PlatformNotSupported {
platform: "aws".to_string(),
permission_set_id: permission_set.id.clone(),
})
})?;
let mut statements = Vec::new();
// Process each AWS platform permission in the permission set
for (index, platform_permission) in aws_platform_permissions.iter().enumerate() {
let actions = platform_permission.grant.actions.as_ref().ok_or_else(|| {
alien_error::AlienError::new(ErrorData::GeneratorError {
platform: "aws".to_string(),
message: "AWS permission grant must have 'actions' field".to_string(),
})
})?;
let binding_spec = match binding_target {
BindingTarget::Stack => {
platform_permission.binding.stack.as_ref().ok_or_else(|| {
alien_error::AlienError::new(ErrorData::BindingTargetNotSupported {
platform: "aws".to_string(),
binding_target: "stack".to_string(),
permission_set_id: permission_set.id.clone(),
})
})?
}
BindingTarget::Resource => platform_permission
.binding
.resource
.as_ref()
.ok_or_else(|| {
alien_error::AlienError::new(ErrorData::BindingTargetNotSupported {
platform: "aws".to_string(),
binding_target: "resource".to_string(),
permission_set_id: permission_set.id.clone(),
})
})?,
};
let resources =
self.interpolate_cloudformation_resources(&binding_spec.resources, context)?;
let conditions = self.extract_cloudformation_conditions(binding_spec, context)?;
let statement_id = if aws_platform_permissions.len() > 1 {
format!(
"{}{}",
self.generate_statement_id(&permission_set.id),
index + 1
)
} else {
self.generate_statement_id(&permission_set.id)
};
// Convert actions to JsonValue (plain strings for now, could be intrinsic functions later)
// Sort actions to ensure deterministic output
let mut sorted_actions: Vec<_> = actions.iter().collect();
sorted_actions.sort();
let action_values: Vec<JsonValue> = sorted_actions.iter().map(|a| json!(a)).collect();
let statement = AwsCloudFormationIamStatement {
sid: statement_id,
effect: "Allow".to_string(),
action: action_values,
resource: resources,
condition: if conditions.is_empty() {
None
} else {
Some(conditions)
},
};
statements.push(statement);
}
Ok(AwsCloudFormationIamPolicy {
version: "2012-10-17".to_string(),
statement: statements,
})
}
/// Interpolate CloudFormation resource ARNs with intrinsic functions
fn interpolate_cloudformation_resources(
&self,
templates: &[String],
context: &PermissionContext,
) -> Result<Vec<JsonValue>> {
let mut resources: Result<Vec<JsonValue>> = templates
.iter()
.map(|template| self.interpolate_cloudformation_string(template, context))
.collect();
// Sort resources for deterministic output
if let Ok(ref mut resources_vec) = resources {
resources_vec.sort_by(|a, b| {
// Convert to string for comparison to ensure deterministic ordering
let a_str = serde_json::to_string(a).unwrap_or_default();
let b_str = serde_json::to_string(b).unwrap_or_default();
a_str.cmp(&b_str)
});
}
resources
}
/// Interpolate a CloudFormation string template with variables
/// Creates CloudFormation intrinsic functions (Fn::Sub, Ref) where appropriate
fn interpolate_cloudformation_string(
&self,
template: &str,
context: &PermissionContext,
) -> Result<JsonValue> {
// Check if the template contains CloudFormation variables or regular variables
let contains_cf_vars = template.contains("${AWS::") || template.contains("${!");
let contains_regular_vars = template.contains("${") && !contains_cf_vars;
if contains_cf_vars {
// Template already contains CloudFormation variables, wrap in Fn::Sub
Ok(json!({
"Fn::Sub": template
}))
} else if contains_regular_vars {
// Template contains our custom variables that need to be replaced
let mut result = template.to_string();
// First, replace our known variables with CloudFormation equivalents or literal values
if let Some(stack_prefix) = context.stack_prefix.as_ref() {
if stack_prefix.is_empty() {
// Empty stack prefix means just use the stack name
result = result.replace("${stackPrefix}", "${AWS::StackName}");
} else {
// Non-empty stack prefix gets appended with a dash
result = result.replace(
"${stackPrefix}",
&format!("${{AWS::StackName}}-{}", stack_prefix),
);
}
} else {
result = result.replace("${stackPrefix}", "${AWS::StackName}");
}
if let Some(resource_name) = context.resource_name.as_ref() {
// For resource names in CloudFormation context, we usually want the raw logical ID
// unless it's in an ARN context where we need to build the full ARN
if result.contains("arn:aws:") && result.contains("${resourceName}") {
// This is an ARN template, replace with the resource name directly
result = result.replace("${resourceName}", resource_name);
} else {
// Simple resource reference, just use the name
result = result.replace("${resourceName}", resource_name);
}
}
// Handle AWS-specific variables that should map to CloudFormation pseudo parameters
result = result.replace("${awsRegion}", "${AWS::Region}");
result = result.replace("${awsAccountId}", "${AWS::AccountId}");
// Handle external ID
if let Some(external_id) = context.external_id.as_ref() {
result = result.replace("${externalId}", external_id);
}
// Handle managing account ID - extract from ManagingRoleArn parameter
// ManagingRoleArn format: arn:aws:iam::123456789012:role/role-name
// We need to extract the account ID (element 4 when split by ':')
let needs_managing_account_id = result.contains("${managingAccountId}");
if needs_managing_account_id {
result = result.replace("${managingAccountId}", "${ManagingAccountId}");
// Use Fn::Sub with variable map to extract account ID from role ARN
return Ok(json!({
"Fn::Sub": [
result,
{
"ManagingAccountId": {
"Fn::Select": [4, {"Fn::Split": [":", {"Ref": "ManagingRoleArn"}]}]
}
}
]
}));
}
// If the result still contains CloudFormation variables after our substitutions, wrap in Fn::Sub
// This includes AWS pseudo parameters (${AWS::...}), CloudFormation parameters (${ParameterName}),
// and other CloudFormation references (${!...})
if result.contains("${") {
Ok(json!({
"Fn::Sub": result
}))
} else {
// Just a plain string after substitution
Ok(json!(result))
}
} else {
// No variables, just return as plain string
Ok(json!(template))
}
}
/// Extract AWS conditions from binding spec for CloudFormation
fn extract_cloudformation_conditions(
&self,
binding_spec: &alien_core::AwsBindingSpec,
context: &PermissionContext,
) -> Result<IndexMap<String, IndexMap<String, JsonValue>>> {
if let Some(condition_template) = &binding_spec.condition {
let mut interpolated_conditions = IndexMap::new();
// Sort condition keys for deterministic output
let mut sorted_condition_keys: Vec<_> = condition_template.keys().collect();
sorted_condition_keys.sort();
for condition_key in sorted_condition_keys {
let condition_values = &condition_template[condition_key];
let mut interpolated_values = IndexMap::new();
// Sort value keys for deterministic output
let mut sorted_value_keys: Vec<_> = condition_values.keys().collect();
sorted_value_keys.sort();
for value_key in sorted_value_keys {
let value_template = &condition_values[value_key];
let interpolated_value =
self.interpolate_cloudformation_string(value_template, context)?;
interpolated_values.insert(value_key.clone(), interpolated_value);
}
interpolated_conditions.insert(condition_key.clone(), interpolated_values);
}
Ok(interpolated_conditions)
} else {
Ok(IndexMap::new())
}
}
/// Generate a valid IAM statement ID from a permission set ID
fn generate_statement_id(&self, permission_set_id: &str) -> String {
// Convert to PascalCase and remove special characters for valid AWS Sid
permission_set_id
.split('/')
.map(|part| {
part.split('-')
.map(|word| {
let mut chars = word.chars();
match chars.next() {
None => String::new(),
Some(first) => {
first.to_uppercase().collect::<String>()
+ &chars.as_str().to_lowercase()
}
}
})
.collect::<String>()
})
.collect::<String>()
}
}
impl Default for AwsCloudFormationPermissionsGenerator {
fn default() -> Self {
Self::new()
}
}