alien-bindings 3.3.27

Alien direct in-process resource bindings
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
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
use crate::{
    error::{binding_env_var, map_cloud_client_error, ErrorData, Result},
    traits::{
        ArtifactRegistry, ArtifactRegistryCredentials, ArtifactRegistryPermissions, Binding,
        ComputeServiceType, CrossAccountAccess, CrossAccountPermissions, GcpCrossAccountAccess,
        RegistryAuthMethod, RepositoryResponse,
    },
};
use alien_core::bindings::ArtifactRegistryBinding;
use alien_error::{AlienError, Context};
use alien_gcp_clients::iam::IamPolicy;
use alien_gcp_clients::{
    artifactregistry::{ArtifactRegistryApi, ArtifactRegistryClient},
    GcpClientConfig, GcpClientConfigExt as _,
};
use async_trait::async_trait;
use chrono;
use tracing::{debug, info, warn};

/// The Google-managed service agent a compute service pulls as.
///
/// Google's default grant covers a same-project pull; naming this agent is what reaches a
/// repository in another project. Three adjacent Vertex agents exist, so naming the wrong one 403s.
fn agent_domain(service_type: &ComputeServiceType) -> &'static str {
    match service_type {
        ComputeServiceType::Worker => "serverless-robot-prod",
        ComputeServiceType::Sandbox => "gcp-sa-vertex-sandbox",
    }
}

/// Whether Google creates this service agent only once the service first runs, so a binding
/// naming it is refused until then and its member has to go on in a write of its own.
fn is_agent_created_on_first_use(service_type: &ComputeServiceType) -> bool {
    match service_type {
        ComputeServiceType::Sandbox => true,
        ComputeServiceType::Worker => false,
    }
}

/// The service type and project a member names, if the write path emitted it.
///
/// Reads through the same table the write used, so a sandbox agent doesn't decode as an ordinary
/// service account and report no grant while its member still sits on the policy.
fn agent_member(service_account: &str) -> Option<(ComputeServiceType, &str)> {
    ComputeServiceType::ALL.iter().find_map(|service_type| {
        let suffix = format!("@{}.iam.gserviceaccount.com", agent_domain(service_type));
        service_account
            .strip_prefix("service-")
            .and_then(|rest| rest.strip_suffix(&suffix))
            .map(|project_number| (service_type.clone(), project_number))
    })
}

/// The IAM members a cross-account grant names, for both the add and the remove path.
///
/// Each compute service pulls as its own service agent, so the project number alone doesn't say
/// who may pull; grant and revoke share this list so a member the revoke misses doesn't strand.
fn cross_account_members(access: &GcpCrossAccountAccess) -> Vec<String> {
    let mut members = Vec::new();
    for service_type in &access.allowed_service_types {
        let agent_domain = agent_domain(service_type);
        for project_number in &access.project_numbers {
            members.push(format!(
                "serviceAccount:service-{project_number}@{agent_domain}.iam.gserviceaccount.com"
            ));
        }
    }
    for service_account_email in &access.service_account_emails {
        members.push(format!("serviceAccount:{service_account_email}"));
    }
    members
}

/// GCP Artifact Registry implementation of the ArtifactRegistry binding.
#[derive(Debug)]
pub struct GarArtifactRegistry {
    client: ArtifactRegistryClient,
    binding_name: String,
    project_id: String,
    location: String,
    repository_name: String,
    pull_service_account_email: Option<String>,
    push_service_account_email: Option<String>,
    gcp_config: GcpClientConfig,
}

