cloudpub-client 3.6.915

CloudPub CLI client for secure tunnel and service publishing
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
use anyhow::{bail, Context, Result};
use cloudpub_common::constants::DEFAULT_HEARTBEAT_TIMEOUT_SECS;
use cloudpub_common::{DOMAIN, PORT};
use serde::{Deserialize, Serialize};
use std::fmt::{Debug, Display, Formatter};
use std::str::FromStr;

use crate::options::ConfigOption;
pub use cloudpub_common::config::{MaskedString, TransportConfig};
use lazy_static::lazy_static;
#[cfg(not(target_os = "android"))]
use machineid_rs::{Encryption, HWIDComponent, IdBuilder};
use std::collections::HashMap;
use std::fs::{self, create_dir_all, File};
use std::io::Write;
use std::path::PathBuf;
use tracing::debug;
use url::Url;
use uuid::Uuid;

#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum Platform {
    #[default]
    X64,
    X32,
    Aarch64,
    Arm,
}

/// The platform entry that describes this architecture (CLOUDPUB-610).
///
/// Architecture, not pointer width: both x86_64 and aarch64 are 64-bit, and
/// picking on width alone is what sent 64-bit ARM agents the x86_64 httpd
/// bundle. Anything unrecognised keeps the historical answer - the download
/// then fails as it did before, rather than the agent refusing to start.
pub fn platform_for_arch(arch: &str) -> Platform {
    match arch {
        "aarch64" => Platform::Aarch64,
        // std::env::consts::ARCH for every 32-bit ARM, armv7 included.
        "arm" => Platform::Arm,
        _ => Platform::X64,
    }
}

#[derive(Clone)]
pub struct EnvConfig {
    pub home_1c: PathBuf,
    #[cfg(target_os = "windows")]
    pub redist: String,
    pub httpd: String,
    pub httpd_dir: String,
}

impl Default for EnvConfig {
    fn default() -> Self {
        // On Linux the architecture decides, and the entries carry no
        // target_arch gate, so the whole table is present at runtime and a
        // unit test on an x86_64 host can check the choice itself
        // (CLOUDPUB-610). The other systems keep the pointer-width answer:
        // their tables describe one architecture each - macOS in particular
        // has a single entry that covers Apple Silicon too.
        #[cfg(target_os = "linux")]
        return ENV_CONFIG
            .get(&platform_for_arch(std::env::consts::ARCH))
            .unwrap()
            .clone();
        #[cfg(all(not(target_os = "linux"), target_pointer_width = "64"))]
        return ENV_CONFIG.get(&Platform::X64).unwrap().clone();
        #[cfg(all(not(target_os = "linux"), target_pointer_width = "32"))]
        return ENV_CONFIG.get(&Platform::X32).unwrap().clone();
    }
}

lazy_static! {
    pub static ref ENV_CONFIG: HashMap<Platform, EnvConfig> = {
        let mut m = HashMap::new();
        #[cfg(target_os = "windows")]
        m.insert(
            Platform::X64,
            EnvConfig {
                home_1c: PathBuf::from("C:\\Program Files\\1cv8\\"),
                redist: "vc_redist.x64.exe".to_string(),
                httpd: "httpd-2.4.61-240703-win64-VS17.zip".to_string(),
                httpd_dir: "httpd-x64".to_string(),
            },
        );
        #[cfg(target_os = "windows")]
        m.insert(
            Platform::X32,
            EnvConfig {
                home_1c: PathBuf::from("C:\\Program Files (x86)\\1cv8"),
                redist: "vc_redist.x86.exe".to_string(),
                httpd: "httpd-2.4.61-240703-win32-vs17.zip".to_string(),
                httpd_dir: "httpd-x32".to_string(),
            },
        );
        #[cfg(target_os = "linux")]
        m.insert(
            Platform::X64,
            EnvConfig {
                home_1c: PathBuf::from("/opt/1C"),
                httpd: "httpd-2.4.68-linux.zip".to_string(),
                httpd_dir: "httpd-x64".to_string(),
            },
        );
        // No target_arch gate on these, deliberately: the table is data, and
        // keeping all of it compiled everywhere is what lets the choice be
        // tested on any host (CLOUDPUB-610). Each architecture unpacks into a
        // directory of its own - setup_httpd reads installed.txt inside it as
        // "already unpacked" without checking which bundle put it there, so a
        // shared directory would serve one architecture's binaries to another.
        #[cfg(target_os = "linux")]
        m.insert(
            Platform::Aarch64,
            EnvConfig {
                home_1c: PathBuf::from("/opt/1C"),
                httpd: "httpd-2.4.68-aarch64-linux.zip".to_string(),
                httpd_dir: "httpd-aarch64".to_string(),
            },
        );
        #[cfg(target_os = "linux")]
        m.insert(
            Platform::Arm,
            EnvConfig {
                home_1c: PathBuf::from("/opt/1C"),
                httpd: "httpd-2.4.68-arm-linux.zip".to_string(),
                httpd_dir: "httpd-arm".to_string(),
            },
        );
        #[cfg(target_os = "macos")]
        m.insert(
            Platform::X64,
            EnvConfig {
                home_1c: PathBuf::from("/Applications/1C"),
                httpd: "httpd-2.4.62-macos.zip".to_string(),
                httpd_dir: "httpd-x64".to_string(),
            },
        );
        #[cfg(target_os = "android")]
        m.insert(
            Platform::X64,
            EnvConfig {
                home_1c: PathBuf::from("/data/local/tmp"),
                httpd: String::new(),
                httpd_dir: String::new(),
            },
        );
        m
    };
}

