alien-core 3.3.55

Deploy software into your customers' cloud accounts and keep it fully managed
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
use serde::{Deserialize, Serialize};

use crate::Platform;

/// Who can provide a stack input value.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub enum StackInputProvider {
    /// Value is provided by the developer before a deployment link is created.
    Developer,
    /// Value is provided by the deployer during setup.
    Deployer,
}

/// Primitive stack input kind.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub enum StackInputKind {
    /// Plain string input.
    String,
    /// Secret string input.
    Secret,
    /// Floating point number input.
    Number,
    /// Integer input.
    Integer,
    /// Boolean input.
    Boolean,
    /// String enum input.
    Enum,
    /// List of strings.
    StringList,
}

/// How a resolved stack input is injected into runtime environment variables.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct StackInputEnvironmentMapping {
    /// Environment variable name.
    pub name: String,
    /// Target resource IDs or patterns. None means every env-capable resource.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target_resources: Option<Vec<String>>,
    /// Whether this env var is plain or secret. Defaults from the input kind.
    #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
    pub var_type: Option<StackInputEnvironmentVariableType>,
}

impl StackInputEnvironmentMapping {
    /// Whether this mapping reaches `resource_id` (see [`targets_resource`]).
    pub fn targets(&self, resource_id: &str) -> bool {
        targets_resource(&self.target_resources, resource_id)
    }
}

/// Whether an environment variable with these `target_resources` reaches
/// `resource_id`: every resource when unset, else an exact id or a `prefix*`
/// pattern. Env delivery and the permissions that follow from it (such as
/// reading a deployer secret) share this one rule.
pub fn targets_resource(target_resources: &Option<Vec<String>>, resource_id: &str) -> bool {
    match target_resources {
        None => true,
        Some(patterns) => patterns
            .iter()
            .any(|pattern| match pattern.strip_suffix('*') {
                Some(prefix) => resource_id.starts_with(prefix),
                None => resource_id == pattern,
            }),
    }
}

/// Environment variable handling for a stack input mapping.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "lowercase")]
pub enum StackInputEnvironmentVariableType {
    /// Plain value injected directly.
    Plain,
    /// Secret value routed through secret handling.
    Secret,
}

/// Portable stack input validation constraints.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct StackInputValidation {
    /// Minimum string length.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min_length: Option<u32>,
    /// Maximum string length.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_length: Option<u32>,
    /// Portable whole-value regex pattern.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pattern: Option<String>,
    /// Semantic format hint such as url.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub format: Option<String>,
    /// Minimum number.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min: Option<String>,
    /// Maximum number.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max: Option<String>,
    /// Allowed string enum values.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub values: Option<Vec<String>>,
    /// Minimum string-list items.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min_items: Option<u32>,
    /// Maximum string-list items.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_items: Option<u32>,
}

/// Stack input default value.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase", tag = "type", content = "value")]
pub enum StackInputDefaultValue {
    /// String default.
    String(String),
    /// Number default.
    Number(String),
    /// Boolean default.
    Boolean(bool),
    /// String list default.
    StringList(Vec<String>),
}

/// Shortest value Alien generates for a secret input.
pub const STACK_INPUT_GENERATE_MIN_LENGTH: u32 = 16;
/// Longest value Alien generates for a secret input.
pub const STACK_INPUT_GENERATE_MAX_LENGTH: u32 = 256;

/// Asks Alien to generate a secret input's value.
///
/// The value is an alphanumeric string (`A-Z`, `a-z`, `0-9`), so it is safe in
/// connection strings, command lines and environment variables. It is generated
/// once, when the deployment's input values are first resolved, and then kept
/// with the deployment's other input values.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct StackInputGenerate {
    /// Number of characters to generate.
    pub length: u32,
}

/// A boolean input condition controlling whether another input applies.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct StackInputCondition {
    /// ID of an unconditional boolean input in the same stack.
    pub input: String,
    /// Boolean value for which this input applies.
    pub equals: bool,
}

