Skip to main content

alien_core/
stack_input.rs

1use serde::{Deserialize, Serialize};
2
3use crate::Platform;
4
5/// Who can provide a stack input value.
6#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
7#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
8#[serde(rename_all = "camelCase")]
9pub enum StackInputProvider {
10    /// Value is provided by the developer before a deployment link is created.
11    Developer,
12    /// Value is provided by the deployer during setup.
13    Deployer,
14}
15
16/// Primitive stack input kind.
17#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
18#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
19#[serde(rename_all = "camelCase")]
20pub enum StackInputKind {
21    /// Plain string input.
22    String,
23    /// Secret string input.
24    Secret,
25    /// Floating point number input.
26    Number,
27    /// Integer input.
28    Integer,
29    /// Boolean input.
30    Boolean,
31    /// String enum input.
32    Enum,
33    /// List of strings.
34    StringList,
35}
36
37/// How a resolved stack input is injected into runtime environment variables.
38#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
39#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
40#[serde(rename_all = "camelCase")]
41pub struct StackInputEnvironmentMapping {
42    /// Environment variable name.
43    pub name: String,
44    /// Target resource IDs or patterns. None means every env-capable resource.
45    #[serde(default, skip_serializing_if = "Option::is_none")]
46    pub target_resources: Option<Vec<String>>,
47    /// Whether this env var is plain or secret. Defaults from the input kind.
48    #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
49    pub var_type: Option<StackInputEnvironmentVariableType>,
50}
51
52impl StackInputEnvironmentMapping {
53    /// Whether this mapping reaches `resource_id` (see [`environment_variable_applies`]).
54    /// Grants that follow from delivery (reading a deployer secret) use this too, so Alien's
55    /// own gateway never gets access to an application secret.
56    pub fn targets(&self, resource_id: &str) -> bool {
57        environment_variable_applies(&self.target_resources, resource_id)
58    }
59}
60
61/// Whether an environment variable with these `target_resources` reaches
62/// `resource_id`: every resource when unset, else an exact id or a `prefix*`
63/// pattern. Env delivery and the permissions that follow from it (such as
64/// reading a deployer secret) share this one rule.
65pub fn targets_resource(target_resources: &Option<Vec<String>>, resource_id: &str) -> bool {
66    match target_resources {
67        None => true,
68        Some(patterns) => patterns
69            .iter()
70            .any(|pattern| match pattern.strip_suffix('*') {
71                Some(prefix) => resource_id.starts_with(prefix),
72                None => resource_id == pattern,
73            }),
74    }
75}
76
77/// Whether a deployment environment variable with these `target_resources` applies to
78/// `resource_id`: its targets match, and the resource is not one Alien adds itself.
79///
80/// This is the one rule for delivering variables, for the secrets and permissions that
81/// follow from them, and for telling an operator what a change restarts. The sandbox egress
82/// gateway is Alien's own: its environment is never the application's, not even for a `*`
83/// pattern. Its ID is reserved (the sandbox gateway mutation refuses a user resource with
84/// it), so the rule needs only the ID.
85pub fn environment_variable_applies(
86    target_resources: &Option<Vec<String>>,
87    resource_id: &str,
88) -> bool {
89    resource_id != crate::sandbox_egress::SANDBOX_EGRESS_GATEWAY_ID
90        && targets_resource(target_resources, resource_id)
91}
92
93/// Environment variable handling for a stack input mapping.
94#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
95#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
96#[serde(rename_all = "lowercase")]
97pub enum StackInputEnvironmentVariableType {
98    /// Plain value injected directly.
99    Plain,
100    /// Secret value routed through secret handling.
101    Secret,
102}
103
104/// Portable stack input validation constraints.
105#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
106#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
107#[serde(rename_all = "camelCase")]
108pub struct StackInputValidation {
109    /// Minimum string length.
110    #[serde(default, skip_serializing_if = "Option::is_none")]
111    pub min_length: Option<u32>,
112    /// Maximum string length.
113    #[serde(default, skip_serializing_if = "Option::is_none")]
114    pub max_length: Option<u32>,
115    /// Portable whole-value regex pattern.
116    #[serde(default, skip_serializing_if = "Option::is_none")]
117    pub pattern: Option<String>,
118    /// Semantic format hint such as url.
119    #[serde(default, skip_serializing_if = "Option::is_none")]
120    pub format: Option<String>,
121    /// Minimum number.
122    #[serde(default, skip_serializing_if = "Option::is_none")]
123    pub min: Option<String>,
124    /// Maximum number.
125    #[serde(default, skip_serializing_if = "Option::is_none")]
126    pub max: Option<String>,
127    /// Allowed string enum values.
128    #[serde(default, skip_serializing_if = "Option::is_none")]
129    pub values: Option<Vec<String>>,
130    /// Minimum string-list items.
131    #[serde(default, skip_serializing_if = "Option::is_none")]
132    pub min_items: Option<u32>,
133    /// Maximum string-list items.
134    #[serde(default, skip_serializing_if = "Option::is_none")]
135    pub max_items: Option<u32>,
136}
137
138/// Stack input default value.
139#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
140#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
141#[serde(rename_all = "camelCase", tag = "type", content = "value")]
142pub enum StackInputDefaultValue {
143    /// String default.
144    String(String),
145    /// Number default.
146    Number(String),
147    /// Boolean default.
148    Boolean(bool),
149    /// String list default.
150    StringList(Vec<String>),
151}
152
153/// Shortest value Alien generates for a secret input.
154pub const STACK_INPUT_GENERATE_MIN_LENGTH: u32 = 16;
155/// Longest value Alien generates for a secret input.
156pub const STACK_INPUT_GENERATE_MAX_LENGTH: u32 = 256;
157
158/// Asks Alien to generate a secret input's value.
159///
160/// The value is an alphanumeric string (`A-Z`, `a-z`, `0-9`), so it is safe in
161/// connection strings, command lines and environment variables. It is generated
162/// once, when the deployment's input values are first resolved, and then kept
163/// with the deployment's other input values.
164#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
165#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
166#[serde(rename_all = "camelCase")]
167pub struct StackInputGenerate {
168    /// Number of characters to generate.
169    pub length: u32,
170}
171
172/// A boolean input condition controlling whether another input applies.
173#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
174#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
175#[serde(rename_all = "camelCase")]
176pub struct StackInputCondition {
177    /// ID of an unconditional boolean input in the same stack.
178    pub input: String,
179    /// Boolean value for which this input applies.
180    pub equals: bool,
181}
182
183/// Stack input definition serialized into a release stack.
184#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
185#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
186#[serde(rename_all = "camelCase")]
187pub struct StackInputDefinition {
188    /// Stable input ID used by CLI/API calls.
189    pub id: String,
190    /// Input primitive kind.
191    pub kind: StackInputKind,
192    /// Who can provide this value.
193    pub provided_by: Vec<StackInputProvider>,
194    /// Whether a resolved value is required before deployment can proceed.
195    pub required: bool,
196    /// Human-facing field label.
197    pub label: String,
198    /// Human-facing helper text.
199    pub description: String,
200    /// Example placeholder shown in UI.
201    #[serde(default, skip_serializing_if = "Option::is_none")]
202    pub placeholder: Option<String>,
203    /// Default value for optional/plain inputs.
204    #[serde(default, skip_serializing_if = "Option::is_none")]
205    pub default: Option<StackInputDefaultValue>,
206    /// Platforms where this input applies.
207    #[serde(default, skip_serializing_if = "Option::is_none")]
208    pub platforms: Option<Vec<Platform>>,
209    /// Only applies when the referenced boolean resolves to the given value.
210    /// Inactive inputs ignore provided values, validation and environment mappings.
211    #[serde(default, skip_serializing_if = "Option::is_none")]
212    pub when: Option<StackInputCondition>,
213    /// Portable validation constraints.
214    #[serde(default, skip_serializing_if = "Option::is_none")]
215    pub validation: Option<StackInputValidation>,
216    /// Alien generates the value when none is provided. Secret,
217    /// developer-provided inputs only.
218    #[serde(default, skip_serializing_if = "Option::is_none")]
219    pub generate: Option<StackInputGenerate>,
220    /// Runtime env-var mappings for v1 input resolution.
221    #[serde(default, skip_serializing_if = "Vec::is_empty")]
222    pub env: Vec<StackInputEnvironmentMapping>,
223}
224
225impl StackInputDefinition {
226    /// Whether this input is available on the deployment platform, independently of its base cloud.
227    /// Empty scopes retain their legacy all-platform meaning for existing releases.
228    /// Build-time checks reject empty scopes in new releases.
229    pub fn applies_to(&self, platform: Platform) -> bool {
230        self.platforms
231            .as_ref()
232            .is_none_or(|platforms| platforms.is_empty() || platforms.contains(&platform))
233    }
234
235    /// Whether this input applies, using the referenced input's provided value
236    /// or boolean default. An off-platform reference resolves to false; an
237    /// unanswered reference never matches. Definitions must pass release preflights first.
238    pub fn applies(
239        &self,
240        inputs: &[StackInputDefinition],
241        values: &std::collections::HashMap<String, serde_json::Value>,
242        platform: Platform,
243    ) -> bool {
244        if !self.applies_to(platform) {
245            return false;
246        }
247        let Some(condition) = &self.when else {
248            return true;
249        };
250        let Some(reference) = inputs.iter().find(|input| input.id == condition.input) else {
251            return false;
252        };
253        if !reference.applies_to(platform) {
254            return !condition.equals;
255        }
256        let value = match values
257            .get(&condition.input)
258            .filter(|value| !value.is_null())
259        {
260            Some(value) => crate::gate_value_as_bool(value),
261            None => match reference.default {
262                Some(StackInputDefaultValue::Boolean(value)) => Some(value),
263                _ => None,
264            },
265        };
266        value == Some(condition.equals)
267    }
268
269    /// Whether this input controls any input selected by the caller.
270    pub fn controls_input(
271        &self,
272        inputs: &[StackInputDefinition],
273        include: impl Fn(&StackInputDefinition) -> bool,
274    ) -> bool {
275        inputs.iter().any(|dependent| {
276            include(dependent)
277                && dependent
278                    .when
279                    .as_ref()
280                    .is_some_and(|when| when.input == self.id)
281        })
282    }
283
284    /// Whether Alien generates this input's value when none is provided. A
285    /// generated input never needs a value from the developer or deployer.
286    pub fn is_generated(&self) -> bool {
287        self.generate.is_some()
288    }
289
290    /// A deployer-provided boolean input, the shape `.enabled(input)` gates
291    /// on. With a default the input is optional; without one it is required,
292    /// since an unanswered gate would leave the resource's existence
293    /// undecided. This is the Rust-side seam gated-stack tests build inputs
294    /// with.
295    #[doc(hidden)]
296    pub fn deployer_boolean(
297        id: &str,
298        label: &str,
299        description: &str,
300        default: Option<bool>,
301    ) -> Self {
302        Self {
303            id: id.to_string(),
304            kind: StackInputKind::Boolean,
305            when: None,
306            provided_by: vec![StackInputProvider::Deployer],
307            required: default.is_none(),
308            label: label.to_string(),
309            description: description.to_string(),
310            placeholder: None,
311            default: default.map(StackInputDefaultValue::Boolean),
312            platforms: None,
313            validation: None,
314            generate: None,
315            env: Vec::new(),
316        }
317    }
318}
319
320/// Finds the boolean deployer input a gate references, for render-time
321/// re-validation. The compile-time preflight enforces the same two rules;
322/// generators repeat them so a caller that renders without preflights cannot
323/// ship a template whose gate variable is undeclared or non-boolean.
324pub fn find_boolean_gate_input<'a>(
325    inputs: &'a [StackInputDefinition],
326    input_id: &str,
327) -> Result<&'a StackInputDefinition, GateInputIssue> {
328    let input = inputs
329        .iter()
330        .find(|input| input.id == input_id)
331        .ok_or(GateInputIssue::Undeclared)?;
332    if input.kind != StackInputKind::Boolean {
333        return Err(GateInputIssue::NotBoolean(input.kind.clone()));
334    }
335    Ok(input)
336}
337
338/// Why a gate input failed render-time validation; the caller owns the
339/// backend-specific error message.
340#[derive(Debug, Clone, PartialEq, Eq)]
341pub enum GateInputIssue {
342    /// The stack declares no input with the gate's id.
343    Undeclared,
344    /// The input exists but is not a boolean.
345    NotBoolean(StackInputKind),
346}
347
348/// Environment variables produced by stack inputs that declare `env`
349/// mappings, from the deployment's input values (or each input's default).
350///
351/// Only inputs that apply to `platform` count: an input that lists
352/// `platforms` without it produces nothing. List values become
353/// comma-separated strings. Secret inputs produce secret variables unless the
354/// mapping sets a type. Two mappings resolving to the same variable name are
355/// rejected.
356pub fn resolve_stack_input_environment_variables(
357    inputs: &[StackInputDefinition],
358    values: &std::collections::HashMap<String, serde_json::Value>,
359    platform: Platform,
360) -> crate::Result<Vec<crate::EnvironmentVariable>> {
361    let mut variables: Vec<crate::EnvironmentVariable> = Vec::new();
362    for input in inputs
363        .iter()
364        .filter(|input| !input.env.is_empty())
365        .filter(|input| input.applies(inputs, values, platform))
366    {
367        let value = match values.get(&input.id) {
368            Some(serde_json::Value::Null) | None => match &input.default {
369                Some(default) => default_environment_string(default),
370                None => continue,
371            },
372            Some(value) => environment_string(value),
373        };
374        for mapping in &input.env {
375            if variables
376                .iter()
377                .any(|variable| variable.name == mapping.name)
378            {
379                return Err(alien_error::AlienError::new(
380                    crate::ErrorData::GenericError {
381                        message: format!(
382                            "Stack inputs map more than one value to environment variable '{}'",
383                            mapping.name
384                        ),
385                    },
386                ));
387            }
388            let secret = match mapping.var_type {
389                Some(StackInputEnvironmentVariableType::Secret) => true,
390                Some(StackInputEnvironmentVariableType::Plain) => false,
391                None => input.kind == StackInputKind::Secret,
392            };
393            variables.push(crate::EnvironmentVariable {
394                name: mapping.name.clone(),
395                value: value.clone(),
396                var_type: if secret {
397                    crate::EnvironmentVariableType::Secret
398                } else {
399                    crate::EnvironmentVariableType::Plain
400                },
401                target_resources: mapping.target_resources.clone(),
402            });
403        }
404    }
405    Ok(variables)
406}
407
408fn environment_string(value: &serde_json::Value) -> String {
409    match value {
410        serde_json::Value::String(value) => value.clone(),
411        serde_json::Value::Array(items) => items
412            .iter()
413            .map(environment_string)
414            .collect::<Vec<_>>()
415            .join(","),
416        other => other.to_string(),
417    }
418}
419
420fn default_environment_string(default: &StackInputDefaultValue) -> String {
421    match default {
422        StackInputDefaultValue::String(value) | StackInputDefaultValue::Number(value) => {
423            value.clone()
424        }
425        StackInputDefaultValue::Boolean(value) => value.to_string(),
426        StackInputDefaultValue::StringList(values) => values.join(","),
427    }
428}
429
430#[cfg(test)]
431mod environment_tests {
432    use std::collections::HashMap;
433
434    use super::*;
435    use crate::EnvironmentVariableType;
436
437    #[test]
438    fn an_env_mapping_targets_every_resource_or_its_patterns() {
439        let mapping = |targets: Option<Vec<&str>>| StackInputEnvironmentMapping {
440            name: "API_KEY".to_string(),
441            target_resources: targets.map(|t| t.into_iter().map(String::from).collect()),
442            var_type: None,
443        };
444
445        assert!(mapping(None).targets("api"));
446        assert!(mapping(Some(vec!["api"])).targets("api"));
447        assert!(!mapping(Some(vec!["api"])).targets("api-worker"));
448        assert!(mapping(Some(vec!["api-*"])).targets("api-worker"));
449        assert!(!mapping(Some(vec!["api-*"])).targets("web"));
450        assert!(mapping(Some(vec!["api-*", "worker"])).targets("worker"));
451        assert!(!mapping(Some(vec!["api-*", "worker"])).targets("scheduler"));
452        assert!(!mapping(Some(vec![])).targets("api"));
453    }
454
455    fn input(id: &str, kind: StackInputKind, env: &str) -> StackInputDefinition {
456        StackInputDefinition {
457            id: id.to_string(),
458            kind,
459            when: None,
460            provided_by: vec![StackInputProvider::Developer],
461            required: false,
462            label: id.to_string(),
463            description: id.to_string(),
464            placeholder: None,
465            default: None,
466            generate: None,
467            platforms: None,
468            validation: None,
469            env: vec![StackInputEnvironmentMapping {
470                name: env.to_string(),
471                target_resources: Some(vec!["api".to_string()]),
472                var_type: None,
473            }],
474        }
475    }
476
477    #[test]
478    fn conditional_environment_uses_provided_boolean_before_default() {
479        let toggle = StackInputDefinition::deployer_boolean(
480            "enabled",
481            "Enabled",
482            "Enable snapshots",
483            Some(true),
484        );
485        let mut bucket = input("bucket", StackInputKind::String, "BUCKET");
486        bucket.required = true;
487        bucket.when = Some(StackInputCondition {
488            input: "enabled".into(),
489            equals: true,
490        });
491        bucket.default = Some(StackInputDefaultValue::String("default-bucket".into()));
492        let inputs = vec![toggle, bucket];
493        for (answer, expected) in [
494            (None, Some("default-bucket")),
495            (Some(serde_json::json!(true)), Some("default-bucket")),
496            (Some(serde_json::json!("true")), Some("default-bucket")),
497            (Some(serde_json::json!(false)), None),
498            (Some(serde_json::json!("false")), None),
499        ] {
500            let values = answer
501                .map(|value| HashMap::from([("enabled".into(), value)]))
502                .unwrap_or_default();
503            let env =
504                resolve_stack_input_environment_variables(&inputs, &values, Platform::Aws).unwrap();
505            assert_eq!(
506                env.first().map(|variable| variable.value.as_str()),
507                expected
508            );
509        }
510        let values = HashMap::from([
511            ("enabled".into(), serde_json::json!(false)),
512            ("bucket".into(), serde_json::json!({"invalid": "ignored"})),
513        ]);
514        assert!(
515            resolve_stack_input_environment_variables(&inputs, &values, Platform::Aws)
516                .unwrap()
517                .is_empty()
518        );
519    }
520
521    #[test]
522    fn conditional_input_requires_an_answer_and_both_platform_scopes() {
523        let mut toggle =
524            StackInputDefinition::deployer_boolean("enabled", "Enabled", "Enable snapshots", None);
525        toggle.platforms = Some(vec![Platform::Aws]);
526        let mut bucket = input("bucket", StackInputKind::String, "BUCKET");
527        bucket.when = Some(StackInputCondition {
528            input: "enabled".into(),
529            equals: false,
530        });
531        let mut inputs = vec![toggle, bucket];
532        assert!(!inputs[1].applies(&inputs, &HashMap::new(), Platform::Aws));
533        let values = HashMap::from([("enabled".into(), serde_json::json!(false))]);
534        assert!(inputs[1].applies(&inputs, &values, Platform::Aws));
535        assert!(inputs[1].applies(&inputs, &values, Platform::Kubernetes));
536        inputs[1].when.as_mut().unwrap().equals = true;
537        assert!(!inputs[1].applies(&inputs, &values, Platform::Kubernetes));
538        inputs[0].platforms = Some(vec![]);
539        assert!(inputs[0].applies_to(Platform::Aws));
540        assert!(!inputs[1].applies(&inputs, &values, Platform::Aws));
541        inputs[1].when.as_mut().unwrap().equals = false;
542        assert!(inputs[1].applies(&inputs, &values, Platform::Aws));
543        inputs[1].platforms = Some(vec![Platform::Kubernetes]);
544        assert!(!inputs[1].applies(&inputs, &values, Platform::Aws));
545    }
546
547    #[test]
548    fn delivery_preserves_stored_values_without_revalidation() {
549        for (kind, value, validation) in [
550            (
551                StackInputKind::Number,
552                "1.50",
553                serde_json::json!({"min":"10"}),
554            ),
555            (StackInputKind::Number, "1e3", serde_json::json!({})),
556            (
557                StackInputKind::Integer,
558                "007",
559                serde_json::json!({"max":"5"}),
560            ),
561            (
562                StackInputKind::String,
563                "not-a-url",
564                serde_json::json!({"format":"url"}),
565            ),
566            (
567                StackInputKind::String,
568                "",
569                serde_json::json!({"minLength":3}),
570            ),
571        ] {
572            let mut stored = input("stored", kind, "STORED");
573            stored.required = true;
574            stored.validation = Some(serde_json::from_value(validation).unwrap());
575            let mut added = input("added", StackInputKind::String, "ADDED");
576            added.required = true;
577            let values = HashMap::from([("stored".into(), serde_json::json!(value))]);
578            let variables =
579                resolve_stack_input_environment_variables(&[stored, added], &values, Platform::Aws)
580                    .expect("delivery must not revalidate existing deployments");
581            assert_eq!(variables.len(), 1);
582            assert_eq!(variables[0].name, "STORED");
583            assert_eq!(variables[0].value, value);
584        }
585    }
586
587    #[test]
588    fn legacy_empty_platform_list_still_maps_environment() {
589        let mut definition = input("region", StackInputKind::String, "REGION");
590        definition.platforms = Some(vec![]);
591        let values = HashMap::from([("region".into(), serde_json::json!("us-east-1"))]);
592        let env = resolve_stack_input_environment_variables(&[definition], &values, Platform::Aws)
593            .unwrap();
594        assert_eq!(env.len(), 1);
595        assert_eq!(env[0].value, "us-east-1");
596    }
597
598    #[test]
599    fn maps_values_defaults_and_secrecy() {
600        let mut region = input("region", StackInputKind::String, "REGION");
601        region.default = Some(StackInputDefaultValue::String("eu-west-1".to_string()));
602        let inputs = vec![
603            input("token", StackInputKind::Secret, "ACCESS_TOKEN"),
604            input("zones", StackInputKind::StringList, "ZONES"),
605            region,
606            input("unset", StackInputKind::String, "UNSET"),
607        ];
608        let values = HashMap::from([
609            ("token".to_string(), serde_json::json!("s3cr3t")),
610            ("zones".to_string(), serde_json::json!(["a", "b"])),
611        ]);
612
613        let variables =
614            resolve_stack_input_environment_variables(&inputs, &values, Platform::Kubernetes)
615                .unwrap();
616
617        let by_name: HashMap<_, _> = variables.iter().map(|v| (v.name.as_str(), v)).collect();
618        assert_eq!(
619            variables.len(),
620            3,
621            "unset inputs without defaults produce nothing"
622        );
623        assert_eq!(by_name["ACCESS_TOKEN"].value, "s3cr3t");
624        assert_eq!(
625            by_name["ACCESS_TOKEN"].var_type,
626            EnvironmentVariableType::Secret
627        );
628        assert_eq!(
629            by_name["ACCESS_TOKEN"].target_resources,
630            Some(vec!["api".to_string()])
631        );
632        assert_eq!(by_name["ZONES"].value, "a,b");
633        assert_eq!(by_name["ZONES"].var_type, EnvironmentVariableType::Plain);
634        assert_eq!(by_name["REGION"].value, "eu-west-1");
635    }
636
637    #[test]
638    fn rejects_two_inputs_mapped_to_one_variable() {
639        let inputs = vec![
640            input("a", StackInputKind::String, "SHARED"),
641            input("b", StackInputKind::String, "SHARED"),
642        ];
643        let values = HashMap::from([
644            ("a".to_string(), serde_json::json!("1")),
645            ("b".to_string(), serde_json::json!("2")),
646        ]);
647        let error =
648            resolve_stack_input_environment_variables(&inputs, &values, Platform::Kubernetes)
649                .expect_err("duplicate names must be rejected");
650        assert!(error.message.contains("SHARED"));
651    }
652
653    #[test]
654    fn legacy_empty_platform_scope_preserves_environment_variables() {
655        let mut input = input("region", StackInputKind::String, "REGION");
656        input.platforms = Some(vec![]);
657        input.default = Some(StackInputDefaultValue::String("us-east-1".into()));
658        let values = HashMap::from([("region".into(), serde_json::json!("us-west-2"))]);
659        let variables =
660            resolve_stack_input_environment_variables(&[input], &values, Platform::Aws).unwrap();
661        assert_eq!(variables.len(), 1);
662        assert_eq!(variables[0].name, "REGION");
663        assert_eq!(variables[0].value, "us-west-2");
664    }
665
666    #[test]
667    fn inputs_for_other_platforms_produce_nothing() {
668        // An AWS-only input with a default must not reach a Kubernetes
669        // workload, and may share a variable name with a Kubernetes one.
670        let mut aws_only = input("aws-region", StackInputKind::String, "REGION");
671        aws_only.platforms = Some(vec![Platform::Aws]);
672        aws_only.default = Some(StackInputDefaultValue::String("us-east-1".to_string()));
673        let mut kubernetes_only = input("zone", StackInputKind::String, "REGION");
674        kubernetes_only.platforms = Some(vec![Platform::Kubernetes]);
675        let values = HashMap::from([("zone".to_string(), serde_json::json!("rack-7"))]);
676
677        let variables = resolve_stack_input_environment_variables(
678            &[aws_only, kubernetes_only],
679            &values,
680            Platform::Kubernetes,
681        )
682        .unwrap();
683
684        assert_eq!(variables.len(), 1);
685        assert_eq!(variables[0].name, "REGION");
686        assert_eq!(variables[0].value, "rack-7");
687    }
688}
689
690#[cfg(test)]
691mod environment_variable_applies_tests {
692    use super::*;
693
694    fn targets(patterns: &[&str]) -> Option<Vec<String>> {
695        Some(patterns.iter().map(|p| p.to_string()).collect())
696    }
697
698    #[test]
699    fn the_gateway_never_receives_a_variable() {
700        let gateway = crate::sandbox_egress::SANDBOX_EGRESS_GATEWAY_ID;
701        for t in [
702            None,
703            targets(&["*"]),
704            targets(&["sandbox-*"]),
705            targets(&[gateway]),
706        ] {
707            assert!(!environment_variable_applies(&t, gateway), "{t:?}");
708        }
709    }
710
711    #[test]
712    fn other_resources_follow_their_targets() {
713        assert!(environment_variable_applies(&None, "backend"));
714        assert!(environment_variable_applies(&targets(&["*"]), "backend"));
715        assert!(environment_variable_applies(
716            &targets(&["back*"]),
717            "backend"
718        ));
719        assert!(environment_variable_applies(
720            &targets(&["backend"]),
721            "backend"
722        ));
723        assert!(!environment_variable_applies(
724            &targets(&["redis"]),
725            "backend"
726        ));
727        assert!(!environment_variable_applies(&targets(&[]), "backend"));
728    }
729
730    /// Grants that follow delivery (reading a deployer secret) use the same rule, so the
731    /// gateway gets no access to an application secret even when a mapping names it.
732    #[test]
733    fn a_mapping_never_grants_the_gateway() {
734        let gateway = crate::sandbox_egress::SANDBOX_EGRESS_GATEWAY_ID;
735        for target_resources in [None, targets(&["*"]), targets(&[gateway])] {
736            let reaches_backend = target_resources != targets(&[gateway]);
737            let mapping = StackInputEnvironmentMapping {
738                name: "API_KEY".to_string(),
739                target_resources,
740                var_type: None,
741            };
742            assert!(!mapping.targets(gateway));
743            assert_eq!(mapping.targets("backend"), reaches_backend);
744        }
745    }
746}
747
748/// The answers a deployment gives to a stack's inputs, with each input's declared default
749/// behind them. Resources that name an input read their value through this.
750#[derive(Debug, Clone, Copy)]
751pub struct InputAnswers<'a> {
752    definitions: &'a [StackInputDefinition],
753    values: &'a std::collections::HashMap<String, serde_json::Value>,
754}
755
756impl<'a> InputAnswers<'a> {
757    pub fn new(
758        definitions: &'a [StackInputDefinition],
759        values: &'a std::collections::HashMap<String, serde_json::Value>,
760    ) -> Self {
761        Self {
762            definitions,
763            values,
764        }
765    }
766
767    /// The string list a deployment resolves for input `id`: its answer (a list, or a
768    /// comma-separated string), else the declared default, else empty. Entries are trimmed
769    /// and blanks dropped. `None` when the stack declares no input `id`.
770    pub fn string_list(&self, id: &str) -> Option<Vec<String>> {
771        let definition = self.definitions.iter().find(|input| input.id == id)?;
772        let entries: Vec<String> = match self.values.get(id) {
773            Some(serde_json::Value::Array(items)) => items
774                .iter()
775                .filter_map(|item| item.as_str().map(str::to_string))
776                .collect(),
777            Some(serde_json::Value::String(text)) => text.split(',').map(str::to_string).collect(),
778            Some(serde_json::Value::Null) | None => match &definition.default {
779                Some(StackInputDefaultValue::StringList(items)) => items.clone(),
780                Some(StackInputDefaultValue::String(text)) => {
781                    text.split(',').map(str::to_string).collect()
782                }
783                _ => Vec::new(),
784            },
785            Some(_) => Vec::new(),
786        };
787        Some(
788            entries
789                .into_iter()
790                .map(|entry| entry.trim().to_string())
791                .filter(|entry| !entry.is_empty())
792                .collect(),
793        )
794    }
795}