diff --git a/docs/source/flight_sql_jdbc_driver.rst b/docs/source/flight_sql_jdbc_driver.rst index 6fee6ad5b7..bf23abc6a6 100644 --- a/docs/source/flight_sql_jdbc_driver.rst +++ b/docs/source/flight_sql_jdbc_driver.rst @@ -220,6 +220,60 @@ session setup. On expiration, the driver cancels pending login RPCs and throws ``connectTimeoutMs`` property separately controls the Netty socket connection timeout. +Connecting Through a Proxy +========================== + +By default, the driver uses the JVM proxy settings, such as the +``https.proxyHost`` and ``https.proxyPort`` system properties. A proxy +can instead be configured per connection with the following properties. +They are only used when ``useProxy`` is enabled, in which case they +take precedence over the JVM proxy settings. + +.. list-table:: + :header-rows: 1 + + * - Parameter + - Default + - Description + + * - useProxy + - false + - Whether to use the proxy configured by the properties below instead + of the JVM proxy settings + + * - proxyHost + - null + - The host of the HTTP proxy. Required unless ``nonProxyHosts`` is ``*`` + + * - proxyPort + - null + - The port of the HTTP proxy. Required when ``proxyHost`` is set + + * - proxyUser + - null + - The username for Basic authentication with the proxy + + * - proxyPassword + - null + - The password for Basic authentication with the proxy + + * - nonProxyHosts + - null + - Hosts that are connected to directly, bypassing the proxy, separated + by ``|``. ``*`` can be used as a wildcard, as in ``*.example.com``, + and ``*`` alone bypasses the proxy for every host + +In a connection URI, the ``|`` separator in ``nonProxyHosts`` must be +URI-encoded as ``%7C``. For example, the following URI :: + + jdbc:arrow-flight-sql://flight.example.com:443/?useProxy=true&proxyHost=proxy.example.com&proxyPort=3128&nonProxyHosts=localhost%7C*.internal + +connects through the proxy at ``proxy.example.com:3128``, except to +``localhost`` and the hosts in the ``internal`` domain. + +To ignore the JVM proxy settings and connect directly, enable +``useProxy`` and set ``nonProxyHosts`` to ``*``. + OAuth 2.0 Authentication ======================== diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java index d3485171b7..07f0d27ec2 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java @@ -148,6 +148,7 @@ private static ArrowFlightSqlClientHandler createNewClientHandler( .withConnectTimeout(config.getConnectTimeout()) .withDriverVersion(driverVersion) .withOAuthConfiguration(config.getOauthConfiguration()) + .withProxyDetector(config.getProxyDetector()) .build(); } diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java index e91dce8e83..c5fb09df9a 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java @@ -18,6 +18,7 @@ import com.google.common.collect.ImmutableMap; import io.grpc.ManagedChannel; +import io.grpc.ProxyDetector; import io.grpc.netty.NettyChannelBuilder; import io.netty.channel.ChannelOption; import java.io.IOException; @@ -783,6 +784,8 @@ public static final class Builder { @VisibleForTesting @Nullable OAuthConfiguration oauthConfig; + @VisibleForTesting @Nullable ProxyDetector proxyDetector; + // These two middleware are for internal use within build() and should not be // exposed by builder // APIs. @@ -826,6 +829,7 @@ public Builder() {} this.oauthConfig = original.oauthConfig; this.ownsSession = false; this.followEndpointLocations = original.followEndpointLocations; + this.proxyDetector = original.proxyDetector; if (original.retainCookies) { this.cookieFactory = original.cookieFactory; @@ -1212,6 +1216,18 @@ public Builder withOAuthConfiguration(final OAuthConfiguration oauthConfig) { return this; } + /** + * Sets the {@link ProxyDetector} for this handler, which overrides the JVM-wide proxy settings + * used by default. + * + * @param proxyDetector the proxy detector, or null to use the default one + * @return this builder instance + */ + public Builder withProxyDetector(ProxyDetector proxyDetector) { + this.proxyDetector = proxyDetector; + return this; + } + public String getCacheKey() { return getLocation().toString(); } @@ -1300,6 +1316,10 @@ public ArrowFlightSqlClientHandler build() throws SQLException { channelBuilder.userAgent(userAgent); + if (proxyDetector != null) { + channelBuilder.proxyDetector(proxyDetector); + } + if (connectTimeout != null) { channelBuilder.withOption( ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) connectTimeout.toMillis()); diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/utils/FlightProxyDetector.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/utils/FlightProxyDetector.java new file mode 100644 index 0000000000..8b6c6bb780 --- /dev/null +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/utils/FlightProxyDetector.java @@ -0,0 +1,164 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.arrow.driver.jdbc.client.utils; + +import io.grpc.HttpConnectProxiedSocketAddress; +import io.grpc.ProxiedSocketAddress; +import io.grpc.ProxyDetector; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.SocketAddress; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.regex.Pattern; + +/** + * A {@link ProxyDetector} configured from the JDBC connection properties, which takes precedence + * over the JVM-wide proxy settings used by default by gRPC. + * + *

