use super::*;
pub fn api_token_path() -> PathBuf {
mj_core::config::data_dir().join(API_TOKEN_FILE)
}
pub fn load_or_create_api_token(path: &std::path::Path) -> AnyResult<String> {
match std::fs::read_to_string(path) {
Ok(token) if token.trim().len() >= 32 => return Ok(token.trim().to_owned()),
Ok(token) => tracing::warn!(
path = %path.display(),
bytes = token.trim().len(),
"Mjolnir API token is too short; generating a new one revokes the old token"
),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => tracing::warn!(
path = %path.display(),
"could not read the Mjolnir API token ({error}); generating a new one revokes the old token"
),
}
let mut bytes = [0_u8; API_TOKEN_BYTES];
getrandom::fill(&mut bytes)
.map_err(|error| anyhow::anyhow!("generate Mjolnir API token: {error}"))?;
let token = mj_core::hex::lower_hex(bytes);
mj_core::config::atomic_write(path, token.as_bytes())
.with_context(|| format!("persist Mjolnir API token {}", path.display()))?;
Ok(token)
}
pub fn certificate_der_sha256(der: &[u8]) -> String {
use sha2::Digest;
mj_core::hex::lower_hex(sha2::Sha256::digest(der))
}
pub fn served_certificate_sha256(pem: &[u8]) -> AnyResult<String> {
use rustls::pki_types::CertificateDer;
use rustls::pki_types::pem::PemObject;
let leaf = CertificateDer::pem_slice_iter(pem)
.next()
.context("the certificate file holds no PEM certificate")?
.context("parse the PEM certificate")?;
Ok(certificate_der_sha256(&leaf))
}