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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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()));
}
}

Expand All @@ -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);
}

/**
Expand Down
15 changes: 1 addition & 14 deletions src/main/java/com/networknt/schema/format/IriFormat.java
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 2 additions & 15 deletions src/main/java/com/networknt/schema/format/UriFormat.java
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions src/test/java/com/networknt/schema/format/IriFormatTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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<Error> messages = schema.validate("\"//\"", InputFormat.JSON, executionContext -> executionContext.executionConfig(executionConfig -> executionConfig.formatAssertionsEnabled(true)));
assertTrue(messages.isEmpty());
assertFalse(messages.isEmpty());
}

@Test
Expand Down
Original file line number Diff line number Diff line change
@@ -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<Error> 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"));
}
}
Loading
Loading