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: + *
- * This is necessary as Vert.x will apply its own sanitization logic. + * 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. 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..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 @@ -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; @@ -226,6 +230,84 @@ public void buildWithAllProxyTypes(ProxyOptions.Type type) throws Exception { assertEquals(proxyPassword, vertxProxyOptions.getPassword()); } + /** + * 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({ + "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 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 { + closeClient(httpClient); + } + } + + @ParameterizedTest + @ValueSource(strings = { "localhost", "LOCALHOST", "local*", ".localhost" }) + public void parserVersion2RequestToNonProxyHostConnectsDirectly(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 parserVersion2RequestToOtherHostUsesProxy(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(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 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..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 @@ -37,14 +37,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 +45,27 @@ public void defaultOptionsReturnsBaseClient() { VertxHttpClient httpClient = (VertxHttpClient) new VertxHttpClientProvider().createInstance(new HttpClientOptions()); - ProxyOptions environmentProxy = loadEnvironmentProxy(); + assertUsesEnvironmentProxy(httpClient); + } + + /* + * 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) { io.vertx.core.net.ProxyOptions proxyOptions = httpClient.buildOptions.getProxyOptions(); + if (proxyOptions == null) { + proxyOptions = httpClient.getProxyOptions("example.com"); + } + + ProxyOptions environmentProxy = loadEnvironmentProxy(); if (environmentProxy == null) { assertNull(proxyOptions); } else { assertNotNull(proxyOptions); assertEquals(environmentProxy.getAddress().getHostName(), proxyOptions.getHost()); + assertEquals(environmentProxy.getAddress().getPort(), proxyOptions.getPort()); } } diff --git a/sdk/core/azure-core/CHANGELOG.md b/sdk/core/azure-core/CHANGELOG.md index c147c389a65f5..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,6 +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 `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 2c4be8dd4c62c..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; @@ -72,6 +73,14 @@ public class ProxyOptions { private static final Pattern UNESCAPED_PERIOD = Pattern.compile("(? NON_PROXY_PROPERTY = ConfigurationPropertyBuilder.ofString(ConfigurationProperties.HTTP_PROXY_NON_PROXY_HOSTS) @@ -101,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. @@ -130,13 +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. - * Individual host strings may contain regex characters such as {@code '*'}. + *
+ * 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: + *
+ * 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 @@ -231,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
@@ -313,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");
}
@@ -342,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,
@@ -366,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) {
@@ -382,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");
}
@@ -408,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);
}
- private static String sanitizeNonProxyHosts(String[] nonProxyHosts) {
+ /*
+ * 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, int parserVersion) {
StringBuilder sanitizedBuilder = new StringBuilder();
for (int i = 0; i < nonProxyHosts.length; i++) {
@@ -420,84 +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 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);
- }
+ return sanitizedBuilder.toString();
+ }
- /*
- * 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 = 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("*")) {
- 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);
- }
+ /*
+ * 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);
+ }
- 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 49bb3269bcfb6..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
@@ -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;
@@ -47,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";
@@ -495,14 +498,120 @@ private static Stream