Skip to main content

isothrum_machine/place/proxmox/
bootstrap.rs

1//! Setting a Proxmox VE node up over SSH, signed in with a key the node already lets in (a user's
2//! own): a second key (the caller's, made by [`ssh::ensure_key`](crate::place::ssh::ensure_key))
3//! is let into the user's `authorized_keys`, then an API token is (re)made with `pveum`, its
4//! secret returned once. The node's host key must already be confirmed in the target's
5//! `known_hosts` ([`known_hosts`](crate::place::ssh::known_hosts)).
6
7use std::fmt::Write as _;
8use std::time::Duration;
9
10use serde::Deserialize;
11use sha2::{Digest as _, Sha256};
12
13use super::is_token;
14use crate::Context;
15use crate::place::ssh::{SshError, Target, sh_quote};
16
17/// The most one SSH call to the node may take.
18const SSH_LIMIT: Duration = Duration::from_secs(60);
19
20/// The longest token secret taken from `pveum`'s answer: Proxmox's are UUIDs (36 characters);
21/// anything far longer is not a secret but something else printed.
22const MAX_SECRET_LEN: usize = 128;
23
24/// A token name for the key `public` on a node: `prefix`, a dash and the first 8 hex digits of the
25/// key's SHA-256, so two computers set up on one node each keep their own token, and setting up
26/// again from one replaces its own.
27#[must_use]
28pub fn token_name(prefix: &str, public: &str) -> String {
29    let digest = Sha256::digest(public.trim().as_bytes());
30    let mut short = String::with_capacity(8);
31    for b in digest.iter().take(4) {
32        let _written = write!(short, "{b:02x}");
33    }
34    format!("{prefix}-{short}")
35}
36
37/// The node command that (re)makes token `name` of `user@pam`: an older token of the same name is
38/// removed first, since Proxmox shows a token's secret only when it is made. Privilege separation
39/// off: the token acts as its user.
40fn token_command(user: &str, name: &str) -> String {
41    let (user, name) = (sh_quote(&format!("{user}@pam")), sh_quote(name));
42    format!("pveum user token remove {user} {name} >/dev/null 2>&1; pveum user token add {user} {name} --privsep 0 --output-format json")
43}
44
45/// The node command that adds `public` to the user's `authorized_keys` unless it is there
46/// already, printing `added` or `present`.
47fn authorize_command(public: &str) -> String {
48    let key = sh_quote(public.trim());
49    format!(
50        "umask 077; mkdir -p ~/.ssh; if grep -qxF {key} ~/.ssh/authorized_keys 2>/dev/null; then echo present; else echo {key} >> ~/.ssh/authorized_keys && echo added; fi"
51    )
52}
53
54/// An API token `pveum user token add` made.
55#[derive(Clone, PartialEq, Eq)]
56pub struct ApiToken {
57    /// Its full id, `user@realm!name`.
58    pub id: String,
59    /// The value the API is called with; shown once.
60    pub secret: String,
61}
62
63impl std::fmt::Debug for ApiToken {
64    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65        f.debug_struct("ApiToken").field("id", &self.id).finish_non_exhaustive()
66    }
67}
68
69/// `pveum`'s JSON answer.
70#[derive(Deserialize)]
71struct Added {
72    #[serde(rename = "full-tokenid", default)]
73    id: String,
74    #[serde(rename = "value", default)]
75    secret: String,
76}
77
78/// The token in `pveum user token add --output-format json`'s answer; why not, when it has none.
79fn parse_token(out: &str) -> Result<ApiToken, String> {
80    let json = out
81        .lines()
82        .find(|l| l.trim_start().starts_with('{'))
83        .ok_or_else(|| format!("pveum gave no token: {}", out.trim()))?;
84    let added: Added = serde_json::from_str(json).map_err(|e| format!("pveum's answer isn't JSON ({e})"))?;
85    let secret_ok = !added.secret.is_empty() && added.secret.len() <= MAX_SECRET_LEN && added.secret.chars().all(|c| c.is_ascii_alphanumeric() || c == '-');
86    if !is_token(&added.id) || !secret_ok {
87        return Err("pveum's answer has no token id and secret".to_owned());
88    }
89    Ok(ApiToken {
90        id: added.id,
91        secret: added.secret,
92    })
93}
94
95/// Which part of the setup failed.
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97#[non_exhaustive]
98pub enum Part {
99    /// Signing in to the node over SSH (no connection, the key refused, a host key not confirmed).
100    Ssh,
101    /// Letting the second key in.
102    Key,
103    /// Making the API token.
104    Token,
105}
106
107/// A failed part and why.
108#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
109#[error("{part:?}: {detail}")]
110pub struct BootstrapError {
111    /// The part that failed.
112    pub part: Part,
113    /// Why, in the words of the tool that failed.
114    pub detail: String,
115    /// The node's host key wasn't one confirmed for it.
116    pub host_key_refused: bool,
117}
118
119/// Whether ssh itself failed (no connection, the key refused, an unknown host key), rather than
120/// the command it ran on the node.
121fn ssh_failed(said: &str) -> bool {
122    [
123        "Permission denied",
124        "Connection refused",
125        "Connection timed out",
126        "Operation timed out",
127        "No route to host",
128        "Could not resolve",
129        "Host key verification failed",
130        "Too many authentication failures",
131        "Load key",
132        "Connection closed",
133        "kex_exchange_identification",
134    ]
135    .iter()
136    .any(|m| said.contains(m))
137}
138
139/// The failure of `part` when SSH gave `e`: ssh's own when ssh itself failed.
140fn failure(e: &SshError, part: Part) -> BootstrapError {
141    let host_key_refused = matches!(e, SshError::HostKeyRefused { .. });
142    let part = match e {
143        SshError::Failed(said) if !ssh_failed(said) => part,
144        _ => Part::Ssh,
145    };
146    BootstrapError {
147        part,
148        detail: e.to_string(),
149        host_key_refused,
150    }
151}
152
153/// Lets `public` into the `authorized_keys` of `node`'s user, over SSH as `node` says; `true` when
154/// it was added, `false` when it was there already.
155///
156/// # Errors
157///
158/// SSH failed ([`Part::Ssh`]), or the node's answer wasn't `added` or `present` ([`Part::Key`]).
159pub async fn authorize(ctx: &Context, node: &Target, public: &str) -> Result<bool, BootstrapError> {
160    let out = node
161        .exec(ctx, &authorize_command(public), SSH_LIMIT)
162        .await
163        .map_err(|e| failure(&e, Part::Key))?;
164    if out.lines().any(|l| l.trim() == "added") {
165        Ok(true)
166    } else if out.lines().any(|l| l.trim() == "present") {
167        Ok(false)
168    } else {
169        Err(BootstrapError {
170            part: Part::Key,
171            detail: format!("unexpected answer: {}", out.trim()),
172            host_key_refused: false,
173        })
174    }
175}
176
177/// What [`bootstrap`] set up.
178#[derive(Debug, Clone, PartialEq, Eq)]
179pub struct Made {
180    /// The token made.
181    pub token: ApiToken,
182    /// Whether the key was added now (false: it was there already).
183    pub key_added: bool,
184}
185
186/// Sets `node` up over SSH as `node` says: lets `public` in (first: it also proves SSH works
187/// before anything is changed), then (re)makes the API token `token_name` of `node`'s user (in the
188/// `pam` realm).
189///
190/// # Errors
191///
192/// The part that failed, and why.
193pub async fn bootstrap(ctx: &Context, node: &Target, public: &str, token_name: &str) -> Result<Made, BootstrapError> {
194    let key_added = authorize(ctx, node, public).await?;
195    let out = node
196        .exec(ctx, &token_command(&node.user, token_name), SSH_LIMIT)
197        .await
198        .map_err(|e| failure(&e, Part::Token))?;
199    let token = parse_token(&out).map_err(|detail| BootstrapError {
200        part: Part::Token,
201        detail,
202        host_key_refused: false,
203    })?;
204    Ok(Made { token, key_added })
205}
206
207#[cfg(test)]
208mod tests;