Skip to main content

alien_core/
runtime_environment.rs

1use crate::{bindings::binding_env_var_name, ErrorData, Platform, ResourceRef, Result};
2use alien_error::AlienError;
3use std::collections::HashMap;
4
5pub const ENV_ALIEN_CURRENT_WORKER_BINDING_NAME: &str = "ALIEN_CURRENT_WORKER_BINDING_NAME";
6pub const ENV_ALIEN_CURRENT_CONTAINER_BINDING_NAME: &str = "ALIEN_CURRENT_CONTAINER_BINDING_NAME";
7pub const ENV_OPERATOR_BASE_PLATFORM: &str = "OPERATOR_BASE_PLATFORM";
8/// Where application pods reach the Kubernetes sandbox session broker. The Helm chart sets it
9/// on the operator from the Service it renders in front of the operator, which serves the
10/// broker; the Sandbox controller publishes it in the sandbox binding.
11pub const ENV_ALIEN_SANDBOX_BROKER_URL: &str = "ALIEN_SANDBOX_BROKER_URL";
12/// The nameserver addresses (comma separated IPv4) the chart admits on port 53 for sandbox pods,
13/// from `sandbox.clusterDNS`; the chart admits only these on port 53 for allow-egress sandbox
14/// pods. The Operator compares them with its own `/etc/resolv.conf` and refuses new
15/// allow-egress sessions when they differ (running sessions stay).
16pub const ENV_ALIEN_SANDBOX_CLUSTER_DNS: &str = "ALIEN_SANDBOX_CLUSTER_DNS";
17/// RuntimeClass the chart chose for sandbox pods (`sandbox.runtimeClassName`, or the cluster's
18/// vendor class when unset). The Operator only checks it; it never picks one.
19/// `ip:port` the policy must refuse, which is how a pod proves its policy is in force. Set by a
20/// chart that predates [`ENV_ALIEN_SANDBOX_OPERATOR_SERVICE`] (it held the Operator pod's address);
21/// used only when the Service variable is absent.
22pub const ENV_ALIEN_SANDBOX_OPERATOR_ADDRESS: &str = "ALIEN_SANDBOX_OPERATOR_ADDRESS";
23/// `name:port` of the Operator's own Service, set by the chart. The Operator resolves it to the
24/// Service's `ClusterIP:port` and uses that as the policy canary: a ClusterIP stays fixed while
25/// the Service exists, where the Operator's pod address changes whenever the pod is rescheduled.
26pub const ENV_ALIEN_SANDBOX_OPERATOR_SERVICE: &str = "ALIEN_SANDBOX_OPERATOR_SERVICE";
27pub const ENV_ALIEN_SANDBOX_RUNTIME_CLASS: &str = "ALIEN_SANDBOX_RUNTIME_CLASS";
28/// Namespace the administrator made for sandbox pods (`sandbox.namespace`). Unset means the
29/// release namespace, where sandbox pods have always run. The chart never creates it.
30pub const ENV_ALIEN_SANDBOX_NAMESPACE: &str = "ALIEN_SANDBOX_NAMESPACE";
31/// Idle sandbox pods the Operator keeps ready (`sandbox.warmPoolSize`).
32pub const ENV_ALIEN_SANDBOX_WARM_POOL_SIZE: &str = "ALIEN_SANDBOX_WARM_POOL_SIZE";
33/// JSON object of node labels sandbox pods must match (`sandbox.nodeSelector`).
34pub const ENV_ALIEN_SANDBOX_NODE_SELECTOR: &str = "ALIEN_SANDBOX_NODE_SELECTOR";
35/// Set by the Kubernetes operator on root-boot pods: the egress limit is enforced outside the pod
36/// (NetworkPolicy and the gateway), so the agent skips in-pod firewall setup. Agent-read only.
37pub const ENV_ALIEN_SANDBOX_NETWORK_ENFORCER: &str = "ALIEN_SANDBOX_NETWORK_ENFORCER";
38/// JSON array of tolerations for sandbox pods (`sandbox.tolerations`).
39pub const ENV_ALIEN_SANDBOX_TOLERATIONS: &str = "ALIEN_SANDBOX_TOLERATIONS";
40/// JSON object mapping workload priority levels (`critical`, `high`, `normal`, `low`) to
41/// Kubernetes PriorityClass names. The Helm chart sets it on the operator only when the
42/// cluster administrator mapped at least one level.
43pub const ENV_ALIEN_KUBERNETES_PRIORITY_CLASSES: &str = "ALIEN_KUBERNETES_PRIORITY_CLASSES";
44pub const ENV_ALIEN_DEPLOYMENT_TYPE: &str = "ALIEN_DEPLOYMENT_TYPE";
45pub const ENV_ALIEN_LAMBDA_MODE: &str = "ALIEN_LAMBDA_MODE";
46pub const ENV_ALIEN_RUNTIME_SEND_OTLP: &str = "ALIEN_RUNTIME_SEND_OTLP";
47pub const ENV_ALIEN_RUNTIME_SECRETS: &str = "ALIEN_RUNTIME_SECRETS";
48pub const ENV_ALIEN_SECRETS: &str = "ALIEN_SECRETS";
49/// Opaque deployment-managed revision that rolls workloads when referenced
50/// secret values change without exposing secret-derived data in the spec.
51pub const ENV_ALIEN_SECRET_ENV_REVISION: &str = "ALIEN_SECRET_ENV_REVISION";
52pub const ENV_ALIEN_TRANSPORT: &str = "ALIEN_TRANSPORT";
53pub const ENV_ALIEN_DEPLOYMENT_ID: &str = "ALIEN_DEPLOYMENT_ID";
54pub const ENV_ALIEN_DEPLOYMENT_NAME: &str = "ALIEN_DEPLOYMENT_NAME";
55/// Identifies the current app resource within its deployment stack. Unlike
56/// command-specific target variables, this is the universal resource identity
57/// name.
58pub const ENV_ALIEN_RESOURCE_ID: &str = "ALIEN_RESOURCE_ID";
59pub const ENV_ALIEN_PUBLIC_ENDPOINTS_JSON: &str = "ALIEN_PUBLIC_ENDPOINTS_JSON";
60pub const ENV_ALIEN_COMMANDS_TOKEN: &str = "ALIEN_COMMANDS_TOKEN";
61/// File containing the command receiver bearer token. Receivers re-read this
62/// file after an unauthorized response so controllers can rotate credentials
63/// without restarting the workload.
64pub const ENV_ALIEN_COMMANDS_TOKEN_FILE: &str = "ALIEN_COMMANDS_TOKEN_FILE";
65/// File holding a short-lived command credential as `{"token","expiresAt"}`,
66/// written and refreshed by the host or operator that runs the workload.
67pub const ENV_ALIEN_COMMANDS_CAPABILITY_FILE: &str = "ALIEN_COMMANDS_CAPABILITY_FILE";
68/// Where a Container or Daemon on a machine with a runtime identity finds its
69/// command credential (`ALIEN_COMMANDS_CAPABILITY_FILE`). The machine writes it.
70pub const HOST_COMMANDS_CAPABILITY_FILE: &str = "/var/run/alien-runtime/commands.json";
71/// The same credential as plain text (`ALIEN_COMMANDS_TOKEN_FILE`), for
72/// receivers that read only a token file.
73pub const HOST_COMMANDS_TOKEN_FILE: &str = "/var/run/alien-runtime/commands.token";
74/// Lease duration requested by app-owned command receivers, in seconds.
75pub const ENV_ALIEN_COMMANDS_LEASE_SECONDS: &str = "ALIEN_COMMANDS_LEASE_SECONDS";
76/// Maximum command leases requested by an app-owned receiver per poll.
77pub const ENV_ALIEN_COMMANDS_MAX_LEASES: &str = "ALIEN_COMMANDS_MAX_LEASES";
78/// Base command receiver poll interval, in milliseconds.
79pub const ENV_ALIEN_COMMANDS_POLL_INTERVAL_MS: &str = "ALIEN_COMMANDS_POLL_INTERVAL_MS";
80/// Maximum command receiver poll interval after adaptive backoff, in milliseconds.
81pub const ENV_ALIEN_COMMANDS_POLL_MAX_INTERVAL_MS: &str = "ALIEN_COMMANDS_POLL_MAX_INTERVAL_MS";
82/// Fractional jitter applied to command receiver poll intervals.
83pub const ENV_ALIEN_COMMANDS_POLL_JITTER: &str = "ALIEN_COMMANDS_POLL_JITTER";
84/// Graceful command receiver drain timeout, in milliseconds.
85pub const ENV_ALIEN_COMMANDS_DRAIN_TIMEOUT_MS: &str = "ALIEN_COMMANDS_DRAIN_TIMEOUT_MS";
86/// Identifies which stack resource an app-owned command receiver leases for.
87pub const ENV_ALIEN_COMMANDS_TARGET_RESOURCE_ID: &str = "ALIEN_COMMANDS_TARGET_RESOURCE_ID";
88/// Base URL of the command server API an app-owned pull `Receiver`
89/// (Container/Daemon) leases commands from. Pinned by the receiver contract;
90/// the TypeScript receiver reads the same variable. Missing or
91/// invalid values fail fast with `COMMAND_RECEIVER_CONFIG_INVALID`. Injected
92/// by the manager and operator controllers, scoped per command-enabled
93/// resource.
94pub const ENV_ALIEN_COMMANDS_URL: &str = "ALIEN_COMMANDS_URL";
95/// Type of the command target a pull `Receiver` leases for (`container` |
96/// `daemon`). Lease requests require a typed target and a receiver must not
97/// guess it (the worker runtime hardcodes `worker`; a Container/Daemon
98/// receiver gets its type injected). Companion to
99/// [`ENV_ALIEN_COMMANDS_TARGET_RESOURCE_ID`].
100pub const ENV_ALIEN_COMMANDS_TARGET_RESOURCE_TYPE: &str = "ALIEN_COMMANDS_TARGET_RESOURCE_TYPE";
101/// Base URL of the deployment's manager.
102pub const ENV_ALIEN_MANAGER_URL: &str = "ALIEN_MANAGER_URL";
103/// Deployment bearer token, distinct from command delivery tokens.
104pub const ENV_ALIEN_DEPLOYMENT_TOKEN: &str = "ALIEN_DEPLOYMENT_TOKEN";
105/// Address of the worker app protocol gRPC server. The runtime binds its
106/// Control + WaitUntil services here and injects the same value for the
107/// application it spawns; the app connects as the gRPC client. Presence of this
108/// variable is what selects the worker-protocol gRPC channel in the app SDK.
109pub const ENV_ALIEN_WORKER_GRPC_ADDRESS: &str = "ALIEN_WORKER_GRPC_ADDRESS";
110/// JSON batch limits keyed by logical queue resource ID.
111pub const ENV_ALIEN_QUEUE_BATCH_CONFIG: &str = "ALIEN_QUEUE_BATCH_CONFIG";
112
113/// Configured maximum Worker execution time in seconds, injected from the trusted resource.
114pub const ENV_ALIEN_WORKER_TIMEOUT_SECONDS: &str = "ALIEN_WORKER_TIMEOUT_SECONDS";
115pub const ENV_AWS_ACCOUNT_ID: &str = "AWS_ACCOUNT_ID";
116pub const ENV_AWS_REGION: &str = "AWS_REGION";
117pub const ENV_AZURE_CLIENT_ID: &str = "AZURE_CLIENT_ID";
118pub const ENV_AZURE_REGION: &str = "AZURE_REGION";
119pub const ENV_AZURE_SUBSCRIPTION_ID: &str = "AZURE_SUBSCRIPTION_ID";
120pub const ENV_AZURE_TENANT_ID: &str = "AZURE_TENANT_ID";
121pub const ENV_GCP_PROJECT_ID: &str = "GCP_PROJECT_ID";
122pub const ENV_GCP_REGION: &str = "GCP_REGION";
123pub const ENV_GOOGLE_CLOUD_PROJECT: &str = "GOOGLE_CLOUD_PROJECT";
124
125#[derive(Debug, Clone, Copy, PartialEq, Eq)]
126pub enum RuntimeEnvironmentValue {
127    Literal(&'static str),
128    AwsAccountId,
129    AwsRegion,
130    AzureClientId,
131    AzureRegion,
132    AzureSubscriptionId,
133    AzureTenantId,
134    BasePlatform,
135    CurrentContainerBindingName,
136    CurrentWorkerBindingName,
137    GcpProjectId,
138    GcpRegion,
139}
140
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142pub struct RuntimeEnvironmentEntry {
143    pub name: &'static str,
144    pub value: RuntimeEnvironmentValue,
145}
146
147#[derive(Debug, Clone, PartialEq, Eq)]
148pub enum RuntimeEnvironmentBindingSource {
149    LinkedResource(ResourceRef),
150    CurrentContainer,
151    CurrentWorker,
152}
153
154#[derive(Debug, Clone, PartialEq, Eq)]
155pub struct RuntimeEnvironmentBindingEntry {
156    pub env_name: String,
157    pub binding_name: String,
158    pub source: RuntimeEnvironmentBindingSource,
159}
160
161#[derive(Debug, Clone, PartialEq, Eq)]
162pub enum RuntimeEnvironmentPlanEntry {
163    Scalar(RuntimeEnvironmentEntry),
164    Binding(RuntimeEnvironmentBindingEntry),
165}
166
167#[derive(Debug, Clone, Default, PartialEq, Eq)]
168pub struct RuntimeEnvironmentPlan {
169    entries: Vec<RuntimeEnvironmentPlanEntry>,
170}
171
172impl RuntimeEnvironmentPlan {
173    pub fn new() -> Self {
174        Self::default()
175    }
176
177    pub fn add_scalar_entries(
178        mut self,
179        entries: impl IntoIterator<Item = RuntimeEnvironmentEntry>,
180    ) -> Self {
181        self.entries
182            .extend(entries.into_iter().map(RuntimeEnvironmentPlanEntry::Scalar));
183        self
184    }
185
186    pub fn add_linked_bindings(mut self, links: &[ResourceRef]) -> Self {
187        self.entries.extend(links.iter().cloned().map(|link| {
188            let binding_name = link.id().to_string();
189            RuntimeEnvironmentPlanEntry::Binding(RuntimeEnvironmentBindingEntry {
190                env_name: binding_env_var_name(&binding_name),
191                binding_name,
192                source: RuntimeEnvironmentBindingSource::LinkedResource(link),
193            })
194        }));
195        self
196    }
197
198    pub fn add_current_worker_binding(mut self, worker_id: &str) -> Self {
199        self.entries.push(RuntimeEnvironmentPlanEntry::Binding(
200            RuntimeEnvironmentBindingEntry {
201                env_name: binding_env_var_name(worker_id),
202                binding_name: worker_id.to_string(),
203                source: RuntimeEnvironmentBindingSource::CurrentWorker,
204            },
205        ));
206        self
207    }
208
209    pub fn add_current_container_binding(mut self, container_id: &str) -> Self {
210        self.entries.push(RuntimeEnvironmentPlanEntry::Binding(
211            RuntimeEnvironmentBindingEntry {
212                env_name: binding_env_var_name(container_id),
213                binding_name: container_id.to_string(),
214                source: RuntimeEnvironmentBindingSource::CurrentContainer,
215            },
216        ));
217        self
218    }
219
220    pub fn entries(&self) -> &[RuntimeEnvironmentPlanEntry] {
221        &self.entries
222    }
223}
224
225pub trait RuntimeEnvironmentRenderer {
226    type Value;
227
228    fn render_runtime_environment_value(
229        &self,
230        value: RuntimeEnvironmentValue,
231    ) -> Result<Option<Self::Value>>;
232
233    fn render_runtime_environment_binding(
234        &self,
235        entry: &RuntimeEnvironmentBindingEntry,
236    ) -> Result<Option<Self::Value>>;
237}
238
239pub fn standard_runtime_environment_plan(platform: Platform) -> Vec<RuntimeEnvironmentEntry> {
240    let mut entries = vec![RuntimeEnvironmentEntry {
241        name: ENV_ALIEN_DEPLOYMENT_TYPE,
242        value: RuntimeEnvironmentValue::Literal(platform.as_str()),
243    }];
244
245    match platform {
246        Platform::Aws => entries.push(RuntimeEnvironmentEntry {
247            name: ENV_AWS_ACCOUNT_ID,
248            value: RuntimeEnvironmentValue::AwsAccountId,
249        }),
250        Platform::Gcp => entries.extend([
251            RuntimeEnvironmentEntry {
252                name: ENV_GOOGLE_CLOUD_PROJECT,
253                value: RuntimeEnvironmentValue::GcpProjectId,
254            },
255            RuntimeEnvironmentEntry {
256                name: ENV_GCP_PROJECT_ID,
257                value: RuntimeEnvironmentValue::GcpProjectId,
258            },
259            RuntimeEnvironmentEntry {
260                name: ENV_GCP_REGION,
261                value: RuntimeEnvironmentValue::GcpRegion,
262            },
263        ]),
264        Platform::Azure => entries.extend([
265            RuntimeEnvironmentEntry {
266                name: ENV_AZURE_SUBSCRIPTION_ID,
267                value: RuntimeEnvironmentValue::AzureSubscriptionId,
268            },
269            RuntimeEnvironmentEntry {
270                name: ENV_AZURE_TENANT_ID,
271                value: RuntimeEnvironmentValue::AzureTenantId,
272            },
273            RuntimeEnvironmentEntry {
274                name: ENV_AZURE_REGION,
275                value: RuntimeEnvironmentValue::AzureRegion,
276            },
277        ]),
278        Platform::Kubernetes => entries.push(RuntimeEnvironmentEntry {
279            name: ENV_OPERATOR_BASE_PLATFORM,
280            value: RuntimeEnvironmentValue::BasePlatform,
281        }),
282        Platform::Machines | Platform::Local | Platform::Test => {}
283    }
284
285    entries
286}
287
288pub fn kubernetes_base_platform_runtime_environment_plan(
289    base_platform: Option<Platform>,
290) -> Vec<RuntimeEnvironmentEntry> {
291    match base_platform {
292        Some(Platform::Aws) => vec![
293            RuntimeEnvironmentEntry {
294                name: ENV_AWS_ACCOUNT_ID,
295                value: RuntimeEnvironmentValue::AwsAccountId,
296            },
297            RuntimeEnvironmentEntry {
298                name: ENV_AWS_REGION,
299                value: RuntimeEnvironmentValue::AwsRegion,
300            },
301        ],
302        Some(Platform::Gcp) => vec![
303            RuntimeEnvironmentEntry {
304                name: ENV_GOOGLE_CLOUD_PROJECT,
305                value: RuntimeEnvironmentValue::GcpProjectId,
306            },
307            RuntimeEnvironmentEntry {
308                name: ENV_GCP_PROJECT_ID,
309                value: RuntimeEnvironmentValue::GcpProjectId,
310            },
311            RuntimeEnvironmentEntry {
312                name: ENV_GCP_REGION,
313                value: RuntimeEnvironmentValue::GcpRegion,
314            },
315        ],
316        Some(Platform::Azure) => vec![
317            RuntimeEnvironmentEntry {
318                name: ENV_AZURE_SUBSCRIPTION_ID,
319                value: RuntimeEnvironmentValue::AzureSubscriptionId,
320            },
321            RuntimeEnvironmentEntry {
322                name: ENV_AZURE_TENANT_ID,
323                value: RuntimeEnvironmentValue::AzureTenantId,
324            },
325            RuntimeEnvironmentEntry {
326                name: ENV_AZURE_REGION,
327                value: RuntimeEnvironmentValue::AzureRegion,
328            },
329            RuntimeEnvironmentEntry {
330                name: ENV_AZURE_CLIENT_ID,
331                value: RuntimeEnvironmentValue::AzureClientId,
332            },
333        ],
334        _ => Vec::new(),
335    }
336}
337
338pub fn worker_transport_runtime_environment_plan(
339    platform: Platform,
340) -> Vec<RuntimeEnvironmentEntry> {
341    match platform {
342        Platform::Aws => vec![
343            RuntimeEnvironmentEntry {
344                name: ENV_ALIEN_TRANSPORT,
345                value: RuntimeEnvironmentValue::Literal("lambda"),
346            },
347            RuntimeEnvironmentEntry {
348                name: ENV_ALIEN_LAMBDA_MODE,
349                value: RuntimeEnvironmentValue::Literal("buffered"),
350            },
351        ],
352        Platform::Gcp => vec![RuntimeEnvironmentEntry {
353            name: ENV_ALIEN_TRANSPORT,
354            value: RuntimeEnvironmentValue::Literal("cloud-run"),
355        }],
356        Platform::Azure => vec![RuntimeEnvironmentEntry {
357            name: ENV_ALIEN_TRANSPORT,
358            value: RuntimeEnvironmentValue::Literal("container-app"),
359        }],
360        Platform::Kubernetes | Platform::Machines => vec![RuntimeEnvironmentEntry {
361            name: ENV_ALIEN_TRANSPORT,
362            value: RuntimeEnvironmentValue::Literal("http"),
363        }],
364        Platform::Local | Platform::Test => vec![RuntimeEnvironmentEntry {
365            name: ENV_ALIEN_TRANSPORT,
366            // Local/Test Workers run under the runtime's `local` transport (the
367            // in-process HTTP invocation proxy the worker manager selects via
368            // `TransportType::Local`). The env-plan value now matches that reality,
369            // so `ALIEN_TRANSPORT` for Workers is exactly the transport set
370            // `lambda | cloud-run | container-app | http | local`.
371            value: RuntimeEnvironmentValue::Literal("local"),
372        }],
373    }
374}
375
376pub fn worker_runtime_environment_plan(platform: Platform) -> Vec<RuntimeEnvironmentEntry> {
377    let mut entries = standard_runtime_environment_plan(platform);
378    entries.extend(worker_transport_runtime_environment_plan(platform));
379    entries.push(RuntimeEnvironmentEntry {
380        name: ENV_ALIEN_RUNTIME_SEND_OTLP,
381        value: RuntimeEnvironmentValue::Literal("true"),
382    });
383    entries.push(RuntimeEnvironmentEntry {
384        name: ENV_ALIEN_CURRENT_WORKER_BINDING_NAME,
385        value: RuntimeEnvironmentValue::CurrentWorkerBindingName,
386    });
387    if platform == Platform::Azure {
388        entries.push(RuntimeEnvironmentEntry {
389            name: ENV_AZURE_CLIENT_ID,
390            value: RuntimeEnvironmentValue::AzureClientId,
391        });
392    }
393    entries
394}
395
396pub fn worker_runtime_environment_contract(
397    platform: Platform,
398    worker_id: &str,
399    links: &[ResourceRef],
400) -> RuntimeEnvironmentPlan {
401    RuntimeEnvironmentPlan::new()
402        .add_scalar_entries(worker_runtime_environment_plan(platform))
403        .add_linked_bindings(links)
404        .add_current_worker_binding(worker_id)
405}
406
407pub fn container_runtime_environment_plan(platform: Platform) -> Vec<RuntimeEnvironmentEntry> {
408    let mut entries = standard_runtime_environment_plan(platform);
409    // `ALIEN_TRANSPORT` is Worker-only. Command-enabled Containers run the pull
410    // receiver configured per resource through the `ALIEN_COMMANDS_*` contract.
411    entries.push(RuntimeEnvironmentEntry {
412        name: ENV_ALIEN_CURRENT_CONTAINER_BINDING_NAME,
413        value: RuntimeEnvironmentValue::CurrentContainerBindingName,
414    });
415    entries
416}
417
418pub fn container_runtime_environment_contract(
419    platform: Platform,
420    container_id: &str,
421    links: &[ResourceRef],
422) -> RuntimeEnvironmentPlan {
423    RuntimeEnvironmentPlan::new()
424        .add_scalar_entries(container_runtime_environment_plan(platform))
425        .add_linked_bindings(links)
426        .add_current_container_binding(container_id)
427}
428
429pub fn daemon_runtime_environment_plan(platform: Platform) -> Vec<RuntimeEnvironmentEntry> {
430    // Daemons run under direct supervision and receive only the standard
431    // platform-identity vars. `ALIEN_TRANSPORT` and the container self-binding
432    // var are not part of the Daemon contract. Command-enabled Daemons get their
433    // `ALIEN_COMMANDS_*` receiver config from the resource controller.
434    standard_runtime_environment_plan(platform)
435}
436
437pub fn daemon_runtime_environment_contract(
438    platform: Platform,
439    links: &[ResourceRef],
440) -> RuntimeEnvironmentPlan {
441    RuntimeEnvironmentPlan::new()
442        .add_scalar_entries(daemon_runtime_environment_plan(platform))
443        .add_linked_bindings(links)
444}
445
446pub fn render_runtime_environment_entries<R>(
447    entries: impl IntoIterator<Item = RuntimeEnvironmentEntry>,
448    renderer: &R,
449) -> Result<Vec<(&'static str, R::Value)>>
450where
451    R: RuntimeEnvironmentRenderer,
452{
453    let mut rendered = Vec::new();
454    for entry in entries {
455        if let Some(value) = renderer.render_runtime_environment_value(entry.value)? {
456            rendered.push((entry.name, value));
457        }
458    }
459    Ok(rendered)
460}
461
462pub fn render_runtime_environment_plan<R>(
463    plan: &RuntimeEnvironmentPlan,
464    renderer: &R,
465) -> Result<Vec<(String, R::Value)>>
466where
467    R: RuntimeEnvironmentRenderer,
468{
469    let mut rendered = Vec::new();
470    for entry in plan.entries() {
471        match entry {
472            RuntimeEnvironmentPlanEntry::Scalar(entry) => {
473                if let Some(value) = renderer.render_runtime_environment_value(entry.value)? {
474                    rendered.push((entry.name.to_string(), value));
475                }
476            }
477            RuntimeEnvironmentPlanEntry::Binding(entry) => {
478                if let Some(value) = renderer.render_runtime_environment_binding(entry)? {
479                    rendered.push((entry.env_name.clone(), value));
480                }
481            }
482        }
483    }
484    Ok(rendered)
485}
486
487pub fn is_runtime_environment_contract_name(name: &str) -> bool {
488    matches!(
489        name,
490        ENV_ALIEN_CURRENT_CONTAINER_BINDING_NAME
491            | ENV_ALIEN_CURRENT_WORKER_BINDING_NAME
492            | ENV_OPERATOR_BASE_PLATFORM
493            | ENV_ALIEN_DEPLOYMENT_TYPE
494            | ENV_ALIEN_LAMBDA_MODE
495            | ENV_ALIEN_RUNTIME_SEND_OTLP
496            | ENV_ALIEN_TRANSPORT
497            | ENV_AWS_ACCOUNT_ID
498            | ENV_AWS_REGION
499            | ENV_AZURE_CLIENT_ID
500            | ENV_AZURE_REGION
501            | ENV_AZURE_SUBSCRIPTION_ID
502            | ENV_AZURE_TENANT_ID
503            | ENV_GCP_PROJECT_ID
504            | ENV_GCP_REGION
505            | ENV_GOOGLE_CLOUD_PROJECT
506    ) || (name.starts_with("ALIEN_") && name.ends_with("_BINDING"))
507}
508
509pub fn is_reserved_runtime_environment_name(name: &str) -> bool {
510    is_runtime_environment_contract_name(name)
511        || matches!(
512            name,
513            ENV_ALIEN_WORKER_GRPC_ADDRESS
514                | ENV_ALIEN_QUEUE_BATCH_CONFIG
515                | ENV_ALIEN_WORKER_TIMEOUT_SECONDS
516                | ENV_ALIEN_COMMANDS_TOKEN
517                | ENV_ALIEN_COMMANDS_TOKEN_FILE
518                | ENV_ALIEN_COMMANDS_LEASE_SECONDS
519                | ENV_ALIEN_COMMANDS_MAX_LEASES
520                | ENV_ALIEN_COMMANDS_POLL_INTERVAL_MS
521                | ENV_ALIEN_COMMANDS_POLL_MAX_INTERVAL_MS
522                | ENV_ALIEN_COMMANDS_POLL_JITTER
523                | ENV_ALIEN_COMMANDS_DRAIN_TIMEOUT_MS
524                | ENV_ALIEN_COMMANDS_TARGET_RESOURCE_ID
525                | ENV_ALIEN_COMMANDS_TARGET_RESOURCE_TYPE
526                | ENV_ALIEN_COMMANDS_URL
527                | ENV_ALIEN_DEPLOYMENT_ID
528                | ENV_ALIEN_DEPLOYMENT_NAME
529                | "ALIEN_DEPLOYMENT_SERVICE_ACCOUNT"
530                | ENV_ALIEN_DEPLOYMENT_TOKEN
531                | ENV_ALIEN_MANAGER_URL
532                | "ALIEN_IDENTITY_PROVIDER"
533                | "ALIEN_MANAGER_AUDIENCE"
534                | "ALIEN_SESSION_FILE"
535                | ENV_ALIEN_COMMANDS_CAPABILITY_FILE
536                | "ALIEN_TELEMETRY_CAPABILITY_FILE"
537                | ENV_ALIEN_RESOURCE_ID
538                | ENV_ALIEN_PUBLIC_ENDPOINTS_JSON
539                | ENV_ALIEN_RUNTIME_SECRETS
540                | ENV_ALIEN_SECRET_ENV_REVISION
541                | ENV_ALIEN_SECRETS
542        )
543        || name.starts_with("ALIEN_BINDING_")
544}
545
546pub fn validate_runtime_environment_user_vars<'a>(
547    names: impl IntoIterator<Item = &'a str>,
548) -> Result<()> {
549    let reserved: Vec<String> = names
550        .into_iter()
551        .filter(|name| is_reserved_runtime_environment_name(name))
552        .map(ToString::to_string)
553        .collect();
554    if reserved.is_empty() {
555        return Ok(());
556    }
557
558    Err(AlienError::new(ErrorData::GenericError {
559        message: format!(
560            "Environment variables use reserved Alien runtime names: {}",
561            reserved.join(", ")
562        ),
563    }))
564}
565
566pub fn validate_runtime_environment_user_map(env: &HashMap<String, String>) -> Result<()> {
567    validate_runtime_environment_user_vars(env.keys().map(String::as_str))
568}
569
570pub fn validate_prepared_runtime_environment_vars<'a>(
571    names: impl IntoIterator<Item = &'a str>,
572) -> Result<()> {
573    let reserved: Vec<String> = names
574        .into_iter()
575        .filter(|name| is_runtime_environment_contract_name(name))
576        .map(ToString::to_string)
577        .collect();
578    if reserved.is_empty() {
579        return Ok(());
580    }
581
582    Err(AlienError::new(ErrorData::GenericError {
583        message: format!(
584            "Environment variables collide with Alien runtime contract names: {}",
585            reserved.join(", ")
586        ),
587    }))
588}
589
590pub fn validate_prepared_runtime_environment_map(env: &HashMap<String, String>) -> Result<()> {
591    validate_prepared_runtime_environment_vars(env.keys().map(String::as_str))
592}
593
594#[cfg(test)]
595mod tests {
596    use super::*;
597
598    #[test]
599    fn reserves_builtin_and_binding_environment_names() {
600        assert!(is_reserved_runtime_environment_name(ENV_ALIEN_TRANSPORT));
601        assert!(is_reserved_runtime_environment_name(
602            ENV_ALIEN_CURRENT_CONTAINER_BINDING_NAME
603        ));
604        assert!(is_reserved_runtime_environment_name(
605            ENV_OPERATOR_BASE_PLATFORM
606        ));
607        assert!(is_reserved_runtime_environment_name(ENV_ALIEN_SECRETS));
608        assert!(is_reserved_runtime_environment_name(
609            ENV_ALIEN_SECRET_ENV_REVISION
610        ));
611        assert!(is_reserved_runtime_environment_name(
612            ENV_ALIEN_WORKER_GRPC_ADDRESS
613        ));
614        assert_eq!(ENV_ALIEN_WORKER_GRPC_ADDRESS, "ALIEN_WORKER_GRPC_ADDRESS");
615        assert!(is_reserved_runtime_environment_name(
616            ENV_ALIEN_WORKER_TIMEOUT_SECONDS
617        ));
618        assert_eq!(
619            ENV_ALIEN_WORKER_TIMEOUT_SECONDS,
620            "ALIEN_WORKER_TIMEOUT_SECONDS"
621        );
622        assert!(is_reserved_runtime_environment_name(
623            "ALIEN_STORAGE_BINDING"
624        ));
625        assert!(is_reserved_runtime_environment_name(
626            "ALIEN_BINDING_STORAGE_URL"
627        ));
628        assert!(!is_reserved_runtime_environment_name("USER_DEFINED"));
629    }
630
631    #[test]
632    fn reserves_deployment_identity_names() {
633        assert!(is_reserved_runtime_environment_name(ENV_ALIEN_MANAGER_URL));
634        assert!(is_reserved_runtime_environment_name(
635            ENV_ALIEN_DEPLOYMENT_TOKEN
636        ));
637        assert!(is_reserved_runtime_environment_name(
638            "ALIEN_DEPLOYMENT_SERVICE_ACCOUNT"
639        ));
640        assert!(is_reserved_runtime_environment_name(ENV_ALIEN_RESOURCE_ID));
641        assert_eq!(ENV_ALIEN_MANAGER_URL, "ALIEN_MANAGER_URL");
642        assert_eq!(ENV_ALIEN_DEPLOYMENT_TOKEN, "ALIEN_DEPLOYMENT_TOKEN");
643        assert_eq!(ENV_ALIEN_RESOURCE_ID, "ALIEN_RESOURCE_ID");
644    }
645
646    #[test]
647    fn reserves_commands_target_resource_id() {
648        assert!(is_reserved_runtime_environment_name(
649            ENV_ALIEN_COMMANDS_TARGET_RESOURCE_ID
650        ));
651        assert_eq!(
652            ENV_ALIEN_COMMANDS_TARGET_RESOURCE_ID,
653            "ALIEN_COMMANDS_TARGET_RESOURCE_ID"
654        );
655    }
656
657    #[test]
658    fn reserves_command_receiver_names() {
659        for (constant, expected) in [
660            (ENV_ALIEN_COMMANDS_URL, "ALIEN_COMMANDS_URL"),
661            (ENV_ALIEN_COMMANDS_TOKEN_FILE, "ALIEN_COMMANDS_TOKEN_FILE"),
662            (
663                ENV_ALIEN_COMMANDS_LEASE_SECONDS,
664                "ALIEN_COMMANDS_LEASE_SECONDS",
665            ),
666            (ENV_ALIEN_COMMANDS_MAX_LEASES, "ALIEN_COMMANDS_MAX_LEASES"),
667            (
668                ENV_ALIEN_COMMANDS_POLL_INTERVAL_MS,
669                "ALIEN_COMMANDS_POLL_INTERVAL_MS",
670            ),
671            (
672                ENV_ALIEN_COMMANDS_POLL_MAX_INTERVAL_MS,
673                "ALIEN_COMMANDS_POLL_MAX_INTERVAL_MS",
674            ),
675            (ENV_ALIEN_COMMANDS_POLL_JITTER, "ALIEN_COMMANDS_POLL_JITTER"),
676            (
677                ENV_ALIEN_COMMANDS_DRAIN_TIMEOUT_MS,
678                "ALIEN_COMMANDS_DRAIN_TIMEOUT_MS",
679            ),
680            (
681                ENV_ALIEN_COMMANDS_TARGET_RESOURCE_TYPE,
682                "ALIEN_COMMANDS_TARGET_RESOURCE_TYPE",
683            ),
684        ] {
685            assert_eq!(constant, expected);
686            assert!(is_reserved_runtime_environment_name(constant));
687        }
688    }
689
690    #[test]
691    fn rejects_reserved_user_environment_names() {
692        let error = validate_runtime_environment_user_vars(["USER_DEFINED", ENV_ALIEN_TRANSPORT])
693            .unwrap_err();
694
695        assert!(error.to_string().contains(ENV_ALIEN_TRANSPORT));
696    }
697
698    #[test]
699    fn prepared_environment_allows_deployment_managed_names() {
700        validate_prepared_runtime_environment_vars([
701            ENV_ALIEN_SECRETS,
702            ENV_ALIEN_DEPLOYMENT_ID,
703            ENV_ALIEN_DEPLOYMENT_NAME,
704            ENV_ALIEN_PUBLIC_ENDPOINTS_JSON,
705        ])
706        .unwrap();
707
708        let error =
709            validate_prepared_runtime_environment_vars([ENV_ALIEN_SECRETS, ENV_ALIEN_TRANSPORT])
710                .unwrap_err();
711
712        assert!(error.to_string().contains(ENV_ALIEN_TRANSPORT));
713        assert!(!error.to_string().contains(ENV_ALIEN_SECRETS));
714    }
715
716    #[test]
717    fn kubernetes_standard_environment_declares_base_platform() {
718        let entries = standard_runtime_environment_plan(Platform::Kubernetes);
719
720        assert!(entries.iter().any(|entry| {
721            entry.name == ENV_OPERATOR_BASE_PLATFORM
722                && entry.value == RuntimeEnvironmentValue::BasePlatform
723        }));
724    }
725
726    #[test]
727    fn kubernetes_gcp_base_environment_declares_gcp_identity() {
728        let entries = kubernetes_base_platform_runtime_environment_plan(Some(Platform::Gcp));
729
730        assert!(entries.iter().any(|entry| {
731            entry.name == ENV_GOOGLE_CLOUD_PROJECT
732                && entry.value == RuntimeEnvironmentValue::GcpProjectId
733        }));
734        assert!(entries.iter().any(|entry| {
735            entry.name == ENV_GCP_PROJECT_ID && entry.value == RuntimeEnvironmentValue::GcpProjectId
736        }));
737        assert!(entries.iter().any(|entry| {
738            entry.name == ENV_GCP_REGION && entry.value == RuntimeEnvironmentValue::GcpRegion
739        }));
740    }
741
742    #[test]
743    fn kubernetes_worker_environment_uses_http_proxy_transport() {
744        let entries = worker_transport_runtime_environment_plan(Platform::Kubernetes);
745
746        assert!(entries.iter().any(|entry| {
747            entry.name == ENV_ALIEN_TRANSPORT
748                && entry.value == RuntimeEnvironmentValue::Literal("http")
749        }));
750    }
751
752    #[test]
753    fn container_environment_does_not_inject_worker_transport() {
754        for platform in [
755            Platform::Local,
756            Platform::Kubernetes,
757            Platform::Aws,
758            Platform::Gcp,
759            Platform::Azure,
760            Platform::Test,
761        ] {
762            let entries = container_runtime_environment_plan(platform);
763            assert!(
764                !entries
765                    .iter()
766                    .any(|entry| entry.name == ENV_ALIEN_TRANSPORT),
767                "container plan for {platform:?} must not set ALIEN_TRANSPORT"
768            );
769            // The container binding-name var is still present.
770            assert!(
771                entries
772                    .iter()
773                    .any(|entry| entry.name == ENV_ALIEN_CURRENT_CONTAINER_BINDING_NAME),
774                "container plan for {platform:?} must still declare the binding-name var"
775            );
776        }
777    }
778
779    #[test]
780    fn daemon_environment_is_standard_identity_only() {
781        // Daemons use the standard platform-identity set. Receiver config is
782        // injected per resource, not by the static environment plan.
783        for platform in [
784            Platform::Local,
785            Platform::Kubernetes,
786            Platform::Aws,
787            Platform::Gcp,
788            Platform::Azure,
789            Platform::Test,
790        ] {
791            let entries = daemon_runtime_environment_plan(platform);
792            assert!(
793                !entries
794                    .iter()
795                    .any(|entry| entry.name == ENV_ALIEN_TRANSPORT),
796                "daemon plan for {platform:?} must not set ALIEN_TRANSPORT"
797            );
798            assert!(
799                !entries
800                    .iter()
801                    .any(|entry| entry.name == ENV_ALIEN_CURRENT_CONTAINER_BINDING_NAME),
802                "daemon plan for {platform:?} must not set the container self-binding var"
803            );
804            // The standard deployment-type identity var is always present.
805            assert!(
806                entries
807                    .iter()
808                    .any(|entry| entry.name == ENV_ALIEN_DEPLOYMENT_TYPE),
809                "daemon plan for {platform:?} must declare ALIEN_DEPLOYMENT_TYPE"
810            );
811        }
812    }
813
814    #[test]
815    fn worker_local_transport_uses_local_proxy() {
816        // Local/Test Workers run under `TransportType::Local`, selected by the
817        // Worker manager.
818        for platform in [Platform::Local, Platform::Test] {
819            let entries = worker_transport_runtime_environment_plan(platform);
820            assert!(entries.iter().any(|entry| {
821                entry.name == ENV_ALIEN_TRANSPORT
822                    && entry.value == RuntimeEnvironmentValue::Literal("local")
823            }));
824        }
825    }
826}