use fastmcp_core::AbsoluteUri;
use regex::Regex;
use serde_json::Value;
use std::{
any::TypeId,
borrow::Cow,
cmp::Ordering,
collections::{BTreeMap, BTreeSet, HashMap, HashSet},
fmt,
io::{self, Write},
marker::PhantomData,
rc::Rc,
sync::Arc,
};
mod flatten;
mod unique_items;
#[doc(hidden)]
pub use flatten::{FlattenableSchemaObject, FlattenedObjectSchema};
pub const FINAL_JSON_SCHEMA_DIALECT: &str = "https://json-schema.org/draft/2020-12/schema";
const CORE_VOCABULARY_URI: &str = "https://json-schema.org/draft/2020-12/vocab/core";
const APPLICATOR_VOCABULARY_URI: &str = "https://json-schema.org/draft/2020-12/vocab/applicator";
const UNEVALUATED_VOCABULARY_URI: &str = "https://json-schema.org/draft/2020-12/vocab/unevaluated";
const VALIDATION_VOCABULARY_URI: &str = "https://json-schema.org/draft/2020-12/vocab/validation";
const META_DATA_VOCABULARY_URI: &str = "https://json-schema.org/draft/2020-12/vocab/meta-data";
const FORMAT_ANNOTATION_VOCABULARY_URI: &str =
"https://json-schema.org/draft/2020-12/vocab/format-annotation";
const FORMAT_ASSERTION_VOCABULARY_URI: &str =
"https://json-schema.org/draft/2020-12/vocab/format-assertion";
const CONTENT_VOCABULARY_URI: &str = "https://json-schema.org/draft/2020-12/vocab/content";
pub const MAX_SCHEMA_VALIDATION_DEPTH: usize = 64;
pub const MAX_SCHEMA_ADMISSION_NODES: usize = 4_096;
pub const MAX_SCHEMA_DOCUMENT_BYTES: usize = 2 * 1024 * 1024;
pub const MAX_SCHEMA_DOCUMENT_NODES: usize = 65_536;
pub const MAX_SCHEMA_INSTANCE_NODES: usize = 4_096;
pub const MAX_SCHEMA_INSTANCE_DEPTH: usize = 64;
pub const MAX_SCHEMA_INSTANCE_BYTES: usize = 8 * 1024 * 1024;
pub const MAX_SCHEMA_INSTANCE_STRING_BYTES: usize = MAX_SCHEMA_INSTANCE_BYTES;
pub const MAX_SCHEMA_INSTANCE_KEY_BYTES: usize = 64 * 1024;
pub const MAX_SCHEMA_PATTERN_INPUT_BYTES: usize = 1024 * 1024;
const SCHEMA_STRING_WORK_UNIT_BYTES: usize = 64 * 1024;
pub const MAX_SCHEMA_VALIDATION_WORK: usize = 4_096;
pub const MAX_LOCAL_REFERENCE_DEPTH: usize = 32;
pub const MAX_COMPOSITION_BRANCHES: usize = 64;
pub const MAX_PATTERN_PROPERTIES: usize = 64;
pub const MAX_PATTERN_PROPERTY_BYTES: usize = 4 * 1024;
pub const MAX_PATTERN_BYTES: usize = 4 * 1024;
const SCHEMA_PATTERN_SOURCE_NEST_LIMIT: u32 = 250;
const SCHEMA_PATTERN_NORMALIZED_NEST_LIMIT: u32 = SCHEMA_PATTERN_SOURCE_NEST_LIMIT + 2;
pub const MAX_SCHEMA_ASSERTION_ENTRIES: usize = 64;
pub const MAX_SCHEMA_ASSERTION_STRING_BYTES: usize = 4 * 1024;
pub const MAX_VALIDATION_ERRORS: usize = 64;
pub const MAX_SCHEMA_DIAGNOSTIC_PATH_BYTES: usize = 1024;
pub const MAX_SCHEMA_DIAGNOSTIC_SEGMENT_BYTES: usize = 64;
const MAX_EXACT_DECIMAL_DIGITS: usize = 4 * 1024;
#[derive(Debug, Clone, Copy)]
pub struct SchemaGenerationLimits {
pub max_types: usize,
pub max_depth: usize,
pub max_nodes: usize,
pub max_bytes: usize,
}
impl Default for SchemaGenerationLimits {
fn default() -> Self {
Self {
max_types: 128,
max_depth: MAX_SCHEMA_VALIDATION_DEPTH,
max_nodes: MAX_SCHEMA_ADMISSION_NODES,
max_bytes: 1024 * 1024,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SchemaGenerationError {
TypeLimit,
DepthLimit,
NodeLimit,
ByteLimit,
WorkLimit,
DefinitionsCollision,
ReferenceResourceBoundary,
InvalidSchema(SchemaAdmissionError),
}
impl fmt::Display for SchemaGenerationError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(match self {
Self::TypeLimit => "schema generation type limit exceeded",
Self::DepthLimit => "schema generation nesting limit exceeded",
Self::NodeLimit => "schema generation node limit exceeded",
Self::ByteLimit => "schema generation byte limit exceeded",
Self::WorkLimit => "schema generation resource comparison limit exceeded",
Self::DefinitionsCollision => "generated definitions conflict with root $defs",
Self::ReferenceResourceBoundary => "schema reference crosses a resource boundary",
Self::InvalidSchema(error) => return write!(formatter, "generated schema: {error}"),
})
}
}
impl std::error::Error for SchemaGenerationError {}
pub trait JsonSchemaType: 'static {
fn schema_body(context: &mut SchemaGenerator) -> Value;
}
macro_rules! impl_scalar_schema {
($($ty:ty => $schema:expr),* $(,)?) => {
$(
impl JsonSchemaType for $ty {
fn schema_body(_context: &mut SchemaGenerator) -> Value {
$schema
}
}
)*
};
}
impl_scalar_schema! {
String => serde_json::json!({"type": "string"}),
str => serde_json::json!({"type": "string"}),
char => serde_json::json!({"type": "string", "minLength": 1, "maxLength": 1}),
bool => serde_json::json!({"type": "boolean"}),
() => serde_json::json!({"type": "null"}),
f32 => serde_json::json!({"type": "number"}),
f64 => serde_json::json!({"type": "number"}),
Value => serde_json::json!({}),
}
macro_rules! impl_integer_schema {
($wide_schema:expr; $($ty:ty),* $(,)?) => {
$(
impl JsonSchemaType for $ty {
fn schema_body(_context: &mut SchemaGenerator) -> Value {
if <$ty>::BITS <= 32 {
serde_json::json!({
"type": "integer",
"minimum": <$ty>::MIN,
"maximum": <$ty>::MAX,
})
} else {
$wide_schema
}
}
}
)*
};
}
impl_integer_schema!(serde_json::json!({"type": "integer"}); i8, i16, i32, i64, i128, isize);
impl_integer_schema!(serde_json::json!({"type": "integer", "minimum": 0}); u8, u16, u32, u64, u128, usize);
impl<T: JsonSchemaType> JsonSchemaType for Option<T> {
fn schema_body(context: &mut SchemaGenerator) -> Value {
let mut inner = context.subschema_for::<T>();
let dialect = inner
.as_object_mut()
.filter(|schema| !schema.contains_key("$id"))
.and_then(|schema| schema.remove("$schema"));
let mut schema = serde_json::json!({
"anyOf": [inner, {"type": "null"}],
});
if let Some(dialect) = dialect {
schema["$schema"] = dialect;
}
schema
}
}
impl<T: JsonSchemaType> JsonSchemaType for Vec<T> {
fn schema_body(context: &mut SchemaGenerator) -> Value {
serde_json::json!({"type": "array", "items": context.subschema_for::<T>()})
}
}
impl<T: JsonSchemaType> JsonSchemaType for [T] {
fn schema_body(context: &mut SchemaGenerator) -> Value {
serde_json::json!({"type": "array", "items": context.subschema_for::<T>()})
}
}
impl<T: JsonSchemaType, const N: usize> JsonSchemaType for [T; N] {
fn schema_body(context: &mut SchemaGenerator) -> Value {
serde_json::json!({
"type": "array",
"items": context.subschema_for::<T>(),
"minItems": N,
"maxItems": N,
})
}
}
impl<T: JsonSchemaType> JsonSchemaType for BTreeSet<T> {
fn schema_body(context: &mut SchemaGenerator) -> Value {
serde_json::json!({
"type": "array",
"items": context.subschema_for::<T>(),
"uniqueItems": true,
})
}
}
impl<T: JsonSchemaType, S: 'static> JsonSchemaType for HashSet<T, S> {
fn schema_body(context: &mut SchemaGenerator) -> Value {
serde_json::json!({
"type": "array",
"items": context.subschema_for::<T>(),
"uniqueItems": true,
})
}
}
impl<T: JsonSchemaType> JsonSchemaType for BTreeMap<String, T> {
fn schema_body(context: &mut SchemaGenerator) -> Value {
serde_json::json!({"type": "object", "additionalProperties": context.subschema_for::<T>()})
}
}
impl<T: JsonSchemaType, S: 'static> JsonSchemaType for HashMap<String, T, S> {
fn schema_body(context: &mut SchemaGenerator) -> Value {
serde_json::json!({"type": "object", "additionalProperties": context.subschema_for::<T>()})
}
}
macro_rules! impl_transparent_schema {
($($wrapper:ty),* $(,)?) => {
$(
impl<T: JsonSchemaType + ?Sized> JsonSchemaType for $wrapper {
fn schema_body(context: &mut SchemaGenerator) -> Value {
context.subschema_for::<T>()
}
}
)*
};
}
impl_transparent_schema!(Box<T>, Rc<T>, Arc<T>, &'static T, &'static mut T);
impl<T> JsonSchemaType for Cow<'static, T>
where
T: JsonSchemaType + ToOwned + ?Sized,
T::Owned: 'static,
{
fn schema_body(context: &mut SchemaGenerator) -> Value {
context.subschema_for::<T>()
}
}
macro_rules! impl_tuple_schema {
($($ty:ident),+ $(,)?) => {
impl<$($ty: JsonSchemaType),+> JsonSchemaType for ($($ty,)+) {
fn schema_body(context: &mut SchemaGenerator) -> Value {
let items = vec![$(context.subschema_for::<$ty>()),+];
let length = items.len();
serde_json::json!({
"type": "array",
"prefixItems": items,
"minItems": length,
"maxItems": length,
})
}
}
};
}
impl_tuple_schema!(A);
impl_tuple_schema!(A, B);
impl_tuple_schema!(A, B, C);
impl_tuple_schema!(A, B, C, D);
impl_tuple_schema!(A, B, C, D, E);
impl_tuple_schema!(A, B, C, D, E, F);
impl_tuple_schema!(A, B, C, D, E, F, G);
impl_tuple_schema!(A, B, C, D, E, F, G, H);
impl_tuple_schema!(A, B, C, D, E, F, G, H, I);
impl_tuple_schema!(A, B, C, D, E, F, G, H, I, J);
impl_tuple_schema!(A, B, C, D, E, F, G, H, I, J, K);
impl_tuple_schema!(A, B, C, D, E, F, G, H, I, J, K, L);
impl_tuple_schema!(A, B, C, D, E, F, G, H, I, J, K, L, M);
impl_tuple_schema!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
impl_tuple_schema!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
impl_tuple_schema!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);
#[derive(Debug)]
struct GeneratedDefinition {
key: String,
body: Option<Value>,
referenced: bool,
}
#[derive(Debug)]
struct HandwrittenSchemaResource {
schema: Value,
nodes: usize,
bytes: usize,
}
#[derive(Debug, Default)]
pub struct SchemaGenerator {
limits: SchemaGenerationLimits,
definitions: BTreeMap<TypeId, GeneratedDefinition>,
handwritten_resources: Vec<HandwrittenSchemaResource>,
depth: usize,
nodes: usize,
bytes: usize,
error: Option<SchemaGenerationError>,
}
impl SchemaGenerator {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_limits(limits: SchemaGenerationLimits) -> Self {
let ceilings = SchemaGenerationLimits::default();
Self {
limits: SchemaGenerationLimits {
max_types: limits.max_types.min(ceilings.max_types),
max_depth: limits.max_depth.min(ceilings.max_depth),
max_nodes: limits.max_nodes.min(ceilings.max_nodes),
max_bytes: limits.max_bytes.min(ceilings.max_bytes),
},
..Self::default()
}
}
pub fn subschema_for<T: JsonSchemaType + ?Sized>(&mut self) -> Value {
if self.error.is_some() {
return Value::Bool(false);
}
let identity = TypeId::of::<T>();
if let Some(entry) = self.definitions.get_mut(&identity) {
entry.referenced = true;
let reference = format!("#/$defs/{}", entry.key);
let schema = serde_json::json!({"$ref": reference});
return if self.account(&schema, 1).is_some() {
schema
} else {
Value::Bool(false)
};
}
if self.definitions.len() >= self.limits.max_types {
self.error = Some(SchemaGenerationError::TypeLimit);
return Value::Bool(false);
}
if self.depth >= self.limits.max_depth {
self.error = Some(SchemaGenerationError::DepthLimit);
return Value::Bool(false);
}
let key = format!("type_{}", self.definitions.len());
self.definitions.insert(
identity,
GeneratedDefinition {
key,
body: None,
referenced: false,
},
);
self.depth += 1;
let body = T::schema_body(self);
self.depth -= 1;
if self.account(&body, 2).is_none() {
return Value::Bool(false);
}
self.definitions
.get_mut(&identity)
.expect("a generated type keeps its reserved definition")
.body = Some(body.clone());
body
}
pub fn inline_schema(&mut self, schema: Value) -> Value {
let Some((nodes, bytes)) = self.account(&schema, 1) else {
return Value::Bool(false);
};
if handwritten_schema_has_unscoped_reference(&schema) {
self.error = Some(SchemaGenerationError::ReferenceResourceBoundary);
return Value::Bool(false);
}
if generated_schema_contains_resource(&schema) {
if self.account(&schema, 1).is_none() {
return Value::Bool(false);
}
self.handwritten_resources.push(HandwrittenSchemaResource {
schema: schema.clone(),
nodes,
bytes,
});
}
schema
}
fn account(&mut self, schema: &Value, copies: usize) -> Option<(usize, usize)> {
if self.error.is_some() {
return None;
}
let result = measure_generated_schema(schema, self.limits).and_then(|(nodes, bytes)| {
if nodes.saturating_mul(copies) > self.limits.max_nodes.saturating_sub(self.nodes) {
return Err(SchemaGenerationError::NodeLimit);
}
if bytes.saturating_mul(copies) > self.limits.max_bytes.saturating_sub(self.bytes) {
return Err(SchemaGenerationError::ByteLimit);
}
self.nodes += nodes * copies;
self.bytes += bytes * copies;
Ok((nodes, bytes))
});
match result {
Ok(size) => Some(size),
Err(error) => {
self.error = Some(error);
None
}
}
}
pub fn finish(mut self, mut root: Value) -> Result<Value, SchemaGenerationError> {
if let Some(error) = self.error.take() {
return Err(error);
}
if root.is_boolean() {
root = serde_json::json!({"allOf": [root]});
}
let definitions: serde_json::Map<String, Value> = self
.definitions
.into_values()
.filter(|entry| entry.referenced)
.map(|entry| {
(
entry.key,
entry.body.expect("completed type has a schema body"),
)
})
.collect::<BTreeMap<_, _>>()
.into_iter()
.collect();
let generated_keys: HashSet<String> = definitions.keys().cloned().collect();
let has_generated_definitions = !generated_keys.is_empty();
if has_generated_definitions {
let object = root.as_object_mut().ok_or_else(|| {
SchemaGenerationError::InvalidSchema(SchemaAdmissionError::new(
"$",
"schema must be a boolean or object",
))
})?;
match object.get_mut("$defs") {
Some(Value::Object(existing)) => {
if definitions.keys().any(|key| existing.contains_key(key)) {
return Err(SchemaGenerationError::DefinitionsCollision);
}
existing.extend(definitions);
}
Some(_) => {
return Err(SchemaGenerationError::InvalidSchema(
SchemaAdmissionError::new(
"$.$defs",
"schema map keyword must be an object",
),
));
}
None => {
object.insert("$defs".to_owned(), Value::Object(definitions));
}
}
}
let (nodes, bytes) = measure_generated_schema(&root, self.limits)?;
if nodes > self.limits.max_nodes.saturating_sub(self.nodes) {
return Err(SchemaGenerationError::NodeLimit);
}
if bytes > self.limits.max_bytes.saturating_sub(self.bytes) {
return Err(SchemaGenerationError::ByteLimit);
}
if has_generated_definitions || !self.handwritten_resources.is_empty() {
let mut comparison_budget = (self.limits.max_nodes * 16, self.limits.max_bytes * 16);
check_generated_reference_resources(
&root,
false,
true,
&generated_keys,
&self.handwritten_resources,
&mut comparison_budget,
)?;
}
admit_final_schema(root)
.map(|admitted| admitted.schema)
.map_err(SchemaGenerationError::InvalidSchema)
}
}
fn measure_generated_schema(
schema: &Value,
limits: SchemaGenerationLimits,
) -> Result<(usize, usize), SchemaGenerationError> {
fn count(
value: &Value,
depth: usize,
nodes: &mut usize,
limits: SchemaGenerationLimits,
) -> Result<(), SchemaGenerationError> {
if depth >= limits.max_depth {
return Err(SchemaGenerationError::DepthLimit);
}
if *nodes >= limits.max_nodes {
return Err(SchemaGenerationError::NodeLimit);
}
*nodes += 1;
match value {
Value::Array(values) => {
for value in values {
count(value, depth + 1, nodes, limits)?;
}
}
Value::Object(values) => {
for (key, value) in values {
if key.len() > limits.max_bytes {
return Err(SchemaGenerationError::ByteLimit);
}
count(value, depth + 1, nodes, limits)?;
}
}
Value::String(value) if value.len() > limits.max_bytes => {
return Err(SchemaGenerationError::ByteLimit);
}
Value::Number(value) if value.as_str().len() > limits.max_bytes => {
return Err(SchemaGenerationError::ByteLimit);
}
_ => {}
}
Ok(())
}
let mut nodes = 0;
count(schema, 0, &mut nodes, limits)?;
let bytes = bounded_schema_json_bytes(schema, limits.max_bytes)
.ok_or(SchemaGenerationError::ByteLimit)?;
Ok((nodes, bytes))
}
fn bounded_schema_json_bytes(value: &Value, maximum: usize) -> Option<usize> {
struct ByteCounter {
remaining: usize,
}
impl Write for ByteCounter {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
if bytes.len() > self.remaining {
return Err(io::Error::other("schema byte limit"));
}
self.remaining -= bytes.len();
Ok(bytes.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
let mut counter = ByteCounter { remaining: maximum };
serde_json::to_writer(&mut counter, value).ok()?;
Some(maximum - counter.remaining)
}
fn generated_schema_contains_resource(schema: &Value) -> bool {
match schema {
Value::Object(values) => {
values.contains_key("$id") || values.values().any(generated_schema_contains_resource)
}
Value::Array(values) => values.iter().any(generated_schema_contains_resource),
_ => false,
}
}
fn handwritten_schema_has_unscoped_reference(schema: &Value) -> bool {
let Some(object) = schema.as_object() else {
return false;
};
if object.contains_key("$id") {
return false;
}
if ["$ref", "$dynamicRef"].iter().any(|keyword| {
object
.get(*keyword)
.and_then(Value::as_str)
.is_some_and(|reference| reference.is_empty() || reference.starts_with('#'))
}) {
return true;
}
for keyword in [
"properties",
"patternProperties",
"$defs",
"definitions",
"dependencies",
"dependentSchemas",
] {
if object
.get(keyword)
.and_then(Value::as_object)
.is_some_and(|children| {
children
.values()
.any(handwritten_schema_has_unscoped_reference)
})
{
return true;
}
}
for keyword in [
"additionalProperties",
"unevaluatedProperties",
"unevaluatedItems",
"items",
"contains",
"not",
"if",
"then",
"else",
"propertyNames",
"contentSchema",
] {
if object
.get(keyword)
.is_some_and(handwritten_schema_has_unscoped_reference)
{
return true;
}
}
for keyword in ["prefixItems", "allOf", "anyOf", "oneOf"] {
if object
.get(keyword)
.and_then(Value::as_array)
.is_some_and(|children| {
children
.iter()
.any(handwritten_schema_has_unscoped_reference)
})
{
return true;
}
}
false
}
fn matches_handwritten_schema(schema: &serde_json::Map<String, Value>, snapshot: &Value) -> bool {
let Some(snapshot) = snapshot.as_object() else {
return false;
};
let retained = |key: &str| !matches!(key, "description" | "default");
schema.keys().filter(|key| retained(key)).count()
== snapshot.keys().filter(|key| retained(key)).count()
&& schema
.iter()
.filter(|(key, _)| retained(key))
.all(|(key, value)| snapshot.get(key) == Some(value))
}
fn check_generated_reference_resources(
schema: &Value,
nested_resource: bool,
root: bool,
definitions: &HashSet<String>,
handwritten: &[HandwrittenSchemaResource],
comparison_budget: &mut (usize, usize),
) -> Result<(), SchemaGenerationError> {
let Some(object) = schema.as_object() else {
return Ok(());
};
for snapshot in handwritten {
if snapshot.nodes > comparison_budget.0 || snapshot.bytes > comparison_budget.1 {
return Err(SchemaGenerationError::WorkLimit);
}
comparison_budget.0 -= snapshot.nodes;
comparison_budget.1 -= snapshot.bytes;
if matches_handwritten_schema(object, &snapshot.schema) {
return Ok(());
}
}
let nested_resource = nested_resource || (!root && object.contains_key("$id"));
if nested_resource
&& object
.get("$ref")
.and_then(Value::as_str)
.and_then(|reference| reference.strip_prefix("#/$defs/"))
.is_some_and(|key| definitions.contains(key))
{
return Err(SchemaGenerationError::ReferenceResourceBoundary);
}
for keyword in [
"properties",
"patternProperties",
"$defs",
"definitions",
"dependencies",
"dependentSchemas",
] {
if let Some(children) = object.get(keyword).and_then(Value::as_object) {
for child in children.values() {
check_generated_reference_resources(
child,
nested_resource,
false,
definitions,
handwritten,
comparison_budget,
)?;
}
}
}
for keyword in [
"additionalProperties",
"unevaluatedProperties",
"unevaluatedItems",
"items",
"contains",
"not",
"if",
"then",
"else",
"propertyNames",
"contentSchema",
] {
if let Some(child) = object.get(keyword) {
check_generated_reference_resources(
child,
nested_resource,
false,
definitions,
handwritten,
comparison_budget,
)?;
}
}
for keyword in ["prefixItems", "allOf", "anyOf", "oneOf"] {
if let Some(children) = object.get(keyword).and_then(Value::as_array) {
for child in children {
check_generated_reference_resources(
child,
nested_resource,
false,
definitions,
handwritten,
comparison_budget,
)?;
}
}
}
Ok(())
}
#[derive(Debug)]
pub struct SchemaTypeDispatch<T>(PhantomData<T>);
impl<T> SchemaTypeDispatch<T> {
#[must_use]
pub const fn new() -> Self {
Self(PhantomData)
}
}
impl<T> Default for SchemaTypeDispatch<T> {
fn default() -> Self {
Self::new()
}
}
#[doc(hidden)]
pub trait SchemaTypeFallback: JsonSchemaType {
fn json_schema() -> Value;
}
impl<T: JsonSchemaType> SchemaTypeFallback for T {
fn json_schema() -> Value {
let mut context = SchemaGenerator::new();
let root = context.subschema_for::<T>();
context
.finish(root)
.expect("FastMCP JSON Schema generation exceeds generation limits")
}
}
pub trait DispatchSchema {
fn schema(self, context: &mut SchemaGenerator, fallback: impl FnOnce() -> Value) -> Value;
}
impl<T: JsonSchemaType> DispatchSchema for &SchemaTypeDispatch<T> {
fn schema(self, context: &mut SchemaGenerator, _fallback: impl FnOnce() -> Value) -> Value {
context.subschema_for::<T>()
}
}
impl<T> DispatchSchema for &&SchemaTypeDispatch<T> {
fn schema(self, context: &mut SchemaGenerator, fallback: impl FnOnce() -> Value) -> Value {
if context.error.is_some() {
Value::Bool(false)
} else {
context.inline_schema(fallback())
}
}
}
#[derive(Debug, Clone)]
pub struct ValidationError {
pub path: String,
pub message: String,
}
impl ValidationError {
#[must_use]
pub fn code(&self) -> &'static str {
if self.message.contains("limit exceeded") || self.message.contains("exceeds") {
"SchemaResourceLimit"
} else if self.message.contains("schema reference") {
"UnresolvedSchemaReference"
} else if self.message.starts_with("invalid ")
|| self.message.starts_with("schema numeric keyword")
{
"InvalidSchema"
} else {
"InvalidSchemaInstance"
}
}
}
impl fmt::Display for ValidationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}: {}", self.path, self.message)
}
}
impl std::error::Error for ValidationError {}
pub type ValidationResult = Result<(), Vec<ValidationError>>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SchemaAdmissionError {
path: String,
reason: &'static str,
}
impl SchemaAdmissionError {
fn new(path: impl Into<String>, reason: &'static str) -> Self {
Self {
path: bounded_diagnostic_path(&path.into(), "$"),
reason,
}
}
#[must_use]
pub fn path(&self) -> &str {
&self.path
}
#[must_use]
pub const fn reason(&self) -> &'static str {
self.reason
}
#[must_use]
pub fn code(&self) -> &'static str {
if matches!(
self.reason,
"unsupported schema dialect" | "cross-dialect meta-schema traversal is unsupported"
) {
"UnsupportedSchemaDialect"
} else if self.reason.contains("limit") || self.reason.contains("exceeds") {
"SchemaResourceLimit"
} else if self.reason.contains("unresolved") {
"UnresolvedSchemaReference"
} else {
"InvalidSchema"
}
}
}
impl fmt::Display for SchemaAdmissionError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{}: {}", self.path, self.reason)
}
}
impl std::error::Error for SchemaAdmissionError {}
#[derive(Clone)]
pub struct AdmittedSchema {
schema: Value,
}
impl fmt::Debug for AdmittedSchema {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("AdmittedSchema")
.finish_non_exhaustive()
}
}
impl AdmittedSchema {
#[must_use]
pub const fn schema(&self) -> &Value {
&self.schema
}
pub fn validate(&self, value: &Value) -> ValidationResult {
validate_admitted_final_schema(&self.schema, value)
}
pub fn validate_strict(&self, value: &Value) -> ValidationResult {
let strict_schema = make_strict_schema(&self.schema);
validate_admitted_final_schema(&strict_schema, value)
}
}
#[derive(Debug, Clone)]
pub struct AdmittedFinalFormSchema {
schema: AdmittedSchema,
}
impl AdmittedFinalFormSchema {
#[must_use]
pub const fn schema(&self) -> &Value {
self.schema.schema()
}
pub fn validate(&self, value: &Value) -> ValidationResult {
self.schema.validate(value)
}
}
impl serde::Serialize for AdmittedFinalFormSchema {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serde::Serialize::serialize(self.schema(), serializer)
}
}
impl<'de> serde::Deserialize<'de> for AdmittedFinalFormSchema {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
Self::admit(<Value as serde::Deserialize>::deserialize(deserializer)?)
.map_err(serde::de::Error::custom)
}
}
impl AdmittedFinalFormSchema {
pub fn admit(schema: Value) -> Result<Self, SchemaAdmissionError> {
admit_final_form_schema(schema)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FinalCoreResultType {
Complete,
InputRequired,
}
impl FinalCoreResultType {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Complete => "complete",
Self::InputRequired => "input_required",
}
}
}
struct SchemaDialectCheck<'a> {
schema: &'a Value,
dialect: &'a str,
path: String,
}
#[derive(Default)]
struct SchemaAdmissionContext<'a> {
node_count: usize,
dialect_checks: Vec<SchemaDialectCheck<'a>>,
}
pub fn admit_final_schema(schema: Value) -> Result<AdmittedSchema, SchemaAdmissionError> {
bound_schema_document(&schema)?;
let mut admission = SchemaAdmissionContext::default();
validate_final_schema_node(
&schema,
&schema,
"$",
true,
FINAL_JSON_SCHEMA_DIALECT,
0,
&mut admission,
)?;
validate_unique_local_anchors(&schema, "$", 0, &mut HashSet::new())?;
validate_unique_local_resource_ids(&schema, "$", 0, None, &mut HashSet::new())?;
validate_schema_dialect_checks(&schema, admission.dialect_checks)?;
Ok(AdmittedSchema { schema })
}
fn validate_schema_dialect_checks<'a>(
root_schema: &'a Value,
checks: Vec<SchemaDialectCheck<'a>>,
) -> Result<(), SchemaAdmissionError> {
let mut remaining_work = MAX_SCHEMA_VALIDATION_WORK;
for check in &checks {
if check.dialect == FINAL_JSON_SCHEMA_DIALECT {
continue;
}
let mut context = ValidationContext::new(root_schema, true);
context.remaining_work = remaining_work;
let mut charge = || {
if context.consume_work() {
Ok(())
} else {
Err("schema meta-validation work limit exceeded")
}
};
let meta_schema =
find_local_schema_resource_with_charge(root_schema, check.dialect, &mut charge)
.map_err(|reason| SchemaAdmissionError::new(&check.path, reason))?
.ok_or_else(|| {
SchemaAdmissionError::new(&check.path, "unsupported schema dialect")
})?;
context.meta_validation = Some(MetaSchemaValidationScope {
resource: check.schema,
dialect: check.dialect,
resources: &checks,
});
let result = validate_with_context(meta_schema, check.schema, &mut context);
let limited = context.work_exhausted
|| context.pattern_input_exceeded
|| context.recursion_limit_exceeded.is_some()
|| result.as_ref().err().is_some_and(|issues| {
issues
.iter()
.any(|issue| issue.code() == "SchemaResourceLimit")
});
if limited {
return Err(SchemaAdmissionError::new(
&check.path,
"schema meta-validation resource limit exceeded",
));
}
if context.unsupported_meta_resource {
return Err(SchemaAdmissionError::new(
&check.path,
"cross-dialect meta-schema traversal is unsupported",
));
}
if result.is_err() {
return Err(SchemaAdmissionError::new(
&check.path,
"schema does not satisfy its declared dialect",
));
}
remaining_work = context.remaining_work;
}
Ok(())
}
pub(crate) fn bound_schema_document(schema: &Value) -> Result<(), SchemaAdmissionError> {
measure_generated_schema(
schema,
SchemaGenerationLimits {
max_nodes: MAX_SCHEMA_DOCUMENT_NODES,
max_bytes: MAX_SCHEMA_DOCUMENT_BYTES,
..SchemaGenerationLimits::default()
},
)
.map_err(|error| {
SchemaAdmissionError::new(
"$",
match error {
SchemaGenerationError::DepthLimit => "schema document nesting limit exceeded",
SchemaGenerationError::NodeLimit => "schema document node limit exceeded",
SchemaGenerationError::ByteLimit => "schema document byte limit exceeded",
_ => "schema document resource limit exceeded",
},
)
})?;
Ok(())
}
pub fn admit_final_form_schema(
schema: Value,
) -> Result<AdmittedFinalFormSchema, SchemaAdmissionError> {
let schema = admit_final_schema(schema)?;
validate_final_form_schema(schema.schema())?;
Ok(AdmittedFinalFormSchema { schema })
}
fn validate_final_form_schema(schema: &Value) -> Result<(), SchemaAdmissionError> {
let root = schema
.as_object()
.ok_or_else(|| SchemaAdmissionError::new("$", "final form schema must be an object"))?;
if root.get("type").and_then(Value::as_str) != Some("object") {
return Err(SchemaAdmissionError::new(
"$.type",
"final form schema type must be object",
));
}
for keyword in [
"$ref",
"$dynamicRef",
"$defs",
"definitions",
"items",
"prefixItems",
"contains",
"allOf",
"anyOf",
"oneOf",
"not",
"if",
"then",
"else",
"dependentSchemas",
"patternProperties",
"propertyNames",
"unevaluatedProperties",
"unevaluatedItems",
"contentSchema",
] {
if root.contains_key(keyword) {
return Err(SchemaAdmissionError::new(
format!("$.{keyword}"),
"final form schema cannot contain nested or composed schemas",
));
}
}
validate_final_form_dependencies(root, "$")?;
let properties = root.get("properties").map_or(Ok(None), |value| {
value.as_object().map(Some).ok_or_else(|| {
SchemaAdmissionError::new("$.properties", "final form properties must be an object")
})
})?;
if root
.get("additionalProperties")
.is_some_and(|value| value != &Value::Bool(false))
{
return Err(SchemaAdmissionError::new(
"$.additionalProperties",
"final form additionalProperties must be false when present",
));
}
if let Some(required) = root.get("required") {
let Some(required) = required.as_array() else {
return Err(SchemaAdmissionError::new(
"$.required",
"final form required must be an array",
));
};
for (index, name) in required.iter().enumerate() {
let Some(name) = name.as_str() else {
return Err(SchemaAdmissionError::new(
format!("$.required[{index}]"),
"final form required entries must be property names",
));
};
if !properties.is_some_and(|properties| properties.contains_key(name)) {
return Err(SchemaAdmissionError::new(
format!("$.required[{index}]"),
"final form required entries must name declared properties",
));
}
}
}
let Some(properties) = properties else {
return Ok(());
};
for (name, property) in properties {
validate_final_form_property_schema(name, property)?;
}
Ok(())
}
fn validate_final_form_property_schema(
name: &str,
property: &Value,
) -> Result<(), SchemaAdmissionError> {
let path = diagnostic_child_path("$.properties", name);
let property = property.as_object().ok_or_else(|| {
SchemaAdmissionError::new(&path, "final form property schema must be an object")
})?;
match property.get("type").and_then(Value::as_str) {
Some("string" | "number" | "integer" | "boolean") => {}
_ => {
return Err(SchemaAdmissionError::new(
format!("{path}.type"),
"final form property type must be a primitive",
));
}
}
for keyword in [
"$ref",
"$dynamicRef",
"$defs",
"definitions",
"properties",
"items",
"prefixItems",
"contains",
"allOf",
"anyOf",
"oneOf",
"not",
"if",
"then",
"else",
"dependentSchemas",
"patternProperties",
"propertyNames",
"unevaluatedProperties",
"unevaluatedItems",
"contentSchema",
] {
if property.contains_key(keyword) {
return Err(SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"final form property cannot contain nested or composed schemas",
));
}
}
validate_final_form_dependencies(property, &path)
}
fn validate_final_form_dependencies(
schema: &serde_json::Map<String, Value>,
path: &str,
) -> Result<(), SchemaAdmissionError> {
if schema
.get("dependencies")
.and_then(Value::as_object)
.is_some_and(|dependencies| {
dependencies
.values()
.any(|dependency| !dependency.is_array())
})
{
return Err(SchemaAdmissionError::new(
format!("{path}.dependencies"),
"final form schema cannot contain nested or composed schemas",
));
}
Ok(())
}
pub fn validate_final_core_result(
schema: &AdmittedSchema,
value: &Value,
expected_result_type: FinalCoreResultType,
) -> ValidationResult {
let mut errors = Vec::new();
let Some(result) = value.as_object() else {
push_error(&mut errors, "root", "final result must be an object");
return Err(errors);
};
match result.get("resultType") {
Some(Value::String(result_type)) if result_type == expected_result_type.as_str() => {}
Some(Value::String(_)) => push_error(
&mut errors,
"root.resultType",
"resultType does not match the selected final core result branch",
),
Some(_) => push_error(
&mut errors,
"root.resultType",
"resultType must be a final core result discriminator string",
),
None => push_error(&mut errors, "root", "final result requires resultType"),
}
if let Err(schema_errors) = schema.validate(value) {
for error in schema_errors {
if errors.len() == MAX_VALIDATION_ERRORS {
break;
}
errors.push(error);
}
}
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
fn validate_final_schema_node<'a>(
schema: &'a Value,
root_schema: &Value,
path: &str,
root: bool,
inherited_dialect: &'a str,
depth: usize,
admission: &mut SchemaAdmissionContext<'a>,
) -> Result<(), SchemaAdmissionError> {
if depth >= MAX_SCHEMA_VALIDATION_DEPTH {
return Err(SchemaAdmissionError::new(
path,
"schema admission nesting limit exceeded",
));
}
admission.node_count += 1;
if admission.node_count > MAX_SCHEMA_ADMISSION_NODES {
return Err(SchemaAdmissionError::new(
path,
"schema admission node limit exceeded",
));
}
if schema.is_boolean() {
return Ok(());
}
let object = schema
.as_object()
.ok_or_else(|| SchemaAdmissionError::new(path, "schema must be an object or boolean"))?;
let unknown_annotations = object
.get("$schema")
.map_or(inherited_dialect == FINAL_JSON_SCHEMA_DIALECT, |dialect| {
dialect.as_str() == Some(FINAL_JSON_SCHEMA_DIALECT)
});
validate_supported_schema_keywords(object, path, root, unknown_annotations)?;
validate_schema_id_keyword(object, path)?;
validate_schema_dialect_keyword(object, root_schema, path)?;
let dialect = object
.get("$schema")
.and_then(Value::as_str)
.unwrap_or(inherited_dialect);
if root || object.contains_key("$id") {
admission.dialect_checks.push(SchemaDialectCheck {
schema,
dialect,
path: bounded_diagnostic_path(&format!("{path}.$schema"), "$"),
});
}
validate_local_reference_keyword(object, "$ref", root_schema, path)?;
validate_local_reference_keyword(object, "$dynamicRef", root_schema, path)?;
validate_anchor_keyword(object, "$anchor", path)?;
validate_anchor_keyword(object, "$dynamicAnchor", path)?;
if let Some(type_value) = object.get("type") {
validate_schema_type(type_value, &format!("{path}.type"))?;
}
validate_string_array_keyword(object, "required", path)?;
validate_string_array_keyword(object, "dependentRequired", path)?;
validate_dependencies_keyword(object, path)?;
validate_nonnegative_integer_keywords(
object,
path,
&[
"minProperties",
"maxProperties",
"minItems",
"maxItems",
"minContains",
"maxContains",
"minLength",
"maxLength",
],
)?;
validate_number_keywords(
object,
path,
&[
"minimum",
"maximum",
"exclusiveMinimum",
"exclusiveMaximum",
"multipleOf",
],
)?;
if object.get("multipleOf").is_some_and(|value| {
ExactDecimal::from_value(value).is_none_or(|multiple| !multiple.is_positive())
}) {
return Err(SchemaAdmissionError::new(
format!("{path}.multipleOf"),
"multipleOf must be a positive number",
));
}
validate_boolean_keywords(object, path, &["uniqueItems"])?;
validate_enum_keyword(object, path)?;
if let Some(value) = object.get("const") {
validate_exact_equality_value(
value,
&format!("{path}.const"),
depth + 1,
&mut admission.node_count,
)?;
}
if let Some(values) = object.get("enum").and_then(Value::as_array) {
for (index, value) in values.iter().enumerate() {
validate_exact_equality_value(
value,
&format!("{path}.enum[{index}]"),
depth + 1,
&mut admission.node_count,
)?;
}
}
validate_pattern_keyword(object, path)?;
validate_format_keyword(object, path)?;
validate_content_annotation_keywords(object, path)?;
for keyword in [
"properties",
"patternProperties",
"$defs",
"definitions",
"dependencies",
"dependentSchemas",
] {
if let Some(subschemas) = object.get(keyword) {
let subschemas = subschemas.as_object().ok_or_else(|| {
SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"schema map keyword must be an object",
)
})?;
if keyword == "patternProperties" {
if subschemas.len() > MAX_PATTERN_PROPERTIES {
return Err(SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"patternProperties exceeds entry limit",
));
}
for pattern in subschemas.keys() {
if pattern.len() > MAX_PATTERN_PROPERTY_BYTES {
return Err(SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"patternProperties pattern exceeds byte limit",
));
}
if compile_schema_pattern(pattern).is_err() {
return Err(SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"invalid patternProperties pattern",
));
}
}
}
for (name, subschema) in subschemas {
if keyword == "dependencies" && subschema.is_array() {
continue;
}
validate_final_schema_node(
subschema,
root_schema,
&diagnostic_schema_member_path(path, keyword, name),
false,
dialect,
depth + 1,
admission,
)?;
}
}
}
for keyword in [
"additionalProperties",
"unevaluatedProperties",
"unevaluatedItems",
"items",
"contains",
"not",
"if",
"then",
"else",
"propertyNames",
"contentSchema",
] {
if let Some(subschema) = object.get(keyword) {
validate_final_schema_node(
subschema,
root_schema,
&format!("{path}.{keyword}"),
false,
dialect,
depth + 1,
admission,
)?;
}
}
for keyword in ["prefixItems", "allOf", "anyOf", "oneOf"] {
if let Some(subschemas) = object.get(keyword) {
let subschemas = subschemas.as_array().ok_or_else(|| {
SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"schema array keyword must be an array",
)
})?;
if subschemas.is_empty() {
return Err(SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"schema array keyword must be nonempty",
));
}
if matches!(keyword, "allOf" | "anyOf" | "oneOf")
&& subschemas.len() > MAX_COMPOSITION_BRANCHES
{
return Err(SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"composition keyword exceeds branch limit",
));
}
for (index, subschema) in subschemas.iter().enumerate() {
validate_final_schema_node(
subschema,
root_schema,
&format!("{path}.{keyword}[{index}]"),
false,
dialect,
depth + 1,
admission,
)?;
}
}
}
Ok(())
}
fn validate_supported_schema_keywords(
object: &serde_json::Map<String, Value>,
path: &str,
root: bool,
unknown_annotations: bool,
) -> Result<(), SchemaAdmissionError> {
const SUPPORTED: &[&str] = &[
"$anchor",
"$comment",
"$defs",
"$dynamicAnchor",
"$dynamicRef",
"$id",
"$ref",
"$schema",
"$vocabulary",
"additionalProperties",
"allOf",
"anyOf",
"const",
"contains",
"contentEncoding",
"contentMediaType",
"contentSchema",
"default",
"dependentRequired",
"dependentSchemas",
"deprecated",
"description",
"else",
"enum",
"examples",
"exclusiveMaximum",
"exclusiveMinimum",
"format",
"if",
"items",
"maxContains",
"maxItems",
"maxLength",
"maxProperties",
"maximum",
"minContains",
"minItems",
"minLength",
"minProperties",
"minimum",
"multipleOf",
"not",
"oneOf",
"pattern",
"patternProperties",
"prefixItems",
"properties",
"propertyNames",
"readOnly",
"required",
"then",
"title",
"type",
"unevaluatedItems",
"unevaluatedProperties",
"uniqueItems",
"writeOnly",
];
for keyword in object.keys() {
let unsupported_reserved = matches!(keyword.as_str(), "$recursiveAnchor" | "$recursiveRef");
if unsupported_reserved || (!unknown_annotations && !SUPPORTED.contains(&keyword.as_str()))
{
return Err(SchemaAdmissionError::new(
diagnostic_child_path(path, keyword),
"unsupported Draft 2020-12 vocabulary keyword",
));
}
}
if !root && object.contains_key("$schema") && !object.contains_key("$id") {
return Err(SchemaAdmissionError::new(
format!("{path}.$schema"),
"nested $schema is unsupported without local resource identifiers",
));
}
for keyword in ["$comment", "title", "description"] {
if object.get(keyword).is_some_and(|value| !value.is_string()) {
return Err(SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"schema annotation keyword must be a string",
));
}
}
if object
.get("examples")
.is_some_and(|value| !value.is_array())
{
return Err(SchemaAdmissionError::new(
format!("{path}.examples"),
"examples must be an array",
));
}
validate_boolean_keywords(object, path, &["deprecated", "readOnly", "writeOnly"])
}
fn validate_schema_id_keyword(
object: &serde_json::Map<String, Value>,
path: &str,
) -> Result<(), SchemaAdmissionError> {
let Some(identifier) = object.get("$id") else {
return Ok(());
};
let identifier = identifier.as_str().ok_or_else(|| {
SchemaAdmissionError::new(format!("{path}.$id"), "schema $id must be a string")
})?;
let (identifier, fragment) = split_uri_reference_fragment(identifier);
if fragment.is_some_and(|fragment| !fragment.is_empty()) {
return Err(SchemaAdmissionError::new(
format!("{path}.$id"),
"schema $id must not contain a fragment",
));
}
if !is_bounded_uri_reference(identifier) {
return Err(SchemaAdmissionError::new(
format!("{path}.$id"),
"schema $id must be a bounded URI reference",
));
}
Ok(())
}
fn validate_schema_dialect_keyword(
object: &serde_json::Map<String, Value>,
root_schema: &Value,
path: &str,
) -> Result<(), SchemaAdmissionError> {
let Some(dialect) = object.get("$schema") else {
return Ok(());
};
let dialect = dialect.as_str().ok_or_else(|| {
SchemaAdmissionError::new(format!("{path}.$schema"), "unsupported schema dialect")
})?;
let dialect = AbsoluteUri::parse_with_max_bytes(dialect, MAX_SCHEMA_ASSERTION_STRING_BYTES)
.ok()
.filter(|dialect| dialect.fragment().is_none())
.ok_or_else(|| {
SchemaAdmissionError::new(
format!("{path}.$schema"),
"schema dialect must be a bounded absolute URI",
)
})?;
if dialect.as_str() == FINAL_JSON_SCHEMA_DIALECT {
return Ok(());
}
let meta_schema =
find_local_schema_resource(root_schema, dialect.as_str()).ok_or_else(|| {
SchemaAdmissionError::new(format!("{path}.$schema"), "unsupported schema dialect")
})?;
validate_meta_schema_vocabulary(meta_schema, path)?;
Ok(())
}
fn validate_meta_schema_vocabulary(
meta_schema: &Value,
path: &str,
) -> Result<(), SchemaAdmissionError> {
let Some(vocabularies) = meta_schema
.as_object()
.and_then(|object| object.get("$vocabulary"))
else {
return Ok(());
};
let vocabularies = vocabularies.as_object().ok_or_else(|| {
SchemaAdmissionError::new(
format!("{path}.$vocabulary"),
"meta-schema $vocabulary must be an object",
)
})?;
if vocabularies.len() > MAX_SCHEMA_ASSERTION_ENTRIES {
return Err(SchemaAdmissionError::new(
format!("{path}.$vocabulary"),
"meta-schema $vocabulary exceeds entry limit",
));
}
if vocabularies.get(CORE_VOCABULARY_URI) == Some(&Value::Bool(false)) {
return Err(SchemaAdmissionError::new(
format!("{path}.$vocabulary"),
"meta-schema $vocabulary cannot disable the Draft 2020-12 core vocabulary",
));
}
for (vocabulary, required) in vocabularies {
let vocabulary_uri =
AbsoluteUri::parse_with_max_bytes(vocabulary, MAX_SCHEMA_ASSERTION_STRING_BYTES)
.map_err(|_| {
SchemaAdmissionError::new(
format!("{path}.$vocabulary"),
"meta-schema $vocabulary keys must be bounded absolute URIs",
)
})?;
if vocabulary_uri.fragment().is_some() {
return Err(SchemaAdmissionError::new(
format!("{path}.$vocabulary"),
"meta-schema $vocabulary keys must not contain fragments",
));
}
let required = required.as_bool().ok_or_else(|| {
SchemaAdmissionError::new(
diagnostic_child_path(&format!("{path}.$vocabulary"), vocabulary),
"meta-schema $vocabulary values must be booleans",
)
})?;
if required && vocabulary == FORMAT_ASSERTION_VOCABULARY_URI {
return Err(SchemaAdmissionError::new(
diagnostic_child_path(&format!("{path}.$vocabulary"), vocabulary),
"format assertion vocabulary is not supported",
));
}
if required && !is_supported_vocabulary_uri(vocabulary) {
return Err(SchemaAdmissionError::new(
diagnostic_child_path(&format!("{path}.$vocabulary"), vocabulary),
"required schema vocabulary is not supported",
));
}
}
if vocabularies.get(CORE_VOCABULARY_URI) != Some(&Value::Bool(true)) {
return Err(SchemaAdmissionError::new(
format!("{path}.$vocabulary"),
"meta-schema $vocabulary must require the Draft 2020-12 core vocabulary",
));
}
Ok(())
}
fn is_supported_vocabulary_uri(vocabulary: &str) -> bool {
matches!(
vocabulary,
CORE_VOCABULARY_URI
| APPLICATOR_VOCABULARY_URI
| UNEVALUATED_VOCABULARY_URI
| VALIDATION_VOCABULARY_URI
| META_DATA_VOCABULARY_URI
| FORMAT_ANNOTATION_VOCABULARY_URI
| CONTENT_VOCABULARY_URI
)
}
fn validate_content_annotation_keywords(
object: &serde_json::Map<String, Value>,
path: &str,
) -> Result<(), SchemaAdmissionError> {
for keyword in ["contentEncoding", "contentMediaType"] {
if object.get(keyword).is_some_and(|value| {
value.as_str().is_none_or(|value| {
value.is_empty() || value.len() > MAX_SCHEMA_ASSERTION_STRING_BYTES
})
}) {
return Err(SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"content annotation keyword must be a bounded non-empty string",
));
}
}
Ok(())
}
fn validate_local_reference_keyword(
object: &serde_json::Map<String, Value>,
keyword: &str,
root_schema: &Value,
path: &str,
) -> Result<(), SchemaAdmissionError> {
let Some(reference) = object.get(keyword) else {
return Ok(());
};
let reference = reference.as_str().ok_or_else(|| {
SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"schema reference must be a string",
)
})?;
match resolve_local_reference(root_schema, object, reference) {
Ok(target) if target.is_boolean() || target.is_object() => {
if !is_admitted_schema_node(root_schema, target) {
return Err(SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"local schema reference target is not an admitted schema node",
));
}
}
Ok(_) => {
return Err(SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"local schema reference target must be an object or boolean",
));
}
Err("external schema reference is not allowed") => {
return Err(SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"external schema reference is not allowed",
));
}
Err("invalid local schema reference") => {
return Err(SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"invalid local schema reference",
));
}
Err(_) => {
return Err(SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"unresolved local schema reference",
));
}
}
Ok(())
}
fn is_admitted_schema_node(schema: &Value, target: &Value) -> bool {
if std::ptr::eq(schema, target) {
return true;
}
let Some(object) = schema.as_object() else {
return false;
};
for keyword in [
"properties",
"patternProperties",
"$defs",
"definitions",
"dependencies",
"dependentSchemas",
] {
if object
.get(keyword)
.and_then(Value::as_object)
.is_some_and(|subschemas| {
subschemas
.values()
.any(|subschema| is_admitted_schema_node(subschema, target))
})
{
return true;
}
}
for keyword in [
"additionalProperties",
"unevaluatedProperties",
"unevaluatedItems",
"items",
"contains",
"not",
"if",
"then",
"else",
"propertyNames",
"contentSchema",
] {
if object
.get(keyword)
.is_some_and(|subschema| is_admitted_schema_node(subschema, target))
{
return true;
}
}
for keyword in ["prefixItems", "allOf", "anyOf", "oneOf"] {
if object
.get(keyword)
.and_then(Value::as_array)
.is_some_and(|subschemas| {
subschemas
.iter()
.any(|subschema| is_admitted_schema_node(subschema, target))
})
{
return true;
}
}
false
}
fn validate_anchor_keyword(
object: &serde_json::Map<String, Value>,
keyword: &str,
path: &str,
) -> Result<(), SchemaAdmissionError> {
let Some(anchor) = object.get(keyword) else {
return Ok(());
};
let anchor = anchor.as_str().ok_or_else(|| {
SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"schema anchor must be a string",
)
})?;
if valid_anchor_name(anchor) {
Ok(())
} else {
Err(SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"schema anchor has an invalid name",
))
}
}
fn valid_anchor_name(anchor: &str) -> bool {
let mut characters = anchor.chars();
matches!(characters.next(), Some(character) if character.is_ascii_alphabetic() || character == '_')
&& characters.all(|character| {
character.is_ascii_alphanumeric() || matches!(character, '_' | '-' | '.')
})
}
fn validate_unique_local_anchors(
schema: &Value,
path: &str,
depth: usize,
anchors: &mut HashSet<String>,
) -> Result<(), SchemaAdmissionError> {
if depth >= MAX_SCHEMA_VALIDATION_DEPTH {
return Err(SchemaAdmissionError::new(
path,
"schema admission nesting limit exceeded",
));
}
let Some(object) = schema.as_object() else {
return Ok(());
};
for keyword in ["$anchor", "$dynamicAnchor"] {
if let Some(anchor) = object.get(keyword).and_then(Value::as_str)
&& !anchors.insert(anchor.to_owned())
{
return Err(SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"duplicate local schema anchor",
));
}
}
for keyword in [
"properties",
"patternProperties",
"$defs",
"definitions",
"dependencies",
"dependentSchemas",
] {
if let Some(subschemas) = object.get(keyword).and_then(Value::as_object) {
for (name, subschema) in subschemas {
validate_unique_local_anchor_child(
subschema,
&diagnostic_schema_member_path(path, keyword, name),
depth + 1,
anchors,
)?;
}
}
}
for keyword in [
"additionalProperties",
"unevaluatedProperties",
"unevaluatedItems",
"items",
"contains",
"not",
"if",
"then",
"else",
"propertyNames",
"contentSchema",
] {
if let Some(subschema) = object.get(keyword) {
validate_unique_local_anchor_child(
subschema,
&format!("{path}.{keyword}"),
depth + 1,
anchors,
)?;
}
}
for keyword in ["prefixItems", "allOf", "anyOf", "oneOf"] {
if let Some(subschemas) = object.get(keyword).and_then(Value::as_array) {
for (index, subschema) in subschemas.iter().enumerate() {
validate_unique_local_anchor_child(
subschema,
&format!("{path}.{keyword}[{index}]"),
depth + 1,
anchors,
)?;
}
}
}
Ok(())
}
fn validate_unique_local_anchor_child(
schema: &Value,
path: &str,
depth: usize,
anchors: &mut HashSet<String>,
) -> Result<(), SchemaAdmissionError> {
if schema
.as_object()
.is_some_and(|object| object.contains_key("$id"))
{
validate_unique_local_anchors(schema, path, depth, &mut HashSet::new())
} else {
validate_unique_local_anchors(schema, path, depth, anchors)
}
}
fn validate_unique_local_resource_ids(
schema: &Value,
path: &str,
depth: usize,
parent_base: Option<&str>,
identifiers: &mut HashSet<String>,
) -> Result<(), SchemaAdmissionError> {
if depth >= MAX_SCHEMA_VALIDATION_DEPTH {
return Err(SchemaAdmissionError::new(
path,
"schema admission nesting limit exceeded",
));
}
let Some(object) = schema.as_object() else {
return Ok(());
};
let base = object
.get("$id")
.and_then(Value::as_str)
.map(|identifier| {
resolve_resource_identifier(parent_base, identifier).ok_or_else(|| {
SchemaAdmissionError::new(
format!("{path}.$id"),
"schema $id must resolve to a bounded absolute URI",
)
})
})
.transpose()?;
if let Some(identifier) = &base
&& !identifiers.insert(identifier.clone())
{
return Err(SchemaAdmissionError::new(
format!("{path}.$id"),
"duplicate local schema resource identifier",
));
}
let current_base = base.as_deref().or(parent_base);
for keyword in [
"properties",
"patternProperties",
"$defs",
"definitions",
"dependencies",
"dependentSchemas",
] {
if let Some(subschemas) = object.get(keyword).and_then(Value::as_object) {
for (name, subschema) in subschemas {
validate_unique_local_resource_ids(
subschema,
&diagnostic_schema_member_path(path, keyword, name),
depth + 1,
current_base,
identifiers,
)?;
}
}
}
for keyword in [
"additionalProperties",
"unevaluatedProperties",
"unevaluatedItems",
"items",
"contains",
"not",
"if",
"then",
"else",
"propertyNames",
"contentSchema",
] {
if let Some(subschema) = object.get(keyword) {
validate_unique_local_resource_ids(
subschema,
&format!("{path}.{keyword}"),
depth + 1,
current_base,
identifiers,
)?;
}
}
for keyword in ["prefixItems", "allOf", "anyOf", "oneOf"] {
if let Some(subschemas) = object.get(keyword).and_then(Value::as_array) {
for (index, subschema) in subschemas.iter().enumerate() {
validate_unique_local_resource_ids(
subschema,
&format!("{path}.{keyword}[{index}]"),
depth + 1,
current_base,
identifiers,
)?;
}
}
}
Ok(())
}
fn validate_schema_type(value: &Value, path: &str) -> Result<(), SchemaAdmissionError> {
let type_bit = |type_name: &str| match type_name {
"array" => Some(1u8 << 0),
"boolean" => Some(1u8 << 1),
"integer" => Some(1u8 << 2),
"null" => Some(1u8 << 3),
"number" => Some(1u8 << 4),
"object" => Some(1u8 << 5),
"string" => Some(1u8 << 6),
_ => None,
};
match value {
Value::String(type_name) if type_bit(type_name).is_some() => Ok(()),
Value::Array(types) if !types.is_empty() => {
let mut seen_mask = 0u8;
for item in types {
let bit = item.as_str().and_then(type_bit).ok_or_else(|| {
SchemaAdmissionError::new(
path,
"type must contain only JSON Schema primitive type names",
)
})?;
if (seen_mask & bit) != 0 {
return Err(SchemaAdmissionError::new(
path,
"type array entries must be unique",
));
}
seen_mask |= bit;
}
Ok(())
}
_ => Err(SchemaAdmissionError::new(
path,
"type must contain only JSON Schema primitive type names",
)),
}
}
fn validate_dependencies_keyword(
object: &serde_json::Map<String, Value>,
path: &str,
) -> Result<(), SchemaAdmissionError> {
let Some(value) = object.get("dependencies") else {
return Ok(());
};
let keyword_path = format!("{path}.dependencies");
let dependencies = value.as_object().ok_or_else(|| {
SchemaAdmissionError::new(&keyword_path, "dependencies must be an object")
})?;
if dependencies.len() > MAX_SCHEMA_ASSERTION_ENTRIES {
return Err(SchemaAdmissionError::new(
&keyword_path,
"dependencies exceeds entry limit",
));
}
let mut validation_work = dependencies.len();
for (trigger, dependency) in dependencies {
if trigger.len() > MAX_SCHEMA_ASSERTION_STRING_BYTES {
return Err(SchemaAdmissionError::new(
&keyword_path,
"dependencies property name exceeds byte limit",
));
}
let Some(members) = dependency.as_array() else {
if !dependency.is_object() && !dependency.is_boolean() {
return Err(SchemaAdmissionError::new(
diagnostic_child_path(&keyword_path, trigger),
"dependencies values must be schemas or arrays of strings",
));
}
continue;
};
if members.len() > MAX_SCHEMA_ASSERTION_ENTRIES {
return Err(SchemaAdmissionError::new(
&keyword_path,
"dependencies property list exceeds entry limit",
));
}
validation_work = validation_work.checked_add(members.len()).ok_or_else(|| {
SchemaAdmissionError::new(&keyword_path, "dependencies exceeds validation work budget")
})?;
if validation_work >= MAX_SCHEMA_VALIDATION_WORK {
return Err(SchemaAdmissionError::new(
&keyword_path,
"dependencies exceeds validation work budget",
));
}
let mut seen = HashSet::with_capacity(members.len());
for member in members {
let Some(member) = member.as_str() else {
return Err(SchemaAdmissionError::new(
&keyword_path,
"dependencies property lists must contain bounded strings",
));
};
if member.len() > MAX_SCHEMA_ASSERTION_STRING_BYTES {
return Err(SchemaAdmissionError::new(
&keyword_path,
"dependencies property lists must contain bounded strings",
));
}
if !seen.insert(member) {
return Err(SchemaAdmissionError::new(
&keyword_path,
"dependencies property list entries must be unique",
));
}
}
}
Ok(())
}
fn validate_string_array_keyword(
object: &serde_json::Map<String, Value>,
keyword: &str,
path: &str,
) -> Result<(), SchemaAdmissionError> {
let Some(value) = object.get(keyword) else {
return Ok(());
};
if keyword == "dependentRequired" {
let dependencies = value.as_object().ok_or_else(|| {
SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"dependentRequired must be an object",
)
})?;
if dependencies.len() > MAX_SCHEMA_ASSERTION_ENTRIES {
return Err(SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"dependentRequired exceeds entry limit",
));
}
let mut validation_work = dependencies.len();
for (trigger, required) in dependencies {
if trigger.len() > MAX_SCHEMA_ASSERTION_STRING_BYTES {
return Err(SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"dependentRequired string exceeds byte limit",
));
}
let members = required.as_array().ok_or_else(|| {
SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"dependentRequired values must be arrays of strings",
)
})?;
if members.len() > MAX_SCHEMA_ASSERTION_ENTRIES {
return Err(SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"dependentRequired values exceed entry limit",
));
}
validation_work = validation_work.checked_add(members.len()).ok_or_else(|| {
SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"dependentRequired exceeds validation work budget",
)
})?;
if validation_work >= MAX_SCHEMA_VALIDATION_WORK {
return Err(SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"dependentRequired exceeds validation work budget",
));
}
let mut seen = HashSet::with_capacity(members.len());
for member in members {
let Some(member_str) = member.as_str() else {
return Err(SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"dependentRequired values must be bounded strings",
));
};
if member_str.len() > MAX_SCHEMA_ASSERTION_STRING_BYTES {
return Err(SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"dependentRequired values must be bounded strings",
));
}
if !seen.insert(member_str) {
return Err(SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"dependentRequired array entries must be unique",
));
}
}
}
return Ok(());
}
let members = value.as_array().ok_or_else(|| {
SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"schema string-array keyword must be an array of strings",
)
})?;
if members.len() > MAX_SCHEMA_ASSERTION_ENTRIES {
return Err(SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"required exceeds entry limit",
));
}
let mut seen = HashSet::with_capacity(members.len());
for member in members {
let Some(member_str) = member.as_str() else {
return Err(SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"schema string-array keyword must contain bounded strings",
));
};
if member_str.len() > MAX_SCHEMA_ASSERTION_STRING_BYTES {
return Err(SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"schema string-array keyword must contain bounded strings",
));
}
if !seen.insert(member_str) {
return Err(SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"required entries must be unique",
));
}
}
Ok(())
}
fn validate_nonnegative_integer_keywords(
object: &serde_json::Map<String, Value>,
path: &str,
keywords: &[&str],
) -> Result<(), SchemaAdmissionError> {
for keyword in keywords {
if object.get(*keyword).is_some_and(|value| {
ExactDecimal::from_value(value)
.is_none_or(|number| number.negative || !number.is_integer())
}) {
return Err(SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"schema count keyword must be a nonnegative integer",
));
}
}
Ok(())
}
fn validate_number_keywords(
object: &serde_json::Map<String, Value>,
path: &str,
keywords: &[&str],
) -> Result<(), SchemaAdmissionError> {
for keyword in keywords {
if object
.get(*keyword)
.is_some_and(|value| ExactDecimal::from_value(value).is_none())
{
return Err(SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"schema numeric keyword must be a bounded exact number",
));
}
}
Ok(())
}
fn validate_boolean_keywords(
object: &serde_json::Map<String, Value>,
path: &str,
keywords: &[&str],
) -> Result<(), SchemaAdmissionError> {
for keyword in keywords {
if object
.get(*keyword)
.is_some_and(|value| !value.is_boolean())
{
return Err(SchemaAdmissionError::new(
format!("{path}.{keyword}"),
"schema boolean keyword must be a boolean",
));
}
}
Ok(())
}
fn validate_enum_keyword(
object: &serde_json::Map<String, Value>,
path: &str,
) -> Result<(), SchemaAdmissionError> {
if let Some(value) = object.get("enum") {
let values = value.as_array().ok_or_else(|| {
SchemaAdmissionError::new(format!("{path}.enum"), "enum must be a nonempty array")
})?;
if values.is_empty() {
return Err(SchemaAdmissionError::new(
format!("{path}.enum"),
"enum must be a nonempty array",
));
}
if values.len() > MAX_SCHEMA_ASSERTION_ENTRIES {
return Err(SchemaAdmissionError::new(
format!("{path}.enum"),
"enum exceeds entry limit",
));
}
}
Ok(())
}
fn validate_exact_equality_value(
value: &Value,
path: &str,
depth: usize,
node_count: &mut usize,
) -> Result<(), SchemaAdmissionError> {
if depth >= MAX_SCHEMA_VALIDATION_DEPTH {
return Err(SchemaAdmissionError::new(
path,
"schema admission nesting limit exceeded",
));
}
*node_count += 1;
if *node_count > MAX_SCHEMA_ADMISSION_NODES {
return Err(SchemaAdmissionError::new(
path,
"schema admission node limit exceeded",
));
}
match value {
Value::Number(number) if ExactDecimal::from_number(number).is_none() => {
Err(SchemaAdmissionError::new(
path,
"const or enum value exceeds exact numeric equality bound",
))
}
Value::String(string) if string.len() > MAX_SCHEMA_ASSERTION_STRING_BYTES => Err(
SchemaAdmissionError::new(path, "schema assertion string exceeds byte limit"),
),
Value::Array(values) => {
for value in values {
validate_exact_equality_value(value, path, depth + 1, node_count)?;
}
Ok(())
}
Value::Object(values) => {
for (name, value) in values {
if name.len() > MAX_SCHEMA_ASSERTION_STRING_BYTES {
return Err(SchemaAdmissionError::new(
path,
"schema assertion string exceeds byte limit",
));
}
validate_exact_equality_value(value, path, depth + 1, node_count)?;
}
Ok(())
}
_ => Ok(()),
}
}
fn validate_pattern_keyword(
object: &serde_json::Map<String, Value>,
path: &str,
) -> Result<(), SchemaAdmissionError> {
let Some(pattern) = object.get("pattern") else {
return Ok(());
};
let pattern = pattern.as_str().ok_or_else(|| {
SchemaAdmissionError::new(format!("{path}.pattern"), "pattern must be a string")
})?;
if pattern.len() > MAX_PATTERN_BYTES {
return Err(SchemaAdmissionError::new(
format!("{path}.pattern"),
"pattern exceeds byte limit",
));
}
if compile_schema_pattern(pattern).is_ok() {
Ok(())
} else {
Err(SchemaAdmissionError::new(
format!("{path}.pattern"),
"invalid schema pattern",
))
}
}
fn compile_schema_pattern(source: &str) -> Result<Regex, regex::Error> {
if source.len() > MAX_PATTERN_BYTES {
return Err(regex::Error::Syntax(
"schema pattern exceeds byte limit".to_owned(),
));
}
let mut normalized = String::with_capacity(source.len());
let mut syntax_source = String::with_capacity(source.len());
let mut classes = Vec::new();
let mut groups = Vec::new();
let mut flags = SchemaPatternFlags::default();
let mut characters = source.chars();
while let Some(character) = characters.next() {
if flags.extended && character == '#' {
syntax_source.push(character);
normalized.push(character);
for comment_character in characters.by_ref() {
syntax_source.push(comment_character);
normalized.push(comment_character);
if comment_character == '\n' {
break;
}
}
continue;
}
if flags.extended && character.is_whitespace() {
syntax_source.push(character);
normalized.push(character);
continue;
}
if character != '\\' {
syntax_source.push(character);
match character {
'[' => {
if let Some(start) = classes.last_mut() {
*start = SchemaPatternClassStart::Populated;
}
classes.push(SchemaPatternClassStart::Open);
normalized.push(character);
}
'^' if matches!(classes.last(), Some(SchemaPatternClassStart::Open)) => {
if let Some(start) = classes.last_mut() {
*start = SchemaPatternClassStart::Negated;
}
normalized.push(character);
}
']' if matches!(classes.last(), Some(SchemaPatternClassStart::Populated)) => {
let _ = classes.pop();
normalized.push(character);
}
'(' if classes.is_empty() => {
normalized.push(character);
if flags.extended {
let ignored = schema_pattern_ignored_prefix(characters.as_str());
syntax_source.push_str(ignored);
normalized.push_str(ignored);
characters = characters.as_str()[ignored.len()..].chars();
}
if let Some(prefix) = schema_pattern_capture_prefix(characters.as_str()) {
syntax_source.push_str(prefix);
normalized.push_str(prefix);
characters = characters.as_str()[prefix.len()..].chars();
groups.push(flags);
} else if let Some((prefix, scoped, next_flags)) =
schema_pattern_group_flags(characters.as_str(), flags)
{
syntax_source.push_str(prefix);
normalized.push_str(prefix);
characters = characters.as_str()[prefix.len()..].chars();
if scoped {
groups.push(flags);
}
flags = next_flags;
} else {
groups.push(flags);
}
}
')' if classes.is_empty() => {
if let Some(parent) = groups.pop() {
flags = parent;
}
normalized.push(character);
}
'.' if classes.is_empty() && !flags.dot_all => {
normalized.push_str(r"[^\r\n\u{2028}\u{2029}]");
}
_ => {
if let Some(start) = classes.last_mut() {
*start = SchemaPatternClassStart::Populated;
}
normalized.push(character);
}
}
continue;
}
let Some(escape) = characters.next() else {
syntax_source.push('\\');
normalized.push('\\');
break;
};
if let Some(start) = classes.last_mut() {
*start = SchemaPatternClassStart::Populated;
}
if escape == 'b' && !classes.is_empty() {
syntax_source.push_str(r"\x08");
normalized.push_str(r"\x08");
continue;
}
syntax_source.push('\\');
syntax_source.push(escape);
if let Some(prefix) = schema_pattern_escape_prefix(escape, characters.as_str(), flags) {
syntax_source.push_str(prefix);
normalized.push('\\');
normalized.push(escape);
normalized.push_str(prefix);
characters = characters.as_str()[prefix.len()..].chars();
continue;
}
match escape {
'd' => normalized.push_str("[0-9]"),
'D' => normalized.push_str("[^0-9]"),
'w' => normalized.push_str("[A-Za-z0-9_]"),
'W' => normalized.push_str("[^A-Za-z0-9_]"),
's' => normalized.push_str(r"[\t\n\x0B\x0C\r\p{Zs}\u{2028}\u{2029}\u{FEFF}]"),
'S' => normalized.push_str(r"[^\t\n\x0B\x0C\r\p{Zs}\u{2028}\u{2029}\u{FEFF}]"),
'b' if classes.is_empty() && !flags.ignore_case => {
normalized.push_str(r"(?-u:\b)");
}
'B' if classes.is_empty() && !flags.ignore_case => {
normalized.push_str(r"(?-u:\B)");
}
_ => {
normalized.push('\\');
normalized.push(escape);
}
}
}
let original = regex::RegexBuilder::new(&syntax_source)
.nest_limit(SCHEMA_PATTERN_SOURCE_NEST_LIMIT)
.build()?;
if normalized == syntax_source {
return Ok(original);
}
drop(original);
regex::RegexBuilder::new(&normalized)
.nest_limit(SCHEMA_PATTERN_NORMALIZED_NEST_LIMIT)
.build()
}
#[derive(Clone, Copy, Default)]
struct SchemaPatternFlags {
dot_all: bool,
extended: bool,
ignore_case: bool,
}
enum SchemaPatternClassStart {
Open,
Negated,
Populated,
}
fn schema_pattern_ignored_prefix(source: &str) -> &str {
let mut in_comment = false;
let mut end = 0;
for (index, character) in source.char_indices() {
if in_comment {
if character == '\n' {
in_comment = false;
}
} else if character == '#' {
in_comment = true;
} else if !character.is_whitespace() {
break;
}
end = index + character.len_utf8();
}
&source[..end]
}
fn schema_pattern_capture_prefix(suffix: &str) -> Option<&str> {
let name = suffix
.strip_prefix("?P<")
.or_else(|| suffix.strip_prefix("?<"))?;
let name_end = name.find('>')?;
let prefix_len = suffix.len() - name.len() + name_end + 1;
Some(&suffix[..prefix_len])
}
fn schema_pattern_escape_prefix(
escape: char,
suffix: &str,
flags: SchemaPatternFlags,
) -> Option<&str> {
let ignored = match escape {
'p' | 'P' | 'x' | 'u' | 'U' if flags.extended => {
schema_pattern_ignored_prefix(suffix).len()
}
'p' | 'P' | 'x' | 'u' | 'U' | 'b' => 0,
_ => return None,
};
let body = suffix[ignored..].strip_prefix('{')?;
if escape == 'b' {
let name = if flags.extended {
&body[schema_pattern_ignored_prefix(body).len()..]
} else {
body
};
if !name
.chars()
.next()
.is_some_and(|character| matches!(character, 'a'..='z' | 'A'..='Z' | '-'))
{
return None;
}
}
let mut in_comment = false;
for (index, character) in body.char_indices() {
if in_comment {
if character == '\n' {
in_comment = false;
}
continue;
}
if flags.extended && character == '#' {
in_comment = true;
} else if character == '}' {
return Some(&suffix[..ignored + index + 2]);
}
}
None
}
fn schema_pattern_group_flags(
suffix: &str,
mut flags: SchemaPatternFlags,
) -> Option<(&str, bool, SchemaPatternFlags)> {
let modifiers = suffix.strip_prefix('?')?;
let mut enabled = true;
for (index, character) in modifiers.char_indices() {
match character {
'-' => enabled = false,
's' => flags.dot_all = enabled,
'x' => flags.extended = enabled,
'i' => flags.ignore_case = enabled,
'm' | 'R' | 'U' | 'u' => {}
':' | ')' => return Some((&suffix[..index + 2], character == ':', flags)),
_ => return None,
}
}
None
}
fn validate_format_keyword(
object: &serde_json::Map<String, Value>,
path: &str,
) -> Result<(), SchemaAdmissionError> {
if object.get("format").is_some_and(|value| !value.is_string()) {
Err(SchemaAdmissionError::new(
format!("{path}.format"),
"format must be a string",
))
} else {
Ok(())
}
}
pub fn validate(schema: &Value, value: &Value) -> ValidationResult {
bound_raw_validation_schema(schema)?;
validate_with_schema_features(schema, value, false)
}
fn bound_raw_validation_schema(schema: &Value) -> ValidationResult {
bound_schema_document(schema).map_err(|error| {
vec![ValidationError {
path: "root".to_owned(),
message: error.reason().to_owned(),
}]
})
}
fn validate_admitted_final_schema(schema: &Value, value: &Value) -> ValidationResult {
validate_with_schema_features(schema, value, true)
}
fn validate_with_schema_features(
schema: &Value,
value: &Value,
enforce_unevaluated_properties: bool,
) -> ValidationResult {
let mut context = ValidationContext::new(schema, enforce_unevaluated_properties);
validate_with_context(schema, value, &mut context)
}
fn validate_with_context<'a>(
schema: &'a Value,
value: &Value,
context: &mut ValidationContext<'a>,
) -> ValidationResult {
let enforce_unevaluated_properties = context.enforce_unevaluated_properties;
let mut errors = Vec::new();
let mut instance_nodes = 0;
let mut instance_string_work = 0;
if !validate_instance_bounds(
value,
"root",
0,
enforce_unevaluated_properties,
&mut instance_nodes,
&mut instance_string_work,
&mut errors,
) {
return Err(errors);
}
if bounded_schema_json_bytes(value, MAX_SCHEMA_INSTANCE_BYTES).is_none() {
push_error(&mut errors, "root", "instance document byte limit exceeded");
return Err(errors);
}
let preflight_work = instance_string_work
+ if enforce_unevaluated_properties {
instance_nodes
} else {
0
};
if !consume_required_work_units(context, preflight_work, "root", &mut errors) {
return Err(errors);
}
validate_internal(schema, value, "root", &mut errors, context);
if context.work_exhausted
&& !errors
.iter()
.any(|error| error.message == "schema validation work limit exceeded")
{
push_error(&mut errors, "root", "schema validation work limit exceeded");
}
if context.pattern_input_exceeded
&& !errors
.iter()
.any(|error| error.message == "pattern input byte limit exceeded")
{
push_error(&mut errors, "root", "pattern input byte limit exceeded");
}
if let Some(message) = context.recursion_limit_exceeded
&& !errors.iter().any(|error| error.message == message)
{
push_error(&mut errors, "root", message);
}
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
pub fn validate_strict(schema: &Value, value: &Value) -> ValidationResult {
bound_raw_validation_schema(schema)?;
let strict_schema = make_strict_schema(schema);
validate(&strict_schema, value)
}
fn make_strict_schema(schema: &Value) -> Value {
match schema {
Value::Object(obj) => {
let mut new_obj = obj.clone();
if let Some(type_val) = obj.get("type") {
let is_object_type = type_val == "object"
|| type_val
.as_array()
.is_some_and(|arr| arr.iter().any(|t| t == "object"));
if is_object_type && !obj.contains_key("additionalProperties") {
new_obj.insert("additionalProperties".to_string(), Value::Bool(false));
}
}
for keyword in [
"properties",
"patternProperties",
"dependentSchemas",
"dependencies",
"$defs",
"definitions",
] {
if let Some(Value::Object(subschemas)) = obj.get(keyword) {
let strict_subschemas: serde_json::Map<String, Value> = subschemas
.iter()
.map(|(key, subschema)| (key.clone(), make_strict_schema(subschema)))
.collect();
new_obj.insert(keyword.to_owned(), Value::Object(strict_subschemas));
}
}
for keyword in [
"additionalProperties",
"additionalItems",
"unevaluatedProperties",
"unevaluatedItems",
"items",
"contains",
"not",
"if",
"then",
"else",
"propertyNames",
"contentSchema",
] {
if let Some(subschema) = obj.get(keyword) {
new_obj.insert(keyword.to_owned(), make_strict_schema(subschema));
}
}
for keyword in ["prefixItems", "allOf", "anyOf", "oneOf"] {
if let Some(Value::Array(subschemas)) = obj.get(keyword) {
let strict_subschemas = subschemas.iter().map(make_strict_schema).collect();
new_obj.insert(keyword.to_owned(), Value::Array(strict_subschemas));
}
}
Value::Object(new_obj)
}
Value::Array(arr) => {
Value::Array(arr.iter().map(make_strict_schema).collect())
}
_ => schema.clone(),
}
}
#[derive(Clone, Copy)]
struct MetaSchemaValidationScope<'a> {
resource: &'a Value,
dialect: &'a str,
resources: &'a [SchemaDialectCheck<'a>],
}
struct ValidationContext<'a> {
root_schema: &'a Value,
schema_depth: usize,
reference_depth: usize,
dynamic_scope: Vec<&'a serde_json::Map<String, Value>>,
remaining_work: usize,
work_exhausted: bool,
pattern_input_exceeded: bool,
recursion_limit_exceeded: Option<&'static str>,
enforce_unevaluated_properties: bool,
meta_validation: Option<MetaSchemaValidationScope<'a>>,
unsupported_meta_resource: bool,
}
impl<'a> ValidationContext<'a> {
const fn new(root_schema: &'a Value, enforce_unevaluated_properties: bool) -> Self {
Self {
root_schema,
schema_depth: 0,
reference_depth: 0,
dynamic_scope: Vec::new(),
remaining_work: MAX_SCHEMA_VALIDATION_WORK,
work_exhausted: false,
pattern_input_exceeded: false,
recursion_limit_exceeded: None,
enforce_unevaluated_properties,
meta_validation: None,
unsupported_meta_resource: false,
}
}
fn consume_work(&mut self) -> bool {
let Some(remaining_work) = self.remaining_work.checked_sub(1) else {
self.work_exhausted = true;
return false;
};
self.remaining_work = remaining_work;
true
}
fn meta_resource_error(&mut self, value: &Value) -> Option<&'static str> {
let scope = self.meta_validation?;
if std::ptr::eq(value, scope.resource) || value.get("$id").is_none() {
return None;
}
for resource in scope.resources {
if !self.consume_work() {
return Some("schema validation work limit exceeded");
}
if std::ptr::eq(value, resource.schema) {
if resource.dialect != scope.dialect {
self.unsupported_meta_resource = true;
return Some("cross-dialect meta-schema traversal is unsupported");
}
return None;
}
}
None
}
fn enter_schema(&mut self) -> bool {
if self.schema_depth >= MAX_SCHEMA_VALIDATION_DEPTH {
self.recursion_limit_exceeded
.get_or_insert("schema validation nesting limit exceeded");
return false;
}
if !self.consume_work() {
return false;
}
self.schema_depth += 1;
true
}
fn leave_schema(&mut self) {
self.schema_depth -= 1;
}
fn enter_reference(&mut self) -> bool {
if self.reference_depth >= MAX_LOCAL_REFERENCE_DEPTH {
self.recursion_limit_exceeded
.get_or_insert("local schema reference depth limit exceeded");
return false;
}
self.reference_depth += 1;
true
}
fn leave_reference(&mut self) {
self.reference_depth -= 1;
}
fn push_dynamic_scope(&mut self, schema: &'a serde_json::Map<String, Value>) {
self.dynamic_scope.push(schema);
}
fn pop_dynamic_scope(&mut self) {
let _ = self.dynamic_scope.pop();
}
fn dynamic_anchor_target(&mut self, name: &str) -> Result<Option<&'a Value>, &'static str> {
let root_schema = self.root_schema;
let mut previous_resource: Option<&Value> = None;
for index in 0..self.dynamic_scope.len() {
let source = self.dynamic_scope[index];
let mut charge = || {
if self.consume_work() {
Ok(())
} else {
Err("schema validation work limit exceeded")
}
};
let scope = find_schema_resource_scope(root_schema, source, &mut charge)?
.ok_or("unresolved local schema reference")?;
if previous_resource.is_some_and(|previous| std::ptr::eq(previous, scope.resource)) {
continue;
}
previous_resource = Some(scope.resource);
if let Some(target) =
find_resource_anchor_with_charge(scope.resource, name, &mut charge)?
&& target.get("$dynamicAnchor").and_then(Value::as_str) == Some(name)
{
return Ok(Some(target));
}
}
Ok(None)
}
}
fn consume_required_work_units(
context: &mut ValidationContext<'_>,
units: usize,
path: &str,
errors: &mut Vec<ValidationError>,
) -> bool {
for _ in 0..units {
if !context.consume_work() {
push_error(errors, path, "schema validation work limit exceeded");
return false;
}
}
true
}
fn consume_validation_work(
context: &mut ValidationContext<'_>,
path: &str,
errors: &mut Vec<ValidationError>,
) -> bool {
if !context.enforce_unevaluated_properties {
return true;
}
if context.consume_work() {
true
} else {
push_error(errors, path, "schema validation work limit exceeded");
false
}
}
fn charged_regex_is_match(
pattern: &Regex,
candidate: &str,
path: &str,
errors: &mut Vec<ValidationError>,
context: &mut ValidationContext<'_>,
) -> Option<bool> {
if candidate.len() > MAX_SCHEMA_PATTERN_INPUT_BYTES {
context.pattern_input_exceeded = true;
push_error(errors, path, "pattern input byte limit exceeded");
return None;
}
(consume_validation_work(context, path, errors)
&& consume_required_work_units(
context,
additional_string_work(candidate.len()),
path,
errors,
))
.then(|| pattern.is_match(candidate))
}
fn additional_string_work(bytes: usize) -> usize {
bytes.saturating_sub(1) / SCHEMA_STRING_WORK_UNIT_BYTES
}
fn validate_instance_bounds(
value: &Value,
path: &str,
depth: usize,
final_semantics: bool,
node_count: &mut usize,
string_work: &mut usize,
errors: &mut Vec<ValidationError>,
) -> bool {
if depth >= MAX_SCHEMA_INSTANCE_DEPTH {
push_error(errors, path, "instance nesting limit exceeded");
return false;
}
*node_count += 1;
if *node_count > MAX_SCHEMA_INSTANCE_NODES {
push_error(errors, path, "instance node limit exceeded");
return false;
}
match value {
Value::String(string) => {
if string.len() > MAX_SCHEMA_INSTANCE_STRING_BYTES {
push_error(errors, path, "instance string byte limit exceeded");
return false;
}
*string_work += additional_string_work(string.len());
}
Value::Array(items) => {
for (index, item) in items.iter().enumerate() {
if !validate_instance_bounds(
item,
&format!("{path}[{index}]"),
depth + 1,
final_semantics,
node_count,
string_work,
errors,
) {
return false;
}
}
}
Value::Object(members) => {
for (name, member) in members {
if name.len() > MAX_SCHEMA_INSTANCE_KEY_BYTES {
push_error(
errors,
path,
"instance object member-name byte limit exceeded",
);
return false;
}
if !validate_instance_bounds(
member,
&diagnostic_child_path(path, name),
depth + 1,
final_semantics,
node_count,
string_work,
errors,
) {
return false;
}
}
}
Value::Number(number) => {
if final_semantics && ExactDecimal::from_number(number).is_none() {
push_error(
errors,
path,
"instance number exceeds exact comparison bound",
);
return false;
}
if !final_semantics {
let bytes = number.as_str().len();
if bytes > MAX_SCHEMA_INSTANCE_BYTES {
push_error(errors, path, "instance number byte limit exceeded");
return false;
}
*string_work += additional_string_work(bytes);
}
}
Value::Null | Value::Bool(_) => {}
}
true
}
fn bounded_diagnostic_path(path: &str, root: &'static str) -> String {
if path.len() <= MAX_SCHEMA_DIAGNOSTIC_PATH_BYTES {
path.to_owned()
} else {
format!("{root}...")
}
}
fn escaped_diagnostic_character(character: char) -> String {
use std::fmt::Write as _;
if character.is_ascii_alphanumeric()
|| matches!(character, '_' | '-' | '.' | '/' | ':' | '$' | '~')
{
return character.to_string();
}
let mut utf16 = [0; 2];
character
.encode_utf16(&mut utf16)
.iter()
.fold(String::new(), |mut escaped, unit| {
let _ = write!(escaped, "\\u{unit:04x}");
escaped
})
}
fn diagnostic_child_path(parent: &str, name: &str) -> String {
let root = if parent.starts_with('$') { "$" } else { "root" };
if parent.ends_with("...") {
return bounded_diagnostic_path(parent, root);
}
let plain = !name.is_empty()
&& name.len() <= MAX_SCHEMA_DIAGNOSTIC_SEGMENT_BYTES
&& name
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'));
let suffix = if plain {
format!(".{name}")
} else {
let mut escaped = String::new();
for (offset, character) in name.char_indices() {
if offset + character.len_utf8() > MAX_SCHEMA_DIAGNOSTIC_SEGMENT_BYTES {
escaped.push_str("...");
break;
}
escaped.push_str(&escaped_diagnostic_character(character));
}
format!("[\"{escaped}\"]")
};
if parent.len() + suffix.len() > MAX_SCHEMA_DIAGNOSTIC_PATH_BYTES - 3 {
return bounded_diagnostic_path(&format!("{parent}..."), root);
}
format!("{parent}{suffix}")
}
fn diagnostic_schema_member_path(parent: &str, keyword: &str, name: &str) -> String {
let keyword_path = format!("{parent}.{keyword}");
if keyword == "patternProperties" {
bounded_diagnostic_path(&keyword_path, "$")
} else {
diagnostic_child_path(&keyword_path, name)
}
}
fn push_error(errors: &mut Vec<ValidationError>, path: &str, message: &'static str) {
if errors.len() < MAX_VALIDATION_ERRORS {
errors.push(ValidationError {
path: bounded_diagnostic_path(path, "root"),
message: message.to_owned(),
});
}
}
fn validate_internal<'a>(
schema: &'a Value,
value: &Value,
path: &str,
errors: &mut Vec<ValidationError>,
context: &mut ValidationContext<'a>,
) {
if !context.enter_schema() {
let reason = if context.remaining_work == 0 {
"schema validation work limit exceeded"
} else {
"schema validation nesting limit exceeded"
};
push_error(errors, path, reason);
return;
}
if let Some(b) = schema.as_bool() {
if !b {
push_error(errors, path, "schema rejects all values");
}
context.leave_schema();
return;
}
let Some(schema_obj) = schema.as_object() else {
context.leave_schema();
return; };
if let Some(reason) = context.meta_resource_error(value) {
push_error(errors, path, reason);
context.leave_schema();
return;
}
if let Some(type_val) = schema_obj.get("type") {
if !validate_type(type_val, value, context.enforce_unevaluated_properties) {
let message = match json_type_name_with_final_semantics(
value,
context.enforce_unevaluated_properties,
) {
"null" => "null does not match the expected type",
"boolean" => "boolean does not match the expected type",
"integer" => "integer does not match the expected type",
"number" => "number does not match the expected type",
"string" => "string does not match the expected type",
"array" => "array does not match the expected type",
_ => "object does not match the expected type",
};
push_error(errors, path, message);
context.leave_schema();
return; }
}
let tracks_dynamic_scope = context.enforce_unevaluated_properties;
if tracks_dynamic_scope {
context.push_dynamic_scope(schema_obj);
}
validate_local_reference(schema_obj, value, path, errors, context);
validate_dynamic_reference(schema_obj, value, path, errors, context);
validate_composition(schema_obj, value, path, errors, context);
if let Some(enum_val) = schema_obj.get("enum") {
if let Some(enum_arr) = enum_val.as_array() {
let mut matches = false;
for candidate in enum_arr {
match json_schema_equal_with_work(candidate, value, path, errors, context) {
Some(true) => {
matches = true;
break;
}
Some(false) => {}
None => break,
}
}
if !matches && !context.work_exhausted {
push_error(errors, path, "value does not match any enum candidate");
}
}
}
if let Some(const_val) = schema_obj.get("const") {
let matches = json_schema_equal_with_work(value, const_val, path, errors, context);
if matches == Some(false) {
push_error(errors, path, "value does not match the const constraint");
}
}
match value {
Value::Object(obj) => {
validate_object(schema_obj, value, obj, path, errors, context);
}
Value::Array(arr) => {
validate_array(schema_obj, value, arr, path, errors, context);
}
Value::String(s) => {
validate_string(schema_obj, s, path, errors, context);
}
Value::Number(n) => {
validate_number(
schema_obj,
n,
path,
errors,
context.enforce_unevaluated_properties,
context,
);
}
_ => {}
}
if tracks_dynamic_scope {
context.pop_dynamic_scope();
}
context.leave_schema();
}
fn validate_local_reference(
schema: &serde_json::Map<String, Value>,
value: &Value,
path: &str,
errors: &mut Vec<ValidationError>,
context: &mut ValidationContext<'_>,
) {
let Some(reference) = schema.get("$ref").and_then(Value::as_str) else {
return;
};
if !context.enter_reference() {
push_error(errors, path, "local schema reference depth limit exceeded");
return;
}
let root_schema = context.root_schema;
let resolution = if context.enforce_unevaluated_properties {
resolve_local_reference_with_work(root_schema, schema, reference, context)
} else {
resolve_legacy_local_reference(root_schema, reference)
};
match resolution {
Ok(target) => validate_internal(target, value, path, errors, context),
Err(message) => push_error(errors, path, message),
}
context.leave_reference();
}
fn validate_dynamic_reference(
schema: &serde_json::Map<String, Value>,
value: &Value,
path: &str,
errors: &mut Vec<ValidationError>,
context: &mut ValidationContext<'_>,
) {
if !context.enforce_unevaluated_properties {
return;
}
let Some(reference) = schema.get("$dynamicRef").and_then(Value::as_str) else {
return;
};
if !context.enter_reference() {
push_error(errors, path, "local schema reference depth limit exceeded");
return;
}
let root_schema = context.root_schema;
match resolve_dynamic_reference_with_work(root_schema, schema, reference, context) {
Ok(target) => validate_internal(target, value, path, errors, context),
Err(message) => push_error(errors, path, message),
}
context.leave_reference();
}
struct SchemaResourceScope<'a> {
resource: &'a Value,
base: Option<String>,
}
fn resolve_dynamic_reference_with_work<'a>(
root_schema: &'a Value,
source: &serde_json::Map<String, Value>,
reference: &str,
context: &mut ValidationContext<'a>,
) -> Result<&'a Value, &'static str> {
let target = resolve_local_reference_with_work(root_schema, source, reference, context)?;
let dynamic_anchor = split_uri_reference_fragment(reference)
.1
.and_then(decode_uri_fragment)
.filter(|fragment| !fragment.is_empty() && !fragment.starts_with('/'))
.filter(|fragment| {
target.get("$dynamicAnchor").and_then(Value::as_str) == Some(fragment.as_str())
});
match dynamic_anchor {
Some(name) => Ok(context.dynamic_anchor_target(&name)?.unwrap_or(target)),
None => Ok(target),
}
}
fn resolve_local_reference<'a>(
root_schema: &'a Value,
source: &serde_json::Map<String, Value>,
reference: &str,
) -> Result<&'a Value, &'static str> {
let mut uncharged = || Ok(());
resolve_local_reference_with_charge(root_schema, source, reference, &mut uncharged)
}
fn resolve_local_reference_with_work<'a>(
root_schema: &'a Value,
source: &serde_json::Map<String, Value>,
reference: &str,
context: &mut ValidationContext<'_>,
) -> Result<&'a Value, &'static str> {
let mut charge = || {
if context.consume_work() {
Ok(())
} else {
Err("schema validation work limit exceeded")
}
};
resolve_local_reference_with_charge(root_schema, source, reference, &mut charge)
}
fn resolve_local_reference_with_charge<'a>(
root_schema: &'a Value,
source: &serde_json::Map<String, Value>,
reference: &str,
charge: &mut dyn FnMut() -> Result<(), &'static str>,
) -> Result<&'a Value, &'static str> {
if reference.len() > MAX_SCHEMA_ASSERTION_STRING_BYTES {
return Err("schema reference exceeds byte limit");
}
if !is_bounded_uri_reference(reference) {
return Err("invalid local schema reference");
}
let source_scope = find_schema_resource_scope(root_schema, source, charge)?
.ok_or("unresolved local schema reference")?;
let (identifier, fragment) = split_uri_reference_fragment(reference);
let fragment = match fragment {
Some(fragment) => {
Some(decode_uri_fragment(fragment).ok_or("invalid local schema reference")?)
}
None => None,
};
let resource = if identifier.is_empty() {
source_scope.resource
} else {
let identifier = resolve_uri_reference(source_scope.base.as_deref(), identifier)
.ok_or("external schema reference is not allowed")?;
find_local_schema_resource_with_charge(root_schema, &identifier, charge)?
.ok_or("external schema reference is not allowed")?
};
resolve_local_reference_fragment_with_charge(
resource,
fragment.as_deref().unwrap_or(""),
charge,
)
}
fn resolve_local_reference_fragment<'a>(
resource: &'a Value,
fragment: &str,
) -> Result<&'a Value, &'static str> {
if !fragment.is_empty() && !fragment.starts_with('/') {
return find_resource_anchor(resource, fragment).ok_or("unresolved local schema reference");
}
let mut uncharged = || Ok(());
resolve_local_reference_fragment_with_charge(resource, fragment, &mut uncharged)
}
fn resolve_local_reference_fragment_with_charge<'a>(
resource: &'a Value,
fragment: &str,
charge: &mut dyn FnMut() -> Result<(), &'static str>,
) -> Result<&'a Value, &'static str> {
if fragment.is_empty() {
return Ok(resource);
}
if let Some(pointer) = fragment.strip_prefix('/') {
let mut target = resource;
for encoded_segment in pointer.split('/') {
charge()?;
let segment = unescape_json_pointer_segment(encoded_segment)
.ok_or("invalid local schema reference")?;
target = match target {
Value::Object(object) => object.get(&segment),
Value::Array(array) => {
let canonical = segment == "0"
|| (segment
.bytes()
.next()
.is_some_and(|byte| matches!(byte, b'1'..=b'9'))
&& segment.bytes().all(|byte| byte.is_ascii_digit()));
if !canonical && segment != "-" {
return Err("invalid local schema reference");
}
segment
.parse::<usize>()
.ok()
.and_then(|index| array.get(index))
}
_ => None,
}
.ok_or("unresolved local schema reference")?;
}
return Ok(target);
}
find_resource_anchor_with_charge(resource, fragment, charge)?
.ok_or("unresolved local schema reference")
}
fn resolve_legacy_local_reference<'a>(
root_schema: &'a Value,
reference: &str,
) -> Result<&'a Value, &'static str> {
if reference == "#" || reference.starts_with("#/") {
resolve_local_reference_fragment(root_schema, &reference[1..])
} else {
Err("external schema reference is not allowed")
}
}
fn find_schema_resource_scope<'a>(
root_schema: &'a Value,
target: &serde_json::Map<String, Value>,
charge: &mut dyn FnMut() -> Result<(), &'static str>,
) -> Result<Option<SchemaResourceScope<'a>>, &'static str> {
find_schema_resource_scope_inner(root_schema, target, None, root_schema, None, charge)
}
fn find_schema_resource_scope_inner<'a>(
schema: &'a Value,
target: &serde_json::Map<String, Value>,
parent_base: Option<&str>,
inherited_resource: &'a Value,
inherited_base: Option<String>,
charge: &mut dyn FnMut() -> Result<(), &'static str>,
) -> Result<Option<SchemaResourceScope<'a>>, &'static str> {
charge()?;
let Some(object) = schema.as_object() else {
return Ok(None);
};
let identifier = object.get("$id").and_then(Value::as_str);
let base = if let Some(identifier) = identifier {
Some(
resolve_resource_identifier(parent_base, identifier)
.ok_or("unresolved local schema reference")?,
)
} else {
inherited_base
};
let resource = if identifier.is_some() {
schema
} else {
inherited_resource
};
if std::ptr::eq(object, target) {
return Ok(Some(SchemaResourceScope { resource, base }));
}
find_schema_child_scope(
schema,
target,
base.as_deref(),
resource,
base.clone(),
charge,
)
}
fn find_schema_child_scope<'a>(
schema: &'a Value,
target: &serde_json::Map<String, Value>,
base: Option<&str>,
resource: &'a Value,
inherited_base: Option<String>,
charge: &mut dyn FnMut() -> Result<(), &'static str>,
) -> Result<Option<SchemaResourceScope<'a>>, &'static str> {
let Some(object) = schema.as_object() else {
return Ok(None);
};
for keyword in [
"properties",
"patternProperties",
"$defs",
"definitions",
"dependencies",
"dependentSchemas",
] {
if let Some(subschemas) = object.get(keyword).and_then(Value::as_object) {
for subschema in subschemas.values() {
if let Some(scope) = find_schema_resource_scope_inner(
subschema,
target,
base,
resource,
inherited_base.clone(),
charge,
)? {
return Ok(Some(scope));
}
}
}
}
for keyword in [
"additionalProperties",
"unevaluatedProperties",
"unevaluatedItems",
"items",
"contains",
"not",
"if",
"then",
"else",
"propertyNames",
"contentSchema",
] {
if let Some(subschema) = object.get(keyword)
&& let Some(scope) = find_schema_resource_scope_inner(
subschema,
target,
base,
resource,
inherited_base.clone(),
charge,
)?
{
return Ok(Some(scope));
}
}
for keyword in ["prefixItems", "allOf", "anyOf", "oneOf"] {
if let Some(subschemas) = object.get(keyword).and_then(Value::as_array) {
for subschema in subschemas {
if let Some(scope) = find_schema_resource_scope_inner(
subschema,
target,
base,
resource,
inherited_base.clone(),
charge,
)? {
return Ok(Some(scope));
}
}
}
}
Ok(None)
}
fn find_local_schema_resource<'a>(schema: &'a Value, identifier: &str) -> Option<&'a Value> {
let mut uncharged = || Ok(());
find_local_schema_resource_with_charge(schema, identifier, &mut uncharged)
.ok()
.flatten()
}
fn find_local_schema_resource_with_charge<'a>(
schema: &'a Value,
identifier: &str,
charge: &mut dyn FnMut() -> Result<(), &'static str>,
) -> Result<Option<&'a Value>, &'static str> {
find_local_schema_resource_inner(schema, identifier, None, charge)
}
fn find_local_schema_resource_inner<'a>(
schema: &'a Value,
identifier: &str,
parent_base: Option<&str>,
charge: &mut dyn FnMut() -> Result<(), &'static str>,
) -> Result<Option<&'a Value>, &'static str> {
charge()?;
let Some(object) = schema.as_object() else {
return Ok(None);
};
let base = if let Some(candidate) = object.get("$id").and_then(Value::as_str) {
Some(
resolve_resource_identifier(parent_base, candidate)
.ok_or("unresolved local schema reference")?,
)
} else {
None
};
if base.as_deref() == Some(identifier) {
return Ok(Some(schema));
}
let inherited_base = base.as_deref().or(parent_base);
find_local_schema_resource_child(schema, identifier, inherited_base, charge)
}
fn find_local_schema_resource_child<'a>(
schema: &'a Value,
identifier: &str,
parent_base: Option<&str>,
charge: &mut dyn FnMut() -> Result<(), &'static str>,
) -> Result<Option<&'a Value>, &'static str> {
let Some(object) = schema.as_object() else {
return Ok(None);
};
for keyword in [
"properties",
"patternProperties",
"$defs",
"definitions",
"dependencies",
"dependentSchemas",
] {
if let Some(subschemas) = object.get(keyword).and_then(Value::as_object) {
for subschema in subschemas.values() {
if let Some(found) =
find_local_schema_resource_inner(subschema, identifier, parent_base, charge)?
{
return Ok(Some(found));
}
}
}
}
for keyword in [
"additionalProperties",
"unevaluatedProperties",
"unevaluatedItems",
"items",
"contains",
"not",
"if",
"then",
"else",
"propertyNames",
"contentSchema",
] {
if let Some(subschema) = object.get(keyword)
&& let Some(found) =
find_local_schema_resource_inner(subschema, identifier, parent_base, charge)?
{
return Ok(Some(found));
}
}
for keyword in ["prefixItems", "allOf", "anyOf", "oneOf"] {
if let Some(subschemas) = object.get(keyword).and_then(Value::as_array) {
for subschema in subschemas {
if let Some(found) =
find_local_schema_resource_inner(subschema, identifier, parent_base, charge)?
{
return Ok(Some(found));
}
}
}
}
Ok(None)
}
fn split_uri_reference_fragment(reference: &str) -> (&str, Option<&str>) {
reference
.split_once('#')
.map_or((reference, None), |(identifier, fragment)| {
(identifier, Some(fragment))
})
}
fn decode_uri_fragment(fragment: &str) -> Option<String> {
let mut decoded = Vec::with_capacity(fragment.len());
let bytes = fragment.as_bytes();
let mut index = 0;
while index < bytes.len() {
if bytes[index] != b'%' {
decoded.push(bytes[index]);
index += 1;
continue;
}
let high = *bytes.get(index + 1)?;
let low = *bytes.get(index + 2)?;
decoded.push((hex_value(high)? << 4) | hex_value(low)?);
index += 3;
}
String::from_utf8(decoded).ok()
}
fn hex_value(byte: u8) -> Option<u8> {
match byte {
b'0'..=b'9' => Some(byte - b'0'),
b'a'..=b'f' => Some(byte - b'a' + 10),
b'A'..=b'F' => Some(byte - b'A' + 10),
_ => None,
}
}
fn resolve_resource_identifier(parent_base: Option<&str>, identifier: &str) -> Option<String> {
let (identifier, fragment) = split_uri_reference_fragment(identifier);
if fragment.is_some_and(|fragment| !fragment.is_empty()) {
return None;
}
resolve_uri_reference(parent_base, identifier)
}
fn resolve_uri_reference(base: Option<&str>, reference: &str) -> Option<String> {
if !is_bounded_uri_reference(reference) {
return None;
}
if has_uri_scheme(reference) {
return normalize_absolute_uri_reference(reference);
}
let base = base?;
let base_uri = AbsoluteUri::parse_with_max_bytes(base, MAX_SCHEMA_ASSERTION_STRING_BYTES)
.ok()
.filter(|uri| uri.fragment().is_none())?;
let scheme = base_uri.scheme().as_str();
let (reference_path, reference_query) = reference
.split_once('?')
.map_or((reference, None), |(path, query)| (path, Some(query)));
if reference_path.starts_with("//") {
let resolved = format!("{scheme}:{reference}");
return normalize_absolute_uri_reference(&resolved);
}
if !reference_path.starts_with('/')
&& reference_path
.split('/')
.next()
.is_some_and(|segment| segment.contains(':'))
{
return None;
}
let hierarchy = base_uri.hier_part();
let (prefix, base_path, has_authority) =
if let Some(authority_and_path) = hierarchy.strip_prefix("//") {
let authority_end = authority_and_path
.find('/')
.map_or(hierarchy.len(), |index| index + 2);
(
format!("{scheme}:{}", &hierarchy[..authority_end]),
&hierarchy[authority_end..],
true,
)
} else {
(format!("{scheme}:"), hierarchy, false)
};
let path = if reference_path.is_empty() {
base_path.to_owned()
} else if reference_path.starts_with('/') {
remove_uri_dot_segments(reference_path)
} else {
let directory_end = base_path.rfind('/').map_or(0, |index| index + 1);
let directory = if has_authority && base_path.is_empty() {
"/"
} else {
&base_path[..directory_end]
};
remove_uri_dot_segments(&format!("{}{}", directory, reference_path))
};
let query = match (reference_path.is_empty(), reference_query, base_uri.query()) {
(_, Some(query), _) => format!("?{query}"),
(true, None, Some(query)) => format!("?{query}"),
(true, None, None) | (false, None, _) => String::new(),
};
let resolved = format!("{prefix}{path}{query}");
AbsoluteUri::parse_with_max_bytes(&resolved, MAX_SCHEMA_ASSERTION_STRING_BYTES)
.ok()
.filter(|uri| uri.fragment().is_none())
.map(|uri| uri.as_str().to_owned())
}
fn normalize_absolute_uri_reference(reference: &str) -> Option<String> {
let uri = AbsoluteUri::parse_with_max_bytes(reference, MAX_SCHEMA_ASSERTION_STRING_BYTES)
.ok()
.filter(|uri| uri.fragment().is_none())?;
let scheme = uri.scheme().as_str();
let hierarchy = reference.strip_prefix(&format!("{scheme}:"))?;
let (hierarchy, query) = hierarchy
.split_once('?')
.map_or((hierarchy, None), |(path, query)| (path, Some(query)));
let normalized = if let Some(authority_and_path) = hierarchy.strip_prefix("//") {
let authority_end = authority_and_path
.find('/')
.map_or(hierarchy.len(), |index| index + 2);
let authority = &hierarchy[..authority_end];
let path = remove_uri_dot_segments(&hierarchy[authority_end..]);
format!("{authority}{path}")
} else {
remove_uri_dot_segments(hierarchy)
};
let query = query.map_or_else(String::new, |query| format!("?{query}"));
let normalized = format!("{scheme}:{normalized}{query}");
AbsoluteUri::parse_with_max_bytes(&normalized, MAX_SCHEMA_ASSERTION_STRING_BYTES)
.ok()
.filter(|uri| uri.fragment().is_none())
.map(|uri| uri.as_str().to_owned())
}
fn has_uri_scheme(reference: &str) -> bool {
reference.find(':').is_some_and(|index| {
!reference[..index].contains(['/', '?']) && is_valid_uri_scheme(&reference[..index])
})
}
fn is_bounded_uri_reference(reference: &str) -> bool {
reference.len() <= MAX_SCHEMA_ASSERTION_STRING_BYTES
&& reference.bytes().enumerate().all(|(index, byte)| {
if byte == b'%' {
return reference
.as_bytes()
.get(index + 1..=index + 2)
.is_some_and(|digits| digits.iter().all(u8::is_ascii_hexdigit));
}
byte.is_ascii()
&& byte > b' '
&& byte != 0x7f
&& (byte.is_ascii_alphanumeric()
|| matches!(
byte,
b'-' | b'.'
| b'_'
| b'~'
| b':'
| b'/'
| b'?'
| b'#'
| b'['
| b']'
| b'@'
| b'!'
| b'$'
| b'&'
| b'\''
| b'('
| b')'
| b'*'
| b'+'
| b','
| b';'
| b'='
| b'%'
))
})
}
fn remove_uri_dot_segments(path: &str) -> String {
let mut input = path.to_owned();
let mut output = String::with_capacity(path.len());
while !input.is_empty() {
if input.starts_with("../") {
input.drain(..3);
} else if input.starts_with("./") {
input.drain(..2);
} else if input.starts_with("/./") {
input.replace_range(..3, "/");
} else if input == "/." {
input.truncate(1);
} else if input.starts_with("/../") {
input.replace_range(..4, "/");
remove_last_uri_path_segment(&mut output);
} else if input == "/.." {
input.replace_range(..3, "/");
remove_last_uri_path_segment(&mut output);
} else if input == "." || input == ".." {
input.clear();
} else {
let segment_end = if let Some(path_after_initial_slash) = input.strip_prefix('/') {
path_after_initial_slash
.find('/')
.map_or(input.len(), |index| index + 1)
} else {
input.find('/').unwrap_or(input.len())
};
output.push_str(&input[..segment_end]);
input.drain(..segment_end);
}
}
output
}
fn remove_last_uri_path_segment(output: &mut String) {
if let Some(separator) = output.rfind('/') {
output.truncate(separator);
} else {
output.clear();
}
}
fn find_resource_anchor<'a>(schema: &'a Value, anchor: &str) -> Option<&'a Value> {
let mut uncharged = || Ok(());
find_resource_anchor_with_charge(schema, anchor, &mut uncharged)
.ok()
.flatten()
}
fn find_resource_anchor_with_charge<'a>(
schema: &'a Value,
anchor: &str,
charge: &mut dyn FnMut() -> Result<(), &'static str>,
) -> Result<Option<&'a Value>, &'static str> {
find_resource_anchor_inner(schema, anchor, true, charge)
}
fn find_resource_anchor_inner<'a>(
schema: &'a Value,
anchor: &str,
resource_root: bool,
charge: &mut dyn FnMut() -> Result<(), &'static str>,
) -> Result<Option<&'a Value>, &'static str> {
charge()?;
let Some(object) = schema.as_object() else {
return Ok(None);
};
if !resource_root && object.contains_key("$id") {
return Ok(None);
}
if ["$anchor", "$dynamicAnchor"].iter().any(|keyword| {
object
.get(*keyword)
.and_then(Value::as_str)
.is_some_and(|candidate| candidate == anchor)
}) {
return Ok(Some(schema));
}
for keyword in [
"properties",
"patternProperties",
"$defs",
"definitions",
"dependencies",
"dependentSchemas",
] {
if let Some(subschemas) = object.get(keyword).and_then(Value::as_object) {
for subschema in subschemas.values() {
if let Some(found) = find_resource_anchor_inner(subschema, anchor, false, charge)? {
return Ok(Some(found));
}
}
}
}
for keyword in [
"additionalProperties",
"unevaluatedProperties",
"unevaluatedItems",
"items",
"contains",
"not",
"if",
"then",
"else",
"propertyNames",
"contentSchema",
] {
if let Some(subschema) = object.get(keyword)
&& let Some(found) = find_resource_anchor_inner(subschema, anchor, false, charge)?
{
return Ok(Some(found));
}
}
for keyword in ["prefixItems", "allOf", "anyOf", "oneOf"] {
if let Some(subschemas) = object.get(keyword).and_then(Value::as_array) {
for subschema in subschemas {
if let Some(found) = find_resource_anchor_inner(subschema, anchor, false, charge)? {
return Ok(Some(found));
}
}
}
}
Ok(None)
}
fn unescape_json_pointer_segment(segment: &str) -> Option<String> {
let mut decoded = String::with_capacity(segment.len());
let mut characters = segment.chars();
while let Some(character) = characters.next() {
if character != '~' {
decoded.push(character);
continue;
}
match characters.next()? {
'0' => decoded.push('~'),
'1' => decoded.push('/'),
_ => return None,
}
}
Some(decoded)
}
fn validate_composition<'a>(
schema: &'a serde_json::Map<String, Value>,
value: &Value,
path: &str,
errors: &mut Vec<ValidationError>,
context: &mut ValidationContext<'a>,
) {
validate_all_of(schema, value, path, errors, context);
validate_any_of(schema, value, path, errors, context);
validate_one_of(schema, value, path, errors, context);
validate_not(schema, value, path, errors, context);
validate_conditional(schema, value, path, errors, context);
}
fn bounded_subschemas<'a>(
schema: &'a serde_json::Map<String, Value>,
keyword: &str,
path: &str,
errors: &mut Vec<ValidationError>,
) -> Option<&'a [Value]> {
let subschemas = schema.get(keyword)?.as_array()?;
if subschemas.len() > MAX_COMPOSITION_BRANCHES {
push_error(errors, path, "composition branch limit exceeded");
return None;
}
Some(subschemas)
}
fn validate_all_of<'a>(
schema: &'a serde_json::Map<String, Value>,
value: &Value,
path: &str,
errors: &mut Vec<ValidationError>,
context: &mut ValidationContext<'a>,
) {
if let Some(subschemas) = bounded_subschemas(schema, "allOf", path, errors) {
for subschema in subschemas {
validate_internal(subschema, value, path, errors, context);
}
}
}
fn validate_any_of<'a>(
schema: &'a serde_json::Map<String, Value>,
value: &Value,
path: &str,
errors: &mut Vec<ValidationError>,
context: &mut ValidationContext<'a>,
) {
let Some(subschemas) = bounded_subschemas(schema, "anyOf", path, errors) else {
return;
};
let mut matched = false;
for subschema in subschemas {
if branch_is_valid(subschema, value, path, context) {
matched = true;
break;
}
}
if !matched {
push_error(errors, path, "no subschema in anyOf matched");
}
}
fn validate_one_of<'a>(
schema: &'a serde_json::Map<String, Value>,
value: &Value,
path: &str,
errors: &mut Vec<ValidationError>,
context: &mut ValidationContext<'a>,
) {
let Some(subschemas) = bounded_subschemas(schema, "oneOf", path, errors) else {
return;
};
let mut matches = 0;
for subschema in subschemas {
if branch_is_valid(subschema, value, path, context) {
matches += 1;
}
}
if matches != 1 {
push_error(errors, path, "exactly one subschema in oneOf must match");
}
}
fn validate_not<'a>(
schema: &'a serde_json::Map<String, Value>,
value: &Value,
path: &str,
errors: &mut Vec<ValidationError>,
context: &mut ValidationContext<'a>,
) {
if let Some(subschema) = schema.get("not") {
if branch_is_valid(subschema, value, path, context) {
push_error(errors, path, "value must not match the not subschema");
}
}
}
fn validate_conditional<'a>(
schema: &'a serde_json::Map<String, Value>,
value: &Value,
path: &str,
errors: &mut Vec<ValidationError>,
context: &mut ValidationContext<'a>,
) {
let Some(condition) = schema.get("if") else {
return;
};
let branch_keyword = if branch_is_valid(condition, value, path, context) {
"then"
} else {
"else"
};
if let Some(subschema) = schema.get(branch_keyword) {
validate_internal(subschema, value, path, errors, context);
}
}
fn branch_is_valid<'a>(
schema: &'a Value,
value: &Value,
path: &str,
context: &mut ValidationContext<'a>,
) -> bool {
if context.enforce_unevaluated_properties && !context.consume_work() {
return false;
}
let mut branch_errors = Vec::new();
validate_internal(schema, value, path, &mut branch_errors, context);
branch_errors.is_empty()
}
fn validate_type(type_val: &Value, value: &Value, final_semantics: bool) -> bool {
match type_val {
Value::String(t) => matches_type(t, value, final_semantics),
Value::Array(types) => types.iter().any(|t| {
t.as_str()
.is_some_and(|type_str| matches_type(type_str, value, final_semantics))
}),
_ => true, }
}
fn matches_type(type_name: &str, value: &Value, final_semantics: bool) -> bool {
match type_name {
"string" => value.is_string(),
"number" => value.is_number(),
"integer" if final_semantics => value
.as_number()
.and_then(ExactDecimal::from_number)
.is_some_and(|number| number.is_integer()),
"integer" => value.is_i64() || value.is_u64(),
"boolean" => value.is_boolean(),
"object" => value.is_object(),
"array" => value.is_array(),
"null" => value.is_null(),
_ => true, }
}
fn json_type_name(value: &Value) -> &'static str {
match value {
Value::Null => "null",
Value::Bool(_) => "boolean",
Value::Number(n) if n.is_i64() || n.is_u64() => "integer",
Value::Number(_) => "number",
Value::String(_) => "string",
Value::Array(_) => "array",
Value::Object(_) => "object",
}
}
fn json_type_name_with_final_semantics(value: &Value, final_semantics: bool) -> &'static str {
if !final_semantics {
return json_type_name(value);
}
match value {
Value::Number(number)
if ExactDecimal::from_number(number).is_some_and(|number| number.is_integer()) =>
{
"integer"
}
_ => json_type_name(value),
}
}
fn validate_object<'a>(
schema: &'a serde_json::Map<String, Value>,
value: &Value,
obj: &serde_json::Map<String, Value>,
path: &str,
errors: &mut Vec<ValidationError>,
context: &mut ValidationContext<'a>,
) {
if let Some(required) = schema.get("required").and_then(|v| v.as_array()) {
for req in required {
if !consume_validation_work(context, path, errors) {
return;
}
if let Some(req_name) = req.as_str() {
if !obj.contains_key(req_name) {
push_error(
errors,
&diagnostic_child_path(path, req_name),
"missing required field",
);
}
}
}
}
let properties = schema.get("properties").and_then(Value::as_object);
let patterns = compile_pattern_properties(schema, path, errors, context);
if context.work_exhausted {
return;
}
for (key, value) in obj {
let property_path = diagnostic_child_path(path, key);
if let Some(property_schema) = properties.and_then(|properties| properties.get(key)) {
validate_internal(property_schema, value, &property_path, errors, context);
}
for (pattern, pattern_schema) in &patterns {
let Some(matches) =
charged_regex_is_match(pattern, key, &property_path, errors, context)
else {
return;
};
if matches {
validate_internal(pattern_schema, value, &property_path, errors, context);
}
}
}
if let Some(property_name_schema) = schema.get("propertyNames") {
for key in obj.keys() {
let property_path = diagnostic_child_path(path, key);
validate_internal(
property_name_schema,
&Value::String(key.clone()),
&property_path,
errors,
context,
);
}
}
validate_dependencies(schema, value, obj, path, errors, context);
if let Some(additional) = schema.get("additionalProperties") {
for (key, value) in obj {
let mut matches_pattern = false;
for (pattern, _) in &patterns {
let Some(matches) = charged_regex_is_match(pattern, key, path, errors, context)
else {
return;
};
if matches {
matches_pattern = true;
break;
}
}
let is_defined_property = properties
.is_some_and(|properties| properties.contains_key(key))
|| matches_pattern;
if !is_defined_property {
match additional {
Value::Bool(false) => {
push_error(
errors,
&diagnostic_child_path(path, key),
"additional property not allowed",
);
}
Value::Object(_) => {
let prop_path = diagnostic_child_path(path, key);
validate_internal(additional, value, &prop_path, errors, context);
}
_ => {}
}
}
}
}
if context.enforce_unevaluated_properties {
validate_unevaluated_properties(schema, value, obj, path, errors, context);
}
if let Some(min) = schema.get("minProperties")
&& count_compare_to_schema_bound(obj.len(), min, context.enforce_unevaluated_properties)
== Some(Ordering::Less)
{
push_error(
errors,
path,
"object has fewer properties than minProperties",
);
}
if let Some(max) = schema.get("maxProperties")
&& count_compare_to_schema_bound(obj.len(), max, context.enforce_unevaluated_properties)
== Some(Ordering::Greater)
{
push_error(
errors,
path,
"object has more properties than maxProperties",
);
}
}
fn validate_unevaluated_properties<'a>(
schema: &'a serde_json::Map<String, Value>,
value: &Value,
obj: &serde_json::Map<String, Value>,
path: &str,
errors: &mut Vec<ValidationError>,
context: &mut ValidationContext<'a>,
) {
let Some(unevaluated_schema) = schema.get("unevaluatedProperties") else {
return;
};
let mut evaluated = std::collections::HashSet::with_capacity(obj.len());
mark_evaluated_object_properties(
schema,
value,
obj,
path,
false,
&mut evaluated,
errors,
context,
);
for (key, member) in obj {
if !consume_validation_work(context, path, errors) {
return;
}
if !evaluated.contains(key) {
validate_internal(
unevaluated_schema,
member,
&diagnostic_child_path(path, key),
errors,
context,
);
}
}
}
fn mark_evaluated_object_properties<'a>(
schema: &'a serde_json::Map<String, Value>,
value: &Value,
obj: &serde_json::Map<String, Value>,
path: &str,
include_unevaluated_properties: bool,
evaluated: &mut std::collections::HashSet<String>,
errors: &mut Vec<ValidationError>,
context: &mut ValidationContext<'a>,
) {
context.push_dynamic_scope(schema);
mark_evaluated_object_properties_inner(
schema,
value,
obj,
path,
include_unevaluated_properties,
evaluated,
errors,
context,
);
context.pop_dynamic_scope();
}
fn mark_evaluated_object_properties_inner<'a>(
schema: &'a serde_json::Map<String, Value>,
value: &Value,
obj: &serde_json::Map<String, Value>,
path: &str,
include_unevaluated_properties: bool,
evaluated: &mut std::collections::HashSet<String>,
errors: &mut Vec<ValidationError>,
context: &mut ValidationContext<'a>,
) {
if !context.consume_work() {
push_error(errors, path, "schema validation work limit exceeded");
return;
}
let properties = schema.get("properties").and_then(Value::as_object);
let patterns = compile_pattern_properties(schema, path, errors, context);
if context.work_exhausted {
return;
}
for key in obj.keys() {
if !consume_validation_work(context, path, errors) {
return;
}
let matched_property = properties.is_some_and(|properties| properties.contains_key(key));
let mut matched_pattern = false;
for (pattern, _) in &patterns {
let Some(matches) = charged_regex_is_match(pattern, key, path, errors, context) else {
return;
};
if matches {
matched_pattern = true;
break;
}
}
if matched_property || matched_pattern || schema.contains_key("additionalProperties") {
evaluated.insert(key.clone());
}
}
if include_unevaluated_properties && schema.contains_key("unevaluatedProperties") {
for key in obj.keys() {
if !consume_validation_work(context, path, errors) {
return;
}
evaluated.insert(key.clone());
}
}
if let Some(reference) = schema.get("$ref").and_then(Value::as_str) {
if !context.enter_reference() {
push_error(errors, path, "local schema reference depth limit exceeded");
} else {
let root_schema = context.root_schema;
match resolve_local_reference_with_work(root_schema, schema, reference, context) {
Ok(target) if branch_is_valid(target, value, path, context) => {
if let Some(target) = target.as_object() {
mark_evaluated_object_properties(
target, value, obj, path, true, evaluated, errors, context,
);
}
}
Ok(_) => {}
Err(message) => push_error(errors, path, message),
}
context.leave_reference();
}
}
if let Some(reference) = schema.get("$dynamicRef").and_then(Value::as_str) {
if !context.enter_reference() {
push_error(errors, path, "local schema reference depth limit exceeded");
} else {
let root_schema = context.root_schema;
match resolve_dynamic_reference_with_work(root_schema, schema, reference, context) {
Ok(target) if branch_is_valid(target, value, path, context) => {
if let Some(target) = target.as_object() {
mark_evaluated_object_properties(
target, value, obj, path, true, evaluated, errors, context,
);
}
}
Ok(_) => {}
Err(message) => push_error(errors, path, message),
}
context.leave_reference();
}
}
for keyword in ["dependentSchemas", "dependencies"] {
if let Some(dependent_schemas) = schema.get(keyword).and_then(Value::as_object) {
for (trigger, dependent_schema) in dependent_schemas {
if !consume_validation_work(context, path, errors) {
return;
}
if !dependent_schema.is_array()
&& obj.contains_key(trigger)
&& branch_is_valid(dependent_schema, value, path, context)
&& let Some(dependent_schema) = dependent_schema.as_object()
{
mark_evaluated_object_properties(
dependent_schema,
value,
obj,
path,
true,
evaluated,
errors,
context,
);
}
}
}
}
mark_composition_evaluated_properties(
schema, "allOf", value, obj, path, evaluated, errors, context,
);
mark_composition_evaluated_properties(
schema, "anyOf", value, obj, path, evaluated, errors, context,
);
if let Some(subschemas) = bounded_subschemas(schema, "oneOf", path, errors) {
let matching: Vec<_> = subschemas
.iter()
.filter(|subschema| branch_is_valid(subschema, value, path, context))
.collect();
if matching.len() == 1
&& let Some(subschema) = matching[0].as_object()
{
mark_evaluated_object_properties(
subschema, value, obj, path, true, evaluated, errors, context,
);
}
}
if let Some(condition) = schema.get("if") {
let condition_matched = branch_is_valid(condition, value, path, context);
if condition_matched && let Some(condition) = condition.as_object() {
mark_evaluated_object_properties(
condition, value, obj, path, true, evaluated, errors, context,
);
}
let branch = if condition_matched { "then" } else { "else" };
if let Some(subschema) = schema.get(branch)
&& branch_is_valid(subschema, value, path, context)
&& let Some(subschema) = subschema.as_object()
{
mark_evaluated_object_properties(
subschema, value, obj, path, true, evaluated, errors, context,
);
}
}
}
fn mark_composition_evaluated_properties<'a>(
schema: &'a serde_json::Map<String, Value>,
keyword: &str,
value: &Value,
obj: &serde_json::Map<String, Value>,
path: &str,
evaluated: &mut std::collections::HashSet<String>,
errors: &mut Vec<ValidationError>,
context: &mut ValidationContext<'a>,
) {
let Some(subschemas) = bounded_subschemas(schema, keyword, path, errors) else {
return;
};
for subschema in subschemas {
if branch_is_valid(subschema, value, path, context)
&& let Some(subschema) = subschema.as_object()
{
mark_evaluated_object_properties(
subschema, value, obj, path, true, evaluated, errors, context,
);
}
}
}
fn compile_pattern_properties<'a>(
schema: &'a serde_json::Map<String, Value>,
path: &str,
errors: &mut Vec<ValidationError>,
context: &mut ValidationContext<'_>,
) -> Vec<(Regex, &'a Value)> {
let Some(pattern_properties) = schema.get("patternProperties").and_then(Value::as_object)
else {
return Vec::new();
};
if pattern_properties.len() > MAX_PATTERN_PROPERTIES {
push_error(errors, path, "patternProperties exceeds entry limit");
return Vec::new();
}
let mut patterns = Vec::with_capacity(pattern_properties.len());
for (source, pattern_schema) in pattern_properties {
if !consume_validation_work(context, path, errors) {
break;
}
if source.len() > MAX_PATTERN_PROPERTY_BYTES {
push_error(errors, path, "patternProperties pattern exceeds byte limit");
continue;
}
match compile_schema_pattern(source) {
Ok(pattern) => patterns.push((pattern, pattern_schema)),
Err(_) => push_error(errors, path, "invalid patternProperties pattern"),
}
}
patterns
}
fn validate_dependencies<'a>(
schema: &'a serde_json::Map<String, Value>,
value: &Value,
obj: &serde_json::Map<String, Value>,
path: &str,
errors: &mut Vec<ValidationError>,
context: &mut ValidationContext<'a>,
) {
for keyword in ["dependentRequired", "dependentSchemas", "dependencies"] {
let Some(dependencies) = schema.get(keyword).and_then(Value::as_object) else {
continue;
};
for (trigger, dependency) in dependencies {
if !consume_validation_work(context, path, errors) {
return;
}
if !obj.contains_key(trigger) {
continue;
}
if let Some(required) = dependency
.as_array()
.filter(|_| keyword != "dependentSchemas")
{
for required_property in required {
if !consume_validation_work(context, path, errors) {
return;
}
if let Some(required_property) = required_property.as_str() {
if !obj.contains_key(required_property) {
push_error(
errors,
&diagnostic_child_path(path, required_property),
if keyword == "dependencies" {
"missing dependency property"
} else {
"missing dependentRequired property"
},
);
}
}
}
} else if keyword != "dependentRequired" {
validate_internal(dependency, value, path, errors, context);
}
}
}
}
fn validate_array<'a>(
schema: &'a serde_json::Map<String, Value>,
value: &Value,
arr: &[Value],
path: &str,
errors: &mut Vec<ValidationError>,
context: &mut ValidationContext<'a>,
) {
let mut prefix_len = 0;
if let Some(prefix_items) = schema.get("prefixItems").and_then(|v| v.as_array()) {
prefix_len = prefix_items.len();
for (i, item_schema) in prefix_items.iter().enumerate() {
if let Some(item) = arr.get(i) {
let item_path = format!("{path}[{i}]");
validate_internal(item_schema, item, &item_path, errors, context);
}
}
}
if let Some(items_schema) = schema.get("items") {
if items_schema.is_array() && prefix_len == 0 {
if let Some(items_arr) = items_schema.as_array() {
for (i, item_schema) in items_arr.iter().enumerate() {
if let Some(item) = arr.get(i) {
let item_path = format!("{path}[{i}]");
validate_internal(item_schema, item, &item_path, errors, context);
}
}
if let Some(additional) = schema.get("additionalItems") {
for (index, item) in arr.iter().enumerate().skip(items_arr.len()) {
let item_path = format!("{path}[{index}]");
validate_internal(additional, item, &item_path, errors, context);
}
}
}
} else if items_schema.is_object() || items_schema.is_boolean() {
for (i, item) in arr.iter().enumerate().skip(prefix_len) {
let item_path = format!("{path}[{i}]");
validate_internal(items_schema, item, &item_path, errors, context);
}
}
}
if let Some(min) = schema.get("minItems")
&& count_compare_to_schema_bound(arr.len(), min, context.enforce_unevaluated_properties)
== Some(Ordering::Less)
{
push_error(errors, path, "array has fewer items than minItems");
}
if let Some(max) = schema.get("maxItems")
&& count_compare_to_schema_bound(arr.len(), max, context.enforce_unevaluated_properties)
== Some(Ordering::Greater)
{
push_error(errors, path, "array has more items than maxItems");
}
if schema
.get("uniqueItems")
.and_then(serde_json::Value::as_bool)
.unwrap_or(false)
{
if context.enforce_unevaluated_properties && arr.len() > unique_items::PAIRWISE_LIMIT {
if !unique_items::validate(arr, path, errors, context) {
return;
}
} else if context.enforce_unevaluated_properties {
for (index, item) in arr.iter().enumerate() {
for previous in &arr[..index] {
if !consume_validation_work(context, path, errors) {
return;
}
let Some(equal) =
json_schema_equal_with_work(previous, item, path, errors, context)
else {
return;
};
if equal {
push_error(
errors,
&format!("{path}[{index}]"),
"duplicate item in array",
);
break;
}
}
}
} else {
let mut seen = std::collections::HashSet::with_capacity(arr.len());
for (index, item) in arr.iter().enumerate() {
if !charge_large_string_tree(item, path, errors, context) {
return;
}
let key = serde_json::to_string(item).unwrap_or_default();
if !seen.insert(key) {
push_error(
errors,
&format!("{path}[{index}]"),
"duplicate item in array",
);
}
}
}
}
if let Some(contains) = schema.get("contains") {
let mut matches = 0;
for item in arr {
if branch_is_valid(contains, item, path, context) {
matches += 1;
}
}
let below_minimum = if context.enforce_unevaluated_properties {
schema.get("minContains").map_or(matches == 0, |minimum| {
count_compare_to_schema_bound(matches, minimum, true) == Some(Ordering::Less)
})
} else {
let minimum = schema
.get("minContains")
.and_then(Value::as_u64)
.unwrap_or(1);
(matches as u64) < minimum
};
if below_minimum {
push_error(
errors,
path,
"array has fewer matching items than minContains",
);
}
if let Some(maximum) = schema.get("maxContains")
&& count_compare_to_schema_bound(
matches,
maximum,
context.enforce_unevaluated_properties,
) == Some(Ordering::Greater)
{
push_error(
errors,
path,
"array has more matching items than maxContains",
);
}
}
if context.enforce_unevaluated_properties {
validate_unevaluated_items(schema, value, arr, path, errors, context);
}
}
fn validate_unevaluated_items<'a>(
schema: &'a serde_json::Map<String, Value>,
value: &Value,
arr: &[Value],
path: &str,
errors: &mut Vec<ValidationError>,
context: &mut ValidationContext<'a>,
) {
let Some(unevaluated_schema) = schema.get("unevaluatedItems") else {
return;
};
let mut evaluated = HashSet::with_capacity(arr.len());
mark_evaluated_array_items(
schema,
value,
arr,
path,
false,
&mut evaluated,
errors,
context,
);
for (index, item) in arr.iter().enumerate() {
if !consume_validation_work(context, path, errors) {
return;
}
if !evaluated.contains(&index) {
validate_internal(
unevaluated_schema,
item,
&format!("{path}[{index}]"),
errors,
context,
);
}
}
}
fn mark_evaluated_array_items<'a>(
schema: &'a serde_json::Map<String, Value>,
value: &Value,
arr: &[Value],
path: &str,
include_unevaluated_items: bool,
evaluated: &mut HashSet<usize>,
errors: &mut Vec<ValidationError>,
context: &mut ValidationContext<'a>,
) {
context.push_dynamic_scope(schema);
mark_evaluated_array_items_inner(
schema,
value,
arr,
path,
include_unevaluated_items,
evaluated,
errors,
context,
);
context.pop_dynamic_scope();
}
fn mark_evaluated_array_items_inner<'a>(
schema: &'a serde_json::Map<String, Value>,
value: &Value,
arr: &[Value],
path: &str,
include_unevaluated_items: bool,
evaluated: &mut HashSet<usize>,
errors: &mut Vec<ValidationError>,
context: &mut ValidationContext<'a>,
) {
if !consume_validation_work(context, path, errors) {
return;
}
if let Some(prefix_items) = schema.get("prefixItems").and_then(Value::as_array) {
for (index, item_schema) in prefix_items.iter().enumerate() {
let Some(item) = arr.get(index) else {
break;
};
if !consume_validation_work(context, path, errors) {
return;
}
if branch_is_valid(item_schema, item, &format!("{path}[{index}]"), context) {
evaluated.insert(index);
}
}
}
let prefix_len = schema
.get("prefixItems")
.and_then(Value::as_array)
.map_or(0, Vec::len);
if let Some(items_schema) = schema.get("items") {
for (index, item) in arr.iter().enumerate().skip(prefix_len) {
if !consume_validation_work(context, path, errors) {
return;
}
if branch_is_valid(items_schema, item, &format!("{path}[{index}]"), context) {
evaluated.insert(index);
}
}
}
if let Some(contains_schema) = schema.get("contains") {
let matches: Vec<usize> = arr
.iter()
.enumerate()
.filter_map(|(index, item)| {
consume_validation_work(context, path, errors)
.then(|| {
branch_is_valid(contains_schema, item, &format!("{path}[{index}]"), context)
})
.filter(|matches| *matches)
.map(|_| index)
})
.collect();
let meets_minimum = schema
.get("minContains")
.map_or(matches.len() >= 1, |minimum| {
count_compare_to_schema_bound(matches.len(), minimum, true) != Some(Ordering::Less)
});
let within_maximum = schema.get("maxContains").is_none_or(|maximum| {
count_compare_to_schema_bound(matches.len(), maximum, true) != Some(Ordering::Greater)
});
if meets_minimum && within_maximum {
evaluated.extend(matches);
}
}
if include_unevaluated_items && schema.contains_key("unevaluatedItems") {
for index in 0..arr.len() {
if !consume_validation_work(context, path, errors) {
return;
}
evaluated.insert(index);
}
}
if let Some(reference) = schema.get("$ref").and_then(Value::as_str) {
mark_reference_evaluated_array_items(
schema, reference, value, arr, path, evaluated, errors, context,
);
}
if let Some(reference) = schema.get("$dynamicRef").and_then(Value::as_str) {
mark_dynamic_reference_evaluated_array_items(
schema, reference, value, arr, path, evaluated, errors, context,
);
}
mark_composition_evaluated_array_items(
schema, "allOf", value, arr, path, evaluated, errors, context,
);
mark_composition_evaluated_array_items(
schema, "anyOf", value, arr, path, evaluated, errors, context,
);
if let Some(subschemas) = bounded_subschemas(schema, "oneOf", path, errors) {
let matching: Vec<_> = subschemas
.iter()
.filter(|subschema| branch_is_valid(subschema, value, path, context))
.collect();
if matching.len() == 1
&& let Some(subschema) = matching[0].as_object()
{
mark_evaluated_array_items(
subschema, value, arr, path, true, evaluated, errors, context,
);
}
}
if let Some(condition) = schema.get("if") {
let condition_matched = branch_is_valid(condition, value, path, context);
if condition_matched && let Some(condition) = condition.as_object() {
mark_evaluated_array_items(
condition, value, arr, path, true, evaluated, errors, context,
);
}
let branch = if condition_matched { "then" } else { "else" };
if let Some(subschema) = schema.get(branch)
&& branch_is_valid(subschema, value, path, context)
&& let Some(subschema) = subschema.as_object()
{
mark_evaluated_array_items(
subschema, value, arr, path, true, evaluated, errors, context,
);
}
}
}
fn mark_reference_evaluated_array_items<'a>(
schema: &'a serde_json::Map<String, Value>,
reference: &str,
value: &Value,
arr: &[Value],
path: &str,
evaluated: &mut HashSet<usize>,
errors: &mut Vec<ValidationError>,
context: &mut ValidationContext<'a>,
) {
if !context.enter_reference() {
push_error(errors, path, "local schema reference depth limit exceeded");
return;
}
let root_schema = context.root_schema;
let target = resolve_local_reference_with_work(root_schema, schema, reference, context).ok();
if let Some(target) = target
&& branch_is_valid(target, value, path, context)
&& let Some(target) = target.as_object()
{
mark_evaluated_array_items(target, value, arr, path, true, evaluated, errors, context);
}
context.leave_reference();
}
fn mark_dynamic_reference_evaluated_array_items<'a>(
schema: &'a serde_json::Map<String, Value>,
reference: &str,
value: &Value,
arr: &[Value],
path: &str,
evaluated: &mut HashSet<usize>,
errors: &mut Vec<ValidationError>,
context: &mut ValidationContext<'a>,
) {
if !context.enter_reference() {
push_error(errors, path, "local schema reference depth limit exceeded");
return;
}
let root_schema = context.root_schema;
match resolve_dynamic_reference_with_work(root_schema, schema, reference, context) {
Ok(target) if branch_is_valid(target, value, path, context) => {
if let Some(target) = target.as_object() {
mark_evaluated_array_items(
target, value, arr, path, true, evaluated, errors, context,
);
}
}
Ok(_) => {}
Err(message) => push_error(errors, path, message),
}
context.leave_reference();
}
fn mark_composition_evaluated_array_items<'a>(
schema: &'a serde_json::Map<String, Value>,
keyword: &str,
value: &Value,
arr: &[Value],
path: &str,
evaluated: &mut HashSet<usize>,
errors: &mut Vec<ValidationError>,
context: &mut ValidationContext<'a>,
) {
let Some(subschemas) = bounded_subschemas(schema, keyword, path, errors) else {
return;
};
for subschema in subschemas {
if branch_is_valid(subschema, value, path, context)
&& let Some(subschema) = subschema.as_object()
{
mark_evaluated_array_items(
subschema, value, arr, path, true, evaluated, errors, context,
);
}
}
}
fn validate_string(
schema: &serde_json::Map<String, Value>,
s: &str,
path: &str,
errors: &mut Vec<ValidationError>,
context: &mut ValidationContext<'_>,
) {
if schema.contains_key("minLength") || schema.contains_key("maxLength") {
if !consume_required_work_units(context, additional_string_work(s.len()), path, errors) {
return;
}
let len = s.chars().count();
if let Some(min) = schema.get("minLength")
&& count_compare_to_schema_bound(len, min, context.enforce_unevaluated_properties)
== Some(Ordering::Less)
{
push_error(errors, path, "string has fewer characters than minLength");
}
if let Some(max) = schema.get("maxLength")
&& count_compare_to_schema_bound(len, max, context.enforce_unevaluated_properties)
== Some(Ordering::Greater)
{
push_error(errors, path, "string has more characters than maxLength");
}
}
if let Some(pattern) = schema.get("pattern").and_then(serde_json::Value::as_str) {
if !consume_validation_work(context, path, errors) {
return;
}
if pattern.len() > MAX_PATTERN_BYTES {
push_error(errors, path, "pattern exceeds byte limit");
return;
}
match compile_schema_pattern(pattern) {
Ok(re) => {
let Some(matches) = charged_regex_is_match(&re, s, path, errors, context) else {
return;
};
if !matches {
push_error(errors, path, "string does not match pattern");
}
}
Err(_) => {
push_error(errors, path, "invalid schema pattern");
}
}
}
}
fn is_valid_uri_scheme(scheme: &str) -> bool {
let bytes = scheme.as_bytes();
bytes.first().is_some_and(u8::is_ascii_alphabetic)
&& bytes
.iter()
.skip(1)
.all(|byte| byte.is_ascii_alphanumeric() || matches!(*byte, b'+' | b'-' | b'.'))
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct ExactDecimal {
negative: bool,
digits: String,
exponent: i64,
}
impl ExactDecimal {
fn from_value(value: &Value) -> Option<Self> {
value.as_number().and_then(Self::from_number)
}
fn from_number(number: &serde_json::Number) -> Option<Self> {
Self::parse(number.as_str())
}
fn parse(source: &str) -> Option<Self> {
if source.is_empty() || source.len() > MAX_EXACT_DECIMAL_DIGITS {
return None;
}
let (negative, unsigned) = match source.as_bytes().first() {
Some(b'-') => (true, &source[1..]),
_ => (false, source),
};
let (significand, exponent) = match unsigned.split_once(['e', 'E']) {
Some((significand, exponent)) => {
let exponent = exponent.parse::<i64>().ok()?;
if exponent.unsigned_abs() > MAX_EXACT_DECIMAL_DIGITS as u64 {
return None;
}
(significand, exponent)
}
None => (unsigned, 0),
};
let (whole, fraction) = match significand.split_once('.') {
Some((whole, fraction)) => (whole, fraction),
None => (significand, ""),
};
if whole.is_empty()
|| !whole.bytes().all(|byte| byte.is_ascii_digit())
|| !fraction.bytes().all(|byte| byte.is_ascii_digit())
{
return None;
}
let coefficient = format!("{whole}{fraction}");
let significant = coefficient.trim_start_matches('0');
if significant.is_empty() {
return Some(Self {
negative: false,
digits: "0".to_owned(),
exponent: 0,
});
}
if significant.len() > MAX_EXACT_DECIMAL_DIGITS {
return None;
}
let exponent = exponent.checked_sub(i64::try_from(fraction.len()).ok()?)?;
if exponent.unsigned_abs() > MAX_EXACT_DECIMAL_DIGITS as u64 {
return None;
}
Some(Self {
negative,
digits: significant.to_owned(),
exponent,
})
}
fn is_zero(&self) -> bool {
self.digits.as_bytes()[0] == b'0'
}
fn is_positive(&self) -> bool {
!self.negative && !self.is_zero()
}
fn is_integer(&self) -> bool {
self.exponent >= 0
|| self
.digits
.bytes()
.rev()
.take(self.exponent.unsigned_abs() as usize)
.all(|digit| digit == b'0')
}
fn compare(&self, other: &Self) -> Ordering {
match (self.negative, other.negative) {
(true, false) => return Ordering::Less,
(false, true) => return Ordering::Greater,
_ => {}
}
let magnitude = self.compare_magnitude(other);
if self.negative {
magnitude.reverse()
} else {
magnitude
}
}
fn compare_magnitude(&self, other: &Self) -> Ordering {
match (self.is_zero(), other.is_zero()) {
(true, true) => return Ordering::Equal,
(true, false) => return Ordering::Less,
(false, true) => return Ordering::Greater,
(false, false) => {}
}
let self_position = self.exponent + self.digits.len() as i64;
let other_position = other.exponent + other.digits.len() as i64;
match self_position.cmp(&other_position) {
Ordering::Equal => compare_digit_strings(&self.digits, &other.digits),
order => order,
}
}
fn is_multiple_of_bounded(
&self,
divisor: &Self,
path: &str,
errors: &mut Vec<ValidationError>,
context: &mut ValidationContext<'_>,
) -> Option<bool> {
if divisor.is_zero() {
return Some(false);
}
if self.is_zero() {
return Some(true);
}
let scale = self.exponent.min(divisor.exponent).min(0).unsigned_abs() as usize;
let dividend_zeros = usize::try_from(self.exponent + scale as i64).ok();
let divisor_zeros = usize::try_from(divisor.exponent + scale as i64).ok();
let (Some(dividend_zeros), Some(divisor_zeros)) = (dividend_zeros, divisor_zeros) else {
return Some(false);
};
if !consume_validation_work_units(
context,
dividend_zeros.saturating_add(divisor_zeros),
path,
errors,
) {
return None;
}
let mut dividend = self.digits.clone();
dividend.extend(std::iter::repeat_n('0', dividend_zeros));
let mut divisor = divisor.digits.clone();
divisor.extend(std::iter::repeat_n('0', divisor_zeros));
decimal_integer_is_divisible(÷nd, &divisor, path, errors, context)
}
}
fn count_compare_to_schema_bound(
count: usize,
bound: &Value,
admitted_final: bool,
) -> Option<Ordering> {
if !admitted_final {
return bound.as_u64().map(|bound| (count as u64).cmp(&bound));
}
let count = ExactDecimal::parse(&count.to_string())?;
let bound = ExactDecimal::from_value(bound)?;
Some(count.compare(&bound))
}
fn compare_digit_strings(left: &str, right: &str) -> Ordering {
let shared_length = left.len().max(right.len());
for index in 0..shared_length {
let left_digit = left.as_bytes().get(index).copied().unwrap_or(b'0');
let right_digit = right.as_bytes().get(index).copied().unwrap_or(b'0');
match left_digit.cmp(&right_digit) {
Ordering::Equal => {}
order => return order,
}
}
Ordering::Equal
}
fn decimal_integer_is_divisible(
dividend: &str,
divisor: &str,
path: &str,
errors: &mut Vec<ValidationError>,
context: &mut ValidationContext<'_>,
) -> Option<bool> {
let divisor = divisor.trim_start_matches('0');
if divisor.is_empty() {
return Some(false);
}
let mut remainder = String::new();
for digit in dividend.bytes() {
if !consume_validation_work(context, path, errors) {
return None;
}
if digit != b'0' || !remainder.is_empty() {
remainder.push(char::from(digit));
}
loop {
if !consume_validation_work_units(
context,
remainder.len().min(divisor.len()),
path,
errors,
) {
return None;
}
if compare_decimal_integers(&remainder, divisor) == Ordering::Less {
break;
}
if !consume_validation_work_units(context, remainder.len(), path, errors) {
return None;
}
subtract_decimal_integers(&mut remainder, divisor);
if !consume_validation_work_units(context, remainder.len(), path, errors) {
return None;
}
trim_decimal_integer(&mut remainder);
}
}
Some(remainder.is_empty() || remainder == "0")
}
fn consume_validation_work_units(
context: &mut ValidationContext<'_>,
units: usize,
path: &str,
errors: &mut Vec<ValidationError>,
) -> bool {
(0..units).all(|_| consume_validation_work(context, path, errors))
}
fn compare_decimal_integers(left: &str, right: &str) -> Ordering {
match left.len().cmp(&right.len()) {
Ordering::Equal => left.cmp(right),
order => order,
}
}
fn subtract_decimal_integers(left: &mut String, right: &str) {
let mut digits = left.bytes().collect::<Vec<_>>();
let right = right.as_bytes();
let mut borrow = 0_i16;
for offset in 0..digits.len() {
let left_index = digits.len() - 1 - offset;
let right_digit = right
.len()
.checked_sub(offset + 1)
.and_then(|index| right.get(index))
.map_or(0, |digit| i16::from(*digit - b'0'));
let mut digit = i16::from(digits[left_index] - b'0') - right_digit - borrow;
if digit < 0 {
digit += 10;
borrow = 1;
} else {
borrow = 0;
}
digits[left_index] = digit as u8 + b'0';
}
*left = digits.into_iter().map(char::from).collect();
}
fn trim_decimal_integer(value: &mut String) {
let first_nonzero = value.bytes().position(|digit| digit != b'0');
match first_nonzero {
Some(index) if index > 0 => {
let _ = value.drain(..index);
}
None => value.clear(),
_ => {}
}
}
fn json_schema_equal_with_work(
left: &Value,
right: &Value,
path: &str,
errors: &mut Vec<ValidationError>,
context: &mut ValidationContext<'_>,
) -> Option<bool> {
if !consume_validation_work(context, path, errors) {
return None;
}
match (left, right) {
(Value::Number(left), Value::Number(right)) if context.enforce_unevaluated_properties => {
Some(
ExactDecimal::from_number(left)
.zip(ExactDecimal::from_number(right))
.is_some_and(|(left, right)| left.compare(&right) == Ordering::Equal),
)
}
(Value::Number(left), Value::Number(right)) => {
let bytes = left.as_str().len();
if bytes != right.as_str().len() {
return Some(false);
}
consume_required_work_units(context, additional_string_work(bytes), path, errors)
.then(|| left == right)
}
(Value::String(left), Value::String(right)) => {
if left.len() != right.len() {
return Some(false);
}
consume_required_work_units(context, additional_string_work(left.len()), path, errors)
.then(|| left == right)
}
(Value::Array(left), Value::Array(right)) => {
if left.len() != right.len() {
return Some(false);
}
for (left, right) in left.iter().zip(right) {
if !json_schema_equal_with_work(left, right, path, errors, context)? {
return Some(false);
}
}
Some(true)
}
(Value::Object(left), Value::Object(right)) => {
if left.len() != right.len() {
return Some(false);
}
for (key, left) in left {
let Some(right) = right.get(key) else {
return Some(false);
};
if !json_schema_equal_with_work(left, right, path, errors, context)? {
return Some(false);
}
}
Some(true)
}
_ => Some(left == right),
}
}
fn charge_large_string_tree(
value: &Value,
path: &str,
errors: &mut Vec<ValidationError>,
context: &mut ValidationContext<'_>,
) -> bool {
match value {
Value::String(value) => {
consume_required_work_units(context, additional_string_work(value.len()), path, errors)
}
Value::Array(values) => values
.iter()
.all(|value| charge_large_string_tree(value, path, errors, context)),
Value::Object(values) => values
.values()
.all(|value| charge_large_string_tree(value, path, errors, context)),
Value::Number(value) => consume_required_work_units(
context,
additional_string_work(value.as_str().len()),
path,
errors,
),
Value::Null | Value::Bool(_) => true,
}
}
fn validate_number(
schema: &serde_json::Map<String, Value>,
n: &serde_json::Number,
path: &str,
errors: &mut Vec<ValidationError>,
final_semantics: bool,
context: &mut ValidationContext<'_>,
) {
if final_semantics {
validate_exact_number(schema, n, path, errors, context);
return;
}
let mut operand_work = additional_string_work(n.as_str().len());
for keyword in [
"minimum",
"maximum",
"exclusiveMinimum",
"exclusiveMaximum",
"multipleOf",
] {
if let Some(bound) = schema.get(keyword).and_then(Value::as_number) {
operand_work =
operand_work.saturating_add(additional_string_work(bound.as_str().len()));
}
}
if !consume_required_work_units(context, operand_work, path, errors) {
return;
}
let val = n.as_f64().unwrap_or(0.0);
if let Some(min) = schema.get("minimum").and_then(serde_json::Value::as_f64) {
if val < min {
push_error(errors, path, "value is below minimum");
}
}
if let Some(max) = schema.get("maximum").and_then(serde_json::Value::as_f64) {
if val > max {
push_error(errors, path, "value is above maximum");
}
}
if let Some(min) = schema
.get("exclusiveMinimum")
.and_then(serde_json::Value::as_f64)
{
if val <= min {
push_error(errors, path, "value does not satisfy exclusiveMinimum");
}
}
if let Some(max) = schema
.get("exclusiveMaximum")
.and_then(serde_json::Value::as_f64)
{
if val >= max {
push_error(errors, path, "value does not satisfy exclusiveMaximum");
}
}
if let Some(multiple) = schema.get("multipleOf").and_then(serde_json::Value::as_f64) {
if multiple != 0.0 && (val % multiple).abs() > f64::EPSILON {
push_error(errors, path, "value is not a multipleOf the schema divisor");
}
}
}
fn validate_exact_number(
schema: &serde_json::Map<String, Value>,
number: &serde_json::Number,
path: &str,
errors: &mut Vec<ValidationError>,
context: &mut ValidationContext<'_>,
) {
let Some(value) = ExactDecimal::from_number(number) else {
push_error(
errors,
path,
"instance number exceeds exact comparison bound",
);
return;
};
for (keyword, message) in [
("minimum", "value is below minimum"),
("maximum", "value is above maximum"),
(
"exclusiveMinimum",
"value does not satisfy exclusiveMinimum",
),
(
"exclusiveMaximum",
"value does not satisfy exclusiveMaximum",
),
] {
let Some(bound_value) = schema.get(keyword) else {
continue;
};
let Some(bound) = ExactDecimal::from_value(bound_value) else {
push_error(
errors,
path,
"schema numeric keyword must be a bounded exact number",
);
continue;
};
let comparison = value.compare(&bound);
let invalid = match keyword {
"minimum" => comparison == Ordering::Less,
"maximum" => comparison == Ordering::Greater,
"exclusiveMinimum" => comparison != Ordering::Greater,
"exclusiveMaximum" => comparison != Ordering::Less,
_ => unreachable!("the numeric keyword set is fixed"),
};
if invalid {
push_error(errors, path, message);
}
}
if let Some(multiple) = schema.get("multipleOf").and_then(ExactDecimal::from_value) {
if let Some(false) = value.is_multiple_of_bounded(&multiple, path, errors, context) {
push_error(
errors,
path,
"value must be a multiple of the exact schema divisor",
);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
struct GeneratedText;
impl JsonSchemaType for GeneratedText {
fn schema_body(_context: &mut SchemaGenerator) -> Value {
json!({"type": "string"})
}
}
struct GeneratedPair;
impl JsonSchemaType for GeneratedPair {
fn schema_body(context: &mut SchemaGenerator) -> Value {
json!({
"type": "object",
"properties": {
"left": context.subschema_for::<GeneratedText>(),
"right": context.subschema_for::<GeneratedText>()
},
"required": ["left", "right"]
})
}
}
struct GeneratedNode;
impl JsonSchemaType for GeneratedNode {
fn schema_body(context: &mut SchemaGenerator) -> Value {
json!({
"type": "object",
"properties": {
"value": {"type": "integer"},
"next": {"anyOf": [{"type": "null"}, context.subschema_for::<Self>()]}
},
"required": ["value", "next"]
})
}
}
fn generate_test_schema<T: JsonSchemaType>(
limits: SchemaGenerationLimits,
) -> Result<Value, SchemaGenerationError> {
let mut context = SchemaGenerator::with_limits(limits);
let root = context.subschema_for::<T>();
context.finish(root)
}
fn assert_builtin_validation<T: JsonSchemaType>(accepted: &[Value], rejected: &[Value]) {
let schema = generate_test_schema::<T>(SchemaGenerationLimits::default())
.expect("built-in types generate a complete schema");
let admitted = admit_final_schema(schema).expect("built-in schemas admit");
for value in accepted {
assert!(
admitted.validate(value).is_ok(),
"{} must accept {value}",
std::any::type_name::<T>(),
);
}
for value in rejected {
assert!(
admitted.validate(value).is_err(),
"{} must reject {value}",
std::any::type_name::<T>(),
);
}
}
#[test]
fn schema_generation_builtin_scalars_enforce_json_representations() {
assert_builtin_validation::<String>(&[json!(""), json!("hello")], &[json!(0), json!(null)]);
assert_builtin_validation::<char>(
&[json!('a'), json!('🦀')],
&[json!(""), json!("ab"), json!("e\u{301}"), json!(null)],
);
assert_builtin_validation::<bool>(&[json!(true), json!(false)], &[json!(0), json!("true")]);
assert_builtin_validation::<()>(&[json!(())], &[json!([]), json!({}), json!(false)]);
assert_builtin_validation::<f32>(
&[json!(0.0_f32), json!(-1.5_f32), json!(f32::MAX)],
&[json!("1.5"), json!(null), json!(false)],
);
assert_builtin_validation::<f64>(
&[json!(0.0_f64), json!(-1.5_f64), json!(f64::MAX)],
&[json!("1.5"), json!(null), json!(false)],
);
assert_builtin_validation::<Value>(
&[
json!(null),
json!(true),
json!(12),
json!("text"),
json!([]),
json!({}),
],
&[],
);
}
#[test]
fn schema_generation_builtin_integers_keep_interoperable_bounds() {
macro_rules! check {
($ty:ty, $below:expr, $above:expr, $minimum:expr, $maximum:expr) => {{
let schema = generate_test_schema::<$ty>(SchemaGenerationLimits::default())
.expect("integer schemas generate");
assert_eq!(schema.get("minimum").is_some(), $minimum);
assert_eq!(schema.get("maximum").is_some(), $maximum);
let mut accepted = vec![json!(<$ty>::MIN), json!(<$ty>::MAX), json!(0)];
let mut rejected = vec![json!(1.5), json!("0")];
for (value, constrained) in [
(
serde_json::from_str($below).expect("exact lower neighbor"),
$minimum,
),
(
serde_json::from_str($above).expect("exact upper neighbor"),
$maximum,
),
] {
if constrained {
rejected.push(value);
} else {
accepted.push(value);
}
}
assert_builtin_validation::<$ty>(&accepted, &rejected);
}};
}
check!(i8, "-129", "128", true, true);
check!(i16, "-32769", "32768", true, true);
check!(i32, "-2147483649", "2147483648", true, true);
check!(
i64,
"-9223372036854775809",
"9223372036854775808",
false,
false
);
check!(
i128,
"-170141183460469231731687303715884105729",
"170141183460469231731687303715884105728",
false,
false
);
check!(
isize,
&(isize::MIN as i128 - 1).to_string(),
&(isize::MAX as i128 + 1).to_string(),
isize::BITS <= 32,
isize::BITS <= 32
);
check!(u8, "-1", "256", true, true);
check!(u16, "-1", "65536", true, true);
check!(u32, "-1", "4294967296", true, true);
check!(u64, "-1", "18446744073709551616", true, false);
check!(
u128,
"-1",
"340282366920938463463374607431768211456",
true,
false
);
check!(
usize,
"-1",
&(usize::MAX as u128 + 1).to_string(),
true,
usize::BITS <= 32
);
}
#[test]
fn schema_generation_builtin_collections_preserve_item_and_length_constraints() {
assert_builtin_validation::<Vec<u16>>(
&[json!([]), json!([0, 65535])],
&[json!([65536]), json!([null]), json!({})],
);
assert_builtin_validation::<[bool; 2]>(
&[json!([true, false])],
&[json!([true]), json!([true, false, true]), json!([true, 0])],
);
assert_builtin_validation::<[u8; 0]>(&[json!([])], &[json!([0])]);
assert_builtin_validation::<BTreeSet<u8>>(
&[json!([]), json!([0, 255])],
&[json!([0, 0]), json!([256]), json!(["0"])],
);
assert_builtin_validation::<HashSet<String>>(
&[json!([]), json!(["a", "b"])],
&[json!(["a", "a"]), json!([1]), json!({})],
);
type CustomHasher = std::hash::BuildHasherDefault<std::hash::DefaultHasher>;
assert_builtin_validation::<HashSet<u8, CustomHasher>>(
&[json!([1, 2])],
&[json!([1, 1]), json!([256])],
);
assert_builtin_validation::<BTreeMap<String, Vec<u8>>>(
&[json!({}), json!({"first": [0, 255], "empty": []})],
&[json!({"first": [256]}), json!({"first": "bad"}), json!([])],
);
assert_builtin_validation::<HashMap<String, Option<u16>, CustomHasher>>(
&[json!({}), json!({"first": 65535, "second": null})],
&[json!({"first": 65536}), json!({"first": false}), json!([])],
);
}
#[test]
fn schema_generation_builtin_optional_and_pointer_payloads_keep_constraints() {
struct Choice;
impl JsonSchemaType for Choice {
fn schema_body(_context: &mut SchemaGenerator) -> Value {
json!({"type": "string", "enum": ["allowed"]})
}
}
assert_builtin_validation::<Option<Choice>>(
&[json!("allowed"), json!(null)],
&[json!("denied"), json!(0)],
);
assert_builtin_validation::<Option<()>>(&[json!(null)], &[json!(false)]);
assert_builtin_validation::<Option<Option<String>>>(
&[json!(null), json!("text")],
&[json!(0)],
);
assert_builtin_validation::<Box<Vec<Option<u8>>>>(
&[json!([]), json!([null, 255])],
&[json!([256]), json!([false]), json!(null)],
);
assert_builtin_validation::<Rc<String>>(&[json!("text")], &[json!(false)]);
assert_builtin_validation::<Arc<Option<u8>>>(
&[json!(null), json!(255)],
&[json!(256), json!(false)],
);
}
#[test]
fn schema_generation_builtin_option_preserves_dialect_and_resource_scopes() {
struct RootDialect;
impl JsonSchemaType for RootDialect {
fn schema_body(_context: &mut SchemaGenerator) -> Value {
json!({"$schema": FINAL_JSON_SCHEMA_DIALECT, "const": "allowed"})
}
}
let root = generate_test_schema::<Option<RootDialect>>(SchemaGenerationLimits::default())
.expect("the optional wrapper carries the root dialect");
assert_eq!(root["$schema"], FINAL_JSON_SCHEMA_DIALECT);
assert!(root["anyOf"][0].get("$schema").is_none());
assert_builtin_validation::<Option<RootDialect>>(
&[json!(null), json!("allowed")],
&[json!("denied")],
);
struct LocalResource;
impl JsonSchemaType for LocalResource {
fn schema_body(context: &mut SchemaGenerator) -> Value {
context.inline_schema(json!({
"$id": "https://example.test/optional-choice",
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"$defs": {"choice": {"const": "allowed"}},
"$ref": "#/$defs/choice",
}))
}
}
let root = generate_test_schema::<Option<LocalResource>>(SchemaGenerationLimits::default())
.expect("the payload keeps its local resource");
assert!(root.get("$schema").is_none());
assert_eq!(root["anyOf"][0]["$schema"], FINAL_JSON_SCHEMA_DIALECT);
assert_eq!(
root["anyOf"][0]["$id"],
"https://example.test/optional-choice"
);
assert_builtin_validation::<Option<LocalResource>>(
&[json!(null), json!("allowed")],
&[json!("denied"), json!(false)],
);
}
#[test]
fn schema_generation_builtin_containers_share_recursive_definitions_and_limits() {
struct CollectionNode;
impl JsonSchemaType for CollectionNode {
fn schema_body(context: &mut SchemaGenerator) -> Value {
json!({
"type": "object",
"properties": {
"children": context.subschema_for::<BTreeMap<String, Vec<Box<Self>>>>(),
},
"required": ["children"],
})
}
}
let schema = generate_test_schema::<CollectionNode>(SchemaGenerationLimits::default())
.expect("collection wrappers share recursive type identity");
assert_eq!(
schema["properties"]["children"]["additionalProperties"]["items"]["$ref"],
"#/$defs/type_0",
);
assert_builtin_validation::<CollectionNode>(
&[json!({"children": {"branch": [{"children": {}}]}})],
&[
json!({"children": {"branch": [{"children": []}]}}),
json!({"children": {"branch": [false]}}),
],
);
for (limits, expected) in [
(
SchemaGenerationLimits {
max_types: 3,
..SchemaGenerationLimits::default()
},
SchemaGenerationError::TypeLimit,
),
(
SchemaGenerationLimits {
max_depth: 3,
..SchemaGenerationLimits::default()
},
SchemaGenerationError::DepthLimit,
),
] {
assert_eq!(
generate_test_schema::<CollectionNode>(limits),
Err(expected)
);
}
assert!(generate_test_schema::<CollectionNode>(SchemaGenerationLimits::default()).is_ok());
}
#[test]
fn schema_generation_reuses_only_referenced_types_and_is_deterministic() {
let schema = generate_test_schema::<GeneratedPair>(SchemaGenerationLimits::default())
.expect("repeated type generates a complete schema");
assert_eq!(schema["properties"]["left"], json!({"type": "string"}));
assert_eq!(
schema["properties"]["right"],
json!({"$ref": "#/$defs/type_1"})
);
assert_eq!(schema["$defs"], json!({"type_1": {"type": "string"}}));
assert_eq!(
schema,
generate_test_schema::<GeneratedPair>(SchemaGenerationLimits::default())
.expect("a separate operation has identical output")
);
let admitted = admit_final_schema(schema).expect("generated schema admits");
assert!(
admitted
.validate(&json!({"left": "one", "right": "two"}))
.is_ok()
);
assert!(
admitted
.validate(&json!({"left": "one", "right": 2}))
.is_err()
);
let single = generate_test_schema::<GeneratedText>(SchemaGenerationLimits::default())
.expect("single type generates");
assert_eq!(single, json!({"type": "string"}));
}
#[test]
fn schema_generation_recursive_root_is_complete_and_enforces_nested_types() {
let schema = generate_test_schema::<GeneratedNode>(SchemaGenerationLimits::default())
.expect("recursive root terminates with a definition");
assert_eq!(
schema["properties"]["next"]["anyOf"][1],
json!({"$ref": "#/$defs/type_0"})
);
assert_eq!(
schema["$defs"]["type_0"]["properties"],
schema["properties"]
);
assert!(schema["$defs"]["type_0"].get("$defs").is_none());
let admitted = admit_final_schema(schema).expect("recursive references resolve");
assert!(
admitted
.validate(&json!({"value": 1, "next": {"value": 2, "next": null}}))
.is_ok()
);
assert!(
admitted
.validate(&json!({"value": 1, "next": {"value": "2", "next": null}}))
.is_err()
);
}
#[test]
fn schema_generation_type_and_depth_limits_have_exact_boundaries() {
struct Wrapper;
impl JsonSchemaType for Wrapper {
fn schema_body(context: &mut SchemaGenerator) -> Value {
context.subschema_for::<GeneratedText>()
}
}
let mut limits = SchemaGenerationLimits {
max_types: 2,
max_depth: 2,
..SchemaGenerationLimits::default()
};
assert_eq!(
generate_test_schema::<Wrapper>(limits),
Ok(json!({"type": "string"}))
);
limits.max_types = 1;
assert_eq!(
generate_test_schema::<Wrapper>(limits),
Err(SchemaGenerationError::TypeLimit)
);
limits.max_types = 2;
limits.max_depth = 1;
assert_eq!(
generate_test_schema::<Wrapper>(limits),
Err(SchemaGenerationError::DepthLimit)
);
}
#[test]
fn schema_generation_retained_and_completed_node_byte_budgets_are_enforced() {
let body = json!({"type": "string"});
let limits = SchemaGenerationLimits {
max_nodes: 6,
max_bytes: serde_json::to_vec(&body).expect("serialize fixture").len() * 3,
..SchemaGenerationLimits::default()
};
assert_eq!(generate_test_schema::<GeneratedText>(limits), Ok(body));
assert_eq!(
generate_test_schema::<GeneratedText>(SchemaGenerationLimits {
max_nodes: limits.max_nodes - 1,
..limits
}),
Err(SchemaGenerationError::NodeLimit)
);
assert_eq!(
generate_test_schema::<GeneratedText>(SchemaGenerationLimits {
max_bytes: limits.max_bytes - 1,
..limits
}),
Err(SchemaGenerationError::ByteLimit)
);
}
#[test]
fn schema_generation_counts_escaped_bytes_and_bounds_caller_assembled_roots() {
let root = json!({"const": "\n\"\\\u{0000}"});
let limits = SchemaGenerationLimits {
max_bytes: serde_json::to_vec(&root)
.expect("serialize escaped fixture")
.len(),
..SchemaGenerationLimits::default()
};
assert_eq!(
SchemaGenerator::with_limits(limits).finish(root.clone()),
Ok(root.clone())
);
assert_eq!(
SchemaGenerator::with_limits(SchemaGenerationLimits {
max_bytes: limits.max_bytes - 1,
..limits
})
.finish(root),
Err(SchemaGenerationError::ByteLimit)
);
let root = json!({"allOf": [{}]});
assert!(
SchemaGenerator::with_limits(SchemaGenerationLimits {
max_depth: 3,
..SchemaGenerationLimits::default()
})
.finish(root.clone())
.is_ok()
);
assert_eq!(
SchemaGenerator::with_limits(SchemaGenerationLimits {
max_depth: 2,
..SchemaGenerationLimits::default()
})
.finish(root),
Err(SchemaGenerationError::DepthLimit)
);
}
#[test]
fn schema_generation_autoref_dispatch_prefers_derived_and_preserves_handwritten_types() {
struct Handwritten;
impl Handwritten {
fn json_schema() -> Value {
json!({"type": "boolean"})
}
}
let mut context = SchemaGenerator::new();
let derived = (&SchemaTypeDispatch::<GeneratedText>::new()).schema(&mut context, || {
panic!("derived dispatch must not run the handwritten fallback")
});
let handwritten = (&SchemaTypeDispatch::<Handwritten>::new())
.schema(&mut context, Handwritten::json_schema);
assert_eq!(derived, json!({"type": "string"}));
assert_eq!(handwritten, json!({"type": "boolean"}));
let schema = context
.finish(json!({"anyOf": [derived, handwritten]}))
.expect("mixed providers generate");
let admitted = admit_final_schema(schema).expect("mixed provider schema admits");
assert!(admitted.validate(&json!(true)).is_ok());
assert!(admitted.validate(&json!(1)).is_err());
let mut failed = SchemaGenerator::with_limits(SchemaGenerationLimits {
max_types: 0,
..SchemaGenerationLimits::default()
});
assert_eq!(failed.subschema_for::<GeneratedText>(), Value::Bool(false));
assert_eq!(
(&SchemaTypeDispatch::<Handwritten>::new()).schema(&mut failed, || panic!(
"sticky failure must not invoke another provider"
)),
Value::Bool(false)
);
assert_eq!(
failed.finish(json!({})),
Err(SchemaGenerationError::TypeLimit)
);
}
#[test]
fn schema_generation_trait_only_and_alias_dispatch_share_definitions_and_limits() {
type Bytes = Vec<u8>;
type Count = u8;
type Nodes = Vec<GeneratedNode>;
macro_rules! schema_for {
($ty:ty, $context:expr) => {{
use super::DispatchSchema as _;
#[allow(unused_imports)]
use super::SchemaTypeFallback as _;
(&SchemaTypeDispatch::<$ty>::new()).schema($context, || <$ty>::json_schema())
}};
}
let mut context = SchemaGenerator::new();
let first = schema_for!(GeneratedNode, &mut context);
let second = schema_for!(GeneratedNode, &mut context);
let bytes = schema_for!(Bytes, &mut context);
let repeated_bytes = schema_for!(Bytes, &mut context);
let count = schema_for!(Count, &mut context);
let nodes = schema_for!(Nodes, &mut context);
assert_eq!(second, json!({"$ref": "#/$defs/type_0"}));
assert_eq!(repeated_bytes, json!({"$ref": "#/$defs/type_1"}));
assert_eq!(count, json!({"$ref": "#/$defs/type_2"}));
assert_eq!(nodes["items"], json!({"$ref": "#/$defs/type_0"}));
let schema = context
.finish(json!({
"type": "object",
"properties": {
"first": first,
"second": second,
"bytes": bytes,
"repeated": repeated_bytes,
"count": count,
"nodes": nodes,
},
"required": ["first", "second", "bytes", "repeated", "count", "nodes"],
}))
.expect("all providers share one reference namespace");
assert_eq!(schema["$defs"].as_object().unwrap().len(), 3);
let admitted = admit_final_schema(schema).unwrap();
let valid = json!({
"first": {"value": 1, "next": {"value": 2, "next": null}},
"second": {"value": 3, "next": null},
"bytes": [0, 255],
"repeated": [1],
"count": 255,
"nodes": [{"value": 4, "next": {"value": 5, "next": null}}],
});
admitted.validate(&valid).unwrap();
for (path, wrong) in [
("/first/next/value", json!(false)),
("/second/value", json!(false)),
("/bytes/1", json!(256)),
("/repeated/0", json!(256)),
("/count", json!(256)),
("/nodes/0/next/value", json!(false)),
] {
let mut invalid = valid.clone();
*invalid.pointer_mut(path).unwrap() = wrong;
assert!(admitted.validate(&invalid).is_err(), "{path}");
}
let mut limited = SchemaGenerator::with_limits(SchemaGenerationLimits {
max_types: 0,
..SchemaGenerationLimits::default()
});
let root = schema_for!(Nodes, &mut limited);
assert_eq!(limited.finish(root), Err(SchemaGenerationError::TypeLimit));
assert_eq!(
<GeneratedText as SchemaTypeFallback>::json_schema(),
json!({"type": "string"})
);
}
#[test]
#[deny(unused_imports)]
fn schema_generation_fallback_import_preserves_inherent_provider_precedence() {
struct InherentOnly;
impl InherentOnly {
fn json_schema() -> Value {
json!({"type": "boolean"})
}
}
struct BothProviders;
impl BothProviders {
fn json_schema() -> Value {
panic!("context-aware dispatch must not invoke the inherent fallback")
}
}
impl JsonSchemaType for BothProviders {
fn schema_body(context: &mut SchemaGenerator) -> Value {
context.subschema_for::<u8>()
}
}
let mut context = SchemaGenerator::new();
let handwritten = {
use super::DispatchSchema as _;
#[allow(unused_imports)]
use super::SchemaTypeFallback as _;
(&SchemaTypeDispatch::<InherentOnly>::new())
.schema(&mut context, InherentOnly::json_schema)
};
let context_aware = {
use super::DispatchSchema as _;
#[allow(unused_imports)]
use super::SchemaTypeFallback as _;
(&SchemaTypeDispatch::<BothProviders>::new())
.schema(&mut context, BothProviders::json_schema)
};
let schema = context
.finish(json!({
"type": "object",
"properties": {"manual": handwritten, "both": context_aware},
"required": ["manual", "both"],
}))
.unwrap();
let admitted = admit_final_schema(schema).unwrap();
admitted
.validate(&json!({"manual": true, "both": 255}))
.unwrap();
assert!(
admitted
.validate(&json!({"manual": 1, "both": 255}))
.is_err()
);
assert!(
admitted
.validate(&json!({"manual": true, "both": 256}))
.is_err()
);
}
#[test]
fn schema_generation_preserves_handwritten_definitions_and_rejects_root_collisions() {
let handwritten = json!({"$defs": {"label": {"type": "string"}}, "$ref": "#/$defs/label"});
assert_eq!(
SchemaGenerator::new().finish(handwritten.clone()),
Ok(handwritten)
);
let mut context = SchemaGenerator::new();
let mut root = context.subschema_for::<GeneratedPair>();
root["$defs"] = json!({"label": {"type": "string"}});
let merged = context
.finish(root)
.expect("disjoint handwritten definitions are retained");
assert_eq!(
merged["$defs"],
json!({
"label": {"type": "string"}, "type_1": {"type": "string"}
})
);
let mut context = SchemaGenerator::new();
let mut root = context.subschema_for::<GeneratedPair>();
root["$defs"] = json!({"type_1": {"type": "boolean"}});
assert_eq!(
context.finish(root),
Err(SchemaGenerationError::DefinitionsCollision)
);
assert!(matches!(
SchemaGenerator::new().finish(json!({"$ref": "#/$defs/missing"})),
Err(SchemaGenerationError::InvalidSchema(_))
));
assert_eq!(
SchemaGenerator::new().finish(Value::Bool(false)),
Ok(json!({"allOf": [false]}))
);
}
#[test]
fn schema_generation_does_not_confuse_handwritten_resources_with_generated_references() {
let handwritten = json!({
"type": "object",
"properties": {"choice": {
"$id": "https://example.test/choice",
"$defs": {"type_0": {"type": "string"}},
"$ref": "#/$defs/type_0"
}}
});
assert_eq!(
SchemaGenerator::new().finish(handwritten.clone()),
Ok(handwritten)
);
let mut context = SchemaGenerator::new();
let first = context.subschema_for::<GeneratedText>();
let reused = context.subschema_for::<GeneratedText>();
let root = json!({"type": "object", "properties": {
"first": first,
"reused": {"$id": "https://example.test/nested", "allOf": [reused]}
}});
assert_eq!(
context.finish(root),
Err(SchemaGenerationError::ReferenceResourceBoundary)
);
let manual_resource = json!({
"$id": "https://example.test/manual",
"$defs": {"type_0": {"type": "boolean"}}, "$ref": "#/$defs/type_0"
});
let mut context = SchemaGenerator::new();
let first = context.subschema_for::<GeneratedText>();
let reused = context.subschema_for::<GeneratedText>();
let mut manual = context.inline_schema(manual_resource.clone());
manual["description"] = json!("Documented custom field");
let root = context
.finish(json!({"type": "object", "properties": {
"first": first, "reused": reused, "manual": manual
}}))
.expect("own-resource handwritten type_0 remains distinct from generated type_0");
assert_eq!(root["properties"]["manual"]["$id"], manual_resource["$id"]);
assert_eq!(
root["properties"]["manual"]["$defs"],
manual_resource["$defs"]
);
assert_eq!(
root["properties"]["manual"]["description"],
json!("Documented custom field")
);
let admitted = admit_final_schema(root).expect("mixed resources admit");
assert!(
admitted
.validate(&json!({"first": "x", "reused": "y", "manual": true}))
.is_ok()
);
assert!(
admitted
.validate(&json!({"first": "x", "reused": "y", "manual": "true"}))
.is_err()
);
let mut unscoped = manual_resource;
unscoped
.as_object_mut()
.expect("object fixture")
.remove("$id");
let mut context = SchemaGenerator::new();
let first = context.subschema_for::<GeneratedText>();
let reused = context.subschema_for::<GeneratedText>();
let manual = context.inline_schema(unscoped);
assert_eq!(manual, Value::Bool(false));
assert_eq!(
context.finish(json!({"type": "object", "properties": {
"first": first, "reused": reused, "manual": manual
}})),
Err(SchemaGenerationError::ReferenceResourceBoundary)
);
}
#[test]
fn schema_generation_uses_exact_identity_for_same_named_local_types() {
let mut context = SchemaGenerator::new();
let text = {
struct SameName;
impl JsonSchemaType for SameName {
fn schema_body(_context: &mut SchemaGenerator) -> Value {
json!({"type": "string"})
}
}
context.subschema_for::<SameName>()
};
let integer = {
struct SameName;
impl JsonSchemaType for SameName {
fn schema_body(_context: &mut SchemaGenerator) -> Value {
json!({"type": "integer"})
}
}
context.subschema_for::<SameName>()
};
assert_eq!(text, json!({"type": "string"}));
assert_eq!(integer, json!({"type": "integer"}));
let root = context
.finish(json!({"type": "object", "properties": {
"text": text, "integer": integer
}}))
.expect("distinct local Rust types retain distinct schemas");
assert!(root.get("$defs").is_none());
let admitted = admit_final_schema(root).expect("exact identity schema admits");
assert!(
admitted
.validate(&json!({"text": "one", "integer": 1}))
.is_ok()
);
assert!(
admitted
.validate(&json!({"text": "one", "integer": "one"}))
.is_err()
);
}
fn sch_01_a_schema() -> Value {
json!({
"$defs": {
"positive-id": {"type": "integer", "minimum": 1}
},
"type": "object",
"properties": {
"id": {"$ref": "#/$defs/positive-id"},
"mode": {"enum": ["fast", "safe"]},
"items": {
"type": "array",
"contains": {"type": "integer", "multipleOf": 2},
"minContains": 2,
"maxContains": 2
}
},
"required": ["id", "mode", "items"],
"patternProperties": {
"^x-": {"type": "string"}
},
"propertyNames": {"pattern": "^[A-Za-z-]+$"},
"dependentRequired": {
"creditCard": ["billingAddress"]
},
"dependentSchemas": {
"creditCard": {"required": ["billingAddress"]}
},
"allOf": [{"required": ["id"]}],
"anyOf": [
{"properties": {"mode": {"const": "fast"}}, "required": ["mode"]},
{"properties": {"mode": {"const": "safe"}}, "required": ["mode"]}
],
"oneOf": [
{"properties": {"mode": {"const": "fast"}}, "required": ["mode"]},
{"properties": {"mode": {"const": "safe"}}, "required": ["mode"]}
],
"not": {
"properties": {"mode": {"const": "disabled"}},
"required": ["mode"]
},
"if": {
"properties": {"mode": {"const": "fast"}},
"required": ["mode"]
},
"then": {"required": ["fastConfig"]},
"else": {"required": ["safeConfig"]}
})
}
fn sch_01_a_valid_instance() -> Value {
json!({
"id": 7,
"mode": "fast",
"fastConfig": true,
"items": [2, 4, 5],
"x-label": "bounded",
"creditCard": "4111",
"billingAddress": "42 Schema Street"
})
}
#[test]
fn sch_01_a_positive() {
let schema = sch_01_a_schema();
let instance = sch_01_a_valid_instance();
assert!(validate(&schema, &instance).is_ok());
}
#[test]
fn sch_01_a_planted_negative() {
let schema = sch_01_a_schema();
let schema_before = schema.clone();
let mut instance = sch_01_a_valid_instance();
instance["items"][1] = json!(3);
let errors = validate(&schema, &instance)
.expect_err("changing only one array item must violate minContains");
assert_eq!(errors.len(), 1);
assert_eq!(errors[0].path, "root.items");
assert_eq!(
errors[0].message,
"array has fewer matching items than minContains"
);
assert_eq!(schema, schema_before);
}
#[test]
fn final_core_result_schema_positive() {
let schema = admit_final_schema(json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": "object",
"properties": {
"resultType": {"const": "complete"},
"content": {"type": "array", "items": {"type": "string"}}
},
"required": ["resultType", "content"],
"additionalProperties": false
}))
.expect("a strict final core result schema admits");
let result = json!({"resultType": "complete", "content": ["ready"]});
validate_final_core_result(&schema, &result, FinalCoreResultType::Complete)
.expect("the selected final core branch and schema both admit the result");
assert_eq!(schema.schema()["$schema"], FINAL_JSON_SCHEMA_DIALECT);
assert_eq!(FinalCoreResultType::Complete.as_str(), "complete");
}
#[test]
fn final_core_result_schema_cross_era_and_unknown_field_negatives() {
let schema = admit_final_schema(json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": "object",
"properties": {
"resultType": {"const": "complete"},
"content": {"type": "array", "items": {"type": "string"}}
},
"required": ["resultType", "content"],
"additionalProperties": false
}))
.expect("the final schema admits");
let accepted = json!({"resultType": "complete", "content": ["ready"]});
let mut cross_era = accepted.clone();
cross_era["resultType"] = json!("legacy_complete");
let cross_era_errors =
validate_final_core_result(&schema, &cross_era, FinalCoreResultType::Complete)
.expect_err("changing only resultType to a non-final branch must reject");
assert!(cross_era_errors.iter().any(|error| {
error.path == "root.resultType"
&& error.message
== "resultType does not match the selected final core result branch"
}));
let mut with_legacy_field = accepted.clone();
with_legacy_field["protocolVersion"] = json!("2024-11-05");
let unknown_field_errors =
validate_final_core_result(&schema, &with_legacy_field, FinalCoreResultType::Complete)
.expect_err("adding only a legacy result field must reject");
assert!(unknown_field_errors.iter().any(|error| {
error.path == "root.protocolVersion"
&& error.message == "additional property not allowed"
}));
assert_eq!(
accepted,
json!({"resultType": "complete", "content": ["ready"]})
);
}
fn bounded_draft_2020_12_schema() -> AdmittedSchema {
admit_final_schema(json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"$defs": {
"positive": {
"allOf": [
{"type": "integer"},
{"minimum": 1}
]
},
"entry": {
"type": "object",
"properties": {
"kind": {"enum": ["number", "label"]},
"value": {}
},
"required": ["kind", "value"],
"additionalProperties": false,
"allOf": [{
"if": {
"properties": {"kind": {"const": "number"}},
"required": ["kind"]
},
"then": {
"properties": {"value": {"$ref": "#/$defs/positive"}}
},
"else": {
"properties": {"value": {"type": "string", "minLength": 3}}
}
}]
}
},
"type": "object",
"properties": {
"entries": {
"type": "array",
"items": {"$ref": "#/$defs/entry"}
}
},
"required": ["entries"],
"additionalProperties": false
}))
.expect("bounded local-reference schema admits")
}
#[test]
fn bounded_draft_2020_12_local_ref_composition_conditional_positive() {
let schema = bounded_draft_2020_12_schema();
let instance = json!({
"entries": [
{"kind": "number", "value": 7},
{"kind": "label", "value": "ready"}
]
});
schema
.validate(&instance)
.expect("local references, allOf, and the selected conditional branch validate");
}
#[test]
fn bounded_draft_2020_12_local_ref_composition_conditional_planted_negative() {
let schema = bounded_draft_2020_12_schema();
let accepted = json!({
"entries": [
{"kind": "number", "value": 7},
{"kind": "label", "value": "ready"}
]
});
let mut planted = accepted.clone();
planted["entries"][0]["value"] = json!(0);
let errors = schema.validate(&planted).expect_err(
"changing only the local-reference value violates the selected then branch",
);
assert!(errors.iter().any(|error| {
error.path == "root.entries[0].value" && error.message == "value is below minimum"
}));
assert_eq!(
accepted,
json!({
"entries": [
{"kind": "number", "value": 7},
{"kind": "label", "value": "ready"}
]
})
);
}
fn bounded_draft_2020_12_unevaluated_properties_schema() -> AdmittedSchema {
admit_final_schema(json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": "object",
"allOf": [{
"properties": {
"label": {"type": "string"}
},
"required": ["label"]
}],
"unevaluatedProperties": false
}))
.expect("the bounded unevaluated-properties schema admits")
}
#[test]
fn bounded_draft_2020_12_unevaluated_properties_positive() {
let schema = bounded_draft_2020_12_unevaluated_properties_schema();
let accepted = json!({"label": "ready"});
schema
.validate(&accepted)
.expect("a property evaluated by a successful allOf branch remains accepted");
assert_eq!(accepted, json!({"label": "ready"}));
}
#[test]
fn bounded_draft_2020_12_unevaluated_properties_planted_negative() {
let schema = bounded_draft_2020_12_unevaluated_properties_schema();
let accepted = json!({"label": "ready"});
let mut planted = accepted.clone();
planted["unexpected"] = json!(true);
let errors = schema
.validate(&planted)
.expect_err("adding only an unevaluated property must be rejected by the false schema");
assert_eq!(errors.len(), 1);
assert_eq!(errors[0].path, "root.unexpected");
assert_eq!(errors[0].message, "schema rejects all values");
assert_eq!(accepted, json!({"label": "ready"}));
}
#[test]
fn raw_validate_preserves_legacy_unevaluated_properties_behavior() {
let legacy_schema = json!({
"type": "object",
"unevaluatedProperties": false
});
let legacy_instance = json!({"legacy": true});
assert!(validate(&legacy_schema, &legacy_instance).is_ok());
assert_eq!(legacy_instance, json!({"legacy": true}));
}
#[test]
fn admitted_anchor_and_dynamic_reference_positive() {
let anchored = admit_final_schema(json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"$defs": {
"positive": {"$anchor": "positive", "type": "integer", "minimum": 1}
},
"$ref": "#positive"
}))
.expect("a local named anchor admits");
anchored
.validate(&json!(1))
.expect("the named anchor resolves without external I/O");
let dynamic = admit_final_schema(json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"$defs": {
"node": {
"$dynamicAnchor": "node",
"type": "object",
"properties": {
"value": {"type": "integer"},
"child": {"$dynamicRef": "#node"}
},
"required": ["value"],
"additionalProperties": false
}
},
"$ref": "#node"
}))
.expect("a bounded recursive dynamic reference admits");
let accepted = json!({"value": 1, "child": {"value": 2}});
dynamic
.validate(&accepted)
.expect("a dynamic reference resolves to the active local anchor");
assert_eq!(accepted, json!({"value": 1, "child": {"value": 2}}));
}
#[test]
fn admitted_anchor_and_dynamic_reference_planted_negative() {
let schema = admit_final_schema(json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"$defs": {
"node": {
"$dynamicAnchor": "node",
"type": "object",
"properties": {
"value": {"type": "integer"},
"child": {"$dynamicRef": "#node"}
},
"required": ["value"],
"additionalProperties": false
}
},
"$ref": "#node"
}))
.expect("the recursive dynamic schema admits");
let accepted = json!({"value": 1, "child": {"value": 2}});
let mut planted = accepted.clone();
planted["child"]["value"] = json!("not-an-integer");
let errors = schema
.validate(&planted)
.expect_err("changing only the dynamically referenced value must reject");
assert!(errors.iter().any(|error| error.path == "root.child.value"));
assert_eq!(accepted, json!({"value": 1, "child": {"value": 2}}));
}
#[test]
fn admitted_dynamic_reference_preserves_recursive_lexical_identity() {
let source = json!({
"$defs": {
"label": {"type": "string", "minLength": 1},
"node": {
"$dynamicAnchor": "node",
"type": "object",
"properties": {
"label": {"$ref": "#/$defs/label"},
"child": {"$dynamicRef": "#node"}
},
"required": ["label"],
"additionalProperties": false
}
},
"$ref": "#node"
});
let schema = admit_final_schema(source.clone()).expect("recursive schemas admit");
let accepted = json!({
"label": "first",
"child": {"label": "second", "child": {"label": "third"}}
});
schema
.validate(&accepted)
.expect("every recursive level retains its original lexical reference scope");
let mut planted = accepted.clone();
planted["child"]["child"]["label"] = json!(7);
let errors = schema
.validate(&planted)
.expect_err("the same referenced label constraint applies at the deepest level");
assert!(
errors
.iter()
.any(|error| error.path == "root.child.child.label")
);
assert_eq!(schema.schema(), &source);
assert_eq!(accepted["child"]["child"]["label"], json!("third"));
}
#[test]
fn admitted_dynamic_reference_uses_outermost_resource_override() {
let schema = admit_final_schema(json!({
"$id": "https://schemas.example.test/strict",
"$dynamicAnchor": "node",
"$ref": "tree",
"properties": {"strict": {"const": true}},
"required": ["strict"],
"$defs": {"tree": {
"$id": "tree",
"$dynamicAnchor": "node",
"type": "object",
"properties": {
"value": {"type": "integer"},
"child": {"$dynamicRef": "#node"}
},
"required": ["value"]
}}
}))
.expect("independent resources may extend the same dynamic anchor");
let accepted = json!({
"value": 1, "strict": true,
"child": {"value": 2, "strict": true}
});
schema
.validate(&accepted)
.expect("the outer resource's constraints apply to recursive children");
let mut planted = accepted.clone();
planted["child"]["strict"] = json!(false);
let errors = schema
.validate(&planted)
.expect_err("the inner tree cannot bypass an outer recursive constraint");
assert!(errors.iter().any(|error| error.path == "root.child.strict"));
assert_eq!(accepted["child"]["strict"], json!(true));
}
#[test]
fn admitted_dynamic_reference_finds_unvisited_resource_anchor() {
let schema = admit_final_schema(json!({
"$id": "https://schemas.example.test/outer",
"properties": {"entry": {"$ref": "inner"}},
"$defs": {
"outerConstraint": {
"$dynamicAnchor": "value",
"type": "string", "minLength": 3
},
"inner": {
"$id": "inner",
"properties": {"value": {"$dynamicRef": "#value"}},
"$defs": {"defaultConstraint": {
"$dynamicAnchor": "value", "type": "string"
}}
}
}
}))
.expect("anchors under $defs belong to their containing resource");
let accepted = json!({"entry": {"value": "ready"}});
schema
.validate(&accepted)
.expect("the extended value satisfies both constraints");
let mut planted = accepted.clone();
planted["entry"]["value"] = json!("x");
let errors = schema
.validate(&planted)
.expect_err("an outer anchor participates before its schema is directly visited");
assert!(errors.iter().any(|error| error.path == "root.entry.value"));
assert_eq!(accepted["entry"]["value"], json!("ready"));
}
#[test]
fn admitted_dynamic_reference_pointer_target_remains_static() {
let source = json!({
"$id": "https://schemas.example.test/outer",
"$dynamicAnchor": "node",
"type": "object",
"properties": {"value": {"$dynamicRef": "inner#/$defs/node"}},
"$defs": {"inner": {
"$id": "inner",
"$defs": {"node": {"$dynamicAnchor": "node", "type": "string"}}
}}
});
let schema =
admit_final_schema(source.clone()).expect("a pointer may name an anchor schema");
let accepted = json!({"value": "ready"});
schema
.validate(&accepted)
.expect("a pointer reference does not activate the containing object's override");
assert!(schema.validate(&json!({"value": 1})).is_err());
let mut dynamic = source;
dynamic["properties"]["value"]["$dynamicRef"] = json!("inner#node");
let schema = admit_final_schema(dynamic).expect("the plain-name anchor also admits");
let errors = schema
.validate(&accepted)
.expect_err("changing only the URI fragment activates the outer object constraint");
assert!(errors.iter().any(|error| error.path == "root.value"));
}
#[test]
fn admitted_dynamic_reference_annotations_preserve_object_and_array_evaluation() {
for (constraints, accepted, planted, expected_path, unevaluated_keyword) in [
(
json!({"properties": {"answer": {"type": "integer"}}}),
json!({"answer": 42}),
json!({"answer": 42, "extra": true}),
"root.extra",
"unevaluatedProperties",
),
(
json!({"prefixItems": [{"type": "integer"}]}),
json!([42]),
json!([42, true]),
"root[1]",
"unevaluatedItems",
),
] {
let schema = admit_final_schema(json!({
"$defs": {
"selected": {"$dynamicAnchor": "shape", "$ref": "#/$defs/constraints"},
"constraints": constraints
},
"$dynamicRef": "#shape",
unevaluated_keyword: false
}))
.expect("dynamic references and their lexical references remain admitted");
schema
.validate(&accepted)
.expect("annotations survive dynamic reference and lexical reference traversal");
let errors = schema
.validate(&planted)
.expect_err("one additional unevaluated member remains rejected");
assert!(errors.iter().any(|error| error.path == expected_path));
}
}
#[test]
fn admitted_dynamic_reference_cycle_and_lookup_limits_fail_closed() {
let terminating = json!({
"$defs": {"node": {"$dynamicAnchor": "node", "type": "object"}},
"not": {"$dynamicRef": "#node"}
});
admit_final_schema(terminating.clone())
.expect("the terminating reference admits")
.validate(&Value::Null)
.expect("a real type mismatch may satisfy not");
let mut cycle = terminating;
cycle["$defs"]["node"] = json!({"$dynamicAnchor": "node", "$dynamicRef": "#node"});
let errors = admit_final_schema(cycle)
.expect("admission permits bounded recursive references")
.validate(&Value::Null)
.expect_err("a recursion limit is never a successful not-branch mismatch");
assert!(errors.iter().any(|error| {
error.message == "local schema reference depth limit exceeded"
|| error.message == "schema validation nesting limit exceeded"
|| error.message == "schema validation work limit exceeded"
}));
let root = json!({"$defs": {"node": {"$dynamicAnchor": "node", "type": "integer"}}});
let source = root.as_object().expect("the schema is an object");
let mut exact = ValidationContext::new(&root, true);
exact.push_dynamic_scope(source);
exact.remaining_work = 3;
let target = exact
.dynamic_anchor_target("node")
.expect("one scope visit and two anchor visits fit the exact budget")
.expect("the configured anchor exists");
assert!(std::ptr::eq(target, &raw const root["$defs"]["node"]));
assert_eq!(exact.remaining_work, 0);
let mut exhausted = ValidationContext::new(&root, true);
exhausted.push_dynamic_scope(source);
exhausted.remaining_work = 2;
assert_eq!(
exhausted.dynamic_anchor_target("node").unwrap_err(),
"schema validation work limit exceeded"
);
assert!(exhausted.work_exhausted);
}
#[test]
fn admitted_unevaluated_items_positive() {
let schema = admit_final_schema(json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": "array",
"prefixItems": [{"type": "string"}],
"contains": {"type": "integer"},
"unevaluatedItems": false
}))
.expect("the bounded unevaluated-items schema admits");
let accepted = json!(["heading", 2]);
schema
.validate(&accepted)
.expect("prefixItems and contains annotations consume every item");
assert_eq!(accepted, json!(["heading", 2]));
}
#[test]
fn admitted_unevaluated_items_planted_negative() {
let schema = admit_final_schema(json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": "array",
"prefixItems": [{"type": "string"}],
"contains": {"type": "integer"},
"unevaluatedItems": false
}))
.expect("the bounded unevaluated-items schema admits");
let accepted = json!(["heading", 2]);
let mut planted = accepted.clone();
planted
.as_array_mut()
.expect("fixture is an array")
.push(json!(true));
let errors = schema
.validate(&planted)
.expect_err("adding only an unevaluated item must reject");
assert!(errors.iter().any(|error| error.path == "root[2]"));
assert_eq!(accepted, json!(["heading", 2]));
}
fn large_annotation_array() -> Value {
json!(["x".repeat(3 * 1024 * 1024), 42])
}
fn assert_large_array_annotations(source: Value) {
let schema =
admit_final_schema(source.clone()).expect("the bounded array annotation schema admits");
let accepted = large_annotation_array();
schema
.validate(&accepted)
.expect("successful applicators annotate the multi-MiB array");
let mut planted = accepted.clone();
planted
.as_array_mut()
.expect("the fixture is an array")
.push(Value::Bool(true));
let errors = schema
.validate(&planted)
.expect_err("one additional unevaluated item must reject");
assert_eq!(errors.len(), 1);
assert_eq!(errors[0].path, "root[2]");
assert_eq!(errors[0].message, "schema rejects all values");
assert_eq!(schema.schema(), &source);
assert_eq!(accepted, large_annotation_array());
}
#[test]
fn admitted_large_array_composition_annotations_preserve_unevaluated_items() {
let shape = json!({"prefixItems": [{"type": "string"}, {"type": "integer"}]});
let mut nested = shape.clone();
for _ in 0..24 {
nested = json!({"allOf": [nested]});
}
nested["unevaluatedItems"] = Value::Bool(false);
assert_large_array_annotations(nested);
assert_large_array_annotations(json!({
"anyOf": [
{"prefixItems": [{"type": "string"}]},
shape,
{"prefixItems": [true, {"type": "string"}, true]}
],
"unevaluatedItems": false
}));
let mut alternatives = vec![Value::Bool(false); MAX_COMPOSITION_BRANCHES - 1];
alternatives.push(shape);
assert_large_array_annotations(json!({
"oneOf": alternatives,
"unevaluatedItems": false
}));
}
#[test]
fn admitted_large_array_reference_annotations_preserve_unevaluated_items() {
for (keyword, reference) in [("$ref", "#/$defs/shape"), ("$dynamicRef", "#shape")] {
assert_large_array_annotations(json!({
"$defs": {
"shape": {
"$dynamicAnchor": "shape",
"$ref": "#/$defs/constraints"
},
"constraints": {
"prefixItems": [{"type": "string"}, {"type": "integer"}]
}
},
keyword: reference,
"unevaluatedItems": false
}));
}
}
#[test]
fn admitted_large_array_conditional_annotations_preserve_unevaluated_items() {
let shape = json!({"prefixItems": [{"type": "string"}, {"type": "integer"}]});
assert_large_array_annotations(json!({
"if": shape,
"unevaluatedItems": false
}));
assert_large_array_annotations(json!({
"if": {"prefixItems": [{"type": "string"}]},
"then": shape,
"else": {"prefixItems": [true, true, true]},
"unevaluatedItems": false
}));
assert_large_array_annotations(json!({
"if": {"prefixItems": [{"type": "integer"}, true, true]},
"then": {"prefixItems": [true, true, true]},
"else": shape,
"unevaluatedItems": false
}));
}
#[test]
fn admitted_large_array_annotations_use_the_nested_instance() {
let source = json!({
"prefixItems": [{
"allOf": [{
"prefixItems": [{"type": "string"}, {"type": "integer"}]
}],
"unevaluatedItems": false
}],
"items": false
});
let schema = admit_final_schema(source.clone()).expect("the nested schema admits");
let accepted = Value::Array(vec![large_annotation_array()]);
schema
.validate(&accepted)
.expect("annotation probes borrow the child array rather than its parent");
let mut planted = accepted.clone();
planted[0]
.as_array_mut()
.expect("the child fixture is an array")
.push(Value::Bool(true));
let errors = schema
.validate(&planted)
.expect_err("one unevaluated child item must reject");
assert_eq!(errors.len(), 1);
assert_eq!(errors[0].path, "root[0][2]");
assert_eq!(errors[0].message, "schema rejects all values");
assert_eq!(schema.schema(), &source);
assert_eq!(accepted, Value::Array(vec![large_annotation_array()]));
}
#[test]
fn admitted_exact_numeric_boundaries_positive() {
let minimum = admit_final_schema(json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": "integer",
"minimum": 9007199254740993_u64
}))
.expect("the exact integer boundary schema admits");
minimum
.validate(&json!(9007199254740993_u64))
.expect("the exact minimum itself is accepted");
let multiple = admit_final_schema(json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": "number",
"multipleOf": 0.1
}))
.expect("the exact decimal divisor schema admits");
multiple
.validate(&json!(0.3))
.expect("0.3 is exactly divisible by the decimal divisor 0.1");
}
#[test]
fn admitted_exact_numeric_boundaries_planted_negative() {
let schema = admit_final_schema(json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": "integer",
"minimum": 9007199254740993_u64
}))
.expect("the exact integer boundary schema admits");
let accepted = json!(9007199254740993_u64);
let planted = json!(9007199254740992_u64);
let errors = schema
.validate(&planted)
.expect_err("changing only the integer below the exact boundary must reject");
assert!(errors.iter().any(|error| error.path == "root"));
assert_eq!(accepted, json!(9007199254740993_u64));
}
#[test]
fn admitted_final_string_lengths_above_u64_are_lossless_positive() {
const BOUND: &str = "184467440737095516160e-1";
let accepted_schema: Value = serde_json::from_str(&format!(
r#"{{"$schema":"{FINAL_JSON_SCHEMA_DIALECT}","type":"string","minLength":1,"maxLength":{BOUND}}}"#
))
.expect("the arbitrary-precision count schema parses");
let schema = admit_final_schema(accepted_schema.clone())
.expect("a mathematical string-length count above u64 admits");
let accepted = json!("x");
schema
.validate(&accepted)
.expect("the exact upper string-length bound accepts the smaller instance");
assert_eq!(
schema.schema()["maxLength"]
.as_number()
.expect("admitted maxLength remains numeric")
.as_str(),
BOUND
);
assert_eq!(accepted_schema["minLength"], json!(1));
assert_eq!(accepted, json!("x"));
}
#[test]
fn admitted_final_string_lengths_above_u64_are_lossless_planted_negative() {
const BOUND: &str = "184467440737095516160e-1";
let accepted_schema: Value = serde_json::from_str(&format!(
r#"{{"$schema":"{FINAL_JSON_SCHEMA_DIALECT}","type":"string","minLength":1,"maxLength":{BOUND}}}"#
))
.expect("the arbitrary-precision count schema parses");
let mut planted_schema = accepted_schema.clone();
planted_schema["minLength"] = planted_schema["maxLength"].clone();
let accepted = json!("x");
let errors = admit_final_schema(planted_schema)
.expect("the mathematical string-length lower bound admits")
.validate(&accepted)
.expect_err("changing only minLength to the exact large bound must reject");
assert!(errors.iter().any(|error| {
error.path == "root" && error.message == "string has fewer characters than minLength"
}));
assert_eq!(accepted_schema["minLength"], json!(1));
assert_eq!(
accepted_schema["maxLength"]
.as_number()
.expect("baseline maxLength remains numeric")
.as_str(),
BOUND
);
assert_eq!(accepted, json!("x"));
}
#[test]
fn admitted_final_item_counts_above_u64_are_lossless_positive() {
const BOUND: &str = "184467440737095516160e-1";
let accepted_schema: Value = serde_json::from_str(&format!(
r#"{{"$schema":"{FINAL_JSON_SCHEMA_DIALECT}","type":"array","minItems":1,"maxItems":{BOUND}}}"#
))
.expect("the arbitrary-precision count schema parses");
let schema = admit_final_schema(accepted_schema.clone())
.expect("a mathematical item count above u64 admits");
let accepted = json!([null]);
schema
.validate(&accepted)
.expect("the exact upper item-count bound accepts the smaller instance");
assert_eq!(
schema.schema()["maxItems"]
.as_number()
.expect("admitted maxItems remains numeric")
.as_str(),
BOUND
);
assert_eq!(accepted_schema["minItems"], json!(1));
assert_eq!(accepted, json!([null]));
}
#[test]
fn admitted_final_item_counts_above_u64_are_lossless_planted_negative() {
const BOUND: &str = "184467440737095516160e-1";
let accepted_schema: Value = serde_json::from_str(&format!(
r#"{{"$schema":"{FINAL_JSON_SCHEMA_DIALECT}","type":"array","minItems":1,"maxItems":{BOUND}}}"#
))
.expect("the arbitrary-precision count schema parses");
let mut planted_schema = accepted_schema.clone();
planted_schema["minItems"] = planted_schema["maxItems"].clone();
let accepted = json!([null]);
let errors = admit_final_schema(planted_schema)
.expect("the mathematical item-count lower bound admits")
.validate(&accepted)
.expect_err("changing only minItems to the exact large bound must reject");
assert!(errors.iter().any(|error| {
error.path == "root" && error.message == "array has fewer items than minItems"
}));
assert_eq!(accepted_schema["minItems"], json!(1));
assert_eq!(
accepted_schema["maxItems"]
.as_number()
.expect("baseline maxItems remains numeric")
.as_str(),
BOUND
);
assert_eq!(accepted, json!([null]));
}
#[test]
fn arbitrary_width_count_comparisons_are_final_only_and_raw_remains_legacy() {
const BOUND: &str = "184467440737095516160e-1";
let accepted_schema: Value = serde_json::from_str(&format!(
r#"{{"$schema":"{FINAL_JSON_SCHEMA_DIALECT}","type":"array","minItems":1,"maxItems":{BOUND}}}"#
))
.expect("the arbitrary-precision count schema parses");
let mut planted_schema = accepted_schema.clone();
planted_schema["minItems"] = planted_schema["maxItems"].clone();
let instance = json!([null]);
validate(&planted_schema, &instance)
.expect("raw validation retains its legacy u64-only count behavior");
validate_strict(&planted_schema, &instance)
.expect("raw strict validation retains its legacy u64-only count behavior");
let errors = admit_final_schema(planted_schema)
.expect("the arbitrary-width final count admits")
.validate(&instance)
.expect_err("the same final count remains mathematically enforced");
assert!(errors.iter().any(|error| {
error.path == "root" && error.message == "array has fewer items than minItems"
}));
assert_eq!(accepted_schema["minItems"], json!(1));
assert_eq!(
accepted_schema["maxItems"]
.as_number()
.expect("baseline maxItems remains numeric")
.as_str(),
BOUND
);
assert_eq!(instance, json!([null]));
}
#[test]
fn admitted_final_property_counts_above_u64_are_lossless_positive() {
const BOUND: &str = "184467440737095516160e-1";
let accepted_schema: Value = serde_json::from_str(&format!(
r#"{{"$schema":"{FINAL_JSON_SCHEMA_DIALECT}","type":"object","minProperties":1,"maxProperties":{BOUND}}}"#
))
.expect("the arbitrary-precision count schema parses");
let schema = admit_final_schema(accepted_schema.clone())
.expect("a mathematical property count above u64 admits");
let accepted = json!({"ready": null});
schema
.validate(&accepted)
.expect("the exact upper property-count bound accepts the smaller instance");
assert_eq!(
schema.schema()["maxProperties"]
.as_number()
.expect("admitted maxProperties remains numeric")
.as_str(),
BOUND
);
assert_eq!(accepted_schema["minProperties"], json!(1));
assert_eq!(accepted, json!({"ready": null}));
}
#[test]
fn admitted_final_property_counts_above_u64_are_lossless_planted_negative() {
const BOUND: &str = "184467440737095516160e-1";
let accepted_schema: Value = serde_json::from_str(&format!(
r#"{{"$schema":"{FINAL_JSON_SCHEMA_DIALECT}","type":"object","minProperties":1,"maxProperties":{BOUND}}}"#
))
.expect("the arbitrary-precision count schema parses");
let mut planted_schema = accepted_schema.clone();
planted_schema["minProperties"] = planted_schema["maxProperties"].clone();
let accepted = json!({"ready": null});
let errors = admit_final_schema(planted_schema)
.expect("the mathematical property-count lower bound admits")
.validate(&accepted)
.expect_err("changing only minProperties to the exact large bound must reject");
assert!(errors.iter().any(|error| {
error.path == "root"
&& error.message == "object has fewer properties than minProperties"
}));
assert_eq!(accepted_schema["minProperties"], json!(1));
assert_eq!(
accepted_schema["maxProperties"]
.as_number()
.expect("baseline maxProperties remains numeric")
.as_str(),
BOUND
);
assert_eq!(accepted, json!({"ready": null}));
}
#[test]
fn admitted_final_contains_counts_above_u64_are_lossless_positive() {
const BOUND: &str = "184467440737095516160e-1";
let accepted_schema: Value = serde_json::from_str(&format!(
r#"{{"$schema":"{FINAL_JSON_SCHEMA_DIALECT}","type":"array","contains":{{"const":"ready"}},"minContains":1,"maxContains":{BOUND},"unevaluatedItems":false}}"#
))
.expect("the arbitrary-precision count schema parses");
let schema = admit_final_schema(accepted_schema.clone())
.expect("a mathematical contains count above u64 admits");
let accepted = json!(["ready"]);
schema
.validate(&accepted)
.expect("the exact upper contains bound retains the successful item annotation");
assert_eq!(
schema.schema()["maxContains"]
.as_number()
.expect("admitted maxContains remains numeric")
.as_str(),
BOUND
);
assert_eq!(accepted_schema["minContains"], json!(1));
assert_eq!(accepted, json!(["ready"]));
}
#[test]
fn admitted_final_contains_counts_above_u64_are_lossless_planted_negative() {
const BOUND: &str = "184467440737095516160e-1";
let accepted_schema: Value = serde_json::from_str(&format!(
r#"{{"$schema":"{FINAL_JSON_SCHEMA_DIALECT}","type":"array","contains":{{"const":"ready"}},"minContains":1,"maxContains":{BOUND},"unevaluatedItems":false}}"#
))
.expect("the arbitrary-precision count schema parses");
let mut planted_schema = accepted_schema.clone();
planted_schema["minContains"] = planted_schema["maxContains"].clone();
let accepted = json!(["ready"]);
let errors = admit_final_schema(planted_schema)
.expect("the mathematical contains lower bound admits")
.validate(&accepted)
.expect_err("changing only minContains to the exact large bound must reject");
assert!(errors.iter().any(|error| {
error.path == "root"
&& error.message == "array has fewer matching items than minContains"
}));
assert_eq!(accepted_schema["minContains"], json!(1));
assert_eq!(
accepted_schema["maxContains"]
.as_number()
.expect("baseline maxContains remains numeric")
.as_str(),
BOUND
);
assert_eq!(accepted, json!(["ready"]));
}
#[test]
fn admitted_underscore_anchor_positive() {
let schema = admit_final_schema(json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"$defs": {
"private": {"$anchor": "_private", "const": "ready"}
},
"$ref": "#_private"
}))
.expect("an underscore-prefixed JSON Schema anchor admits");
let accepted = json!("ready");
schema
.validate(&accepted)
.expect("the underscore-prefixed local anchor resolves");
assert_eq!(accepted, json!("ready"));
}
#[test]
fn admitted_underscore_anchor_planted_negative() {
let accepted = json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"$defs": {
"private": {"$anchor": "_private", "const": "ready"}
}
});
admit_final_schema(accepted.clone())
.expect("the underscore-prefixed anchor remains the valid baseline");
let mut planted = accepted.clone();
planted["$defs"]["private"]["$anchor"] = json!("-private");
let error = admit_final_schema(planted)
.expect_err("changing only the initial anchor character to a hyphen must reject");
assert_eq!(error.path(), "$.$defs.private.$anchor");
assert_eq!(error.reason(), "schema anchor has an invalid name");
assert_eq!(accepted["$defs"]["private"]["$anchor"], json!("_private"));
}
#[test]
fn admitted_unique_items_uses_numeric_schema_equality_positive() {
let schema = admit_final_schema(json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": "array",
"uniqueItems": true
}))
.expect("the final unique-items schema admits");
let accepted = json!([1, 2.0]);
schema
.validate(&accepted)
.expect("numerically distinct items remain unique");
assert_eq!(accepted, json!([1, 2.0]));
}
#[test]
fn admitted_unique_items_uses_numeric_schema_equality_planted_negative() {
let schema = admit_final_schema(json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": "array",
"uniqueItems": true
}))
.expect("the final unique-items schema admits");
let accepted = json!([1, 2.0]);
let mut planted = accepted.clone();
planted[1] = json!(1.0);
let errors = schema
.validate(&planted)
.expect_err("changing only 2.0 to the numerically equal 1.0 must reject");
assert!(errors.iter().any(|error| {
error.path == "root[1]" && error.message == "duplicate item in array"
}));
assert_eq!(accepted, json!([1, 2.0]));
}
fn arbitrary_precision_number(decimal_digits: usize) -> Value {
serde_json::from_str(&"1".repeat(decimal_digits))
.expect("the workspace serde_json configuration retains arbitrary-precision numbers")
}
#[test]
fn admitted_const_and_enum_exact_equality_bound_positive() {
let number = arbitrary_precision_number(MAX_EXACT_DECIMAL_DIGITS);
let const_schema = admit_final_schema(json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"const": number.clone()
}))
.expect("a const at the exact numeric equality bound admits");
const_schema
.validate(&number)
.expect("an admitted const remains reflexive at the exact bound");
let enum_schema = admit_final_schema(json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"enum": [number.clone()]
}))
.expect("an enum member at the exact numeric equality bound admits");
enum_schema
.validate(&number)
.expect("an admitted enum member remains reflexive at the exact bound");
}
#[test]
fn admitted_const_and_enum_exact_equality_bound_planted_negative() {
let accepted = arbitrary_precision_number(MAX_EXACT_DECIMAL_DIGITS);
let planted = arbitrary_precision_number(MAX_EXACT_DECIMAL_DIGITS + 1);
let const_error = admit_final_schema(json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"const": planted.clone()
}))
.expect_err("adding one digit beyond the const equality bound must reject admission");
assert_eq!(const_error.path(), "$.const");
assert_eq!(
const_error.reason(),
"const or enum value exceeds exact numeric equality bound"
);
let enum_error = admit_final_schema(json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"enum": [planted]
}))
.expect_err("adding one digit beyond the enum equality bound must reject admission");
assert_eq!(enum_error.path(), "$.enum[0]");
assert_eq!(
enum_error.reason(),
"const or enum value exceeds exact numeric equality bound"
);
assert_eq!(accepted.to_string().len(), MAX_EXACT_DECIMAL_DIGITS);
}
#[test]
fn admitted_multiple_of_work_accounting_positive() {
let schema = admit_final_schema(json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": "number",
"multipleOf": 1
}))
.expect("the exact divisor schema admits");
let accepted = arbitrary_precision_number((MAX_SCHEMA_VALIDATION_WORK - 1) / 4);
schema
.validate(&accepted)
.expect("the exact long-division work budget admits its final charged digit");
assert_eq!(
accepted.to_string().len(),
(MAX_SCHEMA_VALIDATION_WORK - 1) / 4
);
}
#[test]
fn admitted_multiple_of_work_accounting_planted_negative() {
let schema = admit_final_schema(json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": "number",
"multipleOf": 1
}))
.expect("the exact divisor schema admits");
let accepted = arbitrary_precision_number((MAX_SCHEMA_VALIDATION_WORK - 1) / 4);
let planted = arbitrary_precision_number(((MAX_SCHEMA_VALIDATION_WORK - 1) / 4) + 1);
let errors = schema
.validate(&planted)
.expect_err("adding one decimal digit beyond the charged division budget must reject");
assert!(
errors
.iter()
.any(|error| error.message == "schema validation work limit exceeded")
);
assert_eq!(
accepted.to_string().len(),
(MAX_SCHEMA_VALIDATION_WORK - 1) / 4
);
}
#[test]
fn admitted_schema_retains_opaque_annotations_without_changing_assertions() {
let source = json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": "object",
"properties": {"value": {
"type": "integer", "minimum": 3,
"x-ui": {"type": 17, "$ref": "https://unregistered.example/schema"}
}},
"required": ["value"],
"additionalProperties": false,
"customAnnotation": [null, false, {"$schema": 17}]
});
let admitted = admit_final_schema(source.clone()).expect("custom annotations admit");
assert_eq!(admitted.schema(), &source);
assert!(admitted.validate(&json!({"value": 3})).is_ok());
for invalid in [json!({"value": 2}), json!({"value": "3"}), json!({})] {
assert!(admitted.validate(&invalid).is_err());
}
let mut malformed = source;
malformed["properties"]["value"]["type"] = json!(17);
assert!(admit_final_schema(malformed).is_err());
let numeric: Value =
serde_json::from_str(r#"{"type":"integer","x-number":1.20e+9000}"#).unwrap();
let numeric = admit_final_schema(numeric).unwrap();
let Value::Number(number) = &numeric.schema()["x-number"] else {
panic!("numeric annotation must retain its JSON type");
};
assert_eq!(number.as_str(), "1.20e+9000");
assert!(numeric.validate(&json!(1)).is_ok());
assert!(numeric.validate(&json!("1")).is_err());
}
#[test]
fn raw_schema_validation_retains_legacy_numeric_and_reference_semantics() {
assert!(validate(&json!({"type": "integer"}), &json!(1.0)).is_err());
assert!(validate(&json!({"$ref": "#named"}), &json!(true)).is_err());
}
#[test]
fn custom_annotation_objects_never_acquire_reference_or_dialect_authority() {
let source = json!({
"$id": "https://schemas.example/root",
"$defs": {"real": {"type": "integer", "minimum": 3}},
"$ref": "#/$defs/real",
"x-ui": {
"$id": "https://schemas.example/annotation",
"$anchor": "annotation",
"$dynamicAnchor": "dynamic",
"type": 17,
"$ref": "https://unregistered.example/schema"
}
});
let admitted = admit_final_schema(source.clone()).unwrap();
assert!(admitted.validate(&json!(3)).is_ok());
assert!(admitted.validate(&json!(2)).is_err());
for target in [
"#/x-ui",
"#annotation",
"#dynamic",
"https://schemas.example/annotation",
] {
let mut invalid = source.clone();
invalid["$ref"] = json!(target);
assert!(
admit_final_schema(invalid).is_err(),
"opaque data must not resolve: {target}"
);
}
let mut dialect = source;
dialect["$schema"] = json!("https://schemas.example/annotation");
assert!(admit_final_schema(dialect).is_err());
}
fn custom_dialect_annotated_schema() -> Value {
json!({
"$id": "https://schemas.example.test/annotated",
"$schema": "https://schemas.example.test/meta",
"$defs": {"meta": {
"$id": "https://schemas.example.test/meta",
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"$vocabulary": {
CORE_VOCABULARY_URI: true,
APPLICATOR_VOCABULARY_URI: true,
VALIDATION_VOCABULARY_URI: true
},
"type": "object",
"properties": {"default": {
"type": "object",
"properties": {"label": {"const": "approved"}},
"required": ["label"]
}},
"required": ["default"]
}},
"type": "object",
"properties": {"value": {"type": "integer"}},
"required": ["value"],
"default": {
"$id": "https://schemas.example.test/meta",
"label": "approved", "type": 17
}
})
}
#[test]
fn admitted_custom_dialect_meta_schema_positive() {
let source = custom_dialect_annotated_schema();
let admitted = admit_final_schema(source.clone()).unwrap();
assert_eq!(admitted.schema(), &source);
assert!(admitted.validate(&json!({"value": 3})).is_ok());
assert!(admitted.validate(&json!({"value": "3"})).is_err());
assert_eq!(admitted.schema()["default"]["type"], 17);
}
#[test]
fn admitted_custom_dialect_meta_schema_planted_negative() {
let source = custom_dialect_annotated_schema();
let admitted = admit_final_schema(source.clone()).unwrap();
let mut planted = source.clone();
let secret = "private-schema-default-canary";
planted["default"]["label"] = json!(secret);
let error = admit_final_schema(planted)
.expect_err("an annotation that violates the declared meta-schema must not admit");
assert_eq!(error.code(), "InvalidSchema");
assert_eq!(error.path(), "$.$schema");
assert_eq!(
error.reason(),
"schema does not satisfy its declared dialect"
);
assert!(!format!("{error} {error:?}").contains(secret));
assert_eq!(admitted.schema(), &source);
assert!(admitted.validate(&json!({"value": 3})).is_ok());
let mut rejecting_meta = source;
rejecting_meta["$defs"]["meta"]["const"] = json!(false);
assert_eq!(
admit_final_schema(rejecting_meta).unwrap_err().code(),
"InvalidSchema"
);
}
#[test]
fn admitted_custom_dialect_meta_references_keep_original_resource_scope() {
let source = json!({
"$id": "https://schemas.example.test/root",
"$schema": "https://schemas.example.test/meta",
"$defs": {
"meta": {
"$id": "meta", "$schema": FINAL_JSON_SCHEMA_DIALECT,
"$ref": "constraints#/$defs/rule"
},
"constraints": {
"$id": "constraints", "$schema": FINAL_JSON_SCHEMA_DIALECT,
"$defs": {"rule": {
"type": "object",
"properties": {"title": {"const": "approved"}},
"required": ["title"]
}}
}
},
"type": "object", "title": "approved"
});
let admitted = admit_final_schema(source.clone())
.expect("relative sibling resources resolve from the complete schema document");
assert_eq!(admitted.schema(), &source);
assert!(admitted.validate(&json!({})).is_ok());
let mut planted = source;
planted["title"] = json!("refused");
assert_eq!(
admit_final_schema(planted).unwrap_err().reason(),
"schema does not satisfy its declared dialect"
);
}
#[test]
fn admitted_custom_dialect_meta_constraints_follow_resource_inheritance() {
let source = json!({
"$id": "https://schemas.example.test/root",
"$schema": "https://schemas.example.test/meta",
"$defs": {"meta": {
"$id": "https://schemas.example.test/meta",
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": "object",
"properties": {"title": {"type": "string", "minLength": 3}},
"required": ["title"]
}},
"type": "object", "title": "root",
"properties": {"value": {
"$id": "child", "type": "integer", "title": "child"
}}
});
let admitted = admit_final_schema(source.clone()).unwrap();
assert!(admitted.validate(&json!({"value": 3})).is_ok());
let mut planted = source;
planted["properties"]["value"]["title"] = json!("x");
let error = admit_final_schema(planted.clone())
.expect_err("an embedded resource inherits its enclosing custom dialect");
assert_eq!(error.code(), "InvalidSchema");
assert_eq!(error.path(), "$.properties.value.$schema");
planted["properties"]["value"]["$schema"] = json!(FINAL_JSON_SCHEMA_DIALECT);
let reset = admit_final_schema(planted)
.expect("an explicit canonical dialect resets inherited meta constraints");
assert!(reset.validate(&json!({"value": 3})).is_ok());
assert!(reset.validate(&json!({"value": "3"})).is_err());
}
fn recursive_custom_dialect_schema(reference_keyword: &str) -> Value {
json!({
"$id": "https://schemas.example.test/root",
"$schema": "https://schemas.example.test/meta",
"$defs": {"meta": {
"$id": "https://schemas.example.test/meta",
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"$dynamicAnchor": "meta",
"type": "object",
"required": ["title"],
"properties": {"properties": {
"type": "object",
"additionalProperties": {reference_keyword: "#meta"}
}}
}},
"type": "object", "title": "root",
"properties": {"value": {
"$id": "child", "type": "integer", "title": "child"
}}
})
}
#[test]
fn admitted_custom_dialect_recursive_resource_boundaries_fail_closed() {
for reference_keyword in ["$ref", "$dynamicRef"] {
let source = recursive_custom_dialect_schema(reference_keyword);
let admitted = admit_final_schema(source.clone())
.expect("same-dialect resources support recursive meta validation");
assert_eq!(admitted.schema(), &source);
assert!(admitted.validate(&json!({"value": 3})).is_ok());
assert!(admitted.validate(&json!({"value": "3"})).is_err());
let mut mixed = source.clone();
mixed["properties"]["value"]["$schema"] = json!(FINAL_JSON_SCHEMA_DIALECT);
mixed["properties"]["value"]
.as_object_mut()
.unwrap()
.remove("title");
let error = admit_final_schema(mixed)
.expect_err("mixed-dialect recursive meta traversal is explicitly unsupported");
assert_eq!(error.code(), "UnsupportedSchemaDialect");
assert_eq!(error.path(), "$.$schema");
assert_eq!(
error.reason(),
"cross-dialect meta-schema traversal is unsupported"
);
let mut inherited = source;
inherited["properties"]["value"]
.as_object_mut()
.unwrap()
.remove("title");
assert_eq!(
admit_final_schema(inherited).unwrap_err().code(),
"InvalidSchema"
);
assert!(admitted.validate(&json!({"value": 3})).is_ok());
}
}
#[test]
fn admitted_custom_dialect_resource_boundary_refusal_survives_branch_probes() {
for branch_keyword in ["anyOf", "not"] {
let mut source = recursive_custom_dialect_schema("$dynamicRef");
source["properties"]["value"]["$schema"] = json!(FINAL_JSON_SCHEMA_DIALECT);
let meta = source["$defs"]["meta"].as_object_mut().unwrap();
let recursive_properties = meta.remove("properties").unwrap();
let probe = json!({"properties": recursive_properties});
meta.insert(
branch_keyword.to_owned(),
if branch_keyword == "anyOf" {
json!([probe, true])
} else {
probe
},
);
let error = admit_final_schema(source)
.expect_err("a speculative mismatch cannot authorize an unsupported traversal");
assert_eq!(error.code(), "UnsupportedSchemaDialect");
assert_eq!(
error.reason(),
"cross-dialect meta-schema traversal is unsupported"
);
}
let mut direct_false = recursive_custom_dialect_schema("$ref");
direct_false["properties"]["value"]["$schema"] = json!(FINAL_JSON_SCHEMA_DIALECT);
direct_false["$defs"]["meta"]["properties"]["properties"]["additionalProperties"] =
json!(false);
assert_eq!(
admit_final_schema(direct_false).unwrap_err().code(),
"InvalidSchema",
"resource identity must not bypass a literal rejecting constraint"
);
let mut limited = recursive_custom_dialect_schema("$ref");
limited["properties"]["value"]["$schema"] = json!(FINAL_JSON_SCHEMA_DIALECT);
let meta = limited["$defs"]["meta"].as_object_mut().unwrap();
let recursive_properties = meta.remove("properties").unwrap();
meta.insert(
"anyOf".to_owned(),
json!([
{"properties": recursive_properties},
{"$ref": "#"}
]),
);
assert_eq!(
admit_final_schema(limited).unwrap_err().code(),
"SchemaResourceLimit",
"exhausted work or recursion takes precedence over a crossed resource boundary"
);
}
#[test]
fn admitted_custom_dialect_self_description_does_not_reenter_admission() {
let source = json!({
"$id": "https://schemas.example.test/self-meta",
"$schema": "https://schemas.example.test/self-meta",
"type": "object",
"properties": {"type": {"const": "object"}},
"required": ["type"]
});
let admitted = admit_final_schema(source.clone())
.expect("a self-describing schema is one bounded meta-validation input");
assert_eq!(admitted.schema(), &source);
assert!(admitted.validate(&json!({"type": "object"})).is_ok());
assert!(admitted.validate(&json!({"type": "string"})).is_err());
}
#[test]
fn admitted_custom_dialect_meta_evaluation_cycles_fail_closed() {
let source = json!({
"$id": "https://schemas.example.test/root",
"$schema": "https://schemas.example.test/meta",
"$defs": {"meta": {
"$id": "https://schemas.example.test/meta",
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"$defs": {"rule": {"type": "object"}},
"$ref": "#/$defs/rule"
}},
"type": "object"
});
let admitted = admit_final_schema(source.clone()).unwrap();
assert!(admitted.validate(&json!({})).is_ok());
let mut planted = source;
planted["$defs"]["meta"]["$ref"] = json!("#");
let error = admit_final_schema(planted)
.expect_err("a meta-schema evaluation cycle cannot become successful admission");
assert_eq!(error.code(), "SchemaResourceLimit");
assert_eq!(error.path(), "$.$schema");
assert_eq!(
error.reason(),
"schema meta-validation resource limit exceeded"
);
assert!(admitted.validate(&json!({})).is_ok());
}
fn shared_meta_schema_resource_document(count: usize) -> Value {
let mut definitions = serde_json::Map::new();
for index in 0..count {
definitions.insert(
format!("item_{index:03}"),
json!({
"$id": format!("item_{index}"),
"$schema": "https://schemas.example.test/shared-meta",
"type": "object"
}),
);
}
definitions.insert(
"zz_meta".to_owned(),
json!({
"$id": "https://schemas.example.test/shared-meta",
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": "object"
}),
);
json!({
"$id": "https://schemas.example.test/root",
"type": "object",
"$defs": definitions
})
}
#[test]
fn admitted_custom_dialect_meta_resources_share_one_work_budget() {
let admitted = admit_final_schema(shared_meta_schema_resource_document(60))
.expect("bounded custom resources fit the shared lookup and validation budget");
assert!(admitted.validate(&json!({})).is_ok());
let error = admit_final_schema(shared_meta_schema_resource_document(61))
.expect_err("resource fan-out must not refresh the meta-validation budget");
assert_eq!(error.code(), "SchemaResourceLimit");
assert!(admitted.validate(&json!({})).is_ok());
}
#[test]
fn custom_dialect_keyword_policy_is_inherited_until_canonical_resource_reset() {
let source = json!({
"$id": "https://schemas.example/root",
"$schema": "https://schemas.example/meta",
"$defs": {"meta": {
"$id": "https://schemas.example/meta",
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"$vocabulary": {CORE_VOCABULARY_URI: true, VALIDATION_VOCABULARY_URI: true}
}},
"type": "object",
"properties": {"value": {
"$id": "child",
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": "integer", "x-ui": {"type": 17}
}}
});
let admitted = admit_final_schema(source.clone()).unwrap();
assert!(admitted.validate(&json!({"value": 3})).is_ok());
assert!(admitted.validate(&json!({"value": "3"})).is_err());
let mut inherited = source.clone();
inherited["properties"]["value"]
.as_object_mut()
.unwrap()
.remove("$schema");
let error = admit_final_schema(inherited).unwrap_err();
assert_eq!(error.path(), "$.properties.value.x-ui");
let mut root_annotation = source;
root_annotation["x-ui"] = json!(true);
assert_eq!(
admit_final_schema(root_annotation).unwrap_err().path(),
"$.x-ui"
);
}
#[test]
fn opaque_annotations_share_document_byte_node_and_depth_bounds() {
let overhead = serde_json::to_vec(&json!({"x-note": ""})).unwrap().len();
let source = json!({"x-note": "x".repeat(MAX_SCHEMA_DOCUMENT_BYTES - overhead)});
assert_eq!(
serde_json::to_vec(&source).unwrap().len(),
MAX_SCHEMA_DOCUMENT_BYTES
);
assert!(admit_final_schema(source.clone()).is_ok());
let mut oversized = source;
oversized["x-note"] = json!("x".repeat(MAX_SCHEMA_DOCUMENT_BYTES - overhead + 1));
assert_eq!(
admit_final_schema(oversized).unwrap_err().reason(),
"schema document byte limit exceeded"
);
let mut wide = json!({"x-data": vec![Value::Null; MAX_SCHEMA_DOCUMENT_NODES - 2]});
assert!(admit_final_schema(wide.clone()).is_ok());
wide["x-data"].as_array_mut().unwrap().push(Value::Null);
assert_eq!(
admit_final_schema(wide).unwrap_err().reason(),
"schema document node limit exceeded"
);
let mut nested = Value::Null;
for _ in 0..MAX_SCHEMA_VALIDATION_DEPTH - 2 {
nested = Value::Array(vec![nested]);
}
assert!(admit_final_schema(json!({"x-data": nested.clone()})).is_ok());
assert_eq!(
admit_final_schema(json!({"x-data": [nested]}))
.unwrap_err()
.reason(),
"schema document nesting limit exceeded"
);
}
#[test]
fn reserved_deprecated_keywords_do_not_become_unchecked_custom_annotations() {
for keyword in [
"definitions",
"dependencies",
"$recursiveAnchor",
"$recursiveRef",
] {
let mut source = json!({"type": "integer", "x-ui": {"type": 17}});
source[keyword] = json!(17);
assert!(admit_final_schema(source).is_err());
}
}
#[test]
fn admitted_dependencies_property_lists_preserve_default_dialect_semantics() {
let source = json!({
"dependencies": {
"trigger": ["first", "second"],
"empty": [],
"line\nbreak": ["line\rbreak"],
"double\"quote": ["single'quote"]
}
});
for explicit_dialect in [false, true] {
let mut source = source.clone();
if explicit_dialect {
source["$schema"] = json!(FINAL_JSON_SCHEMA_DIALECT);
}
let admitted = admit_final_schema(source.clone()).unwrap();
for value in [
json!({}),
json!({"first": 1, "second": 2}),
json!({"trigger": null, "first": 1, "second": 2}),
json!({"empty": null}),
json!({"line\nbreak": 1, "line\rbreak": 2}),
json!({"double\"quote": 1, "single'quote": 2}),
json!(["trigger"]),
json!("trigger"),
json!(12),
Value::Null,
] {
assert!(admitted.validate(&value).is_ok(), "{value:?}");
}
for value in [
json!({"trigger": 1}),
json!({"trigger": 1, "first": 2}),
json!({"trigger": 1, "second": 2}),
json!({"line\nbreak": 1}),
json!({"double\"quote": 1}),
] {
assert!(admitted.validate(&value).is_err(), "{value:?}");
}
assert_eq!(admitted.schema(), &source);
}
}
#[test]
fn admitted_dependencies_schema_alternatives_validate_the_containing_object() {
let source = json!({
"dependencies": {
"trigger": {
"properties": {"value": {"type": "integer"}},
"required": ["value"]
},
"allowed": true,
"forbidden": false,
"many": {"minProperties": 3}
},
"dependentRequired": {"trigger": ["other"]},
"dependentSchemas": {"trigger": {"properties": {"value": {"minimum": 2}}}}
});
let admitted = admit_final_schema(source.clone()).unwrap();
for value in [
json!({}),
json!({"allowed": 1}),
json!({"value": "not triggered"}),
json!({"trigger": false, "value": 2, "other": null}),
json!({"many": 1, "a": 2, "b": 3}),
json!(["trigger"]),
json!("trigger"),
json!(12),
] {
assert!(admitted.validate(&value).is_ok(), "{value:?}");
}
for value in [
json!({"forbidden": 1}),
json!({"allowed": 1, "forbidden": 2}),
json!({"trigger": {"value": 2}, "other": null}),
json!({"trigger": false, "value": "2", "other": null}),
json!({"trigger": false, "value": 1, "other": null}),
json!({"trigger": false, "value": 2}),
json!({"many": 1, "a": 2}),
] {
assert!(admitted.validate(&value).is_err(), "{value:?}");
}
assert_eq!(admitted.schema(), &source);
}
#[test]
fn admitted_dependencies_only_successful_schemas_evaluate_properties() {
let source = json!({
"anyOf": [
{
"required": ["trigger"],
"properties": {"trigger": true},
"dependencies": {"trigger": {
"properties": {"value": {"type": "integer"}},
"required": ["value"]
}}
},
{"properties": {"trigger": true}, "required": ["trigger"]}
],
"unevaluatedProperties": false
});
let admitted = admit_final_schema(source.clone()).unwrap();
assert!(
admitted
.validate(&json!({"trigger": 1, "value": 2}))
.is_ok()
);
assert!(admitted.validate(&json!({"trigger": 1})).is_ok());
for value in [
json!({"trigger": 1, "value": "2"}),
json!({"trigger": 1, "value": 2, "extra": true}),
json!({"value": 2}),
] {
assert!(admitted.validate(&value).is_err(), "{value:?}");
}
let lists = admit_final_schema(json!({
"properties": {"trigger": true},
"dependencies": {"trigger": ["value"]},
"unevaluatedProperties": false
}))
.unwrap();
assert!(lists.validate(&json!({})).is_ok());
assert!(lists.validate(&json!({"trigger": 1, "value": 2})).is_err());
assert_eq!(admitted.schema(), &source);
}
#[test]
fn admitted_dependencies_preserve_reference_resource_and_anchor_scopes() {
let source = json!({
"$id": "https://schemas.example/root",
"dependencies": {"trigger": {
"$id": "rules/",
"$ref": "child#record",
"dependencies": {"unused": {
"$id": "child",
"$anchor": "record",
"properties": {"value": {"type": "integer"}},
"required": ["value"]
}}
}}
});
let admitted = admit_final_schema(source.clone()).unwrap();
assert!(
admitted
.validate(&json!({"trigger": 1, "value": 2}))
.is_ok()
);
assert!(
admitted
.validate(&json!({"trigger": 1, "value": "2"}))
.is_err()
);
let mut wrong_scope = source;
wrong_scope["dependencies"]["trigger"]["$ref"] = json!("#record");
assert_eq!(
admit_final_schema(wrong_scope).unwrap_err().reason(),
"unresolved local schema reference"
);
for reference in ["#/dependencies/rule", "#integer"] {
let admitted = admit_final_schema(json!({
"$ref": reference,
"dependencies": {"rule": {"$anchor": "integer", "type": "integer"}}
}))
.unwrap();
assert!(admitted.validate(&json!(2)).is_ok());
assert!(admitted.validate(&json!("2")).is_err());
}
let dynamic = admit_final_schema(json!({
"$dynamicRef": "#integer",
"dependencies": {"rule": {"$dynamicAnchor": "integer", "type": "integer"}}
}))
.unwrap();
assert!(dynamic.validate(&json!(2)).is_ok());
assert!(dynamic.validate(&json!("2")).is_err());
let recursive = admit_final_schema(json!({
"type": "object",
"properties": {"next": {"$ref": "#"}},
"dependencies": {"next": ["value"]}
}))
.unwrap();
assert!(
recursive
.validate(&json!({"next": {"value": 2}, "value": 1}))
.is_ok()
);
assert!(
recursive
.validate(&json!({"next": {"next": {}}, "value": 1}))
.is_err()
);
}
#[test]
fn admitted_dependencies_reject_malformed_lists_schemas_and_authorities() {
for dependencies in [
Value::Null,
json!([]),
json!(true),
json!({"trigger": 17}),
json!({"trigger": "value"}),
json!({"trigger": [1]}),
json!({"trigger": ["value", "value"]}),
json!({"trigger": [{"$id": "https://schemas.example/hidden"}]}),
json!({"trigger": {"type": 17}}),
] {
assert!(admit_final_schema(json!({"dependencies": dependencies})).is_err());
}
let invalid_reference = json!({
"$ref": "#/dependencies/trigger",
"dependencies": {"trigger": ["value"]}
});
assert_eq!(
admit_final_schema(invalid_reference).unwrap_err().reason(),
"local schema reference target must be an object or boolean"
);
for keyword in ["$ref", "$dynamicRef"] {
let unresolved = json!({"dependencies": {"unused": {
keyword: "https://unregistered.example/schema"
}}});
assert_eq!(
admit_final_schema(unresolved).unwrap_err().reason(),
"external schema reference is not allowed"
);
}
for keyword in ["$anchor", "$dynamicAnchor", "$id"] {
let (first, second) = if keyword == "$id" {
(
"https://schemas.example/first",
"https://schemas.example/second",
)
} else {
("first", "second")
};
let source = json!({
"$defs": {"modern": {keyword: first}},
"dependencies": {"trigger": {keyword: second}}
});
assert!(admit_final_schema(source.clone()).is_ok());
let mut duplicate = source;
duplicate["dependencies"]["trigger"][keyword] = json!(first);
let error = admit_final_schema(duplicate).unwrap_err();
assert_eq!(error.path(), format!("$.dependencies.trigger.{keyword}"));
assert!(error.reason().starts_with("duplicate local schema"));
}
}
#[test]
fn admitted_dependencies_preserve_custom_dialect_and_form_boundaries() {
let source = json!({
"$id": "https://schemas.example/root",
"$schema": "https://schemas.example/meta",
"$defs": {"meta": {
"$id": "https://schemas.example/meta",
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"$vocabulary": {CORE_VOCABULARY_URI: true, VALIDATION_VOCABULARY_URI: true}
}},
"properties": {"value": {
"$id": "child",
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"dependencies": {"trigger": ["required"]}
}}
});
let admitted = admit_final_schema(source.clone()).unwrap();
assert!(
admitted
.validate(&json!({"value": {"trigger": 1, "required": 2}}))
.is_ok()
);
assert!(
admitted
.validate(&json!({"value": {"trigger": 1}}))
.is_err()
);
let mut inherited = source;
inherited["properties"]["value"]
.as_object_mut()
.unwrap()
.remove("$schema");
assert_eq!(
admit_final_schema(inherited).unwrap_err().path(),
"$.properties.value.dependencies"
);
let form = json!({
"type": "object",
"properties": {"trigger": {"type": "integer"}, "value": {"type": "integer"}},
"dependencies": {"trigger": ["value"]}
});
assert!(admit_final_form_schema(form.clone()).is_ok());
for at_root in [true, false] {
let mut nested = form.clone();
let target = if at_root {
&mut nested
} else {
&mut nested["properties"]["value"]
};
target["dependencies"] = json!({"trigger": {"required": ["value"]}});
assert!(admit_final_schema(nested.clone()).is_ok());
assert!(admit_final_form_schema(nested).is_err());
}
}
#[test]
fn admitted_dependencies_enforce_entry_string_and_aggregate_work_limits() {
let members: Vec<Value> = (0..MAX_SCHEMA_ASSERTION_ENTRIES)
.map(|index| json!(format!("field-{index}")))
.collect();
let source = json!({"dependencies": {"trigger": members}});
let admitted = admit_final_schema(source.clone()).unwrap();
let mut instance = object_with_null_members(MAX_SCHEMA_ASSERTION_ENTRIES);
instance["trigger"] = Value::Null;
assert!(admitted.validate(&instance).is_ok());
let mut too_many = source;
too_many["dependencies"]["trigger"]
.as_array_mut()
.unwrap()
.push(json!("extra"));
assert_eq!(
admit_final_schema(too_many).unwrap_err().reason(),
"dependencies property list exceeds entry limit"
);
let entries: serde_json::Map<String, Value> = (0..MAX_SCHEMA_ASSERTION_ENTRIES)
.map(|index| (format!("trigger-{index}"), Value::Bool(true)))
.collect();
let mut source = json!({"dependencies": entries});
assert!(admit_final_schema(source.clone()).is_ok());
source["dependencies"]["extra"] = Value::Bool(true);
assert_eq!(
admit_final_schema(source).unwrap_err().reason(),
"dependencies exceeds entry limit"
);
for list_member in [false, true] {
let bounded = "x".repeat(MAX_SCHEMA_ASSERTION_STRING_BYTES);
let source = if list_member {
json!({"dependencies": {"trigger": [bounded]}})
} else {
json!({"dependencies": {bounded: []}})
};
assert!(admit_final_schema(source).is_ok());
let oversized = "x".repeat(MAX_SCHEMA_ASSERTION_STRING_BYTES + 1);
let source = if list_member {
json!({"dependencies": {"trigger": [oversized]}})
} else {
json!({"dependencies": {oversized: []}})
};
assert!(admit_final_schema(source).is_err());
}
let mut dependencies = serde_json::Map::new();
for index in 0..MAX_SCHEMA_ASSERTION_ENTRIES {
let count = if index == 0 {
MAX_SCHEMA_ASSERTION_ENTRIES - 2
} else {
MAX_SCHEMA_ASSERTION_ENTRIES - 1
};
dependencies.insert(
format!("trigger-{index}"),
Value::Array(
(0..count)
.map(|member| json!(format!("field-{member}")))
.collect(),
),
);
}
let mut source = json!({"dependencies": dependencies});
assert!(admit_final_schema(source.clone()).is_ok());
source["dependencies"]["trigger-0"]
.as_array_mut()
.unwrap()
.push(json!("extra"));
assert_eq!(
admit_final_schema(source).unwrap_err().reason(),
"dependencies exceeds validation work budget"
);
}
#[test]
fn admitted_dependencies_share_schema_node_and_runtime_work_budgets() {
let children: serde_json::Map<String, Value> = (0..MAX_SCHEMA_ASSERTION_ENTRIES)
.map(|index| (format!("child-{index}"), Value::Bool(true)))
.collect();
let entries: serde_json::Map<String, Value> = (0..MAX_SCHEMA_ASSERTION_ENTRIES - 1)
.map(|index| {
(
format!("trigger-{index}"),
json!({"dependencies": children}),
)
})
.collect();
let mut source = json!({"dependencies": entries});
assert!(admit_final_schema(source.clone()).is_ok());
source["dependencies"]["extra"] = json!({"dependencies": children});
assert_eq!(
admit_final_schema(source).unwrap_err().reason(),
"schema admission node limit exceeded"
);
let members: Vec<Value> = (0..MAX_SCHEMA_ASSERTION_ENTRIES)
.map(|index| json!(format!("field-{index}")))
.collect();
let dependency = json!({"dependencies": {"trigger": members}});
let mut instance = object_with_null_members(MAX_SCHEMA_ASSERTION_ENTRIES);
instance["trigger"] = Value::Null;
let bounded = admit_final_schema(json!({"allOf": vec![dependency.clone(); 16]})).unwrap();
assert!(bounded.validate(&instance).is_ok());
let excessive =
admit_final_schema(json!({"allOf": vec![dependency; MAX_COMPOSITION_BRANCHES]}))
.unwrap();
let errors = excessive.validate(&instance).unwrap_err();
assert!(
errors
.iter()
.any(|error| error.message == "schema validation work limit exceeded")
);
}
#[test]
fn dependencies_remain_safe_in_handwritten_generation_and_strict_validation() {
let source = json!({
"$id": "https://schemas.example/handwritten",
"dependencies": {"trigger": {
"type": "object",
"properties": {"trigger": true, "value": {"type": "integer"}},
"required": ["value"]
}}
});
assert_eq!(
SchemaGenerator::new().finish(source.clone()).unwrap(),
source
);
assert!(validate_strict(&source, &json!({"trigger": 1, "value": 2})).is_ok());
assert!(
validate_strict(&source, &json!({"trigger": 1, "value": 2, "extra": true})).is_err()
);
let mut generator = SchemaGenerator::new();
assert_eq!(
generator.inline_schema(json!({"dependencies": {"trigger": {"$ref": "#"}}})),
Value::Bool(false)
);
assert_eq!(
generator.finish(json!({})),
Err(SchemaGenerationError::ReferenceResourceBoundary)
);
let mut generator = SchemaGenerator::new();
let first = generator.subschema_for::<GeneratedText>();
let reused = generator.subschema_for::<GeneratedText>();
let root = json!({
"properties": {"first": first},
"dependencies": {"trigger": {"$id": "https://schemas.example/nested", "allOf": [reused]}}
});
assert_eq!(
generator.finish(root),
Err(SchemaGenerationError::ReferenceResourceBoundary)
);
}
#[test]
fn admitted_definitions_preserve_spelling_and_enforce_referenced_tool_arguments() {
let source = json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": "object",
"definitions": {
"id/~value": {"type": "integer", "minimum": 3},
"unused": false
},
"$defs": {"id/~value": {"type": "string", "minLength": 2}},
"properties": {
"id": {"$ref": "#/definitions/id~1~0value"},
"label": {"$ref": "#/$defs/id~1~0value"}
},
"required": ["id", "label"],
"additionalProperties": false
});
let admitted = admit_final_schema(source.clone()).expect("both definition maps admit");
assert_eq!(admitted.schema(), &source);
assert!(admitted.validate(&json!({"id": 3, "label": "ok"})).is_ok());
for invalid in [
json!({"id": 2, "label": "ok"}),
json!({"id": "3", "label": "ok"}),
json!({"id": 3, "label": "x"}),
json!({"id": 3, "label": 3}),
] {
assert!(admitted.validate(&invalid).is_err());
}
assert_eq!(admitted.schema(), &source);
let mut default_dialect = source;
default_dialect.as_object_mut().unwrap().remove("$schema");
assert!(
admit_final_schema(default_dialect)
.unwrap()
.validate(&json!({"id": 3, "label": "ok"}))
.is_ok()
);
}
#[test]
fn admitted_definitions_are_reserved_schemas_without_implicit_application() {
let source = json!({"definitions": {"accept": true, "reject": false}});
let admitted = admit_final_schema(source.clone()).unwrap();
assert!(admitted.validate(&Value::Null).is_ok());
for (target, valid) in [("accept", true), ("reject", false)] {
let mut referenced = source.clone();
referenced["$ref"] = json!(format!("#/definitions/{target}"));
let admitted = admit_final_schema(referenced).unwrap();
assert_eq!(admitted.validate(&Value::Null).is_ok(), valid);
}
let mut annotation = source;
annotation["default"] = json!({"definitions": {"hidden": true}});
annotation["$ref"] = json!("#/default/definitions/hidden");
assert_eq!(
admit_final_schema(annotation).unwrap_err().reason(),
"local schema reference target is not an admitted schema node"
);
}
#[test]
fn admitted_definitions_preserve_nested_resource_and_anchor_resolution() {
let source = json!({
"$id": "https://schemas.example/root",
"$ref": "nested/",
"definitions": {"outer": {
"$id": "nested/",
"$ref": "child#value",
"definitions": {"child": {
"$id": "child",
"definitions": {"value": {
"$anchor": "value", "type": "integer", "minimum": 3
}}
}}
}}
});
let admitted = admit_final_schema(source.clone()).unwrap();
assert!(admitted.validate(&json!(3)).is_ok());
assert!(admitted.validate(&json!(2)).is_err());
let mut wrong_scope = source;
wrong_scope["definitions"]["outer"]["$ref"] = json!("#value");
assert_eq!(
admit_final_schema(wrong_scope).unwrap_err().reason(),
"unresolved local schema reference"
);
let dynamic = admit_final_schema(json!({
"$dynamicRef": "#value",
"definitions": {"value": {"$dynamicAnchor": "value", "type": "boolean"}}
}))
.unwrap();
assert!(dynamic.validate(&json!(true)).is_ok());
assert!(dynamic.validate(&json!("true")).is_err());
}
#[test]
fn admitted_definitions_reject_malformed_children_and_duplicate_authorities() {
for definitions in [Value::Null, json!([]), json!(true), json!({"value": 17})] {
assert!(admit_final_schema(json!({"definitions": definitions})).is_err());
}
let source = json!({"definitions": {"value": {"type": "integer"}}});
assert!(admit_final_schema(source.clone()).is_ok());
let mut malformed = source;
malformed["definitions"]["value"]["type"] = json!(17);
assert_eq!(
admit_final_schema(malformed).unwrap_err().path(),
"$.definitions.value.type"
);
for keyword in ["$ref", "$dynamicRef"] {
let unresolved = json!({"definitions": {"value": {
keyword: "https://unregistered.example/schema"
}}});
assert_eq!(
admit_final_schema(unresolved).unwrap_err().reason(),
"external schema reference is not allowed"
);
}
for keyword in ["$anchor", "$dynamicAnchor", "$id"] {
let (first, second) = if keyword == "$id" {
(
"https://schemas.example/first",
"https://schemas.example/second",
)
} else {
("first", "second")
};
let source = json!({
"$defs": {"modern": {keyword: first}},
"definitions": {"older": {keyword: second}}
});
assert!(admit_final_schema(source.clone()).is_ok());
let mut duplicate = source;
duplicate["definitions"]["older"][keyword] = json!(first);
let error = admit_final_schema(duplicate).unwrap_err();
assert_eq!(error.path(), format!("$.definitions.older.{keyword}"));
assert!(error.reason().starts_with("duplicate local schema"));
}
}
#[test]
fn admitted_definitions_obey_custom_dialect_and_form_boundaries() {
let source = json!({
"$id": "https://schemas.example/root",
"$schema": "https://schemas.example/meta",
"$defs": {"meta": {
"$id": "https://schemas.example/meta",
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"$vocabulary": {CORE_VOCABULARY_URI: true, VALIDATION_VOCABULARY_URI: true}
}},
"type": "object",
"properties": {"value": {
"$id": "child",
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"definitions": {"integer": {"type": "integer"}},
"$ref": "#/definitions/integer"
}}
});
let admitted = admit_final_schema(source.clone()).unwrap();
assert!(admitted.validate(&json!({"value": 3})).is_ok());
assert!(admitted.validate(&json!({"value": "3"})).is_err());
let mut inherited = source;
inherited["properties"]["value"]
.as_object_mut()
.unwrap()
.remove("$schema");
assert_eq!(
admit_final_schema(inherited).unwrap_err().path(),
"$.properties.value.definitions"
);
let form = json!({"type": "object", "properties": {"value": {"type": "integer"}}});
assert!(admit_final_form_schema(form.clone()).is_ok());
for at_root in [true, false] {
let mut nested = form.clone();
let target = if at_root {
&mut nested
} else {
&mut nested["properties"]["value"]
};
target["definitions"] = json!({"value": {"type": "integer"}});
assert!(admit_final_schema(nested.clone()).is_ok());
assert!(admit_final_form_schema(nested).is_err());
}
}
#[test]
fn admitted_definitions_share_schema_node_and_reference_work_bounds() {
let entries: serde_json::Map<String, Value> = (0..MAX_SCHEMA_ADMISSION_NODES - 1)
.map(|index| (format!("value_{index:04}"), Value::Bool(true)))
.collect();
for keyword in ["$defs", "definitions"] {
let source = json!({keyword: entries});
assert!(admit_final_schema(source.clone()).is_ok());
let mut excessive = source;
excessive[keyword]["extra"] = Value::Bool(true);
assert_eq!(
admit_final_schema(excessive).unwrap_err().reason(),
"schema admission node limit exceeded"
);
}
let mut nested = Value::Bool(true);
for _ in 0..(MAX_SCHEMA_VALIDATION_DEPTH - 1) / 2 {
nested = json!({"definitions": {"child": nested}});
}
assert!(admit_final_schema(nested.clone()).is_ok());
assert_eq!(
admit_final_schema(json!({"definitions": {"child": nested}}))
.unwrap_err()
.reason(),
"schema document nesting limit exceeded"
);
let mut entries: serde_json::Map<String, Value> = (0..MAX_SCHEMA_VALIDATION_WORK - 6)
.map(|index| (format!("unused_{index:04}"), Value::Bool(false)))
.collect();
entries.insert(
"zz_target".to_owned(),
json!({"$anchor": "target", "type": "boolean"}),
);
let source = json!({"definitions": entries, "$ref": "#target"});
let admitted = admit_final_schema(source.clone()).unwrap();
assert!(admitted.validate(&json!(true)).is_ok());
let mut excessive = source.clone();
excessive["definitions"]["unused_extra"] = Value::Bool(false);
let errors = admit_final_schema(excessive)
.unwrap()
.validate(&json!(true))
.unwrap_err();
assert!(
errors
.iter()
.any(|error| error.message == "schema validation work limit exceeded")
);
assert_eq!(admitted.schema(), &source);
}
#[test]
fn definitions_remain_safe_in_handwritten_generation_and_strict_validation() {
let source = json!({
"$id": "https://schemas.example/handwritten",
"definitions": {"record": {
"type": "object", "properties": {"value": {"type": "integer"}},
"required": ["value"]
}},
"$ref": "#/definitions/record"
});
assert_eq!(
SchemaGenerator::new().finish(source.clone()).unwrap(),
source
);
assert!(validate_strict(&source, &json!({"value": 3})).is_ok());
assert!(validate_strict(&source, &json!({"value": 3, "extra": true})).is_err());
let mut unscoped = source;
unscoped.as_object_mut().unwrap().remove("$id");
unscoped.as_object_mut().unwrap().remove("$ref");
unscoped["definitions"]["alias"] = json!({"$ref": "#/definitions/record"});
let mut generator = SchemaGenerator::new();
assert_eq!(generator.inline_schema(unscoped), Value::Bool(false));
assert_eq!(
generator.finish(json!({})),
Err(SchemaGenerationError::ReferenceResourceBoundary)
);
let mut generator = SchemaGenerator::new();
let first = generator.subschema_for::<GeneratedText>();
let reused = generator.subschema_for::<GeneratedText>();
let root = json!({
"type": "object", "properties": {"first": first},
"definitions": {"nested": {
"$id": "https://schemas.example/nested", "allOf": [reused]
}}
});
assert_eq!(
generator.finish(root),
Err(SchemaGenerationError::ReferenceResourceBoundary)
);
}
#[test]
fn admitted_schema_accepts_declared_vocabulary_local_resources_and_content_annotations() {
let schema = admit_final_schema(json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"$id": "https://schemas.example.test/root",
"$vocabulary": {
CORE_VOCABULARY_URI: true,
APPLICATOR_VOCABULARY_URI: true,
VALIDATION_VOCABULARY_URI: true,
CONTENT_VOCABULARY_URI: true,
"urn:example:optional-extension": false
},
"type": "object",
"properties": {
"payload": {"$ref": "https://schemas.example.test/payload"}
},
"required": ["payload"],
"$defs": {
"payload": {
"$id": "https://schemas.example.test/payload",
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"$vocabulary": {
CORE_VOCABULARY_URI: true,
CONTENT_VOCABULARY_URI: true
},
"type": "string",
"contentEncoding": "base64",
"contentMediaType": "application/json",
"contentSchema": {
"type": "object",
"required": ["ok"],
"properties": {"ok": {"type": "boolean"}}
}
}
}
}))
.expect("declared supported vocabularies and local resources admit");
schema
.validate(&json!({"payload": "this is deliberately not base64"}))
.expect("content annotations do not decode or validate instance strings");
}
#[test]
fn admitted_schema_rejects_duplicate_and_undeclared_local_resource_ids() {
let accepted = json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"$id": "https://schemas.example.test/root",
"$defs": {
"payload": {
"$id": "https://schemas.example.test/payload",
"type": "string"
},
"other": {
"$id": "https://schemas.example.test/other",
"type": "string"
}
},
"$ref": "https://schemas.example.test/payload"
});
admit_final_schema(accepted.clone())
.expect("a unique declared resource satisfies an absolute local reference");
let mut duplicate = accepted.clone();
duplicate["$defs"]["other"]["$id"] = json!("https://schemas.example.test/root");
let duplicate_error = admit_final_schema(duplicate)
.expect_err("changing only the resource id to a duplicate rejects");
assert_eq!(duplicate_error.path(), "$.$defs.other.$id");
assert_eq!(
duplicate_error.reason(),
"duplicate local schema resource identifier"
);
let mut undeclared = accepted;
undeclared["$ref"] = json!("https://schemas.example.test/not-declared");
let reference_error = admit_final_schema(undeclared)
.expect_err("undeclared URI references cannot trigger retrieval");
assert_eq!(reference_error.path(), "$.$ref");
assert_eq!(
reference_error.reason(),
"external schema reference is not allowed"
);
}
#[test]
fn admitted_schema_rejects_invalid_resource_id_with_a_near_identical_fixture() {
let accepted = json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"$id": "urn:example:bounded-schema",
"type": "string"
});
admit_final_schema(accepted.clone()).expect("a bounded absolute resource id admits");
let mut planted = accepted;
planted["$id"] = json!("relative-schema");
let error = admit_final_schema(planted)
.expect_err("changing only the id to a relative URI rejects");
assert_eq!(error.path(), "$.$id");
assert_eq!(
error.reason(),
"schema $id must resolve to a bounded absolute URI"
);
let fragmented = json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"$id": "urn:example:bounded-schema#fragment",
"type": "string"
});
let fragment_error =
admit_final_schema(fragmented).expect_err("changing only the id fragment rejects");
assert_eq!(fragment_error.path(), "$.$id");
assert_eq!(
fragment_error.reason(),
"schema $id must not contain a fragment"
);
}
#[test]
fn ordinary_schema_vocabulary_is_ignored_and_meta_schema_vocabulary_is_a_dialect_gate() {
let accepted = json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"$vocabulary": {
"not-a-uri": "not-a-boolean"
},
"type": "string"
});
admit_final_schema(accepted)
.expect("ordinary-schema $vocabulary does not select or gate a dialect");
let meta_schema = json!({
"$id": "https://schemas.example.test/meta",
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"$vocabulary": {
CORE_VOCABULARY_URI: true,
"urn:example:unsupported": true
}
});
let schema = json!({
"$id": "https://schemas.example.test/root",
"$schema": "https://schemas.example.test/meta",
"$defs": {"meta": meta_schema},
"type": "string"
});
let error = admit_final_schema(schema).expect_err(
"only a selected meta-schema vocabulary can reject an unsupported requirement",
);
assert_eq!(error.path(), "$.$vocabulary[\"urn:example:unsupported\"]");
assert_eq!(
error.reason(),
"required schema vocabulary is not supported"
);
}
#[test]
fn schema_dialect_must_be_absolute_with_a_one_value_negative() {
let accepted = json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": "string"
});
admit_final_schema(accepted.clone()).expect("the canonical absolute dialect admits");
let mut planted = accepted.clone();
planted["$schema"] = json!("meta/validation");
let error = admit_final_schema(planted)
.expect_err("changing only the dialect to a relative identifier must reject");
assert_eq!(error.path(), "$.$schema");
assert_eq!(
error.reason(),
"schema dialect must be a bounded absolute URI"
);
assert_eq!(accepted["$schema"], json!(FINAL_JSON_SCHEMA_DIALECT));
}
#[test]
fn admitted_schema_scopes_relative_ids_anchors_and_inner_local_references() {
let accepted = json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"$id": "https://schemas.example.test/catalog/root.json",
"$anchor": "outer",
"type": "object",
"properties": {
"outer": {"$ref": "resources/outer.json#outer"}
},
"required": ["outer"],
"$defs": {
"outer": {
"$id": "resources/outer.json",
"$anchor": "outer",
"type": "object",
"properties": {
"value": {"$ref": "#integer"},
"nested": {"$ref": "nested.json#nested"}
},
"required": ["value", "nested"],
"$defs": {
"integer": {"$anchor": "integer", "type": "integer"},
"nested": {
"$id": "nested.json",
"$anchor": "nested",
"type": "string"
}
}
}
}
});
let schema = admit_final_schema(accepted.clone())
.expect("relative ids and resource-scoped anchors admit");
schema
.validate(&json!({"outer": {"value": 7, "nested": "ready"}}))
.expect("inner local and relative references resolve from the owning resource");
let mut planted = accepted;
planted["$defs"]["outer"]["properties"]["value"]["$ref"] = json!("#root-only");
let error = admit_final_schema(planted)
.expect_err("changing only an inner reference to an outer anchor rejects");
assert_eq!(error.path(), "$.$defs.outer.properties.value.$ref");
assert_eq!(error.reason(), "unresolved local schema reference");
}
#[test]
fn relative_resource_ids_resolve_from_authority_only_and_query_bases() {
for base in [
"https://schemas.example.test",
"https://schemas.example.test?catalog=bounded",
] {
let schema = admit_final_schema(json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"$id": base,
"$defs": {
"child": {
"$id": "child.json",
"type": "string",
"const": "ready"
}
},
"$ref": "child.json"
}))
.expect("a relative child resource resolves below an authority-only base");
schema
.validate(&json!("ready"))
.expect("the authority-relative child reference reaches its local resource");
}
}
#[test]
fn authorityless_schema_resources_preserve_nested_reference_scopes() {
for base in [
"file:/schemas/root.json?edition=1",
"schema:/schemas/root.json?edition=1",
"schema:schemas/root.json?edition=1",
] {
let source = json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"$id": base,
"$anchor": "rootOnly",
"$defs": {
"outer": {
"$id": "objects/outer.json",
"$anchor": "outer",
"type": "object",
"properties": {
"local": {"$ref": "#value"},
"relative": {"$ref": "inner.json#inner"},
"root": {"$ref": "/shared.json#shared"},
"query": {"$ref": "?revision=2#revision"}
},
"required": ["local", "relative", "root", "query"],
"$defs": {
"value": {"$anchor": "value", "type": "integer"},
"inner": {
"$id": "inner.json",
"$anchor": "inner",
"type": "string"
},
"query": {
"$id": "?revision=2",
"$anchor": "revision",
"type": "boolean"
}
}
},
"shared": {
"$id": "/shared.json",
"$anchor": "shared",
"const": "shared"
}
},
"$ref": "objects/outer.json#outer"
});
let admitted = admit_final_schema(source.clone())
.expect("bundled authorityless resources admit without external I/O");
let instance = json!({
"local": 7, "relative": "ready", "root": "shared", "query": true
});
admitted
.validate(&instance)
.expect("nested, rooted, query-only and fragment references retain their scopes");
let mut wrong_instance = instance;
wrong_instance["query"] = json!("not a boolean");
assert!(
admitted.validate(&wrong_instance).is_err(),
"the query-selected resource must actually enforce its schema"
);
assert_eq!(admitted.schema(), &source);
let mut wrong_scope = source.clone();
wrong_scope["$defs"]["outer"]["properties"]["local"]["$ref"] = json!("#rootOnly");
let error = admit_final_schema(wrong_scope)
.expect_err("an inner fragment cannot escape to an outer resource's anchor");
assert_eq!(error.path(), "$.$defs.outer.properties.local.$ref");
assert_eq!(error.reason(), "unresolved local schema reference");
let mut missing = source.clone();
missing["$ref"] = json!("objects/missing.json#outer");
let error = admit_final_schema(missing)
.expect_err("an unbundled file or custom resource is never loaded externally");
assert_eq!(error.path(), "$.$ref");
assert_eq!(error.reason(), "external schema reference is not allowed");
let mut wrong_query = source.clone();
wrong_query["$defs"]["outer"]["properties"]["query"]["$ref"] =
json!("?revision=3#revision");
let error = admit_final_schema(wrong_query)
.expect_err("changing only the query cannot select a bundled sibling resource");
assert_eq!(error.path(), "$.$defs.outer.properties.query.$ref");
assert_eq!(error.reason(), "external schema reference is not allowed");
let mut invalid = source;
invalid["$ref"] = json!("objects/%ZZ.json#outer");
let error = admit_final_schema(invalid)
.expect_err("invalid percent encoding remains an admission error");
assert_eq!(error.path(), "$.$ref");
assert_eq!(error.reason(), "invalid local schema reference");
}
}
#[test]
fn authorityless_reference_resolution_preserves_component_presence_and_bounds() {
let vectors = [
("file:/a/b?base=1", "child", "file:/a/child"),
("file:/a/b?base=1", "../child", "file:/child"),
("file:/a/b?base=1", "/child", "file:/child"),
("file:/a/b?base=1", "?next=1", "file:/a/b?next=1"),
("file:/a/b?base=1", "?", "file:/a/b?"),
("file:/a/b?base=1", "", "file:/a/b?base=1"),
("file:/a/b?", "", "file:/a/b?"),
("file:/a/b", "", "file:/a/b"),
("schema:a/b?base=1", "child", "schema:a/child"),
("schema:a/b?base=1", "?", "schema:a/b?"),
("schema:a/b?base=1", "/child", "schema:/child"),
("schema:a/b", "//host/child", "schema://host/child"),
("schema:a/b", "other:/child", "other:/child"),
("schema:", "child", "schema:child"),
("schema:/", "child", "schema:/child"),
("schema://", "child", "schema:///child"),
("file:/a//b", "child", "file:/a//child"),
("file:/a/b", "child/.", "file:/a/child/"),
("file:/a/b", "child/..", "file:/a/"),
("file:/a/b", "?path=/../x", "file:/a/b?path=/../x"),
("file:/a/b", "%2E%2E/child", "file:/a/%2E%2E/child"),
("file:/a/b", "./1:child", "file:/a/1:child"),
("file:/a/b", "child/1:leaf", "file:/a/child/1:leaf"),
];
for (base, reference, expected) in vectors {
assert_eq!(
resolve_uri_reference(Some(base), reference).as_deref(),
Some(expected),
"reference {reference:?} against {base:?}"
);
}
for reference in [
"bad%",
"bad%2",
"bad%ZZ",
"bad path",
"é",
"child#fragment",
"1:child",
":child",
] {
assert!(
resolve_uri_reference(Some("file:/schemas/root"), reference).is_none(),
"document identifiers do not relax syntax or retain fragments: {reference:?}"
);
}
let overlong = "x".repeat(MAX_SCHEMA_ASSERTION_STRING_BYTES + 1);
assert!(resolve_uri_reference(Some("file:/schemas/root"), &overlong).is_none());
let bounded_input = "x".repeat(MAX_SCHEMA_ASSERTION_STRING_BYTES);
assert!(
resolve_uri_reference(Some("file:/schemas/root"), &bounded_input).is_none(),
"the fully resolved identifier must also fit the existing byte limit"
);
}
#[test]
fn rfc3986_normal_and_abnormal_path_resolution_examples() {
let vectors = [
("g:h", "g:h"),
("g", "http://a/b/c/g"),
("./g", "http://a/b/c/g"),
("g/", "http://a/b/c/g/"),
("/g", "http://a/g"),
("//g", "http://g"),
("?y", "http://a/b/c/d;p?y"),
("g?y", "http://a/b/c/g?y"),
(";x", "http://a/b/c/;x"),
("g;x", "http://a/b/c/g;x"),
("", "http://a/b/c/d;p?q"),
(".", "http://a/b/c/"),
("./", "http://a/b/c/"),
("..", "http://a/b/"),
("../", "http://a/b/"),
("../g", "http://a/b/g"),
("../..", "http://a/"),
("../../", "http://a/"),
("../../g", "http://a/g"),
("../../../g", "http://a/g"),
("../../../../g", "http://a/g"),
("/./g", "http://a/g"),
("/../g", "http://a/g"),
("g.", "http://a/b/c/g."),
(".g", "http://a/b/c/.g"),
("g..", "http://a/b/c/g.."),
("..g", "http://a/b/c/..g"),
("./../g", "http://a/b/g"),
("./g/.", "http://a/b/c/g/"),
("g/./h", "http://a/b/c/g/h"),
("g/../h", "http://a/b/c/h"),
("g;x=1/./y", "http://a/b/c/g;x=1/y"),
("g;x=1/../y", "http://a/b/c/y"),
("g?y/./x", "http://a/b/c/g?y/./x"),
("g?y/../x", "http://a/b/c/g?y/../x"),
("http:g", "http:g"),
];
for (reference, expected) in vectors {
assert_eq!(
resolve_uri_reference(Some("http://a/b/c/d;p?q"), reference).as_deref(),
Some(expected),
"RFC 3986 reference {reference:?}"
);
}
}
#[test]
fn rfc3986_reference_resolution_table_preserves_network_query_and_dot_boundaries() {
let vectors = [
(
"https://schemas.example.test/a/b?base=1",
"https://schemas.example.test/a//b?absolute=1",
"https://schemas.example.test/a//b?absolute=1",
),
(
"https://schemas.example.test/a/b?base=1",
"/a//b",
"https://schemas.example.test/a//b",
),
(
"https://schemas.example.test/a/b?base=1",
"/a/.",
"https://schemas.example.test/a/",
),
(
"https://schemas.example.test/a/b?base=1",
"/a/..",
"https://schemas.example.test/",
),
(
"https://schemas.example.test/a/b?base=1",
"child/./leaf?relative=1",
"https://schemas.example.test/a/child/leaf?relative=1",
),
(
"https://schemas.example.test/a/b?base=1",
"child/..",
"https://schemas.example.test/a/",
),
(
"https://schemas.example.test/a/b?base=1",
"//authority.example.test/a//b?network=1",
"https://authority.example.test/a//b?network=1",
),
(
"https://schemas.example.test/a/b?base=1",
"//authority.example.test/a/.",
"https://authority.example.test/a/",
),
(
"https://schemas.example.test/a/b?base=1",
"//authority.example.test/a/..",
"https://authority.example.test/",
),
(
"https://schemas.example.test/a/b?base=1",
"?next=1",
"https://schemas.example.test/a/b?next=1",
),
(
"https://schemas.example.test/a/b?base=1",
"",
"https://schemas.example.test/a/b?base=1",
),
];
for (base, reference, expected) in vectors {
assert_eq!(
resolve_uri_reference(Some(base), reference).as_deref(),
Some(expected),
"RFC 3986 resolution must retain the boundary semantics of {reference:?}"
);
}
}
#[test]
fn rfc3986_remove_dot_segments_table_preserves_empty_and_trailing_segments() {
let vectors = [
("/a/b/c/./../../g", "/a/g"),
("mid/content=5/../6", "mid/6"),
("/a//b", "/a//b"),
("/a/.", "/a/"),
("/a/..", "/"),
("/../", "/"),
("../g", "g"),
("g/./h", "g/h"),
];
for (path, expected) in vectors {
assert_eq!(
remove_uri_dot_segments(path),
expected,
"RFC 3986 section 5.2.4 preserves the path boundary semantics of {path:?}"
);
}
}
#[test]
fn rfc3986_dot_segment_one_value_negatives_do_not_select_adjacent_resources() {
let cases = [
("/a//b", "https://schemas.example.test/a//b", "/a/b"),
("/a/.", "https://schemas.example.test/a/", "/a"),
("/a/..", "https://schemas.example.test/", "/a"),
];
for (reference, resource_id, planted_reference) in cases {
let schema = json!({
"$id": "https://schemas.example.test/root.json",
"$defs": {
"target": {"$id": resource_id, "const": "ready"}
}
});
let root = schema
.as_object()
.expect("the dot-segment fixture remains a schema object");
let target = resolve_local_reference(&schema, root, reference)
.expect("the RFC 3986 vector reaches its declared local resource");
assert_eq!(target, &schema["$defs"]["target"]);
assert_eq!(
resolve_local_reference(&schema, root, planted_reference),
Err("external schema reference is not allowed"),
"changing only the path boundary must not select {resource_id:?}"
);
}
}
#[test]
fn final_local_reference_table_preserves_network_query_and_fragment_boundaries() {
let schema = json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"$id": "https://schemas.example.test/root?base=1",
"$anchor": "root",
"$defs": {
"query": {
"$id": "?selected=1",
"$anchor": "selected",
"const": "ready"
},
"network": {
"$id": "https://authority.example.test/a//b?network=1",
"$anchor": "network",
"const": "network"
}
}
});
let root = schema
.as_object()
.expect("the RFC boundary fixture remains a schema object");
let vectors = [
("#root", "root"),
("?selected=1#selected", "query"),
("//authority.example.test/a//b?network=1#network", "network"),
];
for (reference, expected_definition) in vectors {
let target = resolve_local_reference(&schema, root, reference)
.expect("the table vector resolves inside the local schema catalog");
assert_eq!(
target,
if expected_definition == "root" {
&schema
} else {
&schema["$defs"][expected_definition]
},
"the URI identifier and fragment boundaries select the expected resource for {reference:?}"
);
}
let accepted = json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"$id": "https://schemas.example.test/root?base=1",
"$defs": {"query": schema["$defs"]["query"].clone()},
"$ref": "?selected=1#selected"
});
admit_final_schema(accepted.clone())
.expect("the query and fragment boundary fixture admits")
.validate(&json!("ready"))
.expect("the query-selected anchored resource validates");
let mut planted = accepted.clone();
planted["$ref"] = json!("?selected=2#selected");
let error = admit_final_schema(planted)
.expect_err("changing only the query value must not select the declared resource");
assert_eq!(error.path(), "$.$ref");
assert_eq!(error.reason(), "external schema reference is not allowed");
assert_eq!(accepted["$ref"], json!("?selected=1#selected"));
}
#[test]
fn absolute_references_normalize_dot_segments_with_a_one_value_negative() {
let accepted = json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"$id": "https://schemas.example.test/catalog/root.json",
"$defs": {
"child": {
"$id": "../child.json",
"const": "ready"
}
},
"$ref": "https://schemas.example.test/catalog/../child.json"
});
let schema = admit_final_schema(accepted.clone())
.expect("an absolute reference resolves after dot-segment normalization");
schema
.validate(&json!("ready"))
.expect("the normalized absolute reference reaches the local child resource");
let mut planted = accepted.clone();
planted["$ref"] = json!("https://schemas.example.test/catalog/../missing.json");
let error = admit_final_schema(planted)
.expect_err("changing only the normalized target to an undeclared resource rejects");
assert_eq!(error.path(), "$.$ref");
assert_eq!(error.reason(), "external schema reference is not allowed");
assert_eq!(
accepted["$ref"],
json!("https://schemas.example.test/catalog/../child.json")
);
}
#[test]
fn final_references_require_canonical_array_index_tokens() {
let choices: Vec<_> = (0..12).map(|value| json!({"const": value})).collect();
for keyword in ["$ref", "$dynamicRef"] {
for (token, expected) in [("0", 0), ("1", 1), ("10", 10), ("%30", 0), ("%31%30", 10)] {
let source = json!({
"$defs": {"choices": {"anyOf": choices}},
keyword: format!("#/$defs/choices/anyOf/{token}")
});
let admitted = admit_final_schema(source.clone()).unwrap();
assert!(
admitted.validate(&json!(expected)).is_ok(),
"{keyword}: {token}"
);
assert!(
admitted.validate(&json!(expected + 1)).is_err(),
"{keyword}: {token}"
);
assert_eq!(admitted.schema(), &source);
}
for token in [
"00", "01", "+0", "-0", "", "1.0", "1e0", "%30%30", "%2B0", "%2D0", "%20%31",
"%31%20", "%D9%A1",
] {
let source = json!({
"$defs": {"choices": {"anyOf": choices}},
keyword: format!("#/$defs/choices/anyOf/{token}")
});
let error = admit_final_schema(source).unwrap_err();
assert_eq!(error.path(), format!("$.{keyword}"), "{token}");
assert_eq!(error.reason(), "invalid local schema reference", "{token}");
}
for token in ["-".to_owned(), "12".to_owned(), "9".repeat(100)] {
let source = json!({
"$defs": {"choices": {"anyOf": choices}},
keyword: format!("#/$defs/choices/anyOf/{token}")
});
let error = admit_final_schema(source).unwrap_err();
assert_eq!(error.reason(), "unresolved local schema reference");
}
}
}
#[test]
fn raw_references_require_canonical_array_index_tokens() {
let choices: Vec<_> = (0..12).map(|value| json!({"const": value})).collect();
for (token, expected) in [("0", 0), ("1", 1), ("10", 10)] {
let source = json!({
"$defs": {"choices": {"anyOf": choices}},
"$ref": format!("#/$defs/choices/anyOf/{token}")
});
assert!(validate(&source, &json!(expected)).is_ok(), "{token}");
assert!(validate(&source, &json!(expected + 1)).is_err(), "{token}");
}
for token in ["00", "01", "+0", "-0", "", "1.0", "1e0", " 1", "1 "] {
let source = json!({
"$defs": {"choices": {"anyOf": choices}},
"$ref": format!("#/$defs/choices/anyOf/{token}")
});
let errors = validate(&source, &json!(0)).unwrap_err();
assert_eq!(
errors[0].message, "invalid local schema reference",
"{token}"
);
}
for token in ["-".to_owned(), "12".to_owned(), "9".repeat(100)] {
let source = json!({
"$defs": {"choices": {"anyOf": choices}},
"$ref": format!("#/$defs/choices/anyOf/{token}")
});
let errors = validate(&source, &json!(0)).unwrap_err();
assert_eq!(
errors[0].message, "unresolved local schema reference",
"{token}"
);
}
}
#[test]
fn reference_numeric_object_members_remain_literal() {
for keyword in ["$ref", "$dynamicRef"] {
for key in ["0", "00", "01", "+0", "-0", "-", ""] {
let source = json!({
"$defs": {key: {"const": key}},
keyword: format!("#/$defs/{key}")
});
let admitted = admit_final_schema(source.clone()).unwrap();
let accepted = json!(key);
let rejected = json!(format!("other-{key}"));
assert!(admitted.validate(&accepted).is_ok(), "{keyword}: {key:?}");
assert!(admitted.validate(&rejected).is_err(), "{keyword}: {key:?}");
if keyword == "$ref" {
assert!(validate(&source, &accepted).is_ok(), "{key:?}");
assert!(validate(&source, &rejected).is_err(), "{key:?}");
}
assert_eq!(admitted.schema(), &source);
}
}
let source = json!({
"$defs": {
"00": {"const": "decoded"},
"%30%30": {"const": "literal"}
},
"$ref": "#/$defs/%30%30"
});
let admitted = admit_final_schema(source.clone()).unwrap();
assert!(admitted.validate(&json!("decoded")).is_ok());
assert!(admitted.validate(&json!("literal")).is_err());
assert!(validate(&source, &json!("literal")).is_ok());
assert!(validate(&source, &json!("decoded")).is_err());
}
#[test]
fn final_references_percent_decode_before_json_pointer_unescaping() {
let accepted = json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"$defs": {
"a/b": {"const": "ready"}
},
"$ref": "#/$defs/a%7E1b"
});
let schema = admit_final_schema(accepted.clone())
.expect("percent decoding before ~1 decoding reaches the slash-containing definition");
schema
.validate(&json!("ready"))
.expect("the percent-encoded pointer token resolves");
let mut invalid_percent = accepted.clone();
invalid_percent["$ref"] = json!("#/$defs/a%7G1b");
let invalid_percent_error = admit_final_schema(invalid_percent)
.expect_err("changing only one percent-escape nibble must reject");
assert_eq!(invalid_percent_error.path(), "$.$ref");
assert_eq!(
invalid_percent_error.reason(),
"invalid local schema reference"
);
let mut invalid_utf8 = accepted.clone();
invalid_utf8["$ref"] = json!("#/$defs/a%FF1b");
let invalid_utf8_error = admit_final_schema(invalid_utf8)
.expect_err("changing only the pointer escape to invalid UTF-8 must reject");
assert_eq!(invalid_utf8_error.path(), "$.$ref");
assert_eq!(
invalid_utf8_error.reason(),
"invalid local schema reference"
);
assert_eq!(accepted["$ref"], json!("#/$defs/a%7E1b"));
}
#[test]
fn raw_validation_retains_its_legacy_local_reference_behavior() {
let legacy = json!({
"$defs": {
"ready": {"const": "ready"},
"a/b": {"const": "ready"}
},
"$ref": "#/$defs/ready"
});
validate(&legacy, &json!("ready"))
.expect("the raw validator retains ordinary legacy JSON Pointer resolution");
let mut percent_encoded = legacy.clone();
percent_encoded["$ref"] = json!("#/$defs/a%7E1b");
let errors = validate(&percent_encoded, &json!("ready"))
.expect_err("raw validation does not acquire final-schema percent decoding semantics");
assert_eq!(errors[0].message, "unresolved local schema reference");
assert_eq!(legacy["$ref"], json!("#/$defs/ready"));
}
#[test]
fn local_resource_resolution_charges_exact_shared_work_units() {
let schema = json!({
"$id": "https://schemas.example.test/root.json",
"properties": {
"source": {"$ref": "child.json"}
},
"$defs": {
"target": {
"$id": "child.json",
"const": "ready"
}
}
});
let source = schema["properties"]["source"]
.as_object()
.expect("the source fixture remains a schema object");
let mut exact_context = ValidationContext::new(&schema, true);
exact_context.remaining_work = 5;
let target =
resolve_local_reference_with_work(&schema, source, "child.json", &mut exact_context)
.expect("two scope visits and three resource visits fit the exact work budget");
assert_eq!(target, &json!({"$id": "child.json", "const": "ready"}));
assert_eq!(exact_context.remaining_work, 0);
let mut planted_context = ValidationContext::new(&schema, true);
planted_context.remaining_work = 4;
let error =
resolve_local_reference_with_work(&schema, source, "child.json", &mut planted_context)
.expect_err("removing one lookup work unit must reject before the target is found");
assert_eq!(error, "schema validation work limit exceeded");
assert_eq!(planted_context.remaining_work, 0);
}
#[test]
fn admitted_schema_content_annotations_have_bounded_positive_and_negative_cases() {
let accepted = json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": "string",
"contentEncoding": "base64",
"contentMediaType": "application/json",
"contentSchema": {"type": "object"}
});
admit_final_schema(accepted.clone()).expect("bounded content annotations admit");
let mut encoding = accepted.clone();
encoding["contentEncoding"] = json!(true);
let encoding_error =
admit_final_schema(encoding).expect_err("changing only contentEncoding rejects");
assert_eq!(encoding_error.path(), "$.contentEncoding");
assert_eq!(
encoding_error.reason(),
"content annotation keyword must be a bounded non-empty string"
);
let mut media_type = accepted.clone();
media_type["contentMediaType"] = json!(true);
let media_type_error =
admit_final_schema(media_type).expect_err("changing only contentMediaType rejects");
assert_eq!(media_type_error.path(), "$.contentMediaType");
assert_eq!(
media_type_error.reason(),
"content annotation keyword must be a bounded non-empty string"
);
let mut empty_encoding = accepted.clone();
empty_encoding["contentEncoding"] = json!("");
let empty_encoding_error = admit_final_schema(empty_encoding)
.expect_err("changing only contentEncoding to empty rejects");
assert_eq!(empty_encoding_error.path(), "$.contentEncoding");
assert_eq!(
empty_encoding_error.reason(),
"content annotation keyword must be a bounded non-empty string"
);
let mut content_schema = accepted;
content_schema["contentSchema"] = json!("not-a-schema");
let content_schema_error =
admit_final_schema(content_schema).expect_err("changing only contentSchema rejects");
assert_eq!(content_schema_error.path(), "$.contentSchema");
assert_eq!(
content_schema_error.reason(),
"schema must be an object or boolean"
);
}
fn assert_admitted_annotations_accept_only_evaluated_members(schema: Value, accepted: Value) {
let schema = admit_final_schema(schema).expect("the bounded annotation schema admits");
schema
.validate(&accepted)
.expect("members annotated by successful applicators remain accepted");
let mut planted = accepted.clone();
planted
.as_object_mut()
.expect("the annotation fixture is an object")
.insert("unexpected".to_owned(), Value::Bool(true));
let errors = schema
.validate(&planted)
.expect_err("adding only an unevaluated member must reject");
assert!(errors.iter().any(|error| {
error.path == "root.unexpected" && error.message == "schema rejects all values"
}));
assert!(accepted.get("unexpected").is_none());
}
#[test]
fn admitted_ref_annotations_reach_unevaluated_properties() {
assert_admitted_annotations_accept_only_evaluated_members(
json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"$defs": {
"referenced": {
"properties": {"viaRef": {"type": "integer"}},
"required": ["viaRef"]
}
},
"$ref": "#/$defs/referenced",
"unevaluatedProperties": false
}),
json!({"viaRef": 1}),
);
}
#[test]
fn admitted_all_of_annotations_reach_unevaluated_properties() {
assert_admitted_annotations_accept_only_evaluated_members(
json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"allOf": [{
"properties": {"viaAllOf": {"type": "integer"}},
"required": ["viaAllOf"]
}],
"unevaluatedProperties": false
}),
json!({"viaAllOf": 1}),
);
}
#[test]
fn admitted_any_of_unions_all_successful_branch_annotations() {
assert_admitted_annotations_accept_only_evaluated_members(
json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"anyOf": [
{
"properties": {"alpha": {"type": "integer"}},
"required": ["alpha"]
},
{
"properties": {"beta": {"type": "integer"}},
"required": ["beta"]
}
],
"unevaluatedProperties": false
}),
json!({"alpha": 1, "beta": 2}),
);
}
#[test]
fn admitted_one_of_uses_only_the_unique_successful_branch_annotations() {
assert_admitted_annotations_accept_only_evaluated_members(
json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"oneOf": [
{
"properties": {"alpha": {"type": "integer"}},
"required": ["alpha"]
},
{
"properties": {"beta": {"type": "integer"}},
"required": ["beta"]
}
],
"unevaluatedProperties": false
}),
json!({"alpha": 1}),
);
}
#[test]
fn admitted_dependent_schema_annotations_reach_unevaluated_properties() {
assert_admitted_annotations_accept_only_evaluated_members(
json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"properties": {"trigger": {"const": true}},
"required": ["trigger"],
"dependentSchemas": {
"trigger": {
"properties": {"payload": {"type": "string"}},
"required": ["payload"]
}
},
"unevaluatedProperties": false
}),
json!({"trigger": true, "payload": "ready"}),
);
}
#[test]
fn admitted_if_without_then_or_else_propagates_successful_annotations() {
assert_admitted_annotations_accept_only_evaluated_members(
json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"if": {
"properties": {"kind": {"const": "ready"}},
"required": ["kind"]
},
"unevaluatedProperties": false
}),
json!({"kind": "ready"}),
);
}
#[test]
fn admitted_if_and_then_union_successful_annotations() {
assert_admitted_annotations_accept_only_evaluated_members(
json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"if": {
"properties": {"kind": {"const": "ready"}},
"required": ["kind"]
},
"then": {
"properties": {"payload": {"type": "string"}},
"required": ["payload"]
},
"unevaluatedProperties": false
}),
json!({"kind": "ready", "payload": "complete"}),
);
}
#[test]
fn admitted_else_propagates_only_the_selected_branch_annotations() {
assert_admitted_annotations_accept_only_evaluated_members(
json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"if": {
"properties": {"kind": {"const": "primary"}},
"required": ["kind"]
},
"else": {
"properties": {
"kind": {"const": "fallback"},
"payload": {"type": "string"}
},
"required": ["kind", "payload"]
},
"unevaluatedProperties": false
}),
json!({"kind": "fallback", "payload": "complete"}),
);
}
#[test]
fn admitted_nested_unevaluated_properties_annotations_reach_outer_schema() {
assert_admitted_annotations_accept_only_evaluated_members(
json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"allOf": [{
"properties": {"nested": {"type": "string"}},
"required": ["nested"],
"unevaluatedProperties": false
}],
"unevaluatedProperties": false
}),
json!({"nested": "ready"}),
);
}
fn pattern_property_work_schema() -> AdmittedSchema {
let mut patterns = serde_json::Map::new();
for index in 0..MAX_PATTERN_PROPERTIES {
patterns.insert(format!("^never-{index}$"), Value::Bool(true));
}
admit_final_schema(json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": "object",
"patternProperties": patterns
}))
.expect("the maximum bounded pattern family admits")
}
fn object_with_null_members(count: usize) -> Value {
let members: serde_json::Map<String, Value> = (0..count)
.map(|index| (format!("field-{index}"), Value::Null))
.collect();
Value::Object(members)
}
#[test]
fn admitted_pattern_compilation_and_key_matching_share_work_limit() {
let schema = pattern_property_work_schema();
let accepted = object_with_null_members(62);
schema
.validate(&accepted)
.expect("pattern compilation and 62 bounded key scans fit the work budget");
let planted = object_with_null_members(63);
let errors = schema
.validate(&planted)
.expect_err("adding one key must exceed the shared regex work budget");
assert!(
errors
.iter()
.any(|error| error.message == "schema validation work limit exceeded")
);
assert_eq!(accepted.as_object().unwrap().len(), 62);
}
#[test]
fn raw_pattern_work_remains_legacy_while_admitted_final_is_bounded() {
let mut patterns = serde_json::Map::new();
for index in 0..MAX_PATTERN_PROPERTIES {
patterns.insert(format!("^never-{index}$"), Value::Bool(true));
}
let schema = json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": "object",
"patternProperties": patterns,
"additionalProperties": true
});
let instance = object_with_null_members(63);
validate(&schema, &instance)
.expect("raw validation preserves its legacy pattern-work behavior");
validate_strict(&schema, &instance)
.expect("raw strict validation preserves its legacy pattern-work behavior");
let admitted = admit_final_schema(schema).expect("the bounded final schema admits");
let errors = admitted
.validate(&instance)
.expect_err("admitted-final validation enforces the shared regex work budget");
assert!(
errors
.iter()
.any(|error| error.message == "schema validation work limit exceeded")
);
}
fn named_property_annotation_work_schema(count: usize) -> AdmittedSchema {
let properties: serde_json::Map<String, Value> = (0..count)
.map(|index| (format!("field-{index}"), Value::Bool(true)))
.collect();
admit_final_schema(json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": "object",
"properties": properties,
"unevaluatedProperties": false
}))
.expect("the bounded named-property schema admits")
}
#[test]
fn admitted_key_annotation_bookkeeping_shares_work_limit() {
let accepted_schema = named_property_annotation_work_schema(1_023);
let accepted = object_with_null_members(1_023);
accepted_schema.validate(&accepted).expect(
"1,023 property validations, annotations, and preflight nodes fit the work budget",
);
let planted_schema = named_property_annotation_work_schema(1_024);
let planted = object_with_null_members(1_024);
let errors = planted_schema
.validate(&planted)
.expect_err("adding one property must exceed the shared annotation work budget");
assert!(
errors
.iter()
.any(|error| error.message == "schema validation work limit exceeded")
);
assert_eq!(accepted.as_object().unwrap().len(), 1_023);
}
fn repeated_pattern_work_schema(units: usize) -> AdmittedSchema {
let unit = json!({
"allOf": vec![
json!({"$ref": "#/$defs/matching-pattern"});
MAX_COMPOSITION_BRANCHES
]
});
admit_final_schema(json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"$defs": {
"matching-pattern": {"type": "string", "pattern": "^ready$"}
},
"allOf": vec![unit; units]
}))
.expect("the bounded repeated-pattern schema admits")
}
#[test]
fn admitted_string_pattern_compilation_and_matching_share_work_limit() {
repeated_pattern_work_schema(1)
.validate(&json!("ready"))
.expect(
"one repeated pattern unit and its local-reference traversal fit the work budget",
);
let errors = repeated_pattern_work_schema(2)
.validate(&json!("ready"))
.expect_err("adding one repeated pattern unit must exceed the shared work budget");
assert!(
errors
.iter()
.any(|error| error.message == "schema validation work limit exceeded")
);
}
fn repeated_branch_probe_work_schema(units: usize) -> AdmittedSchema {
let mut branches = vec![Value::Bool(false); MAX_COMPOSITION_BRANCHES];
branches[0] = Value::Bool(true);
let unit = json!({"oneOf": branches});
admit_final_schema(json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"allOf": vec![unit; units],
"unevaluatedProperties": true
}))
.expect("the bounded repeated-branch schema admits")
}
#[test]
fn admitted_repeated_branch_probes_share_work_limit() {
repeated_branch_probe_work_schema(10)
.validate(&json!({}))
.expect("ten repeated branch-probe units fit the work budget");
let errors = repeated_branch_probe_work_schema(11)
.validate(&json!({}))
.expect_err("adding one repeated branch unit must exceed the shared work budget");
assert!(
errors
.iter()
.any(|error| error.message == "schema validation work limit exceeded")
);
}
fn final_schema_format_annotation_schema() -> AdmittedSchema {
admit_final_schema(json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": "object",
"properties": {
"data": {"type": "string", "format": "byte"},
"uri": {"type": "string", "format": "uri"},
"template": {"type": "string", "format": "uri-template"}
},
"required": ["data", "uri", "template"],
"additionalProperties": false
}))
.expect("the final format annotations admit")
}
fn final_schema_format_instance() -> Value {
json!({
"data": "cGlubmVkIGZpbmFs",
"uri": "https://example.test/resources?id=1#ready",
"template": "mcp://resources/{id}{?cursor}"
})
}
#[test]
fn final_schema_format_annotations_are_not_assertions_by_default() {
final_schema_format_annotation_schema()
.validate(&final_schema_format_instance())
.expect("valid annotations do not reject an instance");
let mut planted = final_schema_format_instance();
planted["uri"] = json!("not a uri");
final_schema_format_annotation_schema()
.validate(&planted)
.expect("changing only an annotated URI value does not assert by default");
}
#[test]
fn format_assertion_meta_schema_is_refused_without_full_format_support() {
let accepted = json!({
"$id": "https://schemas.example.test/root.json",
"$schema": "https://schemas.example.test/meta/format-assertion",
"$defs": {
"meta": {
"$id": "meta/format-assertion",
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"$vocabulary": {
CORE_VOCABULARY_URI: true,
FORMAT_ANNOTATION_VOCABULARY_URI: true,
FORMAT_ASSERTION_VOCABULARY_URI: false
}
}
},
"type": "string",
"format": "uri"
});
let schema = admit_final_schema(accepted.clone())
.expect("the annotation-only format vocabulary declaration admits");
schema
.validate(&json!("not a uri"))
.expect("format annotations remain non-asserting");
let mut planted = accepted.clone();
planted["$defs"]["meta"]["$vocabulary"][FORMAT_ASSERTION_VOCABULARY_URI] = json!(true);
let error = admit_final_schema(planted)
.expect_err("enabling only format assertion must fail closed without full support");
assert_eq!(
error.path(),
"$.$vocabulary[\"https://json-schema.org/draft/2020-12/vocab/format-assertion\"]"
);
assert_eq!(
error.reason(),
"format assertion vocabulary is not supported"
);
assert_eq!(
accepted["$defs"]["meta"]["$vocabulary"][FORMAT_ASSERTION_VOCABULARY_URI],
json!(false)
);
}
#[test]
fn meta_schema_vocabulary_requires_the_core_vocabulary() {
let accepted = json!({
"$id": "https://schemas.example.test/root.json",
"$schema": "https://schemas.example.test/meta/validation",
"$defs": {
"meta": {
"$id": "meta/validation",
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"$vocabulary": {
CORE_VOCABULARY_URI: true,
VALIDATION_VOCABULARY_URI: true
}
}
},
"type": "string"
});
admit_final_schema(accepted.clone())
.expect("a meta-schema that requires Core remains admissible");
let mut planted = accepted.clone();
planted["$defs"]["meta"]["$vocabulary"] = json!({
VALIDATION_VOCABULARY_URI: true
});
let error = admit_final_schema(planted)
.expect_err("removing only the required Core vocabulary must reject");
assert_eq!(error.path(), "$.$vocabulary");
assert_eq!(
error.reason(),
"meta-schema $vocabulary must require the Draft 2020-12 core vocabulary"
);
assert_eq!(
accepted["$defs"]["meta"]["$vocabulary"][CORE_VOCABULARY_URI],
json!(true)
);
}
#[test]
fn schema_admission_node_limit_positive_and_planted_negative() {
let mut properties = serde_json::Map::new();
for index in 0..(MAX_SCHEMA_ADMISSION_NODES - 1) {
properties.insert(format!("field-{index}"), Value::Bool(true));
}
let accepted = json!({"type": "object", "properties": properties});
admit_final_schema(accepted.clone())
.expect("the exact schema-admission node budget is accepted");
let mut planted = accepted.clone();
planted["properties"]
.as_object_mut()
.expect("schema properties stay an object")
.insert(
format!("field-{}", MAX_SCHEMA_ADMISSION_NODES - 1),
Value::Bool(true),
);
let error = admit_final_schema(planted)
.expect_err("adding one schema node beyond the admission budget must reject");
assert_eq!(error.reason(), "schema admission node limit exceeded");
assert_eq!(
accepted["properties"].as_object().unwrap().len(),
MAX_SCHEMA_ADMISSION_NODES - 1
);
}
#[test]
fn instance_node_limit_positive_and_planted_negative() {
let schema = admit_final_schema(Value::Bool(true)).expect("the true schema admits");
let accepted = Value::Array(vec![Value::Null; MAX_SCHEMA_INSTANCE_NODES - 1]);
let accepted_errors = schema
.validate(&accepted)
.expect_err("the exact node budget plus schema evaluation exceeds the work budget");
assert!(
accepted_errors
.iter()
.any(|error| { error.message == "schema validation work limit exceeded" })
);
let mut planted = accepted.clone();
planted.as_array_mut().unwrap().push(Value::Null);
let errors = schema
.validate(&planted)
.expect_err("adding one instance node beyond the budget must reject");
assert_eq!(
errors[0].path,
format!("root[{}]", MAX_SCHEMA_INSTANCE_NODES - 1)
);
assert_eq!(errors[0].message, "instance node limit exceeded");
assert_eq!(
accepted.as_array().unwrap().len(),
MAX_SCHEMA_INSTANCE_NODES - 1
);
}
fn schema_instance_numeric_boundary_pairs() -> [(Value, Value); 4] {
[
(
"9".repeat(MAX_EXACT_DECIMAL_DIGITS),
"9".repeat(MAX_EXACT_DECIMAL_DIGITS + 1),
),
(
format!("1e{}", MAX_EXACT_DECIMAL_DIGITS),
format!("1e{}", MAX_EXACT_DECIMAL_DIGITS + 1),
),
(
format!("1e-{}", MAX_EXACT_DECIMAL_DIGITS),
format!("1e-{}", MAX_EXACT_DECIMAL_DIGITS + 1),
),
(
format!("1.0e-{}", MAX_EXACT_DECIMAL_DIGITS - 1),
format!("1.0e-{}", MAX_EXACT_DECIMAL_DIGITS),
),
]
.map(|(accepted, planted)| {
(
serde_json::from_str(&accepted).expect("bounded exact JSON number"),
serde_json::from_str(&planted).expect("valid JSON outside the exact-number bound"),
)
})
}
fn schema_instance_numeric_locations(number: &Value) -> [(Value, &'static str); 4] {
[
(number.clone(), "root"),
(json!([number]), "root[0]"),
(json!({"declared": number}), "root.declared"),
(
json!({"uncovered": [{"amount": number}]}),
"root.uncovered[0].amount",
),
]
}
#[test]
fn admitted_instance_numeric_bounds_positive() {
for (number, _) in schema_instance_numeric_boundary_pairs() {
for source in [
Value::Bool(true),
json!({}),
json!({"properties": {"declared": true}, "additionalProperties": true}),
] {
let schema = admit_final_schema(source.clone()).unwrap();
for (instance, _) in schema_instance_numeric_locations(&number) {
schema
.validate(&instance)
.expect("exact numeric boundaries remain admitted in every location");
schema
.validate_strict(&instance)
.expect("strict validation preserves the same numeric boundaries");
}
assert_eq!(schema.schema(), &source);
}
}
}
#[test]
fn admitted_instance_numeric_bounds_planted_negative() {
for (accepted, planted) in schema_instance_numeric_boundary_pairs() {
for source in [
Value::Bool(true),
json!({}),
json!({"properties": {"declared": true}, "additionalProperties": true}),
] {
let schema = admit_final_schema(source.clone()).unwrap();
for ((baseline, _), (instance, path)) in
schema_instance_numeric_locations(&accepted)
.into_iter()
.zip(schema_instance_numeric_locations(&planted))
{
schema.validate(&baseline).unwrap();
for strict in [false, true] {
let result = if strict {
schema.validate_strict(&instance)
} else {
schema.validate(&instance)
};
let errors = result.expect_err(
"one extra numeric byte or exponent step must fail before evaluation",
);
assert_eq!(errors.len(), 1);
assert_eq!(errors[0].path, path);
assert_eq!(errors[0].code(), "SchemaResourceLimit");
assert_eq!(
errors[0].message,
"instance number exceeds exact comparison bound"
);
}
schema
.validate(&baseline)
.expect("a rejection does not contaminate subsequent validation");
}
assert_eq!(schema.schema(), &source);
}
}
}
#[test]
fn admitted_instance_numeric_bounds_cannot_be_swallowed_by_applicators() {
let accepted: Value =
serde_json::from_str(&format!("-1e{}", MAX_EXACT_DECIMAL_DIGITS)).unwrap();
let planted: Value =
serde_json::from_str(&format!("-1e{}", MAX_EXACT_DECIMAL_DIGITS + 1)).unwrap();
let condition = json!({"properties": {"value": {"minimum": 0}}});
for source in [
json!({"not": condition.clone()}),
json!({"anyOf": [condition.clone(), true]}),
json!({"oneOf": [condition.clone(), true]}),
json!({"if": condition, "then": false, "else": true}),
json!({"$defs": {"unconstrained": true}, "$ref": "#/$defs/unconstrained"}),
] {
let schema = admit_final_schema(source.clone()).unwrap();
let baseline = json!({"value": accepted.clone()});
let instance = json!({"value": planted.clone()});
schema.validate(&baseline).unwrap();
schema.validate_strict(&baseline).unwrap();
for strict in [false, true] {
let result = if strict {
schema.validate_strict(&instance)
} else {
schema.validate(&instance)
};
let errors = result
.expect_err("an unevaluated number cannot become a successful branch mismatch");
assert_eq!(errors.len(), 1);
assert_eq!(errors[0].path, "root.value");
assert_eq!(errors[0].code(), "SchemaResourceLimit");
}
assert_eq!(schema.schema(), &source);
}
let schema = admit_final_schema(json!({
"contains": {"minimum": 0},
"minContains": 0
}))
.unwrap();
schema.validate(&json!([accepted])).unwrap();
for strict in [false, true] {
let instance = json!([planted.clone()]);
let result = if strict {
schema.validate_strict(&instance)
} else {
schema.validate(&instance)
};
let errors = result
.expect_err("minContains zero cannot discard an exact-number resource failure");
assert_eq!(errors.len(), 1);
assert_eq!(errors[0].path, "root[0]");
assert_eq!(errors[0].code(), "SchemaResourceLimit");
}
}
#[test]
fn exact_number_exponent_bounds_do_not_truncate_on_32_bit_targets() {
let schema = admit_final_schema(Value::Bool(true)).unwrap();
for source in [
"1e4294967296",
"1e-4294967296",
"0e4294967296",
"0e-4294967296",
"1.0e4294967296",
"1.0e-4294967296",
] {
assert!(ExactDecimal::parse(source).is_none());
let instance: Value = serde_json::from_str(source).unwrap();
let errors = schema
.validate(&instance)
.expect_err("exponents must be bounded before any target-width conversion");
assert_eq!(errors.len(), 1);
assert_eq!(errors[0].path, "root");
assert_eq!(errors[0].code(), "SchemaResourceLimit");
}
}
#[test]
fn raw_instance_numeric_bounds_preserve_legacy_behavior() {
for (_, number) in schema_instance_numeric_boundary_pairs() {
for (instance, _) in schema_instance_numeric_locations(&number) {
for schema in [Value::Bool(true), json!({})] {
validate(&schema, &instance)
.expect("raw validation retains its historical numeric admission");
validate_strict(&schema, &instance)
.expect("raw strict validation does not select final numeric semantics");
}
}
}
}
fn schema_instance_byte_fixture(kind: usize) -> Value {
let mut value = match kind {
0 => json!("\u{0001}".repeat(MAX_SCHEMA_INSTANCE_BYTES / 12)),
1 => json!(["x".repeat(MAX_SCHEMA_INSTANCE_BYTES / 2), ""]),
_ => json!({
"escaped\"\\\nkey": [true, false, null, 12.5, "é🦀"],
"payload": "\u{0001}".repeat(MAX_SCHEMA_INSTANCE_BYTES / 12)
}),
};
let padding = MAX_SCHEMA_INSTANCE_BYTES - serde_json::to_vec(&value).unwrap().len();
let target = schema_instance_fixture_string(&mut value);
target.extend(std::iter::repeat_n('x', padding));
value
}
fn schema_instance_fixture_string(value: &mut Value) -> &mut String {
let target = match value {
Value::Array(items) => &mut items[1],
Value::Object(members) => members.get_mut("payload").unwrap(),
value => value,
};
let Value::String(target) = target else {
panic!("byte fixture payload must be a string");
};
target
}
#[test]
fn schema_instance_bytes_positive() {
let schema = admit_final_schema(Value::Bool(true)).unwrap();
for kind in 0..3 {
let instance = schema_instance_byte_fixture(kind);
assert_eq!(
serde_json::to_vec(&instance).unwrap().len(),
8 * 1024 * 1024
);
schema.validate(&instance).expect(
"root strings, aggregate arrays, and escaped object documents admit at 8 MiB",
);
validate(&Value::Bool(true), &instance)
.expect("raw validation shares the aggregate byte admission boundary");
}
let names = json!({("x".repeat(MAX_SCHEMA_INSTANCE_KEY_BYTES)): null});
schema
.validate(&names)
.expect("the existing member-name boundary remains admitted");
}
#[test]
fn schema_instance_bytes_planted_negative() {
let schema = admit_final_schema(Value::Bool(true)).unwrap();
for kind in 0..3 {
let accepted = schema_instance_byte_fixture(kind);
let mut planted = accepted.clone();
schema_instance_fixture_string(&mut planted).push('x');
assert_eq!(
serde_json::to_vec(&planted).unwrap().len(),
8 * 1024 * 1024 + 1
);
let errors = schema
.validate(&planted)
.expect_err("one additional encoded byte must fail before schema evaluation");
assert_eq!(errors[0].path, "root");
assert_eq!(errors[0].message, "instance document byte limit exceeded");
assert!(validate(&Value::Bool(true), &planted).is_err());
assert_eq!(
serde_json::to_vec(&accepted).unwrap().len(),
MAX_SCHEMA_INSTANCE_BYTES
);
}
let names = json!({("x".repeat(MAX_SCHEMA_INSTANCE_KEY_BYTES + 1)): null});
let errors = schema
.validate(&names)
.expect_err("increasing payload capacity must not increase retained name capacity");
assert_eq!(
errors[0].message,
"instance object member-name byte limit exceeded"
);
let string = json!("x".repeat(MAX_SCHEMA_INSTANCE_STRING_BYTES + 1));
let errors = schema
.validate(&string)
.expect_err("one scalar must remain bounded before escaped-size traversal");
assert_eq!(errors[0].message, "instance string byte limit exceeded");
assert_eq!(schema.schema(), &Value::Bool(true));
}
fn schema_large_result_fixture_schema() -> AdmittedSchema {
admit_final_schema(json!({
"type": "object",
"required": ["resultType", "content"],
"properties": {
"resultType": {"const": "complete"},
"content": {"type": "array", "items": {"type": "object",
"required": ["type", "data", "mimeType"],
"properties": {"data": {"type": "string"}}
}}
}
}))
.unwrap()
}
#[test]
fn schema_large_output_semantics_positive() {
let instance = json!("🦀".repeat(1024 * 1024));
assert_eq!(instance.as_str().unwrap().len(), 4 * 1024 * 1024);
let schema = admit_final_schema(json!({
"type": "string", "minLength": 1024 * 1024, "maxLength": 1024 * 1024
}))
.unwrap();
schema
.validate(&instance)
.expect("multi-megabyte structured output retains Unicode length semantics");
let result = json!({
"resultType": "complete",
"content": [{"type": "image", "data": "AAAA".repeat(1024 * 1024), "mimeType": "image/png"}]
});
let result_schema = schema_large_result_fixture_schema();
validate_final_core_result(&result_schema, &result, FinalCoreResultType::Complete)
.expect("full-result schema validation admits a 3 MiB decoded binary block");
}
#[test]
fn schema_large_output_semantics_planted_negative() {
let instance = json!("🦀".repeat(1024 * 1024));
let schema = admit_final_schema(json!({
"type": "string", "minLength": 1024 * 1024, "maxLength": 1024 * 1024 - 1
}))
.unwrap();
let errors = schema
.validate(&instance)
.expect_err("one less allowed Unicode character must reject the same large output");
assert_eq!(
errors[0].message,
"string has more characters than maxLength"
);
assert_eq!(instance.as_str().unwrap().len(), 4 * 1024 * 1024);
let result = json!({
"resultType": "task",
"content": [{"type": "image", "data": "AAAA".repeat(1024 * 1024), "mimeType": "image/png"}]
});
let result_schema = schema_large_result_fixture_schema();
let errors =
validate_final_core_result(&result_schema, &result, FinalCoreResultType::Complete)
.expect_err(
"a changed discriminator cannot bypass full-result validation at large sizes",
);
assert_eq!(errors[0].path, "root.resultType");
assert_eq!(
errors[0].message,
"resultType does not match the selected final core result branch"
);
}
fn schema_pattern_input_fixtures() -> Vec<Value> {
vec![
json!({"type": "string", "pattern": "^x+$"}),
json!({"anyOf": [{"pattern": "^y+$"}, {"type": "string"}]}),
json!({"not": {"pattern": "^y+$"}}),
json!({"if": {"pattern": "^y+$"}, "then": false, "else": true}),
json!({"allOf": [{"pattern": "^x+$"}]}),
]
}
#[test]
fn schema_pattern_input_bytes_positive() {
let instance = json!("x".repeat(MAX_SCHEMA_PATTERN_INPUT_BYTES));
for source in schema_pattern_input_fixtures() {
let schema = admit_final_schema(source.clone()).unwrap();
schema
.validate(&instance)
.expect("matching and non-matching 1 MiB probes retain ordinary branch semantics");
validate(&source, &instance)
.expect("raw validation admits the same pattern-input boundary");
}
}
#[test]
fn schema_pattern_input_bytes_planted_negative() {
let instance = json!("x".repeat(MAX_SCHEMA_PATTERN_INPUT_BYTES + 1));
for source in schema_pattern_input_fixtures() {
let schema = admit_final_schema(source.clone()).unwrap();
let errors = schema.validate(&instance).expect_err(
"one excess pattern-input byte cannot become an ordinary branch mismatch",
);
assert!(
errors
.iter()
.any(|error| error.message == "pattern input byte limit exceeded")
);
assert!(validate(&source, &instance).is_err());
assert_eq!(schema.schema(), &source);
}
assert_eq!(
instance.as_str().unwrap().len(),
MAX_SCHEMA_PATTERN_INPUT_BYTES + 1
);
}
fn schema_large_string_work_fixtures(excess: usize) -> Vec<(Value, Value)> {
let unique = Value::Array(
(0..7)
.map(|index| json!(format!("{}{index}", "x".repeat(1024 * 1024 - 1))))
.collect(),
);
let pattern_unit = json!({"allOf": vec![json!({"pattern": "^x+$"}); 64]});
vec![
(
json!({"allOf": vec![json!({"minLength": 1}); 62 + excess]}),
json!("x".repeat(4 * 1024 * 1024)),
),
(
json!({"allOf": vec![json!({"uniqueItems": true}); 11 + excess]}),
unique,
),
(
json!({"allOf": vec![pattern_unit; 3 + excess]}),
json!("x".repeat(1024 * 1024)),
),
]
}
#[test]
fn schema_large_string_work_positive() {
for (source, instance) in schema_large_string_work_fixtures(0) {
admit_final_schema(source)
.unwrap()
.validate(&instance)
.expect("bounded large-string length, equality, and regex scans fit shared fuel");
}
}
#[test]
fn schema_large_string_work_planted_negative() {
for (source, instance) in schema_large_string_work_fixtures(1) {
let schema = admit_final_schema(source.clone()).unwrap();
let errors = schema
.validate(&instance)
.expect_err("one additional repeated large-string unit exhausts shared fuel");
assert!(
errors
.iter()
.any(|error| error.message == "schema validation work limit exceeded")
);
assert_eq!(schema.schema(), &source);
}
}
fn raw_large_decimal(integer: u8) -> Value {
serde_json::from_str(&format!(
"{integer}.{}",
"0".repeat(2 * SCHEMA_STRING_WORK_UNIT_BYTES)
))
.expect("a finite number retaining more than two 64 KiB chunks of decimal text")
}
#[test]
fn schema_raw_numeric_text_preflight_bounds_and_work() {
let instance = json!({"unevaluated": [raw_large_decimal(1)]});
let mut nodes = 0;
let mut work = 0;
let mut errors = Vec::new();
assert!(validate_instance_bounds(
&instance,
"root",
0,
false,
&mut nodes,
&mut work,
&mut errors,
));
assert_eq!(work, 2);
assert!(errors.is_empty());
validate(&Value::Bool(true), &instance)
.expect("raw boolean schemas retain bounded unevaluated numbers");
let accepted = arbitrary_precision_number(MAX_SCHEMA_INSTANCE_BYTES);
let planted = arbitrary_precision_number(MAX_SCHEMA_INSTANCE_BYTES + 1);
for source in [Value::Bool(true), json!({})] {
validate(&source, &accepted)
.expect("the exact raw numeric byte boundary remains valid");
for result in [
validate(&source, &planted),
validate_strict(&source, &planted),
] {
let errors = result.expect_err("one extra byte must fail before numeric traversal");
assert_eq!(errors[0].message, "instance number byte limit exceeded");
assert_eq!(errors[0].code(), "SchemaResourceLimit");
}
}
assert_eq!(
accepted.as_number().unwrap().as_str().len(),
MAX_SCHEMA_INSTANCE_BYTES
);
}
#[test]
fn schema_raw_numeric_text_equality_charges_nested_number_scans() {
let instance = json!({"nested": [raw_large_decimal(1)]});
for keyword in ["const", "enum"] {
let assertion = if keyword == "enum" {
json!([instance.clone()])
} else {
instance.clone()
};
let source = json!({keyword: assertion});
for (fuel, accepted) in [(3, true), (2, false)] {
let mut context = ValidationContext::new(&source, false);
context.remaining_work = fuel;
let mut errors = Vec::new();
validate_internal(&source, &instance, "root", &mut errors, &mut context);
assert_eq!(errors.is_empty(), accepted, "{keyword}, fuel {fuel}");
assert_eq!(context.work_exhausted, !accepted);
if !accepted {
assert_eq!(errors[0].message, "schema validation work limit exceeded");
}
}
}
}
#[test]
fn schema_raw_numeric_text_uniqueness_charges_nested_serialization() {
let source = json!({"uniqueItems": true});
let instance = json!([
{"nested": [raw_large_decimal(1)]},
{"nested": [raw_large_decimal(2)]}
]);
for (fuel, accepted) in [(5, true), (4, false)] {
let mut context = ValidationContext::new(&source, false);
context.remaining_work = fuel;
let mut errors = Vec::new();
validate_internal(&source, &instance, "root", &mut errors, &mut context);
assert_eq!(errors.is_empty(), accepted);
assert_eq!(context.work_exhausted, !accepted);
if !accepted {
assert_eq!(errors[0].message, "schema validation work limit exceeded");
}
}
}
#[test]
fn schema_raw_numeric_text_conversion_charges_both_operands() {
let instance = raw_large_decimal(1);
for (keyword, bound) in [
("minimum", 1),
("maximum", 1),
("exclusiveMinimum", 0),
("exclusiveMaximum", 2),
("multipleOf", 1),
] {
let source = json!({keyword: raw_large_decimal(bound)});
for (fuel, accepted) in [(5, true), (4, false)] {
let mut context = ValidationContext::new(&source, false);
context.remaining_work = fuel;
let mut errors = Vec::new();
validate_internal(&source, &instance, "root", &mut errors, &mut context);
assert_eq!(errors.is_empty(), accepted, "{keyword}, fuel {fuel}");
assert_eq!(context.work_exhausted, !accepted);
if !accepted {
assert_eq!(errors[0].message, "schema validation work limit exceeded");
}
}
}
}
#[test]
fn schema_raw_numeric_text_work_cannot_be_swallowed_by_fallback() {
let group = json!({"allOf": vec![json!({"$ref": "#/$defs/bound"}); 64]});
let accepted = json!({
"$defs": {"bound": {"minimum": 1.0}},
"anyOf": [{"allOf": vec![group; 16]}, true]
});
let mut planted = accepted.clone();
planted["$defs"]["bound"]["minimum"] = raw_large_decimal(1);
let instance = json!(1.0);
validate(&accepted, &instance).expect("ordinary numeric references fit the work budget");
validate_strict(&accepted, &instance)
.expect("strict raw validation keeps the same ordinary numeric result");
for result in [
validate(&planted, &instance),
validate_strict(&planted, &instance),
] {
let errors = result.expect_err(
"equivalent large numeric text must exhaust fuel before a true fallback can admit",
);
assert!(errors.iter().any(|error| {
error.message == "schema validation work limit exceeded"
&& error.code() == "SchemaResourceLimit"
}));
}
assert_eq!(accepted["$defs"]["bound"]["minimum"], json!(1.0));
}
#[test]
fn schema_raw_numeric_text_charging_preserves_small_number_semantics() {
let source = json!({
"minimum": 0.25,
"maximum": 1.5,
"exclusiveMinimum": 0.0,
"exclusiveMaximum": 2.0,
"multipleOf": 0.125
});
validate(&source, &json!(1.0)).expect("ordinary finite arithmetic remains valid");
assert!(validate(&source, &json!(0.0)).is_err());
validate(&json!({"const": 1.0}), &json!(1.0))
.expect("raw identical numeric representations still match");
assert!(validate(&json!({"const": 1}), &json!(1.0)).is_err());
validate(&json!({"uniqueItems": true}), &json!([1, 1.0]))
.expect("raw uniqueness retains representation semantics");
admit_final_schema(json!({"const": 1}))
.unwrap()
.validate(&json!(1.0))
.expect("admitted final numeric equality remains mathematical");
}
fn schema_raw_large_string_work_fixtures(excess: usize) -> Vec<(Value, Value)> {
let mut fixtures = schema_large_string_work_fixtures(excess);
fixtures[0].0 = json!({"allOf": vec![json!({"minLength": 1}); 63 + excess]});
fixtures[1].0 = json!({"allOf": vec![json!({"uniqueItems": true}); 37 + excess]});
for keyword in ["const", "enum"] {
let instance = json!("x".repeat(1536 * 1024));
let assertion = if keyword == "enum" {
json!([instance.clone()])
} else {
instance.clone()
};
let mut all_of = vec![json!({"$ref": "#/$defs/group"}); 2];
all_of.extend(vec![json!({"$ref": "#/$defs/large"}); 34 + excess]);
let source = json!({
"$defs": {
"large": {keyword: assertion},
"group": {"allOf": vec![json!({"$ref": "#/$defs/large"}); 64]}
},
"allOf": all_of
});
fixtures.push((source, instance));
}
fixtures
}
#[test]
fn schema_raw_large_string_work_positive() {
for (source, instance) in schema_raw_large_string_work_fixtures(0) {
validate(&source, &instance).expect(
"raw length, regex, uniqueItems, const, and enum byte work remains bounded",
);
validate_strict(&source, &instance)
.expect("strict input validation uses the same bounded raw evaluation");
}
for keyword in ["const", "enum"] {
let candidate = json!({"value": 1.0});
let assertion = if keyword == "enum" {
json!([candidate.clone()])
} else {
candidate.clone()
};
validate(&json!({keyword: assertion}), &candidate)
.expect("raw nested numeric equality retains the same representation");
}
validate(&json!({"uniqueItems": true}), &json!([1, 1.0]))
.expect("raw uniqueItems still distinguishes distinct numeric representations");
}
#[test]
fn schema_raw_large_string_work_planted_negative() {
for (source, instance) in schema_raw_large_string_work_fixtures(1) {
for result in [
validate(&source, &instance),
validate_strict(&source, &instance),
] {
let errors =
result.expect_err("one additional raw large-string unit exhausts shared fuel");
assert!(
errors
.iter()
.any(|error| { error.message == "schema validation work limit exceeded" })
);
}
}
for keyword in ["const", "enum"] {
let candidate = json!({"value": 1.0});
let assertion = if keyword == "enum" {
json!([candidate])
} else {
candidate
};
let source = json!({keyword: assertion});
let instance = json!({"value": 1});
assert!(validate(&source, &instance).is_err());
admit_final_schema(source)
.unwrap()
.validate(&instance)
.expect("only admitted-final equality treats distinct numeric spellings equally");
}
}
#[test]
fn instance_preflight_work_is_accounted_with_a_one_node_negative() {
let schema = admit_final_schema(Value::Bool(true)).expect("the true schema admits");
let accepted = Value::Array(vec![Value::Null; MAX_SCHEMA_INSTANCE_NODES - 2]);
schema
.validate(&accepted)
.expect("preflight plus one schema application fits the shared work budget");
let mut planted = accepted.clone();
planted.as_array_mut().unwrap().push(Value::Null);
let errors = schema
.validate(&planted)
.expect_err("adding one instance node exhausts the shared work budget");
assert!(
errors
.iter()
.any(|error| { error.message == "schema validation work limit exceeded" })
);
assert_eq!(
accepted
.as_array()
.expect("the baseline remains an array")
.len(),
MAX_SCHEMA_INSTANCE_NODES - 2
);
}
#[test]
fn raw_validation_does_not_charge_admitted_final_instance_preflight_work() {
let legacy_instance = Value::Array(vec![Value::Null; MAX_SCHEMA_INSTANCE_NODES - 1]);
validate(&Value::Bool(true), &legacy_instance)
.expect("raw validation retains its legacy non-preflight work accounting");
assert_eq!(
legacy_instance
.as_array()
.expect("the legacy fixture remains an array")
.len(),
MAX_SCHEMA_INSTANCE_NODES - 1
);
}
fn composition_work_schema(branches: usize) -> Value {
let unit = json!({"allOf": vec![Value::Bool(true); MAX_COMPOSITION_BRANCHES]});
json!({"allOf": vec![unit; branches]})
}
#[test]
fn composition_work_limit_positive_and_planted_negative() {
let accepted = composition_work_schema(MAX_COMPOSITION_BRANCHES - 1);
validate(&accepted, &Value::Null)
.expect("the exact shared composition-work budget is accepted");
let planted = composition_work_schema(MAX_COMPOSITION_BRANCHES);
let errors = validate(&planted, &Value::Null)
.expect_err("adding one composition branch beyond the shared work budget must reject");
assert!(
errors
.iter()
.any(|error| error.message == "schema validation work limit exceeded")
);
assert_eq!(
accepted["allOf"].as_array().unwrap().len(),
MAX_COMPOSITION_BRANCHES - 1
);
}
#[test]
fn admitted_schema_array_keywords_reject_empty_arrays_at_all_locations() {
for keyword in ["prefixItems", "allOf", "anyOf", "oneOf"] {
for (path, schema) in [
(format!("$.{keyword}"), json!({keyword: []})),
(
format!("$.$defs.unused.{keyword}"),
json!({"$defs": {"unused": {keyword: []}}}),
),
(
format!("$.else.{keyword}"),
json!({"if": true, "else": {keyword: []}}),
),
] {
let error = admit_final_schema(schema)
.expect_err("empty schema arrays must reject even in unused schema locations");
assert_eq!(error.path(), path);
assert_eq!(error.reason(), "schema array keyword must be nonempty");
assert_eq!(error.code(), "InvalidSchema");
}
}
}
#[test]
fn admitted_schema_array_keywords_preserve_singleton_schema_semantics() {
for keyword in ["prefixItems", "allOf", "anyOf", "oneOf"] {
let schema = admit_final_schema(json!({keyword: [{"type": "integer"}]}))
.expect("one valid subschema satisfies the schema-array lower bound");
let (accepted, rejected) = if keyword == "prefixItems" {
(json!([7]), json!(["7"]))
} else {
(json!(7), json!("7"))
};
assert!(schema.validate(&accepted).is_ok(), "{keyword}");
assert!(schema.validate(&rejected).is_err(), "{keyword}");
let unconstrained = admit_final_schema(json!({keyword: [true]}))
.expect("a singleton true schema is structurally valid");
assert!(unconstrained.validate(&json!([null])).is_ok(), "{keyword}");
let false_subschema = admit_final_schema(json!({keyword: [false]}))
.expect("a singleton false schema is structurally valid");
assert!(
false_subschema.validate(&json!([null])).is_err(),
"{keyword}"
);
}
}
#[test]
fn raw_schema_array_keyword_behavior_remains_legacy() {
for keyword in ["prefixItems", "allOf", "anyOf", "oneOf"] {
assert_eq!(
validate(&json!({keyword: []}), &json!([0])).is_ok(),
matches!(keyword, "prefixItems" | "allOf"),
"raw {keyword} behavior must not inherit final-schema admission",
);
}
}
#[test]
fn admitted_composition_branch_limit_positive_and_planted_negative() {
let accepted = json!({"allOf": vec![Value::Bool(true); MAX_COMPOSITION_BRANCHES]});
admit_final_schema(accepted.clone()).expect("the exact composition branch limit admits");
let mut planted = accepted.clone();
planted["allOf"]
.as_array_mut()
.expect("the allOf fixture remains an array")
.push(Value::Bool(true));
let error = admit_final_schema(planted)
.expect_err("adding one composition branch beyond the bound must reject admission");
assert_eq!(error.path(), "$.allOf");
assert_eq!(error.reason(), "composition keyword exceeds branch limit");
assert_eq!(
accepted["allOf"]
.as_array()
.expect("the baseline remains an array")
.len(),
MAX_COMPOSITION_BRANCHES
);
}
#[test]
fn admitted_schema_rejects_unresolved_local_reference() {
let error = admit_final_schema(json!({"$ref": "#/$defs/missing"}))
.expect_err("unresolved local references fail before validation");
assert_eq!(error.path(), "$.$ref");
assert_eq!(error.reason(), "unresolved local schema reference");
}
#[test]
fn external_references_fail_closed_without_resolution() {
let errors = validate(
&json!({"$ref": "https://schemas.example.test/tool.json"}),
&json!({"input": "value"}),
)
.expect_err("external references must not acquire network or filesystem authority");
assert_eq!(errors.len(), 1);
assert_eq!(errors[0].path, "root");
assert_eq!(
errors[0].message,
"external schema reference is not allowed"
);
}
#[test]
fn admitted_local_reference_target_membership_positive_and_planted_negative() {
let accepted = json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"$defs": {"always": true},
"default": {"annotation": "object"},
"$ref": "#/$defs/always"
});
let schema = admit_final_schema(accepted.clone())
.expect("a local reference to a boolean schema admits");
let instance = json!({"any": "value"});
schema
.validate(&instance)
.expect("the referenced true schema accepts the instance");
let mut planted = accepted.clone();
planted["$ref"] = json!("#/default");
let error = admit_final_schema(planted)
.expect_err("changing only the target to a non-schema annotation must reject");
assert_eq!(error.path(), "$.$ref");
assert_eq!(
error.reason(),
"local schema reference target is not an admitted schema node"
);
assert_eq!(accepted["$ref"], json!("#/$defs/always"));
assert_eq!(instance, json!({"any": "value"}));
}
#[test]
fn admitted_dynamic_reference_target_membership_positive_and_planted_negative() {
let accepted = json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"$defs": {"always": true},
"default": {"annotation": "object"},
"$dynamicRef": "#/$defs/always"
});
let schema = admit_final_schema(accepted.clone())
.expect("a local dynamic reference to a boolean schema admits");
let instance = json!({"any": "value"});
schema
.validate(&instance)
.expect("the dynamically referenced true schema accepts the instance");
let mut planted = accepted.clone();
planted["$dynamicRef"] = json!("#/default");
let error = admit_final_schema(planted)
.expect_err("changing only the dynamic target to a non-schema annotation must reject");
assert_eq!(error.path(), "$.$dynamicRef");
assert_eq!(
error.reason(),
"local schema reference target is not an admitted schema node"
);
assert_eq!(accepted["$dynamicRef"], json!("#/$defs/always"));
assert_eq!(instance, json!({"any": "value"}));
}
#[test]
fn admitted_enum_entry_limit_positive_and_planted_negative() {
let values: Vec<Value> = (0..MAX_SCHEMA_ASSERTION_ENTRIES)
.map(|index| json!(format!("value-{index}")))
.collect();
let accepted = json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"enum": values
});
let schema =
admit_final_schema(accepted.clone()).expect("the exact enum entry budget admits");
let instance = json!("value-0");
schema
.validate(&instance)
.expect("the first bounded enum value validates");
let mut planted = accepted.clone();
planted["enum"]
.as_array_mut()
.expect("enum remains an array")
.push(json!("value-over-limit"));
let error = admit_final_schema(planted)
.expect_err("adding one enum member beyond the limit must reject");
assert_eq!(error.path(), "$.enum");
assert_eq!(error.reason(), "enum exceeds entry limit");
assert_eq!(
accepted["enum"]
.as_array()
.expect("enum remains an array")
.len(),
MAX_SCHEMA_ASSERTION_ENTRIES
);
assert_eq!(instance, json!("value-0"));
}
#[test]
fn admitted_required_entry_limit_positive_and_planted_negative() {
let members: Vec<Value> = (0..MAX_SCHEMA_ASSERTION_ENTRIES)
.map(|index| json!(format!("field-{index}")))
.collect();
let accepted = json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": "object",
"required": members
});
let schema =
admit_final_schema(accepted.clone()).expect("the exact required-entry budget admits");
let instance = object_with_null_members(MAX_SCHEMA_ASSERTION_ENTRIES);
schema
.validate(&instance)
.expect("every required property at the entry limit is present");
let mut planted = accepted.clone();
planted["required"]
.as_array_mut()
.expect("required remains an array")
.push(json!("field-over-limit"));
let error = admit_final_schema(planted)
.expect_err("adding one required member beyond the limit must reject");
assert_eq!(error.path(), "$.required");
assert_eq!(error.reason(), "required exceeds entry limit");
assert_eq!(
accepted["required"]
.as_array()
.expect("required remains an array")
.len(),
MAX_SCHEMA_ASSERTION_ENTRIES
);
assert_eq!(
instance
.as_object()
.expect("instance remains an object")
.len(),
MAX_SCHEMA_ASSERTION_ENTRIES
);
}
#[test]
fn admitted_dependent_required_entry_limit_positive_and_planted_negative() {
let members: Vec<Value> = (0..MAX_SCHEMA_ASSERTION_ENTRIES)
.map(|index| json!(format!("field-{index}")))
.collect();
let accepted = json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": "object",
"dependentRequired": {"trigger": members}
});
let schema = admit_final_schema(accepted.clone())
.expect("the exact dependent-required entry budget admits");
let mut instance = object_with_null_members(MAX_SCHEMA_ASSERTION_ENTRIES);
instance["trigger"] = Value::Null;
schema
.validate(&instance)
.expect("every bounded dependent requirement is present");
let mut planted = accepted.clone();
planted["dependentRequired"]["trigger"]
.as_array_mut()
.expect("dependent-required members remain an array")
.push(json!("field-over-limit"));
let error = admit_final_schema(planted)
.expect_err("adding one dependent requirement beyond the limit must reject");
assert_eq!(error.path(), "$.dependentRequired");
assert_eq!(
error.reason(),
"dependentRequired values exceed entry limit"
);
assert_eq!(
accepted["dependentRequired"]["trigger"]
.as_array()
.expect("baseline members remain an array")
.len(),
MAX_SCHEMA_ASSERTION_ENTRIES
);
assert_eq!(
instance
.as_object()
.expect("instance remains an object")
.len(),
MAX_SCHEMA_ASSERTION_ENTRIES + 1
);
}
#[test]
fn admitted_dependent_required_work_budget_includes_root_overhead() {
let mut dependencies = serde_json::Map::new();
let mut instance = serde_json::Map::new();
for index in 0..MAX_SCHEMA_ASSERTION_ENTRIES {
let member_count = if index + 1 == MAX_SCHEMA_ASSERTION_ENTRIES {
MAX_SCHEMA_ASSERTION_ENTRIES - 2
} else {
MAX_SCHEMA_ASSERTION_ENTRIES - 1
};
let trigger = format!("trigger-{index}");
let mut members = Vec::with_capacity(member_count);
for member_index in 0..member_count {
let member = format!("required-{index}-{member_index}");
members.push(json!(member.clone()));
if index == 0 {
instance.insert(member, Value::Null);
}
}
dependencies.insert(trigger.clone(), Value::Array(members));
if index == 0 {
instance.insert(trigger, Value::Null);
}
}
let accepted = json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": "object",
"dependentRequired": dependencies
});
let instance = Value::Object(instance);
admit_final_schema(accepted.clone())
.expect("the exact dependentRequired payload plus root work budget admits")
.validate(&instance)
.expect("the exact dependentRequired work budget validates");
let mut planted = accepted.clone();
planted["dependentRequired"]["trigger-0"]
.as_array_mut()
.expect("planted dependent requirements remain an array")
.push(json!("required-over-budget"));
let error = admit_final_schema(planted)
.expect_err("one extra dependent requirement beyond root-inclusive work must reject");
assert_eq!(error.path(), "$.dependentRequired");
assert_eq!(
error.reason(),
"dependentRequired exceeds validation work budget"
);
assert_eq!(
accepted["dependentRequired"]
.as_object()
.expect("baseline dependencies remain an object")
.len(),
MAX_SCHEMA_ASSERTION_ENTRIES
);
assert_eq!(
accepted["dependentRequired"]["trigger-0"]
.as_array()
.expect("baseline dependency members remain an array")
.len(),
MAX_SCHEMA_ASSERTION_ENTRIES - 1
);
assert_eq!(
instance
.as_object()
.expect("instance remains an object")
.len(),
MAX_SCHEMA_ASSERTION_ENTRIES
);
}
#[test]
fn admitted_pattern_byte_limit_positive_and_planted_negative() {
let pattern = "a".repeat(MAX_PATTERN_BYTES);
let accepted = json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": "string",
"pattern": pattern
});
let schema =
admit_final_schema(accepted.clone()).expect("the exact pattern byte budget admits");
let instance = json!("a".repeat(MAX_PATTERN_BYTES));
schema
.validate(&instance)
.expect("the bounded exact-length pattern matches the instance");
let mut planted = accepted.clone();
planted["pattern"] = json!(format!("{}a", accepted["pattern"].as_str().unwrap()));
let error = admit_final_schema(planted)
.expect_err("adding one pattern byte beyond the limit must reject");
assert_eq!(error.path(), "$.pattern");
assert_eq!(error.reason(), "pattern exceeds byte limit");
assert_eq!(
accepted["pattern"]
.as_str()
.expect("baseline pattern remains a string")
.len(),
MAX_PATTERN_BYTES
);
assert_eq!(instance, json!("a".repeat(MAX_PATTERN_BYTES)));
}
#[test]
fn admitted_schema_type_uniqueness_positive() {
let accepted = json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": ["string", "number"]
});
let schema = admit_final_schema(accepted).expect("unique type array entries admit");
let str_instance = json!("hello");
let num_instance = json!(42);
schema
.validate(&str_instance)
.expect("string instance matches union type");
schema
.validate(&num_instance)
.expect("number instance matches union type");
}
#[test]
fn admitted_schema_type_duplicate_planted_negative() {
let accepted = json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": ["string", "number"]
});
let mut planted = accepted;
planted["type"] = json!(["string", "number", "string"]);
let error = admit_final_schema(planted).expect_err("duplicate type array entries reject");
assert_eq!(error.path(), "$.type");
assert_eq!(error.reason(), "type array entries must be unique");
}
#[test]
fn admitted_schema_type_seven_primitives_boundary_positive() {
let accepted = json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": [
"array",
"boolean",
"integer",
"null",
"number",
"object",
"string"
]
});
let schema = admit_final_schema(accepted).expect("seven unique primitive types admit");
schema
.validate(&json!([1, 2]))
.expect("array instance validates");
schema
.validate(&json!(true))
.expect("boolean instance validates");
schema
.validate(&json!(42))
.expect("integer instance validates");
schema
.validate(&json!(null))
.expect("null instance validates");
schema
.validate(&json!(1.5))
.expect("number instance validates");
schema
.validate(&json!({"k": "v"}))
.expect("object instance validates");
schema
.validate(&json!("text"))
.expect("string instance validates");
}
#[test]
fn admitted_schema_type_eighth_element_boundary_negative() {
let planted = json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": [
"array",
"boolean",
"integer",
"null",
"number",
"object",
"string",
"string"
]
});
let error = admit_final_schema(planted).expect_err("eighth duplicate element rejects");
assert_eq!(error.path(), "$.type");
assert_eq!(error.reason(), "type array entries must be unique");
}
#[test]
fn admitted_schema_required_uniqueness_positive() {
let accepted = json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"}
},
"required": ["name", "age"]
});
let schema = admit_final_schema(accepted).expect("unique required array entries admit");
let instance = json!({
"name": "Alice",
"age": 30
});
schema
.validate(&instance)
.expect("unique required fields validate");
}
#[test]
fn admitted_schema_required_duplicate_planted_negative() {
let accepted = json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"}
},
"required": ["name", "age"]
});
let mut planted = accepted;
planted["required"] = json!(["name", "age", "name"]);
let error = admit_final_schema(planted).expect_err("duplicate required entries reject");
assert_eq!(error.path(), "$.required");
assert_eq!(error.reason(), "required entries must be unique");
}
#[test]
fn admitted_schema_dependent_required_uniqueness_positive() {
let accepted = json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": "object",
"properties": {
"billing": {"type": "string"},
"street": {"type": "string"},
"zip": {"type": "string"}
},
"dependentRequired": {
"billing": ["street", "zip"]
}
});
let schema = admit_final_schema(accepted).expect("unique dependentRequired entries admit");
let instance = json!({
"billing": "enabled",
"street": "123 Main St",
"zip": "12345"
});
schema
.validate(&instance)
.expect("unique dependent requirements validate");
}
#[test]
fn admitted_schema_dependent_required_duplicate_planted_negative() {
let accepted = json!({
"$schema": FINAL_JSON_SCHEMA_DIALECT,
"type": "object",
"properties": {
"billing": {"type": "string"},
"street": {"type": "string"},
"zip": {"type": "string"}
},
"dependentRequired": {
"billing": ["street", "zip"]
}
});
let mut planted = accepted;
planted["dependentRequired"]["billing"] = json!(["street", "zip", "street"]);
let error = admit_final_schema(planted).expect_err("duplicate dependentRequired rejects");
assert_eq!(error.path(), "$.dependentRequired");
assert_eq!(
error.reason(),
"dependentRequired array entries must be unique"
);
}
#[test]
fn test_type_validation_string() {
let schema = json!({"type": "string"});
assert!(validate(&schema, &json!("hello")).is_ok());
assert!(validate(&schema, &json!(123)).is_err());
}
#[test]
fn test_type_validation_number() {
let schema = json!({"type": "number"});
assert!(validate(&schema, &json!(123)).is_ok());
assert!(validate(&schema, &json!(12.5)).is_ok());
assert!(validate(&schema, &json!("hello")).is_err());
}
#[test]
fn test_type_validation_integer() {
let schema = json!({"type": "integer"});
assert!(validate(&schema, &json!(123)).is_ok());
assert!(validate(&schema, &json!(12.5)).is_err());
}
#[test]
fn test_type_validation_boolean() {
let schema = json!({"type": "boolean"});
assert!(validate(&schema, &json!(true)).is_ok());
assert!(validate(&schema, &json!(false)).is_ok());
assert!(validate(&schema, &json!(1)).is_err());
}
#[test]
fn test_type_validation_object() {
let schema = json!({"type": "object"});
assert!(validate(&schema, &json!({})).is_ok());
assert!(validate(&schema, &json!({"a": 1})).is_ok());
assert!(validate(&schema, &json!([])).is_err());
}
#[test]
fn test_type_validation_array() {
let schema = json!({"type": "array"});
assert!(validate(&schema, &json!([])).is_ok());
assert!(validate(&schema, &json!([1, 2, 3])).is_ok());
assert!(validate(&schema, &json!({})).is_err());
}
#[test]
fn test_type_validation_null() {
let schema = json!({"type": "null"});
assert!(validate(&schema, &json!(null)).is_ok());
assert!(validate(&schema, &json!(0)).is_err());
}
#[test]
fn test_type_validation_union() {
let schema = json!({"type": ["string", "number"]});
assert!(validate(&schema, &json!("hello")).is_ok());
assert!(validate(&schema, &json!(123)).is_ok());
assert!(validate(&schema, &json!(true)).is_err());
}
#[test]
fn test_required_fields() {
let schema = json!({
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"}
},
"required": ["name"]
});
assert!(validate(&schema, &json!({"name": "Alice"})).is_ok());
assert!(validate(&schema, &json!({"name": "Alice", "age": 30})).is_ok());
assert!(validate(&schema, &json!({"age": 30})).is_err());
assert!(validate(&schema, &json!({})).is_err());
}
#[test]
fn test_enum_validation() {
let schema = json!({"enum": ["red", "green", "blue"]});
assert!(validate(&schema, &json!("red")).is_ok());
assert!(validate(&schema, &json!("yellow")).is_err());
}
#[test]
fn test_const_validation() {
let schema = json!({"const": "fixed"});
assert!(validate(&schema, &json!("fixed")).is_ok());
assert!(validate(&schema, &json!("other")).is_err());
}
#[test]
fn test_string_length() {
let schema = json!({
"type": "string",
"minLength": 2,
"maxLength": 5
});
assert!(validate(&schema, &json!("ab")).is_ok());
assert!(validate(&schema, &json!("abcde")).is_ok());
assert!(validate(&schema, &json!("a")).is_err());
assert!(validate(&schema, &json!("abcdef")).is_err());
}
#[test]
fn test_string_pattern() {
let schema = json!({
"type": "string",
"pattern": "^[a-z]+$"
});
assert!(validate(&schema, &json!("hello")).is_ok());
assert!(validate(&schema, &json!("Hello")).is_err());
assert!(validate(&schema, &json!("hello123")).is_err());
}
#[test]
fn ecmascript_word_boundaries_follow_ascii_word_characters() {
let cases: [(&str, &[&str], &[&str]); 6] = [
(r"^a\b.$", &["aπ", "aé", "a!"], &["ab", "a_", "a1"]),
(r"^a\B.$", &["ab", "a_", "a1"], &["aπ", "aé", "a!"]),
(r"^.\ba$", &["πa", "éa", "!a"], &["ba", "_a", "1a"]),
(r"^.\Ba$", &["ba", "_a", "1a"], &["πa", "éa", "!a"]),
(r"^\b.+\b$", &["a", "42", "a_1"], &["π", "é", "!"]),
(r"^\B.+\B$", &["π", "é", "!"], &["a", "42", "a_1"]),
];
for (pattern, accepted, rejected) in cases {
let source = json!({"pattern": pattern});
let admitted = admit_final_schema(source.clone()).unwrap();
for (values, expected) in [(accepted, true), (rejected, false)] {
for value in values {
let value = json!(value);
assert_eq!(
admitted.validate(&value).is_ok(),
expected,
"{pattern}: {value:?}"
);
assert_eq!(
validate(&source, &value).is_ok(),
expected,
"{pattern}: {value:?}"
);
}
}
assert_eq!(admitted.schema(), &source);
}
for (pattern, accepts_empty) in [(r"^\B$", true), (r"^\b$", false)] {
let admitted = admit_final_schema(json!({"pattern": pattern})).unwrap();
assert_eq!(admitted.validate(&json!("")).is_ok(), accepts_empty);
}
}
#[test]
fn ecmascript_dot_excludes_each_line_terminator() {
let accepted = ['a', 'é', '🦀', '\0', '\t', '\u{b}', '\u{c}', '\u{85}'];
let rejected = ['\n', '\r', '\u{2028}', '\u{2029}'];
for (pattern, prefix, suffix) in [(r"^.$", "", ""), (r"^a.b$", "a", "b")] {
let source = json!({"pattern": pattern});
let admitted = admit_final_schema(source.clone()).unwrap();
for (characters, expected) in
[(accepted.as_slice(), true), (rejected.as_slice(), false)]
{
for character in characters {
let value = json!(format!("{prefix}{character}{suffix}"));
assert_eq!(
admitted.validate(&value).is_ok(),
expected,
"{pattern}: {character:?}"
);
assert_eq!(
validate(&source, &value).is_ok(),
expected,
"{pattern}: {character:?}"
);
}
}
}
}
#[test]
fn ecmascript_dot_preserves_flag_scopes_and_extended_comments() {
for pattern in [
r"(?s)^.$",
r"^(?s:.)$",
r"(?x)( ?s:^.$)",
r"(?x)( ?s)^.$",
"(?x)( # ignored [ ( . \\b\n ?s:^.$)",
] {
let source = json!({"pattern": pattern});
let admitted = admit_final_schema(source.clone()).unwrap();
for value in ["\n", "\r", "\u{2028}", "\u{2029}"] {
assert!(admitted.validate(&json!(value)).is_ok(), "{pattern}");
assert!(validate(&source, &json!(value)).is_ok(), "{pattern}");
}
assert!(admitted.validate(&json!("")).is_err());
assert!(admitted.validate(&json!("aa")).is_err());
}
for (pattern, accepted, rejected) in [
(r"^(?s:.)(?-s:.)$", "\ra", "\r\r"),
(r"^(?s:.).$", "\ra", "\r\r"),
(r"^((?s).).$", "\ra", "\r\r"),
(r"^(?s:.(?-s:.).).$", "\na\rb", "\na\r\r"),
(r"(?s)^.(?-s:.)..$", "\na\r\u{2028}", "\n\r\r\u{2028}"),
(r"^(?P<a.1>.)$", "a", "\r"),
(r"^(?<a.1>.)$", "a", "\r"),
(r"^(?P<a[>.)$", "a", "\r"),
(r"^(?<a]>.)$", "a", "\r"),
(r"^(?P<a[1]>.)$", "a", "\r"),
(r"^(?s:(?P<a.1>.))(?<b[>.)$", "\ra", "\r\r"),
(r"^(?P<a.1>(?s).).$", "\ra", "\r\r"),
(r"^(?P<a[>a)\b.$", "aπ", "ab"),
(r"(?x)^( ?P<a.1>.)$", "a", "\r"),
(r"(?x)^(?P<a.1>( ?s).).$", "\ra", "\r\r"),
("(?x)^( # capture prefix [ . \\b\n ?<a[>.)$", "a", "\r"),
(r"(?i:^\bπ\b$)", "π", "!"),
(r"(?x)( ?i:^\bπ\b$)", "π", "!"),
(r"^(?i:a)\b.$", "aπ", "ab"),
(
"(?x) ^ [\\].] # ignored [ ( . \\b\n \\b a . $",
".ab",
".a\r",
),
(r"(?x) ^ [ ^ ].] . $", "ab", "a\r"),
] {
let source = json!({"pattern": pattern});
let admitted = admit_final_schema(source.clone()).unwrap();
assert!(admitted.validate(&json!(accepted)).is_ok(), "{pattern}");
assert!(admitted.validate(&json!(rejected)).is_err(), "{pattern}");
assert!(validate(&source, &json!(accepted)).is_ok(), "{pattern}");
assert!(validate(&source, &json!(rejected)).is_err(), "{pattern}");
}
}
#[test]
fn ecmascript_pattern_class_backspace_and_literal_escapes() {
for (pattern, accepted, rejected) in [
(r"^[\b]$", "\u{8}", "b"),
(r"^[^\b]$", "b", "\u{8}"),
(r"^[\b-\r]$", "\t", "\u{7}"),
(r"^[\b-\r]$", "\r", "\u{e}"),
(r"^[\\b]+$", r"\b", "\u{8}"),
(r"^\\b$", r"\b", "\u{8}"),
(r"^[.]$", ".", "a"),
(r"^\.$", ".", "a"),
(r"^\\.$", r"\a", "\\\r"),
(r"^\\\.$", r"\.", r"\a"),
(r"^[\].]+$", "].", "a"),
(r"^\[.\]$", "[a]", "[\r]"),
(r"^\p{Age:1.1}.$", "ab", "a\r"),
(r"^\P{Age:1.1}.$", "🦀a", "🦀\r"),
(r"^[\p{Age:1.1}].$", "ab", "a\r"),
(
"(?x)^\\p # prefix } . [ \\b\n {Age:1.1 # body } [ . \\b\n }.$",
"ab",
"a\r",
),
(r"^\x{2E}.$", ".a", ".\r"),
(r"^\u{5B}.$", "[a", "[\r"),
(r"^\U{5D}.$", "]a", "]\r"),
(
"(?x)^\\u # prefix } . [\n {4 # body } . [\n 1}.$",
"Aa",
"A\r",
),
(r"^\b{start}Ï€.$", "Ï€a", "Ï€\r"),
(r"^Ï€\b{end}.$", "Ï€!", "Ï€a"),
(r"^\b{start-half}Ï€.$", "Ï€a", "Ï€\r"),
(r"^Ï€\b{end-half}.$", "Ï€!", "Ï€a"),
("(?x)^\\b{ s # name } . [\n t a r t }Ï€.$", "Ï€a", "Ï€\r"),
(r"^a\b{1}.$", "aπ", "ab"),
("(?x)^a\\b{ # count } start\n 1 }.$", "aπ", "ab"),
] {
let source = json!({"pattern": pattern});
let admitted = admit_final_schema(source.clone()).unwrap();
assert!(admitted.validate(&json!(accepted)).is_ok(), "{pattern}");
assert!(admitted.validate(&json!(rejected)).is_err(), "{pattern}");
assert!(validate(&source, &json!(accepted)).is_ok(), "{pattern}");
assert!(validate(&source, &json!(rejected)).is_err(), "{pattern}");
assert_eq!(admitted.schema(), &source);
}
for pattern in [
r"[\B]",
r"[\b-\d]",
r"[\d-\b]",
r"[\b",
r"\b(",
r".(",
r"(?x)(? s : .)",
r"(?x)(?s - s:.)",
] {
let source = json!({"pattern": pattern});
assert!(admit_final_schema(source.clone()).is_err(), "{pattern}");
assert!(validate(&source, &json!("a")).is_err(), "{pattern}");
}
}
#[test]
fn ecmascript_assertions_and_dot_control_property_annotations() {
for (pattern, accepted, rejected) in [
(r"^a\b.$", "aπ", "ab"),
(r"^a\B.$", "ab", "aπ"),
(r"^.$", "a", "\r"),
(r"^.$", "é", "\u{2028}"),
(r"^.$", "é", "\u{2029}"),
(r"^[\b]$", "\u{8}", "b"),
(r"^[.]$", ".", "a"),
(r"^\\b$", r"\b", "\u{8}"),
] {
let source = json!({
"patternProperties": {pattern: {"type": "integer"}},
"additionalProperties": false
});
let admitted = admit_final_schema(source.clone()).unwrap();
assert!(
admitted.validate(&json!({accepted: 1})).is_ok(),
"{pattern}"
);
assert!(
admitted.validate(&json!({rejected: 1})).is_err(),
"{pattern}"
);
assert!(
admitted.validate(&json!({accepted: "1"})).is_err(),
"{pattern}"
);
assert!(
validate(&source, &json!({accepted: 1})).is_ok(),
"{pattern}"
);
assert!(
validate(&source, &json!({rejected: 1})).is_err(),
"{pattern}"
);
let evaluated = admit_final_schema(json!({
"allOf": [{"patternProperties": {pattern: {"type": "integer"}}}],
"unevaluatedProperties": false
}))
.unwrap();
assert!(
evaluated.validate(&json!({accepted: 1})).is_ok(),
"{pattern}"
);
assert!(
evaluated.validate(&json!({rejected: 1})).is_err(),
"{pattern}"
);
assert!(
evaluated.validate(&json!({accepted: "1"})).is_err(),
"{pattern}"
);
let names = admit_final_schema(json!({"propertyNames": {"pattern": pattern}})).unwrap();
assert!(names.validate(&json!({accepted: 1})).is_ok(), "{pattern}");
assert!(names.validate(&json!({rejected: 1})).is_err(), "{pattern}");
}
}
#[test]
fn ecmascript_assertion_and_dot_normalization_preserves_bounds() {
let prefix = "a".repeat(MAX_PATTERN_BYTES - 1);
let source = json!({"pattern": format!("{prefix}.")});
let admitted = admit_final_schema(source.clone()).unwrap();
assert!(admitted.validate(&json!(format!("{prefix}b"))).is_ok());
assert!(admitted.validate(&json!(format!("{prefix}\r"))).is_err());
let oversized = json!({"pattern": format!("a{prefix}.")});
assert_eq!(
admit_final_schema(oversized.clone()).unwrap_err().reason(),
"pattern exceeds byte limit"
);
assert!(validate(&oversized, &json!(format!("a{prefix}b"))).is_err());
let depth = usize::try_from(SCHEMA_PATTERN_SOURCE_NEST_LIMIT).unwrap();
for (atom, accepted, rejected) in [(r"\b", "a", "Ï€"), (".", "a", "\r")] {
let bounded = format!("{}{atom}{}", "(".repeat(depth), ")".repeat(depth));
let source = json!({"pattern": bounded});
let admitted = admit_final_schema(source.clone()).unwrap();
assert!(admitted.validate(&json!(accepted)).is_ok(), "{atom}");
assert!(admitted.validate(&json!(rejected)).is_err(), "{atom}");
let excessive = json!({"pattern": format!("({bounded})")});
assert!(admit_final_schema(excessive.clone()).is_err(), "{atom}");
assert!(validate(&excessive, &json!(accepted)).is_err(), "{atom}");
}
}
#[test]
fn test_string_pattern_invalid_regex_is_error() {
let schema = json!({
"type": "string",
"pattern": "("
});
assert!(validate(&schema, &json!("anything")).is_err());
}
#[allow(clippy::unicode_not_nfc)]
#[test]
fn ecmascript_shorthand_patterns_distinguish_ascii_and_unicode() {
let cases: [(&str, &[&str], &[&str]); 6] = [
(r"^\d+$", &["0", "42"], &["߀", "৪২", "a"]),
(r"^\D+$", &["߀", "৪২", "é"], &["0", "42"]),
(r"^\w+$", &["a", "Az_42"], &["é", "৪২", "K", "\u{200c}"]),
(r"^\W+$", &["é", "৪২", "K", "\u{200c}"], &["a", "Az_42"]),
(
r"^\s+$",
&[" \t\n", "\u{feff}", "\u{2029}"],
&["\u{85}", "a"],
),
(
r"^\S+$",
&["\u{85}", "a"],
&[" \t\n", "\u{feff}", "\u{2029}"],
),
];
for (pattern, accepted, rejected) in cases {
let source = json!({"type": "string", "pattern": pattern});
let admitted = admit_final_schema(source.clone()).unwrap();
for value in accepted {
assert!(
admitted.validate(&json!(value)).is_ok(),
"{pattern}: {value:?}"
);
assert!(
validate(&source, &json!(value)).is_ok(),
"{pattern}: {value:?}"
);
}
for value in rejected {
assert!(
admitted.validate(&json!(value)).is_err(),
"{pattern}: {value:?}"
);
assert!(
validate(&source, &json!(value)).is_err(),
"{pattern}: {value:?}"
);
}
assert_eq!(admitted.schema(), &source);
}
}
#[test]
fn ecmascript_shorthand_whitespace_uses_white_space_and_line_terminators() {
let whitespace = [
'\t', '\n', '\u{b}', '\u{c}', '\r', ' ', '\u{a0}', '\u{1680}', '\u{2000}', '\u{2001}',
'\u{2002}', '\u{2003}', '\u{2004}', '\u{2005}', '\u{2006}', '\u{2007}', '\u{2008}',
'\u{2009}', '\u{200a}', '\u{2028}', '\u{2029}', '\u{202f}', '\u{205f}', '\u{3000}',
'\u{feff}',
];
let other = ['\u{1}', '\u{85}', '\u{180e}', '\u{200b}', '\u{2060}', 'a'];
for (pattern, inverted) in [(r"^\s$", false), (r"^\S$", true)] {
let admitted = admit_final_schema(json!({"pattern": pattern})).unwrap();
for character in whitespace {
assert_eq!(
admitted.validate(&json!(character.to_string())).is_ok(),
!inverted,
"{pattern}: U+{:04X}",
u32::from(character)
);
}
for character in other {
assert_eq!(
admitted.validate(&json!(character.to_string())).is_ok(),
inverted,
"{pattern}: U+{:04X}",
u32::from(character)
);
}
}
}
#[test]
fn ecmascript_shorthand_classes_compose_inside_brackets() {
for (pattern, accepted, rejected) in [
(r"^[\dA-F]+$", "FACE42", "৪২"),
(r"^[^\d]+$", "৪২", "42"),
(r"^[\D_]+$", "৪২_", "42"),
(r"^[\w-]+$", "field_42-", "é"),
(r"^[^\w]+$", "é", "a"),
(r"^[\W\d]+$", "é42", "a"),
(r"^[\s_]+$", "\u{feff}_", "\u{85}"),
(r"^[^\s]+$", "\u{85}", "\u{feff}"),
(r"^[\S_]+$", "\u{85}_", "\u{feff}"),
(r"^[^\S]+$", "\u{feff}", "\u{85}"),
(r"^[\s\S]+$", "é\n\u{feff}\u{85}", ""),
] {
let source = json!({"pattern": pattern});
let admitted = admit_final_schema(source.clone()).unwrap();
assert!(admitted.validate(&json!(accepted)).is_ok(), "{pattern}");
assert!(admitted.validate(&json!(rejected)).is_err(), "{pattern}");
assert!(validate(&source, &json!(accepted)).is_ok(), "{pattern}");
assert!(validate(&source, &json!(rejected)).is_err(), "{pattern}");
}
}
#[test]
fn ecmascript_shorthand_normalization_preserves_literals_and_unicode_properties() {
for (pattern, accepted, rejected) in [
(r"^\\d$", r"\d", "4"),
(r"^\\s$", r"\s", "\u{feff}"),
(r"^[\\dw]+$", "dw\\", "4"),
(r"^\\\\\d$", r"\\4", r"\\৪"),
(r"^\[\d\]$", "[4]", "[৪]"),
(r"^\u{00E9}\d$", "é4", "é৪"),
(r"^\p{Letter}+$", "école", "42"),
(r"\wcole", "l'ecole", "l'école"),
] {
let source = json!({"pattern": pattern});
let admitted = admit_final_schema(source.clone()).unwrap();
assert!(admitted.validate(&json!(accepted)).is_ok(), "{pattern}");
assert!(admitted.validate(&json!(rejected)).is_err(), "{pattern}");
assert_eq!(admitted.schema(), &source);
}
}
#[test]
fn ecmascript_shorthand_pattern_properties_control_applicators_and_annotations() {
for (pattern, accepted, rejected) in [
(r"^\d+$", "42", "৪২"),
(r"^\D+$", "৪২", "42"),
(r"^[\w]+$", "field_42", "é"),
(r"^[\W]+$", "é", "field_42"),
(r"^\s+$", "\u{feff}", "\u{85}"),
(r"^\S+$", "\u{85}", "\u{feff}"),
(r"^\\d$", r"\d", "4"),
] {
let source = json!({
"type": "object",
"patternProperties": {pattern: {"type": "integer"}},
"additionalProperties": false
});
let admitted = admit_final_schema(source.clone()).unwrap();
assert!(
admitted.validate(&json!({accepted: 1})).is_ok(),
"{pattern}"
);
assert!(
admitted.validate(&json!({rejected: 1})).is_err(),
"{pattern}"
);
assert!(
admitted.validate(&json!({accepted: "1"})).is_err(),
"{pattern}"
);
assert!(
validate(&source, &json!({accepted: 1})).is_ok(),
"{pattern}"
);
assert!(
validate(&source, &json!({rejected: 1})).is_err(),
"{pattern}"
);
let evaluated = admit_final_schema(json!({
"allOf": [{"patternProperties": {pattern: {"type": "integer"}}}],
"unevaluatedProperties": false
}))
.unwrap();
assert!(
evaluated.validate(&json!({accepted: 1})).is_ok(),
"{pattern}"
);
assert!(
evaluated.validate(&json!({rejected: 1})).is_err(),
"{pattern}"
);
assert!(
evaluated.validate(&json!({accepted: "1"})).is_err(),
"{pattern}"
);
}
}
#[test]
fn ecmascript_shorthand_patterns_bound_source_before_expansion_and_reject_malformed_syntax() {
let prefix = "a".repeat(MAX_PATTERN_BYTES - 2);
let source = json!({"pattern": format!("{prefix}\\s")});
let admitted = admit_final_schema(source.clone()).unwrap();
let accepted = json!(format!("{prefix}\u{feff}"));
let rejected = json!(format!("{prefix}\u{85}"));
assert!(admitted.validate(&accepted).is_ok());
assert!(admitted.validate(&rejected).is_err());
assert!(validate(&source, &accepted).is_ok());
let oversized = json!({"pattern": format!("a{prefix}\\s")});
assert_eq!(
admit_final_schema(oversized.clone()).unwrap_err().reason(),
"pattern exceeds byte limit"
);
let errors = validate(&oversized, &accepted).unwrap_err();
assert!(
errors
.iter()
.any(|error| error.message == "pattern exceeds byte limit")
);
assert!(compile_schema_pattern(oversized["pattern"].as_str().unwrap()).is_err());
for pattern in [
"(",
r"[\d",
"\\",
r"[\d-a]",
r"[a-\s]",
r"[A-\d]",
r"[0-\s]",
r"[\D-\S]",
r"(?-u:\s)",
] {
let source = json!({"pattern": pattern});
assert!(admit_final_schema(source.clone()).is_err());
assert!(validate(&source, &json!("anything")).is_err());
}
}
#[test]
fn ecmascript_shorthand_normalization_preserves_the_source_nesting_limit() {
let depth = usize::try_from(SCHEMA_PATTERN_SOURCE_NEST_LIMIT).unwrap();
for (shorthand, accepted, rejected) in [
(r"\d", "4", "৪"),
(r"\w", "a", "é"),
(r"\s", "\u{feff}", "\u{85}"),
] {
let bounded = format!("{}{shorthand}{}", "(".repeat(depth), ")".repeat(depth));
let source = json!({"pattern": bounded});
let admitted = admit_final_schema(source.clone()).unwrap();
assert!(admitted.validate(&json!(accepted)).is_ok());
assert!(admitted.validate(&json!(rejected)).is_err());
assert!(validate(&source, &json!(accepted)).is_ok());
let excessive = json!({"pattern": format!("({bounded})")});
assert!(admit_final_schema(excessive.clone()).is_err());
assert!(validate(&excessive, &json!(accepted)).is_err());
}
}
#[test]
fn test_number_range() {
let schema = json!({
"type": "number",
"minimum": 0,
"maximum": 100
});
assert!(validate(&schema, &json!(0)).is_ok());
assert!(validate(&schema, &json!(50)).is_ok());
assert!(validate(&schema, &json!(100)).is_ok());
assert!(validate(&schema, &json!(-1)).is_err());
assert!(validate(&schema, &json!(101)).is_err());
}
#[test]
fn test_number_exclusive_range() {
let schema = json!({
"type": "number",
"exclusiveMinimum": 0,
"exclusiveMaximum": 10
});
assert!(validate(&schema, &json!(1)).is_ok());
assert!(validate(&schema, &json!(9)).is_ok());
assert!(validate(&schema, &json!(0)).is_err());
assert!(validate(&schema, &json!(10)).is_err());
}
#[test]
fn test_array_items() {
let schema = json!({
"type": "array",
"items": {"type": "integer"}
});
assert!(validate(&schema, &json!([1, 2, 3])).is_ok());
assert!(validate(&schema, &json!([])).is_ok());
assert!(validate(&schema, &json!([1, "two", 3])).is_err());
}
#[test]
fn test_array_length() {
let schema = json!({
"type": "array",
"minItems": 1,
"maxItems": 3
});
assert!(validate(&schema, &json!([1])).is_ok());
assert!(validate(&schema, &json!([1, 2, 3])).is_ok());
assert!(validate(&schema, &json!([])).is_err());
assert!(validate(&schema, &json!([1, 2, 3, 4])).is_err());
}
#[test]
fn test_unique_items() {
let schema = json!({
"type": "array",
"uniqueItems": true
});
assert!(validate(&schema, &json!([1, 2, 3])).is_ok());
assert!(validate(&schema, &json!([1, 1, 2])).is_err());
}
#[test]
fn test_nested_object() {
let schema = json!({
"type": "object",
"properties": {
"person": {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"}
},
"required": ["name"]
}
}
});
assert!(validate(&schema, &json!({"person": {"name": "Alice"}})).is_ok());
assert!(validate(&schema, &json!({"person": {"name": "Alice", "age": 30}})).is_ok());
assert!(validate(&schema, &json!({"person": {"age": 30}})).is_err());
}
#[test]
fn test_additional_properties_false() {
let schema = json!({
"type": "object",
"properties": {
"name": {"type": "string"}
},
"additionalProperties": false
});
assert!(validate(&schema, &json!({"name": "Alice"})).is_ok());
assert!(validate(&schema, &json!({})).is_ok());
assert!(validate(&schema, &json!({"name": "Alice", "extra": 1})).is_err());
}
#[test]
fn test_boolean_schema() {
assert!(validate(&json!(true), &json!("anything")).is_ok());
assert!(validate(&json!(true), &json!(123)).is_ok());
assert!(validate(&json!(false), &json!("anything")).is_err());
}
#[test]
fn test_multiple_errors() {
let schema = json!({
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"}
},
"required": ["name", "age"]
});
let result = validate(&schema, &json!({}));
assert!(result.is_err());
let errors = result.unwrap_err();
assert_eq!(errors.len(), 2); }
#[test]
fn test_error_path() {
let schema = json!({
"type": "object",
"properties": {
"items": {
"type": "array",
"items": {"type": "integer"}
}
}
});
let result = validate(&schema, &json!({"items": [1, "two", 3]}));
assert!(result.is_err());
let errors = result.unwrap_err();
assert_eq!(errors.len(), 1);
assert_eq!(errors[0].path, "root.items[1]");
}
#[test]
fn admitted_strict_validation_preserves_numeric_semantics_and_object_policy() {
let schema = admit_final_schema(json!({
"type": "object",
"properties": {"count": {"type": "integer"}},
"required": ["count"]
}))
.expect("the object schema is admitted");
assert!(schema.validate_strict(&json!({"count": 1.0})).is_ok());
assert!(schema.validate_strict(&json!({"count": 1.5})).is_err());
assert!(
schema
.validate(&json!({"count": 1.0, "extra": true}))
.is_ok()
);
assert!(
schema
.validate_strict(&json!({"count": 1.0, "extra": true}))
.is_err()
);
let explicit_policy = admit_final_schema(json!({
"type": "object",
"properties": {"count": {"type": "integer"}},
"additionalProperties": true
}))
.expect("the explicit additional-property policy is admitted");
assert!(
explicit_policy
.validate_strict(&json!({"count": 1.0, "extra": true}))
.is_ok()
);
}
#[test]
fn admitted_strict_validation_preserves_unevaluated_items() {
let schema = admit_final_schema(json!({
"type": "object",
"properties": {
"values": {
"type": "array",
"prefixItems": [{"type": "integer"}],
"unevaluatedItems": false
}
},
"required": ["values"]
}))
.expect("the evaluated array schema is admitted");
assert!(schema.validate_strict(&json!({"values": [1.0]})).is_ok());
assert!(
schema
.validate_strict(&json!({"values": [1.0, 2]}))
.is_err()
);
assert!(schema.validate_strict(&json!({"values": ["one"]})).is_err());
}
#[test]
fn test_validate_strict_rejects_extra_properties() {
let schema = json!({
"type": "object",
"properties": {
"name": {"type": "string"}
}
});
assert!(validate(&schema, &json!({"name": "Alice", "extra": 123})).is_ok());
assert!(validate_strict(&schema, &json!({"name": "Alice", "extra": 123})).is_err());
assert!(validate_strict(&schema, &json!({"name": "Alice"})).is_ok());
}
#[test]
fn test_validate_strict_nested_objects() {
let schema = json!({
"type": "object",
"properties": {
"person": {
"type": "object",
"properties": {
"name": {"type": "string"}
}
}
}
});
assert!(
validate(
&schema,
&json!({
"person": {"name": "Alice", "age": 30}
})
)
.is_ok()
);
assert!(
validate_strict(
&schema,
&json!({
"person": {"name": "Alice", "age": 30}
})
)
.is_err()
);
assert!(
validate_strict(
&schema,
&json!({
"person": {"name": "Alice"}
})
)
.is_ok()
);
}
#[test]
fn test_validate_strict_preserves_explicit_additional_properties() {
let schema = json!({
"type": "object",
"properties": {
"name": {"type": "string"}
},
"additionalProperties": {"type": "integer"}
});
assert!(
validate_strict(
&schema,
&json!({
"name": "Alice",
"count": 42
})
)
.is_ok()
);
assert!(
validate_strict(
&schema,
&json!({
"name": "Alice",
"count": "not an integer"
})
)
.is_err()
);
}
#[test]
fn test_validate_strict_array_items() {
let schema = json!({
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {"type": "integer"}
}
}
});
assert!(
validate(
&schema,
&json!([
{"id": 1, "extra": "value"}
])
)
.is_ok()
);
assert!(
validate_strict(
&schema,
&json!([
{"id": 1, "extra": "value"}
])
)
.is_err()
);
assert!(
validate_strict(
&schema,
&json!([
{"id": 1}
])
)
.is_ok()
);
}
#[test]
fn test_validate_strict_empty_schema() {
let schema = json!({});
assert!(validate_strict(&schema, &json!({"anything": "goes"})).is_ok());
}
#[test]
fn test_validate_strict_non_object_types() {
let string_schema = json!({"type": "string"});
assert!(validate_strict(&string_schema, &json!("hello")).is_ok());
let number_schema = json!({"type": "number"});
assert!(validate_strict(&number_schema, &json!(42)).is_ok());
let array_schema = json!({"type": "array"});
assert!(validate_strict(&array_schema, &json!([1, 2, 3])).is_ok());
}
#[test]
fn schema_diagnostics_redact_schema_and_instance_literals() {
const SCHEMA_SECRET: &str = "schema-secret-canary-7c5f";
const INSTANCE_SECRET: &str = "instance-secret-canary-8a6e";
const PATTERN_SECRET: &str = "^pattern-secret-canary-9b7d$";
let fixtures = [
(
json!({"type": "string", "enum": [SCHEMA_SECRET]}),
json!(SCHEMA_SECRET),
json!(INSTANCE_SECRET),
),
(
json!({"const": {"credential": SCHEMA_SECRET}}),
json!({"credential": SCHEMA_SECRET}),
json!({"credential": INSTANCE_SECRET}),
),
(
json!({"type": "string", "pattern": PATTERN_SECRET}),
json!("pattern-secret-canary-9b7d"),
json!(INSTANCE_SECRET),
),
(
json!({"allOf": [{"enum": [SCHEMA_SECRET]}, {"const": SCHEMA_SECRET}]}),
json!(SCHEMA_SECRET),
json!(INSTANCE_SECRET),
),
(
json!({"minimum": 9_187_463_920_u64}),
json!(9_187_463_920_u64),
json!(9_187_463_919_u64),
),
];
for (schema, accepted, rejected) in fixtures {
validate(&schema, &accepted).expect("valid input still passes raw validation");
let admitted = admit_final_schema(schema.clone()).expect("fixture schema admits");
admitted
.validate(&accepted)
.expect("the same valid input passes admitted validation");
for errors in [
validate(&schema, &rejected).expect_err("only the instance changed"),
admitted
.validate(&rejected)
.expect_err("the same instance is invalid"),
] {
assert!(!errors.is_empty());
for error in errors {
let rendered = format!("{error} {error:?}");
for secret in [
SCHEMA_SECRET,
INSTANCE_SECRET,
PATTERN_SECRET,
"9187463920",
"9187463919",
] {
assert!(
!rendered.contains(secret),
"diagnostics must omit literal data"
);
}
assert_eq!(error.code(), "InvalidSchemaInstance");
assert!(error.message.len() < 128);
}
}
}
let malformed_pattern = json!({"pattern": "(pattern-secret-canary-9b7d"});
let errors = validate(&malformed_pattern, &json!(INSTANCE_SECRET))
.expect_err("a malformed regex still refuses");
assert_eq!(errors[0].code(), "InvalidSchema");
assert_eq!(errors[0].message, "invalid schema pattern");
assert!(!format!("{errors:?}").contains("pattern-secret-canary"));
let unresolved = json!({"$ref": "#/private-reference-secret-canary"});
let errors = validate(&unresolved, &json!(INSTANCE_SECRET))
.expect_err("unresolved references still refuse");
assert_eq!(errors[0].code(), "UnresolvedSchemaReference");
assert!(!format!("{errors:?}").contains("private-reference-secret-canary"));
}
#[test]
fn schema_diagnostics_escape_and_bound_hostile_paths() {
let name = "[red]\u{1b}[31m<value>&\n/雪\"\\.x";
let schema = json!({"properties": {(name): {"type": "string"}}});
validate(&schema, &json!({(name): "accepted"})).expect("the original field accepts");
let errors = validate(&schema, &json!({(name): 7}))
.expect_err("changing only the field's type refuses");
let path = &errors[0].path;
assert!(path.starts_with("root[\""));
assert!(path.ends_with("\"]"));
let decoded: String = serde_json::from_str(&path[5..path.len() - 1])
.expect("quoted path segments retain complete JSON escapes");
assert_eq!(decoded, name);
for forbidden in ['\u{1b}', '\n', '<', '>', '&', '雪'] {
assert!(!path.contains(forbidden));
}
assert!(!path.contains("[red]"));
let huge_name = "long-field-".repeat(500);
let schema = json!({"properties": {(huge_name.clone()): false}});
validate(&schema, &json!({})).expect("the absent optional property still accepts");
let errors = validate(&schema, &json!({(huge_name.clone()): null}))
.expect_err("adding the forbidden property rejects");
assert!(errors[0].path.len() <= MAX_SCHEMA_DIAGNOSTIC_PATH_BYTES);
assert!(errors[0].path.contains("..."));
assert!(!errors[0].path.contains(&huge_name));
let nested_name = "<field>".repeat(8);
let mut nested = json!(false);
let mut instance = json!(null);
for _ in 0..30 {
nested = json!({"properties": {(nested_name.clone()): nested}});
instance = json!({(nested_name.clone()): instance});
}
let errors = validate(&nested, &instance).expect_err("deep invalid input stays invalid");
assert!(errors[0].path.len() <= MAX_SCHEMA_DIAGNOSTIC_PATH_BYTES);
assert!(errors[0].path.ends_with("..."));
assert!(!errors[0].path.contains('<'));
}
#[test]
fn schema_diagnostics_remain_bounded_across_many_failures() {
let schema = json!({"type": "array", "items": {"const": "schema-secret-canary"}});
validate(&schema, &json!(["schema-secret-canary"])).expect("the matching array accepts");
let rejected = json!(vec!["instance-secret-canary"; MAX_VALIDATION_ERRORS + 10]);
let errors = validate(&schema, &rejected).expect_err("all mismatched items reject");
assert_eq!(errors.len(), MAX_VALIDATION_ERRORS);
for error in &errors {
assert!(error.path.len() <= MAX_SCHEMA_DIAGNOSTIC_PATH_BYTES);
assert!(error.message.len() < 128);
assert_eq!(error.code(), "InvalidSchemaInstance");
}
let rendered = format!("{errors:?}");
assert!(!rendered.contains("schema-secret-canary"));
assert!(!rendered.contains("instance-secret-canary"));
assert!(rendered.len() < MAX_VALIDATION_ERRORS * (MAX_SCHEMA_DIAGNOSTIC_PATH_BYTES + 256));
}
#[test]
fn schema_diagnostics_preserve_unicode_escape_boundaries() {
let fixtures = [
("é".repeat(32), "é".repeat(32)),
("é".repeat(33), format!("{}...", "é".repeat(32))),
(
format!("{}💡", "a".repeat(60)),
format!("{}💡", "a".repeat(60)),
),
(
format!("{}💡x", "a".repeat(60)),
format!("{}💡...", "a".repeat(60)),
),
(
format!("{}💡", "a".repeat(63)),
format!("{}...", "a".repeat(63)),
),
];
for (name, expected) in fixtures {
let schema = json!({"properties": {(name.clone()): {"type": "string"}}});
let admitted = admit_final_schema(schema.clone()).expect("Unicode field names admit");
let accepted = json!({(name.clone()): "accepted"});
validate(&schema, &accepted).expect("the original field accepts");
admitted
.validate(&accepted)
.expect("admitted validation also accepts");
let rejected = json!({(name.clone()): false});
for errors in [
validate(&schema, &rejected).expect_err("only the field type changed"),
admitted
.validate(&rejected)
.expect_err("admitted validation also refuses"),
] {
let quoted = errors[0]
.path
.strip_prefix("root[")
.unwrap()
.strip_suffix(']')
.unwrap();
let decoded: String = serde_json::from_str(quoted)
.expect("truncation preserves complete UTF-8 characters and surrogate pairs");
assert_eq!(decoded, expected);
assert!(errors[0].path.len() <= MAX_SCHEMA_DIAGNOSTIC_PATH_BYTES);
}
let error = admit_final_schema(json!({"properties": {(name): 42}}))
.expect_err("changing only the property's schema refuses admission");
let quoted = error
.path()
.strip_prefix("$.properties[")
.unwrap()
.strip_suffix(']')
.unwrap();
let decoded: String = serde_json::from_str(quoted)
.expect("admission retains the same complete escaped segment");
assert_eq!(decoded, expected);
}
}
#[test]
fn schema_admission_diagnostics_redact_pattern_and_literal_locations() {
const PATTERN_SECRET: &str = "^admission-pattern-secret-canary$";
let schema = json!({"patternProperties": {(PATTERN_SECRET): {"type": "string"}}});
admit_final_schema(schema)
.expect("the pattern rule admits")
.validate(&json!({"admission-pattern-secret-canary": "accepted"}))
.expect("the pattern rule still validates matching fields");
let error =
admit_final_schema(json!({"patternProperties": {(PATTERN_SECRET): {"type": 42}}}))
.expect_err("changing only the rule's type declaration refuses");
assert_eq!(error.path(), "$.patternProperties.type");
assert!(!format!("{error} {error:?}").contains("admission-pattern-secret-canary"));
const LITERAL_KEY: &str = "literal-object-key-secret-canary";
for keyword in ["const", "enum"] {
let accepted = json!({(LITERAL_KEY): "accepted"});
let rejected =
json!({(LITERAL_KEY): "x".repeat(MAX_SCHEMA_ASSERTION_STRING_BYTES + 1)});
let (accepted, rejected, expected_path) = if keyword == "enum" {
(json!([accepted]), json!([rejected]), "$.enum[0]")
} else {
(accepted, rejected, "$.const")
};
admit_final_schema(json!({(keyword): accepted})).expect("the bounded literal admits");
let error = admit_final_schema(json!({(keyword): rejected}))
.expect_err("an oversized string inside the literal refuses");
assert_eq!(error.path(), expected_path);
assert_eq!(error.code(), "SchemaResourceLimit");
assert!(!format!("{error} {error:?}").contains(LITERAL_KEY));
}
}
#[test]
fn schema_admission_debug_redacts_retained_schema() {
let schema = admit_final_schema(json!({"const": "retained-schema-secret-canary"}))
.expect("the bounded const schema admits");
assert_eq!(schema.schema()["const"], "retained-schema-secret-canary");
assert_eq!(format!("{schema:?}"), "AdmittedSchema { .. }");
let form = AdmittedFinalFormSchema::admit(json!({
"type": "object",
"properties": {"choice": {"type": "string", "enum": ["form-secret-canary"]}}
}))
.expect("the bounded form admits");
assert!(!format!("{form:?}").contains("form-secret-canary"));
let name = "[red]\u{1b}<admission>\n".repeat(200);
let error = admit_final_schema(json!({"properties": {(name.clone()): 42}}))
.expect_err("a non-schema property value refuses");
assert_eq!(error.code(), "InvalidSchema");
assert!(error.path().len() <= MAX_SCHEMA_DIAGNOSTIC_PATH_BYTES);
assert!(error.path().contains("..."));
let rendered = format!("{error} {error:?}");
assert!(!rendered.contains(&name));
assert!(!rendered.contains("[red]"));
assert!(!rendered.contains('<'));
assert!(!rendered.contains('\u{1b}'));
assert!(!rendered.contains('\n'));
}
#[test]
fn validation_error_display_and_error_trait() {
let err = ValidationError {
path: "root.name".to_string(),
message: "expected string".to_string(),
};
assert_eq!(err.to_string(), "root.name: expected string");
let _: &dyn std::error::Error = &err;
}
#[test]
fn validation_error_debug_and_clone() {
let err = ValidationError {
path: "root".to_string(),
message: "missing".to_string(),
};
let debug = format!("{err:?}");
assert!(debug.contains("ValidationError"));
let cloned = err.clone();
assert_eq!(cloned.path, "root");
assert_eq!(cloned.message, "missing");
}
#[test]
fn json_type_name_all_types() {
assert_eq!(json_type_name(&json!(null)), "null");
assert_eq!(json_type_name(&json!(true)), "boolean");
assert_eq!(json_type_name(&json!(42)), "integer");
assert_eq!(json_type_name(&json!(3.14)), "number");
assert_eq!(json_type_name(&json!("hello")), "string");
assert_eq!(json_type_name(&json!([])), "array");
assert_eq!(json_type_name(&json!({})), "object");
}
#[test]
fn number_multiple_of() {
let schema = json!({"type": "number", "multipleOf": 3});
assert!(validate(&schema, &json!(9)).is_ok());
assert!(validate(&schema, &json!(6)).is_ok());
assert!(validate(&schema, &json!(0)).is_ok());
assert!(validate(&schema, &json!(7)).is_err());
}
#[test]
fn object_min_max_properties() {
let schema = json!({
"type": "object",
"minProperties": 1,
"maxProperties": 2
});
assert!(validate(&schema, &json!({"a": 1})).is_ok());
assert!(validate(&schema, &json!({"a": 1, "b": 2})).is_ok());
assert!(validate(&schema, &json!({})).is_err());
assert!(validate(&schema, &json!({"a": 1, "b": 2, "c": 3})).is_err());
}
#[test]
fn prefix_items_tuple_validation() {
let schema = json!({
"type": "array",
"prefixItems": [
{"type": "string"},
{"type": "integer"}
]
});
assert!(validate(&schema, &json!(["hello", 42])).is_ok());
assert!(validate(&schema, &json!(["hello", 42, true])).is_ok()); assert!(validate(&schema, &json!([123, "wrong"])).is_err()); }
#[test]
fn prefix_items_with_additional_items_schema() {
let schema = json!({
"type": "array",
"prefixItems": [
{"type": "string"}
],
"items": {"type": "integer"}
});
assert!(validate(&schema, &json!(["hello", 1, 2])).is_ok());
assert!(validate(&schema, &json!(["hello", "bad"])).is_err());
}
#[test]
fn items_as_array_draft4_fallback() {
let schema = json!({
"type": "array",
"items": [
{"type": "string"},
{"type": "integer"}
]
});
assert!(validate(&schema, &json!(["hello", 42])).is_ok());
assert!(validate(&schema, &json!([123, "wrong"])).is_err());
}
#[test]
fn legacy_tuple_additional_items_rejects_only_the_tail() {
let schema = json!({
"type": "array",
"items": [{"type": "string"}, {"type": "integer"}],
"additionalItems": false
});
for value in [json!([]), json!(["hello"]), json!(["hello", 42])] {
assert!(validate(&schema, &value).is_ok());
}
let errors = validate(&schema, &json!(["hello", 42, true])).unwrap_err();
assert_eq!(errors.len(), 1);
assert_eq!(errors[0].path, "root[2]");
assert!(validate(&schema, &json!(["hello", "wrong"])).is_err());
let empty = json!({"items": [], "additionalItems": false});
assert!(validate(&empty, &json!([])).is_ok());
assert!(validate(&empty, &json!([null])).is_err());
}
#[test]
fn legacy_tuple_additional_items_applies_references_and_strict_objects() {
let schema = json!({
"type": "array",
"items": [{"type": "string"}],
"additionalItems": {"$ref": "#/definitions/entry"},
"definitions": {
"entry": {
"type": "object",
"properties": {"id": {"type": "integer"}},
"required": ["id"]
}
}
});
let valid = json!(["header", {"id": 1}, {"id": 2}]);
assert!(validate(&schema, &valid).is_ok());
assert!(validate_strict(&schema, &valid).is_ok());
let wrong_type = json!(["header", {"id": 1}, {"id": "secret-canary"}]);
for errors in [
validate(&schema, &wrong_type).unwrap_err(),
validate_strict(&schema, &wrong_type).unwrap_err(),
] {
assert_eq!(errors.len(), 1);
assert_eq!(errors[0].path, "root[2].id");
assert!(!format!("{errors:?}").contains("secret-canary"));
}
let direct = json!({
"items": [{"type": "string"}],
"additionalItems": {
"type": "object",
"properties": {"id": {"type": "integer"}}
}
});
let extra = json!(["header", {"id": 1, "extra": true}]);
assert!(validate(&direct, &extra).is_ok());
assert!(validate_strict(&direct, &json!(["header", {"id": 1}])).is_ok());
assert!(validate_strict(&direct, &extra).is_err());
}
#[test]
fn legacy_tuple_additional_items_is_scoped_to_its_own_tuple() {
for schema in [
json!({"additionalItems": false}),
json!({"items": true, "additionalItems": false}),
json!({"items": {"type": "integer"}, "additionalItems": false}),
json!({"allOf": [{"items": [{"type": "integer"}]}], "additionalItems": false}),
json!({"items": [{"type": "integer"}], "additionalItems": true}),
json!({"items": [{"type": "integer"}]}),
] {
assert!(validate(&schema, &json!([1, 2, 3])).is_ok(), "{schema}");
}
let modern = admit_final_schema(json!({
"prefixItems": [{"type": "integer"}],
"additionalItems": false
}))
.unwrap();
assert!(modern.validate(&json!([1, "still allowed"])).is_ok());
assert!(modern.validate_strict(&json!([1, "still allowed"])).is_ok());
}
#[test]
fn raw_schema_validation_bounds_documents_before_strict_cloning() {
let valid = json!({"type": "object", "properties": {"id": {"type": "integer"}}});
let mut deep = Value::Null;
for _ in 0..MAX_SCHEMA_VALIDATION_DEPTH {
deep = json!([deep]);
}
for (schema, reason) in [
(
json!({"type": "object", "x-annotation": deep}),
"schema document nesting limit exceeded",
),
(
json!({"type": "object", "x-annotation": vec![Value::Null; MAX_SCHEMA_DOCUMENT_NODES]}),
"schema document node limit exceeded",
),
(
json!({"type": "object", "description": "x".repeat(MAX_SCHEMA_DOCUMENT_BYTES)}),
"schema document byte limit exceeded",
),
] {
for validate in [super::validate, validate_strict] {
let errors = validate(&schema, &json!({"id": 1})).unwrap_err();
assert_eq!(errors.len(), 1);
assert_eq!(errors[0].path, "root");
assert_eq!(errors[0].message, reason);
assert!(validate(&valid, &json!({"id": 1})).is_ok());
}
}
}
#[test]
fn additional_properties_as_schema() {
let schema = json!({
"type": "object",
"properties": {
"name": {"type": "string"}
},
"additionalProperties": {"type": "integer"}
});
assert!(validate(&schema, &json!({"name": "Alice", "count": 42})).is_ok());
assert!(validate(&schema, &json!({"name": "Alice", "bad": "string"})).is_err());
}
#[test]
fn strict_schema_with_prefix_items() {
let schema = json!({
"type": "array",
"prefixItems": [
{
"type": "object",
"properties": {
"id": {"type": "integer"}
}
}
]
});
assert!(validate_strict(&schema, &json!([{"id": 1}])).is_ok());
assert!(validate_strict(&schema, &json!([{"id": 1, "extra": "val"}])).is_err());
}
#[test]
fn strict_schema_with_union_type() {
let schema = json!({
"type": ["object", "null"],
"properties": {
"name": {"type": "string"}
}
});
assert!(validate_strict(&schema, &json!(null)).is_ok());
assert!(validate_strict(&schema, &json!({"name": "Alice"})).is_ok());
assert!(validate_strict(&schema, &json!({"name": "Alice", "extra": 1})).is_err());
}
#[test]
fn unknown_type_in_matches_type_is_permissive() {
let schema = json!({"type": "custom_extension"});
assert!(validate(&schema, &json!("anything")).is_ok());
assert!(validate(&schema, &json!(42)).is_ok());
}
#[test]
fn invalid_schema_not_an_object() {
assert!(validate(&json!(42), &json!("anything")).is_ok());
assert!(validate(&json!("bad_schema"), &json!(123)).is_ok());
}
}