impl GarArtifactRegistry {
    /// Creates a new GCP Artifact Registry binding from binding parameters.
    pub async fn new(
        binding_name: String,
        binding: ArtifactRegistryBinding,
        gcp_config: &GcpClientConfig,
    ) -> Result<Self> {
        info!(
            binding_name = %binding_name,
            "Initializing GCP Artifact Registry"
        );

        let client = crate::http_client::create_http_client();
        let artifact_registry_client = ArtifactRegistryClient::new(client, gcp_config.clone());

        // Get project_id and location from GCP config instead of binding
        let project_id = gcp_config.project_id.clone();
        let location = gcp_config.region.clone();

        // Extract service account emails from binding
        let config = match binding {
            ArtifactRegistryBinding::Gar(config) => config,
            _ => {
                return Err(AlienError::new(ErrorData::BindingConfigInvalid {
                    env_var: binding_env_var(&binding_name),
                    binding_name: binding_name.clone(),
                    reason: "Expected GAR binding, got different service type".to_string(),
                }));
            }
        };

        let repository_name = config
            .repository_name
            .into_value(&binding_name, "repository_name")
            .context(ErrorData::BindingConfigInvalid {
                env_var: binding_env_var(&binding_name),
                binding_name: binding_name.clone(),
                reason: "Failed to extract repository_name from binding".to_string(),
            })?;

        let pull_service_account_email = config
            .pull_service_account_email
            .map(|v| {
                v.into_value(&binding_name, "pull_service_account_email")
                    .context(ErrorData::BindingConfigInvalid {
                        env_var: binding_env_var(&binding_name),
                        binding_name: binding_name.clone(),
                        reason: "Failed to extract pull_service_account_email from binding"
                            .to_string(),
                    })
            })
            .transpose()?;

        let push_service_account_email = config
            .push_service_account_email
            .map(|v| {
                v.into_value(&binding_name, "push_service_account_email")
                    .context(ErrorData::BindingConfigInvalid {
                        env_var: binding_env_var(&binding_name),
                        binding_name: binding_name.clone(),
                        reason: "Failed to extract push_service_account_email from binding"
                            .to_string(),
                    })
            })
            .transpose()?;

        Ok(Self {
            client: artifact_registry_client,
            binding_name,
            project_id,
            location,
            repository_name,
            pull_service_account_email,
            push_service_account_email,
            gcp_config: gcp_config.clone(),
        })
    }

    /// Extracts a name segment from a repo ID or routable name.
    /// If `repo_id` is empty, returns the binding's configured `repository_name`
    /// (the GAR repository resource, used for IAM operations).
    fn extract_repo_name(&self, repo_id: &str) -> Result<String> {
        if repo_id.is_empty() {
            return Ok(self.repository_name.clone());
        }
        if let Some(name) = repo_id.split('/').last() {
            Ok(name.to_string())
        } else {
            Err(AlienError::new(ErrorData::BindingConfigInvalid {
                env_var: binding_env_var(&self.binding_name),
                binding_name: self.binding_name.clone(),
                reason: format!("Invalid repository ID format: {}", repo_id),
            }))
        }
    }

    /// Internal helper to add or remove members from IAM policy bindings
    async fn update_policy_members(
        &self,
        repo_name: &str,
        mut current_policy: IamPolicy,
        members: Vec<String>,
        add_members: bool, // true to add, false to remove
    ) -> Result<IamPolicy> {
        let reader_role = "roles/artifactregistry.reader";

        // Find or create the artifactregistry.reader binding
        let mut binding_index = None;
        for (i, binding) in current_policy.bindings.iter().enumerate() {
            if binding.role == reader_role {
                binding_index = Some(i);
                break;
            }
        }

        if add_members {
            // Add members
            if members.is_empty() {
                info!(repo_name = %repo_name, "No new members to add");
                return Ok(current_policy);
            }

            match binding_index {
                Some(i) => {
                    // Add to existing binding
                    let binding = &mut current_policy.bindings[i];
                    for member in members {
                        if !binding.members.contains(&member) {
                            binding.members.push(member);
                        }
                    }
                }
                None => {
                    // Create new binding
                    current_policy
                        .bindings
                        .push(alien_gcp_clients::iam::Binding {
                            role: reader_role.to_string(),
                            members,
                            condition: None,
                        });
                }
            }
        } else {
            // Remove members
            if let Some(i) = binding_index {
                let binding = &mut current_policy.bindings[i];
                binding.members.retain(|member| !members.contains(member));

                // Remove empty binding
                if binding.members.is_empty() {
                    current_policy.bindings.remove(i);
                }
            }
            // If no binding exists, nothing to remove
        }

        // Set the updated policy with the original etag for optimistic concurrency control
        let updated = self.client.set_repository_iam_policy(
            self.project_id.clone(),
            self.location.clone(),
            repo_name.to_string(),
            current_policy,
        ).await
            .map_err(|e| map_cloud_client_error(
                e,
                format!("Failed to update cross-account access for GCP Artifact Registry repository '{}'", repo_name),
                Some(repo_name.to_string()),
            ))?;

        let action = if add_members { "added" } else { "removed" };
        info!(
            repo_name = %repo_name,
            action = %action,
            "GCP Artifact Registry repository cross-account access updated successfully"
        );
        Ok(updated)
    }
}

