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        let key_types: Vec<String> = body
1062            .get("FilterStatement")
1063            .and_then(|f| f.get("Filter"))
1064            .and_then(|f| f.get("KeyTypes"))
1065            .and_then(Value::as_array)
1066            .map(|v| {
1067                v.iter()
1068                    .filter_map(|s| s.as_str().map(|s| s.to_string()))
1069                    .collect()
1070            })
1071            .unwrap_or_default();
1072
1073        let state = self.state.read();
1074        let mut all: Vec<StoredCertificate> = state
1075            .accounts
1076            .get(&req.account_id)
1077            .map(|a| a.certificates.values().cloned().collect())
1078            .unwrap_or_default();
1079        drop(state);
1080        all.sort_by(|a, b| a.arn.cmp(&b.arn));
1081        if !key_types.is_empty() {
1082            all.retain(|c| key_types.contains(&c.key_algorithm));
1083        }
1084        let start = next_token
1085            .and_then(|t| t.parse::<usize>().ok())
1086            .unwrap_or(0);
1087        let end = (start + max_results).min(all.len());
1088        let page: Vec<&StoredCertificate> = all.iter().skip(start).take(max_results).collect();
1089        let next = if end < all.len() {
1090            Some(end.to_string())
1091        } else {
1092            None
1093        };
1094        let mut response = json!({
1095            "Results": page
1096                .iter()
1097                .map(|c| certificate_search_result_json(c))
1098                .collect::<Vec<_>>(),
1099        });
1100        if let Some(t) = next {
1101            response
1102                .as_object_mut()
1103                .unwrap()
1104                .insert("NextToken".to_string(), Value::String(t));
1105        }
1106        Ok(AwsResponse::ok_json(response))
1107    }
1108}
1109
1110// ─── Helpers ────────────────────────────────────────────────────────
1111
1112fn account_mut<'a>(state: &'a mut AcmAccounts, account_id: &str) -> &'a mut AccountState {
1113    state.accounts.entry(account_id.to_string()).or_default()
1114}
1115
1116fn require_certificate_arn(req: &AwsRequest) -> Result<String, AwsServiceError> {
1117    req.json_body()
1118        .get("CertificateArn")
1119        .and_then(Value::as_str)
1120        .map(|s| s.to_string())
1121        .ok_or_else(|| invalid_param("CertificateArn is required"))
1122}
1123
1124fn invalid_param(msg: impl Into<String>) -> AwsServiceError {
1125    AwsServiceError::aws_error(StatusCode::BAD_REQUEST, "InvalidParameterException", msg)
1126}
1127
1128fn validation_error(msg: impl Into<String>) -> AwsServiceError {
1129    AwsServiceError::aws_error(StatusCode::BAD_REQUEST, "ValidationException", msg)
1130}
1131
1132fn no_such_certificate(arn: &str) -> AwsServiceError {
1133    AwsServiceError::aws_error(
1134        StatusCode::BAD_REQUEST,
1135        "ResourceNotFoundException",
1136        format!("Could not find certificate with arn {arn}"),
1137    )
1138}
1139
1140fn synth_certificate_arn(account_id: &str, region: &str) -> String {
1141    let region = if region.is_empty() {
1142        "us-east-1"
1143    } else {
1144        region
1145    };
1146    let id = Uuid::new_v4();
1147    Arn::new("acm", region, account_id, &format!("certificate/{id}")).to_string()
1148}
1149
1150/// Extract the trailing UUID portion of a certificate ARN
1151/// (`arn:aws:acm:region:account:certificate/<id>` -> `<id>`). Returns
1152/// the input unchanged if it doesn't match the ACM ARN shape — callers
1153/// only use this to compare against shorthand identifiers passed to the
1154/// admin endpoint, where a partial match against the full ARN is also
1155/// acceptable.
1156fn cert_id_from_arn(arn: &str) -> &str {
1157    arn.rsplit_once("certificate/")
1158        .map(|(_, id)| id)
1159        .unwrap_or(arn)
1160}
1161
1162fn synth_serial(arn: &str) -> String {
1163    let mut hasher = Sha256::new();
1164    hasher.update(arn.as_bytes());
1165    let digest = hasher.finalize();
1166    hex::encode(&digest[..16])
1167}
1168
1169fn parse_tags(value: Option<&Value>) -> Result<BTreeMap<String, String>, AwsServiceError> {
1170    let mut out = BTreeMap::new();
1171    let Some(arr) = value.and_then(Value::as_array) else {
1172        return Ok(out);
1173    };
1174    for tag in arr {
1175        let key = tag
1176            .get("Key")
1177            .and_then(Value::as_str)
1178            .ok_or_else(|| invalid_param("Tag.Key is required"))?
1179            .to_string();
1180        let value = tag
1181            .get("Value")
1182            .and_then(Value::as_str)
1183            .unwrap_or_default()
1184            .to_string();
1185        out.insert(key, value);
1186    }
1187    Ok(out)
1188}
1189
1190fn parse_options(value: Option<&Value>) -> CertificateOptions {
1191    let v = match value {
1192        Some(v) => v,
1193        None => {
1194            return CertificateOptions {
1195                certificate_transparency_logging_preference: "ENABLED".to_string(),
1196                export: "DISABLED".to_string(),
1197            };
1198        }
1199    };
1200    CertificateOptions {
1201        certificate_transparency_logging_preference: v
1202            .get("CertificateTransparencyLoggingPreference")
1203            .and_then(Value::as_str)
1204            .unwrap_or("ENABLED")
1205            .to_string(),
1206        export: v
1207            .get("Export")
1208            .and_then(Value::as_str)
1209            .unwrap_or("DISABLED")
1210            .to_string(),
1211    }
1212}
1213
1214/// Real ACM always carries the apex `DomainName` as the first entry of
1215/// `SubjectAlternativeNames`; replicate that so SDK tests that read SANs
1216/// don't have to special-case its absence.
1217fn effective_sans(domain: &str, extras: &[String]) -> Vec<String> {
1218    let mut all = vec![domain.to_string()];
1219    for s in extras {
1220        if !all.contains(s) {
1221            all.push(s.clone());
1222        }
1223    }
1224    all
1225}
1226
1227fn synth_domain_validation(domain: &str, sans: &[String], method: &str) -> Vec<DomainValidation> {
1228    effective_sans(domain, sans)
1229        .iter()
1230        .map(|d| {
1231            if method == "DNS" {
1232                let token = synth_dns_token(d);
1233                DomainValidation {
1234                    domain_name: d.clone(),
1235                    validation_status: "PENDING_VALIDATION".to_string(),
1236                    validation_method: "DNS".to_string(),
1237                    resource_record_name: Some(format!("_{token}.{d}.")),
1238                    resource_record_type: Some("CNAME".to_string()),
1239                    resource_record_value: Some(format!("_{token}.acm-validations.aws.")),
1240                }
1241            } else {
1242                DomainValidation {
1243                    domain_name: d.clone(),
1244                    validation_status: "PENDING_VALIDATION".to_string(),
1245                    validation_method: "EMAIL".to_string(),
1246                    resource_record_name: None,
1247                    resource_record_type: None,
1248                    resource_record_value: None,
1249                }
1250            }
1251        })
1252        .collect()
1253}
1254
1255/// Deterministic 32-char hex token derived from the domain so test
1256/// assertions on the validation record stay stable across runs.
1257fn synth_dns_token(domain: &str) -> String {
1258    let mut hasher = Sha256::new();
1259    hasher.update(domain.as_bytes());
1260    let digest = hasher.finalize();
1261    hex::encode(&digest[..16])
1262}
1263
1264fn decode_blob(value: Option<&Value>) -> Option<String> {
1265    let v = value?;
1266    if let Some(s) = v.as_str() {
1267        // Real SDKs base64-encode blob shapes over the wire. Decode the
1268        // outer encoding back to the underlying PEM text; if it isn't
1269        // base64 (which happens with ad-hoc curl tests), pass through.
1270        if let Ok(bytes) = base64::engine::general_purpose::STANDARD.decode(s) {
1271            if let Ok(text) = String::from_utf8(bytes) {
1272                return Some(text);
1273            }
1274        }
1275        return Some(s.to_string());
1276    }
1277    None
1278}
1279
1280/// Cheap CN scan for an imported PEM. Real ACM parses the X.509 cert
1281/// to extract the subject; fakecloud just looks for a `CN=` substring
1282/// or falls back to the PEM hash so the returned `DomainName` is at
1283/// least stable per input.
1284fn parse_cn_from_pem(pem: &str) -> Option<String> {
1285    pem.lines()
1286        .find_map(|line| line.split("CN=").nth(1))
1287        .map(|rest| {
1288            rest.split(['/', ',', '\n', ' '])
1289                .next()
1290                .unwrap_or("")
1291                .to_string()
1292        })
1293        .filter(|s| !s.is_empty())
1294}
1295
1296fn placeholder_cert_pem(arn: &str) -> String {
1297    // Fallback used only when an actually-issued cert was somehow
1298    // dropped. Kept distinguishable so callers don't silently treat
1299    // these as real X.509.
1300    let body = base64::engine::general_purpose::STANDARD.encode(arn.as_bytes());
1301    format!("-----BEGIN CERTIFICATE-----\n{body}\n-----END CERTIFICATE-----\n")
1302}
1303
1304fn placeholder_chain_pem(arn: &str) -> String {
1305    let body =
1306        base64::engine::general_purpose::STANDARD.encode(format!("chain-of-{arn}").as_bytes());
1307    format!("-----BEGIN CERTIFICATE-----\n{body}\n-----END CERTIFICATE-----\n")
1308}
1309
1310fn placeholder_key_pem(arn: &str) -> String {
1311    let body = base64::engine::general_purpose::STANDARD.encode(format!("key-of-{arn}").as_bytes());
1312    format!("-----BEGIN RSA PRIVATE KEY-----\n{body}\n-----END RSA PRIVATE KEY-----\n")
1313}
1314
1315/// Generate a real self-signed X.509 certificate + private key pair
1316/// for `domain_name` covering `sans`. Returns
1317/// `(certificate_pem, private_key_pem)`. Used by RequestCertificate
1318/// so the cert that GetCertificate / ExportCertificate hands back
1319/// is actually parseable as a real PEM-encoded X.509 (matching real
1320/// ACM's output format), not a base64-of-the-ARN placeholder.
1321fn generate_self_signed_cert(domain_name: &str, sans: &[String]) -> Option<(String, String)> {
1322    let mut all_names: Vec<String> = vec![domain_name.to_string()];
1323    for s in sans {
1324        if !all_names.contains(s) {
1325            all_names.push(s.clone());
1326        }
1327    }
1328    let cert = rcgen::generate_simple_self_signed(all_names).ok()?;
1329    Some((cert.cert.pem(), cert.key_pair.serialize_pem()))
1330}
1331
1332fn certificate_summary_json(c: &StoredCertificate) -> Value {
1333    let mut s = json!({
1334        "CertificateArn": c.arn,
1335        "DomainName": c.domain_name,
1336        "SubjectAlternativeNameSummaries": c.subject_alternative_names,
1337        "HasAdditionalSubjectAlternativeNames": false,
1338        "Status": c.status,
1339        "Type": c.cert_type,
1340        "KeyAlgorithm": c.key_algorithm,
1341        "KeyUsages": ["DIGITAL_SIGNATURE", "KEY_ENCIPHERMENT"],
1342        "ExtendedKeyUsages": ["TLS_WEB_SERVER_AUTHENTICATION", "TLS_WEB_CLIENT_AUTHENTICATION"],
1343        "InUse": !c.in_use_by.is_empty(),
1344        "Exported": false,
1345        "RenewalEligibility": c.renewal_eligibility,
1346        "NotBefore": c.not_before.timestamp() as f64,
1347        "NotAfter": c.not_after.timestamp() as f64,
1348        "CreatedAt": c.created_at.timestamp() as f64,
1349    });
1350    if let Some(t) = c.issued_at {
1351        s.as_object_mut()
1352            .unwrap()
1353            .insert("IssuedAt".to_string(), json!(t.timestamp() as f64));
1354    }
1355    if let Some(t) = c.imported_at {
1356        s.as_object_mut()
1357            .unwrap()
1358            .insert("ImportedAt".to_string(), json!(t.timestamp() as f64));
1359    }
1360    if let Some(t) = c.revoked_at {
1361        s.as_object_mut()
1362            .unwrap()
1363            .insert("RevokedAt".to_string(), json!(t.timestamp() as f64));
1364        if let Some(r) = &c.revocation_reason {
1365            s.as_object_mut()
1366                .unwrap()
1367                .insert("RevocationReason".to_string(), json!(r));
1368        }
1369    }
1370    if let Some(m) = &c.managed_by {
1371        s.as_object_mut()
1372            .unwrap()
1373            .insert("ManagedBy".to_string(), json!(m));
1374    }
1375    s
1376}
1377
1378fn certificate_detail_json(c: &StoredCertificate) -> Value {
1379    let mut d = json!({
1380        "CertificateArn": c.arn,
1381        "DomainName": c.domain_name,
1382        "SubjectAlternativeNames": c.subject_alternative_names,
1383        "Status": c.status,
1384        "Type": c.cert_type,
1385        "Serial": c.serial,
1386        "Subject": c.subject,
1387        "Issuer": c.issuer,
1388        "KeyAlgorithm": c.key_algorithm,
1389        "SignatureAlgorithm": c.signature_algorithm,
1390        "InUseBy": c.in_use_by,
1391        "RenewalEligibility": c.renewal_eligibility,
1392        "Options": {
1393            "CertificateTransparencyLoggingPreference":
1394                c.options.certificate_transparency_logging_preference,
1395            "Export": c.options.export,
1396        },
1397        "DomainValidationOptions": c
1398            .domain_validation
1399            .iter()
1400            .map(domain_validation_json)
1401            .collect::<Vec<_>>(),
1402        "NotBefore": c.not_before.timestamp() as f64,
1403        "NotAfter": c.not_after.timestamp() as f64,
1404        "CreatedAt": c.created_at.timestamp() as f64,
1405        "KeyUsages": [{"Name": "DIGITAL_SIGNATURE"}, {"Name": "KEY_ENCIPHERMENT"}],
1406        "ExtendedKeyUsages": [
1407            {"Name": "TLS_WEB_SERVER_AUTHENTICATION", "OID": "1.3.6.1.5.5.7.3.1"},
1408            {"Name": "TLS_WEB_CLIENT_AUTHENTICATION", "OID": "1.3.6.1.5.5.7.3.2"},
1409        ],
1410    });
1411    if let Some(t) = c.issued_at {
1412        d.as_object_mut()
1413            .unwrap()
1414            .insert("IssuedAt".to_string(), json!(t.timestamp() as f64));
1415    }
1416    if let Some(t) = c.imported_at {
1417        d.as_object_mut()
1418            .unwrap()
1419            .insert("ImportedAt".to_string(), json!(t.timestamp() as f64));
1420    }
1421    if let Some(t) = c.revoked_at {
1422        d.as_object_mut()
1423            .unwrap()
1424            .insert("RevokedAt".to_string(), json!(t.timestamp() as f64));
1425    }
1426    if let Some(r) = &c.revocation_reason {
1427        d.as_object_mut()
1428            .unwrap()
1429            .insert("RevocationReason".to_string(), json!(r));
1430    }
1431    if let Some(m) = &c.managed_by {
1432        d.as_object_mut()
1433            .unwrap()
1434            .insert("ManagedBy".to_string(), json!(m));
1435    }
1436    if let Some(ca) = &c.certificate_authority_arn {
1437        d.as_object_mut()
1438            .unwrap()
1439            .insert("CertificateAuthorityArn".to_string(), json!(ca));
1440    }
1441    if let Some(fr) = &c.failure_reason {
1442        d.as_object_mut()
1443            .unwrap()
1444            .insert("FailureReason".to_string(), json!(fr));
1445    }
1446    if let Some(rs) = &c.renewal_summary {
1447        let mut summary = json!({
1448            "RenewalStatus": rs.renewal_status,
1449            "DomainValidationOptions": rs
1450                .domain_validation
1451                .iter()
1452                .map(domain_validation_json)
1453                .collect::<Vec<_>>(),
1454            "UpdatedAt": rs.updated_at.timestamp() as f64,
1455        });
1456        if let Some(reason) = &rs.renewal_status_reason {
1457            summary
1458                .as_object_mut()
1459                .unwrap()
1460                .insert("RenewalStatusReason".to_string(), json!(reason));
1461        }
1462        d.as_object_mut()
1463            .unwrap()
1464            .insert("RenewalSummary".to_string(), summary);
1465    }
1466    d
1467}
1468
1469fn certificate_search_result_json(c: &StoredCertificate) -> Value {
1470    let san_objects: Vec<Value> = c
1471        .subject_alternative_names
1472        .iter()
1473        .map(|s| json!({ "DnsName": s }))
1474        .collect();
1475    let cn = c
1476        .subject
1477        .strip_prefix("CN=")
1478        .unwrap_or(c.subject.as_str())
1479        .to_string();
1480    json!({
1481        "CertificateArn": c.arn,
1482        "X509Attributes": {
1483            "Subject": { "CommonName": cn },
1484            "Issuer": { "CommonName": c.issuer },
1485            "SubjectAlternativeNames": san_objects,
1486            "KeyAlgorithm": c.key_algorithm,
1487            "KeyUsages": ["DIGITAL_SIGNATURE", "KEY_ENCIPHERMENT"],
1488            "ExtendedKeyUsages": ["TLS_WEB_SERVER_AUTHENTICATION", "TLS_WEB_CLIENT_AUTHENTICATION"],
1489            "SerialNumber": c.serial,
1490            "NotBefore": c.not_before.timestamp() as f64,
1491            "NotAfter": c.not_after.timestamp() as f64,
1492        },
1493        "CertificateMetadata": {
1494            "AcmCertificateMetadata": {
1495                "Status": c.status,
1496                "Type": c.cert_type,
1497                "InUse": !c.in_use_by.is_empty(),
1498                "Exported": false,
1499                "RenewalEligibility": c.renewal_eligibility,
1500                "CreatedAt": c.created_at.timestamp() as f64,
1501                "ManagedBy": c.managed_by.clone().unwrap_or_default(),
1502                "ValidationMethod": c.validation_method.clone().unwrap_or_default(),
1503            },
1504        },
1505    })
1506}
1507
1508fn domain_validation_json(v: &DomainValidation) -> Value {
1509    let mut out = json!({
1510        "DomainName": v.domain_name,
1511        "ValidationStatus": v.validation_status,
1512        "ValidationMethod": v.validation_method,
1513    });
1514    if let (Some(name), Some(rtype), Some(value)) = (
1515        &v.resource_record_name,
1516        &v.resource_record_type,
1517        &v.resource_record_value,
1518    ) {
1519        out.as_object_mut().unwrap().insert(
1520            "ResourceRecord".to_string(),
1521            json!({
1522                "Name": name,
1523                "Type": rtype,
1524                "Value": value,
1525            }),
1526        );
1527    }
1528    out
1529}
1530
1531/// Encrypt a PEM-encoded PKCS#8 private key with a passphrase,
1532/// producing a PEM file with `BEGIN ENCRYPTED PRIVATE KEY` headers.
1533/// This matches what real ACM `ExportCertificate` returns: a PKCS#8 v2
1534/// `EncryptedPrivateKeyInfo` using PBES2 (PBKDF2 + AES-256-CBC).
1535///
1536/// The resulting PEM is decryptable with anything that handles modern
1537/// PKCS#8 encrypted keys: `openssl pkcs8 -in key.pem -passin pass:...`,
1538/// Python's `cryptography.hazmat.primitives.serialization`,
1539/// `rsa::pkcs8::DecodePrivateKey::from_pkcs8_encrypted_pem`, etc.
1540fn encrypt_private_key_pem(key_pem: &str, passphrase: &[u8]) -> Result<String, String> {
1541    use pkcs8::{pkcs5::pbes2, LineEnding, PrivateKeyInfo};
1542
1543    // Strip the PEM headers and base64-decode the inner DER. Real keys
1544    // (rcgen, openssl) emit `BEGIN PRIVATE KEY` for PKCS#8 v1; we don't
1545    // support encrypting `BEGIN RSA PRIVATE KEY` (PKCS#1) or other
1546    // legacy SEC1 forms here because rcgen always produces PKCS#8.
1547    let der = pem_decode_private_key(key_pem)?;
1548
1549    // PBES2 parameters: 16-byte random salt, 2048 PBKDF2-SHA256
1550    // iterations (matches OpenSSL defaults for `openssl pkcs8 -topk8`),
1551    // AES-256-CBC with a random 16-byte IV.
1552    let mut salt = [0u8; 16];
1553    let mut iv = [0u8; 16];
1554    rand::RngCore::fill_bytes(&mut rand::thread_rng(), &mut salt);
1555    rand::RngCore::fill_bytes(&mut rand::thread_rng(), &mut iv);
1556    let params = pbes2::Parameters::pbkdf2_sha256_aes256cbc(2048, &salt, &iv)
1557        .map_err(|e| format!("invalid PBES2 parameters: {e}"))?;
1558
1559    let pki = PrivateKeyInfo::try_from(der.as_slice())
1560        .map_err(|e| format!("private key is not valid PKCS#8 DER: {e}"))?;
1561    let encrypted = pki
1562        .encrypt_with_params(params, passphrase)
1563        .map_err(|e| format!("PKCS#8 encryption failed: {e}"))?;
1564
1565    encrypted
1566        .to_pem("ENCRYPTED PRIVATE KEY", LineEnding::LF)
1567        .map(|s| s.to_string())
1568        .map_err(|e| format!("PEM encoding failed: {e}"))
1569}
1570
1571/// Decode a PEM `BEGIN PRIVATE KEY` block to its inner DER bytes.
1572/// Returns an error if the block is missing, has the wrong label, or
1573/// the body is not valid base64.
1574fn pem_decode_private_key(pem: &str) -> Result<Vec<u8>, String> {
1575    let begin = pem.find("-----BEGIN ").ok_or("missing BEGIN line")?;
1576    let after_begin = &pem[begin + 11..];
1577    let dash = after_begin.find("-----").ok_or("malformed BEGIN line")?;
1578    let label = after_begin[..dash].trim();
1579    if label != "PRIVATE KEY" {
1580        return Err(format!(
1581            "expected `BEGIN PRIVATE KEY` (PKCS#8), got `BEGIN {label}`"
1582        ));
1583    }
1584    let end = pem
1585        .find("-----END PRIVATE KEY-----")
1586        .ok_or("missing END line")?;
1587    let body_start = begin + 11 + dash + 5;
1588    let nl = pem[body_start..]
1589        .find('\n')
1590        .ok_or("missing newline after BEGIN")?;
1591    let body: String = pem[body_start + nl + 1..end]
1592        .chars()
1593        .filter(|c| !c.is_whitespace())
1594        .collect();
1595    base64::engine::general_purpose::STANDARD
1596        .decode(body.as_bytes())
1597        .map_err(|e| format!("PEM body is not valid base64: {e}"))
1598}
1599
1600#[cfg(test)]
1601mod tests {
1602    use super::*;
1603
1604    #[test]
1605    fn generate_self_signed_cert_returns_real_pem() {
1606        let (cert_pem, key_pem) =
1607            generate_self_signed_cert("example.com", &["www.example.com".to_string()])
1608                .expect("rcgen should produce a self-signed cert");
1609        assert!(
1610            cert_pem.starts_with("-----BEGIN CERTIFICATE-----"),
1611            "expected real PEM cert, got {cert_pem:.80}"
1612        );
1613        assert!(cert_pem.ends_with("-----END CERTIFICATE-----\n"));
1614        assert!(key_pem.contains("-----BEGIN PRIVATE KEY-----"));
1615        // Substantially longer than the placeholder (= base64-of-domain).
1616        assert!(cert_pem.len() > 400, "real cert PEM should be >400 chars");
1617    }
1618
1619    #[tokio::test]
1620    async fn request_certificate_stores_real_pem_and_key() {
1621        let svc = AcmService::default();
1622        let req = AwsRequest {
1623            service: "acm".to_string(),
1624            action: "RequestCertificate".to_string(),
1625            region: "us-east-1".to_string(),
1626            account_id: "123456789012".to_string(),
1627            request_id: "rid".to_string(),
1628            headers: http::HeaderMap::new(),
1629            query_params: std::collections::HashMap::new(),
1630            body: bytes::Bytes::from(
1631                serde_json::to_vec(&json!({"DomainName": "example.com"})).unwrap(),
1632            ),
1633            body_stream: parking_lot::Mutex::new(None),
1634            path_segments: vec![],
1635            raw_path: "/".to_string(),
1636            raw_query: String::new(),
1637            method: http::Method::POST,
1638            is_query_protocol: false,
1639            access_key_id: None,
1640            principal: None,
1641        };
1642        let resp = svc.handle(req).await.unwrap();
1643        let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
1644        let arn = body["CertificateArn"].as_str().unwrap();
1645        let st = svc.state.read();
1646        let cert = st
1647            .accounts
1648            .get("123456789012")
1649            .unwrap()
1650            .certificates
1651            .get(arn)
1652            .unwrap();
1653        let cert_pem = cert.certificate_pem.as_deref().unwrap();
1654        let key_pem = cert.private_key_pem.as_deref().unwrap();
1655        assert!(cert_pem.starts_with("-----BEGIN CERTIFICATE-----"));
1656        assert!(key_pem.contains("-----BEGIN PRIVATE KEY-----"));
1657        assert!(cert_pem.len() > 400);
1658    }
1659
1660    #[test]
1661    fn encrypt_private_key_pem_emits_pkcs8_v2_pem() {
1662        let (_cert, key_pem) =
1663            generate_self_signed_cert("example.com", &[]).expect("rcgen produces a key");
1664        let out = encrypt_private_key_pem(&key_pem, b"hunter2").expect("encryption succeeds");
1665        assert!(
1666            out.starts_with("-----BEGIN ENCRYPTED PRIVATE KEY-----\n"),
1667            "expected PKCS#8 v2 envelope, got {out:.80}"
1668        );
1669        assert!(out
1670            .trim_end()
1671            .ends_with("-----END ENCRYPTED PRIVATE KEY-----"));
1672        // The plaintext PEM body should not appear in the encrypted
1673        // output — sanity check that we actually encrypted.
1674        let plain_body: String = key_pem
1675            .lines()
1676            .filter(|l| !l.starts_with("-----"))
1677            .collect();
1678        assert!(!plain_body.is_empty());
1679        assert!(!out.contains(&plain_body));
1680    }
1681
1682    #[test]
1683    fn encrypt_private_key_pem_round_trips_via_pkcs8_decoder() {
1684        use pkcs8::{DecodePrivateKey, EncodePrivateKey, LineEnding};
1685
1686        let mut rng = rand::thread_rng();
1687        let original = rsa::RsaPrivateKey::new(&mut rng, 2048).expect("rsa keygen");
1688        let key_pem = original
1689            .to_pkcs8_pem(LineEnding::LF)
1690            .expect("pkcs8 pem encode")
1691            .to_string();
1692        let passphrase = b"correct horse battery staple";
1693
1694        let encrypted = encrypt_private_key_pem(&key_pem, passphrase).unwrap();
1695        assert!(encrypted.contains("BEGIN ENCRYPTED PRIVATE KEY"));
1696
1697        let recovered = rsa::RsaPrivateKey::from_pkcs8_encrypted_pem(&encrypted, passphrase)
1698            .expect("decryption + PKCS#8 parse");
1699        assert_eq!(original, recovered);
1700    }
1701
1702    fn make_req(action: &str, body: Value) -> AwsRequest {
1703        AwsRequest {
1704            service: "acm".to_string(),
1705            action: action.to_string(),
1706            region: "us-east-1".to_string(),
1707            account_id: "123456789012".to_string(),
1708            request_id: "rid".to_string(),
1709            headers: http::HeaderMap::new(),
1710            query_params: std::collections::HashMap::new(),
1711            body: bytes::Bytes::from(serde_json::to_vec(&body).unwrap()),
1712            body_stream: parking_lot::Mutex::new(None),
1713            path_segments: vec![],
1714            raw_path: "/".to_string(),
1715            raw_query: String::new(),
1716            method: http::Method::POST,
1717            is_query_protocol: false,
1718            access_key_id: None,
1719            principal: None,
1720        }
1721    }
1722
1723    async fn make_exportable_cert(svc: &AcmService) -> String {
1724        let req = make_req(
1725            "RequestCertificate",
1726            json!({
1727                "DomainName": "example.com",
1728                "Options": {"Export": "ENABLED"},
1729            }),
1730        );
1731        let resp = svc.handle(req).await.unwrap();
1732        let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
1733        body["CertificateArn"].as_str().unwrap().to_string()
1734    }
1735
1736    #[tokio::test]
1737    async fn export_certificate_emits_passphrase_encrypted_pem() {
1738        let svc = AcmService::default();
1739        let arn = make_exportable_cert(&svc).await;
1740        let original_key_pem = svc
1741            .state
1742            .read()
1743            .accounts
1744            .get("123456789012")
1745            .unwrap()
1746            .certificates
1747            .get(&arn)
1748            .unwrap()
1749            .private_key_pem
1750            .clone()
1751            .unwrap();
1752
1753        let passphrase = b"hunter2";
1754        let passphrase_b64 = base64::engine::general_purpose::STANDARD.encode(passphrase);
1755        let export = make_req(
1756            "ExportCertificate",
1757            json!({"CertificateArn": arn, "Passphrase": passphrase_b64}),
1758        );
1759        let export_resp = svc.handle(export).await.unwrap();
1760        let export_json: Value = serde_json::from_slice(export_resp.body.expect_bytes()).unwrap();
1761        let private_key = export_json["PrivateKey"].as_str().unwrap();
1762        assert!(
1763            private_key.contains("BEGIN ENCRYPTED PRIVATE KEY"),
1764            "expected PKCS#8 v2 PEM, got {private_key}"
1765        );
1766        assert!(private_key.contains("END ENCRYPTED PRIVATE KEY"));
1767        // Round-trip: decrypt with the same passphrase and confirm we
1768        // recover the same private key bytes that ACM stored.
1769        let original_inner_der =
1770            pem_decode_private_key(&original_key_pem).expect("decode original PEM");
1771        let original_pki_bytes = pkcs8::PrivateKeyInfo::try_from(original_inner_der.as_slice())
1772            .map(|p| p.private_key.to_vec())
1773            .expect("parse original PKCS#8");
1774        let encrypted_der =
1775            pem_decode_encrypted_private_key(private_key).expect("decode encrypted PEM");
1776        let decrypted_doc = pkcs8::EncryptedPrivateKeyInfo::try_from(encrypted_der.as_slice())
1777            .expect("parse encrypted PKCS#8")
1778            .decrypt(passphrase)
1779            .expect("decrypt with passphrase");
1780        let decrypted_pki = pkcs8::PrivateKeyInfo::try_from(decrypted_doc.as_bytes())
1781            .expect("parse decrypted PKCS#8");
1782        assert_eq!(decrypted_pki.private_key, original_pki_bytes.as_slice());
1783    }
1784
1785    #[tokio::test]
1786    async fn export_certificate_without_passphrase_returns_plain_pem() {
1787        let svc = AcmService::default();
1788        let arn = make_exportable_cert(&svc).await;
1789        let export_resp = svc
1790            .handle(make_req(
1791                "ExportCertificate",
1792                json!({"CertificateArn": arn}),
1793            ))
1794            .await
1795            .unwrap();
1796        let export_json: Value = serde_json::from_slice(export_resp.body.expect_bytes()).unwrap();
1797        let private_key = export_json["PrivateKey"].as_str().unwrap();
1798        assert!(
1799            private_key.contains("-----BEGIN PRIVATE KEY-----"),
1800            "expected plain PKCS#8 PEM, got {private_key}"
1801        );
1802        assert!(!private_key.contains("ENCRYPTED PRIVATE KEY"));
1803    }
1804
1805    #[tokio::test]
1806    async fn export_certificate_with_empty_passphrase_returns_plain_pem() {
1807        let svc = AcmService::default();
1808        let arn = make_exportable_cert(&svc).await;
1809        let export_resp = svc
1810            .handle(make_req(
1811                "ExportCertificate",
1812                json!({"CertificateArn": arn, "Passphrase": ""}),
1813            ))
1814            .await
1815            .unwrap();
1816        let export_json: Value = serde_json::from_slice(export_resp.body.expect_bytes()).unwrap();
1817        let private_key = export_json["PrivateKey"].as_str().unwrap();
1818        assert!(private_key.contains("-----BEGIN PRIVATE KEY-----"));
1819        assert!(!private_key.contains("ENCRYPTED PRIVATE KEY"));
1820    }
1821
1822    #[tokio::test]
1823    async fn export_certificate_rejects_non_base64_passphrase() {
1824        let svc = AcmService::default();
1825        let resp = svc
1826            .handle(make_req(
1827                "RequestCertificate",
1828                json!({"DomainName": "example.com"}),
1829            ))
1830            .await
1831            .unwrap();
1832        let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
1833        let arn = body["CertificateArn"].as_str().unwrap().to_string();
1834        let export = make_req(
1835            "ExportCertificate",
1836            json!({"CertificateArn": arn, "Passphrase": "not!base64!@#$"}),
1837        );
1838        let err = match svc.handle(export).await {
1839            Ok(_) => panic!("expected error for non-base64 passphrase"),
1840            Err(e) => e,
1841        };
1842        assert!(format!("{err:?}").contains("Passphrase"));
1843    }
1844
1845    fn pem_decode_encrypted_private_key(pem: &str) -> Result<Vec<u8>, String> {
1846        let begin = "-----BEGIN ENCRYPTED PRIVATE KEY-----";
1847        let end = "-----END ENCRYPTED PRIVATE KEY-----";
1848        let begin_idx = pem.find(begin).ok_or("missing BEGIN")?;
1849        let after = &pem[begin_idx + begin.len()..];
1850        let end_idx = after.find(end).ok_or("missing END")?;
1851        let body: String = after[..end_idx]
1852            .chars()
1853            .filter(|c| !c.is_whitespace())
1854            .collect();
1855        base64::engine::general_purpose::STANDARD
1856            .decode(body.as_bytes())
1857            .map_err(|e| format!("base64: {e}"))
1858    }
1859
1860    #[tokio::test]
1861    async fn describe_certificate_observes_auto_issue_transition() {
1862        // After the auto-issue tick fires, successive describes should
1863        // pick up Status=ISSUED, IssuedAt, RenewalEligibility=ELIGIBLE,
1864        // and a populated RenewalSummary without any extra prodding.
1865        let svc = AcmService::default()
1866            .with_pending_validation_delay(std::time::Duration::from_millis(50));
1867        let resp = svc
1868            .handle(make_req(
1869                "RequestCertificate",
1870                json!({"DomainName": "example.com", "ValidationMethod": "DNS"}),
1871            ))
1872            .await
1873            .unwrap();
1874        let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
1875        let arn = body["CertificateArn"].as_str().unwrap().to_string();
1876
1877        // Immediate describe sees PENDING_VALIDATION + ELIGIBILITY
1878        // INELIGIBLE.
1879        let early = svc
1880            .handle(make_req(
1881                "DescribeCertificate",
1882                json!({"CertificateArn": arn}),
1883            ))
1884            .await
1885            .unwrap();
1886        let early: Value = serde_json::from_slice(early.body.expect_bytes()).unwrap();
1887        assert_eq!(early["Certificate"]["Status"], "PENDING_VALIDATION");
1888        assert_eq!(early["Certificate"]["RenewalEligibility"], "INELIGIBLE");
1889        assert!(early["Certificate"].get("RenewalSummary").is_none());
1890
1891        // Poll up to 2s for the auto-issue tick.
1892        let mut last: Value = Value::Null;
1893        for _ in 0..40 {
1894            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1895            let resp = svc
1896                .handle(make_req(
1897                    "DescribeCertificate",
1898                    json!({"CertificateArn": arn}),
1899                ))
1900                .await
1901                .unwrap();
1902            let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
1903            if body["Certificate"]["Status"] == "ISSUED" {
1904                last = body;
1905                break;
1906            }
1907        }
1908        assert_eq!(last["Certificate"]["Status"], "ISSUED");
1909        assert_eq!(last["Certificate"]["RenewalEligibility"], "ELIGIBLE");
1910        let rs = &last["Certificate"]["RenewalSummary"];
1911        assert_eq!(rs["RenewalStatus"], "PENDING_AUTO_RENEWAL");
1912        assert!(rs["UpdatedAt"].as_f64().unwrap() > 0.0);
1913    }
1914
1915    #[tokio::test]
1916    async fn request_certificate_emits_parseable_pem() {
1917        let svc = AcmService::default();
1918        let resp = svc
1919            .handle(make_req(
1920                "RequestCertificate",
1921                json!({"DomainName": "example.com"}),
1922            ))
1923            .await
1924            .unwrap();
1925        let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
1926        let arn = body["CertificateArn"].as_str().unwrap().to_string();
1927
1928        let resp = svc
1929            .handle(make_req("GetCertificate", json!({"CertificateArn": arn})))
1930            .await
1931            .unwrap();
1932        let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
1933        let cert_pem = body["Certificate"].as_str().unwrap();
1934        assert!(
1935            cert_pem.starts_with("-----BEGIN CERTIFICATE-----"),
1936            "expected real PEM cert header, got {cert_pem:.80}"
1937        );
1938        assert!(cert_pem.trim_end().ends_with("-----END CERTIFICATE-----"));
1939        // Real X.509 base64 body is much larger than the legacy
1940        // base64-of-ARN placeholder (which was ~80 chars total).
1941        assert!(
1942            cert_pem.len() > 400,
1943            "expected real X.509 PEM, got placeholder-sized blob"
1944        );
1945        // Sanity-check we didn't smuggle the ARN body back in via the
1946        // old placeholder code path.
1947        assert!(!cert_pem.contains(arn.as_str()));
1948    }
1949
1950    #[tokio::test]
1951    async fn request_certificate_includes_san() {
1952        let svc = AcmService::default();
1953        let resp = svc
1954            .handle(make_req(
1955                "RequestCertificate",
1956                json!({
1957                    "DomainName": "example.com",
1958                    "SubjectAlternativeNames": ["api.example.com", "www.example.com"],
1959                }),
1960            ))
1961            .await
1962            .unwrap();
1963        let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
1964        let arn = body["CertificateArn"].as_str().unwrap().to_string();
1965
1966        let resp = svc
1967            .handle(make_req("GetCertificate", json!({"CertificateArn": arn})))
1968            .await
1969            .unwrap();
1970        let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
1971        let cert_pem = body["Certificate"].as_str().unwrap();
1972        assert!(cert_pem.starts_with("-----BEGIN CERTIFICATE-----"));
1973        assert!(cert_pem.trim_end().ends_with("-----END CERTIFICATE-----"));
1974
1975        // Decode the PEM body and search the DER bytes for the SAN dNSName
1976        // octets. rcgen emits SANs as IA5String entries inside the
1977        // SubjectAltName extension, so the raw domain bytes are present.
1978        let body_b64: String = cert_pem
1979            .lines()
1980            .filter(|l| !l.starts_with("-----"))
1981            .collect::<Vec<_>>()
1982            .join("");
1983        let der = base64::engine::general_purpose::STANDARD
1984            .decode(&body_b64)
1985            .expect("cert body is valid base64");
1986        for san in ["example.com", "api.example.com", "www.example.com"] {
1987            assert!(
1988                der.windows(san.len()).any(|w| w == san.as_bytes()),
1989                "expected SAN {san} embedded in DER"
1990            );
1991        }
1992    }
1993
1994    #[tokio::test]
1995    async fn request_certificate_starts_in_pending_validation() {
1996        let svc = AcmService::default();
1997        let resp = svc
1998            .handle(make_req(
1999                "RequestCertificate",
2000                json!({"DomainName": "example.com", "ValidationMethod": "DNS"}),
2001            ))
2002            .await
2003            .unwrap();
2004        let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
2005        let arn = body["CertificateArn"].as_str().unwrap().to_string();
2006        let st = svc.state.read();
2007        let cert = st
2008            .accounts
2009            .get("123456789012")
2010            .unwrap()
2011            .certificates
2012            .get(&arn)
2013            .unwrap();
2014        assert_eq!(cert.status, "PENDING_VALIDATION");
2015        assert!(cert.issued_at.is_none());
2016    }
2017
2018    #[tokio::test]
2019    async fn set_certificate_status_to_issued_via_admin() {
2020        let svc = AcmService::default();
2021        let resp = svc
2022            .handle(make_req(
2023                "RequestCertificate",
2024                json!({"DomainName": "admin.example.com"}),
2025            ))
2026            .await
2027            .unwrap();
2028        let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
2029        let arn = body["CertificateArn"].as_str().unwrap().to_string();
2030
2031        assert!(svc.set_certificate_status(&arn, "ISSUED", None));
2032        let st = svc.state.read();
2033        let cert = st
2034            .accounts
2035            .get("123456789012")
2036            .unwrap()
2037            .certificates
2038            .get(&arn)
2039            .unwrap();
2040        assert_eq!(cert.status, "ISSUED");
2041        assert!(cert.issued_at.is_some());
2042        for dv in &cert.domain_validation {
2043            assert_eq!(dv.validation_status, "SUCCESS");
2044        }
2045    }
2046
2047    #[tokio::test]
2048    async fn set_certificate_status_unknown_arn_returns_false() {
2049        let svc = AcmService::default();
2050        assert!(!svc.set_certificate_status("does-not-exist", "ISSUED", None));
2051    }
2052
2053    #[tokio::test]
2054    async fn auto_issue_tick_transitions_to_issued() {
2055        let svc = AcmService::default()
2056            .with_pending_validation_delay(std::time::Duration::from_millis(50));
2057        let resp = svc
2058            .handle(make_req(
2059                "RequestCertificate",
2060                json!({"DomainName": "auto.example.com", "ValidationMethod": "DNS"}),
2061            ))
2062            .await
2063            .unwrap();
2064        let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
2065        let arn = body["CertificateArn"].as_str().unwrap().to_string();
2066
2067        tokio::time::sleep(std::time::Duration::from_millis(200)).await;
2068
2069        let st = svc.state.read();
2070        let cert = st
2071            .accounts
2072            .get("123456789012")
2073            .unwrap()
2074            .certificates
2075            .get(&arn)
2076            .unwrap();
2077        assert_eq!(cert.status, "ISSUED");
2078        assert!(cert.issued_at.is_some());
2079        assert_eq!(cert.renewal_eligibility, "ELIGIBLE");
2080        let rs = cert.renewal_summary.as_ref().expect("renewal summary set");
2081        assert_eq!(rs.renewal_status, "PENDING_AUTO_RENEWAL");
2082    }
2083
2084    #[tokio::test]
2085    async fn email_validation_stays_pending_until_approve() {
2086        // EMAIL certs intentionally do NOT trigger the auto-issue tick:
2087        // real ACM only flips them once the user clicks the approval
2088        // link. fakecloud routes the approval through
2089        // `approve_certificate`.
2090        let svc = AcmService::default()
2091            .with_pending_validation_delay(std::time::Duration::from_millis(20));
2092        let resp = svc
2093            .handle(make_req(
2094                "RequestCertificate",
2095                json!({
2096                    "DomainName": "email.example.com",
2097                    "ValidationMethod": "EMAIL",
2098                }),
2099            ))
2100            .await
2101            .unwrap();
2102        let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
2103        let arn = body["CertificateArn"].as_str().unwrap().to_string();
2104
2105        // Wait well past the DNS auto-issue delay; EMAIL must stay
2106        // PENDING_VALIDATION because no tick was scheduled.
2107        tokio::time::sleep(std::time::Duration::from_millis(150)).await;
2108        {
2109            let st = svc.state.read();
2110            let cert = st
2111                .accounts
2112                .get("123456789012")
2113                .unwrap()
2114                .certificates
2115                .get(&arn)
2116                .unwrap();
2117            assert_eq!(cert.status, "PENDING_VALIDATION");
2118            assert!(cert.issued_at.is_none());
2119            assert!(cert.renewal_summary.is_none());
2120        }
2121
2122        assert!(svc.approve_certificate(&arn));
2123        let st = svc.state.read();
2124        let cert = st
2125            .accounts
2126            .get("123456789012")
2127            .unwrap()
2128            .certificates
2129            .get(&arn)
2130            .unwrap();
2131        assert_eq!(cert.status, "ISSUED");
2132        assert_eq!(cert.renewal_eligibility, "ELIGIBLE");
2133        for dv in &cert.domain_validation {
2134            assert_eq!(dv.validation_status, "SUCCESS");
2135        }
2136        assert!(cert.renewal_summary.is_some());
2137    }
2138
2139    #[tokio::test]
2140    async fn renew_certificate_refreshes_renewal_summary() {
2141        let svc = AcmService::default()
2142            .with_pending_validation_delay(std::time::Duration::from_millis(20));
2143        let resp = svc
2144            .handle(make_req(
2145                "RequestCertificate",
2146                json!({"DomainName": "renew.example.com", "ValidationMethod": "DNS"}),
2147            ))
2148            .await
2149            .unwrap();
2150        let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
2151        let arn = body["CertificateArn"].as_str().unwrap().to_string();
2152
2153        tokio::time::sleep(std::time::Duration::from_millis(80)).await;
2154
2155        let resp = svc
2156            .handle(make_req("RenewCertificate", json!({"CertificateArn": arn})))
2157            .await
2158            .unwrap();
2159        assert_eq!(resp.status, http::StatusCode::OK);
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, "ISSUED");
2170        let rs = cert.renewal_summary.as_ref().expect("renewal summary set");
2171        assert_eq!(rs.renewal_status, "SUCCESS");
2172        assert_eq!(rs.domain_validation.len(), cert.domain_validation.len());
2173    }
2174
2175    #[test]
2176    fn auto_issue_delay_default_when_env_unset() {
2177        // Other tests don't touch FAKECLOUD_ACM_AUTO_ISSUE_SECS, so
2178        // reading it here while running serially with `cargo test`
2179        // returns the documented default. We use a constant to guard
2180        // against accidental drift in `DEFAULT_AUTO_ISSUE_SECS`.
2181        if std::env::var("FAKECLOUD_ACM_AUTO_ISSUE_SECS").is_err() {
2182            assert_eq!(
2183                auto_issue_delay_from_env(),
2184                std::time::Duration::from_secs(DEFAULT_AUTO_ISSUE_SECS),
2185            );
2186        }
2187    }
2188
2189    #[tokio::test]
2190    async fn set_certificate_status_failed_records_reason() {
2191        let svc = AcmService::default();
2192        let resp = svc
2193            .handle(make_req(
2194                "RequestCertificate",
2195                json!({"DomainName": "fail.example.com"}),
2196            ))
2197            .await
2198            .unwrap();
2199        let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
2200        let arn = body["CertificateArn"].as_str().unwrap().to_string();
2201        assert!(svc.set_certificate_status(&arn, "FAILED", Some("DNS lookup error".to_string())));
2202        let st = svc.state.read();
2203        let cert = st
2204            .accounts
2205            .get("123456789012")
2206            .unwrap()
2207            .certificates
2208            .get(&arn)
2209            .unwrap();
2210        assert_eq!(cert.status, "FAILED");
2211        assert_eq!(cert.failure_reason.as_deref(), Some("DNS lookup error"));
2212    }
2213
2214    #[tokio::test]
2215    async fn request_certificate_private_key_pem_is_valid() {
2216        let svc = AcmService::default();
2217        let resp = svc
2218            .handle(make_req(
2219                "RequestCertificate",
2220                json!({"DomainName": "key.example.com"}),
2221            ))
2222            .await
2223            .unwrap();
2224        let body: Value = serde_json::from_slice(resp.body.expect_bytes()).unwrap();
2225        let arn = body["CertificateArn"].as_str().unwrap().to_string();
2226
2227        let st = svc.state.read();
2228        let cert = st
2229            .accounts
2230            .get("123456789012")
2231            .unwrap()
2232            .certificates
2233            .get(&arn)
2234            .unwrap();
2235        let key_pem = cert
2236            .private_key_pem
2237            .as_deref()
2238            .expect("RequestCertificate should populate a real private key");
2239        let starts_pkcs8 = key_pem.starts_with("-----BEGIN PRIVATE KEY-----");
2240        let starts_rsa = key_pem.starts_with("-----BEGIN RSA PRIVATE KEY-----");
2241        assert!(
2242            starts_pkcs8 || starts_rsa,
2243            "expected PKCS#8 or RSA private key header, got {key_pem:.80}"
2244        );
2245        assert!(
2246            key_pem.trim_end().ends_with("-----END PRIVATE KEY-----")
2247                || key_pem
2248                    .trim_end()
2249                    .ends_with("-----END RSA PRIVATE KEY-----")
2250        );
2251        assert!(key_pem.len() > 200);
2252    }
2253}