use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::path::{Component, Path, PathBuf};
use base64::Engine as _;
use prost_reflect::DescriptorPool;
use serde_json::Value;
use sha2::{Digest, Sha256};
use crate::authoring::{RawType, SchemasSection, TypeRef};
use crate::diag::{Diagnostic, Report};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum SchemaKind {
Protobuf,
JsonSchema,
Packed,
}
impl SchemaKind {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Protobuf => "protobuf",
Self::JsonSchema => "jsonschema",
Self::Packed => "packed",
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Artifact {
pub kind: SchemaKind,
pub name: String,
pub data: ArtifactData,
}
#[derive(Debug, Clone, PartialEq)]
pub enum ArtifactData {
Protobuf(Vec<u8>),
Json(Value),
}
impl Artifact {
#[must_use]
pub fn id(&self) -> String {
match &self.data {
ArtifactData::Protobuf(b) => sha256_id(b),
ArtifactData::Json(v) => sha256_id(&jcs(v)),
}
}
#[must_use]
pub fn data_value(&self) -> Value {
match &self.data {
ArtifactData::Protobuf(b) => {
Value::String(base64::engine::general_purpose::STANDARD.encode(b))
}
ArtifactData::Json(v) => v.clone(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum TypeId {
Protobuf {
name: String,
schema: String,
},
JsonSchema {
name: String,
schema: String,
},
Packed {
name: String,
schema: String,
},
Raw {
media_type: String,
media_param: Option<String>,
},
}
impl TypeId {
#[must_use]
pub fn kind_str(&self) -> &'static str {
match self {
Self::Protobuf { .. } => "protobuf",
Self::JsonSchema { .. } => "jsonschema",
Self::Packed { .. } => "packed",
Self::Raw { .. } => "raw",
}
}
#[must_use]
pub fn is_json(&self) -> bool {
matches!(self, Self::JsonSchema { .. })
}
#[must_use]
pub fn is_packed(&self) -> bool {
matches!(self, Self::Packed { .. })
}
}
struct ProtoFile {
name: String,
pool: DescriptorPool,
artifact: String,
}
struct JsonFile {
stem: String,
doc: Value,
artifact: String,
}
struct PackedFile {
stem: String,
doc: crate::packed::PackedDoc,
artifact: String,
}
pub struct SchemaSet {
artifacts: BTreeMap<String, Artifact>,
proto: Vec<ProtoFile>,
json: Vec<JsonFile>,
packed: Vec<PackedFile>,
proto_failed: bool,
json_failed: bool,
packed_failed: bool,
}
const WELL_KNOWN: &[(&str, &[&str])] = &[
("google/protobuf/any.proto", &["Any"]),
("google/protobuf/duration.proto", &["Duration"]),
("google/protobuf/empty.proto", &["Empty"]),
("google/protobuf/field_mask.proto", &["FieldMask"]),
(
"google/protobuf/struct.proto",
&["Struct", "Value", "ListValue"],
),
("google/protobuf/timestamp.proto", &["Timestamp"]),
(
"google/protobuf/wrappers.proto",
&[
"DoubleValue",
"FloatValue",
"Int64Value",
"UInt64Value",
"Int32Value",
"UInt32Value",
"BoolValue",
"StringValue",
"BytesValue",
],
),
];
impl SchemaSet {
pub fn load(dir: &Path, sec: &SchemasSection, report: &mut Report) -> Self {
let mut set = Self {
artifacts: BTreeMap::new(),
proto: Vec::new(),
json: Vec::new(),
packed: Vec::new(),
proto_failed: false,
json_failed: false,
packed_failed: false,
};
set.load_proto(dir, sec, report);
set.load_json(dir, sec, report);
set.load_packed(dir, sec, report);
set
}
fn load_packed(&mut self, dir: &Path, sec: &SchemasSection, report: &mut Report) {
for f in &sec.packed {
let at = format!("schemas.packed {f:?}");
let doc = match std::fs::read_to_string(dir.join(f)) {
Ok(text) => match crate::strict::parse_json(&text) {
Ok(v) => v,
Err(e) => {
report.push(Diagnostic::error(
"E029",
at,
format!("is not valid JSON: {e}"),
));
self.packed_failed = true;
continue;
}
},
Err(e) => {
report.push(Diagnostic::error(
"E029",
at,
format!("cannot be read: {e}"),
));
self.packed_failed = true;
continue;
}
};
if let Some(n) = unsafe_integer(&doc) {
report.push(Diagnostic::error(
"E028",
at.clone(),
format!("{n} is outside ±(2^53−1), so the artifact has no portable id"),
));
}
let stem = file_stem(f);
if self.packed.iter().any(|p| p.stem == stem) {
report.push(Diagnostic::error(
"E024",
at,
format!(
"a second listed packed file has the stem {stem:?}; stems are unique per contract"
),
));
continue;
}
let art = Artifact {
kind: SchemaKind::Packed,
name: stem.clone(),
data: ArtifactData::Json(doc.clone()),
};
let id = art.id();
let taken = self
.json
.iter()
.map(|j| (&j.artifact, &j.stem))
.chain(self.packed.iter().map(|p| (&p.artifact, &p.stem)))
.find(|(a, _)| **a == id);
if let Some((_, first)) = taken {
report.push(Diagnostic::error(
"E024",
at,
format!("the same document as {first:?} (one id); list it once"),
));
continue;
}
let read = crate::packed::PackedDoc::read(&doc);
for x in &read.findings {
let place = if x.at.is_empty() {
at.clone()
} else {
format!("{at} {}", x.at)
};
report.push(Diagnostic::error(x.code, place, x.message.clone()));
}
self.artifacts.insert(id.clone(), art);
self.packed.push(PackedFile {
stem,
doc: read,
artifact: id,
});
}
}
#[must_use]
pub fn packed_layout(&self, t: &TypeId) -> Option<&crate::packed::Layout> {
let TypeId::Packed { name, schema } = t else {
return None;
};
self.packed
.iter()
.find(|p| &p.artifact == schema)?
.doc
.types
.get(name)?
.as_ref()
}
fn load_proto(&mut self, dir: &Path, sec: &SchemasSection, report: &mut Report) {
if sec.protobuf.is_empty() {
return;
}
let includes: Vec<PathBuf> = match &sec.proto_include {
Some(v) => v.iter().map(|p| dir.join(p)).collect(),
None if dir.join("proto").is_dir() => vec![dir.join("proto")],
None => vec![dir.to_path_buf()],
};
for f in &sec.protobuf {
let at = format!("schemas.protobuf {f:?}");
let compiled = protox::Compiler::new(&includes).and_then(|mut c| {
c.include_imports(true).include_source_info(false);
c.open_file(dir.join(f))?;
Ok(c)
});
let c = match compiled {
Ok(c) => c,
Err(e) => {
report.push(Diagnostic::error(
"E029",
at,
format!("does not compile: {e}"),
));
self.proto_failed = true;
continue;
}
};
let Some(name) = c
.files()
.find(|m| !m.is_import())
.map(|m| m.name().to_owned())
else {
report.push(Diagnostic::error("E029", at, "compiled to no file"));
self.proto_failed = true;
continue;
};
let art = Artifact {
kind: SchemaKind::Protobuf,
name: name.clone(),
data: ArtifactData::Protobuf(c.encode_file_descriptor_set()),
};
let id = art.id();
self.artifacts.insert(id.clone(), art);
self.proto.push(ProtoFile {
name,
pool: c.descriptor_pool(),
artifact: id,
});
}
}
fn load_json(&mut self, dir: &Path, sec: &SchemasSection, report: &mut Report) {
let mut paths = Vec::new();
for f in &sec.jsonschema {
let at = format!("schemas.jsonschema {f:?}");
let path = dir.join(f);
let doc = match std::fs::read_to_string(&path) {
Ok(text) => match crate::strict::parse_json(&text) {
Ok(v) => v,
Err(e) => {
report.push(Diagnostic::error(
"E029",
at,
format!("is not valid JSON: {e}"),
));
self.json_failed = true;
continue;
}
},
Err(e) => {
report.push(Diagnostic::error(
"E029",
at,
format!("cannot be read: {e}"),
));
self.json_failed = true;
continue;
}
};
if let Some(n) = unsafe_integer(&doc) {
report.push(Diagnostic::error(
"E028",
at.clone(),
format!("{n} is outside ±(2^53−1), so the artifact has no portable id"),
));
}
let mut refused = std::collections::BTreeSet::new();
refused_keywords(&doc, &mut refused);
for k in refused {
report.push(Diagnostic::error(
"E037",
at.clone(),
format!("keyword {k:?} is outside the zk2 JSON Schema subset"),
));
}
let stem = file_stem(f);
if self.json.iter().any(|j| j.stem == stem) {
report.push(Diagnostic::error(
"E024",
at,
format!(
"a second listed file has the stem {stem:?}; stems are unique per contract"
),
));
continue;
}
let art = Artifact {
kind: SchemaKind::JsonSchema,
name: stem.clone(),
data: ArtifactData::Json(doc.clone()),
};
let id = art.id();
if let Some(first) = self.json.iter().find(|j| j.artifact == id) {
report.push(Diagnostic::error(
"E024",
at,
format!(
"the same document as {:?} (one id); list it once",
first.stem
),
));
continue;
}
self.artifacts.insert(id.clone(), art);
self.json.push(JsonFile {
stem,
doc,
artifact: id,
});
paths.push((f.clone(), normalize(&path)));
}
for (i, (f, path)) in paths.iter().enumerate() {
let mut refs = Vec::new();
collect_refs(&self.json[i].doc, &mut refs);
for r in refs {
let at = format!("schemas.jsonschema {f:?}");
let (file_part, pointer) = r.split_once('#').unwrap_or((r.as_str(), ""));
let target = if file_part.is_empty() {
Some(i)
} else if file_part.contains(':') {
None
} else {
let p = normalize(&path.parent().unwrap_or(Path::new("")).join(file_part));
paths.iter().position(|(_, q)| *q == p)
};
let Some(t) = target else {
report.push(Diagnostic::error(
"E032",
at,
format!("$ref {r:?} points outside the listed files"),
));
continue;
};
if !pointer.is_empty() && self.json[t].doc.pointer(pointer).is_none() {
report.push(Diagnostic::error(
"E032",
at,
format!("$ref {r:?} points at a missing definition"),
));
}
}
}
}
pub fn resolve(&mut self, r: &TypeRef, at: &str, report: &mut Report) -> Option<TypeId> {
match r {
TypeRef::Raw(raw) => resolve_raw(raw, at, report),
TypeRef::Named(s) => {
if let Some(rest) = s.strip_prefix("json:") {
self.resolve_json(s, rest, at, report)
} else if let Some(rest) = s.strip_prefix("packed:") {
self.resolve_packed(s, rest, at, report)
} else {
self.resolve_proto(s, at, report)
}
}
}
}
fn resolve_json(
&self,
full: &str,
rest: &str,
at: &str,
report: &mut Report,
) -> Option<TypeId> {
let (stem, name) = match rest.split_once('#') {
Some((stem, name)) => (Some(stem), name),
None => (None, rest),
};
let has = |j: &JsonFile| j.doc.get("$defs").and_then(|d| d.get(name)).is_some();
let found: Vec<&JsonFile> = self
.json
.iter()
.filter(|j| stem.is_none_or(|s| j.stem == s) && has(j))
.collect();
match found.as_slice() {
[j] => Some(TypeId::JsonSchema {
name: name.to_owned(),
schema: j.artifact.clone(),
}),
[] => {
if !self.json_failed {
report.push(Diagnostic::error(
"E023",
at,
format!("{full:?}: no listed JSON Schema file defines $defs/{name}"),
));
}
None
}
many => {
let stems: Vec<&str> = many.iter().map(|j| j.stem.as_str()).collect();
report.push(Diagnostic::error(
"E024",
at,
format!("{full:?} is defined in {stems:?}; qualify it as json:<stem>#{name}"),
));
None
}
}
}
fn resolve_packed(
&self,
full: &str,
rest: &str,
at: &str,
report: &mut Report,
) -> Option<TypeId> {
let (stem, name) = match rest.split_once('#') {
Some((stem, name)) => (Some(stem), name),
None => (None, rest),
};
let found: Vec<&PackedFile> = self
.packed
.iter()
.filter(|p| stem.is_none_or(|s| p.stem == s) && p.doc.types.contains_key(name))
.collect();
match found.as_slice() {
[p] => Some(TypeId::Packed {
name: name.to_owned(),
schema: p.artifact.clone(),
}),
[] => {
if !self.packed_failed {
report.push(Diagnostic::error(
"E023",
at,
format!("{full:?}: no listed packed file defines types/{name}"),
));
}
None
}
many => {
let stems: Vec<&str> = many.iter().map(|p| p.stem.as_str()).collect();
report.push(Diagnostic::error(
"E024",
at,
format!("{full:?} is defined in {stems:?}; qualify it as packed:<stem>#{name}"),
));
None
}
}
}
fn resolve_proto(&mut self, name: &str, at: &str, report: &mut Report) -> Option<TypeId> {
let found: Vec<&ProtoFile> = self
.proto
.iter()
.filter(|p| {
p.pool
.get_message_by_name(name)
.is_some_and(|m| m.parent_file().name() == p.name)
})
.collect();
match found.as_slice() {
[p] => {
return Some(TypeId::Protobuf {
name: name.to_owned(),
schema: p.artifact.clone(),
});
}
[] => {}
_ => {
report.push(Diagnostic::error(
"E023",
at,
format!("{name:?} is defined by more than one listed .proto file"),
));
return None;
}
}
if let Some(short) = name.strip_prefix("google.protobuf.")
&& let Some((file, _)) = WELL_KNOWN.iter().find(|(_, ms)| ms.contains(&short))
{
return self.well_known(file, name);
}
if !self.proto_failed {
let hint = if self
.proto
.iter()
.any(|p| p.pool.get_message_by_name(name).is_some())
{
" (it is defined by an imported file: list that file)"
} else {
""
};
report.push(Diagnostic::error(
"E023",
at,
format!("{name:?}: no listed .proto file defines this message{hint}"),
));
}
None
}
fn well_known(&mut self, file: &str, name: &str) -> Option<TypeId> {
if let Some(p) = self.proto.iter().find(|p| p.name == file) {
return Some(TypeId::Protobuf {
name: name.to_owned(),
schema: p.artifact.clone(),
});
}
let mut c = protox::Compiler::new::<_, &Path>([]).ok()?;
c.include_imports(true).include_source_info(false);
c.open_file(file).ok()?;
let art = Artifact {
kind: SchemaKind::Protobuf,
name: file.to_owned(),
data: ArtifactData::Protobuf(c.encode_file_descriptor_set()),
};
let id = art.id();
self.artifacts.insert(id.clone(), art);
self.proto.push(ProtoFile {
name: file.to_owned(),
pool: c.descriptor_pool(),
artifact: id.clone(),
});
Some(TypeId::Protobuf {
name: name.to_owned(),
schema: id,
})
}
#[must_use]
pub fn field_names(&self, t: &TypeId) -> Option<Vec<String>> {
match t {
TypeId::Protobuf { name, schema } => {
let p = self.proto.iter().find(|p| &p.artifact == schema)?;
let m = p.pool.get_message_by_name(name)?;
Some(m.fields().map(|f| f.name().to_owned()).collect())
}
TypeId::JsonSchema { name, schema } => {
let j = self.json.iter().find(|j| &j.artifact == schema)?;
let props = j
.doc
.get("$defs")?
.get(name)?
.get("properties")?
.as_object()?;
Some(props.keys().cloned().collect())
}
TypeId::Packed { .. } | TypeId::Raw { .. } => None,
}
}
#[must_use]
pub fn artifacts(&self) -> &BTreeMap<String, Artifact> {
&self.artifacts
}
}
fn resolve_raw(raw: &RawType, at: &str, report: &mut Report) -> Option<TypeId> {
if !is_media_type(&raw.raw) {
report.push(Diagnostic::error(
"E023",
at,
format!(
"{:?} is not a lowercase media type <type>/<subtype> or family <type>/*",
raw.raw
),
));
return None;
}
Some(TypeId::Raw {
media_type: raw.raw.clone(),
media_param: raw.media_param.clone(),
})
}
fn is_media_type(s: &str) -> bool {
let tok = |t: &str| {
let mut cs = t.chars();
cs.next()
.is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
&& cs.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || "!#$&-^_.+".contains(c))
};
match s.split_once('/') {
Some((t, sub)) => tok(t) && (sub == "*" || tok(sub)),
None => false,
}
}
fn file_stem(f: &str) -> String {
let base = f.rsplit('/').next().unwrap_or(f);
base.strip_suffix(".json").unwrap_or(base).to_owned()
}
fn normalize(p: &Path) -> PathBuf {
let mut out = PathBuf::new();
for c in p.components() {
match c {
Component::CurDir => {}
Component::ParentDir => {
if !out.pop() {
out.push("..");
}
}
other => out.push(other),
}
}
out
}
pub(crate) fn visit_schemas<'a>(
schema: &'a Value,
f: &mut dyn FnMut(&'a serde_json::Map<String, Value>),
) {
let Value::Object(m) = schema else { return };
f(m);
for (k, v) in m {
match (k.as_str(), v) {
("properties" | "$defs", Value::Object(subs)) => {
subs.values().for_each(|s| visit_schemas(s, f));
}
("prefixItems" | "oneOf" | "anyOf", Value::Array(subs)) => {
subs.iter().for_each(|s| visit_schemas(s, f));
}
("items" | "additionalProperties", sub) => visit_schemas(sub, f),
_ => {}
}
}
}
fn collect_refs(v: &Value, out: &mut Vec<String>) {
visit_schemas(v, &mut |m| {
if let Some(Value::String(r)) = m.get("$ref") {
out.push(r.clone());
}
});
}
#[must_use]
pub fn jcs(v: &Value) -> Vec<u8> {
serde_json_canonicalizer::to_vec(v).expect("a serde_json::Value always serializes")
}
#[must_use]
pub fn sha256_id(bytes: &[u8]) -> String {
let digest = Sha256::digest(bytes);
let mut s = String::with_capacity(71);
s.push_str("sha256:");
for b in digest {
let _ = write!(s, "{b:02x}");
}
s
}
pub(crate) fn unsafe_integer(v: &Value) -> Option<String> {
match v {
Value::Number(n) => crate::canonical::outside_safe_range(n).then(|| n.to_string()),
Value::Array(a) => a.iter().find_map(unsafe_integer),
Value::Object(m) => m.values().find_map(unsafe_integer),
_ => None,
}
}
const SUBSET: &[&str] = &[
"type",
"properties",
"required",
"additionalProperties",
"items",
"prefixItems",
"enum",
"const",
"minimum",
"maximum",
"exclusiveMinimum",
"exclusiveMaximum",
"minLength",
"maxLength",
"minItems",
"maxItems",
"$ref",
"oneOf",
"anyOf",
];
const ANNOTATIONS: &[&str] = &[
"$schema",
"$id",
"$defs",
"$comment",
"title",
"description",
"default",
"examples",
"format",
"deprecated",
"readOnly",
"writeOnly",
];
fn refused_keywords(schema: &Value, out: &mut std::collections::BTreeSet<String>) {
visit_schemas(schema, &mut |m| {
for k in m.keys() {
if !SUBSET.contains(&k.as_str()) && !ANNOTATIONS.contains(&k.as_str()) {
out.insert(k.clone());
}
}
});
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn media_types() {
for ok in [
"image/jpeg",
"video/*",
"application/vnd.foo+cbor",
"audio/l16",
] {
assert!(is_media_type(ok), "{ok}");
}
for bad in ["image", "Image/jpeg", "*/*", "image/", "image/jpeg; q=1"] {
assert!(!is_media_type(bad), "{bad}");
}
}
#[test]
fn well_known_types_compile_on_demand() {
let mut report = Report::default();
let mut set = SchemaSet::load(Path::new("."), &SchemasSection::default(), &mut report);
let t = set
.resolve(
&TypeRef::Named("google.protobuf.Empty".into()),
"x",
&mut report,
)
.unwrap();
assert!(report.0.is_empty(), "{report}");
let TypeId::Protobuf { schema, .. } = t else {
panic!()
};
assert_eq!(set.artifacts()[&schema].name, "google/protobuf/empty.proto");
assert!(
set.resolve(
&TypeRef::Named("google.protobuf.Nope".into()),
"x",
&mut report
)
.is_none()
);
assert_eq!(report.codes(), ["E023"]);
}
#[test]
fn a_listed_file_with_a_taken_id_is_e024() {
let dir = std::env::temp_dir().join(format!("zk2-schema-ids-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("a.json"),
r#"{"$defs": {"X": {"type": "string"}}}"#,
)
.unwrap();
std::fs::write(
dir.join("b.json"),
"{\"$defs\":{\"X\":{\"type\":\"string\"}}}\n",
)
.unwrap();
std::fs::write(
dir.join("c.json"),
r#"{"$defs": {"Y": {"$ref": "a.json#/$defs/X"}}}"#,
)
.unwrap();
let sec = SchemasSection {
jsonschema: vec!["a.json".into(), "b.json".into(), "c.json".into()],
..SchemasSection::default()
};
let mut report = Report::default();
let set = SchemaSet::load(&dir, &sec, &mut report);
std::fs::remove_dir_all(&dir).unwrap();
assert_eq!(report.codes(), ["E024"], "{report}");
let names: Vec<&str> = set.artifacts().values().map(|a| a.name.as_str()).collect();
assert_eq!(names.len(), 2);
assert!(names.contains(&"a") && names.contains(&"c"), "{names:?}");
}
#[test]
fn normalize_folds_dots() {
assert_eq!(
normalize(Path::new("a/./b/../c.json")),
PathBuf::from("a/c.json")
);
assert_eq!(normalize(Path::new("../x")), PathBuf::from("../x"));
}
}