1use crate::{
2 is_prepared_cluster, ownership_policy_for_resource_type, Build, ComputeCluster, Container,
3 CustomResource, Daemon, ErrorData, Key, KubernetesCluster, KubernetesClusterOwnership,
4 ManagementPermissions, NetworkSettings, Platform, ResourceEntry, ResourceLifecycle,
5 ResourceRef, ResourceType, Result, Sandbox, SetupManagement, Stack, StackSettings, Storage,
6 Worker,
7};
8use alien_error::AlienError;
9
10fn is_granted_on(stack: &Stack, id: &str, resource_type: &ResourceType) -> bool {
13 let links_sets = stack
15 .descriptor(resource_type)
16 .is_some_and(|descriptor| !descriptor.link.permission_sets.is_empty());
17 let linked = |links: &[ResourceRef]| links_sets && links.iter().any(|link| link.id == id);
18 stack
19 .permissions
20 .profiles
21 .values()
22 .any(|profile| profile.0.get(id).is_some_and(|sets| !sets.is_empty()))
23 || stack.resources().any(|(_, entry)| {
24 let config = &entry.config;
25 config
26 .downcast_ref::<Worker>()
27 .is_some_and(|w| linked(&w.links))
28 || config
29 .downcast_ref::<Container>()
30 .is_some_and(|c| linked(&c.links))
31 || config
32 .downcast_ref::<Daemon>()
33 .is_some_and(|d| d.permissions.is_some() && linked(&d.links))
34 || config
35 .downcast_ref::<Build>()
36 .is_some_and(|b| linked(&b.links))
37 })
38}
39
40pub fn validate_automatic_setup_resources(
43 stack: &Stack,
44 platform: Platform,
45 management: SetupManagement,
46) -> Result<()> {
47 if management == SetupManagement::Automatic
48 && matches!(platform, Platform::Aws | Platform::Gcp | Platform::Azure)
49 {
50 let unsupported = |resource_type: &str, resource_id: &str| {
51 AlienError::new(ErrorData::AutomaticSetupResourceUnsupported {
52 resource_type: resource_type.to_string(),
53 resource_id: resource_id.to_string(),
54 platform,
55 })
56 };
57 match stack.management() {
58 ManagementPermissions::Override(_) => {
60 return Err(unsupported(
61 "management permission override",
62 "permissions.management",
63 ));
64 }
65 ManagementPermissions::Extend(profile) if platform == Platform::Aws => {
68 if let Some(scope) = profile.0.keys().find(|scope| scope.as_str() != "*") {
69 return Err(unsupported("resource-scoped management permission", scope));
70 }
71 }
72 _ => {}
73 }
74 for (id, entry) in stack.resources() {
75 if let Some(resource_type) = automatic_setup_unsupported_resource(entry, platform) {
76 return Err(unsupported(&resource_type, id));
77 }
78 if platform == Platform::Aws
81 && entry.config.downcast_ref::<CustomResource>().is_some()
82 && is_granted_on(stack, id, &entry.config.resource_type())
83 {
84 return Err(unsupported("custom resource grant", id));
85 }
86 }
87 }
88 if management == SetupManagement::Automatic && platform == Platform::Azure {
89 for (id, entry) in stack.resources() {
90 if entry.config.downcast_ref::<Sandbox>().is_some() {
91 return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
92 capability: format!(
93 "automatic infrastructure management for sandbox '{id}'; use manual setup to create and import its sandbox group"
94 ),
95 platform: platform.to_string(),
96 }));
97 }
98 }
99 }
100 Ok(())
101}
102
103fn automatic_setup_unsupported_resource(
106 entry: &ResourceEntry,
107 platform: Platform,
108) -> Option<String> {
109 if entry.config.downcast_ref::<Key>().is_some() {
110 return Some("key".to_string());
111 }
112 let resource_type = entry.config.resource_type();
113 if matches!(
115 resource_type.as_ref(),
116 "email" | "experimental/aws-opensearch" | "kubernetes-cluster"
117 ) {
118 return Some(resource_type.as_ref().to_string());
119 }
120 if platform == Platform::Azure
123 && entry
124 .config
125 .downcast_ref::<Storage>()
126 .is_some_and(|storage| storage.has_cors())
127 {
128 return Some("storage with CORS origins".to_string());
129 }
130 None
131}
132
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
136pub enum SetupConfigurationProfile {
137 Standard,
138 Advanced,
139}
140
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
148pub struct SetupTarget {
149 pub deployment_platform: Platform,
151 pub cloud_platform: Platform,
153}
154
155impl SetupTarget {
156 pub fn new(deployment_platform: Platform, base_platform: Option<Platform>) -> Self {
158 Self {
159 deployment_platform,
160 cloud_platform: base_platform.unwrap_or(deployment_platform),
161 }
162 }
163
164 pub fn from_cloud(cloud_platform: Platform, targets_kubernetes: bool) -> Self {
166 Self {
167 deployment_platform: if targets_kubernetes {
168 Platform::Kubernetes
169 } else {
170 cloud_platform
171 },
172 cloud_platform,
173 }
174 }
175
176 pub fn is_kubernetes(&self) -> bool {
177 self.deployment_platform == Platform::Kubernetes
178 }
179}
180
181pub fn is_kubernetes_native_resource_type(resource_type: &crate::ResourceType) -> bool {
189 *resource_type == Sandbox::RESOURCE_TYPE || *resource_type == ComputeCluster::RESOURCE_TYPE
190}
191
192pub fn is_network_database(entry: &ResourceEntry) -> bool {
199 let resource_type = entry.config.resource_type();
200 resource_type == crate::Postgres::RESOURCE_TYPE || resource_type == crate::Redis::RESOURCE_TYPE
201}
202
203pub fn keeps_cloud_network(stack: &Stack, entry: &ResourceEntry) -> bool {
208 is_network_database(entry)
209 || stack
210 .descriptor(&entry.config.resource_type())
211 .is_some_and(|descriptor| descriptor.requires_network)
212}
213
214pub fn existing_cluster_network_hosts(entry: &ResourceEntry, cloud_platform: Platform) -> bool {
226 if !is_network_database(entry) {
227 return true;
228 }
229 entry.config.resource_type() == crate::Postgres::RESOURCE_TYPE
230 && cloud_platform == Platform::Gcp
231}
232
233pub fn existing_cluster_network_refusal(
237 resource_type: &str,
238 resource_id: &str,
239 network_hint: Option<&str>,
240) -> String {
241 let hint = network_hint
242 .map(|hint| format!(" {hint},"))
243 .unwrap_or_default();
244 format!(
245 "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}."
246 )
247}
248
249pub fn setup_targets_existing_cluster(stack: &Stack, settings: &StackSettings) -> bool {
253 let ownership = stack
254 .resources()
255 .filter(|(id, entry)| !is_prepared_cluster(id, entry))
256 .find_map(|(_, entry)| entry.config.downcast_ref::<KubernetesCluster>())
257 .map(|cluster| cluster.ownership)
258 .or_else(|| {
259 settings
260 .kubernetes
261 .as_ref()
262 .and_then(|kubernetes| kubernetes.cluster.as_ref())
263 .map(|cluster| cluster.ownership)
264 });
265 ownership.is_some_and(|ownership| ownership != KubernetesClusterOwnership::Managed)
266}
267
268pub fn refuse_unreachable_databases(
274 stack: &Stack,
275 settings: &StackSettings,
276 cloud_platform: Platform,
277 network_hint: Option<&str>,
278 creates: impl Fn(&ResourceEntry) -> bool,
279) -> Result<()> {
280 if !setup_targets_existing_cluster(stack, settings)
281 || matches!(
282 settings.network,
283 Some(
284 NetworkSettings::ByoVpcAws { .. }
285 | NetworkSettings::ByoVpcGcp { .. }
286 | NetworkSettings::ByoVnetAzure { .. }
287 )
288 )
289 {
290 return Ok(());
291 }
292 for (id, entry) in stack.resources() {
293 if entry.enabled_when.is_none()
296 && !existing_cluster_network_hosts(entry, cloud_platform)
297 && creates(entry)
298 {
299 return Err(AlienError::new(ErrorData::SetupPlacementUnsupported {
300 message: existing_cluster_network_refusal(
301 entry.config.resource_type().as_ref(),
302 id,
303 network_hint,
304 ),
305 resource_type: entry.config.resource_type().to_string(),
306 resource_id: id.to_string(),
307 }));
308 }
309 }
310 Ok(())
311}
312
313pub fn refuse_declinable_network_extensions(stack: &Stack, settings: &StackSettings) -> Result<()> {
322 if !setup_targets_existing_cluster(stack, settings)
323 || matches!(
324 settings.network,
325 Some(
326 NetworkSettings::ByoVpcAws { .. }
327 | NetworkSettings::ByoVpcGcp { .. }
328 | NetworkSettings::ByoVnetAzure { .. }
329 )
330 )
331 {
332 return Ok(());
333 }
334 let frozen_gating: std::collections::HashSet<&str> = crate::frozen_gated(stack)
335 .map(|(_, input_id)| input_id)
336 .collect();
337 let declinable = |entry: &ResourceEntry| {
338 entry
339 .enabled_when
340 .as_deref()
341 .is_some_and(|input_id| frozen_gating.contains(input_id))
342 };
343 if stack
344 .resources()
345 .any(|(_, entry)| keeps_cloud_network(stack, entry) && !declinable(entry))
346 {
347 return Ok(());
348 }
349 for (id, entry) in stack.resources() {
350 if is_network_database(entry) || !keeps_cloud_network(stack, entry) || !declinable(entry) {
351 continue;
352 }
353 let resource_type = entry.config.resource_type();
354 let input_id = entry.enabled_when.as_deref().unwrap_or_default();
355 return Err(AlienError::new(ErrorData::SetupPlacementUnsupported {
356 message: format!(
357 "Setup cannot yet place the {resource_type} '{id}' on an existing cluster while its input '{input_id}' also turns off a resource setup creates, because the network it requires is fixed when the template is rendered. Use a cluster that setup creates, bring the cluster's own network in the stack's network settings, give the {resource_type} an input that turns off only resources the runtime creates, or remove its input."
358 ),
359 resource_type: resource_type.to_string(),
360 resource_id: id.to_string(),
361 }));
362 }
363 Ok(())
364}
365
366pub fn emits_package_scaffolding(
385 entry: &ResourceEntry,
386 management: SetupManagement,
387 target: SetupTarget,
388) -> bool {
389 let resource_type = entry.config.resource_type();
390 if target.is_kubernetes() && is_kubernetes_native_resource_type(&resource_type) {
391 return false;
392 }
393 if management == SetupManagement::Automatic {
394 is_automatic_setup_package_resource_type(resource_type.as_ref(), target.cloud_platform)
395 } else {
396 ownership_policy_for_resource_type(resource_type.as_ref())
397 .emits_setup_scaffolding(entry.lifecycle)
398 }
399}
400
401pub fn is_automatic_setup_package_resource_type(resource_type: &str, platform: Platform) -> bool {
405 matches!(
406 resource_type,
407 "remote-stack-management" | "vault" | "azure_resource_group" | "service_activation"
408 ) || (platform == Platform::Azure
409 && matches!(resource_type, "service-account" | "resource-access"))
410}
411
412pub fn removed_by_runtime_cleanup(
421 resource_type: &str,
422 lifecycle: ResourceLifecycle,
423 management: SetupManagement,
424 platform: Platform,
425) -> bool {
426 if management == SetupManagement::Automatic {
427 return !is_automatic_setup_package_resource_type(resource_type, platform);
428 }
429 lifecycle == ResourceLifecycle::Live
430 || ownership_policy_for_resource_type(resource_type).has_runtime_cleanup_before_teardown()
431}
432
433#[cfg(test)]
434mod cors_tests {
435 use super::*;
436
437 #[test]
438 fn automatic_cors_requires_an_implementing_controller() {
439 let stack = Stack::new("browser-storage".into())
440 .add(
441 Storage::new("assets".into())
442 .cors_allowed_origins(vec!["https://app.example.com".into()])
443 .build(),
444 ResourceLifecycle::Live,
445 )
446 .build();
447 for platform in [Platform::Aws, Platform::Gcp] {
448 validate_automatic_setup_resources(&stack, platform, SetupManagement::Automatic)
449 .unwrap();
450 }
451 let error =
452 validate_automatic_setup_resources(&stack, Platform::Azure, SetupManagement::Automatic)
453 .unwrap_err();
454 assert!(matches!(
455 error.error,
456 Some(ErrorData::AutomaticSetupResourceUnsupported { .. })
457 ));
458 }
459}
460
461#[cfg(test)]
462mod custom_resource_grant_tests {
463 use super::*;
464 use crate::{ResourceType, WorkerCode};
465
466 fn linked_zone() -> Stack {
467 let zone =
468 CustomResource::from_untagged("acme/dns-zone", serde_json::json!({ "id": "zone" }))
469 .unwrap();
470 let mut api = Worker::new("api".to_string())
471 .code(WorkerCode::Image {
472 image: "registry.example.com/api:1".to_string(),
473 })
474 .permissions("api".to_string())
475 .build();
476 api.links.push(ResourceRef::new(
477 ResourceType::from("acme/dns-zone"),
478 "zone",
479 ));
480 let mut stack = Stack::new("app".to_string())
481 .add(zone, ResourceLifecycle::Live)
482 .add(api, ResourceLifecycle::Live)
483 .build();
484 stack
485 .extensions
486 .push(acme(&["acme/dns-zone/records-write"]));
487 stack
488 }
489
490 fn acme(link_sets: &[&str]) -> crate::ExtensionManifest {
492 serde_json::from_value(serde_json::json!({
493 "name": "acme", "version": "1.0.0", "digest": "sha256:0",
494 "resourceTypes": { "acme/dns-zone": {
495 "lifecycles": ["live"], "holdsData": false,
496 "setup": { "cloudformation": [], "terraform": [], "helm": [], "importers": [] },
497 "controllerPlatforms": ["aws"], "permissionSets": [],
498 "link": { "permissionSets": link_sets },
499 "schemas": { "config": {}, "outputs": {} }
500 }}
501 }))
502 .unwrap()
503 }
504
505 #[test]
508 fn automatic_setup_on_aws_refuses_a_grant_on_a_custom_resource() {
509 let error = validate_automatic_setup_resources(
510 &linked_zone(),
511 Platform::Aws,
512 SetupManagement::Automatic,
513 )
514 .expect_err("the link is refused");
515 assert_eq!(
516 error.code, "AUTOMATIC_SETUP_RESOURCE_UNSUPPORTED",
517 "{error}"
518 );
519 assert!(error.to_string().contains("'zone'"), "{error}");
520 assert!(!error.retryable);
521
522 let mut scoped = linked_zone();
524 let api = scoped.resources.get_mut("api").unwrap();
525 api.config.downcast_mut::<Worker>().unwrap().links.clear();
526 scoped.permissions.profiles.insert(
527 "api".to_string(),
528 serde_json::from_value(serde_json::json!({ "zone": ["acme/dns-zone/records-write"] }))
529 .unwrap(),
530 );
531 validate_automatic_setup_resources(&scoped, Platform::Aws, SetupManagement::Automatic)
532 .expect_err("the profile's grant is refused");
533
534 let mut unlinked = linked_zone();
535 unlinked.resources.shift_remove("api");
536 let mut no_link_sets = linked_zone();
538 no_link_sets.extensions = vec![acme(&[])];
539 for (stack, platform, management) in [
540 (linked_zone(), Platform::Aws, SetupManagement::Manual),
541 (linked_zone(), Platform::Gcp, SetupManagement::Automatic),
542 (unlinked, Platform::Aws, SetupManagement::Automatic),
543 (no_link_sets, Platform::Aws, SetupManagement::Automatic),
544 ] {
545 validate_automatic_setup_resources(&stack, platform, management)
546 .unwrap_or_else(|error| panic!("{platform:?} {management:?}: {error}"));
547 }
548 }
549}