Skip to main content

alien_core/
stack_settings.rs

1//!
2//! Defines stack-level settings and management configurations for different cloud platforms.
3//! These settings customize deployment behavior and cross-account/cross-tenant access patterns.
4
5use serde::{Deserialize, Serialize};
6use std::collections::HashMap;
7
8use crate::{ErrorData, KubernetesCloudReference, KubernetesClusterOwnership, Result};
9use alien_error::AlienError;
10use alien_signing::SigningSettings;
11
12/// AWS management configuration extracted from stack settings
13#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
14#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
15#[serde(rename_all = "camelCase")]
16pub struct AwsManagementConfig {
17    /// The managing AWS IAM role ARN that can assume cross-account roles
18    pub managing_role_arn: String,
19}
20
21/// GCP management configuration extracted from stack settings
22#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
23#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
24#[serde(rename_all = "camelCase")]
25pub struct GcpManagementConfig {
26    /// Linked source account metadata; never a direct target trust grant.
27    pub service_account_email: String,
28    /// Available on managers supporting customer-owned target federation.
29    /// New GCP setup requires this capability; unaffected cloud metadata stays readable.
30    #[serde(default, skip_serializing_if = "Option::is_none")]
31    pub federation_trust: Option<crate::GcpFederationTrust>,
32}
33
34/// Azure management configuration extracted from stack settings
35#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
36#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
37#[serde(rename_all = "camelCase")]
38pub struct AzureManagementConfig {
39    /// The managing Azure Tenant ID for cross-tenant access
40    pub managing_tenant_id: String,
41    /// OIDC issuer URL trusted by the target-side managed identity.
42    pub oidc_issuer: String,
43    /// OIDC subject claim trusted by the target-side managed identity.
44    pub oidc_subject: String,
45}
46
47/// Management configuration for different cloud platforms.
48///
49/// Platform-derived configuration for cross-account/cross-tenant access.
50/// This is NOT user-specified - it's derived from the Manager's ServiceAccount.
51#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
52#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
53#[serde(rename_all = "camelCase", tag = "platform")]
54pub enum ManagementConfig {
55    /// AWS management configuration
56    Aws(AwsManagementConfig),
57    /// GCP management configuration  
58    Gcp(GcpManagementConfig),
59    /// Azure management configuration
60    Azure(AzureManagementConfig),
61    /// Kubernetes management configuration (minimal for now)
62    Kubernetes,
63}
64
65/// Network configuration for the stack.
66///
67/// Controls how VPC/VNet networking is provisioned. Users configure this in
68/// `StackSettings`; the Network resource itself is auto-generated by preflights.
69///
70/// ## Egress policy
71///
72/// Container cluster VMs are configured for egress based on the mode:
73///
74/// - `UseDefault` → VMs get ephemeral public IPs (no NAT is provisioned)
75/// - `Create` → VMs use private IPs; Alien provisions a NAT gateway for outbound access
76/// - `ByoVpc*` / `ByoVnet*` → no public IPs assigned; customer manages egress
77///
78/// For production workloads, use `Create`. For fast dev/test iteration, `UseDefault` is
79/// sufficient. For environments with existing VPCs, use the appropriate `ByoVpc*` variant.
80#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
81#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
82#[serde(rename_all = "camelCase", tag = "type")]
83pub enum NetworkSettings {
84    /// Use the cloud provider's default VPC/network.
85    ///
86    /// Designed for fast dev/test provisioning. No isolated VPC is created, so there
87    /// is nothing to wait for or clean up. VMs receive ephemeral public IPs for internet
88    /// access — no NAT gateway is provisioned.
89    ///
90    /// - **AWS**: Discovers the account's default VPC. Subnets are public with auto-assigned IPs.
91    /// - **GCP**: Discovers the project's `default` network and regional subnet. Instance
92    ///   templates include an `AccessConfig` to assign an ephemeral external IP.
93    /// - **Azure**: Azure has no default VNet, so one is created along with a NAT Gateway.
94    ///   VMs stay private and use NAT for egress.
95    ///
96    /// Not recommended for production. Use `Create` instead.
97    #[serde(rename = "use-default")]
98    UseDefault,
99
100    /// Create a new isolated VPC/VNet with a managed NAT gateway.
101    ///
102    /// All networking infrastructure is provisioned by Alien and cleaned up on delete.
103    /// VMs use private IPs only; all outbound traffic routes through the NAT gateway.
104    ///
105    /// Recommended for production deployments.
106    #[serde(rename = "create")]
107    Create {
108        /// VPC/VNet CIDR block. If not specified, auto-generated from stack ID
109        /// to reduce conflicts (e.g., "10.{hash}.0.0/16").
110        #[serde(skip_serializing_if = "Option::is_none")]
111        cidr: Option<String>,
112
113        /// Number of availability zones (default: 2).
114        #[serde(default = "default_availability_zones")]
115        availability_zones: u8,
116    },
117
118    /// Use an existing VPC (AWS).
119    ///
120    /// Alien validates the references but creates no networking infrastructure.
121    /// The customer is responsible for routing and egress (NAT, proxy, VPN, etc.).
122    #[serde(rename = "byo-vpc-aws")]
123    ByoVpcAws {
124        /// The ID of the existing VPC
125        vpc_id: String,
126        /// IDs of public subnets (required for public ingress)
127        #[serde(deserialize_with = "crate::network_ids::deserialize_ids")]
128        public_subnet_ids: Vec<String>,
129        /// IDs of private subnets
130        #[serde(deserialize_with = "crate::network_ids::deserialize_ids")]
131        private_subnet_ids: Vec<String>,
132        /// Optional security group IDs to use
133        #[serde(default)]
134        #[serde(deserialize_with = "crate::network_ids::deserialize_ids")]
135        security_group_ids: Vec<String>,
136    },
137
138    /// Use an existing VPC (GCP).
139    ///
140    /// Alien validates the references but creates no networking infrastructure.
141    /// The customer is responsible for routing and egress (Cloud NAT, proxy, VPN, etc.).
142    #[serde(rename = "byo-vpc-gcp")]
143    ByoVpcGcp {
144        /// The name of the existing VPC network
145        network_name: String,
146        /// The name of the subnet to use
147        subnet_name: String,
148        /// The region of the subnet
149        region: String,
150    },
151
152    /// Use an existing VNet (Azure).
153    ///
154    /// Alien validates the references but creates no networking infrastructure.
155    /// The customer is responsible for routing and egress (NAT Gateway, proxy, VPN, etc.).
156    #[serde(rename = "byo-vnet-azure")]
157    ByoVnetAzure {
158        /// The full resource ID of the existing VNet
159        vnet_resource_id: String,
160        /// Name of the public subnet within the VNet
161        public_subnet_name: String,
162        /// Name of the private subnet within the VNet
163        private_subnet_name: String,
164        /// Name of the dedicated classic Application Gateway subnet within the VNet.
165        #[serde(default, skip_serializing_if = "Option::is_none")]
166        application_gateway_subnet_name: Option<String>,
167        /// Name of the dedicated subnet that hosts Private Endpoints (e.g. for a
168        /// Postgres Flexible Server or Azure Managed Redis). A Private Endpoint must not share the private
169        /// subnet, which is already claimed by the Container Apps environment's
170        /// `infrastructure_subnet_id`. Required only when the stack contains a
171        /// Postgres or Redis resource; otherwise unused.
172        #[serde(default, skip_serializing_if = "Option::is_none")]
173        private_endpoint_subnet_name: Option<String>,
174    },
175}
176
177fn default_availability_zones() -> u8 {
178    2
179}
180
181/// Most availability zones a created network can span. The AWS network gives each zone a
182/// /20 public subnet from x.x.0.0 and a /20 private subnet from x.x.128.0 of the /16, so a
183/// ninth zone would overlap the private range.
184pub const MAX_CREATED_NETWORK_AVAILABILITY_ZONES: u8 = 8;
185
186/// Deployment-time compute choices for Alien-managed compute pools.
187///
188/// Application source declares portable pool requirements. This settings
189/// object stores the concrete choices made for one deployment, such as the
190/// provider machine type and selected machine counts.
191#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
192#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
193#[serde(rename_all = "camelCase")]
194pub struct ComputeSettings {
195    /// Selected compute choices keyed by pool ID.
196    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
197    pub pools: HashMap<String, ComputePoolSelection>,
198    /// Per-replica resources selected within each container's declared ranges.
199    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
200    pub containers: HashMap<String, ContainerResourceSelection>,
201}
202
203/// Deployment-time resource allocation for a container. Omitted fields use release defaults.
204#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
205#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
206#[serde(rename_all = "camelCase", deny_unknown_fields)]
207pub struct ContainerResourceSelection {
208    /// CPU allocation in vCPUs.
209    #[serde(
210        default,
211        skip_serializing_if = "Option::is_none",
212        deserialize_with = "deserialize_selected_cpu"
213    )]
214    #[cfg_attr(feature = "openapi", schema(value_type = Option<f64>))]
215    pub cpu: Option<serde_json::Number>,
216    /// Memory allocation, using binary units such as Mi or Gi.
217    #[serde(default, skip_serializing_if = "Option::is_none")]
218    pub memory: Option<String>,
219    /// Persistent volume capacity per replica, in whole GiB. Omitted values
220    /// use the release default. Existing volumes can only grow.
221    #[serde(default, skip_serializing_if = "Option::is_none")]
222    #[serde(deserialize_with = "deserialize_selected_volume_size")]
223    pub volume_size_gib: Option<u32>,
224}
225
226fn deserialize_selected_volume_size<'de, D: serde::Deserializer<'de>>(
227    deserializer: D,
228) -> std::result::Result<Option<u32>, D::Error> {
229    // CloudFormation Number references arrive as strings in setup import JSON.
230    match Option::<serde_json::Value>::deserialize(deserializer)? {
231        None => Ok(None),
232        Some(serde_json::Value::Number(number)) => number
233            .as_u64()
234            .and_then(|number| u32::try_from(number).ok())
235            .map(Some)
236            .ok_or_else(|| {
237                serde::de::Error::custom("volumeSizeGib must be a whole positive capacity")
238            }),
239        Some(serde_json::Value::String(number)) => {
240            number.parse().map(Some).map_err(serde::de::Error::custom)
241        }
242        Some(_) => Err(serde::de::Error::custom(
243            "volumeSizeGib must be a whole positive capacity",
244        )),
245    }
246}
247
248fn deserialize_selected_cpu<'de, D: serde::Deserializer<'de>>(
249    deserializer: D,
250) -> std::result::Result<Option<serde_json::Number>, D::Error> {
251    // CloudFormation returns Number parameter references as strings.
252    match Option::<serde_json::Value>::deserialize(deserializer)? {
253        None => Ok(None),
254        Some(serde_json::Value::Number(number)) => Ok(Some(number)),
255        Some(serde_json::Value::String(number)) => {
256            number.parse().map(Some).map_err(serde::de::Error::custom)
257        }
258        Some(_) => Err(serde::de::Error::custom("CPU must be a number")),
259    }
260}
261
262/// Failure-domain policy selected for a compute pool.
263#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
264#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
265#[serde(rename_all = "camelCase")]
266pub struct FailureDomainSelection {
267    /// Number of distinct failure domains across which new stateful replicas may be spread.
268    pub spread: u8,
269    /// Concrete provider domains selected during setup.
270    /// Empty delegates deterministic selection to the provider setup implementation.
271    #[serde(default, skip_serializing_if = "Vec::is_empty")]
272    pub selected_failure_domains: Vec<String>,
273}
274
275/// User-selected deployment settings for one compute pool.
276#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
277#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
278#[serde(rename_all = "camelCase", tag = "mode")]
279pub enum ComputePoolSelection {
280    /// Fixed number of machines.
281    Fixed {
282        /// Number of machines to run.
283        machines: u32,
284        /// Provider machine type selected for this deployment.
285        #[serde(
286            default,
287            skip_serializing_if = "Option::is_none",
288            deserialize_with = "deserialize_machine_override"
289        )]
290        machine: Option<String>,
291        /// Optional failure-domain policy. Absence preserves the existing aggregate layout.
292        #[serde(default, skip_serializing_if = "Option::is_none")]
293        failure_domains: Option<FailureDomainSelection>,
294        /// Data disk size per machine, in whole GiB, within the pool's declared
295        /// range. Omitted uses the release default; 0 runs the pool without one.
296        #[serde(
297            rename = "dataDiskGib",
298            default,
299            skip_serializing_if = "Option::is_none",
300            deserialize_with = "deserialize_selected_data_disk_gib"
301        )]
302        data_disk_gib: Option<u32>,
303    },
304    /// Autoscaling machine pool.
305    Autoscale {
306        /// Minimum machine count.
307        min: u32,
308        /// Maximum machine count.
309        max: u32,
310        /// Provider machine type selected for this deployment.
311        #[serde(
312            default,
313            skip_serializing_if = "Option::is_none",
314            deserialize_with = "deserialize_machine_override"
315        )]
316        machine: Option<String>,
317        /// Optional failure-domain policy. Absence preserves the existing aggregate layout.
318        #[serde(default, skip_serializing_if = "Option::is_none")]
319        failure_domains: Option<FailureDomainSelection>,
320        /// Data disk size per machine, in whole GiB, within the pool's declared
321        /// range. Omitted uses the release default; 0 runs the pool without one.
322        #[serde(
323            rename = "dataDiskGib",
324            default,
325            skip_serializing_if = "Option::is_none",
326            deserialize_with = "deserialize_selected_data_disk_gib"
327        )]
328        data_disk_gib: Option<u32>,
329    },
330}
331
332fn deserialize_selected_data_disk_gib<'de, D: serde::Deserializer<'de>>(
333    deserializer: D,
334) -> std::result::Result<Option<u32>, D::Error> {
335    // CloudFormation Number references arrive as strings in setup import JSON.
336    match Option::<serde_json::Value>::deserialize(deserializer)? {
337        None => Ok(None),
338        Some(serde_json::Value::Number(number)) => number
339            .as_u64()
340            .and_then(|number| u32::try_from(number).ok())
341            .map(Some)
342            .ok_or_else(|| serde::de::Error::custom("dataDiskGib must be a whole number of GiB")),
343        Some(serde_json::Value::String(number)) => number
344            .parse()
345            .map(Some)
346            .map_err(|_| serde::de::Error::custom("dataDiskGib must be a whole number of GiB")),
347        Some(_) => Err(serde::de::Error::custom(
348            "dataDiskGib must be a whole number of GiB",
349        )),
350    }
351}
352
353fn deserialize_machine_override<'de, D: serde::Deserializer<'de>>(
354    deserializer: D,
355) -> std::result::Result<Option<String>, D::Error> {
356    // CloudFormation represents its optional String parameters as empty strings.
357    Ok(Option::<String>::deserialize(deserializer)?.filter(|machine| !machine.is_empty()))
358}
359
360impl ComputePoolSelection {
361    /// Selected provider machine type, when this platform needs one.
362    pub fn machine(&self) -> Option<&str> {
363        match self {
364            Self::Fixed { machine, .. } | Self::Autoscale { machine, .. } => machine.as_deref(),
365        }
366    }
367
368    /// Selected failure-domain policy, if this deployment explicitly adopted one.
369    pub fn failure_domains(&self) -> Option<&FailureDomainSelection> {
370        match self {
371            Self::Fixed {
372                failure_domains, ..
373            }
374            | Self::Autoscale {
375                failure_domains, ..
376            } => failure_domains.as_ref(),
377        }
378    }
379
380    /// Selected data disk size in GiB, when the deployment chose one.
381    pub fn data_disk_gib(&self) -> Option<u32> {
382        match self {
383            Self::Fixed { data_disk_gib, .. } | Self::Autoscale { data_disk_gib, .. } => {
384                *data_disk_gib
385            }
386        }
387    }
388
389    /// Selected minimum machine count.
390    pub fn min_size(&self) -> u32 {
391        match self {
392            Self::Fixed { machines, .. } => *machines,
393            Self::Autoscale { min, .. } => *min,
394        }
395    }
396
397    /// Selected maximum machine count.
398    pub fn max_size(&self) -> u32 {
399        match self {
400            Self::Fixed { machines, .. } => *machines,
401            Self::Autoscale { max, .. } => *max,
402        }
403    }
404
405    /// Whether the selection has internally valid scale bounds.
406    pub fn validate(&self) -> std::result::Result<(), String> {
407        if self
408            .failure_domains()
409            .is_some_and(|selection| selection.spread == 0)
410        {
411            return Err("failure-domain spread must be at least one".to_string());
412        }
413        if self.failure_domains().is_some_and(|selection| {
414            !selection.selected_failure_domains.is_empty()
415                && selection.selected_failure_domains.len() != usize::from(selection.spread)
416        }) {
417            return Err("selected failure domains must match the requested spread".to_string());
418        }
419        if self.failure_domains().is_some_and(|selection| {
420            selection.selected_failure_domains.len()
421                != selection
422                    .selected_failure_domains
423                    .iter()
424                    .collect::<std::collections::HashSet<_>>()
425                    .len()
426        }) {
427            return Err("selected failure domains must be unique".to_string());
428        }
429        match self {
430            Self::Fixed { machines, .. } => {
431                if *machines == 0 {
432                    return Err("fixed compute pools must select at least one machine".to_string());
433                }
434                if let Some(failure_domains) = self.failure_domains() {
435                    if *machines < u32::from(failure_domains.spread) {
436                        return Err(format!(
437                            "fixed compute pool machines ({machines}) must be at least failure-domain spread ({})",
438                            failure_domains.spread
439                        ));
440                    }
441                }
442            }
443            Self::Autoscale { min, max, .. } => {
444                if min > max {
445                    return Err(format!(
446                        "autoscaling compute pool minimum ({min}) cannot exceed maximum ({max})"
447                    ));
448                }
449                if let Some(failure_domains) = self.failure_domains() {
450                    let spread = u32::from(failure_domains.spread);
451                    if *max < spread {
452                        return Err(format!(
453                            "autoscaling compute pool maximum ({max}) must be at least failure-domain spread ({spread})"
454                        ));
455                    }
456                    if *min < spread {
457                        return Err(format!(
458                            "autoscaling compute pool minimum ({min}) must be at least failure-domain spread ({spread})"
459                        ));
460                    }
461                }
462            }
463        }
464        Ok(())
465    }
466}
467
468/// Deployment model: how updates are delivered to the remote environment.
469#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
470#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
471#[serde(rename_all = "camelCase")]
472pub enum DeploymentModel {
473    /// Manager pushes updates via cross-account access.
474    /// Available for AWS, GCP, Azure only.
475    #[default]
476    Push,
477    /// Agent in remote environment pulls updates.
478    /// Available for all platforms (AWS, GCP, Azure, Kubernetes, Local).
479    Pull,
480}
481
482/// How updates are delivered to the deployment.
483#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
484#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
485#[serde(rename_all = "kebab-case")]
486pub enum UpdatesMode {
487    /// Updates deploy automatically (default).
488    #[default]
489    Auto,
490    /// Updates require explicit approval before deployment.
491    ApprovalRequired,
492}
493
494/// How telemetry (logs, metrics, traces) is handled.
495#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
496#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
497#[serde(rename_all = "kebab-case")]
498pub enum TelemetryMode {
499    /// No telemetry permissions. Data will not be collected.
500    Off,
501    /// Telemetry flows automatically (default).
502    #[default]
503    Auto,
504    /// Telemetry requires explicit approval before collection begins.
505    ApprovalRequired,
506}
507
508impl TelemetryMode {
509    /// Returns true if telemetry is enabled (Auto or ApprovalRequired).
510    pub fn is_enabled(&self) -> bool {
511        !matches!(self, TelemetryMode::Off)
512    }
513}
514
515/// How heartbeat health checks are handled.
516#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
517#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
518#[serde(rename_all = "kebab-case")]
519pub enum HeartbeatsMode {
520    /// No heartbeat permissions. Health checks disabled.
521    Off,
522    /// Heartbeat enabled (default).
523    #[default]
524    On,
525}
526
527impl HeartbeatsMode {
528    /// Returns true if heartbeat is enabled.
529    pub fn is_enabled(&self) -> bool {
530        matches!(self, HeartbeatsMode::On)
531    }
532}
533
534/// Reachability of the deployment's public endpoints, fixed at setup.
535#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
536#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
537#[serde(rename_all = "camelCase")]
538pub enum EndpointAccess {
539    /// Endpoints are reachable from the internet.
540    #[default]
541    Internet,
542    /// Endpoints are reachable only through the deployment network (AWS only).
543    Private,
544}
545
546impl EndpointAccess {
547    /// Serialized setup parameter value.
548    pub fn as_str(self) -> &'static str {
549        match self {
550            Self::Internet => "internet",
551            Self::Private => "private",
552        }
553    }
554}
555
556/// Domain configuration for the stack.
557///
558/// When `custom_domains` is set, the specified resources use customer-provided
559/// domains with supplied or managed certificates. Otherwise, Alien auto-generates domains.
560#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
561#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
562#[serde(rename_all = "camelCase")]
563pub struct DomainSettings {
564    /// Custom domain configuration per resource ID.
565    #[serde(default, skip_serializing_if = "Option::is_none")]
566    pub custom_domains: Option<HashMap<String, CustomDomainConfig>>,
567    /// Public endpoint DNS target selection for machines deployments.
568    ///
569    /// When omitted, machines deployments publish healthy machine public
570    /// addresses directly. Use `LoadBalancer` when an external load balancer
571    /// fronts the machines and Alien should publish a CNAME to that target.
572    #[serde(default, skip_serializing_if = "Option::is_none")]
573    pub public_endpoint_target: Option<PublicEndpointTargetSettings>,
574}
575
576/// DNS target mode for public endpoints.
577#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
578#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
579#[serde(rename_all = "camelCase", tag = "mode")]
580pub enum PublicEndpointTargetSettings {
581    /// Publish DNS records directly to healthy machine public IP addresses.
582    MachineAddresses,
583    /// Publish a CNAME record to an external load balancer.
584    #[serde(rename_all = "camelCase")]
585    LoadBalancer {
586        /// DNS name or URL for the external load balancer.
587        cname_target: String,
588    },
589}
590
591/// Custom domain configuration for a single resource.
592#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
593#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
594#[serde(rename_all = "camelCase")]
595pub struct CustomDomainConfig {
596    /// Fully qualified domain name for a supplied certificate.
597    #[serde(default, skip_serializing_if = "String::is_empty")]
598    pub domain: String,
599    /// Hostnames keyed by endpoint name for a managed certificate.
600    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
601    pub endpoints: HashMap<String, String>,
602    /// Supplied certificate reference or managed issuance.
603    pub certificate: CustomCertificateConfig,
604}
605
606/// Platform-specific certificate references for custom domains.
607#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
608#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
609#[serde(rename_all = "camelCase")]
610pub struct CustomCertificateConfig {
611    /// Issue and renew a certificate for the configured endpoint hostnames.
612    #[serde(default, skip_serializing_if = "Option::is_none")]
613    pub managed: Option<ManagedCustomCertificateConfig>,
614    /// AWS ACM certificate ARN
615    #[serde(default, skip_serializing_if = "Option::is_none")]
616    pub aws: Option<AwsCustomCertificateConfig>,
617    /// GCP Certificate Manager certificate name
618    #[serde(default, skip_serializing_if = "Option::is_none")]
619    pub gcp: Option<GcpCustomCertificateConfig>,
620    /// Azure Key Vault certificate ID
621    #[serde(default, skip_serializing_if = "Option::is_none")]
622    pub azure: Option<AzureCustomCertificateConfig>,
623    /// Kubernetes TLS Secret reference for Secret-backed route profiles.
624    #[serde(default, skip_serializing_if = "Option::is_none")]
625    pub kubernetes: Option<KubernetesCustomCertificateConfig>,
626}
627
628/// Managed certificate issuance settings.
629#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
630#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
631#[serde(rename_all = "camelCase", deny_unknown_fields)]
632pub struct ManagedCustomCertificateConfig {}
633
634#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
635#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
636#[serde(rename_all = "camelCase")]
637pub struct AwsCustomCertificateConfig {
638    pub certificate_arn: String,
639}
640
641#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
642#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
643#[serde(rename_all = "camelCase")]
644pub struct GcpCustomCertificateConfig {
645    pub certificate_name: String,
646}
647
648#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
649#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
650#[serde(rename_all = "camelCase")]
651pub struct AzureCustomCertificateConfig {
652    pub key_vault_certificate_id: String,
653    #[serde(default, skip_serializing_if = "Option::is_none")]
654    pub key_vault_resource_id: Option<String>,
655}
656
657#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
658#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
659#[serde(rename_all = "camelCase")]
660pub struct KubernetesCustomCertificateConfig {
661    /// Existing TLS Secret containing `tls.crt` and `tls.key`.
662    pub tls_secret_ref: KubernetesTlsSecretRef,
663}
664
665/// Kubernetes runtime substrate configuration.
666///
667/// This controls how setup chooses the cluster backing `Platform::Kubernetes`
668/// deployments. When omitted, cloud-backed Kubernetes deployments default to a
669/// managed cluster and generic/on-prem Kubernetes defaults to an external
670/// cluster.
671#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
672#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
673#[serde(rename_all = "camelCase")]
674pub struct KubernetesSettings {
675    /// Cluster selection or creation settings.
676    #[serde(default, skip_serializing_if = "Option::is_none")]
677    pub cluster: Option<KubernetesClusterSettings>,
678    /// Public HTTPS exposure contract shared by setup, Helm, and runtime.
679    #[serde(default, skip_serializing_if = "Option::is_none")]
680    pub exposure: Option<KubernetesExposureSettings>,
681}
682
683/// Kubernetes cluster setup settings.
684#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
685#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
686#[serde(rename_all = "camelCase")]
687pub struct KubernetesClusterSettings {
688    /// Whether Alien should create the cluster, use a setup-owned existing
689    /// cluster, or bind to an external/on-prem cluster.
690    pub ownership: KubernetesClusterOwnership,
691    /// Namespace where the Alien chart and application resources run.
692    #[serde(default, skip_serializing_if = "Option::is_none")]
693    pub namespace: Option<String>,
694    /// Optional provider-specific cloud identity for existing clusters.
695    #[serde(default, skip_serializing_if = "Option::is_none")]
696    pub cloud: Option<KubernetesCloudReference>,
697}
698
699/// Kubernetes public HTTPS exposure mode.
700#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
701#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
702#[serde(rename_all = "camelCase", tag = "mode")]
703pub enum KubernetesExposureSettings {
704    /// Do not create Alien-managed external routing.
705    Disabled,
706    /// Use Alien-generated DNS and Platform-managed certificate material.
707    Generated {
708        /// Runtime route profile to materialize.
709        route: KubernetesRouteProfile,
710        /// How managed certificate material reaches the route profile.
711        certificate: KubernetesCertificateMode,
712    },
713    /// Use a customer hostname and customer-owned certificate reference.
714    Custom {
715        /// Hostname routed by the Kubernetes public endpoint.
716        domain: String,
717        /// Runtime route profile to materialize.
718        route: KubernetesRouteProfile,
719        /// Customer-owned certificate reference consumed by the route profile.
720        certificate: KubernetesCertificateMode,
721    },
722    /// Give each named public endpoint a hostname below a customer-owned base domain.
723    #[serde(rename_all = "camelCase")]
724    CustomBaseDomain {
725        /// DNS name without a wildcard or URL scheme, for example `app.example.com`.
726        base_domain: String,
727        /// Route profile shared by all public endpoints.
728        route: KubernetesRouteProfile,
729        /// One customer-owned certificate reference covering every endpoint hostname.
730        certificate: KubernetesCertificateMode,
731    },
732}
733
734/// Kubernetes route API selected for public endpoints.
735#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
736#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
737#[serde(rename_all = "camelCase", tag = "routeApi")]
738pub enum KubernetesRouteProfile {
739    /// `networking.k8s.io/v1` Ingress route profile.
740    Ingress(KubernetesIngressRouteProfile),
741    /// Gateway API `Gateway` + `HTTPRoute` route profile.
742    Gateway(KubernetesGatewayRouteProfile),
743}
744
745/// Shared Ingress route profile values.
746#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
747#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
748#[serde(rename_all = "camelCase")]
749pub struct KubernetesIngressRouteProfile {
750    /// Route controller identifier, for example `eks.amazonaws.com/alb`.
751    #[serde(default, skip_serializing_if = "Option::is_none")]
752    pub controller: Option<String>,
753    /// `spec.ingressClassName` for generated Ingresses.
754    pub ingress_class_name: String,
755    /// Labels applied to route objects.
756    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
757    pub labels: HashMap<String, String>,
758    /// Annotations applied to route objects.
759    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
760    pub annotations: HashMap<String, String>,
761    /// Provider-specific route options that are required by the selected class.
762    #[serde(default, skip_serializing_if = "Option::is_none")]
763    pub provider: Option<KubernetesRouteProviderOptions>,
764}
765
766/// Shared Gateway API route profile values.
767#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
768#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
769#[serde(rename_all = "camelCase")]
770pub struct KubernetesGatewayRouteProfile {
771    /// Route controller identifier, for example a cloud Gateway controller.
772    #[serde(default, skip_serializing_if = "Option::is_none")]
773    pub controller: Option<String>,
774    /// GatewayClass selected for generated Gateways.
775    pub gateway_class_name: String,
776    /// Listener port, usually 443.
777    pub listener_port: u16,
778    /// Labels applied to route objects.
779    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
780    pub labels: HashMap<String, String>,
781    /// Annotations applied to route objects.
782    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
783    pub annotations: HashMap<String, String>,
784    /// Provider-specific route options that are required by the selected class.
785    #[serde(default, skip_serializing_if = "Option::is_none")]
786    pub provider: Option<KubernetesRouteProviderOptions>,
787}
788
789/// Provider-specific route options required by supported managed profiles.
790#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
791#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
792#[serde(rename_all = "camelCase", tag = "provider")]
793pub enum KubernetesRouteProviderOptions {
794    /// AWS ALB route options for EKS.
795    #[serde(rename_all = "camelCase")]
796    AwsAlb {
797        /// Internet-facing or internal ALB scheme.
798        scheme: String,
799        /// ALB target type, usually `ip`.
800        target_type: String,
801        /// Optional ALB IP address type, such as `dualstack`.
802        #[serde(default, skip_serializing_if = "Option::is_none")]
803        ip_address_type: Option<String>,
804        /// Explicit subnet IDs when the profile cannot rely on controller discovery.
805        #[serde(default, skip_serializing_if = "Vec::is_empty")]
806        subnet_ids: Vec<String>,
807    },
808    /// GKE Gateway route options.
809    #[serde(rename_all = "camelCase")]
810    GkeGateway {
811        /// Optional static address name for the Gateway frontend.
812        #[serde(default, skip_serializing_if = "Option::is_none")]
813        static_address_name: Option<String>,
814    },
815    /// Azure Application Gateway for Containers route options.
816    #[serde(rename_all = "camelCase")]
817    AzureApplicationGatewayForContainers {
818        /// Optional ALB namespace when using BYO Application Gateway resources.
819        #[serde(default, skip_serializing_if = "Option::is_none")]
820        alb_namespace: Option<String>,
821        /// Optional ALB name when using BYO Application Gateway resources.
822        #[serde(default, skip_serializing_if = "Option::is_none")]
823        alb_name: Option<String>,
824        /// Public or internal frontend exposure.
825        frontend: String,
826    },
827}
828
829/// Certificate publication or reference mode for Kubernetes public endpoints.
830#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
831#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
832#[serde(rename_all = "camelCase", tag = "mode")]
833pub enum KubernetesCertificateMode {
834    /// Platform-managed cert imported into AWS ACM by the runtime.
835    #[serde(rename_all = "camelCase")]
836    ManagedAcmImport {
837        /// ACM region. Defaults to the deployment region when omitted.
838        #[serde(default, skip_serializing_if = "Option::is_none")]
839        region: Option<String>,
840        /// Tags applied to runtime-imported ACM certificates.
841        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
842        tags: HashMap<String, String>,
843    },
844    /// Customer-provided AWS ACM certificate ARN.
845    #[serde(rename_all = "camelCase")]
846    AwsAcmArn {
847        /// Existing ACM certificate ARN.
848        certificate_arn: String,
849    },
850    /// Platform-managed cert written to a Kubernetes TLS Secret.
851    #[serde(rename_all = "camelCase")]
852    ManagedTlsSecret {
853        /// Secret name template. Runtime may substitute resource/deployment tokens.
854        secret_name_template: String,
855    },
856    /// Customer-provided Kubernetes TLS Secret.
857    TlsSecretRef(KubernetesTlsSecretRef),
858    /// No TLS certificate should be configured by Alien.
859    None,
860}
861
862/// Namespace-scoped Kubernetes TLS Secret reference.
863#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
864#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
865#[serde(rename_all = "camelCase")]
866pub struct KubernetesTlsSecretRef {
867    /// Secret name.
868    pub secret_name: String,
869    /// Secret namespace. Defaults to the release namespace when omitted.
870    #[serde(default, skip_serializing_if = "Option::is_none")]
871    pub namespace: Option<String>,
872}
873
874/// User-customizable deployment settings specified at deploy time.
875///
876/// These settings are provided by the customer via CloudFormation parameters,
877/// Terraform attributes, CLI flags, or Helm values. They customize how the
878/// deployment runs and what capabilities are enabled.
879///
880/// **Key distinction**: StackSettings is user-customizable, while ManagementConfig
881/// is platform-derived (from the Manager's ServiceAccount).
882#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
883#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
884#[serde(rename_all = "camelCase")]
885pub struct StackSettings {
886    /// Ongoing authority over infrastructure normally owned by setup. Automatic requires
887    /// an explicit CLI setup grant; changing this setting alone never grants that authority.
888    #[serde(default, skip_serializing_if = "is_manual_setup_management")]
889    pub setup_management: SetupManagement,
890    /// Provider quota identities whose preflight failures become visible warnings
891    /// for this deployment. Checks still run; deploy-time provider limits still apply.
892    /// Unknown identities are rejected. An empty list restores normal blocking.
893    #[serde(default, skip_serializing_if = "Vec::is_empty")]
894    pub quota_warning_overrides: Vec<String>,
895
896    /// Who can reach public endpoints. Private access requires AWS managed containers.
897    /// This choice cannot change after setup; create a new deployment to change it.
898    #[serde(default)]
899    pub endpoint_access: EndpointAccess,
900
901    /// Network configuration for the stack (VPC/VNet settings).
902    /// If `None`, an isolated VPC with NAT is auto-created when the stack has resources
903    /// that require networking (e.g., containers). Set explicitly to customize:
904    /// `UseDefault` for the provider's default network (fast, dev/test only),
905    /// `Create` for an isolated VPC with managed NAT (production), or `ByoVpc*`
906    /// to reference an existing customer-managed VPC.
907    #[serde(default, skip_serializing_if = "Option::is_none")]
908    pub network: Option<NetworkSettings>,
909
910    /// Domain configuration (future).
911    #[serde(default, skip_serializing_if = "Option::is_none")]
912    pub domains: Option<DomainSettings>,
913
914    /// Kubernetes runtime substrate configuration.
915    #[serde(default, skip_serializing_if = "Option::is_none")]
916    pub kubernetes: Option<KubernetesSettings>,
917
918    /// Deployment-time compute selections for Alien-managed compute pools.
919    ///
920    /// This is where provider machine names such as EC2 instance types, GCE
921    /// machine types, or Azure VM SKUs belong. Application source should
922    /// declare portable requirements instead.
923    #[serde(default, skip_serializing_if = "Option::is_none")]
924    pub compute: Option<ComputeSettings>,
925
926    /// Exact externally managed endpoint URLs, keyed by resource ID and endpoint name.
927    ///
928    /// This is intended for adopted Machines deployments whose DNS and certificates remain
929    /// customer-owned. The platform passes these URLs to the runtime without creating or
930    /// replacing DNS records or certificates.
931    #[serde(default, skip_serializing_if = "Option::is_none")]
932    #[cfg_attr(
933        feature = "openapi",
934        schema(value_type = Option<HashMap<String, HashMap<String, String>>>)
935    )]
936    pub public_endpoints: Option<crate::PublicEndpointUrls>,
937
938    /// Deployment model: push (Manager) or pull (Agent).
939    /// Default: Push.
940    /// - Push: Manager drives updates. For cloud platforms, requires cross-account
941    ///   credentials established during initial setup. For push-mode local
942    ///   deployments (currently `alien dev`), the manager has direct access —
943    ///   no bootstrap needed.
944    /// - Pull: Agent in the target environment drives updates via polling.
945    ///   Required for Kubernetes and remote local deployments.
946    #[serde(default, skip_serializing_if = "is_default_deployment_model")]
947    pub deployment_model: DeploymentModel,
948
949    /// Deliver Kubernetes updates and reports as carried bundles instead of a live connection.
950    /// The Operator still executes deployments with the pull model.
951    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
952    pub airgapped: bool,
953
954    /// How updates are delivered.
955    /// - auto: Updates deploy automatically (default)
956    /// - approval-required: Updates wait for explicit approval
957    #[serde(default, skip_serializing_if = "is_default_updates_mode")]
958    pub updates: UpdatesMode,
959
960    /// How telemetry (logs, metrics, traces) is handled.
961    /// - off: No telemetry permissions
962    /// - auto: Telemetry flows automatically (default)
963    /// - approval-required: Telemetry waits for explicit approval
964    #[serde(default, skip_serializing_if = "is_default_telemetry_mode")]
965    pub telemetry: TelemetryMode,
966
967    /// How heartbeat health checks are handled.
968    /// - off: No heartbeat permissions
969    /// - on: Heartbeat enabled (default)
970    #[serde(default, skip_serializing_if = "is_default_heartbeats_mode")]
971    pub heartbeats: HeartbeatsMode,
972
973    /// External bindings for pre-existing infrastructure.
974    /// Allows using existing resources (MinIO, Redis, shared Container Apps
975    /// Environment, etc.) instead of having Alien provision them.
976    /// Required for Kubernetes platform, optional for cloud platforms.
977    #[serde(default, skip_serializing_if = "Option::is_none")]
978    pub external_bindings: Option<crate::ExternalBindings>,
979
980    /// Release signing for this install. When set, setup writes the signing settings
981    /// (the fingerprint, the install's prefix and the channel) where only setup can change
982    /// them, and the install's enforcers run only what the vendor signed. Setup alone writes
983    /// them: changing this later does not change what an install already pinned.
984    #[serde(default, skip_serializing_if = "Option::is_none")]
985    pub signing: Option<StackSigning>,
986}
987
988/// The 12-digit AWS account that publishes the machine images protected installs boot, if this
989/// build has one. The CLI release workflow writes it into `machine-image-publisher-aws.txt`
990/// before building, so every build of a release renders the same setup; source builds have none.
991pub fn machine_image_publisher_aws() -> Option<&'static str> {
992    let account = include_str!("../machine-image-publisher-aws.txt").trim();
993    (account.len() == 12 && account.bytes().all(|byte| byte.is_ascii_digit())).then_some(account)
994}
995
996/// The GCP project that publishes the machine images protected installs boot
997/// (`projects/<project>/global/images/<name>`), if this build has one. The CLI release
998/// workflow writes it into `machine-image-publisher-gcp.txt`; source builds have none.
999pub fn machine_image_publisher_gcp() -> Option<&'static str> {
1000    let project = include_str!("../machine-image-publisher-gcp.txt").trim();
1001    (!project.is_empty()
1002        && project.len() <= 30
1003        && project
1004            .bytes()
1005            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-'))
1006    .then_some(project)
1007}
1008
1009/// The public name of the Azure community gallery that publishes the machine images
1010/// protected installs boot (`/CommunityGalleries/<name>/Images/...`), if this build has one.
1011/// The CLI release workflow writes it into `machine-image-publisher-azure.txt`; source builds
1012/// have none.
1013pub fn machine_image_publisher_azure() -> Option<&'static str> {
1014    let gallery = include_str!("../machine-image-publisher-azure.txt").trim();
1015    (!gallery.is_empty()
1016        && gallery.len() <= 100
1017        && gallery
1018            .bytes()
1019            .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-'))
1020    .then_some(gallery)
1021}
1022
1023/// The oldest machine image protected installs boot: an image the cloud records as created
1024/// before this is refused even from the publisher, so a fixed image replaces every older one.
1025/// The CLI release workflow writes it (RFC 3339) into `machine-image-minimum-created.txt` with
1026/// the publisher; a build without it launches no machines on protected installs.
1027pub fn machine_image_minimum_created() -> Option<chrono::DateTime<chrono::Utc>> {
1028    let text = include_str!("../machine-image-minimum-created.txt").trim();
1029    chrono::DateTime::parse_from_rfc3339(text)
1030        .ok()
1031        .map(|time| time.with_timezone(&chrono::Utc))
1032}
1033
1034/// The AWS verifier image protected setups run, as `<repository>@sha256:<64 hex>` in the
1035/// publisher's registry, if this build has one. The CLI release workflow writes it into
1036/// `verifier-image-aws.txt` with the publisher; setups run
1037/// `<publisher>.dkr.ecr.<region>.amazonaws.com/<repository>@<digest>`.
1038pub fn verifier_image_aws() -> Option<&'static str> {
1039    let image = include_str!("../verifier-image-aws.txt").trim();
1040    is_pinned_image(image).then_some(image)
1041}
1042
1043/// The GCP verifier image protected setups run on Cloud Run, as
1044/// `<registry host>/<repository>@sha256:<64 hex>`, if this build has one. The CLI release
1045/// workflow writes it into `verifier-image-gcp.txt`.
1046pub fn verifier_image_gcp() -> Option<&'static str> {
1047    let image = include_str!("../verifier-image-gcp.txt").trim();
1048    is_pinned_image(image).then_some(image)
1049}
1050
1051/// The Azure verifier image protected setups run as a Container App, as
1052/// `<registry host>/<repository>@sha256:<64 hex>` in a registry that serves it without
1053/// credentials, if this build has one. The CLI release workflow writes it into
1054/// `verifier-image-azure.txt`.
1055pub fn verifier_image_azure() -> Option<&'static str> {
1056    let image = include_str!("../verifier-image-azure.txt").trim();
1057    is_pinned_image(image).then_some(image)
1058}
1059
1060/// Whether `image` is `<repository>@sha256:<64 lowercase hex>` with a plain repository path.
1061pub fn is_pinned_image(image: &str) -> bool {
1062    let Some((repository, hex)) = image.split_once("@sha256:") else {
1063        return false;
1064    };
1065    !repository.is_empty()
1066        && repository
1067            .bytes()
1068            .all(|byte| matches!(byte, b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'/'))
1069        && hex.len() == 64
1070        && hex
1071            .bytes()
1072            .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
1073}
1074
1075/// Digest (`sha256:<64 hex>`) of the Operator image protected charts run, if this build has
1076/// one. The CLI release workflow writes it into `operator-digest.txt` with the other pins; it
1077/// is the `operator` digest a signed release names in `components`.
1078pub fn operator_digest() -> Option<&'static str> {
1079    let digest = include_str!("../operator-digest.txt").trim();
1080    let hex = digest.strip_prefix("sha256:")?;
1081    (hex.len() == 64
1082        && hex
1083            .bytes()
1084            .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f')))
1085    .then_some(digest)
1086}
1087
1088/// Values a protected setup pins that come with the CLI build, not with the stack: the account
1089/// whose machine images machines may boot and the verifier image of each cloud. Renders that a release
1090/// records use [`SetupPins::compiled_in`], so every build of one release renders the same
1091/// bytes; tests pin their own.
1092#[derive(Debug, Clone, Default, PartialEq, Eq)]
1093pub struct SetupPins {
1094    /// 12-digit AWS account that publishes machine images and the verifier image.
1095    pub aws_publisher: Option<String>,
1096    /// AWS verifier image, `<repository>@sha256:<64 hex>` in the publisher's registry.
1097    pub aws_verifier_image: Option<String>,
1098    /// GCP verifier image, `<registry host>/<repository>@sha256:<64 hex>`.
1099    pub gcp_verifier_image: Option<String>,
1100    /// Azure verifier image, `<registry host>/<repository>@sha256:<64 hex>`.
1101    pub azure_verifier_image: Option<String>,
1102    /// `sha256:<64 hex>` of the Operator image protected charts run.
1103    pub operator_digest: Option<String>,
1104}
1105
1106impl SetupPins {
1107    /// The pins this build was released with; empty for source builds.
1108    pub fn compiled_in() -> Self {
1109        Self {
1110            aws_publisher: machine_image_publisher_aws().map(str::to_string),
1111            aws_verifier_image: verifier_image_aws().map(str::to_string),
1112            gcp_verifier_image: verifier_image_gcp().map(str::to_string),
1113            azure_verifier_image: verifier_image_azure().map(str::to_string),
1114            operator_digest: operator_digest().map(str::to_string),
1115        }
1116    }
1117}
1118
1119/// What setup pins for a protected install.
1120///
1121/// Take the values from the vendor's install guide or signed release, not from the
1122/// control plane.
1123#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1124#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
1125#[serde(rename_all = "camelCase", deny_unknown_fields)]
1126pub struct StackSigning {
1127    /// `SHA256:<64 hex>` fingerprint of the vendor's signer list version 1.
1128    pub fingerprint: String,
1129    /// Release channel the install follows, such as `production`.
1130    pub channel: String,
1131}
1132
1133impl StackSigning {
1134    /// The settings setup writes for the install whose resource prefix is `prefix`, checked
1135    /// the way enforcers check them when they read them.
1136    pub fn settings(&self, prefix: &str) -> Result<SigningSettings> {
1137        let settings = SigningSettings {
1138            fingerprint: self.fingerprint.clone(),
1139            prefix: prefix.to_string(),
1140            channel: self.channel.clone(),
1141        };
1142        settings.validate().map_err(|error| {
1143            AlienError::new(ErrorData::SigningSettingsInvalid {
1144                reason: error.message,
1145            })
1146        })?;
1147        Ok(settings)
1148    }
1149}
1150
1151/// Whether setup remains a separate administrator operation.
1152#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
1153#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
1154#[serde(rename_all = "camelCase")]
1155pub enum SetupManagement {
1156    /// Setup owns structural infrastructure changes and teardown.
1157    #[default]
1158    Manual,
1159    /// Alien continues managing setup infrastructure with permissions explicitly granted at setup.
1160    Automatic,
1161}
1162
1163impl SetupManagement {
1164    /// Serialized setup parameter value.
1165    pub fn as_str(self) -> &'static str {
1166        match self {
1167            Self::Manual => "manual",
1168            Self::Automatic => "automatic",
1169        }
1170    }
1171}
1172
1173fn is_manual_setup_management(mode: &SetupManagement) -> bool {
1174    *mode == SetupManagement::Manual
1175}
1176
1177fn is_default_deployment_model(model: &DeploymentModel) -> bool {
1178    *model == DeploymentModel::default()
1179}
1180
1181fn is_default_updates_mode(mode: &UpdatesMode) -> bool {
1182    *mode == UpdatesMode::default()
1183}
1184
1185fn is_default_telemetry_mode(mode: &TelemetryMode) -> bool {
1186    *mode == TelemetryMode::default()
1187}
1188
1189fn is_default_heartbeats_mode(mode: &HeartbeatsMode) -> bool {
1190    *mode == HeartbeatsMode::default()
1191}
1192
1193#[cfg(test)]
1194mod failure_domain_tests {
1195    use super::*;
1196
1197    #[test]
1198    fn old_compute_selection_deserializes_without_topology() {
1199        let selection: ComputePoolSelection = serde_json::from_value(serde_json::json!({
1200            "mode": "fixed",
1201            "machines": 2,
1202            "machine": "m7i.xlarge"
1203        }))
1204        .expect("existing selection should deserialize");
1205        assert!(selection.failure_domains().is_none());
1206    }
1207
1208    #[test]
1209    fn rejects_duplicate_concrete_failure_domains() {
1210        let selection = ComputePoolSelection::Fixed {
1211            machines: 2,
1212            machine: Some("m7i.xlarge".to_string()),
1213            failure_domains: Some(FailureDomainSelection {
1214                spread: 2,
1215                selected_failure_domains: vec!["us-west-2a".to_string(); 2],
1216            }),
1217            data_disk_gib: None,
1218        };
1219        assert_eq!(
1220            selection.validate(),
1221            Err("selected failure domains must be unique".to_string())
1222        );
1223    }
1224
1225    #[test]
1226    fn fixed_pool_must_have_one_machine_per_failure_domain() {
1227        let invalid = ComputePoolSelection::Fixed {
1228            machines: 1,
1229            machine: None,
1230            failure_domains: Some(FailureDomainSelection {
1231                spread: 2,
1232                selected_failure_domains: Vec::new(),
1233            }),
1234            data_disk_gib: None,
1235        };
1236        assert_eq!(
1237            invalid.validate(),
1238            Err(
1239                "fixed compute pool machines (1) must be at least failure-domain spread (2)"
1240                    .to_string()
1241            )
1242        );
1243
1244        let valid = ComputePoolSelection::Fixed {
1245            machines: 2,
1246            machine: None,
1247            failure_domains: Some(FailureDomainSelection {
1248                spread: 2,
1249                selected_failure_domains: Vec::new(),
1250            }),
1251            data_disk_gib: None,
1252        };
1253        assert_eq!(valid.validate(), Ok(()));
1254    }
1255
1256    #[test]
1257    fn autoscaling_pool_bounds_must_cover_every_failure_domain() {
1258        let invalid_max = ComputePoolSelection::Autoscale {
1259            min: 1,
1260            max: 1,
1261            machine: None,
1262            failure_domains: Some(FailureDomainSelection {
1263                spread: 2,
1264                selected_failure_domains: Vec::new(),
1265            }),
1266            data_disk_gib: None,
1267        };
1268        assert_eq!(
1269            invalid_max.validate(),
1270            Err(
1271                "autoscaling compute pool maximum (1) must be at least failure-domain spread (2)"
1272                    .to_string()
1273            )
1274        );
1275
1276        let invalid_min = ComputePoolSelection::Autoscale {
1277            min: 1,
1278            max: 3,
1279            machine: None,
1280            failure_domains: Some(FailureDomainSelection {
1281                spread: 2,
1282                selected_failure_domains: Vec::new(),
1283            }),
1284            data_disk_gib: None,
1285        };
1286        assert_eq!(
1287            invalid_min.validate(),
1288            Err(
1289                "autoscaling compute pool minimum (1) must be at least failure-domain spread (2)"
1290                    .to_string()
1291            )
1292        );
1293
1294        let valid = ComputePoolSelection::Autoscale {
1295            min: 2,
1296            max: 2,
1297            machine: None,
1298            failure_domains: Some(FailureDomainSelection {
1299                spread: 2,
1300                selected_failure_domains: Vec::new(),
1301            }),
1302            data_disk_gib: None,
1303        };
1304        assert_eq!(valid.validate(), Ok(()));
1305    }
1306
1307    #[test]
1308    fn machine_public_endpoints_round_trip_without_rewriting_urls() {
1309        let settings: StackSettings = serde_json::from_value(serde_json::json!({
1310            "publicEndpoints": {
1311                "loader": {
1312                    "api": "https://loader.compute.example.com",
1313                    "shares": "https://shares.compute.example.com",
1314                    "webhooks": "https://webhooks.compute.example.com"
1315                }
1316            }
1317        }))
1318        .expect("stack settings should deserialize");
1319
1320        assert_eq!(
1321            serde_json::to_value(settings).expect("stack settings should serialize")
1322                ["publicEndpoints"]["loader"]["shares"],
1323            "https://shares.compute.example.com"
1324        );
1325    }
1326
1327    #[test]
1328    fn custom_domains_preserve_managed_endpoint_names_and_supplied_certificates() {
1329        for config in [
1330            serde_json::json!({
1331                "endpoints": {
1332                    "api": "q7.m2x.example.com",
1333                    "shares": "*.q7.s9t.example.com",
1334                    "webhooks": "*.q7.w3h.example.com"
1335                },
1336                "certificate": {"managed": {}}
1337            }),
1338            serde_json::json!({
1339                "domain": "app.example.com",
1340                "certificate": {"aws": {"certificateArn": "arn:example"}}
1341            }),
1342        ] {
1343            let parsed: CustomDomainConfig = serde_json::from_value(config.clone())
1344                .expect("custom domain configuration should deserialize");
1345            assert_eq!(serde_json::to_value(parsed).unwrap(), config);
1346        }
1347    }
1348}