Skip to main content

alien_core/
setup_package.rs

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
9/// Refuse resources whose setup-owned scaffolding cannot yet be created by runtime.
10/// Check both package generation and deployment planning, including later additions.
11pub 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            // Setup must be able to grant whatever a later release adds.
28            ManagementPermissions::Override(_) => {
29                return Err(unsupported(
30                    "management permission override",
31                    "permissions.management",
32                ));
33            }
34            // The AWS management role may not change its own policies after setup, so a
35            // grant scoped to one resource could never be attached by the runtime.
36            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
64/// Return resources whose declarations cannot be created by their runtime
65/// controllers when omitted from automatic setup.
66fn 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    // These controllers refuse runtime creation: only a setup package can provision them.
75    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    // Azure CORS belongs to the shared account blob service; the container
82    // controller cannot apply it independently.
83    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/// Controls configuration exposure, independently of installation authority.
95/// Existing generator entry points retain the complete Advanced interface.
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97pub enum SetupConfigurationProfile {
98    Standard,
99    Advanced,
100}
101
102/// Where a setup package installs: the platform the deployment runs on and the cloud its
103/// infrastructure lives in. They differ for managed Kubernetes (an EKS, GKE or AKS cluster runs
104/// on `Kubernetes`, in the `Aws`, `Gcp` or `Azure` cloud).
105///
106/// Every question about what a setup package emits and registers is answered from this, so the
107/// generators, the emitters and the manager's registration check cannot disagree about it.
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109pub struct SetupTarget {
110    /// The platform the deployment runs on.
111    pub deployment_platform: Platform,
112    /// The cloud the setup's infrastructure lives in.
113    pub cloud_platform: Platform,
114}
115
116impl SetupTarget {
117    /// A target from a registration's `platform` and `basePlatform`.
118    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    /// A target from the cloud and whether the setup installs onto a Kubernetes cluster in it.
126    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
142/// Whether the resource type is one a Kubernetes target runs on the cluster itself: a
143/// `ComputeCluster` is a set of logical pools the Operator validates and a `Sandbox` is a pod.
144/// Setup creates no cloud infrastructure for either, and runtime provisioning verifies them
145/// through the Kubernetes controllers rather than a cloud controller.
146///
147/// Setup's emit rule ([`emits_package_scaffolding`]) and the executor's choice of controller
148/// both ask this, so they cannot disagree.
149pub fn is_kubernetes_native_resource_type(resource_type: &crate::ResourceType) -> bool {
150    *resource_type == Sandbox::RESOURCE_TYPE || *resource_type == ComputeCluster::RESOURCE_TYPE
151}
152
153/// Whether this resource is a cloud database (Postgres or Redis) whose private endpoint needs a
154/// network of the cloud's own. On a Kubernetes target a stack keeps a network for it in every
155/// cluster mode; without one an existing cluster's own network serves the workloads.
156///
157/// The network preflight and the setup generators both ask this, so "this stack needs a network"
158/// has one answer.
159pub 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
164/// Whether setup can put this resource's private endpoint on the network of an existing
165/// Kubernetes cluster, so that the cluster's workloads reach it.
166///
167/// Only a GCP Postgres can: the module looks the cluster's own network up. A Memorystore
168/// instance cannot move to another network after creation, and on AWS and Azure the module keeps
169/// a network of its own that the cluster is not attached to. A resource that is not a cloud
170/// database needs no network, so the answer for it is `true`.
171///
172/// The network preflight (at build time) and the generated modules (at plan time, where the
173/// cluster mode is chosen) both ask this, so they refuse the same cases.
174pub 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
182/// The message for a database or cache that setup cannot place on an existing cluster's network.
183/// `network_hint`, when the deployer can bring the cluster's own network, names how in the
184/// caller's terms.
185pub 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
198/// Whether the setup is for an existing Kubernetes cluster: the cluster the source stack declares
199/// decides; with none declared, the stack settings do. A setup that serves both modes (the
200/// deployer picks at apply) is not "existing" here.
201pub 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
217/// The first resource setup would create that an existing cluster could not reach, as the error
218/// a generator returns when it knows the cluster is existing. `creates` says whether setup
219/// creates the resource: one the installer binds to infrastructure it already has is the
220/// deployer's, so it is not refused. A network the deployer names in the settings is theirs to
221/// choose, so nothing is refused for it.
222pub 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        // A resource the deployer can decline is checked by the module's plan instead, once its
243        // input is known.
244        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
262/// Whether setup emits this resource and registers it with the manager.
263///
264/// This is the one rule. Both setup generators render exactly the resources it accepts, and the
265/// manager expects a registration to hold exactly those, so a change here moves all three
266/// together.
267///
268/// - On Kubernetes the cluster's own nodes and pods stand in for the cloud machines: a
269///   `ComputeCluster` is a set of logical pools the Operator validates, and a `Sandbox` is a pod.
270///   Setup creates no cloud infrastructure for either, whatever the cloud or whether the cluster
271///   is new or existing.
272/// - Automatic packages install access and secret storage, then let the runtime create
273///   application infrastructure. Cloud API activation and Azure's containing resource group must
274///   exist before their management identity can be installed. Azure also installs application
275///   identities so management can name their principals in the role-assignment conditions.
276/// - Manual packages emit what the resource's ownership policy says.
277///
278/// Whether a Kubernetes cluster is new or existing decides which resources the stack declares
279/// (the cluster and network mutations add or omit them), not which of them setup emits.
280pub 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
297/// Resources whose state is replaced by an automatic setup package import.
298/// Application resources are managed through the installed identity and must
299/// retain their controller state when that package is reimported.
300pub 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
308/// Whether deleting an installation through runtime cleanup removes this resource before the
309/// setup package's own teardown runs.
310///
311/// An automatic package creates only its scaffolding types (see
312/// [`is_automatic_setup_package_resource_type`]). The runtime created everything else, Frozen
313/// resources included, and the package's teardown cannot see those, so runtime cleanup removes
314/// them. It leaves the package's resources, Live vaults included, to that teardown. Any other
315/// package owns its Frozen resources, apart from types that need runtime cleanup first.
316pub 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}