1use crate::{
2 is_prepared_cluster, ownership_policy_for_resource_type, ComputeCluster, ErrorData, Key,
3 KubernetesCluster, KubernetesClusterOwnership, ManagementPermissions, NetworkSettings,
4 Platform, ResourceEntry, ResourceLifecycle, Result, Sandbox, SetupManagement, Stack,
5 StackSettings, Storage,
6};
7use alien_error::AlienError;
8
9pub fn validate_automatic_setup_resources(
12 stack: &Stack,
13 platform: Platform,
14 management: SetupManagement,
15) -> Result<()> {
16 if management == SetupManagement::Automatic
17 && matches!(platform, Platform::Aws | Platform::Gcp | Platform::Azure)
18 {
19 let unsupported = |resource_type: &str, resource_id: &str| {
20 AlienError::new(ErrorData::AutomaticSetupResourceUnsupported {
21 resource_type: resource_type.to_string(),
22 resource_id: resource_id.to_string(),
23 platform,
24 })
25 };
26 match stack.management() {
27 ManagementPermissions::Override(_) => {
29 return Err(unsupported(
30 "management permission override",
31 "permissions.management",
32 ));
33 }
34 ManagementPermissions::Extend(profile) if platform == Platform::Aws => {
37 if let Some(scope) = profile.0.keys().find(|scope| scope.as_str() != "*") {
38 return Err(unsupported("resource-scoped management permission", scope));
39 }
40 }
41 _ => {}
42 }
43 for (id, entry) in stack.resources() {
44 if let Some(resource_type) = automatic_setup_unsupported_resource(entry, platform) {
45 return Err(unsupported(&resource_type, id));
46 }
47 }
48 }
49 if management == SetupManagement::Automatic && platform == Platform::Azure {
50 for (id, entry) in stack.resources() {
51 if entry.config.downcast_ref::<Sandbox>().is_some() {
52 return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
53 capability: format!(
54 "automatic infrastructure management for sandbox '{id}'; use manual setup to create and import its sandbox group"
55 ),
56 platform: platform.to_string(),
57 }));
58 }
59 }
60 }
61 Ok(())
62}
63
64fn automatic_setup_unsupported_resource(
67 entry: &ResourceEntry,
68 platform: Platform,
69) -> Option<String> {
70 if entry.config.downcast_ref::<Key>().is_some() {
71 return Some("key".to_string());
72 }
73 let resource_type = entry.config.resource_type();
74 if matches!(
76 resource_type.as_ref(),
77 "email" | "experimental/aws-opensearch" | "kubernetes-cluster"
78 ) {
79 return Some(resource_type.as_ref().to_string());
80 }
81 if platform == Platform::Azure
84 && entry
85 .config
86 .downcast_ref::<Storage>()
87 .is_some_and(|storage| storage.has_cors())
88 {
89 return Some("storage with CORS origins".to_string());
90 }
91 None
92}
93
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97pub enum SetupConfigurationProfile {
98 Standard,
99 Advanced,
100}
101
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109pub struct SetupTarget {
110 pub deployment_platform: Platform,
112 pub cloud_platform: Platform,
114}
115
116impl SetupTarget {
117 pub fn new(deployment_platform: Platform, base_platform: Option<Platform>) -> Self {
119 Self {
120 deployment_platform,
121 cloud_platform: base_platform.unwrap_or(deployment_platform),
122 }
123 }
124
125 pub fn from_cloud(cloud_platform: Platform, targets_kubernetes: bool) -> Self {
127 Self {
128 deployment_platform: if targets_kubernetes {
129 Platform::Kubernetes
130 } else {
131 cloud_platform
132 },
133 cloud_platform,
134 }
135 }
136
137 pub fn is_kubernetes(&self) -> bool {
138 self.deployment_platform == Platform::Kubernetes
139 }
140}
141
142pub fn is_kubernetes_native_resource_type(resource_type: &crate::ResourceType) -> bool {
150 *resource_type == Sandbox::RESOURCE_TYPE || *resource_type == ComputeCluster::RESOURCE_TYPE
151}
152
153pub fn is_network_database(entry: &ResourceEntry) -> bool {
160 let resource_type = entry.config.resource_type();
161 resource_type == crate::Postgres::RESOURCE_TYPE || resource_type == crate::Redis::RESOURCE_TYPE
162}
163
164pub fn existing_cluster_network_hosts(entry: &ResourceEntry, cloud_platform: Platform) -> bool {
175 if !is_network_database(entry) {
176 return true;
177 }
178 entry.config.resource_type() == crate::Postgres::RESOURCE_TYPE
179 && cloud_platform == Platform::Gcp
180}
181
182pub fn existing_cluster_network_refusal(
186 resource_type: &str,
187 resource_id: &str,
188 network_hint: Option<&str>,
189) -> String {
190 let hint = network_hint
191 .map(|hint| format!(" {hint},"))
192 .unwrap_or_default();
193 format!(
194 "Setup cannot yet place the {resource_type} '{resource_id}' on an existing cluster's network, so the cluster could not reach it. Use a cluster that setup creates,{hint} or remove the {resource_type}."
195 )
196}
197
198pub fn setup_targets_existing_cluster(stack: &Stack, settings: &StackSettings) -> bool {
202 let ownership = stack
203 .resources()
204 .filter(|(id, entry)| !is_prepared_cluster(id, entry))
205 .find_map(|(_, entry)| entry.config.downcast_ref::<KubernetesCluster>())
206 .map(|cluster| cluster.ownership)
207 .or_else(|| {
208 settings
209 .kubernetes
210 .as_ref()
211 .and_then(|kubernetes| kubernetes.cluster.as_ref())
212 .map(|cluster| cluster.ownership)
213 });
214 ownership.is_some_and(|ownership| ownership != KubernetesClusterOwnership::Managed)
215}
216
217pub fn refuse_unreachable_databases(
223 stack: &Stack,
224 settings: &StackSettings,
225 cloud_platform: Platform,
226 network_hint: Option<&str>,
227 creates: impl Fn(&ResourceEntry) -> bool,
228) -> Result<()> {
229 if !setup_targets_existing_cluster(stack, settings)
230 || matches!(
231 settings.network,
232 Some(
233 NetworkSettings::ByoVpcAws { .. }
234 | NetworkSettings::ByoVpcGcp { .. }
235 | NetworkSettings::ByoVnetAzure { .. }
236 )
237 )
238 {
239 return Ok(());
240 }
241 for (id, entry) in stack.resources() {
242 if entry.enabled_when.is_none()
245 && !existing_cluster_network_hosts(entry, cloud_platform)
246 && creates(entry)
247 {
248 return Err(AlienError::new(ErrorData::SetupPlacementUnsupported {
249 message: existing_cluster_network_refusal(
250 entry.config.resource_type().as_ref(),
251 id,
252 network_hint,
253 ),
254 resource_type: entry.config.resource_type().to_string(),
255 resource_id: id.to_string(),
256 }));
257 }
258 }
259 Ok(())
260}
261
262pub fn emits_package_scaffolding(
281 entry: &ResourceEntry,
282 management: SetupManagement,
283 target: SetupTarget,
284) -> bool {
285 let resource_type = entry.config.resource_type();
286 if target.is_kubernetes() && is_kubernetes_native_resource_type(&resource_type) {
287 return false;
288 }
289 if management == SetupManagement::Automatic {
290 is_automatic_setup_package_resource_type(resource_type.as_ref(), target.cloud_platform)
291 } else {
292 ownership_policy_for_resource_type(resource_type.as_ref())
293 .emits_setup_scaffolding(entry.lifecycle)
294 }
295}
296
297pub fn is_automatic_setup_package_resource_type(resource_type: &str, platform: Platform) -> bool {
301 matches!(
302 resource_type,
303 "remote-stack-management" | "vault" | "azure_resource_group" | "service_activation"
304 ) || (platform == Platform::Azure
305 && matches!(resource_type, "service-account" | "resource-access"))
306}
307
308pub fn removed_by_runtime_cleanup(
317 resource_type: &str,
318 lifecycle: ResourceLifecycle,
319 management: SetupManagement,
320 platform: Platform,
321) -> bool {
322 if management == SetupManagement::Automatic {
323 return !is_automatic_setup_package_resource_type(resource_type, platform);
324 }
325 lifecycle == ResourceLifecycle::Live
326 || ownership_policy_for_resource_type(resource_type).has_runtime_cleanup_before_teardown()
327}
328
329#[cfg(test)]
330mod cors_tests {
331 use super::*;
332
333 #[test]
334 fn automatic_cors_requires_an_implementing_controller() {
335 let stack = Stack::new("browser-storage".into())
336 .add(
337 Storage::new("assets".into())
338 .cors_allowed_origins(vec!["https://app.example.com".into()])
339 .build(),
340 ResourceLifecycle::Live,
341 )
342 .build();
343 for platform in [Platform::Aws, Platform::Gcp] {
344 validate_automatic_setup_resources(&stack, platform, SetupManagement::Automatic)
345 .unwrap();
346 }
347 let error =
348 validate_automatic_setup_resources(&stack, Platform::Azure, SetupManagement::Automatic)
349 .unwrap_err();
350 assert!(matches!(
351 error.error,
352 Some(ErrorData::AutomaticSetupResourceUnsupported { .. })
353 ));
354 }
355}