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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ This project does not adhere to [Semantic Versioning](https://semver.org/) and m
### Breaking changes

- `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.
- `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.

### Changed
Expand Down
121 changes: 121 additions & 0 deletions src/main/java/com/networknt/schema/format/AbstractRFC3986Format.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ public abstract class AbstractRFC3986Format implements Format {
public final boolean matches(ExecutionContext executionContext, String value) {
try {
URI uri = new URI(value);
String authority = uri.getRawAuthority();
if (authority != null && !isValidAuthority(authority)) {
return false;
}
return validate(uri);
} catch (URISyntaxException e) {
return handleException(e);
Expand All @@ -39,4 +43,121 @@ public final boolean matches(ExecutionContext executionContext, String value) {
protected boolean handleException(URISyntaxException e) {
return VALID.matcher(e.getInput()).matches();
}

/**
* Determines if the userinfo and the host may contain the non-ASCII characters RFC 3987 allows in an IRI
* ({@code ucschar}).
*
* @return true for the IRI formats
*/
protected boolean isInternationalized() {
return false;
}

/**
* Checks the authority against RFC 3986 section 3.2:
* {@code authority = [ userinfo "@" ] host [ ":" port ]}.
* <p>
* {@link URI} falls back to a registry-based authority when it cannot parse the authority as a server, and then
* checks neither the port, the userinfo nor the host. A registry-based authority such as {@code a_b.example} is
* still a valid reg-name, so {@link URI#parseServerAuthority()} cannot be used instead.
*
* @param authority the raw authority
* @return true if the authority is valid
*/
private boolean isValidAuthority(String authority) {
String hostAndPort = authority;
int at = authority.indexOf('@');
if (at != -1) {
// userinfo = *( unreserved / pct-encoded / sub-delims / ":" ), so it cannot contain another "@"
if (authority.indexOf('@', at + 1) != -1 || !isValid(authority.substring(0, at), true)) {
return false;
}
hostAndPort = authority.substring(at + 1);
}
if (hostAndPort.startsWith("[")) {
// java.net.URI returns a bracketed host only after parsing the authority as a server, which guarantees
// "[" IPv6address "]" [ ":" *DIGIT ]; it throws on an IPvFuture. RFC 3986 has no zone id, and its
// dec-octet has no leading zeros, as in the ipv6 format.
int end = hostAndPort.indexOf(']');
return end > 0 && IPv6Format.isValid(hostAndPort.substring(1, end));
}
// A reg-name or an IPv4address cannot contain ":", so the first ":" starts the port; an IPv6 address without
// brackets leaves a port that is not a number
int colon = hostAndPort.indexOf(':');
String host = colon == -1 ? hostAndPort : hostAndPort.substring(0, colon);
if (!isValid(host, false)) {
return false;
}
// port = *DIGIT
return colon == -1 || hostAndPort.chars().skip(colon + 1).allMatch(ch -> ch >= '0' && ch <= '9');
}

/**
* Checks a userinfo or a reg-name: {@code *( unreserved / pct-encoded / sub-delims )}, with {@code ":"} in a
* userinfo, and {@code ucschar} in an IRI.
*/
private boolean isValid(String value, boolean colonAllowed) {
int i = 0;
while (i < value.length()) {
int cp = value.codePointAt(i);
if (cp == '%') {
if (i + 2 >= value.length() || !isHexDigit(value.charAt(i + 1)) || !isHexDigit(value.charAt(i + 2))) {
return false;
}
i += 3;
continue;
}
if (!(isUnreserved(cp) || isSubDelim(cp) || (colonAllowed && cp == ':')
|| (isInternationalized() && isUcschar(cp)))) {
return false;
}
i += Character.charCount(cp);
}
return true;
}

private static boolean isUnreserved(int cp) {
return (cp >= 'A' && cp <= 'Z') || (cp >= 'a' && cp <= 'z') || (cp >= '0' && cp <= '9') || cp == '-'
|| cp == '.' || cp == '_' || cp == '~';
}

private static boolean isSubDelim(int cp) {
return "!$&'()*+,;=".indexOf(cp) != -1;
}

private static boolean isHexDigit(char ch) {
return (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f');
}

/**
* Determines if the value contains a bidirectional formatting character: the ones RFC 3987 section 4.1 forbids in
* an IRI (LRM, RLM, LRE, RLE, PDF, LRO and RLO), and the ones Unicode added later that can reorder the displayed
* text the same way (ALM and the isolates LRI, RLI, FSI and PDI). {@code IriFormat} and {@code IriReferenceFormat}
* reject such values; a subclass for another IRI-like format can call this from its {@link #validate(URI)}.
*
* @param value the value
* @return true if the value contains one
*/
protected static boolean containsBidiFormatting(String value) {
for (int i = 0; i < value.length(); i++) {
char ch = value.charAt(i);
if (ch == '\u061C' || ch == '\u200E' || ch == '\u200F' || (ch >= '\u202A' && ch <= '\u202E')
|| (ch >= '\u2066' && ch <= '\u2069')) {
return true;
}
}
return false;
}

/**
* RFC 3987 {@code ucschar}.
*/
private static boolean isUcschar(int cp) {
if (cp < 0x10000) {
return (cp >= 0xA0 && cp <= 0xD7FF) || (cp >= 0xF900 && cp <= 0xFDCF) || (cp >= 0xFDF0 && cp <= 0xFFEF);
}
// %x10000-1FFFD / %x20000-2FFFD / ... / %xD0000-DFFFD / %xE1000-EFFFD
return cp <= 0xEFFFD && (cp & 0xFFFF) <= 0xFFFD && !(cp >= 0xE0000 && cp < 0xE1000);
}
}
10 changes: 10 additions & 0 deletions src/main/java/com/networknt/schema/format/IPv6Format.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,16 @@ public class IPv6Format implements Format {

@Override
public boolean matches(ExecutionContext executionContext, String value) {
return isValid(value);
}

/**
* Determines if the value is an RFC 4291 IPv6 address, without a zone id.
*
* @param value the value
* @return true if valid
*/
public static boolean isValid(String value) {
if (!value.trim().equals(value)) {
// leading and trailing spaces
return false;
Expand Down
15 changes: 8 additions & 7 deletions src/main/java/com/networknt/schema/format/IriFormat.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,11 @@
public class IriFormat extends AbstractRFC3986Format {
@Override
protected boolean validate(URI uri) {
if (containsBidiFormatting(uri.toString())) {
return false;
}
boolean result = uri.isAbsolute();
if (result) {
String authority = uri.getAuthority();
if (authority != null) {
if (IPv6Format.PATTERN.matcher(authority).matches() ) {
return false;
}
}

String query = uri.getRawQuery();
if (query != null) {
// [ and ] must be percent encoded
Expand All @@ -28,6 +24,11 @@ protected boolean validate(URI uri) {
return result;
}

@Override
protected boolean isInternationalized() {
return true;
}

@Override
public String getName() {
return "iri";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,8 @@
public class IriReferenceFormat extends AbstractRFC3986Format {
@Override
protected boolean validate(URI uri) {
String authority = uri.getAuthority();
if (authority != null) {
if (IPv6Format.PATTERN.matcher(authority).matches() ) {
return false;
}
if (containsBidiFormatting(uri.toString())) {
return false;
}
String query = uri.getRawQuery();
if (query != null) {
Expand All @@ -22,6 +19,11 @@ protected boolean validate(URI uri) {
return true;
}

@Override
protected boolean isInternationalized() {
return true;
}

@Override
public String getName() {
return "iri-reference";
Expand Down
105 changes: 105 additions & 0 deletions src/test/java/com/networknt/schema/format/UriAuthorityFormatTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
/*
* 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 java.util.List;

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 RFC 3986 section 3.2 authority checks shared by the uri, uri-reference, iri and iri-reference formats.
*/
class UriAuthorityFormatTest {

@ParameterizedTest
@CsvSource(delimiter = '|', value = {
// port = *DIGIT
"uri | http://example.com:8080/p | true",
"uri | http://example.com:/p | true",
"uri | http://example.com:abc/p | false",
"uri | http://example.com:80a/p | false",
"uri | http://[::1]:8080/p | true",
// userinfo = *( unreserved / pct-encoded / sub-delims / ":" )
"uri | http://user:pass@example.com/p | true",
"uri | http://us%40er@example.com/p | true",
"uri | http://a@b@example.com/p | false",
// reg-name: a registry-based name that java.net.URI cannot parse as a server is still valid
"uri | http://a_b.example/p | true",
"uri | http://087.10.0.1/ | true",
// IP-literal = "[" ( IPv6address / IPvFuture ) "]"
"uri | http://[2001:db8::7]/p | true",
"uri | http://[::ffff:1.2.3.4]/p | true",
"uri | http://[::ffff:01.2.3.4]/p | false",
"uri | http://[fe80::1%25en1]/p | false",
"uri | http://2001:db8::1/p | false",
// no authority, or an empty one
"uri | http:// | true",
"uri | about: | true",
"uri | urn:example:resource | true",
"uri-reference | //example.com:abc/p | false",
"uri-reference | //a@b@example.com/ | false",
"uri-reference | //[::ffff:192.168.0.01]/p | false",
"uri-reference | //example.com:8080/p | true",
"uri-reference | /p | true",
// ucschar is allowed in the userinfo and the host of an IRI only
"iri | http://â@ƒøø.ßår/ | true",
"iri | http://â@b@ƒøø.ßår/ | false",
"iri | http://ƒøø.ßår:abc/path | false",
"iri | http://ƒøø.ßår:8080/path | true",
"iri-reference | //ƒøø.ßår/p | true",
"iri-reference | //ƒøø.ßår:abc/p | false",
"uri | http://ƒøø.ßår/ | false",
// a percent-encoded "::" is a valid reg-name, not an IPv6 address
"uri | http://1%3A%3A2/ | true",
"iri | http://1%3A%3A2/ | true",
"iri-reference | //1%3A%3A2/ | true",
// RFC 3987 section 4.1 forbids bidirectional formatting characters anywhere in an IRI
"iri | http://ex\u202Eample/ | false",
"iri | http://ex\u200Fample/ | false",
"iri-reference | //ex\u202Aample/p | false",
"iri | http://example.com/a\u202Eb | false",
"iri | http://example.com/?q=\u200F | false",
"iri-reference | /a\u202Db | false",
"iri | http://example.com/#\u202A | false",
"iri-reference | http://example.com/?q=\u200F | false",
"iri-reference | http://example.com/#\u202A | false",
"uri | http://example.com/a\u202Eb | false",
"iri | http://a\u202Eb@example.com/ | false",
"iri | http://example.com/a%E2%80%AEb | true",
// Unicode bidi characters added after RFC 3987: ALM and the isolates
"iri | http://ex\u2067ample/ | false",
"iri-reference | /a\u061Cb | false",
"iri | http://example.com/a\u2069b | false",
"uri | http://example.com/a%E2%80%AEb | true",
})
void authority(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);
}
}
15 changes: 15 additions & 0 deletions src/test/suite/tests/draft-next/optional/format/iri-reference.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,21 @@
"description": "an invalid IRI fragment",
"data": "#ƒräg\\mênt",
"valid": false
},
{
"description": "an embedded IPv4 with a leading zero is invalid",
"data": "//[::ffff:192.168.0.01]/p",
"valid": false
},
{
"description": "a non-numeric port in a network-path reference is invalid",
"data": "//ƒøø.ßår:abc/p",
"valid": false
},
{
"description": "more than one at-sign in the authority is invalid",
"data": "//â@b@ƒøø.ßår/",
"valid": false
}
]
}
Expand Down
15 changes: 15 additions & 0 deletions src/test/suite/tests/draft-next/optional/format/iri.json
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,21 @@
"description": "an invalid IRI though valid IRI reference",
"data": "âππ",
"valid": false
},
{
"description": "an IPv6 host whose embedded IPv4 has a leading zero is invalid",
"data": "http://[::ffff:192.168.0.01]",
"valid": false
},
{
"description": "non-numeric port is invalid",
"data": "http://ƒøø.ßår:abc/path",
"valid": false
},
{
"description": "more than one at-sign in the authority is invalid",
"data": "http://â@b@ƒøø.ßår/",
"valid": false
}
]
}
Expand Down
15 changes: 15 additions & 0 deletions src/test/suite/tests/draft-next/optional/format/uri-reference.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,21 @@
"description": "an invalid URI fragment",
"data": "#frag\\ment",
"valid": false
},
{
"description": "a non-numeric port in a network-path reference",
"data": "//example.com:abc/p",
"valid": false
},
{
"description": "more than one at-sign in the authority",
"data": "//a@b@example.com/",
"valid": false
},
{
"description": "a leading zero in the IPv4 part of an IPv6 literal",
"data": "//[::ffff:192.168.0.01]/p",
"valid": false
}
]
}
Expand Down
Loading
Loading