use std::collections::BTreeMap;
use std::fmt;
use serde::Deserialize;
use crate::signature::{Domain, Signature, SignatureError};
use super::corpus::DetectionError;
pub const MAX_DETECTIONS: usize = 4_096;
#[derive(Debug, Clone)]
pub struct Bundle {
name: String,
version: String,
entries: Vec<Entry>,
}
#[derive(Debug, Clone)]
pub struct Entry {
name: String,
tier: Tier,
source: String,
sha256: String,
}
impl Entry {
pub fn name(&self) -> &str {
&self.name
}
pub fn tier(&self) -> Tier {
self.tier
}
pub fn source(&self) -> &str {
&self.source
}
pub fn sha256(&self) -> &str {
&self.sha256
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Tier {
Flow,
Compute,
Host,
}
impl Tier {
pub const ALL: [Tier; 3] = [Self::Flow, Self::Compute, Self::Host];
}
#[non_exhaustive]
#[derive(Debug)]
pub enum BundleError {
Signature(SignatureError),
Manifest(String),
Missing {
name: String,
},
Altered {
name: String,
},
Unnamed {
name: String,
},
Duplicate {
name: String,
},
TooMany {
named: usize,
},
}
impl fmt::Display for BundleError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
BundleError::Signature(error) => {
write!(f, "the bundle's signature did not verify: {error}")
}
BundleError::Manifest(reason) => {
write!(f, "the bundle manifest is malformed: {reason}")
}
BundleError::Missing { name } => {
write!(
f,
"the manifest names '{name}' and no source was supplied for it"
)
}
BundleError::Altered { name } => write!(
f,
"'{name}' does not hash to what the manifest recorded, so it is not what was signed"
),
BundleError::Unnamed { name } => write!(
f,
"a source was supplied for '{name}', which the manifest does not name and the \
signature says nothing about"
),
BundleError::Duplicate { name } => {
write!(f, "the manifest names '{name}' more than once")
}
BundleError::TooMany { named } => write!(
f,
"the manifest names {named} detections, above the {MAX_DETECTIONS} a bundle may \
carry"
),
}
}
}
impl std::error::Error for BundleError {}
impl From<SignatureError> for BundleError {
fn from(error: SignatureError) -> Self {
BundleError::Signature(error)
}
}
impl Bundle {
pub fn verified(
manifest: &str,
signature: &Signature,
trusted_key: &[u8],
mut sources: BTreeMap<String, String>,
) -> Result<Self, BundleError> {
signature.verify(manifest.as_bytes(), trusted_key, Domain::DETECTIONS)?;
let document: ManifestDocument =
toml::from_str(manifest).map_err(|error| BundleError::Manifest(error.to_string()))?;
if document.detection.len() > MAX_DETECTIONS {
return Err(BundleError::TooMany {
named: document.detection.len(),
});
}
let mut entries = Vec::with_capacity(document.detection.len());
let mut seen: BTreeMap<&str, ()> = BTreeMap::new();
for named in &document.detection {
if seen.insert(named.name.as_str(), ()).is_some() {
return Err(BundleError::Duplicate {
name: named.name.clone(),
});
}
let source = sources
.remove(&named.name)
.ok_or_else(|| BundleError::Missing {
name: named.name.clone(),
})?;
if !hash_matches(&source, &named.sha256) {
return Err(BundleError::Altered {
name: named.name.clone(),
});
}
entries.push(Entry {
name: named.name.clone(),
tier: named.tier,
source,
sha256: named.sha256.clone(),
});
}
if let Some((name, _)) = sources.into_iter().next() {
return Err(BundleError::Unnamed { name });
}
Ok(Self {
name: document.bundle.name,
version: document.bundle.version,
entries,
})
}
pub fn name(&self) -> &str {
&self.name
}
pub fn version(&self) -> &str {
&self.version
}
pub fn entries(&self) -> &[Entry] {
&self.entries
}
pub fn publishable(
sources: &BTreeMap<String, String>,
) -> Result<BTreeMap<String, (Tier, String)>, DetectionError> {
let prepared = super::source::prepare(sources).map_err(DetectionError::from)?;
Ok(prepared
.into_iter()
.map(|detection| (detection.name, (detection.tier, detection.document)))
.collect())
}
#[must_use]
pub fn manifest(
name: &str,
version: &str,
sources: &BTreeMap<String, (Tier, String)>,
) -> String {
let mut document = format!(
"# A zond detection bundle. The signature beside this file covers these\n\
# bytes; each source is held to the hash recorded here.\n\
[bundle]\n\
name = \"{name}\"\n\
version = \"{version}\"\n"
);
for (source_name, (tier, source)) in sources {
document.push_str(&format!(
"\n[[detection]]\n\
name = \"{source_name}\"\n\
tier = \"{}\"\n\
sha256 = \"{}\"\n",
tier.name(),
sha256_hex(source),
));
}
document
}
}
impl Tier {
pub const fn name(self) -> &'static str {
match self {
Tier::Flow => "flow",
Tier::Compute => "compute",
Tier::Host => "host",
}
}
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct ManifestDocument {
bundle: BundleHeader,
#[serde(default)]
detection: Vec<NamedDetection>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct BundleHeader {
name: String,
version: String,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct NamedDetection {
name: String,
tier: Tier,
sha256: String,
}
fn hash_matches(source: &str, expected: &str) -> bool {
sha256_hex(source) == expected
}
#[must_use]
pub fn content_hash(source: &str) -> String {
sha256_hex(source)
}
fn sha256_hex(source: &str) -> String {
let digest = ring::digest::digest(&ring::digest::SHA256, source.as_bytes());
digest.as_ref().iter().fold(String::new(), |mut hex, byte| {
use std::fmt::Write;
let _ = write!(hex, "{byte:02x}");
hex
})
}
#[cfg(test)]
mod tests {
#[test]
fn the_list_of_tiers_holds_every_one_of_them_once() {
fn place(tier: super::Tier) -> usize {
match tier {
super::Tier::Flow => 0,
super::Tier::Compute => 1,
super::Tier::Host => 2,
}
}
let places: Vec<usize> = super::Tier::ALL.into_iter().map(place).collect();
assert_eq!(
places,
(0..super::Tier::ALL.len()).collect::<Vec<_>>(),
"every tier, once"
);
}
use super::*;
use crate::signature::{Signing, SigningKey};
use std::io::Write;
const FLOW: &str = r#"
[detection]
id = "bundle-test"
version = "1.0.0"
title = "Bundle test"
[detection.when]
service = "http"
[detection.capabilities]
class = "active-benign"
speak = "target"
[[step]]
send = "PING\r\n"
expect = "PONG"
on_no_match = "continue"
[[step.finding]]
when = "matched"
severity = "low"
summary = "the bundle test fired"
"#;
fn sources() -> BTreeMap<String, (Tier, String)> {
let mut sources = BTreeMap::new();
sources.insert("flow.toml".to_string(), (Tier::Flow, FLOW.to_string()));
sources
}
fn plain(sources: &BTreeMap<String, (Tier, String)>) -> BTreeMap<String, String> {
sources
.iter()
.map(|(name, (_, source))| (name.clone(), source.clone()))
.collect()
}
fn signed(manifest: &str) -> (SigningKey, Signature) {
let (_, key) = SigningKey::generate().expect("a key");
let mut sink = Vec::new();
let mut writer = Signing::new(&mut sink);
writer
.write_all(manifest.as_bytes())
.expect("the manifest is written");
let signature = writer.finish(&key, Domain::DETECTIONS);
(key, signature)
}
#[test]
fn a_bundle_this_crate_wrote_is_one_it_verifies() {
let sources = sources();
let manifest = Bundle::manifest("acme", "2026.09.1", &sources);
let (key, signature) = signed(&manifest);
let bundle = Bundle::verified(&manifest, &signature, &key.public_key(), plain(&sources))
.expect("the bundle verifies");
assert_eq!(bundle.name(), "acme");
assert_eq!(bundle.version(), "2026.09.1");
assert_eq!(bundle.entries().len(), 1);
assert_eq!(bundle.entries()[0].name(), "flow.toml");
assert_eq!(bundle.entries()[0].tier(), Tier::Flow);
assert_eq!(bundle.entries()[0].source(), FLOW);
assert_eq!(bundle.entries()[0].sha256().len(), 64, "a hex sha256");
}
#[test]
fn a_bundle_signed_by_another_key_is_refused() {
let sources = sources();
let manifest = Bundle::manifest("acme", "2026.09.1", &sources);
let (_, signature) = signed(&manifest);
let (_, recipient) = SigningKey::generate().expect("a key");
assert!(matches!(
Bundle::verified(
&manifest,
&signature,
&recipient.public_key(),
plain(&sources)
),
Err(BundleError::Signature(_))
));
}
#[test]
fn a_source_that_is_not_what_was_signed_is_refused() {
let sources = sources();
let manifest = Bundle::manifest("acme", "2026.09.1", &sources);
let (key, signature) = signed(&manifest);
let mut swapped = plain(&sources);
swapped.insert(
"flow.toml".to_string(),
FLOW.replace("active-benign", "exploit"),
);
assert!(matches!(
Bundle::verified(&manifest, &signature, &key.public_key(), swapped),
Err(BundleError::Altered { name }) if name == "flow.toml"
));
}
#[test]
fn a_detection_withheld_from_a_signed_set_is_refused() {
let sources = sources();
let manifest = Bundle::manifest("acme", "2026.09.1", &sources);
let (key, signature) = signed(&manifest);
assert!(matches!(
Bundle::verified(&manifest, &signature, &key.public_key(), BTreeMap::new()),
Err(BundleError::Missing { name }) if name == "flow.toml"
));
}
#[test]
fn a_source_the_manifest_does_not_name_is_refused() {
let sources = sources();
let manifest = Bundle::manifest("acme", "2026.09.1", &sources);
let (key, signature) = signed(&manifest);
let mut extra = plain(&sources);
extra.insert("smuggled.toml".to_string(), FLOW.to_string());
assert!(matches!(
Bundle::verified(&manifest, &signature, &key.public_key(), extra),
Err(BundleError::Unnamed { name }) if name == "smuggled.toml"
));
}
#[test]
fn a_manifest_altered_after_signing_is_refused() {
let sources = sources();
let manifest = Bundle::manifest("acme", "2026.09.1", &sources);
let (key, signature) = signed(&manifest);
let edited = manifest.replace("2026.09.1", "2026.09.2");
assert!(matches!(
Bundle::verified(&edited, &signature, &key.public_key(), plain(&sources)),
Err(BundleError::Signature(_))
));
}
#[test]
fn the_tier_is_the_manifests_and_not_the_sources() {
let mut sources = BTreeMap::new();
sources.insert("thing.toml".to_string(), (Tier::Compute, FLOW.to_string()));
let manifest = Bundle::manifest("acme", "1", &sources);
let (key, signature) = signed(&manifest);
let bundle = Bundle::verified(&manifest, &signature, &key.public_key(), plain(&sources))
.expect("the bundle verifies");
assert_eq!(bundle.entries()[0].tier(), Tier::Compute);
}
#[test]
fn a_manifest_naming_one_detection_twice_is_refused() {
let sources = sources();
let manifest = Bundle::manifest("acme", "1", &sources);
let doubled = format!(
"{manifest}\n[[detection]]\nname = \"flow.toml\"\ntier = \"flow\"\nsha256 = \"{}\"\n",
sha256_hex(FLOW)
);
let (key, signature) = signed(&doubled);
assert!(matches!(
Bundle::verified(&doubled, &signature, &key.public_key(), plain(&sources)),
Err(BundleError::Duplicate { name }) if name == "flow.toml"
));
}
#[test]
fn a_bundle_carrying_nothing_verifies_and_carries_nothing() {
let manifest = Bundle::manifest("acme", "2026.09.2", &BTreeMap::new());
let (key, signature) = signed(&manifest);
let bundle = Bundle::verified(&manifest, &signature, &key.public_key(), BTreeMap::new())
.expect("an empty bundle is a bundle");
assert!(bundle.entries().is_empty());
}
}