Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ mod try_from_schema;

#[cfg(all(test, feature = "validation"))]
pub(in crate::data_contract) use try_from_schema::DOCUMENT_SCHEMA_ROOT_KEYS;
#[cfg(feature = "validation")]
pub(in crate::data_contract) use try_from_schema::{
first_repeated_key_of_definitions, first_repeated_key_of_schema,
};
pub use try_from_schema::{
referenced_peer_kind_error, referenced_peer_kind_mismatch, referenced_reads_error,
where_condition_literal_error,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,10 @@ mod v4;

#[cfg(all(test, feature = "validation"))]
pub(in crate::data_contract) use native_schema::DOCUMENT_SCHEMA_ROOT_KEYS;
#[cfg(feature = "validation")]
pub(in crate::data_contract) use native_schema::{
first_repeated_key_of_definitions, first_repeated_key_of_schema,
};
pub(in crate::data_contract) use v3::{
resolve_derived_index_properties, validate_preallocated_indexes_kept_on_removal,
validate_summable_off_count_indexes_lossless,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,21 +113,74 @@ pub(super) fn refuse_a_repeated_doctype_key(
name: &str,
read: &mut u64,
) -> Result<(), ProtocolError> {
refuse_a_repeated_key_within(schema, name, &mut String::new(), read)?;
for (definition, value) in schema_defs.into_iter().flatten() {
refuse_a_repeated_key_within(value, name, &mut format!("$defs.{definition}"), read)?;
let repeated = first_repeated_key_of_schema(schema, read)
.or_else(|| first_repeated_key_of_definitions(schema_defs, read));
match repeated {
None => Ok(()),
Some(repeated) => Err(consensus_or_protocol_data_contract_error(
DataContractError::InvalidContractStructure(format!(
"document type \"{name}\" declares `{}` more than once {}: \
the document type parser may read its first entry where the \
schema checks read its last",
repeated.key(),
repeated.place()
)),
)),
}
}

/// A key an object of a document schema, or of a contract's `$defs`, names more than once.
pub(in crate::data_contract) struct RepeatedKey {
key: String,
/// The path of the object naming it: empty at a document schema's root,
/// `$defs.<name>...` in a definition.
path: String,
}

impl RepeatedKey {
/// The key named more than once.
pub(in crate::data_contract) fn key(&self) -> &str {
&self.key
}
Ok(())

/// Where the object naming it is, as a refusal words it.
pub(in crate::data_contract) fn place(&self) -> String {
if self.path.is_empty() {
"at its root".to_string()
} else {
format!("at `{}`", self.path)
}
}
}

/// The first key an object of the document `schema` names more than once, at its root or
/// anywhere below it, walking as [`refuse_a_repeated_doctype_key`] does and counting in
/// `read` each value it reads. `None` when no object repeats a key.
pub(in crate::data_contract) fn first_repeated_key_of_schema(
schema: &Value,
read: &mut u64,
) -> Option<RepeatedKey> {
first_repeated_key_within(schema, &mut String::new(), read)
}

/// [`first_repeated_key_of_schema`] over each definition of a contract's `schema_defs`, in
/// the order of their names.
pub(in crate::data_contract) fn first_repeated_key_of_definitions(
schema_defs: Option<&BTreeMap<String, Value>>,
read: &mut u64,
) -> Option<RepeatedKey> {
schema_defs.into_iter().flatten().find_map(|(name, value)| {
first_repeated_key_within(value, &mut format!("$defs.{name}"), read)
})
}

/// [`refuse_a_repeated_doctype_key`] over `value`, found at `path` within the schema (empty
/// at its root), and everything it holds.
fn refuse_a_repeated_key_within(
/// The first repeated key of `value`, found at `path` within the schema (empty at its
/// root), and of everything it holds.
fn first_repeated_key_within(
value: &Value,
name: &str,
path: &mut String,
read: &mut u64,
) -> Result<(), ProtocolError> {
) -> Option<RepeatedKey> {
*read = read.saturating_add(1);
match value {
Value::Map(map) => {
Expand All @@ -140,39 +193,37 @@ fn refuse_a_repeated_key_within(
continue;
};
if !declared.insert(key) {
let place = if path.is_empty() {
"at its root".to_string()
} else {
format!("at `{path}`")
};
return Err(consensus_or_protocol_data_contract_error(
DataContractError::InvalidContractStructure(format!(
"document type \"{name}\" declares `{key}` more than once {place}: \
the document type parser may read its first entry where the \
schema checks read its last"
)),
));
return Some(RepeatedKey {
key: key.to_string(),
path: path.clone(),
});
}
let len = path.len();
if !path.is_empty() {
path.push('.');
}
path.push_str(key);
refuse_a_repeated_key_within(entry, name, path, read)?;
let repeat = first_repeated_key_within(entry, path, read);
path.truncate(len);
if repeat.is_some() {
return repeat;
}
}
Ok(())
None
}
Value::Array(items) => {
for (index, item) in items.iter().enumerate() {
let len = path.len();
path.push_str(&format!("[{index}]"));
refuse_a_repeated_key_within(item, name, path, read)?;
let repeat = first_repeated_key_within(item, path, read);
path.truncate(len);
if repeat.is_some() {
return repeat;
}
}
Ok(())
None
}
_ => Ok(()),
_ => None,
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -638,3 +638,227 @@ fn should_refuse_a_nested_repeat_beside_a_reference_only_the_expansion_resolves(
"`properties.note`",
);
}

/// A map of `entries` in order, keeping every repeat.
fn map_of(entries: Vec<(&str, Value)>) -> Value {
Value::Map(
entries
.into_iter()
.map(|(key, value)| (text(key), value))
.collect(),
)
}

/// Every key the parser reads, repeated in either order, at the root, in a nested object, in
/// an array's `items`, in an index and in a definition, is refused under full validation,
/// naming the object repeating it.
#[test]
fn should_refuse_a_repeated_key_in_every_object_a_schema_or_its_definitions_hold() {
let string_list = |items: Value| {
platform_value!({
"list": map_of(vec![
("type", text("array")),
("position", Value::U64(0)),
("maxItems", Value::U64(4)),
("items", items),
])
})
};
let note_object = |entries: Vec<(&str, Value)>| {
let mut note = vec![
("type", text("object")),
("position", Value::U64(0)),
(
"properties",
platform_value!({ "leaf": { "type": "string", "maxLength": 10, "position": 0 } }),
),
("additionalProperties", Value::Bool(false)),
];
note.extend(entries);
platform_value!({ "note": map_of(note) })
};
let index_on_a = |index: Value| {
schema_of(vec![
("properties", string_properties()),
("indices", Value::Array(vec![index])),
])
};
let cases: Vec<(&str, &str, &str, Value)> = vec![
(
"root properties, the second entry first",
"properties",
"its root",
schema_of(vec![
("properties", integer_properties()),
("properties", string_properties()),
]),
),
(
"root type",
"type",
"its root",
schema_of(vec![
("type", text("array")),
("properties", string_properties()),
]),
),
(
"root required",
"required",
"its root",
schema_of(vec![
("properties", string_properties()),
("required", platform_value!(["a"])),
("required", platform_value!([])),
]),
),
(
"root indices",
"indices",
"its root",
schema_of(vec![
("properties", string_properties()),
(
"indices",
platform_value!([{ "name": "byA", "properties": [{ "a": "asc" }], "unique": true }]),
),
("indices", platform_value!([])),
]),
),
(
"root additionalProperties",
"additionalProperties",
"its root",
Value::Map(vec![
(text("type"), text("object")),
(text("properties"), string_properties()),
(text("additionalProperties"), Value::Bool(true)),
(text("additionalProperties"), Value::Bool(false)),
]),
),
(
"required of a nested object",
"required",
"`properties.note`",
schema_of(vec![(
"properties",
note_object(vec![
("required", platform_value!(["leaf"])),
("required", platform_value!([])),
]),
)]),
),
(
"type of a nested property",
"type",
"`properties.note.properties.leaf`",
schema_of(vec![(
"properties",
platform_value!({
"note": {
"type": "object",
"position": 0,
"properties": {
"leaf": map_of(vec![
("type", text("integer")),
("position", Value::U64(0)),
("type", text("string")),
("maxLength", Value::U64(10)),
])
},
"additionalProperties": false
}
}),
)]),
),
(
"a key of an array's items",
"maxLength",
"`properties.list.items`",
schema_of(vec![(
"properties",
string_list(map_of(vec![
("type", text("string")),
("maxLength", Value::U64(5)),
("maxLength", Value::U64(50)),
])),
)]),
),
(
"an array's items",
"items",
"`properties.list`",
schema_of(vec![(
"properties",
platform_value!({
"list": map_of(vec![
("type", text("array")),
("position", Value::U64(0)),
("maxItems", Value::U64(4)),
("items", platform_value!({ "type": "string", "maxLength": 5 })),
("items", platform_value!({ "type": "integer" })),
])
}),
)]),
),
(
"a property of an index",
"a",
"`indices[0].properties[0]`",
index_on_a(platform_value!({
"name": "byA",
"properties": [map_of(vec![("a", text("asc")), ("a", text("desc"))])]
})),
),
];
for (case, key, place, schema) in cases {
let error =
parse(schema, true).expect_err(&format!("expected the repeat of {case} to be refused"));
assert_repeat_refused(error, key, place);
}

let schema = schema_of(vec![(
"properties",
platform_value!({ "a": { "$ref": "#/$defs/address", "position": 0 } }),
)]);
let street = |max_length: u64| platform_value!({ "street": { "type": "string", "maxLength": max_length, "position": 0 } });
let defs_cases: Vec<(&str, &str, &str, Value)> = vec![
(
"properties of a definition",
"properties",
"`$defs.address`",
map_of(vec![
("type", text("object")),
("properties", street(10)),
(
"properties",
platform_value!({ "street": { "type": "integer", "position": 0 } }),
),
("additionalProperties", Value::Bool(false)),
]),
),
(
"a key of a definition's property",
"maxLength",
"`$defs.address.properties.street`",
platform_value!({
"type": "object",
"properties": {
"street": map_of(vec![
("type", text("string")),
("maxLength", Value::U64(10)),
("position", Value::U64(0)),
("maxLength", Value::U64(20)),
])
},
"additionalProperties": false
}),
),
];
for (case, key, place, definition) in defs_cases {
let defs = BTreeMap::from([("address".to_string(), definition)]);
let error = parse_on(schema.clone(), Some(&defs), true, PlatformVersion::latest())
.expect_err(&format!("expected the repeat of {case} to be refused"));
assert_repeat_refused(error, key, place);
}
}
Loading
Loading