impl Binding for GarArtifactRegistry {}

#[async_trait]
impl ArtifactRegistry for GarArtifactRegistry {
    fn registry_endpoint(&self) -> String {
        format!("https://{}-docker.pkg.dev", self.location)
    }

    fn upstream_repository_prefix(&self) -> String {
        format!("{}/{}", self.project_id, self.repository_name)
    }

    async fn create_repository(&self, repo_name: &str) -> Result<RepositoryResponse> {
        // In GAR, the binding's GAR repository (e.g., "alien-artifacts") IS the registry.
        // Image paths within it (e.g., "prj_abc123") are created automatically on first push.
        // No GAR API call needed — the GAR repository is created by alien-infra at provisioning time.
        // Underscores are valid in image paths (OCI distribution spec allows [a-z0-9._-/]).
        let routable_name = format!("{}/{}", self.upstream_repository_prefix(), repo_name);
        Ok(RepositoryResponse {
            name: routable_name,
            uri: None,
            created_at: None,
        })
    }

    async fn get_repository(&self, repo_id: &str) -> Result<RepositoryResponse> {
        // Image paths within a GAR repository are implicit — no GAR API call needed.
        // Just return the routable name, same as create_repository.
        let image_path = self.extract_repo_name(repo_id)?;
        let routable_name = format!("{}/{}", self.upstream_repository_prefix(), image_path);
        let repository_uri = format!(
            "{}-docker.pkg.dev/{}/{}",
            self.location, self.project_id, image_path
        );

        Ok(RepositoryResponse {
            name: routable_name,
            uri: Some(repository_uri),
            created_at: None,
        })
    }

