fundaia 0.7.2

Command line for the Fundaia deployment platform: projects, services, variables, deployments, logs and metrics
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
//! Replacing this program with a newer one, in place.
//!
//! The release workflow already builds four binaries, tars each one and puts a
//! `.sha256` beside it, and `install.sh` already knows how to fetch them. This
//! is that same script, in the tool, so the version somebody is running catches
//! up on its own rather than after they read a notice and remember to act on it.
//!
//! Three decisions are worth knowing before changing anything here.
//!
//! - **The checksum is mandatory, unlike in `install.sh`.** That script runs
//!   because a person typed it and can see what it says; this runs by itself.
//!   A download nothing vouched for is not written over the binary that holds
//!   somebody's deploy credentials, so a missing `.sha256` fails the update.
//! - **The new binary is staged in the directory it will land in**, never in
//!   `/tmp`, because the swap has to be a `rename` and a rename does not cross
//!   filesystems. What is downloaded and unpacked lives in a scratch directory;
//!   only the finished file is copied next to its destination.
//! - **Nothing is written over the running binary.** `rename` replaces the
//!   directory entry and leaves this process on the old inode, which is what
//!   makes it safe to do halfway through a command. The alternative — opening
//!   the running file for writing — is `ETXTBSY` on Linux and a corrupt binary
//!   where it is not.

use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use std::time::Duration;

use anyhow::{anyhow, bail, Context, Result};
use sha2::{Digest, Sha256};

/// Where the binaries are published. The crate is on crates.io and the compiled
/// artefacts are on GitHub, which is why the version is asked of one and
/// downloaded from the other.
const REPO: &str = "alex28042/fundaia-apps";

/// Generous next to the two seconds the check gets: by the time this runs,
/// there is a decision to download several megabytes and a line on screen
/// saying so.
const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(120);

/// Where the running commentary goes.
///
/// An update takes long enough to need one, and the two callers need it in
/// different places: the automatic check writes to stderr, because it is not
/// what anybody asked for, and `upgrade` writes to stdout, because it is. This
/// module knows what is happening and nothing about which stream that is.
pub trait Progress {
    fn say(&self, message: &str);
}

/// Everything the swap needs, resolved before a single byte is downloaded.
///
/// Built by `prepare`, which is where every reason this machine cannot update
/// itself is discovered — an unknown platform, a binary owned by root, a
/// directory that is read-only. Failing there costs nothing; failing after the
/// download costs the download.
pub struct SelfInstaller {
    version: String,
    target: &'static str,
    /// The file that gets replaced: this program, with symlinks followed.
    executable: PathBuf,
}

impl SelfInstaller {
    pub fn prepare(version: &str) -> Result<Self> {
        let target = target_triple().ok_or_else(|| {
            anyhow!(
                "no hay binario publicado para {}-{}",
                std::env::consts::ARCH,
                std::env::consts::OS
            )
        })?;

        // Canonical, so a symlinked install replaces what the link points at
        // rather than turning the link into a copy.
        let executable = std::env::current_exe()
            .and_then(|path| path.canonicalize())
            .context("no se ha podido localizar el propio ejecutable")?;

        let directory = executable
            .parent()
            .ok_or_else(|| anyhow!("el ejecutable no está dentro de ningún directorio"))?;

        // Asked by writing rather than by reading the permission bits: the
        // question is whether *this* process can write there, and the answer
        // involves the owner, the group, the mode and whether the filesystem is
        // mounted read-only.
        let probe = directory.join(".fundaia-write-check");
        std::fs::write(&probe, b"")
            .with_context(|| format!("{} no es escribible", directory.display()))?;
        let _ = std::fs::remove_file(&probe);

        Ok(Self {
            version: version.to_owned(),
            target,
            executable,
        })
    }

    /// Where the finished binary will end up. Shown after a successful update,
    /// because "installed" without a path is the sentence that leaves somebody
    /// wondering which of their two copies moved.
    pub fn destination(&self) -> &Path {
        &self.executable
    }

