apiforge 0.4.0

Production-grade API release automation CLI. From merged code to healthy pods in production — one command.
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
use crate::error::{AwsError, Result};
use crate::utils::{with_retry, RetryConfig, RetryableError};
use aws_config::BehaviorVersion;
use aws_sdk_cloudfront::Client as CloudFrontClient;
use aws_sdk_ecr::error::SdkError;
use aws_sdk_ecr::Client as EcrClient;
use aws_sdk_ssm::Client as SsmClient;
use aws_sdk_sts::Client as StsClient;
use base64::Engine;
use bollard::auth::DockerCredentials;

/// Wrapper for AWS errors that implements RetryableError
#[derive(Debug)]
struct AwsRetryableError(AwsError);

impl std::fmt::Display for AwsRetryableError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl RetryableError for AwsRetryableError {
    fn is_retryable(&self) -> bool {
        match &self.0 {
            // These are transient errors that can be retried
            AwsError::SdkError(msg) => {
                // Retry on common transient errors
                msg.contains("ThrottlingException")
                    || msg.contains("RequestTimeout")
                    || msg.contains("ServiceUnavailable")
                    || msg.contains("InternalServiceError")
                    || msg.contains("connection")
                    || msg.contains("timeout")
            }
            // Auth failures should not be retried
            AwsError::CredentialsInvalid => false,
            AwsError::EcrAuthFailed(_) => false,
            AwsError::PermissionDenied(_) => false,
            // Repo not found is a permanent error
            AwsError::EcrRepoNotFound(_) => false,
            AwsError::RegionNotConfigured => false,
        }
    }
}

impl From<AwsRetryableError> for crate::error::ApiForgeError {
    fn from(e: AwsRetryableError) -> Self {
        crate::error::ApiForgeError::Aws(e.0)
    }
}

pub struct AwsClient {
    ecr: EcrClient,
    sts: StsClient,
    ssm: SsmClient,
    cloudfront: CloudFrontClient,
    region: String,
    retry_config: RetryConfig,
}

impl AwsClient {
    pub async fn new(region: &str) -> Result<Self> {
        let config = aws_config::defaults(BehaviorVersion::latest())
            .region(aws_config::Region::new(region.to_string()))
            .load()
            .await;

        Ok(Self::from_sdk_config(&config, region))
    }

    pub async fn with_profile(region: &str, profile: &str) -> Result<Self> {
        let config = aws_config::defaults(BehaviorVersion::latest())
            .region(aws_config::Region::new(region.to_string()))
            .profile_name(profile)
            .load()
            .await;

        Ok(Self::from_sdk_config(&config, region))
    }

    fn from_sdk_config(config: &aws_config::SdkConfig, region: &str) -> Self {
        Self {
            ecr: EcrClient::new(config),
            sts: StsClient::new(config),
            ssm: SsmClient::new(config),
            cloudfront: CloudFrontClient::new(config),
            region: region.to_string(),
            retry_config: RetryConfig::default(),
        }
    }

    /// Fetch (and decrypt) an SSM parameter value by name/path.
    pub async fn get_ssm_parameter(&self, name: &str) -> Result<String> {
        let ssm = self.ssm.clone();
        let name = name.to_string();
        let retry_config = self.retry_config.clone();

        let result = with_retry(&retry_config, "AWS get_ssm_parameter", || {
            let ssm = ssm.clone();
            let name = name.clone();
            async move {
                let response = ssm
                    .get_parameter()
                    .name(&name)
                    .with_decryption(true)
                    .send()
                    .await
                    .map_err(|e| {
                        let msg = e.to_string();
                        if msg.contains("ParameterNotFound") {
                            AwsRetryableError(AwsError::SdkError(format!(
                                "SSM parameter '{}' not found",
                                name
                            )))
                        } else {
                            AwsRetryableError(AwsError::SdkError(msg))
                        }
                    })?;

                response
                    .parameter()
                    .and_then(|p| p.value())
                    .map(|v| v.to_string())
                    .ok_or_else(|| {
                        AwsRetryableError(AwsError::SdkError(format!(
                            "SSM parameter '{}' has no value",
                            name
                        )))
                    })
            }
        })
        .await?;

        Ok(result)
    }

