alien-core 3.3.46

Deploy software into your customers' cloud accounts and keep it fully managed
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
use crate::error::{ErrorData, Result};
use crate::permissions::{PermissionProfile, PermissionSet};
use crate::resource::{ResourceDefinition, ResourceOutputsDefinition, ResourceRef, ResourceType};
use crate::Stack;
use alien_error::AlienError;
use bon::Builder;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use std::any::Any;
use std::borrow::Cow;
use std::collections::BTreeSet;
use std::fmt::Debug;

/// Represents a non-human identity that can be assumed by compute services
/// such as Lambda, Cloud Run, ECS, Container Apps, etc.
///
/// Maps to:
/// - AWS: IAM Role
/// - GCP: Service Account
/// - Azure: User-assigned Managed Identity
///
/// The ServiceAccount is automatically created from permission profiles in the stack
/// and contains the resolved permission sets for both stack-level and resource-scoped access.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Builder)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[builder(start_fn = new)]
pub struct ServiceAccount {
    /// Identifier for the service account. Must contain only alphanumeric characters, hyphens, and underscores ([A-Za-z0-9-_]).
    /// Maximum 64 characters.
    #[builder(start_fn)]
    pub id: String,

    /// Stack-level permission sets that apply to all resources in the stack.
    /// These are derived from the "*" scope in the permission profile.
    /// Resource-scoped permissions are handled by individual resource controllers.
    #[builder(field)]
    pub stack_permission_sets: Vec<PermissionSet>,

    /// Resolved grants for concrete resource IDs, captured for setup comparison.
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    #[builder(default)]
    pub resource_permission_sets: IndexMap<String, Vec<PermissionSet>>,
}

impl ServiceAccount {
    /// The resource type identifier for ServiceAccount
    pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("service-account");

    /// Returns the service account's unique identifier.
    pub fn id(&self) -> &str {
        &self.id
    }

    /// Creates a ServiceAccount from a permission profile by resolving permission set references.
    /// This is used by the stack processor to convert profiles into concrete ServiceAccount resources.
    pub fn from_permission_profile(
        id: String,
        profile: &PermissionProfile,
        permission_set_resolver: impl Fn(&str) -> Option<PermissionSet>,
    ) -> Result<Self> {
        let mut stack_permission_sets = Vec::new();
        let mut resource_permission_sets = IndexMap::new();
        for (resource_id, references) in &profile.0 {
            let sets = references
                .iter()
                .map(|reference| {
                    reference.resolve(&permission_set_resolver).ok_or_else(|| {
                        AlienError::new(ErrorData::GenericError {
                            message: format!(
                                "Permission set '{}' not found for service account '{}'",
                                reference.id(),
                                id
                            ),
                        })
                    })
                })
                .collect::<Result<Vec<_>>>()?;
            if resource_id == "*" {
                stack_permission_sets = sets;
            } else {
                resource_permission_sets.insert(resource_id.clone(), sets);
            }
        }
        Ok(Self {
            id,
            stack_permission_sets,
            resource_permission_sets,
        })
    }

    /// Uses captured grants; legacy templates may supply their existing explicit profile.
    /// This compatibility path does not create a profile or add default grants.
    pub fn concrete_permission_sets(
        &self,
        legacy_profile: Option<&PermissionProfile>,
        resolver: impl Fn(&str) -> Option<PermissionSet>,
    ) -> Result<Cow<'_, IndexMap<String, Vec<PermissionSet>>>> {
        if !self.resource_permission_sets.is_empty() {
            return Ok(Cow::Borrowed(&self.resource_permission_sets));
        }
        match legacy_profile {
            Some(profile) => Ok(Cow::Owned(
                Self::from_permission_profile(self.id.clone(), profile, resolver)?
                    .resource_permission_sets,
            )),
            None => Ok(Cow::Borrowed(&self.resource_permission_sets)),
        }
    }
}

/// The permission set that lets one service account assume another.
const IMPERSONATE_PERMISSION_SET: &str = "service-account/impersonate";

impl ServiceAccount {
    /// The service account a resource-scoped impersonation grant targets. A grant names either
    /// the account itself or the profile it was created from (`{profile}` → `{profile}-sa`).
    pub fn impersonation_target(stack: &Stack, scope: &str) -> Option<String> {
        [scope.to_string(), format!("{scope}-sa")]
            .into_iter()
            .find(|id| is_service_account(stack, id))
    }

