use serde::{Deserialize, Serialize};
use crate::chunk::TransferChunks;
use crate::error::{BlobError, Result};
use crate::hash::Hash;
use crate::id::BlobId;
use crate::wire::WIRE_VERSION;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Manifest {
pub version: u16,
pub id: BlobId,
pub filename: Option<String>,
pub total_len: u64,
pub chunk_size: u32,
pub root: Hash,
pub created_ms: i64,
pub ext: crate::wire::Ext,
}
impl Manifest {
pub fn validate(&self, max_blob_size: u64) -> Result<()> {
if self.version != WIRE_VERSION {
return Err(BlobError::UnsupportedVersion(self.version));
}
TransferChunks::validate_chunk_size(self.chunk_size)?;
if self.total_len > max_blob_size {
return Err(BlobError::InvalidManifest(format!(
"total_len {} exceeds the configured max blob size {max_blob_size}",
self.total_len
)));
}
Ok(())
}
pub fn chunks(&self) -> Result<TransferChunks> {
TransferChunks::new(self.chunk_size, self.total_len)
}
pub fn max_chunks_per_query(&self) -> Option<u32> {
self.ext.get_u32(crate::wire::EXT_MAX_CHUNKS_PER_QUERY)
}
pub fn max_blob_size(&self) -> Option<u64> {
self.ext.get_u64(crate::wire::EXT_MAX_BLOB_SIZE)
}
pub fn chunk_count(&self) -> Result<u32> {
Ok(self.chunks()?.count())
}
pub fn suggested_filename(&self) -> Option<String> {
let raw = self.filename.as_deref()?;
let name = std::path::Path::new(raw)
.components()
.filter_map(|c| match c {
std::path::Component::Normal(s) => s.to_str(),
_ => None,
})
.next_back()?;
if name.is_empty() {
None
} else {
Some(name.to_string())
}
}
}
pub(crate) fn validate_id(id: &str) -> Result<()> {
BlobId::new(id).map(|_| ())
}
#[derive(Debug, Clone)]
pub struct BlobSpec {
pub(crate) id: String,
pub(crate) filename: Option<String>,
pub(crate) chunk_size: u32,
pub(crate) created_ms: i64,
}
impl BlobSpec {
pub fn new(id: impl Into<String>) -> Self {
BlobSpec {
id: id.into(),
filename: None,
chunk_size: crate::chunk::DEFAULT_CHUNK_SIZE,
created_ms: 0,
}
}
#[must_use]
pub fn filename(mut self, filename: impl Into<String>) -> Self {
self.filename = Some(filename.into());
self
}
#[must_use]
pub fn chunk_size(mut self, bytes: u32) -> Self {
self.chunk_size = bytes;
self
}
#[must_use]
pub fn created_ms(mut self, ms: i64) -> Self {
self.created_ms = ms;
self
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::chunk::DEFAULT_CHUNK_SIZE;
fn manifest() -> Manifest {
Manifest {
version: WIRE_VERSION,
id: BlobId::new("abc").unwrap(),
filename: Some("f.bin".into()),
total_len: DEFAULT_CHUNK_SIZE as u64 * 2 + 100,
chunk_size: DEFAULT_CHUNK_SIZE,
root: Hash::of(b"whatever"),
created_ms: 42,
ext: crate::wire::Ext::new(),
}
}
#[test]
fn valid_manifest_passes() {
let m = manifest();
m.validate(u64::MAX).unwrap();
assert_eq!(m.chunks().unwrap().count(), 3);
}
#[test]
fn wrong_version_rejected() {
for v in [2u16, 4] {
let m = Manifest {
version: v,
..manifest()
};
assert!(
matches!(m.validate(u64::MAX), Err(BlobError::UnsupportedVersion(got)) if got == v),
"version {v} should be refused"
);
}
}
#[test]
fn bad_chunk_size_rejected_not_clamped() {
for bad in [0u32, 1024, DEFAULT_CHUNK_SIZE + 1, u32::MAX] {
let m = Manifest {
chunk_size: bad,
..manifest()
};
assert!(m.validate(u64::MAX).is_err(), "chunk_size {bad}");
}
}
#[test]
fn oversized_blob_rejected() {
let m = Manifest {
total_len: 1024 * 1024 + 1,
..manifest()
};
assert!(m.validate(1024 * 1024).is_err());
}
#[test]
fn bad_ids_are_refused_at_decode_not_at_validate() {
let m = manifest();
let encode_with = |id: &str| {
crate::wire::encode(&(
m.version,
id.to_string(),
m.filename.clone(),
m.total_len,
m.chunk_size,
m.root,
m.created_ms,
m.ext.clone(),
))
.unwrap()
};
for bad in [
"",
"a/b",
"a*",
"a?x",
"..",
"a b",
"@verbatim",
"a\\b",
"@",
] {
assert!(
crate::wire::decode::<Manifest>(&encode_with(bad)).is_err(),
"id {bad:?} decoded"
);
}
let decoded = crate::wire::decode::<Manifest>(&encode_with("good-id")).unwrap();
assert_eq!(decoded.id, "good-id");
assert_eq!(decoded.root, m.root);
}
#[test]
fn leading_at_ids_would_be_unservable() {
let pattern: zenoh::key_expr::KeyExpr = "p/**".try_into().unwrap();
let verbatim: zenoh::key_expr::KeyExpr = "p/@id/manifest".try_into().unwrap();
let ordinary: zenoh::key_expr::KeyExpr = "p/x@y/manifest".try_into().unwrap();
assert!(
!pattern.intersects(&verbatim),
"if this ever passes, the leading-@ id rule can be relaxed"
);
assert!(pattern.intersects(&ordinary));
assert!(validate_id("@id").is_err());
assert!(validate_id("x@y").is_ok());
}
#[test]
fn suggested_filename_is_traversal_safe() {
let cases = [
(Some("report.pcap"), Some("report.pcap")),
(Some("/etc/passwd"), Some("passwd")),
(Some("../../x.bin"), Some("x.bin")),
(Some("a/b/c.txt"), Some("c.txt")),
(Some(".."), None),
(Some(""), None),
(None, None),
];
for (input, expected) in cases {
let m = Manifest {
filename: input.map(String::from),
..manifest()
};
assert_eq!(m.suggested_filename().as_deref(), expected, "{input:?}");
}
}
}