1use std::collections::HashMap;
14
15use serde::{Deserialize, Serialize};
16
17use crate::{
18 vault_naming, BindingValue, EnvironmentVariable, EnvironmentVariableType, Platform,
19 StackInputDefinition, StackInputEnvironmentVariableType, StackInputKind, StackInputProvider,
20 VaultBinding,
21};
22
23pub const DEPLOYER_SECRET_VALUE_PLACEHOLDER: &str = "<VALUE>";
25
26pub fn deployer_secret_vault_key(input_id: &str) -> String {
32 let mut key = String::new();
33 let mut previous_lower_or_digit = false;
34 let mut pending_separator = false;
35 for character in input_id.chars() {
36 if character.is_ascii_alphanumeric() {
37 let starts_word = character.is_ascii_uppercase() && previous_lower_or_digit;
38 if (pending_separator || starts_word) && !key.is_empty() && !key.ends_with('-') {
39 key.push('-');
40 }
41 key.push(character.to_ascii_lowercase());
42 previous_lower_or_digit = character.is_ascii_lowercase() || character.is_ascii_digit();
43 pending_separator = false;
44 } else {
45 pending_separator = true;
46 previous_lower_or_digit = false;
47 }
48 }
49 key.trim_end_matches('-').to_string()
50}
51
52pub fn is_deployer_secret_input(input: &StackInputDefinition) -> bool {
54 input.kind == StackInputKind::Secret
55 && input.provided_by.contains(&StackInputProvider::Deployer)
56}
57
58pub fn deployer_secret_value_refusal(name: &str) -> String {
61 format!(
62 "'{name}' is a deployer secret: its value goes into your own secret store and never \
63 through Alien. Do not pass it here; write it into the deployment's deployer-secrets vault \
64 instead (the deployment status shows the secret's name and the command that writes it)."
65 )
66}
67
68#[derive(Debug, Clone, PartialEq, Eq)]
70pub struct DeployerSecretSlot<'a> {
71 pub input: &'a StackInputDefinition,
73 pub vault_key: String,
75 pub has_stored_value: bool,
78}
79
80pub fn deployer_secret_slots<'a>(
90 inputs: &'a [StackInputDefinition],
91 values: &HashMap<String, serde_json::Value>,
92 stored_secret_input_ids: Option<&[String]>,
93 environment: &[EnvironmentVariable],
94 platform: Platform,
95) -> Vec<DeployerSecretSlot<'a>> {
96 inputs
97 .iter()
98 .filter(|input| is_deployer_secret_input(input))
99 .filter(|input| input.applies(inputs, values, platform))
100 .filter_map(|input| {
101 let has_stored_value = stored_secret_input_ids
102 .is_some_and(|ids| ids.contains(&input.id))
103 || values.get(&input.id).is_some_and(|value| !value.is_null());
104 let developer_value = input.provided_by.contains(&StackInputProvider::Developer)
105 && (has_stored_value
106 || (stored_secret_input_ids.is_none()
107 && legacy_secret_delivery_complete(input, environment)));
108 (!developer_value).then(|| DeployerSecretSlot {
109 input,
110 vault_key: deployer_secret_vault_key(&input.id),
111 has_stored_value,
112 })
113 })
114 .collect()
115}
116
117pub fn protected_deployer_secret_slots<'a>(
122 inputs: &'a [StackInputDefinition],
123 values: &HashMap<String, serde_json::Value>,
124 platform: Platform,
125) -> Vec<DeployerSecretSlot<'a>> {
126 let values: HashMap<String, serde_json::Value> = values
127 .iter()
128 .filter(|(id, _)| {
129 !inputs
130 .iter()
131 .any(|input| &input.id == *id && is_deployer_secret_input(input))
132 })
133 .map(|(id, value)| (id.clone(), value.clone()))
134 .collect();
135 deployer_secret_slots(inputs, &values, Some(&[]), &[], platform)
136}
137
138fn legacy_secret_delivery_complete(
141 input: &StackInputDefinition,
142 environment: &[EnvironmentVariable],
143) -> bool {
144 !input.env.is_empty()
145 && input.env.iter().all(|mapping| {
146 let mut matches = environment
147 .iter()
148 .filter(|variable| variable.name == mapping.name);
149 let Some(variable) = matches.next() else {
150 return false;
151 };
152 if matches.next().is_some() {
154 return false;
155 }
156 !mapping.name.is_empty()
157 && mapping
158 .target_resources
159 .as_ref()
160 .is_none_or(|targets| !targets.is_empty())
161 && !matches!(
162 mapping.var_type,
163 Some(StackInputEnvironmentVariableType::Plain)
164 )
165 && variable.var_type == EnvironmentVariableType::Secret
166 && match (&mapping.target_resources, &variable.target_resources) {
167 (_, None) => true,
168 (None, Some(delivered)) => delivered.iter().any(|pattern| pattern == "*"),
169 (Some(required), Some(delivered)) => {
170 !required.is_empty()
171 && required.iter().all(|target| {
172 delivered.iter().any(|pattern| {
173 pattern == target
174 || pattern
175 .strip_suffix('*')
176 .is_some_and(|prefix| target.starts_with(prefix))
177 })
178 })
179 }
180 }
181 })
182}
183
184#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
186#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
187#[serde(rename_all = "kebab-case")]
188pub enum DeployerSecretStore {
189 AwsParameterStore,
191 GcpSecretManager,
193 AzureKeyVault,
195 KubernetesSecret,
197 LocalVault,
199}
200
201#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
203#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
204#[serde(rename_all = "camelCase")]
205pub struct DeployerSecretCommandVariants {
206 pub inline: String,
208 pub prompt: String,
210}
211
212#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
214#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
215#[serde(rename_all = "camelCase")]
216pub struct DeployerSecretCommands {
217 pub unix: DeployerSecretCommandVariants,
219 pub windows: DeployerSecretCommandVariants,
221 #[serde(default, skip_serializing_if = "Option::is_none")]
223 pub target: Option<String>,
224 #[serde(default, skip_serializing_if = "Option::is_none")]
226 pub check_command: Option<String>,
227}
228
229#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
231#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
232#[serde(rename_all = "camelCase")]
233pub struct DeployerSecretLocation {
234 pub store: DeployerSecretStore,
236 pub name: String,
238 #[serde(default, skip_serializing_if = "Option::is_none")]
241 pub vault_name: Option<String>,
242 #[serde(default, skip_serializing_if = "Option::is_none")]
244 pub console_url: Option<String>,
245 pub cli_command: String,
247 #[serde(default, skip_serializing_if = "Option::is_none")]
249 pub commands: Option<DeployerSecretCommands>,
250 #[serde(default, skip_serializing_if = "Option::is_none")]
253 pub delete_command: Option<String>,
254}
255
256#[derive(Debug, Clone, Default, PartialEq, Eq)]
258pub struct DeployerSecretLocationContext {
259 pub secret_label: Option<String>,
261 pub aws_account_id: Option<String>,
263 pub aws_region: Option<String>,
265 pub gcp_project_id: Option<String>,
267 pub azure_subscription_id: Option<String>,
269 pub azure_resource_group: Option<String>,
271 pub deployment_name: Option<String>,
273}
274
275pub fn deployer_secret_location(
278 binding: &VaultBinding,
279 vault_key: &str,
280 context: &DeployerSecretLocationContext,
281) -> crate::Result<DeployerSecretLocation> {
282 let label = context.secret_label.as_deref().unwrap_or(vault_key);
283 let mut prepare = String::new();
284 let mut location = match binding {
285 VaultBinding::ParameterStore(binding) => {
286 let prefix = concrete(&binding.vault_prefix, "vaultPrefix")?;
287 let name = vault_naming::parameter_store_parameter_name(&prefix, vault_key);
288 let region = context.aws_region.as_deref();
289 let region_flag = region
290 .map(|region| format!(" --region {}", shell_quote(region)))
291 .unwrap_or_default();
292 DeployerSecretLocation {
293 commands: None,
294 store: DeployerSecretStore::AwsParameterStore,
295 vault_name: None,
296 console_url: region.map(|region| {
297 format!(
298 "https://{region}.console.aws.amazon.com/systems-manager/parameters/create?region={region}"
299 )
300 }),
301 cli_command: format!(
302 "aws ssm put-parameter{region_flag} --name {} --type SecureString --overwrite --value file:///dev/stdin", shell_quote(&name)
303 ),
304 delete_command: Some(format!(
305 "aws ssm delete-parameter{region_flag} --name '{name}'"
306 )),
307 name,
308 }
309 }
310 VaultBinding::SecretManager(binding) => {
311 let prefix = concrete(&binding.vault_prefix, "vaultPrefix")?;
312 let name = vault_naming::secret_manager_secret_id(&prefix, vault_key);
313 let project = context.gcp_project_id.as_deref();
314 let project_flag = project
315 .map(|project| format!(" --project {}", shell_quote(project)))
316 .unwrap_or_default();
317 prepare = format!(
318 "(gcloud secrets describe {0}{project_flag} >/dev/null 2>&1 || gcloud secrets create {0}{project_flag} --replication-policy=automatic) &&\n",
319 shell_quote(&name)
320 );
321 DeployerSecretLocation {
322 commands: None,
323 store: DeployerSecretStore::GcpSecretManager,
324 vault_name: None,
325 console_url: project.map(|project| {
326 format!(
327 "https://console.cloud.google.com/security/secret-manager/create?project={project}"
328 )
329 }),
330 cli_command: format!(
333 "gcloud secrets versions add {}{project_flag} --data-file=-", shell_quote(&name)
334 ),
335 delete_command: Some(format!(
336 "gcloud secrets delete {name}{project_flag} --quiet"
337 )),
338 name,
339 }
340 }
341 VaultBinding::KeyVault(binding) => {
342 let vault_name = concrete(&binding.vault_name, "vaultName")?;
343 let name = vault_naming::key_vault_secret_name(vault_key);
344 DeployerSecretLocation {
345 commands: None,
346 store: DeployerSecretStore::AzureKeyVault,
347 vault_name: Some(vault_name.clone()),
348 console_url: match (
349 context.azure_subscription_id.as_deref(),
350 context.azure_resource_group.as_deref(),
351 ) {
352 (Some(subscription), Some(resource_group)) => Some(format!(
353 "https://portal.azure.com/#@/resource/subscriptions/{subscription}/resourceGroups/{resource_group}/providers/Microsoft.KeyVault/vaults/{vault_name}/secrets"
354 )),
355 _ => None,
356 },
357 cli_command: format!(
358 "az keyvault secret set --vault-name {} --name {} --file /dev/stdin --encoding utf-8 --output none",
359 shell_quote(&vault_name),
360 shell_quote(&name)
361 ),
362 delete_command: Some(format!(
363 "az keyvault secret delete --vault-name {vault_name} --name {name}"
364 )),
365 name,
366 }
367 }
368 VaultBinding::KubernetesSecret(binding) => {
369 let prefix = concrete(&binding.vault_prefix, "vaultPrefix")?;
370 let namespace = concrete(&binding.namespace, "namespace")?;
371 let name = vault_naming::kubernetes_secret_name(&prefix, vault_key);
372 DeployerSecretLocation {
373 commands: None,
374 store: DeployerSecretStore::KubernetesSecret,
375 vault_name: None,
376 console_url: None,
377 cli_command: format!(
378 "kubectl create secret generic {} --namespace {} --from-file={}=/dev/stdin --dry-run=client -o yaml | kubectl apply -f -",
379 shell_quote(&name),
380 shell_quote(&namespace),
381 vault_naming::KUBERNETES_SECRET_VALUE_KEY
382 ),
383 delete_command: Some(format!(
384 "kubectl delete secret {name} --namespace {namespace}"
385 )),
386 name,
387 }
388 }
389 VaultBinding::Local(binding) => {
390 let deployment_flag = context
391 .deployment_name
392 .as_deref()
393 .map(|name| format!(" --deployment {}", shell_quote(name)))
394 .unwrap_or_default();
395 DeployerSecretLocation {
396 commands: None,
397 store: DeployerSecretStore::LocalVault,
398 vault_name: None,
399 console_url: None,
400 cli_command: format!(
401 "alien dev vault{deployment_flag} set {} {} --stdin",
402 shell_quote(&binding.vault_name),
403 shell_quote(vault_key)
404 ),
405 delete_command: Some(format!(
406 "alien dev vault{deployment_flag} delete {} {vault_key}",
407 binding.vault_name
408 )),
409 name: vault_key.to_string(),
410 }
411 }
412 };
413 let unix_inline = match location.store {
414 DeployerSecretStore::AwsParameterStore => location
415 .cli_command
416 .replace("file:///dev/stdin", "'<VALUE>'"),
417 DeployerSecretStore::AzureKeyVault => location
418 .cli_command
419 .replace("--file /dev/stdin --encoding utf-8", "--value '<VALUE>'"),
420 DeployerSecretStore::KubernetesSecret => location.cli_command.replace(
421 "--from-file=value=/dev/stdin",
422 "--from-literal=value='<VALUE>'",
423 ),
424 DeployerSecretStore::LocalVault => format!(
425 "{} '<VALUE>'",
426 location.cli_command.trim_end_matches(" --stdin")
427 ),
428 DeployerSecretStore::GcpSecretManager => format!(
429 "{}printf '%s' '<VALUE>' | {}",
430 prepare.replace('\n', " "),
431 location.cli_command
432 ),
433 };
434 let windows = windows_secret_commands(binding, vault_key, context)?;
435 let prompt = shell_quote(&format!("{label}: "));
438 location.cli_command = format!(
439 "(set +x; set -o pipefail; printf '%s' {prompt} >&2; IFS= read -rs secret || [ -n \"$secret\" ]\n[ -n \"$secret\" ] && printf '\\n' >&2 && {prepare}printf '%s' \"$secret\" | {}\n)",
440 location.cli_command,
441 prepare = prepare.replace('\n', " "),
442 );
443 let (target, check_command) = match binding {
444 VaultBinding::ParameterStore(_) => (
445 context.aws_account_id.clone(),
446 Some("aws sts get-caller-identity --query Account --output text".to_string()),
447 ),
448 VaultBinding::SecretManager(_) => (
449 context.gcp_project_id.clone(),
450 Some("gcloud auth list --filter=status:ACTIVE --format=\"value(account)\"".to_string()),
451 ),
452 VaultBinding::KeyVault(_) => (
453 context.azure_subscription_id.clone(),
454 Some("az account show --query id --output tsv".to_string()),
455 ),
456 VaultBinding::KubernetesSecret(binding) => (
457 Some(concrete(&binding.namespace, "namespace")?),
458 Some("kubectl config current-context".to_string()),
459 ),
460 VaultBinding::Local(_) => (context.deployment_name.clone(), None),
461 };
462 location.commands = Some(DeployerSecretCommands {
463 unix: DeployerSecretCommandVariants {
464 inline: unix_inline,
465 prompt: location.cli_command.clone(),
466 },
467 windows,
468 target,
469 check_command,
470 });
471 Ok(location)
472}
473
474fn windows_secret_commands(
477 binding: &VaultBinding,
478 vault_key: &str,
479 context: &DeployerSecretLocationContext,
480) -> crate::Result<DeployerSecretCommandVariants> {
481 let mut prepare = String::new();
482 let write = match binding {
483 VaultBinding::ParameterStore(binding) => {
484 let name = vault_naming::parameter_store_parameter_name(
485 &concrete(&binding.vault_prefix, "vaultPrefix")?,
486 vault_key,
487 );
488 let region = context
489 .aws_region
490 .as_deref()
491 .map(|value| format!(" --region {}", powershell_quote(value)))
492 .unwrap_or_default();
493 format!(
494 "aws ssm put-parameter{region} --name {} --type SecureString --overwrite --value \"file://$path\"",
495 powershell_quote(&name)
496 )
497 }
498 VaultBinding::SecretManager(binding) => {
499 let name = powershell_quote(&vault_naming::secret_manager_secret_id(
500 &concrete(&binding.vault_prefix, "vaultPrefix")?,
501 vault_key,
502 ));
503 let project = context
504 .gcp_project_id
505 .as_deref()
506 .map(|value| format!(" --project {}", powershell_quote(value)))
507 .unwrap_or_default();
508 prepare = format!(
509 "gcloud secrets describe {name}{project} 2>$null | Out-Null; if ($LASTEXITCODE -ne 0) {{ gcloud secrets create {name}{project} --replication-policy=automatic; if ($LASTEXITCODE -ne 0) {{ throw 'Could not create secret' }} }}; "
510 );
511 format!("gcloud secrets versions add {name}{project} --data-file=$path")
512 }
513 VaultBinding::KeyVault(binding) => format!(
514 "az keyvault secret set --vault-name {} --name {} --file $path --encoding utf-8 --output none",
515 powershell_quote(&concrete(&binding.vault_name, "vaultName")?),
516 powershell_quote(&vault_naming::key_vault_secret_name(vault_key))
517 ),
518 VaultBinding::KubernetesSecret(binding) => format!(
519 "kubectl create secret generic {} --namespace {} --from-file=\"value=$path\" --dry-run=client -o yaml | kubectl apply -f -",
520 powershell_quote(&vault_naming::kubernetes_secret_name(
521 &concrete(&binding.vault_prefix, "vaultPrefix")?,
522 vault_key
523 )),
524 powershell_quote(&concrete(&binding.namespace, "namespace")?)
525 ),
526 VaultBinding::Local(binding) => {
527 let deployment = context
528 .deployment_name
529 .as_deref()
530 .map(|value| format!(" --deployment {}", powershell_quote(value)))
531 .unwrap_or_default();
532 format!(
533 "alien dev vault{deployment} set {} {} --file $path",
534 powershell_quote(&binding.vault_name),
535 powershell_quote(vault_key)
536 )
537 }
538 };
539 let file = "$path = [IO.Path]::GetTempFileName()";
540 let save = "[IO.File]::WriteAllText($path, $value, (New-Object Text.UTF8Encoding $false))";
541 let cleanup = "Remove-Item -LiteralPath $path -Force; $value = $null";
542 let result = "; if ($LASTEXITCODE -ne 0) { throw 'Could not write secret' }";
543 let inline = format!(
544 "& {{ $value = '<VALUE>'; {file}; try {{ {save}; {prepare}{write}{result} }} finally {{ {cleanup} }} }}"
545 );
546 let inline = match binding {
547 VaultBinding::ParameterStore(_) => write.replace("\"file://$path\"", "'<VALUE>'"),
548 VaultBinding::KeyVault(_) => {
549 write.replace("--file $path --encoding utf-8", "--value '<VALUE>'")
550 }
551 VaultBinding::KubernetesSecret(_) => write.replace(
552 "--from-file=\"value=$path\"",
553 "--from-literal=value='<VALUE>'",
554 ),
555 VaultBinding::Local(binding) => {
556 let deployment = context
557 .deployment_name
558 .as_deref()
559 .map(|value| format!(" --deployment {}", powershell_quote(value)))
560 .unwrap_or_default();
561 format!(
562 "alien dev vault{deployment} set {} {} '<VALUE>'",
563 powershell_quote(&binding.vault_name),
564 powershell_quote(vault_key)
565 )
566 }
567 VaultBinding::SecretManager(_) => inline,
568 };
569 let label = powershell_quote(context.secret_label.as_deref().unwrap_or(vault_key));
570 let prompt = format!(
573 "& {{ $value = [Net.NetworkCredential]::new('', (Read-Host {label} -AsSecureString)).Password\nif (!$value) {{ return }}\n{file}\ntry {{ {save}\n{prepare}{write}{result}\n}} finally {{ {cleanup} }} }}"
574 );
575 Ok(DeployerSecretCommandVariants { inline, prompt })
576}
577
578fn powershell_quote(value: &str) -> String {
579 format!("'{}'", value.replace('\'', "''"))
580}
581
582fn shell_quote(value: &str) -> String {
583 if !value.is_empty()
584 && value
585 .bytes()
586 .all(|byte| byte.is_ascii_alphanumeric() || b"-_./:@".contains(&byte))
587 {
588 value.to_string()
589 } else {
590 format!("'{}'", value.replace('\'', "'\"'\"'"))
591 }
592}
593
594fn concrete(value: &BindingValue<String>, field: &str) -> crate::Result<String> {
595 value
596 .clone()
597 .into_value(crate::DEPLOYER_SECRETS_VAULT_ID, field)
598}
599
600#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
603#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
604#[serde(rename_all = "kebab-case")]
605pub enum DeployerSecretStatus {
606 Present,
608 Missing,
610 Invalid,
613}
614
615#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
617#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
618#[serde(rename_all = "camelCase")]
619pub struct DeployerSecretReport {
620 pub input_id: String,
622 pub label: String,
624 pub required: bool,
626 pub status: DeployerSecretStatus,
628 #[serde(default, skip_serializing_if = "Option::is_none")]
630 pub message: Option<String>,
631 #[serde(default, skip_serializing_if = "Option::is_none")]
634 pub version: Option<String>,
635 pub location: DeployerSecretLocation,
637}
638
639impl DeployerSecretReport {
640 pub fn blocks_start(&self) -> bool {
642 self.required && self.status != DeployerSecretStatus::Present
643 }
644
645 pub fn summary(&self) -> String {
648 match self.status {
649 DeployerSecretStatus::Present => format!("present: {}", self.label),
650 DeployerSecretStatus::Missing => format!("missing: {}", self.label),
651 DeployerSecretStatus::Invalid => match &self.message {
652 Some(message) => format!("invalid: {} ({message})", self.label),
653 None => format!("invalid: {}", self.label),
654 },
655 }
656 }
657}
658
659pub const ENV_ALIEN_DEPLOYER_SECRETS: &str = "ALIEN_DEPLOYER_SECRETS";
664
665#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
668#[serde(rename_all = "camelCase")]
669pub struct DeployerSecretEnv {
670 pub name: String,
672 pub vault_key: String,
674 pub secret_name: String,
676 #[serde(default, skip_serializing_if = "Option::is_none")]
679 pub vault_name: Option<String>,
680 pub label: String,
682 pub required: bool,
684 #[serde(default, skip_serializing_if = "Option::is_none")]
688 pub version: Option<String>,
689}
690
691pub fn deployer_secret_environment(
700 inputs: &[StackInputDefinition],
701 values: &HashMap<String, serde_json::Value>,
702 stored_secret_input_ids: Option<&[String]>,
703 environment: &[EnvironmentVariable],
704 platform: Platform,
705 reports: &[DeployerSecretReport],
706) -> Vec<(DeployerSecretEnv, Option<Vec<String>>)> {
707 deployer_secret_slots(
708 inputs,
709 values,
710 stored_secret_input_ids,
711 environment,
712 platform,
713 )
714 .into_iter()
715 .filter(|slot| !slot.has_stored_value)
718 .filter_map(|slot| {
719 reports
720 .iter()
721 .find(|report| report.input_id == slot.input.id)
722 .map(|report| (slot, report))
723 })
724 .flat_map(|(slot, report)| {
725 slot.input.env.iter().map(move |mapping| {
726 (
727 DeployerSecretEnv {
728 name: mapping.name.clone(),
729 vault_key: slot.vault_key.clone(),
730 secret_name: report.location.name.clone(),
731 vault_name: report.location.vault_name.clone(),
732 label: slot.input.label.clone(),
733 required: slot.input.required,
734 version: report.version.clone(),
735 },
736 mapping.target_resources.clone(),
737 )
738 })
739 })
740 .collect()
741}
742
743#[cfg(test)]
744mod tests {
745 use super::*;
746 use crate::StackInputEnvironmentMapping;
747
748 fn secret(id: &str, provided_by: Vec<StackInputProvider>) -> StackInputDefinition {
749 StackInputDefinition {
750 id: id.to_string(),
751 kind: StackInputKind::Secret,
752 when: None,
753 provided_by,
754 required: true,
755 label: "Database password".to_string(),
756 description: String::new(),
757 placeholder: None,
758 default: None,
759 platforms: None,
760 validation: None,
761 generate: None,
762 env: vec![StackInputEnvironmentMapping {
763 name: "DATABASE_PASSWORD".to_string(),
764 target_resources: None,
765 var_type: None,
766 }],
767 }
768 }
769
770 #[test]
771 fn legacy_omitted_presence_uses_only_complete_scoped_secret_delivery() {
772 let base = serde_json::json!({
773 "environmentVariables": {
774 "variables": [{"name": "DATABASE_PASSWORD", "value": "fixture-value", "type": "secret"}],
775 "hash": "fixture", "createdAt": "2026-01-01T00:00:00Z"
776 }
777 });
778 let legacy: crate::DeploymentConfig = serde_json::from_value(base.clone()).unwrap();
779 assert_eq!(legacy.stored_secret_input_ids, None);
780 let input = secret(
781 "databasePassword",
782 vec![StackInputProvider::Developer, StackInputProvider::Deployer],
783 );
784 for case in [
785 "legacy",
786 "null",
787 "empty",
788 "unrelated",
789 "missing",
790 "plain",
791 "wrong-name",
792 "partial",
793 "narrow",
794 "matching-scope",
795 "broader-scope",
796 "deployer-only",
797 "no-mappings",
798 "plain-mapping",
799 "duplicate-plain",
800 "duplicate-scoped-secret",
801 ] {
802 let mut wire = base.clone();
803 let mut input = input.clone();
804 match case {
805 "null" => wire["storedSecretInputIds"] = serde_json::Value::Null,
806 "empty" => wire["storedSecretInputIds"] = serde_json::json!([]),
807 "unrelated" => wire["storedSecretInputIds"] = serde_json::json!(["other"]),
808 "missing" => wire["environmentVariables"]["variables"] = serde_json::json!([]),
809 "plain" => {
810 wire["environmentVariables"]["variables"][0]["type"] =
811 serde_json::json!("plain")
812 }
813 "duplicate-plain" | "duplicate-scoped-secret" => {
814 let mut duplicate = wire["environmentVariables"]["variables"][0].clone();
815 if case == "duplicate-plain" {
816 duplicate["type"] = serde_json::json!("plain");
817 } else {
818 input.env[0].target_resources = Some(vec!["app".to_string()]);
819 wire["environmentVariables"]["variables"][0]["targetResources"] =
820 serde_json::json!(["app"]);
821 duplicate["targetResources"] = serde_json::json!(["other"]);
822 }
823 wire["environmentVariables"]["variables"]
824 .as_array_mut()
825 .unwrap()
826 .push(duplicate);
827 }
828 "wrong-name" => {
829 wire["environmentVariables"]["variables"][0]["name"] =
830 serde_json::json!("OTHER")
831 }
832 "partial" => {
833 let mut mapping = input.env[0].clone();
834 mapping.name = "SECOND".to_string();
835 input.env.push(mapping);
836 }
837 "narrow" => {
838 wire["environmentVariables"]["variables"][0]["targetResources"] =
839 serde_json::json!(["app"])
840 }
841 "matching-scope" => {
842 input.env[0].target_resources = Some(vec!["app*".to_string()]);
843 wire["environmentVariables"]["variables"][0]["targetResources"] =
844 serde_json::json!(["app*"]);
845 }
846 "broader-scope" => input.env[0].target_resources = Some(vec!["app".to_string()]),
847 "deployer-only" => input.provided_by = vec![StackInputProvider::Deployer],
848 "no-mappings" => input.env.clear(),
849 "plain-mapping" => {
850 input.env[0].var_type = Some(StackInputEnvironmentVariableType::Plain)
851 }
852 _ => {}
853 }
854 let config: crate::DeploymentConfig = serde_json::from_value(wire).unwrap();
855 let inputs = [input];
856 let delivered = matches!(case, "legacy" | "null" | "matching-scope" | "broader-scope");
857 let slots = deployer_secret_slots(
858 &inputs,
859 &config.input_values,
860 config.stored_secret_input_ids.as_deref(),
861 &config.environment_variables.variables,
862 Platform::Aws,
863 );
864 assert_eq!(slots.is_empty(), delivered, "{case}");
865 let reports = [report("databasePassword", DeployerSecretStatus::Present)];
866 let pointers = deployer_secret_environment(
867 &inputs,
868 &config.input_values,
869 config.stored_secret_input_ids.as_deref(),
870 &config.environment_variables.variables,
871 Platform::Aws,
872 &reports,
873 );
874 assert_eq!(
875 pointers.len(),
876 if delivered || case == "no-mappings" {
877 0
878 } else {
879 inputs[0].env.len()
880 },
881 "{case}"
882 );
883 assert!(config.input_values.is_empty());
884 assert!(is_deployer_secret_input(&inputs[0]));
885 }
886 }
887
888 #[test]
889 fn vault_keys_are_kebab_case_and_backend_safe() {
890 assert_eq!(
891 deployer_secret_vault_key("databasePassword"),
892 "database-password"
893 );
894 assert_eq!(deployer_secret_vault_key("api_key"), "api-key");
895 assert_eq!(deployer_secret_vault_key("OAuth2Token"), "oauth2-token");
896 assert_eq!(deployer_secret_vault_key("a--b__c"), "a-b-c");
897 }
898
899 #[test]
900 fn deployer_only_secrets_are_slots_even_with_a_stored_value() {
901 let inputs = vec![secret(
902 "databasePassword",
903 vec![StackInputProvider::Deployer],
904 )];
905 let stored = HashMap::from([(
906 "databasePassword".to_string(),
907 serde_json::json!("from-before"),
908 )]);
909
910 let slots = deployer_secret_slots(&inputs, &stored, Some(&[]), &[], Platform::Aws);
911 assert_eq!(slots.len(), 1);
912 assert_eq!(slots[0].vault_key, "database-password");
913 assert!(slots[0].has_stored_value);
914 }
915
916 #[test]
917 fn a_developer_value_keeps_a_dual_provided_secret_off_the_vault_path() {
918 let inputs = vec![secret(
919 "databasePassword",
920 vec![StackInputProvider::Developer, StackInputProvider::Deployer],
921 )];
922 let with_developer_value =
923 HashMap::from([("databasePassword".to_string(), serde_json::json!("dev"))]);
924
925 assert!(deployer_secret_slots(
926 &inputs,
927 &with_developer_value,
928 Some(&[]),
929 &[],
930 Platform::Aws
931 )
932 .is_empty());
933 assert_eq!(
934 deployer_secret_slots(&inputs, &HashMap::new(), Some(&[]), &[], Platform::Aws).len(),
935 1
936 );
937 }
938
939 #[test]
940 fn legacy_empty_platform_scope_preserves_secret_slots() {
941 let mut input = secret("token", vec![StackInputProvider::Deployer]);
942 input.platforms = Some(vec![]);
943 assert_eq!(
944 deployer_secret_slots(&[input], &HashMap::new(), Some(&[]), &[], Platform::Aws).len(),
945 1
946 );
947 }
948
949 #[test]
950 fn developer_secrets_and_other_platforms_are_not_slots() {
951 let mut aws_only = secret("token", vec![StackInputProvider::Deployer]);
952 aws_only.platforms = Some(vec![Platform::Aws]);
953 let inputs = vec![secret("key", vec![StackInputProvider::Developer]), aws_only];
954
955 assert!(
956 deployer_secret_slots(&inputs, &HashMap::new(), Some(&[]), &[], Platform::Gcp)
957 .is_empty()
958 );
959 }
960
961 #[test]
962 fn locations_name_the_same_secret_the_vault_reads() {
963 let context = DeployerSecretLocationContext {
964 aws_region: Some("us-east-1".to_string()),
965 gcp_project_id: Some("acme-prod".to_string()),
966 deployment_name: Some("default".to_string()),
967 ..Default::default()
968 };
969 let key = "database-password";
970
971 let aws = deployer_secret_location(
972 &VaultBinding::parameter_store("stack-deployer-secrets"),
973 key,
974 &context,
975 )
976 .unwrap();
977 assert_eq!(aws.name, "stack-deployer-secrets-database-password");
978 assert_eq!(aws.store, DeployerSecretStore::AwsParameterStore);
979 assert!(aws.cli_command.contains("--type SecureString"));
980
981 assert_eq!(
982 aws.delete_command.as_deref(),
983 Some(
984 "aws ssm delete-parameter --region us-east-1 --name 'stack-deployer-secrets-database-password'"
985 )
986 );
987
988 let gcp = deployer_secret_location(
989 &VaultBinding::secret_manager("stack-deployer-secrets"),
990 key,
991 &context,
992 )
993 .unwrap();
994 assert_eq!(gcp.name, "stack-deployer-secrets-database-password");
995 assert_eq!(gcp.vault_name, None);
996 assert!(gcp.console_url.unwrap().contains("project=acme-prod"));
997 assert_eq!(
998 gcp.delete_command.as_deref(),
999 Some(
1000 "gcloud secrets delete stack-deployer-secrets-database-password --project acme-prod --quiet"
1001 )
1002 );
1003
1004 let azure =
1007 deployer_secret_location(&VaultBinding::key_vault("stacksecrets7f3a"), key, &context)
1008 .unwrap();
1009 assert_eq!(azure.store, DeployerSecretStore::AzureKeyVault);
1010 assert_eq!(azure.vault_name.as_deref(), Some("stacksecrets7f3a"));
1011 assert!(azure.cli_command.contains("--vault-name stacksecrets7f3a"));
1012 assert_eq!(
1013 azure.delete_command,
1014 Some(format!(
1015 "az keyvault secret delete --vault-name stacksecrets7f3a --name {}",
1016 azure.name
1017 ))
1018 );
1019
1020 let kubernetes = deployer_secret_location(
1021 &VaultBinding::kubernetes_secret("apps", "Stack-Deployer-Secrets"),
1022 key,
1023 &context,
1024 )
1025 .unwrap();
1026 assert_eq!(kubernetes.name, "stack-deployer-secrets-database-password");
1027 assert!(kubernetes.cli_command.contains("--namespace apps"));
1028 assert_eq!(
1029 kubernetes.delete_command.as_deref(),
1030 Some("kubectl delete secret stack-deployer-secrets-database-password --namespace apps")
1031 );
1032
1033 let local = deployer_secret_location(
1034 &VaultBinding::local("deployer-secrets", "/tmp/x"),
1035 key,
1036 &context,
1037 )
1038 .unwrap();
1039
1040 assert_eq!(
1041 local.delete_command.as_deref(),
1042 Some("alien dev vault --deployment default delete deployer-secrets database-password")
1043 );
1044 }
1045
1046 #[test]
1047 fn a_template_expression_has_no_location() {
1048 let binding = VaultBinding::ParameterStore(crate::ParameterStoreVaultBinding {
1049 vault_prefix: BindingValue::expression(serde_json::json!({"Ref": "Prefix"})),
1050 });
1051 assert!(
1052 deployer_secret_location(&binding, "x", &DeployerSecretLocationContext::default())
1053 .is_err()
1054 );
1055 }
1056
1057 #[test]
1058 fn only_required_unfilled_slots_block_start() {
1059 let location = deployer_secret_location(
1060 &VaultBinding::local("deployer-secrets", "/tmp/x"),
1061 "x",
1062 &DeployerSecretLocationContext::default(),
1063 )
1064 .unwrap();
1065 let mut report = DeployerSecretReport {
1066 input_id: "x".to_string(),
1067 label: "Database password".to_string(),
1068 required: true,
1069 status: DeployerSecretStatus::Missing,
1070 message: None,
1071 version: None,
1072 location,
1073 };
1074 assert!(report.blocks_start());
1075 assert_eq!(report.summary(), "missing: Database password");
1076
1077 report.required = false;
1078 assert!(!report.blocks_start());
1079
1080 report.required = true;
1081 report.status = DeployerSecretStatus::Present;
1082 assert!(!report.blocks_start());
1083 }
1084
1085 fn report(input_id: &str, status: DeployerSecretStatus) -> DeployerSecretReport {
1086 DeployerSecretReport {
1087 input_id: input_id.to_string(),
1088 label: "Database password".to_string(),
1089 required: true,
1090 status,
1091 message: None,
1092 version: None,
1093 location: DeployerSecretLocation {
1094 commands: None,
1095 store: DeployerSecretStore::AwsParameterStore,
1096 name: "stack-deployer-secrets-database-password".to_string(),
1097 vault_name: None,
1098 console_url: None,
1099 cli_command: String::new(),
1100 delete_command: None,
1101 },
1102 }
1103 }
1104
1105 #[test]
1106 fn a_slot_is_read_from_the_vault_once_it_is_reported() {
1107 let inputs = vec![secret(
1108 "databasePassword",
1109 vec![StackInputProvider::Deployer],
1110 )];
1111 let no_values = HashMap::new();
1112
1113 assert!(deployer_secret_environment(
1114 &inputs,
1115 &no_values,
1116 Some(&[]),
1117 &[],
1118 Platform::Aws,
1119 &[]
1120 )
1121 .is_empty());
1122
1123 let env = deployer_secret_environment(
1124 &inputs,
1125 &no_values,
1126 Some(&[]),
1127 &[],
1128 Platform::Aws,
1129 &[report("databasePassword", DeployerSecretStatus::Missing)],
1130 );
1131 assert_eq!(env.len(), 1);
1132 let (variable, targets) = &env[0];
1133 assert_eq!(variable.name, "DATABASE_PASSWORD");
1134 assert_eq!(variable.vault_key, "database-password");
1135 assert_eq!(
1136 variable.secret_name,
1137 "stack-deployer-secrets-database-password"
1138 );
1139 assert!(variable.required);
1140 assert_eq!(variable.vault_name, None);
1141 assert_eq!(targets, &None);
1142 }
1143
1144 #[test]
1145 fn a_key_vault_slot_names_its_vault_for_the_workload() {
1146 let inputs = vec![secret(
1147 "databasePassword",
1148 vec![StackInputProvider::Deployer],
1149 )];
1150 let location = deployer_secret_location(
1151 &VaultBinding::key_vault("stacksecrets7f3a"),
1152 "database-password",
1153 &DeployerSecretLocationContext::default(),
1154 )
1155 .unwrap();
1156 let mut azure_report = report("databasePassword", DeployerSecretStatus::Present);
1157 azure_report.location = location;
1158
1159 let env = deployer_secret_environment(
1160 &inputs,
1161 &HashMap::new(),
1162 Some(&[]),
1163 &[],
1164 Platform::Azure,
1165 &[azure_report],
1166 );
1167
1168 assert_eq!(env.len(), 1);
1169 assert_eq!(env[0].0.secret_name, "database-password");
1170 assert_eq!(env[0].0.vault_name.as_deref(), Some("stacksecrets7f3a"));
1171 }
1172
1173 #[test]
1174 fn a_stored_value_keeps_today_s_path_until_it_is_dropped() {
1175 let inputs = vec![secret(
1176 "databasePassword",
1177 vec![StackInputProvider::Deployer],
1178 )];
1179 let stored = HashMap::from([(
1180 "databasePassword".to_string(),
1181 serde_json::json!("from-before"),
1182 )]);
1183
1184 assert!(deployer_secret_environment(
1185 &inputs,
1186 &stored,
1187 Some(&[]),
1188 &[],
1189 Platform::Aws,
1190 &[report("databasePassword", DeployerSecretStatus::Missing)],
1191 )
1192 .is_empty());
1193 assert!(
1194 deployer_secret_environment(
1195 &inputs,
1196 &stored,
1197 Some(&[]),
1198 &[],
1199 Platform::Aws,
1200 &[report("databasePassword", DeployerSecretStatus::Present)],
1201 )
1202 .is_empty(),
1203 "a filled slot is not read while the stored value has no vault read grant"
1204 );
1205 assert_eq!(
1206 deployer_secret_environment(
1207 &inputs,
1208 &HashMap::new(),
1209 Some(&[]),
1210 &[],
1211 Platform::Aws,
1212 &[report("databasePassword", DeployerSecretStatus::Present)],
1213 )
1214 .len(),
1215 1
1216 );
1217 }
1218 #[test]
1219 fn stored_secret_ids_classify_presence_without_input_values() {
1220 for required in [true, false] {
1221 let mut input = secret(
1222 "apiKey",
1223 vec![StackInputProvider::Developer, StackInputProvider::Deployer],
1224 );
1225 input.required = required;
1226 let inputs = vec![input];
1227 let values = HashMap::new();
1228 let present = vec!["apiKey".to_string()];
1229 assert!(
1230 deployer_secret_slots(&inputs, &values, Some(&present), &[], Platform::Aws)
1231 .is_empty()
1232 );
1233 for ids in [vec![], vec!["removedInput".to_string()]] {
1234 let slots = deployer_secret_slots(&inputs, &values, Some(&ids), &[], Platform::Aws);
1235 assert_eq!(slots.len(), 1);
1236 assert!(!slots[0].has_stored_value);
1237 assert_eq!(slots[0].input.required, required);
1238 }
1239 let null_value = HashMap::from([("apiKey".to_string(), serde_json::Value::Null)]);
1240 assert!(deployer_secret_slots(
1241 &inputs,
1242 &null_value,
1243 Some(&present),
1244 &[],
1245 Platform::Aws
1246 )
1247 .is_empty());
1248 assert_eq!(
1249 deployer_secret_slots(&inputs, &null_value, Some(&[]), &[], Platform::Aws).len(),
1250 1
1251 );
1252 for status in [DeployerSecretStatus::Missing, DeployerSecretStatus::Present] {
1253 assert!(deployer_secret_environment(
1254 &inputs,
1255 &values,
1256 Some(&present),
1257 &[],
1258 Platform::Aws,
1259 &[report("apiKey", status)]
1260 )
1261 .is_empty());
1262 }
1263 assert!(
1264 values.is_empty(),
1265 "presence must not manufacture an input value"
1266 );
1267 }
1268 }
1269
1270 #[test]
1271 fn stored_secret_ids_keep_deployer_only_slots_on_stored_delivery() {
1272 let inputs = vec![secret("apiKey", vec![StackInputProvider::Deployer])];
1273 let values = HashMap::new();
1274 let present = vec!["apiKey".to_string()];
1275 let slots = deployer_secret_slots(&inputs, &values, Some(&present), &[], Platform::Aws);
1276 assert_eq!(slots.len(), 1);
1277 assert!(slots[0].has_stored_value);
1278 assert!(deployer_secret_environment(
1279 &inputs,
1280 &values,
1281 Some(&present),
1282 &[],
1283 Platform::Aws,
1284 &[report("apiKey", DeployerSecretStatus::Missing)]
1285 )
1286 .is_empty());
1287 let environment = deployer_secret_environment(
1288 &inputs,
1289 &values,
1290 Some(&present),
1291 &[],
1292 Platform::Aws,
1293 &[report("apiKey", DeployerSecretStatus::Present)],
1294 );
1295 assert!(
1296 environment.is_empty(),
1297 "a filled native slot cannot replace stored delivery without its read grant"
1298 );
1299 }
1300
1301 #[test]
1302 fn stored_secret_ids_do_not_change_platform_or_kind_classification() {
1303 let mut input = secret("apiKey", vec![StackInputProvider::Deployer]);
1304 input.platforms = Some(vec![Platform::Aws]);
1305 let inputs = vec![input.clone()];
1306 let present = vec!["apiKey".to_string()];
1307 assert!(deployer_secret_slots(
1308 &inputs,
1309 &HashMap::new(),
1310 Some(&present),
1311 &[],
1312 Platform::Gcp
1313 )
1314 .is_empty());
1315 input.kind = StackInputKind::String;
1316 assert!(deployer_secret_slots(
1317 &[input],
1318 &HashMap::new(),
1319 Some(&present),
1320 &[],
1321 Platform::Aws
1322 )
1323 .is_empty());
1324 }
1325}