    async fn add_cross_account_access(
        &self,
        repo_id: &str,
        access: CrossAccountAccess,
    ) -> Result<()> {
        // Cross-account access in GAR is enforced via IAM bindings on the
        // *parent* repository (the GAR resource provisioned by alien-infra),
        // not on individual image paths. `repo_id` may name an image path
        // within the parent (it's the routable name from `create_repository`),
        // but IAM ops always target the parent registry.
        let _ = repo_id; // The image path doesn't have its own IAM scope.
        let repo_name = self.repository_name.clone();

        let gcp_access = match access {
            CrossAccountAccess::Gcp(gcp_access) => gcp_access,
            _ => {
                return Err(AlienError::new(ErrorData::BindingConfigInvalid {
                    env_var: binding_env_var(&self.binding_name),
                    binding_name: self.binding_name.clone(),
                    reason: "GCP artifact registry can only accept GCP cross-account access configuration".to_string(),
                }));
            }
        };

        info!(
            repo_name = %repo_name,
            project_numbers = ?gcp_access.project_numbers,
            allowed_service_types = ?gcp_access.allowed_service_types,
            service_account_emails = ?gcp_access.service_account_emails,
            "Adding GCP Artifact Registry repository cross-account access"
        );

        // Only a repository that is gone has no policy. Any other failure read as an empty one
        // writes back a policy holding this deployment's members alone, with no etag to lose the
        // race on — dropping every other binding on a repository all deployments share.
        let current_policy = match self
            .client
            .get_repository_iam_policy(
                self.project_id.clone(),
                self.location.clone(),
                repo_name.clone(),
            )
            .await
        {
            Ok(policy) => policy,
            Err(error) if error.http_status_code == Some(404) => IamPolicy {
                version: Some(1),
                kind: None,
                resource_id: None,
                bindings: vec![],
                etag: None,
            },
            Err(error) => {
                return Err(map_cloud_client_error(
                    error,
                    format!(
                        "Failed to read the IAM policy of GCP Artifact Registry repository '{repo_name}' to grant access"
                    ),
                    Some(repo_name.to_string()),
                ))
            }
        };

        // Two writes, not one: a sandbox agent that has never run doesn't exist yet, and Google
        // refuses a binding naming an unresolvable principal. One update naming both would lose
        // the worker grant to the sandbox agent's absence; splitting keeps a refusal there off it.
        let (deferred, present): (Vec<ComputeServiceType>, Vec<ComputeServiceType>) = gcp_access
            .allowed_service_types
            .iter()
            .cloned()
            .partition(is_agent_created_on_first_use);

        let policy = self
            .update_policy_members(
                &repo_name,
                current_policy,
                cross_account_members(&GcpCrossAccountAccess {
                    allowed_service_types: present,
                    ..gcp_access.clone()
                }),
                true,
            )
            .await?;

        if deferred.is_empty() {
            return Ok(());
        }
        // The second write is only safe behind the etag the first one returned. Without it the
        // write carries no concurrency check and replaces a policy every deployment shares, so the
        // reconcile retries instead.
        if policy.etag.is_none() {
            return Err(AlienError::new(ErrorData::RemoteResourceConflict {
                operation_context: "adding cross-account access".to_string(),
                resource_type: "repository".to_string(),
                resource_name: repo_name.clone(),
                conflict_reason:
                    "the updated IAM policy carries no etag, so the sandbox agent's member cannot be added without replacing the policy"
                        .to_string(),
            }));
        }
        self.update_policy_members(
            &repo_name,
            policy,
            cross_account_members(&GcpCrossAccountAccess {
                allowed_service_types: deferred,
                service_account_emails: Vec::new(),
                ..gcp_access
            }),
            true,
        )
        .await?;
        Ok(())
    }

    async fn remove_cross_account_access(
        &self,
        repo_id: &str,
        access: CrossAccountAccess,
    ) -> Result<()> {
        // IAM ops target the parent registry. See `add_cross_account_access`.
        let _ = repo_id;
        let repo_name = self.repository_name.clone();

        let gcp_access = match access {
            CrossAccountAccess::Gcp(gcp_access) => gcp_access,
            _ => {
                return Err(AlienError::new(ErrorData::BindingConfigInvalid {
                    env_var: binding_env_var(&self.binding_name),
                    binding_name: self.binding_name.clone(),
                    reason: "GCP artifact registry can only accept GCP cross-account access configuration".to_string(),
                }));
            }
        };

        info!(
            repo_name = %repo_name,
            project_numbers = ?gcp_access.project_numbers,
            allowed_service_types = ?gcp_access.allowed_service_types,
            service_account_emails = ?gcp_access.service_account_emails,
            "Removing GCP Artifact Registry repository cross-account access"
        );

        // Get current policy with etag
        let current_policy = match self
            .client
            .get_repository_iam_policy(
                self.project_id.clone(),
                self.location.clone(),
                repo_name.clone(),
            )
            .await
        {
            Ok(policy) => policy,
            // Only a repository that is gone carries no members. Reading a 403 or a timeout as
            // "nothing to remove" reports the revoke as done and strands every member on it, with
            // the state that named them deleted right after.
            Err(error) if error.http_status_code == Some(404) => {
                info!(repo_name = %repo_name, "No existing GCP IAM policy to remove permissions from");
                return Ok(());
            }
            Err(error) => {
                return Err(map_cloud_client_error(
                    error,
                    format!(
                        "Failed to read the IAM policy of GCP Artifact Registry repository '{repo_name}' to revoke access"
                    ),
                    Some(repo_name.to_string()),
                ))
            }
        };

        let members_to_remove = cross_account_members(&gcp_access);
        self.update_policy_members(&repo_name, current_policy, members_to_remove, false)
            .await?;
        Ok(())
    }

