Skip to main content

alien_signing/
release.rs

1//! `release/v2`: what a release may run, workload by workload, and how an
2//! enforcer builds a workload from it.
3//!
4//! The control plane still decides placement, replica counts within signed
5//! bounds, and the values of the few environment variables the release names
6//! exactly as provided. Everything that decides which code runs, how it is
7//! loaded and which resources it reaches comes from the signed body or from
8//! the enforcer itself: the image digest, the command, fixed environment
9//! values, runtime privileges, mounts, identity, and binding values the
10//! enforcer computes from its own install.
11
12use std::collections::{BTreeMap, BTreeSet};
13
14use alien_error::AlienError;
15use serde::{Deserialize, Serialize};
16
17use crate::envelope::Kind;
18use crate::error::{ErrorData, Result};
19
20/// Environment variables that change how a runtime loads code. They can only
21/// come from the release itself: no control-plane value, config statement or
22/// provided-name pattern may set them.
23pub 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
85/// Families of loader variables, by prefix: the dynamic linkers' and
86/// exported shell functions.
87pub const LOADER_ENV_PREFIXES: &[&str] = &["LD_", "DYLD_", "BASH_FUNC_", "CORECLR_"];
88
89/// Names a request never fills, whatever the signed release says: the address
90/// the worker runtime listens on, and the list of public URLs. Releases signed
91/// before these left the provided list may still name them.
92const NEVER_FROM_REQUEST: &[&str] = &["ALIEN_WORKER_GRPC_ADDRESS", "ALIEN_PUBLIC_ENDPOINTS_JSON"];
93
94/// Whether the workload's runtime ships telemetry: a switch the deployment sets, which can't say
95/// where the telemetry goes.
96pub const RUNTIME_SEND_OTLP: &str = "ALIEN_RUNTIME_SEND_OTLP";
97
98/// Whether `name` is a loader variable.
99pub 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
106/// Components whose builds a release pins. An enforcer runs only a build
107/// whose digest the release names. The verifier isn't one: setup pins it.
108pub const COMPONENTS: &[&str] = &[
109    "machine-agent/linux-x86_64",
110    "machine-agent/linux-aarch64",
111    "operator",
112];
113
114/// Setup templates a release can carry digests of.
115pub const SETUP_TEMPLATES: &[&str] = &[
116    "cloudformation",
117    "terraform-aws",
118    "terraform-gcp",
119    "terraform-azure",
120    "helm",
121];
122
123/// What one release lets run on one platform.
124#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
125#[serde(rename_all = "camelCase", deny_unknown_fields)]
126pub struct ReleaseBody {
127    /// Platform the release is for, such as `aws` or `machines`.
128    pub platform: String,
129    /// Release channel, such as `production`. An install accepts only the
130    /// channel its setup pinned.
131    pub channel: String,
132    /// Every workload, by name.
133    pub workloads: Vec<Workload>,
134    /// What `config/v1` statements may set.
135    #[serde(default)]
136    pub configurable: Configurable,
137    /// Digest of each enforcer build this release runs with, by name from
138    /// [`COMPONENTS`].
139    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
140    pub components: BTreeMap<String, String>,
141    /// Digests of the setup templates this release renders, by name from
142    /// [`SETUP_TEMPLATES`], so a customer can check what they install.
143    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
144    pub setup: BTreeMap<String, SetupTemplate>,
145    /// The full stack, for enforcers that deploy from it. It is signed with
146    /// the rest of the body, so it is as trusted as the workloads.
147    #[serde(default, skip_serializing_if = "Option::is_none")]
148    pub stack: Option<serde_json::Value>,
149}
150
151/// One setup template as the release rendered it.
152#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
153#[serde(rename_all = "camelCase", deny_unknown_fields)]
154pub struct SetupTemplate {
155    /// `sha256:<hex>` of the rendered template bytes.
156    pub sha256: String,
157    /// Parameters (or Helm values) the customer may choose. Every other
158    /// parameter must keep the template's pinned value.
159    #[serde(default, skip_serializing_if = "Vec::is_empty")]
160    pub allowed: Vec<String>,
161}
162
163/// Names config statements may set.
164#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
165#[serde(rename_all = "camelCase", deny_unknown_fields)]
166pub struct Configurable {
167    /// Environment variable names, applied to every workload that lists them
168    /// in its own `configurableEnv`.
169    #[serde(default, skip_serializing_if = "Vec::is_empty")]
170    pub env: Vec<String>,
171    /// Developer input ids.
172    #[serde(default, skip_serializing_if = "Vec::is_empty")]
173    pub inputs: Vec<String>,
174}
175
176/// What kind of compute a workload is.
177#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
178#[serde(rename_all = "camelCase")]
179pub enum WorkloadKind {
180    /// A long-running container.
181    Container,
182    /// One container per machine.
183    Daemon,
184    /// A serverless function.
185    Function,
186    /// A sandbox runtime.
187    Sandbox,
188    /// A build environment.
189    Build,
190}
191
192/// One workload, exactly as it may run.
193#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
194#[serde(rename_all = "camelCase", deny_unknown_fields)]
195pub struct Workload {
196    /// Workload name, unique in the release.
197    pub name: String,
198    /// What kind of compute it is.
199    pub kind: WorkloadKind,
200    /// `<repository>@sha256:<hex>`.
201    pub image: String,
202    /// Command overriding the image's, if any.
203    #[serde(default, skip_serializing_if = "Option::is_none")]
204    pub command: Option<Vec<String>>,
205    /// Fixed environment values.
206    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
207    pub env: BTreeMap<String, String>,
208    /// Exact environment names whose values the control plane provides.
209    #[serde(default, skip_serializing_if = "Vec::is_empty")]
210    pub provided_env: Vec<String>,
211    /// Resources the workload is bound to: resource id to resource type.
212    /// The enforcer computes each binding's value from its own install, so
213    /// the control plane can't point a binding at another resource.
214    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
215    pub bindings: BTreeMap<String, String>,
216    /// Environment names a config statement may set on this workload.
217    #[serde(default, skip_serializing_if = "Vec::is_empty")]
218    pub configurable_env: Vec<String>,
219    /// Environment names whose values come from deployer inputs, by input
220    /// id. The enforcer reads the values from the customer's own store; the
221    /// control plane never supplies them.
222    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
223    pub deployer_env: BTreeMap<String, String>,
224    /// Secrets the workload may receive, by name.
225    #[serde(default, skip_serializing_if = "Vec::is_empty")]
226    pub secrets: Vec<SecretBinding>,
227    /// Runtime privileges and mounts.
228    #[serde(default)]
229    pub runtime: Runtime,
230    /// Where the workload's persistent volume is mounted, if it has one.
231    #[serde(default, skip_serializing_if = "Option::is_none")]
232    pub volume_mount_path: Option<String>,
233    /// Permission profile the workload runs as, if any.
234    #[serde(default, skip_serializing_if = "Option::is_none")]
235    pub identity: Option<String>,
236    /// Upper bounds the control plane may scale within.
237    #[serde(default)]
238    pub bounds: Bounds,
239    /// Function settings, for `function` workloads.
240    #[serde(default, skip_serializing_if = "Option::is_none")]
241    pub function: Option<FunctionSettings>,
242}
243
244/// A secret the workload may receive. The value is not signed; the name and
245/// where it lands are.
246#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
247#[serde(rename_all = "camelCase", deny_unknown_fields)]
248pub struct SecretBinding {
249    /// Secret name.
250    pub name: String,
251    /// Environment variable that receives the value, if any.
252    #[serde(default, skip_serializing_if = "Option::is_none")]
253    pub env_name: Option<String>,
254    /// File the value is written to, if any.
255    #[serde(default, skip_serializing_if = "Option::is_none")]
256    pub file_path: Option<String>,
257}
258
259/// Runtime privileges. The defaults are the unprivileged ones.
260#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
261#[serde(rename_all = "camelCase", deny_unknown_fields)]
262pub struct Runtime {
263    /// Full host capabilities.
264    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
265    pub privileged: bool,
266    /// `host` to share the host PID namespace.
267    #[serde(default, skip_serializing_if = "Option::is_none")]
268    pub pid_namespace: Option<String>,
269    /// `host` to share the host network namespace.
270    #[serde(default, skip_serializing_if = "Option::is_none")]
271    pub network_mode: Option<String>,
272    /// `uid[:gid]` to run as.
273    #[serde(default, skip_serializing_if = "Option::is_none")]
274    pub user: Option<String>,
275    /// Host bind mounts.
276    #[serde(default, skip_serializing_if = "Vec::is_empty")]
277    pub mounts: Vec<Mount>,
278    /// Hardened execution settings.
279    #[serde(default, skip_serializing_if = "Option::is_none")]
280    pub security: Option<Security>,
281    /// `internet` for public-internet-only egress.
282    #[serde(default, skip_serializing_if = "Option::is_none")]
283    pub egress: Option<String>,
284}
285
286/// A host bind mount.
287#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
288#[serde(rename_all = "camelCase", deny_unknown_fields)]
289pub struct Mount {
290    /// Host path.
291    pub source: String,
292    /// Path in the container.
293    pub target: String,
294    /// Mount options such as `ro`.
295    #[serde(default, skip_serializing_if = "Option::is_none")]
296    pub options: Option<String>,
297}
298
299/// Hardened execution settings.
300#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
301#[serde(rename_all = "camelCase", deny_unknown_fields)]
302pub struct Security {
303    /// `restricted`, `restrictedInternet`, or `unrestricted` (the workload's opt-out).
304    pub profile: String,
305    /// User id; absent means the image's own non-root user.
306    #[serde(default, skip_serializing_if = "Option::is_none")]
307    pub run_as_user: Option<i64>,
308    /// Group id; absent means the image's own group.
309    #[serde(default, skip_serializing_if = "Option::is_none")]
310    pub run_as_group: Option<i64>,
311    /// Whether the root filesystem is read-only; absent means the profile's default.
312    #[serde(default, skip_serializing_if = "Option::is_none")]
313    pub read_only_root_filesystem: Option<bool>,
314    /// Absolute paths backed by a writable emptyDir.
315    #[serde(default, skip_serializing_if = "Vec::is_empty")]
316    pub writable_paths: Vec<String>,
317}
318
319/// Upper bounds on what the control plane may request.
320#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
321#[serde(rename_all = "camelCase", deny_unknown_fields)]
322pub struct Bounds {
323    /// Most CPU per replica, as a quantity such as `2` or `500m`.
324    #[serde(default, skip_serializing_if = "Option::is_none")]
325    pub max_cpu: Option<String>,
326    /// Most memory per replica, as a quantity such as `512Mi`.
327    #[serde(default, skip_serializing_if = "Option::is_none")]
328    pub max_memory: Option<String>,
329    /// Most replicas.
330    #[serde(default, skip_serializing_if = "Option::is_none")]
331    pub max_replicas: Option<u32>,
332}
333
334/// Settings of a serverless function that change what runs.
335#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
336#[serde(rename_all = "camelCase", deny_unknown_fields)]
337pub struct FunctionSettings {
338    /// Memory in MiB.
339    pub memory_mb: u32,
340    /// Timeout in seconds.
341    pub timeout_seconds: u32,
342    /// CPU architecture, such as `arm64`.
343    #[serde(default, skip_serializing_if = "Option::is_none")]
344    pub architecture: Option<String>,
345}
346
347impl ReleaseBody {
348    /// The ids of the signed stack's Live resources, whose names their controllers choose.
349    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    /// Check the rules a release must follow before any of it is used.
362    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    /// The workload named `name`.
422    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/// What the control plane supplies when it asks an enforcer to run one
496/// replica of a workload. Nothing here can change the code that runs.
497#[derive(Debug, Clone, Default)]
498pub struct WorkloadRequest {
499    /// The full environment the control plane computed. Signed names must
500    /// carry their signed value; other names must be provided or configured.
501    pub env: BTreeMap<String, String>,
502    /// Secrets the control plane delivers, by name, with where they land.
503    pub secrets: Vec<RequestedSecret>,
504    /// CPU per replica.
505    pub cpu: Option<String>,
506    /// Memory per replica.
507    pub memory: Option<String>,
508    /// Replica count the control plane wants.
509    pub replicas: Option<u32>,
510}
511
512/// Values the enforcer reads or computes itself, never from the control
513/// plane.
514#[derive(Debug, Clone, Default)]
515pub struct LocalValues {
516    /// The env the release's deployer inputs resolve to for this workload, by env name: the
517    /// customer's stored value or the signed default. A name left out here is a variable the
518    /// install does not set (an optional input with neither, or one whose `when` is off).
519    pub deployer_env: BTreeMap<String, String>,
520    /// Binding values, by environment name, from [`crate::resolve_bindings`].
521    pub bindings: BTreeMap<String, String>,
522    /// What the workload's own binding is checked against.
523    pub own_binding: crate::binding::OwnBindingFacts,
524}
525
526/// A secret delivery the control plane asks for.
527#[derive(Debug, Clone, PartialEq, Eq)]
528pub struct RequestedSecret {
529    /// Secret name.
530    pub name: String,
531    /// Environment variable that receives it.
532    pub env_name: Option<String>,
533    /// File it is written to.
534    pub file_path: Option<String>,
535}
536
537/// A workload built from its signed release.
538#[derive(Debug, Clone, PartialEq, Eq)]
539pub struct BuiltWorkload {
540    /// Workload name.
541    pub name: String,
542    /// The signed image.
543    pub image: String,
544    /// The signed command.
545    pub command: Option<Vec<String>>,
546    /// Signed values, then configured values, then provided values.
547    pub env: BTreeMap<String, String>,
548    /// The signed runtime.
549    pub runtime: Runtime,
550    /// The signed volume mount path.
551    pub volume_mount_path: Option<String>,
552    /// The signed permission profile.
553    pub identity: Option<String>,
554}
555
556/// Build workload `name` from a verified release, applying config values
557/// from a verified `config/v1`, the values the enforcer computed itself, and
558/// the values the control plane provides.
559///
560/// A request that tries to change a signed or computed value, set a name the
561/// release doesn't let it set, deliver an unbound secret or go past a bound
562/// is refused, so the attempt is reported rather than silently dropped.
563pub 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        // Deployer inputs come from the customer's store; whatever the
596        // control plane sends for them is ignored.
597        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        // The workload's own binding only describes the workload to itself.
614        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        // Whether the runtime ships telemetry at all; where it goes is never the request's.
624        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
689/// Whether two values of one variable are the same. Binding values are JSON
690/// whose key order the control plane may not keep, so JSON objects compare
691/// by content.
692fn 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
705/// Whether `image` is `<repository>@sha256:<64 hex>`.
706pub 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
712/// Whether `digest` is `sha256:<64 lowercase hex>`.
713pub 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
739/// Names the enforcer fills itself: the vault secrets list and binding values.
740/// A control plane that could set them would pick which vault keys load or
741/// where a binding points.
742fn 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
749/// CPU quantity in millicores: `2`, `0.5` or `500m`.
750pub 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
775/// Memory quantity in bytes: a number with an optional `Ki`/`Mi`/`Gi`/`Ti`
776/// or `K`/`M`/`G`/`T` suffix.
777pub 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}