Skip to main content

alien_core/
setup_package.rs

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
10/// Whether a permission profile scopes sets to `id`, or a workload with a profile links it and
11/// its type links sets, as `ResourceLinkPermissionsMutation` grants them.
12fn is_granted_on(stack: &Stack, id: &str, resource_type: &ResourceType) -> bool {
13    // A type no extension defines links nothing, as the mutation skips its links.
14    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
40/// Refuse resources whose setup-owned scaffolding cannot yet be created by runtime.
41/// Check both package generation and deployment planning, including later additions.
42pub 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            // Setup must be able to grant whatever a later release adds.
59            ManagementPermissions::Override(_) => {
60                return Err(unsupported(
61                    "management permission override",
62                    "permissions.management",
63                ));
64            }
65            // The AWS management role may not change its own policies after setup, so a
66            // grant scoped to one resource could never be attached by the runtime.
67            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            // On AWS the runtime creates a workload's role after setup, and nothing then grants
79            // a custom resource's sets, so a grant on one would never be written.
80            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
103/// Return resources whose declarations cannot be created by their runtime
104/// controllers when omitted from automatic setup.
105fn 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    // These controllers refuse runtime creation: only a setup package can provision them.
114    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    // Azure CORS belongs to the shared account blob service; the container
121    // controller cannot apply it independently.
122    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/// Controls configuration exposure, independently of installation authority.
134/// Existing generator entry points retain the complete Advanced interface.
135#[derive(Debug, Clone, Copy, PartialEq, Eq)]
136pub enum SetupConfigurationProfile {
137    Standard,
138    Advanced,
139}
140
141/// Where a setup package installs: the platform the deployment runs on and the cloud its
142/// infrastructure lives in. They differ for managed Kubernetes (an EKS, GKE or AKS cluster runs
143/// on `Kubernetes`, in the `Aws`, `Gcp` or `Azure` cloud).
144///
145/// Every question about what a setup package emits and registers is answered from this, so the
146/// generators, the emitters and the manager's registration check cannot disagree about it.
147#[derive(Debug, Clone, Copy, PartialEq, Eq)]
148pub struct SetupTarget {
149    /// The platform the deployment runs on.
150    pub deployment_platform: Platform,
151    /// The cloud the setup's infrastructure lives in.
152    pub cloud_platform: Platform,
153}
154
155impl SetupTarget {
156    /// A target from a registration's `platform` and `basePlatform`.
157    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    /// A target from the cloud and whether the setup installs onto a Kubernetes cluster in it.
165    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
181/// Whether the resource type is one a Kubernetes target runs on the cluster itself: a
182/// `ComputeCluster` is a set of logical pools the Operator validates and a `Sandbox` is a pod.
183/// Setup creates no cloud infrastructure for either, and runtime provisioning verifies them
184/// through the Kubernetes controllers rather than a cloud controller.
185///
186/// Setup's emit rule ([`emits_package_scaffolding`]) and the executor's choice of controller
187/// both ask this, so they cannot disagree.
188pub fn is_kubernetes_native_resource_type(resource_type: &crate::ResourceType) -> bool {
189    *resource_type == Sandbox::RESOURCE_TYPE || *resource_type == ComputeCluster::RESOURCE_TYPE
190}
191
192/// Whether this resource is a cloud database (Postgres or Redis) whose private endpoint needs a
193/// network of the cloud's own. On a Kubernetes target a stack keeps a network for it in every
194/// cluster mode; without one an existing cluster's own network serves the workloads.
195///
196/// The network preflight and the setup generators both ask this, so "this stack needs a network"
197/// has one answer.
198pub 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
203/// Whether this resource keeps a network of the cloud's own on a Kubernetes target, in every
204/// cluster mode: a cloud database, or an extension type whose descriptor requires the network.
205///
206/// The network preflight and the Terraform network gate both ask this, so they cannot disagree.
207pub 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
214/// Whether setup can put this resource's private endpoint on the network of an existing
215/// Kubernetes cluster, so that the cluster's workloads reach it.
216///
217/// Only a GCP Postgres can: the module looks the cluster's own network up. A Memorystore
218/// instance cannot move to another network after creation, and on AWS and Azure the module keeps
219/// a network of its own that the cluster is not attached to. Any other resource is never
220/// refused, so the answer for it is `true`. That includes an extension type that requires the
221/// network: it uses whichever network the module keeps, whether or not the cluster reaches it.
222///
223/// The network preflight (at build time) and the generated modules (at plan time, where the
224/// cluster mode is chosen) both ask this, so they refuse the same cases.
225pub 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
233/// The message for a database or cache that setup cannot place on an existing cluster's network.
234/// `network_hint`, when the deployer can bring the cluster's own network, names how in the
235/// caller's terms.
236pub 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
249/// Whether the setup is for an existing Kubernetes cluster: the cluster the source stack declares
250/// decides; with none declared, the stack settings do. A setup that serves both modes (the
251/// deployer picks at apply) is not "existing" here.
252pub 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
268/// The first resource setup would create that an existing cluster could not reach, as the error
269/// a generator returns when it knows the cluster is existing. `creates` says whether setup
270/// creates the resource: one the installer binds to infrastructure it already has is the
271/// deployer's, so it is not refused. A network the deployer names in the settings is theirs to
272/// choose, so nothing is refused for it.
273pub 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        // A resource the deployer can decline is checked by the module's plan instead, once its
294        // input is known.
295        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
313/// Refuses an extension type that requires the network on an existing cluster when its input
314/// also gates a frozen resource, for a setup that fixes the network when it is rendered
315/// (CloudFormation). Declining that input drops the resource before the manager prepares the
316/// stack, so the manager could expect no network while the setup still registers one.
317///
318/// Nothing is refused when the deployer brings the network in the settings, or when another
319/// resource keeps the network without such an input, so it stays whatever the deployer answers.
320/// A database is left to [`refuse_unreachable_databases`].
321pub 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
366/// Whether setup emits this resource and registers it with the manager.
367///
368/// This is the one rule. Both setup generators render exactly the resources it accepts, and the
369/// manager expects a registration to hold exactly those, so a change here moves all three
370/// together.
371///
372/// - On Kubernetes the cluster's own nodes and pods stand in for the cloud machines: a
373///   `ComputeCluster` is a set of logical pools the Operator validates, and a `Sandbox` is a pod.
374///   Setup creates no cloud infrastructure for either, whatever the cloud or whether the cluster
375///   is new or existing.
376/// - Automatic packages install access and secret storage, then let the runtime create
377///   application infrastructure. Cloud API activation and Azure's containing resource group must
378///   exist before their management identity can be installed. Azure also installs application
379///   identities so management can name their principals in the role-assignment conditions.
380/// - Manual packages emit what the resource's ownership policy says.
381///
382/// Whether a Kubernetes cluster is new or existing decides which resources the stack declares
383/// (the cluster and network mutations add or omit them), not which of them setup emits.
384pub 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
401/// Resources whose state is replaced by an automatic setup package import.
402/// Application resources are managed through the installed identity and must
403/// retain their controller state when that package is reimported.
404pub 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
412/// Whether deleting an installation through runtime cleanup removes this resource before the
413/// setup package's own teardown runs.
414///
415/// An automatic package creates only its scaffolding types (see
416/// [`is_automatic_setup_package_resource_type`]). The runtime created everything else, Frozen
417/// resources included, and the package's teardown cannot see those, so runtime cleanup removes
418/// them. It leaves the package's resources, Live vaults included, to that teardown. Any other
419/// package owns its Frozen resources, apart from types that need runtime cleanup first.
420pub 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    /// The extension that defines `acme/dns-zone`, whose type links `link_sets`.
491    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    /// A workload that links a custom resource needs a grant setup writes, which automatic setup
506    /// on AWS can't, at package generation and when a later release adds the link alike.
507    #[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        // A permission profile that scopes sets to the resource grants it too.
523        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        // A link to a type that links no sets grants nothing.
537        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}