use std::path::Path;
use serde::Deserialize;
use zeroize::{Zeroize as _, Zeroizing};
use crate::error::CliError;
use crate::private_file::{self, ModePolicy};
use crate::token::BootstrapToken;
const RESUME_VERSION: u32 = 1;
const RESUME_FILE_LIMIT: usize = 64 * 1024;
#[derive(Debug)]
pub(crate) struct ResumeRecord {
pub(crate) url: String,
pub(crate) authorization: String,
pub(crate) token: BootstrapToken,
pub(crate) claim_body: String,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Stored {
version: u32,
url: String,
authorization: String,
bootstrap_token: String,
claim_body: String,
}
impl ResumeRecord {
pub(crate) fn save(&self, path: &Path) -> Result<(), CliError> {
let mut value = serde_json::json!({
"version": RESUME_VERSION,
"url": self.url,
"authorization": self.authorization,
"bootstrap_token": self.token.expose(),
"claim_body": self.claim_body,
});
let bytes =
Zeroizing::new(serde_json::to_vec(&value).map_err(|err| {
CliError::Local(format!("encoding the resume file failed: {err}"))
})?);
if let Some(serde_json::Value::String(text)) = value.get_mut("bootstrap_token") {
text.zeroize();
}
private_file::create(path, &bytes).map_err(|source| CliError::File {
path: path.to_owned(),
source,
})
}
pub(crate) fn load(path: &Path) -> Result<Self, CliError> {
let bytes = private_file::read(path, RESUME_FILE_LIMIT, ModePolicy::OwnerOnly).map_err(
|source| CliError::File {
path: path.to_owned(),
source,
},
)?;
let malformed = |message: &str| CliError::FileContents {
path: path.to_owned(),
message: message.to_owned(),
};
let mut stored: Stored = serde_json::from_slice(&bytes)
.map_err(|_| malformed("not a stratum setup resume file"))?;
let token = BootstrapToken::parse(&stored.bootstrap_token);
stored.bootstrap_token.zeroize();
if stored.version != RESUME_VERSION {
return Err(malformed("unsupported resume file version"));
}
let token = token.ok_or_else(|| malformed("the saved bootstrap token is malformed"))?;
Ok(Self {
url: stored.url,
authorization: stored.authorization,
token,
claim_body: stored.claim_body,
})
}
}