1use std::collections::BTreeMap;
13
14use alien_error::AlienError;
15use alien_signing::release::{
16 Bounds, Configurable, FunctionSettings, Mount, Runtime, Security, WorkloadKind,
17};
18use alien_signing::{ConfigBody, ReleaseBody, SetupTemplate, Workload};
19
20use crate::error::{ErrorData, Result};
21use crate::runtime_environment::*;
22use crate::{
23 Container, ContainerCode, Daemon, DaemonCode, Platform, Resource, ResourceRef, Sandbox,
24 SandboxCode, Stack, Worker, WorkerCode,
25};
26
27const RESOURCE_TYPES_WITHOUT_CODE: &[&str] = &[
31 "vault",
32 "compute-cluster",
33 "kubernetes-cluster",
34 "storage",
35 "key",
36 "queue",
37 "email",
38 "kv",
39 "postgres",
40 "ai",
41 "network",
42 "build",
43 "service-account",
44 "artifact-registry",
45 "service_activation",
46 "remote-stack-management",
47 "resource-access",
48];
49
50const PROVIDED_ENV_NAMES: &[&str] = &[
55 "PORT",
56 ENV_ALIEN_CURRENT_CONTAINER_BINDING_NAME,
57 ENV_ALIEN_CURRENT_WORKER_BINDING_NAME,
58 ENV_ALIEN_DEPLOYMENT_TYPE,
59 ENV_ALIEN_LAMBDA_MODE,
60 ENV_ALIEN_TRANSPORT,
61 ENV_AWS_ACCOUNT_ID,
62 ENV_AWS_REGION,
63 ENV_AZURE_CLIENT_ID,
64 ENV_AZURE_REGION,
65 ENV_AZURE_SUBSCRIPTION_ID,
66 ENV_AZURE_TENANT_ID,
67 ENV_GCP_PROJECT_ID,
68 ENV_GCP_REGION,
69 ENV_GOOGLE_CLOUD_PROJECT,
70 ENV_ALIEN_QUEUE_BATCH_CONFIG,
71 ENV_ALIEN_WORKER_TIMEOUT_SECONDS,
72 ENV_ALIEN_COMMANDS_TOKEN,
73 ENV_ALIEN_COMMANDS_TOKEN_FILE,
74 ENV_ALIEN_COMMANDS_LEASE_SECONDS,
75 ENV_ALIEN_COMMANDS_MAX_LEASES,
76 ENV_ALIEN_COMMANDS_POLL_INTERVAL_MS,
77 ENV_ALIEN_COMMANDS_POLL_MAX_INTERVAL_MS,
78 ENV_ALIEN_COMMANDS_POLL_JITTER,
79 ENV_ALIEN_COMMANDS_DRAIN_TIMEOUT_MS,
80 ENV_ALIEN_COMMANDS_TARGET_RESOURCE_ID,
81 ENV_ALIEN_COMMANDS_TARGET_RESOURCE_TYPE,
82 ENV_ALIEN_COMMANDS_URL,
83 ENV_ALIEN_DEPLOYMENT_ID,
84 ENV_ALIEN_DEPLOYMENT_NAME,
85 ENV_ALIEN_DEPLOYMENT_TOKEN,
86 ENV_ALIEN_MANAGER_URL,
87 ENV_ALIEN_RESOURCE_ID,
88 ENV_ALIEN_SECRET_ENV_REVISION,
89];
90
91#[derive(Debug, Clone, Default)]
93pub struct ReleaseOptions {
94 pub channel: String,
96 pub configurable_env: Vec<String>,
98 pub configurable_inputs: Vec<String>,
100 pub components: BTreeMap<String, String>,
102 pub setup: BTreeMap<String, SetupTemplate>,
104}
105
106pub fn release_body(
111 platform: Platform,
112 stack: &Stack,
113 options: &ReleaseOptions,
114) -> Result<ReleaseBody> {
115 let mut workloads = Vec::new();
116 for (id, entry) in stack.resources() {
117 if let Some(mut workload) = workload(id, &entry.config, options)? {
118 add_input_env(&mut workload, stack, platform);
119 workloads.push(workload);
120 }
121 }
122 workloads.sort_by(|a, b| a.name.cmp(&b.name));
125 let mut configurable_env = options.configurable_env.clone();
126 let mut configurable_inputs = options.configurable_inputs.clone();
127 for input in stack
128 .inputs
129 .iter()
130 .filter(|input| developer_input(input, platform))
131 {
132 if !configurable_inputs.contains(&input.id) {
133 configurable_inputs.push(input.id.clone());
134 }
135 for mapping in input.env.iter().filter(|mapping| plain(input, mapping)) {
136 if !configurable_env.contains(&mapping.name) {
137 configurable_env.push(mapping.name.clone());
138 }
139 }
140 }
141 for workload in &mut workloads {
144 workload.configurable_env = configurable_env.clone();
145 }
146 let body = ReleaseBody {
147 platform: platform.as_str().to_string(),
148 channel: options.channel.clone(),
149 workloads,
150 configurable: Configurable {
151 env: configurable_env,
152 inputs: configurable_inputs,
153 },
154 components: options.components.clone(),
155 setup: options.setup.clone(),
156 stack: Some(serde_json::to_value(stack).map_err(|error| {
157 statement_invalid(format!("the stack could not be serialized: {error}"))
158 })?),
159 };
160 body.validate()
161 .map_err(|error| statement_invalid(error.message))?;
162 Ok(body)
163}
164
165pub fn check_deployer_env_mappings(stack: &Stack, platform: Platform) -> Result<()> {
173 if !matches!(platform, Platform::Aws | Platform::Gcp | Platform::Azure) {
174 return Ok(());
175 }
176 for input in stack.inputs.iter().filter(|input| {
177 input.applies_to(platform)
178 && input
179 .provided_by
180 .contains(&crate::StackInputProvider::Deployer)
181 }) {
182 let secret_kind = input.kind == crate::StackInputKind::Secret;
183 for mapping in &input.env {
184 if plain(input, mapping) == secret_kind {
185 return Err(statement_invalid(format!(
186 "deployer input '{}' is {}, so its env '{}' can't be mapped as {}: a protected \
187 install reads a deployer's secret input from its own secret store and every \
188 other deployer input as plain env. Change the input's kind or the mapping's type",
189 input.id,
190 if secret_kind { "a secret" } else { "not a secret" },
191 mapping.name,
192 if secret_kind { "plain" } else { "a secret" },
193 )));
194 }
195 }
196 }
197 Ok(())
198}
199
200pub fn signed_stack(body: &ReleaseBody, platform: Platform) -> Result<Stack> {
204 if body.platform != platform.as_str() {
205 return Err(statement_invalid(format!(
206 "the release is for platform '{}', not '{}'",
207 body.platform,
208 platform.as_str()
209 )));
210 }
211 let value = body
212 .stack
213 .clone()
214 .ok_or_else(|| statement_invalid("the release carries no stack"))?;
215 let stack: Stack = serde_json::from_value(value)
216 .map_err(|error| statement_invalid(format!("the signed stack does not parse: {error}")))?;
217 let expected = release_body(
218 platform,
219 &stack,
220 &ReleaseOptions {
221 channel: body.channel.clone(),
222 configurable_env: body.configurable.env.clone(),
223 configurable_inputs: body.configurable.inputs.clone(),
224 components: body.components.clone(),
225 setup: body.setup.clone(),
226 },
227 )?;
228 if expected.workloads != body.workloads {
229 return Err(statement_invalid(
230 "the signed workloads do not match the signed stack",
231 ));
232 }
233 Ok(stack)
234}
235
236pub fn signed_input_variables(
242 stack: &Stack,
243 platform: Platform,
244 developer_values: &BTreeMap<String, serde_json::Value>,
245 deployer_values: &std::collections::HashMap<String, serde_json::Value>,
246) -> Result<Vec<crate::EnvironmentVariable>> {
247 let mut values = std::collections::HashMap::new();
248 let mut inputs = Vec::with_capacity(stack.inputs.len());
249 for input in &stack.inputs {
250 let developer = developer_input(input, platform);
251 let value = if developer {
252 developer_values.get(&input.id)
253 } else {
254 deployer_values.get(&input.id)
255 };
256 if let Some(value) = value {
257 values.insert(input.id.clone(), value.clone());
258 }
259 let mut input = input.clone();
260 if !developer {
261 input.env.clear();
262 }
263 inputs.push(input);
264 }
265 Ok(
266 crate::resolve_stack_input_environment_variables(&inputs, &values, platform)?
267 .into_iter()
268 .filter(|variable| variable.var_type == crate::EnvironmentVariableType::Plain)
269 .collect(),
270 )
271}
272
273pub fn gating_deployer_inputs(body: &ReleaseBody) -> Result<Vec<String>> {
277 if body.stack.is_none() {
278 return Ok(Vec::new());
279 }
280 let platform: Platform = body.platform.parse().map_err(|_| {
281 statement_invalid(format!("the release names no platform '{}'", body.platform))
282 })?;
283 let stack = signed_stack(body, platform)?;
284 let mut gating = std::collections::BTreeSet::new();
285 for input in stack
286 .inputs
287 .iter()
288 .filter(|input| input.applies_to(platform))
289 {
290 let Some(condition) = &input.when else {
291 continue;
292 };
293 if stack
294 .inputs
295 .iter()
296 .any(|other| other.id == condition.input && !developer_input(other, platform))
297 {
298 gating.insert(condition.input.clone());
299 }
300 }
301 Ok(gating.into_iter().collect())
302}
303
304pub fn signed_config_env(
315 body: &ReleaseBody,
316 workload: &str,
317 config: &ConfigBody,
318 deployer_values: &std::collections::HashMap<String, serde_json::Value>,
319) -> Result<BTreeMap<String, String>> {
320 let mut env = BTreeMap::new();
321 if body.stack.is_some() {
322 let platform: Platform = body.platform.parse().map_err(|_| {
323 statement_invalid(format!("the release names no platform '{}'", body.platform))
324 })?;
325 let stack = signed_stack(body, platform)?;
326 for variable in signed_input_variables(&stack, platform, &config.inputs, deployer_values)? {
327 if crate::targets_resource(&variable.target_resources, workload) {
328 env.insert(variable.name, variable.value);
329 }
330 }
331 }
332 env.extend(config.env.clone());
333 Ok(env)
334}
335
336pub fn signed_deployer_env(
345 body: &ReleaseBody,
346 workload: &str,
347 config_inputs: &BTreeMap<String, serde_json::Value>,
348 deployer_values: &std::collections::HashMap<String, serde_json::Value>,
349) -> Result<BTreeMap<String, String>> {
350 if body.stack.is_none() {
351 return Ok(BTreeMap::new());
352 }
353 let platform: Platform = body.platform.parse().map_err(|_| {
354 statement_invalid(format!("the release names no platform '{}'", body.platform))
355 })?;
356 let stack = signed_stack(body, platform)?;
357 let values = input_values(&stack, platform, config_inputs, deployer_values);
358 let inputs: Vec<crate::StackInputDefinition> = stack
359 .inputs
360 .iter()
361 .map(|input| {
362 let mut input = input.clone();
363 if developer_input(&input, platform) {
364 input.env.clear();
365 } else {
366 let mappings = std::mem::take(&mut input.env);
367 input.env = mappings
368 .into_iter()
369 .filter(|mapping| plain(&input, mapping))
370 .collect();
371 }
372 input
373 })
374 .collect();
375 for input in inputs
376 .iter()
377 .filter(|input| input.env.iter().any(|mapping| mapping.targets(workload)))
378 {
379 let unset = values.get(&input.id).is_none_or(serde_json::Value::is_null);
380 if unset
381 && input.default.is_none()
382 && input.required
383 && !input.is_generated()
384 && input.applies(&inputs, &values, platform)
385 {
386 return Err(statement_invalid(format!(
387 "deployer input '{}' is required and has no value in this deployment's store",
388 input.id
389 )));
390 }
391 }
392 Ok(
393 crate::resolve_stack_input_environment_variables(&inputs, &values, platform)?
394 .into_iter()
395 .filter(|variable| crate::targets_resource(&variable.target_resources, workload))
396 .map(|variable| (variable.name, variable.value))
397 .collect(),
398 )
399}
400
401fn input_values(
404 stack: &Stack,
405 platform: Platform,
406 config_inputs: &BTreeMap<String, serde_json::Value>,
407 deployer_values: &std::collections::HashMap<String, serde_json::Value>,
408) -> std::collections::HashMap<String, serde_json::Value> {
409 stack
410 .inputs
411 .iter()
412 .filter_map(|input| {
413 let value = if developer_input(input, platform) {
414 config_inputs.get(&input.id)
415 } else {
416 deployer_values.get(&input.id)
417 };
418 value.map(|value| (input.id.clone(), value.clone()))
419 })
420 .collect()
421}
422
423pub fn signed_deployer_secrets(
432 body: &ReleaseBody,
433 workload: &str,
434 config_inputs: &BTreeMap<String, serde_json::Value>,
435 deployer_values: &std::collections::HashMap<String, serde_json::Value>,
436) -> Result<Vec<crate::DeployerSecretEnv>> {
437 if body.stack.is_none() {
438 return Ok(Vec::new());
439 }
440 let platform: Platform = body.platform.parse().map_err(|_| {
441 statement_invalid(format!("the release names no platform '{}'", body.platform))
442 })?;
443 let stack = signed_stack(body, platform)?;
444 let values = input_values(&stack, platform, config_inputs, deployer_values);
445 Ok(
446 crate::protected_deployer_secret_slots(&stack.inputs, &values, platform)
447 .into_iter()
448 .flat_map(|slot| {
449 slot.input
450 .env
451 .iter()
452 .filter(|mapping| mapping.targets(workload))
453 .map(move |mapping| crate::DeployerSecretEnv {
454 name: mapping.name.clone(),
455 secret_name: slot.vault_key.clone(),
456 vault_key: slot.vault_key.clone(),
457 vault_name: None,
458 label: slot.input.label.clone(),
459 required: slot.input.required,
460 version: None,
461 })
462 })
463 .collect(),
464 )
465}
466
467pub fn signed_workload_secrets(
472 body: &ReleaseBody,
473 workload: &str,
474 digest: &str,
475 config_inputs: &BTreeMap<String, serde_json::Value>,
476 deployer_values: &std::collections::HashMap<String, serde_json::Value>,
477) -> Result<Option<String>> {
478 let keys: Vec<&str> = body
479 .workload(workload)
480 .map_err(|error| statement_invalid(error.to_string()))?
481 .secrets
482 .iter()
483 .map(|secret| secret.name.as_str())
484 .collect();
485 let deployer = signed_deployer_secrets(body, workload, config_inputs, deployer_values)?;
486 if keys.is_empty() && deployer.is_empty() {
487 return Ok(None);
488 }
489 let mut list = serde_json::json!({ "keys": keys, "hash": digest });
490 if !deployer.is_empty() {
491 list["deployerSecrets"] = serde_json::to_value(&deployer)
492 .map_err(|error| statement_invalid(error.to_string()))?;
493 }
494 Ok(Some(list.to_string()))
495}
496
497fn add_input_env(workload: &mut Workload, stack: &Stack, platform: Platform) {
502 for input in stack
503 .inputs
504 .iter()
505 .filter(|input| input.applies_to(platform))
506 {
507 for mapping in input
508 .env
509 .iter()
510 .filter(|mapping| plain(input, mapping) && mapping.targets(&workload.name))
511 {
512 if input
513 .provided_by
514 .contains(&crate::StackInputProvider::Deployer)
515 {
516 workload
517 .deployer_env
518 .insert(mapping.name.clone(), input.id.clone());
519 }
520 }
521 }
522}
523
524fn developer_input(input: &crate::StackInputDefinition, platform: Platform) -> bool {
525 input.applies_to(platform)
526 && !input
527 .provided_by
528 .contains(&crate::StackInputProvider::Deployer)
529}
530
531fn plain(
533 input: &crate::StackInputDefinition,
534 mapping: &crate::StackInputEnvironmentMapping,
535) -> bool {
536 match mapping.var_type {
537 Some(crate::StackInputEnvironmentVariableType::Secret) => false,
538 Some(crate::StackInputEnvironmentVariableType::Plain) => true,
539 None => input.kind != crate::StackInputKind::Secret,
540 }
541}
542
543fn workload(id: &str, config: &Resource, options: &ReleaseOptions) -> Result<Option<Workload>> {
544 let base = |kind: WorkloadKind, image: &str| Workload {
545 name: id.to_string(),
546 kind,
547 image: image.to_string(),
548 command: None,
549 env: BTreeMap::new(),
550 provided_env: PROVIDED_ENV_NAMES
551 .iter()
552 .map(|name| name.to_string())
553 .collect(),
554 bindings: BTreeMap::new(),
555 configurable_env: options.configurable_env.clone(),
556 deployer_env: BTreeMap::new(),
557 secrets: Vec::new(),
558 runtime: Runtime::default(),
559 volume_mount_path: None,
560 identity: None,
561 bounds: Bounds::default(),
562 function: None,
563 };
564 if let Some(container) = config.downcast_ref::<Container>() {
565 let image = pinned_image(id, container_image(id, container)?)?;
566 let mut workload = base(WorkloadKind::Container, image);
567 workload.bindings = bindings(&container.links);
568 workload.command = container.command.clone();
569 workload.env = container.environment.clone().into_iter().collect();
570 workload.runtime = Runtime {
571 security: container.security.as_ref().map(|security| Security {
572 profile: if security.profile == crate::ContainerSecurityProfile::Unrestricted {
573 "unrestricted".to_string()
574 } else if container.egress.is_some() {
575 "restrictedInternet".to_string()
576 } else {
577 "restricted".to_string()
578 },
579 run_as_user: security.run_as_user,
580 run_as_group: security.run_as_group,
581 read_only_root_filesystem: security.read_only_root_filesystem,
582 writable_paths: security.writable_paths.clone(),
583 }),
584 egress: container.egress.map(|_| "internet".to_string()),
585 ..Runtime::default()
586 };
587 workload.volume_mount_path = container
588 .persistent_storage
589 .as_ref()
590 .map(|storage| storage.mount_path.clone());
591 workload.identity = Some(container.permissions.clone());
592 let choices = container.resource_choices.as_ref();
593 workload.bounds = Bounds {
594 max_cpu: Some(
595 choices
596 .and_then(|choices| choices.cpu.as_ref())
597 .map(|range| range.max.clone())
598 .unwrap_or_else(|| container.cpu.desired.clone()),
599 ),
600 max_memory: Some(
601 choices
602 .and_then(|choices| choices.memory.as_ref())
603 .map(|range| range.max.clone())
604 .unwrap_or_else(|| container.memory.desired.clone()),
605 ),
606 max_replicas: container
607 .autoscaling
608 .as_ref()
609 .map(|autoscaling| autoscaling.max)
610 .or(container.replicas),
611 };
612 return Ok(Some(workload));
613 }
614 if let Some(daemon) = config.downcast_ref::<Daemon>() {
615 let image = match &daemon.code {
616 DaemonCode::Image { image } => pinned_image(id, image)?,
617 DaemonCode::Source { .. } => return Err(source_code(id)),
618 };
619 let mut workload = base(WorkloadKind::Daemon, image);
620 workload.bindings = bindings(&daemon.links);
621 workload.command = daemon.command.clone();
622 workload.env = daemon.environment.clone().into_iter().collect();
623 if let Some(runtime) = &daemon.runtime {
624 workload.runtime = Runtime {
625 privileged: runtime.privileged.unwrap_or(false),
626 pid_namespace: runtime.pid_namespace.clone(),
627 network_mode: runtime.network_mode.clone(),
628 user: runtime.user.clone(),
629 mounts: runtime
630 .mounts
631 .iter()
632 .map(|mount| Mount {
633 source: mount.source.clone(),
634 target: mount.target.clone(),
635 options: mount.options.clone(),
636 })
637 .collect(),
638 security: None,
639 egress: None,
640 };
641 }
642 workload.identity = daemon.permissions.clone();
643 workload.bounds = Bounds {
644 max_cpu: Some(daemon.cpu.desired.clone()),
645 max_memory: Some(daemon.memory.desired.clone()),
646 max_replicas: None,
647 };
648 return Ok(Some(workload));
649 }
650 if let Some(worker) = config.downcast_ref::<Worker>() {
651 let image = match &worker.code {
652 WorkerCode::Image { image } => pinned_image(id, image)?,
653 WorkerCode::Source { .. } => return Err(source_code(id)),
654 };
655 let mut workload = base(WorkloadKind::Function, image);
656 workload.bindings = bindings(&worker.links);
657 workload.env = worker.environment.clone().into_iter().collect();
658 workload.identity = Some(worker.permissions.clone());
659 workload.function = Some(FunctionSettings {
660 memory_mb: worker.memory_mb,
661 timeout_seconds: worker.timeout_seconds,
662 architecture: None,
663 });
664 return Ok(Some(workload));
665 }
666 if let Some(sandbox) = config.downcast_ref::<Sandbox>() {
667 let image = sandbox_pinned_image(id, sandbox)?;
668 let mut workload = base(WorkloadKind::Sandbox, image);
669 let limits = sandbox.resolved_limits();
670 workload.bounds = Bounds {
671 max_cpu: Some(limits.cpu.clone()),
672 max_memory: Some(limits.memory.clone()),
673 max_replicas: None,
674 };
675 return Ok(Some(workload));
676 }
677 let resource_type = config.resource_type();
678 if RESOURCE_TYPES_WITHOUT_CODE.contains(&resource_type.as_ref()) {
679 return Ok(None);
680 }
681 Err(statement_invalid(format!(
682 "resource '{id}' has type '{resource_type}', which a signed release can't carry"
683 )))
684}
685
686fn bindings(links: &[ResourceRef]) -> BTreeMap<String, String> {
688 links
689 .iter()
690 .map(|link| (link.id.clone(), link.resource_type.to_string()))
691 .collect()
692}
693
694fn container_image<'a>(id: &str, container: &'a Container) -> Result<&'a str> {
695 match &container.code {
696 ContainerCode::Image { image } => Ok(image),
697 ContainerCode::Source { .. } => Err(source_code(id)),
698 }
699}
700
701pub fn sandbox_pinned_image<'a>(id: &str, sandbox: &'a Sandbox) -> Result<&'a str> {
706 match &sandbox.code {
707 SandboxCode::Image {
708 image,
709 bundled_from,
710 } => {
711 if image.starts_with("s3://") {
712 let built_from = bundled_from.as_deref().ok_or_else(|| {
713 statement_invalid(format!(
714 "resource '{id}' is a sandbox bundle with no pinned image it was built from"
715 ))
716 })?;
717 pinned_image(id, built_from)
718 } else {
719 pinned_image(id, image)
720 }
721 }
722 SandboxCode::Source { .. } => Err(source_code(id)),
723 }
724}
725
726fn pinned_image<'a>(id: &str, image: &'a str) -> Result<&'a str> {
727 if image_digest(image).is_none() {
728 return Err(statement_invalid(format!(
729 "resource '{id}' uses image '{image}', which is not pinned by sha256 digest"
730 )));
731 }
732 Ok(image)
733}
734
735pub fn code_image(resource: &Resource) -> Option<&str> {
737 if let Some(container) = resource.downcast_ref::<Container>() {
738 match &container.code {
739 ContainerCode::Image { image } => Some(image),
740 ContainerCode::Source { .. } => None,
741 }
742 } else if let Some(worker) = resource.downcast_ref::<Worker>() {
743 match &worker.code {
744 WorkerCode::Image { image } => Some(image),
745 WorkerCode::Source { .. } => None,
746 }
747 } else if let Some(daemon) = resource.downcast_ref::<Daemon>() {
748 match &daemon.code {
749 DaemonCode::Image { image } => Some(image),
750 DaemonCode::Source { .. } => None,
751 }
752 } else if let Some(sandbox) = resource.downcast_ref::<Sandbox>() {
753 match &sandbox.code {
754 SandboxCode::Image { image, .. } => Some(image),
755 SandboxCode::Source { .. } => None,
756 }
757 } else {
758 None
759 }
760}
761
762pub fn code_image_mut(resource: &mut Resource) -> Option<&mut String> {
764 if resource.downcast_ref::<Container>().is_some() {
768 match &mut resource.downcast_mut::<Container>()?.code {
769 ContainerCode::Image { image } => Some(image),
770 ContainerCode::Source { .. } => None,
771 }
772 } else if resource.downcast_ref::<Worker>().is_some() {
773 match &mut resource.downcast_mut::<Worker>()?.code {
774 WorkerCode::Image { image } => Some(image),
775 WorkerCode::Source { .. } => None,
776 }
777 } else if resource.downcast_ref::<Daemon>().is_some() {
778 match &mut resource.downcast_mut::<Daemon>()?.code {
779 DaemonCode::Image { image } => Some(image),
780 DaemonCode::Source { .. } => None,
781 }
782 } else if resource.downcast_ref::<Sandbox>().is_some() {
783 match &mut resource.downcast_mut::<Sandbox>()?.code {
784 SandboxCode::Image { image, .. } => Some(image),
785 SandboxCode::Source { .. } => None,
786 }
787 } else {
788 None
789 }
790}
791
792pub fn relocate_images(signed: &Stack, carried: &Stack) -> Stack {
797 let mut relocated = signed.clone();
798 for (id, entry) in relocated.resources_mut() {
799 if let (Some(sandbox), Some(carried_sandbox)) = (
801 entry.config.downcast_mut::<Sandbox>(),
802 carried
803 .resources
804 .get(id)
805 .and_then(|carried| carried.config.downcast_ref::<Sandbox>()),
806 ) {
807 if let (
808 SandboxCode::Image {
809 bundled_from: Some(image),
810 ..
811 },
812 SandboxCode::Image {
813 bundled_from: Some(location),
814 ..
815 },
816 ) = (&mut sandbox.code, &carried_sandbox.code)
817 {
818 if image_digest(image).is_some() && image_digest(image) == image_digest(location) {
819 *image = location.clone();
820 }
821 }
822 }
823 let Some(location) = carried
824 .resources
825 .get(id)
826 .and_then(|carried| code_image(&carried.config))
827 else {
828 continue;
829 };
830 if let Some(image) = code_image_mut(&mut entry.config) {
831 if image_digest(image).is_some() && image_digest(image) == image_digest(location) {
832 *image = location.to_string();
833 }
834 }
835 }
836 relocated
837}
838
839pub fn image_digest(image: &str) -> Option<&str> {
841 let (repository, digest) = image.rsplit_once('@')?;
842 let valid = !repository.is_empty()
843 && !repository.chars().any(char::is_whitespace)
844 && alien_signing::release::is_sha256_digest(digest);
845 valid.then_some(digest)
846}
847
848fn source_code(id: &str) -> AlienError<ErrorData> {
849 statement_invalid(format!(
850 "resource '{id}' is built from source, which a signed release can't carry; build it first"
851 ))
852}
853
854fn statement_invalid(reason: impl Into<String>) -> AlienError<ErrorData> {
855 AlienError::new(ErrorData::ReleaseStatementInvalid {
856 reason: reason.into(),
857 })
858}
859
860#[cfg(test)]
861mod tests {
862 use super::*;
863 use crate::{ResourceLifecycle, ResourceSpec};
864
865 const DIGEST: &str = "sha256:9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08";
866
867 fn container(image: &str) -> Container {
868 Container::new("api".to_string())
869 .code(ContainerCode::Image {
870 image: image.to_string(),
871 })
872 .cpu(ResourceSpec {
873 min: "0.5".to_string(),
874 desired: "1".to_string(),
875 })
876 .memory(ResourceSpec {
877 min: "512Mi".to_string(),
878 desired: "1Gi".to_string(),
879 })
880 .port(8080)
881 .permissions("execution".to_string())
882 .environment(std::collections::HashMap::from([(
883 "LOG_LEVEL".to_string(),
884 "info".to_string(),
885 )]))
886 .build()
887 }
888
889 fn stack(image: &str) -> Stack {
890 Stack::new("shop".to_string())
891 .add(container(image), ResourceLifecycle::Live)
892 .build()
893 }
894
895 fn pinned() -> String {
896 format!("registry.example.com/shop/api@{DIGEST}")
897 }
898
899 fn production() -> ReleaseOptions {
900 ReleaseOptions {
901 channel: "production".to_string(),
902 ..ReleaseOptions::default()
903 }
904 }
905
906 fn sandbox_stack(image: &str, bundled_from: Option<&str>) -> Stack {
907 let sandbox = Sandbox::new("agent".to_string())
908 .code(SandboxCode::Image {
909 image: image.to_string(),
910 bundled_from: bundled_from.map(str::to_string),
911 })
912 .egress(crate::SandboxEgress::None)
913 .lifecycle(crate::SandboxLifecyclePolicy {
914 max_lifetime_seconds: None,
915 idle_pause_seconds: None,
916 })
917 .build();
918 Stack::new("shop".to_string())
919 .add(sandbox, ResourceLifecycle::Live)
920 .build()
921 }
922
923 #[test]
924 fn a_sandbox_is_signed_by_the_digest_of_its_image() {
925 let registry = format!("registry.example.com/shop/sandbox@{DIGEST}");
926 let bundle = "s3://bundles/sandbox-bundle/agent/abc/bundle.zip";
927 for (stack, pin) in [
928 (sandbox_stack(®istry, None), registry.as_str()),
929 (sandbox_stack(bundle, Some(®istry)), registry.as_str()),
930 ] {
931 let body = release_body(Platform::Aws, &stack, &production()).unwrap();
932 assert_eq!(body.workloads.len(), 1);
933 assert_eq!(body.workloads[0].kind, WorkloadKind::Sandbox);
934 assert_eq!(body.workloads[0].image, pin);
935 }
936 }
937
938 #[test]
939 fn a_sandbox_without_a_pinned_image_is_refused() {
940 let unpinned = "registry.example.com/shop/sandbox:latest";
941 let bundle = "s3://bundles/sandbox-bundle/agent/abc/bundle.zip";
942 for stack in [
943 sandbox_stack(unpinned, None),
944 sandbox_stack("ubuntu", None),
946 sandbox_stack(bundle, None),
948 sandbox_stack(bundle, Some(unpinned)),
949 ] {
950 let error = release_body(Platform::Aws, &stack, &production()).unwrap_err();
951 assert!(
952 error.message.contains("pinned") || error.message.contains("bundle"),
953 "{}",
954 error.message
955 );
956 }
957 }
958
959 #[test]
960 fn a_pushed_stack_becomes_workloads_that_build_back_to_the_stack() {
961 let stack = stack(&pinned());
962 let body = release_body(Platform::Aws, &stack, &production()).unwrap();
963 assert_eq!(body.workloads.len(), 1);
964 let api = &body.workloads[0];
965 assert_eq!(api.name, "api");
966 assert_eq!(api.image, pinned());
967 assert_eq!(api.env["LOG_LEVEL"], "info");
968 assert_eq!(api.identity.as_deref(), Some("execution"));
969 assert_eq!(api.bounds.max_cpu.as_deref(), Some("1"));
970 assert_eq!(api.bounds.max_memory.as_deref(), Some("1Gi"));
971 assert_eq!(body.channel, "production");
972 assert!(api
973 .provided_env
974 .contains(&"ALIEN_DEPLOYMENT_ID".to_string()));
975 assert!(
976 !api.provided_env
977 .iter()
978 .any(|name| name.ends_with("_BINDING")
979 || name == ENV_ALIEN_SECRETS
980 || name.starts_with("OTEL_")),
981 "bindings, the secrets list and telemetry are never the control plane's: {:?}",
982 api.provided_env
983 );
984 assert_eq!(signed_stack(&body, Platform::Aws).unwrap(), stack);
985 }
986
987 #[test]
988 fn stack_inputs_become_configurable_or_deployer_env() {
989 let mut stack = stack(&pinned());
990 stack.inputs = serde_json::from_value(serde_json::json!([
991 {"id": "logLevel", "kind": "string", "providedBy": ["developer"], "required": false,
992 "label": "l", "description": "d", "env": [{"name": "LOG_LEVEL", "targetResources": ["api"]}]},
993 {"id": "databaseUrl", "kind": "string", "providedBy": ["deployer"], "required": false,
994 "label": "l", "description": "d", "env": [{"name": "DATABASE_URL", "targetResources": ["api"]}]},
995 ]))
996 .unwrap();
997 let mut container = container(&pinned());
1000 container.environment.clear();
1001 stack.resources.get_mut("api").unwrap().config = alien_core_resource(container);
1002 let body = release_body(Platform::Aws, &stack, &production()).unwrap();
1003 let api = &body.workloads[0];
1004 assert_eq!(api.deployer_env["DATABASE_URL"], "databaseUrl");
1005 assert!(api.configurable_env.contains(&"LOG_LEVEL".to_string()));
1006 assert_eq!(body.configurable.inputs, vec!["logLevel".to_string()]);
1007 assert_eq!(signed_stack(&body, Platform::Aws).unwrap(), stack);
1008 }
1009
1010 #[test]
1014 fn a_signed_config_sets_the_env_its_inputs_map_to() {
1015 let mut stack = stack(&pinned());
1016 stack.inputs = serde_json::from_value(serde_json::json!([
1017 {"id": "logLevel", "kind": "string", "providedBy": ["developer"], "required": false,
1018 "label": "l", "description": "d", "default": {"type": "string", "value": "info"},
1019 "env": [{"name": "LOG_LEVEL", "targetResources": ["api"]}]},
1020 {"id": "region", "kind": "string", "providedBy": ["developer"], "required": false,
1021 "label": "l", "description": "d",
1022 "env": [{"name": "REGION", "targetResources": ["api"]}, {"name": "ELSEWHERE", "targetResources": ["other"]}]},
1023 {"id": "token", "kind": "secret", "providedBy": ["developer"], "required": false,
1024 "label": "l", "description": "d", "env": [{"name": "TOKEN", "targetResources": ["api"]}]},
1025 {"id": "databaseUrl", "kind": "string", "providedBy": ["deployer"], "required": false,
1026 "label": "l", "description": "d", "default": {"type": "string", "value": "postgres://default"},
1027 "env": [{"name": "DATABASE_URL", "targetResources": ["api"]}]},
1028 ]))
1029 .unwrap();
1030 let mut api = container(&pinned());
1031 api.environment.clear();
1032 stack.resources.get_mut("api").unwrap().config = alien_core_resource(api);
1033 let body = release_body(Platform::Aws, &stack, &production()).unwrap();
1034 let config = |inputs: serde_json::Value, env: &[(&str, &str)]| ConfigBody {
1035 inputs: serde_json::from_value(inputs).unwrap(),
1036 env: env
1037 .iter()
1038 .map(|(name, value)| (name.to_string(), value.to_string()))
1039 .collect(),
1040 ..Default::default()
1041 };
1042
1043 let env = signed_config_env(
1044 &body,
1045 "api",
1046 &config(serde_json::json!({"region": "eu", "token": "s3cret"}), &[]),
1047 &Default::default(),
1048 )
1049 .unwrap();
1050 assert_eq!(
1051 env,
1052 BTreeMap::from([
1053 ("LOG_LEVEL".to_string(), "info".to_string()),
1054 ("REGION".to_string(), "eu".to_string()),
1055 ]),
1056 "the default applies, secrets and deployer inputs never travel in a signed config, \
1057 and a mapping aimed at another resource isn't this workload's"
1058 );
1059
1060 let env = signed_config_env(
1061 &body,
1062 "api",
1063 &config(
1064 serde_json::json!({"logLevel": "debug"}),
1065 &[("LOG_LEVEL", "trace")],
1066 ),
1067 &Default::default(),
1068 )
1069 .unwrap();
1070 assert_eq!(env["LOG_LEVEL"], "trace", "the config's own env wins");
1071 }
1072
1073 #[test]
1076 fn a_developer_input_gated_on_a_deployer_input_follows_the_installs_value() {
1077 let mut stack = stack(&pinned());
1078 stack.inputs = serde_json::from_value(serde_json::json!([
1079 {"id": "audit", "kind": "boolean", "providedBy": ["deployer"], "required": false,
1080 "label": "l", "description": "d", "default": {"type": "boolean", "value": true}},
1081 {"id": "auditSink", "kind": "string", "providedBy": ["developer"], "required": false,
1082 "label": "l", "description": "d", "when": {"input": "audit", "equals": true},
1083 "env": [{"name": "AUDIT_SINK", "targetResources": ["api"]}]},
1084 {"id": "logLevel", "kind": "string", "providedBy": ["developer"], "required": false,
1085 "label": "l", "description": "d", "env": [{"name": "LOG_LEVEL", "targetResources": ["api"]}]},
1086 ]))
1087 .unwrap();
1088 let mut api = container(&pinned());
1089 api.environment.clear();
1090 stack.resources.get_mut("api").unwrap().config = alien_core_resource(api);
1091 let body = release_body(Platform::Aws, &stack, &production()).unwrap();
1092 assert_eq!(
1093 gating_deployer_inputs(&body).unwrap(),
1094 vec!["audit".to_string()]
1095 );
1096
1097 let config = ConfigBody {
1098 inputs: serde_json::from_value(
1099 serde_json::json!({"auditSink": "https://audit.example"}),
1100 )
1101 .unwrap(),
1102 ..Default::default()
1103 };
1104 let with = |audit: Option<&str>| {
1105 let values = audit
1106 .map(|audit| {
1107 std::collections::HashMap::from([(
1108 "audit".to_string(),
1109 serde_json::Value::String(audit.to_string()),
1110 )])
1111 })
1112 .unwrap_or_default();
1113 signed_config_env(&body, "api", &config, &values).unwrap()
1114 };
1115 assert_eq!(with(Some("true"))["AUDIT_SINK"], "https://audit.example");
1116 assert_eq!(
1117 with(None)["AUDIT_SINK"],
1118 "https://audit.example",
1119 "the default is on"
1120 );
1121 assert!(
1122 !with(Some("false")).contains_key("AUDIT_SINK"),
1123 "the customer turned it off"
1124 );
1125 }
1126
1127 fn deployer_env_stack(inputs: serde_json::Value) -> ReleaseBody {
1128 let mut stack = stack(&pinned());
1129 stack.inputs = serde_json::from_value(inputs).unwrap();
1130 let mut api = container(&pinned());
1131 api.environment.clear();
1132 stack.resources.get_mut("api").unwrap().config = alien_core_resource(api);
1133 release_body(Platform::Aws, &stack, &production()).unwrap()
1134 }
1135
1136 fn stored(values: &[(&str, &str)]) -> std::collections::HashMap<String, serde_json::Value> {
1137 values
1138 .iter()
1139 .map(|(id, value)| (id.to_string(), serde_json::Value::String(value.to_string())))
1140 .collect()
1141 }
1142
1143 #[test]
1144 fn deployer_env_resolves_defaults_and_leaves_out_unset_optional_inputs() {
1145 let body = deployer_env_stack(serde_json::json!([
1146 {"id": "region", "kind": "string", "providedBy": ["deployer"], "required": false,
1147 "label": "l", "description": "d", "default": {"type": "string", "value": "eu"},
1148 "env": [{"name": "REGION", "targetResources": ["api"]}]},
1149 {"id": "proxy", "kind": "string", "providedBy": ["deployer"], "required": false,
1150 "label": "l", "description": "d",
1151 "env": [{"name": "PROXY_URL", "targetResources": ["api"]}]},
1152 {"id": "databaseUrl", "kind": "string", "providedBy": ["deployer"], "required": true,
1153 "label": "l", "description": "d",
1154 "env": [{"name": "DATABASE_URL", "targetResources": ["api"]}]},
1155 ]));
1156 let none = BTreeMap::new();
1157 let env = signed_deployer_env(&body, "api", &none, &stored(&[("databaseUrl", "pg://a")]))
1158 .unwrap();
1159 assert_eq!(
1160 env,
1161 BTreeMap::from([
1162 ("REGION".to_string(), "eu".to_string()),
1163 ("DATABASE_URL".to_string(), "pg://a".to_string()),
1164 ]),
1165 "the default fills an unset input and an optional input with neither is left out"
1166 );
1167 let env = signed_deployer_env(
1168 &body,
1169 "api",
1170 &none,
1171 &stored(&[
1172 ("databaseUrl", "pg://a"),
1173 ("region", "us"),
1174 ("proxy", "http://p"),
1175 ]),
1176 )
1177 .unwrap();
1178 assert_eq!(env["REGION"], "us");
1179 assert_eq!(env["PROXY_URL"], "http://p");
1180 let error = signed_deployer_env(&body, "api", &none, &stored(&[]))
1181 .expect_err("a required input with no value is refused");
1182 assert!(error.message.contains("databaseUrl"), "{}", error.message);
1183 }
1184
1185 #[test]
1186 fn deployer_env_follows_the_signed_when_not_the_stored_values() {
1187 let body = deployer_env_stack(serde_json::json!([
1188 {"id": "audit", "kind": "boolean", "providedBy": ["deployer"], "required": false,
1189 "label": "l", "description": "d", "default": {"type": "boolean", "value": false}},
1190 {"id": "auditSink", "kind": "string", "providedBy": ["deployer"], "required": true,
1191 "label": "l", "description": "d", "when": {"input": "audit", "equals": true},
1192 "env": [{"name": "AUDIT_SINK", "targetResources": ["api"]}]},
1193 ]));
1194 assert_eq!(
1195 gating_deployer_inputs(&body).unwrap(),
1196 vec!["audit".to_string()],
1197 "a deployer input's own gate is read from the store too"
1198 );
1199 let none = BTreeMap::new();
1200 let off = signed_deployer_env(&body, "api", &none, &stored(&[])).unwrap();
1201 assert!(
1202 off.is_empty(),
1203 "an inactive required input demands nothing: {off:?}"
1204 );
1205 let off = signed_deployer_env(
1206 &body,
1207 "api",
1208 &none,
1209 &stored(&[("auditSink", "https://stale.example")]),
1210 )
1211 .unwrap();
1212 assert!(
1213 off.is_empty(),
1214 "a stored value of an inactive input is ignored"
1215 );
1216 let on = signed_deployer_env(
1217 &body,
1218 "api",
1219 &none,
1220 &stored(&[("audit", "true"), ("auditSink", "https://audit.example")]),
1221 )
1222 .unwrap();
1223 assert_eq!(on["AUDIT_SINK"], "https://audit.example");
1224 signed_deployer_env(&body, "api", &none, &stored(&[("audit", "true")]))
1225 .expect_err("active and required, so a value is needed");
1226 }
1227
1228 #[test]
1229 fn a_secret_input_never_becomes_plain_deployer_env() {
1230 let body = deployer_env_stack(serde_json::json!([
1231 {"id": "apiKey", "kind": "secret", "providedBy": ["deployer"], "required": true,
1232 "label": "l", "description": "d",
1233 "env": [{"name": "API_KEY", "targetResources": ["api"]}]},
1234 ]));
1235 assert!(
1236 body.workloads[0].deployer_env.is_empty(),
1237 "a secret input is delivered through the secrets vault, never as plain env"
1238 );
1239 let env = signed_deployer_env(&body, "api", &BTreeMap::new(), &stored(&[("apiKey", "x")]))
1240 .unwrap();
1241 assert!(env.is_empty(), "{env:?}");
1242 }
1243
1244 #[test]
1245 fn deployer_secrets_come_from_the_signed_stack_and_follow_its_gates() {
1246 let body = deployer_env_stack(serde_json::json!([
1247 {"id": "audit", "kind": "boolean", "providedBy": ["deployer"], "required": false,
1248 "label": "l", "description": "d", "default": {"type": "boolean", "value": false}},
1249 {"id": "databasePassword", "kind": "secret", "providedBy": ["deployer"], "required": true,
1250 "label": "Database password", "description": "d",
1251 "env": [{"name": "DATABASE_PASSWORD", "targetResources": ["api"]},
1252 {"name": "ELSEWHERE", "targetResources": ["other"]}]},
1253 {"id": "auditToken", "kind": "secret", "providedBy": ["deployer"], "required": false,
1254 "label": "Audit token", "description": "d", "when": {"input": "audit", "equals": true},
1255 "env": [{"name": "AUDIT_TOKEN"}]},
1256 {"id": "vendorKey", "kind": "secret", "providedBy": ["developer"], "required": true,
1257 "label": "Vendor key", "description": "d",
1258 "env": [{"name": "VENDOR_KEY"}]},
1259 ]));
1260 let none = BTreeMap::new();
1261 let secrets = signed_deployer_secrets(&body, "api", &none, &stored(&[])).unwrap();
1262 assert_eq!(
1263 secrets,
1264 vec![crate::DeployerSecretEnv {
1265 name: "DATABASE_PASSWORD".into(),
1266 vault_key: "database-password".into(),
1267 secret_name: "database-password".into(),
1268 vault_name: None,
1269 label: "Database password".into(),
1270 required: true,
1271 version: None,
1272 }],
1273 "only the deployer's secret that applies and targets the worker; the gated one is off, \
1274 the developer's has no value on a protected install"
1275 );
1276 let on =
1277 signed_deployer_secrets(&body, "api", &none, &stored(&[("audit", "true")])).unwrap();
1278 let names: Vec<&str> = on.iter().map(|secret| secret.name.as_str()).collect();
1279 assert_eq!(names, ["DATABASE_PASSWORD", "AUDIT_TOKEN"]);
1280 assert!(!on[1].required);
1281
1282 let list = signed_workload_secrets(&body, "api", "sha256:abc", &none, &stored(&[]))
1283 .unwrap()
1284 .expect("a worker with a deployer secret loads a list");
1285 let list: serde_json::Value = serde_json::from_str(&list).unwrap();
1286 assert_eq!(list["keys"], serde_json::json!([]));
1287 assert_eq!(list["hash"], "sha256:abc");
1288 assert_eq!(list["deployerSecrets"][0]["vaultKey"], "database-password");
1289 assert_eq!(list["deployerSecrets"][0]["required"], true);
1290 assert!(
1291 signed_workload_secrets(&body, "worker-without-any", "d", &none, &stored(&[])).is_err(),
1292 "a workload the release doesn't name has no list"
1293 );
1294 }
1295
1296 #[test]
1297 fn a_deployer_mapping_the_protected_install_would_drop_is_refused_when_signing() {
1298 let build = |input: serde_json::Value| {
1299 let mut stack = stack(&pinned());
1300 stack.inputs = serde_json::from_value(serde_json::json!([input])).unwrap();
1301 check_deployer_env_mappings(&stack, Platform::Aws)
1302 };
1303 let error = build(serde_json::json!(
1304 {"id": "operatorNote", "kind": "string", "providedBy": ["deployer"], "required": false,
1305 "label": "l", "description": "d",
1306 "env": [{"name": "OPERATOR_NOTE", "type": "secret", "targetResources": ["api"]}]}
1307 ))
1308 .expect_err(
1309 "a text input mapped as a secret has no vault slot, so its value would be dropped",
1310 );
1311 assert!(
1312 error.message.contains("operatorNote") && error.message.contains("OPERATOR_NOTE"),
1313 "{}",
1314 error.message
1315 );
1316 build(serde_json::json!(
1317 {"id": "apiKey", "kind": "secret", "providedBy": ["deployer"], "required": true,
1318 "label": "l", "description": "d",
1319 "env": [{"name": "API_KEY", "type": "plain", "targetResources": ["api"]}]}
1320 ))
1321 .expect_err("a secret input mapped as plain would be read from the deployment's store");
1322
1323 for input in [
1324 serde_json::json!({"id": "apiKey", "kind": "secret", "providedBy": ["deployer"],
1325 "required": true, "label": "l", "description": "d",
1326 "env": [{"name": "API_KEY", "targetResources": ["api"]}]}),
1327 serde_json::json!({"id": "region", "kind": "string", "providedBy": ["deployer"],
1328 "required": false, "label": "l", "description": "d",
1329 "env": [{"name": "REGION", "type": "plain"}]}),
1330 serde_json::json!({"id": "vendorNote", "kind": "string", "providedBy": ["developer"],
1331 "required": false, "label": "l", "description": "d",
1332 "env": [{"name": "VENDOR_NOTE", "type": "secret"}]}),
1333 ] {
1334 build(input).expect("the mapping matches how the install delivers the value");
1335 }
1336
1337 let mut stack = stack(&pinned());
1338 stack.inputs = serde_json::from_value(serde_json::json!([
1339 {"id": "operatorNote", "kind": "string", "providedBy": ["deployer"], "required": false,
1340 "label": "l", "description": "d",
1341 "env": [{"name": "OPERATOR_NOTE", "type": "secret"}]}
1342 ]))
1343 .unwrap();
1344 check_deployer_env_mappings(&stack, Platform::Kubernetes)
1345 .expect("a Kubernetes install honours the mapping's type itself");
1346 release_body(Platform::Aws, &stack, &production())
1347 .expect("an install reading a release it accepted does not refuse it again");
1348 }
1349
1350 #[test]
1351 fn a_stored_value_for_a_secret_input_does_not_change_the_signed_list() {
1352 let body = deployer_env_stack(serde_json::json!([
1353 {"id": "sharedKey", "kind": "secret", "providedBy": ["developer", "deployer"],
1354 "required": false, "label": "Shared key", "description": "d",
1355 "env": [{"name": "SHARED_KEY"}]},
1356 ]));
1357 let none = BTreeMap::new();
1358 for stored_values in [
1359 stored(&[]),
1360 stored(&[("sharedKey", "from-the-control-plane")]),
1361 ] {
1362 let secrets = signed_deployer_secrets(&body, "api", &none, &stored_values).unwrap();
1363 assert_eq!(
1364 secrets
1365 .iter()
1366 .map(|secret| secret.name.as_str())
1367 .collect::<Vec<_>>(),
1368 ["SHARED_KEY"],
1369 "the controller and the verifier see the same list whatever the store holds"
1370 );
1371 }
1372 }
1373
1374 fn alien_core_resource(container: Container) -> Resource {
1375 Resource::new(container)
1376 }
1377
1378 #[test]
1379 fn unsigned_code_is_refused_before_signing() {
1380 let error = release_body(
1381 Platform::Aws,
1382 &stack("registry.example.com/shop/api:latest"),
1383 &production(),
1384 )
1385 .expect_err("a tag is refused");
1386 assert!(error.message.contains("not pinned"), "{}", error.message);
1387
1388 let options = ReleaseOptions {
1389 configurable_env: vec!["LD_PRELOAD".to_string()],
1390 ..production()
1391 };
1392 release_body(Platform::Aws, &stack(&pinned()), &options)
1393 .expect_err("a loader variable can't be configurable");
1394 }
1395
1396 #[test]
1401 fn a_stack_declared_out_of_order_reads_back_as_its_own() {
1402 let mut web = container(&pinned());
1403 web.id = "web".to_string();
1404 let mut agent = container(&pinned());
1405 agent.id = "agent".to_string();
1406 let stack = Stack::new("shop".to_string())
1407 .add(web, ResourceLifecycle::Live)
1408 .add(agent, ResourceLifecycle::Live)
1409 .build();
1410 let body = release_body(Platform::Aws, &stack, &production()).unwrap();
1411 assert_eq!(
1412 body.workloads
1413 .iter()
1414 .map(|workload| workload.name.as_str())
1415 .collect::<Vec<_>>(),
1416 ["agent", "web"],
1417 "workloads are in name order"
1418 );
1419 let back = signed_stack(&body, Platform::Aws).expect("the release reads back as its stack");
1420 let mut ids = back
1423 .resources()
1424 .map(|(id, _)| id.as_str())
1425 .collect::<Vec<_>>();
1426 ids.sort_unstable();
1427 assert_eq!(ids, ["agent", "web"]);
1428 }
1429
1430 #[test]
1431 fn a_stack_that_disagrees_with_its_workloads_is_refused() {
1432 let mut body = release_body(Platform::Aws, &stack(&pinned()), &production()).unwrap();
1433 let other = format!("registry.example.com/shop/other@{DIGEST}");
1434 body.stack = Some(serde_json::to_value(stack(&other)).unwrap());
1435 signed_stack(&body, Platform::Aws).expect_err("a swapped stack is refused");
1436
1437 let body = release_body(Platform::Aws, &stack(&pinned()), &production()).unwrap();
1438 signed_stack(&body, Platform::Gcp).expect_err("another platform is refused");
1439 }
1440
1441 #[test]
1442 fn links_become_bindings_the_enforcer_computes() {
1443 let mut container = container(&pinned());
1444 container.links.push(ResourceRef::new(
1445 crate::ResourceType::from("storage"),
1446 "uploads".to_string(),
1447 ));
1448 let stack = Stack::new("shop".to_string())
1449 .add(container, ResourceLifecycle::Live)
1450 .build();
1451 let body = release_body(Platform::Aws, &stack, &production()).unwrap();
1452 assert_eq!(
1453 body.workloads[0].bindings,
1454 BTreeMap::from([("uploads".to_string(), "storage".to_string())])
1455 );
1456 let mut released_without_channel = body.clone();
1457 released_without_channel.channel = String::new();
1458 released_without_channel
1459 .validate()
1460 .expect_err("a release names its channel");
1461 }
1462
1463 #[test]
1464 fn images_move_between_registries_only_with_the_same_digest() {
1465 let signed = stack(&pinned());
1466 let carried = stack(&format!("proxy.example.com/shop/api@{DIGEST}"));
1467 let relocated = relocate_images(&signed, &carried);
1468 assert_eq!(
1469 code_image(&relocated.resources["api"].config),
1470 Some(format!("proxy.example.com/shop/api@{DIGEST}").as_str())
1471 );
1472
1473 let other_digest = format!("proxy.example.com/shop/api@sha256:{}", "0".repeat(64));
1474 let relocated = relocate_images(&signed, &stack(&other_digest));
1475 assert_eq!(
1476 code_image(&relocated.resources["api"].config),
1477 Some(pinned().as_str())
1478 );
1479 }
1480
1481 #[test]
1482 fn the_control_plane_cannot_set_the_runtime_address_or_public_endpoints() {
1483 use alien_signing::release::{build_workload, LocalValues, WorkloadRequest};
1484
1485 let body = release_body(Platform::Aws, &stack(&pinned()), &production()).unwrap();
1486 let build = |name: &str, value: &str| {
1487 build_workload(
1488 &body,
1489 "api",
1490 &BTreeMap::new(),
1491 &LocalValues::default(),
1492 &WorkloadRequest {
1493 env: BTreeMap::from([(name.to_string(), value.to_string())]),
1494 ..WorkloadRequest::default()
1495 },
1496 )
1497 };
1498
1499 build(ENV_ALIEN_DEPLOYMENT_ID, "dep_123").expect("a provided name is accepted");
1500 for (name, value) in [
1501 (ENV_ALIEN_WORKER_GRPC_ADDRESS, "0.0.0.0:51351"),
1502 (
1503 ENV_ALIEN_PUBLIC_ENDPOINTS_JSON,
1504 r#"{"api":{"url":"https://evil.example.com","host":"evil.example.com"}}"#,
1505 ),
1506 ] {
1507 let error = build(name, value).expect_err(name);
1508 assert_eq!(error.code, "SIGNING_WORKLOAD_REFUSED", "{name}");
1509 assert!(
1510 error
1511 .message
1512 .contains("is set by the runtime, not by the control plane"),
1513 "{name}: {}",
1514 error.message
1515 );
1516 }
1517 }
1518}