Skip to main content

workload_spec/
control_plane_install.rs

1//! Shared install-script builder for a control-plane (yubaba + kamaji) roll.
2//!
3//! This is the ONE net-new mechanism of the rolling-upgrade envelope (R608):
4//! the atomic fetch→verify→anchor→install→assert→restart of the signed
5//! yubaba+kamaji pair. It lives here — in the crate BOTH the CLI orchestrator
6//! and yubaba itself depend on — so the two apply transports share a single,
7//! trusted script and cannot drift:
8//!
9//! - **SSH transport** (R608-F5, `app/yah/cli/src/rollout/apply.rs::apply_over_ssh`)
10//!   pipes the script to `ssh <node> bash -s` from the orchestrator.
11//! - **Mesh transport** (R608-F10, yubaba `POST /self-update`) runs the *same*
12//!   script locally on the node via a `systemd-run` transient unit — no SSH.
13//!
14//! **The script body is not written here.** It lives beside this file as
15//! [`control_plane_install.sh`](./control_plane_install.sh) and is `include_str!`d,
16//! because a third caller — `scripts/roll-node.sh`, the one-node operator SSH
17//! job (R755-F3) — has to run the identical bytes from bash with no Rust in the
18//! loop. This function only prepends the four-variable prologue the template
19//! declares (`URL` / `SHA` / `VER` / `SUDO`); `roll-node.sh` prepends the same
20//! four. Keeping the body in a `format!` string would have forced that script to
21//! become a fourth transcription of the most safety-critical code in the fleet
22//! (`stand-up-yubaba.sh`'s install tail is already the second).
23//!
24//! The script is a state-preserving, atomic transcription of the install tail of
25//! `stand-up-yubaba.sh`: fetch the signed release tarball, `sha256 -c` it against
26//! the digest the signed manifest already resolved (callers only ever pass
27//! manifest-derived values — there is no path for an AI or a wire request to
28//! fabricate a version/url/digest), extract, leave a dated rollback anchor beside
29//! every file it is about to replace, stage each file next to its target on the
30//! same filesystem, then `mv` it into place so a half-written
31//! `/usr/local/bin/yubaba` can never appear. yubaba + kamaji install as one
32//! atomic pair (W275 OQ5).
33//!
34//! **Success is proved by content, never by `--version`.** After the rename the
35//! script hashes each installed binary against the file it extracted from the
36//! manifest-verified tarball. The version string is the workspace version baked
37//! in at build time and can be right on a binary that predates the code it
38//! claims — us-east-001 reported kamaji 0.8.22 while carrying none of the 0.8.22
39//! tree (R746-T3). The hash chain manifest → tarball → extracted → installed has
40//! no version string in it.
41//!
42//! **Never touches durable state.** The script contains no reference to
43//! `/var/lib/yah-cloud/identity.json` (the ed25519 host identity — wiping it
44//! forces a re-TOFU and breaks hostkey-drift detection, the R589 gotcha) or the
45//! raft log dir. A roll moves `/usr/local/bin` bytes + unit files, nothing else.
46//! The [`tests::script_never_touches_durable_state`] test is the guard.
47
48/// Single-quote a value for safe embedding inside the generated bash. Callers
49/// only ever embed manifest-derived URLs/digests (already constrained) and a
50/// version string, but we quote defensively regardless.
51fn sh_squote(s: &str) -> String {
52    format!("'{}'", s.replace('\'', r"'\''"))
53}
54
55/// The canonical roll script body, shared verbatim with `scripts/roll-node.sh`.
56/// Expects the four-variable prologue [`build_install_script`] emits.
57pub const INSTALL_SCRIPT_TEMPLATE: &str = include_str!("control_plane_install.sh");
58
59/// Build the self-contained install script for the yubaba+kamaji pair.
60///
61/// `sudo` is `true` when the executing user is not root (e.g. an SSH login as
62/// `debian@…`), matching `stand-up-yubaba.sh`'s `SUDO` convention. The mesh
63/// (self-update) path runs the script as root inside a `systemd-run` transient
64/// unit, so it passes `sudo = false`. The script is idempotent and atomic; it
65/// anchors what it is about to replace, restarts kamaji then yubaba (W154
66/// supervision order) and echoes the installed versions so the caller can log
67/// them — after having already proved the install by hash, not by those strings.
68///
69/// `version`/`url`/`sha256` MUST come from a signed release manifest — this
70/// builder does no verification of its own beyond emitting the `sha256sum -c`
71/// check; integrity rests on the caller only ever passing manifest-resolved
72/// values.
73pub fn build_install_script(version: &str, url: &str, sha256: &str, sudo: bool) -> String {
74    let sudo_kw = if sudo { "sudo" } else { "" };
75    format!(
76        "SUDO={sudo_kw}\nURL={url}\nSHA={sha}\nVER={ver}\n{body}",
77        sudo_kw = sudo_kw,
78        url = sh_squote(url),
79        sha = sh_squote(sha256),
80        ver = sh_squote(version),
81        body = INSTALL_SCRIPT_TEMPLATE,
82    )
83}
84
85#[cfg(test)]
86mod tests {
87    use super::*;
88
89    #[test]
90    fn script_embeds_the_signed_digest_and_url() {
91        let url = "https://cdn.yah.dev/yubaba/0.8.19/yubaba-0.8.19-x86_64-unknown-linux-musl.tar.gz";
92        let sha = "abc123def456";
93        let s = build_install_script("0.8.19", url, sha, false);
94        assert!(s.contains(sha), "script must carry the manifest sha256");
95        assert!(s.contains(url), "script must carry the manifest url");
96        assert!(s.contains("sha256sum -c -"), "script must verify the digest");
97    }
98
99    #[test]
100    fn script_is_atomic_and_installs_the_whole_pair() {
101        let s = build_install_script("0.8.19", "u", "d", false);
102        // Atomic: stage-then-rename, never a direct write to the live path.
103        assert!(s.contains("mv -f"), "install must be an atomic rename");
104        assert!(s.contains(".roll-new.$$"), "install must stage to a temp name");
105        // Both binaries + all three unit files.
106        for target in [
107            "/usr/local/bin/yubaba",
108            "/usr/local/bin/kamaji",
109            "/etc/systemd/system/yubaba.slice",
110            "/etc/systemd/system/kamaji.service",
111            "/etc/systemd/system/yubaba.service",
112        ] {
113            assert!(s.contains(target), "script must install {target}");
114        }
115        // Restart order: kamaji before yubaba (W154).
116        let k = s.find("restart kamaji.service").unwrap();
117        let y = s.find("restart yubaba.service").unwrap();
118        assert!(k < y, "kamaji must restart before yubaba");
119        assert!(s.contains("daemon-reload"));
120    }
121
122    /// The script with every comment line removed — i.e. only the lines bash
123    /// will actually execute. The template documents the durable-state rule in
124    /// prose *by naming the paths it must not touch*, so the guard below has to
125    /// look at commands, not at the whole file, or the doc comment describing
126    /// the property would be what breaks the test asserting it.
127    fn executable_lines(script: &str) -> String {
128        script
129            .lines()
130            .filter(|l| !l.trim_start().starts_with('#'))
131            .collect::<Vec<_>>()
132            .join("\n")
133    }
134
135    #[test]
136    fn script_never_touches_durable_state() {
137        // The load-bearing safety property: a roll moves binaries + unit files
138        // ONLY. Wiping identity.json forces a re-TOFU (R589 gotcha); touching
139        // the raft dir corrupts consensus. The script must reference neither.
140        let s = executable_lines(&build_install_script("0.8.19", "u", "d", true));
141        assert!(!s.contains("identity.json"), "must not touch host identity");
142        assert!(!s.contains("/var/lib/yah-cloud"), "must not touch state dir");
143        assert!(!s.contains("raft"), "must not touch the raft log dir");
144        assert!(!s.contains("rm -rf /"), "must not wipe system paths");
145    }
146
147    #[test]
148    fn script_anchors_every_file_it_replaces_before_replacing_it() {
149        // R755-F3. Every path the script installs must first be copied to a
150        // dated `.rollback-YYYYMMDD` sibling — the convention the fleet's boxes
151        // already carry — and the anchoring must happen BEFORE the install, or
152        // the anchor holds the new build and there is no way back.
153        let s = build_install_script("0.8.19", "u", "d", true);
154        let first_anchor = s.find("anchor /usr/local/bin/yubaba").expect("anchors");
155        let first_install = s.find("install_atomic \"$D/yubaba\"").expect("installs");
156        assert!(
157            first_anchor < first_install,
158            "anchors must be written before anything is replaced"
159        );
160        assert!(s.contains(r#"STAMP="$(date -u +%Y%m%d)""#));
161        for target in [
162            "/usr/local/bin/yubaba",
163            "/usr/local/bin/kamaji",
164            "/etc/systemd/system/yubaba.slice",
165            "/etc/systemd/system/kamaji.service",
166            "/etc/systemd/system/yubaba.service",
167        ] {
168            assert!(
169                s.contains(&format!("anchor {target}\n")),
170                "every installed path needs a rollback anchor, missing {target}"
171            );
172        }
173    }
174
175    #[test]
176    fn anchoring_is_idempotent_within_a_day() {
177        // The subtle half: a second roll on the same day must NOT re-anchor,
178        // or the escape hatch gets overwritten with the build being escaped.
179        let s = build_install_script("0.8.19", "u", "d", true);
180        assert!(
181            s.contains(r#"if [ ! -e "$1.rollback-$STAMP" ]; then"#),
182            "anchor must refuse to overwrite an existing same-day anchor"
183        );
184    }
185
186    #[test]
187    fn success_is_asserted_by_content_not_by_version_string() {
188        // R746-T3's trap: `--version` reports the workspace version baked in at
189        // build time and was right on a binary carrying none of that version's
190        // code. The proof has to be a hash of the installed bytes against the
191        // bytes extracted from the manifest-verified tarball.
192        let s = build_install_script("0.8.19", "u", "d", true);
193        for pair in [
194            r#"assert_installed_bytes "$D/yubaba" /usr/local/bin/yubaba"#,
195            r#"assert_installed_bytes "$D/kamaji" /usr/local/bin/kamaji"#,
196        ] {
197            assert!(s.contains(pair), "missing content assertion: {pair}");
198        }
199        // …and a mismatch must fail the roll, not merely print.
200        let body = &s[s.find("assert_installed_bytes() {").expect("assert fn")..];
201        assert!(
202            body.contains("content assertion FAILED") && body.contains("exit 1"),
203            "a content mismatch must exit nonzero so the caller sees a failed roll"
204        );
205        // The assertion must land before the restart — restarting onto bytes
206        // you haven't proved is the failure mode this closes.
207        assert!(
208            s.find("assert_installed_bytes \"$D/yubaba\"").unwrap()
209                < s.find("systemctl restart kamaji.service").unwrap(),
210            "content must be proved before the supervision tree restarts"
211        );
212    }
213
214    #[test]
215    fn the_template_is_the_only_copy_of_the_body() {
216        // scripts/roll-node.sh runs these same bytes with no Rust in the loop,
217        // so build_install_script must be a prologue over the template and
218        // nothing more. If this drifts, the SSH job and the mesh self-update
219        // stop being the same roll.
220        let s = build_install_script("0.8.19", "u", "d", false);
221        assert!(
222            s.ends_with(INSTALL_SCRIPT_TEMPLATE),
223            "the built script must be prologue + the shared template, verbatim"
224        );
225        let prologue = &s[..s.len() - INSTALL_SCRIPT_TEMPLATE.len()];
226        assert_eq!(
227            prologue.lines().count(),
228            4,
229            "the prologue is exactly URL/SHA/VER/SUDO — anything else belongs in the template"
230        );
231    }
232
233    #[test]
234    fn sudo_prefix_tracks_the_caller() {
235        let s = build_install_script("0.8.19", "u", "d", true);
236        assert!(s.contains("SUDO=sudo"));
237        let s = build_install_script("0.8.19", "u", "d", false);
238        assert!(s.contains("SUDO=\n") || s.contains("SUDO="));
239    }
240}