alien-permissions 1.5.0

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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
use crate::{
    error::{ErrorData, Result},
    generators::labels::{
        entry_description, entry_snake_label, entry_title_label, has_explicit_label,
    },
    variables::VariableInterpolator,
    BindingTarget, PermissionContext,
};
use alien_core::{GcpBindingSpec, PermissionGrant, PermissionSet};
use serde::{Deserialize, Serialize};

const GCP_CUSTOM_ROLE_ID_MAX_LEN: usize = 64;
const ROLE_ID_HASH_LEN: usize = 8;

/// GCP IAM binding condition.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct GcpIamCondition {
    /// Human-readable condition title.
    pub title: String,
    /// Description of the condition.
    pub description: String,
    /// CEL expression for the condition.
    pub expression: String,
}

/// GCP custom role definition.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct GcpCustomRole {
    /// GCP role ID.
    pub role_id: String,
    /// Fully-qualified role name.
    pub name: String,
    /// Human-readable title.
    pub title: String,
    /// Role description.
    pub description: String,
    /// Permissions included in the custom role.
    pub included_permissions: Vec<String>,
    /// Role launch stage.
    pub stage: String,
}

/// Scope where a GCP IAM role binding should be applied.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum GcpBindingTargetScope {
    /// Bind the role on the target project.
    Project,
    /// Bind the role on the current resource IAM policy.
    CurrentResource,
}

/// Resource family for current-resource IAM bindings that need provider-specific routing.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum GcpBindingResourceKind {
    /// Pub/Sub topic IAM policy.
    PubsubTopic,
    /// Pub/Sub subscription IAM policy.
    PubsubSubscription,
    /// Artifact Registry repository IAM policy.
    ArtifactRegistryRepository,
}

/// GCP IAM policy binding.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct GcpIamBinding {
    /// Role to bind to members.
    pub role: String,
    /// List of members (users, service accounts, groups).
    pub members: Vec<String>,
    /// IAM policy scope where this role should be bound.
    pub target: GcpBindingTargetScope,
    /// Resource family for current-resource IAM policy routing.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resource_kind: Option<GcpBindingResourceKind>,
    /// Optional condition for conditional IAM.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub condition: Option<GcpIamCondition>,
}

/// GCP IAM bindings wrapper.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct GcpIamBindings {
    /// List of IAM bindings.
    pub bindings: Vec<GcpIamBinding>,
}

/// GCP grant plan generated from a permission set.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct GcpGrantPlan {
    /// Predefined and generated custom-role bindings.
    pub bindings: Vec<GcpIamBinding>,
    /// Residual custom roles that must exist before their bindings are applied.
    pub custom_roles: Vec<GcpCustomRole>,
}

impl GcpGrantPlan {
    /// Return IAM bindings selected for one binding target scope.
    pub fn bindings_for_target(&self, target: GcpBindingTargetScope) -> Vec<GcpIamBinding> {
        self.bindings
            .iter()
            .filter(|binding| binding.target == target)
            .cloned()
            .collect()
    }

    /// Return only the custom roles referenced by `bindings`.
    pub fn custom_roles_for_bindings(&self, bindings: &[GcpIamBinding]) -> Vec<GcpCustomRole> {
        self.custom_roles
            .iter()
            .filter(|custom_role| {
                bindings
                    .iter()
                    .any(|binding| binding.role == custom_role.name)
            })
            .cloned()
            .collect()
    }
}

/// GCP custom-role planner.
pub struct GcpRuntimePermissionsGenerator;

impl GcpRuntimePermissionsGenerator {
    /// Create a new GCP runtime permissions generator.
    pub fn new() -> Self {
        Self
    }

    /// Generate a custom role from a permission set.
    ///
    /// GCP uses project custom roles for exact permission-set semantics. The
    /// role ID is derived from the deployment namespace and permission-set ID,
    /// so different service accounts in the same deployment share one role per
    /// permission-set entry without sharing roles across deployments.
    pub fn generate_custom_role(
        &self,
        permission_set: &PermissionSet,
        context: &PermissionContext,
    ) -> Result<GcpCustomRole> {
        let roles = self.generate_custom_roles(permission_set, context)?;
        if roles.len() == 1 {
            return Ok(roles.into_iter().next().expect("single role"));
        }
        if roles.is_empty() {
            return Err(alien_error::AlienError::new(ErrorData::GeneratorError {
                platform: "gcp".to_string(),
                message: format!(
                    "GCP permission set '{}' has no residual custom role",
                    permission_set.id
                ),
            }));
        }

        Err(alien_error::AlienError::new(ErrorData::GeneratorError {
            platform: "gcp".to_string(),
            message: format!(
                "GCP permission set '{}' generates multiple custom roles; use generate_custom_roles() to preserve binding scopes",
                permission_set.id
            ),
        }))
    }

