isothrum_machine/place/proxmox/
bootstrap.rs1use 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
17const SSH_LIMIT: Duration = Duration::from_secs(60);
19
20const MAX_SECRET_LEN: usize = 128;
23
24#[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
37fn 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
45fn 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#[derive(Clone, PartialEq, Eq)]
56pub struct ApiToken {
57 pub id: String,
59 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#[derive(Deserialize)]
71struct Added {
72 #[serde(rename = "full-tokenid", default)]
73 id: String,
74 #[serde(rename = "value", default)]
75 secret: String,
76}
77
78fn 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97#[non_exhaustive]
98pub enum Part {
99 Ssh,
101 Key,
103 Token,
105}
106
107#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
109#[error("{part:?}: {detail}")]
110pub struct BootstrapError {
111 pub part: Part,
113 pub detail: String,
115 pub host_key_refused: bool,
117}
118
119fn 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
139fn 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
153pub 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#[derive(Debug, Clone, PartialEq, Eq)]
179pub struct Made {
180 pub token: ApiToken,
182 pub key_added: bool,
184}
185
186pub 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;