alien-core 3.3.73

Deploy software into your customers' cloud accounts and keep it fully managed
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//! Embedded configuration support for alien-deploy-cli and alien-operator binaries.
//!
//! The package builder appends a JSON-encoded config struct to the end of the
//! binary, followed by a 4-byte little-endian length and 8-byte magic trailer.
//! This allows a single binary to be customized per deployment group without
//! recompilation.

use serde::{de::DeserializeOwned, Deserialize, Serialize};
use std::path::Path;

/// Default location of the operator configuration packaged in a container image.
pub const OPERATOR_CONFIG_PATH: &str = "/etc/alien/operator-config.json";

/// Magic bytes at the end of a binary with embedded config.
pub const MAGIC_BYTES: &[u8; 8] = b"WLCFG001";

/// Size of the footer: 4 bytes (length) + 8 bytes (magic).
pub const FOOTER_SIZE: usize = 12;

/// Configuration embedded in alien-deploy-cli binaries.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DeployCliConfig {
    // --- Connection (for pre-configured binaries) ---
    /// Authentication token for the platform/manager API.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub token: Option<String>,
    /// Deployment group ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deployment_group_id: Option<String>,
    /// Default platform for deployments.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default_platform: Option<String>,
    /// Platform API base URL used for manager discovery.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub api_base_url: Option<String>,
    /// Exact agent binary URL to install for local pull-model deployments.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub agent_binary_url: Option<String>,
    /// Machine bootstrap bundle manifest URL used by `alien-deploy join`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub machine_bundle_url: Option<String>,
    /// Unix install script URL for this CLI package.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub install_script_url: Option<String>,
    /// Package build revision for setup-affecting code and artifacts. Existing
    /// direct-setup deployments reconcile setup once when this value changes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub setup_revision: Option<String>,
    /// Branded environment variable that contains the deployment token.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub token_env_var: Option<String>,
    // --- Branding (for rebranded binaries) ---
    /// Binary name (e.g., "acme-deploy").
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Human-friendly display name (e.g., "Acme Deploy CLI").
    #[serde(skip_serializing_if = "Option::is_none")]
    pub display_name: Option<String>,
    /// Branded Kubernetes label domain (e.g., "acme.dev") the installs of this package carry on
    /// their objects. A delete run from this binary uses it to recognise those objects.
    /// An empty value reads as none, so every user of it (the runtime cleanup and the listing
    /// of what it left) agrees on the default domain.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "non_empty_text"
    )]
    pub label_domain: Option<String>,
}

fn non_empty_text<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let value: Option<String> = serde::Deserialize::deserialize(deserializer)?;
    Ok(value.filter(|text| !text.trim().is_empty()))
}

/// Configuration embedded in alien-operator binaries.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OperatorConfig {
    // --- Connection (for pre-configured/OSS binaries) ---
    /// Manager URL to connect to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub manager_url: Option<String>,
    /// Authentication token for the manager API.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub token: Option<String>,
    /// Deployment ID this operator manages.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deployment_id: Option<String>,
    /// Sync interval in seconds (default: 30).
    #[serde(default = "default_sync_interval")]
    pub sync_interval_secs: u64,
    // --- Branding (for rebranded binaries) ---
    /// Binary name (e.g., "acme-operator").
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Short brand slug used for generated resource names.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub brand: Option<String>,
    /// Human-friendly display name (e.g., "Acme Operator").
    #[serde(skip_serializing_if = "Option::is_none")]
    pub display_name: Option<String>,
    /// Branded environment variable prefix (e.g., "ACME").
    #[serde(skip_serializing_if = "Option::is_none")]
    pub env_prefix: Option<String>,
    /// Branded Kubernetes/cloud label domain (e.g., "acme.dev").
    #[serde(skip_serializing_if = "Option::is_none")]
    pub label_domain: Option<String>,
}

fn default_sync_interval() -> u64 {
    30
}