impl Display for Platform {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        match self {
            Platform::X64 => write!(f, "x64"),
            Platform::X32 => write!(f, "x32"),
            Platform::Aarch64 => write!(f, "aarch64"),
            Platform::Arm => write!(f, "arm"),
        }
    }
}

impl std::str::FromStr for Platform {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self> {
        match s {
            "x64" => Ok(Platform::X64),
            "x32" => Ok(Platform::X32),
            "aarch64" => Ok(Platform::Aarch64),
            "arm" => Ok(Platform::Arm),
            _ => bail!("Invalid platform: {}", s),
        }
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Default)]
pub struct ClientOpts {
    pub gui: bool,
    pub credentials: Option<(String, String)>,
    pub transient: bool,
    pub secondary: bool,
    pub is_service: bool,
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
pub struct ClientConfig {
    // This fields are not persistent
    #[serde(skip)]
    config_path: PathBuf,
    #[serde(skip)]
    pub readonly: bool,
    pub agent_id: String,
    pub hwid: Option<String>,
    pub server: Url,
    pub token: Option<MaskedString>,
    pub heartbeat_timeout: u64,
    pub one_c_home: Option<String>,
    pub one_c_platform: Option<Platform>,
    pub one_c_publish_dir: Option<String>,
    pub minecraft_server: Option<String>,
    pub minecraft_java_opts: Option<String>,
    pub minimize_to_tray_on_close: Option<bool>,
    pub minimize_to_tray_on_start: Option<bool>,
    pub transport: TransportConfig,
}

impl ClientConfig {
    pub fn get_config_path(&self) -> &PathBuf {
        &self.config_path
    }

    pub fn from_file(path: &PathBuf, readonly: bool) -> Result<Self> {
        if !path.exists() && !readonly {
            let default_config = Self::default();
            debug!("Creating default config at {:?}", default_config);
            let s = toml::to_string_pretty(&default_config)
                .context("Failed to serialize the default config")?;
            fs::write(path, s).context("Failed to write the default config")?;
        }

        let s: String = fs::read_to_string(path)
            .with_context(|| format!("Failed to read the config {:?}", path))?;
        let mut cfg: Self = toml::from_str(&s).with_context(|| {
            "Configuration is invalid. Please refer to the configuration specification."
        })?;

        cfg.config_path = path.clone();
        cfg.readonly = readonly;
        Ok(cfg)
    }

    pub fn get_config_dir(user_dir: bool) -> Result<PathBuf> {
        let dir = if user_dir {
            let mut dir = dirs::config_dir().context("Can't get config_dir")?;
            dir.push("cloudpub");
            dir
        } else if cfg!(target_family = "unix") {
            PathBuf::from("./etc/cloudpub")
        } else {
            PathBuf::from("C:\\Windows\\system32\\config\\systemprofile\\AppData\\Local\\cloudpub")
        };
        if !dir.exists() {
            create_dir_all(&dir).context("Can't create config dir")?;
        }
        debug!("Config dir: {:?}", dir);
        Ok(dir)
    }

    pub fn save(&self) -> Result<()> {
        if self.readonly {
            debug!("Skipping saving the config in readonly mode");
        } else {
            let s = toml::to_string_pretty(self).context("Failed to serialize the config")?;
            let mut f = File::create(&self.config_path)?;
            f.write_all(s.as_bytes())?;
            f.sync_all()?;
        }
        Ok(())
    }

