From 8d75924c138f43b40c9d9a0d91962117b1a93f1f Mon Sep 17 00:00:00 2001 From: Victor Colin Amador Date: Fri, 20 Nov 2026 01:36:46 -0800 Subject: [PATCH 1/2] Fix non-proxy hosts matching unintended hosts --- sdk/clientcore/core/CHANGELOG.md | 7 ++ .../core/http/models/ProxyOptions.java | 93 ++++++++++--------- .../core/http/models/ProxyOptionsTests.java | 55 +++++++++++ sdk/core/azure-core-http-vertx/CHANGELOG.md | 4 + .../core/http/vertx/VertxHttpClient.java | 39 +++++++- .../http/vertx/VertxHttpClientBuilder.java | 40 ++------ .../vertx/VertxHttpClientBuilderTests.java | 72 +++++++++++++- .../vertx/VertxHttpClientProviderTests.java | 47 +++++++--- sdk/core/azure-core/CHANGELOG.md | 7 ++ .../com/azure/core/http/ProxyOptions.java | 93 ++++++++++--------- .../azure/core/http/ProxyOptionsTests.java | 55 +++++++++++ 11 files changed, 372 insertions(+), 140 deletions(-) diff --git a/sdk/clientcore/core/CHANGELOG.md b/sdk/clientcore/core/CHANGELOG.md index 97e244bcd44e4..6524e0518a857 100644 --- a/sdk/clientcore/core/CHANGELOG.md +++ b/sdk/clientcore/core/CHANGELOG.md @@ -19,6 +19,13 @@ - Fixed HTTP timeout resolution to prefer explicit builder values, then builder-specific configuration, then global configuration, and finally SDK defaults. Global timeouts are resolved when needed rather than cached at class initialization. Nonpositive JDK HTTP timeouts now disable the timeout, including the connection timeout. +- Fixed suffix wildcards in `ProxyOptions` non-proxy hosts removing the character before the wildcard, so `storage1*` + matched `storage2.example.com` and `10.*` matched `100.64.0.1`. This affected `setNonProxyHosts` as well as + `http.nonProxyHosts`, `http.proxy.non-proxy-hosts`, and `NO_PROXY`. Entries such as `.*` no longer throw + `StringIndexOutOfBoundsException`. ([#51341](https://github.com/Azure/azure-sdk-for-java/issues/51341)) +- Fixed `ProxyOptions` non-proxy hosts with a leading or trailing dot, or a bracketed IPv6 address, matching other + hosts. `.example.com` now matches `example.com` and its subdomains but not `badexample.com`, `192.168.` no longer + matches `192.1689.0.1`, and `[::1]` is matched literally instead of as a regex character class. ### Other Changes diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/ProxyOptions.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/ProxyOptions.java index ad290e1e2243f..149b031c76e15 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/ProxyOptions.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/ProxyOptions.java @@ -66,6 +66,7 @@ public final class ProxyOptions { private static final Pattern UNESCAPED_PERIOD = Pattern.compile("(? * The expected format of the passed string is a {@code '|'} delimited list of hosts which should bypass the proxy. - * Individual host strings may contain regex characters such as {@code '*'}. + * In each host, {@code '*'} is a wildcard and {@code '.'} is a literal dot. Other regex characters, such as + * character classes, keep their regex meaning. For example: + * * * @param nonProxyHosts Hosts that bypass the proxy. * @return the updated ProxyOptions object @@ -412,69 +421,63 @@ private static String sanitizeNonProxyHosts(String[] nonProxyHosts) { String sanitizedNonProxyHost = nonProxyHosts[i]; /* - * If the non-proxy host begins with either '.', '*', '.*', or any of the previous with a trailing '?' - * substring the non-proxy host and set the wildcard prefix. + * If the non-proxy host begins with '*', '.*', or either with a trailing '?', it matches any prefix. If it + * begins with '.', or '.?', it matches the domain and its subdomains, so '.example.com' matches + * 'example.com' and 'api.example.com' but not 'badexample.com'. */ - if (sanitizedNonProxyHost.startsWith(".")) { + if (sanitizedNonProxyHost.startsWith(".*?")) { prefixWildcard = ".*?"; - sanitizedNonProxyHost = sanitizedNonProxyHost.substring(1); - } else if (sanitizedNonProxyHost.startsWith(".?")) { - prefixWildcard = ".*?"; - sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2); - } else if (sanitizedNonProxyHost.startsWith("*?")) { + sanitizedNonProxyHost = sanitizedNonProxyHost.substring(3); + } else if (sanitizedNonProxyHost.startsWith(".*") || sanitizedNonProxyHost.startsWith("*?")) { prefixWildcard = ".*?"; sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2); } else if (sanitizedNonProxyHost.startsWith("*")) { prefixWildcard = ".*?"; sanitizedNonProxyHost = sanitizedNonProxyHost.substring(1); - } else if (sanitizedNonProxyHost.startsWith(".*?")) { - prefixWildcard = ".*?"; - sanitizedNonProxyHost = sanitizedNonProxyHost.substring(3); - } else if (sanitizedNonProxyHost.startsWith(".*")) { - prefixWildcard = ".*?"; + } else if (sanitizedNonProxyHost.startsWith(".?")) { + prefixWildcard = "(?:.*?\\.)?"; sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2); + } else if (sanitizedNonProxyHost.startsWith(".")) { + prefixWildcard = "(?:.*?\\.)?"; + sanitizedNonProxyHost = sanitizedNonProxyHost.substring(1); } /* - * Same with the ending of the non-proxy host, if it has a suffix wildcard trim the non-proxy host and - * retain the suffix wildcard. + * If the non-proxy host ends with '*', '.', or either with a trailing '?', it matches any suffix. Only the + * '*' and '?' are trimmed. A '.' is a literal dot, so '10.*' matches '10.0.0.1' but not '100.64.0.1', and + * '192.168.' matches '192.168.0.1' but not '192.1689.0.1'. */ - if (sanitizedNonProxyHost.endsWith(".")) { - suffixWildcard = ".*?"; - sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 2); - } else if (sanitizedNonProxyHost.endsWith(".?")) { - suffixWildcard = ".*?"; - sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 3); - } else if (sanitizedNonProxyHost.endsWith("*?")) { - suffixWildcard = ".*?"; - sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 3); - } else if (sanitizedNonProxyHost.endsWith("*")) { + if (sanitizedNonProxyHost.endsWith("*?")) { suffixWildcard = ".*?"; sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 2); - } else if (sanitizedNonProxyHost.endsWith(".*?")) { + } else if (sanitizedNonProxyHost.endsWith("*") || sanitizedNonProxyHost.endsWith(".?")) { suffixWildcard = ".*?"; - sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 4); - } else if (sanitizedNonProxyHost.endsWith(".*")) { + sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 1); + } else if (sanitizedNonProxyHost.endsWith(".")) { suffixWildcard = ".*?"; - sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 3); } - try { - // Sanitize the non-proxy host before any appending to prevent errant characters being added to the - // final response if the non-proxy host isn't a valid Pattern. - String attemptToSanitizeAsRegex = sanitizedNonProxyHost; - attemptToSanitizeAsRegex = UNESCAPED_PERIOD.matcher(attemptToSanitizeAsRegex).replaceAll("\\\\."); - attemptToSanitizeAsRegex = ANY.matcher(attemptToSanitizeAsRegex).replaceAll("\\.*?"); - sanitizedNonProxyHost = Pattern.compile(attemptToSanitizeAsRegex).pattern(); - } catch (PatternSyntaxException ex) { - /* - * Replace the non-proxy host with the sanitized value. - * - * The body of the non-proxy host is quoted to handle scenarios such a '127.0.0.1' or '*.somecloud.com' - * where without quoting the '.' in the string would be treated as the match any character instead of - * the literal '.' character. - */ + if (BRACKETED_IPV6_LITERAL.matcher(sanitizedNonProxyHost).matches()) { + // Match IPv6 literals such as '[::1]' as-is. As a regex, the brackets would be a character class. sanitizedNonProxyHost = Pattern.quote(sanitizedNonProxyHost); + } else { + try { + // Sanitize the non-proxy host before any appending to prevent errant characters being added to + // the final response if the non-proxy host isn't a valid Pattern. + String attemptToSanitizeAsRegex = sanitizedNonProxyHost; + attemptToSanitizeAsRegex = UNESCAPED_PERIOD.matcher(attemptToSanitizeAsRegex).replaceAll("\\\\."); + attemptToSanitizeAsRegex = ANY.matcher(attemptToSanitizeAsRegex).replaceAll("\\.*?"); + sanitizedNonProxyHost = Pattern.compile(attemptToSanitizeAsRegex).pattern(); + } catch (PatternSyntaxException ex) { + /* + * Replace the non-proxy host with the sanitized value. + * + * The body of the non-proxy host is quoted to handle scenarios such a '127.0.0.1' or + * '*.somecloud.com' where without quoting the '.' in the string would be treated as the match any + * character instead of the literal '.' character. + */ + sanitizedNonProxyHost = Pattern.quote(sanitizedNonProxyHost); + } } sanitizedBuilder.append("(") diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/ProxyOptionsTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/ProxyOptionsTests.java index 9617412cd76d5..ac6cfc2448590 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/ProxyOptionsTests.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/ProxyOptionsTests.java @@ -18,6 +18,8 @@ import java.net.InetSocketAddress; import java.net.Proxy; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.regex.Pattern; import java.util.stream.Stream; @@ -485,6 +487,59 @@ public void sanitizeJavaHttpNonProxyHostsDoesNotSplitEscapedPipes() { assertEquals("(" + nonProxyHosts + ")", ProxyOptions.sanitizeNoProxy(nonProxyHosts)); } + /** + * Tests that wildcards, leading and trailing dots, and IPv6 literals in non-proxy hosts only match the intended + * hosts, however the non-proxy hosts are configured. Hosts are matched the way HTTP clients match them: the whole + * host, ignoring case. + */ + @ParameterizedTest + @MethodSource("nonProxyHostsMatchOnlyIntendedHostsSupplier") + public void nonProxyHostsMatchOnlyIntendedHosts(String nonProxyHost, List bypassedHosts, + List proxiedHosts) { + String[] sanitizedNonProxyHosts = { + new ProxyOptions(ProxyOptions.Type.HTTP, InetSocketAddress.createUnresolved("localhost", 7777)) + .setNonProxyHosts(nonProxyHost) + .getNonProxyHosts(), + fromConfiguration(createJavaEnvConfiguration(443, null, null, nonProxyHost, true), true).getNonProxyHosts(), + fromConfiguration(createExplicitConfiguration(443, null, null, nonProxyHost), true).getNonProxyHosts(), + fromConfiguration(setJavaSystemProxyPrerequisiteToTrue("http://localhost:7777", nonProxyHost, true), true) + .getNonProxyHosts() }; + + for (String sanitizedNonProxyHost : sanitizedNonProxyHosts) { + Pattern pattern = compile(sanitizedNonProxyHost, Pattern.CASE_INSENSITIVE); + + for (String host : bypassedHosts) { + assertTrue(pattern.matcher(host).matches(), () -> String + .format("Expected '%s' (Pattern '%s') to match '%s'.", nonProxyHost, pattern.pattern(), host)); + } + + for (String host : proxiedHosts) { + assertFalse(pattern.matcher(host).matches(), () -> String + .format("Expected '%s' (Pattern '%s') not to match '%s'.", nonProxyHost, pattern.pattern(), host)); + } + } + } + + private static Stream nonProxyHostsMatchOnlyIntendedHostsSupplier() { + List anyHost = Arrays.asList("example.com", "10.0.0.1", "[::1]"); + + return Stream.of( + Arguments.of("storage1*", Arrays.asList("storage1.example.com"), Arrays.asList("storage2.example.com")), + Arguments.of("storage1*?", Arrays.asList("storage1.example.com"), Arrays.asList("storage2.example.com")), + Arguments.of("storage1.?", Arrays.asList("storage1.example.com"), Arrays.asList("storage2.example.com")), + Arguments.of("storage1.*", Arrays.asList("storage1.example.com"), + Arrays.asList("storage1other.example.com")), + Arguments.of("10.*", Arrays.asList("10.0.0.1"), Arrays.asList("100.64.0.1")), + Arguments.of("192.168.", Arrays.asList("192.168.0.1"), Arrays.asList("192.16.0.1", "192.1689.0.1")), + Arguments.of(".example.com", Arrays.asList("example.com", "api.example.com"), + Arrays.asList("badexample.com")), + Arguments.of("[::1]", Arrays.asList("[::1]"), Arrays.asList("1")), + Arguments.of("[2001:db8::1]*", Arrays.asList("[2001:db8::1]"), Arrays.asList("2evil.example.com")), + Arguments.of(".*", anyHost, Collections.emptyList()), Arguments.of("*", anyHost, Collections.emptyList()), + Arguments.of("*?", anyHost, Collections.emptyList()), + Arguments.of(".*?", anyHost, Collections.emptyList())); + } + private static Configuration setJavaSystemProxyPrerequisiteToTrue(String proxy, String nonProxyHosts, boolean isHttps) { TestConfigurationSource testSource = new TestConfigurationSource().put(JAVA_SYSTEM_PROXY_PREREQUISITE, "true") diff --git a/sdk/core/azure-core-http-vertx/CHANGELOG.md b/sdk/core/azure-core-http-vertx/CHANGELOG.md index 451bf777b2921..4a0a6e574fcfd 100644 --- a/sdk/core/azure-core-http-vertx/CHANGELOG.md +++ b/sdk/core/azure-core-http-vertx/CHANGELOG.md @@ -15,6 +15,10 @@ - Fixed the `Expect: 100-continue` fallback wait starting before the request headers were written. Time the headers spent reaching the wire, such as on the first request in a JVM, shortened the wait for `100 Continue` and could cause the body to be sent before the service had a chance to answer. +- Fixed `ProxyOptions` non-proxy hosts being converted to Vert.x's non-proxy host list, which bypassed the proxy for + the wrong hosts. For example, `10.*` bypassed the proxy for `100.64.0.1`, and entries without a wildcard were + compared case-sensitively. Non-proxy hosts are now matched the same way as in the other HTTP clients, and the proxy + is set on each request to a host that doesn't match them. ### Other Changes diff --git a/sdk/core/azure-core-http-vertx/src/main/java/com/azure/core/http/vertx/VertxHttpClient.java b/sdk/core/azure-core-http-vertx/src/main/java/com/azure/core/http/vertx/VertxHttpClient.java index ac6546901627e..2d36a904af8a1 100644 --- a/sdk/core/azure-core-http-vertx/src/main/java/com/azure/core/http/vertx/VertxHttpClient.java +++ b/sdk/core/azure-core-http-vertx/src/main/java/com/azure/core/http/vertx/VertxHttpClient.java @@ -55,6 +55,7 @@ import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; +import java.util.regex.Pattern; import static com.azure.core.http.vertx.implementation.VertxUtils.resetRequest; @@ -90,6 +91,8 @@ class VertxHttpClient implements HttpClient { final io.vertx.core.http.HttpClient client; final HttpClientOptions buildOptions; + private final io.vertx.core.net.ProxyOptions proxyOptions; + private final Pattern nonProxyHosts; private final Duration responseTimeout; private final Duration writeTimeout; private final ScheduledExecutorService writeTimeoutExecutor; @@ -101,12 +104,18 @@ class VertxHttpClient implements HttpClient { * @param client The Vert.x {@link io.vertx.core.http.HttpClient} */ VertxHttpClient(io.vertx.core.http.HttpClient client, HttpClientOptions buildOptions, Duration responseTimeout) { - this(client, buildOptions, responseTimeout, Duration.ZERO); + this(client, buildOptions, null, null, responseTimeout, Duration.ZERO); } - VertxHttpClient(io.vertx.core.http.HttpClient client, HttpClientOptions buildOptions, Duration responseTimeout, + /* + * proxyOptions is set on each request whose host doesn't match nonProxyHosts. When it's null, requests use the + * proxy configured in buildOptions, if any. + */ + VertxHttpClient(io.vertx.core.http.HttpClient client, HttpClientOptions buildOptions, + io.vertx.core.net.ProxyOptions proxyOptions, Pattern nonProxyHosts, Duration responseTimeout, Duration writeTimeout) { - this(client, buildOptions, responseTimeout, writeTimeout, SharedExecutorService.getInstance()); + this(client, buildOptions, proxyOptions, nonProxyHosts, responseTimeout, writeTimeout, + SharedExecutorService.getInstance(), EXPECT_CONTINUE_TIMEOUT); } VertxHttpClient(io.vertx.core.http.HttpClient client, HttpClientOptions buildOptions, Duration responseTimeout, @@ -116,9 +125,18 @@ class VertxHttpClient implements HttpClient { // Visible for testing, so tests can make the body follow 100 Continue regardless of how slow the agent is. VertxHttpClient(io.vertx.core.http.HttpClient client, HttpClientOptions buildOptions, Duration responseTimeout, + Duration writeTimeout, ScheduledExecutorService writeTimeoutExecutor, Duration expectContinueTimeout) { + this(client, buildOptions, null, null, responseTimeout, writeTimeout, writeTimeoutExecutor, + expectContinueTimeout); + } + + private VertxHttpClient(io.vertx.core.http.HttpClient client, HttpClientOptions buildOptions, + io.vertx.core.net.ProxyOptions proxyOptions, Pattern nonProxyHosts, Duration responseTimeout, Duration writeTimeout, ScheduledExecutorService writeTimeoutExecutor, Duration expectContinueTimeout) { this.client = Objects.requireNonNull(client, "client cannot be null"); this.buildOptions = buildOptions; + this.proxyOptions = proxyOptions; + this.nonProxyHosts = nonProxyHosts; this.responseTimeout = responseTimeout; this.writeTimeout = writeTimeout; this.writeTimeoutExecutor = Objects.requireNonNull(writeTimeoutExecutor, "writeTimeoutExecutor cannot be null"); @@ -171,7 +189,8 @@ private CompletableFuture sendInternal(HttpRequest request, Contex ProgressReporter progressReporter = Contexts.with(context).getHttpRequestProgressReporter(); RequestOptions options = new RequestOptions().setMethod(HttpMethod.valueOf(request.getHttpMethod().name())) - .setAbsoluteURI(request.getUrl()); + .setAbsoluteURI(request.getUrl()) + .setProxyOptions(getProxyOptions(request.getUrl().getHost())); // This is the shared design for sending a request and receiving a response in Vert.x. The design relies on // using a Vert.x Promise and the handler methods to control the flow of the request-response cycle. The Promise @@ -269,6 +288,18 @@ private CompletableFuture sendInternal(HttpRequest request, Contex return requestFuture; } + /* + * Gets the proxy for a request to the host, or null to use the proxy configured in buildOptions, if any. Hosts are + * matched the same way as the other HTTP clients: the whole host, ignoring case. + */ + io.vertx.core.net.ProxyOptions getProxyOptions(String host) { + if (proxyOptions == null || (nonProxyHosts != null && nonProxyHosts.matcher(host).matches())) { + return null; + } + + return proxyOptions; + } + private void sendBody(ContextView contextView, HttpRequest azureRequest, ProgressReporter progressReporter, HttpClientRequest vertxRequest, Promise promise, WriteTimeout writeWatcher) { BinaryData body = azureRequest.getBodyAsBinaryData(); diff --git a/sdk/core/azure-core-http-vertx/src/main/java/com/azure/core/http/vertx/VertxHttpClientBuilder.java b/sdk/core/azure-core-http-vertx/src/main/java/com/azure/core/http/vertx/VertxHttpClientBuilder.java index 6efc28ae64066..0e349ad4abdb5 100644 --- a/sdk/core/azure-core-http-vertx/src/main/java/com/azure/core/http/vertx/VertxHttpClientBuilder.java +++ b/sdk/core/azure-core-http-vertx/src/main/java/com/azure/core/http/vertx/VertxHttpClientBuilder.java @@ -43,10 +43,6 @@ */ public class VertxHttpClientBuilder { private static final ClientLogger LOGGER = new ClientLogger(VertxHttpClientBuilder.class); - private static final Pattern NON_PROXY_HOSTS_SPLIT = Pattern.compile("(? VERTX_HTTP_CLIENT_FACTORY; static { @@ -271,6 +267,8 @@ public HttpClient build() { } HttpClientOptions buildOptions = this.httpClientOptions; + io.vertx.core.net.ProxyOptions vertxProxyOptions = null; + Pattern nonProxyHostsPattern = null; Duration writeTimeout = Duration.ZERO; if (buildOptions == null) { writeTimeout = getTimeout(this.writeTimeout, configuration, PROPERTY_AZURE_REQUEST_WRITE_TIMEOUT, @@ -291,7 +289,7 @@ public HttpClient build() { = (proxyOptions == null) ? ProxyOptions.fromConfiguration(buildConfiguration, true) : proxyOptions; if (buildProxyOptions != null) { - io.vertx.core.net.ProxyOptions vertxProxyOptions = new io.vertx.core.net.ProxyOptions(); + vertxProxyOptions = new io.vertx.core.net.ProxyOptions(); InetSocketAddress proxyAddress = buildProxyOptions.getAddress(); if (proxyAddress != null) { @@ -317,14 +315,12 @@ public HttpClient build() { } } + // Vert.x can't match the non-proxy hosts regex, and a request can't opt out of a proxy set on + // HttpClientOptions. Instead, VertxHttpClient sets the proxy on each request whose host doesn't match. String nonProxyHosts = buildProxyOptions.getNonProxyHosts(); if (!CoreUtils.isNullOrEmpty(nonProxyHosts)) { - for (String nonProxyHost : removeNonProxyHostsSanitation(nonProxyHosts)) { - buildOptions.addNonProxyHost(nonProxyHost); - } + nonProxyHostsPattern = Pattern.compile(nonProxyHosts, Pattern.CASE_INSENSITIVE); } - - buildOptions.setProxyOptions(vertxProxyOptions); } } @@ -342,8 +338,10 @@ public HttpClient build() { } io.vertx.core.http.HttpClient client = VERTX_HTTP_CLIENT_FACTORY.apply(configuredVertx, buildOptions); - return new VertxHttpClient(client, buildOptions, getTimeout(this.responseTimeout, configuration, - PROPERTY_AZURE_REQUEST_RESPONSE_TIMEOUT, DEFAULT_RESPONSE_TIMEOUT), writeTimeout); + return new VertxHttpClient(client, buildOptions, vertxProxyOptions, nonProxyHostsPattern, + getTimeout(this.responseTimeout, configuration, PROPERTY_AZURE_REQUEST_RESPONSE_TIMEOUT, + DEFAULT_RESPONSE_TIMEOUT), + writeTimeout); } static Vertx getVertx(Iterator iterator) { @@ -365,24 +363,6 @@ static Vertx getVertx(Iterator iterator) { return configuredVertx; } - /** - * Reverses non-proxy host string sanitization applied by {@link ProxyOptions}. - *

- * This is necessary as Vert.x will apply its own sanitization logic. - * - * @param nonProxyHosts The list of non-proxy hosts - * @return String array of proxy host strings without sanitation. - */ - private String[] removeNonProxyHostsSanitation(String nonProxyHosts) { - String nonProxyHostsSanitationRemoved - = NON_PROXY_HOST_REMOVE_SANITIZATION.matcher(nonProxyHosts).replaceAll(""); - - nonProxyHostsSanitationRemoved - = NON_PROXY_HOST_DOT_STAR.matcher(nonProxyHostsSanitationRemoved).replaceAll("*"); - - return NON_PROXY_HOSTS_SPLIT.split(nonProxyHostsSanitationRemoved); - } - // Enum Singleton Pattern private enum DefaultVertx { DEFAULT_VERTX(Vertx.vertx()); diff --git a/sdk/core/azure-core-http-vertx/src/test/java/com/azure/core/http/vertx/VertxHttpClientBuilderTests.java b/sdk/core/azure-core-http-vertx/src/test/java/com/azure/core/http/vertx/VertxHttpClientBuilderTests.java index 888061f19ce26..fd801ff0af978 100644 --- a/sdk/core/azure-core-http-vertx/src/test/java/com/azure/core/http/vertx/VertxHttpClientBuilderTests.java +++ b/sdk/core/azure-core-http-vertx/src/test/java/com/azure/core/http/vertx/VertxHttpClientBuilderTests.java @@ -19,12 +19,15 @@ import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.ValueSource; import reactor.test.StepVerifier; +import java.io.IOException; import java.net.ConnectException; import java.net.InetSocketAddress; +import java.net.ServerSocket; import java.time.Duration; import java.util.Arrays; import java.util.Collections; @@ -38,6 +41,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -217,7 +221,11 @@ public void buildWithAllProxyTypes(ProxyOptions.Type type) throws Exception { VertxHttpClient httpClient = (VertxHttpClient) new VertxHttpClientBuilder().proxy(proxyOptions).build(); - io.vertx.core.net.ProxyOptions vertxProxyOptions = httpClient.buildOptions.getProxyOptions(); + // The proxy is set on each request whose host isn't a non-proxy host, not on the Vert.x options. + assertNull(httpClient.buildOptions.getProxyOptions()); + assertNull(httpClient.getProxyOptions("microsoft.com")); + + io.vertx.core.net.ProxyOptions vertxProxyOptions = httpClient.getProxyOptions("example.com"); assertNotNull(vertxProxyOptions); assertEquals(address.getHostName(), vertxProxyOptions.getHost()); assertEquals(address.getPort(), vertxProxyOptions.getPort()); @@ -226,6 +234,68 @@ public void buildWithAllProxyTypes(ProxyOptions.Type type) throws Exception { assertEquals(proxyPassword, vertxProxyOptions.getPassword()); } + /** + * Tests that the proxy is only skipped for request hosts matching the non-proxy hosts. They're matched like in the + * other HTTP clients, rather than by Vert.x, which matched '10.*' with '100.64.0.1' and compared hosts without + * wildcards case-sensitively. + */ + @ParameterizedTest + @CsvSource({ + "10.*, http://10.0.0.1, false", + "10.*, http://100.64.0.1, true", + "LOCALHOST, http://localhost, false", + "*.example.com, https://API.EXAMPLE.COM, false", + ".example.com, https://example.com, false", + ".example.com, https://badexample.com, true", + "[::1], http://[::1]:8080, false", + "[::1], http://1, true" }) + public void proxyIsSkippedOnlyForNonProxyHosts(String nonProxyHosts, String url, boolean proxied) throws Exception { + ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("localhost", 8888)) + .setNonProxyHosts(nonProxyHosts); + VertxHttpClient httpClient = (VertxHttpClient) new VertxHttpClientBuilder().proxy(proxyOptions).build(); + + try { + String host = new HttpRequest(HttpMethod.GET, url).getUrl().getHost(); + assertEquals(proxied, httpClient.getProxyOptions(host) != null); + } finally { + closeClient(httpClient); + } + } + + @ParameterizedTest + @ValueSource(strings = { "localhost", "LOCALHOST", "local*", ".localhost" }) + public void requestToNonProxyHostConnectsDirectly(String nonProxyHosts) throws IOException { + HttpClient httpClient = buildWithUnreachableProxy(nonProxyHosts); + + StepVerifier.create(httpClient.send(new HttpRequest(HttpMethod.GET, SERVER_HTTP_URI + SERVICE_ENDPOINT))) + .assertNext(response -> assertEquals(200, response.getStatusCode())) + .verifyComplete(); + } + + @ParameterizedTest + @ValueSource(strings = { "localhost.*", "localhostx*", "example.com" }) + public void requestToOtherHostUsesProxy(String nonProxyHosts) throws IOException { + HttpClient httpClient = buildWithUnreachableProxy(nonProxyHosts); + + StepVerifier.create(httpClient.send(new HttpRequest(HttpMethod.GET, SERVER_HTTP_URI + SERVICE_ENDPOINT))) + .verifyError(ConnectException.class); + } + + /* + * Nothing listens on the proxy port, so only requests that connect directly to the local server succeed. + */ + private static HttpClient buildWithUnreachableProxy(String nonProxyHosts) throws IOException { + int unusedPort; + try (ServerSocket socket = new ServerSocket(0)) { + unusedPort = socket.getLocalPort(); + } + + return new VertxHttpClientBuilder() + .proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("localhost", unusedPort)) + .setNonProxyHosts(nonProxyHosts)) + .build(); + } + @Test public void buildWithHttpProxy() { ProxyOptions clientProxyOptions diff --git a/sdk/core/azure-core-http-vertx/src/test/java/com/azure/core/http/vertx/VertxHttpClientProviderTests.java b/sdk/core/azure-core-http-vertx/src/test/java/com/azure/core/http/vertx/VertxHttpClientProviderTests.java index b39c07f31742e..83ac2c69e950c 100644 --- a/sdk/core/azure-core-http-vertx/src/test/java/com/azure/core/http/vertx/VertxHttpClientProviderTests.java +++ b/sdk/core/azure-core-http-vertx/src/test/java/com/azure/core/http/vertx/VertxHttpClientProviderTests.java @@ -8,6 +8,7 @@ import com.azure.core.http.HttpProtocolVersion; import com.azure.core.http.ProxyOptions; import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; import com.azure.core.util.HttpClientOptions; import com.azure.core.validation.http.HttpClientOptionsProviderTests; import io.vertx.core.Vertx; @@ -21,6 +22,7 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.regex.Pattern; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertInstanceOf; @@ -37,14 +39,7 @@ public class VertxHttpClientProviderTests extends HttpClientOptionsProviderTests public void nullOptionsReturnsBaseClient() { VertxHttpClient httpClient = (VertxHttpClient) new VertxHttpClientProvider().createInstance(null); - ProxyOptions environmentProxy = loadEnvironmentProxy(); - io.vertx.core.net.ProxyOptions proxyOptions = httpClient.buildOptions.getProxyOptions(); - if (environmentProxy == null) { - assertNull(proxyOptions); - } else { - assertNotNull(proxyOptions); - assertEquals(environmentProxy.getAddress().getHostName(), proxyOptions.getHost()); - } + assertUsesEnvironmentProxy(httpClient); } @Test @@ -52,13 +47,32 @@ public void defaultOptionsReturnsBaseClient() { VertxHttpClient httpClient = (VertxHttpClient) new VertxHttpClientProvider().createInstance(new HttpClientOptions()); + assertUsesEnvironmentProxy(httpClient); + } + + /* + * Checks the proxy each request would use against the environment proxy, which CI agents set but most dev + * machines don't. Requests to the environment's non-proxy hosts connect directly. + */ + private static void assertUsesEnvironmentProxy(VertxHttpClient httpClient) { + // The proxy is set on each request, not on the Vert.x options. + assertNull(httpClient.buildOptions.getProxyOptions()); + ProxyOptions environmentProxy = loadEnvironmentProxy(); - io.vertx.core.net.ProxyOptions proxyOptions = httpClient.buildOptions.getProxyOptions(); - if (environmentProxy == null) { - assertNull(proxyOptions); - } else { - assertNotNull(proxyOptions); - assertEquals(environmentProxy.getAddress().getHostName(), proxyOptions.getHost()); + Pattern nonProxyHosts + = (environmentProxy == null || CoreUtils.isNullOrEmpty(environmentProxy.getNonProxyHosts())) + ? null + : Pattern.compile(environmentProxy.getNonProxyHosts(), Pattern.CASE_INSENSITIVE); + + for (String host : new String[] { "example.com", "localhost" }) { + io.vertx.core.net.ProxyOptions proxyOptions = httpClient.getProxyOptions(host); + if (environmentProxy == null || (nonProxyHosts != null && nonProxyHosts.matcher(host).matches())) { + assertNull(proxyOptions, host); + } else { + assertNotNull(proxyOptions, host); + assertEquals(environmentProxy.getAddress().getHostName(), proxyOptions.getHost()); + assertEquals(environmentProxy.getAddress().getPort(), proxyOptions.getPort()); + } } } @@ -80,7 +94,10 @@ public void optionsWithAProxy() { VertxHttpClient httpClient = (VertxHttpClient) new VertxHttpClientProvider().createInstance(clientOptions); - io.vertx.core.net.ProxyOptions vertxProxyOptions = httpClient.buildOptions.getProxyOptions(); + assertNull(httpClient.buildOptions.getProxyOptions()); + assertNull(httpClient.getProxyOptions("cheese.com")); + + io.vertx.core.net.ProxyOptions vertxProxyOptions = httpClient.getProxyOptions("example.com"); assertNotNull(vertxProxyOptions); assertEquals(proxyOptions.getAddress().getHostName(), vertxProxyOptions.getHost()); assertEquals(proxyOptions.getAddress().getPort(), vertxProxyOptions.getPort()); diff --git a/sdk/core/azure-core/CHANGELOG.md b/sdk/core/azure-core/CHANGELOG.md index c147c389a65f5..7f4be06a47f57 100644 --- a/sdk/core/azure-core/CHANGELOG.md +++ b/sdk/core/azure-core/CHANGELOG.md @@ -18,6 +18,13 @@ consumers that retain the emitted buffers, such as uploads from an `InputStream` returning small reads, to use many times more memory than the data read and fail with `OutOfMemoryError`. Emitted buffers are now sized to the data read. +- Fixed suffix wildcards in `ProxyOptions` non-proxy hosts removing the character before the wildcard, so `storage1*` + matched `storage2.example.com` and `10.*` matched `100.64.0.1`. This affected `setNonProxyHosts` as well as + `http.nonProxyHosts`, `http.proxy.non-proxy-hosts`, and `NO_PROXY`. Entries such as `.*` no longer throw + `StringIndexOutOfBoundsException`. ([#51341](https://github.com/Azure/azure-sdk-for-java/issues/51341)) +- Fixed `ProxyOptions` non-proxy hosts with a leading or trailing dot, or a bracketed IPv6 address, matching other + hosts. `.example.com` now matches `example.com` and its subdomains but not `badexample.com`, `192.168.` no longer + matches `192.1689.0.1`, and `[::1]` is matched literally instead of as a regex character class. ### Other Changes diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/http/ProxyOptions.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/ProxyOptions.java index 2c4be8dd4c62c..e6d13c110d6e1 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/http/ProxyOptions.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/http/ProxyOptions.java @@ -72,6 +72,7 @@ public class ProxyOptions { private static final Pattern UNESCAPED_PERIOD = Pattern.compile("(? NON_PROXY_PROPERTY = ConfigurationPropertyBuilder.ofString(ConfigurationProperties.HTTP_PROXY_NON_PROXY_HOSTS) @@ -130,7 +131,15 @@ public ProxyOptions setCredentials(String username, String password) { * Sets the hosts which bypass the proxy. *

* The expected format of the passed string is a {@code '|'} delimited list of hosts which should bypass the proxy. - * Individual host strings may contain regex characters such as {@code '*'}. + * In each host, {@code '*'} is a wildcard and {@code '.'} is a literal dot. Other regex characters, such as + * character classes, keep their regex meaning. For example: + *

    + *
  • {@code *.example.com} matches any subdomain of {@code example.com}.
  • + *
  • {@code 10.*}, or {@code 10.}, matches hosts beginning with {@code 10.}, such as {@code 10.0.0.1} but not + * {@code 100.64.0.1}.
  • + *
  • {@code .example.com} matches {@code example.com} and its subdomains, but not {@code badexample.com}.
  • + *
  • {@code [::1]} matches the bracketed IPv6 address literally.
  • + *
* * @param nonProxyHosts Hosts that bypass the proxy. * @return the updated ProxyOptions object @@ -425,69 +434,63 @@ private static String sanitizeNonProxyHosts(String[] nonProxyHosts) { String sanitizedNonProxyHost = nonProxyHosts[i]; /* - * If the non-proxy host begins with either '.', '*', '.*', or any of the previous with a trailing '?' - * substring the non-proxy host and set the wildcard prefix. + * If the non-proxy host begins with '*', '.*', or either with a trailing '?', it matches any prefix. If it + * begins with '.', or '.?', it matches the domain and its subdomains, so '.example.com' matches + * 'example.com' and 'api.example.com' but not 'badexample.com'. */ - if (sanitizedNonProxyHost.startsWith(".")) { + if (sanitizedNonProxyHost.startsWith(".*?")) { prefixWildcard = ".*?"; - sanitizedNonProxyHost = sanitizedNonProxyHost.substring(1); - } else if (sanitizedNonProxyHost.startsWith(".?")) { - prefixWildcard = ".*?"; - sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2); - } else if (sanitizedNonProxyHost.startsWith("*?")) { + sanitizedNonProxyHost = sanitizedNonProxyHost.substring(3); + } else if (sanitizedNonProxyHost.startsWith(".*") || sanitizedNonProxyHost.startsWith("*?")) { prefixWildcard = ".*?"; sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2); } else if (sanitizedNonProxyHost.startsWith("*")) { prefixWildcard = ".*?"; sanitizedNonProxyHost = sanitizedNonProxyHost.substring(1); - } else if (sanitizedNonProxyHost.startsWith(".*?")) { - prefixWildcard = ".*?"; - sanitizedNonProxyHost = sanitizedNonProxyHost.substring(3); - } else if (sanitizedNonProxyHost.startsWith(".*")) { - prefixWildcard = ".*?"; + } else if (sanitizedNonProxyHost.startsWith(".?")) { + prefixWildcard = "(?:.*?\\.)?"; sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2); + } else if (sanitizedNonProxyHost.startsWith(".")) { + prefixWildcard = "(?:.*?\\.)?"; + sanitizedNonProxyHost = sanitizedNonProxyHost.substring(1); } /* - * Same with the ending of the non-proxy host, if it has a suffix wildcard trim the non-proxy host and - * retain the suffix wildcard. + * If the non-proxy host ends with '*', '.', or either with a trailing '?', it matches any suffix. Only the + * '*' and '?' are trimmed. A '.' is a literal dot, so '10.*' matches '10.0.0.1' but not '100.64.0.1', and + * '192.168.' matches '192.168.0.1' but not '192.1689.0.1'. */ - if (sanitizedNonProxyHost.endsWith(".")) { + if (sanitizedNonProxyHost.endsWith("*?")) { suffixWildcard = ".*?"; sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 2); - } else if (sanitizedNonProxyHost.endsWith(".?")) { + } else if (sanitizedNonProxyHost.endsWith("*") || sanitizedNonProxyHost.endsWith(".?")) { suffixWildcard = ".*?"; - sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 3); - } else if (sanitizedNonProxyHost.endsWith("*?")) { + sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 1); + } else if (sanitizedNonProxyHost.endsWith(".")) { suffixWildcard = ".*?"; - sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 3); - } else if (sanitizedNonProxyHost.endsWith("*")) { - suffixWildcard = ".*?"; - sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 2); - } else if (sanitizedNonProxyHost.endsWith(".*?")) { - suffixWildcard = ".*?"; - sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 4); - } else if (sanitizedNonProxyHost.endsWith(".*")) { - suffixWildcard = ".*?"; - sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 3); } - try { - // Sanitize the non-proxy host before any appending to prevent errant characters being added to the - // final response if the non-proxy host isn't a valid Pattern. - String attemptToSanitizeAsRegex = sanitizedNonProxyHost; - attemptToSanitizeAsRegex = UNESCAPED_PERIOD.matcher(attemptToSanitizeAsRegex).replaceAll("\\\\."); - attemptToSanitizeAsRegex = ANY.matcher(attemptToSanitizeAsRegex).replaceAll("\\.*?"); - sanitizedNonProxyHost = Pattern.compile(attemptToSanitizeAsRegex).pattern(); - } catch (PatternSyntaxException ex) { - /* - * Replace the non-proxy host with the sanitized value. - * - * The body of the non-proxy host is quoted to handle scenarios such a '127.0.0.1' or '*.azure.com' - * where without quoting the '.' in the string would be treated as the match any character instead of - * the literal '.' character. - */ + if (BRACKETED_IPV6_LITERAL.matcher(sanitizedNonProxyHost).matches()) { + // Match IPv6 literals such as '[::1]' as-is. As a regex, the brackets would be a character class. sanitizedNonProxyHost = Pattern.quote(sanitizedNonProxyHost); + } else { + try { + // Sanitize the non-proxy host before any appending to prevent errant characters being added to + // the final response if the non-proxy host isn't a valid Pattern. + String attemptToSanitizeAsRegex = sanitizedNonProxyHost; + attemptToSanitizeAsRegex = UNESCAPED_PERIOD.matcher(attemptToSanitizeAsRegex).replaceAll("\\\\."); + attemptToSanitizeAsRegex = ANY.matcher(attemptToSanitizeAsRegex).replaceAll("\\.*?"); + sanitizedNonProxyHost = Pattern.compile(attemptToSanitizeAsRegex).pattern(); + } catch (PatternSyntaxException ex) { + /* + * Replace the non-proxy host with the sanitized value. + * + * The body of the non-proxy host is quoted to handle scenarios such a '127.0.0.1' or '*.azure.com' + * where without quoting the '.' in the string would be treated as the match any character instead + * of the literal '.' character. + */ + sanitizedNonProxyHost = Pattern.quote(sanitizedNonProxyHost); + } } sanitizedBuilder.append("(") diff --git a/sdk/core/azure-core/src/test/java/com/azure/core/http/ProxyOptionsTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/http/ProxyOptionsTests.java index 49bb3269bcfb6..94083bc2fd7f8 100644 --- a/sdk/core/azure-core/src/test/java/com/azure/core/http/ProxyOptionsTests.java +++ b/sdk/core/azure-core/src/test/java/com/azure/core/http/ProxyOptionsTests.java @@ -20,6 +20,8 @@ import java.net.InetSocketAddress; import java.net.Proxy; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.regex.Pattern; import java.util.stream.Stream; @@ -505,6 +507,59 @@ public void sanitizeJavaHttpNonProxyHostsDoesNotSplitEscapedPipes() { assertEquals("(" + nonProxyHosts + ")", ProxyOptions.sanitizeNoProxy(nonProxyHosts)); } + /** + * Tests that wildcards, leading and trailing dots, and IPv6 literals in non-proxy hosts only match the intended + * hosts, however the non-proxy hosts are configured. Hosts are matched the way HTTP clients match them: the whole + * host, ignoring case. + */ + @ParameterizedTest + @MethodSource("nonProxyHostsMatchOnlyIntendedHostsSupplier") + public void nonProxyHostsMatchOnlyIntendedHosts(String nonProxyHost, List bypassedHosts, + List proxiedHosts) { + String[] sanitizedNonProxyHosts = { + new ProxyOptions(ProxyOptions.Type.HTTP, InetSocketAddress.createUnresolved("localhost", 7777)) + .setNonProxyHosts(nonProxyHost) + .getNonProxyHosts(), + fromConfiguration(createJavaEnvConfiguration(null, null, nonProxyHost, true), true).getNonProxyHosts(), + fromConfiguration(createExplicitConfiguration(null, null, nonProxyHost), true).getNonProxyHosts(), + fromConfiguration(setJavaSystemProxyPrerequisiteToTrue("http://localhost:7777", nonProxyHost, true), true) + .getNonProxyHosts() }; + + for (String sanitizedNonProxyHost : sanitizedNonProxyHosts) { + Pattern pattern = compile(sanitizedNonProxyHost, Pattern.CASE_INSENSITIVE); + + for (String host : bypassedHosts) { + assertTrue(pattern.matcher(host).matches(), () -> String + .format("Expected '%s' (Pattern '%s') to match '%s'.", nonProxyHost, pattern.pattern(), host)); + } + + for (String host : proxiedHosts) { + assertFalse(pattern.matcher(host).matches(), () -> String + .format("Expected '%s' (Pattern '%s') not to match '%s'.", nonProxyHost, pattern.pattern(), host)); + } + } + } + + private static Stream nonProxyHostsMatchOnlyIntendedHostsSupplier() { + List anyHost = Arrays.asList("example.com", "10.0.0.1", "[::1]"); + + return Stream.of( + Arguments.of("storage1*", Arrays.asList("storage1.example.com"), Arrays.asList("storage2.example.com")), + Arguments.of("storage1*?", Arrays.asList("storage1.example.com"), Arrays.asList("storage2.example.com")), + Arguments.of("storage1.?", Arrays.asList("storage1.example.com"), Arrays.asList("storage2.example.com")), + Arguments.of("storage1.*", Arrays.asList("storage1.example.com"), + Arrays.asList("storage1other.example.com")), + Arguments.of("10.*", Arrays.asList("10.0.0.1"), Arrays.asList("100.64.0.1")), + Arguments.of("192.168.", Arrays.asList("192.168.0.1"), Arrays.asList("192.16.0.1", "192.1689.0.1")), + Arguments.of(".example.com", Arrays.asList("example.com", "api.example.com"), + Arrays.asList("badexample.com")), + Arguments.of("[::1]", Arrays.asList("[::1]"), Arrays.asList("1")), + Arguments.of("[2001:db8::1]*", Arrays.asList("[2001:db8::1]"), Arrays.asList("2evil.example.com")), + Arguments.of(".*", anyHost, Collections.emptyList()), Arguments.of("*", anyHost, Collections.emptyList()), + Arguments.of("*?", anyHost, Collections.emptyList()), + Arguments.of(".*?", anyHost, Collections.emptyList())); + } + private static Configuration setJavaSystemProxyPrerequisiteToTrue(String proxy, String nonProxyHosts, boolean isHttps) { TestConfigurationSource testSource = new TestConfigurationSource().put(JAVA_SYSTEM_PROXY_PREREQUISITE, "true") From b5d5762956ae822ef5ab0ae43912b0cc510dccad Mon Sep 17 00:00:00 2001 From: Victor Colin Amador Date: Tue, 24 Nov 2026 17:22:49 -0800 Subject: [PATCH 2/2] Make the azure-core and Vert.x non-proxy host fixes opt-in --- sdk/core/azure-core-http-vertx/CHANGELOG.md | 9 +- .../http/vertx/VertxHttpClientBuilder.java | 46 ++- .../vertx/VertxHttpClientBuilderTests.java | 48 +-- .../vertx/VertxHttpClientProviderTests.java | 38 +-- sdk/core/azure-core/CHANGELOG.md | 16 +- .../com/azure/core/http/ProxyOptions.java | 292 +++++++++++++----- .../util/ProxyOptionsAccessHelper.java | 47 +++ .../azure/core/http/ProxyOptionsTests.java | 82 ++++- 8 files changed, 420 insertions(+), 158 deletions(-) create mode 100644 sdk/core/azure-core/src/main/java/com/azure/core/implementation/util/ProxyOptionsAccessHelper.java diff --git a/sdk/core/azure-core-http-vertx/CHANGELOG.md b/sdk/core/azure-core-http-vertx/CHANGELOG.md index 4a0a6e574fcfd..f8a924115a30d 100644 --- a/sdk/core/azure-core-http-vertx/CHANGELOG.md +++ b/sdk/core/azure-core-http-vertx/CHANGELOG.md @@ -7,6 +7,11 @@ - Added `maximumHttpVersion` to select HTTP/1.1 or HTTP/2 with HTTP/1.1 fallback without changing defaults or mutating caller-supplied Vert.x options. - Added support for `HttpClientOptions.setMaximumHttpVersion` through the HTTP client provider. +- Added support for azure-core's `AZURE_NON_PROXY_PARSER_VERSION` setting. With version `2`, non-proxy hosts are + matched the same way as in the other HTTP clients, and the proxy is set on each request to a host that doesn't match + them. Version `1`, the default, still converts them to Vert.x's non-proxy host list, which can bypass the proxy for + the wrong hosts. For example, `10.*` bypasses the proxy for `100.64.0.1`, and entries without a wildcard are compared + case-sensitively. ### Breaking Changes @@ -15,10 +20,6 @@ - Fixed the `Expect: 100-continue` fallback wait starting before the request headers were written. Time the headers spent reaching the wire, such as on the first request in a JVM, shortened the wait for `100 Continue` and could cause the body to be sent before the service had a chance to answer. -- Fixed `ProxyOptions` non-proxy hosts being converted to Vert.x's non-proxy host list, which bypassed the proxy for - the wrong hosts. For example, `10.*` bypassed the proxy for `100.64.0.1`, and entries without a wildcard were - compared case-sensitively. Non-proxy hosts are now matched the same way as in the other HTTP clients, and the proxy - is set on each request to a host that doesn't match them. ### Other Changes diff --git a/sdk/core/azure-core-http-vertx/src/main/java/com/azure/core/http/vertx/VertxHttpClientBuilder.java b/sdk/core/azure-core-http-vertx/src/main/java/com/azure/core/http/vertx/VertxHttpClientBuilder.java index 0e349ad4abdb5..65d3f77185fd2 100644 --- a/sdk/core/azure-core-http-vertx/src/main/java/com/azure/core/http/vertx/VertxHttpClientBuilder.java +++ b/sdk/core/azure-core-http-vertx/src/main/java/com/azure/core/http/vertx/VertxHttpClientBuilder.java @@ -8,6 +8,7 @@ import com.azure.core.http.ProxyOptions; import com.azure.core.implementation.ReflectionUtils; import com.azure.core.implementation.ReflectiveInvoker; +import com.azure.core.implementation.util.ProxyOptionsAccessHelper; import com.azure.core.util.Configuration; import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; @@ -43,6 +44,10 @@ */ public class VertxHttpClientBuilder { private static final ClientLogger LOGGER = new ClientLogger(VertxHttpClientBuilder.class); + private static final Pattern NON_PROXY_HOSTS_SPLIT = Pattern.compile("(? VERTX_HTTP_CLIENT_FACTORY; static { @@ -267,7 +272,7 @@ public HttpClient build() { } HttpClientOptions buildOptions = this.httpClientOptions; - io.vertx.core.net.ProxyOptions vertxProxyOptions = null; + io.vertx.core.net.ProxyOptions requestProxyOptions = null; Pattern nonProxyHostsPattern = null; Duration writeTimeout = Duration.ZERO; if (buildOptions == null) { @@ -289,7 +294,7 @@ public HttpClient build() { = (proxyOptions == null) ? ProxyOptions.fromConfiguration(buildConfiguration, true) : proxyOptions; if (buildProxyOptions != null) { - vertxProxyOptions = new io.vertx.core.net.ProxyOptions(); + io.vertx.core.net.ProxyOptions vertxProxyOptions = new io.vertx.core.net.ProxyOptions(); InetSocketAddress proxyAddress = buildProxyOptions.getAddress(); if (proxyAddress != null) { @@ -315,11 +320,21 @@ public HttpClient build() { } } - // Vert.x can't match the non-proxy hosts regex, and a request can't opt out of a proxy set on - // HttpClientOptions. Instead, VertxHttpClient sets the proxy on each request whose host doesn't match. String nonProxyHosts = buildProxyOptions.getNonProxyHosts(); - if (!CoreUtils.isNullOrEmpty(nonProxyHosts)) { + if (CoreUtils.isNullOrEmpty(nonProxyHosts)) { + buildOptions.setProxyOptions(vertxProxyOptions); + } else if (ProxyOptionsAccessHelper.getNonProxyHostsParserVersion(buildProxyOptions) == 2) { + // Vert.x can't match the non-proxy hosts regex, and a request can't opt out of a proxy set on + // HttpClientOptions. Instead, VertxHttpClient sets the proxy on each request whose host doesn't + // match. + requestProxyOptions = vertxProxyOptions; nonProxyHostsPattern = Pattern.compile(nonProxyHosts, Pattern.CASE_INSENSITIVE); + } else { + for (String nonProxyHost : removeNonProxyHostsSanitation(nonProxyHosts)) { + buildOptions.addNonProxyHost(nonProxyHost); + } + + buildOptions.setProxyOptions(vertxProxyOptions); } } } @@ -338,7 +353,7 @@ public HttpClient build() { } io.vertx.core.http.HttpClient client = VERTX_HTTP_CLIENT_FACTORY.apply(configuredVertx, buildOptions); - return new VertxHttpClient(client, buildOptions, vertxProxyOptions, nonProxyHostsPattern, + return new VertxHttpClient(client, buildOptions, requestProxyOptions, nonProxyHostsPattern, getTimeout(this.responseTimeout, configuration, PROPERTY_AZURE_REQUEST_RESPONSE_TIMEOUT, DEFAULT_RESPONSE_TIMEOUT), writeTimeout); @@ -363,6 +378,25 @@ static Vertx getVertx(Iterator iterator) { return configuredVertx; } + /** + * Reverses non-proxy host string sanitization applied by {@link ProxyOptions}. + *

+ * This is necessary as Vert.x will apply its own sanitization logic. It's only used for non-proxy hosts converted + * by version 1 of the {@link ProxyOptions} parser. + * + * @param nonProxyHosts The list of non-proxy hosts + * @return String array of proxy host strings without sanitation. + */ + private String[] removeNonProxyHostsSanitation(String nonProxyHosts) { + String nonProxyHostsSanitationRemoved + = NON_PROXY_HOST_REMOVE_SANITIZATION.matcher(nonProxyHosts).replaceAll(""); + + nonProxyHostsSanitationRemoved + = NON_PROXY_HOST_DOT_STAR.matcher(nonProxyHostsSanitationRemoved).replaceAll("*"); + + return NON_PROXY_HOSTS_SPLIT.split(nonProxyHostsSanitationRemoved); + } + // Enum Singleton Pattern private enum DefaultVertx { DEFAULT_VERTX(Vertx.vertx()); diff --git a/sdk/core/azure-core-http-vertx/src/test/java/com/azure/core/http/vertx/VertxHttpClientBuilderTests.java b/sdk/core/azure-core-http-vertx/src/test/java/com/azure/core/http/vertx/VertxHttpClientBuilderTests.java index fd801ff0af978..2014009768afd 100644 --- a/sdk/core/azure-core-http-vertx/src/test/java/com/azure/core/http/vertx/VertxHttpClientBuilderTests.java +++ b/sdk/core/azure-core-http-vertx/src/test/java/com/azure/core/http/vertx/VertxHttpClientBuilderTests.java @@ -221,11 +221,7 @@ public void buildWithAllProxyTypes(ProxyOptions.Type type) throws Exception { VertxHttpClient httpClient = (VertxHttpClient) new VertxHttpClientBuilder().proxy(proxyOptions).build(); - // The proxy is set on each request whose host isn't a non-proxy host, not on the Vert.x options. - assertNull(httpClient.buildOptions.getProxyOptions()); - assertNull(httpClient.getProxyOptions("microsoft.com")); - - io.vertx.core.net.ProxyOptions vertxProxyOptions = httpClient.getProxyOptions("example.com"); + io.vertx.core.net.ProxyOptions vertxProxyOptions = httpClient.buildOptions.getProxyOptions(); assertNotNull(vertxProxyOptions); assertEquals(address.getHostName(), vertxProxyOptions.getHost()); assertEquals(address.getPort(), vertxProxyOptions.getPort()); @@ -235,9 +231,9 @@ public void buildWithAllProxyTypes(ProxyOptions.Type type) throws Exception { } /** - * Tests that the proxy is only skipped for request hosts matching the non-proxy hosts. They're matched like in the - * other HTTP clients, rather than by Vert.x, which matched '10.*' with '100.64.0.1' and compared hosts without - * wildcards case-sensitively. + * Tests that with AZURE_NON_PROXY_PARSER_VERSION set to 2, the proxy is only skipped for request hosts matching the + * non-proxy hosts. They're matched like in the other HTTP clients, rather than by Vert.x, which matched '10.*' with + * '100.64.0.1' and compared hosts without wildcards case-sensitively. */ @ParameterizedTest @CsvSource({ @@ -249,12 +245,15 @@ public void buildWithAllProxyTypes(ProxyOptions.Type type) throws Exception { ".example.com, https://badexample.com, true", "[::1], http://[::1]:8080, false", "[::1], http://1, true" }) - public void proxyIsSkippedOnlyForNonProxyHosts(String nonProxyHosts, String url, boolean proxied) throws Exception { - ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("localhost", 8888)) - .setNonProxyHosts(nonProxyHosts); - VertxHttpClient httpClient = (VertxHttpClient) new VertxHttpClientBuilder().proxy(proxyOptions).build(); + public void parserVersion2SkipsProxyOnlyForNonProxyHosts(String nonProxyHosts, String url, boolean proxied) + throws Exception { + VertxHttpClient httpClient + = (VertxHttpClient) new VertxHttpClientBuilder().proxy(loadProxyWithParserVersion2(8888, nonProxyHosts)) + .build(); try { + assertNull(httpClient.buildOptions.getProxyOptions()); + String host = new HttpRequest(HttpMethod.GET, url).getUrl().getHost(); assertEquals(proxied, httpClient.getProxyOptions(host) != null); } finally { @@ -264,7 +263,7 @@ public void proxyIsSkippedOnlyForNonProxyHosts(String nonProxyHosts, String url, @ParameterizedTest @ValueSource(strings = { "localhost", "LOCALHOST", "local*", ".localhost" }) - public void requestToNonProxyHostConnectsDirectly(String nonProxyHosts) throws IOException { + public void parserVersion2RequestToNonProxyHostConnectsDirectly(String nonProxyHosts) throws IOException { HttpClient httpClient = buildWithUnreachableProxy(nonProxyHosts); StepVerifier.create(httpClient.send(new HttpRequest(HttpMethod.GET, SERVER_HTTP_URI + SERVICE_ENDPOINT))) @@ -274,7 +273,7 @@ public void requestToNonProxyHostConnectsDirectly(String nonProxyHosts) throws I @ParameterizedTest @ValueSource(strings = { "localhost.*", "localhostx*", "example.com" }) - public void requestToOtherHostUsesProxy(String nonProxyHosts) throws IOException { + public void parserVersion2RequestToOtherHostUsesProxy(String nonProxyHosts) throws IOException { HttpClient httpClient = buildWithUnreachableProxy(nonProxyHosts); StepVerifier.create(httpClient.send(new HttpRequest(HttpMethod.GET, SERVER_HTTP_URI + SERVICE_ENDPOINT))) @@ -290,10 +289,23 @@ private static HttpClient buildWithUnreachableProxy(String nonProxyHosts) throws unusedPort = socket.getLocalPort(); } - return new VertxHttpClientBuilder() - .proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("localhost", unusedPort)) - .setNonProxyHosts(nonProxyHosts)) - .build(); + return new VertxHttpClientBuilder().proxy(loadProxyWithParserVersion2(unusedPort, nonProxyHosts)).build(); + } + + /* + * Loads a proxy whose non-proxy hosts are converted by version 2 of the ProxyOptions parser, which VertxHttpClient + * matches on each request. + */ + private static ProxyOptions loadProxyWithParserVersion2(int port, String nonProxyHosts) { + Configuration configuration = new ConfigurationBuilder( + new TestConfigurationSource().put("http.proxy.hostname", "localhost") + .put("http.proxy.port", String.valueOf(port)) + .put("http.proxy.non-proxy-hosts", nonProxyHosts), + new TestConfigurationSource().put("java.net.useSystemProxies", "false") + .put("AZURE_NON_PROXY_PARSER_VERSION", "2"), + EMPTY_SOURCE).build(); + + return ProxyOptions.fromConfiguration(configuration, true); } @Test diff --git a/sdk/core/azure-core-http-vertx/src/test/java/com/azure/core/http/vertx/VertxHttpClientProviderTests.java b/sdk/core/azure-core-http-vertx/src/test/java/com/azure/core/http/vertx/VertxHttpClientProviderTests.java index 83ac2c69e950c..ac81fefc32c10 100644 --- a/sdk/core/azure-core-http-vertx/src/test/java/com/azure/core/http/vertx/VertxHttpClientProviderTests.java +++ b/sdk/core/azure-core-http-vertx/src/test/java/com/azure/core/http/vertx/VertxHttpClientProviderTests.java @@ -8,7 +8,6 @@ import com.azure.core.http.HttpProtocolVersion; import com.azure.core.http.ProxyOptions; import com.azure.core.util.Configuration; -import com.azure.core.util.CoreUtils; import com.azure.core.util.HttpClientOptions; import com.azure.core.validation.http.HttpClientOptionsProviderTests; import io.vertx.core.Vertx; @@ -22,7 +21,6 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -import java.util.regex.Pattern; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertInstanceOf; @@ -51,28 +49,23 @@ public void defaultOptionsReturnsBaseClient() { } /* - * Checks the proxy each request would use against the environment proxy, which CI agents set but most dev - * machines don't. Requests to the environment's non-proxy hosts connect directly. + * Checks that the client uses the environment proxy, which CI agents set but most dev machines don't. The proxy is + * set on each request instead of on the Vert.x options when the environment's non-proxy hosts are converted by + * AZURE_NON_PROXY_PARSER_VERSION 2. */ private static void assertUsesEnvironmentProxy(VertxHttpClient httpClient) { - // The proxy is set on each request, not on the Vert.x options. - assertNull(httpClient.buildOptions.getProxyOptions()); + io.vertx.core.net.ProxyOptions proxyOptions = httpClient.buildOptions.getProxyOptions(); + if (proxyOptions == null) { + proxyOptions = httpClient.getProxyOptions("example.com"); + } ProxyOptions environmentProxy = loadEnvironmentProxy(); - Pattern nonProxyHosts - = (environmentProxy == null || CoreUtils.isNullOrEmpty(environmentProxy.getNonProxyHosts())) - ? null - : Pattern.compile(environmentProxy.getNonProxyHosts(), Pattern.CASE_INSENSITIVE); - - for (String host : new String[] { "example.com", "localhost" }) { - io.vertx.core.net.ProxyOptions proxyOptions = httpClient.getProxyOptions(host); - if (environmentProxy == null || (nonProxyHosts != null && nonProxyHosts.matcher(host).matches())) { - assertNull(proxyOptions, host); - } else { - assertNotNull(proxyOptions, host); - assertEquals(environmentProxy.getAddress().getHostName(), proxyOptions.getHost()); - assertEquals(environmentProxy.getAddress().getPort(), proxyOptions.getPort()); - } + if (environmentProxy == null) { + assertNull(proxyOptions); + } else { + assertNotNull(proxyOptions); + assertEquals(environmentProxy.getAddress().getHostName(), proxyOptions.getHost()); + assertEquals(environmentProxy.getAddress().getPort(), proxyOptions.getPort()); } } @@ -94,10 +87,7 @@ public void optionsWithAProxy() { VertxHttpClient httpClient = (VertxHttpClient) new VertxHttpClientProvider().createInstance(clientOptions); - assertNull(httpClient.buildOptions.getProxyOptions()); - assertNull(httpClient.getProxyOptions("cheese.com")); - - io.vertx.core.net.ProxyOptions vertxProxyOptions = httpClient.getProxyOptions("example.com"); + io.vertx.core.net.ProxyOptions vertxProxyOptions = httpClient.buildOptions.getProxyOptions(); assertNotNull(vertxProxyOptions); assertEquals(proxyOptions.getAddress().getHostName(), vertxProxyOptions.getHost()); assertEquals(proxyOptions.getAddress().getPort(), vertxProxyOptions.getPort()); diff --git a/sdk/core/azure-core/CHANGELOG.md b/sdk/core/azure-core/CHANGELOG.md index 7f4be06a47f57..639367505ffb9 100644 --- a/sdk/core/azure-core/CHANGELOG.md +++ b/sdk/core/azure-core/CHANGELOG.md @@ -7,6 +7,14 @@ - Added `HttpProtocolVersion` for configuring the maximum HTTP protocol version in HTTP client builders. - Added `HttpClientOptions.getMaximumHttpVersion` and `setMaximumHttpVersion` for transport-independent HTTP protocol configuration. An unset or cleared maximum preserves the selected transport's existing default. +- Added the `AZURE_NON_PROXY_PARSER_VERSION` environment variable and system property to opt in to corrected + `ProxyOptions` non-proxy host matching. ([#51341](https://github.com/Azure/azure-sdk-for-java/issues/51341)) The + default, `1`, keeps the current matching, and `2` will become the default in a future release. Version `2` applies to + `setNonProxyHosts`, `http.nonProxyHosts`, `http.proxy.non-proxy-hosts`, and `NO_PROXY`. With it: + - `storage1*` no longer matches `storage2.example.com`, and `10.*` no longer matches `100.64.0.1`. + - `192.168.` no longer matches `192.1689.0.1`. + - `.example.com` matches `example.com` and its subdomains, but not `badexample.com`. + - Bracketed IPv6 addresses such as `[::1]` are matched literally instead of as a regex character class. ### Breaking Changes @@ -18,13 +26,7 @@ consumers that retain the emitted buffers, such as uploads from an `InputStream` returning small reads, to use many times more memory than the data read and fail with `OutOfMemoryError`. Emitted buffers are now sized to the data read. -- Fixed suffix wildcards in `ProxyOptions` non-proxy hosts removing the character before the wildcard, so `storage1*` - matched `storage2.example.com` and `10.*` matched `100.64.0.1`. This affected `setNonProxyHosts` as well as - `http.nonProxyHosts`, `http.proxy.non-proxy-hosts`, and `NO_PROXY`. Entries such as `.*` no longer throw - `StringIndexOutOfBoundsException`. ([#51341](https://github.com/Azure/azure-sdk-for-java/issues/51341)) -- Fixed `ProxyOptions` non-proxy hosts with a leading or trailing dot, or a bracketed IPv6 address, matching other - hosts. `.example.com` now matches `example.com` and its subdomains but not `badexample.com`, `192.168.` no longer - matches `192.1689.0.1`, and `[::1]` is matched literally instead of as a regex character class. +- Fixed `ProxyOptions` throwing `StringIndexOutOfBoundsException` for non-proxy hosts such as `.*`. ### Other Changes diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/http/ProxyOptions.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/ProxyOptions.java index e6d13c110d6e1..2d0c86ff64016 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/http/ProxyOptions.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/http/ProxyOptions.java @@ -4,6 +4,7 @@ package com.azure.core.http; import com.azure.core.implementation.ImplUtils; +import com.azure.core.implementation.util.ProxyOptionsAccessHelper; import com.azure.core.util.Configuration; import com.azure.core.util.ConfigurationProperty; import com.azure.core.util.ConfigurationPropertyBuilder; @@ -74,6 +75,13 @@ public class ProxyOptions { private static final Pattern ANY = Pattern.compile("\\*"); private static final Pattern BRACKETED_IPV6_LITERAL = Pattern.compile("\\[[^\\[\\]]*:[^\\[\\]]*\\]"); + /* + * Selects how non-proxy hosts are converted to a regex. Version 1, the default, keeps the original conversion, and + * version 2 stops non-proxy hosts from matching unintended hosts. Version 2 will become the default in a future + * release. + */ + private static final String NON_PROXY_PARSER_VERSION = "AZURE_NON_PROXY_PARSER_VERSION"; + private static final ConfigurationProperty NON_PROXY_PROPERTY = ConfigurationPropertyBuilder.ofString(ConfigurationProperties.HTTP_PROXY_NON_PROXY_HOSTS) .shared(true) @@ -102,6 +110,11 @@ public class ProxyOptions { private String username; private String password; private String nonProxyHosts; + private int nonProxyHostsParserVersion = 1; + + static { + ProxyOptionsAccessHelper.setAccessor(proxyOptions -> proxyOptions.nonProxyHostsParserVersion); + } /** * Creates ProxyOptions. @@ -131,21 +144,27 @@ public ProxyOptions setCredentials(String username, String password) { * Sets the hosts which bypass the proxy. *

* The expected format of the passed string is a {@code '|'} delimited list of hosts which should bypass the proxy. - * In each host, {@code '*'} is a wildcard and {@code '.'} is a literal dot. Other regex characters, such as - * character classes, keep their regex meaning. For example: + *

+ * The {@code AZURE_NON_PROXY_PARSER_VERSION} environment variable or system property, read from the global + * configuration when this method is called, selects how the hosts are matched: *

    - *
  • {@code *.example.com} matches any subdomain of {@code example.com}.
  • - *
  • {@code 10.*}, or {@code 10.}, matches hosts beginning with {@code 10.}, such as {@code 10.0.0.1} but not - * {@code 100.64.0.1}.
  • - *
  • {@code .example.com} matches {@code example.com} and its subdomains, but not {@code badexample.com}.
  • - *
  • {@code [::1]} matches the bracketed IPv6 address literally.
  • + *
  • {@code 1}, the default, keeps the original matching. Individual host strings may contain regex + * characters such as {@code '*'}, and some match more hosts than intended. For example, {@code 10.*} also + * matches {@code 100.64.0.1}.
  • + *
  • {@code 2} treats {@code '*'} as a wildcard and {@code '.'} as a literal dot. Other regex characters, such + * as character classes, keep their regex meaning. {@code 10.*}, or {@code 10.}, matches hosts beginning with + * {@code 10.}, such as {@code 10.0.0.1} but not {@code 100.64.0.1}. {@code .example.com} matches + * {@code example.com} and its subdomains, but not {@code badexample.com}. Bracketed IPv6 addresses, such as + * {@code [::1]}, are matched literally.
  • *
+ * Version {@code 2} will become the default in a future release. * * @param nonProxyHosts Hosts that bypass the proxy. * @return the updated ProxyOptions object */ public ProxyOptions setNonProxyHosts(String nonProxyHosts) { - this.nonProxyHosts = sanitizeJavaHttpNonProxyHosts(nonProxyHosts); + this.nonProxyHostsParserVersion = getNonProxyParserVersion(Configuration.getGlobalConfiguration()); + this.nonProxyHosts = sanitizeJavaHttpNonProxyHosts(nonProxyHosts, nonProxyHostsParserVersion); return this; } @@ -211,6 +230,10 @@ public String getNonProxyHosts() { * the purpose of the SDK. Additionally, more secure protocols, HTTPS vs HTTP, will be preferred. * *

+ * Non-proxy hosts are matched according to the {@code AZURE_NON_PROXY_PARSER_VERSION} setting in the + * configuration, as described in {@link #setNonProxyHosts(String)}. + * + *

* {@code null} will be returned if no proxy was found in the environment. * * @param configuration The {@link Configuration} that is used to load proxy configurations from the environment. If @@ -240,6 +263,9 @@ public static ProxyOptions fromConfiguration(Configuration configuration) { * Azure proxy configurations will be preferred over Java proxy configurations as they are more closely scoped to * the purpose of the SDK. Additionally, more secure protocols, HTTPS vs HTTP, will be preferred. *

+ * Non-proxy hosts are matched according to the {@code AZURE_NON_PROXY_PARSER_VERSION} setting in the + * configuration, as described in {@link #setNonProxyHosts(String)}. + *

* {@code null} will be returned if no proxy was found in the environment. * * @param configuration The {@link Configuration} that is used to load proxy configurations from the environment. If @@ -322,7 +348,9 @@ private static ProxyOptions attemptToLoadSystemProxy(Configuration configuration String nonProxyHostsString = configuration.get(Configuration.PROPERTY_NO_PROXY); if (!CoreUtils.isNullOrEmpty(nonProxyHostsString)) { - proxyOptions.nonProxyHosts = sanitizeNoProxy(nonProxyHostsString); + proxyOptions.nonProxyHostsParserVersion = getNonProxyParserVersion(configuration); + proxyOptions.nonProxyHosts + = sanitizeNoProxy(nonProxyHostsString, proxyOptions.nonProxyHostsParserVersion); LOGGER.atVerbose().addKeyValue("regex", proxyOptions.nonProxyHosts).log("Using non-proxy hosts"); } @@ -351,8 +379,8 @@ private static ProxyOptions attemptToLoadSystemProxy(Configuration configuration /* * Helper function that sanitizes 'NO_PROXY' into a Pattern safe string. */ - static String sanitizeNoProxy(String noProxyString) { - return sanitizeNonProxyHosts(NO_PROXY_SPLIT.split(noProxyString)); + static String sanitizeNoProxy(String noProxyString, int parserVersion) { + return sanitizeNonProxyHosts(NO_PROXY_SPLIT.split(noProxyString), parserVersion); } private static ProxyOptions attemptToLoadJavaProxy(Configuration configuration, boolean createUnresolved, @@ -375,7 +403,7 @@ private static ProxyOptions attemptToLoadJavaProxy(Configuration configuration, String username = configuration.get(type + "." + JAVA_PROXY_USER); String password = configuration.get(type + "." + JAVA_PROXY_PASSWORD); - return createOptions(host, port, nonProxyHostsString, username, password, createUnresolved); + return createOptions(configuration, host, port, nonProxyHostsString, username, password, createUnresolved); } private static ProxyOptions attemptToLoadAzureSdkProxy(Configuration configuration, boolean createUnresolved) { @@ -391,18 +419,20 @@ private static ProxyOptions attemptToLoadAzureSdkProxy(Configuration configurati String username = configuration.get(USER_PROPERTY); String password = configuration.get(PASSWORD_PROPERTY); - return createOptions(host, port, nonProxyHostsString, username, password, createUnresolved); + return createOptions(configuration, host, port, nonProxyHostsString, username, password, createUnresolved); } - private static ProxyOptions createOptions(String host, int port, String nonProxyHostsString, String username, - String password, boolean createUnresolved) { + private static ProxyOptions createOptions(Configuration configuration, String host, int port, + String nonProxyHostsString, String username, String password, boolean createUnresolved) { InetSocketAddress socketAddress = (createUnresolved) ? InetSocketAddress.createUnresolved(host, port) : new InetSocketAddress(host, port); ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, socketAddress); if (!CoreUtils.isNullOrEmpty(nonProxyHostsString)) { - proxyOptions.nonProxyHosts = sanitizeJavaHttpNonProxyHosts(nonProxyHostsString); + proxyOptions.nonProxyHostsParserVersion = getNonProxyParserVersion(configuration); + proxyOptions.nonProxyHosts + = sanitizeJavaHttpNonProxyHosts(nonProxyHostsString, proxyOptions.nonProxyHostsParserVersion); LOGGER.atVerbose().addKeyValue("regex", proxyOptions.nonProxyHosts).log("Using non-proxy host regex"); } @@ -417,11 +447,28 @@ private static ProxyOptions createOptions(String host, int port, String nonProxy /* * Helper function that sanitizes 'http.nonProxyHosts' into a Pattern safe string. */ - static String sanitizeJavaHttpNonProxyHosts(String nonProxyHostsString) { - return sanitizeNonProxyHosts(HTTP_NON_PROXY_HOSTS_SPLIT.split(nonProxyHostsString)); + static String sanitizeJavaHttpNonProxyHosts(String nonProxyHostsString, int parserVersion) { + return sanitizeNonProxyHosts(HTTP_NON_PROXY_HOSTS_SPLIT.split(nonProxyHostsString), parserVersion); + } + + /* + * Gets the non-proxy hosts parser version from the configuration. Unknown versions fall back to version 1. + */ + private static int getNonProxyParserVersion(Configuration configuration) { + String version = configuration.get(NON_PROXY_PARSER_VERSION); + if (CoreUtils.isNullOrEmpty(version) || "1".equals(version.trim())) { + return 1; + } else if ("2".equals(version.trim())) { + return 2; + } + + LOGGER.atWarning() + .addKeyValue(NON_PROXY_PARSER_VERSION, version) + .log("Unknown non-proxy hosts parser version. Using version 1."); + return 1; } - private static String sanitizeNonProxyHosts(String[] nonProxyHosts) { + private static String sanitizeNonProxyHosts(String[] nonProxyHosts, int parserVersion) { StringBuilder sanitizedBuilder = new StringBuilder(); for (int i = 0; i < nonProxyHosts.length; i++) { @@ -429,78 +476,153 @@ private static String sanitizeNonProxyHosts(String[] nonProxyHosts) { sanitizedBuilder.append("|"); } - String prefixWildcard = ""; - String suffixWildcard = ""; - String sanitizedNonProxyHost = nonProxyHosts[i]; + sanitizedBuilder.append("(") + .append((parserVersion == 2) + ? sanitizeNonProxyHostVersion2(nonProxyHosts[i]) + : sanitizeNonProxyHostVersion1(nonProxyHosts[i])) + .append(")"); + } - /* - * If the non-proxy host begins with '*', '.*', or either with a trailing '?', it matches any prefix. If it - * begins with '.', or '.?', it matches the domain and its subdomains, so '.example.com' matches - * 'example.com' and 'api.example.com' but not 'badexample.com'. - */ - if (sanitizedNonProxyHost.startsWith(".*?")) { - prefixWildcard = ".*?"; - sanitizedNonProxyHost = sanitizedNonProxyHost.substring(3); - } else if (sanitizedNonProxyHost.startsWith(".*") || sanitizedNonProxyHost.startsWith("*?")) { - prefixWildcard = ".*?"; - sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2); - } else if (sanitizedNonProxyHost.startsWith("*")) { - prefixWildcard = ".*?"; - sanitizedNonProxyHost = sanitizedNonProxyHost.substring(1); - } else if (sanitizedNonProxyHost.startsWith(".?")) { - prefixWildcard = "(?:.*?\\.)?"; - sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2); - } else if (sanitizedNonProxyHost.startsWith(".")) { - prefixWildcard = "(?:.*?\\.)?"; - sanitizedNonProxyHost = sanitizedNonProxyHost.substring(1); - } + return sanitizedBuilder.toString(); + } - /* - * If the non-proxy host ends with '*', '.', or either with a trailing '?', it matches any suffix. Only the - * '*' and '?' are trimmed. A '.' is a literal dot, so '10.*' matches '10.0.0.1' but not '100.64.0.1', and - * '192.168.' matches '192.168.0.1' but not '192.1689.0.1'. - */ - if (sanitizedNonProxyHost.endsWith("*?")) { - suffixWildcard = ".*?"; - sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 2); - } else if (sanitizedNonProxyHost.endsWith("*") || sanitizedNonProxyHost.endsWith(".?")) { - suffixWildcard = ".*?"; - sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 1); - } else if (sanitizedNonProxyHost.endsWith(".")) { - suffixWildcard = ".*?"; - } + /* + * Version 1 of the non-proxy host conversion, kept as it was released except that entries such as '.*' no longer + * throw. Its suffix wildcards remove the character before them, so '10.*' also matches '100.64.0.1', and a leading + * '.' matches any prefix. + */ + private static String sanitizeNonProxyHostVersion1(String nonProxyHost) { + String prefixWildcard = ""; + String suffixWildcard = ""; + String sanitizedNonProxyHost = nonProxyHost; + + /* + * If the non-proxy host begins with either '.', '*', '.*', or any of the previous with a trailing '?' + * substring the non-proxy host and set the wildcard prefix. + */ + if (sanitizedNonProxyHost.startsWith(".")) { + prefixWildcard = ".*?"; + sanitizedNonProxyHost = sanitizedNonProxyHost.substring(1); + } else if (sanitizedNonProxyHost.startsWith(".?")) { + prefixWildcard = ".*?"; + sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2); + } else if (sanitizedNonProxyHost.startsWith("*?")) { + prefixWildcard = ".*?"; + sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2); + } else if (sanitizedNonProxyHost.startsWith("*")) { + prefixWildcard = ".*?"; + sanitizedNonProxyHost = sanitizedNonProxyHost.substring(1); + } else if (sanitizedNonProxyHost.startsWith(".*?")) { + prefixWildcard = ".*?"; + sanitizedNonProxyHost = sanitizedNonProxyHost.substring(3); + } else if (sanitizedNonProxyHost.startsWith(".*")) { + prefixWildcard = ".*?"; + sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2); + } - if (BRACKETED_IPV6_LITERAL.matcher(sanitizedNonProxyHost).matches()) { - // Match IPv6 literals such as '[::1]' as-is. As a regex, the brackets would be a character class. - sanitizedNonProxyHost = Pattern.quote(sanitizedNonProxyHost); - } else { - try { - // Sanitize the non-proxy host before any appending to prevent errant characters being added to - // the final response if the non-proxy host isn't a valid Pattern. - String attemptToSanitizeAsRegex = sanitizedNonProxyHost; - attemptToSanitizeAsRegex = UNESCAPED_PERIOD.matcher(attemptToSanitizeAsRegex).replaceAll("\\\\."); - attemptToSanitizeAsRegex = ANY.matcher(attemptToSanitizeAsRegex).replaceAll("\\.*?"); - sanitizedNonProxyHost = Pattern.compile(attemptToSanitizeAsRegex).pattern(); - } catch (PatternSyntaxException ex) { - /* - * Replace the non-proxy host with the sanitized value. - * - * The body of the non-proxy host is quoted to handle scenarios such a '127.0.0.1' or '*.azure.com' - * where without quoting the '.' in the string would be treated as the match any character instead - * of the literal '.' character. - */ - sanitizedNonProxyHost = Pattern.quote(sanitizedNonProxyHost); - } - } + /* + * Same with the ending of the non-proxy host, if it has a suffix wildcard trim the non-proxy host and retain the + * suffix wildcard. + */ + if (sanitizedNonProxyHost.endsWith(".")) { + suffixWildcard = ".*?"; + sanitizedNonProxyHost = removeEnd(sanitizedNonProxyHost, 2); + } else if (sanitizedNonProxyHost.endsWith(".?")) { + suffixWildcard = ".*?"; + sanitizedNonProxyHost = removeEnd(sanitizedNonProxyHost, 3); + } else if (sanitizedNonProxyHost.endsWith("*?")) { + suffixWildcard = ".*?"; + sanitizedNonProxyHost = removeEnd(sanitizedNonProxyHost, 3); + } else if (sanitizedNonProxyHost.endsWith("*")) { + suffixWildcard = ".*?"; + sanitizedNonProxyHost = removeEnd(sanitizedNonProxyHost, 2); + } else if (sanitizedNonProxyHost.endsWith(".*?")) { + suffixWildcard = ".*?"; + sanitizedNonProxyHost = removeEnd(sanitizedNonProxyHost, 4); + } else if (sanitizedNonProxyHost.endsWith(".*")) { + suffixWildcard = ".*?"; + sanitizedNonProxyHost = removeEnd(sanitizedNonProxyHost, 3); + } - sanitizedBuilder.append("(") - .append(prefixWildcard) - .append(sanitizedNonProxyHost) - .append(suffixWildcard) - .append(")"); + return prefixWildcard + toRegexOrQuote(sanitizedNonProxyHost) + suffixWildcard; + } + + /* + * Removes characters from the end of the non-proxy host. Version 1 removes more characters than the suffix it + * matched, so stop at an empty string rather than throwing for entries such as '.*'. + */ + private static String removeEnd(String nonProxyHost, int count) { + return nonProxyHost.substring(0, Math.max(0, nonProxyHost.length() - count)); + } + + private static String sanitizeNonProxyHostVersion2(String nonProxyHost) { + String prefixWildcard = ""; + String suffixWildcard = ""; + String sanitizedNonProxyHost = nonProxyHost; + + /* + * If the non-proxy host begins with '*', '.*', or either with a trailing '?', it matches any prefix. If it + * begins with '.', or '.?', it matches the domain and its subdomains, so '.example.com' matches 'example.com' + * and 'api.example.com' but not 'badexample.com'. + */ + if (sanitizedNonProxyHost.startsWith(".*?")) { + prefixWildcard = ".*?"; + sanitizedNonProxyHost = sanitizedNonProxyHost.substring(3); + } else if (sanitizedNonProxyHost.startsWith(".*") || sanitizedNonProxyHost.startsWith("*?")) { + prefixWildcard = ".*?"; + sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2); + } else if (sanitizedNonProxyHost.startsWith("*")) { + prefixWildcard = ".*?"; + sanitizedNonProxyHost = sanitizedNonProxyHost.substring(1); + } else if (sanitizedNonProxyHost.startsWith(".?")) { + prefixWildcard = "(?:.*?\\.)?"; + sanitizedNonProxyHost = sanitizedNonProxyHost.substring(2); + } else if (sanitizedNonProxyHost.startsWith(".")) { + prefixWildcard = "(?:.*?\\.)?"; + sanitizedNonProxyHost = sanitizedNonProxyHost.substring(1); } - return sanitizedBuilder.toString(); + /* + * If the non-proxy host ends with '*', '.', or either with a trailing '?', it matches any suffix. Only the '*' + * and '?' are trimmed. A '.' is a literal dot, so '10.*' matches '10.0.0.1' but not '100.64.0.1', and + * '192.168.' matches '192.168.0.1' but not '192.1689.0.1'. + */ + if (sanitizedNonProxyHost.endsWith("*?")) { + suffixWildcard = ".*?"; + sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 2); + } else if (sanitizedNonProxyHost.endsWith("*") || sanitizedNonProxyHost.endsWith(".?")) { + suffixWildcard = ".*?"; + sanitizedNonProxyHost = sanitizedNonProxyHost.substring(0, sanitizedNonProxyHost.length() - 1); + } else if (sanitizedNonProxyHost.endsWith(".")) { + suffixWildcard = ".*?"; + } + + // Match IPv6 literals such as '[::1]' as-is. As a regex, the brackets would be a character class. + String body = BRACKETED_IPV6_LITERAL.matcher(sanitizedNonProxyHost).matches() + ? Pattern.quote(sanitizedNonProxyHost) + : toRegexOrQuote(sanitizedNonProxyHost); + + return prefixWildcard + body + suffixWildcard; + } + + private static String toRegexOrQuote(String nonProxyHost) { + try { + // Sanitize the non-proxy host before any appending to prevent errant characters being added to the final + // response if the non-proxy host isn't a valid Pattern. + String attemptToSanitizeAsRegex = nonProxyHost; + attemptToSanitizeAsRegex = UNESCAPED_PERIOD.matcher(attemptToSanitizeAsRegex).replaceAll("\\\\."); + attemptToSanitizeAsRegex = ANY.matcher(attemptToSanitizeAsRegex).replaceAll("\\.*?"); + return Pattern.compile(attemptToSanitizeAsRegex).pattern(); + } catch (PatternSyntaxException ex) { + /* + * Replace the non-proxy host with the sanitized value. + * + * The body of the non-proxy host is quoted to handle scenarios such a '127.0.0.1' or '*.azure.com' where + * without quoting the '.' in the string would be treated as the match any character instead of the literal + * '.' character. + */ + return Pattern.quote(nonProxyHost); + } } /** diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/implementation/util/ProxyOptionsAccessHelper.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/util/ProxyOptionsAccessHelper.java new file mode 100644 index 0000000000000..fe1d065e941dd --- /dev/null +++ b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/util/ProxyOptionsAccessHelper.java @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.core.implementation.util; + +import com.azure.core.http.ProxyOptions; + +/** + * This class is used to access internal methods on {@link ProxyOptions}. + */ +public final class ProxyOptionsAccessHelper { + private static ProxyOptionsAccessor accessor; + + /** + * Type defining the methods to access the internal methods on {@link ProxyOptions}. + */ + public interface ProxyOptionsAccessor { + /** + * Gets the version of the parser that converted the non-proxy hosts of {@link ProxyOptions} to a regex. + * + * @param proxyOptions The {@link ProxyOptions} to get the parser version from. + * @return The parser version, 1 or 2. Version 1 is returned when no non-proxy hosts were set. + */ + int getNonProxyHostsParserVersion(ProxyOptions proxyOptions); + } + + /** + * Gets the version of the parser that converted the non-proxy hosts of {@link ProxyOptions} to a regex. + * + * @param proxyOptions The {@link ProxyOptions} to get the parser version from. + * @return The parser version, 1 or 2. Version 1 is returned when no non-proxy hosts were set. + */ + public static int getNonProxyHostsParserVersion(ProxyOptions proxyOptions) { + return accessor.getNonProxyHostsParserVersion(proxyOptions); + } + + /** + * Sets the {@link ProxyOptionsAccessor}. + * + * @param accessor The {@link ProxyOptionsAccessor}. + */ + public static void setAccessor(ProxyOptionsAccessor accessor) { + ProxyOptionsAccessHelper.accessor = accessor; + } + + private ProxyOptionsAccessHelper() { + } +} diff --git a/sdk/core/azure-core/src/test/java/com/azure/core/http/ProxyOptionsTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/http/ProxyOptionsTests.java index 94083bc2fd7f8..e1e674cc349a8 100644 --- a/sdk/core/azure-core/src/test/java/com/azure/core/http/ProxyOptionsTests.java +++ b/sdk/core/azure-core/src/test/java/com/azure/core/http/ProxyOptionsTests.java @@ -49,6 +49,7 @@ public class ProxyOptionsTests { private static final String JAVA_SYSTEM_PROXY_PREREQUISITE = "java.net.useSystemProxies"; private static final String JAVA_NON_PROXY_HOSTS = "http.nonProxyHosts"; + private static final String NON_PROXY_PARSER_VERSION = "AZURE_NON_PROXY_PARSER_VERSION"; private static final String JAVA_HTTPS_PROXY_HOST = "https.proxyHost"; private static final String JAVA_HTTPS_PROXY_PORT = "https.proxyPort"; @@ -497,33 +498,27 @@ private static Stream nonProxyHostsSupplier() { public void sanitizeNoProxyDoesNotSplitEscapedCommas() { String noProxy = "noproxy\\,withescapedcomma"; - assertEquals("(" + noProxy + ")", ProxyOptions.sanitizeNoProxy(noProxy)); + assertEquals("(" + noProxy + ")", ProxyOptions.sanitizeNoProxy(noProxy, 1)); } @Test public void sanitizeJavaHttpNonProxyHostsDoesNotSplitEscapedPipes() { String nonProxyHosts = "nonproxyhosts\\|withescapedpipe"; - assertEquals("(" + nonProxyHosts + ")", ProxyOptions.sanitizeNoProxy(nonProxyHosts)); + assertEquals("(" + nonProxyHosts + ")", ProxyOptions.sanitizeNoProxy(nonProxyHosts, 1)); } /** - * Tests that wildcards, leading and trailing dots, and IPv6 literals in non-proxy hosts only match the intended - * hosts, however the non-proxy hosts are configured. Hosts are matched the way HTTP clients match them: the whole - * host, ignoring case. + * Tests that with AZURE_NON_PROXY_PARSER_VERSION set to 2, wildcards, leading and trailing dots, and IPv6 literals + * in non-proxy hosts only match the intended hosts, however the non-proxy hosts are configured. Hosts are matched + * the way HTTP clients match them: the whole host, ignoring case. */ @ParameterizedTest @MethodSource("nonProxyHostsMatchOnlyIntendedHostsSupplier") - public void nonProxyHostsMatchOnlyIntendedHosts(String nonProxyHost, List bypassedHosts, + public void nonProxyHostsParserVersion2MatchesOnlyIntendedHosts(String nonProxyHost, List bypassedHosts, List proxiedHosts) { - String[] sanitizedNonProxyHosts = { - new ProxyOptions(ProxyOptions.Type.HTTP, InetSocketAddress.createUnresolved("localhost", 7777)) - .setNonProxyHosts(nonProxyHost) - .getNonProxyHosts(), - fromConfiguration(createJavaEnvConfiguration(null, null, nonProxyHost, true), true).getNonProxyHosts(), - fromConfiguration(createExplicitConfiguration(null, null, nonProxyHost), true).getNonProxyHosts(), - fromConfiguration(setJavaSystemProxyPrerequisiteToTrue("http://localhost:7777", nonProxyHost, true), true) - .getNonProxyHosts() }; + List sanitizedNonProxyHosts = new ArrayList<>(loadNonProxyHostsRegexes(nonProxyHost, "2")); + sanitizedNonProxyHosts.add(ProxyOptions.sanitizeJavaHttpNonProxyHosts(nonProxyHost, 2)); for (String sanitizedNonProxyHost : sanitizedNonProxyHosts) { Pattern pattern = compile(sanitizedNonProxyHost, Pattern.CASE_INSENSITIVE); @@ -560,6 +555,65 @@ private static Stream nonProxyHostsMatchOnlyIntendedHostsSupplier() { Arguments.of(".*?", anyHost, Collections.emptyList())); } + /** + * Tests that version 1 of the non-proxy hosts parser is used when AZURE_NON_PROXY_PARSER_VERSION is unset, 1, or + * unknown, and that it keeps the released regex, except that entries such as '.*' no longer throw. + */ + @ParameterizedTest + @MethodSource("nonProxyHostsParserVersion1Supplier") + public void nonProxyHostsParserVersion1KeepsReleasedRegex(String nonProxyHost, String expectedRegex) { + assertEquals(expectedRegex, ProxyOptions.sanitizeJavaHttpNonProxyHosts(nonProxyHost, 1)); + + for (String parserVersion : new String[] { null, "1", "3" }) { + for (String regex : loadNonProxyHostsRegexes(nonProxyHost, parserVersion)) { + assertEquals(expectedRegex, regex, () -> "AZURE_NON_PROXY_PARSER_VERSION=" + parserVersion); + } + } + } + + private static Stream nonProxyHostsParserVersion1Supplier() { + return Stream.of(Arguments.of("storage1*", "(storage.*?)"), Arguments.of("10.*", "(10.*?)"), + Arguments.of("192.168.", "(192\\.16.*?)"), Arguments.of(".example.com", "(.*?example\\.com)"), + Arguments.of("[::1]", "([::1])"), Arguments.of(".*", "(.*?.*?)"), Arguments.of(".*?", "(.*?.*?)")); + } + + /* + * Loads the non-proxy host from the Java proxy system properties, the Azure SDK proxy properties, and NO_PROXY, with + * AZURE_NON_PROXY_PARSER_VERSION set to the given value, and returns the regex each creates. A null value masks the + * setting in the real environment. + */ + private static List loadNonProxyHostsRegexes(String nonProxyHost, String parserVersion) { + TestConfigurationSource javaProxy = new TestConfigurationSource().put(JAVA_SYSTEM_PROXY_PREREQUISITE, "false") + .put(JAVA_HTTPS_PROXY_HOST, PROXY_HOST) + .put(JAVA_HTTPS_PROXY_PORT, "443") + .put(JAVA_HTTPS_PROXY_USER, null) + .put(JAVA_HTTPS_PROXY_PASSWORD, null) + .put(JAVA_NON_PROXY_HOSTS, nonProxyHost) + .put(NON_PROXY_PARSER_VERSION, parserVersion); + + TestConfigurationSource azureSdkProxy = new TestConfigurationSource().put("http.proxy.hostname", PROXY_HOST) + .put("http.proxy.port", "443") + .put("http.proxy.non-proxy-hosts", nonProxyHost); + TestConfigurationSource azureSdkProxySystemProperties + = new TestConfigurationSource().put(JAVA_SYSTEM_PROXY_PREREQUISITE, "false") + .put(NON_PROXY_PARSER_VERSION, parserVersion); + + TestConfigurationSource environmentProxy + = new TestConfigurationSource().put(JAVA_SYSTEM_PROXY_PREREQUISITE, "true") + .put(Configuration.PROPERTY_HTTPS_PROXY, "http://localhost:7777") + .put(Configuration.PROPERTY_NO_PROXY, nonProxyHost) + .put(NON_PROXY_PARSER_VERSION, parserVersion); + + return Arrays.asList( + fromConfiguration(new ConfigurationBuilder(EMPTY_SOURCE, javaProxy, EMPTY_SOURCE).build(), true) + .getNonProxyHosts(), + fromConfiguration( + new ConfigurationBuilder(azureSdkProxy, azureSdkProxySystemProperties, EMPTY_SOURCE).build(), true) + .getNonProxyHosts(), + fromConfiguration(new ConfigurationBuilder(EMPTY_SOURCE, EMPTY_SOURCE, environmentProxy).build(), true) + .getNonProxyHosts()); + } + private static Configuration setJavaSystemProxyPrerequisiteToTrue(String proxy, String nonProxyHosts, boolean isHttps) { TestConfigurationSource testSource = new TestConfigurationSource().put(JAVA_SYSTEM_PROXY_PREREQUISITE, "true")