    /// Generate one custom role per unique GCP permission entry.
    ///
    /// Permission-set JSONC can split GCP permissions into multiple entries
    /// when some permissions must be bound at project scope and others at a
    /// resource scope. Keeping those entries as separate custom roles prevents
    /// project-scoped helper permissions from broadening resource permissions,
    /// and vice versa.
    pub fn generate_custom_roles(
        &self,
        permission_set: &PermissionSet,
        context: &PermissionContext,
    ) -> Result<Vec<GcpCustomRole>> {
        let gcp_platform_permissions = permission_set.platforms.gcp.as_ref().ok_or_else(|| {
            alien_error::AlienError::new(ErrorData::PlatformNotSupported {
                platform: "gcp".to_string(),
                permission_set_id: permission_set.id.clone(),
            })
        })?;

        if gcp_platform_permissions.is_empty() {
            return Err(alien_error::AlienError::new(ErrorData::GeneratorError {
                platform: "gcp".to_string(),
                message: format!(
                    "GCP permission set '{}' has no platform entries",
                    permission_set.id
                ),
            }));
        }

        let mut roles: Vec<GcpCustomRole> = Vec::new();
        let residual_entry_count = gcp_platform_permissions
            .iter()
            .filter(|entry| gcp_residual_permissions(&entry.grant).is_some_and(|p| !p.is_empty()))
            .count();
        let has_multiple_entries = residual_entry_count > 1;
        for (index, platform_permission) in gcp_platform_permissions.iter().enumerate() {
            validate_gcp_grant(permission_set, index, &platform_permission.grant)?;

            let Some(permissions) = gcp_residual_permissions(&platform_permission.grant) else {
                continue;
            };
            if permissions.is_empty() {
                continue;
            }
            let role = self.custom_role_for_permissions(
                permission_set,
                permissions.clone(),
                context,
                role_suffix(
                    &platform_permission.grant,
                    platform_permission.label.as_deref(),
                    has_multiple_entries,
                ),
                platform_permission.label.as_deref(),
                platform_permission.description.as_deref(),
            )?;
            if !roles
                .iter()
                .any(|existing| existing.role_id == role.role_id)
            {
                roles.push(role);
            }
        }

        Ok(roles)
    }

    fn custom_role_for_permissions(
        &self,
        permission_set: &PermissionSet,
        mut included_permissions: Vec<String>,
        context: &PermissionContext,
        suffix: Option<String>,
        explicit_label: Option<&str>,
        entry_description_override: Option<&str>,
    ) -> Result<GcpCustomRole> {
        included_permissions.sort();
        included_permissions.dedup();

        let project = context.project_name.as_deref().unwrap_or("PROJECT_NAME");
        let role_id = generate_role_id(permission_set, context, suffix.as_deref(), explicit_label);
        let role_name = format!("projects/{project}/roles/{role_id}");

        Ok(GcpCustomRole {
            role_id: role_id.clone(),
            name: role_name,
            title: custom_role_title(permission_set, context, suffix.as_deref(), explicit_label),
            description: custom_role_description(
                permission_set,
                context,
                entry_description_override,
            ),
            included_permissions,
            stage: "GA".to_string(),
        })
    }

    /// Generate IAM bindings from a permission set and binding target.
    pub fn generate_bindings(
        &self,
        permission_set: &PermissionSet,
        binding_target: BindingTarget,
        context: &PermissionContext,
    ) -> Result<GcpIamBindings> {
        Ok(GcpIamBindings {
            bindings: self
                .generate_grant_plan(permission_set, binding_target, context)?
                .bindings,
        })
    }

