use std::fmt::Write as _;
use std::time::Duration;
use serde::Deserialize;
use sha2::{Digest as _, Sha256};
use super::is_token;
use crate::Context;
use crate::place::ssh::{SshError, Target, sh_quote};
const SSH_LIMIT: Duration = Duration::from_secs(60);
const MAX_SECRET_LEN: usize = 128;
#[must_use]
pub fn token_name(prefix: &str, public: &str) -> String {
let digest = Sha256::digest(public.trim().as_bytes());
let mut short = String::with_capacity(8);
for b in digest.iter().take(4) {
let _written = write!(short, "{b:02x}");
}
format!("{prefix}-{short}")
}
fn token_command(user: &str, name: &str) -> String {
let (user, name) = (sh_quote(&format!("{user}@pam")), sh_quote(name));
format!("pveum user token remove {user} {name} >/dev/null 2>&1; pveum user token add {user} {name} --privsep 0 --output-format json")
}
fn authorize_command(public: &str) -> String {
let key = sh_quote(public.trim());
format!(
"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"
)
}
#[derive(Clone, PartialEq, Eq)]
pub struct ApiToken {
pub id: String,
pub secret: String,
}
impl std::fmt::Debug for ApiToken {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ApiToken").field("id", &self.id).finish_non_exhaustive()
}
}
#[derive(Deserialize)]
struct Added {
#[serde(rename = "full-tokenid", default)]
id: String,
#[serde(rename = "value", default)]
secret: String,
}
fn parse_token(out: &str) -> Result<ApiToken, String> {
let json = out
.lines()
.find(|l| l.trim_start().starts_with('{'))
.ok_or_else(|| format!("pveum gave no token: {}", out.trim()))?;
let added: Added = serde_json::from_str(json).map_err(|e| format!("pveum's answer isn't JSON ({e})"))?;
let secret_ok = !added.secret.is_empty() && added.secret.len() <= MAX_SECRET_LEN && added.secret.chars().all(|c| c.is_ascii_alphanumeric() || c == '-');
if !is_token(&added.id) || !secret_ok {
return Err("pveum's answer has no token id and secret".to_owned());
}
Ok(ApiToken {
id: added.id,
secret: added.secret,
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Part {
Ssh,
Key,
Token,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{part:?}: {detail}")]
pub struct BootstrapError {
pub part: Part,
pub detail: String,
pub host_key_refused: bool,
}
fn ssh_failed(said: &str) -> bool {
[
"Permission denied",
"Connection refused",
"Connection timed out",
"Operation timed out",
"No route to host",
"Could not resolve",
"Host key verification failed",
"Too many authentication failures",
"Load key",
"Connection closed",
"kex_exchange_identification",
]
.iter()
.any(|m| said.contains(m))
}
fn failure(e: &SshError, part: Part) -> BootstrapError {
let host_key_refused = matches!(e, SshError::HostKeyRefused { .. });
let part = match e {
SshError::Failed(said) if !ssh_failed(said) => part,
_ => Part::Ssh,
};
BootstrapError {
part,
detail: e.to_string(),
host_key_refused,
}
}
pub async fn authorize(ctx: &Context, node: &Target, public: &str) -> Result<bool, BootstrapError> {
let out = node
.exec(ctx, &authorize_command(public), SSH_LIMIT)
.await
.map_err(|e| failure(&e, Part::Key))?;
if out.lines().any(|l| l.trim() == "added") {
Ok(true)
} else if out.lines().any(|l| l.trim() == "present") {
Ok(false)
} else {
Err(BootstrapError {
part: Part::Key,
detail: format!("unexpected answer: {}", out.trim()),
host_key_refused: false,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Made {
pub token: ApiToken,
pub key_added: bool,
}
pub async fn bootstrap(ctx: &Context, node: &Target, public: &str, token_name: &str) -> Result<Made, BootstrapError> {
let key_added = authorize(ctx, node, public).await?;
let out = node
.exec(ctx, &token_command(&node.user, token_name), SSH_LIMIT)
.await
.map_err(|e| failure(&e, Part::Token))?;
let token = parse_token(&out).map_err(|detail| BootstrapError {
part: Part::Token,
detail,
host_key_refused: false,
})?;
Ok(Made { token, key_added })
}
#[cfg(test)]
mod tests;