    async fn get_cross_account_access(&self, repo_id: &str) -> Result<CrossAccountPermissions> {
        // IAM ops target the parent registry. See `add_cross_account_access`.
        let _ = repo_id;
        let repo_name = self.repository_name.clone();

        info!(
            repo_name = %repo_name,
            "Getting GCP Artifact Registry repository cross-account access"
        );

        let policy = match self
            .client
            .get_repository_iam_policy(
                self.project_id.clone(),
                self.location.clone(),
                repo_name.clone(),
            )
            .await
        {
            Ok(policy) => policy,
            Err(e) => {
                warn!(
                    repo_name = %repo_name,
                    error = %e,
                    "Failed to get GCP Artifact Registry repository IAM policy"
                );
                // If no policy exists, return empty permissions
                return Ok(CrossAccountPermissions {
                    access: CrossAccountAccess::Gcp(GcpCrossAccountAccess {
                        project_numbers: Vec::new(),
                        allowed_service_types: Vec::new(),
                        service_account_emails: Vec::new(),
                    }),
                    last_updated: None,
                });
            }
        };

        let mut project_numbers = Vec::new();
        let mut service_account_emails = Vec::new();
        let mut allowed_service_types = Vec::new();

        for binding in policy.bindings {
            // Look for reader roles or artifact registry roles
            if binding.role.contains("reader") || binding.role.contains("artifactregistry") {
                for member in binding.members {
                    // Parse service account members only
                    if let Some(service_account) = member.strip_prefix("serviceAccount:") {
                        match agent_member(service_account) {
                            Some((service_type, project_number)) => {
                                project_numbers.push(project_number.to_string());
                                if !allowed_service_types.contains(&service_type) {
                                    allowed_service_types.push(service_type);
                                }
                            }
                            None => service_account_emails.push(service_account.to_string()),
                        }
                    }
                }
            }
        }

        // Remove duplicates and sort
        project_numbers.sort();
        project_numbers.dedup();
        service_account_emails.sort();
        service_account_emails.dedup();
        allowed_service_types.sort_by_key(|rt| format!("{:?}", rt));
        allowed_service_types.dedup();

        info!(
            repo_name = %repo_name,
            project_numbers = ?project_numbers,
            allowed_service_types = ?allowed_service_types,
            service_account_emails = ?service_account_emails,
            "Retrieved GCP Artifact Registry repository cross-account access"
        );

        Ok(CrossAccountPermissions {
            access: CrossAccountAccess::Gcp(GcpCrossAccountAccess {
                project_numbers,
                allowed_service_types,
                service_account_emails,
            }),
            last_updated: None, // GCP IAM doesn't provide policy modification time
        })
    }

