Skip to main content

alien_core/resources/
service_account.rs

1use crate::error::{ErrorData, Result};
2use crate::permissions::{PermissionProfile, PermissionSet};
3use crate::resource::{ResourceDefinition, ResourceOutputsDefinition, ResourceRef, ResourceType};
4use crate::Stack;
5use alien_error::AlienError;
6use bon::Builder;
7use indexmap::IndexMap;
8use serde::{Deserialize, Serialize};
9use std::any::Any;
10use std::borrow::Cow;
11use std::collections::BTreeSet;
12use std::fmt::Debug;
13
14/// Represents a non-human identity that can be assumed by compute services
15/// such as Lambda, Cloud Run, ECS, Container Apps, etc.
16///
17/// Maps to:
18/// - AWS: IAM Role
19/// - GCP: Service Account
20/// - Azure: User-assigned Managed Identity
21///
22/// The ServiceAccount is automatically created from permission profiles in the stack
23/// and contains the resolved permission sets for both stack-level and resource-scoped access.
24#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Builder)]
25#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
26#[serde(rename_all = "camelCase", deny_unknown_fields)]
27#[builder(start_fn = new)]
28pub struct ServiceAccount {
29    /// Identifier for the service account. Must contain only alphanumeric characters, hyphens, and underscores ([A-Za-z0-9-_]).
30    /// Maximum 64 characters.
31    #[builder(start_fn)]
32    pub id: String,
33
34    /// Stack-level permission sets that apply to all resources in the stack.
35    /// These are derived from the "*" scope in the permission profile.
36    /// Resource-scoped permissions are handled by individual resource controllers.
37    #[builder(field)]
38    pub stack_permission_sets: Vec<PermissionSet>,
39
40    /// Resolved grants for concrete resource IDs, captured for setup comparison.
41    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
42    #[builder(default)]
43    pub resource_permission_sets: IndexMap<String, Vec<PermissionSet>>,
44
45    /// The extension whose controllers run as this identity. No workload may assume it: on a
46    /// cloud Alien's manager does, the way it assumes the remote bindings identity, and on
47    /// Kubernetes the Operator's pod does, the way it assumes the management identity.
48    #[serde(default, skip_serializing_if = "Option::is_none")]
49    pub extension: Option<String>,
50}
51
52impl ServiceAccount {
53    /// The resource type identifier for ServiceAccount
54    pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("service-account");
55
56    /// Returns the service account's unique identifier.
57    pub fn id(&self) -> &str {
58        &self.id
59    }
60
61    /// Creates a ServiceAccount from a permission profile by resolving permission set references.
62    /// This is used by the stack processor to convert profiles into concrete ServiceAccount resources.
63    pub fn from_permission_profile(
64        id: String,
65        profile: &PermissionProfile,
66        permission_set_resolver: impl Fn(&str) -> Option<PermissionSet>,
67    ) -> Result<Self> {
68        let mut stack_permission_sets = Vec::new();
69        let mut resource_permission_sets = IndexMap::new();
70        for (resource_id, references) in &profile.0 {
71            let sets = references
72                .iter()
73                .map(|reference| {
74                    reference.resolve(&permission_set_resolver).ok_or_else(|| {
75                        AlienError::new(ErrorData::GenericError {
76                            message: format!(
77                                "Permission set '{}' not found for service account '{}'",
78                                reference.id(),
79                                id
80                            ),
81                        })
82                    })
83                })
84                .collect::<Result<Vec<_>>>()?;
85            if resource_id == "*" {
86                stack_permission_sets = sets;
87            } else {
88                resource_permission_sets.insert(resource_id.clone(), sets);
89            }
90        }
91        Ok(Self {
92            id,
93            stack_permission_sets,
94            resource_permission_sets,
95            extension: None,
96        })
97    }
98
99    /// Uses captured grants; legacy templates may supply their existing explicit profile.
100    /// This compatibility path does not create a profile or add default grants.
101    pub fn concrete_permission_sets(
102        &self,
103        legacy_profile: Option<&PermissionProfile>,
104        resolver: impl Fn(&str) -> Option<PermissionSet>,
105    ) -> Result<Cow<'_, IndexMap<String, Vec<PermissionSet>>>> {
106        if !self.resource_permission_sets.is_empty() {
107            return Ok(Cow::Borrowed(&self.resource_permission_sets));
108        }
109        match legacy_profile {
110            Some(profile) => Ok(Cow::Owned(
111                Self::from_permission_profile(self.id.clone(), profile, resolver)?
112                    .resource_permission_sets,
113            )),
114            None => Ok(Cow::Borrowed(&self.resource_permission_sets)),
115        }
116    }
117}
118
119/// The permission set that lets one service account assume another.
120const IMPERSONATE_PERMISSION_SET: &str = "service-account/impersonate";
121
122impl ServiceAccount {
123    /// The service account a resource-scoped impersonation grant targets. A grant names either
124    /// the account itself or the profile it was created from (`{profile}` → `{profile}-sa`).
125    pub fn impersonation_target(stack: &Stack, scope: &str) -> Option<String> {
126        [scope.to_string(), format!("{scope}-sa")]
127            .into_iter()
128            .find(|id| is_service_account(stack, id))
129    }
130
131    /// Ids of the other service accounts in `stack` that may impersonate this one.
132    ///
133    /// Reads the permission profiles and each account's captured grants: a frozen account keeps
134    /// its grants after the profile that produced them is gone, and the caller policy is written
135    /// from those grants, so its trust has to be too.
136    pub fn impersonators(&self, stack: &Stack) -> BTreeSet<String> {
137        let scopes = [Some(self.id.as_str()), self.id.strip_suffix("-sa")];
138        let mut ids: BTreeSet<String> = stack
139            .permissions
140            .profiles
141            .iter()
142            .filter(|(_, profile)| {
143                scopes
144                    .iter()
145                    .flatten()
146                    .filter_map(|scope| profile.0.get(*scope))
147                    .flatten()
148                    .any(|reference| reference.id() == IMPERSONATE_PERMISSION_SET)
149            })
150            .map(|(profile, _)| format!("{profile}-sa"))
151            .collect();
152        for (id, entry) in stack.resources() {
153            let Some(caller) = entry.config.downcast_ref::<ServiceAccount>() else {
154                continue;
155            };
156            let grants_this = caller.resource_permission_sets.iter().any(|(scope, sets)| {
157                sets.iter().any(|set| set.id == IMPERSONATE_PERMISSION_SET)
158                    && Self::impersonation_target(stack, scope).as_deref() == Some(self.id.as_str())
159            });
160            if grants_this {
161                ids.insert(id.clone());
162            }
163        }
164        ids.retain(|id| id != &self.id && is_service_account(stack, id));
165        ids
166    }
167}
168
169fn is_service_account(stack: &Stack, id: &str) -> bool {
170    stack.resources().any(|(resource_id, entry)| {
171        resource_id == id && entry.config.downcast_ref::<ServiceAccount>().is_some()
172    })
173}
174
175impl ServiceAccountBuilder {
176    /// Adds a stack-level permission set to the service account.
177    /// Stack-level permissions apply to all resources in the stack.
178    pub fn stack_permission_set(mut self, permission_set: PermissionSet) -> Self {
179        self.stack_permission_sets.push(permission_set);
180        self
181    }
182}
183
184// Implementation of ResourceDefinition trait for ServiceAccount
185impl ResourceDefinition for ServiceAccount {
186    fn get_resource_type(&self) -> ResourceType {
187        Self::RESOURCE_TYPE
188    }
189
190    fn id(&self) -> &str {
191        &self.id
192    }
193
194    fn get_dependencies(&self) -> Vec<ResourceRef> {
195        // ServiceAccount doesn't depend on other resources directly
196        // Dependencies will be managed through the stack processor
197        Vec::new()
198    }
199
200    fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
201        let new_service_account = new_config
202            .as_any()
203            .downcast_ref::<ServiceAccount>()
204            .ok_or_else(|| {
205                AlienError::new(ErrorData::UnexpectedResourceType {
206                    resource_id: self.id.clone(),
207                    expected: Self::RESOURCE_TYPE,
208                    actual: new_config.get_resource_type(),
209                })
210            })?;
211
212        if self.id != new_service_account.id {
213            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
214                resource_id: self.id.clone(),
215                reason: "the 'id' field is immutable".to_string(),
216            }));
217        }
218        // The extension decides who may assume the identity, and an update never changes trust.
219        if self.extension != new_service_account.extension {
220            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
221                resource_id: self.id.clone(),
222                reason: "the 'extension' field is immutable".to_string(),
223            }));
224        }
225
226        Ok(())
227    }
228
229    fn as_any(&self) -> &dyn Any {
230        self
231    }
232
233    fn as_any_mut(&mut self) -> &mut dyn Any {
234        self
235    }
236
237    fn box_clone(&self) -> Box<dyn ResourceDefinition> {
238        Box::new(self.clone())
239    }
240
241    fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
242        other.as_any().downcast_ref::<ServiceAccount>() == Some(self)
243    }
244
245    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
246        serde_json::to_value(self)
247    }
248}
249
250/// Outputs generated by a successfully provisioned ServiceAccount.
251#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
252#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
253#[serde(rename_all = "camelCase")]
254pub struct ServiceAccountOutputs {
255    /// The platform-specific identifier of the service account
256    /// - AWS: Role ARN
257    /// - GCP: Service Account email
258    /// - Azure: Managed Identity client ID
259    pub identity: String,
260
261    /// The platform-specific resource name/ID
262    /// - AWS: Role name
263    /// - GCP: Service Account unique ID
264    /// - Azure: Managed Identity resource ID
265    pub resource_id: String,
266}
267
268impl ResourceOutputsDefinition for ServiceAccountOutputs {
269    fn get_resource_type(&self) -> ResourceType {
270        ServiceAccount::RESOURCE_TYPE.clone()
271    }
272
273    fn as_any(&self) -> &dyn Any {
274        self
275    }
276
277    fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
278        Box::new(self.clone())
279    }
280
281    fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
282        other.as_any().downcast_ref::<ServiceAccountOutputs>() == Some(self)
283    }
284
285    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
286        serde_json::to_value(self)
287    }
288}
289
290#[cfg(test)]
291mod tests {
292    use super::*;
293    use serde_json::json;
294
295    /// Who may assume an identity is decided at setup; an update can't turn a workload's account
296    /// into an extension's identity or back.
297    #[test]
298    fn an_update_never_changes_whose_identity_it_is() {
299        let workload = ServiceAccount::new("acme-ext".to_string()).build();
300        let identity = ServiceAccount::new("acme-ext".to_string())
301            .extension("acme".to_string())
302            .build();
303        let other = ServiceAccount::new("acme-ext".to_string())
304            .extension("other".to_string())
305            .build();
306        for (from, to) in [
307            (&workload, &identity),
308            (&identity, &workload),
309            (&identity, &other),
310        ] {
311            let error = from.validate_update(to).unwrap_err();
312            assert!(
313                format!("{error:?}").contains("the 'extension' field is immutable"),
314                "{error:?}"
315            );
316        }
317        identity.validate_update(&identity.clone()).unwrap();
318    }
319
320    fn signing(scope: &str) -> PermissionSet {
321        serde_json::from_value(json!({
322            "id": "storage/sign", "description": "Sign object URLs",
323            "platforms": {"gcp": [{"label": "sign", "description": "Sign URLs",
324                "grant": {"permissions": ["iam.serviceAccounts.signBlob"]},
325                "binding": {"resource": {"scope": scope}, "stack": {"scope": scope}}
326            }]}
327        }))
328        .unwrap()
329    }
330
331    fn impersonate() -> PermissionSet {
332        serde_json::from_value(json!({
333            "id": "service-account/impersonate", "description": "Assume a service account",
334            "platforms": {"aws": [{"grant": {"actions": ["sts:AssumeRole"]},
335                "binding": {"resource": {"resources": ["*"]}}}]}
336        }))
337        .unwrap()
338    }
339
340    #[test]
341    fn a_frozen_callers_captured_grant_makes_it_an_impersonator_without_a_profile() {
342        use crate::{permissions::PermissionsConfig, ResourceLifecycle, Stack};
343        let target = ServiceAccount::new("target-sa".to_string()).build();
344        // Captured grants name the target by profile ("target") and by id ("target-sa").
345        let by_profile = ServiceAccount::new("manager-sa".to_string())
346            .resource_permission_sets(IndexMap::from([(
347                "target".to_string(),
348                vec![impersonate()],
349            )]))
350            .build();
351        let by_id = ServiceAccount::new("operator-sa".to_string())
352            .resource_permission_sets(IndexMap::from([(
353                "target-sa".to_string(),
354                vec![impersonate()],
355            )]))
356            .build();
357        let bystander = ServiceAccount::new("reader-sa".to_string())
358            .resource_permission_sets(IndexMap::from([("target".to_string(), vec![signing("*")])]))
359            .build();
360        let profiled = ServiceAccount::new("execution-sa".to_string()).build();
361        let stack = Stack::new("acme".to_string())
362            .add(target.clone(), ResourceLifecycle::Frozen)
363            .add(by_profile, ResourceLifecycle::Frozen)
364            .add(by_id, ResourceLifecycle::Frozen)
365            .add(bystander, ResourceLifecycle::Frozen)
366            .add(profiled, ResourceLifecycle::Frozen)
367            .permissions(PermissionsConfig::new().with_profile(
368                "execution",
369                PermissionProfile::new().resource("target", ["service-account/impersonate"]),
370            ))
371            .build();
372
373        assert_eq!(
374            target.impersonators(&stack),
375            BTreeSet::from([
376                "execution-sa".to_string(),
377                "manager-sa".to_string(),
378                "operator-sa".to_string(),
379            ])
380        );
381    }
382
383    #[test]
384    fn concrete_definitions_are_captured_separately_and_override_legacy_lookup() {
385        let old = signing("projects/${projectName}");
386        let new = signing("projects/${projectName}/serviceAccounts/${serviceAccountName}@${projectName}.iam.gserviceaccount.com");
387        let profile = PermissionProfile::new()
388            .resource("*", ["storage/sign"])
389            .resource("objects", ["storage/sign"]);
390        let before =
391            ServiceAccount::from_permission_profile("reader-sa".to_string(), &profile, |_| {
392                Some(old.clone())
393            })
394            .unwrap();
395        let after =
396            ServiceAccount::from_permission_profile("reader-sa".to_string(), &profile, |_| {
397                Some(new.clone())
398            })
399            .unwrap();
400        assert_eq!(before.stack_permission_sets, vec![old.clone()]);
401        assert_eq!(before.resource_permission_sets["objects"], vec![old]);
402        assert_eq!(after.resource_permission_sets["objects"], vec![new.clone()]);
403        assert!(!before.resource_eq(&after));
404        assert_eq!(
405            after
406                .concrete_permission_sets(Some(&profile), |_| panic!(
407                    "captured definitions must be used"
408                ))
409                .unwrap()["objects"],
410            vec![new]
411        );
412        assert!(
413            ServiceAccount::from_permission_profile("reader-sa".to_string(), &profile, |_| None)
414                .is_err()
415        );
416    }
417
418    #[test]
419    fn legacy_account_deserializes_without_implicit_grants_and_rejects_malformed_map() {
420        let account: ServiceAccount =
421            serde_json::from_value(json!({"id": "reader-sa", "stackPermissionSets": []})).unwrap();
422        assert!(account.resource_permission_sets.is_empty());
423        assert!(account
424            .concrete_permission_sets(None, |_| None)
425            .unwrap()
426            .is_empty());
427        assert!(serde_json::to_value(&account)
428            .unwrap()
429            .get("resourcePermissionSets")
430            .is_none());
431        let set = signing("projects/${projectName}");
432        let profile = PermissionProfile::new().resource("objects", ["storage/sign"]);
433        assert_eq!(
434            account
435                .concrete_permission_sets(Some(&profile), |_| Some(set.clone()))
436                .unwrap()["objects"],
437            vec![set]
438        );
439        assert!(account
440            .concrete_permission_sets(Some(&profile), |_| None)
441            .is_err());
442        assert!(serde_json::from_value::<ServiceAccount>(json!({"id": "reader-sa", "stackPermissionSets": [], "resourcePermissionSets": {"objects": ["storage/sign"]}})).is_err());
443    }
444}