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};
9
10/// Magic bytes at the end of a binary with embedded config.
11pub const MAGIC_BYTES: &[u8; 8] = b"WLCFG001";
12
13/// Size of the footer: 4 bytes (length) + 8 bytes (magic).
14pub const FOOTER_SIZE: usize = 12;
15
16/// Configuration embedded in alien-deploy-cli binaries.
17#[derive(Debug, Clone, Serialize, Deserialize)]
18#[serde(rename_all = "camelCase")]
19pub struct DeployCliConfig {
20    // --- Connection (for pre-configured binaries) ---
21    /// Authentication token for the platform/manager API.
22    #[serde(skip_serializing_if = "Option::is_none")]
23    pub token: Option<String>,
24    /// Deployment group ID.
25    #[serde(skip_serializing_if = "Option::is_none")]
26    pub deployment_group_id: Option<String>,
27    /// Default platform for deployments.
28    #[serde(skip_serializing_if = "Option::is_none")]
29    pub default_platform: Option<String>,
30    /// Platform API base URL used for manager discovery.
31    #[serde(skip_serializing_if = "Option::is_none")]
32    pub api_base_url: Option<String>,
33    /// Exact agent binary URL to install for local pull-model deployments.
34    #[serde(skip_serializing_if = "Option::is_none")]
35    pub agent_binary_url: Option<String>,
36    /// Machine bootstrap bundle manifest URL used by `alien-deploy join`.
37    #[serde(skip_serializing_if = "Option::is_none")]
38    pub machine_bundle_url: Option<String>,
39    /// Unix install script URL for this CLI package.
40    #[serde(skip_serializing_if = "Option::is_none")]
41    pub install_script_url: Option<String>,
42    /// Branded environment variable that contains the deployment token.
43    #[serde(skip_serializing_if = "Option::is_none")]
44    pub token_env_var: Option<String>,
45    // --- Branding (for rebranded binaries) ---
46    /// Binary name (e.g., "acme-deploy").
47    #[serde(skip_serializing_if = "Option::is_none")]
48    pub name: Option<String>,
49    /// Human-friendly display name (e.g., "Acme Deploy CLI").
50    #[serde(skip_serializing_if = "Option::is_none")]
51    pub display_name: Option<String>,
52}
53
54/// Configuration embedded in alien-operator binaries.
55#[derive(Debug, Clone, Serialize, Deserialize)]
56#[serde(rename_all = "camelCase")]
57pub struct OperatorConfig {
58    // --- Connection (for pre-configured/OSS binaries) ---
59    /// Manager URL to connect to.
60    #[serde(skip_serializing_if = "Option::is_none")]
61    pub manager_url: Option<String>,
62    /// Authentication token for the manager API.
63    #[serde(skip_serializing_if = "Option::is_none")]
64    pub token: Option<String>,
65    /// Deployment ID this operator manages.
66    #[serde(skip_serializing_if = "Option::is_none")]
67    pub deployment_id: Option<String>,
68    /// Sync interval in seconds (default: 30).
69    #[serde(default = "default_sync_interval")]
70    pub sync_interval_secs: u64,
71    // --- Branding (for rebranded binaries) ---
72    /// Binary name (e.g., "acme-operator").
73    #[serde(skip_serializing_if = "Option::is_none")]
74    pub name: Option<String>,
75    /// Short brand slug used for generated resource names.
76    #[serde(skip_serializing_if = "Option::is_none")]
77    pub brand: Option<String>,
78    /// Human-friendly display name (e.g., "Acme Operator").
79    #[serde(skip_serializing_if = "Option::is_none")]
80    pub display_name: Option<String>,
81    /// Branded environment variable prefix (e.g., "ACME").
82    #[serde(skip_serializing_if = "Option::is_none")]
83    pub env_prefix: Option<String>,
84    /// Branded Kubernetes/cloud label domain (e.g., "acme.dev").
85    #[serde(skip_serializing_if = "Option::is_none")]
86    pub label_domain: Option<String>,
87}
88
89fn default_sync_interval() -> u64 {
90    30
91}
92
93/// Load embedded configuration from the current binary.
94///
95/// Reads the binary's own file, checks for the magic trailer, extracts the
96/// JSON payload, and deserializes it into the requested type.
97///
98/// Returns `None` if the binary has no embedded config (no magic trailer).
99pub fn load_embedded_config<T: DeserializeOwned>() -> Result<Option<T>, EmbeddedConfigError> {
100    let exe_path = std::env::current_exe().map_err(EmbeddedConfigError::Io)?;
101    load_embedded_config_from_path(&exe_path)
102}
103
104/// Load embedded configuration from a specific binary path.
105pub fn load_embedded_config_from_path<T: DeserializeOwned>(
106    path: &std::path::Path,
107) -> Result<Option<T>, EmbeddedConfigError> {
108    let data = std::fs::read(path).map_err(EmbeddedConfigError::Io)?;
109
110    if data.len() < FOOTER_SIZE {
111        return Ok(None);
112    }
113
114    // Check magic bytes at the end
115    let magic_start = data.len() - MAGIC_BYTES.len();
116    if &data[magic_start..] != MAGIC_BYTES {
117        return Ok(None);
118    }
119
120    // Read the 4-byte little-endian length before the magic
121    let len_start = magic_start - 4;
122    let len_bytes: [u8; 4] = data[len_start..magic_start]
123        .try_into()
124        .map_err(|_| EmbeddedConfigError::InvalidFormat("invalid length bytes".into()))?;
125    let json_len = u32::from_le_bytes(len_bytes) as usize;
126
127    if json_len == 0 || len_start < json_len {
128        return Err(EmbeddedConfigError::InvalidFormat(
129            "config length exceeds binary size".into(),
130        ));
131    }
132
133    let json_start = len_start - json_len;
134    let json_bytes = &data[json_start..len_start];
135
136    let config: T =
137        serde_json::from_slice(json_bytes).map_err(EmbeddedConfigError::Deserialization)?;
138
139    Ok(Some(config))
140}
141
142/// Append embedded configuration to a binary.
143///
144/// Writes: original binary bytes + JSON payload + 4-byte LE length + magic bytes.
145pub fn append_embedded_config<T: Serialize>(
146    binary_data: &[u8],
147    config: &T,
148) -> Result<Vec<u8>, EmbeddedConfigError> {
149    let json_bytes = serde_json::to_vec(config).map_err(EmbeddedConfigError::Deserialization)?;
150    let json_len = json_bytes.len() as u32;
151
152    let mut result = Vec::with_capacity(binary_data.len() + json_bytes.len() + FOOTER_SIZE);
153    result.extend_from_slice(binary_data);
154    result.extend_from_slice(&json_bytes);
155    result.extend_from_slice(&json_len.to_le_bytes());
156    result.extend_from_slice(MAGIC_BYTES);
157
158    Ok(result)
159}
160
161/// Errors from embedded config operations.
162#[derive(Debug)]
163pub enum EmbeddedConfigError {
164    Io(std::io::Error),
165    InvalidFormat(String),
166    Deserialization(serde_json::Error),
167}
168
169impl std::fmt::Display for EmbeddedConfigError {
170    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
171        match self {
172            Self::Io(e) => write!(f, "IO error reading embedded config: {}", e),
173            Self::InvalidFormat(msg) => write!(f, "invalid embedded config format: {}", msg),
174            Self::Deserialization(e) => write!(f, "failed to deserialize embedded config: {}", e),
175        }
176    }
177}
178
179impl std::error::Error for EmbeddedConfigError {}
180
181#[cfg(test)]
182mod tests {
183    use super::*;
184
185    #[test]
186    fn test_roundtrip_deploy_cli_config() {
187        let config = DeployCliConfig {
188            token: Some("ax_dg_abc123".into()),
189            deployment_group_id: Some("dg_xyz".into()),
190            display_name: Some("Production".into()),
191            default_platform: Some("aws".into()),
192            api_base_url: Some("https://api.example.com".into()),
193            agent_binary_url: Some("https://packages.example.com/acme/agent".into()),
194            machine_bundle_url: Some(
195                "https://packages.example.com/acme/machine-bundle.json".into(),
196            ),
197            install_script_url: Some("https://packages.example.com/acme/install.sh".into()),
198            token_env_var: Some("ACME_DEPLOYMENT_TOKEN".into()),
199            name: Some("acme-deploy".into()),
200        };
201
202        let binary = b"fake binary content";
203        let embedded = append_embedded_config(binary, &config).unwrap();
204
205        let loaded: Option<DeployCliConfig> =
206            load_embedded_config_from_path_bytes(&embedded).unwrap();
207        let loaded = loaded.unwrap();
208
209        assert_eq!(loaded.token, config.token);
210        assert_eq!(loaded.deployment_group_id, config.deployment_group_id);
211        assert_eq!(loaded.default_platform, config.default_platform);
212        assert_eq!(loaded.api_base_url, config.api_base_url);
213        assert_eq!(loaded.agent_binary_url, config.agent_binary_url);
214        assert_eq!(loaded.machine_bundle_url, config.machine_bundle_url);
215        assert_eq!(loaded.install_script_url, config.install_script_url);
216        assert_eq!(loaded.token_env_var, config.token_env_var);
217        assert_eq!(loaded.display_name, config.display_name);
218        assert_eq!(loaded.name, config.name);
219    }
220
221    #[test]
222    fn test_no_embedded_config() {
223        let binary = b"just a regular binary";
224        let result: Option<DeployCliConfig> = load_embedded_config_from_path_bytes(binary).unwrap();
225        assert!(result.is_none());
226    }
227
228    #[test]
229    fn test_roundtrip_operator_config() {
230        let config = OperatorConfig {
231            manager_url: Some("https://manager.example.com".into()),
232            token: Some("ax_dep_operator123".into()),
233            deployment_id: Some("dep_abc".into()),
234            sync_interval_secs: 60,
235            name: Some("acme-operator".into()),
236            brand: Some("acme".into()),
237            display_name: Some("Acme Operator".into()),
238            env_prefix: Some("ACME".into()),
239            label_domain: Some("acme.dev".into()),
240        };
241
242        let binary = b"operator binary";
243        let embedded = append_embedded_config(binary, &config).unwrap();
244
245        let loaded: Option<OperatorConfig> =
246            load_embedded_config_from_path_bytes(&embedded).unwrap();
247        let loaded = loaded.unwrap();
248
249        assert_eq!(loaded.manager_url, config.manager_url);
250        assert_eq!(loaded.deployment_id, config.deployment_id);
251        assert_eq!(loaded.sync_interval_secs, 60);
252        assert_eq!(loaded.name, config.name);
253        assert_eq!(loaded.brand, config.brand);
254        assert_eq!(loaded.display_name, config.display_name);
255        assert_eq!(loaded.env_prefix, config.env_prefix);
256        assert_eq!(loaded.label_domain, config.label_domain);
257    }
258
259    /// Helper that works on in-memory bytes (for tests that don't need files).
260    fn load_embedded_config_from_path_bytes<T: DeserializeOwned>(
261        data: &[u8],
262    ) -> Result<Option<T>, EmbeddedConfigError> {
263        if data.len() < FOOTER_SIZE {
264            return Ok(None);
265        }
266
267        let magic_start = data.len() - MAGIC_BYTES.len();
268        if &data[magic_start..] != MAGIC_BYTES {
269            return Ok(None);
270        }
271
272        let len_start = magic_start - 4;
273        let len_bytes: [u8; 4] = data[len_start..magic_start]
274            .try_into()
275            .map_err(|_| EmbeddedConfigError::InvalidFormat("invalid length bytes".into()))?;
276        let json_len = u32::from_le_bytes(len_bytes) as usize;
277
278        if json_len == 0 || len_start < json_len {
279            return Err(EmbeddedConfigError::InvalidFormat(
280                "config length exceeds binary size".into(),
281            ));
282        }
283
284        let json_start = len_start - json_len;
285        let json_bytes = &data[json_start..len_start];
286
287        let config: T =
288            serde_json::from_slice(json_bytes).map_err(EmbeddedConfigError::Deserialization)?;
289
290        Ok(Some(config))
291    }
292}