    pub fn load(cfg_name: &str, user_dir: bool, readonly: bool) -> Result<Self> {
        let mut config_path = Self::get_config_dir(user_dir)?;
        config_path.push(cfg_name);

        Self::from_file(&config_path, readonly)
    }

    pub fn set(&mut self, key: &str, value: &str) -> Result<()> {
        let option = ConfigOption::from_str(key)?;
        self.set_option(option, value)
    }

    pub fn get(&self, key: &str) -> Result<String> {
        let option = ConfigOption::from_str(key)?;
        self.get_option(option)
    }

    pub fn get_all_options(&self) -> Vec<(String, String)> {
        self.get_all_config_options()
    }

    pub fn validate(&self) -> Result<()> {
        if self.token.is_none() {
            bail!("{}", crate::t!("error-auth-missing"));
        }
        TransportConfig::validate(&self.transport, false)?;
        Ok(())
    }

    #[cfg(not(target_os = "android"))]
    pub fn get_hwid(&self) -> String {
        self.hwid
            .as_ref()
            .unwrap_or(
                &IdBuilder::new(Encryption::SHA256)
                    .add_component(HWIDComponent::OSName)
                    .add_component(HWIDComponent::SystemID)
                    .add_component(HWIDComponent::MachineName)
                    .add_component(HWIDComponent::CPUID)
                    .build("cloudpub")
                    .unwrap_or(self.agent_id.clone()),
            )
            .to_string()
    }

