Skip to content

Commit 495ac92

Browse files
Denys Kurylenkocopybara-github
Denys Kurylenko
authored andcommitted
Allow UrlRewriter to change protocol, i.e. https->http, and http->https
Fixes #13114 Closes #13115. PiperOrigin-RevId: 360172767
1 parent 1e258d2 commit 495ac92

File tree

2 files changed

+39
-8
lines changed

2 files changed

+39
-8
lines changed

src/main/java/com/google/devtools/build/lib/bazel/repository/downloader/UrlRewriter.java

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -187,17 +187,24 @@ private ImmutableList<URL> applyRewriteRules(URL url) {
187187
}
188188

189189
return rewrittenUrls.build().stream()
190-
.map(
191-
urlString -> {
192-
try {
193-
return new URL(url.getProtocol() + "://" + urlString);
194-
} catch (MalformedURLException e) {
195-
throw new IllegalStateException(e);
196-
}
197-
})
190+
.map(urlString -> prefixWithProtocol(urlString, url.getProtocol()))
198191
.collect(toImmutableList());
199192
}
200193

194+
/** Prefixes url with protocol if not already prefixed by {@link #REWRITABLE_SCHEMES} */
195+
private static URL prefixWithProtocol(String url, String protocol) {
196+
try {
197+
for (String schemaPrefix : REWRITABLE_SCHEMES) {
198+
if (url.startsWith(schemaPrefix + "://")) {
199+
return new URL(url);
200+
}
201+
}
202+
return new URL(protocol + "://" + url);
203+
} catch (MalformedURLException e) {
204+
throw new IllegalStateException(e);
205+
}
206+
}
207+
201208
@Nullable
202209
public String getAllBlockedMessage() {
203210
return config.getAllBlockedMessage();

src/test/java/com/google/devtools/build/lib/bazel/repository/downloader/UrlRewriterTest.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,4 +212,28 @@ public void multipleAllBlockedMessage() throws Exception {
212212
assertThat(e.getLocation()).isEqualTo(Location.fromFileLineColumn("/some/file", 3, 0));
213213
}
214214
}
215+
216+
@Test
217+
public void rewritingUrlsAllowsProtocolRewrite() throws Exception {
218+
String config =
219+
""
220+
+ "block *\n"
221+
+ "allow mycorp.com\n"
222+
+ "allow othercorp.com\n"
223+
+ "rewrite bad.com/foo/(.*) http://mycorp.com/$1\n"
224+
+ "rewrite bad.com/bar/(.*) https://othercorp.com/bar/$1\n";
225+
226+
UrlRewriter munger = new UrlRewriter(str -> {}, "/dev/null", new StringReader(config));
227+
228+
List<URL> amended =
229+
munger.amend(
230+
ImmutableList.of(
231+
new URL("https://www.bad.com"),
232+
new URL("https://bad.com/foo/bar"),
233+
new URL("http://bad.com/bar/xyz")));
234+
235+
assertThat(amended)
236+
.containsExactly(
237+
new URL("http://mycorp.com/bar"), new URL("https://othercorp.com/bar/xyz"));
238+
}
215239
}

0 commit comments

Comments
 (0)