Skip to content

Commit

Permalink
Add URN validation to URI rule (#236)
Browse files Browse the repository at this point in the history
This adds additional validation for URNs to the `isUri` rule.
  • Loading branch information
smaye81 authored Feb 4, 2025
1 parent 967e898 commit 07f1637
Showing 1 changed file with 22 additions and 15 deletions.
37 changes: 22 additions & 15 deletions src/main/java/build/buf/protovalidate/CustomOverload.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,8 @@
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;
import org.projectnessie.cel.common.types.BoolT;
Expand Down Expand Up @@ -357,11 +356,7 @@ private static Overload isUri() {
if (addr.isEmpty()) {
return BoolT.False;
}
try {
return Types.boolOf(new URL(addr).toURI().isAbsolute());
} catch (MalformedURLException | URISyntaxException e) {
return BoolT.False;
}
return Types.boolOf(validateURI(addr, true));
});
}

Expand All @@ -381,14 +376,7 @@ private static Overload isUriRef() {
if (addr.isEmpty()) {
return BoolT.False;
}
try {
// TODO: The URL api requires a host or it always fails.
String host = "http://protovalidate.buf.build";
URL url = new URL(host + addr);
return Types.boolOf(url.getPath() != null && !url.getPath().isEmpty());
} catch (MalformedURLException e) {
return BoolT.False;
}
return Types.boolOf(validateURI(addr, false));
});
}

Expand Down Expand Up @@ -609,6 +597,25 @@ private static boolean validateIP(String addr, long ver) {
return false;
}

/**
* Validates if the input string is a valid URI, which can be a URL or a URN.
*
* @param val The input string to validate as a URI.
* @param checkAbsolute Whether to check if this URI is absolute (i.e. has a scheme component)
* @return {@code true} if the input string is a valid URI, {@code false} otherwise.
*/
private static boolean validateURI(String val, boolean checkAbsolute) {
try {
URI uri = new URI(val);
if (checkAbsolute) {
return uri.isAbsolute();
}
return true;
} catch (URISyntaxException e) {
return false;
}
}

/**
* Validates if the input string is a valid IP prefix.
*
Expand Down

0 comments on commit 07f1637

Please sign in to comment.