Skip to main content

alien_core/deployment/
state.rs

1//! Deployment state, step results, and runtime metadata.
2
3use crate::{ObservedInventoryBatch, Platform, ResourceHeartbeat, StackState};
4use alien_error::AlienError;
5use bon::Builder;
6use indexmap::IndexMap;
7use serde::{Deserialize, Serialize};
8use std::collections::BTreeMap;
9
10use super::{DeploymentStatus, EnvironmentInfo, ReleaseInfo};
11
12/// Actor that owns structural work during the initial setup phase.
13#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
14#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
15#[serde(rename_all = "camelCase")]
16pub enum InitialSetupAuthority {
17    /// Setup state was registered by an external setup engine. Alien may only
18    /// continue controller states that the importer explicitly initialized.
19    #[default]
20    ImportedHandoff,
21    /// Alien is the setup engine and is running with administrator credentials.
22    DirectSetup,
23}
24
25/// One-shot authority for a setup re-import to replace setup-owned resources.
26#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
27#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
28#[serde(rename_all = "camelCase")]
29pub struct SetupUpdateAuthorization {
30    /// Unique revision used by persistence layers for compare-and-swap updates.
31    pub nonce: String,
32    /// Setup resources and permissions digest (`Stack::setup_update_digest`) of the last
33    /// successful deployment. The field name is retained for serialized compatibility.
34    pub baseline_frozen_digest: String,
35    /// Setup resources and permissions digest (`Stack::setup_update_digest`) of the stack
36    /// the setup re-import prepared.
37    pub target_frozen_digest: String,
38    /// Release whose stack was prepared by setup.
39    pub release_id: String,
40    /// Stable setup target recorded on the imported deployment.
41    pub setup_target: String,
42    /// Exact setup artifact revision that authored this authority.
43    pub setup_fingerprint: String,
44    /// Setup fingerprint contract version.
45    pub setup_fingerprint_version: u32,
46}
47
48/// A setup report the manager declined, for display next to the waiting update.
49#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
50#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
51#[serde(rename_all = "camelCase")]
52pub struct SetupReportRefusal {
53    /// Plain-language reason, safe to show to the customer.
54    pub reason: String,
55    /// Release the chart reported.
56    pub reported_release_id: String,
57    /// When the manager declined it.
58    pub at: chrono::DateTime<chrono::Utc>,
59}
60
61/// A waiting release whose setup change a Helm chart upgrade cannot carry. The
62/// manager works this out from the release and the installed setup, so every
63/// place that offers an upgrade agrees with the manager's report handling.
64#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
65#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
66#[serde(rename_all = "camelCase")]
67pub struct CloudSetupRequired {
68    /// The waiting release this applies to.
69    pub release_id: String,
70    /// Plain-language reason, safe to show to the customer.
71    pub reason: String,
72}
73
74/// The Helm release an Operator reports it was installed as, so the exact
75/// upgrade command can be shown. Reported, never trusted for authority.
76#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
77#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
78#[serde(rename_all = "camelCase")]
79pub struct InstalledHelmRelease {
80    /// Release name, as passed to `helm install`.
81    pub name: String,
82    /// Kubernetes namespace the release is installed in.
83    pub namespace: String,
84}
85
86/// A credential outage's durable retry window, scoped to its deployment phase.
87#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
88#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
89#[serde(rename_all = "camelCase")]
90pub struct CredentialRetry {
91    /// First credential failure in this phase; subsequent attempts keep this timestamp.
92    pub started_at: chrono::DateTime<chrono::Utc>,
93    /// Changing phase starts a new window instead of carrying a previous outage forward.
94    pub status: DeploymentStatus,
95}
96
97/// Explicit disposition of durable data when deleting a deployment.
98/// Missing values from older checkpoints always preserve data.
99#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
100#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
101#[serde(rename_all = "camelCase")]
102pub enum DeletionPolicy {
103    #[default]
104    Retain,
105    Erase,
106}
107
108/// When an air-gapped site's latest status was written and received.
109#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
110#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
111#[serde(rename_all = "camelCase")]
112pub struct AirgappedReportMetadata {
113    /// Site clock time; absent for reports from older clients.
114    #[serde(default, skip_serializing_if = "Option::is_none")]
115    pub written_at: Option<chrono::DateTime<chrono::Utc>>,
116    /// Manager clock time when the report was accepted.
117    pub received_at: chrono::DateTime<chrono::Utc>,
118}
119
120/// Runtime metadata for deployment
121///
122/// Stores deployment state that needs to persist across step calls.
123#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
124#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
125#[serde(rename_all = "camelCase")]
126pub struct RuntimeMetadata {
127    /// User-authorized data disposition, persisted before deletion starts.
128    #[serde(default)]
129    pub deletion_policy: DeletionPolicy,
130
131    /// Most recent air-gapped report accepted by the manager.
132    #[serde(default, skip_serializing_if = "Option::is_none")]
133    pub airgapped_report: Option<AirgappedReportMetadata>,
134
135    /// Version of the Operator binary that last reported this deployment, set
136    /// by the manager from the sync request. Missing until an Operator that
137    /// reports its version has synced.
138    #[serde(default, skip_serializing_if = "Option::is_none")]
139    pub operator_version: Option<String>,
140
141    /// Bounded credential retry state shared by all deployment drivers.
142    #[serde(default, skip_serializing_if = "Option::is_none")]
143    pub credential_retry: Option<CredentialRetry>,
144
145    /// Actor authorized to perform structural Frozen-resource work during
146    /// InitialSetup. Missing legacy values fail closed as ImportedHandoff.
147    #[serde(default)]
148    pub initial_setup_authority: InitialSetupAuthority,
149
150    /// Setup-owned grant to keep using the direct setup executor for updates.
151    /// Runtime settings and release contents must never create or change this grant.
152    #[serde(default, skip_serializing_if = "super::is_false")]
153    pub automatic_setup: bool,
154
155    /// An imported install whose machines have not been selected yet. Set when the setup
156    /// import registers the deployment; the first InitialSetup step picks machines from free
157    /// quota and clears it with the same result, so the pick happens once and a later step
158    /// never re-picks against quota that its own machines reduced. Deployments stored
159    /// without it deserialize as done.
160    #[serde(default, skip_serializing_if = "super::is_false")]
161    pub first_setup_machines_unselected: bool,
162
163    /// Hash of the environment variables snapshot that was last synced to the vault
164    /// Used to avoid redundant sync operations during incremental deployment
165    #[serde(skip_serializing_if = "Option::is_none")]
166    pub last_synced_env_vars_hash: Option<String>,
167
168    /// Exact vault keys owned by the deployment secret synchronizer. This
169    /// inventory lets a later snapshot delete removed keys without listing or
170    /// touching unrelated values in the same vault.
171    #[serde(default, skip_serializing_if = "Vec::is_empty")]
172    pub last_synced_secret_names: Vec<String>,
173
174    /// Credential revocation completed before resource teardown. A delete retry
175    /// can use this receipt after the vault or its binding is gone. Secret sync
176    /// clears it before a deployment can write runtime credentials again.
177    #[serde(default, skip_serializing_if = "is_false")]
178    pub vault_credentials_revoked: bool,
179
180    /// Digest of the installed data inventory whose runtime public-access and
181    /// expiry configuration was protected before cleanup. The serialized field
182    /// name is retained for compatibility. This is not a
183    /// receipt for effective expiry propagation or privileged setup teardown.
184    #[serde(default, skip_serializing_if = "Option::is_none")]
185    pub retained_storage_protection_hash: Option<String>,
186
187    /// UTC API-confirmation time for the matching data protection digest.
188    /// Provider propagation must be qualified separately before final retention.
189    #[serde(default, skip_serializing_if = "Option::is_none")]
190    pub retained_storage_protection_confirmed_at: Option<chrono::DateTime<chrono::Utc>>,
191
192    /// Start of the bounded wait for retained data's expiry controls to disable.
193    /// Cleared on confirmation, explicit retry, or returning to normal execution.
194    #[serde(default, skip_serializing_if = "Option::is_none")]
195    pub retained_data_protection_started_at: Option<chrono::DateTime<chrono::Utc>>,
196
197    /// The prepared (mutated) stack from the last successful deployment phase
198    /// This is the stack AFTER mutations have been applied (with service accounts, vault, etc.)
199    /// Used for compatibility checks during updates to compare mutated stacks
200    #[serde(skip_serializing_if = "Option::is_none")]
201    pub prepared_stack: Option<crate::Stack>,
202
203    /// Canonical resolved answers for inputs that gate Frozen resources,
204    /// keyed by input id, recorded when the deployment is created or its
205    /// setup import registers.
206    ///
207    /// Manual installations keep these answers fixed. An installation with an
208    /// ongoing-management grant refreshes them when preparing a release. Live
209    /// resources sharing a gate use the same recorded answer as Frozen resources.
210    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
211    pub persisted_gate_answers: GateAnswers,
212
213    /// Prepared target for an update that has not reached Running yet. Keeping
214    /// it separate preserves the last successful baseline across retries.
215    #[serde(default, skip_serializing_if = "Option::is_none")]
216    pub pending_prepared_stack: Option<crate::Stack>,
217
218    /// Release the in-flight stack was prepared from: `pending_prepared_stack`
219    /// during updates, or `prepared_stack` during local first startup. The target can move
220    /// to a newer release while that stack is still being applied; this tells
221    /// the update which release actually converged.
222    #[serde(default, skip_serializing_if = "Option::is_none")]
223    pub pending_prepared_release_id: Option<String>,
224
225    /// One-shot setup update authority. It contains only non-secret identity
226    /// and canonical resource digests, never the imported payload or tokens.
227    #[serde(default, skip_serializing_if = "Option::is_none")]
228    pub setup_update_authorization: Option<SetupUpdateAuthorization>,
229
230    /// Why the manager last declined a setup report from the installed chart,
231    /// with when. Cleared when a report is accepted or no longer needed.
232    #[serde(default, skip_serializing_if = "Option::is_none")]
233    pub setup_report_refusal: Option<SetupReportRefusal>,
234
235    /// Set while the waiting release changes something only the cloud setup
236    /// can apply, so a chart upgrade is not offered for it.
237    #[serde(default, skip_serializing_if = "Option::is_none")]
238    pub cloud_setup_required: Option<CloudSetupRequired>,
239
240    /// The Helm release the Operator reported it runs as.
241    #[serde(default, skip_serializing_if = "Option::is_none")]
242    pub installed_helm_release: Option<InstalledHelmRelease>,
243
244    /// Last generated CLI package revision whose direct setup was applied.
245    /// This lets a newer generated CLI refresh setup-owned infrastructure once
246    /// before handing runtime changes back to the hosted manager.
247    #[serde(default, skip_serializing_if = "Option::is_none")]
248    pub direct_setup_revision: Option<String>,
249
250    /// Whether cross-account registry access has been successfully granted.
251    /// Set to true after the manager successfully sets the ECR/GAR repo policy
252    /// for this deployment's target account. Prevents redundant API calls on
253    /// every reconcile tick.
254    #[serde(default, skip_serializing_if = "is_false")]
255    pub registry_access_granted: bool,
256
257    /// What that grant opened, compared against what the deployment needs now so a grant made
258    /// before a resource existed is finished rather than skipped, and the revoke names what was
259    /// granted. Absent on a grant recorded before this field existed.
260    #[serde(default, skip_serializing_if = "Option::is_none")]
261    pub registry_access: Option<RegistryAccess>,
262
263    /// What a direct setup created for resources it does not own, keyed by resource id. Setup
264    /// teardown removes exactly what is recorded here.
265    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
266    pub setup_scaffolding: BTreeMap<String, SetupScaffolding>,
267
268    /// Whether each vault-native deployer secret is in the customer's secret
269    /// store, with where it goes. Checked from metadata only; no value is ever
270    /// read or recorded here.
271    #[serde(default, skip_serializing_if = "Vec::is_empty")]
272    pub deployer_secrets: Vec<crate::DeployerSecretReport>,
273
274    /// What a one-token call with the customer admin's setup credentials said about each
275    /// model an AI resource declares. Written once, during setup; the AI controller's heartbeat
276    /// reports it. Absent when no model is declared or the setup could not check.
277    #[serde(default, skip_serializing_if = "Vec::is_empty")]
278    pub ai_access_checks: Vec<AiAccessCheck>,
279    /// When `deployer_secrets` was last read from the customer's secret store. While the
280    /// deployment waits for secrets the check is repeated at most every 30 seconds, because
281    /// the engine steps much faster than the store's rate limits allow.
282    #[serde(default, skip_serializing_if = "Option::is_none")]
283    pub deployer_secrets_checked_at: Option<chrono::DateTime<chrono::Utc>>,
284
285    /// Resources held back while a required deployer secret is missing: the ones that read
286    /// it and everything that depends on them. Everything else keeps installing. Empty once
287    /// no required secret is missing. An Operator that predates this field leaves it absent,
288    /// so readers must treat absence as unknown.
289    #[serde(default, skip_serializing_if = "Vec::is_empty")]
290    pub resources_waiting_for_secrets: Vec<String>,
291}
292
293/// The setup-time answer for one declared model.
294#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
295#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
296#[serde(rename_all = "camelCase")]
297pub struct AiAccessCheck {
298    /// The AI resource that declares the model.
299    pub resource_id: String,
300    /// The model id as the app uses it.
301    pub model_id: String,
302    /// `verified`, `refused` (the cloud refused the model) or `not-checked`.
303    pub result: AiAccessCheckResult,
304    /// The cloud's error code or the reason the check could not run.
305    #[serde(default, skip_serializing_if = "Option::is_none")]
306    pub detail: Option<String>,
307    pub tested_at: chrono::DateTime<chrono::Utc>,
308}
309
310#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
311#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
312#[serde(rename_all = "kebab-case")]
313pub enum AiAccessCheckResult {
314    Verified,
315    Refused,
316    NotChecked,
317}
318
319/// Cloud objects a direct setup created so a runtime-owned resource can run.
320#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
321#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
322#[serde(rename_all = "camelCase", tag = "type")]
323pub enum SetupScaffolding {
324    /// An AWS sandbox's image-build role, and for `egress: deny` its egress objects.
325    #[serde(rename_all = "camelCase")]
326    AwsSandbox {
327        /// IAM role the image build runs as.
328        build_role_name: String,
329        /// What `egress: deny` needs; absent for an open sandbox.
330        #[serde(default, skip_serializing_if = "Option::is_none")]
331        egress: Option<AwsSandboxEgressScaffolding>,
332        /// A Frozen sandbox's MicroVM image, built during setup. A Live one's image belongs to its
333        /// runtime controller.
334        #[serde(default, skip_serializing_if = "Option::is_none")]
335        image_arn: Option<String>,
336    },
337}
338
339/// The objects that keep an AWS deny sandbox's sessions inside the VPC. Each id is recorded as
340/// soon as the object exists and cleared once it is deleted.
341#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
342#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
343#[serde(rename_all = "camelCase")]
344pub struct AwsSandboxEgressScaffolding {
345    /// IAM role Lambda assumes to place the connector's network interfaces.
346    pub operator_role_name: String,
347    /// Security group permitting egress to loopback only.
348    #[serde(default, skip_serializing_if = "Option::is_none")]
349    pub security_group_id: Option<String>,
350    /// `AWS::Lambda::NetworkConnector` the sessions start with.
351    #[serde(default, skip_serializing_if = "Option::is_none")]
352    pub connector_arn: Option<String>,
353    /// Cloud Control request creating or deleting the connector that AWS has not finished. Kept
354    /// so the request's outcome, and AWS's reason when it fails, is read on a later call.
355    #[serde(default, skip_serializing_if = "Option::is_none")]
356    pub connector_request: Option<String>,
357}
358
359impl SetupScaffolding {
360    /// Takes each object `found` names that this record does not, and keeps every one it does:
361    /// a recorded id is what setup last saw, and teardown must delete that one.
362    pub fn fill_missing(&mut self, found: SetupScaffolding) {
363        match (self, found) {
364            (
365                SetupScaffolding::AwsSandbox {
366                    egress, image_arn, ..
367                },
368                SetupScaffolding::AwsSandbox {
369                    egress: found_egress,
370                    image_arn: found_image_arn,
371                    ..
372                },
373            ) => {
374                if image_arn.is_none() {
375                    *image_arn = found_image_arn;
376                }
377                match (egress.as_mut(), found_egress) {
378                    (None, found_egress) => *egress = found_egress,
379                    (Some(recorded), Some(found)) => {
380                        if recorded.security_group_id.is_none() {
381                            recorded.security_group_id = found.security_group_id;
382                        }
383                        if recorded.connector_arn.is_none() {
384                            recorded.connector_arn = found.connector_arn;
385                        }
386                    }
387                    (Some(_), None) => {}
388                }
389            }
390        }
391    }
392}
393
394/// The cross-account read a manager opened on Alien's registry for one deployment.
395#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
396#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
397#[serde(rename_all = "camelCase")]
398pub struct RegistryAccess {
399    /// Repository identifiers the grant names, sorted.
400    #[serde(default, skip_serializing_if = "Vec::is_empty")]
401    pub repositories: Vec<String>,
402
403    /// Compute services the grant admits, sorted. Each pulls as its own principal, so a service
404    /// added later needs the policy rewritten.
405    #[serde(default, skip_serializing_if = "Vec::is_empty")]
406    pub service_types: Vec<String>,
407
408    /// A protected install's verifier, which deploys its functions from these images and so
409    /// reads them as well. `None` on an unprotected install.
410    #[serde(default, skip_serializing_if = "Option::is_none")]
411    pub verifier: Option<String>,
412}
413
414/// Deployment state
415///
416/// Represents the current state of deployed infrastructure, including release tracking.
417/// This is platform-agnostic - no backend IDs or database relationships.
418///
419/// The deployment engine manages releases internally: when a deployment succeeds,
420/// it promotes `target_release` to `current_release` and clears `target_release`.
421#[derive(Debug, Clone, Serialize, Deserialize, Builder)]
422#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
423#[serde(rename_all = "camelCase")]
424pub struct DeploymentState {
425    /// Current lifecycle phase
426    pub status: DeploymentStatus,
427    /// Target cloud platform (AWS, GCP, Azure, Kubernetes)
428    pub platform: Platform,
429    /// Currently deployed release (None for first deployment)
430    #[serde(skip_serializing_if = "Option::is_none")]
431    pub current_release: Option<ReleaseInfo>,
432    /// Target release to deploy (None when synced with current)
433    #[serde(skip_serializing_if = "Option::is_none")]
434    pub target_release: Option<ReleaseInfo>,
435    /// Infrastructure resource tracking (which resources exist, their status, outputs)
436    #[serde(skip_serializing_if = "Option::is_none")]
437    pub stack_state: Option<StackState>,
438    /// Deployment-level error for failures not owned by a specific resource.
439    ///
440    /// Resource controller failures belong in `stack_state.resources[*].error`.
441    #[serde(skip_serializing_if = "Option::is_none")]
442    pub error: Option<AlienError>,
443    /// Cloud account details (account ID, project number, region)
444    #[serde(skip_serializing_if = "Option::is_none")]
445    pub environment_info: Option<EnvironmentInfo>,
446    /// Deployment-specific data (prepared stacks, phase tracking, etc.)
447    #[serde(skip_serializing_if = "Option::is_none")]
448    pub runtime_metadata: Option<RuntimeMetadata>,
449    /// Whether a retry has been requested for a failed deployment
450    /// When true and status is a failed state, the deployment system will retry failed resources
451    #[serde(default, skip_serializing_if = "is_false")]
452    pub retry_requested: bool,
453    /// Protocol version for cross-actor compatibility.
454    /// All actors (manager, push client, agent) check this before stepping.
455    /// Mismatched versions produce a clear error instead of silent corruption.
456    /// See docs/02-manager/10-deployment-protocol.md.
457    pub protocol_version: u32,
458}
459
460impl DeploymentState {
461    /// Returns whether this state carries desired infrastructure for the
462    /// deployment runner to converge.
463    pub fn has_desired(&self) -> bool {
464        self.current_release.is_some()
465            || self.target_release.is_some()
466            || self.stack_state.is_some()
467    }
468}
469
470/// Result of a deployment step
471///
472/// Contains the complete next deployment state along with hints for the platform.
473/// This replaces the old delta-based `DeploymentStateUpdate` approach.
474#[derive(Debug, Clone, Serialize, Deserialize)]
475#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
476#[serde(rename_all = "camelCase")]
477pub struct DeploymentStepResult {
478    /// The complete next deployment state
479    pub state: DeploymentState,
480
481    /// Suggested delay before next step (optimization hint)
482    /// - `None`: No suggested delay, can poll immediately
483    /// - `Some(ms)`: Wait this many milliseconds before next step
484    #[serde(skip_serializing_if = "Option::is_none")]
485    pub suggested_delay_ms: Option<u64>,
486
487    /// Whether to update heartbeat timestamp (monitoring signal)
488    /// - `false`: Don't update heartbeat (default for most steps)
489    /// - `true`: Update lastHeartbeatAt (for successful health checks in Running state)
490    #[serde(default, skip_serializing_if = "is_false")]
491    pub update_heartbeat: bool,
492
493    /// Managed Alien resource status samples emitted by controllers during this step.
494    #[serde(
495        default,
496        rename = "resourceHeartbeats",
497        skip_serializing_if = "Vec::is_empty"
498    )]
499    pub heartbeats: Vec<ResourceHeartbeat>,
500
501    /// Observed raw-resource inventory batches read during this step.
502    #[serde(
503        default,
504        rename = "observedInventoryBatches",
505        skip_serializing_if = "Vec::is_empty"
506    )]
507    pub observed_inventory_batches: Vec<ObservedInventoryBatch>,
508}
509
510pub(crate) fn is_false(b: &bool) -> bool {
511    !*b
512}
513
514/// Answers for inputs gating Frozen resources, keyed by input id.
515pub type GateAnswers = IndexMap<String, bool>;
516
517/// Oldest deployment protocol version this binary can read.
518pub const MIN_SUPPORTED_DEPLOYMENT_PROTOCOL_VERSION: u32 = 1;
519
520/// Deployment protocol written by actors with resumable protection, CORS and
521/// database update states and retained deletion. Older readers must be fenced
522/// before these states exist.
523pub const CURRENT_DEPLOYMENT_PROTOCOL_VERSION: u32 = 4;
524
525/// Latest state protocol this binary can execute.
526pub const MAX_SUPPORTED_DEPLOYMENT_PROTOCOL_VERSION: u32 = 4;
527
528/// GCP federation changes setup ownership and target credential semantics.
529pub const GCP_FEDERATION_DEPLOYMENT_PROTOCOL_VERSION: u32 = 2;
530
531pub fn deployment_protocol_version_for_platform(
532    _platform: crate::Platform,
533    _base_platform: Option<crate::Platform>,
534) -> u32 {
535    CURRENT_DEPLOYMENT_PROTOCOL_VERSION
536}
537
538/// Accept unchanged reports or the explicit upgrade to this writer protocol.
539/// Never permit downgrade or unknown protocols. Provider setup prerequisites
540/// remain separate from this checkpoint compatibility check.
541pub fn accepts_deployment_protocol_report(registered: u32, reported: u32) -> bool {
542    (MIN_SUPPORTED_DEPLOYMENT_PROTOCOL_VERSION..=MAX_SUPPORTED_DEPLOYMENT_PROTOCOL_VERSION)
543        .contains(&registered)
544        && (reported == registered
545            || (registered < CURRENT_DEPLOYMENT_PROTOCOL_VERSION
546                && reported == CURRENT_DEPLOYMENT_PROTOCOL_VERSION))
547}
548
549/// Backwards-compatible alias for older call sites.
550pub const DEPLOYMENT_PROTOCOL_VERSION: u32 = CURRENT_DEPLOYMENT_PROTOCOL_VERSION;
551
552#[cfg(test)]
553mod tests {
554    use super::*;
555    use crate::{Platform, ReleaseInfo, Stack, StackState};
556    use indexmap::IndexMap;
557
558    fn empty_stack() -> Stack {
559        Stack {
560            id: "stack_test".to_string(),
561            resources: IndexMap::new(),
562            inputs: vec![],
563            dynamic_container_repositories: Vec::new(),
564            dynamic_container_image_resources: Vec::new(),
565            operations: None,
566            built_architectures: Default::default(),
567            permissions: crate::PermissionsConfig::default(),
568            supported_platforms: None,
569        }
570    }
571
572    fn release_info(id: &str) -> ReleaseInfo {
573        ReleaseInfo {
574            release_id: Some(id.to_string()),
575            version: None,
576            description: None,
577            stack: empty_stack(),
578            signed: None,
579            signer_lists: Vec::new(),
580        }
581    }
582
583    fn state() -> DeploymentState {
584        DeploymentState {
585            status: DeploymentStatus::Pending,
586            platform: Platform::Kubernetes,
587            current_release: None,
588            target_release: None,
589            stack_state: None,
590            error: None,
591            environment_info: None,
592            runtime_metadata: None,
593            retry_requested: false,
594            protocol_version: DEPLOYMENT_PROTOCOL_VERSION,
595        }
596    }
597
598    #[test]
599    fn deployment_state_has_desired_when_release_or_stack_state_exists() {
600        let observe_only = state();
601        assert!(!observe_only.has_desired());
602
603        let mut current = state();
604        current.current_release = Some(release_info("rel_current"));
605        assert!(current.has_desired());
606
607        let mut target = state();
608        target.target_release = Some(release_info("rel_target"));
609        assert!(target.has_desired());
610
611        let mut imported = state();
612        imported.stack_state = Some(StackState::new(Platform::Kubernetes));
613        assert!(imported.has_desired());
614    }
615
616    #[test]
617    fn runtime_metadata_from_before_secret_inventory_defaults_to_empty() {
618        let metadata: RuntimeMetadata = serde_json::from_value(serde_json::json!({
619            "lastSyncedEnvVarsHash": "old-hash"
620        }))
621        .expect("old runtime metadata remains readable");
622
623        assert_eq!(
624            metadata.last_synced_env_vars_hash.as_deref(),
625            Some("old-hash")
626        );
627        assert!(metadata.last_synced_secret_names.is_empty());
628        assert!(!metadata.vault_credentials_revoked);
629        assert!(metadata.retained_storage_protection_hash.is_none());
630        assert!(metadata.retained_storage_protection_confirmed_at.is_none());
631        assert!(metadata.pending_prepared_stack.is_none());
632        assert!(metadata.setup_update_authorization.is_none());
633        assert!(metadata.setup_scaffolding.is_empty());
634    }
635
636    /// Teardown reads this record back from persisted state, so its wire form is a contract.
637    #[test]
638    fn setup_scaffolding_round_trips_in_its_persisted_form() {
639        let persisted = serde_json::json!({
640            "initialSetupAuthority": "directSetup",
641            "setupScaffolding": {
642                "agents": { "type": "awsSandbox", "buildRoleName": "acme-agents-build" }
643            }
644        });
645        let metadata: RuntimeMetadata =
646            serde_json::from_value(persisted.clone()).expect("persisted record reads");
647        assert_eq!(
648            metadata.setup_scaffolding["agents"],
649            SetupScaffolding::AwsSandbox {
650                build_role_name: "acme-agents-build".to_string(),
651                egress: None,
652                image_arn: None,
653            }
654        );
655        assert_eq!(metadata.deletion_policy, DeletionPolicy::Retain);
656        let mut expected = persisted;
657        expected["deletionPolicy"] = serde_json::json!("retain");
658        assert_eq!(serde_json::to_value(&metadata).unwrap(), expected);
659        assert!(
660            serde_json::to_value(RuntimeMetadata::default()).unwrap()["setupScaffolding"].is_null(),
661            "state with no scaffolding serializes as it did before the field existed"
662        );
663    }
664
665    #[test]
666    fn filling_a_record_takes_only_what_it_lacks() {
667        let egress = |group: Option<&str>, connector: Option<&str>| AwsSandboxEgressScaffolding {
668            operator_role_name: "acme-agents-egress".to_string(),
669            security_group_id: group.map(str::to_string),
670            connector_arn: connector.map(str::to_string),
671            connector_request: None,
672        };
673        let record = |egress| SetupScaffolding::AwsSandbox {
674            build_role_name: "acme-agents-build".to_string(),
675            egress,
676            image_arn: None,
677        };
678
679        let mut partial = record(Some(egress(Some("sg-recorded"), None)));
680        partial.fill_missing(record(Some(egress(Some("sg-found"), Some("arn:found")))));
681        assert_eq!(
682            partial,
683            record(Some(egress(Some("sg-recorded"), Some("arn:found")))),
684            "a recorded id is the one teardown deletes"
685        );
686
687        let mut role_only = record(None);
688        role_only.fill_missing(record(Some(egress(Some("sg-found"), None))));
689        assert_eq!(role_only, record(Some(egress(Some("sg-found"), None))));
690
691        let image = |arn: Option<&str>| SetupScaffolding::AwsSandbox {
692            build_role_name: "acme-agents-build".to_string(),
693            egress: None,
694            image_arn: arn.map(str::to_string),
695        };
696        let mut without_image = image(None);
697        without_image.fill_missing(image(Some("arn:found")));
698        assert_eq!(without_image, image(Some("arn:found")));
699        let mut with_image = image(Some("arn:recorded"));
700        with_image.fill_missing(image(Some("arn:found")));
701        assert_eq!(with_image, image(Some("arn:recorded")));
702    }
703
704    /// A deny sandbox's record is written piece by piece, so a partial one must read back as is.
705    #[test]
706    fn a_partial_egress_record_round_trips_in_its_persisted_form() {
707        let persisted = serde_json::json!({
708            "type": "awsSandbox",
709            "buildRoleName": "acme-agents-build",
710            "egress": {
711                "operatorRoleName": "acme-agents-egress",
712                "securityGroupId": "sg-0123"
713            }
714        });
715        let record: SetupScaffolding =
716            serde_json::from_value(persisted.clone()).expect("persisted record reads");
717        assert_eq!(
718            record,
719            SetupScaffolding::AwsSandbox {
720                build_role_name: "acme-agents-build".to_string(),
721                egress: Some(AwsSandboxEgressScaffolding {
722                    operator_role_name: "acme-agents-egress".to_string(),
723                    security_group_id: Some("sg-0123".to_string()),
724                    connector_arn: None,
725                    connector_request: None,
726                }),
727                image_arn: None,
728            }
729        );
730        assert_eq!(serde_json::to_value(&record).unwrap(), persisted);
731    }
732}