use crate::encoding::{base64_bytes, Sha256Hash};
use crate::error::{Error, Result};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Checkpoint {
pub origin: String,
pub tree_size: u64,
pub root_hash: Sha256Hash,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub other_content: Vec<String>,
pub signatures: Vec<CheckpointSignature>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CheckpointSignature {
#[serde(with = "base64_bytes")]
pub key_id: Vec<u8>,
#[serde(with = "base64_bytes")]
pub signature: Vec<u8>,
}
impl Checkpoint {
pub fn from_text(text: &str) -> Result<Self> {
use base64::{engine::general_purpose::STANDARD, Engine};
let mut lines = text.lines();
let origin = lines
.next()
.ok_or_else(|| Error::InvalidCheckpoint("missing origin".to_string()))?
.trim()
.to_string();
let tree_size_str = lines
.next()
.ok_or_else(|| Error::InvalidCheckpoint("missing tree size".to_string()))?
.trim();
let tree_size = tree_size_str
.parse()
.map_err(|_| Error::InvalidCheckpoint("invalid tree size".to_string()))?;
let root_hash_b64 = lines
.next()
.ok_or_else(|| Error::InvalidCheckpoint("missing root hash".to_string()))?
.trim();
let root_hash_bytes = STANDARD
.decode(root_hash_b64)
.map_err(|_| Error::InvalidCheckpoint("invalid root hash base64".to_string()))?;
let root_hash = Sha256Hash::try_from_slice(&root_hash_bytes)
.map_err(|e| Error::InvalidCheckpoint(format!("invalid root hash: {}", e)))?;
let mut other_content = Vec::new();
let mut signatures = Vec::new();
for line in lines {
if line.is_empty() {
continue;
}
if line.starts_with("— ") || line.starts_with("\u{2014} ") {
let content = if let Some(stripped) = line.strip_prefix("— ") {
stripped
} else if let Some(stripped) = line.strip_prefix("\u{2014} ") {
stripped
} else {
unreachable!("line must start with one of the prefixes")
};
let parts: Vec<&str> = content.splitn(2, ' ').collect();
if parts.len() != 2 {
return Err(Error::InvalidCheckpoint(
"invalid signature line format".to_string(),
));
}
let key_and_sig = parts[1];
let decoded = STANDARD.decode(key_and_sig).map_err(|_| {
Error::InvalidCheckpoint("invalid signature base64".to_string())
})?;
if decoded.len() < 4 {
return Err(Error::InvalidCheckpoint(
"signature too short for key_id".to_string(),
));
}
let key_id = decoded[..4].to_vec();
let signature = decoded[4..].to_vec();
signatures.push(CheckpointSignature { key_id, signature });
} else {
other_content.push(line.to_string());
}
}
Ok(Checkpoint {
origin,
tree_size,
root_hash,
other_content,
signatures,
})
}
pub fn to_signed_note_body(&self) -> String {
let mut result = format!(
"{}\n{}\n{}\n",
self.origin,
self.tree_size,
self.root_hash.to_base64()
);
for line in &self.other_content {
result.push_str(line);
result.push('\n');
}
result
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_checkpoint() {
let checkpoint_text = "rekor.sigstore.dev - 1193050959916656506
42591958
npv1T/m9N8zX0jPlbh4rB51zL6GpnV9bQaXSOdzAV+s=
— rekor.sigstore.dev wNI9ajBFAiEA0OP4Pv5ks5MoTTwcM0kS6HMn8gZ5fFPjT9s6vVqXgHkCIDCe5qWSdM4OXpCQ1YNP2KpLo1r/2dRfFHXkPR5h3ywe
";
let checkpoint = Checkpoint::from_text(checkpoint_text).unwrap();
assert_eq!(
checkpoint.origin,
"rekor.sigstore.dev - 1193050959916656506"
);
assert_eq!(checkpoint.tree_size, 42591958);
assert_eq!(checkpoint.root_hash.as_bytes().len(), 32); assert_eq!(checkpoint.signatures.len(), 1);
}
}