Compare commits
15 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| dccaa0a46e | |||
| 441597e604 | |||
| 710598752f | |||
| 5fbf64bac5 | |||
| 2dd17f0b37 | |||
| cbda45e610 | |||
| 1085964c17 | |||
| 65971d9b93 | |||
| d938058d34 | |||
| 69ab6165bb | |||
| 03beada825 | |||
| efdd7528cc | |||
| 59395a33ac | |||
| 92c0a6fc0b | |||
| 7f66a4a35a |
1
rustfmt.toml
Normal file
1
rustfmt.toml
Normal file
@ -0,0 +1 @@
|
|||||||
|
tab_spaces = 2
|
||||||
839
src/lib.rs
839
src/lib.rs
@ -2,16 +2,27 @@ use pgrx::*;
|
|||||||
|
|
||||||
pg_module_magic!();
|
pg_module_magic!();
|
||||||
|
|
||||||
use serde_json::{json, Value};
|
use boon::{CompileError, Compiler, ErrorKind, SchemaIndex, Schemas, ValidationError, Type, Types};
|
||||||
use std::{collections::HashMap, sync::RwLock};
|
|
||||||
use boon::{Compiler, Schemas, ValidationError, SchemaIndex, CompileError};
|
|
||||||
use lazy_static::lazy_static;
|
use lazy_static::lazy_static;
|
||||||
|
use serde_json::{json, Value, Number};
|
||||||
|
use std::borrow::Cow;
|
||||||
|
use std::collections::hash_map::Entry;
|
||||||
|
use std::{collections::HashMap, sync::RwLock};
|
||||||
|
|
||||||
struct BoonCache {
|
struct BoonCache {
|
||||||
schemas: Schemas,
|
schemas: Schemas,
|
||||||
id_to_index: HashMap<String, SchemaIndex>,
|
id_to_index: HashMap<String, SchemaIndex>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Structure to hold error information without lifetimes
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct Error {
|
||||||
|
path: String,
|
||||||
|
code: String,
|
||||||
|
message: String,
|
||||||
|
cause: Value, // Changed from String to Value to store JSON
|
||||||
|
}
|
||||||
|
|
||||||
lazy_static! {
|
lazy_static! {
|
||||||
static ref SCHEMA_CACHE: RwLock<BoonCache> = RwLock::new(BoonCache {
|
static ref SCHEMA_CACHE: RwLock<BoonCache> = RwLock::new(BoonCache {
|
||||||
schemas: Schemas::new(),
|
schemas: Schemas::new(),
|
||||||
@ -30,6 +41,7 @@ fn cache_json_schema(schema_id: &str, schema: JsonB, strict: bool) -> JsonB {
|
|||||||
apply_strict_validation(&mut schema_value);
|
apply_strict_validation(&mut schema_value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Create the boon compiler and enable format assertions
|
||||||
let mut compiler = Compiler::new();
|
let mut compiler = Compiler::new();
|
||||||
compiler.enable_format_assertions();
|
compiler.enable_format_assertions();
|
||||||
|
|
||||||
@ -40,7 +52,7 @@ fn cache_json_schema(schema_id: &str, schema: JsonB, strict: bool) -> JsonB {
|
|||||||
"code": "SCHEMA_RESOURCE_ADD_FAILED",
|
"code": "SCHEMA_RESOURCE_ADD_FAILED",
|
||||||
"message": format!("Failed to add schema resource '{}'", schema_id),
|
"message": format!("Failed to add schema resource '{}'", schema_id),
|
||||||
"details": {
|
"details": {
|
||||||
"path": schema_path,
|
"schema": schema_id,
|
||||||
"cause": format!("{}", e)
|
"cause": format!("{}", e)
|
||||||
}
|
}
|
||||||
}]
|
}]
|
||||||
@ -59,9 +71,9 @@ fn cache_json_schema(schema_id: &str, schema: JsonB, strict: bool) -> JsonB {
|
|||||||
CompileError::ValidationError { url: _url, src } => {
|
CompileError::ValidationError { url: _url, src } => {
|
||||||
// Collect leaf errors from the meta-schema validation failure
|
// Collect leaf errors from the meta-schema validation failure
|
||||||
let mut error_list = Vec::new();
|
let mut error_list = Vec::new();
|
||||||
collect_validation_errors(src, &mut error_list);
|
collect_errors(src, &mut error_list);
|
||||||
// Filter and format errors properly - no instance for schema compilation
|
// Filter and format errors properly - no instance for schema compilation
|
||||||
format_drop_errors(error_list, &schema_value)
|
format_errors(error_list, &schema_value, schema_id)
|
||||||
}
|
}
|
||||||
_ => {
|
_ => {
|
||||||
// Other compilation errors
|
// Other compilation errors
|
||||||
@ -69,7 +81,7 @@ fn cache_json_schema(schema_id: &str, schema: JsonB, strict: bool) -> JsonB {
|
|||||||
"code": "SCHEMA_COMPILATION_FAILED",
|
"code": "SCHEMA_COMPILATION_FAILED",
|
||||||
"message": format!("Schema '{}' compilation failed", schema_id),
|
"message": format!("Schema '{}' compilation failed", schema_id),
|
||||||
"details": {
|
"details": {
|
||||||
"path": schema_path,
|
"schema": schema_id,
|
||||||
"cause": format!("{:?}", e)
|
"cause": format!("{:?}", e)
|
||||||
}
|
}
|
||||||
})]
|
})]
|
||||||
@ -80,36 +92,49 @@ fn cache_json_schema(schema_id: &str, schema: JsonB, strict: bool) -> JsonB {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Helper function to recursively apply strict validation to all objects in a schema
|
// Helper function to apply strict validation to a schema
|
||||||
|
//
|
||||||
|
// This recursively adds unevaluatedProperties: false to object-type schemas,
|
||||||
|
// but SKIPS schemas inside if/then/else to avoid breaking conditional validation.
|
||||||
fn apply_strict_validation(schema: &mut Value) {
|
fn apply_strict_validation(schema: &mut Value) {
|
||||||
|
apply_strict_validation_recursive(schema, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn apply_strict_validation_recursive(schema: &mut Value, inside_conditional: bool) {
|
||||||
match schema {
|
match schema {
|
||||||
Value::Object(map) => {
|
Value::Object(map) => {
|
||||||
// If this is an object type schema, add additionalProperties: false
|
// Skip adding strict validation if we're inside a conditional
|
||||||
if let Some(Value::String(t)) = map.get("type") {
|
if !inside_conditional {
|
||||||
if t == "object" && !map.contains_key("additionalProperties") {
|
// Add strict validation to object schemas only at top level
|
||||||
map.insert("additionalProperties".to_string(), Value::Bool(false));
|
if let Some(Value::String(t)) = map.get("type") {
|
||||||
}
|
if t == "object" && !map.contains_key("unevaluatedProperties") && !map.contains_key("additionalProperties") {
|
||||||
}
|
// At top level, use unevaluatedProperties: false
|
||||||
|
// This considers all evaluated properties from all schemas
|
||||||
// Recurse into all properties
|
map.insert("unevaluatedProperties".to_string(), Value::Bool(false));
|
||||||
for (_, value) in map.iter_mut() {
|
|
||||||
apply_strict_validation(value);
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Value::Array(arr) => {
|
|
||||||
// Recurse into array items
|
// Recurse into all properties
|
||||||
for item in arr.iter_mut() {
|
for (key, value) in map.iter_mut() {
|
||||||
apply_strict_validation(item);
|
// Mark when we're inside conditional branches
|
||||||
}
|
let in_conditional = inside_conditional || matches!(key.as_str(), "if" | "then" | "else");
|
||||||
|
apply_strict_validation_recursive(value, in_conditional);
|
||||||
}
|
}
|
||||||
_ => {}
|
}
|
||||||
|
Value::Array(arr) => {
|
||||||
|
// Recurse into array items
|
||||||
|
for item in arr.iter_mut() {
|
||||||
|
apply_strict_validation_recursive(item, inside_conditional);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[pg_extern(strict, parallel_safe)]
|
#[pg_extern(strict, parallel_safe)]
|
||||||
fn validate_json_schema(schema_id: &str, instance: JsonB) -> JsonB {
|
fn validate_json_schema(schema_id: &str, instance: JsonB) -> JsonB {
|
||||||
let cache = SCHEMA_CACHE.read().unwrap();
|
let cache = SCHEMA_CACHE.read().unwrap();
|
||||||
|
|
||||||
// Lookup uses the original schema_id
|
// Lookup uses the original schema_id
|
||||||
match cache.id_to_index.get(schema_id) {
|
match cache.id_to_index.get(schema_id) {
|
||||||
None => JsonB(json!({
|
None => JsonB(json!({
|
||||||
@ -117,6 +142,7 @@ fn validate_json_schema(schema_id: &str, instance: JsonB) -> JsonB {
|
|||||||
"code": "SCHEMA_NOT_FOUND",
|
"code": "SCHEMA_NOT_FOUND",
|
||||||
"message": format!("Schema '{}' not found in cache", schema_id),
|
"message": format!("Schema '{}' not found in cache", schema_id),
|
||||||
"details": {
|
"details": {
|
||||||
|
"schema": schema_id,
|
||||||
"cause": "Schema must be cached before validation"
|
"cause": "Schema must be cached before validation"
|
||||||
}
|
}
|
||||||
}]
|
}]
|
||||||
@ -127,10 +153,15 @@ fn validate_json_schema(schema_id: &str, instance: JsonB) -> JsonB {
|
|||||||
Ok(_) => JsonB(json!({ "response": "success" })),
|
Ok(_) => JsonB(json!({ "response": "success" })),
|
||||||
Err(validation_error) => {
|
Err(validation_error) => {
|
||||||
let mut error_list = Vec::new();
|
let mut error_list = Vec::new();
|
||||||
collect_validation_errors(&validation_error, &mut error_list);
|
collect_errors(&validation_error, &mut error_list);
|
||||||
let errors = format_drop_errors(error_list, &instance_value);
|
let errors = format_errors(error_list, &instance_value, schema_id);
|
||||||
|
// Filter out FALSE_SCHEMA errors if there are other validation errors
|
||||||
JsonB(json!({ "errors": errors }))
|
let filtered_errors = filter_false_schema_errors(errors);
|
||||||
|
if filtered_errors.is_empty() {
|
||||||
|
JsonB(json!({ "response": "success" }))
|
||||||
|
} else {
|
||||||
|
JsonB(json!({ "errors": filtered_errors }))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -138,203 +169,594 @@ fn validate_json_schema(schema_id: &str, instance: JsonB) -> JsonB {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Recursively collects validation errors
|
// Recursively collects validation errors
|
||||||
fn collect_validation_errors(error: &ValidationError, errors_list: &mut Vec<(String, String, String)>) {
|
fn collect_errors(error: &ValidationError, errors_list: &mut Vec<Error>) {
|
||||||
// Check if this is a structural error that we should skip
|
// Check if this is a structural error that we should skip
|
||||||
let error_message = format!("{}", error.kind);
|
let is_structural = matches!(
|
||||||
let is_structural = error_message == "validation failed" ||
|
&error.kind,
|
||||||
error_message == "allOf failed" ||
|
ErrorKind::Group | ErrorKind::AllOf | ErrorKind::AnyOf | ErrorKind::Not | ErrorKind::OneOf(_)
|
||||||
error_message == "anyOf failed" ||
|
);
|
||||||
error_message == "not failed" ||
|
|
||||||
error_message.starts_with("oneOf failed");
|
|
||||||
|
|
||||||
if error.causes.is_empty() && !is_structural {
|
|
||||||
// This is a leaf error that's not structural
|
|
||||||
// Format just the error kind, not the whole validation error
|
|
||||||
let message = format!("{}", error.kind);
|
|
||||||
|
|
||||||
errors_list.push((
|
// Special handling for FalseSchema - if it has causes, use those instead
|
||||||
error.instance_location.to_string(),
|
if matches!(&error.kind, ErrorKind::FalseSchema) {
|
||||||
error.schema_url.to_string(),
|
if !error.causes.is_empty() {
|
||||||
message
|
// FalseSchema often wraps more specific errors in if/then conditionals
|
||||||
));
|
for cause in &error.causes {
|
||||||
|
collect_errors(cause, errors_list);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// If FalseSchema has no causes, it's likely from unevaluatedProperties
|
||||||
|
// We'll handle it as a leaf error below
|
||||||
|
}
|
||||||
|
|
||||||
|
if error.causes.is_empty() && !is_structural {
|
||||||
|
let base_path = error.instance_location.to_string();
|
||||||
|
|
||||||
|
// Match on error kind and handle each type
|
||||||
|
let errors_to_add = match &error.kind {
|
||||||
|
ErrorKind::Type { got, want } => handle_type_error(&base_path, got, want),
|
||||||
|
ErrorKind::Required { want } => handle_required_error(&base_path, want),
|
||||||
|
ErrorKind::Dependency { prop, missing } => handle_dependency_error(&base_path, prop, missing, false),
|
||||||
|
ErrorKind::DependentRequired { prop, missing } => handle_dependency_error(&base_path, prop, missing, true),
|
||||||
|
ErrorKind::AdditionalProperties { got } => handle_additional_properties_error(&base_path, got),
|
||||||
|
ErrorKind::Enum { want } => handle_enum_error(&base_path, want),
|
||||||
|
ErrorKind::Const { want } => handle_const_error(&base_path, want),
|
||||||
|
ErrorKind::MinLength { got, want } => handle_min_length_error(&base_path, *got, *want),
|
||||||
|
ErrorKind::MaxLength { got, want } => handle_max_length_error(&base_path, *got, *want),
|
||||||
|
ErrorKind::Pattern { got, want } => handle_pattern_error(&base_path, got, want),
|
||||||
|
ErrorKind::Minimum { got, want } => handle_minimum_error(&base_path, got, want),
|
||||||
|
ErrorKind::Maximum { got, want } => handle_maximum_error(&base_path, got, want),
|
||||||
|
ErrorKind::ExclusiveMinimum { got, want } => handle_exclusive_minimum_error(&base_path, got, want),
|
||||||
|
ErrorKind::ExclusiveMaximum { got, want } => handle_exclusive_maximum_error(&base_path, got, want),
|
||||||
|
ErrorKind::MultipleOf { got, want } => handle_multiple_of_error(&base_path, got, want),
|
||||||
|
ErrorKind::MinItems { got, want } => handle_min_items_error(&base_path, *got, *want),
|
||||||
|
ErrorKind::MaxItems { got, want } => handle_max_items_error(&base_path, *got, *want),
|
||||||
|
ErrorKind::UniqueItems { got } => handle_unique_items_error(&base_path, got),
|
||||||
|
ErrorKind::MinProperties { got, want } => handle_min_properties_error(&base_path, *got, *want),
|
||||||
|
ErrorKind::MaxProperties { got, want } => handle_max_properties_error(&base_path, *got, *want),
|
||||||
|
ErrorKind::AdditionalItems { got } => handle_additional_items_error(&base_path, *got),
|
||||||
|
ErrorKind::Format { want, got, err } => handle_format_error(&base_path, want, got, err),
|
||||||
|
ErrorKind::PropertyName { prop } => handle_property_name_error(&base_path, prop),
|
||||||
|
ErrorKind::Contains => handle_contains_error(&base_path),
|
||||||
|
ErrorKind::MinContains { got, want } => handle_min_contains_error(&base_path, got, *want),
|
||||||
|
ErrorKind::MaxContains { got, want } => handle_max_contains_error(&base_path, got, *want),
|
||||||
|
ErrorKind::ContentEncoding { want, err } => handle_content_encoding_error(&base_path, want, err),
|
||||||
|
ErrorKind::ContentMediaType { want, err, .. } => handle_content_media_type_error(&base_path, want, err),
|
||||||
|
ErrorKind::FalseSchema => handle_false_schema_error(&base_path),
|
||||||
|
ErrorKind::Not => handle_not_error(&base_path),
|
||||||
|
ErrorKind::RefCycle { url, kw_loc1, kw_loc2 } => handle_ref_cycle_error(&base_path, url, kw_loc1, kw_loc2),
|
||||||
|
ErrorKind::Reference { kw, url } => handle_reference_error(&base_path, kw, url),
|
||||||
|
ErrorKind::Schema { url } => handle_schema_error(&base_path, url),
|
||||||
|
ErrorKind::ContentSchema => handle_content_schema_error(&base_path),
|
||||||
|
ErrorKind::Group => handle_group_error(&base_path),
|
||||||
|
ErrorKind::AllOf => handle_all_of_error(&base_path),
|
||||||
|
ErrorKind::AnyOf => handle_any_of_error(&base_path),
|
||||||
|
ErrorKind::OneOf(matched) => handle_one_of_error(&base_path, matched),
|
||||||
|
};
|
||||||
|
|
||||||
|
// Add all generated errors
|
||||||
|
for error in errors_to_add {
|
||||||
|
errors_list.push(error);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
// Recurse into causes
|
// Recurse into causes
|
||||||
for cause in &error.causes {
|
for cause in &error.causes {
|
||||||
collect_validation_errors(cause, errors_list);
|
collect_errors(cause, errors_list);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Formats errors according to DropError structure
|
// Handler functions for each error kind
|
||||||
fn format_drop_errors(raw_errors: Vec<(String, String, String)>, instance: &Value) -> Vec<Value> {
|
fn handle_type_error(base_path: &str, got: &Type, want: &Types) -> Vec<Error> {
|
||||||
use std::collections::HashMap;
|
vec![Error {
|
||||||
use std::collections::hash_map::Entry;
|
path: base_path.to_string(),
|
||||||
|
code: "TYPE_MISMATCH".to_string(),
|
||||||
|
message: format!("Expected {} but got {}",
|
||||||
|
want.iter().map(|t| t.to_string()).collect::<Vec<_>>().join(" or "),
|
||||||
|
got
|
||||||
|
),
|
||||||
|
cause: json!({
|
||||||
|
"got": got.to_string(),
|
||||||
|
"want": want.iter().map(|t| t.to_string()).collect::<Vec<_>>()
|
||||||
|
}),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
// We don't filter structural paths from instance paths anymore
|
fn handle_required_error(base_path: &str, want: &[&str]) -> Vec<Error> {
|
||||||
// because instance paths shouldn't contain these segments anyway
|
// Create a separate error for each missing required field
|
||||||
// The issue was likely with schema paths, not instance paths
|
want.iter().map(|missing_field| {
|
||||||
let plausible_errors = raw_errors;
|
let field_path = if base_path.is_empty() {
|
||||||
|
format!("/{}", missing_field)
|
||||||
// 2. Deduplicate by instance_path and format as DropError
|
} else {
|
||||||
let mut unique_errors: HashMap<String, Value> = HashMap::new();
|
format!("{}/{}", base_path, missing_field)
|
||||||
for (instance_path, _schema_path, message) in plausible_errors {
|
};
|
||||||
if let Entry::Vacant(entry) = unique_errors.entry(instance_path.clone()) {
|
|
||||||
// Convert message to error code and make it human readable
|
Error {
|
||||||
let (code, human_message) = enhance_error_message(&message);
|
path: field_path,
|
||||||
|
code: "REQUIRED_FIELD_MISSING".to_string(),
|
||||||
// Extract the failing value from the instance
|
message: format!("Required field '{}' is missing", missing_field),
|
||||||
let failing_value = extract_value_at_path(instance, &instance_path);
|
cause: json!({ "want": [missing_field] }),
|
||||||
|
|
||||||
entry.insert(json!({
|
|
||||||
"code": code,
|
|
||||||
"message": human_message,
|
|
||||||
"details": {
|
|
||||||
"path": instance_path,
|
|
||||||
"context": failing_value,
|
|
||||||
"cause": message // Original error message
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}).collect()
|
||||||
|
}
|
||||||
|
|
||||||
unique_errors.into_values().collect()
|
fn handle_dependency_error(base_path: &str, prop: &str, missing: &[&str], is_dependent_required: bool) -> Vec<Error> {
|
||||||
|
// Create a separate error for each missing field
|
||||||
|
missing.iter().map(|missing_field| {
|
||||||
|
let field_path = if base_path.is_empty() {
|
||||||
|
format!("/{}", missing_field)
|
||||||
|
} else {
|
||||||
|
format!("{}/{}", base_path, missing_field)
|
||||||
|
};
|
||||||
|
|
||||||
|
let (code, message) = if is_dependent_required {
|
||||||
|
(
|
||||||
|
"DEPENDENT_REQUIRED_MISSING".to_string(),
|
||||||
|
format!("Field '{}' is required when '{}' is present", missing_field, prop),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
(
|
||||||
|
"DEPENDENCY_FAILED".to_string(),
|
||||||
|
format!("Field '{}' is required when '{}' is present", missing_field, prop),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
Error {
|
||||||
|
path: field_path,
|
||||||
|
code,
|
||||||
|
message,
|
||||||
|
cause: json!({ "prop": prop, "missing": [missing_field] }),
|
||||||
|
}
|
||||||
|
}).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_additional_properties_error(base_path: &str, got: &[Cow<str>]) -> Vec<Error> {
|
||||||
|
// Create a separate error for each additional property that's not allowed
|
||||||
|
got.iter().map(|extra_prop| {
|
||||||
|
let field_path = if base_path.is_empty() {
|
||||||
|
format!("/{}", extra_prop)
|
||||||
|
} else {
|
||||||
|
format!("{}/{}", base_path, extra_prop)
|
||||||
|
};
|
||||||
|
|
||||||
|
Error {
|
||||||
|
path: field_path,
|
||||||
|
code: "ADDITIONAL_PROPERTIES_NOT_ALLOWED".to_string(),
|
||||||
|
message: format!("Property '{}' is not allowed", extra_prop),
|
||||||
|
cause: json!({ "got": [extra_prop.to_string()] }),
|
||||||
|
}
|
||||||
|
}).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_enum_error(base_path: &str, want: &[Value]) -> Vec<Error> {
|
||||||
|
let message = if want.len() == 1 {
|
||||||
|
format!("Value must be {}", serde_json::to_string(&want[0]).unwrap_or_else(|_| "unknown".to_string()))
|
||||||
|
} else {
|
||||||
|
format!("Value must be one of: {}",
|
||||||
|
want.iter()
|
||||||
|
.map(|v| serde_json::to_string(v).unwrap_or_else(|_| "unknown".to_string()))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(", ")
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "ENUM_VIOLATED".to_string(),
|
||||||
|
message,
|
||||||
|
cause: json!({ "want": want }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_const_error(base_path: &str, want: &Value) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "CONST_VIOLATED".to_string(),
|
||||||
|
message: format!("Value must be exactly {}", serde_json::to_string(want).unwrap_or_else(|_| "unknown".to_string())),
|
||||||
|
cause: json!({ "want": want }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_min_length_error(base_path: &str, got: usize, want: usize) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "MIN_LENGTH_VIOLATED".to_string(),
|
||||||
|
message: format!("String length must be at least {} characters, but got {}", want, got),
|
||||||
|
cause: json!({ "got": got, "want": want }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_max_length_error(base_path: &str, got: usize, want: usize) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "MAX_LENGTH_VIOLATED".to_string(),
|
||||||
|
message: format!("String length must be at most {} characters, but got {}", want, got),
|
||||||
|
cause: json!({ "got": got, "want": want }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_pattern_error(base_path: &str, got: &Cow<str>, want: &str) -> Vec<Error> {
|
||||||
|
let display_value = if got.len() > 50 {
|
||||||
|
format!("{}...", &got[..50])
|
||||||
|
} else {
|
||||||
|
got.to_string()
|
||||||
|
};
|
||||||
|
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "PATTERN_VIOLATED".to_string(),
|
||||||
|
message: format!("Value '{}' does not match pattern '{}'", display_value, want),
|
||||||
|
cause: json!({ "got": got.to_string(), "want": want }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_minimum_error(base_path: &str, got: &Cow<Number>, want: &Number) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "MINIMUM_VIOLATED".to_string(),
|
||||||
|
message: format!("Value must be at least {}, but got {}", want, got),
|
||||||
|
cause: json!({ "got": got, "want": want }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_maximum_error(base_path: &str, got: &Cow<Number>, want: &Number) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "MAXIMUM_VIOLATED".to_string(),
|
||||||
|
message: format!("Value must be at most {}, but got {}", want, got),
|
||||||
|
cause: json!({ "got": got, "want": want }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_exclusive_minimum_error(base_path: &str, got: &Cow<Number>, want: &Number) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "EXCLUSIVE_MINIMUM_VIOLATED".to_string(),
|
||||||
|
message: format!("Value must be greater than {}, but got {}", want, got),
|
||||||
|
cause: json!({ "got": got, "want": want }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_exclusive_maximum_error(base_path: &str, got: &Cow<Number>, want: &Number) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "EXCLUSIVE_MAXIMUM_VIOLATED".to_string(),
|
||||||
|
message: format!("Value must be less than {}, but got {}", want, got),
|
||||||
|
cause: json!({ "got": got, "want": want }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_multiple_of_error(base_path: &str, got: &Cow<Number>, want: &Number) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "MULTIPLE_OF_VIOLATED".to_string(),
|
||||||
|
message: format!("{} is not a multiple of {}", got, want),
|
||||||
|
cause: json!({ "got": got, "want": want }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_min_items_error(base_path: &str, got: usize, want: usize) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "MIN_ITEMS_VIOLATED".to_string(),
|
||||||
|
message: format!("Array must have at least {} items, but has {}", want, got),
|
||||||
|
cause: json!({ "got": got, "want": want }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_max_items_error(base_path: &str, got: usize, want: usize) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "MAX_ITEMS_VIOLATED".to_string(),
|
||||||
|
message: format!("Array must have at most {} items, but has {}", want, got),
|
||||||
|
cause: json!({ "got": got, "want": want }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_unique_items_error(base_path: &str, got: &[usize; 2]) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "UNIQUE_ITEMS_VIOLATED".to_string(),
|
||||||
|
message: format!("Array items at positions {} and {} are duplicates", got[0], got[1]),
|
||||||
|
cause: json!({ "got": got }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_min_properties_error(base_path: &str, got: usize, want: usize) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "MIN_PROPERTIES_VIOLATED".to_string(),
|
||||||
|
message: format!("Object must have at least {} properties, but has {}", want, got),
|
||||||
|
cause: json!({ "got": got, "want": want }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_max_properties_error(base_path: &str, got: usize, want: usize) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "MAX_PROPERTIES_VIOLATED".to_string(),
|
||||||
|
message: format!("Object must have at most {} properties, but has {}", want, got),
|
||||||
|
cause: json!({ "got": got, "want": want }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_additional_items_error(base_path: &str, got: usize) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "ADDITIONAL_ITEMS_NOT_ALLOWED".to_string(),
|
||||||
|
message: format!("Last {} array items are not allowed", got),
|
||||||
|
cause: json!({ "got": got }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_format_error(base_path: &str, want: &str, got: &Cow<Value>, err: &Box<dyn std::error::Error>) -> Vec<Error> {
|
||||||
|
// If the value is an empty string, skip format validation.
|
||||||
|
if let Value::String(s) = got.as_ref() {
|
||||||
|
if s.is_empty() {
|
||||||
|
return vec![];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "FORMAT_INVALID".to_string(),
|
||||||
|
message: format!("Value {} is not a valid {} format",
|
||||||
|
serde_json::to_string(got.as_ref()).unwrap_or_else(|_| "unknown".to_string()),
|
||||||
|
want
|
||||||
|
),
|
||||||
|
cause: json!({ "got": got, "want": want, "err": err.to_string() }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_property_name_error(base_path: &str, prop: &str) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "INVALID_PROPERTY_NAME".to_string(),
|
||||||
|
message: format!("Property name '{}' is invalid", prop),
|
||||||
|
cause: json!({ "prop": prop }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_contains_error(base_path: &str) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "CONTAINS_FAILED".to_string(),
|
||||||
|
message: "No array items match the required schema".to_string(),
|
||||||
|
cause: json!({}),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_min_contains_error(base_path: &str, got: &[usize], want: usize) -> Vec<Error> {
|
||||||
|
let message = if got.is_empty() {
|
||||||
|
format!("At least {} array items must match the schema, but none do", want)
|
||||||
|
} else {
|
||||||
|
format!("At least {} array items must match the schema, but only {} do (at positions {})",
|
||||||
|
want,
|
||||||
|
got.len(),
|
||||||
|
got.iter().map(|i| i.to_string()).collect::<Vec<_>>().join(", ")
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "MIN_CONTAINS_VIOLATED".to_string(),
|
||||||
|
message,
|
||||||
|
cause: json!({ "got": got, "want": want }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_max_contains_error(base_path: &str, got: &[usize], want: usize) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "MAX_CONTAINS_VIOLATED".to_string(),
|
||||||
|
message: format!("At most {} array items can match the schema, but {} do (at positions {})",
|
||||||
|
want,
|
||||||
|
got.len(),
|
||||||
|
got.iter().map(|i| i.to_string()).collect::<Vec<_>>().join(", ")
|
||||||
|
),
|
||||||
|
cause: json!({ "got": got, "want": want }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_content_encoding_error(base_path: &str, want: &str, err: &Box<dyn std::error::Error>) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "CONTENT_ENCODING_INVALID".to_string(),
|
||||||
|
message: format!("Content is not valid {} encoding: {}", want, err),
|
||||||
|
cause: json!({ "want": want, "err": err.to_string() }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_content_media_type_error(base_path: &str, want: &str, err: &Box<dyn std::error::Error>) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "CONTENT_MEDIA_TYPE_INVALID".to_string(),
|
||||||
|
message: format!("Content is not valid {} media type: {}", want, err),
|
||||||
|
cause: json!({ "want": want, "err": err.to_string() }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_false_schema_error(base_path: &str) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "FALSE_SCHEMA".to_string(),
|
||||||
|
message: "This schema always fails validation".to_string(),
|
||||||
|
cause: json!({}),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_not_error(base_path: &str) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "NOT_VIOLATED".to_string(),
|
||||||
|
message: "Value matches a schema that it should not match".to_string(),
|
||||||
|
cause: json!({}),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_ref_cycle_error(base_path: &str, url: &str, kw_loc1: &str, kw_loc2: &str) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "REFERENCE_CYCLE".to_string(),
|
||||||
|
message: format!("Reference cycle detected: both '{}' and '{}' resolve to '{}'", kw_loc1, kw_loc2, url),
|
||||||
|
cause: json!({ "url": url, "kw_loc1": kw_loc1, "kw_loc2": kw_loc2 }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_reference_error(base_path: &str, kw: &str, url: &str) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "REFERENCE_FAILED".to_string(),
|
||||||
|
message: format!("{} reference to '{}' failed validation", kw, url),
|
||||||
|
cause: json!({ "kw": kw, "url": url }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_schema_error(base_path: &str, url: &str) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "SCHEMA_FAILED".to_string(),
|
||||||
|
message: format!("Schema '{}' validation failed", url),
|
||||||
|
cause: json!({ "url": url }),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_content_schema_error(base_path: &str) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "CONTENT_SCHEMA_FAILED".to_string(),
|
||||||
|
message: "Content schema validation failed".to_string(),
|
||||||
|
cause: json!({}),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_group_error(base_path: &str) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "VALIDATION_FAILED".to_string(),
|
||||||
|
message: "Validation failed".to_string(),
|
||||||
|
cause: json!({}),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_all_of_error(base_path: &str) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "ALL_OF_VIOLATED".to_string(),
|
||||||
|
message: "Value does not match all required schemas".to_string(),
|
||||||
|
cause: json!({}),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_any_of_error(base_path: &str) -> Vec<Error> {
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "ANY_OF_VIOLATED".to_string(),
|
||||||
|
message: "Value does not match any of the allowed schemas".to_string(),
|
||||||
|
cause: json!({}),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_one_of_error(base_path: &str, matched: &Option<(usize, usize)>) -> Vec<Error> {
|
||||||
|
let (message, cause) = match matched {
|
||||||
|
None => (
|
||||||
|
"Value must match exactly one schema, but matches none".to_string(),
|
||||||
|
json!({ "matched_indices": null })
|
||||||
|
),
|
||||||
|
Some((i, j)) => (
|
||||||
|
format!("Value must match exactly one schema, but matches schemas at positions {} and {}", i, j),
|
||||||
|
json!({ "matched_indices": [i, j] })
|
||||||
|
),
|
||||||
|
};
|
||||||
|
|
||||||
|
vec![Error {
|
||||||
|
path: base_path.to_string(),
|
||||||
|
code: "ONE_OF_VIOLATED".to_string(),
|
||||||
|
message,
|
||||||
|
cause,
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Filter out FALSE_SCHEMA errors if there are other validation errors
|
||||||
|
fn filter_false_schema_errors(errors: Vec<Value>) -> Vec<Value> {
|
||||||
|
// Check if there are any non-FALSE_SCHEMA errors
|
||||||
|
let has_non_false_schema = errors.iter().any(|e| {
|
||||||
|
e.get("code")
|
||||||
|
.and_then(|c| c.as_str())
|
||||||
|
.map(|code| code != "FALSE_SCHEMA")
|
||||||
|
.unwrap_or(false)
|
||||||
|
});
|
||||||
|
|
||||||
|
if has_non_false_schema {
|
||||||
|
// Filter out FALSE_SCHEMA errors
|
||||||
|
errors.into_iter()
|
||||||
|
.filter(|e| {
|
||||||
|
e.get("code")
|
||||||
|
.and_then(|c| c.as_str())
|
||||||
|
.map(|code| code != "FALSE_SCHEMA")
|
||||||
|
.unwrap_or(true)
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
} else {
|
||||||
|
// Keep all errors (they're all FALSE_SCHEMA)
|
||||||
|
errors
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Formats errors according to DropError structure
|
||||||
|
fn format_errors(errors: Vec<Error>, instance: &Value, schema_id: &str) -> Vec<Value> {
|
||||||
|
// Deduplicate by instance_path and format as DropError
|
||||||
|
let mut unique_errors: HashMap<String, Value> = HashMap::new();
|
||||||
|
for error in errors {
|
||||||
|
if let Entry::Vacant(entry) = unique_errors.entry(error.path.clone()) {
|
||||||
|
// Extract the failing value from the instance
|
||||||
|
let failing_value = extract_value_at_path(instance, &error.path);
|
||||||
|
entry.insert(json!({
|
||||||
|
"code": error.code,
|
||||||
|
"message": error.message,
|
||||||
|
"details": {
|
||||||
|
"path": error.path,
|
||||||
|
"context": failing_value,
|
||||||
|
"cause": error.cause,
|
||||||
|
"schema": schema_id
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
unique_errors.into_values().collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Helper function to extract value at a JSON pointer path
|
// Helper function to extract value at a JSON pointer path
|
||||||
fn extract_value_at_path(instance: &Value, path: &str) -> Value {
|
fn extract_value_at_path(instance: &Value, path: &str) -> Value {
|
||||||
let parts: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
|
let parts: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
|
||||||
let mut current = instance;
|
let mut current = instance;
|
||||||
|
|
||||||
for part in parts {
|
for part in parts {
|
||||||
match current {
|
match current {
|
||||||
Value::Object(map) => {
|
Value::Object(map) => {
|
||||||
if let Some(value) = map.get(part) {
|
if let Some(value) = map.get(part) {
|
||||||
current = value;
|
current = value;
|
||||||
} else {
|
} else {
|
||||||
return Value::Null;
|
return Value::Null;
|
||||||
}
|
|
||||||
}
|
|
||||||
Value::Array(arr) => {
|
|
||||||
if let Ok(index) = part.parse::<usize>() {
|
|
||||||
if let Some(value) = arr.get(index) {
|
|
||||||
current = value;
|
|
||||||
} else {
|
|
||||||
return Value::Null;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return Value::Null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => return Value::Null,
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
Value::Array(arr) => {
|
||||||
|
if let Ok(index) = part.parse::<usize>() {
|
||||||
|
if let Some(value) = arr.get(index) {
|
||||||
|
current = value;
|
||||||
|
} else {
|
||||||
|
return Value::Null;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return Value::Null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => return Value::Null,
|
||||||
}
|
}
|
||||||
|
}
|
||||||
current.clone()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Helper to convert validation messages to error codes and human-readable messages
|
current.clone()
|
||||||
fn enhance_error_message(message: &str) -> (String, String) {
|
|
||||||
// Match exact boon error message patterns
|
|
||||||
let trimmed = message.trim();
|
|
||||||
|
|
||||||
if trimmed.contains("value must be one of") {
|
|
||||||
("ENUM_VIOLATED".to_string(),
|
|
||||||
"Value is not one of the allowed options".to_string())
|
|
||||||
} else if trimmed.contains("length must be >=") && trimmed.contains("but got") {
|
|
||||||
("MIN_LENGTH_VIOLATED".to_string(),
|
|
||||||
"Field length is below the minimum required".to_string())
|
|
||||||
} else if trimmed.contains("length must be <=") && trimmed.contains("but got") {
|
|
||||||
("MAX_LENGTH_VIOLATED".to_string(),
|
|
||||||
"Field length exceeds the maximum allowed".to_string())
|
|
||||||
} else if trimmed.contains("must be >=") && trimmed.contains("but got") {
|
|
||||||
("MINIMUM_VIOLATED".to_string(),
|
|
||||||
"Value is below the minimum allowed".to_string())
|
|
||||||
} else if trimmed.contains("must be <=") && trimmed.contains("but got") {
|
|
||||||
("MAXIMUM_VIOLATED".to_string(),
|
|
||||||
"Value exceeds the maximum allowed".to_string())
|
|
||||||
} else if trimmed.contains("must be >") && trimmed.contains("but got") {
|
|
||||||
("EXCLUSIVE_MINIMUM_VIOLATED".to_string(),
|
|
||||||
"Value must be greater than the minimum".to_string())
|
|
||||||
} else if trimmed.contains("must be <") && trimmed.contains("but got") {
|
|
||||||
("EXCLUSIVE_MAXIMUM_VIOLATED".to_string(),
|
|
||||||
"Value must be less than the maximum".to_string())
|
|
||||||
} else if trimmed.contains("does not match pattern") {
|
|
||||||
("PATTERN_VIOLATED".to_string(),
|
|
||||||
"Value does not match the required pattern".to_string())
|
|
||||||
} else if trimmed.contains("missing properties") {
|
|
||||||
("REQUIRED_FIELD_MISSING".to_string(),
|
|
||||||
"Required field is missing".to_string())
|
|
||||||
} else if trimmed.contains("want") && trimmed.contains("but got") {
|
|
||||||
("TYPE_MISMATCH".to_string(),
|
|
||||||
"Field type does not match the expected type".to_string())
|
|
||||||
} else if trimmed.starts_with("value must be") && !trimmed.contains("one of") {
|
|
||||||
("CONST_VIOLATED".to_string(),
|
|
||||||
"Value does not match the required constant".to_string())
|
|
||||||
} else if trimmed.contains("is not valid") && trimmed.contains(":") {
|
|
||||||
("FORMAT_INVALID".to_string(),
|
|
||||||
extract_format_message(trimmed))
|
|
||||||
} else if trimmed.contains("items at") && trimmed.contains("are equal") {
|
|
||||||
("UNIQUE_ITEMS_VIOLATED".to_string(),
|
|
||||||
"Array contains duplicate items".to_string())
|
|
||||||
} else if trimmed.contains("additionalProperties") && trimmed.contains("not allowed") {
|
|
||||||
("ADDITIONAL_PROPERTIES_NOT_ALLOWED".to_string(),
|
|
||||||
"Object contains properties that are not allowed".to_string())
|
|
||||||
} else if trimmed.contains("is not multipleOf") {
|
|
||||||
("MULTIPLE_OF_VIOLATED".to_string(),
|
|
||||||
"Value is not a multiple of the required factor".to_string())
|
|
||||||
} else if trimmed.contains("minimum") && trimmed.contains("properties required") {
|
|
||||||
("MIN_PROPERTIES_VIOLATED".to_string(),
|
|
||||||
"Object has fewer properties than required".to_string())
|
|
||||||
} else if trimmed.contains("maximum") && trimmed.contains("properties required") {
|
|
||||||
("MAX_PROPERTIES_VIOLATED".to_string(),
|
|
||||||
"Object has more properties than allowed".to_string())
|
|
||||||
} else if trimmed.contains("minimum") && trimmed.contains("items required") {
|
|
||||||
("MIN_ITEMS_VIOLATED".to_string(),
|
|
||||||
"Array has fewer items than required".to_string())
|
|
||||||
} else if trimmed.contains("maximum") && trimmed.contains("items required") {
|
|
||||||
("MAX_ITEMS_VIOLATED".to_string(),
|
|
||||||
"Array has more items than allowed".to_string())
|
|
||||||
} else if trimmed == "false schema" {
|
|
||||||
("FALSE_SCHEMA".to_string(),
|
|
||||||
"Schema validation always fails".to_string())
|
|
||||||
} else if trimmed == "not failed" {
|
|
||||||
("NOT_VIOLATED".to_string(),
|
|
||||||
"Value matched a schema it should not match".to_string())
|
|
||||||
} else if trimmed == "allOf failed" {
|
|
||||||
("ALL_OF_VIOLATED".to_string(),
|
|
||||||
"Value does not match all required schemas".to_string())
|
|
||||||
} else if trimmed == "anyOf failed" {
|
|
||||||
("ANY_OF_VIOLATED".to_string(),
|
|
||||||
"Value does not match any of the allowed schemas".to_string())
|
|
||||||
} else if trimmed.contains("oneOf failed") {
|
|
||||||
("ONE_OF_VIOLATED".to_string(),
|
|
||||||
"Value must match exactly one schema".to_string())
|
|
||||||
} else if trimmed == "validation failed" {
|
|
||||||
("VALIDATION_FAILED".to_string(),
|
|
||||||
"Validation failed".to_string())
|
|
||||||
} else {
|
|
||||||
// For any unmatched patterns, try to provide a generic human-readable message
|
|
||||||
// while preserving the original error in details.cause
|
|
||||||
("VALIDATION_FAILED".to_string(),
|
|
||||||
"Validation failed".to_string())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// Extract a better format message
|
|
||||||
fn extract_format_message(message: &str) -> String {
|
|
||||||
if message.contains("date-time") {
|
|
||||||
"Invalid date-time format".to_string()
|
|
||||||
} else if message.contains("email") {
|
|
||||||
"Invalid email format".to_string()
|
|
||||||
} else if message.contains("uri") {
|
|
||||||
"Invalid URI format".to_string()
|
|
||||||
} else if message.contains("uuid") {
|
|
||||||
"Invalid UUID format".to_string()
|
|
||||||
} else {
|
|
||||||
"Invalid format".to_string()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[pg_extern(strict, parallel_safe)]
|
#[pg_extern(strict, parallel_safe)]
|
||||||
@ -375,7 +797,6 @@ pub mod pg_test {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
#[cfg(any(test, feature = "pg_test"))]
|
#[cfg(any(test, feature = "pg_test"))]
|
||||||
#[pg_schema]
|
#[pg_schema]
|
||||||
mod tests {
|
mod tests {
|
||||||
|
|||||||
852
src/tests.rs
852
src/tests.rs
@ -45,24 +45,24 @@ macro_rules! assert_failure_with_json {
|
|||||||
|
|
||||||
let errors_array = errors_opt.unwrap().as_array().expect("'errors' should be an array");
|
let errors_array = errors_opt.unwrap().as_array().expect("'errors' should be an array");
|
||||||
|
|
||||||
if errors_array.len() != $expected_error_count {
|
if errors_array.len() != $expected_error_count {
|
||||||
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
|
||||||
panic!("Assertion Failed (wrong error count): Expected {} errors, got {}. {}\nResult JSON:\n{}", $expected_error_count, errors_array.len(), base_msg, pretty_json);
|
|
||||||
}
|
|
||||||
|
|
||||||
if $expected_error_count > 0 {
|
|
||||||
let first_error_message = errors_array[0].get("message").and_then(Value::as_str);
|
|
||||||
match first_error_message {
|
|
||||||
Some(msg) => {
|
|
||||||
if !msg.contains($expected_first_message_contains) {
|
|
||||||
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
||||||
panic!("Assertion Failed (first error message mismatch): Expected contains '{}', got: '{}'. {}\nResult JSON:\n{}", $expected_first_message_contains, msg, base_msg, pretty_json);
|
panic!("Assertion Failed (wrong error count): Expected {} errors, got {}. {}\nResult JSON:\n{}", $expected_error_count, errors_array.len(), base_msg, pretty_json);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
None => {
|
if $expected_error_count > 0 {
|
||||||
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
let first_error_message = errors_array[0].get("message").and_then(Value::as_str);
|
||||||
panic!("Assertion Failed (first error in array has no 'message' string): {}\nResult JSON:\n{}", base_msg, pretty_json);
|
match first_error_message {
|
||||||
}
|
Some(msg) => {
|
||||||
|
if !msg.contains($expected_first_message_contains) {
|
||||||
|
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
||||||
|
panic!("Assertion Failed (first error message mismatch): Expected contains '{}', got: '{}'. {}\nResult JSON:\n{}", $expected_first_message_contains, msg, base_msg, pretty_json);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
||||||
|
panic!("Assertion Failed (first error in array has no 'message' string): {}\nResult JSON:\n{}", base_msg, pretty_json);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -86,9 +86,9 @@ macro_rules! assert_failure_with_json {
|
|||||||
|
|
||||||
let errors_array = errors_opt.unwrap().as_array().expect("'errors' should be an array");
|
let errors_array = errors_opt.unwrap().as_array().expect("'errors' should be an array");
|
||||||
|
|
||||||
if errors_array.len() != $expected_error_count {
|
if errors_array.len() != $expected_error_count {
|
||||||
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
||||||
panic!("Assertion Failed (wrong error count): Expected {} errors, got {}. {}\nResult JSON:\n{}", $expected_error_count, errors_array.len(), base_msg, pretty_json);
|
panic!("Assertion Failed (wrong error count): Expected {} errors, got {}. {}\nResult JSON:\n{}", $expected_error_count, errors_array.len(), base_msg, pretty_json);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
// Without custom message (calls the one above with ""):
|
// Without custom message (calls the one above with ""):
|
||||||
@ -112,7 +112,7 @@ macro_rules! assert_failure_with_json {
|
|||||||
let errors_array = errors_opt.unwrap().as_array().expect("'errors' should be an array");
|
let errors_array = errors_opt.unwrap().as_array().expect("'errors' should be an array");
|
||||||
|
|
||||||
if errors_array.is_empty() {
|
if errors_array.is_empty() {
|
||||||
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
||||||
panic!("Assertion Failed (expected errors, but 'errors' array is empty): {}\nResult JSON:\n{}", base_msg, pretty_json);
|
panic!("Assertion Failed (expected errors, but 'errors' array is empty): {}\nResult JSON:\n{}", base_msg, pretty_json);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -151,18 +151,29 @@ fn test_cache_and_validate_json_schema() {
|
|||||||
|
|
||||||
// Invalid type - age is negative
|
// Invalid type - age is negative
|
||||||
let invalid_result_type = validate_json_schema(schema_id, jsonb(invalid_instance_type));
|
let invalid_result_type = validate_json_schema(schema_id, jsonb(invalid_instance_type));
|
||||||
assert_failure_with_json!(invalid_result_type, 1, "Value is below the minimum allowed", "Validation with invalid type should fail.");
|
assert_failure_with_json!(invalid_result_type, 1, "Value must be at least 0, but got -5", "Validation with invalid type should fail.");
|
||||||
let errors_type = invalid_result_type.0["errors"].as_array().unwrap();
|
let errors_type = invalid_result_type.0["errors"].as_array().unwrap();
|
||||||
assert_eq!(errors_type[0]["details"]["path"], "/age");
|
assert_eq!(errors_type[0]["details"]["path"], "/age");
|
||||||
assert_eq!(errors_type[0]["details"]["context"], -5);
|
assert_eq!(errors_type[0]["details"]["context"], -5);
|
||||||
|
assert_eq!(errors_type[0]["details"]["schema"], "my_schema");
|
||||||
assert_eq!(errors_type[0]["code"], "MINIMUM_VIOLATED");
|
assert_eq!(errors_type[0]["code"], "MINIMUM_VIOLATED");
|
||||||
|
// Check the cause is now a JSON object
|
||||||
|
let cause_type = &errors_type[0]["details"]["cause"];
|
||||||
|
assert!(cause_type.is_object());
|
||||||
|
assert_eq!(cause_type["got"], -5);
|
||||||
|
assert_eq!(cause_type["want"], 0);
|
||||||
|
|
||||||
// Missing field
|
// Missing field
|
||||||
let invalid_result_missing = validate_json_schema(schema_id, jsonb(invalid_instance_missing));
|
let invalid_result_missing = validate_json_schema(schema_id, jsonb(invalid_instance_missing));
|
||||||
assert_failure_with_json!(invalid_result_missing, 1, "Required field is missing", "Validation with missing field should fail.");
|
assert_failure_with_json!(invalid_result_missing, 1, "Required field 'age' is missing", "Validation with missing field should fail.");
|
||||||
let errors_missing = invalid_result_missing.0["errors"].as_array().unwrap();
|
let errors_missing = invalid_result_missing.0["errors"].as_array().unwrap();
|
||||||
assert_eq!(errors_missing[0]["details"]["path"], "");
|
assert_eq!(errors_missing[0]["details"]["path"], "/age");
|
||||||
|
assert_eq!(errors_missing[0]["details"]["schema"], "my_schema");
|
||||||
assert_eq!(errors_missing[0]["code"], "REQUIRED_FIELD_MISSING");
|
assert_eq!(errors_missing[0]["code"], "REQUIRED_FIELD_MISSING");
|
||||||
|
// Check the cause is now a JSON object
|
||||||
|
let cause_missing = &errors_missing[0]["details"]["cause"];
|
||||||
|
assert!(cause_missing.is_object());
|
||||||
|
assert_eq!(cause_missing["want"], json!(["age"]));
|
||||||
|
|
||||||
// Schema not found
|
// Schema not found
|
||||||
let non_existent_id = "non_existent_schema";
|
let non_existent_id = "non_existent_schema";
|
||||||
@ -170,6 +181,9 @@ fn test_cache_and_validate_json_schema() {
|
|||||||
assert_failure_with_json!(invalid_schema_result, 1, "Schema 'non_existent_schema' not found", "Validation with non-existent schema should fail.");
|
assert_failure_with_json!(invalid_schema_result, 1, "Schema 'non_existent_schema' not found", "Validation with non-existent schema should fail.");
|
||||||
let errors_notfound = invalid_schema_result.0["errors"].as_array().unwrap();
|
let errors_notfound = invalid_schema_result.0["errors"].as_array().unwrap();
|
||||||
assert_eq!(errors_notfound[0]["code"], "SCHEMA_NOT_FOUND");
|
assert_eq!(errors_notfound[0]["code"], "SCHEMA_NOT_FOUND");
|
||||||
|
assert_eq!(errors_notfound[0]["details"]["schema"], "non_existent_schema");
|
||||||
|
// Schema not found still has string cause (it's not from ErrorKind)
|
||||||
|
assert_eq!(errors_notfound[0]["details"]["cause"], "Schema must be cached before validation");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[pg_test]
|
#[pg_test]
|
||||||
@ -197,7 +211,7 @@ fn test_cache_invalid_json_schema() {
|
|||||||
assert_failure_with_json!(
|
assert_failure_with_json!(
|
||||||
cache_result,
|
cache_result,
|
||||||
2, // Expect exactly two leaf errors
|
2, // Expect exactly two leaf errors
|
||||||
"Value is not one of the allowed options", // Updated to human-readable message
|
"Value must be one of", // Updated to human-readable message
|
||||||
"Caching invalid schema should fail with specific meta-schema validation errors."
|
"Caching invalid schema should fail with specific meta-schema validation errors."
|
||||||
);
|
);
|
||||||
|
|
||||||
@ -213,6 +227,15 @@ fn test_cache_invalid_json_schema() {
|
|||||||
.collect();
|
.collect();
|
||||||
assert!(paths.contains(&"/type"));
|
assert!(paths.contains(&"/type"));
|
||||||
assert!(paths.contains(&"/type/0"));
|
assert!(paths.contains(&"/type/0"));
|
||||||
|
// Check schema field is present
|
||||||
|
assert_eq!(errors_array[0]["details"]["schema"], "invalid_schema");
|
||||||
|
assert_eq!(errors_array[1]["details"]["schema"], "invalid_schema");
|
||||||
|
// Check that cause is now a JSON object with want array
|
||||||
|
for error in errors_array {
|
||||||
|
let cause = &error["details"]["cause"];
|
||||||
|
assert!(cause.is_object());
|
||||||
|
assert!(cause["want"].is_array());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[pg_test]
|
#[pg_test]
|
||||||
@ -283,11 +306,13 @@ fn test_validate_json_schema_oneof_validation_errors() {
|
|||||||
let errors_string = result_invalid_string.0["errors"].as_array().expect("Expected error array for invalid string");
|
let errors_string = result_invalid_string.0["errors"].as_array().expect("Expected error array for invalid string");
|
||||||
assert!(errors_string.iter().any(|e|
|
assert!(errors_string.iter().any(|e|
|
||||||
e["details"]["path"] == "/string_prop" &&
|
e["details"]["path"] == "/string_prop" &&
|
||||||
e["code"] == "MAX_LENGTH_VIOLATED"
|
e["code"] == "MAX_LENGTH_VIOLATED" &&
|
||||||
|
e["details"]["schema"] == "oneof_schema"
|
||||||
), "Missing maxLength error");
|
), "Missing maxLength error");
|
||||||
assert!(errors_string.iter().any(|e|
|
assert!(errors_string.iter().any(|e|
|
||||||
e["details"]["path"] == "" &&
|
e["details"]["path"] == "/number_prop" &&
|
||||||
e["code"] == "REQUIRED_FIELD_MISSING"
|
e["code"] == "REQUIRED_FIELD_MISSING" &&
|
||||||
|
e["details"]["schema"] == "oneof_schema"
|
||||||
), "Missing number_prop required error");
|
), "Missing number_prop required error");
|
||||||
|
|
||||||
// --- Test case 2: Fails number minimum (in branch 1) AND missing string_prop (in branch 0) ---
|
// --- Test case 2: Fails number minimum (in branch 1) AND missing string_prop (in branch 0) ---
|
||||||
@ -299,11 +324,13 @@ fn test_validate_json_schema_oneof_validation_errors() {
|
|||||||
let errors_number = result_invalid_number.0["errors"].as_array().expect("Expected error array for invalid number");
|
let errors_number = result_invalid_number.0["errors"].as_array().expect("Expected error array for invalid number");
|
||||||
assert!(errors_number.iter().any(|e|
|
assert!(errors_number.iter().any(|e|
|
||||||
e["details"]["path"] == "/number_prop" &&
|
e["details"]["path"] == "/number_prop" &&
|
||||||
e["code"] == "MINIMUM_VIOLATED"
|
e["code"] == "MINIMUM_VIOLATED" &&
|
||||||
|
e["details"]["schema"] == "oneof_schema"
|
||||||
), "Missing minimum error");
|
), "Missing minimum error");
|
||||||
assert!(errors_number.iter().any(|e|
|
assert!(errors_number.iter().any(|e|
|
||||||
e["details"]["path"] == "" &&
|
e["details"]["path"] == "/string_prop" &&
|
||||||
e["code"] == "REQUIRED_FIELD_MISSING"
|
e["code"] == "REQUIRED_FIELD_MISSING" &&
|
||||||
|
e["details"]["schema"] == "oneof_schema"
|
||||||
), "Missing string_prop required error");
|
), "Missing string_prop required error");
|
||||||
|
|
||||||
// --- Test case 3: Fails type check (not object) for both branches ---
|
// --- Test case 3: Fails type check (not object) for both branches ---
|
||||||
@ -317,20 +344,29 @@ fn test_validate_json_schema_oneof_validation_errors() {
|
|||||||
assert_eq!(errors_bool.len(), 1, "Expected exactly one error after deduplication");
|
assert_eq!(errors_bool.len(), 1, "Expected exactly one error after deduplication");
|
||||||
assert_eq!(errors_bool[0]["code"], "TYPE_MISMATCH");
|
assert_eq!(errors_bool[0]["code"], "TYPE_MISMATCH");
|
||||||
assert_eq!(errors_bool[0]["details"]["path"], "");
|
assert_eq!(errors_bool[0]["details"]["path"], "");
|
||||||
|
assert_eq!(errors_bool[0]["details"]["schema"], "oneof_schema");
|
||||||
|
|
||||||
// --- Test case 4: Fails missing required for both branches ---
|
// --- Test case 4: Fails missing required for both branches ---
|
||||||
// Input: empty object, expected string_prop (branch 0) OR number_prop (branch 1)
|
// Input: empty object, expected string_prop (branch 0) OR number_prop (branch 1)
|
||||||
let invalid_empty_obj = json!({});
|
let invalid_empty_obj = json!({});
|
||||||
let result_empty_obj = validate_json_schema(schema_id, jsonb(invalid_empty_obj));
|
let result_empty_obj = validate_json_schema(schema_id, jsonb(invalid_empty_obj));
|
||||||
// Expect only 1 leaf error after filtering, as both original errors have instance_path ""
|
// Now we expect 2 errors because required fields are split into individual errors
|
||||||
assert_failure_with_json!(result_empty_obj, 1);
|
assert_failure_with_json!(result_empty_obj, 2);
|
||||||
// Explicitly check that the single remaining error is one of the expected missing properties errors
|
let errors_empty = result_empty_obj.0["errors"].as_array().unwrap();
|
||||||
let errors_empty = result_empty_obj.0["errors"].as_array().expect("Expected error array for empty object");
|
assert_eq!(errors_empty.len(), 2, "Expected two errors for missing required fields");
|
||||||
assert_eq!(errors_empty.len(), 1, "Expected exactly one error after filtering empty object");
|
|
||||||
assert_eq!(errors_empty[0]["code"], "REQUIRED_FIELD_MISSING");
|
// Check that we have errors for both missing fields
|
||||||
assert_eq!(errors_empty[0]["details"]["path"], "");
|
assert!(errors_empty.iter().any(|e|
|
||||||
// The human message should be generic
|
e["details"]["path"] == "/string_prop" &&
|
||||||
assert_eq!(errors_empty[0]["message"], "Required field is missing");
|
e["code"] == "REQUIRED_FIELD_MISSING" &&
|
||||||
|
e["details"]["schema"] == "oneof_schema"
|
||||||
|
), "Missing string_prop required error");
|
||||||
|
|
||||||
|
assert!(errors_empty.iter().any(|e|
|
||||||
|
e["details"]["path"] == "/number_prop" &&
|
||||||
|
e["code"] == "REQUIRED_FIELD_MISSING" &&
|
||||||
|
e["details"]["schema"] == "oneof_schema"
|
||||||
|
), "Missing number_prop required error");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[pg_test]
|
#[pg_test]
|
||||||
@ -376,6 +412,87 @@ fn test_show_json_schemas() {
|
|||||||
assert!(schemas.contains(&json!(schema_id2)));
|
assert!(schemas.contains(&json!(schema_id2)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[pg_test]
|
||||||
|
fn test_root_level_type_mismatch() {
|
||||||
|
clear_json_schemas();
|
||||||
|
let schema_id = "array_schema";
|
||||||
|
|
||||||
|
// Schema expecting an array (like delete_tokens response)
|
||||||
|
let schema = json!({
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"id": { "type": "string", "format": "uuid" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let cache_result = cache_json_schema(schema_id, jsonb(schema), false);
|
||||||
|
assert_success_with_json!(cache_result, "Schema caching should succeed");
|
||||||
|
|
||||||
|
// Test 1: Validate null against array schema (simulating delete_tokens issue)
|
||||||
|
let null_instance = json!(null);
|
||||||
|
let null_result = validate_json_schema(schema_id, jsonb(null_instance));
|
||||||
|
assert_failure_with_json!(null_result, 1, "Expected array but got null");
|
||||||
|
let null_errors = null_result.0["errors"].as_array().unwrap();
|
||||||
|
assert_eq!(null_errors[0]["code"], "TYPE_MISMATCH");
|
||||||
|
assert_eq!(null_errors[0]["details"]["path"], ""); // Root level path should be empty string
|
||||||
|
assert_eq!(null_errors[0]["details"]["context"], json!(null));
|
||||||
|
assert_eq!(null_errors[0]["details"]["schema"], "array_schema");
|
||||||
|
// Check cause is now a JSON object
|
||||||
|
let cause_null = &null_errors[0]["details"]["cause"];
|
||||||
|
assert!(cause_null.is_object());
|
||||||
|
assert_eq!(cause_null["got"], "null");
|
||||||
|
assert_eq!(cause_null["want"], json!(["array"]));
|
||||||
|
|
||||||
|
// Test 2: Validate object against array schema
|
||||||
|
let object_instance = json!({"id": "not-an-array"});
|
||||||
|
let object_result = validate_json_schema(schema_id, jsonb(object_instance.clone()));
|
||||||
|
assert_failure_with_json!(object_result, 1, "Expected array but got object");
|
||||||
|
let object_errors = object_result.0["errors"].as_array().unwrap();
|
||||||
|
assert_eq!(object_errors[0]["code"], "TYPE_MISMATCH");
|
||||||
|
assert_eq!(object_errors[0]["details"]["path"], ""); // Root level path should be empty string
|
||||||
|
assert_eq!(object_errors[0]["details"]["context"], object_instance);
|
||||||
|
assert_eq!(object_errors[0]["details"]["schema"], "array_schema");
|
||||||
|
// Check cause is now a JSON object
|
||||||
|
let cause_object = &object_errors[0]["details"]["cause"];
|
||||||
|
assert!(cause_object.is_object());
|
||||||
|
assert_eq!(cause_object["got"], "object");
|
||||||
|
assert_eq!(cause_object["want"], json!(["array"]));
|
||||||
|
|
||||||
|
// Test 3: Valid empty array
|
||||||
|
let valid_empty = json!([]);
|
||||||
|
let valid_result = validate_json_schema(schema_id, jsonb(valid_empty));
|
||||||
|
assert_success_with_json!(valid_result, "Empty array should be valid");
|
||||||
|
|
||||||
|
// Test 4: Schema expecting object at root
|
||||||
|
let object_schema_id = "object_schema";
|
||||||
|
let object_schema = json!({
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"name": { "type": "string" }
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let _ = cache_json_schema(object_schema_id, jsonb(object_schema), false);
|
||||||
|
|
||||||
|
// String at root when object expected
|
||||||
|
let string_instance = json!("not an object");
|
||||||
|
let string_result = validate_json_schema(object_schema_id, jsonb(string_instance));
|
||||||
|
assert_failure_with_json!(string_result, 1, "Expected object but got string");
|
||||||
|
let string_errors = string_result.0["errors"].as_array().unwrap();
|
||||||
|
assert_eq!(string_errors[0]["code"], "TYPE_MISMATCH");
|
||||||
|
assert_eq!(string_errors[0]["details"]["path"], ""); // Root level path
|
||||||
|
assert_eq!(string_errors[0]["details"]["schema"], "object_schema");
|
||||||
|
assert_eq!(string_errors[0]["details"]["context"], json!("not an object"));
|
||||||
|
// Check cause is now a JSON object
|
||||||
|
let cause_string = &string_errors[0]["details"]["cause"];
|
||||||
|
assert!(cause_string.is_object());
|
||||||
|
assert_eq!(cause_string["got"], "string");
|
||||||
|
assert_eq!(cause_string["want"], json!(["object"]));
|
||||||
|
}
|
||||||
|
|
||||||
#[pg_test]
|
#[pg_test]
|
||||||
fn test_auto_strict_validation() {
|
fn test_auto_strict_validation() {
|
||||||
clear_json_schemas();
|
clear_json_schemas();
|
||||||
@ -448,10 +565,15 @@ fn test_auto_strict_validation() {
|
|||||||
|
|
||||||
// Should fail with strict schema
|
// Should fail with strict schema
|
||||||
let result_root_strict = validate_json_schema(schema_id, jsonb(invalid_root_extra.clone()));
|
let result_root_strict = validate_json_schema(schema_id, jsonb(invalid_root_extra.clone()));
|
||||||
assert_failure_with_json!(result_root_strict, 1, "Object contains properties that are not allowed");
|
assert_failure_with_json!(result_root_strict, 1, "This schema always fails validation");
|
||||||
let errors_root = result_root_strict.0["errors"].as_array().unwrap();
|
let errors_root = result_root_strict.0["errors"].as_array().unwrap();
|
||||||
assert_eq!(errors_root[0]["code"], "ADDITIONAL_PROPERTIES_NOT_ALLOWED");
|
assert_eq!(errors_root[0]["code"], "FALSE_SCHEMA");
|
||||||
assert_eq!(errors_root[0]["details"]["path"], "");
|
assert_eq!(errors_root[0]["details"]["path"], "/extraField");
|
||||||
|
assert_eq!(errors_root[0]["details"]["schema"], "strict_test");
|
||||||
|
// Check cause is now a JSON object (empty for FalseSchema)
|
||||||
|
let cause_root = &errors_root[0]["details"]["cause"];
|
||||||
|
assert!(cause_root.is_object());
|
||||||
|
assert_eq!(cause_root, &json!({}));
|
||||||
|
|
||||||
// Should pass with non-strict schema
|
// Should pass with non-strict schema
|
||||||
let result_root_non_strict = validate_json_schema(schema_id_non_strict, jsonb(invalid_root_extra));
|
let result_root_non_strict = validate_json_schema(schema_id_non_strict, jsonb(invalid_root_extra));
|
||||||
@ -468,10 +590,11 @@ fn test_auto_strict_validation() {
|
|||||||
|
|
||||||
// Should fail with strict schema
|
// Should fail with strict schema
|
||||||
let result_nested_strict = validate_json_schema(schema_id, jsonb(invalid_nested_extra.clone()));
|
let result_nested_strict = validate_json_schema(schema_id, jsonb(invalid_nested_extra.clone()));
|
||||||
assert_failure_with_json!(result_nested_strict, 1, "Object contains properties that are not allowed");
|
assert_failure_with_json!(result_nested_strict, 1, "This schema always fails validation");
|
||||||
let errors_nested = result_nested_strict.0["errors"].as_array().unwrap();
|
let errors_nested = result_nested_strict.0["errors"].as_array().unwrap();
|
||||||
assert_eq!(errors_nested[0]["code"], "ADDITIONAL_PROPERTIES_NOT_ALLOWED");
|
assert_eq!(errors_nested[0]["code"], "FALSE_SCHEMA");
|
||||||
assert_eq!(errors_nested[0]["details"]["path"], "/profile");
|
assert_eq!(errors_nested[0]["details"]["path"], "/profile/extraNested");
|
||||||
|
assert_eq!(errors_nested[0]["details"]["schema"], "strict_test");
|
||||||
|
|
||||||
// Should pass with non-strict schema
|
// Should pass with non-strict schema
|
||||||
let result_nested_non_strict = validate_json_schema(schema_id_non_strict, jsonb(invalid_nested_extra));
|
let result_nested_non_strict = validate_json_schema(schema_id_non_strict, jsonb(invalid_nested_extra));
|
||||||
@ -491,10 +614,11 @@ fn test_auto_strict_validation() {
|
|||||||
|
|
||||||
// Should fail with strict schema
|
// Should fail with strict schema
|
||||||
let result_deep_strict = validate_json_schema(schema_id, jsonb(invalid_deep_extra.clone()));
|
let result_deep_strict = validate_json_schema(schema_id, jsonb(invalid_deep_extra.clone()));
|
||||||
assert_failure_with_json!(result_deep_strict, 1, "Object contains properties that are not allowed");
|
assert_failure_with_json!(result_deep_strict, 1, "This schema always fails validation");
|
||||||
let errors_deep = result_deep_strict.0["errors"].as_array().unwrap();
|
let errors_deep = result_deep_strict.0["errors"].as_array().unwrap();
|
||||||
assert_eq!(errors_deep[0]["code"], "ADDITIONAL_PROPERTIES_NOT_ALLOWED");
|
assert_eq!(errors_deep[0]["code"], "FALSE_SCHEMA");
|
||||||
assert_eq!(errors_deep[0]["details"]["path"], "/profile/preferences");
|
assert_eq!(errors_deep[0]["details"]["path"], "/profile/preferences/extraDeep");
|
||||||
|
assert_eq!(errors_deep[0]["details"]["schema"], "strict_test");
|
||||||
|
|
||||||
// Should pass with non-strict schema
|
// Should pass with non-strict schema
|
||||||
let result_deep_non_strict = validate_json_schema(schema_id_non_strict, jsonb(invalid_deep_extra));
|
let result_deep_non_strict = validate_json_schema(schema_id_non_strict, jsonb(invalid_deep_extra));
|
||||||
@ -510,15 +634,16 @@ fn test_auto_strict_validation() {
|
|||||||
|
|
||||||
// Should fail with strict schema
|
// Should fail with strict schema
|
||||||
let result_array_strict = validate_json_schema(schema_id, jsonb(invalid_array_item_extra.clone()));
|
let result_array_strict = validate_json_schema(schema_id, jsonb(invalid_array_item_extra.clone()));
|
||||||
assert_failure_with_json!(result_array_strict, 1, "Object contains properties that are not allowed");
|
assert_failure_with_json!(result_array_strict, 1, "This schema always fails validation");
|
||||||
let errors_array = result_array_strict.0["errors"].as_array().unwrap();
|
let errors_array = result_array_strict.0["errors"].as_array().unwrap();
|
||||||
assert_eq!(errors_array[0]["code"], "ADDITIONAL_PROPERTIES_NOT_ALLOWED");
|
assert_eq!(errors_array[0]["code"], "FALSE_SCHEMA");
|
||||||
assert_eq!(errors_array[0]["details"]["path"], "/tags/0");
|
assert_eq!(errors_array[0]["details"]["path"], "/tags/0/extraInArray");
|
||||||
|
assert_eq!(errors_array[0]["details"]["schema"], "strict_test");
|
||||||
|
|
||||||
// Should pass with non-strict schema
|
// Should pass with non-strict schema
|
||||||
let result_array_non_strict = validate_json_schema(schema_id_non_strict, jsonb(invalid_array_item_extra));
|
let result_array_non_strict = validate_json_schema(schema_id_non_strict, jsonb(invalid_array_item_extra));
|
||||||
assert_success_with_json!(result_array_non_strict, "Extra array item property should be allowed with non-strict schema");
|
assert_success_with_json!(result_array_non_strict, "Extra array item property should be allowed with non-strict schema");
|
||||||
|
|
||||||
// Test 6: Schema with explicit additionalProperties: true should allow extras even with strict=true
|
// Test 6: Schema with explicit additionalProperties: true should allow extras even with strict=true
|
||||||
let schema_id_permissive = "permissive_test";
|
let schema_id_permissive = "permissive_test";
|
||||||
let permissive_schema = json!({
|
let permissive_schema = json!({
|
||||||
@ -538,4 +663,627 @@ fn test_auto_strict_validation() {
|
|||||||
|
|
||||||
let result_permissive = validate_json_schema(schema_id_permissive, jsonb(instance_with_extra));
|
let result_permissive = validate_json_schema(schema_id_permissive, jsonb(instance_with_extra));
|
||||||
assert_success_with_json!(result_permissive, "Instance with extra property should pass when additionalProperties is explicitly true, even with strict=true");
|
assert_success_with_json!(result_permissive, "Instance with extra property should pass when additionalProperties is explicitly true, even with strict=true");
|
||||||
|
|
||||||
|
// Test 7: Schema with conditionals (if/then/else) should NOT add unevaluatedProperties to conditional branches
|
||||||
|
let schema_id_conditional = "conditional_strict_test";
|
||||||
|
let conditional_schema = json!({
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"kind": { "type": "string", "enum": ["checking", "savings"] },
|
||||||
|
"creating": { "type": "boolean" }
|
||||||
|
},
|
||||||
|
"if": {
|
||||||
|
"properties": {
|
||||||
|
"creating": { "const": true }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"then": {
|
||||||
|
"properties": {
|
||||||
|
"account_number": {
|
||||||
|
"type": "string",
|
||||||
|
"pattern": "^[0-9]{4,17}$"
|
||||||
|
},
|
||||||
|
"routing_number": {
|
||||||
|
"type": "string",
|
||||||
|
"pattern": "^[0-9]{9}$"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["account_number", "routing_number"]
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let _ = cache_json_schema(schema_id_conditional, jsonb(conditional_schema), true); // strict=true
|
||||||
|
|
||||||
|
// Valid data with properties from both main schema and then clause
|
||||||
|
let valid_conditional = json!({
|
||||||
|
"kind": "checking",
|
||||||
|
"creating": true,
|
||||||
|
"account_number": "1234567890",
|
||||||
|
"routing_number": "123456789"
|
||||||
|
});
|
||||||
|
|
||||||
|
let result_conditional = validate_json_schema(schema_id_conditional, jsonb(valid_conditional));
|
||||||
|
assert_success_with_json!(result_conditional, "Conditional properties should be recognized as evaluated");
|
||||||
|
|
||||||
|
// Invalid: extra property not defined anywhere
|
||||||
|
let invalid_conditional = json!({
|
||||||
|
"kind": "checking",
|
||||||
|
"creating": true,
|
||||||
|
"account_number": "1234567890",
|
||||||
|
"routing_number": "123456789",
|
||||||
|
"extra": "not allowed"
|
||||||
|
});
|
||||||
|
|
||||||
|
let result_invalid_conditional = validate_json_schema(schema_id_conditional, jsonb(invalid_conditional));
|
||||||
|
assert_failure_with_json!(result_invalid_conditional, 1, "This schema always fails validation");
|
||||||
|
let errors_conditional = result_invalid_conditional.0["errors"].as_array().unwrap();
|
||||||
|
assert_eq!(errors_conditional[0]["code"], "FALSE_SCHEMA");
|
||||||
|
assert_eq!(errors_conditional[0]["details"]["path"], "/extra");
|
||||||
|
|
||||||
|
// Test the specific edge case: pattern validation failure in a conditional branch
|
||||||
|
// We filter out FALSE_SCHEMA errors when there are other validation errors
|
||||||
|
let pattern_failure = json!({
|
||||||
|
"kind": "checking",
|
||||||
|
"creating": true,
|
||||||
|
"account_number": "22", // Too short - will fail pattern validation
|
||||||
|
"routing_number": "123456789" // Valid, but would be unevaluated - filtered out
|
||||||
|
});
|
||||||
|
|
||||||
|
let result_pattern = validate_json_schema(schema_id_conditional, jsonb(pattern_failure));
|
||||||
|
let pattern_errors = result_pattern.0["errors"].as_array().unwrap();
|
||||||
|
|
||||||
|
// We expect only 1 error: PATTERN_VIOLATED for account_number
|
||||||
|
// FALSE_SCHEMA for routing_number is filtered out because there's a real validation error
|
||||||
|
assert_failure_with_json!(result_pattern, 1);
|
||||||
|
assert_eq!(pattern_errors[0]["code"], "PATTERN_VIOLATED");
|
||||||
|
assert_eq!(pattern_errors[0]["details"]["path"], "/account_number");
|
||||||
|
|
||||||
|
// Test case where both fields have pattern violations
|
||||||
|
let both_pattern_failures = json!({
|
||||||
|
"kind": "checking",
|
||||||
|
"creating": true,
|
||||||
|
"account_number": "22", // Too short - will fail pattern validation
|
||||||
|
"routing_number": "123" // Too short - will fail pattern validation
|
||||||
|
});
|
||||||
|
|
||||||
|
let result_both = validate_json_schema(schema_id_conditional, jsonb(both_pattern_failures));
|
||||||
|
let both_errors = result_both.0["errors"].as_array().unwrap();
|
||||||
|
|
||||||
|
// We expect 2 errors: both PATTERN_VIOLATED
|
||||||
|
assert_failure_with_json!(result_both, 2);
|
||||||
|
|
||||||
|
assert!(both_errors.iter().any(|e|
|
||||||
|
e["code"] == "PATTERN_VIOLATED" &&
|
||||||
|
e["details"]["path"] == "/account_number"
|
||||||
|
), "Should have pattern violation for account_number");
|
||||||
|
|
||||||
|
assert!(both_errors.iter().any(|e|
|
||||||
|
e["code"] == "PATTERN_VIOLATED" &&
|
||||||
|
e["details"]["path"] == "/routing_number"
|
||||||
|
), "Should have pattern violation for routing_number");
|
||||||
|
|
||||||
|
// Test case where there are only FALSE_SCHEMA errors (no other validation errors)
|
||||||
|
let only_false_schema = json!({
|
||||||
|
"kind": "checking",
|
||||||
|
"creating": true,
|
||||||
|
"account_number": "1234567890", // Valid
|
||||||
|
"routing_number": "123456789", // Valid
|
||||||
|
"extra": "not allowed" // Will cause FALSE_SCHEMA
|
||||||
|
});
|
||||||
|
|
||||||
|
let result_only_false = validate_json_schema(schema_id_conditional, jsonb(only_false_schema));
|
||||||
|
let only_false_errors = result_only_false.0["errors"].as_array().unwrap();
|
||||||
|
|
||||||
|
// We expect 1 FALSE_SCHEMA error since there are no other validation errors
|
||||||
|
assert_failure_with_json!(result_only_false, 1);
|
||||||
|
assert_eq!(only_false_errors[0]["code"], "FALSE_SCHEMA");
|
||||||
|
assert_eq!(only_false_errors[0]["details"]["path"], "/extra");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pg_test]
|
||||||
|
fn test_required_fields_split_errors() {
|
||||||
|
clear_json_schemas();
|
||||||
|
let schema_id = "required_split_test";
|
||||||
|
|
||||||
|
// Schema with multiple required fields
|
||||||
|
let schema = json!({
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"name": { "type": "string" },
|
||||||
|
"kind": { "type": "string" },
|
||||||
|
"age": { "type": "number" }
|
||||||
|
},
|
||||||
|
"required": ["name", "kind", "age"]
|
||||||
|
});
|
||||||
|
|
||||||
|
let cache_result = cache_json_schema(schema_id, jsonb(schema), false);
|
||||||
|
assert_success_with_json!(cache_result, "Schema caching should succeed");
|
||||||
|
|
||||||
|
// Test 1: Missing all required fields
|
||||||
|
let empty_instance = json!({});
|
||||||
|
let result = validate_json_schema(schema_id, jsonb(empty_instance));
|
||||||
|
|
||||||
|
// Should get 3 separate errors, one for each missing field
|
||||||
|
assert_failure_with_json!(result, 3, "Required field");
|
||||||
|
|
||||||
|
let errors = result.0["errors"].as_array().unwrap();
|
||||||
|
|
||||||
|
// Check that we have errors for each missing field with correct paths
|
||||||
|
assert!(errors.iter().any(|e|
|
||||||
|
e["code"] == "REQUIRED_FIELD_MISSING" &&
|
||||||
|
e["details"]["path"] == "/name" &&
|
||||||
|
e["message"] == "Required field 'name' is missing"
|
||||||
|
), "Missing error for name field");
|
||||||
|
|
||||||
|
assert!(errors.iter().any(|e|
|
||||||
|
e["code"] == "REQUIRED_FIELD_MISSING" &&
|
||||||
|
e["details"]["path"] == "/kind" &&
|
||||||
|
e["message"] == "Required field 'kind' is missing"
|
||||||
|
), "Missing error for kind field");
|
||||||
|
|
||||||
|
assert!(errors.iter().any(|e|
|
||||||
|
e["code"] == "REQUIRED_FIELD_MISSING" &&
|
||||||
|
e["details"]["path"] == "/age" &&
|
||||||
|
e["message"] == "Required field 'age' is missing"
|
||||||
|
), "Missing error for age field");
|
||||||
|
|
||||||
|
// Test 2: Missing only some required fields
|
||||||
|
let partial_instance = json!({
|
||||||
|
"name": "Alice"
|
||||||
|
});
|
||||||
|
let partial_result = validate_json_schema(schema_id, jsonb(partial_instance));
|
||||||
|
|
||||||
|
// Should get 2 errors for the missing fields
|
||||||
|
assert_failure_with_json!(partial_result, 2, "Required field");
|
||||||
|
|
||||||
|
let partial_errors = partial_result.0["errors"].as_array().unwrap();
|
||||||
|
|
||||||
|
assert!(partial_errors.iter().any(|e|
|
||||||
|
e["details"]["path"] == "/kind"
|
||||||
|
), "Missing error for kind field");
|
||||||
|
|
||||||
|
assert!(partial_errors.iter().any(|e|
|
||||||
|
e["details"]["path"] == "/age"
|
||||||
|
), "Missing error for age field");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pg_test]
|
||||||
|
fn test_dependency_fields_split_errors() {
|
||||||
|
clear_json_schemas();
|
||||||
|
let schema_id = "dependency_split_test";
|
||||||
|
|
||||||
|
// Schema with dependencies like the tokenize_external_accounts example
|
||||||
|
let schema = json!({
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"creating": { "type": "boolean" },
|
||||||
|
"name": { "type": "string" },
|
||||||
|
"kind": { "type": "string" },
|
||||||
|
"description": { "type": "string" }
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"creating": ["name", "kind"] // When creating is present, name and kind are required
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let cache_result = cache_json_schema(schema_id, jsonb(schema), false);
|
||||||
|
assert_success_with_json!(cache_result, "Schema caching should succeed");
|
||||||
|
|
||||||
|
// Test 1: Has creating=true but missing both dependent fields
|
||||||
|
let missing_both = json!({
|
||||||
|
"creating": true,
|
||||||
|
"description": "Some description"
|
||||||
|
});
|
||||||
|
let result = validate_json_schema(schema_id, jsonb(missing_both));
|
||||||
|
|
||||||
|
// Should get 2 separate errors, one for each missing dependent field
|
||||||
|
assert_failure_with_json!(result, 2, "Field");
|
||||||
|
|
||||||
|
let errors = result.0["errors"].as_array().unwrap();
|
||||||
|
|
||||||
|
assert!(errors.iter().any(|e|
|
||||||
|
e["code"] == "DEPENDENCY_FAILED" &&
|
||||||
|
e["details"]["path"] == "/name" &&
|
||||||
|
e["message"] == "Field 'name' is required when 'creating' is present"
|
||||||
|
), "Missing error for dependent name field");
|
||||||
|
|
||||||
|
assert!(errors.iter().any(|e|
|
||||||
|
e["code"] == "DEPENDENCY_FAILED" &&
|
||||||
|
e["details"]["path"] == "/kind" &&
|
||||||
|
e["message"] == "Field 'kind' is required when 'creating' is present"
|
||||||
|
), "Missing error for dependent kind field");
|
||||||
|
|
||||||
|
// Test 2: Has creating=true with only one dependent field
|
||||||
|
let missing_one = json!({
|
||||||
|
"creating": true,
|
||||||
|
"name": "My Account"
|
||||||
|
});
|
||||||
|
let result_one = validate_json_schema(schema_id, jsonb(missing_one));
|
||||||
|
|
||||||
|
// Should get 1 error for the missing kind field
|
||||||
|
assert_failure_with_json!(result_one, 1, "Field 'kind' is required when 'creating' is present");
|
||||||
|
|
||||||
|
let errors_one = result_one.0["errors"].as_array().unwrap();
|
||||||
|
assert_eq!(errors_one[0]["details"]["path"], "/kind");
|
||||||
|
|
||||||
|
// Test 3: Has no creating field - no dependency errors
|
||||||
|
let no_creating = json!({
|
||||||
|
"description": "No creating field"
|
||||||
|
});
|
||||||
|
let result_no_creating = validate_json_schema(schema_id, jsonb(no_creating));
|
||||||
|
assert_success_with_json!(result_no_creating, "Should succeed when creating field is not present");
|
||||||
|
|
||||||
|
// Test 4: Has creating=false - dependencies still apply because field exists!
|
||||||
|
let creating_false = json!({
|
||||||
|
"creating": false,
|
||||||
|
"description": "Creating is false"
|
||||||
|
});
|
||||||
|
let result_false = validate_json_schema(schema_id, jsonb(creating_false));
|
||||||
|
// Dependencies are triggered by field existence, not value, so this should fail
|
||||||
|
assert_failure_with_json!(result_false, 2, "Field");
|
||||||
|
|
||||||
|
let errors_false = result_false.0["errors"].as_array().unwrap();
|
||||||
|
assert!(errors_false.iter().any(|e|
|
||||||
|
e["details"]["path"] == "/name"
|
||||||
|
), "Should have error for name when creating exists with false value");
|
||||||
|
assert!(errors_false.iter().any(|e|
|
||||||
|
e["details"]["path"] == "/kind"
|
||||||
|
), "Should have error for kind when creating exists with false value");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pg_test]
|
||||||
|
fn test_nested_required_dependency_errors() {
|
||||||
|
clear_json_schemas();
|
||||||
|
let schema_id = "nested_dep_test";
|
||||||
|
|
||||||
|
// More complex schema with nested objects
|
||||||
|
let schema = json!({
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"items": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"id": { "type": "string" },
|
||||||
|
"creating": { "type": "boolean" },
|
||||||
|
"name": { "type": "string" },
|
||||||
|
"kind": { "type": "string" }
|
||||||
|
},
|
||||||
|
"required": ["id"],
|
||||||
|
"dependencies": {
|
||||||
|
"creating": ["name", "kind"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["items"]
|
||||||
|
});
|
||||||
|
|
||||||
|
let cache_result = cache_json_schema(schema_id, jsonb(schema), false);
|
||||||
|
assert_success_with_json!(cache_result, "Schema caching should succeed");
|
||||||
|
|
||||||
|
// Test with array items that have dependency violations
|
||||||
|
let instance = json!({
|
||||||
|
"items": [
|
||||||
|
{
|
||||||
|
"id": "item1",
|
||||||
|
"creating": true
|
||||||
|
// Missing name and kind
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "item2",
|
||||||
|
"creating": true,
|
||||||
|
"name": "Item 2"
|
||||||
|
// Missing kind
|
||||||
|
}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
let result = validate_json_schema(schema_id, jsonb(instance));
|
||||||
|
|
||||||
|
// Should get 3 errors total: 2 for first item, 1 for second item
|
||||||
|
assert_failure_with_json!(result, 3, "Field");
|
||||||
|
|
||||||
|
let errors = result.0["errors"].as_array().unwrap();
|
||||||
|
|
||||||
|
// Check paths are correct for array items
|
||||||
|
assert!(errors.iter().any(|e|
|
||||||
|
e["details"]["path"] == "/items/0/name" &&
|
||||||
|
e["code"] == "DEPENDENCY_FAILED"
|
||||||
|
), "Missing error for first item's name");
|
||||||
|
|
||||||
|
assert!(errors.iter().any(|e|
|
||||||
|
e["details"]["path"] == "/items/0/kind" &&
|
||||||
|
e["code"] == "DEPENDENCY_FAILED"
|
||||||
|
), "Missing error for first item's kind");
|
||||||
|
|
||||||
|
assert!(errors.iter().any(|e|
|
||||||
|
e["details"]["path"] == "/items/1/kind" &&
|
||||||
|
e["code"] == "DEPENDENCY_FAILED"
|
||||||
|
), "Missing error for second item's kind");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pg_test]
|
||||||
|
fn test_additional_properties_split_errors() {
|
||||||
|
clear_json_schemas();
|
||||||
|
let schema_id = "additional_props_split_test";
|
||||||
|
|
||||||
|
// Schema with additionalProperties: false
|
||||||
|
let schema = json!({
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"name": { "type": "string" },
|
||||||
|
"age": { "type": "number" }
|
||||||
|
},
|
||||||
|
"additionalProperties": false
|
||||||
|
});
|
||||||
|
|
||||||
|
let cache_result = cache_json_schema(schema_id, jsonb(schema), false);
|
||||||
|
assert_success_with_json!(cache_result, "Schema caching should succeed");
|
||||||
|
|
||||||
|
// Test 1: Multiple additional properties not allowed
|
||||||
|
let instance_many_extras = json!({
|
||||||
|
"name": "Alice",
|
||||||
|
"age": 30,
|
||||||
|
"extra1": "not allowed",
|
||||||
|
"extra2": 42,
|
||||||
|
"extra3": true
|
||||||
|
});
|
||||||
|
|
||||||
|
let result = validate_json_schema(schema_id, jsonb(instance_many_extras));
|
||||||
|
|
||||||
|
// Should get 3 separate errors, one for each additional property
|
||||||
|
assert_failure_with_json!(result, 3, "Property");
|
||||||
|
|
||||||
|
let errors = result.0["errors"].as_array().unwrap();
|
||||||
|
|
||||||
|
// Check that we have errors for each additional property with correct paths
|
||||||
|
assert!(errors.iter().any(|e|
|
||||||
|
e["code"] == "ADDITIONAL_PROPERTIES_NOT_ALLOWED" &&
|
||||||
|
e["details"]["path"] == "/extra1" &&
|
||||||
|
e["message"] == "Property 'extra1' is not allowed"
|
||||||
|
), "Missing error for extra1 property");
|
||||||
|
|
||||||
|
assert!(errors.iter().any(|e|
|
||||||
|
e["code"] == "ADDITIONAL_PROPERTIES_NOT_ALLOWED" &&
|
||||||
|
e["details"]["path"] == "/extra2" &&
|
||||||
|
e["message"] == "Property 'extra2' is not allowed"
|
||||||
|
), "Missing error for extra2 property");
|
||||||
|
|
||||||
|
assert!(errors.iter().any(|e|
|
||||||
|
e["code"] == "ADDITIONAL_PROPERTIES_NOT_ALLOWED" &&
|
||||||
|
e["details"]["path"] == "/extra3" &&
|
||||||
|
e["message"] == "Property 'extra3' is not allowed"
|
||||||
|
), "Missing error for extra3 property");
|
||||||
|
|
||||||
|
// Test 2: Single additional property
|
||||||
|
let instance_one_extra = json!({
|
||||||
|
"name": "Bob",
|
||||||
|
"age": 25,
|
||||||
|
"unauthorized": "field"
|
||||||
|
});
|
||||||
|
|
||||||
|
let result_one = validate_json_schema(schema_id, jsonb(instance_one_extra));
|
||||||
|
|
||||||
|
// Should get 1 error for the additional property
|
||||||
|
assert_failure_with_json!(result_one, 1, "Property 'unauthorized' is not allowed");
|
||||||
|
|
||||||
|
let errors_one = result_one.0["errors"].as_array().unwrap();
|
||||||
|
assert_eq!(errors_one[0]["details"]["path"], "/unauthorized");
|
||||||
|
|
||||||
|
// Test 3: Nested objects with additional properties
|
||||||
|
let nested_schema_id = "nested_additional_props_test";
|
||||||
|
let nested_schema = json!({
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"user": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"name": { "type": "string" }
|
||||||
|
},
|
||||||
|
"additionalProperties": false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let _ = cache_json_schema(nested_schema_id, jsonb(nested_schema), false);
|
||||||
|
|
||||||
|
let nested_instance = json!({
|
||||||
|
"user": {
|
||||||
|
"name": "Charlie",
|
||||||
|
"role": "admin",
|
||||||
|
"level": 5
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let nested_result = validate_json_schema(nested_schema_id, jsonb(nested_instance));
|
||||||
|
|
||||||
|
// Should get 2 errors for the nested additional properties
|
||||||
|
assert_failure_with_json!(nested_result, 2, "Property");
|
||||||
|
|
||||||
|
let nested_errors = nested_result.0["errors"].as_array().unwrap();
|
||||||
|
|
||||||
|
assert!(nested_errors.iter().any(|e|
|
||||||
|
e["details"]["path"] == "/user/role" &&
|
||||||
|
e["code"] == "ADDITIONAL_PROPERTIES_NOT_ALLOWED"
|
||||||
|
), "Missing error for nested role property");
|
||||||
|
|
||||||
|
assert!(nested_errors.iter().any(|e|
|
||||||
|
e["details"]["path"] == "/user/level" &&
|
||||||
|
e["code"] == "ADDITIONAL_PROPERTIES_NOT_ALLOWED"
|
||||||
|
), "Missing error for nested level property");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pg_test]
|
||||||
|
fn test_unevaluated_properties_errors() {
|
||||||
|
clear_json_schemas();
|
||||||
|
let schema_id = "unevaluated_test";
|
||||||
|
|
||||||
|
// Schema with unevaluatedProperties: false
|
||||||
|
// This is more complex than additionalProperties because it considers
|
||||||
|
// properties matched by pattern properties and additional properties
|
||||||
|
let schema = json!({
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"name": { "type": "string" },
|
||||||
|
"age": { "type": "number" }
|
||||||
|
},
|
||||||
|
"patternProperties": {
|
||||||
|
"^attr_": { "type": "string" } // Properties starting with attr_ are allowed
|
||||||
|
},
|
||||||
|
"unevaluatedProperties": false // No other properties allowed
|
||||||
|
});
|
||||||
|
|
||||||
|
let cache_result = cache_json_schema(schema_id, jsonb(schema), false);
|
||||||
|
assert_success_with_json!(cache_result, "Schema caching should succeed");
|
||||||
|
|
||||||
|
// Test 1: Multiple unevaluated properties
|
||||||
|
let instance_uneval = json!({
|
||||||
|
"name": "Alice",
|
||||||
|
"age": 30,
|
||||||
|
"attr_color": "blue", // This is OK - matches pattern
|
||||||
|
"extra1": "not evaluated", // These should fail
|
||||||
|
"extra2": 42,
|
||||||
|
"extra3": true
|
||||||
|
});
|
||||||
|
|
||||||
|
let result = validate_json_schema(schema_id, jsonb(instance_uneval));
|
||||||
|
|
||||||
|
// Should get 3 separate FALSE_SCHEMA errors, one for each unevaluated property
|
||||||
|
assert_failure_with_json!(result, 3, "This schema always fails validation");
|
||||||
|
|
||||||
|
let errors = result.0["errors"].as_array().unwrap();
|
||||||
|
|
||||||
|
// Verify all errors are FALSE_SCHEMA with specific paths
|
||||||
|
for error in errors {
|
||||||
|
assert_eq!(error["code"], "FALSE_SCHEMA", "All unevaluated properties should generate FALSE_SCHEMA errors");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check that we have errors for each unevaluated property with correct paths
|
||||||
|
assert!(errors.iter().any(|e|
|
||||||
|
e["code"] == "FALSE_SCHEMA" &&
|
||||||
|
e["details"]["path"] == "/extra1"
|
||||||
|
), "Missing error for extra1 property");
|
||||||
|
|
||||||
|
assert!(errors.iter().any(|e|
|
||||||
|
e["code"] == "FALSE_SCHEMA" &&
|
||||||
|
e["details"]["path"] == "/extra2"
|
||||||
|
), "Missing error for extra2 property");
|
||||||
|
|
||||||
|
assert!(errors.iter().any(|e|
|
||||||
|
e["code"] == "FALSE_SCHEMA" &&
|
||||||
|
e["details"]["path"] == "/extra3"
|
||||||
|
), "Missing error for extra3 property");
|
||||||
|
|
||||||
|
// Test 2: Complex schema with allOf and unevaluatedProperties
|
||||||
|
let complex_schema_id = "complex_unevaluated_test";
|
||||||
|
let complex_schema = json!({
|
||||||
|
"type": "object",
|
||||||
|
"allOf": [
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"firstName": { "type": "string" }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"properties": {
|
||||||
|
"lastName": { "type": "string" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"properties": {
|
||||||
|
"age": { "type": "number" }
|
||||||
|
},
|
||||||
|
"unevaluatedProperties": false
|
||||||
|
});
|
||||||
|
|
||||||
|
let _ = cache_json_schema(complex_schema_id, jsonb(complex_schema), false);
|
||||||
|
|
||||||
|
// firstName and lastName are evaluated by allOf schemas, age by main schema
|
||||||
|
let complex_instance = json!({
|
||||||
|
"firstName": "John",
|
||||||
|
"lastName": "Doe",
|
||||||
|
"age": 25,
|
||||||
|
"nickname": "JD", // Not evaluated by any schema
|
||||||
|
"title": "Mr" // Not evaluated by any schema
|
||||||
|
});
|
||||||
|
|
||||||
|
let complex_result = validate_json_schema(complex_schema_id, jsonb(complex_instance));
|
||||||
|
|
||||||
|
// Should get 2 FALSE_SCHEMA errors for unevaluated properties
|
||||||
|
assert_failure_with_json!(complex_result, 2, "This schema always fails validation");
|
||||||
|
|
||||||
|
let complex_errors = complex_result.0["errors"].as_array().unwrap();
|
||||||
|
|
||||||
|
assert!(complex_errors.iter().any(|e|
|
||||||
|
e["code"] == "FALSE_SCHEMA" &&
|
||||||
|
e["details"]["path"] == "/nickname"
|
||||||
|
), "Missing error for nickname property");
|
||||||
|
|
||||||
|
assert!(complex_errors.iter().any(|e|
|
||||||
|
e["code"] == "FALSE_SCHEMA" &&
|
||||||
|
e["details"]["path"] == "/title"
|
||||||
|
), "Missing error for title property");
|
||||||
|
|
||||||
|
// Test 3: Valid instance with all properties evaluated
|
||||||
|
let valid_instance = json!({
|
||||||
|
"name": "Bob",
|
||||||
|
"age": 40,
|
||||||
|
"attr_style": "modern",
|
||||||
|
"attr_theme": "dark"
|
||||||
|
});
|
||||||
|
|
||||||
|
let valid_result = validate_json_schema(schema_id, jsonb(valid_instance));
|
||||||
|
assert_success_with_json!(valid_result, "All properties are evaluated, should pass");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pg_test]
|
||||||
|
fn test_format_validation_allows_empty_string() {
|
||||||
|
clear_json_schemas();
|
||||||
|
let schema_id = "format_schema_empty";
|
||||||
|
let schema = json!({
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"uuid": { "type": "string", "format": "uuid" },
|
||||||
|
"date_time": { "type": "string", "format": "date-time" },
|
||||||
|
"email": { "type": "string", "format": "email" }
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let _ = cache_json_schema(schema_id, jsonb(schema), false);
|
||||||
|
|
||||||
|
// Test with empty strings for all formatted fields
|
||||||
|
let instance = json!({
|
||||||
|
"uuid": "",
|
||||||
|
"date_time": "",
|
||||||
|
"email": ""
|
||||||
|
});
|
||||||
|
|
||||||
|
let result = validate_json_schema(schema_id, jsonb(instance));
|
||||||
|
|
||||||
|
// This is the test that should fail before the change and pass after
|
||||||
|
assert_success_with_json!(result, "Empty strings should be allowed for format validation");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pg_test]
|
||||||
|
fn test_non_empty_string_format_validation_still_fails() {
|
||||||
|
clear_json_schemas();
|
||||||
|
let schema_id = "non_empty_fail_schema";
|
||||||
|
let schema = json!({
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"date_time": { "type": "string", "format": "date-time" }
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let _ = cache_json_schema(schema_id, jsonb(schema), false);
|
||||||
|
|
||||||
|
// A non-empty but invalid string should still fail
|
||||||
|
let instance = json!({
|
||||||
|
"date_time": "not-a-date"
|
||||||
|
});
|
||||||
|
|
||||||
|
let result = validate_json_schema(schema_id, jsonb(instance));
|
||||||
|
assert_failure_with_json!(result, 1, "Value \"not-a-date\" is not a valid date-time format");
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user