Skip to main content

alien_core/deployment/
config.rs

1//! Deployment configuration and OTLP observability settings.
2
3use crate::{ExternalBindings, ManagementConfig, StackSettings};
4use bon::Builder;
5use serde::{Deserialize, Serialize};
6use std::collections::HashMap;
7
8use super::{
9    is_false, ComputeBackend, DeletionPolicy, DomainMetadata, EnvironmentVariableType,
10    EnvironmentVariablesSnapshot,
11};
12
13/// Deployment configuration
14///
15/// Configuration for how to perform the deployment.
16/// Note: Credentials (ClientConfig) are passed separately to step() function.
17#[derive(Debug, Clone, Serialize, Deserialize, Builder)]
18#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
19#[serde(rename_all = "camelCase")]
20pub struct DeploymentConfig {
21    /// This invocation is an explicit setup run using the installer's credentials.
22    /// Not serialized: a release or stored configuration cannot request an identity refresh.
23    #[serde(skip)]
24    #[cfg_attr(feature = "openapi", schema(ignore))]
25    #[builder(default)]
26    pub setup_run: bool,
27    /// Identifies this setup run, set together with `setup_run`. Every setup run gets a new
28    /// one, so a controller can tell a result recorded earlier in this run from one recorded in
29    /// an earlier run.
30    #[serde(skip)]
31    #[cfg_attr(feature = "openapi", schema(ignore))]
32    pub setup_run_id: Option<String>,
33    /// Human-readable deployment name for cloud console metadata.
34    ///
35    /// This is separate from the physical resource prefix in StackState. It is
36    /// used only for display text such as IAM role descriptions, service
37    /// account descriptions, and custom role titles.
38    #[serde(default, skip_serializing_if = "Option::is_none")]
39    pub deployment_name: Option<String>,
40    /// User-customizable deployment settings (network, deployment model, approvals).
41    /// Provided by customer via CloudFormation, Terraform, CLI, or Helm.
42    #[serde(default)]
43    pub stack_settings: StackSettings,
44    /// Platform service account/role that will manage the infrastructure remotely.
45    /// Derived from Manager's ServiceAccount, not user-specified.
46    #[serde(skip_serializing_if = "Option::is_none")]
47    pub management_config: Option<ManagementConfig>,
48    /// Registered installation identity for target federation setup.
49    /// Callers derive this from registration, separately from display metadata.
50    #[serde(default, skip_serializing_if = "Option::is_none")]
51    pub gcp_federation_scope: Option<crate::GcpFederationScope>,
52    /// Environment variables snapshot
53    pub environment_variables: EnvironmentVariablesSnapshot,
54    /// Deployer-provided stack input values, keyed by input id. A resource
55    /// gated with `.enabled(input)` and a Live lifecycle follows these
56    /// values; a missing key falls back to the input's declared boolean
57    /// default. Suppliers must not place secret-kind input values here:
58    /// this map serializes and debug-prints unredacted.
59    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
60    #[builder(default)]
61    pub input_values: HashMap<String, serde_json::Value>,
62    /// Values the manager holds for this deployment instead of the sender.
63    /// For each slot the sender gives the kind and a keyed digest, never the
64    /// value. The manager loads the value from its own store, refuses to run
65    /// when a digest differs, and merges the value into `environment_variables`
66    /// or `input_values` before the deployment steps.
67    #[serde(default, skip_serializing_if = "Vec::is_empty")]
68    #[builder(default)]
69    pub value_slots: Vec<ValueSlotRef>,
70    /// IDs of applicable secret inputs stored for this exact deployment target.
71    /// Trusted presence metadata only: never values, gate answers, or authority.
72    /// Absent on legacy targets; an explicit empty list means no stored secrets.
73    #[serde(default, skip_serializing_if = "Option::is_none")]
74    #[cfg_attr(feature = "openapi", schema(nullable = false))]
75    pub stored_secret_input_ids: Option<Vec<String>>,
76    /// Allow frozen resource changes during updates
77    /// When true, skips the frozen resources compatibility check.
78    /// This requires running with elevated cloud credentials.
79    #[serde(default, skip_serializing_if = "is_false")]
80    pub allow_frozen_changes: bool,
81    /// Compute backend for Container and Worker resources.
82    /// When None, the platform default is used for cloud platforms.
83    /// Contains cluster IDs and management tokens for container orchestration.
84    /// Worker runtime credentials are provided through cloud identity and vault-backed secrets.
85    #[serde(skip_serializing_if = "Option::is_none")]
86    pub compute_backend: Option<ComputeBackend>,
87    /// External bindings for pre-existing services.
88    /// Required for Kubernetes platform (all infrastructure resources).
89    /// Optional for cloud platforms (override specific resources).
90    #[serde(default)]
91    pub external_bindings: ExternalBindings,
92    /// Cloud platform that owns imported base infrastructure for a Kubernetes
93    /// runtime deployment.
94    #[serde(default, skip_serializing_if = "Option::is_none")]
95    pub base_platform: Option<crate::Platform>,
96    /// DNS-style label domain used for Kubernetes resource ownership labels.
97    ///
98    /// Defaults to `alien.dev` when absent. Whitelabeled Operator builds set this
99    /// so generated workloads and optional log collectors share the same label
100    /// namespace.
101    #[serde(default, skip_serializing_if = "Option::is_none")]
102    pub label_domain: Option<String>,
103    /// Kubernetes label selector that narrows which raw resources the observe
104    /// pass reports (e.g. `app.kubernetes.io/part-of=my-app`). `None` observes
105    /// everything in the namespace. Ignored by cloud observers.
106    #[serde(default, skip_serializing_if = "Option::is_none")]
107    pub observe_label_selector: Option<String>,
108    /// When true the observe pass reports raw resources across every namespace
109    /// (cluster scope); otherwise it stays within the operator's own namespace.
110    /// The label selector, if any, still filters within whichever scope applies.
111    /// Ignored by cloud observers.
112    #[serde(default)]
113    #[builder(default)]
114    pub observe_all_namespaces: bool,
115    /// Public endpoint URLs for exposed resources (optional override).
116    ///
117    /// Use this only when a caller already knows the public URL. Managed public
118    /// endpoint flows should prefer `domain_metadata` plus controller-reported
119    /// load balancer outputs so DNS, certificate renewal, and route readiness
120    /// stay tied to the resource state.
121    ///
122    /// If not set, platforms determine public endpoint URLs from other sources:
123    /// - Managed DNS/TLS flows: `domain_metadata` FQDN or load balancer DNS
124    /// - Local: `http://localhost:{allocated_port}`
125    /// - Custom or disabled exposure: no public endpoint URL unless a controller reports one
126    ///
127    /// Outer key: resource ID. Inner key: endpoint name. Value: public URL.
128    #[serde(skip_serializing_if = "Option::is_none")]
129    pub public_endpoints: Option<HashMap<String, HashMap<String, String>>>,
130    /// Domain metadata for auto-managed public resources.
131    ///
132    /// Contains generated hostnames, DNS record state, certificate material,
133    /// and renewal markers for platforms that use managed public endpoints.
134    /// Kubernetes uses this only when its exposure mode is `generated`; BYO and
135    /// disabled Kubernetes exposure do not receive managed domain metadata.
136    #[serde(skip_serializing_if = "Option::is_none")]
137    pub domain_metadata: Option<DomainMetadata>,
138    /// OTLP observability configuration for log export (optional).
139    ///
140    /// When set, worker runtimes export captured application logs through this
141    /// endpoint. Container orchestrators may use it for their node-level log
142    /// collectors, but app container configs must not receive the auth header.
143    #[serde(skip_serializing_if = "Option::is_none")]
144    pub monitoring: Option<OtlpConfig>,
145    /// Manager base URL (e.g., "https://manager.alien.dev").
146    ///
147    /// The manager IS the container registry — its `/v2/` endpoint serves as
148    /// the OCI Distribution API. Controllers derive the proxy host from this
149    /// to configure pull auth (RegistryCredentials, imagePullSecrets).
150    ///
151    /// When None (e.g., `alien dev`), controllers use image URIs as-is.
152    #[serde(default, skip_serializing_if = "Option::is_none")]
153    pub manager_url: Option<String>,
154    /// Exact audience for bounded runtime identity exchange. When present,
155    /// runtimes must use identity exchange and cannot fall back to stored tokens.
156    /// Absence preserves the legacy mode for installs awaiting migration.
157    #[serde(default, skip_serializing_if = "Option::is_none")]
158    pub runtime_identity_audience: Option<String>,
159    /// Deployment token for pull authentication with the manager's registry.
160    ///
161    /// Used by controllers to configure registry credentials so cloud platforms
162    /// and K8s can pull images from the manager's `/v2/` endpoint.
163    #[serde(default, skip_serializing_if = "Option::is_none")]
164    pub deployment_token: Option<String>,
165    /// Native image registry host+prefix for platforms that require it.
166    ///
167    /// Lambda (ECR) and Cloud Run (GAR) require native registry URIs. Other
168    /// runtimes, including Azure Container Apps, pull through the manager's
169    /// registry proxy.
170    ///
171    /// Derived by the manager from the artifact registry binding:
172    /// - ECR: `{account_id}.dkr.ecr.{region}.amazonaws.com/{repository_prefix}`
173    /// - GAR: `{region}-docker.pkg.dev/{project_id}/{repository_name}`
174    #[serde(default, skip_serializing_if = "Option::is_none")]
175    pub native_image_host: Option<String>,
176    /// Operator requests to replace a replica's persistent volume with a new
177    /// volume made from a snapshot. A container controller performs each
178    /// request once, identified by its `request_id`, and reports it in
179    /// `ContainerOutputs.volumes`. Only a volume that a controller reports in
180    /// `ContainerOutputs.volumes` can be the target of a request.
181    #[serde(default, skip_serializing_if = "Vec::is_empty")]
182    #[builder(default)]
183    pub volume_restores: Vec<VolumeRestoreRequest>,
184    /// How the deletion this run performs treats data. Under `Erase`, controllers also
185    /// delete what they would otherwise keep after the resource is gone, such as a
186    /// container's final volume snapshots.
187    /// Not serialized: deletion sets it from the policy persisted in runtime metadata,
188    /// so a stored configuration cannot request an erase.
189    #[serde(skip)]
190    #[cfg_attr(feature = "openapi", schema(ignore))]
191    #[builder(default)]
192    pub deletion_policy: DeletionPolicy,
193}
194
195/// A value the manager holds, named by slot, with the digest the sender expects.
196///
197/// The slot is `env:NAME` for an environment variable, `input:ID` for a stack
198/// input, or `cenv.<container>.<NAME>` for a dynamic container's variable. An
199/// input's stored value is the JSON text of the input value.
200#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
201#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
202#[serde(rename_all = "camelCase")]
203pub struct ValueSlotRef {
204    /// `env:NAME`, `input:ID` or `cenv.<container>.<NAME>`.
205    pub slot: String,
206    /// Whether the value is a secret. The manager checks it against the stored kind.
207    pub kind: EnvironmentVariableType,
208    /// Keyed digest of the value, as lowercase hex.
209    pub digest: String,
210    /// Variable name, repeated for display. The slot decides the name.
211    #[serde(default, skip_serializing_if = "Option::is_none")]
212    pub env_name: Option<String>,
213    /// Target resource patterns for an environment variable. `None` means all resources.
214    #[serde(default, skip_serializing_if = "Option::is_none")]
215    pub targets: Option<Vec<String>>,
216}
217
218/// Replace one replica's persistent volume with a new volume made from a snapshot.
219///
220/// The controller stops the replica, snapshots the volume it is about to
221/// replace (so the restore can be undone), creates the new volume in the same
222/// zone, starts the replica on it, and deletes the replaced volume.
223#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
224#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
225#[serde(rename_all = "camelCase")]
226pub struct VolumeRestoreRequest {
227    /// Unique ID of this request. A controller performs each request once.
228    pub request_id: String,
229    /// ID of the container resource that owns the volume
230    pub resource_id: String,
231    /// Replica ordinal whose volume is replaced
232    pub ordinal: u32,
233    /// Cloud ID of the snapshot to restore: an EBS snapshot ID, a Compute
234    /// Engine snapshot name, or an Azure snapshot resource ID
235    pub snapshot_id: String,
236}
237
238/// Resource-attribute key marking OTLP telemetry as Alien system-component
239/// output (infrastructure daemons and internal runtimes) rather than user
240/// workload. Log consumers — the CLI log viewer and the dashboard — hide
241/// telemetry carrying this attribute by default. The value is the string
242/// `"true"`.
243///
244/// System components set this on their own telemetry's resource attributes so
245/// consumers can filter generically, without enumerating component names.
246pub const ALIEN_SYSTEM_RESOURCE_ATTRIBUTE: &str = "alien.system";
247
248/// Prefix that marks one captured output line of a Worker as Alien system output.
249///
250/// The worker runtime strips it from the line and records
251/// [`ALIEN_SYSTEM_RESOURCE_ATTRIBUTE`] on the exported record. Alien components that run as a
252/// Worker's application write it at the start of every line they print. Like the attribute, it
253/// only hides a line by default; it grants nothing.
254pub const ALIEN_SYSTEM_LOG_LINE_PREFIX: &str = "\u{1e}ALIEN_SYSTEM\u{1f}";
255
256/// OTLP log export configuration for a deployment.
257///
258/// When set, injected compute runtimes export captured application logs
259/// through the given endpoint via OTLP/HTTP; which resources are injected
260/// is platform-dependent. Workers read auth headers from a runtime-only
261/// secret. Runtime-less Containers and Daemons receive standard OTEL auth
262/// variables only at the final hosting boundary: Local passes them directly
263/// to the process and Kubernetes projects them from a per-workload Secret.
264#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
265#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
266#[serde(rename_all = "camelCase")]
267pub struct OtlpConfig {
268    /// Full OTLP logs endpoint URL.
269    /// Example: "https://<manager-host>/v1/logs"
270    pub logs_endpoint: String,
271    /// Auth header value in "key=value,..." format.
272    /// Example: "authorization=Bearer <write-token>"
273    pub logs_auth_header: String,
274    /// Full OTLP metrics endpoint URL (optional).
275    /// When set, the worker runtime exports its own VM/container orchestration metrics here.
276    /// Example: "https://api.axiom.co/v1/metrics"
277    #[serde(skip_serializing_if = "Option::is_none")]
278    pub metrics_endpoint: Option<String>,
279    /// Auth header value for the metrics endpoint in "key=value,..." format (optional).
280    ///
281    /// When absent, `logs_auth_header` is reused for metrics -- suitable when the same
282    /// credential covers both signals. When present (e.g. Axiom with separate datasets),
283    /// this value is used exclusively for metrics.
284    ///
285    /// Example: "authorization=Bearer <token>,x-axiom-dataset=<metrics-dataset>"
286    #[serde(skip_serializing_if = "Option::is_none")]
287    pub metrics_auth_header: Option<String>,
288    /// Resource attributes attached to every OTLP signal emitted for this deployment.
289    ///
290    /// Platform managers use this for stable identity such as `alien.workspace_id`,
291    /// `alien.project_id`, `alien.deployment_group_id`, and `alien.deployment_id`.
292    /// Runtime-specific resource attributes such as `service.name` remain owned by
293    /// the runtime/exporter.
294    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
295    pub resource_attributes: HashMap<String, String>,
296}
297
298#[cfg(test)]
299mod input_values_tests {
300    use super::*;
301
302    /// Older actors serialize configs without the field; it must deserialize
303    /// to an empty map, and an empty map must not serialize at all.
304    #[test]
305    fn input_values_default_to_empty_and_stay_off_the_wire() {
306        let json = serde_json::json!({
307            "stackSettings": serde_json::to_value(crate::StackSettings::default()).unwrap(),
308            "environmentVariables": {
309                "variables": [],
310                "hash": "hash",
311                "createdAt": "2026-01-01T00:00:00Z",
312            },
313            "externalBindings": {},
314        });
315        let config: DeploymentConfig =
316            serde_json::from_value(json).expect("old shape deserializes");
317        assert!(config.input_values.is_empty());
318        assert!(config.stored_secret_input_ids.is_none());
319
320        let round = serde_json::to_value(&config).expect("serializes");
321        assert!(round.get("storedSecretInputIds").is_none());
322        assert!(
323            round.get("inputValues").is_none(),
324            "empty map must not serialize"
325        );
326    }
327    #[test]
328    fn stored_secret_presence_roundtrips_without_values_or_gate_answers() {
329        let mut config = DeploymentConfig::builder()
330            .stack_settings(StackSettings::default())
331            .environment_variables(EnvironmentVariablesSnapshot {
332                variables: vec![],
333                hash: String::new(),
334                created_at: String::new(),
335            })
336            .allow_frozen_changes(false)
337            .external_bindings(ExternalBindings::default())
338            .build();
339        assert!(config.stored_secret_input_ids.is_none());
340        config.stored_secret_input_ids = Some(Vec::new());
341        let empty = serde_json::to_value(&config).unwrap();
342        assert_eq!(empty["storedSecretInputIds"], serde_json::json!([]));
343        assert_eq!(
344            serde_json::from_value::<DeploymentConfig>(empty)
345                .unwrap()
346                .stored_secret_input_ids,
347            Some(Vec::new())
348        );
349        config.stored_secret_input_ids =
350            Some(vec!["apiKey".to_string(), "enableFeature".to_string()]);
351        let wire = serde_json::to_value(&config).unwrap();
352        assert_eq!(
353            wire["storedSecretInputIds"],
354            serde_json::json!(["apiKey", "enableFeature"])
355        );
356        assert!(wire.get("inputValues").is_none());
357        let decoded: DeploymentConfig = serde_json::from_value(wire.clone()).unwrap();
358        assert_eq!(
359            decoded.stored_secret_input_ids,
360            config.stored_secret_input_ids
361        );
362        assert_eq!(serde_json::to_value(decoded.clone()).unwrap(), wire);
363        assert!(decoded.input_values.is_empty());
364        for default in [false, true] {
365            let input: crate::StackInputDefinition = serde_json::from_value(serde_json::json!({
366                "id": "enableFeature", "kind": "boolean", "providedBy": ["deployer"],
367                "required": false, "label": "Enable feature", "description": "", "default": crate::StackInputDefaultValue::Boolean(default)
368            }))
369            .unwrap();
370            assert_eq!(
371                crate::gate_resolves_true(
372                    &[input],
373                    "enableFeature",
374                    &decoded.input_values,
375                    "worker",
376                    crate::Platform::Aws
377                )
378                .unwrap(),
379                default
380            );
381        }
382        assert!(crate::gate_resolves_true(
383            &[],
384            "enableFeature",
385            &decoded.input_values,
386            "worker",
387            crate::Platform::Aws
388        )
389        .is_err());
390    }
391
392    fn deployment_config_with_cluster(
393        cluster_image: Option<serde_json::Value>,
394    ) -> serde_json::Value {
395        let config = DeploymentConfig::builder()
396            .stack_settings(StackSettings::default())
397            .environment_variables(EnvironmentVariablesSnapshot {
398                variables: vec![],
399                hash: String::new(),
400                created_at: String::new(),
401            })
402            .allow_frozen_changes(false)
403            .external_bindings(ExternalBindings::default())
404            .compute_backend(crate::ComputeBackend::Horizon(crate::HorizonConfig {
405                url: "https://horizon.example.com".to_string(),
406                horizon_machine_image: None,
407                clusters: HashMap::from([(
408                    "compute".to_string(),
409                    crate::HorizonClusterConfig {
410                        cluster_id: "cluster-1".to_string(),
411                        management_token: "hm_test".to_string(),
412                        runtime_identity: None,
413                        horizon_machine_image: cluster_image
414                            .map(|image| serde_json::from_value(image).unwrap()),
415                    },
416                )]),
417            }))
418            .build();
419        serde_json::to_value(&config).unwrap()
420    }
421
422    fn machine_image(version: &str) -> serde_json::Value {
423        serde_json::json!({
424            "channel": "stable",
425            "machineImageVersion": version,
426            "horizondVersion": version,
427            "gitSha": "abc123",
428            "createdAt": "2026-01-01T00:00:00Z",
429            "baseImage": { "name": "linux", "version": "1" },
430            "horizondArtifacts": {}
431        })
432    }
433
434    /// A deployment config written before clusters could carry a machine image, as managers
435    /// receive and store it, reads back with no cluster image.
436    #[test]
437    fn deployment_config_without_cluster_machine_image_reads_as_before() {
438        let wire = deployment_config_with_cluster(None);
439        let cluster = &wire["computeBackend"]["clusters"]["compute"];
440        assert_eq!(
441            cluster,
442            &serde_json::json!({ "clusterId": "cluster-1", "managementToken": "hm_test" })
443        );
444
445        let config: DeploymentConfig = serde_json::from_value(wire).unwrap();
446        let Some(crate::ComputeBackend::Horizon(horizon)) = config.compute_backend else {
447            panic!("the Horizon backend reads back");
448        };
449        assert_eq!(horizon.clusters["compute"].horizon_machine_image, None);
450    }
451
452    /// The types on the path from the deployment config to a cluster as they were before the
453    /// cluster machine image existed: none of them rejects unknown fields.
454    #[derive(Debug, Deserialize)]
455    #[serde(rename_all = "camelCase")]
456    struct PreviousDeploymentConfig {
457        compute_backend: Option<PreviousComputeBackend>,
458    }
459
460    #[derive(Debug, Deserialize)]
461    #[serde(tag = "type", rename_all = "camelCase")]
462    enum PreviousComputeBackend {
463        Horizon(PreviousHorizonConfig),
464    }
465
466    #[derive(Debug, Deserialize)]
467    #[serde(rename_all = "camelCase")]
468    struct PreviousHorizonConfig {
469        clusters: HashMap<String, PreviousHorizonClusterConfig>,
470    }
471
472    #[derive(Debug, Deserialize, PartialEq)]
473    #[serde(rename_all = "camelCase")]
474    struct PreviousHorizonClusterConfig {
475        cluster_id: String,
476        management_token: String,
477    }
478
479    /// A manager built before the field reads a deployment config that sets it and ignores it.
480    #[test]
481    fn deployment_config_with_cluster_machine_image_reads_in_older_readers() {
482        let wire = deployment_config_with_cluster(Some(machine_image("1")));
483        assert!(wire["computeBackend"]["clusters"]["compute"]["horizonMachineImage"].is_object());
484
485        let previous: PreviousDeploymentConfig = serde_json::from_value(wire.clone())
486            .expect("an older reader must accept a cluster that carries its own image");
487        let Some(PreviousComputeBackend::Horizon(horizon)) = previous.compute_backend else {
488            panic!("the Horizon backend reads back");
489        };
490        assert_eq!(
491            horizon.clusters["compute"],
492            PreviousHorizonClusterConfig {
493                cluster_id: "cluster-1".to_string(),
494                management_token: "hm_test".to_string(),
495            }
496        );
497
498        let current: DeploymentConfig = serde_json::from_value(wire).unwrap();
499        let Some(crate::ComputeBackend::Horizon(horizon)) = current.compute_backend else {
500            panic!("the Horizon backend reads back");
501        };
502        assert_eq!(
503            horizon
504                .machine_image_for("compute")
505                .map(|image| image.machine_image_version.as_str()),
506            Some("1")
507        );
508    }
509}