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