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