    /// Generate the full GCP grant plan from a permission set and binding target.
    pub fn generate_grant_plan(
        &self,
        permission_set: &PermissionSet,
        binding_target: BindingTarget,
        context: &PermissionContext,
    ) -> Result<GcpGrantPlan> {
        let gcp_platform_permissions = permission_set.platforms.gcp.as_ref().ok_or_else(|| {
            alien_error::AlienError::new(ErrorData::PlatformNotSupported {
                platform: "gcp".to_string(),
                permission_set_id: permission_set.id.clone(),
            })
        })?;

        if gcp_platform_permissions.is_empty() {
            return Err(alien_error::AlienError::new(ErrorData::GeneratorError {
                platform: "gcp".to_string(),
                message: format!(
                    "GCP permission set '{}' has no platform entries",
                    permission_set.id
                ),
            }));
        }

        let project = context.project_name.as_deref().unwrap_or("PROJECT_NAME");
        let service_account = format!(
            "serviceAccount:{}@{}.iam.gserviceaccount.com",
            context
                .service_account_name
                .as_deref()
                .unwrap_or("SERVICE_ACCOUNT"),
            project
        );

        let mut bindings = Vec::new();
        let mut custom_roles = Vec::new();
        let residual_entry_count = gcp_platform_permissions
            .iter()
            .filter(|entry| gcp_residual_permissions(&entry.grant).is_some_and(|p| !p.is_empty()))
            .count();
        let has_multiple_entries = residual_entry_count > 1;
        for (index, platform_permission) in gcp_platform_permissions.iter().enumerate() {
            validate_gcp_grant(permission_set, index, &platform_permission.grant)?;

            let binding_spec = match binding_target {
                BindingTarget::Stack => platform_permission.binding.stack.as_ref(),
                BindingTarget::Resource => platform_permission.binding.resource.as_ref(),
            };

            let Some(binding_spec) = binding_spec else {
                continue;
            };

            let target = binding_target_scope(binding_spec);
            let resource_kind = binding_resource_kind(binding_spec);
            let condition = self.binding_condition(binding_spec, context)?;

            if let Some(predefined_roles) = &platform_permission.grant.predefined_roles {
                for predefined_role in predefined_roles {
                    bindings.push(GcpIamBinding {
                        role: predefined_role.clone(),
                        members: vec![service_account.clone()],
                        target,
                        resource_kind,
                        condition: condition.clone(),
                    });
                }
            }

            let Some(permissions) = gcp_residual_permissions(&platform_permission.grant) else {
                continue;
            };
            if permissions.is_empty() {
                continue;
            }

            let custom_role = self.custom_role_for_permissions(
                permission_set,
                permissions.clone(),
                context,
                role_suffix(
                    &platform_permission.grant,
                    platform_permission.label.as_deref(),
                    has_multiple_entries,
                ),
                platform_permission.label.as_deref(),
                platform_permission.description.as_deref(),
            )?;
            bindings.push(GcpIamBinding {
                role: custom_role.name.clone(),
                members: vec![service_account.clone()],
                target,
                resource_kind,
                condition,
            });
            if !custom_roles
                .iter()
                .any(|existing: &GcpCustomRole| existing.role_id == custom_role.role_id)
            {
                custom_roles.push(custom_role);
            }
        }

        Ok(GcpGrantPlan {
            bindings: dedupe_bindings(bindings),
            custom_roles,
        })
    }

    fn binding_condition(
        &self,
        binding_spec: &GcpBindingSpec,
        context: &PermissionContext,
    ) -> Result<Option<GcpIamCondition>> {
        let Some(gcp_condition) = binding_spec.condition.as_ref() else {
            return Ok(None);
        };

        let interpolated = self.interpolate_condition(gcp_condition, context)?;
        Ok(Some(GcpIamCondition {
            title: interpolated.title.clone(),
            description: format!("Limit to {}", interpolated.title),
            expression: interpolated.expression,
        }))
    }

    /// Interpolate variables in a GCP condition.
    fn interpolate_condition(
        &self,
        condition: &alien_core::GcpCondition,
        context: &PermissionContext,
    ) -> Result<alien_core::GcpCondition> {
        let interpolated_title =
            VariableInterpolator::interpolate_variables(&condition.title, context)?;
        let interpolated_expression =
            VariableInterpolator::interpolate_variables(&condition.expression, context)?;

        Ok(alien_core::GcpCondition {
            title: interpolated_title,
            expression: interpolated_expression,
        })
    }
}

fn gcp_residual_permissions(grant: &PermissionGrant) -> Option<&Vec<String>> {
    grant
        .residual_permissions
        .as_ref()
        .or(grant.permissions.as_ref())
}