    /// Create a CloudFront invalidation for the given paths.
    /// Returns the invalidation ID; completion is asynchronous on AWS's side.
    pub async fn create_cloudfront_invalidation(
        &self,
        distribution_id: &str,
        paths: &[String],
    ) -> Result<String> {
        let cloudfront = self.cloudfront.clone();
        let distribution_id = distribution_id.to_string();
        let paths = paths.to_vec();
        let retry_config = self.retry_config.clone();

        let result = with_retry(&retry_config, "AWS create_cloudfront_invalidation", || {
            let cloudfront = cloudfront.clone();
            let distribution_id = distribution_id.clone();
            let paths = paths.clone();
            async move {
                let cf_paths = aws_sdk_cloudfront::types::Paths::builder()
                    .quantity(paths.len() as i32)
                    .set_items(Some(paths.clone()))
                    .build()
                    .map_err(|e| AwsRetryableError(AwsError::SdkError(e.to_string())))?;

                let batch = aws_sdk_cloudfront::types::InvalidationBatch::builder()
                    .paths(cf_paths)
                    .caller_reference(uuid::Uuid::new_v4().to_string())
                    .build()
                    .map_err(|e| AwsRetryableError(AwsError::SdkError(e.to_string())))?;

                let response = cloudfront
                    .create_invalidation()
                    .distribution_id(&distribution_id)
                    .invalidation_batch(batch)
                    .send()
                    .await
                    .map_err(|e| AwsRetryableError(AwsError::SdkError(e.to_string())))?;

                response
                    .invalidation()
                    .map(|inv| inv.id().to_string())
                    .ok_or_else(|| {
                        AwsRetryableError(AwsError::SdkError(
                            "No invalidation in response".to_string(),
                        ))
                    })
            }
        })
        .await?;

        Ok(result)
    }

    pub async fn get_caller_identity(&self) -> Result<(String, String)> {
        let _ecr = self.ecr.clone();
        let sts = self.sts.clone();
        let retry_config = self.retry_config.clone();

        let result = with_retry(&retry_config, "AWS get_caller_identity", || {
            let sts = sts.clone();
            async move {
                let response = sts
                    .get_caller_identity()
                    .send()
                    .await
                    .map_err(|e| AwsRetryableError(AwsError::SdkError(e.to_string())))?;

                let account = response
                    .account()
                    .ok_or(AwsRetryableError(AwsError::CredentialsInvalid))?
                    .to_string();

                let arn = response
                    .arn()
                    .ok_or(AwsRetryableError(AwsError::CredentialsInvalid))?
                    .to_string();

                Ok::<(String, String), AwsRetryableError>((account, arn))
            }
        })
        .await?;

        Ok(result)
    }

    pub async fn get_ecr_authorization(&self) -> Result<DockerCredentials> {
        let ecr = self.ecr.clone();
        let retry_config = self.retry_config.clone();

        let result = with_retry(&retry_config, "AWS get_ecr_authorization", || {
            let ecr = ecr.clone();
            async move {
                let response = ecr
                    .get_authorization_token()
                    .send()
                    .await
                    .map_err(|e| AwsRetryableError(AwsError::EcrAuthFailed(e.to_string())))?;

                let auth_data = response.authorization_data().first().ok_or_else(|| {
                    AwsRetryableError(AwsError::EcrAuthFailed(
                        "No authorization data returned".to_string(),
                    ))
                })?;

                let token = auth_data.authorization_token().ok_or_else(|| {
                    AwsRetryableError(AwsError::EcrAuthFailed("No token in response".to_string()))
                })?;

                // Token is base64 encoded "username:password"
                let decoded = base64::engine::general_purpose::STANDARD
                    .decode(token)
                    .map_err(|e| {
                        AwsRetryableError(AwsError::EcrAuthFailed(format!(
                            "Failed to decode token: {}",
                            e
                        )))
                    })?;

                let decoded_str = String::from_utf8(decoded).map_err(|e| {
                    AwsRetryableError(AwsError::EcrAuthFailed(format!(
                        "Invalid token encoding: {}",
                        e
                    )))
                })?;

                let (username, password) = decoded_str.split_once(':').ok_or_else(|| {
                    AwsRetryableError(AwsError::EcrAuthFailed("Invalid token format".to_string()))
                })?;

                let server_address = auth_data.proxy_endpoint().map(|s| s.to_string());

                Ok::<DockerCredentials, AwsRetryableError>(DockerCredentials {
                    username: Some(username.to_string()),
                    password: Some(password.to_string()),
                    serveraddress: server_address,
                    ..Default::default()
                })
            }
        })
        .await?;

        Ok(result)
    }

    pub fn get_ecr_registry_url(&self, account_id: &str) -> String {
        format!("{}.dkr.ecr.{}.amazonaws.com", account_id, self.region)
    }