    /// Installs the newer version by whichever of the two routes works, and
    /// leaves the binary exactly as it was if neither does.
    pub async fn install(&self, progress: &dyn Progress) -> Result<()> {
        let scratch =
            std::env::temp_dir().join(format!("fundaia-{}-{}", self.version, std::process::id()));
        std::fs::create_dir_all(&scratch)
            .with_context(|| format!("no se ha podido crear {}", scratch.display()))?;

        let outcome = self.take_a_route(&scratch, progress).await;

        // However it went: an aborted update must not leave a half-unpacked
        // binary in a temporary directory nobody ever looks at.
        let _ = std::fs::remove_dir_all(&scratch);

        outcome
    }

    /// The published binary if it can be had, and the crate if it cannot.
    ///
    /// Both routes end at the same version; they differ in what they need from
    /// the machine and in how long they take. The binary is seconds and needs
    /// no toolchain, so it is tried first — but the assets hang off a **private**
    /// repository, and GitHub serves those to nobody without a credential. So
    /// today the first route answers 404 in a fifth of a second and the second
    /// one is what actually installs. The order stays this way because the day
    /// that repository is public, the fast route starts working with no change
    /// here.
    ///
    /// Only an archive that could not be *obtained* falls through. One that
    /// arrives and fails its checksum stops everything: that is the difference
    /// between "not available" and "not to be trusted", and quietly building
    /// from source after a failed signature check would turn a red flag into a
    /// retry.
    async fn take_a_route(&self, scratch: &Path, progress: &dyn Progress) -> Result<()> {
        let http = reqwest::Client::builder()
            .timeout(DOWNLOAD_TIMEOUT)
            .user_agent(concat!("fundaia/", env!("CARGO_PKG_VERSION")))
            .build()?;

        progress.say("descargando…");

        let url = self.asset_url();
        let Ok(archive) = fetch(&http, &url).await else {
            progress.say("el binario publicado no está a la vista; compilando desde crates.io…");
            return self.build_from_the_crate(progress).await;
        };

        let published = fetch(&http, &format!("{url}.sha256"))
            .await
            .context("la release no publica checksum para este binario")?;
        let published = String::from_utf8(published).context("el checksum no es texto")?;

        verify(&archive, &published)?;

        let packed = scratch.join("fundaia.tar.gz");
        std::fs::write(&packed, &archive).context("no se ha podido guardar la descarga")?;
        unpack(&packed, scratch).await?;

        let fresh = scratch.join("fundaia");
        if !fresh.is_file() {
            bail!("el archivo descargado no contiene fundaia");
        }

        self.swap(&fresh)
    }

    /// `cargo install`, which needs no swapping of our own: cargo writes the
    /// finished binary into place itself, and does it the same careful way.
    ///
    /// `--root` so it lands on the copy that is running rather than on
    /// whichever one `~/.cargo/bin` holds. `--locked` so it builds against the
    /// dependencies the release was tested with. `--version` because "newest"
    /// is decided up in `update`, and a crate that gained a version in the last
    /// four seconds must not change what this installs.
    async fn build_from_the_crate(&self, progress: &dyn Progress) -> Result<()> {
        let mut cargo = tokio::process::Command::new("cargo");
        cargo
            .arg("install")
            .arg("fundaia")
            .arg("--version")
            .arg(&self.version)
            .arg("--locked")
            .arg("--force")
            .arg("--quiet");

        if let Some(root) = cargo_root(&self.executable) {
            cargo.arg("--root").arg(root);
        }

        let built = cargo
            .output()
            .await
            .context("no se ha podido ejecutar cargo — instálalo o actualiza a mano")?;

        if !built.status.success() {
            let complaint = String::from_utf8_lossy(&built.stderr);
            bail!("cargo install ha fallado: {}", last_line(&complaint));
        }

        progress.say("compilada e instalada");

        Ok(())
    }

    /// Copy next door, make it executable, and move it over the old one. The
    /// three steps are in this order so the only irreversible one is last and
    /// atomic.
    fn swap(&self, fresh: &Path) -> Result<()> {
        let staged = self
            .executable
            .with_file_name(format!(".fundaia-{}.new", self.version));

        std::fs::copy(fresh, &staged)
            .with_context(|| format!("no se ha podido escribir en {}", staged.display()))?;

        if let Err(error) = make_executable(&staged) {
            let _ = std::fs::remove_file(&staged);
            return Err(error);
        }

        if let Err(error) = std::fs::rename(&staged, &self.executable) {
            let _ = std::fs::remove_file(&staged);
            return Err(error).with_context(|| {
                format!("no se ha podido reemplazar {}", self.executable.display())
            });
        }

        Ok(())
    }

