Skip to content

Commit b9c3f78

Browse files
committed
add new domain validation api
1 parent 806f5d7 commit b9c3f78

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

src/main/java/io/github/pixee/security/HostValidator.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,4 +47,16 @@ public boolean isAllowed(final String host) {
4747
static HostValidator fromAllowedHostPattern(final Pattern allowPattern) {
4848
return new PatternBasedHostValidator(allowPattern);
4949
}
50+
51+
/**
52+
* Return a {@link HostValidator} that will assure a given domain is within the allowed domain. For example, given
53+
* a domain of "good.com", this validator will allow "good.com", "www.good.com", "internal.good.com", etc.
54+
*
55+
* @param domainName the domain to allow, e.g., "good.com", or "internal-host"
56+
* @return a validator that will only allow hosts within the given domain space
57+
*/
58+
static HostValidator fromAllowedHostDomain(final String domainName) {
59+
Pattern p = Pattern.compile("(.*\\." + Pattern.quote(domainName) + "|" + Pattern.quote(domainName) +")");
60+
return new PatternBasedHostValidator(p);
61+
}
5062
}

src/test/java/io/github/pixee/security/UrlsTest.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
import java.net.MalformedURLException;
99
import java.net.URL;
10+
import java.util.List;
1011
import java.util.regex.Pattern;
1112
import java.util.stream.Stream;
1213
import org.junit.jupiter.api.Test;
@@ -138,6 +139,21 @@ void it_disallows_bad_domains() throws MalformedURLException {
138139
() -> {
139140
Urls.create("https://evil.com/", setOf(UrlProtocol.HTTPS), allowsOnlyGoodDotCom);
140141
});
142+
143+
HostValidator allowsOnlyGoodDotComByDomainString = HostValidator.fromAllowedHostDomain("good.com");
144+
Urls.create("https://good.com/", setOf(UrlProtocol.HTTPS), allowsOnlyGoodDotComByDomainString);
145+
Urls.create("https://sub.good.com/", setOf(UrlProtocol.HTTPS), allowsOnlyGoodDotComByDomainString);
146+
Urls.create("https://different-sub-123.good.com/", setOf(UrlProtocol.HTTPS), allowsOnlyGoodDotComByDomainString);
147+
Urls.create("https://.good.com/", setOf(UrlProtocol.HTTPS), allowsOnlyGoodDotComByDomainString);
148+
149+
List.of("https://goodAcom/", "https://evil.com", "https://good.com.evil", "https://good.com.").stream().forEach(badDomain -> {
150+
assertThrows(
151+
SecurityException.class,
152+
() -> {
153+
Urls.create(badDomain, setOf(UrlProtocol.HTTPS), allowsOnlyGoodDotComByDomainString);
154+
});
155+
});
156+
141157
}
142158

143159
@Test

0 commit comments

Comments
 (0)