diff --git a/CHANGELOG.md b/CHANGELOG.md index 9af6978f9..dd6385883 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,9 +10,18 @@ This project does not adhere to [Semantic Versioning](https://semver.org/) and m - `idn-hostname` rejects a trailing label separator, such as `example.`, `example。` or `a..`. Released versions up to 3.0.9 accepted any number of them, so a fully-qualified name written with the root dot, such as `example.`, now fails; strip the trailing dot before validating such input. This follows the JSON-Schema-Test-Suite and matches `hostname`, which already rejects a trailing dot. - `uri-template` limits literals to the characters RFC 6570 section 2.1 allows. A space or a backslash (`a b`, `a\b`), C1 control characters, lone surrogates, noncharacters, U+FFF0 to U+FFFD and U+E0000 to U+E0FFF are now rejected in a literal; 3.0.9 and earlier accepted any character other than ASCII controls and ``" < > ^ ` { | }``. The apostrophe is still accepted, as in the JSON-Schema-Test-Suite. The vendored `uri-template.json` suite files are updated to the current JSON-Schema-Test-Suite. +- The value of an annotation is now the value the keyword holds, for every JSON value type. Boolean, array and null values used to be dropped, so a keyword whose value was a boolean, an array or `null` did not appear in the collected annotations at all. This applies to every annotation keyword, including the ones created for `readOnly` and `writeOnly`, for keywords that are not in the dialect, such as unknown keywords and root level fields, and for `deprecated`, `default`, `examples`, `example`, `xml` and `contentSchema`. [#1376](https://github.com/networknt/json-schema-validator/pull/1376) +- `RequiredValidator.getFieldKeyword` is now called for each required property and keyword on the first validation, whether or not a policy is enabled, and the result is cached; previously it ran only when a policy was enabled and the property was missing during validation. It is deprecated for removal. [#1376](https://github.com/networknt/json-schema-validator/pull/1376) +- The generic return type of `Annotation.getValue()` now has a wider set of values. Existing code such as `String s = annotation.getValue()` still compiles but now throws `ClassCastException` where the value is not a string; read the value as the type the keyword holds. An object, an array or a null is returned as a fresh copy of the schema node, so mutating it does not change the cached schema. A null value is reported as a `NullNode` rather than as the Java null that means there is no value. [#1376](https://github.com/networknt/json-schema-validator/pull/1376) + +### Added + +- `readOnly` and `writeOnly` are reported as annotations at the instance location they apply to when annotation collection is enabled. This is the keyword value in the schema; it has nothing to do with the `readOnly` and `writeOnly` execution config options. [#1376](https://github.com/networknt/json-schema-validator/pull/1376) +- `Annotation.isSchemaNodeAnnotation()` and `Annotation.Builder.schemaNodeAnnotation(boolean)` report whether an annotation is the raw value of its schema node rather than an applicator result. [#1376](https://github.com/networknt/json-schema-validator/pull/1376) ### Changed +- The `readOnly` and `writeOnly` execution policies no longer report an error when the keyword value is the boolean `false`, because the error contradicts the annotation reported for that value. This applies whether annotation collection is enabled or not. Every other value still reports the error, including `true` and a value that is not a boolean, so nothing that was accepted before is now rejected. [#1376](https://github.com/networknt/json-schema-validator/pull/1376) - `hostname` rejects names longer than 253 characters. - `hostname` checks a label that starts with `xn--`, in any case, as an A-label. It must be at most 63 characters of Punycode that encodes back to itself, and its U-label must pass the IDNA2008 rules listed below. `xn--X`, `xn--hello-txk` and `xn--1-0hc` (U-label `1א`, which breaks the RFC 5893 Bidi Rule) are now rejected; before, any LDH label passed. The Bidi Rule applies within each A-label only: the other labels stay RFC 1123 LDH labels, so `3com.xn--mgbaam7a8h` remains valid. - `idn-hostname` decodes A-labels with an RFC 3492 Punycode decoder instead of `java.net.IDN` (IDNA2003). A-labels with characters IDNA2008 allows in context, such as U+00DF, U+03C2, U+200C and U+200D, are accepted when the RFC 5892 rules allow them. A-labels are case-insensitive. @@ -31,10 +40,13 @@ This project does not adhere to [Semantic Versioning](https://semver.org/) and m - `idn-hostname` does not apply UTS 46 mapping. - Removed the unused `UnicodeDatabase.isGreek`, `isHebrew` and `isKatakana`, which tested code blocks rather than scripts. - Updated the vendored `hostname.json` and `idn-hostname.json` suite files to the current JSON-Schema-Test-Suite, including `draft-next`. Cases that need UTS 46 mapping are disabled with a reason. + ### Fixed - `uri-template` no longer throws `StackOverflowError` on long templates, such as a 5,000-character literal or an expression with a 1,000-character variable name. Runs of literal and variable-name characters are matched without recursion. +- Collecting annotations no longer changes the result of `unevaluatedItems` or `unevaluatedProperties` when an annotation keyword shares a name with an applicator the validator consumes. An annotation collected from a schema node now reports that it is not an applicator result, so an unknown keyword, a root field of a document container, a keyword a dialect registers as an `AnnotationKeyword`, or `readOnly`/`writeOnly` cannot mark items or properties as evaluated. [#1376](https://github.com/networknt/json-schema-validator/pull/1376) - Prevent descendant discriminator state from leaking between `oneOf` and `anyOf` branches in OpenAPI 3.0 and 3.1. [#1378](https://github.com/networknt/json-schema-validator/issues/1378) +- The `required` keyword no longer demands a `readOnly` or `writeOnly` property that the corresponding policy would assert for. It follows the policy rule, so a value that is not the boolean `false` exempts the property; a value that is not a boolean is no longer passed to `booleanValue()`, which threw `JsonNodeException`. Both policies are honoured when both are enabled. The exemption is decided from the keyword declared directly on the property schema in `properties`; a `readOnly` or `writeOnly` reached through `$ref` or `allOf` is not resolved into the property schema, so such a property is still required and still reports the policy error. The dialect is not consulted either: Draft 4 and 6 do not define `readOnly` or `writeOnly`, yet a property that declares one is still exempt from `required` there, which a test pins. [#1376](https://github.com/networknt/json-schema-validator/pull/1376) ## 3.0.9- 2026-11-03 diff --git a/README.md b/README.md index 8ac96c945..788357034 100644 --- a/README.md +++ b/README.md @@ -587,11 +587,13 @@ The following is sample output from the Hierarchical format. | `locale` | The locale to use for generating messages in `Error`. Note that this value is copied from `SchemaRegistryConfig` for each execution. | `Locale.getDefault()` | | `failFast` | Whether to return failure immediately when an assertion is generated. Note that this value is copied from `SchemaRegistryConfig` for each execution but is automatically set to `true` for the Boolean and Flag output formats. | `false` | | `formatAssertionsEnabled` | The default is to generate format assertions from Draft 4 to Draft 7 and to only generate annotations from Draft 2019-09. Setting to `true` or `false` will override the default behavior. | `null` | -| `readOnly` | Used to indicate that the property should not be sent as part of the request payload, but only in the response payload. This affects the `readOnly` keyword used for the OpenAPI dialect. | `null` | -| `writeOnly` | Used to indicate that the property should not be sent as part of the response payload, but only in the request payload. This affects the `writeOnly` keyword used for the OpenAPI dialect. | `null` | +| `readOnly` | Used to indicate that the property should not be sent as part of the request payload, but only in the response payload. See the note on the two policies below this table. | `null` | +| `writeOnly` | Used to indicate that the property should not be sent as part of the response payload, but only in the request payload. See the note on the two policies below this table. | `null` | | `maxEvaluationSteps` | Maximum admitted schema-entry and keyword-dispatch steps per validation or walk execution. Zero means unlimited; negative values are rejected. See [Validation execution limits](doc/validation-execution-limits.md). | `0` | | `maxEvaluationDepth` | Maximum simultaneously active schema evaluation frames, including the root, references, and schema wrappers. Zero means unlimited; negative values are rejected. | `0` | +**The `readOnly` and `writeOnly` policies.** Both apply to the keyword in Draft 7 and later, including the OpenAPI 3.0 and 3.1 dialects. When a policy is `true`, the keyword reports an error unless its value is the boolean `false`. A property whose keyword the policy asserts for (any value but the boolean `false`) is also exempt from `required`, whether or not the dialect defines the keyword, but only a declaration directly on the property schema is seen, not one reached through `$ref` or `allOf`. + ### Schema Registry Configuration | Name | Description | Default Value | diff --git a/doc/error-reference.md b/doc/error-reference.md index 0c4eadae8..d8aee05d0 100644 --- a/doc/error-reference.md +++ b/doc/error-reference.md @@ -115,8 +115,8 @@ The built-in formats have their own key: `format.date`, `format.date-time`, `for | `dependentRequired` | `dependentRequired` | A property is present but a property it depends on is missing. Draft 2019-09 and later. | `{0}` the missing property, `{1}` the property that is present | `property` | `has a missing property '{0}' which is dependent required because '{1}' is present` | | `dependencies` | `dependencies` | A property is present but a property listed for it in `dependencies` is missing. Draft 7 and earlier. | `{0}` the list of dependencies | `property` | `has an error with dependencies {0}` | | `notAllowed` | `notAllowed` | A property listed in `notAllowed` is present. Only in dialects that add `notAllowed`. | `{0}` the property name | `property` | `property '{0}' is not allowed but it is in the data` | -| `readOnly` | `readOnly` | A `readOnly` value is present and the execution config sets `readOnly(true)`. | none | | `is a readonly field, it cannot be changed` | -| `writeOnly` | `writeOnly` | A `writeOnly` value is present and the execution config sets `writeOnly(true)`. | none | | `is a write-only field, it cannot appear in the data` | +| `readOnly` | `readOnly` | A `readOnly` value is present, the value is not the boolean `false`, and the execution config sets `readOnly(true)`. | none | | `is a readonly field, it cannot be changed` | +| `writeOnly` | `writeOnly` | A `writeOnly` value is present, the value is not the boolean `false`, and the execution config sets `writeOnly(true)`. | none | | `is a write-only field, it cannot appear in the data` | ### Combining schemas diff --git a/src/main/java/com/networknt/schema/ExecutionConfig.java b/src/main/java/com/networknt/schema/ExecutionConfig.java index c62a994e9..890aa2d0c 100644 --- a/src/main/java/com/networknt/schema/ExecutionConfig.java +++ b/src/main/java/com/networknt/schema/ExecutionConfig.java @@ -206,18 +206,24 @@ public Predicate getAnnotationCollectionFilter() { } /** - * Returns the value of the read only flag. + * Returns the read only policy. + *

+ * See {@link BuilderSupport#readOnly(Boolean)} for what the policy does. * * @return the value of read only flag or null if not set + * @see BuilderSupport#readOnly(Boolean) */ public Boolean getReadOnly() { return this.readOnly; } /** - * Returns the value of the write only flag. + * Returns the write only policy. + *

+ * See {@link BuilderSupport#writeOnly(Boolean)} for what the policy does. * * @return the value of the write only flag or null if not set + * @see BuilderSupport#writeOnly(Boolean) */ public Boolean getWriteOnly() { return this.writeOnly; @@ -254,6 +260,14 @@ protected Builder self() { /** * Builder for {@link ExecutionConfig}. + *

+ * The {@code readOnly} and {@code writeOnly} policies apply to the keyword in + * Draft 7 and later, including the OpenAPI 3.0 and 3.1 dialects. When a policy is + * true, the keyword reports an error unless its value is the boolean false. A + * property whose keyword the policy asserts for (any value but the boolean false) + * is also exempt from required, whether or not the dialect defines the keyword, + * although only a declaration directly on the property schema is seen, not one + * reached through $ref or allOf. */ public static abstract class BuilderSupport { protected Locale locale = Locale.ROOT; @@ -336,11 +350,25 @@ public T failFast(boolean failFast) { return self(); } + /** + * Sets the read only policy. See {@link BuilderSupport} for what the policy does. + * + * @param readOnly the read only policy, null clears it so that the getter returns + * null + * @return the builder + */ public T readOnly(Boolean readOnly) { this.readOnly = readOnly; return self(); } + /** + * Sets the write only policy. See {@link BuilderSupport} for what the policy does. + * + * @param writeOnly the write only policy, null clears it so that the getter + * returns null + * @return the builder + */ public T writeOnly(Boolean writeOnly) { this.writeOnly = writeOnly; return self(); diff --git a/src/main/java/com/networknt/schema/annotation/Annotation.java b/src/main/java/com/networknt/schema/annotation/Annotation.java index 7d59579d0..621f22f4d 100644 --- a/src/main/java/com/networknt/schema/annotation/Annotation.java +++ b/src/main/java/com/networknt/schema/annotation/Annotation.java @@ -15,8 +15,10 @@ */ package com.networknt.schema.annotation; +import java.util.IdentityHashMap; import java.util.Objects; +import tools.jackson.databind.JsonNode; import com.networknt.schema.SchemaLocation; import com.networknt.schema.keyword.Keyword; import com.networknt.schema.path.NodePath; @@ -30,16 +32,23 @@ public class Annotation { private final SchemaLocation schemaLocation; private final NodePath evaluationPath; private final Object value; + private final boolean schemaNodeAnnotation; private boolean valid = true; // If not valid it means dropped public Annotation(String keyword, NodePath instanceLocation, SchemaLocation schemaLocation, NodePath evaluationPath, Object value) { + this(keyword, instanceLocation, schemaLocation, evaluationPath, value, false); + } + + private Annotation(String keyword, NodePath instanceLocation, SchemaLocation schemaLocation, + NodePath evaluationPath, Object value, boolean schemaNodeAnnotation) { super(); this.keyword = keyword; this.instanceLocation = instanceLocation; this.schemaLocation = schemaLocation; this.evaluationPath = evaluationPath; this.value = value; + this.schemaNodeAnnotation = schemaNodeAnnotation; } /** @@ -51,6 +60,26 @@ public String getKeyword() { return keyword; } + /** + * Whether the annotation reports the raw value of its schema node rather than the + * result of applying an applicator to the instance. + *

+ * This is true for every annotation produced by + * {@code AbstractKeywordValidator.putSchemaNodeAnnotation}: the annotation keywords, + * including an unknown keyword, a root field of a document container and a keyword a + * dialect registers as an {@code AnnotationKeyword}, and {@code readOnly} and + * {@code writeOnly}. Such a keyword may have the same name as a keyword an applicator + * consumes in another dialect, for example {@code items}, {@code contains}, + * {@code properties} or {@code unevaluatedProperties}. The applicator validators must + * ignore these annotations, or collecting annotations would change the validation + * result. + * + * @return whether the annotation reports a schema node value + */ + public boolean isSchemaNodeAnnotation() { + return schemaNodeAnnotation; + } + /** * The instance location to which it is attached, as a JSON Pointer. * @@ -81,13 +110,59 @@ public NodePath getEvaluationPath() { } /** - * The attached value(s). - * + * The value the annotation reports, which is not always the keyword's JSON value. + *

+ * For a keyword whose annotation is collected from its schema node (the + * annotation keywords and readOnly/writeOnly), the value is that node's value as + * the Java type that matches the JSON type: a string, a number and a boolean are + * unwrapped to {@link String}, {@link Number} and {@link Boolean}, and an object, + * an array and a JSON null are reported as a copy of the schema node. A JSON null + * is therefore a node whose {@code isNull()} is true, not the Java null that means + * that the annotation has no value. + *

+ * Other keywords report the value their own validator computes, which has the type + * that validator documents and need not be the keyword's JSON value. In particular + * {@code properties}, {@code patternProperties} and {@code additionalProperties} + * report a {@link java.util.Set} of the matched property names; + * {@code prefixItems} and {@code items} report {@code true} or, when the instance + * array is longer than the tuple, the number of tuple schemas that were applied as + * an {@link Integer}; {@code contains} reports {@code true} or a + * {@link java.util.List} of the matched indexes as {@link Integer}; and + * {@code format} reports its computed value. In Draft 7, + * {@code contentEncoding} and {@code contentMediaType} report the raw schema + * string; in 2019-09 and 2020-12, {@code contentEncoding} is an annotation + * keyword, so it reports the schema node and is marked as such. The value of such + * a keyword must not be read as its schema node. + * * @param the value type * @return the value */ @SuppressWarnings("unchecked") public T getValue() { + return (T) getValue(new IdentityHashMap<>()); + } + + /** + * The value the annotation reports, sharing one copy of each distinct container + * schema node through {@code copies}. + *

+ * This is intended for output formatters that attach the same schema-node + * annotation at many instance locations. Without the shared cache every output + * unit would retain its own deep copy of the schema node. The caller must not + * mutate the returned value. + * + * @param the value type + * @param copies identity-keyed cache of copies of the stored schema nodes + * @return the value + */ + @SuppressWarnings("unchecked") + public T getValue(IdentityHashMap copies) { + if (schemaNodeAnnotation && value instanceof JsonNode) { + JsonNode node = (JsonNode) value; + if (node.isObject() || node.isArray() || node.isNull()) { + return (T) copies.computeIfAbsent(node, n -> ((JsonNode) n).deepCopy()); + } + } return (T) value; } @@ -102,7 +177,8 @@ public void setValid(boolean valid) { @Override public String toString() { return "Annotation [evaluationPath=" + evaluationPath + ", schemaLocation=" + schemaLocation - + ", instanceLocation=" + instanceLocation + ", keyword=" + keyword + ", value=" + value + "]"; + + ", instanceLocation=" + instanceLocation + ", keyword=" + keyword + ", value=" + value + + ", schemaNodeAnnotation=" + schemaNodeAnnotation + "]"; } @Override @@ -119,6 +195,9 @@ public boolean equals(Object obj) { if (getClass() != obj.getClass()) return false; Annotation other = (Annotation) obj; + // schemaNodeAnnotation records where the value came from, not which annotation + // this is: two annotations with the same keyword and locations report the same + // thing regardless of that flag. return Objects.equals(evaluationPath, other.evaluationPath) && Objects.equals(instanceLocation, other.instanceLocation) && Objects.equals(keyword, other.keyword) && Objects.equals(schemaLocation, other.schemaLocation) && Objects.equals(value, other.value); @@ -134,6 +213,7 @@ public static class Builder { private SchemaLocation schemaLocation; private NodePath evaluationPath; private Object value; + private boolean schemaNodeAnnotation; public Builder keyword(Keyword keyword) { this.keyword = keyword.getValue(); @@ -165,8 +245,19 @@ public Builder value(Object value) { return this; } + /** + * Marks that the annotation reports the raw value of its schema node. + * + * @param schemaNodeAnnotation whether the annotation reports a schema node value + * @return the builder + */ + public Builder schemaNodeAnnotation(boolean schemaNodeAnnotation) { + this.schemaNodeAnnotation = schemaNodeAnnotation; + return this; + } + public Annotation build() { - return new Annotation(keyword, instanceLocation, schemaLocation, evaluationPath, value); + return new Annotation(keyword, instanceLocation, schemaLocation, evaluationPath, value, schemaNodeAnnotation); } } diff --git a/src/main/java/com/networknt/schema/keyword/AbstractKeywordValidator.java b/src/main/java/com/networknt/schema/keyword/AbstractKeywordValidator.java index 67fe16269..d3a988408 100644 --- a/src/main/java/com/networknt/schema/keyword/AbstractKeywordValidator.java +++ b/src/main/java/com/networknt/schema/keyword/AbstractKeywordValidator.java @@ -24,6 +24,7 @@ import com.networknt.schema.Schema; import com.networknt.schema.SchemaLocation; import com.networknt.schema.annotation.Annotation; +import com.networknt.schema.path.NodePath; /** * Abstract {@link KeywordValidator}. @@ -114,8 +115,64 @@ protected void putAnnotation(ExecutionContext executionContext, Consumer + * This is shared by the keywords that only contribute an annotation, and by the + * keywords that assert in addition to being an annotation. No applicator reports + * its evaluation result through this method, so consumers of an applicator's + * annotation, such as {@code unevaluatedItems} and {@code unevaluatedProperties}, + * must ignore the annotations this method produces. + * + * @param executionContext the execution context + * @param instanceLocation the instance location + */ + protected void putSchemaNodeAnnotation(ExecutionContext executionContext, NodePath instanceLocation) { + if (collectAnnotations(executionContext)) { + Object value = getAnnotationValue(this.schemaNode); + if (value != null) { + putAnnotation(executionContext, annotation -> annotation.instanceLocation(instanceLocation).value(value) + .schemaNodeAnnotation(true)); + } + } + } + + /** + * Gets the value to report as an annotation from the schema node of a keyword. + *

+ * The keywords that contribute an annotation do not all use the same value type. + * The meta-data, content and OpenAPI vocabularies use strings, numbers, booleans, + * arrays and objects, and a meta-data keyword can also be null, so every JSON value + * type is mapped. Strings, numbers and booleans are unwrapped to their Java type. + * An object, an array or null is stored as the schema's own node rather than + * copied for every annotation: a copy for every annotation retains memory + * proportional to the number of annotated instance locations times the size of + * the node, which reaches hundreds of megabytes on a large array with a large + * object default, and a single copy shared by every annotation is mutated by the + * first caller and seen by all of them. {@code Annotation.getValue()} returns a + * fresh copy of a container or null value instead. + *

+ * The returned null in this method means that there is no value to report, which + * is different from an annotation whose value is the JSON null. + * + * @param schemaNode the schema node of the keyword + * @return the annotation value, or null if there is no value to report + */ + private static Object getAnnotationValue(JsonNode schemaNode) { + if (schemaNode.isString()) { + return schemaNode.asString(); + } else if (schemaNode.isNumber()) { + return schemaNode.numberValue(); + } else if (schemaNode.isBoolean()) { + return schemaNode.booleanValue(); + } else if (schemaNode.isObject() || schemaNode.isArray() || schemaNode.isNull()) { + return schemaNode; + } + return null; + } + /** * Determines if the keyword exists adjacent in the evaluation path. *

diff --git a/src/main/java/com/networknt/schema/keyword/AnnotationKeyword.java b/src/main/java/com/networknt/schema/keyword/AnnotationKeyword.java index 5c1d43fc0..995019b56 100644 --- a/src/main/java/com/networknt/schema/keyword/AnnotationKeyword.java +++ b/src/main/java/com/networknt/schema/keyword/AnnotationKeyword.java @@ -36,24 +36,7 @@ public Validator(SchemaLocation schemaLocation, JsonNode schemaNode, @Override public void validate(ExecutionContext executionContext, JsonNode node, JsonNode rootNode, NodePath instanceLocation) { - if (collectAnnotations(executionContext)) { - Object value = getAnnotationValue(getSchemaNode()); - if (value != null) { - putAnnotation(executionContext, - annotation -> annotation.instanceLocation(instanceLocation).value(value)); - } - } - } - - private Object getAnnotationValue(JsonNode schemaNode) { - if (schemaNode.isString()) { - return schemaNode.asString(); - } else if (schemaNode.isNumber()) { - return schemaNode.numberValue(); - } else if (schemaNode.isObject()) { - return schemaNode; - } - return null; + putSchemaNodeAnnotation(executionContext, instanceLocation); } } diff --git a/src/main/java/com/networknt/schema/keyword/ReadOnlyValidator.java b/src/main/java/com/networknt/schema/keyword/ReadOnlyValidator.java index 351c2177c..b388ba9ee 100644 --- a/src/main/java/com/networknt/schema/keyword/ReadOnlyValidator.java +++ b/src/main/java/com/networknt/schema/keyword/ReadOnlyValidator.java @@ -39,13 +39,13 @@ public ReadOnlyValidator(SchemaLocation schemaLocation, JsonNode schemaNode, Sch @Override public void validate(ExecutionContext executionContext, JsonNode node, JsonNode rootNode, NodePath instanceLocation) { - - if (Boolean.TRUE.equals(executionContext.getExecutionConfig().getReadOnly())) { + Boolean readOnly = executionContext.getExecutionConfig().getReadOnly(); + if (ReadOnlyWriteOnlyPolicy.asserts(readOnly, this.schemaNode)) { executionContext.addError(error().instanceNode(node).instanceLocation(instanceLocation) - .evaluationPath(executionContext.getEvaluationPath()).locale(executionContext.getExecutionConfig().getLocale()) - .build()); + .evaluationPath(executionContext.getEvaluationPath()) + .locale(executionContext.getExecutionConfig().getLocale()).build()); } - return; + putSchemaNodeAnnotation(executionContext, instanceLocation); } } \ No newline at end of file diff --git a/src/main/java/com/networknt/schema/keyword/ReadOnlyWriteOnlyPolicy.java b/src/main/java/com/networknt/schema/keyword/ReadOnlyWriteOnlyPolicy.java new file mode 100644 index 000000000..6b27f4827 --- /dev/null +++ b/src/main/java/com/networknt/schema/keyword/ReadOnlyWriteOnlyPolicy.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2026 Network New Technologies Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.networknt.schema.keyword; + +import tools.jackson.databind.JsonNode; + +/** + * The readOnly and writeOnly execution policies, which turn those annotation + * keywords into assertions. + */ +final class ReadOnlyWriteOnlyPolicy { + private ReadOnlyWriteOnlyPolicy() { + } + + /** + * Whether the execution policy is in force. + * + * @param policy the config value of the policy, true turns the keyword into an + * assertion + * @return whether the policy is in force + */ + static boolean enabled(Boolean policy) { + return Boolean.TRUE.equals(policy); + } + + /** + * Whether the policy asserts for the given value of the keyword. + *

+ * The policy asserts only when it is in force and the keyword does not hold the + * boolean false. The value of false is the only value that does not contradict + * the annotation that is reported for the keyword, so it is the only value that + * does not assert. Every other value asserts, including a value that is not a + * boolean, which is not a valid keyword value. + *

+ * The rule lives here rather than in either validator so that readOnly and + * writeOnly cannot drift apart, and the policy value is part of the predicate so + * that a caller cannot ask whether the keyword asserts while the policy is off. + * + * @param policy the config value of the policy + * @param schemaNode the schema node of the keyword, may be null + * @return whether the policy asserts + */ + static boolean asserts(Boolean policy, JsonNode schemaNode) { + return enabled(policy) && valueAsserts(schemaNode); + } + + /** + * Whether the keyword value asserts, independent of the policy. + * + * @param schemaNode the schema node of the keyword, may be null + * @return whether every value except the boolean false asserts + */ + private static boolean valueAsserts(JsonNode schemaNode) { + return schemaNode != null && !(schemaNode.isBoolean() && !schemaNode.booleanValue()); + } +} diff --git a/src/main/java/com/networknt/schema/keyword/RequiredValidator.java b/src/main/java/com/networknt/schema/keyword/RequiredValidator.java index 0b662a828..a785fc246 100644 --- a/src/main/java/com/networknt/schema/keyword/RequiredValidator.java +++ b/src/main/java/com/networknt/schema/keyword/RequiredValidator.java @@ -31,6 +31,16 @@ public class RequiredValidator extends BaseKeywordValidator implements KeywordValidator { private final List fieldNames; + /** + * The resolved keyword values, built on the first validation. + *

+ * They are not built in the constructor because {@link #getFieldKeyword} is an + * overridable hook: an override that resolves a reference needs the parent + * schema's validators, and those are not installed until the schema has been + * read. + */ + private volatile FieldKeywords fieldKeywords; + public RequiredValidator(SchemaLocation schemaLocation, JsonNode schemaNode, Schema parentSchema, SchemaContext schemaContext) { super(KeywordType.REQUIRED, schemaNode, schemaLocation, parentSchema, schemaContext); if (schemaNode.isArray()) { @@ -50,22 +60,20 @@ public void validate(ExecutionContext executionContext, JsonNode node, JsonNode return; } + FieldKeywords keywords = getFieldKeywords(); for (String fieldName : fieldNames) { JsonNode propertyNode = node.get(fieldName); if (propertyNode == null) { Boolean readOnly = executionContext.getExecutionConfig().getReadOnly(); Boolean writeOnly = executionContext.getExecutionConfig().getWriteOnly(); - if (Boolean.TRUE.equals(readOnly)) { - JsonNode readOnlyNode = getFieldKeyword(fieldName, "readOnly"); - if (readOnlyNode != null && readOnlyNode.booleanValue()) { - continue; - } - } else if(Boolean.TRUE.equals(writeOnly)) { - JsonNode writeOnlyNode = getFieldKeyword(fieldName, "writeOnly"); - if (writeOnlyNode != null && writeOnlyNode.booleanValue()) { - continue; - } + // Mirror the readOnly and writeOnly execution policies: each asserts for + // every value except the boolean false, so a property it would assert for + // must not be demanded here. The two are checked independently so that + // both are honoured when both policies are on. + if (ReadOnlyWriteOnlyPolicy.asserts(readOnly, keywords.readOnlyNodes.get(fieldName)) + || ReadOnlyWriteOnlyPolicy.asserts(writeOnly, keywords.writeOnlyNodes.get(fieldName))) { + continue; } /** * Note that for the required validation the instanceLocation does not contain the missing property @@ -79,6 +87,67 @@ public void validate(ExecutionContext executionContext, JsonNode node, JsonNode } } + /** + * Resolves the keyword value of each required property from its property schema. + *

+ * Only a declaration directly on the property schema is seen; {@code $ref} and + * {@code allOf} are not resolved into the property schema. A property that does not + * declare the keyword does not get an entry, so the map is empty when no required + * property declares it. + * + * @param keyword the readOnly or writeOnly keyword + * @return the keyword value by property name + */ + private Map resolveFieldKeywords(String keyword) { + Map keywordNodes = new HashMap<>(); + for (String fieldName : this.fieldNames) { + JsonNode keywordNode = getFieldKeyword(fieldName, keyword); + if (keywordNode != null) { + keywordNodes.put(fieldName, keywordNode); + } + } + return keywordNodes.isEmpty() ? Collections.emptyMap() : keywordNodes; + } + + /** + * Gets the resolved keyword values, building them on the first call. + *

+ * The double-checked lock keeps concurrent validations from resolving the maps + * more than once while publishing a fully initialized holder. + * + * @return the resolved keyword values + */ + private FieldKeywords getFieldKeywords() { + FieldKeywords keywords = this.fieldKeywords; + if (keywords == null) { + synchronized (this) { + keywords = this.fieldKeywords; + if (keywords == null) { + keywords = new FieldKeywords(resolveFieldKeywords("readOnly"), + resolveFieldKeywords("writeOnly")); + this.fieldKeywords = keywords; + } + } + } + return keywords; + } + + /** + * Gets the keyword value of a required property from its property schema. + *

+ * This is called for each required property and keyword on the first validation, + * whether or not a policy is enabled, and the result is cached so that later + * validations only do map lookups. An override may resolve a reference because + * the parent schema's validators are installed by then. + * + * @param fieldName the property name + * @param keyword the readOnly or writeOnly keyword + * @return the keyword value, or null when the property schema does not declare it + * @deprecated this hook is called for each required property and keyword on the + * first validation and its result is cached; it will be replaced by a + * lookup that cannot be overridden + */ + @Deprecated(since = "3.0.10", forRemoval = true) protected JsonNode getFieldKeyword(String fieldName, String keyword) { JsonNode propertiesNode = this.parentSchema.getSchemaNode().get("properties"); if (propertiesNode != null) { @@ -89,4 +158,14 @@ protected JsonNode getFieldKeyword(String fieldName, String keyword) { } return null; } + + private static final class FieldKeywords { + private final Map readOnlyNodes; + private final Map writeOnlyNodes; + + private FieldKeywords(Map readOnlyNodes, Map writeOnlyNodes) { + this.readOnlyNodes = readOnlyNodes; + this.writeOnlyNodes = writeOnlyNodes; + } + } } diff --git a/src/main/java/com/networknt/schema/keyword/UnevaluatedItemsValidator.java b/src/main/java/com/networknt/schema/keyword/UnevaluatedItemsValidator.java index 311125759..c85b7a7f0 100644 --- a/src/main/java/com/networknt/schema/keyword/UnevaluatedItemsValidator.java +++ b/src/main/java/com/networknt/schema/keyword/UnevaluatedItemsValidator.java @@ -75,6 +75,13 @@ public void validate(ExecutionContext executionContext, JsonNode node, JsonNode Predicate validEvaluationPathFilter = a -> a.isValid(); //Predicate validEvaluationPathFilter = a -> executionContext.getInstanceResults().isValid(instanceLocation, a.getEvaluationPath()); + // An annotation collected from a schema node may share a name with a keyword this + // validator consumes. It reports the raw schema value, not the evaluation result, so it + // must not count as an evaluated-items annotation or annotation collection would change + // the result. This covers unknown keywords, document-container root fields, keywords a + // dialect registers as annotation keywords, and readOnly/writeOnly. + Predicate schemaNodeAnnotationFilter = a -> !a.isSchemaNodeAnnotation(); + Predicate adjacentEvaluationPathFilter = a -> a.getEvaluationPath() .startsWith(executionContext.getEvaluationPath().getParent()); @@ -92,8 +99,8 @@ public void validate(ExecutionContext executionContext, JsonNode node, JsonNode } else { // Get all the "items" for the instanceLocation List items = instanceLocationAnnotations.stream() - .filter(a -> itemsKeyword.equals(a.getKeyword())).filter(adjacentEvaluationPathFilter) - .filter(validEvaluationPathFilter).collect(Collectors.toList()); + .filter(a -> itemsKeyword.equals(a.getKeyword())).filter(schemaNodeAnnotationFilter) + .filter(adjacentEvaluationPathFilter).filter(validEvaluationPathFilter).collect(Collectors.toList()); if (items.isEmpty()) { // The "items" wasn't applied meaning it is unevaluated if there is content valid = false; @@ -124,8 +131,8 @@ public void validate(ExecutionContext executionContext, JsonNode node, JsonNode // annotation value of true, then the combined result from these keywords is // also true. List additionalItems = instanceLocationAnnotations.stream() - .filter(a -> additionalItemsKeyword.equals(a.getKeyword())).filter(adjacentEvaluationPathFilter) - .filter(validEvaluationPathFilter).collect(Collectors.toList()); + .filter(a -> additionalItemsKeyword.equals(a.getKeyword())).filter(schemaNodeAnnotationFilter) + .filter(adjacentEvaluationPathFilter).filter(validEvaluationPathFilter).collect(Collectors.toList()); for (Annotation annotation : additionalItems) { if (annotation.getValue() instanceof Boolean && Boolean.TRUE.equals(annotation.getValue())) { // The annotation "additionalItems: true" @@ -137,8 +144,8 @@ public void validate(ExecutionContext executionContext, JsonNode node, JsonNode // Unevaluated // Check if there are any "unevaluatedItems" annotations List unevaluatedItems = instanceLocationAnnotations.stream() - .filter(a -> "unevaluatedItems".equals(a.getKeyword())).filter(adjacentEvaluationPathFilter) - .filter(validEvaluationPathFilter).collect(Collectors.toList()); + .filter(a -> "unevaluatedItems".equals(a.getKeyword())).filter(schemaNodeAnnotationFilter) + .filter(adjacentEvaluationPathFilter).filter(validEvaluationPathFilter).collect(Collectors.toList()); for (Annotation annotation : unevaluatedItems) { if (annotation.getValue() instanceof Boolean && Boolean.TRUE.equals(annotation.getValue())) { // The annotation "unevaluatedItems: true" @@ -151,8 +158,8 @@ public void validate(ExecutionContext executionContext, JsonNode node, JsonNode int currentErrors = executionContext.getErrors().size(); // Get all the "contains" for the instanceLocation List contains = instanceLocationAnnotations.stream() - .filter(a -> "contains".equals(a.getKeyword())).filter(adjacentEvaluationPathFilter) - .filter(validEvaluationPathFilter).collect(Collectors.toList()); + .filter(a -> "contains".equals(a.getKeyword())).filter(schemaNodeAnnotationFilter) + .filter(adjacentEvaluationPathFilter).filter(validEvaluationPathFilter).collect(Collectors.toList()); Set containsEvaluated = new HashSet<>(); boolean containsEvaluatedAll = false; diff --git a/src/main/java/com/networknt/schema/keyword/UnevaluatedPropertiesValidator.java b/src/main/java/com/networknt/schema/keyword/UnevaluatedPropertiesValidator.java index cc5deb766..a9c3d9ae0 100644 --- a/src/main/java/com/networknt/schema/keyword/UnevaluatedPropertiesValidator.java +++ b/src/main/java/com/networknt/schema/keyword/UnevaluatedPropertiesValidator.java @@ -59,6 +59,13 @@ public void validate(ExecutionContext executionContext, JsonNode node, JsonNode Predicate validEvaluationPathFilter = a -> a.isValid(); //Predicate validEvaluationPathFilter = a -> executionContext.getInstanceResults().isValid(instanceLocation, a.getEvaluationPath()); + // An annotation collected from a schema node may share a name with a keyword this + // validator consumes. It reports the raw schema value, not the evaluation result, so it + // must not count as an evaluated-properties annotation. This covers unknown keywords, + // document-container root fields, keywords a dialect registers as annotation keywords, + // and readOnly/writeOnly. + Predicate schemaNodeAnnotationFilter = a -> !a.isSchemaNodeAnnotation(); + Predicate adjacentEvaluationPathFilter = a -> a.getEvaluationPath() .startsWith(executionContext.getEvaluationPath().getParent()); @@ -69,7 +76,8 @@ public void validate(ExecutionContext executionContext, JsonNode node, JsonNode Set existingEvaluatedProperties = new LinkedHashSet<>(); // Get all the "properties" for the instanceLocation List properties = instanceLocationAnnotations.stream() - .filter(a -> "properties".equals(a.getKeyword())).filter(adjacentEvaluationPathFilter) + .filter(a -> "properties".equals(a.getKeyword())).filter(schemaNodeAnnotationFilter) + .filter(adjacentEvaluationPathFilter) .filter(validEvaluationPathFilter).collect(Collectors.toList()); for (Annotation annotation : properties) { if (annotation.getValue() instanceof Set) { @@ -80,7 +88,8 @@ public void validate(ExecutionContext executionContext, JsonNode node, JsonNode // Get all the "patternProperties" for the instanceLocation List patternProperties = instanceLocationAnnotations.stream() - .filter(a -> "patternProperties".equals(a.getKeyword())).filter(adjacentEvaluationPathFilter) + .filter(a -> "patternProperties".equals(a.getKeyword())).filter(schemaNodeAnnotationFilter) + .filter(adjacentEvaluationPathFilter) .filter(validEvaluationPathFilter).collect(Collectors.toList()); for (Annotation annotation : patternProperties) { if (annotation.getValue() instanceof Set) { @@ -91,7 +100,8 @@ public void validate(ExecutionContext executionContext, JsonNode node, JsonNode // Get all the "patternProperties" for the instanceLocation List additionalProperties = instanceLocationAnnotations.stream() - .filter(a -> "additionalProperties".equals(a.getKeyword())).filter(adjacentEvaluationPathFilter) + .filter(a -> "additionalProperties".equals(a.getKeyword())).filter(schemaNodeAnnotationFilter) + .filter(adjacentEvaluationPathFilter) .filter(validEvaluationPathFilter).collect(Collectors.toList()); for (Annotation annotation : additionalProperties) { if (annotation.getValue() instanceof Set) { @@ -102,7 +112,8 @@ public void validate(ExecutionContext executionContext, JsonNode node, JsonNode // Get all the "unevaluatedProperties" for the instanceLocation List unevaluatedProperties = instanceLocationAnnotations.stream() - .filter(a -> "unevaluatedProperties".equals(a.getKeyword())).filter(adjacentEvaluationPathFilter) + .filter(a -> "unevaluatedProperties".equals(a.getKeyword())).filter(schemaNodeAnnotationFilter) + .filter(adjacentEvaluationPathFilter) .filter(validEvaluationPathFilter).collect(Collectors.toList()); for (Annotation annotation : unevaluatedProperties) { if (annotation.getValue() instanceof Set) { diff --git a/src/main/java/com/networknt/schema/keyword/WriteOnlyValidator.java b/src/main/java/com/networknt/schema/keyword/WriteOnlyValidator.java index d9d634144..6608da105 100644 --- a/src/main/java/com/networknt/schema/keyword/WriteOnlyValidator.java +++ b/src/main/java/com/networknt/schema/keyword/WriteOnlyValidator.java @@ -23,12 +23,13 @@ public WriteOnlyValidator(SchemaLocation schemaLocation, JsonNode schemaNode, Sc @Override public void validate(ExecutionContext executionContext, JsonNode node, JsonNode rootNode, NodePath instanceLocation) { - - if (Boolean.TRUE.equals(executionContext.getExecutionConfig().getWriteOnly())) { + Boolean writeOnly = executionContext.getExecutionConfig().getWriteOnly(); + if (ReadOnlyWriteOnlyPolicy.asserts(writeOnly, this.schemaNode)) { executionContext.addError(error().instanceNode(node).instanceLocation(instanceLocation) - .evaluationPath(executionContext.getEvaluationPath()).locale(executionContext.getExecutionConfig().getLocale()) - .build()); - } + .evaluationPath(executionContext.getEvaluationPath()) + .locale(executionContext.getExecutionConfig().getLocale()).build()); + } + putSchemaNodeAnnotation(executionContext, instanceLocation); } } diff --git a/src/main/java/com/networknt/schema/output/OutputUnitData.java b/src/main/java/com/networknt/schema/output/OutputUnitData.java index b76e8ded4..75562e855 100644 --- a/src/main/java/com/networknt/schema/output/OutputUnitData.java +++ b/src/main/java/com/networknt/schema/output/OutputUnitData.java @@ -16,6 +16,7 @@ package com.networknt.schema.output; import java.util.ArrayList; +import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -64,6 +65,7 @@ public static OutputUnitData from(List validationErrors, ExecutionContext Map> errors = data.errors; Map> annotations = data.annotations; Map> droppedAnnotations = data.droppedAnnotations; + IdentityHashMap annotationValueCopies = new IdentityHashMap<>(); for (Error error : validationErrors) { SchemaLocation assertionSchemaLocation = new SchemaLocation(error.getSchemaLocation().getAbsoluteIri(), @@ -108,12 +110,12 @@ public static OutputUnitData from(List validationErrors, ExecutionContext // annotations Map annotationMap = annotations.computeIfAbsent(key, k -> new LinkedHashMap<>()); - annotationMap.put(annotation.getKeyword(), annotation.getValue()); + annotationMap.put(annotation.getKeyword(), annotation.getValue(annotationValueCopies)); } else { // dropped annotations Map droppedAnnotationMap = droppedAnnotations.computeIfAbsent(key, k -> new LinkedHashMap<>()); - droppedAnnotationMap.put(annotation.getKeyword(), annotation.getValue()); + droppedAnnotationMap.put(annotation.getKeyword(), annotation.getValue(annotationValueCopies)); } } } diff --git a/src/test/java/com/networknt/schema/AnnotationCapture.java b/src/test/java/com/networknt/schema/AnnotationCapture.java new file mode 100644 index 000000000..77653aad1 --- /dev/null +++ b/src/test/java/com/networknt/schema/AnnotationCapture.java @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2026 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.networknt.schema; + +import java.util.Collections; +import java.util.List; +import java.util.function.Consumer; + +import com.networknt.schema.annotation.Annotation; +import com.networknt.schema.path.NodePath; + +/** + * Collects annotations through the public API for the tests that assert on them. + *

+ * The readOnly and writeOnly tests and the annotation keyword tests both need to + * validate an instance and then inspect what was collected at an instance location. + * This holds the part that is the same for both: the validation callback that enables + * collection for every keyword, and the lookup of the annotation of a keyword. They + * build their schemas differently, so the schema is passed in. + */ +public final class AnnotationCapture { + private AnnotationCapture() { + } + + /** + * Enables annotation collection for every keyword on a configuration builder. + * + * @param builder the configuration builder + */ + public static void collectEverything(ExecutionConfig.Builder builder) { + builder.annotationCollectionEnabled(true).annotationCollectionFilter(keyword -> true); + } + + /** + * Validates an instance and captures the execution context, with annotation + * collection enabled for every keyword and the given configuration applied on + * top of that. + * + * @param schema the schema to validate against + * @param instanceText the instance + * @param config the configuration to apply, or null for collection only + * @return the execution context, which holds the collected annotations + */ + public static ExecutionContext validate(Schema schema, String instanceText, Consumer config) { + ExecutionContext[] holder = new ExecutionContext[1]; + schema.validate(instanceText, InputFormat.JSON, context -> { + context.executionConfig(builder -> { + collectEverything(builder); + if (config != null) { + config.accept(builder); + } + }); + holder[0] = context; + }); + return holder[0]; + } + + /** + * Gets the annotations collected at an instance location. + * + * @param executionContext the execution context + * @param instanceLocation the instance location + * @return the annotations, which is empty if there are none at that location + */ + public static List at(ExecutionContext executionContext, NodePath instanceLocation) { + return executionContext.getAnnotations().asMap().getOrDefault(instanceLocation, Collections.emptyList()); + } + + /** + * Gets the annotation collected for a keyword at an instance location. + * + * @param executionContext the execution context + * @param instanceLocation the instance location + * @param keyword the keyword + * @return the annotation + * @throws AssertionError if no annotation was collected for the keyword + */ + public static Annotation of(ExecutionContext executionContext, NodePath instanceLocation, String keyword) { + List annotations = at(executionContext, instanceLocation); + for (Annotation annotation : annotations) { + if (keyword.equals(annotation.getKeyword())) { + return annotation; + } + } + throw new AssertionError("No " + keyword + " annotation was collected: " + annotations); + } +} diff --git a/src/test/java/com/networknt/schema/AnnotationsTest.java b/src/test/java/com/networknt/schema/AnnotationsTest.java index e147ef12a..f9f891ff2 100644 --- a/src/test/java/com/networknt/schema/AnnotationsTest.java +++ b/src/test/java/com/networknt/schema/AnnotationsTest.java @@ -15,10 +15,16 @@ */ package com.networknt.schema; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.util.IdentityHashMap; + import org.junit.jupiter.api.Test; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; import com.networknt.schema.annotation.Annotation; import com.networknt.schema.annotation.Annotations; import com.networknt.schema.path.NodePath; @@ -37,4 +43,26 @@ void put() { annotations.put(annotation); assertTrue(annotations.asMap().get(annotation.getInstanceLocation()).contains(annotation)); } + + @Test + void computedJsonNodeValueIsNotCopied() throws Exception { + JsonNode value = new ObjectMapper().readTree("{\"a\":1}"); + Annotation annotation = new Annotation("custom", new NodePath(PathType.JSON_POINTER), + SchemaLocation.of(""), new NodePath(PathType.JSON_POINTER), value); + assertSame(value, annotation.getValue()); + } + + @Test + void schemaNodeValueIsCopiedOncePerDistinctNode() throws Exception { + JsonNode value = new ObjectMapper().readTree("{\"a\":1}"); + Annotation first = Annotation.builder().keyword("default").value(value).schemaNodeAnnotation(true).build(); + Annotation second = Annotation.builder().keyword("default").value(value).schemaNodeAnnotation(true).build(); + IdentityHashMap copies = new IdentityHashMap<>(); + + Object firstCopy = first.getValue(copies); + Object secondCopy = second.getValue(copies); + + assertNotSame(value, firstCopy); + assertSame(firstCopy, secondCopy); + } } diff --git a/src/test/java/com/networknt/schema/OutputUnitTest.java b/src/test/java/com/networknt/schema/OutputUnitTest.java index 33cab6a7a..358973f59 100644 --- a/src/test/java/com/networknt/schema/OutputUnitTest.java +++ b/src/test/java/com/networknt/schema/OutputUnitTest.java @@ -19,9 +19,11 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.HashMap; +import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; @@ -140,6 +142,34 @@ void annotationCollectionHierarchical2() throws JacksonException { assertEquals(expected, output); } + @Test + void annotationCollectionSharesContainerCopyAcrossOutputUnits() { + SchemaRegistry factory = SchemaRegistry.withDefaultDialect(SpecificationVersion.DRAFT_2020_12); + Schema schema = factory.getSchema("{\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"," + + "\"items\":{\"default\":{\"a\":1}}}"); + + OutputUnit outputUnit = schema.validate("[1,2]", InputFormat.JSON, OutputFormat.LIST, + executionConfiguration -> executionConfiguration.executionConfig(executionConfig -> executionConfig + .annotationCollectionEnabled(true).annotationCollectionFilter(keyword -> true))); + + List details = outputUnit.getDetails(); + Object first = null; + Object second = null; + for (OutputUnit detail : details) { + Object value = detail.getAnnotations().get("default"); + if (value != null) { + if (first == null) { + first = value; + } else if (second == null) { + second = value; + } + } + } + assertNotNull(first); + assertNotNull(second); + assertSame(first, second); + } + enum FormatInput { DATE_TIME("date-time"), DATE("date"), diff --git a/src/test/java/com/networknt/schema/ReadOnlyWriteOnlyAnnotationTest.java b/src/test/java/com/networknt/schema/ReadOnlyWriteOnlyAnnotationTest.java new file mode 100644 index 000000000..c436d8b26 --- /dev/null +++ b/src/test/java/com/networknt/schema/ReadOnlyWriteOnlyAnnotationTest.java @@ -0,0 +1,590 @@ +/* + * Copyright (c) 2026 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.networknt.schema; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.function.Consumer; +import java.util.stream.Stream; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; + +import tools.jackson.databind.JsonNode; +import com.networknt.schema.annotation.Annotation; +import com.networknt.schema.dialect.Dialect; +import com.networknt.schema.dialect.Dialects; +import com.networknt.schema.keyword.AbstractKeyword; +import com.networknt.schema.keyword.KeywordValidator; +import com.networknt.schema.keyword.RequiredValidator; +import com.networknt.schema.path.NodePath; +import com.networknt.schema.path.PathType; + +/** + * readOnly and writeOnly are annotations, with optional execution policies that + * turn them into assertions. + *

+ * The first cases are the "`readOnly` is an annotation" and "`writeOnly` is an + * annotation" cases from the JSON Schema annotation test suite, which is vendored + * at src/test/suite/annotations/tests/meta-data.json. Both are marked compatible + * with draft 7 and later, where the keywords are annotations by default. The rest + * of the class covers the readOnly(true)/writeOnly(true) policies, including the + * exemption from required, so the class is not limited to pure annotation behaviour. + *

+ * The value mapping that is shared with the other annotation keywords is tested + * in {@link com.networknt.schema.keyword.AnnotationKeywordTest}. + */ +class ReadOnlyWriteOnlyAnnotationTest { + + private static final String READ_ONLY = "readOnly"; + private static final String WRITE_ONLY = "writeOnly"; + private static final String READ_ONLY_MESSAGE = "is a readonly field, it cannot be changed"; + private static final String WRITE_ONLY_MESSAGE = "is a write-only field, it cannot appear in the data"; + private static final NodePath ROOT = new NodePath(PathType.JSON_POINTER); + private static final NodePath NESTED = ROOT.append("a"); + + @ParameterizedTest + @ValueSource(strings = { READ_ONLY, WRITE_ONLY }) + void keywordIsCollectedAsAnAnnotation(String keyword) { + assertRootAnnotation("{\"" + keyword + "\":true}", keyword, Boolean.TRUE); + } + + @ParameterizedTest + @ValueSource(strings = { READ_ONLY, WRITE_ONLY }) + void keywordFalseIsCollectedAsAnAnnotation(String keyword) { + assertRootAnnotation("{\"" + keyword + "\":false}", keyword, Boolean.FALSE); + } + + /** + * The values used by the cases in the annotation test suite. The two keywords + * are collected alongside the other meta-data keywords of the same schema. + */ + @Test + void allMetaDataKeywordValuesAreCollected() { + ExecutionContext executionContext = collect("42", + "{\"deprecated\":true,\"default\":false,\"examples\":[1],\"title\":\"t\"," + + "\"readOnly\":true,\"writeOnly\":false}", + SpecificationVersion.DRAFT_2020_12); + assertEquals(Boolean.TRUE, annotationOf(executionContext, "deprecated").getValue()); + assertEquals(Boolean.FALSE, annotationOf(executionContext, "default").getValue()); + assertEquals("t", annotationOf(executionContext, "title").getValue()); + assertInstanceOf(JsonNode.class, annotationOf(executionContext, "examples").getValue()); + assertEquals(Boolean.TRUE, annotationOf(executionContext, READ_ONLY).getValue()); + assertEquals(Boolean.FALSE, annotationOf(executionContext, WRITE_ONLY).getValue()); + } + + @ParameterizedTest + @ValueSource(strings = { READ_ONLY, WRITE_ONLY }) + void keywordIsAnAnnotationInDraft7(String keyword) { + assertRootAnnotation("{\"" + keyword + "\":true}", keyword, Boolean.TRUE, SpecificationVersion.DRAFT_7); + assertRootAnnotation("{\"" + keyword + "\":false}", keyword, Boolean.FALSE, SpecificationVersion.DRAFT_7); + } + + /** + * The annotation is attached to the instance location the keyword applies to, + * which is the property and not the document root. + */ + @ParameterizedTest + @ValueSource(strings = { READ_ONLY, WRITE_ONLY }) + void keywordIsAnAnnotationOfANestedProperty(String keyword) { + assertNestedAnnotation(keyword, "{\"properties\":{\"a\":{\"" + keyword + "\":true}}}"); + } + + /** + * Annotation collection is opt-in, so nothing is reported unless it is + * enabled, even when the filter would collect everything. + */ + @ParameterizedTest + @ValueSource(strings = { READ_ONLY, WRITE_ONLY }) + void keywordIsNotCollectedWhenCollectionIsDisabled(String keyword) { + assertTrue(rootAnnotations("{\"" + keyword + "\":true}", false, + SpecificationVersion.DRAFT_2020_12).isEmpty()); + } + + /** + * Enabling collection is not enough, the keyword still has to be accepted by + * the filter. This covers both a root level keyword and a nested one, to show + * that the filter is what stops it and not the instance location. + */ + @ParameterizedTest + @ValueSource(strings = { READ_ONLY, WRITE_ONLY }) + void keywordIsNotCollectedWhenItIsFilteredOut(String keyword) { + assertTrue(filteredOutAnnotations("{\"" + keyword + "\":true}", "42", ROOT).isEmpty()); + assertTrue(filteredOutAnnotations("{\"properties\":{\"a\":{\"" + keyword + "\":true}}}", "{\"a\":1}", + NESTED).isEmpty()); + } + + /** + * Annotating does not change validation, so a schema using these keywords + * still accepts everything when the readOnly and writeOnly execution + * policies are not in force. + */ + @Test + void readOnlyAndWriteOnlyStillDoNotAssert() { + assertTrue(validate("{\"readOnly\":true}", "42", e -> e.annotationCollectionEnabled(true)).isEmpty()); + assertTrue(validate("{\"writeOnly\":true}", "42", e -> e.annotationCollectionEnabled(true)).isEmpty()); + assertTrue(validate("{\"readOnly\":true}", null).isEmpty()); + assertTrue(validate("{\"readOnly\":false}", null).isEmpty()); + } + + /** + * The execution policies that make readOnly and writeOnly assert still work + * alongside the annotation, for both keywords. + */ + @Test + void readOnlyAndWriteOnlyPoliciesStillReportAnError() { + assertEquals(1, validate("{\"readOnly\":true}", e -> e.readOnly(true)).size()); + assertEquals(1, validate("{\"writeOnly\":true}", e -> e.writeOnly(true)).size()); + assertTrue(validate("{\"readOnly\":true}", e -> e.readOnly(false)).isEmpty()); + } + + /** + * A boolean false does not assert under the policy. The annotation that is + * collected in the same run is not dropped, because nothing failed. + */ + @ParameterizedTest + @ValueSource(strings = { READ_ONLY, WRITE_ONLY }) + void keywordFalseDoesNotAssertUnderItsPolicy(String keyword) { + assertFalseValueDoesNotAssert(keyword, + "{\"properties\":{\"a\":{\"" + keyword + "\":false}}}", policy(keyword)); + } + + /** + * A value that is not a boolean is not a valid readOnly or writeOnly value. + * It asserted before the annotation was collected, so it still asserts. + */ + @ParameterizedTest + @ValueSource(strings = { READ_ONLY, WRITE_ONLY }) + void keywordNonBooleanValueStillAssertsUnderItsPolicy(String keyword) { + assertNonBooleanValueAsserts("{\"properties\":{\"a\":{\"" + keyword + "\":\"true\"}}}", + message(keyword), policy(keyword)); + } + + /** + * A null value is not a boolean either, so it asserts as well. + */ + @Test + void nullKeywordValueStillAssertsUnderThePolicies() { + assertNonBooleanValueAsserts("{\"properties\":{\"a\":{\"readOnly\":null}}}", + READ_ONLY_MESSAGE, e -> e.readOnly(true)); + assertNonBooleanValueAsserts("{\"properties\":{\"a\":{\"writeOnly\":null}}}", + WRITE_ONLY_MESSAGE, e -> e.writeOnly(true)); + } + + /** + * A value that is not a boolean is still collected. It is reported as whatever + * JSON value it is, without inventing a boolean for it. + */ + @Test + void nonBooleanKeywordValueIsCollectedAsAnAnnotation() { + ExecutionContext readOnly = collect("{\"a\":1}", + "{\"properties\":{\"a\":{\"readOnly\":\"yes\"}}}", SpecificationVersion.DRAFT_2020_12); + assertEquals("yes", annotationOf(readOnly, NESTED, READ_ONLY).getValue()); + + ExecutionContext nullValue = collect("{\"a\":1}", + "{\"properties\":{\"a\":{\"readOnly\":null}}}", SpecificationVersion.DRAFT_2020_12); + Object value = annotationOf(nullValue, NESTED, READ_ONLY).getValue(); + assertInstanceOf(JsonNode.class, value); + assertTrue(((JsonNode) value).isNull()); + + ExecutionContext arrayValue = collect("{\"a\":1}", + "{\"properties\":{\"a\":{\"readOnly\":[true]}}}", SpecificationVersion.DRAFT_2020_12); + assertInstanceOf(JsonNode.class, annotationOf(arrayValue, NESTED, READ_ONLY).getValue()); + } + + /** + * The policy of both keywords applies to the OpenAPI dialects as well, where + * those keywords are part of the vocabulary rather than the meta-data ones: 3.0 + * registers them itself, and 3.1 registers the same keywords through its own + * dialect. + */ + @ParameterizedTest + @MethodSource("openApiDialects") + void readOnlyPolicyAppliesToTheOpenApiDialects(Dialect dialect) { + assertOpenApiPolicy(dialect, READ_ONLY, "{\"readOnly\":true}", 1); + assertOpenApiPolicy(dialect, READ_ONLY, "{\"readOnly\":false}", 0); + assertOpenApiPolicy(dialect, WRITE_ONLY, "{\"writeOnly\":true}", 1); + assertOpenApiPolicy(dialect, WRITE_ONLY, "{\"writeOnly\":false}", 0); + } + + static Stream openApiDialects() { + return Stream.of(Dialects.getOpenApi30(), Dialects.getOpenApi31()); + } + + /** + * The interaction with required, which is where the readOnly and writeOnly + * policies were introduced for: a property the policy would assert for is not + * reported as missing, and a false value stays required because the policy does + * not assert for it. + */ + @Test + void requiredInteractsWithTheReadOnlyPolicy() { + // required follows the policy: a true value exempts the property, a false + // value does not. + assertEquals(0, validateRequired("{\"readOnly\":true}", e -> e.readOnly(true)).size()); + assertEquals(1, validateRequired("{\"readOnly\":false}", e -> e.readOnly(true)).size()); + assertEquals(0, validateRequired("{\"writeOnly\":true}", e -> e.writeOnly(true)).size()); + assertEquals(1, validateRequired("{\"writeOnly\":false}", e -> e.writeOnly(true)).size()); + + // Without the policy both are required, whatever the keyword value is. + assertEquals(1, validateRequired("{\"readOnly\":true}", null).size()); + assertEquals(1, validateRequired("{\"readOnly\":false}", null).size()); + + // A value that is not the boolean false makes the property read only, the same + // way the policy asserts for it, so the property is not required. It must be + // exempted rather than passed to booleanValue(), which throws for these values. + assertEquals(0, validateRequired("{\"readOnly\":\"true\"}", e -> e.readOnly(true)).size()); + assertEquals(0, validateRequired("{\"writeOnly\":\"true\"}", e -> e.writeOnly(true)).size()); + assertEquals(0, validateRequired("{\"readOnly\":null}", e -> e.readOnly(true)).size()); + assertEquals(0, validateRequired("{\"readOnly\":[true]}", e -> e.readOnly(true)).size()); + assertEquals(0, validateRequired("{\"readOnly\":1}", e -> e.readOnly(true)).size()); + } + + /** + * The present instance of a non-boolean keyword value is asserted by the policy + * rather than reported as a missing property. The absent instance is covered by + * {@link #requiredInteractsWithTheReadOnlyPolicy()}. + */ + @Test + void requiredAndThePolicyAgreeOnANonBooleanValue() { + List present = validateRequiredWithInstance("{\"readOnly\":\"true\"}", "{\"a\":1}", + e -> e.readOnly(true)); + assertEquals(1, present.size(), present.toString()); + assertTrue(present.get(0).getMessage().contains("readonly"), present.toString()); + } + + /** + * Both policies are honoured when both are enabled, so a writeOnly property is + * exempt from required even though the readOnly policy is on as well. + */ + @Test + void requiredHonoursBothPoliciesWhenBothAreEnabled() { + Consumer both = e -> e.readOnly(true).writeOnly(true); + assertEquals(0, validateRequired("{\"readOnly\":true}", both).size()); + assertEquals(0, validateRequired("{\"writeOnly\":true}", both).size()); + assertEquals(1, validateRequired("{\"readOnly\":false}", both).size()); + assertEquals(1, validateRequired("{\"writeOnly\":false}", both).size()); + } + + /** + * Each policy only looks at its own keyword. With only the readOnly policy on, a + * property that declares writeOnly is still required, and the other way round. A + * mistake that let either enabled policy exempt on either keyword would pass every + * other assertion in this class. + */ + @Test + void requiredExemptsOnlyTheKeywordOfTheEnabledPolicy() { + assertEquals(1, validateRequired("{\"writeOnly\":true}", e -> e.readOnly(true)).size()); + assertEquals(1, validateRequired("{\"readOnly\":true}", e -> e.writeOnly(true)).size()); + assertEquals(0, validateRequired("{\"readOnly\":true}", e -> e.readOnly(true)).size()); + assertEquals(0, validateRequired("{\"writeOnly\":true}", e -> e.writeOnly(true)).size()); + } + + /** + * The exemption is decided from the keyword declared directly on the property + * schema, so a readOnly reached through $ref or allOf is not resolved into it. + * Such a property is still required and still reports the policy error; this + * pins the limit the CHANGELOG describes rather than leaving it implicit. + */ + @Test + void requiredOnlySeesAReadOnlyDeclaredOnThePropertySchema() { + String refSchema = "{\"type\":\"object\",\"required\":[\"a\"]," + + "\"properties\":{\"a\":{\"$ref\":\"#/$defs/R\"}}," + + "\"$defs\":{\"R\":{\"readOnly\":true}}}"; + assertEquals(1, validateSchema(refSchema, "{}", e -> e.readOnly(true)).size()); + + String allOfSchema = "{\"type\":\"object\",\"required\":[\"a\"]," + + "\"properties\":{\"a\":{\"allOf\":[{\"readOnly\":true}]}}}"; + assertEquals(1, validateSchema(allOfSchema, "{}", e -> e.readOnly(true)).size()); + } + + /** + * {@code getFieldKeyword} is called on the first validation, after the parent + * schema has installed its validators and the subclass is initialized. An + * override may therefore resolve a reference and read its own state. Calling it + * from the constructor would recurse through {@code getValidators()} or see an + * uninitialized field. + */ + @Test + void overridingGetFieldKeywordCanResolveRefsAndUseSubclassState() { + Dialect dialect = Dialect.builder(Dialects.getDraft202012()) + .keyword(new RefResolvingRequiredKeyword()).build(); + Schema schema = SchemaRegistry.withDialect(dialect).getSchema( + "{\"type\":\"object\",\"required\":[\"a\"],\"properties\":{\"a\":{\"readOnly\":true}}}", + InputFormat.JSON); + List errors = schema.validate("{}", InputFormat.JSON, + context -> context.executionConfig(config -> config.readOnly(true))); + assertEquals(0, errors.size(), errors.toString()); + } + + /** + * The dialect is not consulted: Draft 4 and 6 do not define readOnly or + * writeOnly, so no validator for either is registered there, yet a property that + * declares one is still exempt from required. This pins the narrowed behaviour + * the CHANGELOG describes instead of leaving it implicit. + */ + @Test + void requiredExemptsAKeywordThatTheDialectDoesNotDefine() { + for (SpecificationVersion version : new SpecificationVersion[] { + SpecificationVersion.DRAFT_4, SpecificationVersion.DRAFT_6 }) { + Schema schema = SchemaRegistry.withDefaultDialect(version).getSchema( + "{\"type\":\"object\",\"required\":[\"a\"],\"properties\":{\"a\":{\"readOnly\":true}}}", + InputFormat.JSON); + List errors = schema.validate("{}", InputFormat.JSON, context -> context + .executionConfig(config -> config.readOnly(true))); + assertEquals(0, errors.size(), version + ": " + errors); + } + } + + private List validateRequired(String propertySchema, Consumer config) { + return validateRequiredWithInstance(propertySchema, "{}", config); + } + + private List validateSchema(String schemaText, String instance, Consumer config) { + Schema schema = SchemaRegistry.withDefaultDialect(SpecificationVersion.DRAFT_2020_12) + .getSchema(schemaText, InputFormat.JSON); + return schema.validate(instance, InputFormat.JSON, context -> { + if (config != null) { + context.executionConfig(config); + } + }); + } + + private List validateRequiredWithInstance(String propertySchema, String instance, + Consumer config) { + Schema schema = SchemaRegistry.withDefaultDialect(SpecificationVersion.DRAFT_2020_12).getSchema( + "{\"type\":\"object\",\"required\":[\"a\"],\"properties\":{\"a\":" + propertySchema + "}}", + InputFormat.JSON); + return schema.validate(instance, InputFormat.JSON, context -> { + if (config != null) { + context.executionConfig(config); + } + }); + } + + private void assertOpenApiPolicy(Dialect dialect, String keyword, String schemaText, int expectedErrors) { + Schema schema = SchemaRegistry.withDialect(dialect).getSchema(schemaText, InputFormat.JSON); + List errors = schema.validate("42", InputFormat.JSON, context -> context + .executionConfig(config -> config.readOnly(true).writeOnly(true))); + assertEquals(expectedErrors, errors.size(), keyword + " " + dialect + " " + errors); + } + + /** + * The policy error and the annotation are reported by the same run. The + * annotation is collected first and then marked as dropped, because the schema + * that reported it failed. + */ + @ParameterizedTest + @ValueSource(strings = { READ_ONLY, WRITE_ONLY }) + void keywordPolicyErrorAndAnnotationAreBothReportedInTheSameRun(String keyword) { + assertPolicyErrorDropsAnnotation(keyword, "{\"properties\":{\"a\":{\"" + keyword + "\":true}}}", + message(keyword), policy(keyword)); + } + + private static Consumer policy(String keyword) { + return READ_ONLY.equals(keyword) ? e -> e.readOnly(true) : e -> e.writeOnly(true); + } + + private static String message(String keyword) { + return READ_ONLY.equals(keyword) ? READ_ONLY_MESSAGE : WRITE_ONLY_MESSAGE; + } + + private void assertFalseValueDoesNotAssert(String keyword, String schemaText, + Consumer policy) { + ExecutionContext[] holder = new ExecutionContext[1]; + List errors = validate(schema(SpecificationVersion.DRAFT_2020_12, schemaText), "{\"a\":1}", + e -> { + policy.accept(e); + AnnotationCapture.collectEverything(e); + }, holder); + assertTrue(errors.isEmpty(), errors.toString()); + + Annotation annotation = annotationOf(holder[0], NESTED, keyword); + assertEquals(Boolean.FALSE, annotation.getValue()); + assertEquals(NESTED, annotation.getInstanceLocation()); + assertEquals("#/properties/a/" + keyword, annotation.getSchemaLocation().toString()); + assertTrue(annotation.isValid()); + } + + private void assertNonBooleanValueAsserts(String schemaText, String expectedMessage, + Consumer policy) { + List errors = validate(schemaText, "{\"a\":1}", policy); + assertEquals(1, errors.size(), errors.toString()); + assertEquals(expectedMessage, errors.get(0).getMessage()); + assertEquals(NESTED, errors.get(0).getInstanceLocation()); + } + + private void assertPolicyErrorDropsAnnotation(String keyword, String schemaText, String expectedMessage, + Consumer policy) { + ExecutionContext[] holder = new ExecutionContext[1]; + List errors = validate(schema(SpecificationVersion.DRAFT_2020_12, schemaText), "{\"a\":1}", + e -> { + policy.accept(e); + AnnotationCapture.collectEverything(e); + }, holder); + + // The policy error is reported. + assertEquals(1, errors.size(), errors.toString()); + assertEquals(expectedMessage, errors.get(0).getMessage()); + assertEquals(NESTED, errors.get(0).getInstanceLocation()); + + // The annotation of the failed schema is collected as a dropped annotation. + Annotation annotation = annotationOf(holder[0], NESTED, keyword); + assertEquals(Boolean.TRUE, annotation.getValue()); + assertEquals(NESTED, annotation.getInstanceLocation()); + assertEquals("#/properties/a/" + keyword, annotation.getSchemaLocation().toString()); + assertFalse(annotation.isValid()); + } + + private void assertNestedAnnotation(String keyword, String schemaText) { + Annotation annotation = annotationOf( + collect("{\"a\":1}", schemaText, SpecificationVersion.DRAFT_2020_12), NESTED, keyword); + assertEquals(keyword, annotation.getKeyword()); + assertEquals(Boolean.TRUE, annotation.getValue()); + assertEquals("#/properties/a/" + keyword, annotation.getSchemaLocation().toString()); + assertEquals(NESTED, annotation.getInstanceLocation()); + assertTrue(annotation.isValid()); + } + + private void assertRootAnnotation(String schemaText, String keyword, Boolean expected) { + assertRootAnnotation(schemaText, keyword, expected, SpecificationVersion.DRAFT_2020_12); + } + + private void assertRootAnnotation(String schemaText, String keyword, Boolean expected, + SpecificationVersion specificationVersion) { + Annotation annotation = annotationOf( + collect("42", schemaText, specificationVersion), ROOT, keyword); + assertEquals(keyword, annotation.getKeyword()); + assertEquals(expected, annotation.getValue()); + assertEquals("#/" + keyword, annotation.getSchemaLocation().toString()); + assertEquals(ROOT, annotation.getInstanceLocation()); + assertTrue(annotation.isValid()); + } + + /** + * Validates the instance and returns the annotations collected at the instance + * location, with collection enabled but the filter rejecting every keyword. + */ + private List filteredOutAnnotations(String schemaText, String instanceText, + NodePath instanceLocation) { + ExecutionContext executionContext = collect(instanceText, schemaText, SpecificationVersion.DRAFT_2020_12, + e -> e.annotationCollectionFilter(keyword -> false)); + return AnnotationCapture.at(executionContext, instanceLocation); + } + + /** + * Validates the instance and returns the annotations collected at the root, with + * the filter accepting every keyword and collection controlled by the argument. + */ + private List rootAnnotations(String schemaText, boolean annotationCollectionEnabled, + SpecificationVersion specificationVersion) { + ExecutionContext executionContext = collect("42", schemaText, specificationVersion, + e -> e.annotationCollectionEnabled(annotationCollectionEnabled)); + return AnnotationCapture.at(executionContext, ROOT); + } + + /** + * Validates the instance and returns the execution context, with annotation + * collection enabled for every keyword and the given configuration applied on + * top of that. + */ + private ExecutionContext collect(String instanceText, String schemaText, + SpecificationVersion specificationVersion) { + return collect(instanceText, schemaText, specificationVersion, null); + } + + private ExecutionContext collect(String instanceText, String schemaText, + SpecificationVersion specificationVersion, Consumer config) { + return AnnotationCapture.validate(schema(specificationVersion, schemaText), instanceText, config); + } + + private Annotation annotationOf(ExecutionContext executionContext, String keyword) { + return annotationOf(executionContext, ROOT, keyword); + } + + private Annotation annotationOf(ExecutionContext executionContext, NodePath instanceLocation, String keyword) { + return AnnotationCapture.of(executionContext, instanceLocation, keyword); + } + + private List validate(String schemaText, Consumer config) { + return validate(schemaText, "42", config); + } + + private List validate(String schemaText, String instanceText, Consumer config) { + return validate(schema(SpecificationVersion.DRAFT_2020_12, schemaText), instanceText, config, + new ExecutionContext[1]); + } + + private List validate(Schema schema, String instanceText, Consumer config) { + return validate(schema, instanceText, config, new ExecutionContext[1]); + } + + private List validate(Schema schema, String instanceText, Consumer config, + ExecutionContext[] holder) { + return schema.validate(instanceText, InputFormat.JSON, context -> { + if (config != null) { + context.executionConfig(config); + } + holder[0] = context; + }); + } + + private Schema schema(SpecificationVersion specificationVersion, String schemaText) { + return SchemaRegistry.withDefaultDialect(specificationVersion).getSchema(schemaText, InputFormat.JSON); + } + + private static final class RefResolvingRequiredKeyword extends AbstractKeyword { + private RefResolvingRequiredKeyword() { + super("required"); + } + + @Override + public KeywordValidator newValidator(SchemaLocation schemaLocation, JsonNode schemaNode, + Schema parentSchema, SchemaContext schemaContext) { + return new RefResolvingRequiredValidator(schemaLocation, schemaNode, parentSchema, schemaContext); + } + } + + private static final class RefResolvingRequiredValidator extends RequiredValidator { + private boolean initialized; + + private RefResolvingRequiredValidator(SchemaLocation schemaLocation, JsonNode schemaNode, + Schema parentSchema, SchemaContext schemaContext) { + super(schemaLocation, schemaNode, parentSchema, schemaContext); + this.initialized = true; + } + + @Override + protected JsonNode getFieldKeyword(String fieldName, String keyword) { + // Resolving a reference needs the parent's validators; during the + // constructor this call would recurse into the RequiredValidator that is + // being constructed. + getParentSchema().getValidators(); + if (!this.initialized) { + throw new IllegalStateException("getFieldKeyword called from the constructor"); + } + return super.getFieldKeyword(fieldName, keyword); + } + } +} + diff --git a/src/test/java/com/networknt/schema/UnevaluatedItemsValidatorTest.java b/src/test/java/com/networknt/schema/UnevaluatedItemsValidatorTest.java index 159a2925d..054416de6 100644 --- a/src/test/java/com/networknt/schema/UnevaluatedItemsValidatorTest.java +++ b/src/test/java/com/networknt/schema/UnevaluatedItemsValidatorTest.java @@ -19,9 +19,18 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; +import java.util.Map; import java.util.stream.Collectors; +import java.util.stream.Stream; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import com.networknt.schema.dialect.Dialect; +import com.networknt.schema.dialect.Dialects; +import com.networknt.schema.keyword.AnnotationKeyword; /** * UnevaluatedItemsValidatorTest. @@ -78,4 +87,126 @@ void unevaluatedItemsSchema() { assertEquals("/2", assertions.get(1).getInstanceLocation().toString()); assertEquals("/unevaluatedItems/type", assertions.get(1).getEvaluationPath().toString()); } + + static Stream unknownKeywordThatSharesApplicatorName() { + String additionalItemsRoot = "{\r\n" + + " \"$schema\" : \"https://json-schema.org/draft/2019-09/schema\",\r\n" + + " \"$id\" : \"https://www.example.org/root-unknown-additional-items.json\",\r\n" + + " \"$ref\" : \"sub-2020-additional-items.json\",\r\n" + + " \"unevaluatedItems\" : false\r\n" + + "}"; + String additionalItemsSub = "{\r\n" + + " \"$schema\" : \"https://json-schema.org/draft/2020-12/schema\",\r\n" + + " \"$id\" : \"https://www.example.org/sub-2020-additional-items.json\",\r\n" + + " \"additionalItems\" : true\r\n" + + "}"; + String containsRoot = "{\r\n" + + " \"$schema\" : \"https://json-schema.org/draft/2020-12/schema\",\r\n" + + " \"$id\" : \"https://www.example.org/root-unknown-contains.json\",\r\n" + + " \"allOf\" : [ { \"$ref\" : \"sub-draft4-contains.json\" } ],\r\n" + + " \"unevaluatedItems\" : false\r\n" + + "}"; + String containsSub = "{\r\n" + + " \"$schema\" : \"http://json-schema.org/draft-04/schema#\",\r\n" + + " \"id\" : \"https://www.example.org/sub-draft4-contains.json\",\r\n" + + " \"contains\" : false\r\n" + + "}"; + return Stream.of( + Arguments.of("unknown additionalItems in a 2020-12 subschema", + "https://www.example.org/root-unknown-additional-items.json", + Map.of("https://www.example.org/root-unknown-additional-items.json", additionalItemsRoot, + "https://www.example.org/sub-2020-additional-items.json", additionalItemsSub), + "[1,2]"), + Arguments.of("unknown contains in a Draft 4 subschema", + "https://www.example.org/root-unknown-contains.json", + Map.of("https://www.example.org/root-unknown-contains.json", containsRoot, + "https://www.example.org/sub-draft4-contains.json", containsSub), + "[1,2]")); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("unknownKeywordThatSharesApplicatorName") + void annotationCollectionDoesNotChangeUnknownKeywordResult(String description, String rootIri, + Map schemas, String inputData) { + List withoutAnnotations = validateUnknownKeywordSchema(rootIri, schemas, inputData, false); + List withAnnotations = validateUnknownKeywordSchema(rootIri, schemas, inputData, true); + assertEquals(2, withoutAnnotations.size()); + assertEquals(withoutAnnotations, withAnnotations); + } + + static Stream documentContainerRootFieldThatSharesApplicatorName() { + String rootIri = "https://www.example.org/root-container-additional-items.json"; + String containerIri = "https://www.example.org/container-2020-additional-items.json"; + String root = "{\r\n" + + " \"$schema\" : \"https://json-schema.org/draft/2019-09/schema\",\r\n" + + " \"$id\" : \"" + rootIri + "\",\r\n" + + " \"allOf\" : [\r\n" + + " { \"$ref\" : \"container-2020-additional-items.json#/$defs/x\" },\r\n" + + " { \"$ref\" : \"container-2020-additional-items.json\" }\r\n" + + " ],\r\n" + + " \"unevaluatedItems\" : false\r\n" + + "}"; + String container = "{\r\n" + + " \"$schema\" : \"https://json-schema.org/draft/2020-12/schema\",\r\n" + + " \"$id\" : \"" + containerIri + "\",\r\n" + + " \"additionalItems\" : true,\r\n" + + " \"$defs\" : { \"x\" : {} }\r\n" + + "}"; + return Stream.of(Arguments.of("unknown additionalItems root field of a document container", rootIri, + Map.of(rootIri, root, containerIri, container), "[1,2]")); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("documentContainerRootFieldThatSharesApplicatorName") + void annotationCollectionDoesNotChangeDocumentContainerRootFieldResult(String description, String rootIri, + Map schemas, String inputData) { + List withoutAnnotations = validateUnknownKeywordSchema(rootIri, schemas, inputData, false); + List withAnnotations = validateUnknownKeywordSchema(rootIri, schemas, inputData, true); + assertEquals(2, withoutAnnotations.size()); + assertEquals(withoutAnnotations, withAnnotations); + } + + @Test + void annotationCollectionDoesNotChangeRegisteredAnnotationKeywordResult() { + String rootIri = "https://www.example.org/root-registered-additional-items.json"; + String subIri = "https://www.example.org/sub-registered-additional-items.json"; + String root = "{\r\n" + + " \"$schema\" : \"https://json-schema.org/draft/2019-09/schema\",\r\n" + + " \"$id\" : \"" + rootIri + "\",\r\n" + + " \"$ref\" : \"" + subIri + "\",\r\n" + + " \"unevaluatedItems\" : false\r\n" + + "}"; + String sub = "{\r\n" + + " \"$schema\" : \"https://json-schema.org/draft/2020-12/schema\",\r\n" + + " \"$id\" : \"" + subIri + "\",\r\n" + + " \"additionalItems\" : true\r\n" + + "}"; + Dialect custom = Dialect.builder(Dialects.getDraft202012()) + .keyword(new AnnotationKeyword("additionalItems")).build(); + SchemaRegistry schemaRegistry = SchemaRegistry.withDialects( + List.of(Dialects.getDraft201909(), custom), + builder -> builder.schemas(Map.of(rootIri, root, subIri, sub))); + List withoutAnnotations = validateUnknownKeywordSchema(schemaRegistry, rootIri, "[1,2]", false); + List withAnnotations = validateUnknownKeywordSchema(schemaRegistry, rootIri, "[1,2]", true); + assertEquals(2, withoutAnnotations.size()); + assertEquals(withoutAnnotations, withAnnotations); + } + + private List validateUnknownKeywordSchema(String rootIri, Map schemas, String inputData, + boolean collectAnnotations) { + SchemaRegistry schemaRegistry = SchemaRegistry.withDefaultDialect(SpecificationVersion.DRAFT_2019_09, + builder -> builder.schemas(schemas)); + return validateUnknownKeywordSchema(schemaRegistry, rootIri, inputData, collectAnnotations); + } + + private List validateUnknownKeywordSchema(SchemaRegistry schemaRegistry, String rootIri, String inputData, + boolean collectAnnotations) { + Schema schema = schemaRegistry.getSchema(SchemaLocation.of(rootIri)); + return schema.validate(inputData, InputFormat.JSON, + executionContext -> executionContext.executionConfig(config -> config + .annotationCollectionEnabled(collectAnnotations).annotationCollectionFilter(keyword -> true))) + .stream().map(error -> error.getKeyword() + "|" + error.getInstanceLocation() + "|" + + error.getEvaluationPath()) + .collect(Collectors.toList()); + } } diff --git a/src/test/java/com/networknt/schema/UnevaluatedPropertiesValidatorTest.java b/src/test/java/com/networknt/schema/UnevaluatedPropertiesValidatorTest.java index 25b4a59b8..797eebe61 100644 --- a/src/test/java/com/networknt/schema/UnevaluatedPropertiesValidatorTest.java +++ b/src/test/java/com/networknt/schema/UnevaluatedPropertiesValidatorTest.java @@ -19,6 +19,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -26,7 +27,14 @@ import org.junit.jupiter.api.Test; +import tools.jackson.databind.JsonNode; +import com.networknt.schema.dialect.Dialect; +import com.networknt.schema.dialect.Dialects; +import com.networknt.schema.keyword.AbstractKeyword; +import com.networknt.schema.keyword.AbstractKeywordValidator; +import com.networknt.schema.keyword.KeywordValidator; import com.networknt.schema.output.OutputUnit; +import com.networknt.schema.path.NodePath; /** * UnevaluatedPropertiesValidatorTest. @@ -238,4 +246,49 @@ void nestedRef() { }); assertTrue(outputUnit.isValid()); } + + @Test + void schemaNodeAnnotationNamedPropertiesDoesNotMarkPropertiesEvaluated() { + String schemaData = "{\r\n" + + " \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\r\n" + + " \"properties\": true,\r\n" + + " \"unevaluatedProperties\": false\r\n" + + "}"; + Dialect dialect = Dialect.builder(Dialects.getDraft202012()) + .keyword(new EvaluatedPropertiesAnnotationKeyword()).build(); + Schema schema = SchemaRegistry.withDialect(dialect).getSchema(schemaData); + List messages = schema.validate("{\"a\":1}", InputFormat.JSON, + executionContext -> executionContext.executionConfig(executionConfig -> executionConfig + .annotationCollectionEnabled(true).annotationCollectionFilter(keyword -> true))); + assertEquals(1, messages.size()); + assertEquals("unevaluatedProperties", messages.get(0).getKeyword()); + assertEquals("a", messages.get(0).getProperty()); + } + + /** + * Reports a {@code Set} under the name {@code properties}, but marks it as a + * schema-node annotation. This is the value type and keyword name that + * {@code unevaluatedProperties} consumes, so only the flag keeps it from counting + * as an evaluated-properties annotation. + */ + private static final class EvaluatedPropertiesAnnotationKeyword extends AbstractKeyword { + private EvaluatedPropertiesAnnotationKeyword() { + super("properties"); + } + + @Override + public KeywordValidator newValidator(SchemaLocation schemaLocation, JsonNode schemaNode, + Schema parentSchema, SchemaContext schemaContext) { + return new AbstractKeywordValidator(this, schemaNode, schemaLocation) { + @Override + public void validate(ExecutionContext executionContext, JsonNode node, JsonNode rootNode, + NodePath instanceLocation) { + if (collectAnnotations(executionContext)) { + putAnnotation(executionContext, annotation -> annotation.instanceLocation(instanceLocation) + .value(Collections.singleton("a")).schemaNodeAnnotation(true)); + } + } + }; + } + } } diff --git a/src/test/java/com/networknt/schema/keyword/AnnotationKeywordTest.java b/src/test/java/com/networknt/schema/keyword/AnnotationKeywordTest.java new file mode 100644 index 000000000..c0410e793 --- /dev/null +++ b/src/test/java/com/networknt/schema/keyword/AnnotationKeywordTest.java @@ -0,0 +1,224 @@ +/* + * Copyright (c) 2026 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.networknt.schema.keyword; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +import tools.jackson.databind.JsonNode; +import com.networknt.schema.AnnotationCapture; +import com.networknt.schema.ExecutionContext; +import com.networknt.schema.InputFormat; +import com.networknt.schema.Schema; +import com.networknt.schema.SchemaRegistry; +import com.networknt.schema.dialect.Dialect; +import com.networknt.schema.dialect.Dialects; +import com.networknt.schema.path.NodePath; +import com.networknt.schema.path.PathType; + +/** + * The value reported for the keywords that only contribute an annotation. + *

+ * The value mapping lives in the private helper of + * {@link AbstractKeywordValidator#putSchemaNodeAnnotation(ExecutionContext, NodePath)}, which + * every keyword that reports its schema node uses, including {@link ReadOnlyValidator} and + * {@link WriteOnlyValidator}; the execution policy itself lives in + * {@link ReadOnlyWriteOnlyPolicy}. The keywords that use the helper are spread over the + * meta-data, content and OpenAPI vocabularies, so the values are not all strings. The tests + * go through the public API, which is how the values reach the caller, and assert both the + * Java type and the node identity of the value. + */ +class AnnotationKeywordTest { + private static final NodePath ROOT = new NodePath(PathType.JSON_POINTER); + + @Test + void stringValueIsUnwrapped() { + assertEquals("t", value("{\"title\":\"t\"}", "title", Dialects.getDraft202012())); + } + + @Test + void numberValueIsUnwrapped() { + assertEquals(42, value("{\"default\":42}", "default", Dialects.getDraft202012())); + assertEquals(1.5, value("{\"default\":1.5}", "default", Dialects.getDraft202012())); + } + + /** + * A boolean value is unwrapped to the Java Boolean, for a plain annotation + * keyword such as deprecated and for readOnly, which is collected by the same + * mapping. + */ + @Test + void booleanValueIsUnwrapped() { + assertEquals(Boolean.TRUE, + value("{\"deprecated\":true,\"readOnly\":true}", "deprecated", Dialects.getDraft202012())); + assertEquals(Boolean.TRUE, + value("{\"deprecated\":true,\"readOnly\":true}", "readOnly", Dialects.getDraft202012())); + assertEquals(Boolean.FALSE, + value("{\"deprecated\":false,\"readOnly\":false}", "deprecated", Dialects.getDraft202012())); + } + + /** + * A meta-data keyword is allowed to be null. The value is the schema's own + * NullNode, which is not the Java null that means there is no value. + */ + @Test + void nullValueIsReportedAsTheNode() { + Object value = value("{\"default\":null}", "default", Dialects.getDraft202012()); + assertInstanceOf(JsonNode.class, value); + assertTrue(((JsonNode) value).isNull()); + } + + /** + * An array of examples is returned as a copy of the schema's node, so a caller + * can modify the value without modifying the cached schema. + */ + @Test + void arrayValueIsReturnedAsACopyOfTheSchemaNode() { + Schema schema = schema(Dialects.getDraft202012(), "{\"examples\":[1,2]}"); + JsonNode reported = assertInstanceOf(JsonNode.class, value(schema, "examples")); + assertEquals(schema.getSchemaNode().get("examples"), reported); + assertNotSame(schema.getSchemaNode().get("examples"), reported); + } + + /** + * An object valued keyword such as an object default is returned as a copy of + * the schema's node as well. + */ + @Test + void objectValueIsReturnedAsACopyOfTheSchemaNode() { + Schema schema = schema(Dialects.getDraft202012(), "{\"default\":{\"a\":[1]}}"); + JsonNode reported = assertInstanceOf(JsonNode.class, value(schema, "default")); + assertEquals(schema.getSchemaNode().get("default"), reported); + assertNotSame(schema.getSchemaNode().get("default"), reported); + } + + /** + * contentSchema is an annotation keyword of the content vocabulary and is a + * schema, so its value may be a boolean. + */ + @Test + void booleanContentSchemaIsReported() { + assertEquals(Boolean.TRUE, + value("{\"contentSchema\":true}", "contentSchema", Dialects.getDraft202012())); + assertEquals(Boolean.FALSE, + value("{\"contentSchema\":false}", "contentSchema", Dialects.getDraft202012())); + } + + /** + * The Draft 4 keywords use the same mapping. exampleSetFlag is its + * boolean valued annotation keyword. + */ + @Test + void draft4AnnotationKeywordIsReported() { + assertEquals(Boolean.TRUE, + value("{\"exampleSetFlag\":true}", "exampleSetFlag", Dialects.getDraft4())); + assertEquals("t", value("{\"title\":\"t\"}", "title", Dialects.getDraft4())); + } + + /** + * The Draft 6 examples keyword is an array. + */ + @Test + void draft6ExamplesAreReported() { + Schema schema = schema(Dialects.getDraft6(), "{\"examples\":[1,2]}"); + assertEquals(schema.getSchemaNode().get("examples"), value(schema, "examples")); + } + + /** + * The OpenAPI 3.0 dialect adds its own annotation keywords, including a boolean + * and an object. + */ + @Test + void openApi30AnnotationKeywordsAreReported() { + Schema schema = schema(Dialects.getOpenApi30(), "{\"deprecated\":true,\"xml\":{\"name\":\"a\"}}"); + assertEquals(Boolean.TRUE, value(schema, "deprecated")); + assertEquals(schema.getSchemaNode().get("xml"), value(schema, "xml")); + } + + /** + * The OpenAPI 3.1 base vocabulary adds example, which may hold any value. + */ + @Test + void openApi31AnnotationKeywordIsReported() { + Schema schema = schema(Dialects.getOpenApi31(), "{\"example\":{\"a\":[1]}}"); + assertEquals(schema.getSchemaNode().get("example"), value(schema, "example")); + } + + /** + * An unknown keyword is an annotation keyword, so it reports its value the same + * way the keywords in a dialect do. The value of a keyword that is not in a + * vocabulary is not restricted to a string, which is the contract change that + * this mapping makes. + */ + @Test + void unknownKeywordValueIsReported() { + assertEquals("Foo", value("{\"x-unknownKeyword\":\"Foo\"}", "x-unknownKeyword", Dialects.getDraft202012())); + assertEquals(Boolean.TRUE, value("{\"x-unknownKeyword\":true}", "x-unknownKeyword", Dialects.getDraft202012())); + assertEquals(42, value("{\"x-unknownKeyword\":42}", "x-unknownKeyword", Dialects.getDraft202012())); + } + + /** + * The value that a caller receives is whatever the value of the keyword is, so + * code that reads it through the generic method of the annotation gets that type. + * This is the contract that the CHANGELOG describes; it is asserted through + * getValue() rather than by casting a local, because a cast would only test the + * compiler. + */ + @Test + void theTypeOfTheValueComesFromTheSchema() { + Schema schema = schema(Dialects.getDraft202012(), + "{\"x-boolean\":true,\"x-number\":42,\"x-string\":\"s\",\"x-object\":{\"a\":1}}"); + ExecutionContext executionContext = AnnotationCapture.validate(schema, "42", null); + + // The generic method returns the type of the value, which is what a caller of + // a known boolean or number valued annotation relies on. + Boolean booleanValue = AnnotationCapture.of(executionContext, ROOT, "x-boolean").getValue(); + assertEquals(Boolean.TRUE, booleanValue); + Number numberValue = AnnotationCapture.of(executionContext, ROOT, "x-number").getValue(); + assertEquals(42, numberValue.intValue()); + String stringValue = AnnotationCapture.of(executionContext, ROOT, "x-string").getValue(); + assertEquals("s", stringValue); + JsonNode objectValue = AnnotationCapture.of(executionContext, ROOT, "x-object").getValue(); + assertEquals(1, objectValue.get("a").intValue()); + + // An object or an array is stored as the schema's own node but returned as a + // fresh copy, so a caller cannot mutate the cached schema and the annotation + // itself does not retain a copy per annotated instance location. + assertNotSame(schema.getSchemaNode().get("x-object"), objectValue); + } + + /** + * Validates the instance against the schema and returns the value of the + * annotation that the keyword collected at the root. + */ + private Object value(String schemaText, String keyword, Dialect dialect) { + return value(schema(dialect, schemaText), keyword); + } + + private Object value(Schema schema, String keyword) { + ExecutionContext executionContext = AnnotationCapture.validate(schema, "42", null); + return AnnotationCapture.of(executionContext, ROOT, keyword).getValue(); + } + + private Schema schema(Dialect dialect, String schemaText) { + return SchemaRegistry.withDialect(dialect).getSchema(schemaText, InputFormat.JSON); + } +}