mirror of https://github.com/jacekkow/keycloak-protocol-cas

Ricardo Martin
2024-01-09 760bd7b814836fca58922151abe67207cc0db1a2
src/main/java/org/keycloak/protocol/cas/utils/RedirectUtils.java
@@ -73,7 +73,7 @@
                validRedirect = relativeToAbsoluteURI(session, rootUrl, validRedirect);
                logger.debugv("replacing relative valid redirect with: {0}", validRedirect);
            }
            resolveValidRedirects.add(lowerCaseHostname(validRedirect));
            resolveValidRedirects.add(validRedirect);
        }
        return resolveValidRedirects;
    }
@@ -114,7 +114,7 @@
            // Make the validations against fully decoded and normalized redirect-url. This also allows wildcards (case when client configured "Valid redirect-urls" contain wildcards)
            String decodedRedirectUri = decodeRedirectUri(redirectUri);
            URI decodedRedirect = toUri(decodedRedirectUri);
            decodedRedirectUri = getNormalizedRedirectUri(decodedRedirect, true);
            decodedRedirectUri = getNormalizedRedirectUri(decodedRedirect);
            if (decodedRedirectUri == null) return null;
            String r = decodedRedirectUri;
@@ -139,7 +139,7 @@
            }
            // Return the original redirectUri, which can be partially encoded - for example http://localhost:8280/foo/bar%20bar%2092%2F72/3 . Just make sure it is normalized
            redirectUri = getNormalizedRedirectUri(originalRedirect, false);
            redirectUri = getNormalizedRedirectUri(originalRedirect);
            // We try to check validity also for original (encoded) redirectUrl, but just in case it exactly matches some "Valid Redirect URL" specified for client (not wildcards allowed)
            if (valid == null) {
@@ -157,7 +157,7 @@
            String scheme = decodedRedirect.getScheme();
            if (valid != null && scheme != null) {
                // check the scheme is valid, it should be http(s) or explicitly allowed by the validation
                if (!valid.startsWith(scheme.toLowerCase() + ":") && !"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
                if (!valid.startsWith(scheme + ":") && !"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
                    logger.debugf("Invalid URI because scheme is not allowed: %s", redirectUri);
                    valid = null;
                }
@@ -187,18 +187,15 @@
        return uri;
    }
    private static String getNormalizedRedirectUri(URI uri, boolean lower) {
    private static String getNormalizedRedirectUri(URI uri) {
        String redirectUri = null;
        if (uri != null) {
            redirectUri = uri.normalize().toString();
            if (lower) {
                redirectUri = lowerCaseHostname(redirectUri);
            }
        }
        return redirectUri;
    }
    // Decode redirectUri. We don't decode query and fragment as those can be encoded in the original URL.
    // Decode redirectUri. Only path is decoded as other elements can be encoded in the original URL or cannot be encoded at all.
    // URL can be decoded multiple times (in case it was encoded multiple times, or some of it's parts were encoded multiple times)
    private static String decodeRedirectUri(String redirectUri) {
        if (redirectUri == null) return null;
@@ -206,28 +203,20 @@
        try {
            KeycloakUriBuilder uriBuilder = KeycloakUriBuilder.fromUri(redirectUri, false).preserveDefaultPort();
            String origQuery = uriBuilder.getQuery();
            String origFragment = uriBuilder.getFragment();
            String origUserInfo = uriBuilder.getUserInfo();
            String encodedRedirectUri = uriBuilder
                    .replaceQuery(null)
                    .fragment(null)
                    .userInfo(null)
                    .buildAsString();
            String decodedRedirectUri = null;
            if (uriBuilder.getPath() == null) {
                return redirectUri;
            }
            String encodedPath = uriBuilder.getPath();
            String decodedPath;
            for (int i = 0; i < MAX_DECODING_COUNT; i++) {
                decodedRedirectUri = Encode.decode(encodedRedirectUri);
                if (decodedRedirectUri.equals(encodedRedirectUri)) {
                    // URL is decoded. We can return it (after attach original query and fragment)
                    return KeycloakUriBuilder.fromUri(decodedRedirectUri, false).preserveDefaultPort()
                            .replaceQuery(origQuery)
                            .fragment(origFragment)
                            .userInfo(origUserInfo)
                            .buildAsString();
                decodedPath = Encode.decode(encodedPath);
                if (decodedPath.equals(encodedPath)) {
                    // URL path is decoded. We can return it in the original redirect URI
                    return uriBuilder.replacePath(decodedPath, false).buildAsString();
                } else {
                    // Next attempt
                    encodedRedirectUri = decodedRedirectUri;
                    encodedPath = decodedPath;
                }
            }
        } catch (IllegalArgumentException iae) {
@@ -237,18 +226,6 @@
        return null;
    }
    private static String lowerCaseHostname(String redirectUri) {
        // lower case host and scheme which are case-insensitive by spec
        KeycloakUriBuilder uriBuilder = KeycloakUriBuilder.fromUri(redirectUri, false).preserveDefaultPort();
        if (uriBuilder.getScheme() != null) {
            uriBuilder.scheme(uriBuilder.getScheme().toLowerCase());
        }
        if (uriBuilder.getHost() != null) {
            uriBuilder.host(uriBuilder.getHost().toLowerCase());
        }
        return uriBuilder.buildAsString();
    }
    private static String relativeToAbsoluteURI(KeycloakSession session, String rootUrl, String relative) {
        if (rootUrl != null) {
            rootUrl = ResolveRelative.resolveRootUrl(session, rootUrl);
@@ -263,13 +240,24 @@
        return sb.toString();
    }
    // removes the queryString, fragment and userInfo from the redirect
    // to avoid comparing this when wildcards are used
    private static String stripOffRedirectForWildcard(String redirect) {
        return KeycloakUriBuilder.fromUri(redirect, false)
                .preserveDefaultPort()
                .userInfo(null)
                .replaceQuery(null)
                .fragment(null)
                .buildAsString();
    }
    // return the String that matched the redirect or null if not matched
    private static String matchesRedirects(Set<String> validRedirects, String redirect, boolean allowWildcards) {
        logger.tracef("matchesRedirects: redirect URL to check: %s, allow wildcards: %b, Configured valid redirect URLs: %s", redirect, allowWildcards, validRedirects);
        for (String validRedirect : validRedirects) {
            if (validRedirect.endsWith("*") && !validRedirect.contains("?") && allowWildcards) {
                // 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 the userInfo, query or fragment components - we don't check them when wildcards are effective
                String r = stripOffRedirectForWildcard(redirect);
                // strip off *
                int length = validRedirect.length() - 1;
                validRedirect = validRedirect.substring(0, length);