Skip to main content

alien_core/
aws_naming.rs

1//! How setup names AWS resources whose names something else derives later.
2//!
3//! The Terraform setup computes these names in HCL, from the resource prefix
4//! it only knows when applied. The functions here compute the same names in
5//! Rust, and the setup generator's tests check, through `terraform console`,
6//! that both give the same name.
7
8use sha1::{Digest, Sha1};
9
10/// IAM role names are capped at 64 characters.
11const IAM_ROLE_NAME_MAX_LEN: usize = 64;
12/// Characters of the stable hash appended to a shortened role name.
13const HASH_LEN: usize = 8;
14
15/// The IAM role name setup gives the role it creates under `suffix` (the
16/// service account `execution-sa` for the profile `execution`).
17///
18/// `<prefix>-<suffix>` while it fits in 64 characters; otherwise its first
19/// 55 characters and an 8-character hash of the full name.
20pub fn aws_iam_role_name(resource_prefix: &str, suffix: &str) -> String {
21    let full = format!("{resource_prefix}-{suffix}");
22    if full.chars().count() <= IAM_ROLE_NAME_MAX_LEN {
23        return full;
24    }
25    let start: String = full
26        .chars()
27        .take(IAM_ROLE_NAME_MAX_LEN - 1 - HASH_LEN)
28        .collect();
29    let hash: String = Sha1::digest(full.as_bytes())
30        .iter()
31        .map(|byte| format!("{byte:02x}"))
32        .collect();
33    format!("{start}-{}", &hash[..HASH_LEN])
34}
35
36#[cfg(test)]
37mod tests {
38    use super::*;
39
40    #[test]
41    fn a_name_over_64_characters_keeps_its_start_and_a_hash_of_the_full_name() {
42        assert_eq!(
43            aws_iam_role_name("acme-prod", "execution-sa"),
44            "acme-prod-execution-sa"
45        );
46        let long = aws_iam_role_name(
47            "acme-production-eu-west-1-tenant-customer42",
48            "background-processor-sa",
49        );
50        assert_eq!(
51            long,
52            "acme-production-eu-west-1-tenant-customer42-background--894db55f"
53        );
54        assert_eq!(long.len(), 64);
55    }
56}