    /// Ids of the other service accounts in `stack` that may impersonate this one.
    ///
    /// Reads the permission profiles and each account's captured grants: a frozen account keeps
    /// its grants after the profile that produced them is gone, and the caller policy is written
    /// from those grants, so its trust has to be too.
    pub fn impersonators(&self, stack: &Stack) -> BTreeSet<String> {
        let scopes = [Some(self.id.as_str()), self.id.strip_suffix("-sa")];
        let mut ids: BTreeSet<String> = stack
            .permissions
            .profiles
            .iter()
            .filter(|(_, profile)| {
                scopes
                    .iter()
                    .flatten()
                    .filter_map(|scope| profile.0.get(*scope))
                    .flatten()
                    .any(|reference| reference.id() == IMPERSONATE_PERMISSION_SET)
            })
            .map(|(profile, _)| format!("{profile}-sa"))
            .collect();
        for (id, entry) in stack.resources() {
            let Some(caller) = entry.config.downcast_ref::<ServiceAccount>() else {
                continue;
            };
            let grants_this = caller.resource_permission_sets.iter().any(|(scope, sets)| {
                sets.iter().any(|set| set.id == IMPERSONATE_PERMISSION_SET)
                    && Self::impersonation_target(stack, scope).as_deref() == Some(self.id.as_str())
            });
            if grants_this {
                ids.insert(id.clone());
            }
        }
        ids.retain(|id| id != &self.id && is_service_account(stack, id));
        ids
    }
}

fn is_service_account(stack: &Stack, id: &str) -> bool {
    stack.resources().any(|(resource_id, entry)| {
        resource_id == id && entry.config.downcast_ref::<ServiceAccount>().is_some()
    })
}

impl ServiceAccountBuilder {
    /// Adds a stack-level permission set to the service account.
    /// Stack-level permissions apply to all resources in the stack.
    pub fn stack_permission_set(mut self, permission_set: PermissionSet) -> Self {
        self.stack_permission_sets.push(permission_set);
        self
    }
}

// Implementation of ResourceDefinition trait for ServiceAccount
impl ResourceDefinition for ServiceAccount {
    fn get_resource_type(&self) -> ResourceType {
        Self::RESOURCE_TYPE
    }

    fn id(&self) -> &str {
        &self.id
    }

    fn get_dependencies(&self) -> Vec<ResourceRef> {
        // ServiceAccount doesn't depend on other resources directly
        // Dependencies will be managed through the stack processor
        Vec::new()
    }

    fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
        let new_service_account = new_config
            .as_any()
            .downcast_ref::<ServiceAccount>()
            .ok_or_else(|| {
                AlienError::new(ErrorData::UnexpectedResourceType {
                    resource_id: self.id.clone(),
                    expected: Self::RESOURCE_TYPE,
                    actual: new_config.get_resource_type(),
                })
            })?;

        if self.id != new_service_account.id {
            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
                resource_id: self.id.clone(),
                reason: "the 'id' field is immutable".to_string(),
            }));
        }

        Ok(())
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    fn box_clone(&self) -> Box<dyn ResourceDefinition> {
        Box::new(self.clone())
    }

    fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
        other.as_any().downcast_ref::<ServiceAccount>() == Some(self)
    }

    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
        serde_json::to_value(self)
    }
}

/// Outputs generated by a successfully provisioned ServiceAccount.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct ServiceAccountOutputs {
    /// The platform-specific identifier of the service account
    /// - AWS: Role ARN
    /// - GCP: Service Account email
    /// - Azure: Managed Identity client ID
    pub identity: String,

    /// The platform-specific resource name/ID
    /// - AWS: Role name
    /// - GCP: Service Account unique ID
    /// - Azure: Managed Identity resource ID
    pub resource_id: String,
}

impl ResourceOutputsDefinition for ServiceAccountOutputs {
    fn get_resource_type(&self) -> ResourceType {
        ServiceAccount::RESOURCE_TYPE.clone()
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
        Box::new(self.clone())
    }

    fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
        other.as_any().downcast_ref::<ServiceAccountOutputs>() == Some(self)
    }

    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
        serde_json::to_value(self)
    }
}

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

    fn signing(scope: &str) -> PermissionSet {
        serde_json::from_value(json!({
            "id": "storage/sign", "description": "Sign object URLs",
            "platforms": {"gcp": [{"label": "sign", "description": "Sign URLs",
                "grant": {"permissions": ["iam.serviceAccounts.signBlob"]},
                "binding": {"resource": {"scope": scope}, "stack": {"scope": scope}}
            }]}
        }))
        .unwrap()
    }

    fn impersonate() -> PermissionSet {
        serde_json::from_value(json!({
            "id": "service-account/impersonate", "description": "Assume a service account",
            "platforms": {"aws": [{"grant": {"actions": ["sts:AssumeRole"]},
                "binding": {"resource": {"resources": ["*"]}}}]}
        }))
        .unwrap()
    }

    #[test]
    fn a_frozen_callers_captured_grant_makes_it_an_impersonator_without_a_profile() {
        use crate::{permissions::PermissionsConfig, ResourceLifecycle, Stack};
        let target = ServiceAccount::new("target-sa".to_string()).build();
        // Captured grants name the target by profile ("target") and by id ("target-sa").
        let by_profile = ServiceAccount::new("manager-sa".to_string())
            .resource_permission_sets(IndexMap::from([(
                "target".to_string(),
                vec![impersonate()],
            )]))
            .build();
        let by_id = ServiceAccount::new("operator-sa".to_string())
            .resource_permission_sets(IndexMap::from([(
                "target-sa".to_string(),
                vec![impersonate()],
            )]))
            .build();
        let bystander = ServiceAccount::new("reader-sa".to_string())
            .resource_permission_sets(IndexMap::from([("target".to_string(), vec![signing("*")])]))
            .build();
        let profiled = ServiceAccount::new("execution-sa".to_string()).build();
        let stack = Stack::new("acme".to_string())
            .add(target.clone(), ResourceLifecycle::Frozen)
            .add(by_profile, ResourceLifecycle::Frozen)
            .add(by_id, ResourceLifecycle::Frozen)
            .add(bystander, ResourceLifecycle::Frozen)
            .add(profiled, ResourceLifecycle::Frozen)
            .permissions(PermissionsConfig::new().with_profile(
                "execution",
                PermissionProfile::new().resource("target", ["service-account/impersonate"]),
            ))
            .build();

        assert_eq!(
            target.impersonators(&stack),
            BTreeSet::from([
                "execution-sa".to_string(),
                "manager-sa".to_string(),
                "operator-sa".to_string(),
            ])
        );
    }

    #[test]
    fn concrete_definitions_are_captured_separately_and_override_legacy_lookup() {
        let old = signing("projects/${projectName}");
        let new = signing("projects/${projectName}/serviceAccounts/${serviceAccountName}@${projectName}.iam.gserviceaccount.com");
        let profile = PermissionProfile::new()
            .resource("*", ["storage/sign"])
            .resource("objects", ["storage/sign"]);
        let before =
            ServiceAccount::from_permission_profile("reader-sa".to_string(), &profile, |_| {
                Some(old.clone())
            })
            .unwrap();
        let after =
            ServiceAccount::from_permission_profile("reader-sa".to_string(), &profile, |_| {
                Some(new.clone())
            })
            .unwrap();
        assert_eq!(before.stack_permission_sets, vec![old.clone()]);
        assert_eq!(before.resource_permission_sets["objects"], vec![old]);
        assert_eq!(after.resource_permission_sets["objects"], vec![new.clone()]);
        assert!(!before.resource_eq(&after));
        assert_eq!(
            after
                .concrete_permission_sets(Some(&profile), |_| panic!(
                    "captured definitions must be used"
                ))
                .unwrap()["objects"],
            vec![new]
        );
        assert!(
            ServiceAccount::from_permission_profile("reader-sa".to_string(), &profile, |_| None)
                .is_err()
        );
    }

    #[test]
    fn legacy_account_deserializes_without_implicit_grants_and_rejects_malformed_map() {
        let account: ServiceAccount =
            serde_json::from_value(json!({"id": "reader-sa", "stackPermissionSets": []})).unwrap();
        assert!(account.resource_permission_sets.is_empty());
        assert!(account
            .concrete_permission_sets(None, |_| None)
            .unwrap()
            .is_empty());
        assert!(serde_json::to_value(&account)
            .unwrap()
            .get("resourcePermissionSets")
            .is_none());
        let set = signing("projects/${projectName}");
        let profile = PermissionProfile::new().resource("objects", ["storage/sign"]);
        assert_eq!(
            account
                .concrete_permission_sets(Some(&profile), |_| Some(set.clone()))
                .unwrap()["objects"],
            vec![set]
        );
        assert!(account
            .concrete_permission_sets(Some(&profile), |_| None)
            .is_err());
        assert!(serde_json::from_value::<ServiceAccount>(json!({"id": "reader-sa", "stackPermissionSets": [], "resourcePermissionSets": {"objects": ["storage/sign"]}})).is_err());
    }
}