/// Stack input definition serialized into a release stack.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct StackInputDefinition {
    /// Stable input ID used by CLI/API calls.
    pub id: String,
    /// Input primitive kind.
    pub kind: StackInputKind,
    /// Who can provide this value.
    pub provided_by: Vec<StackInputProvider>,
    /// Whether a resolved value is required before deployment can proceed.
    pub required: bool,
    /// Human-facing field label.
    pub label: String,
    /// Human-facing helper text.
    pub description: String,
    /// Example placeholder shown in UI.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub placeholder: Option<String>,
    /// Default value for optional/plain inputs.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default: Option<StackInputDefaultValue>,
    /// Platforms where this input applies.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub platforms: Option<Vec<Platform>>,
    /// Only applies when the referenced boolean resolves to the given value.
    /// Inactive inputs ignore provided values, validation and environment mappings.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub when: Option<StackInputCondition>,
    /// Portable validation constraints.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub validation: Option<StackInputValidation>,
    /// Alien generates the value when none is provided. Secret,
    /// developer-provided inputs only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub generate: Option<StackInputGenerate>,
    /// Runtime env-var mappings for v1 input resolution.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub env: Vec<StackInputEnvironmentMapping>,
}

impl StackInputDefinition {
    /// Whether this input is available on the deployment platform, independently of its base cloud.
    /// Empty scopes retain their legacy all-platform meaning for existing releases.
    /// Build-time checks reject empty scopes in new releases.
    pub fn applies_to(&self, platform: Platform) -> bool {
        self.platforms
            .as_ref()
            .is_none_or(|platforms| platforms.is_empty() || platforms.contains(&platform))
    }

    /// Whether this input applies, using the referenced input's provided value
    /// or boolean default. An off-platform reference resolves to false; an
    /// unanswered reference never matches. Definitions must pass release preflights first.
    pub fn applies(
        &self,
        inputs: &[StackInputDefinition],
        values: &std::collections::HashMap<String, serde_json::Value>,
        platform: Platform,
    ) -> bool {
        if !self.applies_to(platform) {
            return false;
        }
        let Some(condition) = &self.when else {
            return true;
        };
        let Some(reference) = inputs.iter().find(|input| input.id == condition.input) else {
            return false;
        };
        if !reference.applies_to(platform) {
            return !condition.equals;
        }
        let value = match values
            .get(&condition.input)
            .filter(|value| !value.is_null())
        {
            Some(value) => crate::gate_value_as_bool(value),
            None => match reference.default {
                Some(StackInputDefaultValue::Boolean(value)) => Some(value),
                _ => None,
            },
        };
        value == Some(condition.equals)
    }

    /// Whether this input controls any input selected by the caller.
    pub fn controls_input(
        &self,
        inputs: &[StackInputDefinition],
        include: impl Fn(&StackInputDefinition) -> bool,
    ) -> bool {
        inputs.iter().any(|dependent| {
            include(dependent)
                && dependent
                    .when
                    .as_ref()
                    .is_some_and(|when| when.input == self.id)
        })
    }

    /// Whether Alien generates this input's value when none is provided. A
    /// generated input never needs a value from the developer or deployer.
    pub fn is_generated(&self) -> bool {
        self.generate.is_some()
    }

    /// A deployer-provided boolean input, the shape `.enabled(input)` gates
    /// on. With a default the input is optional; without one it is required,
    /// since an unanswered gate would leave the resource's existence
    /// undecided. This is the Rust-side seam gated-stack tests build inputs
    /// with.
    #[doc(hidden)]
    pub fn deployer_boolean(
        id: &str,
        label: &str,
        description: &str,
        default: Option<bool>,
    ) -> Self {
        Self {
            id: id.to_string(),
            kind: StackInputKind::Boolean,
            when: None,
            provided_by: vec![StackInputProvider::Deployer],
            required: default.is_none(),
            label: label.to_string(),
            description: description.to_string(),
            placeholder: None,
            default: default.map(StackInputDefaultValue::Boolean),
            platforms: None,
            validation: None,
            generate: None,
            env: Vec::new(),
        }
    }
}

/// Finds the boolean deployer input a gate references, for render-time
/// re-validation. The compile-time preflight enforces the same two rules;
/// generators repeat them so a caller that renders without preflights cannot
/// ship a template whose gate variable is undeclared or non-boolean.
pub fn find_boolean_gate_input<'a>(
    inputs: &'a [StackInputDefinition],
    input_id: &str,
) -> Result<&'a StackInputDefinition, GateInputIssue> {
    let input = inputs
        .iter()
        .find(|input| input.id == input_id)
        .ok_or(GateInputIssue::Undeclared)?;
    if input.kind != StackInputKind::Boolean {
        return Err(GateInputIssue::NotBoolean(input.kind.clone()));
    }
    Ok(input)
}

