alien-bindings 1.13.2

Alien platform runtime bindings
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
use crate::{
    error::{map_cloud_client_error, ErrorData, Result},
    traits::{
        ArtifactRegistry, ArtifactRegistryCredentials, ArtifactRegistryPermissions, Binding,
        CrossAccountAccess, CrossAccountPermissions, RegistryAuthMethod, RepositoryResponse,
    },
};
use alien_azure_clients::{AzureClientConfig, AzureTokenCache};
use alien_core::bindings::ArtifactRegistryBinding;
use alien_error::{AlienError, Context, IntoAlienError};
use async_trait::async_trait;
use tracing::info;

/// Azure Container Registry implementation of the ArtifactRegistry binding.
#[derive(Debug)]
pub struct AcrArtifactRegistry {
    registry_name: String,
    registry_endpoint: String,
    repository_prefix: String,
    /// Azure credentials for direct registry access (AAD token exchange).
    azure_token_cache: AzureTokenCache,
    http_client: reqwest::Client,
}

impl AcrArtifactRegistry {
    /// Creates a new Azure Container Registry artifact registry binding from binding parameters.
    ///
    /// # Arguments
    /// * `binding_name` - The name of this binding
    /// * `binding` - The parsed binding parameters
    pub async fn new(
        binding_name: String,
        binding: ArtifactRegistryBinding,
        azure_config: &AzureClientConfig,
    ) -> Result<Self> {
        info!(
            binding_name = %binding_name,
            "Initializing Azure Container Registry"
        );

        // Extract values from binding
        let config = match binding {
            ArtifactRegistryBinding::Acr(config) => config,
            _ => {
                return Err(AlienError::new(ErrorData::BindingConfigInvalid {
                    binding_name: binding_name.clone(),
                    reason: "Expected ACR binding, got different service type".to_string(),
                }));
            }
        };

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

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

        // Derive registry endpoint from registry name
        let registry_endpoint = format!("{}.azurecr.io", registry_name);
        let client = crate::http_client::create_http_client();
        let azure_token_cache = AzureTokenCache::new(azure_config.clone());

        let repository_prefix = match config.repository_prefix {
            Some(bv) => bv.into_value(&binding_name, "repository_prefix").context(
                ErrorData::BindingConfigInvalid {
                    binding_name: binding_name.clone(),
                    reason: "Failed to extract repository_prefix from binding".to_string(),
                },
            )?,
            None => String::new(),
        };

        Ok(Self {
            registry_name,
            registry_endpoint,
            repository_prefix,
            azure_token_cache,
            http_client: client,
        })
    }

    fn routable_repository_name(&self, repo_name: &str) -> String {
        if self.repository_prefix.is_empty() {
            repo_name.to_string()
        } else {
            format!("{}/{}", self.repository_prefix, repo_name)
        }
    }
}