Connections are tunneled through an HTTP CONNECT proxy, unless the target host matches one of + * the non-proxy host patterns. Without a proxy host, every connection is made directly. + */ +public final class FlightProxyDetector implements ProxyDetector { + private static final String MATCH_ALL_REGEX = ".*"; + + private final String proxyHost; + private final int proxyPort; + private final String proxyUser; + private final String proxyPassword; + private final List nonProxyHosts; + + private FlightProxyDetector( + String proxyHost, + int proxyPort, + String proxyUser, + String proxyPassword, + List nonProxyHosts) { + this.proxyHost = proxyHost; + this.proxyPort = proxyPort; + this.proxyUser = proxyUser; + this.proxyPassword = proxyPassword; + this.nonProxyHosts = nonProxyHosts; + } + + /** + * Creates a validated {@link FlightProxyDetector}. + * + * @param proxyHost the proxy host, or null to connect directly to every host. + * @param proxyPort the proxy port, required when {@code proxyHost} is set. + * @param proxyUser the username for proxy authentication. + * @param proxyPassword the password for proxy authentication. + * @param nonProxyHosts {@code |}-separated host patterns, with {@code *} wildcards, that bypass + * the proxy. + * @return the proxy detector. + * @throws SQLException if the configuration is invalid. + */ + public static FlightProxyDetector create( + String proxyHost, + Integer proxyPort, + String proxyUser, + String proxyPassword, + String nonProxyHosts) + throws SQLException { + final List nonProxyHostPatterns = parseNonProxyHosts(nonProxyHosts); + if (isNullOrEmpty(proxyHost)) { + if (!matchesAllHosts(nonProxyHostPatterns)) { + throw new SQLException( + "proxyHost is required when useProxy is enabled, unless nonProxyHosts is <*>."); + } + return new FlightProxyDetector(null, 0, null, null, nonProxyHostPatterns); + } + if (proxyPort == null) { + throw new SQLException("proxyPort is required when proxyHost is set."); + } + if (proxyPort < 1 || proxyPort > 65535) { + throw new SQLException(String.format("Invalid proxyPort <%d>.", proxyPort)); + } + if (isNullOrEmpty(proxyUser) != isNullOrEmpty(proxyPassword)) { + throw new SQLException("proxyUser and proxyPassword must be set together."); + } + return new FlightProxyDetector( + proxyHost, proxyPort, proxyUser, proxyPassword, nonProxyHostPatterns); + } + + @Override + public ProxiedSocketAddress proxyFor(SocketAddress targetServerAddress) throws IOException { + if (proxyHost == null || !(targetServerAddress instanceof InetSocketAddress)) { + return null; + } + final InetSocketAddress targetAddress = (InetSocketAddress) targetServerAddress; + if (isNonProxyHost(targetAddress.getHostString())) { + return null; + } + final InetSocketAddress proxyAddress = new InetSocketAddress(proxyHost, proxyPort); + if (proxyAddress.isUnresolved()) { + throw new IOException(String.format("Unable to resolve proxy host <%s>.", proxyHost)); + } + final HttpConnectProxiedSocketAddress.Builder builder = + HttpConnectProxiedSocketAddress.newBuilder() + .setTargetAddress(targetAddress) + .setProxyAddress(proxyAddress); + if (proxyUser != null) { + builder.setUsername(proxyUser).setPassword(proxyPassword); + } + return builder.build(); + } + + private boolean isNonProxyHost(String host) { + final String normalizedHost = host.toLowerCase(Locale.ROOT); + return nonProxyHosts.stream().anyMatch(pattern -> pattern.matcher(normalizedHost).matches()); + } + + private static List parseNonProxyHosts(String nonProxyHosts) { + final List patterns = new ArrayList<>(); + if (nonProxyHosts == null) { + return patterns; + } + for (String hostPattern : nonProxyHosts.split("\\|", -1)) { + String trimmed = hostPattern.trim().toLowerCase(Locale.ROOT); + if (trimmed.isEmpty()) { + continue; + } + // A leading dot matches any subdomain, as in ".example.com". + if (trimmed.startsWith(".")) { + trimmed = "*" + trimmed; + } + final String[] literals = trimmed.split("\\*", -1); + final StringBuilder regex = new StringBuilder(); + for (int i = 0; i < literals.length; i++) { + if (i > 0) { + regex.append(".*"); + } + if (!literals[i].isEmpty()) { + regex.append(Pattern.quote(literals[i])); + } + } + patterns.add(Pattern.compile(regex.toString())); + } + return patterns; + } + + private static boolean matchesAllHosts(List patterns) { + return patterns.stream().anyMatch(pattern -> pattern.pattern().equals(MATCH_ALL_REGEX)); + } + + private static boolean isNullOrEmpty(String value) { + return value == null || value.isEmpty(); + } +} diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/ArrowFlightConnectionConfigImpl.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/ArrowFlightConnectionConfigImpl.java index d6fafb7543..996f09ab37 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/ArrowFlightConnectionConfigImpl.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/ArrowFlightConnectionConfigImpl.java @@ -25,6 +25,7 @@ import java.util.Properties; import org.apache.arrow.driver.jdbc.ArrowFlightConnection; import org.apache.arrow.driver.jdbc.client.oauth.OAuthConfiguration; +import org.apache.arrow.driver.jdbc.client.utils.FlightProxyDetector; import org.apache.arrow.flight.CallHeaders; import org.apache.arrow.flight.CallOption; import org.apache.arrow.flight.FlightCallHeaders; @@ -37,6 +38,16 @@ /** A {@link ConnectionConfig} for the {@link ArrowFlightConnection}. */ public final class ArrowFlightConnectionConfigImpl extends ConnectionConfigImpl { + + // The proxy properties without a default value, which are only used when useProxy is enabled. + private static final ArrowFlightConnectionProperty[] PROXY_PROPERTIES = { + ArrowFlightConnectionProperty.PROXY_HOST, + ArrowFlightConnectionProperty.PROXY_PORT, + ArrowFlightConnectionProperty.PROXY_USER, + ArrowFlightConnectionProperty.PROXY_PASSWORD, + ArrowFlightConnectionProperty.NON_PROXY_HOSTS, + }; + public ArrowFlightConnectionConfigImpl(final Properties properties) { super(properties); } @@ -214,6 +225,36 @@ public boolean useClientCache() { return ArrowFlightConnectionProperty.USE_CLIENT_CACHE.getBoolean(properties); } + /** + * Returns the proxy detector configured by the proxy properties if useProxy is enabled, null + * otherwise. + * + * @return the proxy detector or null + * @throws SQLException if the proxy configuration is invalid + */ + public @Nullable FlightProxyDetector getProxyDetector() throws SQLException { + if (!ArrowFlightConnectionProperty.USE_PROXY.getBoolean(properties)) { + return null; + } + + final Integer proxyPort; + try { + proxyPort = ArrowFlightConnectionProperty.PROXY_PORT.getInteger(properties); + } catch (NumberFormatException e) { + throw new SQLException( + String.format( + "Invalid proxyPort <%s>.", + ArrowFlightConnectionProperty.PROXY_PORT.getString(properties)), + e); + } + return FlightProxyDetector.create( + ArrowFlightConnectionProperty.PROXY_HOST.getString(properties), + proxyPort, + ArrowFlightConnectionProperty.PROXY_USER.getString(properties), + ArrowFlightConnectionProperty.PROXY_PASSWORD.getString(properties), + ArrowFlightConnectionProperty.NON_PROXY_HOSTS.getString(properties)); + } + /** * Gets the {@link CallOption}s from this {@link ConnectionConfig}. * @@ -302,6 +343,14 @@ public enum ArrowFlightConnectionProperty implements ConnectionProperty { CONNECT_TIMEOUT_MILLIS("connectTimeoutMs", 10000, Type.NUMBER, false), USE_CLIENT_CACHE("useClientCache", true, Type.BOOLEAN, false), + // Proxy configuration properties + USE_PROXY("useProxy", false, Type.BOOLEAN, false), + PROXY_HOST("proxyHost", null, Type.STRING, false), + PROXY_PORT("proxyPort", null, Type.NUMBER, false), + PROXY_USER("proxyUser", null, Type.STRING, false), + PROXY_PASSWORD("proxyPassword", null, Type.STRING, false), + NON_PROXY_HOSTS("nonProxyHosts", null, Type.STRING, false), + // OAuth configuration properties OAUTH_FLOW("oauth.flow", null, Type.STRING, false), OAUTH_CLIENT_ID("oauth.clientId", null, Type.STRING, false), diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ConnectionProxyTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ConnectionProxyTest.java new file mode 100644 index 0000000000..cd3c87d89c --- /dev/null +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ConnectionProxyTest.java @@ -0,0 +1,323 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.arrow.driver.jdbc; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.Base64; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import org.apache.arrow.driver.jdbc.authentication.UserPasswordAuthentication; +import org.apache.arrow.driver.jdbc.utils.MockFlightSqlProducer; +import org.apache.arrow.flight.FlightServer; +import org.apache.arrow.flight.Location; +import org.apache.arrow.memory.BufferAllocator; +import org.apache.arrow.memory.RootAllocator; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * Tests the proxy connection properties. The proxy is a minimal HTTP CONNECT server that records + * the requests it receives, so the tests can check which connections went through it. + */ +public class ConnectionProxyTest { + + private static final String HOST = "localhost"; + private static final String PROXY_HOST = "127.0.0.1"; + private static final String USER = "user1"; + private static final String PASSWORD = "pass1"; + + private static BufferAllocator allocator; + private static FlightServer server; + + private ConnectProxyServer proxy; + + @BeforeAll + public static void setUpServer() throws Exception { + DriverManager.registerDriver(new ArrowFlightJdbcDriver()); + allocator = new RootAllocator(Long.MAX_VALUE); + server = + FlightServer.builder( + allocator, Location.forGrpcInsecure(HOST, 0), new MockFlightSqlProducer()) + .headerAuthenticator( + new UserPasswordAuthentication.Builder() + .user(USER, PASSWORD) + .build() + .authenticate()) + .build() + .start(); + } + + @AfterAll + public static void tearDownServer() throws Exception { + server.close(); + allocator.close(); + } + + @BeforeEach + public void setUp() throws Exception { + proxy = new ConnectProxyServer(); + } + + @AfterEach + public void tearDown() throws Exception { + proxy.close(); + } + + private static String url(final String proxyParameters) { + return String.format( + "jdbc:arrow-flight-sql://%s:%d/?useEncryption=false&user=%s&password=%s%s", + HOST, server.getPort(), USER, PASSWORD, proxyParameters); + } + + private String proxyParameters() { + return String.format("&useProxy=true&proxyHost=%s&proxyPort=%d", PROXY_HOST, proxy.getPort()); + } + + private static void connect(final String url) throws SQLException { + try (Connection connection = DriverManager.getConnection(url)) { + assertTrue(connection.isValid(0)); + } + } + + @Test + public void testConnectionThroughProxy() throws Exception { + connect(url(proxyParameters())); + + assertFalse(proxy.requests.isEmpty()); + for (final String request : proxy.requests) { + assertTrue(request.startsWith("CONNECT "), request); + assertTrue(request.contains(":" + server.getPort() + " "), request); + } + } + + @Test + public void testProxyIsNotUsedByDefault() throws Exception { + // The proxy properties are ignored unless useProxy is enabled. + connect(url(String.format("&proxyHost=%s&proxyPort=%d", PROXY_HOST, proxy.getPort()))); + + assertTrue(proxy.requests.isEmpty()); + } + + @Test + public void testNonProxyHostsConnectDirectly() throws Exception { + connect(url(proxyParameters() + "&nonProxyHosts=" + HOST)); + + assertTrue(proxy.requests.isEmpty()); + } + + @Test + public void testNonProxyHostsDoNotMatchOtherHosts() throws Exception { + connect(url(proxyParameters() + "&nonProxyHosts=*.internal%7Cother.example.com")); + + assertFalse(proxy.requests.isEmpty()); + } + + @Test + public void testAllHostsConnectDirectly() throws Exception { + // Without a proxy host, "*" disables the proxy for every host. + connect(url("&useProxy=true&nonProxyHosts=*")); + + assertTrue(proxy.requests.isEmpty()); + } + + @Test + public void testProxyCredentialsAreSent() throws Exception { + connect(url(proxyParameters() + "&proxyUser=proxy-user&proxyPassword=proxy-secret")); + + final String expected = + "Basic " + + Base64.getEncoder() + .encodeToString("proxy-user:proxy-secret".getBytes(StandardCharsets.UTF_8)); + assertFalse(proxy.authorizations.isEmpty()); + assertEquals(expected, proxy.authorizations.get(0)); + } + + @Test + public void testNoCredentialsAreSentWithoutProxyUser() throws Exception { + connect(url(proxyParameters())); + + assertTrue(proxy.authorizations.isEmpty()); + } + + @Test + public void testProxyInProperties() throws Exception { + final java.util.Properties properties = new java.util.Properties(); + properties.setProperty("useProxy", "true"); + properties.setProperty("proxyHost", PROXY_HOST); + properties.setProperty("proxyPort", String.valueOf(proxy.getPort())); + + try (Connection connection = DriverManager.getConnection(url(""), properties)) { + assertTrue(connection.isValid(0)); + } + + assertFalse(proxy.requests.isEmpty()); + } + + @Test + public void testUnreachableProxyFailsConnection() throws Exception { + final int unusedPort; + try (ServerSocket socket = new ServerSocket(0, 0, InetAddress.getByName(PROXY_HOST))) { + unusedPort = socket.getLocalPort(); + } + + // The connection would succeed if the proxy were bypassed. + assertThrows( + SQLException.class, + () -> + connect( + url( + String.format( + "&useProxy=true&proxyHost=%s&proxyPort=%d", PROXY_HOST, unusedPort)))); + } + + @Test + public void testInvalidProxyPortFailsConnection() { + assertThrows( + SQLException.class, + () -> connect(url("&useProxy=true&proxyHost=" + PROXY_HOST + "&proxyPort=not-a-port"))); + } + + @Test + public void testMissingProxyHostFailsConnection() { + assertThrows(SQLException.class, () -> connect(url("&useProxy=true"))); + } + + /** A minimal HTTP CONNECT proxy that records the requests and credentials it receives. */ + private static final class ConnectProxyServer implements AutoCloseable { + final List requests = new CopyOnWriteArrayList<>(); + final List authorizations = new CopyOnWriteArrayList<>(); + private final List sockets = new CopyOnWriteArrayList<>(); + private final ServerSocket serverSocket; + + ConnectProxyServer() throws IOException { + serverSocket = new ServerSocket(0, 50, InetAddress.getByName(PROXY_HOST)); + startThread( + () -> { + while (!serverSocket.isClosed()) { + final Socket client = serverSocket.accept(); + sockets.add(client); + startThread(() -> handle(client)); + } + }); + } + + int getPort() { + return serverSocket.getLocalPort(); + } + + private void handle(final Socket client) throws IOException { + final InputStream in = client.getInputStream(); + final String requestLine = readLine(in); + String line = readLine(in); + while (line != null && !line.isEmpty()) { + if (line.toLowerCase(java.util.Locale.ROOT).startsWith("proxy-authorization:")) { + authorizations.add(line.substring(line.indexOf(':') + 1).trim()); + } + line = readLine(in); + } + requests.add(requestLine); + + // CONNECT host:port HTTP/1.1 + final String authority = requestLine.split(" ")[1]; + final int separator = authority.lastIndexOf(':'); + final Socket target = + new Socket( + authority.substring(0, separator), + Integer.parseInt(authority.substring(separator + 1))); + sockets.add(target); + + final OutputStream out = client.getOutputStream(); + out.write("HTTP/1.1 200 Connection established\r\n\r\n".getBytes(StandardCharsets.US_ASCII)); + out.flush(); + + startThread(() -> pipe(target, client)); + pipe(client, target); + } + + private static void pipe(final Socket from, final Socket to) throws IOException { + final byte[] buffer = new byte[8192]; + final InputStream in = from.getInputStream(); + final OutputStream out = to.getOutputStream(); + try { + int read; + while ((read = in.read(buffer)) != -1) { + out.write(buffer, 0, read); + out.flush(); + } + } finally { + from.close(); + to.close(); + } + } + + /** Reads a line byte by byte, so no data after the headers is consumed. */ + private static String readLine(final InputStream in) throws IOException { + final ByteArrayOutputStream line = new ByteArrayOutputStream(); + int b; + while ((b = in.read()) != -1 && b != '\n') { + if (b != '\r') { + line.write(b); + } + } + return b == -1 && line.size() == 0 ? null : line.toString("US-ASCII"); + } + + private interface ThrowingRunnable { + void run() throws Exception; + } + + private static void startThread(final ThrowingRunnable runnable) { + final Thread thread = + new Thread( + () -> { + try { + runnable.run(); + } catch (Exception e) { + // The sockets are closed when the test ends or the peer disconnects. + } + }); + thread.setDaemon(true); + thread.start(); + } + + @Override + public void close() throws IOException { + serverSocket.close(); + for (final Socket socket : sockets) { + socket.close(); + } + } + } +} diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandlerBuilderTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandlerBuilderTest.java index 657078404c..5d496f8f5e 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandlerBuilderTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandlerBuilderTest.java @@ -23,6 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; +import io.grpc.ProxyDetector; import java.net.URI; import java.util.Optional; import org.apache.arrow.driver.jdbc.FlightServerTestExtension; @@ -153,6 +154,17 @@ public void testDefaults() { assertNull(builder.flightClientCache); assertNull(builder.connectTimeout); assertNull(builder.driverVersion); + assertNull(builder.proxyDetector); + } + + @Test + public void testProxyDetectorIsCopied() { + final ProxyDetector proxyDetector = targetServerAddress -> null; + final ArrowFlightSqlClientHandler.Builder rootBuilder = + new ArrowFlightSqlClientHandler.Builder().withProxyDetector(proxyDetector); + + // The proxy applies to every location, so a copy must keep it. + assertSame(proxyDetector, new ArrowFlightSqlClientHandler.Builder(rootBuilder).proxyDetector); } @Test diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/utils/FlightProxyDetectorTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/utils/FlightProxyDetectorTest.java new file mode 100644 index 0000000000..3b43cbcaf3 --- /dev/null +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/utils/FlightProxyDetectorTest.java @@ -0,0 +1,99 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.arrow.driver.jdbc.client.utils; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import io.grpc.HttpConnectProxiedSocketAddress; +import io.grpc.ProxiedSocketAddress; +import java.net.InetSocketAddress; +import java.sql.SQLException; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +public class FlightProxyDetectorTest { + private static final String PROXY_HOST = "localhost"; + private static final int PROXY_PORT = 3128; + + private static InetSocketAddress target(String host) { + return InetSocketAddress.createUnresolved(host, 443); + } + + @Test + public void testProxyForTarget() throws Exception { + final FlightProxyDetector detector = + FlightProxyDetector.create(PROXY_HOST, PROXY_PORT, null, null, null); + + final ProxiedSocketAddress proxied = detector.proxyFor(target("flight.example.com")); + + final HttpConnectProxiedSocketAddress address = + assertInstanceOf(HttpConnectProxiedSocketAddress.class, proxied); + assertEquals(target("flight.example.com"), address.getTargetAddress()); + assertEquals(PROXY_PORT, ((InetSocketAddress) address.getProxyAddress()).getPort()); + assertEquals(PROXY_HOST, ((InetSocketAddress) address.getProxyAddress()).getHostString()); + assertNull(address.getUsername()); + assertNull(address.getPassword()); + } + + @Test + public void testProxyCredentials() throws Exception { + final FlightProxyDetector detector = + FlightProxyDetector.create(PROXY_HOST, PROXY_PORT, "user", "secret", null); + + final HttpConnectProxiedSocketAddress address = + assertInstanceOf( + HttpConnectProxiedSocketAddress.class, detector.proxyFor(target("flight.example.com"))); + assertEquals("user", address.getUsername()); + assertEquals("secret", address.getPassword()); + } + + @ParameterizedTest + @CsvSource({ + "localhost|*.internal, localhost, true", + "localhost|*.internal, db.internal, true", + "localhost|*.internal, flight.example.com, false", + "*, flight.example.com, true", + }) + public void testNonProxyHosts(String nonProxyHosts, String host, boolean direct) + throws Exception { + final FlightProxyDetector detector = + FlightProxyDetector.create(PROXY_HOST, PROXY_PORT, null, null, nonProxyHosts); + + final ProxiedSocketAddress proxied = detector.proxyFor(target(host)); + + if (direct) { + assertNull(proxied); + } else { + assertInstanceOf(HttpConnectProxiedSocketAddress.class, proxied); + } + } + + @Test + public void testInvalidConfigurations() { + assertThrows( + SQLException.class, () -> FlightProxyDetector.create(null, null, null, null, null)); + assertThrows( + SQLException.class, () -> FlightProxyDetector.create(PROXY_HOST, 0, null, null, null)); + assertThrows( + SQLException.class, + () -> FlightProxyDetector.create(PROXY_HOST, PROXY_PORT, "user", null, null)); + } +} diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ArrowFlightConnectionConfigImplTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ArrowFlightConnectionConfigImplTest.java index 1889dfab69..5232cd8107 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ArrowFlightConnectionConfigImplTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ArrowFlightConnectionConfigImplTest.java @@ -33,12 +33,18 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import java.sql.SQLException; import java.time.Duration; import java.util.Properties; import java.util.Random; import java.util.function.Function; import java.util.stream.Stream; +import org.apache.arrow.driver.jdbc.client.utils.FlightProxyDetector; import org.apache.arrow.driver.jdbc.utils.ArrowFlightConnectionConfigImpl.ArrowFlightConnectionProperty; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -126,6 +132,57 @@ public void testBlankTlsRootCertsIsNull(String value) { assertThat(arrowFlightConnectionConfig.getTlsRootCertificatesPath(), is(nullValue())); } + @Test + public void testProxyDetectorDisabledByDefault() throws SQLException { + properties.put("proxyHost", "localhost"); + properties.put("proxyPort", "3128"); + + // The proxy properties are ignored unless useProxy is enabled. + assertNull(arrowFlightConnectionConfig.getProxyDetector()); + } + + @Test + public void testProxyDetectorEnabled() throws SQLException { + properties.put("useProxy", "true"); + properties.put("proxyHost", "localhost"); + properties.put("proxyPort", "3128"); + properties.put("nonProxyHosts", "*.internal"); + + final FlightProxyDetector proxyDetector = arrowFlightConnectionConfig.getProxyDetector(); + + assertNotNull(proxyDetector); + } + + @Test + public void testProxyDetectorEnabledWithoutHostFails() { + properties.put("useProxy", "true"); + + assertThrows(SQLException.class, arrowFlightConnectionConfig::getProxyDetector); + } + + @Test + public void testInvalidProxyPort() { + properties.put("useProxy", "true"); + properties.put("proxyHost", "localhost"); + properties.put("proxyPort", "not-a-port"); + + assertThrows(SQLException.class, arrowFlightConnectionConfig::getProxyDetector); + } + + @Test + public void testProxyPropertiesAreNotHeaders() { + properties.put("useProxy", "true"); + properties.put("proxyHost", "localhost"); + properties.put("proxyPort", "3128"); + properties.put("proxyUser", "user"); + properties.put("proxyPassword", "secret"); + properties.put("nonProxyHosts", "localhost"); + + // Built-in properties must not be sent to the server as gRPC headers, least of all the proxy + // credentials. + assertTrue(arrowFlightConnectionConfig.getHeaderAttributes().isEmpty()); + } + public static Stream provideParameters() { int port = RANDOM.nextInt(Short.toUnsignedInt(Short.MAX_VALUE)); boolean useEncryption = RANDOM.nextBoolean();