/// Why a gate input failed render-time validation; the caller owns the
/// backend-specific error message.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GateInputIssue {
    /// The stack declares no input with the gate's id.
    Undeclared,
    /// The input exists but is not a boolean.
    NotBoolean(StackInputKind),
}

/// Environment variables produced by stack inputs that declare `env`
/// mappings, from the deployment's input values (or each input's default).
///
/// Only inputs that apply to `platform` count: an input that lists
/// `platforms` without it produces nothing. List values become
/// comma-separated strings. Secret inputs produce secret variables unless the
/// mapping sets a type. Two mappings resolving to the same variable name are
/// rejected.
pub fn resolve_stack_input_environment_variables(
    inputs: &[StackInputDefinition],
    values: &std::collections::HashMap<String, serde_json::Value>,
    platform: Platform,
) -> crate::Result<Vec<crate::EnvironmentVariable>> {
    let mut variables: Vec<crate::EnvironmentVariable> = Vec::new();
    for input in inputs
        .iter()
        .filter(|input| !input.env.is_empty())
        .filter(|input| input.applies(inputs, values, platform))
    {
        let value = match values.get(&input.id) {
            Some(serde_json::Value::Null) | None => match &input.default {
                Some(default) => default_environment_string(default),
                None => continue,
            },
            Some(value) => environment_string(value),
        };
        for mapping in &input.env {
            if variables
                .iter()
                .any(|variable| variable.name == mapping.name)
            {
                return Err(alien_error::AlienError::new(
                    crate::ErrorData::GenericError {
                        message: format!(
                            "Stack inputs map more than one value to environment variable '{}'",
                            mapping.name
                        ),
                    },
                ));
            }
            let secret = match mapping.var_type {
                Some(StackInputEnvironmentVariableType::Secret) => true,
                Some(StackInputEnvironmentVariableType::Plain) => false,
                None => input.kind == StackInputKind::Secret,
            };
            variables.push(crate::EnvironmentVariable {
                name: mapping.name.clone(),
                value: value.clone(),
                var_type: if secret {
                    crate::EnvironmentVariableType::Secret
                } else {
                    crate::EnvironmentVariableType::Plain
                },
                target_resources: mapping.target_resources.clone(),
            });
        }
    }
    Ok(variables)
}

fn environment_string(value: &serde_json::Value) -> String {
    match value {
        serde_json::Value::String(value) => value.clone(),
        serde_json::Value::Array(items) => items
            .iter()
            .map(environment_string)
            .collect::<Vec<_>>()
            .join(","),
        other => other.to_string(),
    }
}

fn default_environment_string(default: &StackInputDefaultValue) -> String {
    match default {
        StackInputDefaultValue::String(value) | StackInputDefaultValue::Number(value) => {
            value.clone()
        }
        StackInputDefaultValue::Boolean(value) => value.to_string(),
        StackInputDefaultValue::StringList(values) => values.join(","),
    }
}

#[cfg(test)]
mod environment_tests {
    use std::collections::HashMap;

    use super::*;
    use crate::EnvironmentVariableType;

    #[test]
    fn an_env_mapping_targets_every_resource_or_its_patterns() {
        let mapping = |targets: Option<Vec<&str>>| StackInputEnvironmentMapping {
            name: "API_KEY".to_string(),
            target_resources: targets.map(|t| t.into_iter().map(String::from).collect()),
            var_type: None,
        };

        assert!(mapping(None).targets("api"));
        assert!(mapping(Some(vec!["api"])).targets("api"));
        assert!(!mapping(Some(vec!["api"])).targets("api-worker"));
        assert!(mapping(Some(vec!["api-*"])).targets("api-worker"));
        assert!(!mapping(Some(vec!["api-*"])).targets("web"));
        assert!(mapping(Some(vec!["api-*", "worker"])).targets("worker"));
        assert!(!mapping(Some(vec!["api-*", "worker"])).targets("scheduler"));
        assert!(!mapping(Some(vec![])).targets("api"));
    }

    fn input(id: &str, kind: StackInputKind, env: &str) -> StackInputDefinition {
        StackInputDefinition {
            id: id.to_string(),
            kind,
            when: None,
            provided_by: vec![StackInputProvider::Developer],
            required: false,
            label: id.to_string(),
            description: id.to_string(),
            placeholder: None,
            default: None,
            generate: None,
            platforms: None,
            validation: None,
            env: vec![StackInputEnvironmentMapping {
                name: env.to_string(),
                target_resources: Some(vec!["api".to_string()]),
                var_type: None,
            }],
        }
    }

