From ce57b7aad5ccb8bb71a73d5393f015ff5417282e Mon Sep 17 00:00:00 2001 From: Sergio Cruz Santos Date: Mon, 30 Nov 2026 15:20:49 +0100 Subject: [PATCH 1/3] GH-1384: [JDBC] Add proxy connection properties to the Flight SQL JDBC driver Add useProxy, proxyHost, proxyPort, proxyUser, proxyPassword and nonProxyHosts connection properties, following the names used by other JDBC drivers. When useProxy is enabled, connections are tunneled through the configured HTTP CONNECT proxy, overriding the JVM proxy settings used by default, including the connections used to retrieve streams from separate endpoints. --- docs/source/flight_sql_jdbc_driver.rst | 54 +++ .../driver/jdbc/ArrowFlightConnection.java | 1 + .../client/ArrowFlightSqlClientHandler.java | 20 ++ .../client/utils/FlightProxyDetector.java | 164 +++++++++ .../ArrowFlightConnectionConfigImpl.java | 49 +++ .../driver/jdbc/ConnectionProxyTest.java | 323 ++++++++++++++++++ ...rrowFlightSqlClientHandlerBuilderTest.java | 12 + .../client/utils/FlightProxyDetectorTest.java | 99 ++++++ .../ArrowFlightConnectionConfigImplTest.java | 57 ++++ 9 files changed, 779 insertions(+) create mode 100644 flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/utils/FlightProxyDetector.java create mode 100644 flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ConnectionProxyTest.java create mode 100644 flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/utils/FlightProxyDetectorTest.java 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(); From aa82b2766cb2c7169c96d4b305ef0789be1d8af4 Mon Sep 17 00:00:00 2001 From: Sergio Cruz Santos Date: Wed, 2 Dec 2026 17:43:45 +0100 Subject: [PATCH 2/3] GH-1384: [JDBC] Add proxy connection properties to the Flight SQL JDBC driver Adding proxy support also to OAUTH requests, through the setProxy method of the Nimbus HTTPRequest. Proxy authentication is not supported for the OAuth token requests. --- docs/source/flight_sql_jdbc_driver.rst | 12 +- .../client/ArrowFlightSqlClientHandler.java | 2 +- .../oauth/AbstractOAuthTokenProvider.java | 46 +++++- .../jdbc/client/oauth/OAuthConfiguration.java | 19 ++- .../client/oauth/OAuthTokenProviders.java | 37 ++++- .../oauth/OAuthTokenProviderProxyTest.java | 145 ++++++++++++++++++ 6 files changed, 255 insertions(+), 6 deletions(-) create mode 100644 flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/oauth/OAuthTokenProviderProxyTest.java diff --git a/docs/source/flight_sql_jdbc_driver.rst b/docs/source/flight_sql_jdbc_driver.rst index bf23abc6a6..ae7c9218cb 100644 --- a/docs/source/flight_sql_jdbc_driver.rst +++ b/docs/source/flight_sql_jdbc_driver.rst @@ -227,7 +227,17 @@ 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. +take precedence over the JVM proxy settings. They also apply to the +requests sent to the OAuth token endpoint, which are sent through the +proxy unless the token endpoint host matches ``nonProxyHosts``. + +.. note:: + + Proxy authentication is not supported for the requests sent to the + OAuth token endpoint: ``proxyUser`` and ``proxyPassword`` are only used + for the connection to the Flight SQL server, and the token requests are + sent through the proxy without credentials. The proxy must therefore + allow unauthenticated access to the token endpoint. .. list-table:: :header-rows: 1 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 c5fb09df9a..f78cbfbe94 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 @@ -1329,7 +1329,7 @@ public ArrowFlightSqlClientHandler build() throws SQLException { final ArrayList credentialOptions = new ArrayList<>(); // Authentication priority: OAuth > token > username/password if (oauthConfig != null) { - OAuthTokenProvider tokenProvider = oauthConfig.createTokenProvider(); + OAuthTokenProvider tokenProvider = oauthConfig.createTokenProvider(proxyDetector); credentialOptions.add(new CredentialCallOption(new OAuthCredentialWriter(tokenProvider))); } else if (isUsingUserPasswordAuth) { // If the authFactory has already been used for a handshake, use the existing diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/oauth/AbstractOAuthTokenProvider.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/oauth/AbstractOAuthTokenProvider.java index 9c377a5850..7261920cce 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/oauth/AbstractOAuthTokenProvider.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/oauth/AbstractOAuthTokenProvider.java @@ -22,9 +22,17 @@ import com.nimbusds.oauth2.sdk.TokenRequest; import com.nimbusds.oauth2.sdk.TokenResponse; import com.nimbusds.oauth2.sdk.auth.ClientAuthentication; +import com.nimbusds.oauth2.sdk.http.HTTPRequest; +import com.nimbusds.oauth2.sdk.http.HTTPResponse; import com.nimbusds.oauth2.sdk.token.AccessToken; +import io.grpc.HttpConnectProxiedSocketAddress; +import io.grpc.ProxiedSocketAddress; +import io.grpc.ProxyDetector; import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.Proxy; import java.net.URI; +import java.net.URL; import java.sql.SQLException; import java.time.Instant; import org.apache.arrow.util.VisibleForTesting; @@ -47,6 +55,12 @@ public abstract class AbstractOAuthTokenProvider implements OAuthTokenProvider { @VisibleForTesting @Nullable Scope scope; + /** + * Decides whether the token requests go through a proxy. When null, the JVM-wide proxy settings + * apply. + */ + @VisibleForTesting @Nullable ProxyDetector proxyDetector; + @Override public String getValidToken() throws SQLException { TokenInfo token = cachedToken; @@ -74,7 +88,7 @@ public String getValidToken() throws SQLException { protected TokenInfo fetchNewToken() throws SQLException { try { TokenRequest request = buildTokenRequest(); - TokenResponse response = TokenResponse.parse(request.toHTTPRequest().send()); + TokenResponse response = TokenResponse.parse(send(request.toHTTPRequest())); if (!response.indicatesSuccess()) { TokenErrorResponse errorResponse = response.toErrorResponse(); @@ -99,6 +113,36 @@ protected TokenInfo fetchNewToken() throws SQLException { } } + /** + * Sends the token request, honoring the configured {@link ProxyDetector} if any. + * + *

The request is sent through the proxy with {@link HTTPRequest#setProxy(Proxy)}, which does + * not support proxy authentication: the proxy user and password are not used. + * + * @param httpRequest the HTTP request to send to the authorization server + * @return the HTTP response + * @throws IOException if the request cannot be sent + */ + private HTTPResponse send(HTTPRequest httpRequest) throws IOException { + if (proxyDetector == null) { + return httpRequest.send(); + } + + final URL url = httpRequest.getURL(); + final int port = url.getPort() != -1 ? url.getPort() : url.getDefaultPort(); + final ProxiedSocketAddress proxied = + proxyDetector.proxyFor(InetSocketAddress.createUnresolved(url.getHost(), port)); + if (!(proxied instanceof HttpConnectProxiedSocketAddress)) { + // The target is not proxied: connect directly, ignoring the JVM-wide proxy settings. + httpRequest.setProxy(Proxy.NO_PROXY); + return httpRequest.send(); + } + + final HttpConnectProxiedSocketAddress httpProxy = (HttpConnectProxiedSocketAddress) proxied; + httpRequest.setProxy(new Proxy(Proxy.Type.HTTP, httpProxy.getProxyAddress())); + return httpRequest.send(); + } + /** * Builds the flow-specific token request. * diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/oauth/OAuthConfiguration.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/oauth/OAuthConfiguration.java index cba9d4c2e6..153687712c 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/oauth/OAuthConfiguration.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/oauth/OAuthConfiguration.java @@ -17,6 +17,7 @@ package org.apache.arrow.driver.jdbc.client.oauth; import com.nimbusds.oauth2.sdk.GrantType; +import io.grpc.ProxyDetector; import java.net.URI; import java.net.URISyntaxException; import java.sql.SQLException; @@ -87,12 +88,27 @@ private void validate() throws SQLException { * @throws SQLException if the grant type is not supported or configuration is invalid */ public OAuthTokenProvider createTokenProvider() throws SQLException { + return createTokenProvider(null); + } + + /** + * Creates an OAuthTokenProvider based on the configured grant type, sending the token requests + * according to the given proxy detector. + * + * @param proxyDetector the proxy detector deciding how the token requests reach the token + * endpoint, or null to use the JVM-wide proxy settings + * @return the token provider + * @throws SQLException if the grant type is not supported or configuration is invalid + */ + public OAuthTokenProvider createTokenProvider(@Nullable ProxyDetector proxyDetector) + throws SQLException { if (GrantType.CLIENT_CREDENTIALS.equals(grantType)) { return OAuthTokenProviders.clientCredentials() .tokenUri(tokenUri) .clientId(clientId) .clientSecret(clientSecret) .scope(scope) + .proxyDetector(proxyDetector) .build(); } else if (GrantType.TOKEN_EXCHANGE.equals(grantType)) { OAuthTokenProviders.TokenExchangeBuilder builder = @@ -105,7 +121,8 @@ public OAuthTokenProvider createTokenProvider() throws SQLException { .audience(audience) .requestedTokenType(requestedTokenType) .scope(scope) - .resource(resource); + .resource(resource) + .proxyDetector(proxyDetector); if (clientId != null && clientSecret != null) { builder.clientCredentials(clientId, clientSecret); diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/oauth/OAuthTokenProviders.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/oauth/OAuthTokenProviders.java index bbf7072d39..32d09cbf7d 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/oauth/OAuthTokenProviders.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/oauth/OAuthTokenProviders.java @@ -26,6 +26,7 @@ import com.nimbusds.oauth2.sdk.token.TokenTypeURI; import com.nimbusds.oauth2.sdk.token.TypelessAccessToken; import com.nimbusds.oauth2.sdk.tokenexchange.TokenExchangeGrant; +import io.grpc.ProxyDetector; import java.net.URI; import java.net.URISyntaxException; import java.util.Collections; @@ -91,6 +92,7 @@ public static class ClientCredentialsBuilder { private @Nullable String clientId; private @Nullable String clientSecret; private @Nullable String scope; + private @Nullable ProxyDetector proxyDetector; ClientCredentialsBuilder() {} @@ -155,6 +157,18 @@ public ClientCredentialsBuilder scope(@Nullable String scope) { return this; } + /** + * Sets the {@link ProxyDetector} used to decide whether the token requests are sent through a + * proxy (optional). When not set, the JVM-wide proxy settings are used. + * + * @param proxyDetector the proxy detector, or null to use the JVM-wide proxy settings + * @return this builder + */ + public ClientCredentialsBuilder proxyDetector(@Nullable ProxyDetector proxyDetector) { + this.proxyDetector = proxyDetector; + return this; + } + /** * Builds a new ClientCredentialsTokenProvider instance. * @@ -171,7 +185,10 @@ public ClientCredentialsTokenProvider build() { if (clientSecret == null) { throw new IllegalStateException("clientSecret is required"); } - return new ClientCredentialsTokenProvider(tokenUri, clientId, clientSecret, scope); + final ClientCredentialsTokenProvider provider = + new ClientCredentialsTokenProvider(tokenUri, clientId, clientSecret, scope); + provider.proxyDetector = proxyDetector; + return provider; } } @@ -187,6 +204,7 @@ public static class TokenExchangeBuilder { private @Nullable Scope scope; private @Nullable List resources; private @Nullable ClientAuthentication clientAuth; + private @Nullable ProxyDetector proxyDetector; TokenExchangeBuilder() {} @@ -369,6 +387,18 @@ public TokenExchangeBuilder clientCredentials(String clientId, String clientSecr return this; } + /** + * Sets the {@link ProxyDetector} used to decide whether the token requests are sent through a + * proxy (optional). When not set, the JVM-wide proxy settings are used. + * + * @param proxyDetector the proxy detector, or null to use the JVM-wide proxy settings + * @return this builder + */ + public TokenExchangeBuilder proxyDetector(@Nullable ProxyDetector proxyDetector) { + this.proxyDetector = proxyDetector; + return this; + } + /** * Builds a new TokenExchangeTokenProvider instance. * @@ -387,7 +417,10 @@ public TokenExchangeTokenProvider build() { } TokenExchangeGrant grant = createGrant(); - return new TokenExchangeTokenProvider(tokenUri, grant, clientAuth, scope, resources); + final TokenExchangeTokenProvider provider = + new TokenExchangeTokenProvider(tokenUri, grant, clientAuth, scope, resources); + provider.proxyDetector = proxyDetector; + return provider; } private TokenExchangeGrant createGrant() { diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/oauth/OAuthTokenProviderProxyTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/oauth/OAuthTokenProviderProxyTest.java new file mode 100644 index 0000000000..35d84c2e14 --- /dev/null +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/oauth/OAuthTokenProviderProxyTest.java @@ -0,0 +1,145 @@ +/* + * 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.oauth; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.sun.net.httpserver.HttpServer; +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import org.apache.arrow.driver.jdbc.client.utils.FlightProxyDetector; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** Tests that the OAuth token requests honor the proxy configuration. */ +public class OAuthTokenProviderProxyTest { + + private static final String TOKEN_RESPONSE = + "{\"access_token\":\"proxied-token\",\"token_type\":\"Bearer\",\"expires_in\":3600}"; + + private HttpServer server; + private final List requests = new CopyOnWriteArrayList<>(); + private final List proxyAuthorizations = new CopyOnWriteArrayList<>(); + + @BeforeEach + public void setUp() throws IOException { + server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); + server.createContext( + "/", + exchange -> { + requests.add(exchange.getRequestMethod() + " " + exchange.getRequestURI()); + final String proxyAuthorization = + exchange.getRequestHeaders().getFirst("Proxy-Authorization"); + if (proxyAuthorization != null) { + proxyAuthorizations.add(proxyAuthorization); + } + exchange.getRequestBody().readAllBytes(); + final byte[] response = TOKEN_RESPONSE.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, response.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(response); + } + exchange.close(); + }); + server.start(); + } + + @AfterEach + public void tearDown() { + server.stop(0); + } + + private int serverPort() { + return server.getAddress().getPort(); + } + + @Test + public void testClientCredentialsTokenRequestThroughProxy() throws Exception { + final OAuthTokenProvider provider = + OAuthTokenProviders.clientCredentials() + .tokenUri("http://oauth.invalid/token") + .clientId("client") + .clientSecret("secret") + .proxyDetector(FlightProxyDetector.create("127.0.0.1", serverPort(), null, null, null)) + .build(); + + assertEquals("proxied-token", provider.getValidToken()); + + assertTrue( + requests.stream().allMatch(r -> r.equals("POST http://oauth.invalid/token")), + requests.toString()); + } + + @Test + public void testTokenExchangeTokenRequestThroughProxy() throws Exception { + final OAuthTokenProvider provider = + OAuthTokenProviders.tokenExchange() + .tokenUri("http://oauth.invalid/token") + .subjectToken("subject") + .subjectTokenType("urn:ietf:params:oauth:token-type:access_token") + .proxyDetector(FlightProxyDetector.create("127.0.0.1", serverPort(), null, null, null)) + .build(); + + assertEquals("proxied-token", provider.getValidToken()); + + assertTrue( + requests.stream().allMatch(r -> r.equals("POST http://oauth.invalid/token")), + requests.toString()); + } + + @Test + public void testProxyCredentialsAreNotSentInTokenRequests() throws Exception { + final OAuthTokenProvider provider = + OAuthTokenProviders.clientCredentials() + .tokenUri("http://oauth.invalid/token") + .clientId("client") + .clientSecret("secret") + .proxyDetector( + FlightProxyDetector.create( + "127.0.0.1", serverPort(), "proxyUser", "proxyPassword", null)) + .build(); + + assertEquals("proxied-token", provider.getValidToken()); + + assertEquals(List.of("POST http://oauth.invalid/token"), requests); + assertTrue(proxyAuthorizations.isEmpty(), proxyAuthorizations.toString()); + } + + @Test + public void testTokenRequestToNonProxyHostIsDirect() throws Exception { + // The proxy is unreachable, so the request only succeeds if it bypasses the proxy. + final OAuthTokenProvider provider = + OAuthTokenProviders.clientCredentials() + .tokenUri(String.format("http://localhost:%d/token", serverPort())) + .clientId("client") + .clientSecret("secret") + .proxyDetector(FlightProxyDetector.create("127.0.0.1", 1, null, null, "localhost")) + .build(); + + assertEquals("proxied-token", provider.getValidToken()); + + assertEquals(List.of("POST /token"), requests); + } +} From 08d0c7c318da076ca302904efe490f7c8e886634 Mon Sep 17 00:00:00 2001 From: Sergio Cruz Santos Date: Thu, 3 Dec 2026 12:44:32 +0100 Subject: [PATCH 3/3] GH-1384: [JDBC] Add proxy authentication to the OAuth token requests The OAuth token requests are sent with a ProxyHttpRequestSender instead of the setProxy method of the Nimbus HTTPRequest, which does not support proxy authentication. HTTP requests use the JDK HttpClient with the proxy credentials, and HTTPS requests use a CONNECT tunnel that sends the Basic proxy credentials preemptively, as the JDK disables Basic authentication for tunnels by default. --- docs/source/flight_sql_jdbc_driver.rst | 11 +- .../oauth/AbstractOAuthTokenProvider.java | 10 +- .../client/oauth/ProxyHttpRequestSender.java | 344 ++++++++++++++++++ .../oauth/OAuthTokenProviderProxyTest.java | 109 ++++-- 4 files changed, 436 insertions(+), 38 deletions(-) create mode 100644 flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/oauth/ProxyHttpRequestSender.java diff --git a/docs/source/flight_sql_jdbc_driver.rst b/docs/source/flight_sql_jdbc_driver.rst index ae7c9218cb..28c779040a 100644 --- a/docs/source/flight_sql_jdbc_driver.rst +++ b/docs/source/flight_sql_jdbc_driver.rst @@ -229,15 +229,8 @@ 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. They also apply to the requests sent to the OAuth token endpoint, which are sent through the -proxy unless the token endpoint host matches ``nonProxyHosts``. - -.. note:: - - Proxy authentication is not supported for the requests sent to the - OAuth token endpoint: ``proxyUser`` and ``proxyPassword`` are only used - for the connection to the Flight SQL server, and the token requests are - sent through the proxy without credentials. The proxy must therefore - allow unauthenticated access to the token endpoint. +proxy, authenticating with ``proxyUser`` and ``proxyPassword`` if set, +unless the token endpoint host matches ``nonProxyHosts``. .. list-table:: :header-rows: 1 diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/oauth/AbstractOAuthTokenProvider.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/oauth/AbstractOAuthTokenProvider.java index 7261920cce..8f9c8c5e8e 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/oauth/AbstractOAuthTokenProvider.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/oauth/AbstractOAuthTokenProvider.java @@ -116,9 +116,6 @@ protected TokenInfo fetchNewToken() throws SQLException { /** * Sends the token request, honoring the configured {@link ProxyDetector} if any. * - *

The request is sent through the proxy with {@link HTTPRequest#setProxy(Proxy)}, which does - * not support proxy authentication: the proxy user and password are not used. - * * @param httpRequest the HTTP request to send to the authorization server * @return the HTTP response * @throws IOException if the request cannot be sent @@ -139,8 +136,11 @@ private HTTPResponse send(HTTPRequest httpRequest) throws IOException { } final HttpConnectProxiedSocketAddress httpProxy = (HttpConnectProxiedSocketAddress) proxied; - httpRequest.setProxy(new Proxy(Proxy.Type.HTTP, httpProxy.getProxyAddress())); - return httpRequest.send(); + return httpRequest.send( + new ProxyHttpRequestSender( + (InetSocketAddress) httpProxy.getProxyAddress(), + httpProxy.getUsername(), + httpProxy.getPassword())); } /** diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/oauth/ProxyHttpRequestSender.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/oauth/ProxyHttpRequestSender.java new file mode 100644 index 0000000000..877f100fc0 --- /dev/null +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/oauth/ProxyHttpRequestSender.java @@ -0,0 +1,344 @@ +/* + * 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.oauth; + +import com.nimbusds.oauth2.sdk.http.HTTPRequestSender; +import com.nimbusds.oauth2.sdk.http.ReadOnlyHTTPRequest; +import com.nimbusds.oauth2.sdk.http.ReadOnlyHTTPResponse; +import java.io.ByteArrayOutputStream; +import java.io.EOFException; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.Authenticator; +import java.net.InetSocketAddress; +import java.net.PasswordAuthentication; +import java.net.ProxySelector; +import java.net.Socket; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.SSLSocketFactory; +import org.checkerframework.checker.nullness.qual.Nullable; + +/** + * An {@link HTTPRequestSender} that sends the OAuth token requests through an HTTP proxy, with + * optional proxy authentication. + * + *

HTTPS requests are sent through a CONNECT tunnel opened by this class, which sends the proxy + * credentials preemptively. The JDK HTTP clients disable Basic proxy authentication for tunnels by + * default ({@code jdk.http.auth.tunneling.disabledSchemes}) and offer no per-request way to + * override it. + */ +final class ProxyHttpRequestSender implements HTTPRequestSender { + // Headers that are managed by this sender and must not be copied from the request. + private static final Set RESTRICTED_HEADERS = + Set.of("connection", "content-length", "expect", "host", "upgrade"); + + private final InetSocketAddress proxyAddress; + private final @Nullable String proxyUser; + private final @Nullable String proxyPassword; + + ProxyHttpRequestSender( + InetSocketAddress proxyAddress, @Nullable String proxyUser, @Nullable String proxyPassword) { + this.proxyAddress = proxyAddress; + this.proxyUser = proxyUser; + this.proxyPassword = proxyPassword; + } + + @Override + public ReadOnlyHTTPResponse send(ReadOnlyHTTPRequest request) throws IOException { + if ("https".equalsIgnoreCase(request.getURI().getScheme())) { + return sendThroughTunnel(request); + } + return sendWithHttpClient(request); + } + + /** Sends a plain HTTP request to the proxy, which forwards it to the target. */ + private ReadOnlyHTTPResponse sendWithHttpClient(ReadOnlyHTTPRequest request) throws IOException { + final HttpClient.Builder clientBuilder = + HttpClient.newBuilder().proxy(ProxySelector.of(proxyAddress)); + if (request.getConnectTimeout() > 0) { + clientBuilder.connectTimeout(Duration.ofMillis(request.getConnectTimeout())); + } + if (proxyUser != null) { + final PasswordAuthentication credentials = + new PasswordAuthentication( + proxyUser, proxyPassword == null ? new char[0] : proxyPassword.toCharArray()); + clientBuilder.authenticator( + new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return getRequestorType() == RequestorType.PROXY ? credentials : null; + } + }); + } + + final HttpRequest.Builder requestBuilder = HttpRequest.newBuilder(request.getURI()); + if (request.getReadTimeout() > 0) { + requestBuilder.timeout(Duration.ofMillis(request.getReadTimeout())); + } + for (Map.Entry> header : request.getHeaderMap().entrySet()) { + if (RESTRICTED_HEADERS.contains(header.getKey().toLowerCase(Locale.ROOT))) { + continue; + } + for (String value : header.getValue()) { + requestBuilder.header(header.getKey(), value); + } + } + final String body = request.getBody(); + requestBuilder.method( + request.getMethod().name(), + body == null + ? HttpRequest.BodyPublishers.noBody() + : HttpRequest.BodyPublishers.ofString(body)); + + final HttpResponse response; + try { + response = + clientBuilder.build().send(requestBuilder.build(), HttpResponse.BodyHandlers.ofString()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException("Interrupted while sending the OAuth token request", e); + } + + final Map> headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + headers.putAll(response.headers().map()); + return newResponse(response.statusCode(), headers, response.body()); + } + + /** Sends an HTTPS request through a CONNECT tunnel opened with the proxy credentials. */ + private ReadOnlyHTTPResponse sendThroughTunnel(ReadOnlyHTTPRequest request) throws IOException { + final URI uri = request.getURI(); + final String host = uri.getHost(); + final int port = uri.getPort() != -1 ? uri.getPort() : 443; + final String authority = host + ":" + port; + + try (Socket socket = new Socket()) { + socket.connect( + proxyAddress, request.getConnectTimeout() > 0 ? request.getConnectTimeout() : 0); + socket.setSoTimeout(Math.max(request.getReadTimeout(), 0)); + + openTunnel(socket, authority); + + final SSLSocket sslSocket = + (SSLSocket) + ((SSLSocketFactory) SSLSocketFactory.getDefault()) + .createSocket(socket, host, port, true); + final SSLParameters sslParameters = sslSocket.getSSLParameters(); + sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); + sslSocket.setSSLParameters(sslParameters); + sslSocket.startHandshake(); + + writeRequest(sslSocket.getOutputStream(), request, authority); + return readResponse(sslSocket.getInputStream()); + } + } + + private void openTunnel(Socket socket, String authority) throws IOException { + final StringBuilder connect = new StringBuilder(); + connect.append("CONNECT ").append(authority).append(" HTTP/1.1\r\n"); + connect.append("Host: ").append(authority).append("\r\n"); + if (proxyUser != null) { + final String credentials = proxyUser + ":" + (proxyPassword == null ? "" : proxyPassword); + connect + .append("Proxy-Authorization: Basic ") + .append(Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8))) + .append("\r\n"); + } + connect.append("\r\n"); + final OutputStream out = socket.getOutputStream(); + out.write(connect.toString().getBytes(StandardCharsets.ISO_8859_1)); + out.flush(); + + // The input stream is not buffered, so no TLS bytes are consumed past the response headers. + final InputStream in = socket.getInputStream(); + final String statusLine = readLine(in); + if (statusLine == null) { + throw new EOFException("The proxy closed the connection before answering CONNECT"); + } + final String[] parts = statusLine.split(" ", 3); + final int status; + try { + status = parts.length >= 2 ? Integer.parseInt(parts[1]) : -1; + } catch (NumberFormatException e) { + throw new IOException("Invalid proxy response to CONNECT: " + statusLine, e); + } + String line; + while ((line = readLine(in)) != null && !line.isEmpty()) { + // Skip the proxy response headers. + } + if (status < 200 || status > 299) { + throw new IOException("The proxy refused the CONNECT to " + authority + ": " + statusLine); + } + } + + private static void writeRequest(OutputStream out, ReadOnlyHTTPRequest request, String authority) + throws IOException { + final URI uri = request.getURI(); + String path = uri.getRawPath(); + if (path == null || path.isEmpty()) { + path = "/"; + } + if (uri.getRawQuery() != null) { + path += "?" + uri.getRawQuery(); + } + final String body = request.getBody(); + final byte[] bodyBytes = body == null ? null : body.getBytes(StandardCharsets.UTF_8); + + final StringBuilder head = new StringBuilder(); + head.append(request.getMethod().name()).append(' ').append(path).append(" HTTP/1.1\r\n"); + head.append("Host: ").append(authority).append("\r\n"); + head.append("Connection: close\r\n"); + for (Map.Entry> header : request.getHeaderMap().entrySet()) { + if (RESTRICTED_HEADERS.contains(header.getKey().toLowerCase(Locale.ROOT))) { + continue; + } + for (String value : header.getValue()) { + head.append(header.getKey()).append(": ").append(value).append("\r\n"); + } + } + if (bodyBytes != null) { + head.append("Content-Length: ").append(bodyBytes.length).append("\r\n"); + } + head.append("\r\n"); + out.write(head.toString().getBytes(StandardCharsets.ISO_8859_1)); + if (bodyBytes != null) { + out.write(bodyBytes); + } + out.flush(); + } + + private static ReadOnlyHTTPResponse readResponse(InputStream rawIn) throws IOException { + final InputStream in = new java.io.BufferedInputStream(rawIn); + final String statusLine = readLine(in); + if (statusLine == null) { + throw new EOFException("The server closed the connection without answering"); + } + final String[] parts = statusLine.split(" ", 3); + final int status; + try { + status = parts.length >= 2 ? Integer.parseInt(parts[1]) : -1; + } catch (NumberFormatException e) { + throw new IOException("Invalid HTTP response: " + statusLine, e); + } + + final Map> headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + String line; + while ((line = readLine(in)) != null && !line.isEmpty()) { + final int colon = line.indexOf(':'); + if (colon > 0) { + headers + .computeIfAbsent(line.substring(0, colon).trim(), k -> new ArrayList<>()) + .add(line.substring(colon + 1).trim()); + } + } + + final byte[] bodyBytes; + final List transferEncoding = headers.get("Transfer-Encoding"); + final List contentLength = headers.get("Content-Length"); + if (transferEncoding != null + && transferEncoding.stream() + .anyMatch(v -> v.toLowerCase(Locale.ROOT).contains("chunked"))) { + bodyBytes = readChunked(in); + } else if (contentLength != null && !contentLength.isEmpty()) { + bodyBytes = in.readNBytes(Integer.parseInt(contentLength.get(0))); + } else { + bodyBytes = in.readAllBytes(); + } + return newResponse(status, headers, new String(bodyBytes, StandardCharsets.UTF_8)); + } + + private static byte[] readChunked(InputStream in) throws IOException { + final ByteArrayOutputStream body = new ByteArrayOutputStream(); + while (true) { + final String sizeLine = readLine(in); + if (sizeLine == null) { + throw new EOFException("Unexpected end of the chunked response"); + } + final int semicolon = sizeLine.indexOf(';'); + final int size = + Integer.parseInt( + (semicolon >= 0 ? sizeLine.substring(0, semicolon) : sizeLine).trim(), 16); + if (size == 0) { + // Skip the trailers. + String line; + while ((line = readLine(in)) != null && !line.isEmpty()) { + // Ignore. + } + return body.toByteArray(); + } + body.write(in.readNBytes(size)); + readLine(in); + } + } + + /** Reads a CRLF (or LF) terminated line byte by byte, or returns null at the end of stream. */ + private static @Nullable String readLine(InputStream in) throws IOException { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + int b; + while ((b = in.read()) != -1) { + if (b == '\n') { + break; + } + if (b != '\r') { + buffer.write(b); + } + } + if (b == -1 && buffer.size() == 0) { + return null; + } + return buffer.toString(StandardCharsets.ISO_8859_1); + } + + private static ReadOnlyHTTPResponse newResponse( + int statusCode, Map> headers, String body) { + return new ReadOnlyHTTPResponse() { + @Override + public int getStatusCode() { + return statusCode; + } + + @Override + public @Nullable String getStatusMessage() { + return null; + } + + @Override + public Map> getHeaderMap() { + return headers; + } + + @Override + public String getBody() { + return body; + } + }; + } +} diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/oauth/OAuthTokenProviderProxyTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/oauth/OAuthTokenProviderProxyTest.java index 35d84c2e14..8cf91c35cb 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/oauth/OAuthTokenProviderProxyTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/oauth/OAuthTokenProviderProxyTest.java @@ -17,14 +17,21 @@ package org.apache.arrow.driver.jdbc.client.oauth; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import com.sun.net.httpserver.HttpServer; +import java.io.BufferedReader; import java.io.IOException; +import java.io.InputStreamReader; import java.io.OutputStream; import java.net.InetAddress; import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.Socket; import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.util.Base64; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.apache.arrow.driver.jdbc.client.utils.FlightProxyDetector; @@ -37,6 +44,8 @@ public class OAuthTokenProviderProxyTest { private static final String TOKEN_RESPONSE = "{\"access_token\":\"proxied-token\",\"token_type\":\"Bearer\",\"expires_in\":3600}"; + private static final String PROXY_USER = "proxyUser"; + private static final String PROXY_PASSWORD = "proxyPassword"; private HttpServer server; private final List requests = new CopyOnWriteArrayList<>(); @@ -51,15 +60,21 @@ public void setUp() throws IOException { requests.add(exchange.getRequestMethod() + " " + exchange.getRequestURI()); final String proxyAuthorization = exchange.getRequestHeaders().getFirst("Proxy-Authorization"); - if (proxyAuthorization != null) { - proxyAuthorizations.add(proxyAuthorization); - } exchange.getRequestBody().readAllBytes(); final byte[] response = TOKEN_RESPONSE.getBytes(StandardCharsets.UTF_8); - exchange.getResponseHeaders().add("Content-Type", "application/json"); - exchange.sendResponseHeaders(200, response.length); - try (OutputStream out = exchange.getResponseBody()) { - out.write(response); + final boolean proxyRequest = exchange.getRequestURI().isAbsolute(); + if (proxyRequest) { + proxyAuthorizations.add(String.valueOf(proxyAuthorization)); + } + if (proxyRequest && proxyAuthorization == null) { + exchange.getResponseHeaders().add("Proxy-Authenticate", "Basic realm=\"test\""); + exchange.sendResponseHeaders(407, -1); + } else { + exchange.getResponseHeaders().add("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, response.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(response); + } } exchange.close(); }); @@ -75,6 +90,12 @@ private int serverPort() { return server.getAddress().getPort(); } + private static String expectedProxyAuthorization() { + return "Basic " + + Base64.getEncoder() + .encodeToString((PROXY_USER + ":" + PROXY_PASSWORD).getBytes(StandardCharsets.UTF_8)); + } + @Test public void testClientCredentialsTokenRequestThroughProxy() throws Exception { final OAuthTokenProvider provider = @@ -82,7 +103,9 @@ public void testClientCredentialsTokenRequestThroughProxy() throws Exception { .tokenUri("http://oauth.invalid/token") .clientId("client") .clientSecret("secret") - .proxyDetector(FlightProxyDetector.create("127.0.0.1", serverPort(), null, null, null)) + .proxyDetector( + FlightProxyDetector.create( + "127.0.0.1", serverPort(), PROXY_USER, PROXY_PASSWORD, null)) .build(); assertEquals("proxied-token", provider.getValidToken()); @@ -90,6 +113,8 @@ public void testClientCredentialsTokenRequestThroughProxy() throws Exception { assertTrue( requests.stream().allMatch(r -> r.equals("POST http://oauth.invalid/token")), requests.toString()); + assertTrue( + proxyAuthorizations.contains(expectedProxyAuthorization()), proxyAuthorizations.toString()); } @Test @@ -99,7 +124,9 @@ public void testTokenExchangeTokenRequestThroughProxy() throws Exception { .tokenUri("http://oauth.invalid/token") .subjectToken("subject") .subjectTokenType("urn:ietf:params:oauth:token-type:access_token") - .proxyDetector(FlightProxyDetector.create("127.0.0.1", serverPort(), null, null, null)) + .proxyDetector( + FlightProxyDetector.create( + "127.0.0.1", serverPort(), PROXY_USER, PROXY_PASSWORD, null)) .build(); assertEquals("proxied-token", provider.getValidToken()); @@ -107,24 +134,57 @@ public void testTokenExchangeTokenRequestThroughProxy() throws Exception { assertTrue( requests.stream().allMatch(r -> r.equals("POST http://oauth.invalid/token")), requests.toString()); + assertTrue( + proxyAuthorizations.contains(expectedProxyAuthorization()), proxyAuthorizations.toString()); } @Test - public void testProxyCredentialsAreNotSentInTokenRequests() throws Exception { - final OAuthTokenProvider provider = - OAuthTokenProviders.clientCredentials() - .tokenUri("http://oauth.invalid/token") - .clientId("client") - .clientSecret("secret") - .proxyDetector( - FlightProxyDetector.create( - "127.0.0.1", serverPort(), "proxyUser", "proxyPassword", null)) - .build(); - - assertEquals("proxied-token", provider.getValidToken()); - - assertEquals(List.of("POST http://oauth.invalid/token"), requests); - assertTrue(proxyAuthorizations.isEmpty(), proxyAuthorizations.toString()); + public void testHttpsTokenRequestSendsProxyCredentialsInConnect() throws Exception { + final List connectRequests = new CopyOnWriteArrayList<>(); + try (ServerSocket proxy = new ServerSocket(0, 50, InetAddress.getLoopbackAddress())) { + final Thread proxyThread = + new Thread( + () -> { + try (Socket socket = proxy.accept()) { + final BufferedReader reader = + new BufferedReader( + new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8)); + final StringBuilder request = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null && !line.isEmpty()) { + request.append(line).append('\n'); + } + connectRequests.add(request.toString()); + socket + .getOutputStream() + .write( + "HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\n\r\n" + .getBytes(StandardCharsets.UTF_8)); + } catch (IOException e) { + // The test asserts on the recorded requests. + } + }); + proxyThread.setDaemon(true); + proxyThread.start(); + + final OAuthTokenProvider provider = + OAuthTokenProviders.clientCredentials() + .tokenUri("https://oauth.invalid:9031/token") + .clientId("client") + .clientSecret("secret") + .proxyDetector( + FlightProxyDetector.create( + "127.0.0.1", proxy.getLocalPort(), PROXY_USER, PROXY_PASSWORD, null)) + .build(); + + assertThrows(SQLException.class, provider::getValidToken); + proxyThread.join(5000); + } + + assertEquals(1, connectRequests.size(), connectRequests.toString()); + final String connect = connectRequests.get(0); + assertTrue(connect.startsWith("CONNECT oauth.invalid:9031 "), connect); + assertTrue(connect.contains("Proxy-Authorization: " + expectedProxyAuthorization()), connect); } @Test @@ -141,5 +201,6 @@ public void testTokenRequestToNonProxyHostIsDirect() throws Exception { assertEquals("proxied-token", provider.getValidToken()); assertEquals(List.of("POST /token"), requests); + assertTrue(proxyAuthorizations.isEmpty()); } }