Skip to content
Closed
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
7 changes: 7 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@
<hamcrest.version>1.3</hamcrest.version>
<jmeter.version>2.10</jmeter.version>
<junit.version>4.12</junit.version>
<mockito.version>1.10.19</mockito.version>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have decided not to use mocking frameworks so we can't accept this

<picketlink.version>2.7.0.Final</picketlink.version>
<selenium.version>2.35.0</selenium.version>
<xml-apis.version>1.4.01</xml-apis.version>
Expand Down Expand Up @@ -419,6 +420,12 @@
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
Expand Down
5 changes: 5 additions & 0 deletions services/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,11 @@
<groupId>com.openshift</groupId>
<artifactId>openshift-restclient-java</artifactId>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,15 @@
import org.keycloak.models.ClientModel;
import org.keycloak.models.Constants;
import org.keycloak.models.RealmModel;
import org.keycloak.protocol.oidc.utils.url.WildcardStringMatches;
import org.keycloak.protocol.oidc.utils.url.WildcardUrlMatches;
import org.keycloak.services.Urls;

import javax.ws.rs.core.UriInfo;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
Expand Down Expand Up @@ -57,11 +61,12 @@ public static Set<String> resolveValidRedirects(UriInfo uriInfo, String rootUrl,
// If the valid redirect URI is relative (no scheme, host, port) then use the request's scheme, host, and port
Set<String> resolveValidRedirects = new HashSet<>();
for (String validRedirect : validRedirects) {
resolveValidRedirects.add(validRedirect); // add even relative urls.
if (validRedirect.startsWith("/")) {
validRedirect = relativeToAbsoluteURI(uriInfo, rootUrl, validRedirect);
logger.debugv("replacing relative valid redirect with: {0}", validRedirect);
resolveValidRedirects.add(validRedirect);
} else { // already full url
resolveValidRedirects.add(validRedirect);
}
}
return resolveValidRedirects;
Expand Down Expand Up @@ -96,6 +101,9 @@ private static String verifyRedirectUri(UriInfo uriInfo, String rootUrl, String
redirectUri = null;
} else {
redirectUri = lowerCaseHostname(redirectUri);
if (redirectUri.startsWith("/")) {
redirectUri = relativeToAbsoluteURI(uriInfo, rootUrl, redirectUri);
}

String r = redirectUri;
Set<String> resolveValidRedirects = resolveValidRedirects(uriInfo, rootUrl, validRedirects);
Expand All @@ -117,9 +125,6 @@ private static String verifyRedirectUri(UriInfo uriInfo, String rootUrl, String

valid = matchesRedirects(resolveValidRedirects, r);
}
if (valid && redirectUri.startsWith("/")) {
redirectUri = relativeToAbsoluteURI(uriInfo, rootUrl, redirectUri);
}
redirectUri = valid ? redirectUri : null;
}

Expand Down Expand Up @@ -149,20 +154,15 @@ private static String relativeToAbsoluteURI(UriInfo uriInfo, String rootUrl, Str
return sb.toString();
}

private static boolean matchesRedirects(Set<String> validRedirects, String redirect) {
for (String validRedirect : validRedirects) {
if (validRedirect.endsWith("*") && !validRedirect.contains("?")) {
// strip off the query component - we don't check them when wildcards are effective
String r = redirect.contains("?") ? redirect.substring(0, redirect.indexOf("?")) : redirect;
// strip off *
int length = validRedirect.length() - 1;
validRedirect = validRedirect.substring(0, length);
if (r.startsWith(validRedirect)) return true;
// strip off trailing '/'
if (length - 1 > 0 && validRedirect.charAt(length - 1) == '/') length--;
validRedirect = validRedirect.substring(0, length);
if (validRedirect.equals(r)) return true;
} else if (validRedirect.equals(redirect)) return true;
private static boolean matchesRedirects(final Set<String> validRedirects, final String requestedRedirect) {
for (final String validRedirect : validRedirects) {
if (validRedirect.equals(requestedRedirect)) {
return true;
} else {
if (new WildcardStringMatches(validRedirect).test(requestedRedirect)) {
return true;
}
}
}
return false;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package org.keycloak.protocol.oidc.utils;

import java.util.function.Function;
import java.util.regex.Pattern;

/**
* Class responsible for taking common wildcard syntax (*), and turning it into Java regex syntax
* <p>
* I.E.
* foo*bar -> ^foo*.bar$
* with-chars-need-escaping -> ^with\-chars\-need\-escaping$
*
* Note, that if null is passed in, it will match NOTHING.
*/
public class Regexify {

public static final String MATCH_ANYTHING_REGEX = "^.*$";
public static final String MATCH_NOTHING_REGEX = "1^";

public static Function<String, String> asString = stringToRegexify -> {
if (stringToRegexify == null) {
return MATCH_NOTHING_REGEX;
}
// Per http://docs.oracle.com/javase/tutorial/essential/regex/literals.html
// the Java regex metachars are: <([{\^-=$!|]})?*+.>
return "^" + stringToRegexify.replaceAll("[\\<\\(\\[\\{\\\\\\^\\-\\=\\$\\!\\|\\]\\}\\)‌​\\?\\+\\.\\>]", "\\\\$0").replaceAll("\\*", ".*") + "$";
};

public static Function<String, Pattern> asPattern = stringToRegexify -> Pattern.compile(asString.apply(stringToRegexify));
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package org.keycloak.protocol.oidc.utils.url;

import java.net.URL;
import java.util.function.Predicate;

/**
* Wrapper class to handle conversion of strings to URLs when attempting to find out what matches. If any problems are encountered
* constructing a URL from the given strings (either in the base case or predicate test case), then result will always be "false".
*
* @see org.keycloak.procotol.oidc.utils.url.WildcardUrlMatches for full description on what will and will not match.
* @see java.net.URL for more info on URL construction
*/
public class WildcardStringMatches implements Predicate<String> {

private Predicate<URL> urlStringMatches;

/**
* @param urlToMatch base case against which tests should be applied. Is allowed to have wildcards in either part of the host name, or the path.
*/
public WildcardStringMatches(final String urlToMatch) {
try {
urlStringMatches = new WildcardUrlMatches(new URL(urlToMatch));
} catch (Exception e) {
urlStringMatches = url -> false;
}
}

@Override
public boolean test(final String matchString) {
try {
return urlStringMatches.test(new URL(matchString));
} catch (Exception e) {
return false;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package org.keycloak.protocol.oidc.utils.url;

import org.keycloak.protocol.oidc.utils.Regexify;

import java.net.URL;
import java.util.Optional;
import java.util.function.Predicate;

/**
* Attempts to determine whether the given wildcard url string matches an input string assumed to be a normal url. Note that
* this *only* currently evaluates protocol, host, port, and path. Query parameters and fragments are not evaluated.
*
* E.X.
* new WildcardUrlStringMatch(http://www.redhat.com/*).test("http://www.redhat.com/foo.html?lang=en) = true
*/
public class WildcardUrlMatches implements Predicate<URL> {

public static final String MATCH_ANYTHING_REGEX = "^.*$";
private final URL baseCaseWithWildcards;

public WildcardUrlMatches(final URL baseCaseWithWildcards) {
this.baseCaseWithWildcards = baseCaseWithWildcards;
}

@Override
public boolean test(final URL regularUrlString) {

// first check on the protocol, host, and port
boolean matches = regularUrlString.getProtocol().matches(Regexify.asString.apply(baseCaseWithWildcards.getProtocol())) &&
regularUrlString.getHost().matches(Regexify.asString.apply(baseCaseWithWildcards.getHost())) &&
String.valueOf(regularUrlString.getPort()).matches(Regexify.asString.apply(String.valueOf(baseCaseWithWildcards.getPort())));

// Special Snowflake Case = when the path ends in 'foo/*', then 'foo' must also be accepted as valid
final String wildcardPathString = Optional.ofNullable(baseCaseWithWildcards.getPath()).orElse("");
final boolean specialSnowflakeCase = wildcardPathString.endsWith("/*");
if (matches) {
final String regularUrlPathString = Optional.ofNullable(regularUrlString.getPath()).orElse("");
matches = regularUrlPathString.matches(Regexify.asString.apply(wildcardPathString)) ||
(specialSnowflakeCase && regularUrlPathString.matches(Regexify.asString.apply(wildcardPathString.substring(0, wildcardPathString.length() - 2))));
}

// Now perform a naive check on the query params (if applicable)
if (matches && !specialSnowflakeCase) {
matches = Optional.ofNullable(regularUrlString.getQuery()).orElse("").equals(Optional.ofNullable(baseCaseWithWildcards.getQuery()).orElse(""));
}

return matches;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
package org.keycloak.protocol.oidc.utils;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Look at OAuthRedirectUriTest which can be extended to cover these tests properly


import org.jboss.resteasy.spi.ResteasyUriInfo;
import org.junit.Before;
import org.junit.Test;
import org.keycloak.models.ClientModel;
import org.keycloak.models.RealmModel;
import org.mockito.Mock;

import javax.ws.rs.core.UriInfo;
import java.net.URI;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;

public class RedirectUtilsTest {

@Mock
ClientModel client;
@Mock
RealmModel realm;
private Set<String> validRedirects;
private UriInfo uriInfo;

@Before
public void setUp() throws Exception {
initMocks(this);

validRedirects = new HashSet<>(Arrays.asList(
"http://example.com",
"http://with-dash.example.com/*",
"http://sub.domain.example.com/foo",
"http://localhost:8180/*",
"http://*.subwildcard.example.com"));
uriInfo = new ResteasyUriInfo(new URI("http://localhost:8180/auth/realms/test/protocol/openid-connect/auth"));

when(realm.getName()).thenReturn("test-realm");
when(client.getRedirectUris()).thenReturn(validRedirects);
}

@Test
public void shouldReturnNull_whenNoRedirectUriInput() throws Exception {
assertThat(RedirectUtils.verifyRedirectUri(uriInfo, null, realm, client), nullValue());
}

@Test
public void shouldReturnNull_whenNoValidRedirectUrisSpecified() throws Exception {
when(client.getRedirectUris()).thenReturn(Collections.EMPTY_SET);
assertThat(RedirectUtils.verifyRedirectUri(uriInfo, "http://localhost:8180/", realm, client), nullValue());
}

@Test
public void shouldReturnNull_whenPortNumberIncorrect() throws Exception {
assertThat(RedirectUtils.verifyRedirectUri(uriInfo, "http://localhost:8181/", realm, client), nullValue());
}

@Test
public void shouldReturnNull_whenNewPortAddedToHostname() throws Exception {
assertThat(RedirectUtils.verifyRedirectUri(uriInfo, "http://with-dash.example.com:8080", realm, client), nullValue());
}

@Test
public void shouldReturnRequestedRedirect_withDash() throws Exception {
assertThat(RedirectUtils.verifyRedirectUri(uriInfo, "http://with-dash.example.com", realm, client),
equalTo("http://with-dash.example.com"));
}

@Test
public void shouldReturnRequestedRedirect_withQueryParams() throws Exception {
assertThat(RedirectUtils.verifyRedirectUri(uriInfo, "http://with-dash.example.com/return?key=value/", realm, client),
equalTo("http://with-dash.example.com/return?key=value/"));
assertThat(RedirectUtils.verifyRedirectUri(uriInfo, "http://with-dash.example.com/return?key", realm, client),
equalTo("http://with-dash.example.com/return?key"));
assertThat(RedirectUtils.verifyRedirectUri(uriInfo, "http://with-dash.example.com/return?key&otherKey=otherValue", realm, client),
equalTo("http://with-dash.example.com/return?key&otherKey=otherValue"));
assertThat(RedirectUtils.verifyRedirectUri(uriInfo, "http://with-dash.example.com/return?key&otherKey", realm, client),
equalTo("http://with-dash.example.com/return?key&otherKey"));
}

@Test
public void shouldReturnRequestedRedirect_forVariousPathsAfterWildcard() throws Exception {
assertThat(RedirectUtils.verifyRedirectUri(uriInfo, "http://with-dash.example.com/somepath", realm, client),
equalTo("http://with-dash.example.com/somepath"));
assertThat(RedirectUtils.verifyRedirectUri(uriInfo, "http://with-dash.example.com/somepath/with/long/path", realm, client),
equalTo("http://with-dash.example.com/somepath/with/long/path"));
assertThat(RedirectUtils.verifyRedirectUri(uriInfo, "http://localhost:8180/somepath/with/long/path", realm, client),
equalTo("http://localhost:8180/somepath/with/long/path"));
}

@Test
public void shouldReturnRequestedRedirect_whenDifferentCasedHostnameGiven() throws Exception {
assertThat(RedirectUtils.verifyRedirectUri(uriInfo, "http://wItH-DaSh.example.com", realm, client),
equalTo("http://with-dash.example.com"));
assertThat(RedirectUtils.verifyRedirectUri(uriInfo, "hTTP://wItH-DaSh.example.com", realm, client),
equalTo("http://with-dash.example.com"));
assertThat(RedirectUtils.verifyRedirectUri(uriInfo, "httP://sub.dOMAIn.example.com/foo", realm, client),
equalTo("http://sub.domain.example.com/foo"));
}

@Test
public void shouldReturnRequestedRedirect_forWildcardedSubdomain() throws Exception {
assertThat(RedirectUtils.verifyRedirectUri(uriInfo, "http://dev1.subwildcard.example.com", realm, client),
equalTo("http://dev1.subwildcard.example.com"));
}

@Test
public void shouldReturnRequestedRedirect_forRelativeDomain() throws Exception {
assertThat(RedirectUtils.verifyRedirectUri(uriInfo, "/client1/landing", realm, client), equalTo("http://localhost:8180/client1/landing"));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package org.keycloak.protocol.oidc.utils;

import org.junit.Test;

import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;

public class RegexifyTest {

@Test
public void testToRegexString_null() {
assertThat(Regexify.asString.apply(null), equalTo(Regexify.MATCH_NOTHING_REGEX));
}

@Test
public void testToRegexString_empty() {
assertThat(Regexify.asString.apply(""), equalTo("^$"));
}

@Test
public void testToRegexString_basic() {
assertThat(Regexify.asString.apply("http://"), equalTo("^http://$"));
}

@Test
public void testToRegexString_wildcardStart() {
assertThat(Regexify.asString.apply("*tp://"), equalTo("^.*tp://$"));
}

@Test
public void testToRegexString_wildcardEnd() {
assertThat(Regexify.asString.apply("http*://"), equalTo("^http.*://$"));
}

@Test
public void testToRegexString_escapeMetachars() {
assertThat(Regexify.asString.apply("with-dash.example.com"), equalTo("^with\\-dash\\.example\\.com$"));
}

@Test
public void testToRegexString_escapeMetacharsWithWidlcard() {
assertThat(Regexify.asString.apply("dev.*.example.com"), equalTo("^dev\\..*\\.example\\.com$"));
}

}
Loading