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