/// Load embedded configuration from the current binary.
///
/// Reads the binary's own file, checks for the magic trailer, extracts the
/// JSON payload, and deserializes it into the requested type.
///
/// Returns `None` if the binary has no embedded config (no magic trailer).
pub fn load_embedded_config<T: DeserializeOwned>() -> Result<Option<T>, EmbeddedConfigError> {
    let exe_path = std::env::current_exe().map_err(EmbeddedConfigError::Io)?;
    load_embedded_config_from_path(&exe_path)
}

/// Load a JSON configuration file.
pub fn load_config_file<T: DeserializeOwned>(path: &Path) -> Result<T, EmbeddedConfigError> {
    let data = std::fs::read(path).map_err(EmbeddedConfigError::Io)?;
    serde_json::from_slice(&data).map_err(EmbeddedConfigError::Deserialization)
}

/// Load embedded configuration from a specific binary path.
pub fn load_embedded_config_from_path<T: DeserializeOwned>(
    path: &std::path::Path,
) -> Result<Option<T>, EmbeddedConfigError> {
    let data = std::fs::read(path).map_err(EmbeddedConfigError::Io)?;

    if data.len() < FOOTER_SIZE {
        return Ok(None);
    }

    // Check magic bytes at the end
    let magic_start = data.len() - MAGIC_BYTES.len();
    if &data[magic_start..] != MAGIC_BYTES {
        return Ok(None);
    }

    // Read the 4-byte little-endian length before the magic
    let len_start = magic_start - 4;
    let len_bytes: [u8; 4] = data[len_start..magic_start]
        .try_into()
        .map_err(|_| EmbeddedConfigError::InvalidFormat("invalid length bytes".into()))?;
    let json_len = u32::from_le_bytes(len_bytes) as usize;

    if json_len == 0 || len_start < json_len {
        return Err(EmbeddedConfigError::InvalidFormat(
            "config length exceeds binary size".into(),
        ));
    }

    let json_start = len_start - json_len;
    let json_bytes = &data[json_start..len_start];

    let config: T =
        serde_json::from_slice(json_bytes).map_err(EmbeddedConfigError::Deserialization)?;

    Ok(Some(config))
}

/// Append embedded configuration to a binary.
///
/// Writes: original binary bytes + JSON payload + 4-byte LE length + magic bytes.
pub fn append_embedded_config<T: Serialize>(
    binary_data: &[u8],
    config: &T,
) -> Result<Vec<u8>, EmbeddedConfigError> {
    let trailer = encode_embedded_config_trailer(config)?;

    let mut result = Vec::with_capacity(binary_data.len() + trailer.len());
    result.extend_from_slice(binary_data);
    result.extend_from_slice(&trailer);

    Ok(result)
}

/// Encode the self-contained trailer appended to a binary with embedded config.
///
/// Writes: JSON payload + 4-byte LE length + magic bytes. Keeping this separate
/// lets object stores compose an existing binary with a small configuration
/// object without downloading and uploading the binary again.
pub fn encode_embedded_config_trailer<T: Serialize>(
    config: &T,
) -> Result<Vec<u8>, EmbeddedConfigError> {
    let json_bytes = serde_json::to_vec(config).map_err(EmbeddedConfigError::Deserialization)?;
    let json_len = json_bytes.len() as u32;

    let mut result = Vec::with_capacity(json_bytes.len() + FOOTER_SIZE);
    result.extend_from_slice(&json_bytes);
    result.extend_from_slice(&json_len.to_le_bytes());
    result.extend_from_slice(MAGIC_BYTES);

    Ok(result)
}

/// Errors from embedded config operations.
#[derive(Debug)]
pub enum EmbeddedConfigError {
    Io(std::io::Error),
    InvalidFormat(String),
    Deserialization(serde_json::Error),
}

impl std::fmt::Display for EmbeddedConfigError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Io(e) => write!(f, "IO error reading embedded config: {}", e),
            Self::InvalidFormat(msg) => write!(f, "invalid embedded config format: {}", msg),
            Self::Deserialization(e) => write!(f, "failed to deserialize embedded config: {}", e),
        }
    }
}

