Skip to main content

alien_core/
embedded_config.rs

1//! Embedded configuration support for alien-deploy-cli and alien-operator binaries.
2//!
3//! The package builder appends a JSON-encoded config struct to the end of the
4//! binary, followed by a 4-byte little-endian length and 8-byte magic trailer.
5//! This allows a single binary to be customized per deployment group without
6//! recompilation.
7
8use serde::{de::DeserializeOwned, Deserialize, Serialize};
9use std::path::Path;
10
11/// Default location of the operator configuration packaged in a container image.
12pub const OPERATOR_CONFIG_PATH: &str = "/etc/alien/operator-config.json";
13
14/// Magic bytes at the end of a binary with embedded config.
15pub const MAGIC_BYTES: &[u8; 8] = b"WLCFG001";
16
17/// Size of the footer: 4 bytes (length) + 8 bytes (magic).
18pub const FOOTER_SIZE: usize = 12;
19
20/// Configuration embedded in alien-deploy-cli binaries.
21#[derive(Debug, Clone, Serialize, Deserialize)]
22#[serde(rename_all = "camelCase")]
23pub struct DeployCliConfig {
24    // --- Connection (for pre-configured binaries) ---
25    /// Authentication token for the platform/manager API.
26    #[serde(skip_serializing_if = "Option::is_none")]
27    pub token: Option<String>,
28    /// Deployment group ID.
29    #[serde(skip_serializing_if = "Option::is_none")]
30    pub deployment_group_id: Option<String>,
31    /// Default platform for deployments.
32    #[serde(skip_serializing_if = "Option::is_none")]
33    pub default_platform: Option<String>,
34    /// Platform API base URL used for manager discovery.
35    #[serde(skip_serializing_if = "Option::is_none")]
36    pub api_base_url: Option<String>,
37    /// Exact agent binary URL to install for local pull-model deployments.
38    #[serde(skip_serializing_if = "Option::is_none")]
39    pub agent_binary_url: Option<String>,
40    /// Machine bootstrap bundle manifest URL used by `alien-deploy join`.
41    #[serde(skip_serializing_if = "Option::is_none")]
42    pub machine_bundle_url: Option<String>,
43    /// Unix install script URL for this CLI package.
44    #[serde(skip_serializing_if = "Option::is_none")]
45    pub install_script_url: Option<String>,
46    /// Package build revision for setup-affecting code and artifacts. Existing
47    /// direct-setup deployments reconcile setup once when this value changes.
48    #[serde(default, skip_serializing_if = "Option::is_none")]
49    pub setup_revision: Option<String>,
50    /// Branded environment variable that contains the deployment token.
51    #[serde(skip_serializing_if = "Option::is_none")]
52    pub token_env_var: Option<String>,
53    // --- Branding (for rebranded binaries) ---
54    /// Binary name (e.g., "acme-deploy").
55    #[serde(skip_serializing_if = "Option::is_none")]
56    pub name: Option<String>,
57    /// Human-friendly display name (e.g., "Acme Deploy CLI").
58    #[serde(skip_serializing_if = "Option::is_none")]
59    pub display_name: Option<String>,
60    /// Branded Kubernetes label domain (e.g., "acme.dev") the installs of this package carry on
61    /// their objects. A delete run from this binary uses it to recognise those objects.
62    /// An empty value reads as none, so every user of it (the runtime cleanup and the listing
63    /// of what it left) agrees on the default domain.
64    #[serde(
65        default,
66        skip_serializing_if = "Option::is_none",
67        deserialize_with = "non_empty_text"
68    )]
69    pub label_domain: Option<String>,
70}
71
72fn non_empty_text<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
73where
74    D: serde::Deserializer<'de>,
75{
76    let value: Option<String> = serde::Deserialize::deserialize(deserializer)?;
77    Ok(value.filter(|text| !text.trim().is_empty()))
78}
79
80/// Configuration embedded in alien-operator binaries.
81#[derive(Debug, Clone, Serialize, Deserialize)]
82#[serde(rename_all = "camelCase")]
83pub struct OperatorConfig {
84    // --- Connection (for pre-configured/OSS binaries) ---
85    /// Manager URL to connect to.
86    #[serde(skip_serializing_if = "Option::is_none")]
87    pub manager_url: Option<String>,
88    /// Authentication token for the manager API.
89    #[serde(skip_serializing_if = "Option::is_none")]
90    pub token: Option<String>,
91    /// Deployment ID this operator manages.
92    #[serde(skip_serializing_if = "Option::is_none")]
93    pub deployment_id: Option<String>,
94    /// Sync interval in seconds (default: 30).
95    #[serde(default = "default_sync_interval")]
96    pub sync_interval_secs: u64,
97    // --- Branding (for rebranded binaries) ---
98    /// Binary name (e.g., "acme-operator").
99    #[serde(skip_serializing_if = "Option::is_none")]
100    pub name: Option<String>,
101    /// Short brand slug used for generated resource names.
102    #[serde(skip_serializing_if = "Option::is_none")]
103    pub brand: Option<String>,
104    /// Human-friendly display name (e.g., "Acme Operator").
105    #[serde(skip_serializing_if = "Option::is_none")]
106    pub display_name: Option<String>,
107    /// Branded environment variable prefix (e.g., "ACME").
108    #[serde(skip_serializing_if = "Option::is_none")]
109    pub env_prefix: Option<String>,
110    /// Branded Kubernetes/cloud label domain (e.g., "acme.dev").
111    #[serde(skip_serializing_if = "Option::is_none")]
112    pub label_domain: Option<String>,
113}
114
115fn default_sync_interval() -> u64 {
116    30
117}
118
119/// Load embedded configuration from the current binary.
120///
121/// Reads the binary's own file, checks for the magic trailer, extracts the
122/// JSON payload, and deserializes it into the requested type.
123///
124/// Returns `None` if the binary has no embedded config (no magic trailer).
125pub fn load_embedded_config<T: DeserializeOwned>() -> Result<Option<T>, EmbeddedConfigError> {
126    let exe_path = std::env::current_exe().map_err(EmbeddedConfigError::Io)?;
127    load_embedded_config_from_path(&exe_path)
128}
129
130/// Load a JSON configuration file.
131pub fn load_config_file<T: DeserializeOwned>(path: &Path) -> Result<T, EmbeddedConfigError> {
132    let data = std::fs::read(path).map_err(EmbeddedConfigError::Io)?;
133    serde_json::from_slice(&data).map_err(EmbeddedConfigError::Deserialization)
134}
135
136/// Load embedded configuration from a specific binary path.
137pub fn load_embedded_config_from_path<T: DeserializeOwned>(
138    path: &std::path::Path,
139) -> Result<Option<T>, EmbeddedConfigError> {
140    let data = std::fs::read(path).map_err(EmbeddedConfigError::Io)?;
141
142    if data.len() < FOOTER_SIZE {
143        return Ok(None);
144    }
145
146    // Check magic bytes at the end
147    let magic_start = data.len() - MAGIC_BYTES.len();
148    if &data[magic_start..] != MAGIC_BYTES {
149        return Ok(None);
150    }
151
152    // Read the 4-byte little-endian length before the magic
153    let len_start = magic_start - 4;
154    let len_bytes: [u8; 4] = data[len_start..magic_start]
155        .try_into()
156        .map_err(|_| EmbeddedConfigError::InvalidFormat("invalid length bytes".into()))?;
157    let json_len = u32::from_le_bytes(len_bytes) as usize;
158
159    if json_len == 0 || len_start < json_len {
160        return Err(EmbeddedConfigError::InvalidFormat(
161            "config length exceeds binary size".into(),
162        ));
163    }
164
165    let json_start = len_start - json_len;
166    let json_bytes = &data[json_start..len_start];
167
168    let config: T =
169        serde_json::from_slice(json_bytes).map_err(EmbeddedConfigError::Deserialization)?;
170
171    Ok(Some(config))
172}
173
174/// Append embedded configuration to a binary.
175///
176/// Writes: original binary bytes + JSON payload + 4-byte LE length + magic bytes.
177pub fn append_embedded_config<T: Serialize>(
178    binary_data: &[u8],
179    config: &T,
180) -> Result<Vec<u8>, EmbeddedConfigError> {
181    let trailer = encode_embedded_config_trailer(config)?;
182
183    let mut result = Vec::with_capacity(binary_data.len() + trailer.len());
184    result.extend_from_slice(binary_data);
185    result.extend_from_slice(&trailer);
186
187    Ok(result)
188}
189
190/// Encode the self-contained trailer appended to a binary with embedded config.
191///
192/// Writes: JSON payload + 4-byte LE length + magic bytes. Keeping this separate
193/// lets object stores compose an existing binary with a small configuration
194/// object without downloading and uploading the binary again.
195pub fn encode_embedded_config_trailer<T: Serialize>(
196    config: &T,
197) -> Result<Vec<u8>, EmbeddedConfigError> {
198    let json_bytes = serde_json::to_vec(config).map_err(EmbeddedConfigError::Deserialization)?;
199    let json_len = json_bytes.len() as u32;
200
201    let mut result = Vec::with_capacity(json_bytes.len() + FOOTER_SIZE);
202    result.extend_from_slice(&json_bytes);
203    result.extend_from_slice(&json_len.to_le_bytes());
204    result.extend_from_slice(MAGIC_BYTES);
205
206    Ok(result)
207}
208
209/// Errors from embedded config operations.
210#[derive(Debug)]
211pub enum EmbeddedConfigError {
212    Io(std::io::Error),
213    InvalidFormat(String),
214    Deserialization(serde_json::Error),
215}
216
217impl std::fmt::Display for EmbeddedConfigError {
218    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
219        match self {
220            Self::Io(e) => write!(f, "IO error reading embedded config: {}", e),
221            Self::InvalidFormat(msg) => write!(f, "invalid embedded config format: {}", msg),
222            Self::Deserialization(e) => write!(f, "failed to deserialize embedded config: {}", e),
223        }
224    }
225}
226
227impl std::error::Error for EmbeddedConfigError {}
228
229#[cfg(test)]
230mod tests {
231    use super::*;
232
233    #[test]
234    fn encoded_trailer_matches_append_output_exactly() {
235        let config = DeployCliConfig {
236            token: Some("secret".into()),
237            deployment_group_id: Some("dg_123".into()),
238            default_platform: Some("aws".into()),
239            api_base_url: Some("https://api.example.com".into()),
240            agent_binary_url: None,
241            machine_bundle_url: None,
242            install_script_url: None,
243            setup_revision: Some("revision".into()),
244            token_env_var: Some("EXAMPLE_TOKEN".into()),
245            name: Some("example-deploy".into()),
246            display_name: Some("Example Deploy".into()),
247            label_domain: Some("example.dev".into()),
248        };
249        let binary = b"an existing executable";
250
251        let appended = append_embedded_config(binary, &config).expect("config should append");
252        let trailer = encode_embedded_config_trailer(&config).expect("trailer should encode");
253
254        assert_eq!(appended, [binary.as_slice(), trailer.as_slice()].concat());
255
256        let loaded: DeployCliConfig = load_embedded_config_from_path_bytes(&appended)
257            .expect("appended config should parse")
258            .expect("appended config should exist");
259        assert_eq!(loaded.token, config.token);
260        assert_eq!(loaded.deployment_group_id, config.deployment_group_id);
261        assert_eq!(loaded.setup_revision, config.setup_revision);
262        assert_eq!(loaded.name, config.name);
263        assert_eq!(loaded.label_domain.as_deref(), Some("example.dev"));
264    }
265
266    /// An empty label domain is none, not a domain of its own.
267    #[test]
268    fn an_empty_label_domain_reads_as_none() {
269        for json in [
270            r#"{"labelDomain":""}"#,
271            r#"{"labelDomain":"  "}"#,
272            r#"{"labelDomain":null}"#,
273        ] {
274            let loaded: DeployCliConfig = serde_json::from_str(json).unwrap();
275            assert_eq!(loaded.label_domain, None, "{json}");
276        }
277        let loaded: DeployCliConfig = serde_json::from_str(r#"{"labelDomain":"acme.dev"}"#).unwrap();
278        assert_eq!(loaded.label_domain.as_deref(), Some("acme.dev"));
279    }
280
281    /// A package built before the label domain was embedded still loads, with none.
282    #[test]
283    fn a_deploy_cli_config_without_a_label_domain_still_loads() {
284        let loaded: DeployCliConfig = serde_json::from_str(r#"{"name":"example-deploy"}"#).unwrap();
285        assert_eq!(loaded.label_domain, None);
286    }
287
288    #[test]
289    fn test_roundtrip_deploy_cli_config() {
290        let config = DeployCliConfig {
291            token: Some("ax_dg_abc123".into()),
292            deployment_group_id: Some("dg_xyz".into()),
293            display_name: Some("Production".into()),
294            default_platform: Some("aws".into()),
295            api_base_url: Some("https://api.example.com".into()),
296            agent_binary_url: Some("https://packages.example.com/acme/agent".into()),
297            machine_bundle_url: Some(
298                "https://packages.example.com/acme/machine-bundle.json".into(),
299            ),
300            install_script_url: Some("https://packages.example.com/acme/install.sh".into()),
301            setup_revision: Some("build-123".into()),
302            token_env_var: Some("ACME_DEPLOYMENT_TOKEN".into()),
303            name: Some("acme-deploy".into()),
304            label_domain: None,
305        };
306
307        let binary = b"fake binary content";
308        let embedded = append_embedded_config(binary, &config).unwrap();
309
310        let loaded: Option<DeployCliConfig> =
311            load_embedded_config_from_path_bytes(&embedded).unwrap();
312        let loaded = loaded.unwrap();
313
314        assert_eq!(loaded.token, config.token);
315        assert_eq!(loaded.deployment_group_id, config.deployment_group_id);
316        assert_eq!(loaded.default_platform, config.default_platform);
317        assert_eq!(loaded.api_base_url, config.api_base_url);
318        assert_eq!(loaded.agent_binary_url, config.agent_binary_url);
319        assert_eq!(loaded.machine_bundle_url, config.machine_bundle_url);
320        assert_eq!(loaded.install_script_url, config.install_script_url);
321        assert_eq!(loaded.token_env_var, config.token_env_var);
322        assert_eq!(loaded.display_name, config.display_name);
323        assert_eq!(loaded.name, config.name);
324    }
325
326    #[test]
327    fn test_no_embedded_config() {
328        let binary = b"just a regular binary";
329        let result: Option<DeployCliConfig> = load_embedded_config_from_path_bytes(binary).unwrap();
330        assert!(result.is_none());
331    }
332
333    #[test]
334    fn test_roundtrip_operator_config() {
335        let config = OperatorConfig {
336            manager_url: Some("https://manager.example.com".into()),
337            token: Some("ax_dep_operator123".into()),
338            deployment_id: Some("dep_abc".into()),
339            sync_interval_secs: 60,
340            name: Some("acme-operator".into()),
341            brand: Some("acme".into()),
342            display_name: Some("Acme Operator".into()),
343            env_prefix: Some("ACME".into()),
344            label_domain: Some("acme.dev".into()),
345        };
346
347        let binary = b"operator binary";
348        let embedded = append_embedded_config(binary, &config).unwrap();
349
350        let loaded: Option<OperatorConfig> =
351            load_embedded_config_from_path_bytes(&embedded).unwrap();
352        let loaded = loaded.unwrap();
353
354        assert_eq!(loaded.manager_url, config.manager_url);
355        assert_eq!(loaded.deployment_id, config.deployment_id);
356        assert_eq!(loaded.sync_interval_secs, 60);
357        assert_eq!(loaded.name, config.name);
358        assert_eq!(loaded.brand, config.brand);
359        assert_eq!(loaded.display_name, config.display_name);
360        assert_eq!(loaded.env_prefix, config.env_prefix);
361        assert_eq!(loaded.label_domain, config.label_domain);
362    }
363
364    #[test]
365    fn operator_config_roundtrips_through_packaged_file() {
366        let config = OperatorConfig {
367            manager_url: None,
368            token: None,
369            deployment_id: None,
370            sync_interval_secs: 17,
371            name: Some("acme-operator".into()),
372            brand: Some("acme".into()),
373            display_name: Some("Acme Operator".into()),
374            env_prefix: Some("ACME".into()),
375            label_domain: Some("acme.dev".into()),
376        };
377        let path = std::env::temp_dir().join(format!(
378            "alien-operator-config-{}-{}.json",
379            std::process::id(),
380            std::thread::current().name().unwrap_or("test")
381        ));
382        std::fs::write(
383            &path,
384            serde_json::to_vec(&config).expect("serialize operator config"),
385        )
386        .expect("write operator config");
387
388        let loaded: OperatorConfig = load_config_file(&path).expect("load operator config");
389
390        assert_eq!(loaded.sync_interval_secs, 17);
391        assert_eq!(loaded.name.as_deref(), Some("acme-operator"));
392        assert_eq!(loaded.brand.as_deref(), Some("acme"));
393        assert_eq!(loaded.display_name.as_deref(), Some("Acme Operator"));
394        assert_eq!(loaded.env_prefix.as_deref(), Some("ACME"));
395        assert_eq!(loaded.label_domain.as_deref(), Some("acme.dev"));
396        std::fs::remove_file(path).expect("remove operator config");
397    }
398
399    /// Helper that works on in-memory bytes (for tests that don't need files).
400    fn load_embedded_config_from_path_bytes<T: DeserializeOwned>(
401        data: &[u8],
402    ) -> Result<Option<T>, EmbeddedConfigError> {
403        if data.len() < FOOTER_SIZE {
404            return Ok(None);
405        }
406
407        let magic_start = data.len() - MAGIC_BYTES.len();
408        if &data[magic_start..] != MAGIC_BYTES {
409            return Ok(None);
410        }
411
412        let len_start = magic_start - 4;
413        let len_bytes: [u8; 4] = data[len_start..magic_start]
414            .try_into()
415            .map_err(|_| EmbeddedConfigError::InvalidFormat("invalid length bytes".into()))?;
416        let json_len = u32::from_le_bytes(len_bytes) as usize;
417
418        if json_len == 0 || len_start < json_len {
419            return Err(EmbeddedConfigError::InvalidFormat(
420                "config length exceeds binary size".into(),
421            ));
422        }
423
424        let json_start = len_start - json_len;
425        let json_bytes = &data[json_start..len_start];
426
427        let config: T =
428            serde_json::from_slice(json_bytes).map_err(EmbeddedConfigError::Deserialization)?;
429
430        Ok(Some(config))
431    }
432}