use boon::{Compiler, Schemas};
use serde_json::Value;
use crate::config::OsDetection;
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 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";
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 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)] {
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 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"
);
}