Skip to main content

isothrum_runner/graphical/
proxmox.rs

1//! A Proxmox VE VM's console, through its API (`source.from: proxmox_api`): `vncproxy` asked of
2//! the VM with `curl`, signed in with the run's connection (an API token, else the user's
3//! password through a ticket), its answer turned into the API's VNC websocket and the ticket that
4//! opens it ([`ProxmoxVnc`]). The credentials reach `curl` in a config file the runner writes
5//! owner-only in the run's state folder, pipes into it, and removes however the request ends
6//! (a cancel, Ctrl-C included): never on its command line.
7
8use std::time::Duration;
9
10use isoloom_manifest::{ConsoleSource, Machine};
11
12use super::none;
13use crate::Result;
14use crate::error::Error;
15use crate::executor::{Cx, Echo, call};
16use crate::process::ProcessSpec;
17use crate::secrets::SecretValue;
18use crate::store::Transient;
19
20/// How long one API call may go without progress.
21const LIMIT: Duration = Duration::from_secs(30);
22
23/// The config file `curl` reads, in the run's state folder, only while it runs ([`Transient`]).
24const CONFIG: &str = "proxmox-console.curl";
25
26/// Proxmox VE's VNC websocket for one VM, opened for one session: connect to `websocket` with
27/// the `authorization` header (TLS unverified when `insecure`), then speak VNC with `ticket` as
28/// the password. Every secret is a [`SecretValue`]: never print or log one.
29#[derive(Debug, Clone, PartialEq, Eq)]
30#[non_exhaustive]
31pub struct ProxmoxVnc {
32    /// `wss://<server>:8006/api2/json/nodes/<node>/qemu/<id>/vncwebsocket?port=<port>&vncticket=<ticket>`:
33    /// it holds the ticket.
34    pub websocket: SecretValue,
35    /// The VNC port `vncproxy` opened on the node (in the URL already).
36    pub port: u16,
37    /// The ticket: the VNC password, and in the URL.
38    pub ticket: SecretValue,
39    /// The header that signs the websocket in: its name (`Authorization`, `Cookie`) and value.
40    pub authorization: (String, SecretValue),
41    /// The server's certificate isn't verified (a self-signed one: the run's `proxmox_insecure`).
42    pub insecure: bool,
43}
44
45/// How the API is signed in to.
46enum SignIn {
47    /// An API token: `Authorization: PVEAPIToken=<token>`.
48    Token(String),
49    /// A ticket from `access/ticket`: the cookie, and the CSRF header a POST needs.
50    Ticket { ticket: String, csrf: String },
51}
52
53impl SignIn {
54    /// The config lines that sign a request in.
55    fn lines(&self, post: bool) -> Vec<String> {
56        match self {
57            SignIn::Token(t) => vec![format!("header = {}", quoted(&format!("Authorization: PVEAPIToken={t}")))],
58            SignIn::Ticket { ticket, csrf } => {
59                let mut out = vec![format!("cookie = {}", quoted(&format!("PVEAuthCookie={ticket}")))];
60                if post {
61                    out.push(format!("header = {}", quoted(&format!("CSRFPreventionToken: {csrf}"))));
62                }
63                out
64            }
65        }
66    }
67
68    /// The websocket's header.
69    fn header(&self) -> (String, SecretValue) {
70        match self {
71            SignIn::Token(t) => ("Authorization".into(), SecretValue::new(format!("PVEAPIToken={t}"))),
72            SignIn::Ticket { ticket, .. } => ("Cookie".into(), SecretValue::new(format!("PVEAuthCookie={ticket}"))),
73        }
74    }
75}
76
77/// `machine`'s console as `console` (a `proxmox_api` one) says, `vncproxy` asked for it.
78pub(super) async fn vnc(cx: &Cx<'_>, machine: &Machine, console: &isoloom_manifest::Console) -> Result<ProxmoxVnc> {
79    let Some(ConsoleSource::ProxmoxApi {
80        endpoint,
81        node,
82        vm_id,
83        insecure,
84        username,
85        token,
86        password,
87    }) = &console.source
88    else {
89        return Err(none(machine, "it has no Proxmox console"));
90    };
91    let at = |f: &str| format!("machines.{}.consoles.source.{f}", machine.name);
92    let base = cx.vars.render(endpoint, &at("endpoint"))?.trim_end_matches('/').to_owned();
93    let (node, vm_id) = (cx.vars.render(node, &at("node"))?, cx.vars.render(vm_id, &at("vm_id"))?);
94    let insecure = cx.vars.render(insecure, &at("insecure"))?.trim() == "true";
95    let host = base
96        .strip_prefix("https://")
97        .ok_or_else(|| none(machine, format!("the Proxmox API `{base}` isn't https")))?;
98    if !plain(&node) || !vm_id.chars().all(|c| c.is_ascii_digit()) || vm_id.is_empty() {
99        return Err(none(machine, format!("its VM `{vm_id}` on node `{node}` can't be named in a request")));
100    }
101    let sign_in = sign_in(cx, machine, &base, insecure, (username, token, password)).await?;
102    let path = format!("/api2/json/nodes/{node}/qemu/{vm_id}");
103    let mut fields = sign_in.lines(true);
104    fields.push("data = \"websocket=1\"".to_owned());
105    let said = api(cx, machine, &format!("{base}{path}/vncproxy"), insecure, &fields).await?;
106    let port = said
107        .get("port")
108        .and_then(|p| p.as_u64().or_else(|| p.as_str()?.parse().ok()))
109        .and_then(|p| u16::try_from(p).ok());
110    let ticket = said.get("ticket").and_then(serde_json::Value::as_str);
111    let (Some(port), Some(ticket)) = (port, ticket) else {
112        return Err(none(machine, "Proxmox's vncproxy gave no port and ticket"));
113    };
114    cx.events.hide([ticket.to_owned()]);
115    Ok(ProxmoxVnc {
116        websocket: SecretValue::new(format!("wss://{host}{path}/vncwebsocket?port={port}&vncticket={}", encoded(ticket))),
117        port,
118        ticket: SecretValue::new(ticket),
119        authorization: sign_in.header(),
120        insecure,
121    })
122}
123
124/// How the API is signed in to: the run's connection's API token (`token`), else the user's
125/// password (`password`) traded for a ticket.
126async fn sign_in(
127    cx: &Cx<'_>,
128    machine: &Machine,
129    base: &str,
130    insecure: bool,
131    (username, token, password): (&isoloom_manifest::Template, &isoloom_manifest::Identifier, &isoloom_manifest::Identifier),
132) -> Result<SignIn> {
133    let value = |slot: &isoloom_manifest::Identifier| cx.secrets.get(slot.as_str()).map(|v| v.expose().to_owned()).filter(|v| !v.is_empty());
134    match (value(token), value(password)) {
135        (Some(t), _) => Ok(SignIn::Token(t)),
136        (None, Some(p)) => {
137            let user = cx.vars.render(username, &format!("machines.{}.consoles.source.username", machine.name))?;
138            let fields = [
139                format!("data-urlencode = {}", quoted(&format!("username={user}"))),
140                format!("data-urlencode = {}", quoted(&format!("password={p}"))),
141            ];
142            let said = api(cx, machine, &format!("{base}/api2/json/access/ticket"), insecure, &fields).await?;
143            let ticket = said.get("ticket").and_then(serde_json::Value::as_str);
144            let csrf = said.get("CSRFPreventionToken").and_then(serde_json::Value::as_str);
145            match (ticket, csrf) {
146                (Some(t), Some(c)) => Ok(SignIn::Ticket {
147                    ticket: t.to_owned(),
148                    csrf: c.to_owned(),
149                }),
150                _ => Err(none(machine, "Proxmox gave no ticket for the user's password")),
151            }
152        }
153        (None, None) => Err(none(machine, "the run's connection gives no Proxmox API token or password")),
154    }
155}
156
157/// The `data` of a POST to `url`, its `fields` (the config lines that sign it in and its form)
158/// in the config file `curl` reads, removed once it ran or the request is cut short.
159async fn api(cx: &Cx<'_>, machine: &Machine, url: &str, insecure: bool, fields: &[String]) -> Result<serde_json::Value> {
160    let out = request(cx, "console", (url, Some("POST")), insecure, fields).await?;
161    if !out.success() {
162        return Err(none(machine, format!("Proxmox's API refused: {}", cx.events.mask(&out.reason()))));
163    }
164    let body: serde_json::Value = serde_json::from_str(&out.stdout.join("\n")).map_err(|e| Error::NoConsole {
165        machine: machine.name.to_string(),
166        why: format!("Proxmox's API answered no JSON: {e}"),
167    })?;
168    Ok(body.get("data").cloned().unwrap_or(serde_json::Value::Null))
169}
170
171/// What `curl` answered to a request to `url` (`method`: `POST`, or a GET), for step `step`, its
172/// `fields` in the config file it reads, removed once it ran or the request is cut short.
173async fn request(cx: &Cx<'_>, step: &str, (url, method): (&str, Option<&str>), insecure: bool, fields: &[String]) -> Result<crate::process::Captured> {
174    let mut text = format!("url = {}\n", quoted(url));
175    if let Some(method) = method {
176        text.push_str("request = ");
177        text.push_str(&quoted(method));
178        text.push('\n');
179    }
180    for f in fields {
181        text.push_str(f);
182        text.push('\n');
183    }
184    let config = Transient::write(cx.state_dir().join(CONFIG), text.as_bytes(), "a Proxmox API request's curl config")?;
185    let mut args = vec!["--silent", "--show-error", "--fail-with-body", "--max-time", "25", "--config", "-"];
186    if insecure {
187        args.push("--insecure");
188    }
189    let mut spec = ProcessSpec::new("curl", args);
190    spec.stdin = Some(config.path().to_path_buf());
191    config.remove_after(call(cx, step, &spec, LIMIT, Echo::Quiet).await)
192}
193
194/// Where each VM of the run with Proxmox's console stands on its server, by machine name, as the
195/// server's API says (`cluster/resources`, every VM of the cluster it lets the run's credentials
196/// see, wherever it migrated): running, stopped, or absent when the server no longer has it (its
197/// web UI's Remove). `vars` holds the run's params and outputs (each VM's id). Nothing for a run
198/// whose VMs have no such console, no id yet, or whose connection gives no credentials; nothing
199/// either when the server can't be asked (unreachable, an answer that isn't the API's), traced:
200/// the run's own state then stands.
201///
202/// # Errors
203///
204/// `server_auth_failed` when the server refuses the credentials (401, 403); a value of the
205/// console that can't be filled.
206pub(crate) async fn vm_states(cx: &Cx<'_>, vars: &crate::vars::Vars) -> Result<std::collections::BTreeMap<String, crate::MachineState>> {
207    let mut out = std::collections::BTreeMap::new();
208    let vms = proxmox_vms(cx, vars)?;
209    let Some((_, first)) = vms.first() else { return Ok(out) };
210    let Some(sign_in) = status_sign_in(cx, vars, first).await? else {
211        return Ok(out);
212    };
213    let url = format!("{}/api2/json/cluster/resources?type=vm", first.base);
214    let Some(answer) = asked(request(cx, "status", (&url, None), first.insecure, &sign_in.lines(false)).await) else {
215        return Ok(out);
216    };
217    let Some(listed) = answered(cx, vars, &answer)? else { return Ok(out) };
218    for (name, vm) in &vms {
219        let found = listed.iter().find(|r| {
220            r.get("vmid")
221                .and_then(|v| v.as_u64().map(|n| n.to_string()).or_else(|| v.as_str().map(str::to_owned)))
222                .as_deref()
223                == Some(vm.id.as_str())
224        });
225        let state = match found.and_then(|r| r.get("status")).and_then(serde_json::Value::as_str) {
226            None if found.is_none() => crate::MachineState::Absent,
227            Some("running") => crate::MachineState::Running,
228            Some("stopped") => crate::MachineState::Stopped,
229            Some(other) => crate::MachineState::Unknown(other.to_owned()),
230            None => continue,
231        };
232        out.insert(name.clone(), state);
233    }
234    Ok(out)
235}
236
237/// One VM as its Proxmox console names it, filled.
238struct ApiVm<'m> {
239    /// The API's address, without its last `/`.
240    base: String,
241    /// Its id on the server.
242    id: String,
243    /// The server's certificate isn't verified.
244    insecure: bool,
245    /// The console's sign-in: its user, token slot and password slot.
246    sign_in: (
247        &'m isoloom_manifest::Template,
248        &'m isoloom_manifest::Identifier,
249        &'m isoloom_manifest::Identifier,
250    ),
251}
252
253/// The run's VMs with Proxmox's console and an id `vars` fills, by machine name.
254fn proxmox_vms<'m>(cx: &Cx<'m>, vars: &crate::vars::Vars) -> Result<Vec<(String, ApiVm<'m>)>> {
255    let mut out = Vec::new();
256    for m in &cx.run.manifest().machines {
257        let source = m.consoles.iter().find_map(|c| match &c.source {
258            Some(s @ ConsoleSource::ProxmoxApi { .. }) => Some(s),
259            _ => None,
260        });
261        let Some(ConsoleSource::ProxmoxApi {
262            endpoint,
263            vm_id,
264            insecure,
265            username,
266            token,
267            password,
268            ..
269        }) = source
270        else {
271            continue;
272        };
273        let at = |f: &str| format!("machines.{}.consoles.source.{f}", m.name);
274        // Before its first apply (or from a state of an older module), the run has no id.
275        let Ok(id) = vars.render(vm_id, &at("vm_id")) else { continue };
276        if id.is_empty() || !id.chars().all(|c| c.is_ascii_digit()) {
277            continue;
278        }
279        let base = vars.render(endpoint, &at("endpoint"))?.trim_end_matches('/').to_owned();
280        let insecure = vars.render(insecure, &at("insecure"))?.trim() == "true";
281        out.push((
282            m.name.to_string(),
283            ApiVm {
284                base,
285                id,
286                insecure,
287                sign_in: (username, token, password),
288            },
289        ));
290    }
291    Ok(out)
292}
293
294/// How a status read signs in to the API: the connection's token, else a ticket for its password;
295/// none when it gives neither (the run's state then stands).
296async fn status_sign_in(cx: &Cx<'_>, vars: &crate::vars::Vars, vm: &ApiVm<'_>) -> Result<Option<SignIn>> {
297    let (username, token, password) = vm.sign_in;
298    let value = |slot: &isoloom_manifest::Identifier| cx.secrets.get(slot.as_str()).map(|v| v.expose().to_owned()).filter(|v| !v.is_empty());
299    if let Some(t) = value(token) {
300        return Ok(Some(SignIn::Token(t)));
301    }
302    let Some(p) = value(password) else { return Ok(None) };
303    let user = vars.render(username, "consoles.source.username")?;
304    let fields = [
305        format!("data-urlencode = {}", quoted(&format!("username={user}"))),
306        format!("data-urlencode = {}", quoted(&format!("password={p}"))),
307    ];
308    let url = format!("{}/api2/json/access/ticket", vm.base);
309    let Some(answer) = asked(request(cx, "status", (&url, Some("POST")), vm.insecure, &fields).await) else {
310        return Ok(None);
311    };
312    let Some(data) = data_of(cx, vars, &answer)? else { return Ok(None) };
313    let field = |k: &str| data.get(k).and_then(serde_json::Value::as_str).map(str::to_owned);
314    Ok(field("ticket")
315        .zip(field("CSRFPreventionToken"))
316        .map(|(ticket, csrf)| SignIn::Ticket { ticket, csrf }))
317}
318
319/// What `curl` answered a status read, when it ran to its end; a request that couldn't (`curl`
320/// missing, the server silent past the limit) is traced, and the run's state then stands.
321fn asked(done: Result<crate::process::Captured>) -> Option<crate::process::Captured> {
322    done.map_err(|e| tracing::warn!(error = %e, "Proxmox's API couldn't be asked where the run's VMs stand: its state stands"))
323        .ok()
324}
325
326/// The list a status read's `answer` holds; none when the API couldn't be asked (traced).
327fn answered(cx: &Cx<'_>, vars: &crate::vars::Vars, answer: &crate::process::Captured) -> Result<Option<Vec<serde_json::Value>>> {
328    Ok(data_of(cx, vars, answer)?.and_then(|d| d.as_array().cloned()))
329}
330
331/// The `data` of the API's `answer`; none when it didn't answer one (unreachable, not the API),
332/// which is traced.
333///
334/// # Errors
335///
336/// `server_auth_failed` when it refused the credentials.
337fn data_of(cx: &Cx<'_>, vars: &crate::vars::Vars, answer: &crate::process::Captured) -> Result<Option<serde_json::Value>> {
338    if !answer.success() {
339        let reason = cx.events.mask(&answer.reason());
340        if crate::server_auth::refused(&reason) {
341            return Err(Error::ServerAuthFailed {
342                step: "status".into(),
343                server: crate::server_auth::server_of(vars.params()),
344                reason,
345            });
346        }
347        tracing::warn!(%reason, "Proxmox's API couldn't be asked where the run's VMs stand: its state stands");
348        return Ok(None);
349    }
350    match serde_json::from_str::<serde_json::Value>(&answer.stdout.join("\n")) {
351        Ok(body) => Ok(body.get("data").cloned()),
352        Err(e) => {
353            tracing::warn!(error = %e, "Proxmox's API answered no JSON: the run's state stands");
354            Ok(None)
355        }
356    }
357}
358
359/// `s` as a double-quoted value of a curl config file (`\` and `"` escaped).
360fn quoted(s: &str) -> String {
361    format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"").replace('\n', "\\n").replace('\r', "\\r"))
362}
363
364/// Whether `s` is a node name that goes in a URL path as it is.
365fn plain(s: &str) -> bool {
366    !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '.')
367}
368
369/// `s` percent-encoded for a query value: every byte but an unreserved one.
370fn encoded(s: &str) -> String {
371    s.bytes()
372        .map(|b| {
373            if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
374                char::from(b).to_string()
375            } else {
376                format!("%{b:02X}")
377            }
378        })
379        .collect()
380}
381
382#[cfg(test)]
383mod tests {
384    use super::*;
385
386    #[test]
387    fn a_ticket_is_encoded_for_the_url_and_a_value_quoted_for_curl() {
388        assert_eq!(encoded("PVEVNC:6A3F::a+b/c="), "PVEVNC%3A6A3F%3A%3Aa%2Bb%2Fc%3D");
389        assert_eq!(quoted(r#"a"b\c"#), r#""a\"b\\c""#);
390        assert_eq!(quoted("x\ny"), "\"x\\ny\"", "a new line can't start another option");
391        assert!(plain("pve-1") && !plain("pve/../x") && !plain(""));
392    }
393
394    #[test]
395    fn a_token_or_a_ticket_signs_the_websocket_in() {
396        let t = SignIn::Token("root@pam!x=s3cr3t".into());
397        assert_eq!(t.lines(true), ["header = \"Authorization: PVEAPIToken=root@pam!x=s3cr3t\""]);
398        assert_eq!(t.header().0, "Authorization");
399        let k = SignIn::Ticket {
400            ticket: "PVE:t".into(),
401            csrf: "c".into(),
402        };
403        assert_eq!(k.lines(true), ["cookie = \"PVEAuthCookie=PVE:t\"", "header = \"CSRFPreventionToken: c\""]);
404        assert_eq!(k.header(), ("Cookie".to_owned(), SecretValue::new("PVEAuthCookie=PVE:t")));
405    }
406}