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 ..Default::default()
917 })
918 .build();
919 Stack::new("shop".to_string())
920 .add(sandbox, ResourceLifecycle::Live)
921 .build()
922 }
923
924 #[test]
925 fn a_sandbox_is_signed_by_the_digest_of_its_image() {
926 let registry = format!("registry.example.com/shop/sandbox@{DIGEST}");
927 let bundle = "s3://bundles/sandbox-bundle/agent/abc/bundle.zip";
928 for (stack, pin) in [
929 (sandbox_stack(®istry, None), registry.as_str()),
930 (sandbox_stack(bundle, Some(®istry)), registry.as_str()),
931 ] {
932 let body = release_body(Platform::Aws, &stack, &production()).unwrap();
933 assert_eq!(body.workloads.len(), 1);
934 assert_eq!(body.workloads[0].kind, WorkloadKind::Sandbox);
935 assert_eq!(body.workloads[0].image, pin);
936 }
937 }
938
939 #[test]
940 fn a_sandbox_without_a_pinned_image_is_refused() {
941 let unpinned = "registry.example.com/shop/sandbox:latest";
942 let bundle = "s3://bundles/sandbox-bundle/agent/abc/bundle.zip";
943 for stack in [
944 sandbox_stack(unpinned, None),
945 sandbox_stack("ubuntu", None),
947 sandbox_stack(bundle, None),
949 sandbox_stack(bundle, Some(unpinned)),
950 ] {
951 let error = release_body(Platform::Aws, &stack, &production()).unwrap_err();
952 assert!(
953 error.message.contains("pinned") || error.message.contains("bundle"),
954 "{}",
955 error.message
956 );
957 }
958 }
959
960 #[test]
961 fn a_pushed_stack_becomes_workloads_that_build_back_to_the_stack() {
962 let stack = stack(&pinned());
963 let body = release_body(Platform::Aws, &stack, &production()).unwrap();
964 assert_eq!(body.workloads.len(), 1);
965 let api = &body.workloads[0];
966 assert_eq!(api.name, "api");
967 assert_eq!(api.image, pinned());
968 assert_eq!(api.env["LOG_LEVEL"], "info");
969 assert_eq!(api.identity.as_deref(), Some("execution"));
970 assert_eq!(api.bounds.max_cpu.as_deref(), Some("1"));
971 assert_eq!(api.bounds.max_memory.as_deref(), Some("1Gi"));
972 assert_eq!(body.channel, "production");
973 assert!(api
974 .provided_env
975 .contains(&"ALIEN_DEPLOYMENT_ID".to_string()));
976 assert!(
977 !api.provided_env
978 .iter()
979 .any(|name| name.ends_with("_BINDING")
980 || name == ENV_ALIEN_SECRETS
981 || name.starts_with("OTEL_")),
982 "bindings, the secrets list and telemetry are never the control plane's: {:?}",
983 api.provided_env
984 );
985 assert_eq!(signed_stack(&body, Platform::Aws).unwrap(), stack);
986 }
987
988 #[test]
989 fn stack_inputs_become_configurable_or_deployer_env() {
990 let mut stack = stack(&pinned());
991 stack.inputs = serde_json::from_value(serde_json::json!([
992 {"id": "logLevel", "kind": "string", "providedBy": ["developer"], "required": false,
993 "label": "l", "description": "d", "env": [{"name": "LOG_LEVEL", "targetResources": ["api"]}]},
994 {"id": "databaseUrl", "kind": "string", "providedBy": ["deployer"], "required": false,
995 "label": "l", "description": "d", "env": [{"name": "DATABASE_URL", "targetResources": ["api"]}]},
996 ]))
997 .unwrap();
998 let mut container = container(&pinned());
1001 container.environment.clear();
1002 stack.resources.get_mut("api").unwrap().config = alien_core_resource(container);
1003 let body = release_body(Platform::Aws, &stack, &production()).unwrap();
1004 let api = &body.workloads[0];
1005 assert_eq!(api.deployer_env["DATABASE_URL"], "databaseUrl");
1006 assert!(api.configurable_env.contains(&"LOG_LEVEL".to_string()));
1007 assert_eq!(body.configurable.inputs, vec!["logLevel".to_string()]);
1008 assert_eq!(signed_stack(&body, Platform::Aws).unwrap(), stack);
1009 }
1010
1011 #[test]
1015 fn a_signed_config_sets_the_env_its_inputs_map_to() {
1016 let mut stack = stack(&pinned());
1017 stack.inputs = serde_json::from_value(serde_json::json!([
1018 {"id": "logLevel", "kind": "string", "providedBy": ["developer"], "required": false,
1019 "label": "l", "description": "d", "default": {"type": "string", "value": "info"},
1020 "env": [{"name": "LOG_LEVEL", "targetResources": ["api"]}]},
1021 {"id": "region", "kind": "string", "providedBy": ["developer"], "required": false,
1022 "label": "l", "description": "d",
1023 "env": [{"name": "REGION", "targetResources": ["api"]}, {"name": "ELSEWHERE", "targetResources": ["other"]}]},
1024 {"id": "token", "kind": "secret", "providedBy": ["developer"], "required": false,
1025 "label": "l", "description": "d", "env": [{"name": "TOKEN", "targetResources": ["api"]}]},
1026 {"id": "databaseUrl", "kind": "string", "providedBy": ["deployer"], "required": false,
1027 "label": "l", "description": "d", "default": {"type": "string", "value": "postgres://default"},
1028 "env": [{"name": "DATABASE_URL", "targetResources": ["api"]}]},
1029 ]))
1030 .unwrap();
1031 let mut api = container(&pinned());
1032 api.environment.clear();
1033 stack.resources.get_mut("api").unwrap().config = alien_core_resource(api);
1034 let body = release_body(Platform::Aws, &stack, &production()).unwrap();
1035 let config = |inputs: serde_json::Value, env: &[(&str, &str)]| ConfigBody {
1036 inputs: serde_json::from_value(inputs).unwrap(),
1037 env: env
1038 .iter()
1039 .map(|(name, value)| (name.to_string(), value.to_string()))
1040 .collect(),
1041 ..Default::default()
1042 };
1043
1044 let env = signed_config_env(
1045 &body,
1046 "api",
1047 &config(serde_json::json!({"region": "eu", "token": "s3cret"}), &[]),
1048 &Default::default(),
1049 )
1050 .unwrap();
1051 assert_eq!(
1052 env,
1053 BTreeMap::from([
1054 ("LOG_LEVEL".to_string(), "info".to_string()),
1055 ("REGION".to_string(), "eu".to_string()),
1056 ]),
1057 "the default applies, secrets and deployer inputs never travel in a signed config, \
1058 and a mapping aimed at another resource isn't this workload's"
1059 );
1060
1061 let env = signed_config_env(
1062 &body,
1063 "api",
1064 &config(
1065 serde_json::json!({"logLevel": "debug"}),
1066 &[("LOG_LEVEL", "trace")],
1067 ),
1068 &Default::default(),
1069 )
1070 .unwrap();
1071 assert_eq!(env["LOG_LEVEL"], "trace", "the config's own env wins");
1072 }
1073
1074 #[test]
1077 fn a_developer_input_gated_on_a_deployer_input_follows_the_installs_value() {
1078 let mut stack = stack(&pinned());
1079 stack.inputs = serde_json::from_value(serde_json::json!([
1080 {"id": "audit", "kind": "boolean", "providedBy": ["deployer"], "required": false,
1081 "label": "l", "description": "d", "default": {"type": "boolean", "value": true}},
1082 {"id": "auditSink", "kind": "string", "providedBy": ["developer"], "required": false,
1083 "label": "l", "description": "d", "when": {"input": "audit", "equals": true},
1084 "env": [{"name": "AUDIT_SINK", "targetResources": ["api"]}]},
1085 {"id": "logLevel", "kind": "string", "providedBy": ["developer"], "required": false,
1086 "label": "l", "description": "d", "env": [{"name": "LOG_LEVEL", "targetResources": ["api"]}]},
1087 ]))
1088 .unwrap();
1089 let mut api = container(&pinned());
1090 api.environment.clear();
1091 stack.resources.get_mut("api").unwrap().config = alien_core_resource(api);
1092 let body = release_body(Platform::Aws, &stack, &production()).unwrap();
1093 assert_eq!(
1094 gating_deployer_inputs(&body).unwrap(),
1095 vec!["audit".to_string()]
1096 );
1097
1098 let config = ConfigBody {
1099 inputs: serde_json::from_value(
1100 serde_json::json!({"auditSink": "https://audit.example"}),
1101 )
1102 .unwrap(),
1103 ..Default::default()
1104 };
1105 let with = |audit: Option<&str>| {
1106 let values = audit
1107 .map(|audit| {
1108 std::collections::HashMap::from([(
1109 "audit".to_string(),
1110 serde_json::Value::String(audit.to_string()),
1111 )])
1112 })
1113 .unwrap_or_default();
1114 signed_config_env(&body, "api", &config, &values).unwrap()
1115 };
1116 assert_eq!(with(Some("true"))["AUDIT_SINK"], "https://audit.example");
1117 assert_eq!(
1118 with(None)["AUDIT_SINK"],
1119 "https://audit.example",
1120 "the default is on"
1121 );
1122 assert!(
1123 !with(Some("false")).contains_key("AUDIT_SINK"),
1124 "the customer turned it off"
1125 );
1126 }
1127
1128 fn deployer_env_stack(inputs: serde_json::Value) -> ReleaseBody {
1129 let mut stack = stack(&pinned());
1130 stack.inputs = serde_json::from_value(inputs).unwrap();
1131 let mut api = container(&pinned());
1132 api.environment.clear();
1133 stack.resources.get_mut("api").unwrap().config = alien_core_resource(api);
1134 release_body(Platform::Aws, &stack, &production()).unwrap()
1135 }
1136
1137 fn stored(values: &[(&str, &str)]) -> std::collections::HashMap<String, serde_json::Value> {
1138 values
1139 .iter()
1140 .map(|(id, value)| (id.to_string(), serde_json::Value::String(value.to_string())))
1141 .collect()
1142 }
1143
1144 #[test]
1145 fn deployer_env_resolves_defaults_and_leaves_out_unset_optional_inputs() {
1146 let body = deployer_env_stack(serde_json::json!([
1147 {"id": "region", "kind": "string", "providedBy": ["deployer"], "required": false,
1148 "label": "l", "description": "d", "default": {"type": "string", "value": "eu"},
1149 "env": [{"name": "REGION", "targetResources": ["api"]}]},
1150 {"id": "proxy", "kind": "string", "providedBy": ["deployer"], "required": false,
1151 "label": "l", "description": "d",
1152 "env": [{"name": "PROXY_URL", "targetResources": ["api"]}]},
1153 {"id": "databaseUrl", "kind": "string", "providedBy": ["deployer"], "required": true,
1154 "label": "l", "description": "d",
1155 "env": [{"name": "DATABASE_URL", "targetResources": ["api"]}]},
1156 ]));
1157 let none = BTreeMap::new();
1158 let env = signed_deployer_env(&body, "api", &none, &stored(&[("databaseUrl", "pg://a")]))
1159 .unwrap();
1160 assert_eq!(
1161 env,
1162 BTreeMap::from([
1163 ("REGION".to_string(), "eu".to_string()),
1164 ("DATABASE_URL".to_string(), "pg://a".to_string()),
1165 ]),
1166 "the default fills an unset input and an optional input with neither is left out"
1167 );
1168 let env = signed_deployer_env(
1169 &body,
1170 "api",
1171 &none,
1172 &stored(&[
1173 ("databaseUrl", "pg://a"),
1174 ("region", "us"),
1175 ("proxy", "http://p"),
1176 ]),
1177 )
1178 .unwrap();
1179 assert_eq!(env["REGION"], "us");
1180 assert_eq!(env["PROXY_URL"], "http://p");
1181 let error = signed_deployer_env(&body, "api", &none, &stored(&[]))
1182 .expect_err("a required input with no value is refused");
1183 assert!(error.message.contains("databaseUrl"), "{}", error.message);
1184 }
1185
1186 #[test]
1187 fn deployer_env_follows_the_signed_when_not_the_stored_values() {
1188 let body = deployer_env_stack(serde_json::json!([
1189 {"id": "audit", "kind": "boolean", "providedBy": ["deployer"], "required": false,
1190 "label": "l", "description": "d", "default": {"type": "boolean", "value": false}},
1191 {"id": "auditSink", "kind": "string", "providedBy": ["deployer"], "required": true,
1192 "label": "l", "description": "d", "when": {"input": "audit", "equals": true},
1193 "env": [{"name": "AUDIT_SINK", "targetResources": ["api"]}]},
1194 ]));
1195 assert_eq!(
1196 gating_deployer_inputs(&body).unwrap(),
1197 vec!["audit".to_string()],
1198 "a deployer input's own gate is read from the store too"
1199 );
1200 let none = BTreeMap::new();
1201 let off = signed_deployer_env(&body, "api", &none, &stored(&[])).unwrap();
1202 assert!(
1203 off.is_empty(),
1204 "an inactive required input demands nothing: {off:?}"
1205 );
1206 let off = signed_deployer_env(
1207 &body,
1208 "api",
1209 &none,
1210 &stored(&[("auditSink", "https://stale.example")]),
1211 )
1212 .unwrap();
1213 assert!(
1214 off.is_empty(),
1215 "a stored value of an inactive input is ignored"
1216 );
1217 let on = signed_deployer_env(
1218 &body,
1219 "api",
1220 &none,
1221 &stored(&[("audit", "true"), ("auditSink", "https://audit.example")]),
1222 )
1223 .unwrap();
1224 assert_eq!(on["AUDIT_SINK"], "https://audit.example");
1225 signed_deployer_env(&body, "api", &none, &stored(&[("audit", "true")]))
1226 .expect_err("active and required, so a value is needed");
1227 }
1228
1229 #[test]
1230 fn a_secret_input_never_becomes_plain_deployer_env() {
1231 let body = deployer_env_stack(serde_json::json!([
1232 {"id": "apiKey", "kind": "secret", "providedBy": ["deployer"], "required": true,
1233 "label": "l", "description": "d",
1234 "env": [{"name": "API_KEY", "targetResources": ["api"]}]},
1235 ]));
1236 assert!(
1237 body.workloads[0].deployer_env.is_empty(),
1238 "a secret input is delivered through the secrets vault, never as plain env"
1239 );
1240 let env = signed_deployer_env(&body, "api", &BTreeMap::new(), &stored(&[("apiKey", "x")]))
1241 .unwrap();
1242 assert!(env.is_empty(), "{env:?}");
1243 }
1244
1245 #[test]
1246 fn deployer_secrets_come_from_the_signed_stack_and_follow_its_gates() {
1247 let body = deployer_env_stack(serde_json::json!([
1248 {"id": "audit", "kind": "boolean", "providedBy": ["deployer"], "required": false,
1249 "label": "l", "description": "d", "default": {"type": "boolean", "value": false}},
1250 {"id": "databasePassword", "kind": "secret", "providedBy": ["deployer"], "required": true,
1251 "label": "Database password", "description": "d",
1252 "env": [{"name": "DATABASE_PASSWORD", "targetResources": ["api"]},
1253 {"name": "ELSEWHERE", "targetResources": ["other"]}]},
1254 {"id": "auditToken", "kind": "secret", "providedBy": ["deployer"], "required": false,
1255 "label": "Audit token", "description": "d", "when": {"input": "audit", "equals": true},
1256 "env": [{"name": "AUDIT_TOKEN"}]},
1257 {"id": "vendorKey", "kind": "secret", "providedBy": ["developer"], "required": true,
1258 "label": "Vendor key", "description": "d",
1259 "env": [{"name": "VENDOR_KEY"}]},
1260 ]));
1261 let none = BTreeMap::new();
1262 let secrets = signed_deployer_secrets(&body, "api", &none, &stored(&[])).unwrap();
1263 assert_eq!(
1264 secrets,
1265 vec![crate::DeployerSecretEnv {
1266 name: "DATABASE_PASSWORD".into(),
1267 vault_key: "database-password".into(),
1268 secret_name: "database-password".into(),
1269 vault_name: None,
1270 label: "Database password".into(),
1271 required: true,
1272 version: None,
1273 }],
1274 "only the deployer's secret that applies and targets the worker; the gated one is off, \
1275 the developer's has no value on a protected install"
1276 );
1277 let on =
1278 signed_deployer_secrets(&body, "api", &none, &stored(&[("audit", "true")])).unwrap();
1279 let names: Vec<&str> = on.iter().map(|secret| secret.name.as_str()).collect();
1280 assert_eq!(names, ["DATABASE_PASSWORD", "AUDIT_TOKEN"]);
1281 assert!(!on[1].required);
1282
1283 let list = signed_workload_secrets(&body, "api", "sha256:abc", &none, &stored(&[]))
1284 .unwrap()
1285 .expect("a worker with a deployer secret loads a list");
1286 let list: serde_json::Value = serde_json::from_str(&list).unwrap();
1287 assert_eq!(list["keys"], serde_json::json!([]));
1288 assert_eq!(list["hash"], "sha256:abc");
1289 assert_eq!(list["deployerSecrets"][0]["vaultKey"], "database-password");
1290 assert_eq!(list["deployerSecrets"][0]["required"], true);
1291 assert!(
1292 signed_workload_secrets(&body, "worker-without-any", "d", &none, &stored(&[])).is_err(),
1293 "a workload the release doesn't name has no list"
1294 );
1295 }
1296
1297 #[test]
1298 fn a_deployer_mapping_the_protected_install_would_drop_is_refused_when_signing() {
1299 let build = |input: serde_json::Value| {
1300 let mut stack = stack(&pinned());
1301 stack.inputs = serde_json::from_value(serde_json::json!([input])).unwrap();
1302 check_deployer_env_mappings(&stack, Platform::Aws)
1303 };
1304 let error = build(serde_json::json!(
1305 {"id": "operatorNote", "kind": "string", "providedBy": ["deployer"], "required": false,
1306 "label": "l", "description": "d",
1307 "env": [{"name": "OPERATOR_NOTE", "type": "secret", "targetResources": ["api"]}]}
1308 ))
1309 .expect_err(
1310 "a text input mapped as a secret has no vault slot, so its value would be dropped",
1311 );
1312 assert!(
1313 error.message.contains("operatorNote") && error.message.contains("OPERATOR_NOTE"),
1314 "{}",
1315 error.message
1316 );
1317 build(serde_json::json!(
1318 {"id": "apiKey", "kind": "secret", "providedBy": ["deployer"], "required": true,
1319 "label": "l", "description": "d",
1320 "env": [{"name": "API_KEY", "type": "plain", "targetResources": ["api"]}]}
1321 ))
1322 .expect_err("a secret input mapped as plain would be read from the deployment's store");
1323
1324 for input in [
1325 serde_json::json!({"id": "apiKey", "kind": "secret", "providedBy": ["deployer"],
1326 "required": true, "label": "l", "description": "d",
1327 "env": [{"name": "API_KEY", "targetResources": ["api"]}]}),
1328 serde_json::json!({"id": "region", "kind": "string", "providedBy": ["deployer"],
1329 "required": false, "label": "l", "description": "d",
1330 "env": [{"name": "REGION", "type": "plain"}]}),
1331 serde_json::json!({"id": "vendorNote", "kind": "string", "providedBy": ["developer"],
1332 "required": false, "label": "l", "description": "d",
1333 "env": [{"name": "VENDOR_NOTE", "type": "secret"}]}),
1334 ] {
1335 build(input).expect("the mapping matches how the install delivers the value");
1336 }
1337
1338 let mut stack = stack(&pinned());
1339 stack.inputs = serde_json::from_value(serde_json::json!([
1340 {"id": "operatorNote", "kind": "string", "providedBy": ["deployer"], "required": false,
1341 "label": "l", "description": "d",
1342 "env": [{"name": "OPERATOR_NOTE", "type": "secret"}]}
1343 ]))
1344 .unwrap();
1345 check_deployer_env_mappings(&stack, Platform::Kubernetes)
1346 .expect("a Kubernetes install honours the mapping's type itself");
1347 release_body(Platform::Aws, &stack, &production())
1348 .expect("an install reading a release it accepted does not refuse it again");
1349 }
1350
1351 #[test]
1352 fn a_stored_value_for_a_secret_input_does_not_change_the_signed_list() {
1353 let body = deployer_env_stack(serde_json::json!([
1354 {"id": "sharedKey", "kind": "secret", "providedBy": ["developer", "deployer"],
1355 "required": false, "label": "Shared key", "description": "d",
1356 "env": [{"name": "SHARED_KEY"}]},
1357 ]));
1358 let none = BTreeMap::new();
1359 for stored_values in [
1360 stored(&[]),
1361 stored(&[("sharedKey", "from-the-control-plane")]),
1362 ] {
1363 let secrets = signed_deployer_secrets(&body, "api", &none, &stored_values).unwrap();
1364 assert_eq!(
1365 secrets
1366 .iter()
1367 .map(|secret| secret.name.as_str())
1368 .collect::<Vec<_>>(),
1369 ["SHARED_KEY"],
1370 "the controller and the verifier see the same list whatever the store holds"
1371 );
1372 }
1373 }
1374
1375 fn alien_core_resource(container: Container) -> Resource {
1376 Resource::new(container)
1377 }
1378
1379 #[test]
1380 fn unsigned_code_is_refused_before_signing() {
1381 let error = release_body(
1382 Platform::Aws,
1383 &stack("registry.example.com/shop/api:latest"),
1384 &production(),
1385 )
1386 .expect_err("a tag is refused");
1387 assert!(error.message.contains("not pinned"), "{}", error.message);
1388
1389 let options = ReleaseOptions {
1390 configurable_env: vec!["LD_PRELOAD".to_string()],
1391 ..production()
1392 };
1393 release_body(Platform::Aws, &stack(&pinned()), &options)
1394 .expect_err("a loader variable can't be configurable");
1395 }
1396
1397 #[test]
1402 fn a_stack_declared_out_of_order_reads_back_as_its_own() {
1403 let mut web = container(&pinned());
1404 web.id = "web".to_string();
1405 let mut agent = container(&pinned());
1406 agent.id = "agent".to_string();
1407 let stack = Stack::new("shop".to_string())
1408 .add(web, ResourceLifecycle::Live)
1409 .add(agent, ResourceLifecycle::Live)
1410 .build();
1411 let body = release_body(Platform::Aws, &stack, &production()).unwrap();
1412 assert_eq!(
1413 body.workloads
1414 .iter()
1415 .map(|workload| workload.name.as_str())
1416 .collect::<Vec<_>>(),
1417 ["agent", "web"],
1418 "workloads are in name order"
1419 );
1420 let back = signed_stack(&body, Platform::Aws).expect("the release reads back as its stack");
1421 let mut ids = back
1424 .resources()
1425 .map(|(id, _)| id.as_str())
1426 .collect::<Vec<_>>();
1427 ids.sort_unstable();
1428 assert_eq!(ids, ["agent", "web"]);
1429 }
1430
1431 #[test]
1432 fn a_stack_that_disagrees_with_its_workloads_is_refused() {
1433 let mut body = release_body(Platform::Aws, &stack(&pinned()), &production()).unwrap();
1434 let other = format!("registry.example.com/shop/other@{DIGEST}");
1435 body.stack = Some(serde_json::to_value(stack(&other)).unwrap());
1436 signed_stack(&body, Platform::Aws).expect_err("a swapped stack is refused");
1437
1438 let body = release_body(Platform::Aws, &stack(&pinned()), &production()).unwrap();
1439 signed_stack(&body, Platform::Gcp).expect_err("another platform is refused");
1440 }
1441
1442 #[test]
1443 fn links_become_bindings_the_enforcer_computes() {
1444 let mut container = container(&pinned());
1445 container.links.push(ResourceRef::new(
1446 crate::ResourceType::from("storage"),
1447 "uploads".to_string(),
1448 ));
1449 let stack = Stack::new("shop".to_string())
1450 .add(container, ResourceLifecycle::Live)
1451 .build();
1452 let body = release_body(Platform::Aws, &stack, &production()).unwrap();
1453 assert_eq!(
1454 body.workloads[0].bindings,
1455 BTreeMap::from([("uploads".to_string(), "storage".to_string())])
1456 );
1457 let mut released_without_channel = body.clone();
1458 released_without_channel.channel = String::new();
1459 released_without_channel
1460 .validate()
1461 .expect_err("a release names its channel");
1462 }
1463
1464 #[test]
1465 fn images_move_between_registries_only_with_the_same_digest() {
1466 let signed = stack(&pinned());
1467 let carried = stack(&format!("proxy.example.com/shop/api@{DIGEST}"));
1468 let relocated = relocate_images(&signed, &carried);
1469 assert_eq!(
1470 code_image(&relocated.resources["api"].config),
1471 Some(format!("proxy.example.com/shop/api@{DIGEST}").as_str())
1472 );
1473
1474 let other_digest = format!("proxy.example.com/shop/api@sha256:{}", "0".repeat(64));
1475 let relocated = relocate_images(&signed, &stack(&other_digest));
1476 assert_eq!(
1477 code_image(&relocated.resources["api"].config),
1478 Some(pinned().as_str())
1479 );
1480 }
1481
1482 #[test]
1483 fn the_control_plane_cannot_set_the_runtime_address_or_public_endpoints() {
1484 use alien_signing::release::{build_workload, LocalValues, WorkloadRequest};
1485
1486 let body = release_body(Platform::Aws, &stack(&pinned()), &production()).unwrap();
1487 let build = |name: &str, value: &str| {
1488 build_workload(
1489 &body,
1490 "api",
1491 &BTreeMap::new(),
1492 &LocalValues::default(),
1493 &WorkloadRequest {
1494 env: BTreeMap::from([(name.to_string(), value.to_string())]),
1495 ..WorkloadRequest::default()
1496 },
1497 )
1498 };
1499
1500 build(ENV_ALIEN_DEPLOYMENT_ID, "dep_123").expect("a provided name is accepted");
1501 for (name, value) in [
1502 (ENV_ALIEN_WORKER_GRPC_ADDRESS, "0.0.0.0:51351"),
1503 (
1504 ENV_ALIEN_PUBLIC_ENDPOINTS_JSON,
1505 r#"{"api":{"url":"https://evil.example.com","host":"evil.example.com"}}"#,
1506 ),
1507 ] {
1508 let error = build(name, value).expect_err(name);
1509 assert_eq!(error.code, "SIGNING_WORKLOAD_REFUSED", "{name}");
1510 assert!(
1511 error
1512 .message
1513 .contains("is set by the runtime, not by the control plane"),
1514 "{name}: {}",
1515 error.message
1516 );
1517 }
1518 }
1519}