diff --git a/CHANGELOG.md b/CHANGELOG.md index 3bf5e2a6f..2d9def139 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,9 @@ 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`, `uri-reference`, `iri` and `iri-reference` check the authority against RFC 3986 section 3.2 (RFC 3987 for the IRI formats). A port must be digits only, the userinfo cannot contain another `@`, and an IPv6 literal must not have leading zeros in an embedded IPv4 address. `http://example.com:abc/path`, `http://a@b@example.com/` and `http://[::ffff:01.2.3.4]` are now rejected in all four formats (and the same authorities in a network-path reference such as `//a@b@example.com/` in `uri-reference` and `iri-reference`), and an IPv6 address without brackets, such as `http://2001:db8::1`, in `uri` and `uri-reference`; 3.0.9 and earlier accepted them, because `java.net.URI` treats an authority it cannot parse as registry-based (`iri` and `iri-reference` already rejected an IPv6 address without brackets). An IPv6 zone id, such as `http://[fe80::1%25en1]/`, is now rejected in all four formats, since RFC 3986 has none; 3.0.9 accepted it. In `iri` and `iri-reference`, the userinfo and the host may contain RFC 3987 `ucschar`, and bidirectional formatting characters are rejected anywhere in the value: U+200E, U+200F and U+202A to U+202E, which RFC 3987 section 4.1 forbids, and U+061C and U+2066 to U+2069, which Unicode added later and which can reorder the displayed text the same way. 3.0.9 accepted them, for example in a path such as `http://example.com/a\u202Eb`. A percent-encoded colon in a reg-name, such as `http://1%3A%3A2/`, is now valid in `iri` and `iri-reference`, as it already was in `uri`. Registry-based names such as `a_b.example` and inputs such as `http://` and `about:` remain valid. The vendored `uri`, `uri-reference`, `iri` and `iri-reference` suite files gain the matching JSON-Schema-Test-Suite cases. +- `uri` and `iri` reject `//`, which has no scheme (RFC 3986 section 3 requires one); it stays valid in `uri-reference` and `iri-reference`. In all four formats, a scheme must start with a letter and contain only letters, digits, `+`, `-` and `.` (section 3.1), also in a value that `java.net.URI` cannot parse, such as an empty authority: `1http://`, `bar,baz://` and `,:` are now invalid as `uri` and `iri`, `1http:` as `uri-reference` and `iri-reference`, and `://` in all four. 3.0.9 and earlier accepted all of these. `http://` and `about:` remain valid, and a scheme followed by only a fragment, such as `about:#frag`, is now valid, as RFC 3986 allows. `UriFormatTest` and `IriFormatTest` now expect `//` to fail. +- `AbstractRFC3986Format.handleException` passes a value that `java.net.URI` cannot parse, but that RFC 3986 allows, to `validate(URI)` as if its empty path were `/`, for example `http:///` for `http://`. A subclass that requires an absolute URI or a certain scheme therefore rejects `//`, or `http://` for another scheme; before, these values skipped `validate(URI)`. +- `uri`, `uri-reference`, `iri` and `iri-reference` accept `[` and `]` only around an IP-literal in the authority, as RFC 3986 requires. `http://x/#a[b`, `#a]b` and `urn:a[b` are now invalid; 3.0.9 and earlier rejected them only in the query. `AbstractRFC3986Format` does this check, so a subclass gets it too, and the four formats no longer check the query themselves. A subclass that accepts brackets, for example in a query such as `?tags[]=a`, can override the new `protected` `containsMisplacedBracket(URI)` to return `false`. - `AbstractRFC3986Format` checks the authority in its final `matches` method, so a subclass outside this library gets the check too. A subclass for an IRI-like format must override the new `isInternationalized()` to return `true`, or non-ASCII characters in the userinfo and the host are rejected. `isInternationalized()` controls only that; the bidirectional formatting check is done in `IriFormat` and `IriReferenceFormat`, so such a subclass should also reject values for which the new `protected static` `containsBidiFormatting(String)` returns `true`, or extend one of those two classes. - `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. @@ -35,6 +38,7 @@ This project does not adhere to [Semantic Versioning](https://semver.org/) and m - 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`, `uri-reference`, `iri` and `iri-reference` check the value as it is when `java.net.URI` cannot parse it. Since JDK 25, the input of the `URISyntaxException` is trimmed, or empty, depending on the `jdk.includeInExceptions` security property, so `http://` with a leading space was accepted and `about:` could be rejected. - `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. - 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) diff --git a/src/main/java/com/networknt/schema/format/AbstractRFC3986Format.java b/src/main/java/com/networknt/schema/format/AbstractRFC3986Format.java index 21291e78d..e312c0935 100644 --- a/src/main/java/com/networknt/schema/format/AbstractRFC3986Format.java +++ b/src/main/java/com/networknt/schema/format/AbstractRFC3986Format.java @@ -10,7 +10,17 @@ * {@link Format} for RFC 3986 Uniform Resource Identifier (URI): Generic Syntax. */ public abstract class AbstractRFC3986Format implements Format { - private static final Pattern VALID = Pattern.compile("([A-Za-z0-9+-\\.]*:)?//|[A-Za-z0-9+-\\.]+:"); + /** + * RFC 3986 section 3.1: {@code scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )}, followed by {@code ":"}. + */ + private static final String SCHEME = "[A-Za-z][A-Za-z0-9+.-]*:"; + + /** + * What {@link URI} rejects although RFC 3986 allows it: an empty authority with nothing after it, as in + * {@code http://} or the network-path reference {@code //}, and an empty hier-part with no query, as in + * {@code about:} or {@code about:#fragment}. + */ + private static final Pattern VALID = Pattern.compile("(" + SCHEME + ")?//|" + SCHEME + "(#.*)?", Pattern.DOTALL); @Override public final boolean matches(ExecutionContext executionContext, String value) { @@ -20,9 +30,11 @@ public final boolean matches(ExecutionContext executionContext, String value) { if (authority != null && !isValidAuthority(authority)) { return false; } - return validate(uri); + return check(uri); } catch (URISyntaxException e) { - return handleException(e); + // Since JDK 25 the input of the exception can be trimmed, or empty, depending on the + // jdk.includeInExceptions security property, so pass on the value as it is + return handleException(new URISyntaxException(value, e.getReason(), e.getIndex())); } } @@ -34,14 +46,52 @@ public final boolean matches(ExecutionContext executionContext, String value) { */ protected abstract boolean validate(URI uri); + private boolean check(URI uri) { + return !containsMisplacedBracket(uri) && validate(uri); + } + /** - * Determines if the uri matches the format. + * Determines if a value that {@link URI} cannot parse still matches the format: {@code scheme ":" "//"}, + * {@code "//"} or {@code scheme ":" [ "#" fragment ]}. Such a value is checked with {@link #validate(URI)} as if + * its empty path were {@code "/"}, so {@code //} is rejected by a format that requires an absolute URI, and a + * subclass that requires a certain scheme rejects {@code http://} for another scheme. * - * @param e the URISyntaxException + * @param e the URISyntaxException, whose input is the value * @return false if it does not match */ protected boolean handleException(URISyntaxException e) { - return VALID.matcher(e.getInput()).matches(); + String value = e.getInput(); + if (!VALID.matcher(value).matches()) { + return false; + } + // the empty path ends at the fragment, since "#" cannot be part of a scheme + int hash = value.indexOf('#'); + int end = hash == -1 ? value.length() : hash; + try { + URI uri = new URI(value.substring(0, end) + "/" + value.substring(end)); + return check(uri); + } catch (URISyntaxException invalid) { + // for example, a fragment with a character that is not allowed + return false; + } + } + + /** + * Determines if the uri contains {@code "["} or {@code "]"} outside an IP-literal. RFC 3986 allows them only + * around an IP-literal in the authority, but {@link URI} also accepts them in the query, the fragment and an opaque + * scheme-specific part, such as {@code urn:a[b}. It rejects them in a path. A subclass that accepts them, for + * example in a query such as {@code ?tags[]=a}, can override this to return false. + * + * @param uri the uri + * @return true if the uri contains one + */ + protected boolean containsMisplacedBracket(URI uri) { + return containsBracket(uri.isOpaque() ? uri.getRawSchemeSpecificPart() : uri.getRawQuery()) + || containsBracket(uri.getRawFragment()); + } + + private static boolean containsBracket(String value) { + return value != null && (value.indexOf('[') != -1 || value.indexOf(']') != -1); } /** diff --git a/src/main/java/com/networknt/schema/format/IriFormat.java b/src/main/java/com/networknt/schema/format/IriFormat.java index df8710f61..e2031e414 100644 --- a/src/main/java/com/networknt/schema/format/IriFormat.java +++ b/src/main/java/com/networknt/schema/format/IriFormat.java @@ -8,20 +8,7 @@ public class IriFormat extends AbstractRFC3986Format { @Override protected boolean validate(URI uri) { - if (containsBidiFormatting(uri.toString())) { - return false; - } - boolean result = uri.isAbsolute(); - if (result) { - String query = uri.getRawQuery(); - if (query != null) { - // [ and ] must be percent encoded - if (query.indexOf('[') != -1 || query.indexOf(']') != -1) { - return false; - } - } - } - return result; + return !containsBidiFormatting(uri.toString()) && uri.isAbsolute(); } @Override diff --git a/src/main/java/com/networknt/schema/format/IriReferenceFormat.java b/src/main/java/com/networknt/schema/format/IriReferenceFormat.java index b3e56c035..620374269 100644 --- a/src/main/java/com/networknt/schema/format/IriReferenceFormat.java +++ b/src/main/java/com/networknt/schema/format/IriReferenceFormat.java @@ -8,15 +8,7 @@ public class IriReferenceFormat extends AbstractRFC3986Format { @Override protected boolean validate(URI uri) { - if (containsBidiFormatting(uri.toString())) { - return false; - } - String query = uri.getRawQuery(); - if (query != null) { - // [ and ] must be percent encoded - return query.indexOf('[') == -1 && query.indexOf(']') == -1; - } - return true; + return !containsBidiFormatting(uri.toString()); } @Override diff --git a/src/main/java/com/networknt/schema/format/UriFormat.java b/src/main/java/com/networknt/schema/format/UriFormat.java index 1b98c02d7..e9f5c0841 100644 --- a/src/main/java/com/networknt/schema/format/UriFormat.java +++ b/src/main/java/com/networknt/schema/format/UriFormat.java @@ -8,21 +8,8 @@ public class UriFormat extends AbstractRFC3986Format { @Override protected boolean validate(URI uri) { - boolean result = uri.isAbsolute(); - if (result) { - // Java URI accepts non ASCII characters and this is not a valid in RFC3986 - result = uri.toString().codePoints().allMatch(ch -> ch < 0x7F); - if (result) { - String query = uri.getRawQuery(); - if (query != null) { - // [ and ] must be percent encoded - if (query.indexOf('[') != -1 || query.indexOf(']') != -1) { - return false; - } - } - } - } - return result; + // Java URI accepts non ASCII characters and this is not a valid in RFC3986 + return uri.isAbsolute() && uri.toString().codePoints().allMatch(ch -> ch < 0x7F); } @Override diff --git a/src/main/java/com/networknt/schema/format/UriReferenceFormat.java b/src/main/java/com/networknt/schema/format/UriReferenceFormat.java index 4cb5a203a..e833783fe 100644 --- a/src/main/java/com/networknt/schema/format/UriReferenceFormat.java +++ b/src/main/java/com/networknt/schema/format/UriReferenceFormat.java @@ -9,17 +9,7 @@ public class UriReferenceFormat extends AbstractRFC3986Format { @Override protected boolean validate(URI uri) { // Java URI accepts non ASCII characters and this is not a valid in RFC3986 - boolean result = uri.toString().codePoints().allMatch(ch -> ch < 0x7F); - if (result) { - String query = uri.getRawQuery(); - if (query != null) { - // [ and ] must be percent encoded - if (query.indexOf('[') != -1 || query.indexOf(']') != -1) { - return false; - } - } - } - return result; + return uri.toString().codePoints().allMatch(ch -> ch < 0x7F); } @Override diff --git a/src/test/java/com/networknt/schema/format/IriFormatTest.java b/src/test/java/com/networknt/schema/format/IriFormatTest.java index 84479f45a..a6e666772 100644 --- a/src/test/java/com/networknt/schema/format/IriFormatTest.java +++ b/src/test/java/com/networknt/schema/format/IriFormatTest.java @@ -89,14 +89,14 @@ void noAuthorityShouldPass() { } @Test - void noSchemeNoAuthorityShouldPass() { + void noSchemeNoAuthorityShouldFail() { String schemaData = "{\r\n" + " \"format\": \"iri\"\r\n" + "}"; Schema schema = SchemaRegistry.withDefaultDialect(SpecificationVersion.DRAFT_2020_12).getSchema(schemaData); List messages = schema.validate("\"//\"", InputFormat.JSON, executionContext -> executionContext.executionConfig(executionConfig -> executionConfig.formatAssertionsEnabled(true))); - assertTrue(messages.isEmpty()); + assertFalse(messages.isEmpty()); } @Test diff --git a/src/test/java/com/networknt/schema/format/UriBracketFormatTest.java b/src/test/java/com/networknt/schema/format/UriBracketFormatTest.java new file mode 100644 index 000000000..feb5e4f3f --- /dev/null +++ b/src/test/java/com/networknt/schema/format/UriBracketFormatTest.java @@ -0,0 +1,75 @@ +/* + * 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.format; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.net.URI; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import com.networknt.schema.Error; +import com.networknt.schema.InputFormat; +import com.networknt.schema.Schema; +import com.networknt.schema.SchemaRegistry; +import com.networknt.schema.SpecificationVersion; + +/** + * Tests that "[" and "]" are valid only around an IP-literal in the authority. + */ +class UriBracketFormatTest { + + @ParameterizedTest + @CsvSource(delimiter = '|', value = { + "uri | http://[::1]/p?q#f | true", + "uri | http://x/?a[b | false", + "uri | http://x/#a[b | false", + "uri | http://x/#a]b | false", + "uri | http://x/#a%5Bb%5D | true", + "uri | urn:a[b | false", + "uri | mailto:a]b | false", + "uri | about:#a[b | false", + "uri-reference | #a[b | false", + "uri-reference | //[::1]/#a]b | false", + "iri | http://x/#a[b | false", + "iri | urn:a]b | false", + "iri-reference | #a]b | false", + "iri-reference | ?a[b | false", + }) + void brackets(String format, String value, boolean valid) { + Schema schema = SchemaRegistry.withDefaultDialect(SpecificationVersion.DRAFT_2020_12) + .getSchema("{\"format\":\"" + format + "\"}"); + List messages = schema.validate("\"" + value + "\"", InputFormat.JSON, + executionContext -> executionContext + .executionConfig(executionConfig -> executionConfig.formatAssertionsEnabled(true))); + assertEquals(valid, messages.isEmpty(), () -> format + " " + value + ": " + messages); + } + + @Test + void subclassCanAcceptBrackets() { + AbstractRFC3986Format format = new UriFormat() { + @Override + protected boolean containsMisplacedBracket(URI uri) { + return false; + } + }; + assertTrue(format.matches(null, "https://x/search?tags[]=a")); + } +} diff --git a/src/test/java/com/networknt/schema/format/UriFallbackFormatTest.java b/src/test/java/com/networknt/schema/format/UriFallbackFormatTest.java new file mode 100644 index 000000000..d94c92b70 --- /dev/null +++ b/src/test/java/com/networknt/schema/format/UriFallbackFormatTest.java @@ -0,0 +1,127 @@ +/* + * 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.format; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import com.networknt.schema.Error; +import com.networknt.schema.InputFormat; +import com.networknt.schema.Schema; +import com.networknt.schema.SchemaRegistry; +import com.networknt.schema.SpecificationVersion; + +/** + * Tests the values that java.net.URI cannot parse but RFC 3986 allows: an empty authority, or an empty hier-part with + * or without a fragment. + */ +class UriFallbackFormatTest { + + @ParameterizedTest + @CsvSource(delimiter = '|', value = { + // scheme ":" "//" with an empty authority, and scheme ":" with an empty hier-part + "uri | http:// | true", + "uri | a+b.c-d9:// | true", + "uri | about: | true", + "iri | http:// | true", + "uri-reference | http:// | true", + "uri-reference | about: | true", + "iri-reference | about: | true", + // the network-path reference "//" has no scheme, so it is not an absolute URI + "uri | // | false", + "iri | // | false", + "uri-reference | // | true", + "iri-reference | // | true", + // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) + "uri | 1http:// | false", + "uri | bar,baz:// | false", + "uri | ,: | false", + "uri | :// | false", + "uri-reference | 1http: | false", + "uri-reference | 1http:// | false", + "iri-reference | bar,baz: | false", + "iri | 1http:// | false", + "iri | about: | true", + // the empty scheme that 3.0.9 accepted + "iri | :// | false", + "uri-reference | :// | false", + "iri-reference | :// | false", + // scheme ":" "#" fragment, with an empty hier-part + "uri | about:#frag | true", + "uri | about:# | true", + "uri-reference | about:#frag | true", + "uri | about:#a b | false", + "uri | about:#\u0192 | false", + "iri | about:#\u0192 | true", + "iri | about:#a\u202Eb | false", + // the value is checked as it is: JDK 25 trims the input of the URISyntaxException + "uri | ' http://' | false", + "uri | 'about: ' | false", + "uri-reference | ' // ' | false", + "iri | ' about:#frag' | false", + }) + void fallback(String format, String value, boolean valid) { + Schema schema = SchemaRegistry.withDefaultDialect(SpecificationVersion.DRAFT_2020_12) + .getSchema("{\"format\":\"" + format + "\"}"); + List messages = schema.validate("\"" + value + "\"", InputFormat.JSON, + executionContext -> executionContext + .executionConfig(executionConfig -> executionConfig.formatAssertionsEnabled(true))); + assertEquals(valid, messages.isEmpty(), () -> format + " " + value + ": " + messages); + } + + @Test + void subclassGetsValueUnchanged() { + String[] input = new String[1]; + AbstractRFC3986Format format = new UriReferenceFormat() { + @Override + protected boolean handleException(URISyntaxException e) { + input[0] = e.getInput(); + return super.handleException(e); + } + }; + assertFalse(format.matches(null, " http:// ")); + assertEquals(" http:// ", input[0]); + } + + @Test + void subclassValidatesFallback() { + // a custom format for absolute https URIs only + AbstractRFC3986Format format = new AbstractRFC3986Format() { + @Override + protected boolean validate(URI uri) { + return uri.isAbsolute() && "https".equals(uri.getScheme()); + } + + @Override + public String getName() { + return "https-uri"; + } + }; + assertTrue(format.matches(null, "https://")); + assertFalse(format.matches(null, "//")); + assertFalse(format.matches(null, "http://")); + assertFalse(format.matches(null, "ftp:")); + } +} diff --git a/src/test/java/com/networknt/schema/format/UriFormatTest.java b/src/test/java/com/networknt/schema/format/UriFormatTest.java index c7a5c83ca..0f62b8119 100644 --- a/src/test/java/com/networknt/schema/format/UriFormatTest.java +++ b/src/test/java/com/networknt/schema/format/UriFormatTest.java @@ -87,14 +87,14 @@ void noAuthorityShouldPass() { } @Test - void noSchemeNoAuthorityShouldPass() { + void noSchemeNoAuthorityShouldFail() { String schemaData = "{\r\n" + " \"format\": \"uri\"\r\n" + "}"; Schema schema = SchemaRegistry.withDefaultDialect(SpecificationVersion.DRAFT_2020_12).getSchema(schemaData); List messages = schema.validate("\"//\"", InputFormat.JSON, executionContext -> executionContext.executionConfig(executionConfig -> executionConfig.formatAssertionsEnabled(true))); - assertTrue(messages.isEmpty()); + assertFalse(messages.isEmpty()); } @Test