Skip to content

Commit 07f1637

Browse files
authored
Add URN validation to URI rule (#236)
This adds additional validation for URNs to the `isUri` rule.
1 parent 967e898 commit 07f1637

File tree

1 file changed

+22
-15
lines changed

1 file changed

+22
-15
lines changed

src/main/java/build/buf/protovalidate/CustomOverload.java

Lines changed: 22 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,8 @@
2525
import java.net.Inet4Address;
2626
import java.net.Inet6Address;
2727
import java.net.InetAddress;
28-
import java.net.MalformedURLException;
28+
import java.net.URI;
2929
import java.net.URISyntaxException;
30-
import java.net.URL;
3130
import java.util.HashSet;
3231
import java.util.Set;
3332
import org.projectnessie.cel.common.types.BoolT;
@@ -357,11 +356,7 @@ private static Overload isUri() {
357356
if (addr.isEmpty()) {
358357
return BoolT.False;
359358
}
360-
try {
361-
return Types.boolOf(new URL(addr).toURI().isAbsolute());
362-
} catch (MalformedURLException | URISyntaxException e) {
363-
return BoolT.False;
364-
}
359+
return Types.boolOf(validateURI(addr, true));
365360
});
366361
}
367362

@@ -381,14 +376,7 @@ private static Overload isUriRef() {
381376
if (addr.isEmpty()) {
382377
return BoolT.False;
383378
}
384-
try {
385-
// TODO: The URL api requires a host or it always fails.
386-
String host = "http://protovalidate.buf.build";
387-
URL url = new URL(host + addr);
388-
return Types.boolOf(url.getPath() != null && !url.getPath().isEmpty());
389-
} catch (MalformedURLException e) {
390-
return BoolT.False;
391-
}
379+
return Types.boolOf(validateURI(addr, false));
392380
});
393381
}
394382

@@ -609,6 +597,25 @@ private static boolean validateIP(String addr, long ver) {
609597
return false;
610598
}
611599

600+
/**
601+
* Validates if the input string is a valid URI, which can be a URL or a URN.
602+
*
603+
* @param val The input string to validate as a URI.
604+
* @param checkAbsolute Whether to check if this URI is absolute (i.e. has a scheme component)
605+
* @return {@code true} if the input string is a valid URI, {@code false} otherwise.
606+
*/
607+
private static boolean validateURI(String val, boolean checkAbsolute) {
608+
try {
609+
URI uri = new URI(val);
610+
if (checkAbsolute) {
611+
return uri.isAbsolute();
612+
}
613+
return true;
614+
} catch (URISyntaxException e) {
615+
return false;
616+
}
617+
}
618+
612619
/**
613620
* Validates if the input string is a valid IP prefix.
614621
*

0 commit comments

Comments
 (0)