impl Binding for AcrArtifactRegistry {}

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

    fn upstream_repository_prefix(&self) -> String {
        self.repository_prefix.clone()
    }

    async fn create_repository(&self, repo_name: &str) -> Result<RepositoryResponse> {
        // ACR repositories are created implicitly on first push.
        // The ACR resource itself is provisioned by alien-infra.
        let routable_name = self.routable_repository_name(repo_name);
        let repository_uri = format!("{}/{}", self.registry_endpoint, routable_name);

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

    async fn get_repository(&self, repo_id: &str) -> Result<RepositoryResponse> {
        // ACR repositories are implicit — return the routable name and URI.
        let repository_uri = format!("{}/{}", self.registry_endpoint, repo_id);

        Ok(RepositoryResponse {
            name: repo_id.to_string(),
            uri: Some(repository_uri),
            created_at: None,
        })
    }

    async fn add_cross_account_access(
        &self,
        repo_id: &str,
        _access: CrossAccountAccess,
    ) -> Result<()> {
        let repo_name = repo_id;

        info!(
            repo_name = %repo_name,
            registry_name = %self.registry_name,
            "Azure Container Registry cross-account access not supported"
        );

        Err(AlienError::new(ErrorData::OperationNotSupported {
            operation: "add_cross_account_access".to_string(),
            reason: "Azure Container Registry uses token-based access via generate_credentials - cross-account permissions are not supported".to_string(),
        }))
    }

    async fn remove_cross_account_access(
        &self,
        repo_id: &str,
        _access: CrossAccountAccess,
    ) -> Result<()> {
        let repo_name = repo_id;

        info!(
            repo_name = %repo_name,
            registry_name = %self.registry_name,
            "Azure Container Registry cross-account access not supported"
        );

        Err(AlienError::new(ErrorData::OperationNotSupported {
            operation: "remove_cross_account_access".to_string(),
            reason: "Azure Container Registry uses token-based access via generate_credentials - cross-account permissions are not supported".to_string(),
        }))
    }

    async fn get_cross_account_access(&self, repo_id: &str) -> Result<CrossAccountPermissions> {
        let repo_name = repo_id;

        info!(
            repo_name = %repo_name,
            registry_name = %self.registry_name,
            "Azure Container Registry cross-account access not supported"
        );

        Err(AlienError::new(ErrorData::OperationNotSupported {
            operation: "get_cross_account_access".to_string(),
            reason: "Azure Container Registry uses token-based access via generate_credentials - cross-account permissions are not supported".to_string(),
        }))
    }

    async fn generate_credentials(
        &self,
        repo_id: &str,
        permissions: ArtifactRegistryPermissions,
        _ttl_seconds: Option<u32>,
    ) -> Result<ArtifactRegistryCredentials> {
        info!(
            registry = %self.registry_endpoint,
            repo_id = %repo_id,
            permissions = ?permissions,
            "Generating ACR credentials via AAD → refresh → access token flow"
        );

        // Step 1: Get an AAD access token for the management API.
        let aad_token = self
            .azure_token_cache
            .get_bearer_token_with_scope("https://management.azure.com/.default")
            .await
            .map_err(|e| {
                map_cloud_client_error(e, "Failed to get AAD token for ACR".to_string(), None)
            })?;

        // Step 2: Exchange AAD token for an ACR refresh token.
        // See: https://github.com/Azure/acr/blob/main/docs/AAD-OAuth.md
        let exchange_url = format!("https://{}/oauth2/exchange", self.registry_endpoint);
        let exchange_resp = self
            .http_client
            .post(&exchange_url)
            .form(&[
                ("grant_type", "access_token"),
                ("service", &self.registry_endpoint),
                ("access_token", &aad_token),
            ])
            .send()
            .await
            .into_alien_error()
            .context(ErrorData::Other {
                message: "ACR OAuth2 exchange request failed".to_string(),
            })?;

        if !exchange_resp.status().is_success() {
            let status = exchange_resp.status();
            let body = exchange_resp.text().await.unwrap_or_default();
            return Err(AlienError::new(ErrorData::Other {
                message: format!("ACR OAuth2 exchange failed with {}: {}", status, body),
            }));
        }

        #[derive(serde::Deserialize)]
        struct ExchangeResponse {
            refresh_token: String,
        }
        let refresh_token = exchange_resp
            .json::<ExchangeResponse>()
            .await
            .into_alien_error()
            .context(ErrorData::Other {
                message: "Failed to parse ACR exchange response".to_string(),
            })?
            .refresh_token;

        // Step 3: Exchange refresh token for a scoped access token.
        // The access token is what ACR's /v2/ API accepts as Bearer auth.
        // Scope: "repository:{repo}:pull,push" or "repository:{repo}:pull"
        let scope = if repo_id.is_empty() {
            // No specific repo — request registry-wide catalog access
            "registry:catalog:*".to_string()
        } else {
            let actions = match permissions {
                ArtifactRegistryPermissions::Pull => "pull",
                ArtifactRegistryPermissions::PushPull => "pull,push",
            };
            format!("repository:{}:{}", repo_id, actions)
        };

        let token_url = format!("https://{}/oauth2/token", self.registry_endpoint);
        let token_resp = self
            .http_client
            .post(&token_url)
            .form(&[
                ("grant_type", "refresh_token"),
                ("service", &self.registry_endpoint),
                ("scope", &scope),
                ("refresh_token", &refresh_token),
            ])
            .send()
            .await
            .into_alien_error()
            .context(ErrorData::Other {
                message: "ACR OAuth2 token request failed".to_string(),
            })?;

        if !token_resp.status().is_success() {
            let status = token_resp.status();
            let body = token_resp.text().await.unwrap_or_default();
            return Err(AlienError::new(ErrorData::Other {
                message: format!("ACR OAuth2 token failed with {}: {}", status, body),
            }));
        }

        #[derive(serde::Deserialize)]
        struct TokenResponse {
            access_token: String,
        }
        let access_token = token_resp
            .json::<TokenResponse>()
            .await
            .into_alien_error()
            .context(ErrorData::Other {
                message: "Failed to parse ACR token response".to_string(),
            })?
            .access_token;

        info!(
            registry = %self.registry_endpoint,
            scope = %scope,
            "ACR access token generated"
        );

        // ACR OAuth2 access tokens expire in ~5 minutes
        let expires_at = Some((chrono::Utc::now() + chrono::Duration::seconds(300)).to_rfc3339());

        Ok(ArtifactRegistryCredentials {
            auth_method: RegistryAuthMethod::Bearer,
            username: String::new(),
            password: access_token,
            expires_at,
        })
    }

    // No-op: generate_credentials() uses the stateless AAD → refresh → access token
    // OAuth2 flow. No persistent resources (scope maps, tokens) are created, so
    // there is nothing to clean up.

    async fn delete_repository(&self, _repo_id: &str) -> Result<()> {
        // ACR repositories are implicit (created on push). Nothing to delete.
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alien_core::bindings::{AcrArtifactRegistryBinding, ArtifactRegistryBinding, BindingValue};
    use alien_core::AzureCredentials;

    fn test_config() -> AzureClientConfig {
        AzureClientConfig {
            subscription_id: "sub-test".to_string(),
            tenant_id: "tenant-test".to_string(),
            region: Some("eastus".to_string()),
            credentials: AzureCredentials::AccessToken {
                token: "token-test".to_string(),
            },
            service_overrides: None,
        }
    }

    #[tokio::test]
    async fn new_fails_when_configured_repository_prefix_cannot_be_resolved() {
        let binding = ArtifactRegistryBinding::Acr(AcrArtifactRegistryBinding {
            registry_name: BindingValue::Value("registrytest".to_string()),
            resource_group_name: BindingValue::Value("rg-test".to_string()),
            repository_prefix: Some(BindingValue::expression(serde_json::json!({
                "ref": "repositoryPrefix"
            }))),
        });

        let result =
            AcrArtifactRegistry::new("artifact-registry".to_string(), binding, &test_config())
                .await;
        let Err(error) = result else {
            panic!("configured repository_prefix resolution failure should fail initialization");
        };

        assert!(error
            .to_string()
            .contains("Failed to extract repository_prefix from binding"));
    }

    #[tokio::test]
    async fn new_uses_empty_repository_prefix_when_repository_prefix_is_omitted() {
        let binding = ArtifactRegistryBinding::Acr(AcrArtifactRegistryBinding {
            registry_name: BindingValue::Value("registrytest".to_string()),
            resource_group_name: BindingValue::Value("rg-test".to_string()),
            repository_prefix: None,
        });

        let registry =
            AcrArtifactRegistry::new("artifact-registry".to_string(), binding, &test_config())
                .await
                .expect("omitted repository_prefix should initialize");

        assert_eq!(registry.upstream_repository_prefix(), "");
    }

    #[tokio::test]
    async fn new_uses_configured_repository_prefix_for_routable_names() {
        let binding = ArtifactRegistryBinding::Acr(AcrArtifactRegistryBinding {
            registry_name: BindingValue::Value("registrytest".to_string()),
            resource_group_name: BindingValue::Value("rg-test".to_string()),
            repository_prefix: Some(BindingValue::Value("team-a".to_string())),
        });

        let registry =
            AcrArtifactRegistry::new("artifact-registry".to_string(), binding, &test_config())
                .await
                .expect("configured repository_prefix should initialize");
        let repository = registry
            .create_repository("worker")
            .await
            .expect("ACR repository response should be implicit");

        assert_eq!(registry.upstream_repository_prefix(), "team-a");
        assert_eq!(repository.name, "team-a/worker");
        assert_eq!(
            repository.uri,
            Some("registrytest.azurecr.io/team-a/worker".to_string())
        );
    }
}