1use 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
20const LIMIT: Duration = Duration::from_secs(30);
22
23const CONFIG: &str = "proxmox-console.curl";
25
26#[derive(Debug, Clone, PartialEq, Eq)]
30#[non_exhaustive]
31pub struct ProxmoxVnc {
32 pub websocket: SecretValue,
35 pub port: u16,
37 pub ticket: SecretValue,
39 pub authorization: (String, SecretValue),
41 pub insecure: bool,
43}
44
45enum SignIn {
47 Token(String),
49 Ticket { ticket: String, csrf: String },
51}
52
53impl SignIn {
54 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 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
77pub(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
124async 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
157async 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
171async 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("ed(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
194pub(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
237struct ApiVm<'m> {
239 base: String,
241 id: String,
243 insecure: bool,
245 sign_in: (
247 &'m isoloom_manifest::Template,
248 &'m isoloom_manifest::Identifier,
249 &'m isoloom_manifest::Identifier,
250 ),
251}
252
253fn 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 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
294async 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
319fn 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
326fn 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
331fn 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
359fn quoted(s: &str) -> String {
361 format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"").replace('\n', "\\n").replace('\r', "\\r"))
362}
363
364fn plain(s: &str) -> bool {
366 !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '.')
367}
368
369fn 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}