    fn asset_url(&self) -> String {
        format!(
            "https://github.com/{REPO}/releases/download/{tag}/{asset}",
            tag = tag_of(&self.version),
            asset = asset_name(&self.version, self.target),
        )
    }
}

async fn fetch(http: &reqwest::Client, url: &str) -> Result<Vec<u8>> {
    let response = http.get(url).send().await?.error_for_status()?;
    Ok(response.bytes().await?.to_vec())
}

/// `tar` rather than a Rust decompressor, deliberately: every platform this
/// publishes for has it, `install.sh` already depends on it, and two crates of
/// build time is a poor trade for unpacking one file.
async fn unpack(archive: &Path, into: &Path) -> Result<()> {
    let status = tokio::process::Command::new("tar")
        .arg("-xzf")
        .arg(archive)
        .arg("-C")
        .arg(into)
        .status()
        .await
        .context("no se ha podido ejecutar tar")?;

    if !status.success() {
        bail!("tar no ha podido descomprimir la descarga");
    }

    Ok(())
}

/// What the release says the archive should hash to, against what it does.
fn verify(archive: &[u8], published: &str) -> Result<()> {
    let expected = expected_digest(published)
        .ok_or_else(|| anyhow!("el checksum publicado está vacío o mal formado"))?;
    let actual = digest_of(archive);

    if actual != expected {
        bail!("el checksum no coincide: la descarga se descarta");
    }

    Ok(())
}

/// `sha256sum` writes `<hash>  <filename>`, and `shasum -a 256` writes the same
/// with one space fewer on some platforms. Only the first field is ours.
fn expected_digest(published: &str) -> Option<String> {
    let digest = published.split_whitespace().next()?;

    if digest.len() != 64 || !digest.chars().all(|c| c.is_ascii_hexdigit()) {
        return None;
    }

    Some(digest.to_ascii_lowercase())
}

fn digest_of(bytes: &[u8]) -> String {
    let digest = Sha256::digest(bytes);

    digest
        .iter()
        .fold(String::with_capacity(64), |mut text, byte| {
            let _ = write!(text, "{byte:02x}");
            text
        })
}

/// The tag the release workflow lays down, which is also what the asset is
/// named after.
fn tag_of(version: &str) -> String {
    format!("cli-v{version}")
}

fn asset_name(version: &str, target: &str) -> String {
    format!("fundaia-{tag}-{target}.tar.gz", tag = tag_of(version))
}

/// What to hand `cargo install --root`, so it writes over the copy that is
/// running rather than over whatever `~/.cargo/bin` holds.
///
/// Cargo appends `bin/` to the root itself, so this is the parent of the
/// directory the executable sits in — and only when that directory is called
/// `bin`, because anywhere else the two would not agree on the final path.
/// `None` means "let cargo decide", which is `~/.cargo/bin` and is the right
/// answer for the installs that came from there in the first place.
fn cargo_root(executable: &Path) -> Option<&Path> {
    let directory = executable.parent()?;

    if directory.file_name()? != "bin" {
        return None;
    }

    directory.parent()
}

/// The last thing a failed build complained about. Cargo's stderr is a wall of
/// progress lines and the reason is at the bottom of it.
fn last_line(complaint: &str) -> &str {
    complaint
        .lines()
        .map(str::trim)
        .rfind(|line| !line.is_empty())
        .unwrap_or("sin explicación")
}

/// Which of the four published binaries this machine runs.
///
/// Worked out from what the standard library already knows rather than from a
/// build script exporting `TARGET`: there are four of them, they are listed in
/// `cli.yml`, and anything else has to be told there is no binary for it rather
/// than handed the closest guess.
fn target_triple() -> Option<&'static str> {
    triple_for(std::env::consts::ARCH, std::env::consts::OS)
}

fn triple_for(arch: &str, os: &str) -> Option<&'static str> {
    match (arch, os) {
        ("aarch64", "macos") => Some("aarch64-apple-darwin"),
        ("x86_64", "macos") => Some("x86_64-apple-darwin"),
        ("x86_64", "linux") => Some("x86_64-unknown-linux-gnu"),
        ("aarch64", "linux") => Some("aarch64-unknown-linux-gnu"),
        _ => None,
    }
}