    #[test]
    fn conditional_environment_uses_provided_boolean_before_default() {
        let toggle = StackInputDefinition::deployer_boolean(
            "enabled",
            "Enabled",
            "Enable snapshots",
            Some(true),
        );
        let mut bucket = input("bucket", StackInputKind::String, "BUCKET");
        bucket.required = true;
        bucket.when = Some(StackInputCondition {
            input: "enabled".into(),
            equals: true,
        });
        bucket.default = Some(StackInputDefaultValue::String("default-bucket".into()));
        let inputs = vec![toggle, bucket];
        for (answer, expected) in [
            (None, Some("default-bucket")),
            (Some(serde_json::json!(true)), Some("default-bucket")),
            (Some(serde_json::json!("true")), Some("default-bucket")),
            (Some(serde_json::json!(false)), None),
            (Some(serde_json::json!("false")), None),
        ] {
            let values = answer
                .map(|value| HashMap::from([("enabled".into(), value)]))
                .unwrap_or_default();
            let env =
                resolve_stack_input_environment_variables(&inputs, &values, Platform::Aws).unwrap();
            assert_eq!(
                env.first().map(|variable| variable.value.as_str()),
                expected
            );
        }
        let values = HashMap::from([
            ("enabled".into(), serde_json::json!(false)),
            ("bucket".into(), serde_json::json!({"invalid": "ignored"})),
        ]);
        assert!(
            resolve_stack_input_environment_variables(&inputs, &values, Platform::Aws)
                .unwrap()
                .is_empty()
        );
    }

    #[test]
    fn conditional_input_requires_an_answer_and_both_platform_scopes() {
        let mut toggle =
            StackInputDefinition::deployer_boolean("enabled", "Enabled", "Enable snapshots", None);
        toggle.platforms = Some(vec![Platform::Aws]);
        let mut bucket = input("bucket", StackInputKind::String, "BUCKET");
        bucket.when = Some(StackInputCondition {
            input: "enabled".into(),
            equals: false,
        });
        let mut inputs = vec![toggle, bucket];
        assert!(!inputs[1].applies(&inputs, &HashMap::new(), Platform::Aws));
        let values = HashMap::from([("enabled".into(), serde_json::json!(false))]);
        assert!(inputs[1].applies(&inputs, &values, Platform::Aws));
        assert!(inputs[1].applies(&inputs, &values, Platform::Kubernetes));
        inputs[1].when.as_mut().unwrap().equals = true;
        assert!(!inputs[1].applies(&inputs, &values, Platform::Kubernetes));
        inputs[0].platforms = Some(vec![]);
        assert!(inputs[0].applies_to(Platform::Aws));
        assert!(!inputs[1].applies(&inputs, &values, Platform::Aws));
        inputs[1].when.as_mut().unwrap().equals = false;
        assert!(inputs[1].applies(&inputs, &values, Platform::Aws));
        inputs[1].platforms = Some(vec![Platform::Kubernetes]);
        assert!(!inputs[1].applies(&inputs, &values, Platform::Aws));
    }

    #[test]
    fn delivery_preserves_stored_values_without_revalidation() {
        for (kind, value, validation) in [
            (
                StackInputKind::Number,
                "1.50",
                serde_json::json!({"min":"10"}),
            ),
            (StackInputKind::Number, "1e3", serde_json::json!({})),
            (
                StackInputKind::Integer,
                "007",
                serde_json::json!({"max":"5"}),
            ),
            (
                StackInputKind::String,
                "not-a-url",
                serde_json::json!({"format":"url"}),
            ),
            (
                StackInputKind::String,
                "",
                serde_json::json!({"minLength":3}),
            ),
        ] {
            let mut stored = input("stored", kind, "STORED");
            stored.required = true;
            stored.validation = Some(serde_json::from_value(validation).unwrap());
            let mut added = input("added", StackInputKind::String, "ADDED");
            added.required = true;
            let values = HashMap::from([("stored".into(), serde_json::json!(value))]);
            let variables =
                resolve_stack_input_environment_variables(&[stored, added], &values, Platform::Aws)
                    .expect("delivery must not revalidate existing deployments");
            assert_eq!(variables.len(), 1);
            assert_eq!(variables[0].name, "STORED");
            assert_eq!(variables[0].value, value);
        }
    }

