1use sha1::{Digest, Sha1};
9
10const IAM_ROLE_NAME_MAX_LEN: usize = 64;
12const HASH_LEN: usize = 8;
14
15pub 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}