    async fn generate_credentials(
        &self,
        repo_id: &str,
        permissions: ArtifactRegistryPermissions,
        ttl_seconds: Option<u32>,
    ) -> Result<ArtifactRegistryCredentials> {
        info!(
            repo_id = %repo_id,
            permissions = ?permissions,
            ttl_seconds = ?ttl_seconds,
            "Generating GCP Artifact Registry credentials by impersonating service account"
        );

        // Parse repo_id to extract project and location info if it's in full format
        // Just use the configured project/location from this client since they come from the binding
        let _project_id = &self.project_id;
        let _location = &self.location;

        // Get the service account email from stored fields
        let service_account_email = match permissions {
            ArtifactRegistryPermissions::Pull => {
                self.pull_service_account_email.clone()
                    .ok_or_else(|| AlienError::new(ErrorData::BindingConfigInvalid {
                        env_var: binding_env_var(&self.binding_name),
                        binding_name: self.binding_name.clone(),
                        reason: "Pull service account email not available - ensure the artifact registry resource is properly linked".to_string(),
                    }))?
            }
            ArtifactRegistryPermissions::PushPull => {
                self.push_service_account_email.clone()
                    .ok_or_else(|| AlienError::new(ErrorData::BindingConfigInvalid {
                        env_var: binding_env_var(&self.binding_name),
                        binding_name: self.binding_name.clone(),
                        reason: "Push service account email not available - ensure the artifact registry resource is properly linked".to_string(),
                    }))?
            }
        };

        info!(
            service_account_email = %service_account_email,
            "Using stored service account email for GCP Artifact Registry access"
        );

        // Use the stored GCP configuration for impersonation
        let gcp_config = &self.gcp_config;

        let scopes = vec![
            "https://www.googleapis.com/auth/cloud-platform".to_string(),
            "https://www.googleapis.com/auth/devstorage.read_write".to_string(),
        ];

        let lifetime = ttl_seconds.map(|ttl| format!("{}s", ttl.min(3600))); // Max 1 hour

        let impersonation_config = alien_gcp_clients::GcpImpersonationConfig {
            service_account_email: service_account_email.clone(),
            scopes,
            delegates: None,
            lifetime,
            target_project_id: None,
            target_region: None,
        };

        // Impersonate the service account
        let impersonated_config =
            gcp_config
                .impersonate(impersonation_config)
                .await
                .map_err(|e| {
                    map_cloud_client_error(
                        e,
                        "Failed to impersonate GCP service account for artifact registry access"
                            .to_string(),
                        Some(repo_id.to_string()),
                    )
                })?;

        // Get the access token from the impersonated config
        let access_token = impersonated_config
            .get_bearer_token("https://www.googleapis.com/")
            .await
            .map_err(|e| {
                map_cloud_client_error(
                    e,
                    "Failed to get OAuth token from impersonated service account".to_string(),
                    Some(repo_id.to_string()),
                )
            })?;

        // Calculate expiration time
        let expires_at = if let Some(ttl) = ttl_seconds {
            Some(
                (chrono::Utc::now() + chrono::Duration::seconds(ttl.min(3600) as i64)).to_rfc3339(),
            )
        } else {
            Some((chrono::Utc::now() + chrono::Duration::seconds(3600)).to_rfc3339())
            // Default 1 hour
        };

        info!(
            permissions = ?permissions,
            service_account = %service_account_email,
            "GCP Artifact Registry OAuth token generated successfully with impersonated service account"
        );

        // For GCP Artifact Registry, the username is 'oauth2accesstoken' and password is the OAuth token
        Ok(ArtifactRegistryCredentials {
            auth_method: RegistryAuthMethod::Basic,
            username: "oauth2accesstoken".to_string(),
            password: access_token,
            expires_at,
        })
    }