fn validate_gcp_grant(
    permission_set: &PermissionSet,
    index: usize,
    grant: &PermissionGrant,
) -> Result<()> {
    if let Some(predefined_roles) = &grant.predefined_roles {
        if predefined_roles.is_empty() {
            return Err(alien_error::AlienError::new(ErrorData::GeneratorError {
                platform: "gcp".to_string(),
                message: format!(
                    "GCP permission set '{}' entry {} has an empty predefinedRoles list",
                    permission_set.id, index
                ),
            }));
        }
        for role in predefined_roles {
            if !role.starts_with("roles/") {
                return Err(alien_error::AlienError::new(ErrorData::GeneratorError {
                    platform: "gcp".to_string(),
                    message: format!(
                        "GCP permission set '{}' entry {} has invalid predefined role '{}'",
                        permission_set.id, index, role
                    ),
                }));
            }
        }
    }

    if let Some(permissions) = gcp_residual_permissions(grant) {
        if permissions.is_empty() {
            return Err(alien_error::AlienError::new(ErrorData::GeneratorError {
                platform: "gcp".to_string(),
                message: format!(
                    "GCP permission set '{}' entry {} has an empty permissions list",
                    permission_set.id, index
                ),
            }));
        }
    }

    if grant.predefined_roles.is_none() && gcp_residual_permissions(grant).is_none() {
        return Err(alien_error::AlienError::new(ErrorData::GeneratorError {
            platform: "gcp".to_string(),
            message: format!(
                "GCP permission set '{}' entry {} has no permissions",
                permission_set.id, index
            ),
        }));
    }

    Ok(())
}

fn generate_role_id(
    permission_set: &PermissionSet,
    context: &PermissionContext,
    suffix: Option<&str>,
    explicit_label: Option<&str>,
) -> String {
    let namespace = custom_role_namespace(context);
    if has_explicit_label(explicit_label) {
        let suffix = suffix.unwrap_or("custom");
        let prefix = format!("role_{namespace}_");
        let suffix = fit_role_suffix(suffix, GCP_CUSTOM_ROLE_ID_MAX_LEN - prefix.len());
        return format!("{prefix}{suffix}");
    }

    let permission_set_slug = sanitize_role_segment(&permission_set.id.replace('/', "_"), 28);
    match suffix {
        Some(suffix) => {
            let prefix = format!("role_{namespace}_{permission_set_slug}_");
            let suffix = fit_role_suffix(suffix, GCP_CUSTOM_ROLE_ID_MAX_LEN - prefix.len());
            format!("{prefix}{suffix}")
        }
        None => format!("role_{namespace}_{permission_set_slug}"),
    }
}

/// Return the project custom-role prefix for all roles owned by this stack.
pub fn custom_role_prefix(context: &PermissionContext) -> String {
    format!("role_{}_", custom_role_namespace(context))
}

/// Return the project custom-role prefix for one permission set in this stack.
pub fn custom_role_permission_set_prefix(
    permission_set_id: &str,
    context: &PermissionContext,
) -> String {
    let permission_set_slug = sanitize_role_segment(&permission_set_id.replace('/', "_"), 28);
    format!("{}{permission_set_slug}", custom_role_prefix(context))
}

fn custom_role_namespace(context: &PermissionContext) -> String {
    sanitize_role_segment(context.stack_prefix.as_deref().unwrap_or("stack"), 18)
}

fn custom_role_title(
    permission_set: &PermissionSet,
    context: &PermissionContext,
    suffix: Option<&str>,
    explicit_label: Option<&str>,
) -> String {
    let deployment_name = context.deployment_name.as_deref();
    if has_explicit_label(explicit_label) {
        let title = entry_title_label(explicit_label, &PermissionGrant::default());
        return role_title(deployment_name, &title);
    }

    let label = permission_set_display_label(&permission_set.id);
    let title = match suffix {
        Some(suffix) => format!(
            "{label} - {}",
            entry_title_label(Some(suffix), &PermissionGrant::default())
        ),
        None => label,
    };
    role_title(deployment_name, &title)
}

fn custom_role_description(
    permission_set: &PermissionSet,
    context: &PermissionContext,
    entry_description_override: Option<&str>,
) -> String {
    let stack_prefix = context.stack_prefix.as_deref().unwrap_or("unknown");
    let description = entry_description(entry_description_override, &permission_set.description);
    let description = description.trim_end_matches('.');
    match context.deployment_name.as_deref() {
        Some(deployment_name) if !deployment_name.trim().is_empty() => {
            format!("Used by {deployment_name}. {description}. Resource prefix: {stack_prefix}.")
        }
        _ => format!("{description}. Resource prefix: {stack_prefix}."),
    }
}

fn role_title(deployment_name: Option<&str>, title: &str) -> String {
    match deployment_name {
        Some(deployment_name) if !deployment_name.trim().is_empty() => {
            format!("{deployment_name}: {title}")
        }
        _ => title.to_string(),
    }
}