#[cfg(unix)]
fn make_executable(path: &Path) -> Result<()> {
    use std::os::unix::fs::PermissionsExt;

    std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).with_context(|| {
        format!(
            "no se han podido ajustar los permisos de {}",
            path.display()
        )
    })
}

/// There is no published binary for a platform without Unix permissions, so
/// this exists to keep the module compiling rather than to be reached.
#[cfg(not(unix))]
fn make_executable(_path: &Path) -> Result<()> {
    Ok(())
}

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

    #[test]
    fn it_should_name_the_asset_the_way_the_release_workflow_does() {
        assert_eq!(
            asset_name("0.4.0", "aarch64-apple-darwin"),
            "fundaia-cli-v0.4.0-aarch64-apple-darwin.tar.gz",
        );
    }

    #[test]
    fn it_should_name_the_tag_the_way_the_release_workflow_does() {
        assert_eq!(tag_of("0.4.0"), "cli-v0.4.0");
    }

    #[test]
    fn it_should_know_the_binary_an_apple_silicon_mac_runs() {
        assert_eq!(triple_for("aarch64", "macos"), Some("aarch64-apple-darwin"));
    }

    #[test]
    fn it_should_know_the_binary_the_home_server_runs() {
        assert_eq!(
            triple_for("x86_64", "linux"),
            Some("x86_64-unknown-linux-gnu")
        );
    }

    #[test]
    fn it_should_refuse_a_platform_nothing_is_published_for() {
        assert!(triple_for("x86_64", "windows").is_none());
    }

    #[test]
    fn it_should_read_the_digest_out_of_what_sha256sum_writes() {
        let line = format!("{}  fundaia.tar.gz", "a".repeat(64));
        assert_eq!(expected_digest(&line), Some("a".repeat(64)));
    }

    #[test]
    fn it_should_read_a_digest_that_arrived_on_its_own() {
        assert_eq!(expected_digest(&"b".repeat(64)), Some("b".repeat(64)));
    }

    #[test]
    fn it_should_read_an_uppercase_digest_as_the_same_digest() {
        assert_eq!(expected_digest(&"A".repeat(64)), Some("a".repeat(64)));
    }

    #[test]
    fn it_should_refuse_a_checksum_file_that_is_empty() {
        assert!(expected_digest("   \n").is_none());
    }

    #[test]
    fn it_should_refuse_a_digest_of_the_wrong_length() {
        assert!(expected_digest("deadbeef  fundaia.tar.gz").is_none());
    }

    #[test]
    fn it_should_refuse_a_digest_that_is_not_hexadecimal() {
        assert!(expected_digest(&"z".repeat(64)).is_none());
    }

    #[test]
    fn it_should_hash_the_way_sha256sum_does() {
        assert_eq!(
            digest_of(b"fundaia"),
            "2973701beace145a932d249fbf716f25802a722be3ca41476b59e666597a83d4"
        );
    }

    #[test]
    fn it_should_accept_an_archive_whose_digest_matches() {
        let published = format!("{}  fundaia.tar.gz", digest_of(b"fundaia"));
        assert!(verify(b"fundaia", &published).is_ok());
    }

    #[test]
    fn it_should_refuse_an_archive_whose_digest_does_not_match() {
        let published = format!("{}  fundaia.tar.gz", digest_of(b"fundaia"));
        assert!(verify(b"something else entirely", &published).is_err());
    }

    #[test]
    fn it_should_refuse_an_archive_with_no_checksum_at_all() {
        assert!(verify(b"fundaia", "").is_err());
    }

    #[test]
    fn it_should_point_cargo_at_the_prefix_the_binary_lives_under() {
        assert_eq!(
            cargo_root(Path::new("/home/alex/.local/bin/fundaia")),
            Some(Path::new("/home/alex/.local")),
        );
    }

    #[test]
    fn it_should_let_cargo_decide_when_the_binary_is_not_in_a_bin_directory() {
        assert!(cargo_root(Path::new("/opt/tools/fundaia")).is_none());
    }

    #[test]
    fn it_should_report_what_cargo_complained_about_last() {
        assert_eq!(
            last_line("   Compiling fundaia\nerror: could not compile\n\n"),
            "error: could not compile",
        );
    }

    #[test]
    fn it_should_say_something_when_cargo_failed_without_a_word() {
        assert_eq!(last_line("  \n\n"), "sin explicación");
    }
}