    async fn delete_repository(&self, repo_id: &str) -> Result<()> {
        // No-op, mirroring `create_repository`/`get_repository`.
        //
        // In GAR, image paths within the parent repository are implicit —
        // they materialise on first push, and there's no "delete a path"
        // operation in the GAR API. The parent repository itself is owned
        // by `alien-infra` (provisioned at deployment time), not by the
        // binding; deleting it would tear down the whole registry every
        // user shares.
        //
        // Garbage collection of unused image data is a separate concern,
        // achievable via `deletePackage` if/when needed. Not done here
        // because the test pattern `create → ... → delete` should be
        // idempotent and side-effect-free at the registry-resource level.
        debug!(
            repo_id = %repo_id,
            "GCP Artifact Registry delete_repository: no-op (image paths are implicit)"
        );
        Ok(())
    }
}

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

    /// Pins the member spelling, not the agent domains themselves: both sides of this assertion
    /// come from the same constants, so a wrong domain fails against GCP rather than here. What it
    /// does catch is a member built for the wrong project, in the wrong order, or silently dropped.
    #[test]
    fn each_service_type_resolves_to_its_own_service_agent() {
        let members = cross_account_members(&GcpCrossAccountAccess {
            project_numbers: vec!["123456789012".to_string()],
            allowed_service_types: vec![ComputeServiceType::Worker, ComputeServiceType::Sandbox],
            service_account_emails: vec![
                "management@test-project.iam.gserviceaccount.com".to_string()
            ],
        });

        assert_eq!(
            members,
            vec![
                "serviceAccount:service-123456789012@serverless-robot-prod.iam.gserviceaccount.com",
                "serviceAccount:service-123456789012@gcp-sa-vertex-sandbox.iam.gserviceaccount.com",
                "serviceAccount:management@test-project.iam.gserviceaccount.com",
            ]
        );
    }

    /// Granting and revoking read one list, so every service type survives a write then a read.
    /// The read path reports what the write path emitted. Without this a sandbox member decodes as
    /// an ordinary service account, so a caller reading current permissions is told the sandbox has
    /// no grant while its member sits on the policy.
    #[test]
    fn every_service_type_survives_a_write_then_read() {
        for service_type in [ComputeServiceType::Worker, ComputeServiceType::Sandbox] {
            let written = cross_account_members(&GcpCrossAccountAccess {
                project_numbers: vec!["123456789012".to_string()],
                allowed_service_types: vec![service_type.clone()],
                service_account_emails: Vec::new(),
            });
            let member = written
                .first()
                .expect("a project and a type name one member");
            let account = member
                .strip_prefix("serviceAccount:")
                .expect("members carry the IAM principal prefix");
            // Through the parser the read path uses, so dropping a type there fails this.
            assert_eq!(
                agent_member(account),
                Some((service_type.clone(), "123456789012")),
                "{service_type:?} must decode back to the project that earned it"
            );
        }
    }

    /// The sandbox agent does not exist until a project's first session, and Google refuses a
    /// binding naming a principal it cannot resolve. The two writes keep that refusal off the
    /// worker's grant, so the member sets must not overlap.
    #[test]
    fn the_worker_and_sandbox_members_are_written_apart() {
        let access = GcpCrossAccountAccess {
            project_numbers: vec!["123456789012".to_string()],
            allowed_service_types: vec![ComputeServiceType::Worker, ComputeServiceType::Sandbox],
            service_account_emails: vec![
                "management@test-project.iam.gserviceaccount.com".to_string()
            ],
        };
        let first = cross_account_members(&GcpCrossAccountAccess {
            allowed_service_types: vec![ComputeServiceType::Worker],
            ..access.clone()
        });
        let second = cross_account_members(&GcpCrossAccountAccess {
            allowed_service_types: vec![ComputeServiceType::Sandbox],
            service_account_emails: Vec::new(),
            ..access.clone()
        });

        assert!(second
            .iter()
            .all(|member| member.contains("gcp-sa-vertex-sandbox")));
        assert!(first
            .iter()
            .all(|member| !member.contains("gcp-sa-vertex-sandbox")));
        // Together they are the whole grant, so splitting the write loses no member.
        let mut both = [first, second].concat();
        both.sort();
        let mut whole = cross_account_members(&access);
        whole.sort();
        assert_eq!(both, whole);
    }

    /// A service type that names no project contributes no member to either list.
    #[test]
    fn a_service_type_grants_nothing_for_a_project_it_does_not_name() {
        // The service account is what separates this from the whole function returning nothing:
        // with it empty too, deleting the per-type loop would leave the assertion passing.
        let members = cross_account_members(&GcpCrossAccountAccess {
            project_numbers: Vec::new(),
            allowed_service_types: vec![ComputeServiceType::Sandbox],
            service_account_emails: vec![
                "management@test-project.iam.gserviceaccount.com".to_string()
            ],
        });

        assert_eq!(
            members,
            vec!["serviceAccount:management@test-project.iam.gserviceaccount.com"]
        );
    }
}