impl std::error::Error for EmbeddedConfigError {}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn encoded_trailer_matches_append_output_exactly() {
        let config = DeployCliConfig {
            token: Some("secret".into()),
            deployment_group_id: Some("dg_123".into()),
            default_platform: Some("aws".into()),
            api_base_url: Some("https://api.example.com".into()),
            agent_binary_url: None,
            machine_bundle_url: None,
            install_script_url: None,
            setup_revision: Some("revision".into()),
            token_env_var: Some("EXAMPLE_TOKEN".into()),
            name: Some("example-deploy".into()),
            display_name: Some("Example Deploy".into()),
            label_domain: Some("example.dev".into()),
        };
        let binary = b"an existing executable";

        let appended = append_embedded_config(binary, &config).expect("config should append");
        let trailer = encode_embedded_config_trailer(&config).expect("trailer should encode");

        assert_eq!(appended, [binary.as_slice(), trailer.as_slice()].concat());

        let loaded: DeployCliConfig = load_embedded_config_from_path_bytes(&appended)
            .expect("appended config should parse")
            .expect("appended config should exist");
        assert_eq!(loaded.token, config.token);
        assert_eq!(loaded.deployment_group_id, config.deployment_group_id);
        assert_eq!(loaded.setup_revision, config.setup_revision);
        assert_eq!(loaded.name, config.name);
        assert_eq!(loaded.label_domain.as_deref(), Some("example.dev"));
    }

    /// An empty label domain is none, not a domain of its own.
    #[test]
    fn an_empty_label_domain_reads_as_none() {
        for json in [
            r#"{"labelDomain":""}"#,
            r#"{"labelDomain":"  "}"#,
            r#"{"labelDomain":null}"#,
        ] {
            let loaded: DeployCliConfig = serde_json::from_str(json).unwrap();
            assert_eq!(loaded.label_domain, None, "{json}");
        }
        let loaded: DeployCliConfig = serde_json::from_str(r#"{"labelDomain":"acme.dev"}"#).unwrap();
        assert_eq!(loaded.label_domain.as_deref(), Some("acme.dev"));
    }

    /// A package built before the label domain was embedded still loads, with none.
    #[test]
    fn a_deploy_cli_config_without_a_label_domain_still_loads() {
        let loaded: DeployCliConfig = serde_json::from_str(r#"{"name":"example-deploy"}"#).unwrap();
        assert_eq!(loaded.label_domain, None);
    }

    #[test]
    fn test_roundtrip_deploy_cli_config() {
        let config = DeployCliConfig {
            token: Some("ax_dg_abc123".into()),
            deployment_group_id: Some("dg_xyz".into()),
            display_name: Some("Production".into()),
            default_platform: Some("aws".into()),
            api_base_url: Some("https://api.example.com".into()),
            agent_binary_url: Some("https://packages.example.com/acme/agent".into()),
            machine_bundle_url: Some(
                "https://packages.example.com/acme/machine-bundle.json".into(),
            ),
            install_script_url: Some("https://packages.example.com/acme/install.sh".into()),
            setup_revision: Some("build-123".into()),
            token_env_var: Some("ACME_DEPLOYMENT_TOKEN".into()),
            name: Some("acme-deploy".into()),
            label_domain: None,
        };

        let binary = b"fake binary content";
        let embedded = append_embedded_config(binary, &config).unwrap();

        let loaded: Option<DeployCliConfig> =
            load_embedded_config_from_path_bytes(&embedded).unwrap();
        let loaded = loaded.unwrap();

        assert_eq!(loaded.token, config.token);
        assert_eq!(loaded.deployment_group_id, config.deployment_group_id);
        assert_eq!(loaded.default_platform, config.default_platform);
        assert_eq!(loaded.api_base_url, config.api_base_url);
        assert_eq!(loaded.agent_binary_url, config.agent_binary_url);
        assert_eq!(loaded.machine_bundle_url, config.machine_bundle_url);
        assert_eq!(loaded.install_script_url, config.install_script_url);
        assert_eq!(loaded.token_env_var, config.token_env_var);
        assert_eq!(loaded.display_name, config.display_name);
        assert_eq!(loaded.name, config.name);
    }

    #[test]
    fn test_no_embedded_config() {
        let binary = b"just a regular binary";
        let result: Option<DeployCliConfig> = load_embedded_config_from_path_bytes(binary).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_roundtrip_operator_config() {
        let config = OperatorConfig {
            manager_url: Some("https://manager.example.com".into()),
            token: Some("ax_dep_operator123".into()),
            deployment_id: Some("dep_abc".into()),
            sync_interval_secs: 60,
            name: Some("acme-operator".into()),
            brand: Some("acme".into()),
            display_name: Some("Acme Operator".into()),
            env_prefix: Some("ACME".into()),
            label_domain: Some("acme.dev".into()),
        };

        let binary = b"operator binary";
        let embedded = append_embedded_config(binary, &config).unwrap();

        let loaded: Option<OperatorConfig> =
            load_embedded_config_from_path_bytes(&embedded).unwrap();
        let loaded = loaded.unwrap();

        assert_eq!(loaded.manager_url, config.manager_url);
        assert_eq!(loaded.deployment_id, config.deployment_id);
        assert_eq!(loaded.sync_interval_secs, 60);
        assert_eq!(loaded.name, config.name);
        assert_eq!(loaded.brand, config.brand);
        assert_eq!(loaded.display_name, config.display_name);
        assert_eq!(loaded.env_prefix, config.env_prefix);
        assert_eq!(loaded.label_domain, config.label_domain);
    }

    #[test]
    fn operator_config_roundtrips_through_packaged_file() {
        let config = OperatorConfig {
            manager_url: None,
            token: None,
            deployment_id: None,
            sync_interval_secs: 17,
            name: Some("acme-operator".into()),
            brand: Some("acme".into()),
            display_name: Some("Acme Operator".into()),
            env_prefix: Some("ACME".into()),
            label_domain: Some("acme.dev".into()),
        };
        let path = std::env::temp_dir().join(format!(
            "alien-operator-config-{}-{}.json",
            std::process::id(),
            std::thread::current().name().unwrap_or("test")
        ));
        std::fs::write(
            &path,
            serde_json::to_vec(&config).expect("serialize operator config"),
        )
        .expect("write operator config");

        let loaded: OperatorConfig = load_config_file(&path).expect("load operator config");

        assert_eq!(loaded.sync_interval_secs, 17);
        assert_eq!(loaded.name.as_deref(), Some("acme-operator"));
        assert_eq!(loaded.brand.as_deref(), Some("acme"));
        assert_eq!(loaded.display_name.as_deref(), Some("Acme Operator"));
        assert_eq!(loaded.env_prefix.as_deref(), Some("ACME"));
        assert_eq!(loaded.label_domain.as_deref(), Some("acme.dev"));
        std::fs::remove_file(path).expect("remove operator config");
    }

    /// Helper that works on in-memory bytes (for tests that don't need files).
    fn load_embedded_config_from_path_bytes<T: DeserializeOwned>(
        data: &[u8],
    ) -> Result<Option<T>, EmbeddedConfigError> {
        if data.len() < FOOTER_SIZE {
            return Ok(None);
        }

        let magic_start = data.len() - MAGIC_BYTES.len();
        if &data[magic_start..] != MAGIC_BYTES {
            return Ok(None);
        }

        let len_start = magic_start - 4;
        let len_bytes: [u8; 4] = data[len_start..magic_start]
            .try_into()
            .map_err(|_| EmbeddedConfigError::InvalidFormat("invalid length bytes".into()))?;
        let json_len = u32::from_le_bytes(len_bytes) as usize;

        if json_len == 0 || len_start < json_len {
            return Err(EmbeddedConfigError::InvalidFormat(
                "config length exceeds binary size".into(),
            ));
        }

        let json_start = len_start - json_len;
        let json_bytes = &data[json_start..len_start];

        let config: T =
            serde_json::from_slice(json_bytes).map_err(EmbeddedConfigError::Deserialization)?;

        Ok(Some(config))
    }
}