diff --git a/CHANGELOG.md b/CHANGELOG.md index d3b593e9e..8db704771 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,9 @@ This project does not adhere to [Semantic Versioning](https://semver.org/) and m ### Added ### Changed +- Ignore zero `multipleOf` divisors returned by custom validators, regardless of scale, matching the default conversion. (#1328) +- Display `multipleOf` divisors in error messages using plain notation when it fits within 32 characters or is no longer than `BigDecimal.toString()`, including values returned by custom validators. Check the length before expanding to plain notation to avoid excessive padding for extreme scales. (#1328) +- Ignore non-finite `multipleOf` divisors and dividends on 2.x, matching master's `multipleOf` behavior. This is a fail-open change: values such as `1e400` rounded to infinity by the default reader are now accepted by this constraint instead of causing an exception. A non-finite divisor disables the constraint for all instances; a non-finite dividend skips the check for that instance. Enable `DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS` to validate these decimal values exactly (see #1293). Other numeric keywords on 2.x retain their existing behavior. (#1328) - `MultipleOfValidator.getDivisor` and `getDividend` now preserve exact integral and BigDecimal values. Custom validators, including overrides calling `super`, receive these exact values; validation uses hook results without further rounding. Integral dividend scales can change (for example, `2.0` becomes `2`), which affects scale-sensitive comparisons in overrides. Mixed integral/Double or Float inputs above 2^53 can produce different results. Precision already lost when parsing floating-point values is tracked separately in #1293. (#1286) - Extend document-root unknown-keyword suppression to external `$ref` JSON Pointer targets. Keep container and direct-schema caches separate so direct registry loads retain normal diagnostics regardless of registry load order, including rejection by `DisallowUnknownKeywordFactory`. Within one schema, a whole-document reference following a JSON Pointer reference can still reuse the container and suppress root diagnostics, including strict-factory rejection. Apply the container annotation fallback after nullable/discriminator special handling and make the container marker volatile. (#1325) - Treat unknown document-root fields as annotations when loading a schema by JSON Pointer fragment, while preserving known keyword processing and diagnostics in subschemas. With `DisallowUnknownKeywordFactory`, such fragment loads now succeed instead of throwing on unknown root fields; direct document loads still throw. If the selected schema references the root with `$ref: "#"`, unknown root fields also remain annotations and do not reach the unknown-keyword factory. (#1205) diff --git a/src/main/java/com/networknt/schema/keyword/MultipleOfValidator.java b/src/main/java/com/networknt/schema/keyword/MultipleOfValidator.java index 730043074..d5cc9fb9c 100644 --- a/src/main/java/com/networknt/schema/keyword/MultipleOfValidator.java +++ b/src/main/java/com/networknt/schema/keyword/MultipleOfValidator.java @@ -31,6 +31,8 @@ * {@link KeywordValidator} for multipleOf. */ public class MultipleOfValidator extends BaseKeywordValidator implements KeywordValidator { + private static final int MAX_PLAIN_DIVISOR_LENGTH = 32; + private final BigDecimal divisor; private final BigInteger denominator; private final long longDivisor; @@ -39,10 +41,11 @@ public class MultipleOfValidator extends BaseKeywordValidator implements Keyword public MultipleOfValidator(SchemaLocation schemaLocation, JsonNode schemaNode, Schema parentSchema, SchemaContext schemaContext) { super(KeywordType.MULTIPLE_OF, schemaNode, schemaLocation, parentSchema, schemaContext); - this.divisor = getDivisor(schemaNode); + BigDecimal divisor = getDivisor(schemaNode); + this.divisor = divisor == null || divisor.signum() == 0 ? null : divisor; this.denominator = this.divisor == null ? null : this.divisor.unscaledValue().abs(); this.longDivisor = integralDivisor(this.divisor); - this.divisorMessage = this.divisor == null ? null : this.divisor.toString(); + this.divisorMessage = formatDivisorMessage(this.divisor); } public void validate(ExecutionContext executionContext, JsonNode node, JsonNode rootNode, @@ -72,6 +75,26 @@ public void validate(ExecutionContext executionContext, JsonNode node, JsonNode } } + private static String formatDivisorMessage(BigDecimal value) { + if (value == null) { + return null; + } + long precision = value.precision(); + long scale = value.scale(); + long length = scale <= 0 ? precision - scale : Math.max(precision + 1, scale + 2); + if (value.signum() < 0) { + length++; + } + if (length <= MAX_PLAIN_DIVISOR_LENGTH) { + return value.toPlainString(); + } + String text = value.toString(); + if (length > text.length()) { + return text; + } + return text.indexOf('E') < 0 ? text : value.toPlainString(); + } + private static long integralDivisor(BigDecimal value) { if (value == null) { return 0; @@ -128,12 +151,19 @@ private static boolean isMultipleOf(BigDecimal dividend, BigDecimal divisor, Big /** * Gets the divisor to use. The default implementation preserves exact values - * for integral and BigDecimal nodes. Double and Float nodes are converted with - * {@link BigDecimal#valueOf(double)} using their {@code doubleValue()}. + * for integral and BigDecimal nodes. Finite Double and Float nodes are converted + * with {@link BigDecimal#valueOf(double)} using their {@code doubleValue()}. + * Non-finite floating-point nodes return null, so this constraint is ignored + * for those inputs. * Validation uses the returned value without further rounding, including when * this method is overridden. + * A null or zero return value causes this constraint to be ignored, including + * when this method is overridden. * The default conversion removes trailing zeros unless doing so would overflow the scale. - * Error messages preserve the string representation of the returned value. + * Error messages use the returned value's plain notation when it fits within + * 32 characters or is no longer than its {@link BigDecimal#toString()} + * representation. Otherwise, that representation is used. + * This also applies to values returned by overrides. * * @param schemaNode the schema node * @return the divisor or null if the input is not correct @@ -145,7 +175,7 @@ protected BigDecimal getDivisor(JsonNode schemaNode) { return value.signum() == 0 ? null : normalizeDivisor(value); } double divisor = schemaNode.doubleValue(); - if (divisor != 0) { + if (divisor != 0 && Double.isFinite(divisor)) { // convert to BigDecimal since double type is not accurate enough to do the // division and multiple return BigDecimal.valueOf(divisor).stripTrailingZeros(); @@ -156,18 +186,23 @@ protected BigDecimal getDivisor(JsonNode schemaNode) { /** * Gets the dividend to use. The default implementation preserves exact values - * for integral and BigDecimal nodes. Double and Float nodes are converted with - * {@link BigDecimal#valueOf(double)} using their {@code doubleValue()}. + * for integral and BigDecimal nodes. Finite Double and Float nodes are converted + * with {@link BigDecimal#valueOf(double)} using their {@code doubleValue()}. + * Non-finite floating-point nodes return null, so this constraint is ignored + * for those inputs. * Validation uses the returned value without further rounding, including when * this method is overridden. * Integral inputs can have a different scale than with the former * double-based conversion, for example {@code 2} instead of {@code 2.0}. * * @param node the node - * @return the dividend or null if the type is incorrect + * @return the dividend or null if the type is incorrect or the floating-point value is non-finite */ protected BigDecimal getDividend(JsonNode node) { if (node.isNumber()) { + if (JsonNodeTypes.isNonFiniteNumber(node)) { + return null; + } // convert to BigDecimal since double type is not accurate enough to do the // division and multiple if (node.isIntegralNumber() || node.isBigDecimal()) { diff --git a/src/test/java/com/networknt/schema/MultipleOfValidatorTest.java b/src/test/java/com/networknt/schema/MultipleOfValidatorTest.java index 981a28be5..384cc3f3a 100644 --- a/src/test/java/com/networknt/schema/MultipleOfValidatorTest.java +++ b/src/test/java/com/networknt/schema/MultipleOfValidatorTest.java @@ -211,6 +211,8 @@ void mixedFloatNodesUseExactIntegralValues() { "1e-400, 1.5e-400, 1", "1e-400, 2e-400, 0", "1e400, 1, 1", + "3, 1e400, 1", + "3, -1e400, 1", "1e400, 2e400, 0", "2, 1e400, 0" }) @@ -249,6 +251,8 @@ void integersBeyondDoubleRange() { "1e-400, 1.5e-400, 1", "1e-400, 2e-400, 0", "1e400, 1, 1", + "3, 1e400, 1", + "3, -1e400, 1", "1e400, 2e400, 0" }) void exactDecimalsFromReader(String divisor, String dividend, int expectedErrors) { @@ -262,9 +266,11 @@ void exactDecimalsFromReader(String divisor, String dividend, int expectedErrors @ParameterizedTest @CsvSource({ - "100, 3, must be multiple of 1E+2", - "100.0, 3, must be multiple of 1E+2", - "100.00, 3, must be multiple of 1E+2", + "100, 3, must be multiple of 100", + "100.0, 3, must be multiple of 100", + "100.00, 3, must be multiple of 100", + "1000, 3, must be multiple of 1000", + "2.50E+3, 3, must be multiple of 2500", "2.0, 3, must be multiple of 2", "9007199254740993, 2, must be multiple of 9007199254740993" }) @@ -275,7 +281,7 @@ void exactDivisorMessage(String divisor, String dividend, String expectedMessage } @ParameterizedTest - @CsvSource({"2.0, 2", "100.00, 1E+2", "0.0000100, 0.00001", + @CsvSource({"2.0, 2", "100.00, 100", "0.0000100, 0.00001", "9007199254740993.0, 9007199254740993", "1e400, 1E+400"}) void exactDecimalDivisorMessage(String divisor, String expectedDivisor) { ObjectNode schemaNode = JsonNodeFactory.instance.objectNode(); @@ -304,8 +310,13 @@ protected BigDecimal getDivisor(JsonNode node) { } @ParameterizedTest - @ValueSource(strings = {"3.0", "100.00"}) - void overriddenDivisorRetainsMessageRepresentation(String value) { + @CsvSource({"3.0, 3.0", "100.00, 100.00", "1E+2, 100", "1E-7, 0.0000001", "1E+400, 1E+400", + "123456789012345678901234567890000, 123456789012345678901234567890000", + "1.2345678901234567890123456789E+32, 123456789012345678901234567890000", + "1.2345678901234567890123456789E+33, 1234567890123456789012345678900000", + "1.2345678901234567890123456789E+34, 1.2345678901234567890123456789E+34", + "1234567890123456789012345678901234, 1234567890123456789012345678901234"}) + void overriddenDivisorMessage(String value, String expectedDivisor) { Schema parent = SchemaRegistry.withDefaultDialect(SpecificationVersion.DRAFT_2020_12) .getSchema("{\"multipleOf\":2}"); MultipleOfValidator validator = new MultipleOfValidator(SchemaLocation.of("#/multipleOf"), @@ -316,11 +327,106 @@ protected BigDecimal getDivisor(JsonNode node) { } }; ExecutionContext context = parent.createExecutionContext(); + JsonNode node = DecimalNode.valueOf(new BigDecimal("0.00000015")); + validator.validate(context, node, node, new NodePath(PathType.JSON_POINTER)); + assertEquals(1, context.getErrors().size()); + assertEquals(expectedDivisor, context.getErrors().get(0).getArguments()[0]); + assertEquals("must be multiple of " + expectedDivisor, context.getErrors().get(0).getMessage()); + } + + @ParameterizedTest + @ValueSource(ints = {0, 2, -100, 100, 30, Integer.MIN_VALUE, Integer.MAX_VALUE}) + void ignoresZeroDivisorFromOverride(int scale) { + Schema parent = SchemaRegistry.withDefaultDialect(SpecificationVersion.DRAFT_2020_12) + .getSchema("{\"multipleOf\":2}"); + MultipleOfValidator validator = new MultipleOfValidator(SchemaLocation.of("#/multipleOf"), + IntNode.valueOf(2), parent, parent.getSchemaContext()) { + @Override + protected BigDecimal getDivisor(JsonNode node) { + return new BigDecimal(BigInteger.ZERO, scale); + } + }; + for (String value : new String[] {"1", "1.5", "0.00000015", "0"}) { + ExecutionContext context = parent.createExecutionContext(); + JsonNode node = DecimalNode.valueOf(new BigDecimal(value)); + validator.validate(context, node, node, new NodePath(PathType.JSON_POINTER)); + assertTrue(context.getErrors().isEmpty(), "scale=" + scale + ", dividend=" + value); + } + } + + @ParameterizedTest + @CsvSource({ + "1e31, 10000000000000000000000000000000", + "1e32, 1E+32", + "1e-30, 0.000000000000000000000000000001", + "1e-31, 1E-31", + "-1e30, -1000000000000000000000000000000", + "-1e31, -1E+31", + "-1e-29, -0.00000000000000000000000000001", + "-1e-30, -1E-30", + "1e400, 1E+400", + "1.5e31, 15000000000000000000000000000000", + "1.5e32, 1.5E+32", + "1.5e-29, 0.000000000000000000000000000015", + "1.5e-30, 1.5E-30", + "-1.5e30, -1500000000000000000000000000000", + "-1.5e31, -1.5E+31", + "-1.5e-28, -0.00000000000000000000000000015", + "-1.5e-29, -1.5E-29", + "123456789012345678901234567890000, 123456789012345678901234567890000", + "1.2345678901234567890123456789E+33, 1234567890123456789012345678900000", + "1.2345678901234567890123456789E+34, 1.2345678901234567890123456789E+34", + "-123456789012345678901234567890000, -123456789012345678901234567890000", + "-1.2345678901234567890123456789E+33, -1234567890123456789012345678900000", + "-1.2345678901234567890123456789E+34, -1.2345678901234567890123456789E+34"}) + void divisorMessageBoundsPlainNotation(String text, String expectedDivisor) { + BigDecimal divisor = new BigDecimal(text); + ObjectNode schemaNode = JsonNodeFactory.instance.objectNode(); + schemaNode.set("multipleOf", DecimalNode.valueOf(divisor)); + Schema schema = SchemaRegistry.withDefaultDialect(SpecificationVersion.DRAFT_2020_12) + .getSchema(schemaNode); + BigDecimal dividend = divisor.multiply(new BigDecimal("1.5")); + List errors = schema.validate(DecimalNode.valueOf(dividend)); + assertEquals(1, errors.size()); + assertEquals("must be multiple of " + expectedDivisor, errors.get(0).getMessage()); + } + + @Test + void inheritedDivisorUsesPlainNotation() { + Schema parent = SchemaRegistry.withDefaultDialect(SpecificationVersion.DRAFT_2020_12) + .getSchema("{\"multipleOf\":100}"); + MultipleOfValidator validator = new MultipleOfValidator(SchemaLocation.of("#/multipleOf"), + IntNode.valueOf(100), parent, parent.getSchemaContext()) { + @Override + protected BigDecimal getDivisor(JsonNode node) { + return super.getDivisor(node); + } + }; + ExecutionContext context = parent.createExecutionContext(); JsonNode node = IntNode.valueOf(1); validator.validate(context, node, node, new NodePath(PathType.JSON_POINTER)); assertEquals(1, context.getErrors().size()); - assertEquals(value, context.getErrors().get(0).getArguments()[0]); - assertEquals("must be multiple of " + value, context.getErrors().get(0).getMessage()); + assertEquals("must be multiple of 100", context.getErrors().get(0).getMessage()); + } + + @ParameterizedTest + @ValueSource(strings = {"1e400", "-1e400"}) + void ignoresDivisorThatOverflowsDouble(String divisor) { + Schema schema = SchemaRegistry.withDefaultDialect(SpecificationVersion.DRAFT_2020_12) + .getSchema("{\"multipleOf\":" + divisor + "}"); + assertTrue(schema.validate("1", InputFormat.JSON).isEmpty()); + } + + @ParameterizedTest + @ValueSource(doubles = {Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY}) + void ignoresNonFiniteDivisors(double value) { + SchemaRegistry registry = SchemaRegistry.withDefaultDialect(SpecificationVersion.DRAFT_2020_12); + for (JsonNode divisor : new JsonNode[] {DoubleNode.valueOf(value), FloatNode.valueOf((float) value)}) { + ObjectNode schemaNode = JsonNodeFactory.instance.objectNode(); + schemaNode.set("multipleOf", divisor); + Schema schema = registry.getSchema(schemaNode); + assertTrue(schema.validate("1", InputFormat.JSON).isEmpty()); + } } @Test @@ -851,46 +957,66 @@ protected BigDecimal getDividend(JsonNode node) { } } - @Test - void convertedNonFiniteInputDoesNotRoundTheDivisor() { - long value = 9007199254740993L; + @ParameterizedTest + @CsvSource({"9007199254740993, 0", "9007199254740992, 1"}) + void convertedNonFiniteInputDoesNotRoundTheDivisor(long dividend, int expectedErrors) { + long divisor = 9007199254740993L; Schema parent = SchemaRegistry.withDefaultDialect(SpecificationVersion.DRAFT_2020_12) - .getSchema("{\"multipleOf\":" + value + "}"); + .getSchema("{\"multipleOf\":" + divisor + "}"); MultipleOfValidator validator = new MultipleOfValidator(SchemaLocation.of("#/multipleOf"), - LongNode.valueOf(value), parent, parent.getSchemaContext()) { + LongNode.valueOf(divisor), parent, parent.getSchemaContext()) { @Override protected BigDecimal getDividend(JsonNode node) { - return BigDecimal.valueOf(value); + return BigDecimal.valueOf(dividend); } }; for (JsonNode node : Arrays.asList(DoubleNode.valueOf(Double.NaN), DoubleNode.valueOf(Double.POSITIVE_INFINITY), FloatNode.valueOf(Float.NaN), FloatNode.valueOf(Float.NEGATIVE_INFINITY))) { ExecutionContext context = parent.createExecutionContext(); validator.validate(context, node, node, new NodePath(PathType.JSON_POINTER)); - assertTrue(context.getErrors().isEmpty()); + assertEquals(expectedErrors, context.getErrors().size()); + if (expectedErrors != 0) { + assertEquals("must be multiple of 9007199254740993", context.getErrors().get(0).getMessage()); + } } } - @Test - void preservesNonFiniteConversionBehaviorOnJackson2() { + @ParameterizedTest + @ValueSource(strings = {"1e400", "-1e400"}) + void ignoresDividendThatOverflowsDouble(String dividend) { + Schema schema = SchemaRegistry.withDefaultDialect(SpecificationVersion.DRAFT_2020_12) + .getSchema("{\"multipleOf\":3}"); + assertTrue(schema.validate(dividend, InputFormat.JSON).isEmpty()); + } + + @ParameterizedTest + @ValueSource(doubles = {Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY}) + void ignoresNonFiniteDividends(double value) { + Schema schema = SchemaRegistry.withDefaultDialect(SpecificationVersion.DRAFT_2020_12) + .getSchema("{\"multipleOf\":2}"); + for (JsonNode node : new JsonNode[] {DoubleNode.valueOf(value), FloatNode.valueOf((float) value)}) { + assertTrue(schema.validate(node).isEmpty()); + } + } + + @ParameterizedTest + @ValueSource(doubles = {Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY}) + void nonFiniteDivisorOverrideIsStillUsed(double value) { Schema parent = SchemaRegistry.withDefaultDialect(SpecificationVersion.DRAFT_2020_12) .getSchema("{\"multipleOf\":2}"); - for (JsonNode node : Arrays.asList(DoubleNode.valueOf(Double.NaN), - DoubleNode.valueOf(Double.POSITIVE_INFINITY), FloatNode.valueOf(Float.NEGATIVE_INFINITY))) { - assertThrows(NumberFormatException.class, () -> new MultipleOfValidator( - SchemaLocation.of("#/multipleOf"), node, parent, parent.getSchemaContext())); - assertThrows(NumberFormatException.class, () -> parent.validate(node)); + for (JsonNode schemaNode : new JsonNode[] {DoubleNode.valueOf(value), FloatNode.valueOf((float) value)}) { MultipleOfValidator validator = new MultipleOfValidator(SchemaLocation.of("#/multipleOf"), - node, parent, parent.getSchemaContext()) { + schemaNode, parent, parent.getSchemaContext()) { @Override - protected BigDecimal getDivisor(JsonNode schemaNode) { + protected BigDecimal getDivisor(JsonNode node) { return BigDecimal.valueOf(2); } }; ExecutionContext context = parent.createExecutionContext(); - JsonNode input = IntNode.valueOf(6); + JsonNode input = IntNode.valueOf(3); validator.validate(context, input, input, new NodePath(PathType.JSON_POINTER)); - assertTrue(context.getErrors().isEmpty()); + assertEquals(1, context.getErrors().size()); + assertEquals("must be multiple of 2", context.getErrors().get(0).getMessage()); } }