fn permission_set_display_label(permission_set_id: &str) -> String {
    let mut words = Vec::new();
    let mut current = String::new();

    for ch in permission_set_id.chars() {
        if ch.is_ascii_alphanumeric() {
            current.push(ch.to_ascii_lowercase());
        } else if !current.is_empty() {
            words.push(std::mem::take(&mut current));
        }
    }
    if !current.is_empty() {
        words.push(current);
    }

    let mut label = words.join(" ");
    if let Some(first) = label.get_mut(0..1) {
        first.make_ascii_uppercase();
    }
    label
}

fn role_suffix(
    grant: &PermissionGrant,
    explicit_label: Option<&str>,
    has_multiple_entries: bool,
) -> Option<String> {
    let explicit = has_explicit_label(explicit_label);
    if explicit || has_multiple_entries {
        let max_len = if explicit { 40 } else { 28 };
        let mut label = entry_snake_label(explicit_label, grant);
        if !explicit {
            label.push('_');
            label.push_str(&grant_suffix_hash(grant));
        }
        Some(sanitize_role_segment(&label, max_len))
    } else {
        None
    }
}

fn grant_suffix_hash(grant: &PermissionGrant) -> String {
    let mut values = Vec::new();
    if let Some(predefined_roles) = &grant.predefined_roles {
        values.extend(predefined_roles.iter().map(|role| format!("role:{role}")));
    }
    if let Some(permissions) = gcp_residual_permissions(grant) {
        values.extend(
            permissions
                .iter()
                .map(|permission| format!("permission:{permission}")),
        );
    }
    values.sort();
    stable_role_hash(&values.join("|"))
}

fn sanitize_role_segment(value: &str, max_len: usize) -> String {
    let mut out = String::with_capacity(value.len());
    let mut previous_underscore = false;
    for ch in value.chars() {
        let next = if ch.is_ascii_alphanumeric() {
            ch.to_ascii_lowercase()
        } else {
            '_'
        };
        if next == '_' {
            if !previous_underscore {
                out.push(next);
            }
            previous_underscore = true;
        } else {
            out.push(next);
            previous_underscore = false;
        }
    }

    let trimmed = out.trim_matches('_');
    let mut segment = if trimmed.is_empty() {
        "x".to_string()
    } else {
        trimmed.to_string()
    };
    if segment.len() > max_len {
        segment.truncate(max_len);
        while segment.ends_with('_') {
            segment.pop();
        }
    }
    if segment.is_empty() {
        "x".to_string()
    } else {
        segment
    }
}

fn fit_role_suffix(value: &str, max_len: usize) -> String {
    if value.len() <= max_len {
        return value.to_string();
    }

    let hash = stable_role_hash(value);
    if max_len <= ROLE_ID_HASH_LEN {
        return hash[..max_len].to_string();
    }

    let prefix_len = max_len - ROLE_ID_HASH_LEN - 1;
    let mut prefix = value.to_string();
    prefix.truncate(prefix_len);
    while prefix.ends_with('_') {
        prefix.pop();
    }

    if prefix.is_empty() {
        hash[..max_len].to_string()
    } else {
        format!("{prefix}_{hash}")
    }
}

fn stable_role_hash(value: &str) -> String {
    let mut hash = 0x811c9dc5_u32;
    for byte in value.bytes() {
        hash ^= u32::from(byte);
        hash = hash.wrapping_mul(0x01000193);
    }
    format!("{hash:08x}")
}

fn binding_target_scope(binding_spec: &GcpBindingSpec) -> GcpBindingTargetScope {
    let scope = binding_spec.scope.trim();
    match scope.strip_prefix("projects/") {
        Some(project_scope) if !project_scope.contains('/') => GcpBindingTargetScope::Project,
        _ => GcpBindingTargetScope::CurrentResource,
    }
}

fn binding_resource_kind(binding_spec: &GcpBindingSpec) -> Option<GcpBindingResourceKind> {
    let scope = binding_spec.scope.trim();
    if scope.contains("/topics/") {
        return Some(GcpBindingResourceKind::PubsubTopic);
    }
    if scope.contains("/subscriptions/") {
        return Some(GcpBindingResourceKind::PubsubSubscription);
    }
    if scope.contains("/repositories/") {
        return Some(GcpBindingResourceKind::ArtifactRegistryRepository);
    }
    None
}

fn dedupe_bindings(bindings: Vec<GcpIamBinding>) -> Vec<GcpIamBinding> {
    let mut deduped = Vec::new();
    for binding in bindings {
        if !deduped.contains(&binding) {
            deduped.push(binding);
        }
    }
    deduped
}