1use serde::{Deserialize, Serialize};
6use std::collections::HashMap;
7
8use crate::{ErrorData, KubernetesCloudReference, KubernetesClusterOwnership, Result};
9use alien_error::AlienError;
10use alien_signing::SigningSettings;
11
12#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
14#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
15#[serde(rename_all = "camelCase")]
16pub struct AwsManagementConfig {
17 pub managing_role_arn: String,
19}
20
21#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
23#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
24#[serde(rename_all = "camelCase")]
25pub struct GcpManagementConfig {
26 pub service_account_email: String,
28 #[serde(default, skip_serializing_if = "Option::is_none")]
31 pub federation_trust: Option<crate::GcpFederationTrust>,
32}
33
34#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
36#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
37#[serde(rename_all = "camelCase")]
38pub struct AzureManagementConfig {
39 pub managing_tenant_id: String,
41 pub oidc_issuer: String,
43 pub oidc_subject: String,
45}
46
47#[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(AwsManagementConfig),
57 Gcp(GcpManagementConfig),
59 Azure(AzureManagementConfig),
61 Kubernetes,
63}
64
65#[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 #[serde(rename = "use-default")]
98 UseDefault,
99
100 #[serde(rename = "create")]
107 Create {
108 #[serde(skip_serializing_if = "Option::is_none")]
111 cidr: Option<String>,
112
113 #[serde(default = "default_availability_zones")]
115 availability_zones: u8,
116 },
117
118 #[serde(rename = "byo-vpc-aws")]
123 ByoVpcAws {
124 vpc_id: String,
126 #[serde(deserialize_with = "crate::network_ids::deserialize_ids")]
128 public_subnet_ids: Vec<String>,
129 #[serde(deserialize_with = "crate::network_ids::deserialize_ids")]
131 private_subnet_ids: Vec<String>,
132 #[serde(default)]
134 #[serde(deserialize_with = "crate::network_ids::deserialize_ids")]
135 security_group_ids: Vec<String>,
136 },
137
138 #[serde(rename = "byo-vpc-gcp")]
143 ByoVpcGcp {
144 network_name: String,
146 subnet_name: String,
148 region: String,
150 },
151
152 #[serde(rename = "byo-vnet-azure")]
157 ByoVnetAzure {
158 vnet_resource_id: String,
160 public_subnet_name: String,
162 private_subnet_name: String,
164 #[serde(default, skip_serializing_if = "Option::is_none")]
166 application_gateway_subnet_name: Option<String>,
167 #[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
181pub const MAX_CREATED_NETWORK_AVAILABILITY_ZONES: u8 = 8;
185
186#[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 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
197 pub pools: HashMap<String, ComputePoolSelection>,
198 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
200 pub containers: HashMap<String, ContainerResourceSelection>,
201}
202
203#[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 #[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 #[serde(default, skip_serializing_if = "Option::is_none")]
218 pub memory: Option<String>,
219 #[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 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 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#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
264#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
265#[serde(rename_all = "camelCase")]
266pub struct FailureDomainSelection {
267 pub spread: u8,
269 #[serde(default, skip_serializing_if = "Vec::is_empty")]
272 pub selected_failure_domains: Vec<String>,
273}
274
275#[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 {
282 machines: u32,
284 #[serde(
286 default,
287 skip_serializing_if = "Option::is_none",
288 deserialize_with = "deserialize_machine_override"
289 )]
290 machine: Option<String>,
291 #[serde(default, skip_serializing_if = "Option::is_none")]
293 failure_domains: Option<FailureDomainSelection>,
294 #[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 Autoscale {
306 min: u32,
308 max: u32,
310 #[serde(
312 default,
313 skip_serializing_if = "Option::is_none",
314 deserialize_with = "deserialize_machine_override"
315 )]
316 machine: Option<String>,
317 #[serde(default, skip_serializing_if = "Option::is_none")]
319 failure_domains: Option<FailureDomainSelection>,
320 #[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 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 Ok(Option::<String>::deserialize(deserializer)?.filter(|machine| !machine.is_empty()))
358}
359
360impl ComputePoolSelection {
361 pub fn machine(&self) -> Option<&str> {
363 match self {
364 Self::Fixed { machine, .. } | Self::Autoscale { machine, .. } => machine.as_deref(),
365 }
366 }
367
368 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 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 pub fn min_size(&self) -> u32 {
391 match self {
392 Self::Fixed { machines, .. } => *machines,
393 Self::Autoscale { min, .. } => *min,
394 }
395 }
396
397 pub fn max_size(&self) -> u32 {
399 match self {
400 Self::Fixed { machines, .. } => *machines,
401 Self::Autoscale { max, .. } => *max,
402 }
403 }
404
405 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#[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 #[default]
476 Push,
477 Pull,
480}
481
482#[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 #[default]
489 Auto,
490 ApprovalRequired,
492}
493
494#[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 Off,
501 #[default]
503 Auto,
504 ApprovalRequired,
506}
507
508impl TelemetryMode {
509 pub fn is_enabled(&self) -> bool {
511 !matches!(self, TelemetryMode::Off)
512 }
513}
514
515#[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 Off,
522 #[default]
524 On,
525}
526
527impl HeartbeatsMode {
528 pub fn is_enabled(&self) -> bool {
530 matches!(self, HeartbeatsMode::On)
531 }
532}
533
534#[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 #[default]
541 Internet,
542 Private,
544}
545
546impl EndpointAccess {
547 pub fn as_str(self) -> &'static str {
549 match self {
550 Self::Internet => "internet",
551 Self::Private => "private",
552 }
553 }
554}
555
556#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
561#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
562#[serde(rename_all = "camelCase")]
563pub struct DomainSettings {
564 #[serde(default, skip_serializing_if = "Option::is_none")]
566 pub custom_domains: Option<HashMap<String, CustomDomainConfig>>,
567 #[serde(default, skip_serializing_if = "Option::is_none")]
573 pub public_endpoint_target: Option<PublicEndpointTargetSettings>,
574}
575
576#[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 MachineAddresses,
583 #[serde(rename_all = "camelCase")]
585 LoadBalancer {
586 cname_target: String,
588 },
589}
590
591#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
593#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
594#[serde(rename_all = "camelCase")]
595pub struct CustomDomainConfig {
596 #[serde(default, skip_serializing_if = "String::is_empty")]
598 pub domain: String,
599 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
601 pub endpoints: HashMap<String, String>,
602 pub certificate: CustomCertificateConfig,
604}
605
606#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
613 pub managed: Option<ManagedCustomCertificateConfig>,
614 #[serde(default, skip_serializing_if = "Option::is_none")]
616 pub aws: Option<AwsCustomCertificateConfig>,
617 #[serde(default, skip_serializing_if = "Option::is_none")]
619 pub gcp: Option<GcpCustomCertificateConfig>,
620 #[serde(default, skip_serializing_if = "Option::is_none")]
622 pub azure: Option<AzureCustomCertificateConfig>,
623 #[serde(default, skip_serializing_if = "Option::is_none")]
625 pub kubernetes: Option<KubernetesCustomCertificateConfig>,
626}
627
628#[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 pub tls_secret_ref: KubernetesTlsSecretRef,
663}
664
665#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
672#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
673#[serde(rename_all = "camelCase")]
674pub struct KubernetesSettings {
675 #[serde(default, skip_serializing_if = "Option::is_none")]
677 pub cluster: Option<KubernetesClusterSettings>,
678 #[serde(default, skip_serializing_if = "Option::is_none")]
680 pub exposure: Option<KubernetesExposureSettings>,
681}
682
683#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
685#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
686#[serde(rename_all = "camelCase")]
687pub struct KubernetesClusterSettings {
688 pub ownership: KubernetesClusterOwnership,
691 #[serde(default, skip_serializing_if = "Option::is_none")]
693 pub namespace: Option<String>,
694 #[serde(default, skip_serializing_if = "Option::is_none")]
696 pub cloud: Option<KubernetesCloudReference>,
697}
698
699#[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 Disabled,
706 Generated {
708 route: KubernetesRouteProfile,
710 certificate: KubernetesCertificateMode,
712 },
713 Custom {
715 domain: String,
717 route: KubernetesRouteProfile,
719 certificate: KubernetesCertificateMode,
721 },
722 #[serde(rename_all = "camelCase")]
724 CustomBaseDomain {
725 base_domain: String,
727 route: KubernetesRouteProfile,
729 certificate: KubernetesCertificateMode,
731 },
732}
733
734#[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 Ingress(KubernetesIngressRouteProfile),
741 Gateway(KubernetesGatewayRouteProfile),
743}
744
745#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
752 pub controller: Option<String>,
753 pub ingress_class_name: String,
755 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
757 pub labels: HashMap<String, String>,
758 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
760 pub annotations: HashMap<String, String>,
761 #[serde(default, skip_serializing_if = "Option::is_none")]
763 pub provider: Option<KubernetesRouteProviderOptions>,
764}
765
766#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
773 pub controller: Option<String>,
774 pub gateway_class_name: String,
776 pub listener_port: u16,
778 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
780 pub labels: HashMap<String, String>,
781 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
783 pub annotations: HashMap<String, String>,
784 #[serde(default, skip_serializing_if = "Option::is_none")]
786 pub provider: Option<KubernetesRouteProviderOptions>,
787}
788
789#[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 #[serde(rename_all = "camelCase")]
796 AwsAlb {
797 scheme: String,
799 target_type: String,
801 #[serde(default, skip_serializing_if = "Option::is_none")]
803 ip_address_type: Option<String>,
804 #[serde(default, skip_serializing_if = "Vec::is_empty")]
806 subnet_ids: Vec<String>,
807 },
808 #[serde(rename_all = "camelCase")]
810 GkeGateway {
811 #[serde(default, skip_serializing_if = "Option::is_none")]
813 static_address_name: Option<String>,
814 },
815 #[serde(rename_all = "camelCase")]
817 AzureApplicationGatewayForContainers {
818 #[serde(default, skip_serializing_if = "Option::is_none")]
820 alb_namespace: Option<String>,
821 #[serde(default, skip_serializing_if = "Option::is_none")]
823 alb_name: Option<String>,
824 frontend: String,
826 },
827}
828
829#[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 #[serde(rename_all = "camelCase")]
836 ManagedAcmImport {
837 #[serde(default, skip_serializing_if = "Option::is_none")]
839 region: Option<String>,
840 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
842 tags: HashMap<String, String>,
843 },
844 #[serde(rename_all = "camelCase")]
846 AwsAcmArn {
847 certificate_arn: String,
849 },
850 #[serde(rename_all = "camelCase")]
852 ManagedTlsSecret {
853 secret_name_template: String,
855 },
856 TlsSecretRef(KubernetesTlsSecretRef),
858 None,
860}
861
862#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
864#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
865#[serde(rename_all = "camelCase")]
866pub struct KubernetesTlsSecretRef {
867 pub secret_name: String,
869 #[serde(default, skip_serializing_if = "Option::is_none")]
871 pub namespace: Option<String>,
872}
873
874#[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 #[serde(default, skip_serializing_if = "is_manual_setup_management")]
889 pub setup_management: SetupManagement,
890 #[serde(default, skip_serializing_if = "Vec::is_empty")]
894 pub quota_warning_overrides: Vec<String>,
895
896 #[serde(default)]
899 pub endpoint_access: EndpointAccess,
900
901 #[serde(default, skip_serializing_if = "Vec::is_empty")]
906 pub endpoint_source_ranges: Vec<String>,
907
908 #[serde(default, skip_serializing_if = "Option::is_none")]
915 pub network: Option<NetworkSettings>,
916
917 #[serde(default, skip_serializing_if = "Option::is_none")]
919 pub domains: Option<DomainSettings>,
920
921 #[serde(default, skip_serializing_if = "Option::is_none")]
923 pub kubernetes: Option<KubernetesSettings>,
924
925 #[serde(default, skip_serializing_if = "Option::is_none")]
931 pub compute: Option<ComputeSettings>,
932
933 #[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 #[serde(default, skip_serializing_if = "is_default_deployment_model")]
954 pub deployment_model: DeploymentModel,
955
956 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
959 pub airgapped: bool,
960
961 #[serde(default, skip_serializing_if = "is_default_updates_mode")]
965 pub updates: UpdatesMode,
966
967 #[serde(default, skip_serializing_if = "is_default_telemetry_mode")]
972 pub telemetry: TelemetryMode,
973
974 #[serde(default, skip_serializing_if = "is_default_heartbeats_mode")]
978 pub heartbeats: HeartbeatsMode,
979
980 #[serde(default, skip_serializing_if = "Option::is_none")]
985 pub external_bindings: Option<crate::ExternalBindings>,
986
987 #[serde(default, skip_serializing_if = "Option::is_none")]
992 pub signing: Option<StackSigning>,
993}
994
995pub const MAX_ENDPOINT_SOURCE_RANGES: usize = 25;
998
999pub 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 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
1058pub 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
1066pub 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
1079pub 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
1093pub 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
1104pub 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
1113pub 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
1121pub 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
1130pub 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
1145pub 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#[derive(Debug, Clone, Default, PartialEq, Eq)]
1163pub struct SetupPins {
1164 pub aws_publisher: Option<String>,
1166 pub aws_verifier_image: Option<String>,
1168 pub gcp_verifier_image: Option<String>,
1170 pub azure_verifier_image: Option<String>,
1172 pub operator_digest: Option<String>,
1174}
1175
1176impl SetupPins {
1177 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#[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 pub fingerprint: String,
1199 pub channel: String,
1201}
1202
1203impl StackSigning {
1204 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#[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 #[default]
1228 Manual,
1229 Automatic,
1231}
1232
1233impl SetupManagement {
1234 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 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}