use boon::{Compiler, Schemas};
use serde_json::Value;
use crate::config::{OsDetection, ServiceDetection};
use crate::export::schema::SCHEMA_VERSION;
use crate::export::{ExportOptions, Exporter, JsonExporter, Redaction, fixture};
use crate::model::technique::TcpScanTechnique;
const SCHEMA: &str = include_str!("../../assets/schema/zond-report-v1.schema.json");
const LINES_SCHEMA: &str = include_str!("../../assets/schema/zond-lines-v1.schema.json");
const DIFF_SCHEMA: &str = include_str!("../../assets/schema/zond-diff-v1.schema.json");
const SCHEMA_URL: &str = "https://zond.rs/schema/zond-report-v1.schema.json";
const LINES_SCHEMA_URL: &str = "https://zond.rs/schema/zond-lines-v1.schema.json";
const DIFF_SCHEMA_URL: &str = "https://zond.rs/schema/zond-diff-v1.schema.json";
struct Validator {
schemas: Schemas,
index: boon::SchemaIndex,
}
impl Validator {
fn new() -> Self {
Self::over(SCHEMA_URL)
}
fn lines() -> Self {
Self::over(LINES_SCHEMA_URL)
}
fn diff() -> Self {
Self::over(DIFF_SCHEMA_URL)
}
fn over(url: &str) -> Self {
let mut schemas = Schemas::new();
let mut compiler = Compiler::new();
for (id, text) in [
(SCHEMA_URL, SCHEMA),
(LINES_SCHEMA_URL, LINES_SCHEMA),
(DIFF_SCHEMA_URL, DIFF_SCHEMA),
] {
let document: Value =
serde_json::from_str(text).expect("the schema file is valid JSON");
compiler
.add_resource(id, document)
.expect("the schema file is a usable resource");
}
let index = compiler
.compile(url, &mut schemas)
.expect("the schema file compiles");
Self { schemas, index }
}
fn check(&self, document: &Value) {
if let Err(error) = self.schemas.validate(document, self.index) {
panic!("the exported document does not match the published schema:\n{error:#}");
}
}
fn accepts(&self, document: &Value) -> bool {
self.schemas.validate(document, self.index).is_ok()
}
}
fn document(options: ExportOptions) -> Value {
let mut bytes = Vec::new();
JsonExporter::new(options)
.export(&fixture::report(), &mut bytes)
.expect("the export succeeds");
serde_json::from_slice(&bytes).expect("the export parses as JSON")
}
#[test]
fn the_published_schema_compiles() {
let _ = Validator::new();
}
#[test]
fn the_schema_pins_the_version_the_code_emits() {
let schema: Value = serde_json::from_str(SCHEMA).expect("valid JSON");
assert_eq!(
schema["properties"]["schema_version"]["const"],
Value::from(SCHEMA_VERSION)
);
}
#[test]
fn every_technique_the_engine_runs_is_a_value_the_schema_accepts() {
let schema: Value = serde_json::from_str(SCHEMA).expect("valid JSON");
let accepted = schema["$defs"]["settings"]["properties"]["tcp_technique"]["enum"]
.as_array()
.expect("the schema names the techniques it accepts");
for technique in TcpScanTechnique::ALL {
assert!(
accepted.contains(&Value::from(technique.name())),
"the schema does not accept `{technique}`, which a scan can be asked for"
);
}
}
#[test]
fn every_os_detection_level_the_engine_runs_is_a_value_the_schema_accepts() {
let schema: Value = serde_json::from_str(SCHEMA).expect("valid JSON");
let accepted = schema["$defs"]["settings"]["properties"]["os_detection"]["enum"]
.as_array()
.expect("the schema names the levels it accepts");
for detection in OsDetection::ALL {
assert!(
accepted.contains(&Value::from(detection.name())),
"the schema does not accept `{detection}`, which a scan can be asked for"
);
}
}
#[test]
fn every_service_detection_level_the_engine_runs_is_a_value_the_schema_accepts() {
let schema: Value = serde_json::from_str(SCHEMA).expect("valid JSON");
let accepted = schema["$defs"]["settings"]["properties"]["service_detection"]["enum"]
.as_array()
.expect("the schema names the levels it accepts");
for detection in ServiceDetection::ALL {
assert!(
accepted.contains(&Value::from(detection.name())),
"the schema does not accept `{detection}`, which a scan can be asked for"
);
}
}
#[test]
fn a_full_report_matches_the_schema() {
Validator::new().check(&document(ExportOptions::new()));
}
#[test]
fn a_redacted_report_matches_the_schema() {
Validator::new().check(&document(
ExportOptions::new().with_redaction(Redaction::Standard),
));
}
#[test]
fn the_schema_rejects_a_document_it_should_reject() {
let validator = Validator::new();
let mut missing_field = document(ExportOptions::new());
missing_field
.as_object_mut()
.expect("an object")
.remove("summary");
assert!(
!validator.accepts(&missing_field),
"a report with no summary must not validate"
);
let mut unknown_field = document(ExportOptions::new());
unknown_field["hosts"][0]["surprise"] = Value::from("undocumented");
assert!(
!validator.accepts(&unknown_field),
"a field the schema does not describe must not validate - that failure \
is what stops the schema drifting away from the DTO"
);
let mut float_timestamp = document(ExportOptions::new());
float_timestamp["generated_at"] = Value::from(1_770_000_000.5);
assert!(
!validator.accepts(&float_timestamp),
"an epoch float must not pass where an RFC 3339 string is promised"
);
let mut rounded_count = document(ExportOptions::new());
rounded_count["phases"][0]["targets"]["addresses"] = Value::from(256);
assert!(
!validator.accepts(&rounded_count),
"a count that can exceed 2^53 must be a string, not a number"
);
}
#[cfg(feature = "export-jsonl")]
#[test]
fn every_exported_line_matches_the_lines_schema() {
let validator = Validator::lines();
for options in [
ExportOptions::new(),
ExportOptions::new().with_redaction(Redaction::Standard),
] {
let mut bytes = Vec::new();
crate::export::JsonLinesExporter::new(options)
.export(&fixture::report(), &mut bytes)
.expect("the export succeeds");
let text = String::from_utf8(bytes).expect("utf-8");
let mut records = 0;
for line in text.lines() {
let record: Value = serde_json::from_str(line).expect("a line parses on its own");
validator.check(&record);
records += 1;
}
assert_eq!(records, 4, "a report record and three hosts");
}
}
#[cfg(feature = "export-jsonl")]
#[test]
fn the_lines_schema_rejects_a_record_it_should_reject() {
let validator = Validator::lines();
let host = document(ExportOptions::new())["hosts"][0].clone();
assert!(
!validator.accepts(&host),
"a host object with no `type` is not a record"
);
let mut mislabelled = host.clone();
mislabelled["type"] = Value::from("report");
assert!(
!validator.accepts(&mislabelled),
"a host wearing the report tag must not validate as either"
);
let mut tagged = host;
tagged["type"] = Value::from("host");
assert!(validator.accepts(&tagged), "a tagged host is a host record");
let mut surprising = tagged;
surprising["surprise"] = Value::from("undocumented");
assert!(
!validator.accepts(&surprising),
"a field the schema does not describe must not validate"
);
}
fn comparison(
baseline: &crate::scanner::report::ScanReport,
current: &crate::scanner::report::ScanReport,
options: ExportOptions,
) -> Value {
use crate::diff::ScanDiff;
use crate::export::diff::{DiffExporter, JsonDiffExporter};
let diff = ScanDiff::between(baseline, current);
let mut bytes = Vec::new();
JsonDiffExporter::new(options)
.export(&diff, &mut bytes)
.expect("the export succeeds");
serde_json::from_slice(&bytes).expect("the export parses as JSON")
}
#[test]
fn the_published_comparison_schema_compiles() {
let _ = Validator::diff();
}
#[test]
fn the_comparison_schema_pins_the_version_the_code_emits() {
let schema: Value = serde_json::from_str(DIFF_SCHEMA).expect("valid JSON");
assert_eq!(
schema["properties"]["schema_version"]["const"],
Value::from(crate::format::DIFF_SCHEMA_VERSION)
);
}
#[test]
fn a_comparison_matches_the_published_schema() {
let (before, after) = fixture::compared();
let document = comparison(&before, &after, ExportOptions::new());
Validator::diff().check(&document);
}
#[test]
fn an_unchanged_comparison_matches_the_published_schema() {
let report = fixture::report();
let document = comparison(&report, &report, ExportOptions::new());
Validator::diff().check(&document);
assert_eq!(document["unchanged"], Value::Bool(true));
assert_eq!(document["hosts"].as_array().map(Vec::len), Some(0));
}
#[test]
fn a_redacted_comparison_masks_what_a_redacted_report_masks() {
let (before, after) = fixture::compared();
let document = comparison(
&before,
&after,
ExportOptions::new().with_redaction(Redaction::Standard),
);
Validator::diff().check(&document);
let rendered = document.to_string();
assert!(
!rendered.contains("router.local") && !rendered.contains("gateway.local"),
"a hostname survived redaction into the comparison"
);
assert!(
!rendered.contains("2c:cf:67:f2:51:e3"),
"a hardware address survived redaction into the comparison"
);
}
#[test]
fn every_change_the_fixtures_produce_is_a_token_the_schema_accepts() {
let schema: Value = serde_json::from_str(DIFF_SCHEMA).expect("valid JSON");
let accepted: Vec<&str> = schema["$defs"]["change"]["properties"]["kind"]["enum"]
.as_array()
.expect("the schema names the tokens it accepts")
.iter()
.filter_map(Value::as_str)
.collect();
let (before, after) = fixture::compared();
let document = comparison(&before, &after, ExportOptions::new());
let mut seen = 0usize;
for host in document["hosts"].as_array().expect("hosts") {
for change in host["changes"].as_array().expect("changes") {
let kind = change["kind"].as_str().expect("a token");
assert!(accepted.contains(&kind), "'{kind}' is not in the schema");
seen += 1;
}
for port in host["ports"].as_array().expect("ports") {
for change in port["changes"].as_array().expect("changes") {
let kind = change["kind"].as_str().expect("a token");
assert!(accepted.contains(&kind), "'{kind}' is not in the schema");
seen += 1;
}
}
}
assert!(seen > 0, "the fixtures produced no changes to check");
}