    /// Helper to check if an ECR error indicates the repository was not found
    fn is_repository_not_found_error<E>(error: &SdkError<E>) -> bool
    where
        E: std::fmt::Debug,
    {
        // Check the error code from the service error if available
        match error {
            SdkError::ServiceError(service_err) => {
                // The error message/code typically contains "RepositoryNotFoundException"
                let debug_str = format!("{:?}", service_err);
                debug_str.contains("RepositoryNotFoundException")
                    || debug_str.contains("RepositoryNotFound")
            }
            _ => {
                // For other SDK errors, check the string representation
                let err_str = error.to_string();
                err_str.contains("RepositoryNotFoundException")
                    || err_str.contains("RepositoryNotFound")
            }
        }
    }

    pub async fn ensure_repository_exists(&self, repo_name: &str) -> Result<String> {
        let ecr = self.ecr.clone();
        let repo_name = repo_name.to_string();
        let retry_config = self.retry_config.clone();

        let result = with_retry(&retry_config, "AWS ensure_repository_exists", || {
            let ecr = ecr.clone();
            let repo_name = repo_name.clone();
            async move {
                match ecr
                    .describe_repositories()
                    .repository_names(&repo_name)
                    .send()
                    .await
                {
                    Ok(response) => {
                        let repo = response.repositories().first().ok_or_else(|| {
                            AwsRetryableError(AwsError::EcrRepoNotFound(repo_name.clone()))
                        })?;

                        repo.repository_uri().map(|s| s.to_string()).ok_or_else(|| {
                            AwsRetryableError(AwsError::SdkError(format!(
                                "Repository '{}' exists but has no URI",
                                repo_name
                            )))
                        })
                    }
                    Err(e) => {
                        // Use proper error type checking instead of string matching
                        if Self::is_repository_not_found_error(&e) {
                            Err(AwsRetryableError(AwsError::EcrRepoNotFound(
                                repo_name.clone(),
                            )))
                        } else {
                            // Check if it's a retryable error
                            Err(AwsRetryableError(AwsError::SdkError(e.to_string())))
                        }
                    }
                }
            }
        })
        .await?;

        Ok(result)
    }

    pub async fn create_repository(&self, repo_name: &str) -> Result<String> {
        let ecr = self.ecr.clone();
        let repo_name = repo_name.to_string();
        let retry_config = self.retry_config.clone();

        let result = with_retry(&retry_config, "AWS create_repository", || {
            let ecr = ecr.clone();
            let repo_name = repo_name.clone();
            async move {
                let response = ecr
                    .create_repository()
                    .repository_name(&repo_name)
                    .image_scanning_configuration(
                        aws_sdk_ecr::types::ImageScanningConfiguration::builder()
                            .scan_on_push(true)
                            .build(),
                    )
                    .send()
                    .await
                    .map_err(|e| AwsRetryableError(AwsError::SdkError(e.to_string())))?;

                let repo = response.repository().ok_or_else(|| {
                    AwsRetryableError(AwsError::SdkError("No repository in response".to_string()))
                })?;

                repo.repository_uri().map(|s| s.to_string()).ok_or_else(|| {
                    AwsRetryableError(AwsError::SdkError(format!(
                        "Created repository '{}' but it has no URI",
                        repo_name
                    )))
                })
            }
        })
        .await?;

        Ok(result)
    }

    pub async fn list_image_tags(&self, repo_name: &str) -> Result<Vec<String>> {
        let ecr = self.ecr.clone();
        let repo_name = repo_name.to_string();
        let retry_config = self.retry_config.clone();

        let result = with_retry(&retry_config, "AWS list_image_tags", || {
            let ecr = ecr.clone();
            let repo_name = repo_name.clone();
            async move {
                let mut tags = Vec::new();
                let mut next_token: Option<String> = None;

                loop {
                    let mut request = ecr.list_images().repository_name(&repo_name);

                    if let Some(token) = &next_token {
                        request = request.next_token(token);
                    }

                    let response = request
                        .send()
                        .await
                        .map_err(|e| AwsRetryableError(AwsError::SdkError(e.to_string())))?;

                    for image_id in response.image_ids() {
                        if let Some(tag) = image_id.image_tag() {
                            tags.push(tag.to_string());
                        }
                    }

                    match response.next_token() {
                        Some(token) => next_token = Some(token.to_string()),
                        None => break,
                    }
                }

                Ok::<Vec<String>, AwsRetryableError>(tags)
            }
        })
        .await?;

        Ok(result)
    }
}