Skip to main content

fakecloud_acm/
service.rs

1//! ACM (Certificate Manager) JSON 1.1 service.
2
3use std::collections::BTreeMap;
4use std::sync::Arc;
5
6use async_trait::async_trait;
7use base64::Engine;
8use chrono::{Duration, Utc};
9use http::StatusCode;
10use parking_lot::RwLock;
11use serde_json::{json, Value};
12use sha2::{Digest, Sha256};
13use uuid::Uuid;
14
15use fakecloud_aws::arn::Arn;
16use fakecloud_core::service::{AwsRequest, AwsResponse, AwsService, AwsServiceError};
17
18use crate::state::{
19    AccountState, AcmAccounts, CertificateOptions, DomainValidation, RenewalSummary,
20    SharedAcmState, StoredCertificate,
21};
22
23const SUPPORTED_ACTIONS: &[&str] = &[
24    "RequestCertificate",
25    "DescribeCertificate",
26    "ListCertificates",
27    "DeleteCertificate",
28    "ImportCertificate",
29    "ExportCertificate",
30    "GetCertificate",
31    "RenewCertificate",
32    "RevokeCertificate",
33    "ResendValidationEmail",
34    "AddTagsToCertificate",
35    "RemoveTagsFromCertificate",
36    "ListTagsForCertificate",
37    "GetAccountConfiguration",
38    "PutAccountConfiguration",
39    "UpdateCertificateOptions",
40    "SearchCertificates",
41];
42
43pub struct AcmService {
44    state: SharedAcmState,
45    /// How long the auto-issue tick sleeps before flipping a freshly
46    /// requested DNS cert from `PENDING_VALIDATION` to `ISSUED`. Real
47    /// ACM takes minutes; the default of 5s keeps SDK-driven integration
48    /// tests fast while still simulating the async transition. EMAIL
49    /// certs do **not** auto-issue — they wait for the admin
50    /// `/_fakecloud/acm/certificates/{arn}/approve` endpoint. Tests can
51    /// shrink the delay via the env var `FAKECLOUD_ACM_AUTO_ISSUE_SECS`
52    /// (read at construction time) or via
53    /// [`AcmService::with_pending_validation_delay`].
54    pending_validation_delay: std::time::Duration,
55}
56
57/// Default DNS auto-issue delay when `FAKECLOUD_ACM_AUTO_ISSUE_SECS` is
58/// unset. Five seconds is short enough to keep most real-world SDK
59/// flows snappy without making race-prone tests pass by accident.
60const DEFAULT_AUTO_ISSUE_SECS: u64 = 5;
61
62fn auto_issue_delay_from_env() -> std::time::Duration {
63    let secs = std::env::var("FAKECLOUD_ACM_AUTO_ISSUE_SECS")
64        .ok()
65        .and_then(|v| v.parse::<u64>().ok())
66        .unwrap_or(DEFAULT_AUTO_ISSUE_SECS);
67    std::time::Duration::from_secs(secs)
68}
69
70impl AcmService {
71    pub fn new(state: SharedAcmState) -> Self {
72        Self {
73            state,
74            pending_validation_delay: auto_issue_delay_from_env(),
75        }
76    }
77
78    pub fn shared_state(&self) -> SharedAcmState {
79        Arc::clone(&self.state)
80    }
81
82    /// Override the auto-issue delay. Used by unit tests so they don't
83    /// have to wait wall-clock seconds for the tick to flip
84    /// `PENDING_VALIDATION` -> `ISSUED`.
85    pub fn with_pending_validation_delay(mut self, delay: std::time::Duration) -> Self {
86        self.pending_validation_delay = delay;
87        self
88    }
89
90    /// Synchronously approve a `PENDING_VALIDATION` certificate.
91    /// Mirrors the admin endpoint
92    /// `POST /_fakecloud/acm/certificates/{arn-or-id}/approve` — equivalent
93    /// to the user clicking the approval link in the validation email
94    /// (or in the case of DNS, the validation record landing). Returns
95    /// `false` if no certificate matches `arn_or_id` across any
96    /// account. Already-issued certs are left alone (returns `true`)
97    /// so the endpoint is idempotent.
98    pub fn approve_certificate(&self, arn_or_id: &str) -> bool {
99        self.set_certificate_status(arn_or_id, "ISSUED", None)
100    }
101
102    /// Return parsed-on-best-effort structural info about an imported
103    /// certificate + chain, surfaced via
104    /// `/_fakecloud/acm/certificates/{arn-or-id}/chain-info` so tests can
105    /// assert what fakecloud actually accepted at ImportCertificate.
106    ///
107    /// We deliberately do **not** anchor the chain to a real root —
108    /// fakecloud is not a PKI. The returned JSON exposes the PEM block
109    /// counts and byte lengths so callers can confirm we received the
110    /// chain they expected, plus an `external_ca_validated: false`
111    /// marker that documents the emulator gap.
112    pub fn chain_info(&self, arn_or_id: &str) -> Option<serde_json::Value> {
113        let state = self.state.read();
114        for account in state.accounts.values() {
115            let key = account
116                .certificates
117                .keys()
118                .find(|k| k.as_str() == arn_or_id || cert_id_from_arn(k) == arn_or_id)
119                .cloned()?;
120            if let Some(cert) = account.certificates.get(&key) {
121                let pem = cert.certificate_pem.as_deref().unwrap_or("");
122                let chain = cert.certificate_chain_pem.as_deref().unwrap_or("");
123                return Some(serde_json::json!({
124                    "certificate_arn": key,
125                    "certificate_pem_bytes": pem.len(),
126                    "certificate_pem_blocks": pem.matches("-----BEGIN CERTIFICATE-----").count(),
127                    "chain_pem_bytes": chain.len(),
128                    "chain_pem_blocks": chain.matches("-----BEGIN CERTIFICATE-----").count(),
129                    "external_ca_validated": false,
130                    "status": cert.status,
131                    "cert_type": cert.cert_type,
132                }));
133            }
134        }
135        None
136    }
137
138    /// Flip a stored certificate's status (and optionally a failure
139    /// reason). Returns `false` if no certificate matches `arn_or_id`
140    /// across any account. The admin endpoint `POST
141    /// /_fakecloud/acm/certificates/{arn-or-id}/status` calls this so
142    /// tests can synchronously force a cert into `ISSUED`, `FAILED`, or
143    /// `VALIDATION_TIMED_OUT` without waiting on the auto-issue tick.
144    ///
145    /// `arn_or_id` accepts either a full ACM ARN or just the
146    /// trailing UUID portion (everything after `certificate/`).
147    pub fn set_certificate_status(
148        &self,
149        arn_or_id: &str,
150        status: &str,
151        reason: Option<String>,
152    ) -> bool {
153        let mut state = self.state.write();
154        for account in state.accounts.values_mut() {
155            let key = account
156                .certificates
157                .keys()
158                .find(|k| k.as_str() == arn_or_id || cert_id_from_arn(k) == arn_or_id)
159                .cloned();
160            if let Some(key) = key {
161                if let Some(cert) = account.certificates.get_mut(&key) {
162                    cert.status = status.to_string();
163                    match status {
164                        "ISSUED" => {
165                            let now = Utc::now();
166                            cert.issued_at = Some(now);
167                            for dv in cert.domain_validation.iter_mut() {
168                                dv.validation_status = "SUCCESS".to_string();
169                            }
170                            cert.failure_reason = None;
171                            // AMAZON_ISSUED certs become renewal-eligible
172                            // and gain a fresh RenewalSummary the moment
173                            // they reach ISSUED, matching real ACM.
174                            if cert.cert_type == "AMAZON_ISSUED" {
175                                cert.renewal_eligibility = "ELIGIBLE".to_string();
176                                cert.renewal_summary = Some(RenewalSummary {
177                                    renewal_status: "PENDING_AUTO_RENEWAL".to_string(),
178                                    domain_validation: cert.domain_validation.clone(),
179                                    renewal_status_reason: None,
180                                    updated_at: now,
181                                });
182                            }
183                        }
184                        "FAILED" | "VALIDATION_TIMED_OUT" => {
185                            for dv in cert.domain_validation.iter_mut() {
186                                dv.validation_status = status.to_string();
187                            }
188                            if reason.is_some() {
189                                cert.failure_reason = reason;
190                            }
191                        }
192                        _ => {
193                            if reason.is_some() {
194                                cert.failure_reason = reason;
195                            }
196                        }
197                    }
198                    return true;
199                }
200            }
201        }
202        false
203    }
204}
205
206impl Default for AcmService {
207    fn default() -> Self {
208        Self::new(Arc::new(RwLock::new(AcmAccounts::new())))
209    }
210}
211
212#[async_trait]
213impl AwsService for AcmService {
214    fn service_name(&self) -> &str {
215        "acm"
216    }
217
218    fn supported_actions(&self) -> &[&str] {
219        SUPPORTED_ACTIONS
220    }
221
222    async fn handle(&self, req: AwsRequest) -> Result<AwsResponse, AwsServiceError> {
223        match req.action.as_str() {
224            "RequestCertificate" => self.request_certificate(&req),
225            "DescribeCertificate" => self.describe_certificate(&req),
226            "ListCertificates" => self.list_certificates(&req),
227            "DeleteCertificate" => self.delete_certificate(&req),
228            "ImportCertificate" => self.import_certificate(&req),
229            "ExportCertificate" => self.export_certificate(&req),
230            "GetCertificate" => self.get_certificate(&req),
231            "RenewCertificate" => self.renew_certificate(&req),
232            "RevokeCertificate" => self.revoke_certificate(&req),
233            "ResendValidationEmail" => self.resend_validation_email(&req),
234            "AddTagsToCertificate" => self.add_tags_to_certificate(&req),
235            "RemoveTagsFromCertificate" => self.remove_tags_from_certificate(&req),
236            "ListTagsForCertificate" => self.list_tags_for_certificate(&req),
237            "GetAccountConfiguration" => self.get_account_configuration(&req),
238            "PutAccountConfiguration" => self.put_account_configuration(&req),
239            "UpdateCertificateOptions" => self.update_certificate_options(&req),
240            "SearchCertificates" => self.search_certificates(&req),
241            other => Err(AwsServiceError::action_not_implemented("acm", other)),
242        }
243    }
244}
245
246// ─── Request handlers ────────────────────────────────────────────────
247
248impl AcmService {
249    fn request_certificate(&self, req: &AwsRequest) -> Result<AwsResponse, AwsServiceError> {
250        let body = req.json_body();
251        let domain_name = body
252            .get("DomainName")
253            .and_then(Value::as_str)
254            .ok_or_else(|| invalid_param("DomainName is required"))?
255            .to_string();
256        if domain_name.is_empty() || domain_name.len() > 253 {
257            return Err(invalid_param("DomainName length must be between 1 and 253"));
258        }
259        let validation_method = body
260            .get("ValidationMethod")
261            .and_then(Value::as_str)
262            .unwrap_or("DNS")
263            .to_string();
264        if validation_method != "EMAIL" && validation_method != "DNS" && validation_method != "HTTP"
265        {
266            return Err(invalid_param("Invalid ValidationMethod"));
267        }
268        let sans: Vec<String> = body
269            .get("SubjectAlternativeNames")
270            .and_then(Value::as_array)
271            .map(|v| {
272                v.iter()
273                    .filter_map(|s| s.as_str().map(|s| s.to_string()))
274                    .collect()
275            })
276            .unwrap_or_default();
277        let key_algorithm = body
278            .get("KeyAlgorithm")
279            .and_then(Value::as_str)
280            .unwrap_or("RSA_2048")
281            .to_string();
282        const VALID_KEY_ALGORITHMS: [&str; 7] = [
283            "RSA_1024",
284            "RSA_2048",
285            "RSA_3072",
286            "RSA_4096",
287            "EC_prime256v1",
288            "EC_secp384r1",
289            "EC_secp521r1",
290        ];
291        if !VALID_KEY_ALGORITHMS.contains(&key_algorithm.as_str()) {
292            return Err(invalid_param("Invalid KeyAlgorithm"));
293        }
294        let idempotency_token = body
295            .get("IdempotencyToken")
296            .and_then(Value::as_str)
297            .map(|s| s.to_string());
298        if let Some(ref token) = idempotency_token {
299            if token.is_empty() || token.len() > 32 {
300                return Err(invalid_param(
301                    "IdempotencyToken length must be between 1 and 32",
302                ));
303            }
304            if !token
305                .chars()
306                .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
307            {
308                return Err(invalid_param(
309                    "IdempotencyToken must match pattern ^[\\w-]+$",
310                ));
311            }
312        }
313        let managed_by = body
314            .get("ManagedBy")
315            .and_then(Value::as_str)
316            .map(|s| s.to_string());
317        if let Some(ref m) = managed_by {
318            if m != "CLOUDFRONT" {
319                return Err(invalid_param("Invalid ManagedBy"));
320            }
321        }
322        let ca_arn = body
323            .get("CertificateAuthorityArn")
324            .and_then(Value::as_str)
325            .map(|s| s.to_string());
326        if let Some(ref arn) = ca_arn {
327            if arn.len() < 20 || arn.len() > 2048 {
328                return Err(validation_error(
329                    "CertificateAuthorityArn length must be between 20 and 2048",
330                ));
331            }
332        }
333        let tags = parse_tags(body.get("Tags"))?;
334        let options = parse_options(body.get("Options"));
335
336        let mut state = self.state.write();
337        let account = account_mut(&mut state, &req.account_id);
338
339        // Idempotency: a same-token + same-DomainName + same-SANs request returns
340        // the prior cert. Real ACM keys this on a 1-hour window; fakecloud uses
341        // exact match for determinism.
342        if let Some(token) = &idempotency_token {
343            if let Some(existing) = account.certificates.values().find(|c| {
344                c.idempotency_token.as_deref() == Some(token)
345                    && c.domain_name == domain_name
346                    && c.subject_alternative_names == effective_sans(&domain_name, &sans)
347            }) {
348                return Ok(AwsResponse::ok_json(
349                    json!({ "CertificateArn": existing.arn }),
350                ));
351            }
352        }
353
354        let arn = synth_certificate_arn(&req.account_id, &req.region);
355        let now = Utc::now();
356        let effective = effective_sans(&domain_name, &sans);
357        let (cert_pem, key_pem) = generate_self_signed_cert(&domain_name, &effective)
358            .map(|(c, k)| (Some(c), Some(k)))
359            .unwrap_or((None, None));
360        let cert = StoredCertificate {
361            arn: arn.clone(),
362            domain_name: domain_name.clone(),
363            subject_alternative_names: effective,
364            status: "PENDING_VALIDATION".to_string(),
365            cert_type: "AMAZON_ISSUED".to_string(),
366            certificate_pem: cert_pem,
367            certificate_chain_pem: None,
368            private_key_pem: key_pem,
369            idempotency_token,
370            serial: synth_serial(&arn),
371            subject: format!("CN={domain_name}"),
372            issuer: "Amazon".to_string(),
373            key_algorithm,
374            signature_algorithm: "SHA256WITHRSA".to_string(),
375            created_at: now,
376            issued_at: None,
377            imported_at: None,
378            revoked_at: None,
379            revocation_reason: None,
380            // Issued certs from real ACM are valid 13 months. Match.
381            not_before: now,
382            not_after: now + Duration::days(395),
383            validation_method: Some(validation_method.clone()),
384            domain_validation: synth_domain_validation(&domain_name, &sans, &validation_method),
385            options,
386            renewal_eligibility: "INELIGIBLE".to_string(),
387            managed_by,
388            certificate_authority_arn: ca_arn,
389            tags,
390            in_use_by: Vec::new(),
391            describe_read_count: 0,
392            failure_reason: None,
393            renewal_summary: None,
394        };
395        account.certificates.insert(arn.clone(), cert);
396        drop(state);
397
398        // Auto-issue tick: real ACM transitions DNS-validated certs
399        // from PENDING_VALIDATION to ISSUED asynchronously once the
400        // validation record lands. fakecloud fires the same flip after
401        // `pending_validation_delay` (default 5s, configurable via
402        // `FAKECLOUD_ACM_AUTO_ISSUE_SECS`) so SDK-driven tests can
403        // observe the transition without standing up a real DNS
404        // resolver. EMAIL certs intentionally stay PENDING — real AWS
405        // sends a confirmation email; tests drive the approval via
406        // `POST /_fakecloud/acm/certificates/{arn}/approve`.
407        // ImportCertificate stays ISSUED-on-arrival (its own code path
408        // never enters this branch).
409        if validation_method == "DNS" {
410            let state_for_tick = Arc::clone(&self.state);
411            let arn_for_tick = arn.clone();
412            let account_for_tick = req.account_id.clone();
413            let delay = self.pending_validation_delay;
414            tokio::spawn(async move {
415                tokio::time::sleep(delay).await;
416                let mut state = state_for_tick.write();
417                if let Some(account) = state.accounts.get_mut(&account_for_tick) {
418                    if let Some(cert) = account.certificates.get_mut(&arn_for_tick) {
419                        if cert.status == "PENDING_VALIDATION" && cert.cert_type == "AMAZON_ISSUED"
420                        {
421                            let now = Utc::now();
422                            cert.status = "ISSUED".to_string();
423                            cert.issued_at = Some(now);
424                            cert.renewal_eligibility = "ELIGIBLE".to_string();
425                            for dv in cert.domain_validation.iter_mut() {
426                                dv.validation_status = "SUCCESS".to_string();
427                            }
428                            cert.renewal_summary = Some(RenewalSummary {
429                                renewal_status: "PENDING_AUTO_RENEWAL".to_string(),
430                                domain_validation: cert.domain_validation.clone(),
431                                renewal_status_reason: None,
432                                updated_at: now,
433                            });
434                        }
435                    }
436                }
437            });
438        }
439
440        Ok(AwsResponse::ok_json(json!({ "CertificateArn": arn })))
441    }
442
443    fn describe_certificate(&self, req: &AwsRequest) -> Result<AwsResponse, AwsServiceError> {
444        let arn = require_certificate_arn(req)?;
445        let state = self.state.read();
446        let cert = state
447            .accounts
448            .get(&req.account_id)
449            .and_then(|a| a.certificates.get(&arn))
450            .ok_or_else(|| no_such_certificate(&arn))?
451            .clone();
452        // Status / NotBefore / NotAfter / RenewalEligibility /
453        // RenewalSummary / DomainValidationOptions[].ValidationStatus
454        // all come straight from the stored cert; the auto-issue tick
455        // (DNS) and admin `/approve` endpoint (EMAIL) mutate them
456        // out-of-band so successive describes naturally observe the
457        // transition.
458        Ok(AwsResponse::ok_json(json!({
459            "Certificate": certificate_detail_json(&cert),
460        })))
461    }
462
463    fn list_certificates(&self, req: &AwsRequest) -> Result<AwsResponse, AwsServiceError> {
464        let body = req.json_body();
465        let max_items: usize = body
466            .get("MaxItems")
467            .and_then(Value::as_u64)
468            .map(|n| n as usize)
469            .unwrap_or(100);
470        if !(1..=1000).contains(&max_items) {
471            return Err(validation_error("MaxItems must be between 1 and 1000"));
472        }
473        let next_token = body
474            .get("NextToken")
475            .and_then(Value::as_str)
476            .map(|s| s.to_string());
477        if let Some(ref token) = next_token {
478            if token.is_empty() || token.len() > 10000 {
479                return Err(validation_error(
480                    "NextToken length must be between 1 and 10000",
481                ));
482            }
483        }
484        if let Some(sort_by) = body.get("SortBy").and_then(Value::as_str) {
485            if sort_by != "CREATED_AT" {
486                return Err(validation_error("Invalid SortBy"));
487            }
488        }
489        if let Some(sort_order) = body.get("SortOrder").and_then(Value::as_str) {
490            if sort_order != "ASCENDING" && sort_order != "DESCENDING" {
491                return Err(validation_error("Invalid SortOrder"));
492            }
493        }
494        let statuses: Vec<String> = body
495            .get("CertificateStatuses")
496            .and_then(Value::as_array)
497            .map(|v| {
498                v.iter()
499                    .filter_map(|s| s.as_str().map(|s| s.to_string()))
500                    .collect()
501            })
502            .unwrap_or_default();
503        let includes = body.get("Includes");
504        let key_types: Vec<String> = includes
505            .and_then(|i| i.get("keyTypes"))
506            .and_then(Value::as_array)
507            .map(|v| {
508                v.iter()
509                    .filter_map(|s| s.as_str().map(|s| s.to_string()))
510                    .collect()
511            })
512            .unwrap_or_default();
513
514        let state = self.state.read();
515        let mut all: Vec<StoredCertificate> = state
516            .accounts
517            .get(&req.account_id)
518            .map(|a| a.certificates.values().cloned().collect())
519            .unwrap_or_default();
520        drop(state);
521        all.sort_by(|a, b| a.arn.cmp(&b.arn));
522        all.retain(|c| {
523            (statuses.is_empty() || statuses.contains(&c.status))
524                && (key_types.is_empty() || key_types.contains(&c.key_algorithm))
525        });
526
527        let start = next_token
528            .and_then(|t| t.parse::<usize>().ok())
529            .unwrap_or(0);
530        let end = (start + max_items).min(all.len());
531        let page: Vec<&StoredCertificate> = all.iter().skip(start).take(max_items).collect();
532        let next = if end < all.len() {
533            Some(end.to_string())
534        } else {
535            None
536        };
537        let mut response = json!({
538            "CertificateSummaryList": page
539                .iter()
540                .map(|c| certificate_summary_json(c))
541                .collect::<Vec<_>>(),
542        });
543        if let Some(t) = next {
544            response
545                .as_object_mut()
546                .unwrap()
547                .insert("NextToken".to_string(), Value::String(t));
548        }
549        Ok(AwsResponse::ok_json(response))
550    }
551
552    fn delete_certificate(&self, req: &AwsRequest) -> Result<AwsResponse, AwsServiceError> {
553        let arn = require_certificate_arn(req)?;
554        let mut state = self.state.write();
555        let account = account_mut(&mut state, &req.account_id);
556        let cert = account
557            .certificates
558            .get(&arn)
559            .ok_or_else(|| no_such_certificate(&arn))?;
560        if !cert.in_use_by.is_empty() {
561            return Err(AwsServiceError::aws_error(
562                StatusCode::BAD_REQUEST,
563                "ResourceInUseException",
564                format!(
565                    "Certificate {arn} is in use by {} resource(s)",
566                    cert.in_use_by.len()
567                ),
568            ));
569        }
570        account.certificates.remove(&arn);
571        Ok(AwsResponse::ok_json(json!({})))
572    }
573
574    fn import_certificate(&self, req: &AwsRequest) -> Result<AwsResponse, AwsServiceError> {
575        let body = req.json_body();
576        let cert_pem = decode_blob(body.get("Certificate"))
577            .ok_or_else(|| invalid_param("Certificate is required"))?;
578        let key_pem = decode_blob(body.get("PrivateKey"))
579            .ok_or_else(|| invalid_param("PrivateKey is required"))?;
580        let chain_pem = decode_blob(body.get("CertificateChain"));
581        let arn_in = body
582            .get("CertificateArn")
583            .and_then(Value::as_str)
584            .map(|s| s.to_string());
585        let tags = parse_tags(body.get("Tags"))?;
586
587        let domain_name = parse_cn_from_pem(&cert_pem).unwrap_or_else(|| "imported".to_string());
588        let now = Utc::now();
589        let mut state = self.state.write();
590        let account = account_mut(&mut state, &req.account_id);
591
592        let arn = match arn_in {
593            Some(existing) => {
594                let cert = account
595                    .certificates
596                    .get_mut(&existing)
597                    .ok_or_else(|| no_such_certificate(&existing))?;
598                if cert.cert_type != "IMPORTED" {
599                    return Err(invalid_param(
600                        "Reimport is only supported for IMPORTED certificates",
601                    ));
602                }
603                cert.certificate_pem = Some(cert_pem.clone());
604                cert.private_key_pem = Some(key_pem);
605                cert.certificate_chain_pem = chain_pem;
606                cert.imported_at = Some(now);
607                cert.not_before = now;
608                cert.not_after = now + Duration::days(395);
609                cert.subject = format!("CN={domain_name}");
610                // Reimport must overwrite the domain identity too —
611                // otherwise Describe / List / Search keep returning the
612                // previous DomainName + SANs after a successful import.
613                cert.domain_name = domain_name.clone();
614                cert.subject_alternative_names = vec![domain_name.clone()];
615                if !tags.is_empty() {
616                    for (k, v) in tags {
617                        cert.tags.insert(k, v);
618                    }
619                }
620                existing
621            }
622            None => {
623                let arn = synth_certificate_arn(&req.account_id, &req.region);
624                let cert = StoredCertificate {
625                    arn: arn.clone(),
626                    domain_name: domain_name.clone(),
627                    subject_alternative_names: vec![domain_name.clone()],
628                    status: "ISSUED".to_string(),
629                    cert_type: "IMPORTED".to_string(),
630                    certificate_pem: Some(cert_pem),
631                    certificate_chain_pem: chain_pem,
632                    private_key_pem: Some(key_pem),
633                    idempotency_token: None,
634                    serial: synth_serial(&arn),
635                    subject: format!("CN={domain_name}"),
636                    issuer: "fakecloud-imported".to_string(),
637                    key_algorithm: "RSA_2048".to_string(),
638                    signature_algorithm: "SHA256WITHRSA".to_string(),
639                    created_at: now,
640                    issued_at: Some(now),
641                    imported_at: Some(now),
642                    revoked_at: None,
643                    revocation_reason: None,
644                    not_before: now,
645                    not_after: now + Duration::days(395),
646                    validation_method: None,
647                    domain_validation: Vec::new(),
648                    options: CertificateOptions {
649                        certificate_transparency_logging_preference: "ENABLED".to_string(),
650                        export: "DISABLED".to_string(),
651                    },
652                    renewal_eligibility: "INELIGIBLE".to_string(),
653                    managed_by: None,
654                    certificate_authority_arn: None,
655                    tags,
656                    in_use_by: Vec::new(),
657                    describe_read_count: 0,
658                    failure_reason: None,
659                    renewal_summary: None,
660                };
661                account.certificates.insert(arn.clone(), cert);
662                arn
663            }
664        };
665        Ok(AwsResponse::ok_json(json!({ "CertificateArn": arn })))
666    }
667
668    fn export_certificate(&self, req: &AwsRequest) -> Result<AwsResponse, AwsServiceError> {
669        let body = req.json_body();
670        let arn = body
671            .get("CertificateArn")
672            .and_then(Value::as_str)
673            .ok_or_else(|| invalid_param("CertificateArn is required"))?
674            .to_string();
675        // AWS encodes Passphrase as a Blob. Over awsJson1_1 (the wire
676        // protocol used by ACM) blobs are base64 strings. Missing/empty
677        // means the caller wants the plain PEM back.
678        let passphrase_bytes = match body.get("Passphrase").and_then(Value::as_str) {
679            None | Some("") => None,
680            Some(s) => {
681                let decoded = base64::engine::general_purpose::STANDARD
682                    .decode(s)
683                    .map_err(|_| invalid_param("Passphrase must be valid base64"))?;
684                if decoded.is_empty() {
685                    None
686                } else {
687                    Some(decoded)
688                }
689            }
690        };
691        let state = self.state.read();
692        let cert = state
693            .accounts
694            .get(&req.account_id)
695            .and_then(|a| a.certificates.get(&arn))
696            .ok_or_else(|| no_such_certificate(&arn))?
697            .clone();
698        if cert.options.export != "ENABLED" && cert.cert_type != "IMPORTED" {
699            return Err(AwsServiceError::aws_error(
700                StatusCode::BAD_REQUEST,
701                "RequestInProgressException",
702                "Certificate is not exportable",
703            ));
704        }
705        let cert_pem = cert
706            .certificate_pem
707            .clone()
708            .unwrap_or_else(|| placeholder_cert_pem(&arn));
709        let chain_pem = cert
710            .certificate_chain_pem
711            .clone()
712            .unwrap_or_else(|| placeholder_chain_pem(&arn));
713        let key_pem = cert
714            .private_key_pem
715            .clone()
716            .unwrap_or_else(|| placeholder_key_pem(&arn));
717        let key_out = match passphrase_bytes {
718            Some(pp) => encrypt_private_key_pem(&key_pem, &pp)
719                .map_err(|e| invalid_param(format!("failed to encrypt private key: {e}")))?,
720            None => key_pem,
721        };
722        Ok(AwsResponse::ok_json(json!({
723            "Certificate": cert_pem,
724            "CertificateChain": chain_pem,
725            "PrivateKey": key_out,
726        })))
727    }
728
729    fn get_certificate(&self, req: &AwsRequest) -> Result<AwsResponse, AwsServiceError> {
730        let arn = require_certificate_arn(req)?;
731        let state = self.state.read();
732        let cert = state
733            .accounts
734            .get(&req.account_id)
735            .and_then(|a| a.certificates.get(&arn))
736            .ok_or_else(|| no_such_certificate(&arn))?
737            .clone();
738        let cert_pem = cert
739            .certificate_pem
740            .clone()
741            .unwrap_or_else(|| placeholder_cert_pem(&arn));
742        let chain_pem = cert
743            .certificate_chain_pem
744            .clone()
745            .unwrap_or_else(|| placeholder_chain_pem(&arn));
746        Ok(AwsResponse::ok_json(json!({
747            "Certificate": cert_pem,
748            "CertificateChain": chain_pem,
749        })))
750    }
751
752    fn renew_certificate(&self, req: &AwsRequest) -> Result<AwsResponse, AwsServiceError> {
753        let arn = require_certificate_arn(req)?;
754        let mut state = self.state.write();
755        let account = account_mut(&mut state, &req.account_id);
756        let cert = account
757            .certificates
758            .get_mut(&arn)
759            .ok_or_else(|| no_such_certificate(&arn))?;
760        if cert.cert_type == "IMPORTED" {
761            return Err(invalid_param(
762                "Imported certificates cannot be renewed via ACM",
763            ));
764        }
765        // Renewal: flip to ISSUED from any prior state, refresh the
766        // validity window, mark domain validation SUCCESS, and refresh
767        // RenewalSummary. Real ACM kicks off a managed-renewal
768        // background job; fakecloud collapses that to an immediate
769        // success since there's nothing to actually validate.
770        let now = Utc::now();
771        cert.not_before = now;
772        cert.not_after = now + Duration::days(395);
773        cert.issued_at = Some(now);
774        cert.status = "ISSUED".to_string();
775        cert.renewal_eligibility = "ELIGIBLE".to_string();
776        cert.failure_reason = None;
777        for dv in cert.domain_validation.iter_mut() {
778            dv.validation_status = "SUCCESS".to_string();
779        }
780        cert.renewal_summary = Some(RenewalSummary {
781            renewal_status: "SUCCESS".to_string(),
782            domain_validation: cert.domain_validation.clone(),
783            renewal_status_reason: None,
784            updated_at: now,
785        });
786        Ok(AwsResponse::ok_json(json!({})))
787    }
788
789    fn revoke_certificate(&self, req: &AwsRequest) -> Result<AwsResponse, AwsServiceError> {
790        let body = req.json_body();
791        let arn = body
792            .get("CertificateArn")
793            .and_then(Value::as_str)
794            .ok_or_else(|| invalid_param("CertificateArn is required"))?
795            .to_string();
796        let reason = body
797            .get("RevocationReason")
798            .and_then(Value::as_str)
799            .ok_or_else(|| invalid_param("RevocationReason is required"))?
800            .to_string();
801        let mut state = self.state.write();
802        let account = account_mut(&mut state, &req.account_id);
803        let cert = account
804            .certificates
805            .get_mut(&arn)
806            .ok_or_else(|| no_such_certificate(&arn))?;
807        if cert.cert_type != "AMAZON_ISSUED" {
808            return Err(invalid_param(
809                "Only AMAZON_ISSUED certificates can be revoked",
810            ));
811        }
812        cert.status = "REVOKED".to_string();
813        cert.revoked_at = Some(Utc::now());
814        cert.revocation_reason = Some(reason);
815        Ok(AwsResponse::ok_json(json!({})))
816    }
817
818    fn resend_validation_email(&self, req: &AwsRequest) -> Result<AwsResponse, AwsServiceError> {
819        let body = req.json_body();
820        let arn = body
821            .get("CertificateArn")
822            .and_then(Value::as_str)
823            .ok_or_else(|| invalid_param("CertificateArn is required"))?
824            .to_string();
825        let _ = body
826            .get("Domain")
827            .and_then(Value::as_str)
828            .ok_or_else(|| invalid_param("Domain is required"))?;
829        let _ = body
830            .get("ValidationDomain")
831            .and_then(Value::as_str)
832            .ok_or_else(|| invalid_param("ValidationDomain is required"))?;
833        let state = self.state.read();
834        let cert = state
835            .accounts
836            .get(&req.account_id)
837            .and_then(|a| a.certificates.get(&arn))
838            .ok_or_else(|| no_such_certificate(&arn))?;
839        if cert.validation_method.as_deref() != Some("EMAIL") {
840            return Err(invalid_param(
841                "Certificate is not configured for EMAIL validation",
842            ));
843        }
844        Ok(AwsResponse::ok_json(json!({})))
845    }
846
847    fn add_tags_to_certificate(&self, req: &AwsRequest) -> Result<AwsResponse, AwsServiceError> {
848        let body = req.json_body();
849        let arn = body
850            .get("CertificateArn")
851            .and_then(Value::as_str)
852            .ok_or_else(|| invalid_param("CertificateArn is required"))?
853            .to_string();
854        let tags = parse_tags(body.get("Tags"))?;
855        if tags.is_empty() {
856            return Err(invalid_param("Tags must contain at least one entry"));
857        }
858        let mut state = self.state.write();
859        let account = account_mut(&mut state, &req.account_id);
860        let cert = account
861            .certificates
862            .get_mut(&arn)
863            .ok_or_else(|| no_such_certificate(&arn))?;
864        for (k, v) in tags {
865            cert.tags.insert(k, v);
866        }
867        Ok(AwsResponse::ok_json(json!({})))
868    }
869
870    fn remove_tags_from_certificate(
871        &self,
872        req: &AwsRequest,
873    ) -> Result<AwsResponse, AwsServiceError> {
874        let body = req.json_body();
875        let arn = body
876            .get("CertificateArn")
877            .and_then(Value::as_str)
878            .ok_or_else(|| invalid_param("CertificateArn is required"))?
879            .to_string();
880        let tags = parse_tags(body.get("Tags"))?;
881        if tags.is_empty() {
882            return Err(invalid_param("Tags must contain at least one entry"));
883        }
884        let mut state = self.state.write();
885        let account = account_mut(&mut state, &req.account_id);
886        let cert = account
887            .certificates
888            .get_mut(&arn)
889            .ok_or_else(|| no_such_certificate(&arn))?;
890        // Real ACM: a tag removes if Key matches; if Value is supplied it
891        // also has to match. Otherwise it's a no-op (not an error).
892        for (k, v) in tags {
893            if let Some(existing) = cert.tags.get(&k) {
894                if v.is_empty() || *existing == v {
895                    cert.tags.remove(&k);
896                }
897            }
898        }
899        Ok(AwsResponse::ok_json(json!({})))
900    }
901
902    fn list_tags_for_certificate(&self, req: &AwsRequest) -> Result<AwsResponse, AwsServiceError> {
903        let arn = require_certificate_arn(req)?;
904        let state = self.state.read();
905        let cert = state
906            .accounts
907            .get(&req.account_id)
908            .and_then(|a| a.certificates.get(&arn))
909            .ok_or_else(|| no_such_certificate(&arn))?;
910        let mut tags: Vec<(String, String)> = cert
911            .tags
912            .iter()
913            .map(|(k, v)| (k.clone(), v.clone()))
914            .collect();
915        tags.sort_by(|a, b| a.0.cmp(&b.0));
916        let tag_list: Vec<Value> = tags
917            .into_iter()
918            .map(|(k, v)| json!({ "Key": k, "Value": v }))
919            .collect();
920        Ok(AwsResponse::ok_json(json!({ "Tags": tag_list })))
921    }
922
923    fn get_account_configuration(&self, req: &AwsRequest) -> Result<AwsResponse, AwsServiceError> {
924        let state = self.state.read();
925        let cfg = state
926            .accounts
927            .get(&req.account_id)
928            .map(|a| a.account_config.clone())
929            .unwrap_or_default();
930        let mut expiry = json!({});
931        if let Some(d) = cfg.expiry_events_days_before_expiry {
932            expiry
933                .as_object_mut()
934                .unwrap()
935                .insert("DaysBeforeExpiry".to_string(), json!(d));
936        }
937        Ok(AwsResponse::ok_json(json!({
938            "ExpiryEvents": expiry,
939        })))
940    }
941
942    fn put_account_configuration(&self, req: &AwsRequest) -> Result<AwsResponse, AwsServiceError> {
943        let body = req.json_body();
944        let idempotency_token = body
945            .get("IdempotencyToken")
946            .and_then(Value::as_str)
947            .ok_or_else(|| invalid_param("IdempotencyToken is required"))?;
948        if idempotency_token.is_empty() || idempotency_token.len() > 32 {
949            return Err(validation_error(
950                "IdempotencyToken length must be between 1 and 32",
951            ));
952        }
953        if !idempotency_token
954            .chars()
955            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
956        {
957            return Err(validation_error(
958                "IdempotencyToken must match pattern ^[\\w-]+$",
959            ));
960        }
961        let days = body
962            .get("ExpiryEvents")
963            .and_then(|v| v.get("DaysBeforeExpiry"))
964            .and_then(Value::as_i64)
965            .map(|n| n as i32);
966        let mut state = self.state.write();
967        let account = account_mut(&mut state, &req.account_id);
968        account.account_config.expiry_events_days_before_expiry = days;
969        Ok(AwsResponse::ok_json(json!({})))
970    }
971
972    fn update_certificate_options(&self, req: &AwsRequest) -> Result<AwsResponse, AwsServiceError> {
973        let body = req.json_body();
974        let arn = body
975            .get("CertificateArn")
976            .and_then(Value::as_str)
977            .ok_or_else(|| invalid_param("CertificateArn is required"))?
978            .to_string();
979        let options = body
980            .get("Options")
981            .ok_or_else(|| invalid_param("Options is required"))?;
982        let new_opts = CertificateOptions {
983            certificate_transparency_logging_preference: options
984                .get("CertificateTransparencyLoggingPreference")
985                .and_then(Value::as_str)
986                .unwrap_or("ENABLED")
987                .to_string(),
988            export: options
989                .get("Export")
990                .and_then(Value::as_str)
991                .unwrap_or("DISABLED")
992                .to_string(),
993        };
994        let mut state = self.state.write();
995        let account = account_mut(&mut state, &req.account_id);
996        let cert = account
997            .certificates
998            .get_mut(&arn)
999            .ok_or_else(|| no_such_certificate(&arn))?;
1000        cert.options = new_opts;
1001        Ok(AwsResponse::ok_json(json!({})))
1002    }
1003
1004    fn search_certificates(&self, req: &AwsRequest) -> Result<AwsResponse, AwsServiceError> {
1005        // SearchCertificates is effectively ListCertificates with a
1006        // recursive `FilterStatement` (And/Or/Not/Filter union) plus
1007        // sort knobs. fakecloud honors the leaf-`Filter` cases
1008        // (KeyTypes, ExtendedKeyUsages match by passing through) and
1009        // ignores the And/Or/Not composition for now — enough to keep
1010        // SDK callers and the conformance probe happy.
1011        let body = req.json_body();
1012        let max_results: usize = body
1013            .get("MaxResults")
1014            .and_then(Value::as_u64)
1015            .map(|n| n as usize)
1016            .unwrap_or(100);
1017        if !(1..=500).contains(&max_results) {
1018            return Err(validation_error("MaxResults must be between 1 and 500"));
1019        }
1020        let next_token = body
1021            .get("NextToken")
1022            .and_then(Value::as_str)
1023            .map(|s| s.to_string());
1024        if let Some(ref token) = next_token {
1025            if token.is_empty() || token.len() > 10000 {
1026                return Err(validation_error(
1027                    "NextToken length must be between 1 and 10000",
1028                ));
1029            }
1030        }
1031        if let Some(sort_by) = body.get("SortBy").and_then(Value::as_str) {
1032            const VALID_SORT_BY: [&str; 18] = [
1033                "CREATED_AT",
1034                "NOT_AFTER",
1035                "STATUS",
1036                "RENEWAL_STATUS",
1037                "EXPORTED",
1038                "IN_USE",
1039                "NOT_BEFORE",
1040                "KEY_ALGORITHM",
1041                "TYPE",
1042                "CERTIFICATE_ARN",
1043                "COMMON_NAME",
1044                "REVOKED_AT",
1045                "RENEWAL_ELIGIBILITY",
1046                "ISSUED_AT",
1047                "MANAGED_BY",
1048                "EXPORT_OPTION",
1049                "VALIDATION_METHOD",
1050                "IMPORTED_AT",
1051            ];
1052            if !VALID_SORT_BY.contains(&sort_by) {
1053                return Err(validation_error("Invalid SortBy"));
1054            }
1055        }
1056        if let Some(sort_order) = body.get("SortOrder").and_then(Value::as_str) {
1057            if sort_order != "ASCENDING" && sort_order != "DESCENDING" {
1058                return Err(validation_error("Invalid SortOrder"));
1059            }
1060        }
1061        // Filter values live under FilterStatement.Filter.<Key>; AWS ANDs the
1062        // leaf filters and, within each leaf, keeps certs that match ANY listed
1063        // value. Only KeyTypes was applied before (bug-audit 2026-05-28, 1.5).
1064        let filter_values = |key: &str| -> Vec<String> {
1065            body.get("FilterStatement")
1066                .and_then(|f| f.get("Filter"))
1067                .and_then(|f| f.get(key))
1068                .and_then(Value::as_array)
1069                .map(|v| {
1070                    v.iter()
1071                        .filter_map(|s| s.as_str().map(|s| s.to_ascii_uppercase()))
1072                        .collect()
1073                })
1074                .unwrap_or_default()
1075        };
1076        let key_types = filter_values("KeyTypes");
1077
1078        // CertificateStatuses is a top-level filter on the certificate status.
1079        let statuses: Vec<String> = body
1080            .get("CertificateStatuses")
1081            .and_then(Value::as_array)
1082            .map(|v| {
1083                v.iter()
1084                    .filter_map(|s| s.as_str().map(|s| s.to_ascii_uppercase()))
1085                    .collect()
1086            })
1087            .unwrap_or_default();
1088
1089        let state = self.state.read();
1090        let mut all: Vec<StoredCertificate> = state
1091            .accounts
1092            .get(&req.account_id)
1093            .map(|a| a.certificates.values().cloned().collect())
1094            .unwrap_or_default();
1095        drop(state);
1096
1097        if !key_types.is_empty() {
1098            all.retain(|c| key_types.contains(&c.key_algorithm.to_ascii_uppercase()));
1099        }
1100        if !statuses.is_empty() {
1101            all.retain(|c| statuses.contains(&c.status.to_ascii_uppercase()));
1102        }
1103
1104        // Apply SortBy/SortOrder (validated above but previously never applied,
1105        // 1.5). Default order is descending; the default key is CREATED_AT.
1106        let sort_by = body
1107            .get("SortBy")
1108            .and_then(Value::as_str)
1109            .unwrap_or("CREATED_AT")
1110            .to_string();
1111        let descending = body
1112            .get("SortOrder")
1113            .and_then(Value::as_str)
1114            .map(|o| !o.eq_ignore_ascii_case("ASCENDING"))
1115            .unwrap_or(true);
1116        all.sort_by(|a, b| {
1117            let ord = match sort_by.as_str() {
1118                "NOT_AFTER" => a.not_after.cmp(&b.not_after),
1119                "NOT_BEFORE" => a.not_before.cmp(&b.not_before),
1120                "ISSUED_AT" => a.issued_at.cmp(&b.issued_at),
1121                "STATUS" => a.status.cmp(&b.status),
1122                "KEY_ALGORITHM" => a.key_algorithm.cmp(&b.key_algorithm),
1123                "TYPE" => a.cert_type.cmp(&b.cert_type),
1124                "CERTIFICATE_ARN" => a.arn.cmp(&b.arn),
1125                // CREATED_AT and any other validated-but-unmodeled key.
1126                _ => a.created_at.cmp(&b.created_at),
1127            };
1128            // Stable tiebreak by ARN keeps paging deterministic.
1129            let ord = ord.then_with(|| a.arn.cmp(&b.arn));
1130            if descending {
1131                ord.reverse()
1132            } else {
1133                ord
1134            }
1135        });
1136        let start = next_token
1137            .and_then(|t| t.parse::<usize>().ok())
1138            .unwrap_or(0);
1139        let end = (start + max_results).min(all.len());
1140        let page: Vec<&StoredCertificate> = all.iter().skip(start).take(max_results).collect();
1141        let next = if end < all.len() {
1142            Some(end.to_string())
1143        } else {
1144            None
1145        };
1146        let mut response = json!({
1147            "Results": page
1148                .iter()
1149                .map(|c| certificate_search_result_json(c))
1150                .collect::<Vec<_>>(),
1151        });
1152        if let Some(t) = next {
1153            response
1154                .as_object_mut()
1155                .unwrap()
1156                .insert("NextToken".to_string(), Value::String(t));
1157        }
1158        Ok(AwsResponse::ok_json(response))
1159    }
1160}
1161
1162// ─── Helpers ────────────────────────────────────────────────────────
1163
1164fn account_mut<'a>(state: &'a mut AcmAccounts, account_id: &str) -> &'a mut AccountState {
1165    state.accounts.entry(account_id.to_string()).or_default()
1166}
1167
1168fn require_certificate_arn(req: &AwsRequest) -> Result<String, AwsServiceError> {
1169    req.json_body()
1170        .get("CertificateArn")
1171        .and_then(Value::as_str)
1172        .map(|s| s.to_string())
1173        .ok_or_else(|| invalid_param("CertificateArn is required"))
1174}
1175
1176fn invalid_param(msg: impl Into<String>) -> AwsServiceError {
1177    AwsServiceError::aws_error(StatusCode::BAD_REQUEST, "InvalidParameterException", msg)
1178}
1179
1180fn validation_error(msg: impl Into<String>) -> AwsServiceError {
1181    AwsServiceError::aws_error(StatusCode::BAD_REQUEST, "ValidationException", msg)
1182}
1183
1184fn no_such_certificate(arn: &str) -> AwsServiceError {
1185    AwsServiceError::aws_error(
1186        StatusCode::BAD_REQUEST,
1187        "ResourceNotFoundException",
1188        format!("Could not find certificate with arn {arn}"),
1189    )
1190}
1191
1192fn synth_certificate_arn(account_id: &str, region: &str) -> String {
1193    let region = if region.is_empty() {
1194        "us-east-1"
1195    } else {
1196        region
1197    };
1198    let id = Uuid::new_v4();
1199    Arn::new("acm", region, account_id, &format!("certificate/{id}")).to_string()
1200}
1201
1202/// Extract the trailing UUID portion of a certificate ARN
1203/// (`arn:aws:acm:region:account:certificate/<id>` -> `<id>`). Returns
1204/// the input unchanged if it doesn't match the ACM ARN shape — callers
1205/// only use this to compare against shorthand identifiers passed to the
1206/// admin endpoint, where a partial match against the full ARN is also
1207/// acceptable.
1208fn cert_id_from_arn(arn: &str) -> &str {
1209    arn.rsplit_once("certificate/")
1210        .map(|(_, id)| id)
1211        .unwrap_or(arn)
1212}
1213
1214fn synth_serial(arn: &str) -> String {
1215    let mut hasher = Sha256::new();
1216    hasher.update(arn.as_bytes());
1217    let digest = hasher.finalize();
1218    hex::encode(&digest[..16])
1219}
1220
1221fn parse_tags(value: Option<&Value>) -> Result<BTreeMap<String, String>, AwsServiceError> {
1222    let mut out = BTreeMap::new();
1223    let Some(arr) = value.and_then(Value::as_array) else {
1224        return Ok(out);
1225    };
1226    for tag in arr {
1227        let key = tag
1228            .get("Key")
1229            .and_then(Value::as_str)
1230            .ok_or_else(|| invalid_param("Tag.Key is required"))?
1231            .to_string();
1232        let value = tag
1233            .get("Value")
1234            .and_then(Value::as_str)
1235            .unwrap_or_default()
1236            .to_string();
1237        out.insert(key, value);
1238    }
1239    Ok(out)
1240}
1241
1242fn parse_options(value: Option<&Value>) -> CertificateOptions {
1243    let v = match value {
1244        Some(v) => v,
1245        None => {
1246            return CertificateOptions {
1247                certificate_transparency_logging_preference: "ENABLED".to_string(),
1248                export: "DISABLED".to_string(),
1249            };
1250        }
1251    };
1252    CertificateOptions {
1253        certificate_transparency_logging_preference: v
1254            .get("CertificateTransparencyLoggingPreference")
1255            .and_then(Value::as_str)
1256            .unwrap_or("ENABLED")
1257            .to_string(),
1258        export: v
1259            .get("Export")
1260            .and_then(Value::as_str)
1261            .unwrap_or("DISABLED")
1262            .to_string(),
1263    }
1264}
1265
1266/// Real ACM always carries the apex `DomainName` as the first entry of
1267/// `SubjectAlternativeNames`; replicate that so SDK tests that read SANs
1268/// don't have to special-case its absence.
1269fn effective_sans(domain: &str, extras: &[String]) -> Vec<String> {
1270    let mut all = vec![domain.to_string()];
1271    for s in extras {
1272        if !all.contains(s) {
1273            all.push(s.clone());
1274        }
1275    }
1276    all
1277}
1278
1279fn synth_domain_validation(domain: &str, sans: &[String], method: &str) -> Vec<DomainValidation> {
1280    effective_sans(domain, sans)
1281        .iter()
1282        .map(|d| {
1283            if method == "DNS" {
1284                let token = synth_dns_token(d);
1285                DomainValidation {
1286                    domain_name: d.clone(),
1287                    validation_status: "PENDING_VALIDATION".to_string(),
1288                    validation_method: "DNS".to_string(),
1289                    resource_record_name: Some(format!("_{token}.{d}.")),
1290                    resource_record_type: Some("CNAME".to_string()),
1291                    resource_record_value: Some(format!("_{token}.acm-validations.aws.")),
1292                }
1293            } else {
1294                DomainValidation {
1295                    domain_name: d.clone(),
1296                    validation_status: "PENDING_VALIDATION".to_string(),
1297                    validation_method: "EMAIL".to_string(),
1298                    resource_record_name: None,
1299                    resource_record_type: None,
1300                    resource_record_value: None,
1301                }
1302            }
1303        })
1304        .collect()
1305}
1306
1307/// Deterministic 32-char hex token derived from the domain so test
1308/// assertions on the validation record stay stable across runs.
1309fn synth_dns_token(domain: &str) -> String {
1310    let mut hasher = Sha256::new();
1311    hasher.update(domain.as_bytes());
1312    let digest = hasher.finalize();
1313    hex::encode(&digest[..16])
1314}
1315
1316fn decode_blob(value: Option<&Value>) -> Option<String> {
1317    let v = value?;
1318    if let Some(s) = v.as_str() {
1319        // Real SDKs base64-encode blob shapes over the wire. Decode the
1320        // outer encoding back to the underlying PEM text; if it isn't
1321        // base64 (which happens with ad-hoc curl tests), pass through.
1322        if let Ok(bytes) = base64::engine::general_purpose::STANDARD.decode(s) {
1323            if let Ok(text) = String::from_utf8(bytes) {
1324                return Some(text);
1325            }
1326        }
1327        return Some(s.to_string());
1328    }
1329    None
1330}
1331
1332/// Cheap CN scan for an imported PEM. Real ACM parses the X.509 cert
1333/// to extract the subject; fakecloud just looks for a `CN=` substring
1334/// or falls back to the PEM hash so the returned `DomainName` is at
1335/// least stable per input.
1336fn parse_cn_from_pem(pem: &str) -> Option<String> {
1337    pem.lines()
1338        .find_map(|line| line.split("CN=").nth(1))
1339        .map(|rest| {
1340            rest.split(['/', ',', '\n', ' '])
1341                .next()
1342                .unwrap_or("")
1343                .to_string()
1344        })
1345        .filter(|s| !s.is_empty())
1346}
1347
1348fn placeholder_cert_pem(arn: &str) -> String {
1349    // Fallback used only when an actually-issued cert was somehow
1350    // dropped. Kept distinguishable so callers don't silently treat
1351    // these as real X.509.
1352    let body = base64::engine::general_purpose::STANDARD.encode(arn.as_bytes());
1353    format!("-----BEGIN CERTIFICATE-----\n{body}\n-----END CERTIFICATE-----\n")
1354}
1355
1356fn placeholder_chain_pem(arn: &str) -> String {
1357    let body =
1358        base64::engine::general_purpose::STANDARD.encode(format!("chain-of-{arn}").as_bytes());
1359    format!("-----BEGIN CERTIFICATE-----\n{body}\n-----END CERTIFICATE-----\n")
1360}
1361
1362fn placeholder_key_pem(arn: &str) -> String {
1363    let body = base64::engine::general_purpose::STANDARD.encode(format!("key-of-{arn}").as_bytes());
1364    format!("-----BEGIN RSA PRIVATE KEY-----\n{body}\n-----END RSA PRIVATE KEY-----\n")
1365}
1366
1367/// Generate a real self-signed X.509 certificate + private key pair
1368/// for `domain_name` covering `sans`. Returns
1369/// `(certificate_pem, private_key_pem)`. Used by RequestCertificate
1370/// so the cert that GetCertificate / ExportCertificate hands back
1371/// is actually parseable as a real PEM-encoded X.509 (matching real
1372/// ACM's output format), not a base64-of-the-ARN placeholder.
1373fn generate_self_signed_cert(domain_name: &str, sans: &[String]) -> Option<(String, String)> {
1374    let mut all_names: Vec<String> = vec![domain_name.to_string()];
1375    for s in sans {
1376        if !all_names.contains(s) {
1377            all_names.push(s.clone());
1378        }
1379    }
1380    let cert = rcgen::generate_simple_self_signed(all_names).ok()?;
1381    Some((cert.cert.pem(), cert.key_pair.serialize_pem()))
1382}
1383
1384fn certificate_summary_json(c: &StoredCertificate) -> Value {
1385    let mut s = json!({
1386        "CertificateArn": c.arn,
1387        "DomainName": c.domain_name,
1388        "SubjectAlternativeNameSummaries": c.subject_alternative_names,
1389        "HasAdditionalSubjectAlternativeNames": false,
1390        "Status": c.status,
1391        "Type": c.cert_type,
1392        "KeyAlgorithm": c.key_algorithm,
1393        "KeyUsages": ["DIGITAL_SIGNATURE", "KEY_ENCIPHERMENT"],
1394        "ExtendedKeyUsages": ["TLS_WEB_SERVER_AUTHENTICATION", "TLS_WEB_CLIENT_AUTHENTICATION"],
1395        "InUse": !c.in_use_by.is_empty(),
1396        "Exported": false,
1397        "RenewalEligibility": c.renewal_eligibility,
1398        "NotBefore": c.not_before.timestamp() as f64,
1399        "NotAfter": c.not_after.timestamp() as f64,
1400        "CreatedAt": c.created_at.timestamp() as f64,
1401    });
1402    if let Some(t) = c.issued_at {
1403        s.as_object_mut()
1404            .unwrap()
1405            .insert("IssuedAt".to_string(), json!(t.timestamp() as f64));
1406    }
1407    if let Some(t) = c.imported_at {
1408        s.as_object_mut()
1409            .unwrap()
1410            .insert("ImportedAt".to_string(), json!(t.timestamp() as f64));
1411    }
1412    if let Some(t) = c.revoked_at {
1413        s.as_object_mut()
1414            .unwrap()
1415            .insert("RevokedAt".to_string(), json!(t.timestamp() as f64));
1416        if let Some(r) = &c.revocation_reason {
1417            s.as_object_mut()
1418                .unwrap()
1419                .insert("RevocationReason".to_string(), json!(r));
1420        }
1421    }
1422    if let Some(m) = &c.managed_by {
1423        s.as_object_mut()
1424            .unwrap()
1425            .insert("ManagedBy".to_string(), json!(m));
1426    }
1427    s
1428}
1429
1430fn certificate_detail_json(c: &StoredCertificate) -> Value {
1431    let mut d = json!({
1432        "CertificateArn": c.arn,
1433        "DomainName": c.domain_name,
1434        "SubjectAlternativeNames": c.subject_alternative_names,
1435        "Status": c.status,
1436        "Type": c.cert_type,
1437        "Serial": c.serial,
1438        "Subject": c.subject,
1439        "Issuer": c.issuer,
1440        "KeyAlgorithm": c.key_algorithm,
1441        "SignatureAlgorithm": c.signature_algorithm,
1442        "InUseBy": c.in_use_by,
1443        "RenewalEligibility": c.renewal_eligibility,
1444        "Options": {
1445            "CertificateTransparencyLoggingPreference":
1446                c.options.certificate_transparency_logging_preference,
1447            "Export": c.options.export,
1448        },
1449        "DomainValidationOptions": c
1450            .domain_validation
1451            .iter()
1452            .map(domain_validation_json)
1453            .collect::<Vec<_>>(),
1454        "NotBefore": c.not_before.timestamp() as f64,
1455        "NotAfter": c.not_after.timestamp() as f64,
1456        "CreatedAt": c.created_at.timestamp() as f64,
1457        "KeyUsages": [{"Name": "DIGITAL_SIGNATURE"}, {"Name": "KEY_ENCIPHERMENT"}],
1458        "ExtendedKeyUsages": [
1459            {"Name": "TLS_WEB_SERVER_AUTHENTICATION", "OID": "1.3.6.1.5.5.7.3.1"},
1460            {"Name": "TLS_WEB_CLIENT_AUTHENTICATION", "OID": "1.3.6.1.5.5.7.3.2"},
1461        ],
1462    });
1463    if let Some(t) = c.issued_at {
1464        d.as_object_mut()
1465            .unwrap()
1466            .insert("IssuedAt".to_string(), json!(t.timestamp() as f64));
1467    }
1468    if let Some(t) = c.imported_at {
1469        d.as_object_mut()
1470            .unwrap()
1471            .insert("ImportedAt".to_string(), json!(t.timestamp() as f64));
1472    }
1473    if let Some(t) = c.revoked_at {
1474        d.as_object_mut()
1475            .unwrap()
1476            .insert("RevokedAt".to_string(), json!(t.timestamp() as f64));
1477    }
1478    if let Some(r) = &c.revocation_reason {
1479        d.as_object_mut()
1480            .unwrap()
1481            .insert("RevocationReason".to_string(), json!(r));
1482    }
1483    if let Some(m) = &c.managed_by {
1484        d.as_object_mut()
1485            .unwrap()
1486            .insert("ManagedBy".to_string(), json!(m));
1487    }
1488    if let Some(ca) = &c.certificate_authority_arn {
1489        d.as_object_mut()
1490            .unwrap()
1491            .insert("CertificateAuthorityArn".to_string(), json!(ca));
1492    }
1493    if let Some(fr) = &c.failure_reason {
1494        d.as_object_mut()
1495            .unwrap()
1496            .insert("FailureReason".to_string(), json!(fr));
1497    }
1498    if let Some(rs) = &c.renewal_summary {
1499        let mut summary = json!({
1500            "RenewalStatus": rs.renewal_status,
1501            "DomainValidationOptions": rs
1502                .domain_validation
1503                .iter()
1504                .map(domain_validation_json)
1505                .collect::<Vec<_>>(),
1506            "UpdatedAt": rs.updated_at.timestamp() as f64,
1507        });
1508        if let Some(reason) = &rs.renewal_status_reason {
1509            summary
1510                .as_object_mut()
1511                .unwrap()
1512                .insert("RenewalStatusReason".to_string(), json!(reason));
1513        }
1514        d.as_object_mut()
1515            .unwrap()
1516            .insert("RenewalSummary".to_string(), summary);
1517    }
1518    d
1519}
1520
1521fn certificate_search_result_json(c: &StoredCertificate) -> Value {
1522    let san_objects: Vec<Value> = c
1523        .subject_alternative_names
1524        .iter()
1525        .map(|s| json!({ "DnsName": s }))
1526        .collect();
1527    let cn = c
1528        .subject
1529        .strip_prefix("CN=")
1530        .unwrap_or(c.subject.as_str())
1531        .to_string();
1532    json!({
1533        "CertificateArn": c.arn,
1534        "X509Attributes": {
1535            "Subject": { "CommonName": cn },
1536            "Issuer": { "CommonName": c.issuer },
1537            "SubjectAlternativeNames": san_objects,
1538            "KeyAlgorithm": c.key_algorithm,
1539            "KeyUsages": ["DIGITAL_SIGNATURE", "KEY_ENCIPHERMENT"],
1540            "ExtendedKeyUsages": ["TLS_WEB_SERVER_AUTHENTICATION", "TLS_WEB_CLIENT_AUTHENTICATION"],
1541            "SerialNumber": c.serial,
1542            "NotBefore": c.not_before.timestamp() as f64,
1543            "NotAfter": c.not_after.timestamp() as f64,
1544        },
1545        "CertificateMetadata": {
1546            "AcmCertificateMetadata": {
1547                "Status": c.status,
1548                "Type": c.cert_type,
1549                "InUse": !c.in_use_by.is_empty(),
1550                "Exported": false,
1551                "RenewalEligibility": c.renewal_eligibility,
1552                "CreatedAt": c.created_at.timestamp() as f64,
1553                "ManagedBy": c.managed_by.clone().unwrap_or_default(),
1554                "ValidationMethod": c.validation_method.clone().unwrap_or_default(),
1555            },
1556        },
1557    })
1558}
1559
1560fn domain_validation_json(v: &DomainValidation) -> Value {
1561    let mut out = json!({
1562        "DomainName": v.domain_name,
1563        "ValidationStatus": v.validation_status,
1564        "ValidationMethod": v.validation_method,
1565    });
1566    if let (Some(name), Some(rtype), Some(value)) = (
1567        &v.resource_record_name,
1568        &v.resource_record_type,
1569        &v.resource_record_value,
1570    ) {
1571        out.as_object_mut().unwrap().insert(
1572            "ResourceRecord".to_string(),
1573            json!({
1574                "Name": name,
1575                "Type": rtype,
1576                "Value": value,
1577            }),
1578        );
1579    }
1580    out
1581}
1582
1583/// Encrypt a PEM-encoded PKCS#8 private key with a passphrase,
1584/// producing a PEM file with `BEGIN ENCRYPTED PRIVATE KEY` headers.
1585/// This matches what real ACM `ExportCertificate` returns: a PKCS#8 v2
1586/// `EncryptedPrivateKeyInfo` using PBES2 (PBKDF2 + AES-256-CBC).
1587///
1588/// The resulting PEM is decryptable with anything that handles modern
1589/// PKCS#8 encrypted keys: `openssl pkcs8 -in key.pem -passin pass:...`,
1590/// Python's `cryptography.hazmat.primitives.serialization`,
1591/// `rsa::pkcs8::DecodePrivateKey::from_pkcs8_encrypted_pem`, etc.
1592fn encrypt_private_key_pem(key_pem: &str, passphrase: &[u8]) -> Result<String, String> {
1593    use pkcs8::{pkcs5::pbes2, LineEnding, PrivateKeyInfo};
1594
1595    // Strip the PEM headers and base64-decode the inner DER. Real keys
1596    // (rcgen, openssl) emit `BEGIN PRIVATE KEY` for PKCS#8 v1; we don't
1597    // support encrypting `BEGIN RSA PRIVATE KEY` (PKCS#1) or other
1598    // legacy SEC1 forms here because rcgen always produces PKCS#8.
1599    let der = pem_decode_private_key(key_pem)?;
1600
1601    // PBES2 parameters: 16-byte random salt, 2048 PBKDF2-SHA256
1602    // iterations (matches OpenSSL defaults for `openssl pkcs8 -topk8`),
1603    // AES-256-CBC with a random 16-byte IV.
1604    let mut salt = [0u8; 16];
1605    let mut iv = [0u8; 16];
1606    rand::RngCore::fill_bytes(&mut rand::thread_rng(), &mut salt);
1607    rand::RngCore::fill_bytes(&mut rand::thread_rng(), &mut iv);
1608    let params = pbes2::Parameters::pbkdf2_sha256_aes256cbc(2048, &salt, &iv)
1609        .map_err(|e| format!("invalid PBES2 parameters: {e}"))?;
1610
1611    let pki = PrivateKeyInfo::try_from(der.as_slice())
1612        .map_err(|e| format!("private key is not valid PKCS#8 DER: {e}"))?;
1613    let encrypted = pki
1614        .encrypt_with_params(params, passphrase)
1615        .map_err(|e| format!("PKCS#8 encryption failed: {e}"))?;
1616
1617    encrypted
1618        .to_pem("ENCRYPTED PRIVATE KEY", LineEnding::LF)
1619        .map(|s| s.to_string())
1620        .map_err(|e| format!("PEM encoding failed: {e}"))
1621}
1622
1623/// Decode a PEM `BEGIN PRIVATE KEY` block to its inner DER bytes.
1624/// Returns an error if the block is missing, has the wrong label, or
1625/// the body is not valid base64.
1626fn pem_decode_private_key(pem: &str) -> Result<Vec<u8>, String> {
1627    let begin = pem.find("-----BEGIN ").ok_or("missing BEGIN line")?;
1628    let after_begin = &pem[begin + 11..];
1629    let dash = after_begin.find("-----").ok_or("malformed BEGIN line")?;
1630    let label = after_begin[..dash].trim();
1631    if label != "PRIVATE KEY" {
1632        return Err(format!(
1633            "expected `BEGIN PRIVATE KEY` (PKCS#8), got `BEGIN {label}`"
1634        ));
1635    }
1636    let end = pem
1637        .find("-----END PRIVATE KEY-----")
1638        .ok_or("missing END line")?;
1639    let body_start = begin + 11 + dash + 5;
1640    let nl = pem[body_start..]
1641        .find('\n')
1642        .ok_or("missing newline after BEGIN")?;
1643    let body: String = pem[body_start + nl + 1..end]
1644        .chars()
1645        .filter(|c| !c.is_whitespace())
1646        .collect();
1647    base64::engine::general_purpose::STANDARD
1648        .decode(body.as_bytes())
1649        .map_err(|e| format!("PEM body is not valid base64: {e}"))
1650}
1651
1652#[cfg(test)]
1653mod tests {
1654    use super::*;
1655
1656    #[test]
1657    fn generate_self_signed_cert_returns_real_pem() {
1658        let (cert_pem, key_pem) =
1659            generate_self_signed_cert("example.com", &["www.example.com".to_string()])
1660                .expect("rcgen should produce a self-signed cert");
1661        assert!(
1662            cert_pem.starts_with("-----BEGIN CERTIFICATE-----"),
1663            "expected real PEM cert, got {cert_pem:.80}"
1664        );
1665        assert!(cert_pem.ends_with("-----END CERTIFICATE-----\n"));
1666        assert!(key_pem.contains("-----BEGIN PRIVATE KEY-----"));
1667        // Substantially longer than the placeholder (= base64-of-domain).
1668        assert!(cert_pem.len() > 400, "real cert PEM should be >400 chars");
1669    }
1670
1671    #[tokio::test]
1672    async fn request_certificate_stores_real_pem_and_key() {
1673        let svc = AcmService::default();
1674        let req = AwsRequest {
1675            service: "acm".to_string(),
1676            action: "RequestCertificate".to_string(),
1677            region: "us-east-1".to_string(),
1678            account_id: "123456789012".to_string(),
1679            request_id: "rid".to_string(),
1680            headers: http::HeaderMap::new(),
1681            query_params: std::collections::HashMap::new(),
1682            body: bytes::Bytes::from(
1683                serde_json::to_vec(&json!({"DomainName": "example.com"})).unwrap(),
1684            ),
1685            body_stream: parking_lot::Mutex::new(None),
1686            path_segments: vec![],
1687            raw_path: "/".to_string(),
1688            raw_query: String::new(),
1689            method: http::Method::POST,
1690            is_query_protocol: false,
1691            access_key_id: None,
1692            principal: None,
1693        };
1694        let resp = svc.handle(req).await.unwrap();
1695        let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
1696        let arn = body["CertificateArn"].as_str().unwrap();
1697        let st = svc.state.read();
1698        let cert = st
1699            .accounts
1700            .get("123456789012")
1701            .unwrap()
1702            .certificates
1703            .get(arn)
1704            .unwrap();
1705        let cert_pem = cert.certificate_pem.as_deref().unwrap();
1706        let key_pem = cert.private_key_pem.as_deref().unwrap();
1707        assert!(cert_pem.starts_with("-----BEGIN CERTIFICATE-----"));
1708        assert!(key_pem.contains("-----BEGIN PRIVATE KEY-----"));
1709        assert!(cert_pem.len() > 400);
1710    }
1711
1712    #[test]
1713    fn encrypt_private_key_pem_emits_pkcs8_v2_pem() {
1714        let (_cert, key_pem) =
1715            generate_self_signed_cert("example.com", &[]).expect("rcgen produces a key");
1716        let out = encrypt_private_key_pem(&key_pem, b"hunter2").expect("encryption succeeds");
1717        assert!(
1718            out.starts_with("-----BEGIN ENCRYPTED PRIVATE KEY-----\n"),
1719            "expected PKCS#8 v2 envelope, got {out:.80}"
1720        );
1721        assert!(out
1722            .trim_end()
1723            .ends_with("-----END ENCRYPTED PRIVATE KEY-----"));
1724        // The plaintext PEM body should not appear in the encrypted
1725        // output — sanity check that we actually encrypted.
1726        let plain_body: String = key_pem
1727            .lines()
1728            .filter(|l| !l.starts_with("-----"))
1729            .collect();
1730        assert!(!plain_body.is_empty());
1731        assert!(!out.contains(&plain_body));
1732    }
1733
1734    #[test]
1735    fn encrypt_private_key_pem_round_trips_via_pkcs8_decoder() {
1736        use pkcs8::{DecodePrivateKey, EncodePrivateKey, LineEnding};
1737
1738        let mut rng = rand::thread_rng();
1739        let original = rsa::RsaPrivateKey::new(&mut rng, 2048).expect("rsa keygen");
1740        let key_pem = original
1741            .to_pkcs8_pem(LineEnding::LF)
1742            .expect("pkcs8 pem encode")
1743            .to_string();
1744        let passphrase = b"correct horse battery staple";
1745
1746        let encrypted = encrypt_private_key_pem(&key_pem, passphrase).unwrap();
1747        assert!(encrypted.contains("BEGIN ENCRYPTED PRIVATE KEY"));
1748
1749        let recovered = rsa::RsaPrivateKey::from_pkcs8_encrypted_pem(&encrypted, passphrase)
1750            .expect("decryption + PKCS#8 parse");
1751        assert_eq!(original, recovered);
1752    }
1753
1754    fn make_req(action: &str, body: Value) -> AwsRequest {
1755        AwsRequest {
1756            service: "acm".to_string(),
1757            action: action.to_string(),
1758            region: "us-east-1".to_string(),
1759            account_id: "123456789012".to_string(),
1760            request_id: "rid".to_string(),
1761            headers: http::HeaderMap::new(),
1762            query_params: std::collections::HashMap::new(),
1763            body: bytes::Bytes::from(serde_json::to_vec(&body).unwrap()),
1764            body_stream: parking_lot::Mutex::new(None),
1765            path_segments: vec![],
1766            raw_path: "/".to_string(),
1767            raw_query: String::new(),
1768            method: http::Method::POST,
1769            is_query_protocol: false,
1770            access_key_id: None,
1771            principal: None,
1772        }
1773    }
1774
1775    async fn make_exportable_cert(svc: &AcmService) -> String {
1776        let req = make_req(
1777            "RequestCertificate",
1778            json!({
1779                "DomainName": "example.com",
1780                "Options": {"Export": "ENABLED"},
1781            }),
1782        );
1783        let resp = svc.handle(req).await.unwrap();
1784        let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
1785        body["CertificateArn"].as_str().unwrap().to_string()
1786    }
1787
1788    #[tokio::test]
1789    async fn export_certificate_emits_passphrase_encrypted_pem() {
1790        let svc = AcmService::default();
1791        let arn = make_exportable_cert(&svc).await;
1792        let original_key_pem = svc
1793            .state
1794            .read()
1795            .accounts
1796            .get("123456789012")
1797            .unwrap()
1798            .certificates
1799            .get(&arn)
1800            .unwrap()
1801            .private_key_pem
1802            .clone()
1803            .unwrap();
1804
1805        let passphrase = b"hunter2";
1806        let passphrase_b64 = base64::engine::general_purpose::STANDARD.encode(passphrase);
1807        let export = make_req(
1808            "ExportCertificate",
1809            json!({"CertificateArn": arn, "Passphrase": passphrase_b64}),
1810        );
1811        let export_resp = svc.handle(export).await.unwrap();
1812        let export_json: Value = serde_json::from_slice(export_resp.body.expect_bytes()).unwrap();
1813        let private_key = export_json["PrivateKey"].as_str().unwrap();
1814        assert!(
1815            private_key.contains("BEGIN ENCRYPTED PRIVATE KEY"),
1816            "expected PKCS#8 v2 PEM, got {private_key}"
1817        );
1818        assert!(private_key.contains("END ENCRYPTED PRIVATE KEY"));
1819        // Round-trip: decrypt with the same passphrase and confirm we
1820        // recover the same private key bytes that ACM stored.
1821        let original_inner_der =
1822            pem_decode_private_key(&original_key_pem).expect("decode original PEM");
1823        let original_pki_bytes = pkcs8::PrivateKeyInfo::try_from(original_inner_der.as_slice())
1824            .map(|p| p.private_key.to_vec())
1825            .expect("parse original PKCS#8");
1826        let encrypted_der =
1827            pem_decode_encrypted_private_key(private_key).expect("decode encrypted PEM");
1828        let decrypted_doc = pkcs8::EncryptedPrivateKeyInfo::try_from(encrypted_der.as_slice())
1829            .expect("parse encrypted PKCS#8")
1830            .decrypt(passphrase)
1831            .expect("decrypt with passphrase");
1832        let decrypted_pki = pkcs8::PrivateKeyInfo::try_from(decrypted_doc.as_bytes())
1833            .expect("parse decrypted PKCS#8");
1834        assert_eq!(decrypted_pki.private_key, original_pki_bytes.as_slice());
1835    }
1836
1837    #[tokio::test]
1838    async fn export_certificate_without_passphrase_returns_plain_pem() {
1839        let svc = AcmService::default();
1840        let arn = make_exportable_cert(&svc).await;
1841        let export_resp = svc
1842            .handle(make_req(
1843                "ExportCertificate",
1844                json!({"CertificateArn": arn}),
1845            ))
1846            .await
1847            .unwrap();
1848        let export_json: Value = serde_json::from_slice(export_resp.body.expect_bytes()).unwrap();
1849        let private_key = export_json["PrivateKey"].as_str().unwrap();
1850        assert!(
1851            private_key.contains("-----BEGIN PRIVATE KEY-----"),
1852            "expected plain PKCS#8 PEM, got {private_key}"
1853        );
1854        assert!(!private_key.contains("ENCRYPTED PRIVATE KEY"));
1855    }
1856
1857    #[tokio::test]
1858    async fn export_certificate_with_empty_passphrase_returns_plain_pem() {
1859        let svc = AcmService::default();
1860        let arn = make_exportable_cert(&svc).await;
1861        let export_resp = svc
1862            .handle(make_req(
1863                "ExportCertificate",
1864                json!({"CertificateArn": arn, "Passphrase": ""}),
1865            ))
1866            .await
1867            .unwrap();
1868        let export_json: Value = serde_json::from_slice(export_resp.body.expect_bytes()).unwrap();
1869        let private_key = export_json["PrivateKey"].as_str().unwrap();
1870        assert!(private_key.contains("-----BEGIN PRIVATE KEY-----"));
1871        assert!(!private_key.contains("ENCRYPTED PRIVATE KEY"));
1872    }
1873
1874    #[tokio::test]
1875    async fn export_certificate_rejects_non_base64_passphrase() {
1876        let svc = AcmService::default();
1877        let resp = svc
1878            .handle(make_req(
1879                "RequestCertificate",
1880                json!({"DomainName": "example.com"}),
1881            ))
1882            .await
1883            .unwrap();
1884        let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
1885        let arn = body["CertificateArn"].as_str().unwrap().to_string();
1886        let export = make_req(
1887            "ExportCertificate",
1888            json!({"CertificateArn": arn, "Passphrase": "not!base64!@#$"}),
1889        );
1890        let err = match svc.handle(export).await {
1891            Ok(_) => panic!("expected error for non-base64 passphrase"),
1892            Err(e) => e,
1893        };
1894        assert!(format!("{err:?}").contains("Passphrase"));
1895    }
1896
1897    fn pem_decode_encrypted_private_key(pem: &str) -> Result<Vec<u8>, String> {
1898        let begin = "-----BEGIN ENCRYPTED PRIVATE KEY-----";
1899        let end = "-----END ENCRYPTED PRIVATE KEY-----";
1900        let begin_idx = pem.find(begin).ok_or("missing BEGIN")?;
1901        let after = &pem[begin_idx + begin.len()..];
1902        let end_idx = after.find(end).ok_or("missing END")?;
1903        let body: String = after[..end_idx]
1904            .chars()
1905            .filter(|c| !c.is_whitespace())
1906            .collect();
1907        base64::engine::general_purpose::STANDARD
1908            .decode(body.as_bytes())
1909            .map_err(|e| format!("base64: {e}"))
1910    }
1911
1912    #[tokio::test]
1913    async fn describe_certificate_observes_auto_issue_transition() {
1914        // After the auto-issue tick fires, successive describes should
1915        // pick up Status=ISSUED, IssuedAt, RenewalEligibility=ELIGIBLE,
1916        // and a populated RenewalSummary without any extra prodding.
1917        let svc = AcmService::default()
1918            .with_pending_validation_delay(std::time::Duration::from_millis(50));
1919        let resp = svc
1920            .handle(make_req(
1921                "RequestCertificate",
1922                json!({"DomainName": "example.com", "ValidationMethod": "DNS"}),
1923            ))
1924            .await
1925            .unwrap();
1926        let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
1927        let arn = body["CertificateArn"].as_str().unwrap().to_string();
1928
1929        // Immediate describe sees PENDING_VALIDATION + ELIGIBILITY
1930        // INELIGIBLE.
1931        let early = svc
1932            .handle(make_req(
1933                "DescribeCertificate",
1934                json!({"CertificateArn": arn}),
1935            ))
1936            .await
1937            .unwrap();
1938        let early: Value = serde_json::from_slice(early.body.expect_bytes()).unwrap();
1939        assert_eq!(early["Certificate"]["Status"], "PENDING_VALIDATION");
1940        assert_eq!(early["Certificate"]["RenewalEligibility"], "INELIGIBLE");
1941        assert!(early["Certificate"].get("RenewalSummary").is_none());
1942
1943        // Poll up to 2s for the auto-issue tick.
1944        let mut last: Value = Value::Null;
1945        for _ in 0..40 {
1946            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1947            let resp = svc
1948                .handle(make_req(
1949                    "DescribeCertificate",
1950                    json!({"CertificateArn": arn}),
1951                ))
1952                .await
1953                .unwrap();
1954            let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
1955            if body["Certificate"]["Status"] == "ISSUED" {
1956                last = body;
1957                break;
1958            }
1959        }
1960        assert_eq!(last["Certificate"]["Status"], "ISSUED");
1961        assert_eq!(last["Certificate"]["RenewalEligibility"], "ELIGIBLE");
1962        let rs = &last["Certificate"]["RenewalSummary"];
1963        assert_eq!(rs["RenewalStatus"], "PENDING_AUTO_RENEWAL");
1964        assert!(rs["UpdatedAt"].as_f64().unwrap() > 0.0);
1965    }
1966
1967    #[tokio::test]
1968    async fn request_certificate_emits_parseable_pem() {
1969        let svc = AcmService::default();
1970        let resp = svc
1971            .handle(make_req(
1972                "RequestCertificate",
1973                json!({"DomainName": "example.com"}),
1974            ))
1975            .await
1976            .unwrap();
1977        let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
1978        let arn = body["CertificateArn"].as_str().unwrap().to_string();
1979
1980        let resp = svc
1981            .handle(make_req("GetCertificate", json!({"CertificateArn": arn})))
1982            .await
1983            .unwrap();
1984        let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
1985        let cert_pem = body["Certificate"].as_str().unwrap();
1986        assert!(
1987            cert_pem.starts_with("-----BEGIN CERTIFICATE-----"),
1988            "expected real PEM cert header, got {cert_pem:.80}"
1989        );
1990        assert!(cert_pem.trim_end().ends_with("-----END CERTIFICATE-----"));
1991        // Real X.509 base64 body is much larger than the legacy
1992        // base64-of-ARN placeholder (which was ~80 chars total).
1993        assert!(
1994            cert_pem.len() > 400,
1995            "expected real X.509 PEM, got placeholder-sized blob"
1996        );
1997        // Sanity-check we didn't smuggle the ARN body back in via the
1998        // old placeholder code path.
1999        assert!(!cert_pem.contains(arn.as_str()));
2000    }
2001
2002    #[tokio::test]
2003    async fn request_certificate_includes_san() {
2004        let svc = AcmService::default();
2005        let resp = svc
2006            .handle(make_req(
2007                "RequestCertificate",
2008                json!({
2009                    "DomainName": "example.com",
2010                    "SubjectAlternativeNames": ["api.example.com", "www.example.com"],
2011                }),
2012            ))
2013            .await
2014            .unwrap();
2015        let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
2016        let arn = body["CertificateArn"].as_str().unwrap().to_string();
2017
2018        let resp = svc
2019            .handle(make_req("GetCertificate", json!({"CertificateArn": arn})))
2020            .await
2021            .unwrap();
2022        let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
2023        let cert_pem = body["Certificate"].as_str().unwrap();
2024        assert!(cert_pem.starts_with("-----BEGIN CERTIFICATE-----"));
2025        assert!(cert_pem.trim_end().ends_with("-----END CERTIFICATE-----"));
2026
2027        // Decode the PEM body and search the DER bytes for the SAN dNSName
2028        // octets. rcgen emits SANs as IA5String entries inside the
2029        // SubjectAltName extension, so the raw domain bytes are present.
2030        let body_b64: String = cert_pem
2031            .lines()
2032            .filter(|l| !l.starts_with("-----"))
2033            .collect::<Vec<_>>()
2034            .join("");
2035        let der = base64::engine::general_purpose::STANDARD
2036            .decode(&body_b64)
2037            .expect("cert body is valid base64");
2038        for san in ["example.com", "api.example.com", "www.example.com"] {
2039            assert!(
2040                der.windows(san.len()).any(|w| w == san.as_bytes()),
2041                "expected SAN {san} embedded in DER"
2042            );
2043        }
2044    }
2045
2046    #[tokio::test]
2047    async fn request_certificate_starts_in_pending_validation() {
2048        let svc = AcmService::default();
2049        let resp = svc
2050            .handle(make_req(
2051                "RequestCertificate",
2052                json!({"DomainName": "example.com", "ValidationMethod": "DNS"}),
2053            ))
2054            .await
2055            .unwrap();
2056        let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
2057        let arn = body["CertificateArn"].as_str().unwrap().to_string();
2058        let st = svc.state.read();
2059        let cert = st
2060            .accounts
2061            .get("123456789012")
2062            .unwrap()
2063            .certificates
2064            .get(&arn)
2065            .unwrap();
2066        assert_eq!(cert.status, "PENDING_VALIDATION");
2067        assert!(cert.issued_at.is_none());
2068    }
2069
2070    #[tokio::test]
2071    async fn set_certificate_status_to_issued_via_admin() {
2072        let svc = AcmService::default();
2073        let resp = svc
2074            .handle(make_req(
2075                "RequestCertificate",
2076                json!({"DomainName": "admin.example.com"}),
2077            ))
2078            .await
2079            .unwrap();
2080        let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
2081        let arn = body["CertificateArn"].as_str().unwrap().to_string();
2082
2083        assert!(svc.set_certificate_status(&arn, "ISSUED", None));
2084        let st = svc.state.read();
2085        let cert = st
2086            .accounts
2087            .get("123456789012")
2088            .unwrap()
2089            .certificates
2090            .get(&arn)
2091            .unwrap();
2092        assert_eq!(cert.status, "ISSUED");
2093        assert!(cert.issued_at.is_some());
2094        for dv in &cert.domain_validation {
2095            assert_eq!(dv.validation_status, "SUCCESS");
2096        }
2097    }
2098
2099    #[tokio::test]
2100    async fn set_certificate_status_unknown_arn_returns_false() {
2101        let svc = AcmService::default();
2102        assert!(!svc.set_certificate_status("does-not-exist", "ISSUED", None));
2103    }
2104
2105    #[tokio::test]
2106    async fn auto_issue_tick_transitions_to_issued() {
2107        let svc = AcmService::default()
2108            .with_pending_validation_delay(std::time::Duration::from_millis(50));
2109        let resp = svc
2110            .handle(make_req(
2111                "RequestCertificate",
2112                json!({"DomainName": "auto.example.com", "ValidationMethod": "DNS"}),
2113            ))
2114            .await
2115            .unwrap();
2116        let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
2117        let arn = body["CertificateArn"].as_str().unwrap().to_string();
2118
2119        tokio::time::sleep(std::time::Duration::from_millis(200)).await;
2120
2121        let st = svc.state.read();
2122        let cert = st
2123            .accounts
2124            .get("123456789012")
2125            .unwrap()
2126            .certificates
2127            .get(&arn)
2128            .unwrap();
2129        assert_eq!(cert.status, "ISSUED");
2130        assert!(cert.issued_at.is_some());
2131        assert_eq!(cert.renewal_eligibility, "ELIGIBLE");
2132        let rs = cert.renewal_summary.as_ref().expect("renewal summary set");
2133        assert_eq!(rs.renewal_status, "PENDING_AUTO_RENEWAL");
2134    }
2135
2136    #[tokio::test]
2137    async fn email_validation_stays_pending_until_approve() {
2138        // EMAIL certs intentionally do NOT trigger the auto-issue tick:
2139        // real ACM only flips them once the user clicks the approval
2140        // link. fakecloud routes the approval through
2141        // `approve_certificate`.
2142        let svc = AcmService::default()
2143            .with_pending_validation_delay(std::time::Duration::from_millis(20));
2144        let resp = svc
2145            .handle(make_req(
2146                "RequestCertificate",
2147                json!({
2148                    "DomainName": "email.example.com",
2149                    "ValidationMethod": "EMAIL",
2150                }),
2151            ))
2152            .await
2153            .unwrap();
2154        let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
2155        let arn = body["CertificateArn"].as_str().unwrap().to_string();
2156
2157        // Wait well past the DNS auto-issue delay; EMAIL must stay
2158        // PENDING_VALIDATION because no tick was scheduled.
2159        tokio::time::sleep(std::time::Duration::from_millis(150)).await;
2160        {
2161            let st = svc.state.read();
2162            let cert = st
2163                .accounts
2164                .get("123456789012")
2165                .unwrap()
2166                .certificates
2167                .get(&arn)
2168                .unwrap();
2169            assert_eq!(cert.status, "PENDING_VALIDATION");
2170            assert!(cert.issued_at.is_none());
2171            assert!(cert.renewal_summary.is_none());
2172        }
2173
2174        assert!(svc.approve_certificate(&arn));
2175        let st = svc.state.read();
2176        let cert = st
2177            .accounts
2178            .get("123456789012")
2179            .unwrap()
2180            .certificates
2181            .get(&arn)
2182            .unwrap();
2183        assert_eq!(cert.status, "ISSUED");
2184        assert_eq!(cert.renewal_eligibility, "ELIGIBLE");
2185        for dv in &cert.domain_validation {
2186            assert_eq!(dv.validation_status, "SUCCESS");
2187        }
2188        assert!(cert.renewal_summary.is_some());
2189    }
2190
2191    #[tokio::test]
2192    async fn renew_certificate_refreshes_renewal_summary() {
2193        let svc = AcmService::default()
2194            .with_pending_validation_delay(std::time::Duration::from_millis(20));
2195        let resp = svc
2196            .handle(make_req(
2197                "RequestCertificate",
2198                json!({"DomainName": "renew.example.com", "ValidationMethod": "DNS"}),
2199            ))
2200            .await
2201            .unwrap();
2202        let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
2203        let arn = body["CertificateArn"].as_str().unwrap().to_string();
2204
2205        tokio::time::sleep(std::time::Duration::from_millis(80)).await;
2206
2207        let resp = svc
2208            .handle(make_req("RenewCertificate", json!({"CertificateArn": arn})))
2209            .await
2210            .unwrap();
2211        assert_eq!(resp.status, http::StatusCode::OK);
2212
2213        let st = svc.state.read();
2214        let cert = st
2215            .accounts
2216            .get("123456789012")
2217            .unwrap()
2218            .certificates
2219            .get(&arn)
2220            .unwrap();
2221        assert_eq!(cert.status, "ISSUED");
2222        let rs = cert.renewal_summary.as_ref().expect("renewal summary set");
2223        assert_eq!(rs.renewal_status, "SUCCESS");
2224        assert_eq!(rs.domain_validation.len(), cert.domain_validation.len());
2225    }
2226
2227    #[test]
2228    fn auto_issue_delay_default_when_env_unset() {
2229        // Other tests don't touch FAKECLOUD_ACM_AUTO_ISSUE_SECS, so
2230        // reading it here while running serially with `cargo test`
2231        // returns the documented default. We use a constant to guard
2232        // against accidental drift in `DEFAULT_AUTO_ISSUE_SECS`.
2233        if std::env::var("FAKECLOUD_ACM_AUTO_ISSUE_SECS").is_err() {
2234            assert_eq!(
2235                auto_issue_delay_from_env(),
2236                std::time::Duration::from_secs(DEFAULT_AUTO_ISSUE_SECS),
2237            );
2238        }
2239    }
2240
2241    #[tokio::test]
2242    async fn set_certificate_status_failed_records_reason() {
2243        let svc = AcmService::default();
2244        let resp = svc
2245            .handle(make_req(
2246                "RequestCertificate",
2247                json!({"DomainName": "fail.example.com"}),
2248            ))
2249            .await
2250            .unwrap();
2251        let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
2252        let arn = body["CertificateArn"].as_str().unwrap().to_string();
2253        assert!(svc.set_certificate_status(&arn, "FAILED", Some("DNS lookup error".to_string())));
2254        let st = svc.state.read();
2255        let cert = st
2256            .accounts
2257            .get("123456789012")
2258            .unwrap()
2259            .certificates
2260            .get(&arn)
2261            .unwrap();
2262        assert_eq!(cert.status, "FAILED");
2263        assert_eq!(cert.failure_reason.as_deref(), Some("DNS lookup error"));
2264    }
2265
2266    #[tokio::test]
2267    async fn request_certificate_private_key_pem_is_valid() {
2268        let svc = AcmService::default();
2269        let resp = svc
2270            .handle(make_req(
2271                "RequestCertificate",
2272                json!({"DomainName": "key.example.com"}),
2273            ))
2274            .await
2275            .unwrap();
2276        let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
2277        let arn = body["CertificateArn"].as_str().unwrap().to_string();
2278
2279        let st = svc.state.read();
2280        let cert = st
2281            .accounts
2282            .get("123456789012")
2283            .unwrap()
2284            .certificates
2285            .get(&arn)
2286            .unwrap();
2287        let key_pem = cert
2288            .private_key_pem
2289            .as_deref()
2290            .expect("RequestCertificate should populate a real private key");
2291        let starts_pkcs8 = key_pem.starts_with("-----BEGIN PRIVATE KEY-----");
2292        let starts_rsa = key_pem.starts_with("-----BEGIN RSA PRIVATE KEY-----");
2293        assert!(
2294            starts_pkcs8 || starts_rsa,
2295            "expected PKCS#8 or RSA private key header, got {key_pem:.80}"
2296        );
2297        assert!(
2298            key_pem.trim_end().ends_with("-----END PRIVATE KEY-----")
2299                || key_pem
2300                    .trim_end()
2301                    .ends_with("-----END RSA PRIVATE KEY-----")
2302        );
2303        assert!(key_pem.len() > 200);
2304    }
2305
2306    // bug-audit 2026-05-28, 1.5: SearchCertificates must honor the
2307    // CertificateStatuses filter and apply SortBy/SortOrder (previously only
2308    // KeyTypes was applied and the order was hardcoded).
2309    #[tokio::test]
2310    async fn search_certificates_filters_by_status_and_sorts() {
2311        let svc = AcmService::default();
2312        let mut arn: std::collections::HashMap<&str, String> = std::collections::HashMap::new();
2313        for d in ["a.example.com", "b.example.com", "c.example.com"] {
2314            let resp = svc
2315                .handle(make_req("RequestCertificate", json!({ "DomainName": d })))
2316                .await
2317                .unwrap();
2318            let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
2319            arn.insert(d, body["CertificateArn"].as_str().unwrap().to_string());
2320        }
2321
2322        // Stamp deterministic statuses + creation times: a oldest, c newest.
2323        {
2324            let mut state = svc.state.write();
2325            let certs = &mut state.accounts.get_mut("123456789012").unwrap().certificates;
2326            let now = chrono::Utc::now();
2327            for c in certs.values_mut() {
2328                match c.domain_name.as_str() {
2329                    "a.example.com" => {
2330                        c.status = "ISSUED".to_string();
2331                        c.created_at = now - chrono::Duration::hours(2);
2332                    }
2333                    "b.example.com" => {
2334                        c.status = "PENDING_VALIDATION".to_string();
2335                        c.created_at = now - chrono::Duration::hours(1);
2336                    }
2337                    _ => {
2338                        c.status = "ISSUED".to_string();
2339                        c.created_at = now;
2340                    }
2341                }
2342            }
2343        }
2344
2345        let domains = |body: &Value| -> Vec<String> {
2346            body["Results"]
2347                .as_array()
2348                .unwrap()
2349                .iter()
2350                .map(|r| r["CertificateArn"].as_str().unwrap().to_string())
2351                .collect()
2352        };
2353
2354        // CertificateStatuses filter keeps only ISSUED (a + c).
2355        let resp = svc
2356            .handle(make_req(
2357                "SearchCertificates",
2358                json!({ "CertificateStatuses": ["ISSUED"] }),
2359            ))
2360            .await
2361            .unwrap();
2362        let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
2363        let mut issued = domains(&body);
2364        issued.sort();
2365        let mut want = vec![arn["a.example.com"].clone(), arn["c.example.com"].clone()];
2366        want.sort();
2367        assert_eq!(issued, want);
2368
2369        // SortBy CREATED_AT ASCENDING -> oldest first.
2370        let resp = svc
2371            .handle(make_req(
2372                "SearchCertificates",
2373                json!({ "SortBy": "CREATED_AT", "SortOrder": "ASCENDING" }),
2374            ))
2375            .await
2376            .unwrap();
2377        let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
2378        assert_eq!(
2379            domains(&body),
2380            vec![
2381                arn["a.example.com"].clone(),
2382                arn["b.example.com"].clone(),
2383                arn["c.example.com"].clone(),
2384            ]
2385        );
2386
2387        // DESCENDING -> newest first (reverse).
2388        let resp = svc
2389            .handle(make_req(
2390                "SearchCertificates",
2391                json!({ "SortBy": "CREATED_AT", "SortOrder": "DESCENDING" }),
2392            ))
2393            .await
2394            .unwrap();
2395        let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
2396        assert_eq!(
2397            domains(&body),
2398            vec![
2399                arn["c.example.com"].clone(),
2400                arn["b.example.com"].clone(),
2401                arn["a.example.com"].clone(),
2402            ]
2403        );
2404    }
2405}