    #[test]
    fn legacy_empty_platform_list_still_maps_environment() {
        let mut definition = input("region", StackInputKind::String, "REGION");
        definition.platforms = Some(vec![]);
        let values = HashMap::from([("region".into(), serde_json::json!("us-east-1"))]);
        let env = resolve_stack_input_environment_variables(&[definition], &values, Platform::Aws)
            .unwrap();
        assert_eq!(env.len(), 1);
        assert_eq!(env[0].value, "us-east-1");
    }

    #[test]
    fn maps_values_defaults_and_secrecy() {
        let mut region = input("region", StackInputKind::String, "REGION");
        region.default = Some(StackInputDefaultValue::String("eu-west-1".to_string()));
        let inputs = vec![
            input("token", StackInputKind::Secret, "ACCESS_TOKEN"),
            input("zones", StackInputKind::StringList, "ZONES"),
            region,
            input("unset", StackInputKind::String, "UNSET"),
        ];
        let values = HashMap::from([
            ("token".to_string(), serde_json::json!("s3cr3t")),
            ("zones".to_string(), serde_json::json!(["a", "b"])),
        ]);

        let variables =
            resolve_stack_input_environment_variables(&inputs, &values, Platform::Kubernetes)
                .unwrap();

        let by_name: HashMap<_, _> = variables.iter().map(|v| (v.name.as_str(), v)).collect();
        assert_eq!(
            variables.len(),
            3,
            "unset inputs without defaults produce nothing"
        );
        assert_eq!(by_name["ACCESS_TOKEN"].value, "s3cr3t");
        assert_eq!(
            by_name["ACCESS_TOKEN"].var_type,
            EnvironmentVariableType::Secret
        );
        assert_eq!(
            by_name["ACCESS_TOKEN"].target_resources,
            Some(vec!["api".to_string()])
        );
        assert_eq!(by_name["ZONES"].value, "a,b");
        assert_eq!(by_name["ZONES"].var_type, EnvironmentVariableType::Plain);
        assert_eq!(by_name["REGION"].value, "eu-west-1");
    }

    #[test]
    fn rejects_two_inputs_mapped_to_one_variable() {
        let inputs = vec![
            input("a", StackInputKind::String, "SHARED"),
            input("b", StackInputKind::String, "SHARED"),
        ];
        let values = HashMap::from([
            ("a".to_string(), serde_json::json!("1")),
            ("b".to_string(), serde_json::json!("2")),
        ]);
        let error =
            resolve_stack_input_environment_variables(&inputs, &values, Platform::Kubernetes)
                .expect_err("duplicate names must be rejected");
        assert!(error.message.contains("SHARED"));
    }

    #[test]
    fn legacy_empty_platform_scope_preserves_environment_variables() {
        let mut input = input("region", StackInputKind::String, "REGION");
        input.platforms = Some(vec![]);
        input.default = Some(StackInputDefaultValue::String("us-east-1".into()));
        let values = HashMap::from([("region".into(), serde_json::json!("us-west-2"))]);
        let variables =
            resolve_stack_input_environment_variables(&[input], &values, Platform::Aws).unwrap();
        assert_eq!(variables.len(), 1);
        assert_eq!(variables[0].name, "REGION");
        assert_eq!(variables[0].value, "us-west-2");
    }

    #[test]
    fn inputs_for_other_platforms_produce_nothing() {
        // An AWS-only input with a default must not reach a Kubernetes
        // workload, and may share a variable name with a Kubernetes one.
        let mut aws_only = input("aws-region", StackInputKind::String, "REGION");
        aws_only.platforms = Some(vec![Platform::Aws]);
        aws_only.default = Some(StackInputDefaultValue::String("us-east-1".to_string()));
        let mut kubernetes_only = input("zone", StackInputKind::String, "REGION");
        kubernetes_only.platforms = Some(vec![Platform::Kubernetes]);
        let values = HashMap::from([("zone".to_string(), serde_json::json!("rack-7"))]);

        let variables = resolve_stack_input_environment_variables(
            &[aws_only, kubernetes_only],
            &values,
            Platform::Kubernetes,
        )
        .unwrap();

        assert_eq!(variables.len(), 1);
        assert_eq!(variables[0].name, "REGION");
        assert_eq!(variables[0].value, "rack-7");
    }
}