    #[cfg(target_os = "android")]
    pub fn get_hwid(&self) -> String {
        self.hwid.as_ref().unwrap_or(&self.agent_id).to_string()
    }
}

impl Default for ClientConfig {
    fn default() -> Self {
        Self {
            agent_id: Uuid::new_v4().to_string(),
            hwid: None,
            config_path: PathBuf::new(),
            server: format!("https://{}:{}", DOMAIN.as_str(), *PORT)
                .parse()
                .unwrap(),
            token: None,
            heartbeat_timeout: DEFAULT_HEARTBEAT_TIMEOUT_SECS,
            one_c_home: None,
            one_c_platform: None,
            one_c_publish_dir: None,
            minecraft_server: None,
            minecraft_java_opts: None,
            minimize_to_tray_on_close: Some(true),
            minimize_to_tray_on_start: Some(false),
            transport: TransportConfig::default(),
            readonly: false,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{platform_for_arch, Platform, ENV_CONFIG};
    use regex::Regex;

    /// The httpd bundle and the VC redistributable are fetched by the agent
    /// from its own server (`{server}download/{file}`, see plugins/httpd.rs),
    /// so an on-prem image has to ship every file this table names. It used to
    /// ship none of them: the bundle was downloaded into the Dockerfile's test
    /// stage only, and WebDAV publication failed with "Failed to setup plugin"
    /// on a fresh deployment (CLOUDPUB-1231).
    ///
    /// The literals are read out of this file's own source rather than out of
    /// ENV_CONFIG, because the entries are `cfg(target_os)` gated and only the
    /// host platform's one exists at runtime.
    /// STATUS: FIXED - see the client release artifacts step in the `server`
    /// stage of server/Dockerfile
    /// Every bundle the platform table names.
    ///
    /// The literals are read out of this file's own source rather than out of
    /// ENV_CONFIG, because the entries are `cfg(target_os)` gated and only the
    /// host platform's one exists at runtime.
    fn plugin_bundles() -> Vec<&'static str> {
        let config = include_str!("config.rs");
        let literal = Regex::new(r#"(?:httpd|redist):\s*"([^"]+)"#).unwrap();
        let bundles: Vec<&str> = literal
            .captures_iter(config)
            .filter_map(|c| c.get(1))
            .map(|m| m.as_str())
            .filter(|name| !name.is_empty())
            .collect();
        assert!(
            bundles.len() >= 6,
            "expected the platform table to name at least 6 bundles, found {bundles:?}"
        );
        bundles
    }

    /// The bundle an agent asks for is chosen by architecture, not by pointer
    /// width - see CLOUDPUB-610.
    ///
    /// Before this, Platform knew only X64 and X32 and Default picked between
    /// them on target_pointer_width, so a 64-bit ARM agent - Raspberry Pi 4/5,
    /// an ARM NAS, the latest-arm64 container - asked for the x86_64 bundle
    /// and got an httpd it could not execute. WebDAV was simply unavailable
    /// there.
    ///
    /// The linux entries carry no target_arch gate, which is what lets this
    /// test read all of them on an x86_64 host and check the choice itself
    /// rather than the one entry the host happens to compile.
    #[test]
    fn each_linux_arch_maps_to_its_own_platform() {
        assert_eq!(platform_for_arch("x86_64"), Platform::X64);
        assert_eq!(platform_for_arch("aarch64"), Platform::Aarch64);
        // std::env::consts::ARCH is "arm" for 32-bit ARM, armv7 included.
        assert_eq!(platform_for_arch("arm"), Platform::Arm);
    }

    /// An unknown architecture keeps the historical answer rather than
    /// refusing to start: the worst case is the download failing, which is
    /// where it was before this change anyway.
    #[test]
    fn an_unknown_arch_falls_back_to_x64() {
        assert_eq!(platform_for_arch("riscv64"), Platform::X64);
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn every_linux_arch_has_a_bundle_and_a_cache_dir_of_its_own() {
        let x64 = ENV_CONFIG.get(&Platform::X64).unwrap();
        let aarch64 = ENV_CONFIG.get(&Platform::Aarch64).unwrap();
        let arm = ENV_CONFIG.get(&Platform::Arm).unwrap();

        assert_eq!(aarch64.httpd, "httpd-2.4.68-aarch64-linux.zip");
        assert_eq!(arm.httpd, "httpd-2.4.68-arm-linux.zip");

        // The cache directory must differ per architecture. setup_httpd takes
        // installed.txt inside it as "already unpacked" and never looks at
        // which bundle produced it, so a shared directory would hand an ARM
        // agent the x86_64 binaries left by an earlier attempt.
        assert_eq!(x64.httpd_dir, "httpd-x64");
        assert_eq!(aarch64.httpd_dir, "httpd-aarch64");
        assert_eq!(arm.httpd_dir, "httpd-arm");
        let dirs = [&x64.httpd_dir, &aarch64.httpd_dir, &arm.httpd_dir];
        assert_eq!(
            dirs.iter().collect::<std::collections::HashSet<_>>().len(),
            3,
            "two architectures share a cache directory"
        );
    }

    #[test]
    fn every_plugin_bundle_is_shipped_in_the_server_image() {
        let dockerfile = include_str!("../../server/Dockerfile");
        let wanted = plugin_bundles();

        let missing: Vec<&&str> = wanted
            .iter()
            .filter(|name| !dockerfile.contains(**name))
            .collect();

        assert!(
            missing.is_empty(),
            "server/Dockerfile does not fetch {missing:?}; an agent on that \
             platform cannot install the httpd plugin from an on-prem server"
        );
    }
    /// The bundles have to reach the image from the package registry, not from
    /// the public site. CLOUDPUB-1251 moved every other per-build download into
    /// `build-deps/1` because the build host's link kept cutting slow HTTPS
    /// transfers; this block predates that move and was missed, so it stayed the
    /// one place a build still depended on cloudpub.ru being reachable - and it
    /// is what killed build #885 with `SSL_read: unexpected eof`
    /// (CLOUDPUB-1274).
    /// STATUS: FIXED - see CLOUDPUB-1274
    #[test]
    fn the_plugin_bundles_come_from_the_package_registry() {
        let dockerfile = include_str!("../../server/Dockerfile");
        let gitlab = include_str!("../../bin/gitlab");

        let missing: Vec<&str> = plugin_bundles()
            .into_iter()
            .filter(|name| !dockerfile.contains(&format!("build-deps/{name}")))
            .collect();
        assert!(
            missing.is_empty(),
            "server/Dockerfile does not COPY {missing:?} out of build-deps; \
             the build depends on the public site being reachable"
        );

        assert!(
            !dockerfile.contains("cloudpub.ru/download/"),
            "server/Dockerfile still fetches from cloudpub.ru during the build"
        );

        // The Dockerfile only COPYs what `clo gitlab fetch-deps` staged.
        let unstaged: Vec<&str> = plugin_bundles()
            .into_iter()
            .filter(|name| !gitlab.contains(&format!("\"{name}\"")))
            .collect();
        assert!(
            unstaged.is_empty(),
            "bin/gitlab BUILD_DEPS does not fetch {unstaged:?}, so the COPY \
             has nothing to copy"
        );
    }
}