Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow UrlRewriter to change protocol, i.e. https->http, and http->https #13115

Closed
wants to merge 1 commit into from
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
Original file line number Diff line number Diff line change
Expand Up @@ -187,17 +187,26 @@ private ImmutableList<URL> applyRewriteRules(URL url) {
}

return rewrittenUrls.build().stream()
.map(
urlString -> {
try {
return new URL(url.getProtocol() + "://" + urlString);
} catch (MalformedURLException e) {
throw new IllegalStateException(e);
}
})
.map(urlString -> prefixWithProtocol(urlString, url.getProtocol()))
.collect(toImmutableList());
}

/**
* Prefixes url with protocol if not already prefixed by {@link #REWRITABLE_SCHEMES}
*/
private static URL prefixWithProtocol(String url, String protocol) {
try {
for (String schemaPrefix : REWRITABLE_SCHEMES) {
if (url.startsWith(schemaPrefix + "://")) {
return new URL(url);
}
}
return new URL(protocol + "://" + url);
} catch (MalformedURLException e) {
throw new IllegalStateException(e);
}
}

@Nullable
public String getAllBlockedMessage() {
return config.getAllBlockedMessage();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -212,4 +212,25 @@ public void multipleAllBlockedMessage() throws Exception {
assertThat(e.getLocation()).isEqualTo(Location.fromFileLineColumn("/some/file", 3, 0));
}
}

@Test
public void rewritingUrlsAllowsProtocolRewrite() throws Exception {
String config =
""
+ "block *\n"
+ "allow mycorp.com\n"
+ "allow othercorp.com\n"
+ "rewrite bad.com/foo/(.*) http://mycorp.com/$1\n"
+ "rewrite bad.com/bar/(.*) https://othercorp.com/bar/$1\n";

UrlRewriter munger = new UrlRewriter(str -> {}, "/dev/null", new StringReader(config));

List<URL> amended =
munger.amend(
ImmutableList.of(new URL("https://www.bad.com"), new URL("https://bad.com/foo/bar"),
new URL("http://bad.com/bar/xyz")));

assertThat(amended).containsExactly(new URL("http://mycorp.com/bar"),
new URL("https://othercorp.com/bar/xyz"));
}
}