use std::collections::{BTreeMap, BTreeSet};
use alien_error::AlienError;
use serde::{Deserialize, Serialize};
use crate::envelope::Kind;
use crate::error::{ErrorData, Result};
pub const LOADER_ENV: &[&str] = &[
"LD_PRELOAD",
"LD_LIBRARY_PATH",
"LD_AUDIT",
"LD_BIND_NOW",
"LD_DEBUG",
"LD_PROFILE",
"DYLD_INSERT_LIBRARIES",
"DYLD_LIBRARY_PATH",
"NODE_OPTIONS",
"NODE_PATH",
"NODE_EXTRA_CA_CERTS",
"NODE_TLS_REJECT_UNAUTHORIZED",
"PYTHONPATH",
"PYTHONHOME",
"PYTHONSTARTUP",
"PYTHONINSPECT",
"PYTHONUSERBASE",
"PYTHONWARNINGS",
"PERL5OPT",
"PERL5LIB",
"PERLLIB",
"RUBYOPT",
"RUBYLIB",
"JAVA_TOOL_OPTIONS",
"JDK_JAVA_OPTIONS",
"_JAVA_OPTIONS",
"CLASSPATH",
"DOTNET_STARTUP_HOOKS",
"CORECLR_ENABLE_PROFILING",
"CORECLR_PROFILER",
"CORECLR_PROFILER_PATH",
"BASH_ENV",
"ENV",
"PATH",
"GCONV_PATH",
"SSL_CERT_FILE",
"SSL_CERT_DIR",
"GIT_SSH_COMMAND",
"PHPRC",
"PHP_INI_SCAN_DIR",
"BUN_OPTIONS",
"DENO_DIR",
"GLIBC_TUNABLES",
"LOCPATH",
"NLSPATH",
"PYTHONBREAKPOINT",
"PYTHONEXECUTABLE",
"PYTHONPLATLIBDIR",
"PERL5DB",
"RUBYGEMS_GEMDEPS",
"NODE_REPL_EXTERNAL_MODULE",
"LUA_INIT",
"LUA_PATH",
"LUA_CPATH",
"DOTNET_ADDITIONAL_DEPS",
"DOTNET_SHARED_STORE",
"COR_ENABLE_PROFILING",
"COR_PROFILER",
"COR_PROFILER_PATH",
];
pub const LOADER_ENV_PREFIXES: &[&str] = &["LD_", "DYLD_", "BASH_FUNC_", "CORECLR_"];
const NEVER_FROM_REQUEST: &[&str] = &["ALIEN_WORKER_GRPC_ADDRESS", "ALIEN_PUBLIC_ENDPOINTS_JSON"];
pub const RUNTIME_SEND_OTLP: &str = "ALIEN_RUNTIME_SEND_OTLP";
pub fn is_loader_env(name: &str) -> bool {
LOADER_ENV.contains(&name)
|| LOADER_ENV_PREFIXES
.iter()
.any(|prefix| name.starts_with(prefix))
}
pub const COMPONENTS: &[&str] = &[
"machine-agent/linux-x86_64",
"machine-agent/linux-aarch64",
"operator",
];
pub const SETUP_TEMPLATES: &[&str] = &[
"cloudformation",
"terraform-aws",
"terraform-gcp",
"terraform-azure",
"helm",
];
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ReleaseBody {
pub platform: String,
pub channel: String,
pub workloads: Vec<Workload>,
#[serde(default)]
pub configurable: Configurable,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub components: BTreeMap<String, String>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub setup: BTreeMap<String, SetupTemplate>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub stack: Option<serde_json::Value>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SetupTemplate {
pub sha256: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub allowed: Vec<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Configurable {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub env: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub inputs: Vec<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum WorkloadKind {
Container,
Daemon,
Function,
Sandbox,
Build,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Workload {
pub name: String,
pub kind: WorkloadKind,
pub image: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub command: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub env: BTreeMap<String, String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub provided_env: Vec<String>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub bindings: BTreeMap<String, String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub configurable_env: Vec<String>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub deployer_env: BTreeMap<String, String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub secrets: Vec<SecretBinding>,
#[serde(default)]
pub runtime: Runtime,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub volume_mount_path: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub identity: Option<String>,
#[serde(default)]
pub bounds: Bounds,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub function: Option<FunctionSettings>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SecretBinding {
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub env_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub file_path: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Runtime {
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub privileged: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pid_namespace: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub network_mode: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub user: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub mounts: Vec<Mount>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub security: Option<Security>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub egress: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Mount {
pub source: String,
pub target: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub options: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Security {
pub profile: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub run_as_user: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub run_as_group: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub read_only_root_filesystem: Option<bool>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub writable_paths: Vec<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Bounds {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_cpu: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_memory: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_replicas: Option<u32>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct FunctionSettings {
pub memory_mb: u32,
pub timeout_seconds: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub architecture: Option<String>,
}
impl ReleaseBody {
pub fn live_resources(&self) -> BTreeSet<String> {
self.stack
.as_ref()
.and_then(|stack| stack.get("resources"))
.and_then(|resources| resources.as_object())
.into_iter()
.flatten()
.filter(|(_, entry)| entry["lifecycle"] == "live")
.map(|(id, _)| id.clone())
.collect()
}
pub fn validate(&self) -> Result<()> {
let mut names = BTreeSet::new();
for workload in &self.workloads {
if !names.insert(workload.name.as_str()) {
return Err(body_refused(format!(
"workload '{}' appears twice",
workload.name
)));
}
workload.validate()?;
for name in &workload.configurable_env {
if !self.configurable.env.contains(name) {
return Err(workload_refused(
&workload.name,
format!(
"configurable env '{name}' is not in the release's configurable env"
),
));
}
}
}
for name in &self.configurable.env {
check_settable_name(name).map_err(body_refused)?;
}
if self.channel.is_empty()
|| !self
.channel
.bytes()
.all(|byte| matches!(byte, b'a'..=b'z' | b'0'..=b'9' | b'-'))
{
return Err(body_refused(format!(
"channel '{}' is not [a-z0-9-]",
self.channel
)));
}
for (name, digest) in &self.components {
if !COMPONENTS.contains(&name.as_str()) {
return Err(body_refused(format!("'{name}' is not a component")));
}
if !is_sha256_digest(digest) {
return Err(body_refused(format!(
"'{name}' digest '{digest}' is not sha256:<hex>"
)));
}
}
for (name, template) in &self.setup {
if !SETUP_TEMPLATES.contains(&name.as_str()) {
return Err(body_refused(format!("'{name}' is not a setup template")));
}
if !is_sha256_digest(&template.sha256) {
return Err(body_refused(format!(
"setup '{name}' digest '{}' is not sha256:<hex>",
template.sha256
)));
}
}
Ok(())
}
pub fn workload(&self, name: &str) -> Result<&Workload> {
self.workloads
.iter()
.find(|workload| workload.name == name)
.ok_or_else(|| {
workload_refused(name, "the signed release has no workload by this name")
})
}
}
impl Workload {
fn validate(&self) -> Result<()> {
let refuse = |reason: String| workload_refused(&self.name, reason);
if self.name.is_empty() {
return Err(refuse("the name is empty".to_string()));
}
if !is_pinned_image(&self.image) {
return Err(refuse(format!(
"image '{}' is not pinned by sha256 digest",
self.image
)));
}
for name in self
.provided_env
.iter()
.chain(&self.configurable_env)
.chain(self.deployer_env.keys())
{
check_settable_name(name).map_err(refuse)?;
if self.env.contains_key(name) {
return Err(refuse(format!(
"'{name}' has a fixed value and can't also be provided or configured"
)));
}
}
for secret in &self.secrets {
if let Some(env_name) = &secret.env_name {
check_settable_name(env_name).map_err(refuse)?;
}
if let Some(path) = &secret.file_path {
if !path.starts_with('/') || path.split('/').any(|part| part == "..") {
return Err(refuse(format!(
"secret file path '{path}' is not absolute and plain"
)));
}
}
}
if let Some(max_cpu) = &self.bounds.max_cpu {
parse_cpu_millis(max_cpu).map_err(refuse)?;
}
if let Some(max_memory) = &self.bounds.max_memory {
parse_memory_bytes(max_memory).map_err(refuse)?;
}
for (id, resource_type) in &self.bindings {
if id.is_empty() || resource_type.is_empty() {
return Err(refuse("a binding needs a resource id and type".into()));
}
let name = crate::binding::binding_env_name(id);
if self.env.contains_key(&name) || self.provided_env.contains(&name) {
return Err(refuse(format!(
"{name} is a binding the enforcer computes; it can't also be fixed or provided"
)));
}
}
if (self.kind == WorkloadKind::Function) != self.function.is_some() {
return Err(refuse(
"function settings are required on functions and only on functions".into(),
));
}
Ok(())
}
}
#[derive(Debug, Clone, Default)]
pub struct WorkloadRequest {
pub env: BTreeMap<String, String>,
pub secrets: Vec<RequestedSecret>,
pub cpu: Option<String>,
pub memory: Option<String>,
pub replicas: Option<u32>,
}
#[derive(Debug, Clone, Default)]
pub struct LocalValues {
pub deployer_env: BTreeMap<String, String>,
pub bindings: BTreeMap<String, String>,
pub own_binding: crate::binding::OwnBindingFacts,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RequestedSecret {
pub name: String,
pub env_name: Option<String>,
pub file_path: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BuiltWorkload {
pub name: String,
pub image: String,
pub command: Option<Vec<String>>,
pub env: BTreeMap<String, String>,
pub runtime: Runtime,
pub volume_mount_path: Option<String>,
pub identity: Option<String>,
}
pub fn build_workload(
release: &ReleaseBody,
name: &str,
config_env: &BTreeMap<String, String>,
local: &LocalValues,
request: &WorkloadRequest,
) -> Result<BuiltWorkload> {
let workload = release.workload(name)?;
let refuse = |reason: String| workload_refused(name, reason);
let mut env = workload.env.clone();
for (key, value) in config_env {
if workload.configurable_env.contains(key) {
env.insert(key.clone(), value.clone());
}
}
for id in workload.bindings.keys() {
let key = crate::binding::binding_env_name(id);
let value = local.bindings.get(&key).ok_or_else(|| {
refuse(format!(
"the enforcer has no value for binding '{id}' ({key})"
))
})?;
env.insert(key, value.clone());
}
for key in workload.deployer_env.keys() {
if let Some(value) = local.deployer_env.get(key) {
env.insert(key.clone(), value.clone());
}
}
let own_binding = crate::binding::binding_env_name(name);
for (key, value) in &request.env {
if workload.deployer_env.contains_key(key) {
continue;
}
if let Some(signed) = env.get(key) {
if !same_value(signed, value) {
return Err(refuse(format!(
"env {key} differs from its signed, configured or computed value"
)));
}
continue;
}
if workload.configurable_env.contains(key) {
return Err(refuse(format!(
"env {key} is configurable and only a signed config statement may set it"
)));
}
if *key == own_binding {
crate::binding::check_own_binding(value, &local.own_binding).map_err(|reason| {
refuse(format!(
"env {key} is the workload's own binding but {reason}"
))
})?;
env.insert(key.clone(), value.clone());
continue;
}
if key == RUNTIME_SEND_OTLP {
if value != "true" && value != "false" {
return Err(refuse(format!(
"env {key} is a switch, true or false, not '{value}'"
)));
}
env.insert(key.clone(), value.clone());
continue;
}
if NEVER_FROM_REQUEST.contains(&key.as_str()) {
return Err(refuse(format!(
"env {key} is set by the runtime, not by the control plane"
)));
}
if is_loader_env(key) || !workload.provided_env.contains(key) {
return Err(refuse(format!("env {key} is not in the signed release")));
}
env.insert(key.clone(), value.clone());
}
for secret in &request.secrets {
let bound = workload.secrets.iter().any(|binding| {
binding.name == secret.name
&& binding.env_name == secret.env_name
&& binding.file_path == secret.file_path
});
if !bound {
return Err(refuse(format!(
"secret '{}' is not bound to this workload at that location",
secret.name
)));
}
}
if let (Some(cpu), Some(max)) = (&request.cpu, &workload.bounds.max_cpu) {
if parse_cpu_millis(cpu).map_err(refuse)? > parse_cpu_millis(max).map_err(refuse)? {
return Err(refuse(format!("cpu {cpu} is above the signed bound {max}")));
}
}
if let (Some(memory), Some(max)) = (&request.memory, &workload.bounds.max_memory) {
if parse_memory_bytes(memory).map_err(refuse)? > parse_memory_bytes(max).map_err(refuse)? {
return Err(refuse(format!(
"memory {memory} is above the signed bound {max}"
)));
}
}
if let (Some(replicas), Some(max)) = (request.replicas, workload.bounds.max_replicas) {
if replicas > max {
return Err(refuse(format!(
"{replicas} replicas is above the signed bound {max}"
)));
}
}
Ok(BuiltWorkload {
name: workload.name.clone(),
image: workload.image.clone(),
command: workload.command.clone(),
env,
runtime: workload.runtime.clone(),
volume_mount_path: workload.volume_mount_path.clone(),
identity: workload.identity.clone(),
})
}
fn same_value(expected: &str, actual: &str) -> bool {
if expected == actual {
return true;
}
match (
serde_json::from_str::<serde_json::Value>(expected),
serde_json::from_str::<serde_json::Value>(actual),
) {
(Ok(left @ serde_json::Value::Object(_)), Ok(right)) => left == right,
_ => false,
}
}
pub fn is_pinned_image(image: &str) -> bool {
image
.rsplit_once('@')
.is_some_and(|(repository, digest)| !repository.is_empty() && is_sha256_digest(digest))
}
pub fn is_sha256_digest(digest: &str) -> bool {
digest.strip_prefix("sha256:").is_some_and(|hex_part| {
hex_part.len() == 64
&& hex_part
.bytes()
.all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
})
}
fn check_settable_name(name: &str) -> std::result::Result<(), String> {
if name.is_empty() || name.contains('=') || name.contains('\0') {
return Err(format!("'{name}' is not a valid environment variable name"));
}
if is_loader_env(name) {
return Err(format!(
"{name} changes how code loads and can only have a fixed value"
));
}
if is_enforcer_env(name) {
return Err(format!(
"{name} is set by the enforcer from the signed release and can't be provided or configured"
));
}
Ok(())
}
fn is_enforcer_env(name: &str) -> bool {
matches!(name, "ALIEN_SECRETS" | "WORKLOAD_SECRETS")
|| name
.strip_prefix("ALIEN_")
.is_some_and(|rest| rest.len() > "_BINDING".len() && rest.ends_with("_BINDING"))
}
pub fn parse_cpu_millis(quantity: &str) -> std::result::Result<u64, String> {
let invalid = || format!("'{quantity}' is not a CPU quantity");
if let Some(millis) = quantity.strip_suffix('m') {
return millis.parse().map_err(|_| invalid());
}
let (whole, fraction) = quantity.split_once('.').unwrap_or((quantity, ""));
if fraction.len() > 3 || (whole.is_empty() && fraction.is_empty()) {
return Err(invalid());
}
let whole: u64 = if whole.is_empty() {
0
} else {
whole.parse().map_err(|_| invalid())?
};
let fraction: u64 = if fraction.is_empty() {
0
} else {
format!("{fraction:0<3}").parse().map_err(|_| invalid())?
};
whole
.checked_mul(1000)
.and_then(|millis| millis.checked_add(fraction))
.ok_or_else(invalid)
}
pub fn parse_memory_bytes(quantity: &str) -> std::result::Result<u64, String> {
let invalid = || format!("'{quantity}' is not a memory quantity");
const UNITS: &[(&str, u64)] = &[
("Ki", 1 << 10),
("Mi", 1 << 20),
("Gi", 1 << 30),
("Ti", 1 << 40),
("K", 1_000),
("M", 1_000_000),
("G", 1_000_000_000),
("T", 1_000_000_000_000),
];
let (number, multiplier) = UNITS
.iter()
.find_map(|(suffix, multiplier)| {
quantity
.strip_suffix(suffix)
.map(|number| (number, *multiplier))
})
.unwrap_or((quantity, 1));
let number: u64 = number.parse().map_err(|_| invalid())?;
number.checked_mul(multiplier).ok_or_else(invalid)
}
fn body_refused(reason: String) -> AlienError<ErrorData> {
AlienError::new(ErrorData::BodyRefused {
kind: Kind::Release.as_str().to_string(),
reason,
})
}
fn workload_refused(workload: &str, reason: impl Into<String>) -> AlienError<ErrorData> {
AlienError::new(ErrorData::WorkloadRefused {
workload: workload.to_string(),
reason: reason.into(),
})
}