Skip to main content

minco_deploy_aws/
lib.rs

1//! Fail-closed AWS deployment guards and `CloudFormation` change-set review.
2#![forbid(unsafe_code)]
3
4use minco_plugin_static_site::{StaticSitePublication, StaticSiteReleaseManifest};
5use minco_release::{DeploymentOutcome, DeploymentReceipt, FileDigest, ReleaseEnvironment};
6use serde::{Deserialize, Serialize};
7use sha2::{Digest, Sha256};
8use std::{
9    collections::{BTreeMap, BTreeSet},
10    io::Write as _,
11    path::{Component, Path},
12};
13use thiserror::Error;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
16#[serde(rename_all = "snake_case")]
17pub enum ChangeAction {
18    Add,
19    Modify,
20    Remove,
21    Import,
22    Dynamic,
23    SyncWithActual,
24}
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
27#[serde(rename_all = "snake_case")]
28pub enum Replacement {
29    Never,
30    Conditional,
31    Always,
32}
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(rename_all = "snake_case")]
36pub enum PolicyAction {
37    Delete,
38    Retain,
39    Snapshot,
40    ReplaceAndDelete,
41    ReplaceAndRetain,
42    ReplaceAndSnapshot,
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
46#[serde(rename_all = "snake_case")]
47pub enum ChangeScope {
48    Properties,
49    Metadata,
50    CreationPolicy,
51    UpdatePolicy,
52    DeletionPolicy,
53    UpdateReplacePolicy,
54    Tags,
55}
56
57#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
58#[serde(deny_unknown_fields)]
59pub struct ResourceChange {
60    pub logical_id: String,
61    pub resource_type: String,
62    pub action: ChangeAction,
63    pub replacement: Option<Replacement>,
64    pub policy_action: Option<PolicyAction>,
65    pub scope: Vec<ChangeScope>,
66}
67
68impl ResourceChange {
69    pub fn new(
70        logical_id: impl Into<String>,
71        resource_type: impl Into<String>,
72        action: ChangeAction,
73        replacement: Option<Replacement>,
74    ) -> Self {
75        Self {
76            logical_id: logical_id.into(),
77            resource_type: resource_type.into(),
78            action,
79            replacement,
80            policy_action: None,
81            scope: Vec::new(),
82        }
83    }
84}
85
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
87#[serde(deny_unknown_fields)]
88pub struct ChangeSetReview {
89    pub additions: Vec<ResourceChange>,
90    pub modifications: Vec<ResourceChange>,
91    pub replacements: Vec<ResourceChange>,
92    pub deletions: Vec<ResourceChange>,
93    pub imports: Vec<ResourceChange>,
94    pub indeterminate: Vec<ResourceChange>,
95    pub metadata_syncs: Vec<ResourceChange>,
96}
97
98impl ChangeSetReview {
99    pub fn classify(
100        changes: impl IntoIterator<Item = ResourceChange>,
101    ) -> Result<Self, ChangeReviewError> {
102        let mut logical_ids = BTreeSet::new();
103        let mut review = Self {
104            additions: Vec::new(),
105            modifications: Vec::new(),
106            replacements: Vec::new(),
107            deletions: Vec::new(),
108            imports: Vec::new(),
109            indeterminate: Vec::new(),
110            metadata_syncs: Vec::new(),
111        };
112
113        for change in changes {
114            if change.logical_id.is_empty() || change.resource_type.is_empty() {
115                return Err(ChangeReviewError::MissingIdentity);
116            }
117            if !logical_ids.insert(change.logical_id.clone()) {
118                return Err(ChangeReviewError::DuplicateLogicalId(change.logical_id));
119            }
120            match (change.action, change.replacement) {
121                (ChangeAction::Add, None) => review.additions.push(change),
122                (ChangeAction::Remove, None) => review.deletions.push(change),
123                (ChangeAction::Modify, Some(Replacement::Conditional | Replacement::Always)) => {
124                    review.replacements.push(change);
125                }
126                (ChangeAction::Modify, None | Some(Replacement::Never)) => {
127                    review.modifications.push(change);
128                }
129                (ChangeAction::Import, None) => review.imports.push(change),
130                (ChangeAction::Dynamic, None) => review.indeterminate.push(change),
131                (ChangeAction::SyncWithActual, None) => review.metadata_syncs.push(change),
132                (
133                    ChangeAction::Add
134                    | ChangeAction::Remove
135                    | ChangeAction::Import
136                    | ChangeAction::Dynamic
137                    | ChangeAction::SyncWithActual,
138                    Some(_),
139                ) => {
140                    return Err(ChangeReviewError::UnexpectedReplacement(change.logical_id));
141                }
142            }
143        }
144
145        for changes in [
146            &mut review.additions,
147            &mut review.modifications,
148            &mut review.replacements,
149            &mut review.deletions,
150            &mut review.imports,
151            &mut review.indeterminate,
152            &mut review.metadata_syncs,
153        ] {
154            changes.sort_by(|left, right| {
155                left.logical_id
156                    .cmp(&right.logical_id)
157                    .then_with(|| left.resource_type.cmp(&right.resource_type))
158            });
159        }
160        Ok(review)
161    }
162}
163
164#[derive(Debug, Error)]
165pub enum ChangeReviewError {
166    #[error("change-set resource is missing a logical ID or resource type")]
167    MissingIdentity,
168    #[error("change set contains duplicate logical ID {0}")]
169    DuplicateLogicalId(String),
170    #[error("non-modification change {0} unexpectedly declares replacement behavior")]
171    UnexpectedReplacement(String),
172    #[error("change-set entry has unsupported type {0}")]
173    UnsupportedChangeType(String),
174    #[error(
175        "CloudFormation change-set response type {actual:?} contradicts guarded type {expected:?}"
176    )]
177    UnexpectedChangeSetType {
178        expected: ChangeSetType,
179        actual: ChangeSetType,
180    },
181    #[error("CloudFormation change-set response is invalid: {0}")]
182    ProviderJson(#[from] serde_json::Error),
183}
184
185#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
186#[serde(rename_all = "snake_case")]
187pub enum ChangeSetType {
188    Create,
189    Update,
190    Import,
191}
192
193#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
194#[serde(rename_all = "snake_case")]
195pub enum ChangeSetStatus {
196    CreatePending,
197    CreateInProgress,
198    CreateComplete,
199    DeletePending,
200    DeleteInProgress,
201    DeleteComplete,
202    DeleteFailed,
203    Failed,
204}
205
206#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
207#[serde(rename_all = "snake_case")]
208pub enum ExecutionStatus {
209    Unavailable,
210    Available,
211    ExecuteInProgress,
212    ExecuteComplete,
213    ExecuteFailed,
214    Obsolete,
215}
216
217#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
218#[serde(deny_unknown_fields)]
219pub struct CloudFormationChangeSet {
220    pub change_set_name: String,
221    pub change_set_id: String,
222    pub stack_id: String,
223    pub stack_name: String,
224    pub change_set_type: ChangeSetType,
225    pub status: ChangeSetStatus,
226    pub execution_status: ExecutionStatus,
227    pub review: ChangeSetReview,
228}
229
230impl CloudFormationChangeSet {
231    pub fn from_aws_json(
232        source: &[u8],
233        expected_change_set_type: ChangeSetType,
234    ) -> Result<Self, ChangeReviewError> {
235        let provider: ProviderChangeSet = serde_json::from_slice(source)?;
236        if let Some(actual) = provider.change_set_type.map(Into::into)
237            && actual != expected_change_set_type
238        {
239            return Err(ChangeReviewError::UnexpectedChangeSetType {
240                expected: expected_change_set_type,
241                actual,
242            });
243        }
244        let changes = provider
245            .changes
246            .into_iter()
247            .map(|change| {
248                if change.kind != "Resource" {
249                    return Err(ChangeReviewError::UnsupportedChangeType(change.kind));
250                }
251                let mut resource = ResourceChange::new(
252                    change.resource_change.logical_resource_id,
253                    change.resource_change.resource_type,
254                    change.resource_change.action.into(),
255                    change.resource_change.replacement.map(Into::into),
256                );
257                resource.policy_action = change.resource_change.policy_action.map(Into::into);
258                resource.scope = change
259                    .resource_change
260                    .scope
261                    .into_iter()
262                    .map(Into::into)
263                    .collect();
264                resource.scope.sort();
265                resource.scope.dedup();
266                Ok(resource)
267            })
268            .collect::<Result<Vec<_>, _>>()?;
269        Ok(Self {
270            change_set_name: provider.change_set_name,
271            change_set_id: provider.change_set_id,
272            stack_id: provider.stack_id,
273            stack_name: provider.stack_name,
274            change_set_type: expected_change_set_type,
275            status: provider.status.into(),
276            execution_status: provider.execution_status.into(),
277            review: ChangeSetReview::classify(changes)?,
278        })
279    }
280}
281
282#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
283#[serde(tag = "status", rename_all = "snake_case")]
284pub enum StackDrift {
285    NotApplicableNewStack,
286    InSync {
287        detection_id: String,
288        checked_at: String,
289    },
290}
291
292#[derive(Debug, Clone, PartialEq, Eq)]
293pub struct ChangeSetReceiptInput {
294    pub source_change: String,
295    pub release_manifest: FileDigest,
296    pub release_id: String,
297    pub release_digest: String,
298    pub release_approval_digest: String,
299    pub configuration_digest: String,
300    pub environment: ReleaseEnvironment,
301    pub expected_account_id: String,
302    pub expected_role_arn: String,
303    pub target_config: FileDigest,
304    pub packaged_template: FileDigest,
305    pub drift: StackDrift,
306    pub change_set: CloudFormationChangeSet,
307}
308
309#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
310#[serde(deny_unknown_fields)]
311pub struct ChangeSetReceipt {
312    pub schema_version: u32,
313    pub receipt_digest: String,
314    pub source_change: String,
315    pub release_manifest: FileDigest,
316    pub release_id: String,
317    pub release_digest: String,
318    pub release_approval_digest: String,
319    pub configuration_digest: String,
320    pub environment: ReleaseEnvironment,
321    pub expected_account_id: String,
322    pub expected_role_arn: String,
323    pub target_config: FileDigest,
324    pub packaged_template: FileDigest,
325    pub drift: StackDrift,
326    pub change_set: CloudFormationChangeSet,
327}
328
329impl ChangeSetReceipt {
330    pub fn seal(input: ChangeSetReceiptInput) -> Result<Self, ChangeSetReceiptError> {
331        let mut receipt = Self {
332            schema_version: 1,
333            receipt_digest: String::new(),
334            source_change: input.source_change,
335            release_manifest: input.release_manifest,
336            release_id: input.release_id,
337            release_digest: input.release_digest,
338            release_approval_digest: input.release_approval_digest,
339            configuration_digest: input.configuration_digest,
340            environment: input.environment,
341            expected_account_id: input.expected_account_id,
342            expected_role_arn: input.expected_role_arn,
343            target_config: input.target_config,
344            packaged_template: input.packaged_template,
345            drift: input.drift,
346            change_set: input.change_set,
347        };
348        receipt.receipt_digest = receipt.calculate_digest()?;
349        receipt.verify_structure()?;
350        Ok(receipt)
351    }
352
353    pub fn verify_structure(&self) -> Result<(), ChangeSetReceiptError> {
354        if self.schema_version != 1 {
355            return Err(ChangeSetReceiptError::Invalid(
356                "unsupported change-set receipt schema".into(),
357            ));
358        }
359        if !source_change_is_valid(&self.source_change) {
360            return Err(ChangeSetReceiptError::Invalid(
361                "source change must be an exact lowercase VCS commit ID".into(),
362            ));
363        }
364        if !release_identity_is_valid(&self.release_id, &self.release_digest)
365            || self.release_approval_digest != self.release_digest
366            || !sha256_is_valid(&self.configuration_digest)
367        {
368            return Err(ChangeSetReceiptError::Invalid(
369                "release identity, configuration, or approval is invalid".into(),
370            ));
371        }
372        for (file, label) in [
373            (&self.release_manifest, "release manifest"),
374            (&self.target_config, "target configuration"),
375            (&self.packaged_template, "packaged template"),
376        ] {
377            validate_bound_file(file, label)?;
378        }
379        if !environment_is_valid(&self.environment.environment)
380            || !region_is_valid(&self.environment.region)
381            || self.environment.application.is_empty()
382            || !account_id_is_valid(&self.expected_account_id)
383            || !role_arn_is_valid(&self.expected_role_arn, &self.expected_account_id)
384            || !stack_name_is_valid(&self.change_set.stack_name)
385        {
386            return Err(ChangeSetReceiptError::Invalid(
387                "deployment environment identity is invalid".into(),
388            ));
389        }
390        if self.change_set.status != ChangeSetStatus::CreateComplete
391            || self.change_set.execution_status != ExecutionStatus::Available
392        {
393            return Err(ChangeSetReceiptError::Invalid(
394                "change set is not complete and available".into(),
395            ));
396        }
397        match (&self.change_set.change_set_type, &self.drift) {
398            (ChangeSetType::Create, StackDrift::NotApplicableNewStack)
399            | (ChangeSetType::Update, StackDrift::InSync { .. }) => {}
400            _ => {
401                return Err(ChangeSetReceiptError::Invalid(
402                    "change-set type and drift evidence are inconsistent".into(),
403                ));
404            }
405        }
406        let role_partition = self
407            .expected_role_arn
408            .split(':')
409            .nth(1)
410            .ok_or_else(|| ChangeSetReceiptError::Invalid("role ARN is invalid".into()))?;
411        for (arn, kind, name) in [
412            (
413                &self.change_set.change_set_id,
414                "changeSet",
415                self.change_set.change_set_name.as_str(),
416            ),
417            (
418                &self.change_set.stack_id,
419                "stack",
420                self.change_set.stack_name.as_str(),
421            ),
422        ] {
423            let (partition, region, account_id) = cloudformation_arn_identity(arn, kind, name)?;
424            if region != self.environment.region || account_id != self.expected_account_id {
425                return Err(ChangeSetReceiptError::Invalid(
426                    "change-set ARN does not match the reviewed target".into(),
427                ));
428            }
429            if partition != role_partition {
430                return Err(ChangeSetReceiptError::Invalid(
431                    "change-set ARN partition does not match the reviewed role".into(),
432                ));
433            }
434        }
435        if let StackDrift::InSync {
436            detection_id,
437            checked_at,
438        } = &self.drift
439            && (detection_id.is_empty() || checked_at.is_empty())
440        {
441            return Err(ChangeSetReceiptError::Invalid(
442                "drift evidence is incomplete".into(),
443            ));
444        }
445        if !sha256_is_valid(&self.receipt_digest) {
446            return Err(ChangeSetReceiptError::Invalid(
447                "change-set receipt digest is invalid".into(),
448            ));
449        }
450        if self.calculate_digest()? != self.receipt_digest {
451            return Err(ChangeSetReceiptError::DigestMismatch);
452        }
453        Ok(())
454    }
455
456    pub fn from_json(source: &[u8]) -> Result<Self, ChangeSetReceiptError> {
457        let value: serde_json::Value = serde_json::from_slice(source)?;
458        let receipt: Self = serde_json::from_value(value.clone())?;
459        if serde_json::to_value(&receipt)? != value {
460            return Err(ChangeSetReceiptError::Invalid(
461                "change-set receipt contains unknown or non-canonical fields".into(),
462            ));
463        }
464        receipt.verify_structure()?;
465        Ok(receipt)
466    }
467
468    pub fn verify_at(&self, root: impl AsRef<Path>) -> Result<(), ChangeSetReceiptError> {
469        self.verify_structure()?;
470        let root = root.as_ref();
471        for file in [
472            &self.release_manifest,
473            &self.target_config,
474            &self.packaged_template,
475        ] {
476            file.verify_at(root).map_err(|error| {
477                ChangeSetReceiptError::Invalid(format!("bound file verification failed: {error}"))
478            })?;
479        }
480        let release =
481            minco_release::ReleaseManifest::read_json(root.join(&self.release_manifest.path))
482                .and_then(|release| release.verify_at(root).map(|()| release))
483                .map_err(|error| {
484                    ChangeSetReceiptError::Invalid(format!("release verification failed: {error}"))
485                })?;
486        if release.source_change != self.source_change
487            || release.release_id != self.release_id
488            || release.release_digest != self.release_digest
489            || release.configuration_digest != self.configuration_digest
490            || release.environment != self.environment
491        {
492            return Err(ChangeSetReceiptError::Invalid(
493                "receipt does not match the verified release manifest".into(),
494            ));
495        }
496        let catalog = DeploymentTargetCatalog::from_toml(&std::fs::read_to_string(
497            root.join(&self.target_config.path),
498        )?)
499        .map_err(|error| {
500            ChangeSetReceiptError::Invalid(format!(
501                "deployment target verification failed: {error}"
502            ))
503        })?;
504        let selected = catalog
505            .select(Some(&self.environment.environment))
506            .map_err(|error| {
507                ChangeSetReceiptError::Invalid(format!(
508                    "deployment target selection failed: {error}"
509                ))
510            })?;
511        if !selected.target.enabled
512            || selected.target.expected_account_id != self.expected_account_id
513            || selected.target.expected_region != self.environment.region
514            || selected.target.expected_role_arn != self.expected_role_arn
515            || selected.target.stack_name != self.change_set.stack_name
516        {
517            return Err(ChangeSetReceiptError::Invalid(
518                "receipt does not match the enabled reviewed target".into(),
519            ));
520        }
521        Ok(())
522    }
523
524    pub fn write_json(&self, path: impl AsRef<Path>) -> Result<(), ChangeSetReceiptError> {
525        self.verify_structure()?;
526        let path = path.as_ref();
527        let mut rendered = serde_json::to_vec_pretty(self)?;
528        rendered.push(b'\n');
529        if path.exists() {
530            if std::fs::read(path)? == rendered {
531                return Ok(());
532            }
533            return Err(ChangeSetReceiptError::Conflict(path.display().to_string()));
534        }
535        let mut output = std::fs::OpenOptions::new()
536            .write(true)
537            .create_new(true)
538            .open(path)?;
539        output.write_all(&rendered)?;
540        output.sync_all()?;
541        Ok(())
542    }
543
544    fn calculate_digest(&self) -> Result<String, ChangeSetReceiptError> {
545        #[derive(Serialize)]
546        struct DigestPayload<'a> {
547            schema_version: u32,
548            source_change: &'a str,
549            release_manifest: &'a FileDigest,
550            release_id: &'a str,
551            release_digest: &'a str,
552            release_approval_digest: &'a str,
553            configuration_digest: &'a str,
554            environment: &'a ReleaseEnvironment,
555            expected_account_id: &'a str,
556            expected_role_arn: &'a str,
557            target_config: &'a FileDigest,
558            packaged_template: &'a FileDigest,
559            drift: &'a StackDrift,
560            change_set: &'a CloudFormationChangeSet,
561        }
562        let payload = DigestPayload {
563            schema_version: self.schema_version,
564            source_change: &self.source_change,
565            release_manifest: &self.release_manifest,
566            release_id: &self.release_id,
567            release_digest: &self.release_digest,
568            release_approval_digest: &self.release_approval_digest,
569            configuration_digest: &self.configuration_digest,
570            environment: &self.environment,
571            expected_account_id: &self.expected_account_id,
572            expected_role_arn: &self.expected_role_arn,
573            target_config: &self.target_config,
574            packaged_template: &self.packaged_template,
575            drift: &self.drift,
576            change_set: &self.change_set,
577        };
578        Ok(hex::encode(Sha256::digest(serde_json::to_vec(&payload)?)))
579    }
580}
581
582#[derive(Debug, Error)]
583pub enum ChangeSetReceiptError {
584    #[error("change-set receipt is invalid: {0}")]
585    Invalid(String),
586    #[error("change-set receipt digest does not match its contents")]
587    DigestMismatch,
588    #[error("immutable change-set receipt already exists at {0}")]
589    Conflict(String),
590    #[error("change-set receipt JSON is invalid: {0}")]
591    Json(#[from] serde_json::Error),
592    #[error("change-set receipt I/O failed: {0}")]
593    Io(#[from] std::io::Error),
594}
595
596#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
597#[serde(deny_unknown_fields)]
598pub struct UntrustedFeedbackReference {
599    pub feedback_id: String,
600    pub sha256: String,
601}
602
603#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
604#[serde(rename_all = "snake_case")]
605pub enum ReviewResourceRetention {
606    Delete,
607    Retain,
608}
609
610#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
611#[serde(rename_all = "snake_case")]
612pub enum ReviewCostClass {
613    ZeroCompute,
614    RequestOnly,
615    StorageOnly,
616    ScheduledWakeup,
617    FixedMonthly,
618}
619
620#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
621#[serde(deny_unknown_fields)]
622pub struct ReviewResource {
623    pub logical_id: String,
624    pub resource_type: String,
625    pub retention: ReviewResourceRetention,
626    pub idle_cost_class: ReviewCostClass,
627}
628
629#[derive(Debug, Clone, PartialEq, Eq)]
630pub struct ReviewManifestInput {
631    pub source_change: String,
632    pub release_manifest: FileDigest,
633    pub release_id: String,
634    pub release_digest: String,
635    pub artifacts: Vec<FileDigest>,
636    pub environment: ReleaseEnvironment,
637    pub expected_account_id: String,
638    pub expected_role_arn: String,
639    pub stack_name: String,
640    pub target_config: FileDigest,
641    pub owner: String,
642    pub created_at: String,
643    pub expires_at: String,
644    pub resources: Vec<ReviewResource>,
645    pub pricing_complete: bool,
646    pub cleanup_schedule: Option<ReviewCleanupSchedule>,
647    pub verification: Vec<FileDigest>,
648    pub feedback: Vec<UntrustedFeedbackReference>,
649    pub delivery_trace: Vec<FileDigest>,
650}
651
652#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
653#[serde(deny_unknown_fields)]
654pub struct ReviewManifest {
655    pub schema_version: u32,
656    pub review_id: String,
657    pub manifest_digest: String,
658    pub source_change: String,
659    pub release_manifest: FileDigest,
660    pub release_id: String,
661    pub release_digest: String,
662    pub artifacts: Vec<FileDigest>,
663    pub environment: ReleaseEnvironment,
664    pub expected_account_id: String,
665    pub expected_role_arn: String,
666    pub stack_name: String,
667    pub target_config: FileDigest,
668    pub owner: String,
669    pub created_at: String,
670    pub expires_at: String,
671    pub resources: Vec<ReviewResource>,
672    pub pricing_complete: bool,
673    #[serde(default)]
674    pub cleanup_schedule: Option<ReviewCleanupSchedule>,
675    pub verification: Vec<FileDigest>,
676    pub feedback: Vec<UntrustedFeedbackReference>,
677    pub delivery_trace: Vec<FileDigest>,
678}
679
680impl ReviewManifest {
681    pub fn seal(mut input: ReviewManifestInput) -> Result<Self, ReviewManifestError> {
682        input.artifacts.sort();
683        input
684            .resources
685            .sort_by(|left, right| left.logical_id.cmp(&right.logical_id));
686        input.verification.sort();
687        input
688            .feedback
689            .sort_by(|left, right| left.feedback_id.cmp(&right.feedback_id));
690        input.delivery_trace.sort();
691        let mut manifest = Self {
692            schema_version: 1,
693            review_id: String::new(),
694            manifest_digest: String::new(),
695            source_change: input.source_change,
696            release_manifest: input.release_manifest,
697            release_id: input.release_id,
698            release_digest: input.release_digest,
699            artifacts: input.artifacts,
700            environment: input.environment,
701            expected_account_id: input.expected_account_id,
702            expected_role_arn: input.expected_role_arn,
703            stack_name: input.stack_name,
704            target_config: input.target_config,
705            owner: input.owner,
706            created_at: input.created_at,
707            expires_at: input.expires_at,
708            resources: input.resources,
709            pricing_complete: input.pricing_complete,
710            cleanup_schedule: input.cleanup_schedule,
711            verification: input.verification,
712            feedback: input.feedback,
713            delivery_trace: input.delivery_trace,
714        };
715        manifest.manifest_digest = manifest.calculate_digest()?;
716        manifest.review_id = format!("minco-review.{}", &manifest.manifest_digest[..24]);
717        manifest.verify_structure()?;
718        Ok(manifest)
719    }
720
721    pub fn verify_structure(&self) -> Result<(), ReviewManifestError> {
722        if self.schema_version != 1 {
723            return Err(ReviewManifestError::Invalid(
724                "unsupported review manifest schema".into(),
725            ));
726        }
727        if !source_change_is_valid(&self.source_change)
728            || !release_identity_is_valid(&self.release_id, &self.release_digest)
729        {
730            return Err(ReviewManifestError::Invalid(
731                "review source or release identity is invalid".into(),
732            ));
733        }
734        if self.environment.application.trim().is_empty()
735            || (self.environment.environment != "preview"
736                && !self.environment.environment.starts_with("preview-"))
737            || !region_is_valid(&self.environment.region)
738            || !account_id_is_valid(&self.expected_account_id)
739            || !role_arn_is_valid(&self.expected_role_arn, &self.expected_account_id)
740            || !stack_name_is_valid(&self.stack_name)
741        {
742            return Err(ReviewManifestError::Invalid(
743                "review target is not an exact preview environment".into(),
744            ));
745        }
746        if self.owner.trim().is_empty()
747            || self.owner.len() > 256
748            || self.owner.chars().any(char::is_control)
749        {
750            return Err(ReviewManifestError::Invalid(
751                "review owner is invalid".into(),
752            ));
753        }
754        let created_at = parse_utc_timestamp(&self.created_at).ok_or_else(|| {
755            ReviewManifestError::Invalid("created_at is not canonical UTC".into())
756        })?;
757        let expires_at = parse_utc_timestamp(&self.expires_at).ok_or_else(|| {
758            ReviewManifestError::Invalid("expires_at is not canonical UTC".into())
759        })?;
760        let ttl = expires_at - created_at;
761        if !(300..=2_592_000).contains(&ttl) {
762            return Err(ReviewManifestError::Invalid(
763                "review TTL must be 5 minutes to 30 days".into(),
764            ));
765        }
766        for (file, label) in [
767            (&self.release_manifest, "release manifest"),
768            (&self.target_config, "target configuration"),
769        ] {
770            validate_bound_file(file, label)
771                .map_err(|error| ReviewManifestError::Invalid(error.to_string()))?;
772        }
773        if self.artifacts.is_empty() || self.verification.is_empty() {
774            return Err(ReviewManifestError::Invalid(
775                "review requires artifact and verification evidence".into(),
776            ));
777        }
778        for (files, label) in [
779            (&self.artifacts, "artifact"),
780            (&self.verification, "verification"),
781            (&self.delivery_trace, "delivery trace"),
782        ] {
783            for file in files {
784                validate_bound_file(file, label)
785                    .map_err(|error| ReviewManifestError::Invalid(error.to_string()))?;
786            }
787            if files.windows(2).any(|files| files[0] >= files[1]) {
788                return Err(ReviewManifestError::Invalid(format!(
789                    "review {label} evidence must be sorted and unique"
790                )));
791            }
792        }
793        if self.resources.is_empty()
794            || self
795                .resources
796                .windows(2)
797                .any(|resources| resources[0].logical_id >= resources[1].logical_id)
798            || self.resources.iter().any(|resource| {
799                !cloudformation_logical_id_is_valid(&resource.logical_id)
800                    || resource.resource_type.trim().is_empty()
801                    || resource.resource_type.chars().any(char::is_control)
802            })
803        {
804            return Err(ReviewManifestError::Invalid(
805                "review resources must be explicit, sorted, and unique".into(),
806            ));
807        }
808        if let Some(cleanup) = &self.cleanup_schedule {
809            let retained = self
810                .resources
811                .iter()
812                .filter(|resource| resource.retention == ReviewResourceRetention::Retain)
813                .map(|resource| resource.logical_id.clone())
814                .collect::<Vec<_>>();
815            if !one_time_schedule_expression_is_valid(&cleanup.expression)
816                || cleanup.residual_resources != retained
817                || cleanup.manual_fallback.trim().is_empty()
818                || cleanup.manual_fallback.chars().any(char::is_control)
819            {
820                return Err(ReviewManifestError::Invalid(
821                    "review cleanup schedule must be one-time, self-deleting, and retain a manual fallback"
822                        .into(),
823                ));
824            }
825        }
826        if self
827            .feedback
828            .windows(2)
829            .any(|feedback| feedback[0].feedback_id >= feedback[1].feedback_id)
830            || self.feedback.iter().any(|feedback| {
831                !stable_reference_is_valid(&feedback.feedback_id)
832                    || !sha256_is_valid(&feedback.sha256)
833            })
834        {
835            return Err(ReviewManifestError::Invalid(
836                "untrusted Feedback references must be sorted stable IDs and SHA-256 digests"
837                    .into(),
838            ));
839        }
840        if !sha256_is_valid(&self.manifest_digest)
841            || self.review_id != format!("minco-review.{}", &self.manifest_digest[..24])
842        {
843            return Err(ReviewManifestError::Invalid(
844                "review identity is not digest-derived".into(),
845            ));
846        }
847        if self.calculate_digest()? != self.manifest_digest {
848            return Err(ReviewManifestError::DigestMismatch);
849        }
850        Ok(())
851    }
852
853    pub fn from_json(source: &[u8]) -> Result<Self, ReviewManifestError> {
854        let value: serde_json::Value = serde_json::from_slice(source)?;
855        let manifest: Self = serde_json::from_value(value.clone())?;
856        if serde_json::to_value(&manifest)? != value {
857            return Err(ReviewManifestError::Invalid(
858                "review manifest contains unknown or non-canonical fields".into(),
859            ));
860        }
861        manifest.verify_structure()?;
862        Ok(manifest)
863    }
864
865    pub fn verify_at(&self, root: impl AsRef<Path>) -> Result<(), ReviewManifestError> {
866        self.verify_structure()?;
867        let root = root.as_ref();
868        for file in self
869            .artifacts
870            .iter()
871            .chain(self.verification.iter())
872            .chain(self.delivery_trace.iter())
873            .chain([&self.release_manifest, &self.target_config])
874        {
875            file.verify_at(root)
876                .map_err(|error| ReviewManifestError::Invalid(error.to_string()))?;
877        }
878        let release =
879            minco_release::ReleaseManifest::read_json(root.join(&self.release_manifest.path))
880                .and_then(|release| release.verify_at(root).map(|()| release))
881                .map_err(|error| ReviewManifestError::Invalid(error.to_string()))?;
882        let mut release_artifacts = release
883            .artifacts
884            .iter()
885            .map(|artifact| artifact.file.clone())
886            .collect::<Vec<_>>();
887        release_artifacts.sort();
888        if release.source_change != self.source_change
889            || release.release_id != self.release_id
890            || release.release_digest != self.release_digest
891            || release.environment != self.environment
892            || release_artifacts != self.artifacts
893        {
894            return Err(ReviewManifestError::Invalid(
895                "review does not bind the exact verified release".into(),
896            ));
897        }
898        let deployment_receipt_count = self
899            .verification
900            .iter()
901            .filter_map(|file| {
902                let receipt = DeploymentReceipt::read_json(root.join(&file.path)).ok()?;
903                receipt.verify_at(root).ok()?;
904                (receipt.outcome() == DeploymentOutcome::Succeeded
905                    && receipt.release_manifest == self.release_manifest
906                    && receipt.release_id == self.release_id
907                    && receipt.release_digest == self.release_digest
908                    && receipt.environment == self.environment)
909                    .then_some(receipt)
910            })
911            .count();
912        if deployment_receipt_count != 1 {
913            return Err(ReviewManifestError::Invalid(
914                "review verification must bind exactly one successful deployment receipt".into(),
915            ));
916        }
917        let change_set_receipt_count = self
918            .delivery_trace
919            .iter()
920            .filter_map(|file| {
921                let receipt =
922                    ChangeSetReceipt::from_json(&std::fs::read(root.join(&file.path)).ok()?)
923                        .ok()?;
924                receipt.verify_at(root).ok()?;
925                (receipt.release_manifest == self.release_manifest
926                    && receipt.release_id == self.release_id
927                    && receipt.release_digest == self.release_digest
928                    && receipt.environment == self.environment
929                    && receipt.expected_account_id == self.expected_account_id
930                    && receipt.expected_role_arn == self.expected_role_arn
931                    && receipt.target_config == self.target_config
932                    && receipt.change_set.stack_name == self.stack_name)
933                    .then_some(receipt)
934            })
935            .count();
936        if change_set_receipt_count != 1 {
937            return Err(ReviewManifestError::Invalid(
938                "review delivery trace must bind exactly one exact change-set receipt".into(),
939            ));
940        }
941        let catalog = DeploymentTargetCatalog::from_toml(&std::fs::read_to_string(
942            root.join(&self.target_config.path),
943        )?)
944        .map_err(|error| ReviewManifestError::Invalid(error.to_string()))?;
945        let selected = catalog
946            .select(Some(&self.environment.environment))
947            .map_err(|error| ReviewManifestError::Invalid(error.to_string()))?;
948        let preview = selected.target.preview.as_ref().ok_or_else(|| {
949            ReviewManifestError::Invalid("review target has no preview lifecycle policy".into())
950        })?;
951        let created_at = parse_utc_timestamp(&self.created_at)
952            .ok_or_else(|| ReviewManifestError::Invalid("review created_at is invalid".into()))?;
953        let expires_at = parse_utc_timestamp(&self.expires_at)
954            .ok_or_else(|| ReviewManifestError::Invalid("review expires_at is invalid".into()))?;
955        let configured_resources = preview
956            .resources
957            .iter()
958            .all(|configured| self.resources.contains(configured));
959        if selected.target.lifecycle != DeploymentTargetLifecycle::Preview
960            || selected.target.expected_account_id != self.expected_account_id
961            || selected.target.expected_region != self.environment.region
962            || selected.target.expected_role_arn != self.expected_role_arn
963            || selected.target.stack_name != self.stack_name
964            || preview.owner != self.owner
965            || i64::from(preview.ttl_seconds) != expires_at - created_at
966            || preview.pricing_complete != self.pricing_complete
967            || preview.cleanup_schedule != self.cleanup_schedule
968            || !configured_resources
969        {
970            return Err(ReviewManifestError::Invalid(
971                "review does not match the reviewed preview target policy".into(),
972            ));
973        }
974        Ok(())
975    }
976
977    pub fn write_json(&self, path: impl AsRef<Path>) -> Result<(), ReviewManifestError> {
978        self.verify_structure()?;
979        let path = path.as_ref();
980        let mut rendered = serde_json::to_vec_pretty(self)?;
981        rendered.push(b'\n');
982        if path.exists() {
983            if std::fs::read(path)? == rendered {
984                return Ok(());
985            }
986            return Err(ReviewManifestError::Conflict(path.display().to_string()));
987        }
988        let mut output = std::fs::OpenOptions::new()
989            .write(true)
990            .create_new(true)
991            .open(path)?;
992        output.write_all(&rendered)?;
993        output.sync_all()?;
994        Ok(())
995    }
996
997    fn calculate_digest(&self) -> Result<String, ReviewManifestError> {
998        #[derive(Serialize)]
999        struct DigestPayload<'a> {
1000            schema_version: u32,
1001            source_change: &'a str,
1002            release_manifest: &'a FileDigest,
1003            release_id: &'a str,
1004            release_digest: &'a str,
1005            artifacts: &'a [FileDigest],
1006            environment: &'a ReleaseEnvironment,
1007            expected_account_id: &'a str,
1008            expected_role_arn: &'a str,
1009            stack_name: &'a str,
1010            target_config: &'a FileDigest,
1011            owner: &'a str,
1012            created_at: &'a str,
1013            expires_at: &'a str,
1014            resources: &'a [ReviewResource],
1015            pricing_complete: bool,
1016            cleanup_schedule: &'a Option<ReviewCleanupSchedule>,
1017            verification: &'a [FileDigest],
1018            feedback: &'a [UntrustedFeedbackReference],
1019            delivery_trace: &'a [FileDigest],
1020        }
1021        let payload = DigestPayload {
1022            schema_version: self.schema_version,
1023            source_change: &self.source_change,
1024            release_manifest: &self.release_manifest,
1025            release_id: &self.release_id,
1026            release_digest: &self.release_digest,
1027            artifacts: &self.artifacts,
1028            environment: &self.environment,
1029            expected_account_id: &self.expected_account_id,
1030            expected_role_arn: &self.expected_role_arn,
1031            stack_name: &self.stack_name,
1032            target_config: &self.target_config,
1033            owner: &self.owner,
1034            created_at: &self.created_at,
1035            expires_at: &self.expires_at,
1036            resources: &self.resources,
1037            pricing_complete: self.pricing_complete,
1038            cleanup_schedule: &self.cleanup_schedule,
1039            verification: &self.verification,
1040            feedback: &self.feedback,
1041            delivery_trace: &self.delivery_trace,
1042        };
1043        Ok(hex::encode(Sha256::digest(serde_json::to_vec(&payload)?)))
1044    }
1045}
1046
1047fn cloudformation_logical_id_is_valid(value: &str) -> bool {
1048    let mut bytes = value.bytes();
1049    value.len() <= 255
1050        && bytes.next().is_some_and(|byte| byte.is_ascii_alphabetic())
1051        && bytes.all(|byte| byte.is_ascii_alphanumeric())
1052}
1053
1054fn parse_utc_timestamp(value: &str) -> Option<i64> {
1055    let bytes = value.as_bytes();
1056    if bytes.len() != 20
1057        || bytes[4] != b'-'
1058        || bytes[7] != b'-'
1059        || bytes[10] != b'T'
1060        || bytes[13] != b':'
1061        || bytes[16] != b':'
1062        || bytes[19] != b'Z'
1063    {
1064        return None;
1065    }
1066    let number = |start: usize, end: usize| {
1067        bytes[start..end].iter().try_fold(0_i64, |value, byte| {
1068            byte.is_ascii_digit()
1069                .then(|| value * 10 + i64::from(byte - b'0'))
1070        })
1071    };
1072    let year = number(0, 4)?;
1073    let month = number(5, 7)?;
1074    let day = number(8, 10)?;
1075    let hour = number(11, 13)?;
1076    let minute = number(14, 16)?;
1077    let second = number(17, 19)?;
1078    if year < 1970 || !(1..=12).contains(&month) || hour > 23 || minute > 59 || second > 59 {
1079        return None;
1080    }
1081    let leap = |year: i64| year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
1082    let month_days = [31_i64, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
1083    let maximum_day =
1084        month_days[usize::try_from(month - 1).ok()?] + i64::from(month == 2 && leap(year));
1085    if day == 0 || day > maximum_day {
1086        return None;
1087    }
1088    let mut days = 0_i64;
1089    for current_year in 1970..year {
1090        days += 365 + i64::from(leap(current_year));
1091    }
1092    for current_month in 1..month {
1093        days += month_days[usize::try_from(current_month - 1).ok()?]
1094            + i64::from(current_month == 2 && leap(year));
1095    }
1096    days += day - 1;
1097    Some(days * 86_400 + hour * 3_600 + minute * 60 + second)
1098}
1099
1100fn one_time_schedule_expression_is_valid(value: &str) -> bool {
1101    value
1102        .strip_prefix("at(")
1103        .and_then(|value| value.strip_suffix(')'))
1104        .is_some_and(|timestamp| parse_utc_timestamp(&format!("{timestamp}Z")).is_some())
1105}
1106
1107fn stable_reference_is_valid(value: &str) -> bool {
1108    (1..=256).contains(&value.len())
1109        && value.bytes().all(|byte| {
1110            byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':' | b'/')
1111        })
1112}
1113
1114#[derive(Debug, Error)]
1115pub enum ReviewManifestError {
1116    #[error("review manifest is invalid: {0}")]
1117    Invalid(String),
1118    #[error("review manifest digest does not match its contents")]
1119    DigestMismatch,
1120    #[error("immutable review manifest already exists at {0}")]
1121    Conflict(String),
1122    #[error("review manifest JSON is invalid: {0}")]
1123    Json(#[from] serde_json::Error),
1124    #[error("review manifest I/O failed: {0}")]
1125    Io(#[from] std::io::Error),
1126}
1127
1128#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1129#[serde(rename_all = "snake_case")]
1130pub enum CleanupOutcome {
1131    Started,
1132    Failed,
1133    Succeeded,
1134}
1135
1136#[derive(Debug, Clone, PartialEq, Eq)]
1137pub struct CleanupReceiptInput {
1138    pub attempt_id: String,
1139    pub review_manifest: FileDigest,
1140    pub review_id: String,
1141    pub review_digest: String,
1142    pub environment: ReleaseEnvironment,
1143    pub expected_account_id: String,
1144    pub expected_role_arn: String,
1145    pub stack_name: String,
1146    pub target_config: FileDigest,
1147    pub deleted_resources: Vec<ReviewResource>,
1148    pub retained_resources: Vec<ReviewResource>,
1149}
1150
1151#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1152#[serde(deny_unknown_fields)]
1153pub struct CleanupReceipt {
1154    pub schema_version: u32,
1155    pub receipt_digest: String,
1156    pub attempt_id: String,
1157    pub review_manifest: FileDigest,
1158    pub review_id: String,
1159    pub review_digest: String,
1160    pub environment: ReleaseEnvironment,
1161    pub expected_account_id: String,
1162    pub expected_role_arn: String,
1163    pub stack_name: String,
1164    pub target_config: FileDigest,
1165    pub deleted_resources: Vec<ReviewResource>,
1166    pub retained_resources: Vec<ReviewResource>,
1167    outcome: CleanupOutcome,
1168    failure_code: Option<String>,
1169    absence_verified_at: Option<String>,
1170}
1171
1172impl CleanupReceipt {
1173    pub fn start(mut input: CleanupReceiptInput) -> Result<Self, CleanupReceiptError> {
1174        input
1175            .deleted_resources
1176            .sort_by(|left, right| left.logical_id.cmp(&right.logical_id));
1177        input
1178            .retained_resources
1179            .sort_by(|left, right| left.logical_id.cmp(&right.logical_id));
1180        let mut receipt = Self {
1181            schema_version: 1,
1182            receipt_digest: String::new(),
1183            attempt_id: input.attempt_id,
1184            review_manifest: input.review_manifest,
1185            review_id: input.review_id,
1186            review_digest: input.review_digest,
1187            environment: input.environment,
1188            expected_account_id: input.expected_account_id,
1189            expected_role_arn: input.expected_role_arn,
1190            stack_name: input.stack_name,
1191            target_config: input.target_config,
1192            deleted_resources: input.deleted_resources,
1193            retained_resources: input.retained_resources,
1194            outcome: CleanupOutcome::Started,
1195            failure_code: None,
1196            absence_verified_at: None,
1197        };
1198        receipt.refresh_digest()?;
1199        receipt.verify_structure()?;
1200        Ok(receipt)
1201    }
1202
1203    pub const fn outcome(&self) -> CleanupOutcome {
1204        self.outcome
1205    }
1206
1207    pub fn failure_code(&self) -> Option<&str> {
1208        self.failure_code.as_deref()
1209    }
1210
1211    pub fn absence_verified_at(&self) -> Option<&str> {
1212        self.absence_verified_at.as_deref()
1213    }
1214
1215    pub fn fail(&mut self, failure_code: impl Into<String>) -> Result<(), CleanupReceiptError> {
1216        self.require_started()?;
1217        let failure_code = failure_code.into();
1218        if !stable_reference_is_valid(&failure_code) {
1219            return Err(CleanupReceiptError::Invalid(
1220                "cleanup failure code is invalid".into(),
1221            ));
1222        }
1223        self.outcome = CleanupOutcome::Failed;
1224        self.failure_code = Some(failure_code);
1225        self.refresh_digest()?;
1226        self.verify_structure()
1227    }
1228
1229    pub fn succeed(
1230        &mut self,
1231        absence_verified_at: impl Into<String>,
1232    ) -> Result<(), CleanupReceiptError> {
1233        self.require_started()?;
1234        let absence_verified_at = absence_verified_at.into();
1235        if parse_utc_timestamp(&absence_verified_at).is_none() {
1236            return Err(CleanupReceiptError::Invalid(
1237                "cleanup absence verification time is not canonical UTC".into(),
1238            ));
1239        }
1240        self.outcome = CleanupOutcome::Succeeded;
1241        self.absence_verified_at = Some(absence_verified_at);
1242        self.refresh_digest()?;
1243        self.verify_structure()
1244    }
1245
1246    pub fn verify_structure(&self) -> Result<(), CleanupReceiptError> {
1247        if self.schema_version != 1
1248            || !stable_reference_is_valid(&self.attempt_id)
1249            || !sha256_is_valid(&self.review_digest)
1250            || self.review_id != format!("minco-review.{}", &self.review_digest[..24])
1251        {
1252            return Err(CleanupReceiptError::Invalid(
1253                "cleanup receipt identity is invalid".into(),
1254            ));
1255        }
1256        for (file, label) in [
1257            (&self.review_manifest, "review manifest"),
1258            (&self.target_config, "target configuration"),
1259        ] {
1260            validate_bound_file(file, label)
1261                .map_err(|error| CleanupReceiptError::Invalid(error.to_string()))?;
1262        }
1263        if self.environment.application.trim().is_empty()
1264            || (self.environment.environment != "preview"
1265                && !self.environment.environment.starts_with("preview-"))
1266            || !region_is_valid(&self.environment.region)
1267            || !account_id_is_valid(&self.expected_account_id)
1268            || !role_arn_is_valid(&self.expected_role_arn, &self.expected_account_id)
1269            || !stack_name_is_valid(&self.stack_name)
1270        {
1271            return Err(CleanupReceiptError::Invalid(
1272                "cleanup target is not an exact preview environment".into(),
1273            ));
1274        }
1275        if self.deleted_resources.is_empty()
1276            || !cleanup_resources_are_valid(
1277                &self.deleted_resources,
1278                ReviewResourceRetention::Delete,
1279            )
1280            || !cleanup_resources_are_valid(
1281                &self.retained_resources,
1282                ReviewResourceRetention::Retain,
1283            )
1284            || self.deleted_resources.iter().any(|deleted| {
1285                self.retained_resources
1286                    .iter()
1287                    .any(|retained| retained.logical_id == deleted.logical_id)
1288            })
1289        {
1290            return Err(CleanupReceiptError::Invalid(
1291                "cleanup resources are invalid, repeated, or use the wrong retention policy".into(),
1292            ));
1293        }
1294        let state_valid = match self.outcome {
1295            CleanupOutcome::Started => {
1296                self.failure_code.is_none() && self.absence_verified_at.is_none()
1297            }
1298            CleanupOutcome::Failed => {
1299                self.failure_code
1300                    .as_deref()
1301                    .is_some_and(stable_reference_is_valid)
1302                    && self.absence_verified_at.is_none()
1303            }
1304            CleanupOutcome::Succeeded => {
1305                self.failure_code.is_none()
1306                    && self
1307                        .absence_verified_at
1308                        .as_deref()
1309                        .and_then(parse_utc_timestamp)
1310                        .is_some()
1311            }
1312        };
1313        if !state_valid {
1314            return Err(CleanupReceiptError::Invalid(
1315                "cleanup receipt outcome evidence is inconsistent".into(),
1316            ));
1317        }
1318        if !sha256_is_valid(&self.receipt_digest) {
1319            return Err(CleanupReceiptError::Invalid(
1320                "cleanup receipt digest is invalid".into(),
1321            ));
1322        }
1323        if self.calculate_digest()? != self.receipt_digest {
1324            return Err(CleanupReceiptError::DigestMismatch);
1325        }
1326        Ok(())
1327    }
1328
1329    pub fn from_json(source: &[u8]) -> Result<Self, CleanupReceiptError> {
1330        let value: serde_json::Value = serde_json::from_slice(source)?;
1331        let receipt: Self = serde_json::from_value(value.clone())?;
1332        if serde_json::to_value(&receipt)? != value {
1333            return Err(CleanupReceiptError::Invalid(
1334                "cleanup receipt contains unknown or non-canonical fields".into(),
1335            ));
1336        }
1337        receipt.verify_structure()?;
1338        Ok(receipt)
1339    }
1340
1341    pub fn read_json(path: impl AsRef<Path>) -> Result<Self, CleanupReceiptError> {
1342        Self::from_json(&std::fs::read(path)?)
1343    }
1344
1345    pub fn verify_at(&self, root: impl AsRef<Path>) -> Result<(), CleanupReceiptError> {
1346        self.verify_structure()?;
1347        let root = root.as_ref();
1348        for file in [&self.review_manifest, &self.target_config] {
1349            file.verify_at(root)
1350                .map_err(|error| CleanupReceiptError::Invalid(error.to_string()))?;
1351        }
1352        let review =
1353            ReviewManifest::from_json(&std::fs::read(root.join(&self.review_manifest.path))?)
1354                .and_then(|review| review.verify_at(root).map(|()| review))
1355                .map_err(|error| CleanupReceiptError::Invalid(error.to_string()))?;
1356        let deleted_resources = review
1357            .resources
1358            .iter()
1359            .filter(|resource| resource.retention == ReviewResourceRetention::Delete)
1360            .cloned()
1361            .collect::<Vec<_>>();
1362        let retained_resources = review
1363            .resources
1364            .iter()
1365            .filter(|resource| resource.retention == ReviewResourceRetention::Retain)
1366            .cloned()
1367            .collect::<Vec<_>>();
1368        let review_identity_matches =
1369            (&review.review_id, &review.manifest_digest) == (&self.review_id, &self.review_digest);
1370        if !review_identity_matches
1371            || review.environment != self.environment
1372            || review.expected_account_id != self.expected_account_id
1373            || review.expected_role_arn != self.expected_role_arn
1374            || review.stack_name != self.stack_name
1375            || review.target_config != self.target_config
1376            || deleted_resources != self.deleted_resources
1377            || retained_resources != self.retained_resources
1378        {
1379            return Err(CleanupReceiptError::Invalid(
1380                "cleanup receipt does not bind the exact verified review manifest".into(),
1381            ));
1382        }
1383        Ok(())
1384    }
1385
1386    pub fn write_json(&self, path: impl AsRef<Path>) -> Result<(), CleanupReceiptError> {
1387        self.verify_structure()?;
1388        let path = path.as_ref();
1389        let mut rendered = serde_json::to_vec_pretty(self)?;
1390        rendered.push(b'\n');
1391        if !path.exists() {
1392            let mut output = std::fs::OpenOptions::new()
1393                .write(true)
1394                .create_new(true)
1395                .open(path)?;
1396            output.write_all(&rendered)?;
1397            output.sync_all()?;
1398            return Ok(());
1399        }
1400        let existing = Self::read_json(path)?;
1401        if existing == *self {
1402            return Ok(());
1403        }
1404        let lock_path =
1405            path.with_extension(match path.extension().and_then(|value| value.to_str()) {
1406                Some(extension) => format!("{extension}.lock"),
1407                None => "lock".into(),
1408            });
1409        let mut lock = std::fs::OpenOptions::new()
1410            .write(true)
1411            .create_new(true)
1412            .open(&lock_path)
1413            .map_err(|error| {
1414                if error.kind() == std::io::ErrorKind::AlreadyExists {
1415                    CleanupReceiptError::Conflict(lock_path.display().to_string())
1416                } else {
1417                    CleanupReceiptError::Io(error)
1418                }
1419            })?;
1420        let temporary = path.with_extension(format!("{}.tmp", &self.receipt_digest[..16]));
1421        let result = (|| {
1422            lock.write_all(self.receipt_digest.as_bytes())?;
1423            lock.sync_all()?;
1424            let existing = Self::read_json(path)?;
1425            if existing == *self {
1426                return Ok(());
1427            }
1428            if !existing.same_binding(self)
1429                || existing.outcome != CleanupOutcome::Started
1430                || self.outcome == CleanupOutcome::Started
1431            {
1432                return Err(CleanupReceiptError::Conflict(path.display().to_string()));
1433            }
1434            let mut output = std::fs::OpenOptions::new()
1435                .write(true)
1436                .create_new(true)
1437                .open(&temporary)?;
1438            output.write_all(&rendered)?;
1439            output.sync_all()?;
1440            std::fs::rename(&temporary, path)?;
1441            Ok(())
1442        })();
1443        if result.is_err() {
1444            let _ = std::fs::remove_file(&temporary);
1445        }
1446        let unlock = std::fs::remove_file(&lock_path).map_err(CleanupReceiptError::Io);
1447        result.and(unlock)
1448    }
1449
1450    fn require_started(&self) -> Result<(), CleanupReceiptError> {
1451        if self.outcome == CleanupOutcome::Started {
1452            Ok(())
1453        } else {
1454            Err(CleanupReceiptError::Terminal(self.attempt_id.clone()))
1455        }
1456    }
1457
1458    fn same_binding(&self, other: &Self) -> bool {
1459        self.schema_version == other.schema_version
1460            && self.attempt_id == other.attempt_id
1461            && self.review_manifest == other.review_manifest
1462            && self.review_id == other.review_id
1463            && self.review_digest == other.review_digest
1464            && self.environment == other.environment
1465            && self.expected_account_id == other.expected_account_id
1466            && self.expected_role_arn == other.expected_role_arn
1467            && self.stack_name == other.stack_name
1468            && self.target_config == other.target_config
1469            && self.deleted_resources == other.deleted_resources
1470            && self.retained_resources == other.retained_resources
1471    }
1472
1473    fn refresh_digest(&mut self) -> Result<(), CleanupReceiptError> {
1474        self.receipt_digest = self.calculate_digest()?;
1475        Ok(())
1476    }
1477
1478    fn calculate_digest(&self) -> Result<String, CleanupReceiptError> {
1479        #[derive(Serialize)]
1480        struct DigestPayload<'a> {
1481            schema_version: u32,
1482            attempt_id: &'a str,
1483            review_manifest: &'a FileDigest,
1484            review_id: &'a str,
1485            review_digest: &'a str,
1486            environment: &'a ReleaseEnvironment,
1487            expected_account_id: &'a str,
1488            expected_role_arn: &'a str,
1489            stack_name: &'a str,
1490            target_config: &'a FileDigest,
1491            deleted_resources: &'a [ReviewResource],
1492            retained_resources: &'a [ReviewResource],
1493            outcome: CleanupOutcome,
1494            failure_code: &'a Option<String>,
1495            absence_verified_at: &'a Option<String>,
1496        }
1497        let payload = DigestPayload {
1498            schema_version: self.schema_version,
1499            attempt_id: &self.attempt_id,
1500            review_manifest: &self.review_manifest,
1501            review_id: &self.review_id,
1502            review_digest: &self.review_digest,
1503            environment: &self.environment,
1504            expected_account_id: &self.expected_account_id,
1505            expected_role_arn: &self.expected_role_arn,
1506            stack_name: &self.stack_name,
1507            target_config: &self.target_config,
1508            deleted_resources: &self.deleted_resources,
1509            retained_resources: &self.retained_resources,
1510            outcome: self.outcome,
1511            failure_code: &self.failure_code,
1512            absence_verified_at: &self.absence_verified_at,
1513        };
1514        Ok(hex::encode(Sha256::digest(serde_json::to_vec(&payload)?)))
1515    }
1516}
1517
1518fn cleanup_resources_are_valid(
1519    resources: &[ReviewResource],
1520    expected_retention: ReviewResourceRetention,
1521) -> bool {
1522    resources
1523        .windows(2)
1524        .all(|resources| resources[0].logical_id < resources[1].logical_id)
1525        && resources.iter().all(|resource| {
1526            resource.retention == expected_retention
1527                && cloudformation_logical_id_is_valid(&resource.logical_id)
1528                && !resource.resource_type.trim().is_empty()
1529        })
1530}
1531
1532#[derive(Debug, Error)]
1533pub enum CleanupReceiptError {
1534    #[error("cleanup receipt is invalid: {0}")]
1535    Invalid(String),
1536    #[error("cleanup receipt digest does not match its contents")]
1537    DigestMismatch,
1538    #[error("cleanup receipt conflicts with existing evidence at {0}")]
1539    Conflict(String),
1540    #[error("cleanup receipt {0} is terminal")]
1541    Terminal(String),
1542    #[error("cleanup receipt JSON is invalid: {0}")]
1543    Json(#[from] serde_json::Error),
1544    #[error("cleanup receipt I/O failed: {0}")]
1545    Io(#[from] std::io::Error),
1546}
1547
1548#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
1549#[serde(rename_all = "snake_case")]
1550pub enum HostedCheckKind {
1551    Contract,
1552    Readiness,
1553    Authentication,
1554    Smoke,
1555    ArtifactIdentity,
1556}
1557
1558impl HostedCheckKind {
1559    const REQUIRED: [Self; 5] = [
1560        Self::Contract,
1561        Self::Readiness,
1562        Self::Authentication,
1563        Self::Smoke,
1564        Self::ArtifactIdentity,
1565    ];
1566}
1567
1568#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1569#[serde(deny_unknown_fields)]
1570pub struct HostedCheckResult {
1571    pub kind: HostedCheckKind,
1572    pub passed: bool,
1573    pub request_id: Option<String>,
1574    pub status_code: Option<u16>,
1575}
1576
1577#[derive(Debug, Clone, PartialEq, Eq)]
1578pub struct HostedVerificationInput {
1579    pub endpoint: String,
1580    pub expected_artifact_digest: String,
1581    pub executed_artifact_digest: String,
1582    pub executed_version: String,
1583    pub checks: Vec<HostedCheckResult>,
1584}
1585
1586#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1587#[serde(deny_unknown_fields)]
1588pub struct HostedVerificationReport {
1589    pub endpoint: String,
1590    pub executed_artifact_digest: String,
1591    pub executed_version: String,
1592    pub checks: Vec<HostedCheckResult>,
1593}
1594
1595impl HostedVerificationReport {
1596    pub fn complete(mut input: HostedVerificationInput) -> Result<Self, HostedVerificationError> {
1597        let endpoint = url::Url::parse(&input.endpoint)
1598            .ok()
1599            .filter(|endpoint| {
1600                endpoint.scheme() == "https"
1601                    && endpoint.host_str().is_some()
1602                    && endpoint.username().is_empty()
1603                    && endpoint.password().is_none()
1604                    && endpoint.query().is_none()
1605                    && endpoint.fragment().is_none()
1606            })
1607            .ok_or(HostedVerificationError::InvalidField { field: "endpoint" })?;
1608        if !input
1609            .executed_version
1610            .parse::<u64>()
1611            .ok()
1612            .is_some_and(|version| version > 0 && version.to_string() == input.executed_version)
1613        {
1614            return Err(HostedVerificationError::InvalidField {
1615                field: "executed_version",
1616            });
1617        }
1618        if !sha256_is_valid(&input.expected_artifact_digest)
1619            || !sha256_is_valid(&input.executed_artifact_digest)
1620        {
1621            return Err(HostedVerificationError::InvalidField {
1622                field: "artifact_digest",
1623            });
1624        }
1625        for kind in HostedCheckKind::REQUIRED {
1626            let count = input
1627                .checks
1628                .iter()
1629                .filter(|check| check.kind == kind)
1630                .count();
1631            if count == 0 {
1632                return Err(HostedVerificationError::MissingRequiredCheck { kind });
1633            }
1634            if count > 1 {
1635                return Err(HostedVerificationError::DuplicateRequiredCheck { kind });
1636            }
1637        }
1638        for check in &input.checks {
1639            let valid = if check.kind == HostedCheckKind::ArtifactIdentity {
1640                check.request_id.is_none() && check.status_code.is_none()
1641            } else {
1642                let structural = check.request_id.as_deref().is_some_and(request_id_is_valid)
1643                    && check
1644                        .status_code
1645                        .is_some_and(|status| (100..=599).contains(&status));
1646                let expected_status = match check.kind {
1647                    HostedCheckKind::Contract
1648                    | HostedCheckKind::Readiness
1649                    | HostedCheckKind::Smoke => 200,
1650                    HostedCheckKind::Authentication => 401,
1651                    HostedCheckKind::ArtifactIdentity => unreachable!(),
1652                };
1653                structural && (!check.passed || check.status_code == Some(expected_status))
1654            };
1655            if !valid {
1656                return Err(HostedVerificationError::InvalidCheck { kind: check.kind });
1657            }
1658        }
1659        if let Some(check) = input.checks.iter().find(|check| !check.passed) {
1660            return Err(HostedVerificationError::RequiredCheckFailed { kind: check.kind });
1661        }
1662        if input.executed_artifact_digest != input.expected_artifact_digest {
1663            return Err(HostedVerificationError::ArtifactMismatch);
1664        }
1665        input.checks.sort_by_key(|check| check.kind);
1666        Ok(Self {
1667            endpoint: endpoint.to_string().trim_end_matches('/').to_owned(),
1668            executed_artifact_digest: input.executed_artifact_digest,
1669            executed_version: input.executed_version,
1670            checks: input.checks,
1671        })
1672    }
1673
1674    pub fn write_json(&self, path: impl AsRef<Path>) -> Result<(), HostedVerificationError> {
1675        let path = path.as_ref();
1676        let mut rendered = serde_json::to_vec_pretty(self)
1677            .map_err(|error| HostedVerificationError::Serialization(error.to_string()))?;
1678        rendered.push(b'\n');
1679        match std::fs::OpenOptions::new()
1680            .write(true)
1681            .create_new(true)
1682            .open(path)
1683        {
1684            Ok(mut file) => {
1685                file.write_all(&rendered)
1686                    .map_err(|error| HostedVerificationError::Io(error.to_string()))?;
1687                file.sync_all()
1688                    .map_err(|error| HostedVerificationError::Io(error.to_string()))
1689            }
1690            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
1691                let existing = Self::read_json(path, &self.executed_artifact_digest)?;
1692                if existing == *self {
1693                    Ok(())
1694                } else {
1695                    Err(HostedVerificationError::Conflict(
1696                        path.display().to_string(),
1697                    ))
1698                }
1699            }
1700            Err(error) => Err(HostedVerificationError::Io(error.to_string())),
1701        }
1702    }
1703
1704    pub fn read_json(
1705        path: impl AsRef<Path>,
1706        expected_artifact_digest: &str,
1707    ) -> Result<Self, HostedVerificationError> {
1708        let bytes =
1709            std::fs::read(path).map_err(|error| HostedVerificationError::Io(error.to_string()))?;
1710        let report: Self = serde_json::from_slice(&bytes)
1711            .map_err(|error| HostedVerificationError::Serialization(error.to_string()))?;
1712        Self::complete(HostedVerificationInput {
1713            endpoint: report.endpoint,
1714            expected_artifact_digest: expected_artifact_digest.to_owned(),
1715            executed_artifact_digest: report.executed_artifact_digest,
1716            executed_version: report.executed_version,
1717            checks: report.checks,
1718        })
1719    }
1720}
1721
1722#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1723#[serde(rename_all = "snake_case")]
1724pub enum StaticSiteDistributionStatus {
1725    Deployed,
1726    InProgress,
1727}
1728
1729#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1730#[serde(rename_all = "snake_case")]
1731pub enum StaticSiteInvalidationStatus {
1732    Completed,
1733    InProgress,
1734}
1735
1736#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1737#[serde(rename_all = "snake_case")]
1738pub enum CloudFrontBillingModel {
1739    RequestAndTransfer,
1740    FlatRate,
1741}
1742
1743#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1744#[serde(rename_all = "snake_case")]
1745pub enum FlatRateEligibility {
1746    Ineligible,
1747    EligibleNotSelected,
1748    EligibleSelected,
1749}
1750
1751#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1752#[serde(deny_unknown_fields)]
1753pub struct StaticSiteCertificateObservation {
1754    pub arn: String,
1755    pub status: String,
1756    pub names: Vec<String>,
1757}
1758
1759#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1760#[serde(deny_unknown_fields)]
1761pub struct StaticSiteDnsObservation {
1762    pub hosted_zone_id: String,
1763    pub hosted_zone_name: String,
1764    pub private_zone: bool,
1765    pub a_target: String,
1766    pub aaaa_target: Option<String>,
1767}
1768
1769#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1770#[serde(deny_unknown_fields)]
1771pub struct StaticSiteObjectObservation {
1772    pub path: String,
1773    pub s3_bytes: u64,
1774    pub s3_sha256: String,
1775    pub s3_content_type: String,
1776    pub s3_cache_control: String,
1777    pub cloudfront_bytes: u64,
1778    pub cloudfront_sha256: String,
1779    pub cloudfront_content_type: String,
1780    pub cloudfront_cache_control: String,
1781}
1782
1783#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1784#[serde(deny_unknown_fields)]
1785pub struct StaticSitePricingEvidence {
1786    pub checked_on: String,
1787    pub source: String,
1788    pub billing_model: CloudFrontBillingModel,
1789    pub price_class: String,
1790    pub flat_rate_eligibility: FlatRateEligibility,
1791}
1792
1793#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1794#[serde(deny_unknown_fields)]
1795pub struct StaticSiteProviderObservation {
1796    pub bucket: String,
1797    pub distribution_id: String,
1798    pub distribution_domain: String,
1799    pub distribution_status: StaticSiteDistributionStatus,
1800    pub distribution_aliases: Vec<String>,
1801    pub distribution_certificate_arn: Option<String>,
1802    pub origin_domain: String,
1803    pub origin_access_control_id: String,
1804    pub invalidation_id: String,
1805    pub invalidation_status: StaticSiteInvalidationStatus,
1806    pub certificate: Option<StaticSiteCertificateObservation>,
1807    pub dns: Option<StaticSiteDnsObservation>,
1808    pub objects: Vec<StaticSiteObjectObservation>,
1809    pub pricing: StaticSitePricingEvidence,
1810}
1811
1812#[derive(Debug, Clone, PartialEq, Eq)]
1813pub struct StaticSiteVerificationInput {
1814    pub release_digest: String,
1815    pub expected_account_id: String,
1816    pub deployment_region: String,
1817    pub manifest: StaticSiteReleaseManifest,
1818    pub observation: StaticSiteProviderObservation,
1819}
1820
1821#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1822#[serde(deny_unknown_fields)]
1823pub struct StaticSiteVerificationReport {
1824    pub schema_version: u32,
1825    pub release_digest: String,
1826    pub expected_account_id: String,
1827    pub deployment_region: String,
1828    pub static_site_manifest_digest: String,
1829    pub manifest: StaticSiteReleaseManifest,
1830    pub observation: StaticSiteProviderObservation,
1831}
1832
1833impl StaticSiteVerificationReport {
1834    pub fn complete(
1835        mut input: StaticSiteVerificationInput,
1836    ) -> Result<Self, StaticSiteVerificationError> {
1837        if !sha256_is_valid(&input.release_digest)
1838            || !account_id_is_valid(&input.expected_account_id)
1839            || !region_is_valid(&input.deployment_region)
1840            || input.manifest.schema_version != 1
1841            || input.manifest.plan.validate().is_err()
1842        {
1843            return Err(StaticSiteVerificationError::InvalidIdentity);
1844        }
1845        let manifest_digest = input
1846            .manifest
1847            .digest_sha256()
1848            .map_err(|_| StaticSiteVerificationError::ManifestInvalid)?;
1849        validate_static_site_provider_identity(&input.observation, &input.deployment_region)?;
1850        validate_static_site_pricing(&input.manifest, &input.observation.pricing)?;
1851
1852        input.observation.distribution_aliases.sort_unstable();
1853        if input
1854            .observation
1855            .distribution_aliases
1856            .windows(2)
1857            .any(|aliases| aliases[0] == aliases[1])
1858        {
1859            return Err(StaticSiteVerificationError::DistributionMismatch);
1860        }
1861        validate_static_site_domain(
1862            &input.manifest,
1863            &input.expected_account_id,
1864            &input.observation,
1865        )?;
1866
1867        input
1868            .observation
1869            .objects
1870            .sort_by(|left, right| left.path.cmp(&right.path));
1871        if input.observation.objects.len() != input.manifest.assets.len()
1872            || input
1873                .observation
1874                .objects
1875                .windows(2)
1876                .any(|objects| objects[0].path == objects[1].path)
1877        {
1878            return Err(StaticSiteVerificationError::AssetSetMismatch);
1879        }
1880        for (expected, observed) in input.manifest.assets.iter().zip(&input.observation.objects) {
1881            let s3_matches = expected.bytes == observed.s3_bytes
1882                && expected.sha256 == observed.s3_sha256
1883                && expected.content_type == observed.s3_content_type
1884                && expected.cache_control == observed.s3_cache_control;
1885            let cloudfront_matches = expected.bytes == observed.cloudfront_bytes
1886                && expected.sha256 == observed.cloudfront_sha256
1887                && expected.content_type == observed.cloudfront_content_type
1888                && expected.cache_control == observed.cloudfront_cache_control;
1889            if expected.path != observed.path || !s3_matches || !cloudfront_matches {
1890                return Err(StaticSiteVerificationError::AssetMismatch {
1891                    path: expected.path.clone(),
1892                });
1893            }
1894        }
1895
1896        Ok(Self {
1897            schema_version: 1,
1898            release_digest: input.release_digest,
1899            expected_account_id: input.expected_account_id,
1900            deployment_region: input.deployment_region,
1901            static_site_manifest_digest: manifest_digest,
1902            manifest: input.manifest,
1903            observation: input.observation,
1904        })
1905    }
1906
1907    pub fn verify_structure(&self) -> Result<(), StaticSiteVerificationError> {
1908        if self.schema_version != 1 {
1909            return Err(StaticSiteVerificationError::UnsupportedSchema);
1910        }
1911        let rebuilt = Self::complete(StaticSiteVerificationInput {
1912            release_digest: self.release_digest.clone(),
1913            expected_account_id: self.expected_account_id.clone(),
1914            deployment_region: self.deployment_region.clone(),
1915            manifest: self.manifest.clone(),
1916            observation: self.observation.clone(),
1917        })?;
1918        if &rebuilt != self {
1919            return Err(StaticSiteVerificationError::ManifestInvalid);
1920        }
1921        Ok(())
1922    }
1923}
1924
1925fn validate_static_site_provider_identity(
1926    observation: &StaticSiteProviderObservation,
1927    deployment_region: &str,
1928) -> Result<(), StaticSiteVerificationError> {
1929    let distribution_id = provider_identifier_is_valid(&observation.distribution_id, 'E');
1930    let invalidation_id = provider_identifier_is_valid(&observation.invalidation_id, 'I');
1931    let distribution_domain = normalized_dns_name(&observation.distribution_domain)
1932        .is_some_and(|domain| domain.ends_with(".cloudfront.net"));
1933    let origin_is_private_s3 = private_s3_origin_is_valid(
1934        &observation.origin_domain,
1935        &observation.bucket,
1936        deployment_region,
1937    );
1938    if !bucket_name_is_valid(&observation.bucket)
1939        || !distribution_id
1940        || !invalidation_id
1941        || !distribution_domain
1942        || !origin_is_private_s3
1943        || !provider_identifier_is_valid(&observation.origin_access_control_id, 'E')
1944        || observation.distribution_status != StaticSiteDistributionStatus::Deployed
1945        || observation.invalidation_status != StaticSiteInvalidationStatus::Completed
1946    {
1947        return Err(StaticSiteVerificationError::DistributionMismatch);
1948    }
1949    Ok(())
1950}
1951
1952fn private_s3_origin_is_valid(origin: &str, bucket: &str, region: &str) -> bool {
1953    let suffix = if region.starts_with("cn-") {
1954        "amazonaws.com.cn"
1955    } else {
1956        "amazonaws.com"
1957    };
1958    normalized_dns_name(origin) == Some(format!("{bucket}.s3.{region}.{suffix}").as_str())
1959}
1960
1961fn validate_static_site_domain(
1962    manifest: &StaticSiteReleaseManifest,
1963    account_id: &str,
1964    observation: &StaticSiteProviderObservation,
1965) -> Result<(), StaticSiteVerificationError> {
1966    let custom_domain = manifest.plan.custom_domain.as_deref();
1967    let expected_aliases = custom_domain.map_or_else(Vec::new, |domain| vec![domain.to_owned()]);
1968    if observation.distribution_aliases != expected_aliases {
1969        return Err(StaticSiteVerificationError::DistributionMismatch);
1970    }
1971    match (custom_domain, &observation.certificate) {
1972        (None, None) if observation.distribution_certificate_arn.is_none() => {}
1973        (Some(domain), Some(certificate))
1974            if cloudfront_certificate_arn_is_valid(&certificate.arn, account_id)
1975                && observation.distribution_certificate_arn.as_deref()
1976                    == Some(certificate.arn.as_str())
1977                && certificate.status == "ISSUED"
1978                && certificate
1979                    .names
1980                    .iter()
1981                    .any(|name| certificate_name_covers(name, domain)) => {}
1982        _ => return Err(StaticSiteVerificationError::CertificateMismatch),
1983    }
1984    match (
1985        manifest.plan.manage_dns_alias,
1986        custom_domain,
1987        &observation.dns,
1988    ) {
1989        (false, _, None) => {}
1990        (true, Some(domain), Some(dns))
1991            if dns_observation_matches(
1992                dns,
1993                domain,
1994                &observation.distribution_domain,
1995                manifest.plan.ipv6_enabled,
1996            ) => {}
1997        _ => return Err(StaticSiteVerificationError::DnsMismatch),
1998    }
1999    Ok(())
2000}
2001
2002fn validate_static_site_pricing(
2003    manifest: &StaticSiteReleaseManifest,
2004    pricing: &StaticSitePricingEvidence,
2005) -> Result<(), StaticSiteVerificationError> {
2006    let source = url::Url::parse(&pricing.source).ok();
2007    let official_source = source.as_ref().is_some_and(|source| {
2008        source.scheme() == "https"
2009            && matches!(
2010                source.host_str(),
2011                Some("aws.amazon.com" | "docs.aws.amazon.com")
2012            )
2013            && source.username().is_empty()
2014            && source.password().is_none()
2015    });
2016    let selection_valid = match pricing.billing_model {
2017        CloudFrontBillingModel::RequestAndTransfer => {
2018            pricing.flat_rate_eligibility != FlatRateEligibility::EligibleSelected
2019        }
2020        CloudFrontBillingModel::FlatRate => {
2021            pricing.flat_rate_eligibility == FlatRateEligibility::EligibleSelected
2022        }
2023    };
2024    if pricing.price_class != manifest.plan.price_class
2025        || !iso_date_is_valid(&pricing.checked_on)
2026        || !official_source
2027        || !selection_valid
2028    {
2029        return Err(StaticSiteVerificationError::PricingEvidenceInvalid);
2030    }
2031    Ok(())
2032}
2033
2034fn provider_identifier_is_valid(value: &str, prefix: char) -> bool {
2035    value.len() >= 8
2036        && value.starts_with(prefix)
2037        && value
2038            .bytes()
2039            .all(|byte| byte.is_ascii_uppercase() || byte.is_ascii_digit())
2040}
2041
2042fn normalized_dns_name(value: &str) -> Option<&str> {
2043    let value = value.strip_suffix('.').unwrap_or(value);
2044    (!value.is_empty()
2045        && value.bytes().all(|byte| {
2046            byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'.' | b'-')
2047        }))
2048    .then_some(value)
2049}
2050
2051fn cloudfront_certificate_arn_is_valid(value: &str, account_id: &str) -> bool {
2052    let parts = value.splitn(6, ':').collect::<Vec<_>>();
2053    parts.len() == 6
2054        && parts[0] == "arn"
2055        && parts[1].starts_with("aws")
2056        && parts[2] == "acm"
2057        && parts[3] == "us-east-1"
2058        && parts[4] == account_id
2059        && parts[5]
2060            .strip_prefix("certificate/")
2061            .is_some_and(|id| !id.is_empty() && !id.chars().any(char::is_control))
2062}
2063
2064fn certificate_name_covers(name: &str, domain: &str) -> bool {
2065    if name == domain {
2066        return true;
2067    }
2068    name.strip_prefix("*.").is_some_and(|suffix| {
2069        domain.strip_suffix(suffix).is_some_and(|prefix| {
2070            prefix.ends_with('.') && !prefix[..prefix.len() - 1].contains('.')
2071        })
2072    })
2073}
2074
2075fn dns_observation_matches(
2076    dns: &StaticSiteDnsObservation,
2077    domain: &str,
2078    distribution_domain: &str,
2079    ipv6_enabled: bool,
2080) -> bool {
2081    let zone = normalized_dns_name(&dns.hosted_zone_name);
2082    let distribution = normalized_dns_name(distribution_domain);
2083    let zone_owns_domain = zone.is_some_and(|zone| {
2084        domain == zone
2085            || domain
2086                .strip_suffix(zone)
2087                .is_some_and(|prefix| prefix.ends_with('.'))
2088    });
2089    let target_matches = normalized_dns_name(&dns.a_target) == distribution;
2090    let ipv6_matches = match (&dns.aaaa_target, ipv6_enabled) {
2091        (Some(target), true) => normalized_dns_name(target) == distribution,
2092        (None, false) => true,
2093        _ => false,
2094    };
2095    !dns.private_zone
2096        && dns.hosted_zone_id.starts_with('Z')
2097        && dns.hosted_zone_id.len() >= 8
2098        && dns
2099            .hosted_zone_id
2100            .bytes()
2101            .all(|byte| byte.is_ascii_uppercase() || byte.is_ascii_digit())
2102        && zone_owns_domain
2103        && target_matches
2104        && ipv6_matches
2105}
2106
2107fn iso_date_is_valid(value: &str) -> bool {
2108    let bytes = value.as_bytes();
2109    if bytes.len() != 10
2110        || bytes[4] != b'-'
2111        || bytes[7] != b'-'
2112        || bytes
2113            .iter()
2114            .enumerate()
2115            .any(|(index, byte)| !matches!(index, 4 | 7) && !byte.is_ascii_digit())
2116    {
2117        return false;
2118    }
2119    let year = value[..4].parse::<u16>().ok();
2120    let month = value[5..7].parse::<u8>().ok();
2121    let day = value[8..10].parse::<u8>().ok();
2122    let Some((year, month, day)) = year.zip(month).zip(day).map(|((y, m), d)| (y, m, d)) else {
2123        return false;
2124    };
2125    let leap_year =
2126        year.is_multiple_of(4) && (!year.is_multiple_of(100) || year.is_multiple_of(400));
2127    let days = match month {
2128        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
2129        4 | 6 | 9 | 11 => 30,
2130        2 if leap_year => 29,
2131        2 => 28,
2132        _ => return false,
2133    };
2134    (1..=days).contains(&day)
2135}
2136
2137#[derive(Debug, Error, Clone, PartialEq, Eq)]
2138pub enum StaticSiteVerificationError {
2139    #[error("static-site verification report uses an unsupported schema")]
2140    UnsupportedSchema,
2141    #[error("static-site verification identity is invalid")]
2142    InvalidIdentity,
2143    #[error("static-site release manifest is invalid")]
2144    ManifestInvalid,
2145    #[error("static-site distribution or invalidation does not match")]
2146    DistributionMismatch,
2147    #[error("static-site certificate does not cover the custom domain")]
2148    CertificateMismatch,
2149    #[error("static-site DNS evidence does not own or target the custom domain")]
2150    DnsMismatch,
2151    #[error("static-site provider object set does not match the release")]
2152    AssetSetMismatch,
2153    #[error("static-site provider object {path} does not match the release")]
2154    AssetMismatch { path: String },
2155    #[error("static-site pricing evidence is invalid")]
2156    PricingEvidenceInvalid,
2157}
2158
2159#[derive(Debug, Clone, PartialEq, Eq)]
2160pub struct StaticSitePublicationReceiptInput {
2161    pub release_digest: String,
2162    pub manifest_file: FileDigest,
2163    pub bucket: String,
2164    pub distribution_id: String,
2165    pub distribution_domain: String,
2166    pub publication: StaticSitePublication,
2167}
2168
2169#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2170#[serde(deny_unknown_fields)]
2171pub struct StaticSitePublicationReceipt {
2172    pub schema_version: u32,
2173    pub receipt_digest: String,
2174    pub release_digest: String,
2175    pub manifest_file: FileDigest,
2176    pub bucket: String,
2177    pub distribution_id: String,
2178    pub distribution_domain: String,
2179    pub publication: StaticSitePublication,
2180}
2181
2182impl StaticSitePublicationReceipt {
2183    pub fn seal(
2184        input: StaticSitePublicationReceiptInput,
2185    ) -> Result<Self, StaticSitePublicationReceiptError> {
2186        let mut receipt = Self {
2187            schema_version: 1,
2188            receipt_digest: String::new(),
2189            release_digest: input.release_digest,
2190            manifest_file: input.manifest_file,
2191            bucket: input.bucket,
2192            distribution_id: input.distribution_id,
2193            distribution_domain: input.distribution_domain,
2194            publication: input.publication,
2195        };
2196        receipt.receipt_digest = receipt.calculate_digest()?;
2197        receipt.verify_structure()?;
2198        Ok(receipt)
2199    }
2200
2201    pub fn verify_structure(&self) -> Result<(), StaticSitePublicationReceiptError> {
2202        validate_bound_file(&self.manifest_file, "static-site release manifest")
2203            .map_err(|error| StaticSitePublicationReceiptError::Invalid(error.to_string()))?;
2204        let distribution_domain = normalized_dns_name(&self.distribution_domain);
2205        let url = url::Url::parse(&self.publication.url).ok();
2206        if self.schema_version != 1
2207            || !sha256_is_valid(&self.release_digest)
2208            || !sha256_is_valid(&self.receipt_digest)
2209            || !sha256_is_valid(&self.publication.release_manifest_digest)
2210            || !bucket_name_is_valid(&self.bucket)
2211            || !provider_identifier_is_valid(&self.distribution_id, 'E')
2212            || !distribution_domain.is_some_and(|domain| domain.ends_with(".cloudfront.net"))
2213            || self.publication.assets.is_empty()
2214            || self.publication.uploaded != self.publication.assets.len()
2215            || !self
2216                .publication
2217                .invalidation_id
2218                .as_deref()
2219                .is_some_and(|id| provider_identifier_is_valid(id, 'I'))
2220            || !self.publication.invalidation_completed
2221            || url.as_ref().is_none_or(|url| {
2222                url.scheme() != "https"
2223                    || url.username() != ""
2224                    || url.password().is_some()
2225                    || url.query().is_some()
2226                    || url.fragment().is_some()
2227                    || url.path() != "/"
2228            })
2229            || self
2230                .publication
2231                .assets
2232                .windows(2)
2233                .any(|assets| assets[0].path >= assets[1].path)
2234        {
2235            return Err(StaticSitePublicationReceiptError::Invalid(
2236                "publication identity or completion evidence is invalid".into(),
2237            ));
2238        }
2239        if self.calculate_digest()? != self.receipt_digest {
2240            return Err(StaticSitePublicationReceiptError::DigestMismatch);
2241        }
2242        Ok(())
2243    }
2244
2245    pub fn verify_at(
2246        &self,
2247        root: impl AsRef<Path>,
2248    ) -> Result<(), StaticSitePublicationReceiptError> {
2249        self.verify_structure()?;
2250        let root = root.as_ref();
2251        self.manifest_file
2252            .verify_at(root)
2253            .map_err(|error| StaticSitePublicationReceiptError::Invalid(error.to_string()))?;
2254        let source = std::fs::read(root.join(&self.manifest_file.path))?;
2255        let manifest: StaticSiteReleaseManifest = serde_json::from_slice(&source)?;
2256        manifest
2257            .verify_at(root)
2258            .map_err(|error| StaticSitePublicationReceiptError::Invalid(error.to_string()))?;
2259        let public_host = url::Url::parse(&self.publication.url)
2260            .ok()
2261            .and_then(|url| url.host_str().map(str::to_owned));
2262        let expected_host = manifest
2263            .plan
2264            .custom_domain
2265            .as_ref()
2266            .unwrap_or(&self.distribution_domain);
2267        if public_host.as_deref() != Some(expected_host.as_str())
2268            || manifest
2269                .digest_sha256()
2270                .map_err(|error| StaticSitePublicationReceiptError::Invalid(error.to_string()))?
2271                != self.publication.release_manifest_digest
2272            || manifest.assets != self.publication.assets
2273        {
2274            return Err(StaticSitePublicationReceiptError::Invalid(
2275                "publication does not match the exact static-site release manifest".into(),
2276            ));
2277        }
2278        Ok(())
2279    }
2280
2281    pub fn write_json(
2282        &self,
2283        path: impl AsRef<Path>,
2284    ) -> Result<(), StaticSitePublicationReceiptError> {
2285        self.verify_structure()?;
2286        let path = path.as_ref();
2287        let mut rendered = serde_json::to_vec_pretty(self)?;
2288        rendered.push(b'\n');
2289        if path.exists() {
2290            if std::fs::read(path)? == rendered {
2291                return Ok(());
2292            }
2293            return Err(StaticSitePublicationReceiptError::Conflict(
2294                path.display().to_string(),
2295            ));
2296        }
2297        let mut output = std::fs::OpenOptions::new()
2298            .write(true)
2299            .create_new(true)
2300            .open(path)?;
2301        output.write_all(&rendered)?;
2302        output.sync_all()?;
2303        Ok(())
2304    }
2305
2306    pub fn read_json(path: impl AsRef<Path>) -> Result<Self, StaticSitePublicationReceiptError> {
2307        let source = std::fs::read(path)?;
2308        let receipt: Self = serde_json::from_slice(&source)?;
2309        receipt.verify_structure()?;
2310        Ok(receipt)
2311    }
2312
2313    fn calculate_digest(&self) -> Result<String, StaticSitePublicationReceiptError> {
2314        #[derive(Serialize)]
2315        struct DigestPayload<'a> {
2316            schema_version: u32,
2317            release_digest: &'a str,
2318            manifest_file: &'a FileDigest,
2319            bucket: &'a str,
2320            distribution_id: &'a str,
2321            distribution_domain: &'a str,
2322            publication: &'a StaticSitePublication,
2323        }
2324        let payload = DigestPayload {
2325            schema_version: self.schema_version,
2326            release_digest: &self.release_digest,
2327            manifest_file: &self.manifest_file,
2328            bucket: &self.bucket,
2329            distribution_id: &self.distribution_id,
2330            distribution_domain: &self.distribution_domain,
2331            publication: &self.publication,
2332        };
2333        Ok(hex::encode(Sha256::digest(serde_json::to_vec(&payload)?)))
2334    }
2335}
2336
2337#[derive(Debug, Error)]
2338pub enum StaticSitePublicationReceiptError {
2339    #[error("static-site publication receipt is invalid: {0}")]
2340    Invalid(String),
2341    #[error("static-site publication receipt digest does not match its contents")]
2342    DigestMismatch,
2343    #[error("immutable static-site publication receipt already exists at {0}")]
2344    Conflict(String),
2345    #[error("static-site publication receipt JSON is invalid: {0}")]
2346    Json(#[from] serde_json::Error),
2347    #[error("static-site publication receipt I/O failed: {0}")]
2348    Io(#[from] std::io::Error),
2349}
2350
2351pub fn verify_promotion_boundary(
2352    change_set: &CloudFormationChangeSet,
2353    expected_stack_name: &str,
2354    live_alias_logical_id: &str,
2355) -> Result<(), PromotionBoundaryError> {
2356    if change_set.change_set_type != ChangeSetType::Update
2357        || change_set.status != ChangeSetStatus::CreateComplete
2358        || change_set.execution_status != ExecutionStatus::Available
2359        || change_set.stack_name != expected_stack_name
2360    {
2361        return Err(PromotionBoundaryError::InvalidProviderState);
2362    }
2363    let review = &change_set.review;
2364    let only_live_alias = match review.modifications.as_slice() {
2365        [change] => {
2366            change.logical_id == live_alias_logical_id
2367                && change.resource_type == "AWS::Lambda::Alias"
2368                && change.action == ChangeAction::Modify
2369                && matches!(change.replacement, None | Some(Replacement::Never))
2370                && change.policy_action.is_none()
2371                && change.scope.as_slice() == [ChangeScope::Properties]
2372        }
2373        _ => false,
2374    };
2375    if !only_live_alias
2376        || !review.additions.is_empty()
2377        || !review.replacements.is_empty()
2378        || !review.deletions.is_empty()
2379        || !review.imports.is_empty()
2380        || !review.indeterminate.is_empty()
2381        || !review.metadata_syncs.is_empty()
2382    {
2383        return Err(PromotionBoundaryError::NonRoutingChange);
2384    }
2385    Ok(())
2386}
2387
2388#[derive(Debug, Clone, PartialEq, Eq, Error)]
2389pub enum PromotionBoundaryError {
2390    #[error("promotion change set is not a complete available update for the expected stack")]
2391    InvalidProviderState,
2392    #[error("promotion change set contains a non-routing resource change")]
2393    NonRoutingChange,
2394}
2395
2396#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
2397#[serde(rename_all = "snake_case")]
2398pub enum RollbackClassification {
2399    Compatible,
2400    OperatorDecisionRequired,
2401    Incompatible,
2402}
2403
2404#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2405#[serde(rename_all = "snake_case")]
2406pub enum RollbackCompatibility {
2407    Compatible,
2408    OperatorDecisionRequired,
2409    Incompatible,
2410}
2411
2412#[derive(Debug, Clone, PartialEq, Eq)]
2413pub struct RollbackAssessmentInput {
2414    pub current_release_id: String,
2415    pub target_release_id: String,
2416    pub current_environment: String,
2417    pub target_environment: String,
2418    pub contract: RollbackCompatibility,
2419    pub current_configuration_digest: String,
2420    pub target_configuration_digest: String,
2421    pub current_deployment_plan_digest: String,
2422    pub target_deployment_plan_digest: String,
2423    pub current_migration_catalog_digest: String,
2424    pub target_migration_catalog_digest: String,
2425    pub current_migration_plan_bindings_digest: String,
2426    pub target_migration_plan_bindings_digest: String,
2427    pub current_seed_catalog_digest: String,
2428    pub target_seed_catalog_digest: String,
2429    pub current_seed_plan_bindings_digest: String,
2430    pub target_seed_plan_bindings_digest: String,
2431    pub data_compatibility: RollbackCompatibility,
2432    pub data_compatibility_evidence_digest: Option<String>,
2433    pub current_api_version: String,
2434    pub target_api_version: String,
2435    pub current_worker_artifacts: BTreeMap<String, String>,
2436    pub target_worker_artifacts: BTreeMap<String, String>,
2437}
2438
2439#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2440#[serde(deny_unknown_fields)]
2441pub struct RollbackCheck {
2442    pub area: String,
2443    pub code: String,
2444    pub classification: RollbackClassification,
2445    pub reason: String,
2446}
2447
2448#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2449#[serde(deny_unknown_fields)]
2450pub struct RollbackAssessment {
2451    pub schema_version: u32,
2452    pub current_release_id: String,
2453    pub target_release_id: String,
2454    pub classification: RollbackClassification,
2455    pub checks: Vec<RollbackCheck>,
2456    pub api_routing: String,
2457    pub worker_routing: String,
2458    pub limitations: Vec<String>,
2459}
2460
2461#[derive(Debug, Clone, PartialEq, Eq, Error)]
2462pub enum RollbackAssessmentError {
2463    #[error("rollback assessment input has invalid {0}")]
2464    Invalid(&'static str),
2465}
2466
2467pub fn assess_rollback_compatibility(
2468    input: RollbackAssessmentInput,
2469) -> Result<RollbackAssessment, RollbackAssessmentError> {
2470    if input.current_release_id.trim().is_empty() || input.target_release_id.trim().is_empty() {
2471        return Err(RollbackAssessmentError::Invalid("release identity"));
2472    }
2473    for (label, digest) in [
2474        (
2475            "current configuration digest",
2476            &input.current_configuration_digest,
2477        ),
2478        (
2479            "target configuration digest",
2480            &input.target_configuration_digest,
2481        ),
2482        (
2483            "current deployment plan digest",
2484            &input.current_deployment_plan_digest,
2485        ),
2486        (
2487            "target deployment plan digest",
2488            &input.target_deployment_plan_digest,
2489        ),
2490        (
2491            "current migration catalog digest",
2492            &input.current_migration_catalog_digest,
2493        ),
2494        (
2495            "target migration catalog digest",
2496            &input.target_migration_catalog_digest,
2497        ),
2498        (
2499            "current migration plan bindings digest",
2500            &input.current_migration_plan_bindings_digest,
2501        ),
2502        (
2503            "target migration plan bindings digest",
2504            &input.target_migration_plan_bindings_digest,
2505        ),
2506        (
2507            "current seed catalog digest",
2508            &input.current_seed_catalog_digest,
2509        ),
2510        (
2511            "target seed catalog digest",
2512            &input.target_seed_catalog_digest,
2513        ),
2514        (
2515            "current seed plan bindings digest",
2516            &input.current_seed_plan_bindings_digest,
2517        ),
2518        (
2519            "target seed plan bindings digest",
2520            &input.target_seed_plan_bindings_digest,
2521        ),
2522    ] {
2523        if !sha256_is_valid(digest) {
2524            return Err(RollbackAssessmentError::Invalid(label));
2525        }
2526    }
2527    if input
2528        .data_compatibility_evidence_digest
2529        .as_deref()
2530        .is_some_and(|digest| !sha256_is_valid(digest))
2531    {
2532        return Err(RollbackAssessmentError::Invalid(
2533            "data compatibility evidence digest",
2534        ));
2535    }
2536    let current_api_version = input.current_api_version.parse::<u64>().ok();
2537    let target_api_version = input.target_api_version.parse::<u64>().ok();
2538    if !published_version_is_valid(&input.current_api_version)
2539        || !published_version_is_valid(&input.target_api_version)
2540        || !matches!((current_api_version, target_api_version), (Some(current), Some(target)) if target < current)
2541    {
2542        return Err(RollbackAssessmentError::Invalid("API versions"));
2543    }
2544    if input
2545        .current_worker_artifacts
2546        .iter()
2547        .chain(&input.target_worker_artifacts)
2548        .any(|(worker, digest)| !identifier_is_valid(worker) || !sha256_is_valid(digest))
2549    {
2550        return Err(RollbackAssessmentError::Invalid("worker artifacts"));
2551    }
2552
2553    let mut checks = Vec::new();
2554    let mut push =
2555        |area: &str, code: &str, classification: RollbackClassification, reason: String| {
2556            checks.push(RollbackCheck {
2557                area: area.into(),
2558                code: code.into(),
2559                classification,
2560                reason,
2561            });
2562        };
2563    if input.current_environment == input.target_environment {
2564        push(
2565            "environment",
2566            "environment.matches",
2567            RollbackClassification::Compatible,
2568            format!("both releases target {}", input.current_environment),
2569        );
2570    } else {
2571        push(
2572            "environment",
2573            "environment.mismatch",
2574            RollbackClassification::Incompatible,
2575            format!(
2576                "current environment {} differs from target environment {}",
2577                input.current_environment, input.target_environment
2578            ),
2579        );
2580    }
2581    let (contract_code, contract_classification, contract_reason) = match input.contract {
2582        RollbackCompatibility::Compatible => (
2583            "contract.compatible",
2584            RollbackClassification::Compatible,
2585            "the older API contract is structurally compatible with current clients",
2586        ),
2587        RollbackCompatibility::OperatorDecisionRequired => (
2588            "contract.uncertain",
2589            RollbackClassification::OperatorDecisionRequired,
2590            "contract analysis contains changes that require semantic review",
2591        ),
2592        RollbackCompatibility::Incompatible => (
2593            "contract.breaking",
2594            RollbackClassification::Incompatible,
2595            "the older API contract would break the current external contract",
2596        ),
2597    };
2598    push(
2599        "contract",
2600        contract_code,
2601        contract_classification,
2602        contract_reason.into(),
2603    );
2604    push_digest_check(
2605        &mut push,
2606        "configuration",
2607        ("configuration.matches", "configuration.changed"),
2608        (
2609            &input.current_configuration_digest,
2610            &input.target_configuration_digest,
2611        ),
2612        (
2613            "configuration digest is identical",
2614            "configuration changed; runtime compatibility must be approved",
2615        ),
2616    );
2617    push_digest_check(
2618        &mut push,
2619        "resources",
2620        ("resources.plan_matches", "resources.plan_changed"),
2621        (
2622            &input.current_deployment_plan_digest,
2623            &input.target_deployment_plan_digest,
2624        ),
2625        (
2626            "deployment plan digest is identical",
2627            "deployment resources changed; rollback only changes routing",
2628        ),
2629    );
2630    push_digest_check(
2631        &mut push,
2632        "migrations",
2633        ("migrations.catalog_matches", "migrations.catalog_changed"),
2634        (
2635            &input.current_migration_catalog_digest,
2636            &input.target_migration_catalog_digest,
2637        ),
2638        (
2639            "migration catalog digest is identical",
2640            "migration catalog changed; Minco will not invent reverse SQL",
2641        ),
2642    );
2643    push_digest_check(
2644        &mut push,
2645        "migrations",
2646        (
2647            "migrations.applied_plans_match",
2648            "migrations.applied_plans_changed",
2649        ),
2650        (
2651            &input.current_migration_plan_bindings_digest,
2652            &input.target_migration_plan_bindings_digest,
2653        ),
2654        (
2655            "deployed migration plan bindings are identical",
2656            "deployed migration plan bindings changed; Minco will not invent reverse SQL",
2657        ),
2658    );
2659    push_digest_check(
2660        &mut push,
2661        "data",
2662        ("data.seed_catalog_matches", "data.seed_catalog_changed"),
2663        (
2664            &input.current_seed_catalog_digest,
2665            &input.target_seed_catalog_digest,
2666        ),
2667        (
2668            "seed catalog digest is identical",
2669            "seed catalog changed; Minco will not repair persisted data",
2670        ),
2671    );
2672    push_digest_check(
2673        &mut push,
2674        "data",
2675        ("data.seed_plans_match", "data.seed_plans_changed"),
2676        (
2677            &input.current_seed_plan_bindings_digest,
2678            &input.target_seed_plan_bindings_digest,
2679        ),
2680        (
2681            "deployed seed plan bindings are identical",
2682            "deployed seed plan bindings changed; Minco will not repair persisted data",
2683        ),
2684    );
2685    match (
2686        input.data_compatibility,
2687        &input.data_compatibility_evidence_digest,
2688    ) {
2689        (RollbackCompatibility::Compatible, Some(digest)) => push(
2690            "data",
2691            "data.compatibility_evidence_bound",
2692            RollbackClassification::Compatible,
2693            format!("operator supplied exact data compatibility evidence {digest}"),
2694        ),
2695        (RollbackCompatibility::Incompatible, Some(digest)) => push(
2696            "data",
2697            "data.incompatible",
2698            RollbackClassification::Incompatible,
2699            format!("operator evidence {digest} declares current data incompatible"),
2700        ),
2701        _ => push(
2702            "data",
2703            "data.compatibility_unproved",
2704            RollbackClassification::OperatorDecisionRequired,
2705            "persisted-data compatibility has no exact compatible operator evidence".into(),
2706        ),
2707    }
2708    push(
2709        "api_routing",
2710        "api.exact_published_version",
2711        RollbackClassification::Compatible,
2712        format!(
2713            "target historical version {} is older than current version {}; its exact artifact must be republished and reverified before alias routing",
2714            input.target_api_version, input.current_api_version
2715        ),
2716    );
2717    if input.current_worker_artifacts == input.target_worker_artifacts {
2718        push(
2719            "workers",
2720            "workers.artifacts_match",
2721            RollbackClassification::Compatible,
2722            "worker artifacts match; event sources still remain on the current version".into(),
2723        );
2724    } else {
2725        push(
2726            "workers",
2727            "workers.artifacts_changed",
2728            RollbackClassification::OperatorDecisionRequired,
2729            "worker artifacts differ and worker event sources remain on the current version".into(),
2730        );
2731    }
2732
2733    let classification = if checks
2734        .iter()
2735        .any(|check| check.classification == RollbackClassification::Incompatible)
2736    {
2737        RollbackClassification::Incompatible
2738    } else if checks
2739        .iter()
2740        .any(|check| check.classification == RollbackClassification::OperatorDecisionRequired)
2741    {
2742        RollbackClassification::OperatorDecisionRequired
2743    } else {
2744        RollbackClassification::Compatible
2745    };
2746    Ok(RollbackAssessment {
2747        schema_version: 1,
2748        current_release_id: input.current_release_id,
2749        target_release_id: input.target_release_id,
2750        classification,
2751        checks,
2752        api_routing: "redeploy_target_artifact_as_candidate_then_route_new_verified_version".into(),
2753        worker_routing: "preserve_current_worker_event_sources".into(),
2754        limitations: vec![
2755            "Minco never invents reverse SQL or automatically repairs persisted data.".into(),
2756            "This assessment does not execute a traffic change or prove production behavior."
2757                .into(),
2758        ],
2759    })
2760}
2761
2762fn push_digest_check(
2763    push: &mut impl FnMut(&str, &str, RollbackClassification, String),
2764    area: &str,
2765    codes: (&str, &str),
2766    digests: (&str, &str),
2767    reasons: (&str, &str),
2768) {
2769    if digests.0 == digests.1 {
2770        push(
2771            area,
2772            codes.0,
2773            RollbackClassification::Compatible,
2774            reasons.0.into(),
2775        );
2776    } else {
2777        push(
2778            area,
2779            codes.1,
2780            RollbackClassification::OperatorDecisionRequired,
2781            reasons.1.into(),
2782        );
2783    }
2784}
2785
2786#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2787#[serde(rename_all = "snake_case")]
2788pub enum PromotionOutcome {
2789    Started,
2790    Failed,
2791    Succeeded,
2792}
2793
2794#[derive(Debug, Clone, PartialEq, Eq)]
2795pub struct PromotionReceiptInput {
2796    pub attempt_id: String,
2797    pub release_id: String,
2798    pub release_digest: String,
2799    pub environment: ReleaseEnvironment,
2800    pub deployment_receipt: FileDigest,
2801    pub hosted_verification: FileDigest,
2802    pub operator_approval_digest: String,
2803    pub stack_name: String,
2804    pub live_alias_logical_id: String,
2805    pub previous_version: String,
2806    pub promoted_version: String,
2807    pub change_set: CloudFormationChangeSet,
2808}
2809
2810#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2811#[serde(deny_unknown_fields)]
2812pub struct PromotionReceipt {
2813    pub schema_version: u32,
2814    pub receipt_digest: String,
2815    pub attempt_id: String,
2816    pub release_id: String,
2817    pub release_digest: String,
2818    pub environment: ReleaseEnvironment,
2819    pub deployment_receipt: FileDigest,
2820    pub hosted_verification: FileDigest,
2821    pub operator_approval_digest: String,
2822    pub stack_name: String,
2823    pub live_alias_logical_id: String,
2824    pub previous_version: String,
2825    pub promoted_version: String,
2826    pub change_set: CloudFormationChangeSet,
2827    outcome: PromotionOutcome,
2828    failure_code: Option<String>,
2829}
2830
2831impl PromotionReceipt {
2832    pub fn start(input: PromotionReceiptInput) -> Result<Self, PromotionReceiptError> {
2833        verify_promotion_boundary(
2834            &input.change_set,
2835            &input.stack_name,
2836            &input.live_alias_logical_id,
2837        )?;
2838        let mut receipt = Self {
2839            schema_version: 1,
2840            receipt_digest: String::new(),
2841            attempt_id: input.attempt_id,
2842            release_id: input.release_id,
2843            release_digest: input.release_digest,
2844            environment: input.environment,
2845            deployment_receipt: input.deployment_receipt,
2846            hosted_verification: input.hosted_verification,
2847            operator_approval_digest: input.operator_approval_digest,
2848            stack_name: input.stack_name,
2849            live_alias_logical_id: input.live_alias_logical_id,
2850            previous_version: input.previous_version,
2851            promoted_version: input.promoted_version,
2852            change_set: input.change_set,
2853            outcome: PromotionOutcome::Started,
2854            failure_code: None,
2855        };
2856        receipt.refresh_digest()?;
2857        receipt.verify_structure()?;
2858        Ok(receipt)
2859    }
2860
2861    pub const fn outcome(&self) -> PromotionOutcome {
2862        self.outcome
2863    }
2864
2865    pub fn succeed(&mut self) -> Result<(), PromotionReceiptError> {
2866        self.require_started()?;
2867        self.outcome = PromotionOutcome::Succeeded;
2868        self.refresh_digest()?;
2869        self.verify_structure()
2870    }
2871
2872    pub fn fail(&mut self, code: impl Into<String>) -> Result<(), PromotionReceiptError> {
2873        self.require_started()?;
2874        let code = code.into();
2875        if !identifier_is_valid(&code) {
2876            return Err(PromotionReceiptError::Invalid(
2877                "promotion failure code is invalid".into(),
2878            ));
2879        }
2880        self.outcome = PromotionOutcome::Failed;
2881        self.failure_code = Some(code);
2882        self.refresh_digest()?;
2883        self.verify_structure()
2884    }
2885
2886    pub fn write_json(&self, path: impl AsRef<Path>) -> Result<(), PromotionReceiptError> {
2887        self.verify_structure()?;
2888        let path = path.as_ref();
2889        let parent = path.parent().unwrap_or_else(|| Path::new("."));
2890        let name = path
2891            .file_name()
2892            .and_then(|name| name.to_str())
2893            .ok_or_else(|| PromotionReceiptError::Invalid("receipt path is invalid".into()))?;
2894        let lock = std::fs::OpenOptions::new()
2895            .read(true)
2896            .write(true)
2897            .create(true)
2898            .truncate(false)
2899            .open(parent.join(format!(".{name}.lock")))?;
2900        lock.lock()?;
2901        let mut rendered = serde_json::to_vec_pretty(self)?;
2902        rendered.push(b'\n');
2903        if !path.exists() {
2904            let mut file = std::fs::OpenOptions::new()
2905                .write(true)
2906                .create_new(true)
2907                .open(path)?;
2908            file.write_all(&rendered)?;
2909            file.sync_all()?;
2910            return Ok(());
2911        }
2912        let existing = Self::read_json(path)?;
2913        if existing == *self {
2914            return Ok(());
2915        }
2916        if existing.attempt_id != self.attempt_id || !existing.same_binding(self) {
2917            return Err(PromotionReceiptError::Conflict(self.attempt_id.clone()));
2918        }
2919        if existing.outcome != PromotionOutcome::Started
2920            || self.outcome == PromotionOutcome::Started
2921        {
2922            return Err(PromotionReceiptError::Terminal {
2923                attempt_id: existing.attempt_id,
2924                outcome: existing.outcome,
2925            });
2926        }
2927        let temporary = parent.join(format!(".{name}.{}.tmp", self.receipt_digest));
2928        let mut file = std::fs::OpenOptions::new()
2929            .write(true)
2930            .create_new(true)
2931            .open(&temporary)?;
2932        file.write_all(&rendered)?;
2933        file.sync_all()?;
2934        std::fs::rename(temporary, path)?;
2935        Ok(())
2936    }
2937
2938    pub fn read_json(path: impl AsRef<Path>) -> Result<Self, PromotionReceiptError> {
2939        let value: serde_json::Value = serde_json::from_slice(&std::fs::read(path)?)?;
2940        let receipt: Self = serde_json::from_value(value.clone())?;
2941        if serde_json::to_value(&receipt)? != value {
2942            return Err(PromotionReceiptError::Invalid(
2943                "promotion receipt contains unknown or non-canonical fields".into(),
2944            ));
2945        }
2946        receipt.verify_structure()?;
2947        Ok(receipt)
2948    }
2949
2950    pub fn verify_at(&self, root: impl AsRef<Path>) -> Result<(), PromotionReceiptError> {
2951        self.verify_structure()?;
2952        let root = root.as_ref();
2953        self.deployment_receipt
2954            .verify_at(root)
2955            .map_err(|error| PromotionReceiptError::Invalid(error.to_string()))?;
2956        self.hosted_verification
2957            .verify_at(root)
2958            .map_err(|error| PromotionReceiptError::Invalid(error.to_string()))?;
2959
2960        let deployment_path = root.join(&self.deployment_receipt.path);
2961        let value: serde_json::Value = serde_json::from_slice(&std::fs::read(&deployment_path)?)?;
2962        let deployment: DeploymentReceipt = serde_json::from_value(value.clone())?;
2963        if serde_json::to_value(&deployment)? != value {
2964            return Err(PromotionReceiptError::Invalid(
2965                "deployment receipt contains unknown or non-canonical fields".into(),
2966            ));
2967        }
2968        deployment
2969            .verify_at(root)
2970            .map_err(|error| PromotionReceiptError::Invalid(error.to_string()))?;
2971        if deployment.outcome() != DeploymentOutcome::Succeeded
2972            || deployment.release_id != self.release_id
2973            || deployment.release_digest != self.release_digest
2974            || deployment.environment != self.environment
2975        {
2976            return Err(PromotionReceiptError::Invalid(
2977                "promotion does not bind a successful deployment of the exact release".into(),
2978            ));
2979        }
2980        let hosted = deployment
2981            .verification()
2982            .iter()
2983            .filter(|verification| verification.kind == "hosted_verification")
2984            .collect::<Vec<_>>();
2985        let [verification] = hosted.as_slice() else {
2986            return Err(PromotionReceiptError::Invalid(
2987                "deployment must bind exactly one hosted verification report".into(),
2988            ));
2989        };
2990        if verification.file != self.hosted_verification {
2991            return Err(PromotionReceiptError::Invalid(
2992                "deployment hosted verification binding does not match promotion".into(),
2993            ));
2994        }
2995        for verification in deployment.verification() {
2996            match verification.kind.as_str() {
2997                "hosted_verification" => {}
2998                "static_site_verification" => {
2999                    let value: serde_json::Value = serde_json::from_slice(&std::fs::read(
3000                        root.join(&verification.file.path),
3001                    )?)?;
3002                    let report: StaticSiteVerificationReport =
3003                        serde_json::from_value(value.clone())?;
3004                    if serde_json::to_value(&report)? != value
3005                        || report.verify_structure().is_err()
3006                        || report.release_digest != self.release_digest
3007                    {
3008                        return Err(PromotionReceiptError::Invalid(
3009                            "static-site verification does not bind the promoted release".into(),
3010                        ));
3011                    }
3012                }
3013                _ => {
3014                    return Err(PromotionReceiptError::Invalid(
3015                        "deployment contains an unsupported verification kind".into(),
3016                    ));
3017                }
3018            }
3019        }
3020        let release_value: serde_json::Value = serde_json::from_slice(&std::fs::read(
3021            root.join(&deployment.release_manifest.path),
3022        )?)?;
3023        let release: minco_release::ReleaseManifest =
3024            serde_json::from_value(release_value.clone())?;
3025        if serde_json::to_value(&release)? != release_value {
3026            return Err(PromotionReceiptError::Invalid(
3027                "release manifest contains unknown or non-canonical fields".into(),
3028            ));
3029        }
3030        release
3031            .verify_at(root)
3032            .map_err(|error| PromotionReceiptError::Invalid(error.to_string()))?;
3033        let api_artifacts = release
3034            .artifacts
3035            .iter()
3036            .filter(|artifact| artifact.function_id == "api")
3037            .collect::<Vec<_>>();
3038        let [api_artifact] = api_artifacts.as_slice() else {
3039            return Err(PromotionReceiptError::Invalid(
3040                "release must bind exactly one API artifact".into(),
3041            ));
3042        };
3043        let report = HostedVerificationReport::read_json(
3044            root.join(&self.hosted_verification.path),
3045            &api_artifact.file.sha256,
3046        )
3047        .map_err(|error| PromotionReceiptError::Invalid(error.to_string()))?;
3048        if report.executed_version != self.promoted_version {
3049            return Err(PromotionReceiptError::Invalid(
3050                "hosted verification version does not match promotion".into(),
3051            ));
3052        }
3053        Ok(())
3054    }
3055
3056    fn require_started(&self) -> Result<(), PromotionReceiptError> {
3057        if self.outcome == PromotionOutcome::Started {
3058            Ok(())
3059        } else {
3060            Err(PromotionReceiptError::Terminal {
3061                attempt_id: self.attempt_id.clone(),
3062                outcome: self.outcome,
3063            })
3064        }
3065    }
3066
3067    fn same_binding(&self, other: &Self) -> bool {
3068        self.schema_version == other.schema_version
3069            && self.attempt_id == other.attempt_id
3070            && self.release_id == other.release_id
3071            && self.release_digest == other.release_digest
3072            && self.environment == other.environment
3073            && self.deployment_receipt == other.deployment_receipt
3074            && self.hosted_verification == other.hosted_verification
3075            && self.operator_approval_digest == other.operator_approval_digest
3076            && self.stack_name == other.stack_name
3077            && self.live_alias_logical_id == other.live_alias_logical_id
3078            && self.previous_version == other.previous_version
3079            && self.promoted_version == other.promoted_version
3080            && self.change_set == other.change_set
3081    }
3082
3083    fn verify_structure(&self) -> Result<(), PromotionReceiptError> {
3084        if self.schema_version != 1
3085            || !identifier_is_valid(&self.attempt_id)
3086            || !release_identity_is_valid(&self.release_id, &self.release_digest)
3087            || self.operator_approval_digest != self.hosted_verification.sha256
3088            || !stack_name_is_valid(&self.stack_name)
3089            || !self
3090                .live_alias_logical_id
3091                .bytes()
3092                .all(|byte| byte.is_ascii_alphanumeric())
3093            || !(self.previous_version == "candidate"
3094                || published_version_is_valid(&self.previous_version))
3095            || !published_version_is_valid(&self.promoted_version)
3096            || self.previous_version == self.promoted_version
3097        {
3098            return Err(PromotionReceiptError::Invalid(
3099                "promotion receipt binding is invalid".into(),
3100            ));
3101        }
3102        validate_bound_file(&self.deployment_receipt, "deployment receipt")
3103            .map_err(|error| PromotionReceiptError::Invalid(error.to_string()))?;
3104        validate_bound_file(&self.hosted_verification, "hosted verification")
3105            .map_err(|error| PromotionReceiptError::Invalid(error.to_string()))?;
3106        verify_promotion_boundary(
3107            &self.change_set,
3108            &self.stack_name,
3109            &self.live_alias_logical_id,
3110        )?;
3111        match self.outcome {
3112            PromotionOutcome::Started | PromotionOutcome::Succeeded
3113                if self.failure_code.is_none() => {}
3114            PromotionOutcome::Failed
3115                if self
3116                    .failure_code
3117                    .as_deref()
3118                    .is_some_and(identifier_is_valid) => {}
3119            _ => {
3120                return Err(PromotionReceiptError::Invalid(
3121                    "promotion outcome and failure are inconsistent".into(),
3122                ));
3123            }
3124        }
3125        let actual = self.calculate_digest()?;
3126        if self.receipt_digest != actual {
3127            return Err(PromotionReceiptError::DigestMismatch);
3128        }
3129        Ok(())
3130    }
3131
3132    fn refresh_digest(&mut self) -> Result<(), PromotionReceiptError> {
3133        self.receipt_digest = self.calculate_digest()?;
3134        Ok(())
3135    }
3136
3137    fn calculate_digest(&self) -> Result<String, PromotionReceiptError> {
3138        #[derive(Serialize)]
3139        struct DigestPayload<'a> {
3140            schema_version: u32,
3141            attempt_id: &'a str,
3142            release_id: &'a str,
3143            release_digest: &'a str,
3144            environment: &'a ReleaseEnvironment,
3145            deployment_receipt: &'a FileDigest,
3146            hosted_verification: &'a FileDigest,
3147            operator_approval_digest: &'a str,
3148            stack_name: &'a str,
3149            live_alias_logical_id: &'a str,
3150            previous_version: &'a str,
3151            promoted_version: &'a str,
3152            change_set: &'a CloudFormationChangeSet,
3153            outcome: PromotionOutcome,
3154            failure_code: &'a Option<String>,
3155        }
3156        let payload = DigestPayload {
3157            schema_version: self.schema_version,
3158            attempt_id: &self.attempt_id,
3159            release_id: &self.release_id,
3160            release_digest: &self.release_digest,
3161            environment: &self.environment,
3162            deployment_receipt: &self.deployment_receipt,
3163            hosted_verification: &self.hosted_verification,
3164            operator_approval_digest: &self.operator_approval_digest,
3165            stack_name: &self.stack_name,
3166            live_alias_logical_id: &self.live_alias_logical_id,
3167            previous_version: &self.previous_version,
3168            promoted_version: &self.promoted_version,
3169            change_set: &self.change_set,
3170            outcome: self.outcome,
3171            failure_code: &self.failure_code,
3172        };
3173        Ok(hex::encode(Sha256::digest(serde_json::to_vec(&payload)?)))
3174    }
3175}
3176
3177#[derive(Debug, Error)]
3178pub enum PromotionReceiptError {
3179    #[error("invalid promotion receipt: {0}")]
3180    Invalid(String),
3181    #[error("promotion receipt digest does not match its contents")]
3182    DigestMismatch,
3183    #[error("promotion receipt {0} conflicts with an existing attempt")]
3184    Conflict(String),
3185    #[error("promotion receipt {attempt_id} is already terminal as {outcome:?}")]
3186    Terminal {
3187        attempt_id: String,
3188        outcome: PromotionOutcome,
3189    },
3190    #[error(transparent)]
3191    Boundary(#[from] PromotionBoundaryError),
3192    #[error("promotion receipt JSON is invalid: {0}")]
3193    Json(#[from] serde_json::Error),
3194    #[error("promotion receipt I/O failed: {0}")]
3195    Io(#[from] std::io::Error),
3196}
3197
3198fn identifier_is_valid(value: &str) -> bool {
3199    !value.is_empty()
3200        && value.len() <= 128
3201        && value
3202            .bytes()
3203            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':'))
3204}
3205
3206fn published_version_is_valid(value: &str) -> bool {
3207    value
3208        .parse::<u64>()
3209        .ok()
3210        .is_some_and(|version| version > 0 && version.to_string() == value)
3211}
3212
3213#[derive(Debug, Clone, PartialEq, Eq, Error)]
3214pub enum HostedVerificationError {
3215    #[error("hosted verification field {field} is invalid")]
3216    InvalidField { field: &'static str },
3217    #[error("required hosted {kind:?} check is missing")]
3218    MissingRequiredCheck { kind: HostedCheckKind },
3219    #[error("required hosted {kind:?} check is duplicated")]
3220    DuplicateRequiredCheck { kind: HostedCheckKind },
3221    #[error("hosted {kind:?} check evidence is invalid")]
3222    InvalidCheck { kind: HostedCheckKind },
3223    #[error("required hosted {kind:?} check failed")]
3224    RequiredCheckFailed { kind: HostedCheckKind },
3225    #[error("executed artifact does not match the verified release")]
3226    ArtifactMismatch,
3227    #[error("hosted verification JSON is invalid: {0}")]
3228    Serialization(String),
3229    #[error("hosted verification I/O failed: {0}")]
3230    Io(String),
3231    #[error("immutable hosted verification report already exists at {0}")]
3232    Conflict(String),
3233}
3234
3235fn request_id_is_valid(value: &str) -> bool {
3236    if value.is_empty() || value.len() > 128 {
3237        return false;
3238    }
3239    let value_without_padding = value
3240        .strip_suffix("==")
3241        .or_else(|| value.strip_suffix('='))
3242        .unwrap_or(value);
3243    !value_without_padding.is_empty()
3244        && !value_without_padding.contains('=')
3245        && value_without_padding
3246            .bytes()
3247            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':'))
3248}
3249
3250fn source_change_is_valid(value: &str) -> bool {
3251    matches!(value.len(), 40 | 64)
3252        && value
3253            .bytes()
3254            .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
3255}
3256
3257fn validate_bound_file(
3258    file: &FileDigest,
3259    label: &'static str,
3260) -> Result<(), ChangeSetReceiptError> {
3261    let path = Path::new(&file.path);
3262    if file.bytes == 0
3263        || !sha256_is_valid(&file.sha256)
3264        || path.is_absolute()
3265        || !path
3266            .components()
3267            .all(|component| matches!(component, Component::Normal(_)))
3268    {
3269        return Err(ChangeSetReceiptError::Invalid(format!(
3270            "{label} binding is invalid"
3271        )));
3272    }
3273    Ok(())
3274}
3275
3276fn cloudformation_arn_identity<'a>(
3277    value: &'a str,
3278    expected_kind: &str,
3279    expected_name: &str,
3280) -> Result<(&'a str, &'a str, &'a str), ChangeSetReceiptError> {
3281    let parts = value.splitn(6, ':').collect::<Vec<_>>();
3282    let resource_is_valid = parts.get(5).is_some_and(|resource| {
3283        resource
3284            .strip_prefix(&format!("{expected_kind}/"))
3285            .and_then(|resource| resource.split_once('/'))
3286            .is_some_and(|(name, id)| name == expected_name && !id.is_empty() && !id.contains('/'))
3287    });
3288    if parts.len() != 6
3289        || parts[0] != "arn"
3290        || !parts[1].starts_with("aws")
3291        || parts[2] != "cloudformation"
3292        || !region_is_valid(parts[3])
3293        || !account_id_is_valid(parts[4])
3294        || !resource_is_valid
3295    {
3296        return Err(ChangeSetReceiptError::Invalid(
3297            "CloudFormation ARN is invalid".into(),
3298        ));
3299    }
3300    Ok((parts[1], parts[3], parts[4]))
3301}
3302
3303#[derive(Debug, Deserialize)]
3304#[serde(rename_all = "PascalCase")]
3305struct ProviderChangeSet {
3306    change_set_name: String,
3307    change_set_id: String,
3308    stack_id: String,
3309    stack_name: String,
3310    change_set_type: Option<ProviderChangeSetType>,
3311    status: ProviderChangeSetStatus,
3312    execution_status: ProviderExecutionStatus,
3313    #[serde(default)]
3314    changes: Vec<ProviderChange>,
3315}
3316
3317#[derive(Debug, Deserialize)]
3318struct ProviderChange {
3319    #[serde(rename = "Type")]
3320    kind: String,
3321    #[serde(rename = "ResourceChange")]
3322    resource_change: ProviderResourceChange,
3323}
3324
3325#[derive(Debug, Deserialize)]
3326#[serde(rename_all = "PascalCase")]
3327struct ProviderResourceChange {
3328    action: ProviderChangeAction,
3329    logical_resource_id: String,
3330    resource_type: String,
3331    replacement: Option<ProviderReplacement>,
3332    policy_action: Option<ProviderPolicyAction>,
3333    #[serde(default)]
3334    scope: Vec<ProviderChangeScope>,
3335}
3336
3337macro_rules! provider_enum {
3338    ($provider:ident => $public:ident { $($variant:ident),+ $(,)? }) => {
3339        #[derive(Debug, Deserialize)]
3340        enum $provider {
3341            $($variant),+
3342        }
3343
3344        impl From<$provider> for $public {
3345            fn from(value: $provider) -> Self {
3346                match value {
3347                    $($provider::$variant => Self::$variant),+
3348                }
3349            }
3350        }
3351    };
3352}
3353
3354#[derive(Debug, Deserialize)]
3355#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
3356enum ProviderChangeSetType {
3357    Create,
3358    Update,
3359    Import,
3360}
3361
3362impl From<ProviderChangeSetType> for ChangeSetType {
3363    fn from(value: ProviderChangeSetType) -> Self {
3364        match value {
3365            ProviderChangeSetType::Create => Self::Create,
3366            ProviderChangeSetType::Update => Self::Update,
3367            ProviderChangeSetType::Import => Self::Import,
3368        }
3369    }
3370}
3371
3372#[derive(Debug, Deserialize)]
3373#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
3374enum ProviderChangeSetStatus {
3375    CreatePending,
3376    CreateInProgress,
3377    CreateComplete,
3378    DeletePending,
3379    DeleteInProgress,
3380    DeleteComplete,
3381    DeleteFailed,
3382    Failed,
3383}
3384
3385impl From<ProviderChangeSetStatus> for ChangeSetStatus {
3386    fn from(value: ProviderChangeSetStatus) -> Self {
3387        match value {
3388            ProviderChangeSetStatus::CreatePending => Self::CreatePending,
3389            ProviderChangeSetStatus::CreateInProgress => Self::CreateInProgress,
3390            ProviderChangeSetStatus::CreateComplete => Self::CreateComplete,
3391            ProviderChangeSetStatus::DeletePending => Self::DeletePending,
3392            ProviderChangeSetStatus::DeleteInProgress => Self::DeleteInProgress,
3393            ProviderChangeSetStatus::DeleteComplete => Self::DeleteComplete,
3394            ProviderChangeSetStatus::DeleteFailed => Self::DeleteFailed,
3395            ProviderChangeSetStatus::Failed => Self::Failed,
3396        }
3397    }
3398}
3399
3400#[derive(Debug, Deserialize)]
3401#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
3402enum ProviderExecutionStatus {
3403    Unavailable,
3404    Available,
3405    ExecuteInProgress,
3406    ExecuteComplete,
3407    ExecuteFailed,
3408    Obsolete,
3409}
3410
3411impl From<ProviderExecutionStatus> for ExecutionStatus {
3412    fn from(value: ProviderExecutionStatus) -> Self {
3413        match value {
3414            ProviderExecutionStatus::Unavailable => Self::Unavailable,
3415            ProviderExecutionStatus::Available => Self::Available,
3416            ProviderExecutionStatus::ExecuteInProgress => Self::ExecuteInProgress,
3417            ProviderExecutionStatus::ExecuteComplete => Self::ExecuteComplete,
3418            ProviderExecutionStatus::ExecuteFailed => Self::ExecuteFailed,
3419            ProviderExecutionStatus::Obsolete => Self::Obsolete,
3420        }
3421    }
3422}
3423provider_enum!(ProviderChangeAction => ChangeAction {
3424    Add,
3425    Modify,
3426    Remove,
3427    Import,
3428    Dynamic,
3429    SyncWithActual,
3430});
3431provider_enum!(ProviderPolicyAction => PolicyAction {
3432    Delete,
3433    Retain,
3434    Snapshot,
3435    ReplaceAndDelete,
3436    ReplaceAndRetain,
3437    ReplaceAndSnapshot,
3438});
3439provider_enum!(ProviderChangeScope => ChangeScope {
3440    Properties,
3441    Metadata,
3442    CreationPolicy,
3443    UpdatePolicy,
3444    DeletionPolicy,
3445    UpdateReplacePolicy,
3446    Tags,
3447});
3448
3449#[derive(Debug, Deserialize)]
3450enum ProviderReplacement {
3451    True,
3452    False,
3453    Conditional,
3454}
3455
3456impl From<ProviderReplacement> for Replacement {
3457    fn from(value: ProviderReplacement) -> Self {
3458        match value {
3459            ProviderReplacement::True => Self::Always,
3460            ProviderReplacement::False => Self::Never,
3461            ProviderReplacement::Conditional => Self::Conditional,
3462        }
3463    }
3464}
3465
3466#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3467#[serde(rename_all = "snake_case")]
3468pub enum DriftState {
3469    Clean,
3470    Drifted,
3471    Unknown,
3472}
3473
3474#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3475#[serde(tag = "state", rename_all = "snake_case")]
3476pub enum MigrationState {
3477    NotRequired,
3478    Verified { plan_digest: String },
3479    Missing,
3480    Drifted,
3481}
3482
3483#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3484#[serde(rename_all = "snake_case")]
3485pub enum SourceState {
3486    Clean,
3487    Dirty,
3488    Conflicted,
3489    Unknown,
3490}
3491
3492#[derive(Debug, Clone, PartialEq, Eq)]
3493pub struct EnvironmentExpectation {
3494    pub account_id: String,
3495    pub region: String,
3496    pub environment: String,
3497    pub role_arn: String,
3498    pub release_id: String,
3499    pub release_digest: String,
3500    pub configuration_digest: String,
3501    pub migration_plan_digest: Option<String>,
3502}
3503
3504#[derive(Debug, Clone, PartialEq, Eq)]
3505pub struct EnvironmentObservation {
3506    pub account_id: String,
3507    pub region: String,
3508    pub environment: String,
3509    pub role_arn: String,
3510    pub release_id: String,
3511    pub release_digest: String,
3512    pub release_verified: bool,
3513    pub configuration_digest: String,
3514    pub drift: DriftState,
3515    pub migration: MigrationState,
3516    pub source: SourceState,
3517    pub operator_approval_digest: Option<String>,
3518}
3519
3520#[derive(Debug, Clone, PartialEq, Eq)]
3521pub struct VerifiedEnvironment {
3522    pub account_id: String,
3523    pub region: String,
3524    pub environment: String,
3525    pub role_arn: String,
3526    pub release_id: String,
3527    pub release_digest: String,
3528}
3529
3530#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
3531#[error("caller identity is not an IAM role or STS assumed-role session")]
3532pub struct CallerIdentityError;
3533
3534pub fn caller_role_arn(caller_arn: &str) -> Result<String, CallerIdentityError> {
3535    let parts = caller_arn.splitn(6, ':').collect::<Vec<_>>();
3536    if parts.len() != 6
3537        || parts[0] != "arn"
3538        || !parts[1].starts_with("aws")
3539        || !parts[3].is_empty()
3540        || !account_id_is_valid(parts[4])
3541    {
3542        return Err(CallerIdentityError);
3543    }
3544    if parts[2] == "iam" && parts[5].starts_with("role/") {
3545        return role_arn_is_valid(caller_arn, parts[4])
3546            .then(|| caller_arn.to_owned())
3547            .ok_or(CallerIdentityError);
3548    }
3549    if parts[2] != "sts" {
3550        return Err(CallerIdentityError);
3551    }
3552    let assumed_role = parts[5]
3553        .strip_prefix("assumed-role/")
3554        .ok_or(CallerIdentityError)?;
3555    let (role, session) = assumed_role.split_once('/').ok_or(CallerIdentityError)?;
3556    if role.is_empty() || session.is_empty() || session.contains('/') {
3557        return Err(CallerIdentityError);
3558    }
3559    let role_arn = format!("arn:{}:iam::{}:role/{role}", parts[1], parts[4]);
3560    role_arn_is_valid(&role_arn, parts[4])
3561        .then_some(role_arn)
3562        .ok_or(CallerIdentityError)
3563}
3564
3565#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3566#[serde(rename_all = "snake_case")]
3567pub enum GuardFailureCode {
3568    AccountInvalid,
3569    RegionInvalid,
3570    EnvironmentInvalid,
3571    RoleInvalid,
3572    ReleaseInvalid,
3573    ConfigurationInvalid,
3574    MigrationInvalid,
3575    OperatorApprovalInvalid,
3576    AccountMismatch,
3577    RegionMismatch,
3578    EnvironmentMismatch,
3579    RoleMismatch,
3580    ReleaseMismatch,
3581    ReleaseUnverified,
3582    ConfigurationMismatch,
3583    DriftUnproved,
3584    MigrationUnproved,
3585    SourceDirty,
3586    OperatorApprovalMissing,
3587    OperatorApprovalMismatch,
3588}
3589
3590#[derive(Debug, Clone, PartialEq, Eq, Error)]
3591#[error("deployment guards failed: {codes:?}")]
3592pub struct GuardFailure {
3593    codes: Vec<GuardFailureCode>,
3594}
3595
3596impl GuardFailure {
3597    pub fn codes(&self) -> Vec<GuardFailureCode> {
3598        self.codes.clone()
3599    }
3600}
3601
3602pub fn verify_guards(
3603    expected: &EnvironmentExpectation,
3604    observed: &EnvironmentObservation,
3605) -> Result<VerifiedEnvironment, GuardFailure> {
3606    let mut codes = Vec::new();
3607    if !account_id_is_valid(&expected.account_id) || !account_id_is_valid(&observed.account_id) {
3608        codes.push(GuardFailureCode::AccountInvalid);
3609    }
3610    if !region_is_valid(&expected.region) || !region_is_valid(&observed.region) {
3611        codes.push(GuardFailureCode::RegionInvalid);
3612    }
3613    if !environment_is_valid(&expected.environment) || !environment_is_valid(&observed.environment)
3614    {
3615        codes.push(GuardFailureCode::EnvironmentInvalid);
3616    }
3617    if !role_arn_is_valid(&expected.role_arn, &expected.account_id)
3618        || !role_arn_is_valid(&observed.role_arn, &observed.account_id)
3619    {
3620        codes.push(GuardFailureCode::RoleInvalid);
3621    }
3622    if !release_identity_is_valid(&expected.release_id, &expected.release_digest)
3623        || !release_identity_is_valid(&observed.release_id, &observed.release_digest)
3624    {
3625        codes.push(GuardFailureCode::ReleaseInvalid);
3626    }
3627    if !sha256_is_valid(&expected.configuration_digest)
3628        || !sha256_is_valid(&observed.configuration_digest)
3629    {
3630        codes.push(GuardFailureCode::ConfigurationInvalid);
3631    }
3632    if expected
3633        .migration_plan_digest
3634        .as_deref()
3635        .is_some_and(|digest| !sha256_is_valid(digest))
3636        || matches!(
3637            &observed.migration,
3638            MigrationState::Verified { plan_digest } if !sha256_is_valid(plan_digest)
3639        )
3640    {
3641        codes.push(GuardFailureCode::MigrationInvalid);
3642    }
3643    if observed
3644        .operator_approval_digest
3645        .as_deref()
3646        .is_some_and(|digest| !sha256_is_valid(digest))
3647    {
3648        codes.push(GuardFailureCode::OperatorApprovalInvalid);
3649    }
3650    if observed.account_id != expected.account_id {
3651        codes.push(GuardFailureCode::AccountMismatch);
3652    }
3653    if observed.region != expected.region {
3654        codes.push(GuardFailureCode::RegionMismatch);
3655    }
3656    if observed.environment != expected.environment {
3657        codes.push(GuardFailureCode::EnvironmentMismatch);
3658    }
3659    if observed.role_arn != expected.role_arn {
3660        codes.push(GuardFailureCode::RoleMismatch);
3661    }
3662    if observed.release_id != expected.release_id
3663        || observed.release_digest != expected.release_digest
3664    {
3665        codes.push(GuardFailureCode::ReleaseMismatch);
3666    }
3667    if !observed.release_verified {
3668        codes.push(GuardFailureCode::ReleaseUnverified);
3669    }
3670    if observed.configuration_digest != expected.configuration_digest {
3671        codes.push(GuardFailureCode::ConfigurationMismatch);
3672    }
3673    if observed.drift != DriftState::Clean {
3674        codes.push(GuardFailureCode::DriftUnproved);
3675    }
3676    let migration_matches = match (
3677        expected.migration_plan_digest.as_deref(),
3678        &observed.migration,
3679    ) {
3680        (None, MigrationState::NotRequired) => true,
3681        (Some(expected), MigrationState::Verified { plan_digest }) => plan_digest == expected,
3682        _ => false,
3683    };
3684    if !migration_matches {
3685        codes.push(GuardFailureCode::MigrationUnproved);
3686    }
3687    if observed.source != SourceState::Clean {
3688        codes.push(GuardFailureCode::SourceDirty);
3689    }
3690    match observed.operator_approval_digest.as_deref() {
3691        None => codes.push(GuardFailureCode::OperatorApprovalMissing),
3692        Some(digest) if digest != expected.release_digest => {
3693            codes.push(GuardFailureCode::OperatorApprovalMismatch);
3694        }
3695        Some(_) => {}
3696    }
3697
3698    if !codes.is_empty() {
3699        return Err(GuardFailure { codes });
3700    }
3701
3702    Ok(VerifiedEnvironment {
3703        account_id: observed.account_id.clone(),
3704        region: observed.region.clone(),
3705        environment: observed.environment.clone(),
3706        role_arn: observed.role_arn.clone(),
3707        release_id: observed.release_id.clone(),
3708        release_digest: observed.release_digest.clone(),
3709    })
3710}
3711
3712fn account_id_is_valid(value: &str) -> bool {
3713    value.len() == 12 && value.bytes().all(|byte| byte.is_ascii_digit())
3714}
3715
3716fn region_is_valid(value: &str) -> bool {
3717    let mut segments = value.split('-');
3718    let Some(first) = segments.next() else {
3719        return false;
3720    };
3721    let remaining = segments.collect::<Vec<_>>();
3722    !first.is_empty()
3723        && first.bytes().all(|byte| byte.is_ascii_lowercase())
3724        && remaining.len() >= 2
3725        && remaining[..remaining.len() - 1].iter().all(|segment| {
3726            !segment.is_empty()
3727                && segment
3728                    .bytes()
3729                    .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
3730        })
3731        && remaining.last().is_some_and(|segment| {
3732            !segment.is_empty() && segment.bytes().all(|b| b.is_ascii_digit())
3733        })
3734}
3735
3736fn environment_is_valid(value: &str) -> bool {
3737    let mut bytes = value.bytes();
3738    value.len() <= 64
3739        && bytes
3740            .next()
3741            .is_some_and(|byte| byte.is_ascii_alphanumeric())
3742        && bytes.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
3743}
3744
3745fn role_arn_is_valid(value: &str, account_id: &str) -> bool {
3746    let parts = value.splitn(6, ':').collect::<Vec<_>>();
3747    parts.len() == 6
3748        && parts[0] == "arn"
3749        && parts[1].starts_with("aws")
3750        && parts[2] == "iam"
3751        && parts[3].is_empty()
3752        && parts[4] == account_id
3753        && parts[5].strip_prefix("role/").is_some_and(|role| {
3754            !role.is_empty()
3755                && role.bytes().all(|byte| {
3756                    byte.is_ascii_alphanumeric()
3757                        || matches!(byte, b'/' | b'+' | b'=' | b',' | b'.' | b'@' | b'_' | b'-')
3758                })
3759        })
3760}
3761
3762fn release_identity_is_valid(release_id: &str, release_digest: &str) -> bool {
3763    sha256_is_valid(release_digest) && release_id == format!("minco.{}", &release_digest[..24])
3764}
3765
3766fn sha256_is_valid(value: &str) -> bool {
3767    value.len() == 64
3768        && value
3769            .bytes()
3770            .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
3771}
3772
3773#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3774#[serde(deny_unknown_fields)]
3775pub struct DeploymentTargetCatalog {
3776    pub schema_version: u32,
3777    pub default_environment: String,
3778    pub environments: BTreeMap<String, DeploymentTarget>,
3779}
3780
3781#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3782#[serde(rename_all = "snake_case")]
3783pub enum DeploymentTargetLifecycle {
3784    #[default]
3785    Persistent,
3786    Preview,
3787}
3788
3789#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3790#[serde(rename_all = "snake_case")]
3791pub enum ReviewScheduleCompletionAction {
3792    Delete,
3793}
3794
3795#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3796#[serde(deny_unknown_fields)]
3797pub struct ReviewCleanupSchedule {
3798    pub expression: String,
3799    pub action_after_completion: ReviewScheduleCompletionAction,
3800    pub residual_resources: Vec<String>,
3801    pub manual_fallback: String,
3802}
3803
3804#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3805#[serde(deny_unknown_fields)]
3806pub struct PreviewTargetPolicy {
3807    pub owner: String,
3808    pub ttl_seconds: u32,
3809    pub resources: Vec<ReviewResource>,
3810    pub pricing_complete: bool,
3811    #[serde(default)]
3812    pub cleanup_schedule: Option<ReviewCleanupSchedule>,
3813}
3814
3815#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3816#[serde(deny_unknown_fields)]
3817pub struct CanaryTargetPolicy {
3818    pub initial_traffic_percent: u8,
3819    pub monitoring_minutes: u16,
3820    pub alarm_arns: Vec<String>,
3821    #[serde(default = "weighted_live_alias")]
3822    pub api_routing: String,
3823    #[serde(default = "preserve_current_event_sources")]
3824    pub worker_routing: String,
3825    #[serde(default)]
3826    pub provisioned_concurrency: bool,
3827}
3828
3829#[derive(Debug, Clone, PartialEq, Eq)]
3830pub struct CanaryShiftInput {
3831    pub policy: CanaryTargetPolicy,
3832    pub expected_account_id: String,
3833    pub expected_region: String,
3834    pub stack_name: String,
3835    pub function_name: String,
3836    pub alias_name: String,
3837    pub current_version: String,
3838    pub candidate_version: String,
3839    pub pre_traffic_verification_digest: String,
3840}
3841
3842#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3843#[serde(deny_unknown_fields)]
3844pub struct CanaryShiftPlan {
3845    pub schema_version: u32,
3846    pub expected_account_id: String,
3847    pub expected_region: String,
3848    pub stack_name: String,
3849    pub function_name: String,
3850    pub alias_name: String,
3851    pub current_version: String,
3852    pub candidate_version: String,
3853    pub candidate_weight_basis_points: u16,
3854    pub monitoring_minutes: u16,
3855    pub alarm_arns: Vec<String>,
3856    pub pre_traffic_verification_digest: String,
3857    pub api_routing: String,
3858    pub worker_routing: String,
3859    pub additional_resources: Vec<String>,
3860    pub idle_compute_cost: String,
3861    pub pricing_complete: bool,
3862    pub cost_notes: Vec<String>,
3863}
3864
3865#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3866#[serde(rename_all = "snake_case")]
3867pub enum CanaryAlarmState {
3868    Ok,
3869    Alarm,
3870    InsufficientData,
3871}
3872
3873#[derive(Debug, Clone, PartialEq, Eq)]
3874pub struct CanaryObservation {
3875    pub elapsed_minutes: u16,
3876    pub alarm_states: BTreeMap<String, CanaryAlarmState>,
3877    pub post_traffic_verification_digest: Option<String>,
3878}
3879
3880#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3881#[serde(rename_all = "snake_case")]
3882pub enum CanaryOutcome {
3883    Continue,
3884    Complete,
3885    Reverse { code: String },
3886}
3887
3888#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3889#[serde(rename_all = "snake_case")]
3890pub enum CanaryExecutionOutcome {
3891    Started,
3892    Reversed,
3893    Succeeded,
3894}
3895
3896#[derive(Debug, Clone, PartialEq, Eq)]
3897pub struct CanaryExecutionReceiptInput {
3898    pub attempt_id: String,
3899    pub plan: CanaryShiftPlan,
3900    pub change_set: CloudFormationChangeSet,
3901}
3902
3903#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3904#[serde(deny_unknown_fields)]
3905pub struct CanaryExecutionReceipt {
3906    pub schema_version: u32,
3907    pub receipt_digest: String,
3908    pub attempt_id: String,
3909    pub plan: CanaryShiftPlan,
3910    pub change_set: CloudFormationChangeSet,
3911    pub cleanup_change_set: Option<CloudFormationChangeSet>,
3912    outcome: CanaryExecutionOutcome,
3913    failure_code: Option<String>,
3914}
3915
3916impl CanaryExecutionReceipt {
3917    pub fn start(input: CanaryExecutionReceiptInput) -> Result<Self, CanaryReceiptError> {
3918        verify_promotion_boundary(
3919            &input.change_set,
3920            &input.plan.stack_name,
3921            "LiveFunctionAlias",
3922        )?;
3923        validate_canary_shift_plan(&input.plan)?;
3924        let mut receipt = Self {
3925            schema_version: 1,
3926            receipt_digest: String::new(),
3927            attempt_id: input.attempt_id,
3928            plan: input.plan,
3929            change_set: input.change_set,
3930            cleanup_change_set: None,
3931            outcome: CanaryExecutionOutcome::Started,
3932            failure_code: None,
3933        };
3934        receipt.refresh_digest()?;
3935        receipt.verify_structure()?;
3936        Ok(receipt)
3937    }
3938
3939    pub const fn outcome(&self) -> CanaryExecutionOutcome {
3940        self.outcome
3941    }
3942
3943    pub fn succeed(
3944        &mut self,
3945        cleanup_change_set: CloudFormationChangeSet,
3946    ) -> Result<(), CanaryReceiptError> {
3947        self.require_started()?;
3948        verify_promotion_boundary(
3949            &cleanup_change_set,
3950            &self.plan.stack_name,
3951            "LiveFunctionAlias",
3952        )?;
3953        self.cleanup_change_set = Some(cleanup_change_set);
3954        self.outcome = CanaryExecutionOutcome::Succeeded;
3955        self.refresh_digest()?;
3956        self.verify_structure()
3957    }
3958
3959    pub fn reverse(&mut self, code: impl Into<String>) -> Result<(), CanaryReceiptError> {
3960        self.require_started()?;
3961        let code = code.into();
3962        if !identifier_is_valid(&code) {
3963            return Err(CanaryReceiptError::Invalid(
3964                "canary reversal code is invalid".into(),
3965            ));
3966        }
3967        self.outcome = CanaryExecutionOutcome::Reversed;
3968        self.failure_code = Some(code);
3969        self.refresh_digest()?;
3970        self.verify_structure()
3971    }
3972
3973    pub fn reverse_with_cleanup(
3974        &mut self,
3975        code: impl Into<String>,
3976        cleanup_change_set: CloudFormationChangeSet,
3977    ) -> Result<(), CanaryReceiptError> {
3978        self.require_started()?;
3979        verify_promotion_boundary(
3980            &cleanup_change_set,
3981            &self.plan.stack_name,
3982            "LiveFunctionAlias",
3983        )?;
3984        let code = code.into();
3985        if !identifier_is_valid(&code) {
3986            return Err(CanaryReceiptError::Invalid(
3987                "canary reversal code is invalid".into(),
3988            ));
3989        }
3990        self.cleanup_change_set = Some(cleanup_change_set);
3991        self.outcome = CanaryExecutionOutcome::Reversed;
3992        self.failure_code = Some(code);
3993        self.refresh_digest()?;
3994        self.verify_structure()
3995    }
3996
3997    pub fn write_json(&self, path: impl AsRef<Path>) -> Result<(), CanaryReceiptError> {
3998        self.verify_structure()?;
3999        let path = path.as_ref();
4000        let parent = path.parent().unwrap_or_else(|| Path::new("."));
4001        let name = path
4002            .file_name()
4003            .and_then(|name| name.to_str())
4004            .ok_or_else(|| CanaryReceiptError::Invalid("receipt path is invalid".into()))?;
4005        let lock = std::fs::OpenOptions::new()
4006            .read(true)
4007            .write(true)
4008            .create(true)
4009            .truncate(false)
4010            .open(parent.join(format!(".{name}.lock")))?;
4011        lock.lock()?;
4012        let mut rendered = serde_json::to_vec_pretty(self)?;
4013        rendered.push(b'\n');
4014        if !path.exists() {
4015            let mut file = std::fs::OpenOptions::new()
4016                .write(true)
4017                .create_new(true)
4018                .open(path)?;
4019            file.write_all(&rendered)?;
4020            file.sync_all()?;
4021            return Ok(());
4022        }
4023        let existing = Self::read_json(path)?;
4024        if existing == *self {
4025            return Ok(());
4026        }
4027        if existing.attempt_id != self.attempt_id || !existing.same_binding(self) {
4028            return Err(CanaryReceiptError::Conflict(self.attempt_id.clone()));
4029        }
4030        if existing.outcome != CanaryExecutionOutcome::Started
4031            || self.outcome == CanaryExecutionOutcome::Started
4032        {
4033            return Err(CanaryReceiptError::Terminal {
4034                attempt_id: existing.attempt_id,
4035                outcome: existing.outcome,
4036            });
4037        }
4038        let temporary = parent.join(format!(".{name}.{}.tmp", self.receipt_digest));
4039        let mut file = std::fs::OpenOptions::new()
4040            .write(true)
4041            .create_new(true)
4042            .open(&temporary)?;
4043        file.write_all(&rendered)?;
4044        file.sync_all()?;
4045        std::fs::rename(temporary, path)?;
4046        Ok(())
4047    }
4048
4049    pub fn read_json(path: impl AsRef<Path>) -> Result<Self, CanaryReceiptError> {
4050        let value: serde_json::Value = serde_json::from_slice(&std::fs::read(path)?)?;
4051        let receipt: Self = serde_json::from_value(value.clone())?;
4052        if serde_json::to_value(&receipt)? != value {
4053            return Err(CanaryReceiptError::Invalid(
4054                "canary receipt contains unknown or non-canonical fields".into(),
4055            ));
4056        }
4057        receipt.verify_structure()?;
4058        Ok(receipt)
4059    }
4060
4061    fn require_started(&self) -> Result<(), CanaryReceiptError> {
4062        if self.outcome == CanaryExecutionOutcome::Started {
4063            Ok(())
4064        } else {
4065            Err(CanaryReceiptError::Terminal {
4066                attempt_id: self.attempt_id.clone(),
4067                outcome: self.outcome,
4068            })
4069        }
4070    }
4071
4072    fn same_binding(&self, other: &Self) -> bool {
4073        self.schema_version == other.schema_version
4074            && self.attempt_id == other.attempt_id
4075            && self.plan == other.plan
4076            && self.change_set == other.change_set
4077    }
4078
4079    fn verify_structure(&self) -> Result<(), CanaryReceiptError> {
4080        if self.schema_version != 1 || !identifier_is_valid(&self.attempt_id) {
4081            return Err(CanaryReceiptError::Invalid(
4082                "canary receipt binding is invalid".into(),
4083            ));
4084        }
4085        validate_canary_shift_plan(&self.plan)?;
4086        verify_promotion_boundary(&self.change_set, &self.plan.stack_name, "LiveFunctionAlias")?;
4087        if let Some(change_set) = &self.cleanup_change_set {
4088            verify_promotion_boundary(change_set, &self.plan.stack_name, "LiveFunctionAlias")?;
4089        }
4090        match self.outcome {
4091            CanaryExecutionOutcome::Started
4092                if self.failure_code.is_none() && self.cleanup_change_set.is_none() => {}
4093            CanaryExecutionOutcome::Succeeded
4094                if self.failure_code.is_none() && self.cleanup_change_set.is_some() => {}
4095            CanaryExecutionOutcome::Reversed
4096                if self
4097                    .failure_code
4098                    .as_deref()
4099                    .is_some_and(identifier_is_valid) => {}
4100            _ => {
4101                return Err(CanaryReceiptError::Invalid(
4102                    "canary outcome and failure are inconsistent".into(),
4103                ));
4104            }
4105        }
4106        if self.receipt_digest != self.calculate_digest()? {
4107            return Err(CanaryReceiptError::DigestMismatch);
4108        }
4109        Ok(())
4110    }
4111
4112    fn refresh_digest(&mut self) -> Result<(), CanaryReceiptError> {
4113        self.receipt_digest = self.calculate_digest()?;
4114        Ok(())
4115    }
4116
4117    fn calculate_digest(&self) -> Result<String, CanaryReceiptError> {
4118        #[derive(Serialize)]
4119        struct DigestPayload<'a> {
4120            schema_version: u32,
4121            attempt_id: &'a str,
4122            plan: &'a CanaryShiftPlan,
4123            change_set: &'a CloudFormationChangeSet,
4124            cleanup_change_set: &'a Option<CloudFormationChangeSet>,
4125            outcome: CanaryExecutionOutcome,
4126            failure_code: &'a Option<String>,
4127        }
4128        let payload = DigestPayload {
4129            schema_version: self.schema_version,
4130            attempt_id: &self.attempt_id,
4131            plan: &self.plan,
4132            change_set: &self.change_set,
4133            cleanup_change_set: &self.cleanup_change_set,
4134            outcome: self.outcome,
4135            failure_code: &self.failure_code,
4136        };
4137        Ok(hex::encode(Sha256::digest(serde_json::to_vec(&payload)?)))
4138    }
4139}
4140
4141#[derive(Debug, Error)]
4142pub enum CanaryReceiptError {
4143    #[error("invalid canary receipt: {0}")]
4144    Invalid(String),
4145    #[error("canary receipt digest does not match its contents")]
4146    DigestMismatch,
4147    #[error("canary receipt {0} conflicts with an existing attempt")]
4148    Conflict(String),
4149    #[error("canary receipt {attempt_id} is already terminal as {outcome:?}")]
4150    Terminal {
4151        attempt_id: String,
4152        outcome: CanaryExecutionOutcome,
4153    },
4154    #[error(transparent)]
4155    Boundary(#[from] PromotionBoundaryError),
4156    #[error(transparent)]
4157    Plan(#[from] CanaryPlanError),
4158    #[error("canary receipt JSON is invalid: {0}")]
4159    Json(#[from] serde_json::Error),
4160    #[error("canary receipt I/O failed: {0}")]
4161    Io(#[from] std::io::Error),
4162}
4163
4164#[derive(Debug, Clone, PartialEq, Eq, Error)]
4165pub enum CanaryPlanError {
4166    #[error("canary shift input has invalid {0}")]
4167    Invalid(&'static str),
4168}
4169
4170pub fn plan_canary_shift(input: CanaryShiftInput) -> Result<CanaryShiftPlan, CanaryPlanError> {
4171    if !account_id_is_valid(&input.expected_account_id)
4172        || !region_is_valid(&input.expected_region)
4173        || !stack_name_is_valid(&input.stack_name)
4174        || input.function_name.is_empty()
4175        || input.function_name.len() > 64
4176        || !input
4177            .function_name
4178            .bytes()
4179            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
4180        || input.alias_name.is_empty()
4181        || input.alias_name.len() > 128
4182        || !input
4183            .alias_name
4184            .bytes()
4185            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
4186    {
4187        return Err(CanaryPlanError::Invalid("routing identity"));
4188    }
4189    if !published_version_is_valid(&input.current_version)
4190        || !published_version_is_valid(&input.candidate_version)
4191        || input.current_version == input.candidate_version
4192    {
4193        return Err(CanaryPlanError::Invalid("function versions"));
4194    }
4195    if !sha256_is_valid(&input.pre_traffic_verification_digest) {
4196        return Err(CanaryPlanError::Invalid("pre-traffic verification digest"));
4197    }
4198    let policy = &input.policy;
4199    if !(1..=50).contains(&policy.initial_traffic_percent)
4200        || !(1..=180).contains(&policy.monitoring_minutes)
4201        || !(1..=5).contains(&policy.alarm_arns.len())
4202        || !policy
4203            .alarm_arns
4204            .windows(2)
4205            .all(|alarms| alarms[0] < alarms[1])
4206        || !policy.alarm_arns.iter().all(|arn| {
4207            cloudwatch_alarm_arn_is_valid(arn, &input.expected_account_id, &input.expected_region)
4208        })
4209        || policy.api_routing != "weighted_live_alias"
4210        || policy.worker_routing != "preserve_current_event_sources"
4211        || policy.provisioned_concurrency
4212    {
4213        return Err(CanaryPlanError::Invalid("policy"));
4214    }
4215    let plan = CanaryShiftPlan {
4216        schema_version: 1,
4217        expected_account_id: input.expected_account_id,
4218        expected_region: input.expected_region,
4219        stack_name: input.stack_name,
4220        function_name: input.function_name,
4221        alias_name: input.alias_name,
4222        current_version: input.current_version,
4223        candidate_version: input.candidate_version,
4224        candidate_weight_basis_points: u16::from(policy.initial_traffic_percent) * 100,
4225        monitoring_minutes: policy.monitoring_minutes,
4226        alarm_arns: policy.alarm_arns.clone(),
4227        pre_traffic_verification_digest: input.pre_traffic_verification_digest,
4228        api_routing: policy.api_routing.clone(),
4229        worker_routing: policy.worker_routing.clone(),
4230        additional_resources: Vec::new(),
4231        idle_compute_cost: "none".into(),
4232        pricing_complete: false,
4233        cost_notes: vec![
4234            "The shift creates no Minco-managed resource and no fixed or provisioned compute."
4235                .into(),
4236            "Existing externally managed CloudWatch alarms can incur account-specific charges."
4237                .into(),
4238        ],
4239    };
4240    validate_canary_shift_plan(&plan)?;
4241    Ok(plan)
4242}
4243
4244fn validate_canary_shift_plan(plan: &CanaryShiftPlan) -> Result<(), CanaryPlanError> {
4245    if plan.schema_version != 1
4246        || !account_id_is_valid(&plan.expected_account_id)
4247        || !region_is_valid(&plan.expected_region)
4248        || !stack_name_is_valid(&plan.stack_name)
4249        || plan.function_name.is_empty()
4250        || plan.function_name.len() > 64
4251        || !plan
4252            .function_name
4253            .bytes()
4254            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
4255        || plan.alias_name != "live"
4256        || !published_version_is_valid(&plan.current_version)
4257        || !published_version_is_valid(&plan.candidate_version)
4258        || plan.current_version == plan.candidate_version
4259        || !(100..=5_000).contains(&plan.candidate_weight_basis_points)
4260        || !plan.candidate_weight_basis_points.is_multiple_of(100)
4261        || !(1..=180).contains(&plan.monitoring_minutes)
4262        || !(1..=5).contains(&plan.alarm_arns.len())
4263        || !plan
4264            .alarm_arns
4265            .windows(2)
4266            .all(|alarms| alarms[0] < alarms[1])
4267        || !plan.alarm_arns.iter().all(|arn| {
4268            cloudwatch_alarm_arn_is_valid(arn, &plan.expected_account_id, &plan.expected_region)
4269        })
4270        || !sha256_is_valid(&plan.pre_traffic_verification_digest)
4271        || plan.api_routing != "weighted_live_alias"
4272        || plan.worker_routing != "preserve_current_event_sources"
4273        || !plan.additional_resources.is_empty()
4274        || plan.idle_compute_cost != "none"
4275        || plan.pricing_complete
4276        || plan.cost_notes
4277            != [
4278                "The shift creates no Minco-managed resource and no fixed or provisioned compute.",
4279                "Existing externally managed CloudWatch alarms can incur account-specific charges.",
4280            ]
4281    {
4282        return Err(CanaryPlanError::Invalid("sealed plan"));
4283    }
4284    Ok(())
4285}
4286
4287pub fn evaluate_canary_observation(
4288    plan: &CanaryShiftPlan,
4289    observation: CanaryObservation,
4290) -> CanaryOutcome {
4291    if observation.alarm_states.len() != plan.alarm_arns.len()
4292        || plan
4293            .alarm_arns
4294            .iter()
4295            .any(|alarm| !observation.alarm_states.contains_key(alarm))
4296    {
4297        return CanaryOutcome::Reverse {
4298            code: "alarm_observation_missing".into(),
4299        };
4300    }
4301    if observation
4302        .alarm_states
4303        .values()
4304        .any(|state| *state == CanaryAlarmState::Alarm)
4305    {
4306        return CanaryOutcome::Reverse {
4307            code: "alarm_entered_alarm_state".into(),
4308        };
4309    }
4310    if observation
4311        .alarm_states
4312        .values()
4313        .any(|state| *state == CanaryAlarmState::InsufficientData)
4314    {
4315        return CanaryOutcome::Reverse {
4316            code: "alarm_data_insufficient".into(),
4317        };
4318    }
4319    if observation.elapsed_minutes < plan.monitoring_minutes {
4320        return CanaryOutcome::Continue;
4321    }
4322    match observation.post_traffic_verification_digest {
4323        Some(digest) if sha256_is_valid(&digest) => CanaryOutcome::Complete,
4324        Some(_) => CanaryOutcome::Reverse {
4325            code: "post_traffic_verification_invalid".into(),
4326        },
4327        None => CanaryOutcome::Reverse {
4328            code: "post_traffic_verification_missing".into(),
4329        },
4330    }
4331}
4332
4333fn weighted_live_alias() -> String {
4334    "weighted_live_alias".into()
4335}
4336
4337fn preserve_current_event_sources() -> String {
4338    "preserve_current_event_sources".into()
4339}
4340
4341#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
4342#[serde(deny_unknown_fields)]
4343pub struct DeploymentTarget {
4344    pub enabled: bool,
4345    #[serde(default)]
4346    pub lifecycle: DeploymentTargetLifecycle,
4347    #[serde(default)]
4348    pub preview: Option<PreviewTargetPolicy>,
4349    #[serde(default)]
4350    pub canary: Option<CanaryTargetPolicy>,
4351    pub expected_account_id: String,
4352    pub expected_region: String,
4353    pub expected_role_arn: String,
4354    pub stack_name: String,
4355    pub artifact_bucket: String,
4356    pub database_url_parameter_name: String,
4357    pub database_kms_key_arn: Option<String>,
4358    #[serde(default)]
4359    pub static_site_certificate_arn: Option<String>,
4360    #[serde(default)]
4361    pub static_site_hosted_zone_id: Option<String>,
4362    #[serde(default)]
4363    pub static_site_pricing_checked_on: Option<String>,
4364    #[serde(default)]
4365    pub static_site_pricing_source: Option<String>,
4366    #[serde(default)]
4367    pub static_site_billing_model: Option<CloudFrontBillingModel>,
4368    #[serde(default)]
4369    pub static_site_flat_rate_eligibility: Option<FlatRateEligibility>,
4370    #[serde(default)]
4371    pub lambda_subnet_ids: Vec<String>,
4372    #[serde(default)]
4373    pub lambda_security_group_ids: Vec<String>,
4374    #[serde(default)]
4375    pub stack_tags: BTreeMap<String, String>,
4376}
4377
4378#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
4379pub struct SelectedDeploymentTarget {
4380    pub environment: String,
4381    pub target: DeploymentTarget,
4382}
4383
4384#[derive(Debug, Error)]
4385pub enum DeploymentTargetError {
4386    #[error("deployment target configuration is invalid: {0}")]
4387    Toml(#[from] toml::de::Error),
4388    #[error("unsupported deployment target schema {0}")]
4389    UnsupportedSchema(u32),
4390    #[error("deployment target catalog has no environment {0}")]
4391    UnknownEnvironment(String),
4392    #[error("deployment target {environment} has invalid {field}")]
4393    InvalidField {
4394        environment: String,
4395        field: &'static str,
4396    },
4397    #[error("enabled deployment target {0} still uses a disabled placeholder account")]
4398    EnabledPlaceholder(String),
4399}
4400
4401impl DeploymentTargetCatalog {
4402    pub fn from_toml(source: &str) -> Result<Self, DeploymentTargetError> {
4403        let catalog: Self = toml::from_str(source)?;
4404        if catalog.schema_version != 1 {
4405            return Err(DeploymentTargetError::UnsupportedSchema(
4406                catalog.schema_version,
4407            ));
4408        }
4409        if !environment_is_valid(&catalog.default_environment) {
4410            return Err(DeploymentTargetError::InvalidField {
4411                environment: catalog.default_environment,
4412                field: "default_environment",
4413            });
4414        }
4415        for (environment, target) in &catalog.environments {
4416            validate_deployment_target(environment, target)?;
4417        }
4418        if !catalog
4419            .environments
4420            .contains_key(&catalog.default_environment)
4421        {
4422            return Err(DeploymentTargetError::UnknownEnvironment(
4423                catalog.default_environment,
4424            ));
4425        }
4426        Ok(catalog)
4427    }
4428
4429    pub fn select(
4430        &self,
4431        environment: Option<&str>,
4432    ) -> Result<SelectedDeploymentTarget, DeploymentTargetError> {
4433        let environment = environment.unwrap_or(&self.default_environment);
4434        let target = self
4435            .environments
4436            .get(environment)
4437            .ok_or_else(|| DeploymentTargetError::UnknownEnvironment(environment.to_owned()))?;
4438        Ok(SelectedDeploymentTarget {
4439            environment: environment.to_owned(),
4440            target: target.clone(),
4441        })
4442    }
4443}
4444
4445fn validate_deployment_target(
4446    environment: &str,
4447    target: &DeploymentTarget,
4448) -> Result<(), DeploymentTargetError> {
4449    let lifecycle_valid = match (&target.lifecycle, &target.preview, &target.canary) {
4450        (DeploymentTargetLifecycle::Persistent, None, canary) => canary
4451            .as_ref()
4452            .is_none_or(|policy| canary_target_policy_is_valid(target, policy)),
4453        (DeploymentTargetLifecycle::Preview, Some(preview), None) => {
4454            (environment == "preview" || environment.starts_with("preview-"))
4455                && preview_target_policy_is_valid(preview)
4456        }
4457        _ => false,
4458    };
4459    let valid = [
4460        ("environment", environment_is_valid(environment)),
4461        ("lifecycle", lifecycle_valid),
4462        (
4463            "expected_account_id",
4464            account_id_is_valid(&target.expected_account_id),
4465        ),
4466        ("expected_region", region_is_valid(&target.expected_region)),
4467        (
4468            "expected_role_arn",
4469            role_arn_is_valid(&target.expected_role_arn, &target.expected_account_id),
4470        ),
4471        ("stack_name", stack_name_is_valid(&target.stack_name)),
4472        (
4473            "artifact_bucket",
4474            bucket_name_is_valid(&target.artifact_bucket),
4475        ),
4476        (
4477            "database_url_parameter_name",
4478            parameter_name_is_valid(&target.database_url_parameter_name),
4479        ),
4480        (
4481            "database_kms_key_arn",
4482            target.database_kms_key_arn.as_deref().is_none_or(|arn| {
4483                kms_key_arn_is_valid(
4484                    arn,
4485                    &target.expected_account_id,
4486                    &target.expected_region,
4487                    &target.expected_role_arn,
4488                )
4489            }),
4490        ),
4491        (
4492            "static_site_certificate_arn",
4493            target
4494                .static_site_certificate_arn
4495                .as_deref()
4496                .is_none_or(|arn| {
4497                    cloudfront_certificate_arn_is_valid(arn, &target.expected_account_id)
4498                }),
4499        ),
4500        (
4501            "static_site_hosted_zone_id",
4502            target
4503                .static_site_hosted_zone_id
4504                .as_deref()
4505                .is_none_or(hosted_zone_id_is_valid),
4506        ),
4507        (
4508            "static_site_pricing",
4509            static_site_target_pricing_is_valid(target),
4510        ),
4511        (
4512            "lambda_network",
4513            target.lambda_subnet_ids.is_empty() == target.lambda_security_group_ids.is_empty()
4514                && resource_ids_are_valid(&target.lambda_subnet_ids, "subnet-")
4515                && resource_ids_are_valid(&target.lambda_security_group_ids, "sg-"),
4516        ),
4517        (
4518            "stack_tags",
4519            deployment_stack_tags_are_valid(&target.stack_tags),
4520        ),
4521    ];
4522    if let Some((field, _)) = valid.into_iter().find(|(_, valid)| !valid) {
4523        return Err(DeploymentTargetError::InvalidField {
4524            environment: environment.to_owned(),
4525            field,
4526        });
4527    }
4528    if target.enabled && target.expected_account_id == "000000000000" {
4529        return Err(DeploymentTargetError::EnabledPlaceholder(
4530            environment.to_owned(),
4531        ));
4532    }
4533    Ok(())
4534}
4535
4536fn canary_target_policy_is_valid(target: &DeploymentTarget, policy: &CanaryTargetPolicy) -> bool {
4537    (1..=50).contains(&policy.initial_traffic_percent)
4538        && (1..=180).contains(&policy.monitoring_minutes)
4539        && (1..=5).contains(&policy.alarm_arns.len())
4540        && policy
4541            .alarm_arns
4542            .windows(2)
4543            .all(|alarms| alarms[0] < alarms[1])
4544        && policy.alarm_arns.iter().all(|arn| {
4545            cloudwatch_alarm_arn_is_valid(arn, &target.expected_account_id, &target.expected_region)
4546        })
4547        && policy.api_routing == "weighted_live_alias"
4548        && policy.worker_routing == "preserve_current_event_sources"
4549        && !policy.provisioned_concurrency
4550}
4551
4552fn cloudwatch_alarm_arn_is_valid(arn: &str, account: &str, region: &str) -> bool {
4553    let mut parts = arn.splitn(7, ':');
4554    matches!(parts.next(), Some("arn"))
4555        && parts
4556            .next()
4557            .is_some_and(|partition| matches!(partition, "aws" | "aws-cn" | "aws-us-gov"))
4558        && matches!(parts.next(), Some("cloudwatch"))
4559        && parts.next() == Some(region)
4560        && parts.next() == Some(account)
4561        && matches!(parts.next(), Some("alarm"))
4562        && parts.next().is_some_and(|name| {
4563            !name.is_empty()
4564                && name.len() <= 255
4565                && name
4566                    .bytes()
4567                    .all(|byte| byte.is_ascii_graphic() && byte != b'/' && byte != b'\\')
4568        })
4569}
4570
4571fn preview_target_policy_is_valid(preview: &PreviewTargetPolicy) -> bool {
4572    let retained = preview
4573        .resources
4574        .iter()
4575        .filter(|resource| resource.retention == ReviewResourceRetention::Retain)
4576        .map(|resource| resource.logical_id.clone())
4577        .collect::<Vec<_>>();
4578    let resources_valid = !preview.resources.is_empty()
4579        && preview
4580            .resources
4581            .windows(2)
4582            .all(|resources| resources[0].logical_id < resources[1].logical_id)
4583        && preview.resources.iter().all(|resource| {
4584            cloudformation_logical_id_is_valid(&resource.logical_id)
4585                && !resource.resource_type.trim().is_empty()
4586                && !resource.resource_type.chars().any(char::is_control)
4587        });
4588    let cleanup_valid = preview.cleanup_schedule.as_ref().is_none_or(|cleanup| {
4589        one_time_schedule_expression_is_valid(&cleanup.expression)
4590            && cleanup.residual_resources == retained
4591            && !cleanup.manual_fallback.trim().is_empty()
4592            && !cleanup.manual_fallback.chars().any(char::is_control)
4593    });
4594    !preview.owner.trim().is_empty()
4595        && preview.owner.len() <= 256
4596        && !preview.owner.chars().any(char::is_control)
4597        && (300..=2_592_000).contains(&preview.ttl_seconds)
4598        && resources_valid
4599        && cleanup_valid
4600}
4601
4602fn deployment_stack_tags_are_valid(tags: &BTreeMap<String, String>) -> bool {
4603    tags.len() <= 47
4604        && tags.iter().all(|(key, value)| {
4605            !key.is_empty()
4606                && key.len() <= 128
4607                && value.len() <= 256
4608                && key.chars().all(|character| !character.is_control())
4609                && value.chars().all(|character| !character.is_control())
4610                && !key.to_ascii_lowercase().starts_with("aws:")
4611                && !matches!(
4612                    key.as_str(),
4613                    "MincoEnvironment" | "MincoReleaseId" | "MincoReleaseDigest"
4614                )
4615        })
4616}
4617
4618fn stack_name_is_valid(value: &str) -> bool {
4619    let mut bytes = value.bytes();
4620    value.len() <= 128
4621        && bytes.next().is_some_and(|byte| byte.is_ascii_alphabetic())
4622        && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
4623}
4624
4625fn hosted_zone_id_is_valid(value: &str) -> bool {
4626    value.len() >= 8
4627        && value.starts_with('Z')
4628        && value
4629            .bytes()
4630            .all(|byte| byte.is_ascii_uppercase() || byte.is_ascii_digit())
4631}
4632
4633fn static_site_target_pricing_is_valid(target: &DeploymentTarget) -> bool {
4634    let values_present = [
4635        target.static_site_pricing_checked_on.is_some(),
4636        target.static_site_pricing_source.is_some(),
4637        target.static_site_billing_model.is_some(),
4638        target.static_site_flat_rate_eligibility.is_some(),
4639    ];
4640    if values_present.iter().all(|present| !present) {
4641        return true;
4642    }
4643    if !values_present.iter().all(|present| *present) {
4644        return false;
4645    }
4646    let source = target
4647        .static_site_pricing_source
4648        .as_deref()
4649        .and_then(|source| url::Url::parse(source).ok());
4650    let source_is_official = source.is_some_and(|source| {
4651        source.scheme() == "https"
4652            && matches!(
4653                source.host_str(),
4654                Some("aws.amazon.com" | "docs.aws.amazon.com")
4655            )
4656            && source.username().is_empty()
4657            && source.password().is_none()
4658    });
4659    let selection_is_consistent = match (
4660        target.static_site_billing_model,
4661        target.static_site_flat_rate_eligibility,
4662    ) {
4663        (Some(CloudFrontBillingModel::FlatRate), Some(FlatRateEligibility::EligibleSelected)) => {
4664            true
4665        }
4666        (Some(CloudFrontBillingModel::RequestAndTransfer), Some(eligibility)) => {
4667            eligibility != FlatRateEligibility::EligibleSelected
4668        }
4669        _ => false,
4670    };
4671    target
4672        .static_site_pricing_checked_on
4673        .as_deref()
4674        .is_some_and(iso_date_is_valid)
4675        && source_is_official
4676        && selection_is_consistent
4677}
4678
4679fn bucket_name_is_valid(value: &str) -> bool {
4680    (3..=63).contains(&value.len())
4681        && value.bytes().all(|byte| {
4682            byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'.' | b'-')
4683        })
4684        && value
4685            .bytes()
4686            .next()
4687            .is_some_and(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
4688        && value
4689            .bytes()
4690            .last()
4691            .is_some_and(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
4692        && !value.contains("..")
4693        && value.parse::<std::net::Ipv4Addr>().is_err()
4694}
4695
4696fn parameter_name_is_valid(value: &str) -> bool {
4697    (2..=1011).contains(&value.len())
4698        && value.starts_with('/')
4699        && !value.ends_with('/')
4700        && !value.contains("//")
4701        && value
4702            .bytes()
4703            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'/' | b'.' | b'-' | b'_'))
4704}
4705
4706fn kms_key_arn_is_valid(value: &str, account_id: &str, region: &str, role_arn: &str) -> bool {
4707    let parts = value.splitn(6, ':').collect::<Vec<_>>();
4708    let partition = role_arn.split(':').nth(1);
4709    parts.len() == 6
4710        && parts[0] == "arn"
4711        && Some(parts[1]) == partition
4712        && parts[2] == "kms"
4713        && parts[3] == region
4714        && parts[4] == account_id
4715        && parts[5].strip_prefix("key/").is_some_and(|key_id| {
4716            !key_id.is_empty()
4717                && key_id
4718                    .bytes()
4719                    .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
4720        })
4721}
4722
4723fn resource_ids_are_valid(values: &[String], prefix: &str) -> bool {
4724    let unique = values.iter().collect::<BTreeSet<_>>();
4725    unique.len() == values.len()
4726        && values.iter().all(|value| {
4727            value.strip_prefix(prefix).is_some_and(|id| {
4728                !id.is_empty()
4729                    && id
4730                        .bytes()
4731                        .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
4732            })
4733        })
4734}