Skip to main content

alien_core/
gateability.rs

1//! The single authority on which resources may carry an `.enabled()` gate.
2//!
3//! Both the compile-time check (`ResourceEnabledValidCheck`) and the setup
4//! generators consult this module, so a caller that renders without running
5//! preflights hits the same refusals. The rules live here rather than in the
6//! preflight crate because the generators must not depend on preflights, and
7//! duplicating the rules would let them drift.
8//!
9//! Extension resource types registered outside this crate are gateable by
10//! default (their ownership policy is `user_choice`), matching how the emitter
11//! registries treat them: the generic gating post-pass needs nothing from the
12//! emitter, so there is nothing for an extension to opt into.
13
14use crate::ownership_policy_for_resource_type;
15
16/// Reserved id of the deployment secrets vault.
17///
18/// `SecretsVaultMutation` links this vault to Live Workers and compute
19/// clusters after compile-time checks run, so its presence can never be
20/// optional. Owned here so the gating rules and the mutation agree on one
21/// constant.
22pub const SECRETS_VAULT_ID: &str = "secrets";
23
24/// Permission set id of the grant that lets a machine workload profile read its
25/// own secret values from the secrets vault (AWS).
26pub const MACHINE_WORKLOAD_SECRETS_READ_ID: &str = "vault/machine-workload-secrets-read";
27
28/// Whether an installed AWS stack already has the machine workload grant on one
29/// of its recorded service accounts. Having the secrets vault is not enough: a
30/// worker gives an install the vault without the grant. Adding the grant to a
31/// frozen profile blocks the release, and delivering secrets to a profile that
32/// cannot read them breaks the workload, so setup and delivery share this signal.
33pub fn machine_secrets_installed(state: &crate::StackState) -> bool {
34    state.platform == crate::Platform::Aws
35        && state.resources.values().any(|resource| {
36            resource
37                .config
38                .downcast_ref::<crate::ServiceAccount>()
39                .is_some_and(|account| {
40                    account
41                        .resource_permission_sets
42                        .get(SECRETS_VAULT_ID)
43                        .into_iter()
44                        .flatten()
45                        .any(|set| set.id == MACHINE_WORKLOAD_SECRETS_READ_ID)
46                })
47        })
48}
49
50/// Reserved vault for secrets written by the deployer with their own credentials.
51pub const DEPLOYER_SECRETS_VAULT_ID: &str = "deployer-secrets";
52
53/// Framework and auxiliary infrastructure Alien derives from the stack, the
54/// platform, or the deployment settings. A gate here is never a customer
55/// choice: `ServiceAccountMutation` inserts profile-derived "{profile}-sa"
56/// entries unconditionally, the Azure `default-*` resources are
57/// preflight-injected hosts other resources build on, and network presence is
58/// a StackSettings decision, not a stack-resource one. Both naming variants
59/// are listed where the ownership table accepts both.
60const STACK_DERIVED_TYPES: &[&str] = &[
61    "build",
62    "artifact-registry",
63    "service-account",
64    "compute-cluster",
65    "kubernetes-cluster",
66    "network",
67    "remote-stack-management",
68    "resource-access",
69    "verifier",
70    "service_activation",
71    "service-activation",
72    "azure_resource_group",
73    "azure-resource-group",
74    "azure_storage_account",
75    "azure-storage-account",
76    "azure_container_apps_environment",
77    "azure-container-apps-environment",
78    "azure_service_bus_namespace",
79    "azure-service-bus-namespace",
80];
81
82/// Types whose setup emitters have not been proven under the generic gating
83/// post-pass yet. Emptied as each type's gated render is validated; the list
84/// exists so switching the mechanism cannot silently open gating for a type
85/// nobody has rendered gated before.
86const NOT_YET_GENERIC_TYPES: &[&str] = &[];
87
88/// Why a resource cannot carry an `.enabled()` gate.
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90pub enum GateRefusal {
91    /// The reserved deployment secrets vault (`SECRETS_VAULT_ID`).
92    ReservedSecretsVault,
93    /// Framework infrastructure derived from the stack itself.
94    DerivedFromStack,
95    /// The type's gated setup render has not been validated yet.
96    NotYetGeneric,
97}
98
99impl GateRefusal {
100    /// The reason clause, phrased to follow "Resource 'x' is enabled by input
101    /// 'y', but ...". Callers compose the full message so the preflight and
102    /// the generators report identically.
103    pub fn reason(self) -> &'static str {
104        match self {
105            GateRefusal::ReservedSecretsVault => {
106                "it is the deployment secrets vault. Workers and compute clusters are wired to \
107                 it automatically after compile-time checks run, so a deployer who says no would \
108                 leave them resolving a binding for a vault that was never created. Its presence \
109                 cannot be optional. Give a vault you want to gate a different id"
110            }
111            GateRefusal::DerivedFromStack => {
112                "Alien derives this resource from the stack itself, so it cannot be optional"
113            }
114            GateRefusal::NotYetGeneric => {
115                "this resource type's conditional setup render has not been validated yet, so \
116                 the resource would be created regardless of the deployer's answer"
117            }
118        }
119    }
120}
121
122/// Whether a resource may carry an `.enabled()` gate at all. `None` means
123/// gateable. Lifecycle legality is not decided here — a lifecycle the type
124/// does not allow is refused by the lifecycle rules regardless of gating.
125pub fn gate_refusal(resource_type: &str, resource_id: &str) -> Option<GateRefusal> {
126    if matches!(resource_id, SECRETS_VAULT_ID | DEPLOYER_SECRETS_VAULT_ID) {
127        return Some(GateRefusal::ReservedSecretsVault);
128    }
129    if STACK_DERIVED_TYPES.contains(&resource_type) {
130        return Some(GateRefusal::DerivedFromStack);
131    }
132    // Compute (worker, daemon, container) is deliberately gateable: declining
133    // a live workload rides the same removal path as deleting it from a
134    // release, and its provisioning baseline persists so acceptance can
135    // return. Pausing the sole consumer of an ungated queue is allowed by
136    // design — the queue's retention policy governs the backlog.
137    if NOT_YET_GENERIC_TYPES.contains(&resource_type) {
138        return Some(GateRefusal::NotYetGeneric);
139    }
140    None
141}
142
143/// Per-lifecycle gateability of one resource type, derived from the ownership
144/// table and the gate refusals. Serialized into the generated manifest the
145/// TypeScript SDK's surface test consumes.
146#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
147#[serde(rename_all = "camelCase")]
148pub struct TypeGateability {
149    /// The gate may appear on a Frozen entry of this type.
150    pub frozen: bool,
151    /// The gate may appear on a Live entry of this type.
152    pub live: bool,
153}
154
155/// Gateability of one built-in user resource type, keyed for the manifest.
156pub fn type_gateability(resource_type: &str) -> TypeGateability {
157    let policy = ownership_policy_for_resource_type(resource_type);
158    // The id-based rule cannot be evaluated per type; the manifest describes
159    // types, and the reserved vault id is refused per entry.
160    let gateable = gate_refusal(resource_type, "").is_none();
161    TypeGateability {
162        frozen: gateable && policy.allows_frozen(),
163        live: gateable && policy.allows_live(),
164    }
165}
166
167/// The built-in user resource types listed in the generated manifest. The SDK
168/// builder surface is asserted against exactly this set.
169pub const MANIFEST_TYPES: &[&str] = &[
170    "kv",
171    "storage",
172    "queue",
173    "vault",
174    "postgres",
175    "redis",
176    "ai",
177    "worker",
178    "daemon",
179    "container",
180    "email",
181    "sandbox",
182    "experimental/aws-opensearch",
183];
184
185#[cfg(test)]
186mod tests {
187    use super::*;
188
189    #[test]
190    fn stores_are_gateable_in_both_lifecycles() {
191        for store in ["kv", "storage", "queue", "vault", "ai"] {
192            assert_eq!(gate_refusal(store, "analytics"), None, "{store}");
193            let gateability = type_gateability(store);
194            assert!(gateability.frozen && gateability.live, "{store}");
195        }
196    }
197
198    #[test]
199    fn postgres_is_frozen_gateable_only() {
200        assert_eq!(gate_refusal("postgres", "db"), None);
201        let gateability = type_gateability("postgres");
202        assert!(gateability.frozen && !gateability.live);
203    }
204
205    #[test]
206    fn redis_is_gateable_in_both_lifecycles() {
207        assert_eq!(gate_refusal("redis", "cache"), None);
208        let gateability = type_gateability("redis");
209        assert!(gateability.frozen && gateability.live);
210    }
211
212    #[test]
213    fn compute_is_live_gateable() {
214        for compute in ["worker", "daemon", "container"] {
215            assert_eq!(gate_refusal(compute, "api"), None, "{compute}");
216            let gateability = type_gateability(compute);
217            assert!(!gateability.frozen, "{compute} cannot be frozen");
218            assert!(gateability.live, "{compute} gates as a live resource");
219        }
220    }
221
222    #[test]
223    fn stack_derived_types_are_refused() {
224        for framework in STACK_DERIVED_TYPES {
225            assert_eq!(
226                gate_refusal(framework, "x"),
227                Some(GateRefusal::DerivedFromStack),
228                "{framework}"
229            );
230        }
231    }
232
233    #[test]
234    fn the_reserved_secrets_vault_is_refused_by_id() {
235        assert_eq!(
236            gate_refusal("vault", SECRETS_VAULT_ID),
237            Some(GateRefusal::ReservedSecretsVault)
238        );
239        assert_eq!(gate_refusal("vault", "app-tokens"), None);
240    }
241
242    #[test]
243    fn email_and_opensearch_gate_as_frozen_resources() {
244        for setup_owned in ["email", "experimental/aws-opensearch"] {
245            assert_eq!(gate_refusal(setup_owned, "x"), None, "{setup_owned}");
246            let gateability = type_gateability(setup_owned);
247            assert!(gateability.frozen, "{setup_owned} gates at setup");
248            assert!(!gateability.live, "{setup_owned} has no runtime controller");
249        }
250    }
251
252    /// A sandbox declaration is the image and its pool, never a sandbox — sandboxes are created at
253    /// runtime and cleaned up with the parent, so neither gate sits on one. Both lifecycles gate
254    /// because both are real: Frozen bakes the image at stack creation, Live builds it at runtime.
255    #[test]
256    fn sandbox_gates_under_either_lifecycle() {
257        assert_eq!(gate_refusal("sandbox", "agents"), None);
258        let gateability = type_gateability("sandbox");
259        assert!(gateability.frozen, "a setup-baked image gates at setup");
260        assert!(
261            gateability.live,
262            "a runtime-built image gates in the runtime strip"
263        );
264    }
265
266    /// Every manifest type must state its gateability, because the SDK builder surface is
267    /// generated from it — a type nobody asserted gets whatever the ownership table happens to
268    /// say, which is how a new resource acquires an unintended gate.
269    #[test]
270    fn every_manifest_type_is_asserted_somewhere_above() {
271        let asserted = [
272            "kv",
273            "storage",
274            "queue",
275            "vault",
276            "ai",
277            "postgres",
278            "redis",
279            "worker",
280            "daemon",
281            "container",
282            "email",
283            "experimental/aws-opensearch",
284            "sandbox",
285        ];
286        for declared in MANIFEST_TYPES {
287            assert!(
288                asserted.contains(declared),
289                "{declared} is in the manifest but no test pins its gateability"
290            );
291        }
292    }
293
294    #[test]
295    fn extension_types_default_to_gateable() {
296        assert_eq!(gate_refusal("acme-widgets", "widgets"), None);
297        let gateability = type_gateability("acme-widgets");
298        assert!(gateability.frozen && gateability.live);
299    }
300}