Skip to main content

isothrum_machine/selftest/server/
proxmox.rs

1//! The test VM on a Proxmox VE server: the module `proxmox.tf`, its values from [`Proxmox`], and
2//! its steps read from Terraform's lines (`<address>: Creation complete …`). A resource's address
3//! is matched without its provider's prefix: the runner masks a secret's value in every line, and
4//! a password or token that holds `proxmox` would mask that prefix.
5
6use std::path::PathBuf;
7
8use isothrum_runner::{ErrorReport, RunOptions, Runner, SecretValue, Secrets};
9
10use super::{Course, Failure, Step, TestVm};
11
12/// The module, written as the project's `main.tf`.
13const MODULE: &str = include_str!("proxmox.tf");
14/// The VM's machine name in the run (its resource's name).
15const MACHINE: &str = "selftest_vm";
16/// What of each watched resource's address survives a masked provider prefix.
17const IMAGE: &str = "_download_file.selftest_image";
18const NETWORK: &str = "_sdn_applier.selftest_net";
19const VM: &str = "_virtual_environment_vm.selftest_vm";
20/// The start of the module's own error when the VM gets no address.
21const NO_ADDRESS: &str = "got no IPv4 address on bridge";
22/// The API's port when the endpoint names none.
23const API_PORT: u16 = 8006;
24
25/// How the test signs in to the server's API.
26#[derive(Debug, Clone)]
27#[non_exhaustive]
28pub enum SignIn {
29    /// An API token, `user@realm!name=secret`.
30    Token(SecretValue),
31    /// A user (`root@pam`) and password; the password also signs in to the node over SSH when no
32    /// key is given for it.
33    Password {
34        /// The user.
35        user: String,
36        /// The password.
37        password: SecretValue,
38    },
39}
40
41/// The key pair the test VM lets in and the test signs in with (and a jump host too).
42#[derive(Debug, Clone)]
43#[non_exhaustive]
44pub struct Key {
45    /// The private key's file.
46    pub private_file: PathBuf,
47    /// The public key, as `authorized_keys` takes it.
48    pub public: String,
49}
50
51impl Key {
52    /// The key pair whose private half is in `private_file`, public half `public`.
53    #[must_use]
54    pub fn new(private_file: impl Into<PathBuf>, public: impl Into<String>) -> Key {
55        Key {
56            private_file: private_file.into(),
57            public: public.into(),
58        }
59    }
60}
61
62/// A Proxmox VE server, where on it the test VM goes, and how this computer reaches it.
63#[derive(Debug, Clone)]
64#[non_exhaustive]
65pub struct Proxmox {
66    /// The API, `https://<server>:8006/`.
67    pub endpoint: String,
68    /// Accept the server's certificate unchecked.
69    pub insecure: bool,
70    /// How the test signs in to the API.
71    pub sign_in: SignIn,
72    /// The node the VM goes on.
73    pub node: String,
74    /// The bridge its first card goes on, which must give it an address (DHCP).
75    pub bridge: String,
76    /// Where its disk goes (the module's default: `local-lvm`).
77    pub datastore: Option<String>,
78    /// A datastore with `iso` content, for the cloud image (default: `local`).
79    pub image_datastore: Option<String>,
80    /// A datastore with `snippets` content, for cloud-init (default: `local`).
81    pub snippets_datastore: Option<String>,
82    /// Who the snippet's upload signs in to the node as over SSH (default: `root`).
83    pub node_ssh_user: Option<String>,
84    /// The key that upload signs in with; without one, the password of [`SignIn::Password`].
85    pub node_ssh_key_file: Option<PathBuf>,
86    /// The node's SSH address, when the API reports one this computer can't reach.
87    pub node_address: Option<String>,
88    /// The key the VM lets in; without one, the test runner's own.
89    pub key: Option<Key>,
90    /// `user@host` every SSH to the VM goes through first, when only that host reaches the
91    /// bridge (its node, when the bridge is internal to it).
92    pub jump: Option<String>,
93    /// A `known_hosts` file of the jump host's keys, which the run checks it against (only
94    /// reading it) instead of pinning it first met.
95    pub jump_known_hosts: Option<PathBuf>,
96}
97
98impl Proxmox {
99    /// The server whose API is `endpoint`, signed in to with `sign_in`, the VM on `node`'s
100    /// `vmbr0`, every other setting the module's default.
101    #[must_use]
102    pub fn new(endpoint: impl Into<String>, sign_in: SignIn, node: impl Into<String>) -> Proxmox {
103        Proxmox {
104            endpoint: endpoint.into(),
105            insecure: false,
106            sign_in,
107            node: node.into(),
108            bridge: "vmbr0".to_owned(),
109            datastore: None,
110            image_datastore: None,
111            snippets_datastore: None,
112            node_ssh_user: None,
113            node_ssh_key_file: None,
114            node_address: None,
115            key: None,
116            jump: None,
117            jump_known_hosts: None,
118        }
119    }
120
121    /// The API's `host:port`, from its endpoint (port 8006 when it names none).
122    pub(super) fn api_address(&self) -> String {
123        let rest = self.endpoint.split_once("://").map_or(self.endpoint.as_str(), |(_, r)| r);
124        let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
125        let authority = authority.rsplit_once('@').map_or(authority, |(_, a)| a);
126        let has_port = match authority.rsplit_once(']') {
127            Some((_, after)) => after.starts_with(':'),
128            None => authority.contains(':'),
129        };
130        if has_port { authority.to_owned() } else { format!("{authority}:{API_PORT}") }
131    }
132
133    /// The run's options for VM `vm`, its key's public half `public`.
134    fn options(&self, vm: &TestVm<'_>, public: &str) -> RunOptions {
135        let (zone, vnet) = network_ids(vm.name);
136        let mut secrets = Secrets::new();
137        let mut opts = RunOptions::new()
138            .with_env("endpoint", self.endpoint.clone())
139            .with_env("insecure", self.insecure.to_string())
140            .with_env("node", self.node.clone())
141            .with_env("bridge", self.bridge.clone())
142            .with_env("name", vm.name)
143            .with_env("hostname", vm.hostname)
144            .with_env("zone", zone)
145            .with_env("vnet", vnet)
146            .with_env("ssh_public_key", public.trim());
147        match &self.sign_in {
148            SignIn::Token(token) => secrets.insert("api_token", token.clone()),
149            SignIn::Password { user, password } => {
150                opts = opts.with_env("username", user.clone());
151                secrets.insert("password", password.clone());
152            }
153        }
154        let optional = [
155            ("datastore", self.datastore.clone()),
156            ("image_datastore", self.image_datastore.clone()),
157            ("snippets_datastore", self.snippets_datastore.clone()),
158            ("node_ssh_user", self.node_ssh_user.clone()),
159            ("node_ssh_key_file", self.node_ssh_key_file.as_ref().map(|f| f.to_string_lossy().into_owned())),
160            ("node_address", self.node_address.clone()),
161            // The run's own: what its commands sign in with, and go through first.
162            ("ssh_private_key_file", self.key.as_ref().map(|k| k.private_file.to_string_lossy().into_owned())),
163            ("ssh_jump", self.jump.clone()),
164            (
165                "ssh_jump_known_hosts_file",
166                self.jump_known_hosts.as_ref().map(|f| f.to_string_lossy().into_owned()),
167            ),
168        ];
169        for (name, value) in optional {
170            if let Some(value) = value.filter(|v| !v.is_empty()) {
171                opts = opts.with_env(name, value);
172            }
173        }
174        opts.with_secrets(secrets)
175    }
176}
177
178/// The project: its file and text.
179pub(super) fn project() -> (&'static str, String) {
180    ("main.tf", MODULE.to_owned())
181}
182
183/// The run's options and course on `p`, the VM `vm`, once `runner` is there: its key, else the
184/// runner's own.
185pub(super) async fn prepared(p: &Proxmox, vm: &TestVm<'_>, runner: &Runner) -> Result<(RunOptions, Pve), String> {
186    let public = match &p.key {
187        Some(key) => key.public.clone(),
188        None => runner.ssh_public_key().await.map_err(|e| e.to_string())?,
189    };
190    Ok((p.options(vm, &public), Pve))
191}
192
193/// The SDN zone's and VNet's ids of the test VM named `name` (eight characters at most, as
194/// Proxmox VE takes them): the same at every test of that VM, so an earlier one's are found.
195fn network_ids(name: &str) -> (String, String) {
196    // FNV-1a: stable across builds and platforms.
197    let hash = name.bytes().fold(0x811c_9dc5_u32, |h, b| (h ^ u32::from(b)).wrapping_mul(0x0100_0193)) & 0x00ff_ffff;
198    (format!("st{hash:06x}"), format!("sn{hash:06x}"))
199}
200
201/// How the test VM comes up on Proxmox VE: the image downloaded, the network applied, then the
202/// VM created, which ends once its guest agent reports its address.
203pub(super) struct Pve;
204
205impl Course for Pve {
206    const UP: &'static [Step] = &[Step::Image, Step::Network, Step::Vm, Step::Address];
207
208    fn machine(&self) -> &'static str {
209        MACHINE
210    }
211
212    fn ends(&mut self, line: &str) -> Option<usize> {
213        let (address, _) = line.split_once(": Creation complete")?;
214        if address.ends_with(IMAGE) {
215            Some(0)
216        } else if address.ends_with(NETWORK) {
217            Some(1)
218        } else if address.ends_with(VM) {
219            Some(3)
220        } else {
221            None
222        }
223    }
224
225    fn explain(&self, report: &ErrorReport) -> Option<(usize, Failure)> {
226        let said = &report.message;
227        let boxed = || Box::new(report.clone());
228        if said.contains(NO_ADDRESS) {
229            Some((3, Failure::NoAddress(boxed())))
230        } else if said.contains("does not exist") && said.contains("bridge") {
231            Some((2, Failure::NoBridge(boxed())))
232        } else if said.contains(IMAGE) {
233            Some((0, Failure::ImageDownload(boxed())))
234        } else if said.contains("_sdn_") {
235            Some((1, Failure::Runner(boxed())))
236        } else {
237            None
238        }
239    }
240}
241
242#[cfg(test)]
243mod tests {
244    use super::*;
245
246    fn token() -> SignIn {
247        SignIn::Token(SecretValue::new("root@pam!t=s3cret"))
248    }
249
250    #[test]
251    fn the_api_address_is_the_endpoints_host_and_port() {
252        for (endpoint, address) in [
253            ("https://pve.lan:8006/", "pve.lan:8006"),
254            ("https://10.0.0.5/", "10.0.0.5:8006"),
255            ("https://10.0.0.5", "10.0.0.5:8006"),
256            ("https://[fd00::5]:8443/api2/json", "[fd00::5]:8443"),
257            ("https://[fd00::5]/", "[fd00::5]:8006"),
258            ("pve.lan:9000", "pve.lan:9000"),
259        ] {
260            assert_eq!(Proxmox::new(endpoint, token(), "pve").api_address(), address, "{endpoint}");
261        }
262    }
263
264    #[test]
265    fn the_values_name_the_modules_variables_and_the_secret_is_never_a_value() {
266        let vm = TestVm::new("test-vm-1", "probe");
267        let mut p = Proxmox::new("https://pve:8006/", token(), "pve2");
268        p.bridge = "vmbr1".into();
269        p.image_datastore = Some("isos".into());
270        p.jump = Some("root@pve".into());
271        p.jump_known_hosts = Some("/app/nodes_known_hosts".into());
272        p.key = Some(Key::new("/keys/id_ed25519", "ssh-ed25519 AAAA me\n"));
273        let opts = p.options(&vm, "ssh-ed25519 AAAA me\n");
274        let value = |k: &str| opts.env.get(k).map(String::as_str);
275        assert_eq!(value("node"), Some("pve2"));
276        assert_eq!(value("bridge"), Some("vmbr1"));
277        assert_eq!(value("image_datastore"), Some("isos"));
278        assert_eq!(value("datastore"), None, "the module's default");
279        assert_eq!(value("ssh_public_key"), Some("ssh-ed25519 AAAA me"));
280        assert_eq!(value("ssh_private_key_file"), Some("/keys/id_ed25519"));
281        assert_eq!(value("ssh_jump"), Some("root@pve"));
282        assert_eq!(value("ssh_jump_known_hosts_file"), Some("/app/nodes_known_hosts"));
283        assert_eq!(opts.secrets.get("api_token").map(SecretValue::expose), Some("root@pam!t=s3cret"));
284        assert!(opts.env.values().all(|v| !v.contains("s3cret")));
285        // Every value is one of the module's variables, or one of the run's own.
286        for name in opts.env.keys().map(String::as_str).chain(opts.secrets.iter().map(|(k, _)| k)) {
287            let declared = MODULE.contains(&format!("variable \"{name}\""));
288            assert!(
289                declared || ["ssh_private_key_file", "ssh_jump", "ssh_jump_known_hosts_file"].contains(&name),
290                "{name} isn't a variable"
291            );
292        }
293        let password = Proxmox::new(
294            "https://pve:8006/",
295            SignIn::Password {
296                user: "root@pam".into(),
297                password: SecretValue::new("pw"),
298            },
299            "pve",
300        );
301        let signed_in = password.options(&vm, "k");
302        assert_eq!(signed_in.env.get("username").map(String::as_str), Some("root@pam"));
303        assert_eq!(signed_in.secrets.get("password").map(SecretValue::expose), Some("pw"));
304    }
305
306    #[test]
307    fn the_network_ids_are_short_stable_and_the_vms_own() {
308        let (zone, vnet) = network_ids("cyber-test-0123456789abcdef");
309        assert_eq!((zone.len(), vnet.len()), (8, 8));
310        assert!(zone.starts_with("st") && vnet.starts_with("sn") && zone.get(2..) == vnet.get(2..));
311        assert!(zone.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit()));
312        assert_eq!(network_ids("cyber-test-0123456789abcdef"), (zone.clone(), vnet));
313        assert_ne!(network_ids("cyber-test-fedcba9876543210").0, zone);
314    }
315
316    #[test]
317    fn a_step_ends_on_its_resource_even_with_the_providers_name_masked() {
318        for prefix in ["proxmox", "***"] {
319            let mut pve = Pve;
320            assert_eq!(
321                pve.ends(&format!(
322                    "{prefix}_download_file.selftest_image: Creation complete after 3s [id=local:iso/x.img]"
323                )),
324                Some(0)
325            );
326            assert_eq!(pve.ends(&format!("{prefix}_sdn_applier.selftest_net: Creation complete after 1s")), Some(1));
327            assert_eq!(
328                pve.ends(&format!("{prefix}_virtual_environment_vm.selftest_vm: Creation complete after 41s [id=101]")),
329                Some(3)
330            );
331            assert_eq!(
332                pve.ends(&format!("{prefix}_virtual_environment_vm.selftest_vm: Still creating... [10s elapsed]")),
333                None
334            );
335            assert_eq!(pve.ends(&format!("{prefix}_sdn_applier.selftest_finalizer: Creation complete after 1s")), None);
336        }
337        assert_eq!(Pve.machine(), MACHINE);
338    }
339
340    #[test]
341    fn the_failures_people_hit_belong_to_their_step() {
342        let failed = |message: &str| ErrorReport::new(isothrum_runner::ErrorCode::ToolFailed, message);
343        let explained = |message: &str| Pve.explain(&failed(message)).map(|(at, why)| (at, std::mem::discriminant(&why)));
344        let no_address = format!(
345            "step `up`: terraform failed: Resource postcondition failed (proxmox_virtual_environment_vm.selftest_vm): the VM {NO_ADDRESS} `vmbr1` within 8m"
346        );
347        let report = failed("x");
348        assert_eq!(
349            explained(&no_address),
350            Some((3, std::mem::discriminant(&Failure::NoAddress(Box::new(report.clone())))))
351        );
352        assert_eq!(
353            explained("error creating VM: bridge 'sn12ab34' does not exist"),
354            Some((2, std::mem::discriminant(&Failure::NoBridge(Box::new(report.clone())))))
355        );
356        assert_eq!(
357            explained("Error downloading (***_download_file.selftest_image): 404"),
358            Some((0, std::mem::discriminant(&Failure::ImageDownload(Box::new(report.clone())))))
359        );
360        assert_eq!(
361            explained("Error (proxmox_sdn_zone_simple.selftest_zone): zone exists").map(|(at, _)| at),
362            Some(1)
363        );
364        assert_eq!(explained("401 Unauthorized"), None);
365    }
366
367    /// What the course watches is what the module makes, and what it explains, what it says.
368    #[test]
369    fn the_module_has_the_watched_resources_and_says_no_address_as_explained() {
370        for resource in [
371            "resource \"proxmox_download_file\" \"selftest_image\"",
372            "resource \"proxmox_sdn_applier\" \"selftest_net\"",
373            "resource \"proxmox_virtual_environment_vm\" \"selftest_vm\"",
374            "output \"ssh_user\"",
375            NO_ADDRESS,
376        ] {
377            assert!(MODULE.contains(resource), "{resource} missing from the module");
378        }
379        for end in [IMAGE, NETWORK, VM] {
380            let (kind, name) = end.trim_start_matches('_').split_once('.').unwrap();
381            assert!(MODULE.contains(&format!("\"proxmox_{kind}\" \"{name}\"")), "{end}");
382        }
383        // Terraform makes what doesn't depend on another side by side: the network waits for the
384        // image (and the VM for the network), so a later step's line never ends an earlier one.
385        assert!(MODULE.contains("depends_on = [proxmox_sdn_applier.selftest_finalizer, proxmox_download_file.selftest_image]"));
386        assert!(MODULE.contains("depends_on = [proxmox_sdn_applier.selftest_net]"));
387    }
388}