1use std::collections::{BTreeMap, BTreeSet};
13
14use alien_error::AlienError;
15use serde::{Deserialize, Serialize};
16
17use crate::envelope::Kind;
18use crate::error::{ErrorData, Result};
19
20pub const LOADER_ENV: &[&str] = &[
24 "LD_PRELOAD",
25 "LD_LIBRARY_PATH",
26 "LD_AUDIT",
27 "LD_BIND_NOW",
28 "LD_DEBUG",
29 "LD_PROFILE",
30 "DYLD_INSERT_LIBRARIES",
31 "DYLD_LIBRARY_PATH",
32 "NODE_OPTIONS",
33 "NODE_PATH",
34 "NODE_EXTRA_CA_CERTS",
35 "NODE_TLS_REJECT_UNAUTHORIZED",
36 "PYTHONPATH",
37 "PYTHONHOME",
38 "PYTHONSTARTUP",
39 "PYTHONINSPECT",
40 "PYTHONUSERBASE",
41 "PYTHONWARNINGS",
42 "PERL5OPT",
43 "PERL5LIB",
44 "PERLLIB",
45 "RUBYOPT",
46 "RUBYLIB",
47 "JAVA_TOOL_OPTIONS",
48 "JDK_JAVA_OPTIONS",
49 "_JAVA_OPTIONS",
50 "CLASSPATH",
51 "DOTNET_STARTUP_HOOKS",
52 "CORECLR_ENABLE_PROFILING",
53 "CORECLR_PROFILER",
54 "CORECLR_PROFILER_PATH",
55 "BASH_ENV",
56 "ENV",
57 "PATH",
58 "GCONV_PATH",
59 "SSL_CERT_FILE",
60 "SSL_CERT_DIR",
61 "GIT_SSH_COMMAND",
62 "PHPRC",
63 "PHP_INI_SCAN_DIR",
64 "BUN_OPTIONS",
65 "DENO_DIR",
66 "GLIBC_TUNABLES",
67 "LOCPATH",
68 "NLSPATH",
69 "PYTHONBREAKPOINT",
70 "PYTHONEXECUTABLE",
71 "PYTHONPLATLIBDIR",
72 "PERL5DB",
73 "RUBYGEMS_GEMDEPS",
74 "NODE_REPL_EXTERNAL_MODULE",
75 "LUA_INIT",
76 "LUA_PATH",
77 "LUA_CPATH",
78 "DOTNET_ADDITIONAL_DEPS",
79 "DOTNET_SHARED_STORE",
80 "COR_ENABLE_PROFILING",
81 "COR_PROFILER",
82 "COR_PROFILER_PATH",
83];
84
85pub const LOADER_ENV_PREFIXES: &[&str] = &["LD_", "DYLD_", "BASH_FUNC_", "CORECLR_"];
88
89const NEVER_FROM_REQUEST: &[&str] = &["ALIEN_WORKER_GRPC_ADDRESS", "ALIEN_PUBLIC_ENDPOINTS_JSON"];
93
94pub const RUNTIME_SEND_OTLP: &str = "ALIEN_RUNTIME_SEND_OTLP";
97
98pub fn is_loader_env(name: &str) -> bool {
100 LOADER_ENV.contains(&name)
101 || LOADER_ENV_PREFIXES
102 .iter()
103 .any(|prefix| name.starts_with(prefix))
104}
105
106pub const COMPONENTS: &[&str] = &[
109 "machine-agent/linux-x86_64",
110 "machine-agent/linux-aarch64",
111 "operator",
112];
113
114pub const SETUP_TEMPLATES: &[&str] = &[
116 "cloudformation",
117 "terraform-aws",
118 "terraform-gcp",
119 "terraform-azure",
120 "helm",
121];
122
123#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
125#[serde(rename_all = "camelCase", deny_unknown_fields)]
126pub struct ReleaseBody {
127 pub platform: String,
129 pub channel: String,
132 pub workloads: Vec<Workload>,
134 #[serde(default)]
136 pub configurable: Configurable,
137 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
140 pub components: BTreeMap<String, String>,
141 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
144 pub setup: BTreeMap<String, SetupTemplate>,
145 #[serde(default, skip_serializing_if = "Option::is_none")]
148 pub stack: Option<serde_json::Value>,
149}
150
151#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
153#[serde(rename_all = "camelCase", deny_unknown_fields)]
154pub struct SetupTemplate {
155 pub sha256: String,
157 #[serde(default, skip_serializing_if = "Vec::is_empty")]
160 pub allowed: Vec<String>,
161}
162
163#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
165#[serde(rename_all = "camelCase", deny_unknown_fields)]
166pub struct Configurable {
167 #[serde(default, skip_serializing_if = "Vec::is_empty")]
170 pub env: Vec<String>,
171 #[serde(default, skip_serializing_if = "Vec::is_empty")]
173 pub inputs: Vec<String>,
174}
175
176#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
178#[serde(rename_all = "camelCase")]
179pub enum WorkloadKind {
180 Container,
182 Daemon,
184 Function,
186 Sandbox,
188 Build,
190}
191
192#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
194#[serde(rename_all = "camelCase", deny_unknown_fields)]
195pub struct Workload {
196 pub name: String,
198 pub kind: WorkloadKind,
200 pub image: String,
202 #[serde(default, skip_serializing_if = "Option::is_none")]
204 pub command: Option<Vec<String>>,
205 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
207 pub env: BTreeMap<String, String>,
208 #[serde(default, skip_serializing_if = "Vec::is_empty")]
210 pub provided_env: Vec<String>,
211 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
215 pub bindings: BTreeMap<String, String>,
216 #[serde(default, skip_serializing_if = "Vec::is_empty")]
218 pub configurable_env: Vec<String>,
219 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
223 pub deployer_env: BTreeMap<String, String>,
224 #[serde(default, skip_serializing_if = "Vec::is_empty")]
226 pub secrets: Vec<SecretBinding>,
227 #[serde(default)]
229 pub runtime: Runtime,
230 #[serde(default, skip_serializing_if = "Option::is_none")]
232 pub volume_mount_path: Option<String>,
233 #[serde(default, skip_serializing_if = "Option::is_none")]
235 pub identity: Option<String>,
236 #[serde(default)]
238 pub bounds: Bounds,
239 #[serde(default, skip_serializing_if = "Option::is_none")]
241 pub function: Option<FunctionSettings>,
242}
243
244#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
247#[serde(rename_all = "camelCase", deny_unknown_fields)]
248pub struct SecretBinding {
249 pub name: String,
251 #[serde(default, skip_serializing_if = "Option::is_none")]
253 pub env_name: Option<String>,
254 #[serde(default, skip_serializing_if = "Option::is_none")]
256 pub file_path: Option<String>,
257}
258
259#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
261#[serde(rename_all = "camelCase", deny_unknown_fields)]
262pub struct Runtime {
263 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
265 pub privileged: bool,
266 #[serde(default, skip_serializing_if = "Option::is_none")]
268 pub pid_namespace: Option<String>,
269 #[serde(default, skip_serializing_if = "Option::is_none")]
271 pub network_mode: Option<String>,
272 #[serde(default, skip_serializing_if = "Option::is_none")]
274 pub user: Option<String>,
275 #[serde(default, skip_serializing_if = "Vec::is_empty")]
277 pub mounts: Vec<Mount>,
278 #[serde(default, skip_serializing_if = "Option::is_none")]
280 pub security: Option<Security>,
281 #[serde(default, skip_serializing_if = "Option::is_none")]
283 pub egress: Option<String>,
284}
285
286#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
288#[serde(rename_all = "camelCase", deny_unknown_fields)]
289pub struct Mount {
290 pub source: String,
292 pub target: String,
294 #[serde(default, skip_serializing_if = "Option::is_none")]
296 pub options: Option<String>,
297}
298
299#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
301#[serde(rename_all = "camelCase", deny_unknown_fields)]
302pub struct Security {
303 pub profile: String,
305 #[serde(default, skip_serializing_if = "Option::is_none")]
307 pub run_as_user: Option<i64>,
308 #[serde(default, skip_serializing_if = "Option::is_none")]
310 pub run_as_group: Option<i64>,
311 #[serde(default, skip_serializing_if = "Option::is_none")]
313 pub read_only_root_filesystem: Option<bool>,
314 #[serde(default, skip_serializing_if = "Vec::is_empty")]
316 pub writable_paths: Vec<String>,
317}
318
319#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
321#[serde(rename_all = "camelCase", deny_unknown_fields)]
322pub struct Bounds {
323 #[serde(default, skip_serializing_if = "Option::is_none")]
325 pub max_cpu: Option<String>,
326 #[serde(default, skip_serializing_if = "Option::is_none")]
328 pub max_memory: Option<String>,
329 #[serde(default, skip_serializing_if = "Option::is_none")]
331 pub max_replicas: Option<u32>,
332}
333
334#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
336#[serde(rename_all = "camelCase", deny_unknown_fields)]
337pub struct FunctionSettings {
338 pub memory_mb: u32,
340 pub timeout_seconds: u32,
342 #[serde(default, skip_serializing_if = "Option::is_none")]
344 pub architecture: Option<String>,
345}
346
347impl ReleaseBody {
348 pub fn live_resources(&self) -> BTreeSet<String> {
350 self.stack
351 .as_ref()
352 .and_then(|stack| stack.get("resources"))
353 .and_then(|resources| resources.as_object())
354 .into_iter()
355 .flatten()
356 .filter(|(_, entry)| entry["lifecycle"] == "live")
357 .map(|(id, _)| id.clone())
358 .collect()
359 }
360
361 pub fn validate(&self) -> Result<()> {
363 let mut names = BTreeSet::new();
364 for workload in &self.workloads {
365 if !names.insert(workload.name.as_str()) {
366 return Err(body_refused(format!(
367 "workload '{}' appears twice",
368 workload.name
369 )));
370 }
371 workload.validate()?;
372 for name in &workload.configurable_env {
373 if !self.configurable.env.contains(name) {
374 return Err(workload_refused(
375 &workload.name,
376 format!(
377 "configurable env '{name}' is not in the release's configurable env"
378 ),
379 ));
380 }
381 }
382 }
383 for name in &self.configurable.env {
384 check_settable_name(name).map_err(body_refused)?;
385 }
386 if self.channel.is_empty()
387 || !self
388 .channel
389 .bytes()
390 .all(|byte| matches!(byte, b'a'..=b'z' | b'0'..=b'9' | b'-'))
391 {
392 return Err(body_refused(format!(
393 "channel '{}' is not [a-z0-9-]",
394 self.channel
395 )));
396 }
397 for (name, digest) in &self.components {
398 if !COMPONENTS.contains(&name.as_str()) {
399 return Err(body_refused(format!("'{name}' is not a component")));
400 }
401 if !is_sha256_digest(digest) {
402 return Err(body_refused(format!(
403 "'{name}' digest '{digest}' is not sha256:<hex>"
404 )));
405 }
406 }
407 for (name, template) in &self.setup {
408 if !SETUP_TEMPLATES.contains(&name.as_str()) {
409 return Err(body_refused(format!("'{name}' is not a setup template")));
410 }
411 if !is_sha256_digest(&template.sha256) {
412 return Err(body_refused(format!(
413 "setup '{name}' digest '{}' is not sha256:<hex>",
414 template.sha256
415 )));
416 }
417 }
418 Ok(())
419 }
420
421 pub fn workload(&self, name: &str) -> Result<&Workload> {
423 self.workloads
424 .iter()
425 .find(|workload| workload.name == name)
426 .ok_or_else(|| {
427 workload_refused(name, "the signed release has no workload by this name")
428 })
429 }
430}
431
432impl Workload {
433 fn validate(&self) -> Result<()> {
434 let refuse = |reason: String| workload_refused(&self.name, reason);
435 if self.name.is_empty() {
436 return Err(refuse("the name is empty".to_string()));
437 }
438 if !is_pinned_image(&self.image) {
439 return Err(refuse(format!(
440 "image '{}' is not pinned by sha256 digest",
441 self.image
442 )));
443 }
444 for name in self
445 .provided_env
446 .iter()
447 .chain(&self.configurable_env)
448 .chain(self.deployer_env.keys())
449 {
450 check_settable_name(name).map_err(refuse)?;
451 if self.env.contains_key(name) {
452 return Err(refuse(format!(
453 "'{name}' has a fixed value and can't also be provided or configured"
454 )));
455 }
456 }
457 for secret in &self.secrets {
458 if let Some(env_name) = &secret.env_name {
459 check_settable_name(env_name).map_err(refuse)?;
460 }
461 if let Some(path) = &secret.file_path {
462 if !path.starts_with('/') || path.split('/').any(|part| part == "..") {
463 return Err(refuse(format!(
464 "secret file path '{path}' is not absolute and plain"
465 )));
466 }
467 }
468 }
469 if let Some(max_cpu) = &self.bounds.max_cpu {
470 parse_cpu_millis(max_cpu).map_err(refuse)?;
471 }
472 if let Some(max_memory) = &self.bounds.max_memory {
473 parse_memory_bytes(max_memory).map_err(refuse)?;
474 }
475 for (id, resource_type) in &self.bindings {
476 if id.is_empty() || resource_type.is_empty() {
477 return Err(refuse("a binding needs a resource id and type".into()));
478 }
479 let name = crate::binding::binding_env_name(id);
480 if self.env.contains_key(&name) || self.provided_env.contains(&name) {
481 return Err(refuse(format!(
482 "{name} is a binding the enforcer computes; it can't also be fixed or provided"
483 )));
484 }
485 }
486 if (self.kind == WorkloadKind::Function) != self.function.is_some() {
487 return Err(refuse(
488 "function settings are required on functions and only on functions".into(),
489 ));
490 }
491 Ok(())
492 }
493}
494
495#[derive(Debug, Clone, Default)]
498pub struct WorkloadRequest {
499 pub env: BTreeMap<String, String>,
502 pub secrets: Vec<RequestedSecret>,
504 pub cpu: Option<String>,
506 pub memory: Option<String>,
508 pub replicas: Option<u32>,
510}
511
512#[derive(Debug, Clone, Default)]
515pub struct LocalValues {
516 pub deployer_env: BTreeMap<String, String>,
520 pub bindings: BTreeMap<String, String>,
522 pub own_binding: crate::binding::OwnBindingFacts,
524}
525
526#[derive(Debug, Clone, PartialEq, Eq)]
528pub struct RequestedSecret {
529 pub name: String,
531 pub env_name: Option<String>,
533 pub file_path: Option<String>,
535}
536
537#[derive(Debug, Clone, PartialEq, Eq)]
539pub struct BuiltWorkload {
540 pub name: String,
542 pub image: String,
544 pub command: Option<Vec<String>>,
546 pub env: BTreeMap<String, String>,
548 pub runtime: Runtime,
550 pub volume_mount_path: Option<String>,
552 pub identity: Option<String>,
554}
555
556pub fn build_workload(
564 release: &ReleaseBody,
565 name: &str,
566 config_env: &BTreeMap<String, String>,
567 local: &LocalValues,
568 request: &WorkloadRequest,
569) -> Result<BuiltWorkload> {
570 let workload = release.workload(name)?;
571 let refuse = |reason: String| workload_refused(name, reason);
572
573 let mut env = workload.env.clone();
574 for (key, value) in config_env {
575 if workload.configurable_env.contains(key) {
576 env.insert(key.clone(), value.clone());
577 }
578 }
579 for id in workload.bindings.keys() {
580 let key = crate::binding::binding_env_name(id);
581 let value = local.bindings.get(&key).ok_or_else(|| {
582 refuse(format!(
583 "the enforcer has no value for binding '{id}' ({key})"
584 ))
585 })?;
586 env.insert(key, value.clone());
587 }
588 for key in workload.deployer_env.keys() {
589 if let Some(value) = local.deployer_env.get(key) {
590 env.insert(key.clone(), value.clone());
591 }
592 }
593 let own_binding = crate::binding::binding_env_name(name);
594 for (key, value) in &request.env {
595 if workload.deployer_env.contains_key(key) {
598 continue;
599 }
600 if let Some(signed) = env.get(key) {
601 if !same_value(signed, value) {
602 return Err(refuse(format!(
603 "env {key} differs from its signed, configured or computed value"
604 )));
605 }
606 continue;
607 }
608 if workload.configurable_env.contains(key) {
609 return Err(refuse(format!(
610 "env {key} is configurable and only a signed config statement may set it"
611 )));
612 }
613 if *key == own_binding {
615 crate::binding::check_own_binding(value, &local.own_binding).map_err(|reason| {
616 refuse(format!(
617 "env {key} is the workload's own binding but {reason}"
618 ))
619 })?;
620 env.insert(key.clone(), value.clone());
621 continue;
622 }
623 if key == RUNTIME_SEND_OTLP {
625 if value != "true" && value != "false" {
626 return Err(refuse(format!(
627 "env {key} is a switch, true or false, not '{value}'"
628 )));
629 }
630 env.insert(key.clone(), value.clone());
631 continue;
632 }
633 if NEVER_FROM_REQUEST.contains(&key.as_str()) {
634 return Err(refuse(format!(
635 "env {key} is set by the runtime, not by the control plane"
636 )));
637 }
638 if is_loader_env(key) || !workload.provided_env.contains(key) {
639 return Err(refuse(format!("env {key} is not in the signed release")));
640 }
641 env.insert(key.clone(), value.clone());
642 }
643
644 for secret in &request.secrets {
645 let bound = workload.secrets.iter().any(|binding| {
646 binding.name == secret.name
647 && binding.env_name == secret.env_name
648 && binding.file_path == secret.file_path
649 });
650 if !bound {
651 return Err(refuse(format!(
652 "secret '{}' is not bound to this workload at that location",
653 secret.name
654 )));
655 }
656 }
657
658 if let (Some(cpu), Some(max)) = (&request.cpu, &workload.bounds.max_cpu) {
659 if parse_cpu_millis(cpu).map_err(refuse)? > parse_cpu_millis(max).map_err(refuse)? {
660 return Err(refuse(format!("cpu {cpu} is above the signed bound {max}")));
661 }
662 }
663 if let (Some(memory), Some(max)) = (&request.memory, &workload.bounds.max_memory) {
664 if parse_memory_bytes(memory).map_err(refuse)? > parse_memory_bytes(max).map_err(refuse)? {
665 return Err(refuse(format!(
666 "memory {memory} is above the signed bound {max}"
667 )));
668 }
669 }
670 if let (Some(replicas), Some(max)) = (request.replicas, workload.bounds.max_replicas) {
671 if replicas > max {
672 return Err(refuse(format!(
673 "{replicas} replicas is above the signed bound {max}"
674 )));
675 }
676 }
677
678 Ok(BuiltWorkload {
679 name: workload.name.clone(),
680 image: workload.image.clone(),
681 command: workload.command.clone(),
682 env,
683 runtime: workload.runtime.clone(),
684 volume_mount_path: workload.volume_mount_path.clone(),
685 identity: workload.identity.clone(),
686 })
687}
688
689fn same_value(expected: &str, actual: &str) -> bool {
693 if expected == actual {
694 return true;
695 }
696 match (
697 serde_json::from_str::<serde_json::Value>(expected),
698 serde_json::from_str::<serde_json::Value>(actual),
699 ) {
700 (Ok(left @ serde_json::Value::Object(_)), Ok(right)) => left == right,
701 _ => false,
702 }
703}
704
705pub fn is_pinned_image(image: &str) -> bool {
707 image
708 .rsplit_once('@')
709 .is_some_and(|(repository, digest)| !repository.is_empty() && is_sha256_digest(digest))
710}
711
712pub fn is_sha256_digest(digest: &str) -> bool {
714 digest.strip_prefix("sha256:").is_some_and(|hex_part| {
715 hex_part.len() == 64
716 && hex_part
717 .bytes()
718 .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
719 })
720}
721
722fn check_settable_name(name: &str) -> std::result::Result<(), String> {
723 if name.is_empty() || name.contains('=') || name.contains('\0') {
724 return Err(format!("'{name}' is not a valid environment variable name"));
725 }
726 if is_loader_env(name) {
727 return Err(format!(
728 "{name} changes how code loads and can only have a fixed value"
729 ));
730 }
731 if is_enforcer_env(name) {
732 return Err(format!(
733 "{name} is set by the enforcer from the signed release and can't be provided or configured"
734 ));
735 }
736 Ok(())
737}
738
739fn is_enforcer_env(name: &str) -> bool {
743 matches!(name, "ALIEN_SECRETS" | "WORKLOAD_SECRETS")
744 || name
745 .strip_prefix("ALIEN_")
746 .is_some_and(|rest| rest.len() > "_BINDING".len() && rest.ends_with("_BINDING"))
747}
748
749pub fn parse_cpu_millis(quantity: &str) -> std::result::Result<u64, String> {
751 let invalid = || format!("'{quantity}' is not a CPU quantity");
752 if let Some(millis) = quantity.strip_suffix('m') {
753 return millis.parse().map_err(|_| invalid());
754 }
755 let (whole, fraction) = quantity.split_once('.').unwrap_or((quantity, ""));
756 if fraction.len() > 3 || (whole.is_empty() && fraction.is_empty()) {
757 return Err(invalid());
758 }
759 let whole: u64 = if whole.is_empty() {
760 0
761 } else {
762 whole.parse().map_err(|_| invalid())?
763 };
764 let fraction: u64 = if fraction.is_empty() {
765 0
766 } else {
767 format!("{fraction:0<3}").parse().map_err(|_| invalid())?
768 };
769 whole
770 .checked_mul(1000)
771 .and_then(|millis| millis.checked_add(fraction))
772 .ok_or_else(invalid)
773}
774
775pub fn parse_memory_bytes(quantity: &str) -> std::result::Result<u64, String> {
778 let invalid = || format!("'{quantity}' is not a memory quantity");
779 const UNITS: &[(&str, u64)] = &[
780 ("Ki", 1 << 10),
781 ("Mi", 1 << 20),
782 ("Gi", 1 << 30),
783 ("Ti", 1 << 40),
784 ("K", 1_000),
785 ("M", 1_000_000),
786 ("G", 1_000_000_000),
787 ("T", 1_000_000_000_000),
788 ];
789 let (number, multiplier) = UNITS
790 .iter()
791 .find_map(|(suffix, multiplier)| {
792 quantity
793 .strip_suffix(suffix)
794 .map(|number| (number, *multiplier))
795 })
796 .unwrap_or((quantity, 1));
797 let number: u64 = number.parse().map_err(|_| invalid())?;
798 number.checked_mul(multiplier).ok_or_else(invalid)
799}
800
801fn body_refused(reason: String) -> AlienError<ErrorData> {
802 AlienError::new(ErrorData::BodyRefused {
803 kind: Kind::Release.as_str().to_string(),
804 reason,
805 })
806}
807
808fn workload_refused(workload: &str, reason: impl Into<String>) -> AlienError<ErrorData> {
809 AlienError::new(ErrorData::WorkloadRefused {
810 workload: workload.to_string(),
811 reason: reason.into(),
812 })
813}