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    /// Source address ranges (IPv4 or IPv6 CIDR, in canonical network form) allowed to reach
902    /// the deployment's public endpoints, for example the ranges of a proxy in front of it.
903    /// Empty means anyone can connect. At most 25 entries; needs `endpoint_access: internet`.
904    /// Unlike `endpoint_access`, this can change on a running deployment.
905    #[serde(default, skip_serializing_if = "Vec::is_empty")]
906    pub endpoint_source_ranges: Vec<String>,
907
908    /// Network configuration for the stack (VPC/VNet settings).
909    /// If `None`, an isolated VPC with NAT is auto-created when the stack has resources
910    /// that require networking (e.g., containers). Set explicitly to customize:
911    /// `UseDefault` for the provider's default network (fast, dev/test only),
912    /// `Create` for an isolated VPC with managed NAT (production), or `ByoVpc*`
913    /// to reference an existing customer-managed VPC.
914    #[serde(default, skip_serializing_if = "Option::is_none")]
915    pub network: Option<NetworkSettings>,
916
917    /// Domain configuration (future).
918    #[serde(default, skip_serializing_if = "Option::is_none")]
919    pub domains: Option<DomainSettings>,
920
921    /// Kubernetes runtime substrate configuration.
922    #[serde(default, skip_serializing_if = "Option::is_none")]
923    pub kubernetes: Option<KubernetesSettings>,
924
925    /// Deployment-time compute selections for Alien-managed compute pools.
926    ///
927    /// This is where provider machine names such as EC2 instance types, GCE
928    /// machine types, or Azure VM SKUs belong. Application source should
929    /// declare portable requirements instead.
930    #[serde(default, skip_serializing_if = "Option::is_none")]
931    pub compute: Option<ComputeSettings>,
932
933    /// Exact externally managed endpoint URLs, keyed by resource ID and endpoint name.
934    ///
935    /// This is intended for adopted Machines deployments whose DNS and certificates remain
936    /// customer-owned. The platform passes these URLs to the runtime without creating or
937    /// replacing DNS records or certificates.
938    #[serde(default, skip_serializing_if = "Option::is_none")]
939    #[cfg_attr(
940        feature = "openapi",
941        schema(value_type = Option<HashMap<String, HashMap<String, String>>>)
942    )]
943    pub public_endpoints: Option<crate::PublicEndpointUrls>,
944
945    /// Deployment model: push (Manager) or pull (Agent).
946    /// Default: Push.
947    /// - Push: Manager drives updates. For cloud platforms, requires cross-account
948    ///   credentials established during initial setup. For push-mode local
949    ///   deployments (currently `alien dev`), the manager has direct access —
950    ///   no bootstrap needed.
951    /// - Pull: Agent in the target environment drives updates via polling.
952    ///   Required for Kubernetes and remote local deployments.
953    #[serde(default, skip_serializing_if = "is_default_deployment_model")]
954    pub deployment_model: DeploymentModel,
955
956    /// Deliver Kubernetes updates and reports as carried bundles instead of a live connection.
957    /// The Operator still executes deployments with the pull model.
958    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
959    pub airgapped: bool,
960
961    /// How updates are delivered.
962    /// - auto: Updates deploy automatically (default)
963    /// - approval-required: Updates wait for explicit approval
964    #[serde(default, skip_serializing_if = "is_default_updates_mode")]
965    pub updates: UpdatesMode,
966
967    /// How telemetry (logs, metrics, traces) is handled.
968    /// - off: No telemetry permissions
969    /// - auto: Telemetry flows automatically (default)
970    /// - approval-required: Telemetry waits for explicit approval
971    #[serde(default, skip_serializing_if = "is_default_telemetry_mode")]
972    pub telemetry: TelemetryMode,
973
974    /// How heartbeat health checks are handled.
975    /// - off: No heartbeat permissions
976    /// - on: Heartbeat enabled (default)
977    #[serde(default, skip_serializing_if = "is_default_heartbeats_mode")]
978    pub heartbeats: HeartbeatsMode,
979
980    /// External bindings for pre-existing infrastructure.
981    /// Allows using existing resources (MinIO, Redis, shared Container Apps
982    /// Environment, etc.) instead of having Alien provision them.
983    /// Required for Kubernetes platform, optional for cloud platforms.
984    #[serde(default, skip_serializing_if = "Option::is_none")]
985    pub external_bindings: Option<crate::ExternalBindings>,
986
987    /// Release signing for this install. When set, setup writes the signing settings
988    /// (the fingerprint, the install's prefix and the channel) where only setup can change
989    /// them, and the install's enforcers run only what the vendor signed. Setup alone writes
990    /// them: changing this later does not change what an install already pinned.
991    #[serde(default, skip_serializing_if = "Option::is_none")]
992    pub signing: Option<StackSigning>,
993}
994
995/// Most entries `StackSettings::endpoint_source_ranges` accepts. A load balancer security group
996/// holds 60 inbound rules by default, and each range needs one rule for port 443 and one for 80.
997pub const MAX_ENDPOINT_SOURCE_RANGES: usize = 25;
998
999/// Checks a list of source address ranges. Each entry must be an IPv4 or IPv6 CIDR written in
1000/// canonical network form (no host bits set, `/0` not allowed because an empty list already
1001/// means anyone), without duplicates, and the list holds at most 25 entries.
1002/// Errors name the offending entry.
1003pub fn validate_endpoint_source_ranges(ranges: &[String]) -> std::result::Result<(), String> {
1004    if ranges.len() > MAX_ENDPOINT_SOURCE_RANGES {
1005        return Err(format!(
1006            "{} source ranges were given; at most {MAX_ENDPOINT_SOURCE_RANGES} are allowed",
1007            ranges.len()
1008        ));
1009    }
1010    let mut seen = std::collections::HashSet::new();
1011    for entry in ranges {
1012        let network: ipnet::IpNet = entry.parse().map_err(|_| {
1013            format!(
1014                "source range '{entry}' is not a valid IPv4 or IPv6 CIDR, such as 203.0.113.0/24"
1015            )
1016        })?;
1017        if network.prefix_len() == 0 {
1018            return Err(format!(
1019                "source range '{entry}' allows every address; leave the list empty to allow anyone"
1020            ));
1021        }
1022        if network.trunc() != network {
1023            return Err(format!(
1024                "source range '{entry}' has host bits set; write it as '{}'",
1025                network.trunc()
1026            ));
1027        }
1028        if network.to_string() != *entry {
1029            return Err(format!(
1030                "source range '{entry}' is not in canonical form; write it as '{network}'"
1031            ));
1032        }
1033        if !seen.insert(network) {
1034            return Err(format!("source range '{entry}' is listed more than once"));
1035        }
1036    }
1037    Ok(())
1038}
1039
1040impl StackSettings {
1041    /// Checks `endpoint_source_ranges`: each entry (see [`validate_endpoint_source_ranges`])
1042    /// and that the deployment's endpoints are reachable from the internet at all.
1043    pub fn validate_endpoint_source_ranges(&self) -> std::result::Result<(), String> {
1044        validate_endpoint_source_ranges(&self.endpoint_source_ranges)?;
1045        if !self.endpoint_source_ranges.is_empty()
1046            && self.endpoint_access == EndpointAccess::Private
1047        {
1048            return Err(format!(
1049                "source range '{}' cannot be used with private endpoint access; \
1050                 private endpoints are reachable only through the deployment network",
1051                self.endpoint_source_ranges[0]
1052            ));
1053        }
1054        Ok(())
1055    }
1056}
1057
1058/// The 12-digit AWS account that publishes the machine images protected installs boot, if this
1059/// build has one. The CLI release workflow writes it into `machine-image-publisher-aws.txt`
1060/// before building, so every build of a release renders the same setup; source builds have none.
1061pub fn machine_image_publisher_aws() -> Option<&'static str> {
1062    let account = include_str!("../machine-image-publisher-aws.txt").trim();
1063    (account.len() == 12 && account.bytes().all(|byte| byte.is_ascii_digit())).then_some(account)
1064}
1065
1066/// The GCP project that publishes the machine images protected installs boot
1067/// (`projects/<project>/global/images/<name>`), if this build has one. The CLI release
1068/// workflow writes it into `machine-image-publisher-gcp.txt`; source builds have none.
1069pub fn machine_image_publisher_gcp() -> Option<&'static str> {
1070    let project = include_str!("../machine-image-publisher-gcp.txt").trim();
1071    (!project.is_empty()
1072        && project.len() <= 30
1073        && project
1074            .bytes()
1075            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-'))
1076    .then_some(project)
1077}
1078
1079/// The public name of the Azure community gallery that publishes the machine images
1080/// protected installs boot (`/CommunityGalleries/<name>/Images/...`), if this build has one.
1081/// The CLI release workflow writes it into `machine-image-publisher-azure.txt`; source builds
1082/// have none.
1083pub fn machine_image_publisher_azure() -> Option<&'static str> {
1084    let gallery = include_str!("../machine-image-publisher-azure.txt").trim();
1085    (!gallery.is_empty()
1086        && gallery.len() <= 100
1087        && gallery
1088            .bytes()
1089            .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-'))
1090    .then_some(gallery)
1091}
1092
1093/// The oldest machine image protected installs boot: an image the cloud records as created
1094/// before this is refused even from the publisher, so a fixed image replaces every older one.
1095/// The CLI release workflow writes it (RFC 3339) into `machine-image-minimum-created.txt` with
1096/// the publisher; a build without it launches no machines on protected installs.
1097pub fn machine_image_minimum_created() -> Option<chrono::DateTime<chrono::Utc>> {
1098    let text = include_str!("../machine-image-minimum-created.txt").trim();
1099    chrono::DateTime::parse_from_rfc3339(text)
1100        .ok()
1101        .map(|time| time.with_timezone(&chrono::Utc))
1102}
1103
1104/// The AWS verifier image protected setups run, as `<repository>@sha256:<64 hex>` in the
1105/// publisher's registry, if this build has one. The CLI release workflow writes it into
1106/// `verifier-image-aws.txt` with the publisher; setups run
1107/// `<publisher>.dkr.ecr.<region>.amazonaws.com/<repository>@<digest>`.
1108pub fn verifier_image_aws() -> Option<&'static str> {
1109    let image = include_str!("../verifier-image-aws.txt").trim();
1110    is_pinned_image(image).then_some(image)
1111}
1112
1113/// The GCP verifier image protected setups run on Cloud Run, as
1114/// `<registry host>/<repository>@sha256:<64 hex>`, if this build has one. The CLI release
1115/// workflow writes it into `verifier-image-gcp.txt`.
1116pub fn verifier_image_gcp() -> Option<&'static str> {
1117    let image = include_str!("../verifier-image-gcp.txt").trim();
1118    is_pinned_image(image).then_some(image)
1119}
1120
1121/// The Azure verifier image protected setups run as a Container App, as
1122/// `<registry host>/<repository>@sha256:<64 hex>` in a registry that serves it without
1123/// credentials, if this build has one. The CLI release workflow writes it into
1124/// `verifier-image-azure.txt`.
1125pub fn verifier_image_azure() -> Option<&'static str> {
1126    let image = include_str!("../verifier-image-azure.txt").trim();
1127    is_pinned_image(image).then_some(image)
1128}
1129
1130/// Whether `image` is `<repository>@sha256:<64 lowercase hex>` with a plain repository path.
1131pub fn is_pinned_image(image: &str) -> bool {
1132    let Some((repository, hex)) = image.split_once("@sha256:") else {
1133        return false;
1134    };
1135    !repository.is_empty()
1136        && repository
1137            .bytes()
1138            .all(|byte| matches!(byte, b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'/'))
1139        && hex.len() == 64
1140        && hex
1141            .bytes()
1142            .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
1143}
1144
1145/// Digest (`sha256:<64 hex>`) of the Operator image protected charts run, if this build has
1146/// one. The CLI release workflow writes it into `operator-digest.txt` with the other pins; it
1147/// is the `operator` digest a signed release names in `components`.
1148pub fn operator_digest() -> Option<&'static str> {
1149    let digest = include_str!("../operator-digest.txt").trim();
1150    let hex = digest.strip_prefix("sha256:")?;
1151    (hex.len() == 64
1152        && hex
1153            .bytes()
1154            .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f')))
1155    .then_some(digest)
1156}
1157
1158/// Values a protected setup pins that come with the CLI build, not with the stack: the account
1159/// whose machine images machines may boot and the verifier image of each cloud. Renders that a release
1160/// records use [`SetupPins::compiled_in`], so every build of one release renders the same
1161/// bytes; tests pin their own.
1162#[derive(Debug, Clone, Default, PartialEq, Eq)]
1163pub struct SetupPins {
1164    /// 12-digit AWS account that publishes machine images and the verifier image.
1165    pub aws_publisher: Option<String>,
1166    /// AWS verifier image, `<repository>@sha256:<64 hex>` in the publisher's registry.
1167    pub aws_verifier_image: Option<String>,
1168    /// GCP verifier image, `<registry host>/<repository>@sha256:<64 hex>`.
1169    pub gcp_verifier_image: Option<String>,
1170    /// Azure verifier image, `<registry host>/<repository>@sha256:<64 hex>`.
1171    pub azure_verifier_image: Option<String>,
1172    /// `sha256:<64 hex>` of the Operator image protected charts run.
1173    pub operator_digest: Option<String>,
1174}
1175
1176impl SetupPins {
1177    /// The pins this build was released with; empty for source builds.
1178    pub fn compiled_in() -> Self {
1179        Self {
1180            aws_publisher: machine_image_publisher_aws().map(str::to_string),
1181            aws_verifier_image: verifier_image_aws().map(str::to_string),
1182            gcp_verifier_image: verifier_image_gcp().map(str::to_string),
1183            azure_verifier_image: verifier_image_azure().map(str::to_string),
1184            operator_digest: operator_digest().map(str::to_string),
1185        }
1186    }
1187}
1188
1189/// What setup pins for a protected install.
1190///
1191/// Take the values from the vendor's install guide or signed release, not from the
1192/// control plane.
1193#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1194#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
1195#[serde(rename_all = "camelCase", deny_unknown_fields)]
1196pub struct StackSigning {
1197    /// `SHA256:<64 hex>` fingerprint of the vendor's signer list version 1.
1198    pub fingerprint: String,
1199    /// Release channel the install follows, such as `production`.
1200    pub channel: String,
1201}
1202
1203impl StackSigning {
1204    /// The settings setup writes for the install whose resource prefix is `prefix`, checked
1205    /// the way enforcers check them when they read them.
1206    pub fn settings(&self, prefix: &str) -> Result<SigningSettings> {
1207        let settings = SigningSettings {
1208            fingerprint: self.fingerprint.clone(),
1209            prefix: prefix.to_string(),
1210            channel: self.channel.clone(),
1211        };
1212        settings.validate().map_err(|error| {
1213            AlienError::new(ErrorData::SigningSettingsInvalid {
1214                reason: error.message,
1215            })
1216        })?;
1217        Ok(settings)
1218    }
1219}
1220
1221/// Whether setup remains a separate administrator operation.
1222#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
1223#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
1224#[serde(rename_all = "camelCase")]
1225pub enum SetupManagement {
1226    /// Setup owns structural infrastructure changes and teardown.
1227    #[default]
1228    Manual,
1229    /// Alien continues managing setup infrastructure with permissions explicitly granted at setup.
1230    Automatic,
1231}
1232
1233impl SetupManagement {
1234    /// Serialized setup parameter value.
1235    pub fn as_str(self) -> &'static str {
1236        match self {
1237            Self::Manual => "manual",
1238            Self::Automatic => "automatic",
1239        }
1240    }
1241}
1242
1243fn is_manual_setup_management(mode: &SetupManagement) -> bool {
1244    *mode == SetupManagement::Manual
1245}
1246
1247fn is_default_deployment_model(model: &DeploymentModel) -> bool {
1248    *model == DeploymentModel::default()
1249}
1250
1251fn is_default_updates_mode(mode: &UpdatesMode) -> bool {
1252    *mode == UpdatesMode::default()
1253}
1254
1255fn is_default_telemetry_mode(mode: &TelemetryMode) -> bool {
1256    *mode == TelemetryMode::default()
1257}
1258
1259fn is_default_heartbeats_mode(mode: &HeartbeatsMode) -> bool {
1260    *mode == HeartbeatsMode::default()
1261}
1262
1263#[cfg(test)]
1264mod failure_domain_tests {
1265    use super::*;
1266
1267    #[test]
1268    fn old_compute_selection_deserializes_without_topology() {
1269        let selection: ComputePoolSelection = serde_json::from_value(serde_json::json!({
1270            "mode": "fixed",
1271            "machines": 2,
1272            "machine": "m7i.xlarge"
1273        }))
1274        .expect("existing selection should deserialize");
1275        assert!(selection.failure_domains().is_none());
1276    }
1277
1278    #[test]
1279    fn rejects_duplicate_concrete_failure_domains() {
1280        let selection = ComputePoolSelection::Fixed {
1281            machines: 2,
1282            machine: Some("m7i.xlarge".to_string()),
1283            failure_domains: Some(FailureDomainSelection {
1284                spread: 2,
1285                selected_failure_domains: vec!["us-west-2a".to_string(); 2],
1286            }),
1287            data_disk_gib: None,
1288        };
1289        assert_eq!(
1290            selection.validate(),
1291            Err("selected failure domains must be unique".to_string())
1292        );
1293    }
1294
1295    #[test]
1296    fn fixed_pool_must_have_one_machine_per_failure_domain() {
1297        let invalid = ComputePoolSelection::Fixed {
1298            machines: 1,
1299            machine: None,
1300            failure_domains: Some(FailureDomainSelection {
1301                spread: 2,
1302                selected_failure_domains: Vec::new(),
1303            }),
1304            data_disk_gib: None,
1305        };
1306        assert_eq!(
1307            invalid.validate(),
1308            Err(
1309                "fixed compute pool machines (1) must be at least failure-domain spread (2)"
1310                    .to_string()
1311            )
1312        );
1313
1314        let valid = ComputePoolSelection::Fixed {
1315            machines: 2,
1316            machine: None,
1317            failure_domains: Some(FailureDomainSelection {
1318                spread: 2,
1319                selected_failure_domains: Vec::new(),
1320            }),
1321            data_disk_gib: None,
1322        };
1323        assert_eq!(valid.validate(), Ok(()));
1324    }
1325
1326    #[test]
1327    fn autoscaling_pool_bounds_must_cover_every_failure_domain() {
1328        let invalid_max = ComputePoolSelection::Autoscale {
1329            min: 1,
1330            max: 1,
1331            machine: None,
1332            failure_domains: Some(FailureDomainSelection {
1333                spread: 2,
1334                selected_failure_domains: Vec::new(),
1335            }),
1336            data_disk_gib: None,
1337        };
1338        assert_eq!(
1339            invalid_max.validate(),
1340            Err(
1341                "autoscaling compute pool maximum (1) must be at least failure-domain spread (2)"
1342                    .to_string()
1343            )
1344        );
1345
1346        let invalid_min = ComputePoolSelection::Autoscale {
1347            min: 1,
1348            max: 3,
1349            machine: None,
1350            failure_domains: Some(FailureDomainSelection {
1351                spread: 2,
1352                selected_failure_domains: Vec::new(),
1353            }),
1354            data_disk_gib: None,
1355        };
1356        assert_eq!(
1357            invalid_min.validate(),
1358            Err(
1359                "autoscaling compute pool minimum (1) must be at least failure-domain spread (2)"
1360                    .to_string()
1361            )
1362        );
1363
1364        let valid = ComputePoolSelection::Autoscale {
1365            min: 2,
1366            max: 2,
1367            machine: None,
1368            failure_domains: Some(FailureDomainSelection {
1369                spread: 2,
1370                selected_failure_domains: Vec::new(),
1371            }),
1372            data_disk_gib: None,
1373        };
1374        assert_eq!(valid.validate(), Ok(()));
1375    }
1376
1377    #[test]
1378    fn machine_public_endpoints_round_trip_without_rewriting_urls() {
1379        let settings: StackSettings = serde_json::from_value(serde_json::json!({
1380            "publicEndpoints": {
1381                "loader": {
1382                    "api": "https://loader.compute.example.com",
1383                    "shares": "https://shares.compute.example.com",
1384                    "webhooks": "https://webhooks.compute.example.com"
1385                }
1386            }
1387        }))
1388        .expect("stack settings should deserialize");
1389
1390        assert_eq!(
1391            serde_json::to_value(settings).expect("stack settings should serialize")
1392                ["publicEndpoints"]["loader"]["shares"],
1393            "https://shares.compute.example.com"
1394        );
1395    }
1396
1397    #[test]
1398    fn custom_domains_preserve_managed_endpoint_names_and_supplied_certificates() {
1399        for config in [
1400            serde_json::json!({
1401                "endpoints": {
1402                    "api": "q7.m2x.example.com",
1403                    "shares": "*.q7.s9t.example.com",
1404                    "webhooks": "*.q7.w3h.example.com"
1405                },
1406                "certificate": {"managed": {}}
1407            }),
1408            serde_json::json!({
1409                "domain": "app.example.com",
1410                "certificate": {"aws": {"certificateArn": "arn:example"}}
1411            }),
1412        ] {
1413            let parsed: CustomDomainConfig = serde_json::from_value(config.clone())
1414                .expect("custom domain configuration should deserialize");
1415            assert_eq!(serde_json::to_value(parsed).unwrap(), config);
1416        }
1417    }
1418}
1419
1420#[cfg(test)]
1421mod endpoint_source_range_tests {
1422    use super::*;
1423
1424    fn ranges(entries: &[&str]) -> Vec<String> {
1425        entries.iter().map(|entry| entry.to_string()).collect()
1426    }
1427
1428    #[test]
1429    fn empty_list_serializes_like_settings_without_the_field() {
1430        // Written by a build before the field existed.
1431        let before = r#"{"endpointAccess":"internet"}"#;
1432        let settings: StackSettings = serde_json::from_str(before).unwrap();
1433        assert!(settings.endpoint_source_ranges.is_empty());
1434        assert_eq!(serde_json::to_string(&settings).unwrap(), before);
1435        assert_eq!(
1436            serde_json::to_value(StackSettings::default()).unwrap(),
1437            serde_json::json!({ "endpointAccess": "internet" })
1438        );
1439    }
1440
1441    #[test]
1442    fn list_round_trips_in_camel_case() {
1443        let settings = StackSettings {
1444            endpoint_source_ranges: ranges(&["203.0.113.0/24", "2001:db8::/32"]),
1445            ..Default::default()
1446        };
1447        let json = serde_json::to_value(&settings).unwrap();
1448        assert_eq!(
1449            json["endpointSourceRanges"],
1450            serde_json::json!(["203.0.113.0/24", "2001:db8::/32"])
1451        );
1452        assert_eq!(
1453            serde_json::from_value::<StackSettings>(json).unwrap(),
1454            settings
1455        );
1456        assert_eq!(settings.validate_endpoint_source_ranges(), Ok(()));
1457    }
1458
1459    #[test]
1460    fn invalid_entries_are_refused_and_named() {
1461        let error =
1462            validate_endpoint_source_ranges(&ranges(&["203.0.113.0/24", "nope"])).unwrap_err();
1463        assert!(error.contains("'nope'"), "{error}");
1464        let error = validate_endpoint_source_ranges(&ranges(&["203.0.113.0"])).unwrap_err();
1465        assert!(error.contains("'203.0.113.0'"), "{error}");
1466    }
1467
1468    #[test]
1469    fn host_bits_are_refused_with_the_network_form() {
1470        let error = validate_endpoint_source_ranges(&ranges(&["203.0.113.5/24"])).unwrap_err();
1471        assert!(
1472            error.contains("'203.0.113.5/24'") && error.contains("203.0.113.0/24"),
1473            "{error}"
1474        );
1475        let error = validate_endpoint_source_ranges(&ranges(&["2001:db8::1/32"])).unwrap_err();
1476        assert!(error.contains("'2001:db8::1/32'"), "{error}");
1477    }
1478
1479    #[test]
1480    fn non_canonical_text_is_refused() {
1481        let error =
1482            validate_endpoint_source_ranges(&ranges(&["2001:0DB8:0:0:0:0:0:0/32"])).unwrap_err();
1483        assert!(
1484            error.contains("canonical") && error.contains("2001:db8::/32"),
1485            "{error}"
1486        );
1487    }
1488
1489    #[test]
1490    fn everything_ranges_are_refused() {
1491        for entry in ["0.0.0.0/0", "::/0"] {
1492            let error = validate_endpoint_source_ranges(&ranges(&[entry])).unwrap_err();
1493            assert!(error.contains(entry), "{error}");
1494        }
1495    }
1496
1497    #[test]
1498    fn duplicates_are_refused_and_named() {
1499        let error =
1500            validate_endpoint_source_ranges(&ranges(&["10.0.0.0/8", "192.0.2.0/24", "10.0.0.0/8"]))
1501                .unwrap_err();
1502        assert!(
1503            error.contains("'10.0.0.0/8'") && error.contains("more than once"),
1504            "{error}"
1505        );
1506    }
1507
1508    #[test]
1509    fn twenty_five_entries_pass_and_twenty_six_do_not() {
1510        let list =
1511            |count: u8| -> Vec<String> { (0..count).map(|i| format!("198.51.{i}.0/24")).collect() };
1512        assert_eq!(validate_endpoint_source_ranges(&list(25)), Ok(()));
1513        let error = validate_endpoint_source_ranges(&list(26)).unwrap_err();
1514        assert!(error.contains("26") && error.contains("25"), "{error}");
1515    }
1516
1517    #[test]
1518    fn private_access_with_a_list_is_refused_and_names_the_entry() {
1519        let settings = StackSettings {
1520            endpoint_access: EndpointAccess::Private,
1521            endpoint_source_ranges: ranges(&["203.0.113.0/24"]),
1522            ..Default::default()
1523        };
1524        let error = settings.validate_endpoint_source_ranges().unwrap_err();
1525        assert!(
1526            error.contains("'203.0.113.0/24'") && error.contains("private"),
1527            "{error}"
1528        );
1529        let private_without_list = StackSettings {
1530            endpoint_access: EndpointAccess::Private,
1531            ..Default::default()
1532        };
1533        assert_eq!(
1534            private_without_list.validate_endpoint_source_ranges(),
1535            Ok(())
1536        );
1537    }
1538}