This is an automated email from the ASF dual-hosted git repository.
jbonofre pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-java.git
The following commit(s) were added to refs/heads/main by this push:
new 6f96cb16d GH-1526: [JDBC] Allow disabling connections to
server-advertised endpoint locations (#1527)
6f96cb16d is described below
commit 6f96cb16d644c57858b135da220639777a025756
Author: j00n <[email protected]>
AuthorDate: Fri Nov 27 12:27:30 2026 -0700
GH-1526: [JDBC] Allow disabling connections to server-advertised endpoint
locations (#1527)
## What's Changed
Adds a `followEndpointLocations` connection property, defaulting to
`true` so nothing changes for existing users. With `false`, `getStreams`
never opens a new connection for an endpoint, so the connection's
credentials, client certificate and headers only go to the host the
application connected to.
- An endpoint is fetched over the existing connection if it has no
locations, the `arrow-flight-reuse-connection://?` location, or a
`grpc`, `grpc+tcp` or `grpc+tls` location on the connection's host and
port. A `grpc+tls` location is only used when the connection uses TLS,
and other schemes need another transport, such as an HTTP GET for
`https`. A `grpc` or `grpc+tcp` location on a TLS connection is fetched
over TLS. When TLS is enabled, a location on `hostnameOverride` also
counts, on the connection's port unless the override includes one. Hosts
are compared by name (case-insensitively, IPv6 brackets ignored),
without DNS resolution.
- Other locations are skipped through the per-location path that already
refuses non-TLS locations on encrypted connections, so an endpoint's
other locations are still tried. The query fails with an `SQLException`
only if an endpoint has no location that can be used. The issue proposes
failing on the first such location instead, but `Flight.proto` says an
endpoint's locations are equivalent, so using an allowed one loses
nothing.
- The message for a skipped location only shows its scheme, host and
port, since its other parts can hold credentials, such as a presigned
URL's signature.
- The handler keeps the setting it was built with, so changing the
builder afterwards can't re-enable following.
- Every result fetch (statements, prepared statements and
`DatabaseMetaData`) goes through `getStreams`, so the check is only
needed there. The host and port check is shared with
`getHostnameOverrideForEndpoint`.
- Documented in `docs/source/flight_sql_jdbc_driver.rst`.
Example:
```
jdbc:arrow-flight-sql://flight.example.com:443?followEndpointLocations=false
```
Notes:
- The default stays `true`, since changing it would break servers that
serve partitions from other hosts.
- Drivers without this change ignore the property and send it to the
server as a gRPC header, so applications that rely on it need a driver
version that includes it. As for the other boolean properties, a blank
or unrecognized value counts as `false`.
- Locations on the connection's own host and port only reuse the
connection when the property is `false`. By default they still get a new
connection, as before (see the GH-38574 comment in `getStreams`).
- There is no way to allow specific other hosts when the property is
`false`. An allowlist could be added later if anyone needs it.
- The existing message for non-TLS locations on encrypted connections
still shows the whole location URI. That predates this change and could
be redacted the same way separately.
## Tests
- `ConnectionFollowEndpointLocationsTest` (new). Its servers record the
calls they receive:
- by default, a server at another location is sent the connection's
bearer token;
- with `followEndpointLocations=false`, the query fails and that server
receives no calls;
- for a server that advertises its own location, the calls come from one
client connection with `false`, and from two by default.
- `ArrowFlightSqlClientHandlerTest`: locations on another host (over
encrypted and plaintext connections), on another port of the
connection's host, and on the connection's host and port but needing
another transport (`grpc+tls` on a plaintext connection, `https`) are
refused without using the client. The connection's own location
(including `grpc` and `grpc+tcp` locations on an encrypted connection),
a location on `hostnameOverride`, and `[other host,
arrow-flight-reuse-connection]` are fetched over the existing client.
The setting is kept after the builder changes, and the refusal message
leaves out the location's user info, path, query and fragment.
- `ArrowFlightSqlClientHandlerBuilderTest`: location matching for case,
a different or missing port, Unix sockets, IPv6 hosts with and without
brackets, an override with and without a port, and an override without
TLS. Also the default, and that a builder copy keeps the setting.
- `ArrowFlightConnectionConfigImplTest`: the default and parsing.
This change is additive and has no breaking changes.
The code, tests and docs were drafted with an AI assistant (Claude). The
refusal and connection-reuse tests fail when `getStreams` ignores the
property, and the full `flight-sql-jdbc-core` build passes.
Closes #1526.
---------
Co-authored-by: Fred Park <[email protected]>
---
docs/source/flight_sql_jdbc_driver.rst | 18 ++
.../arrow/driver/jdbc/ArrowFlightConnection.java | 1 +
.../jdbc/client/ArrowFlightSqlClientHandler.java | 82 +++++++-
.../utils/ArrowFlightConnectionConfigImpl.java | 9 +
.../ConnectionFollowEndpointLocationsTest.java | 214 +++++++++++++++++++++
.../ArrowFlightSqlClientHandlerBuilderTest.java | 68 +++++++
.../client/ArrowFlightSqlClientHandlerTest.java | 141 +++++++++++++-
.../utils/ArrowFlightConnectionConfigImplTest.java | 14 +-
.../jdbc/utils/FallbackFlightSqlProducer.java | 8 +
9 files changed, 539 insertions(+), 16 deletions(-)
diff --git a/docs/source/flight_sql_jdbc_driver.rst
b/docs/source/flight_sql_jdbc_driver.rst
index a685e2a79..6fee6ad5b 100644
--- a/docs/source/flight_sql_jdbc_driver.rst
+++ b/docs/source/flight_sql_jdbc_driver.rst
@@ -172,6 +172,24 @@ case-sensitive. The supported parameters are:
in subsequent internal connections used for retrieving streams
from separate endpoints.
+ * - followEndpointLocations
+ - true
+ - Whether to connect to the endpoint locations returned by the
+ server to retrieve query results. These connections are sent the
+ connection's credentials, client certificate and headers. When
+ false, an endpoint is only fetched over the existing connection:
+ if it has no locations, the ``arrow-flight-reuse-connection://?``
+ location, or a ``grpc``, ``grpc+tcp`` or ``grpc+tls`` location on
+ **HOSTNAME** and **PORT**. A ``grpc+tls`` location is only used
+ when TLS is enabled. Hosts are compared by name, without DNS
+ resolution. When TLS is enabled, a location on ``hostnameOverride``
+ is also used, on **PORT** unless the override includes a port.
+ Other locations are skipped, and the query fails with an
+ ``SQLException`` if an endpoint has no location that can be used.
+ ``retainCookies`` and ``retainAuth`` have no effect when this is
+ false. Set this to false when the server is not trusted to choose
+ which hosts the driver connects to and sends credentials to.
+
Note that URI values must be URI-encoded if they contain characters such
as !, @, $, etc.
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 5338bfdc8..d3485171b 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
@@ -142,6 +142,7 @@ public final class ArrowFlightConnection extends
AvaticaConnection {
.withCallOptions(config.toCallOption())
.withRetainCookies(config.retainCookies())
.withRetainAuth(config.retainAuth())
+ .withFollowEndpointLocations(config.followEndpointLocations())
.withCatalog(config.getCatalog())
.withClientCache(config.useClientCache() ? new FlightClientCache() :
null)
.withConnectTimeout(config.getConnectTimeout())
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 96bbe39fe..e91dce8e8 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
@@ -100,6 +100,7 @@ public final class ArrowFlightSqlClientHandler implements
AutoCloseable {
private final FlightSqlClient sqlClient;
private final Set<CallOption> options = new HashSet<>();
private final Builder builder;
+ private final boolean followEndpointLocations;
private final Optional<String> catalog;
private final @Nullable FlightClientCache flightClientCache;
@@ -115,6 +116,7 @@ public final class ArrowFlightSqlClientHandler implements
AutoCloseable {
this.cacheKey = Preconditions.checkNotNull(cacheKey);
this.sqlClient = Preconditions.checkNotNull(sqlClient);
this.builder = builder;
+ this.followEndpointLocations = builder.followEndpointLocations;
this.catalog = catalog;
this.flightClientCache = flightClientCache;
}
@@ -193,12 +195,26 @@ public final class ArrowFlightSqlClientHandler implements
AutoCloseable {
while (locations.hasNext()) {
Location location = locations.next();
final URI endpointUri = location.getUri();
- if
(endpointUri.getScheme().equals(LocationSchemes.REUSE_CONNECTION)) {
+ if
(endpointUri.getScheme().equals(LocationSchemes.REUSE_CONNECTION)
+ || (!followEndpointLocations &&
builder.isConnectionLocation(endpointUri))) {
stream =
new CloseableEndpointStreamPair(
sqlClient.getStream(endpoint.getTicket(), getOptions()),
null);
break;
}
+ if (!followEndpointLocations) {
+ exceptions.add(
+ new SQLException(
+ String.format(
+ "Refusing endpoint location (scheme=%s, host=%s,
port=%d) because "
+ + "followEndpointLocations is false and it
cannot be fetched over "
+ + "the connection to %s.",
+ endpointUri.getScheme(),
+ endpointUri.getHost(),
+ endpointUri.getPort(),
+ builder.getLocation().getUri())));
+ continue;
+ }
final boolean encryptEndpoint =
endpointUri.getScheme().equals(LocationSchemes.GRPC_TLS);
if (builder.useEncryption && !encryptEndpoint) {
@@ -752,6 +768,8 @@ public final class ArrowFlightSqlClientHandler implements
AutoCloseable {
@VisibleForTesting boolean retainAuth = true;
+ @VisibleForTesting boolean followEndpointLocations = true;
+
@VisibleForTesting Optional<String> catalog = Optional.empty();
// Copies (getStreams endpoint handlers) authenticate as the connection;
on servers that key
@@ -807,6 +825,7 @@ public final class ArrowFlightSqlClientHandler implements
AutoCloseable {
this.catalog = original.catalog;
this.oauthConfig = original.oauthConfig;
this.ownsSession = false;
+ this.followEndpointLocations = original.followEndpointLocations;
if (original.retainCookies) {
this.cookieFactory = original.cookieFactory;
@@ -939,17 +958,50 @@ public final class ArrowFlightSqlClientHandler implements
AutoCloseable {
*/
@VisibleForTesting
@Nullable String getHostnameOverrideForEndpoint(final URI endpointUri) {
- final String endpointHost = stripBrackets(endpointUri.getHost());
- if (!useEncryption
- || hostnameOverride == null
- || endpointHost == null
- || endpointUri.getPort() != port
- || !endpointHost.equalsIgnoreCase(stripBrackets(host))) {
+ if (!useEncryption || hostnameOverride == null ||
!isOnHostAndPort(endpointUri, host, port)) {
return null;
}
return hostnameOverride;
}
+ /**
+ * Checks whether an endpoint location is a gRPC location that names the
host and port this
+ * handler connects to or, when encryption is enabled, the hostname
override. The override is
+ * matched with this handler's port, unless it includes a port of its own.
A {@code grpc+tls}
+ * location only matches when encryption is enabled.
+ *
+ * @param endpointUri the endpoint location.
+ * @return whether the endpoint can be fetched over this handler's
connection.
+ */
+ @VisibleForTesting
+ boolean isConnectionLocation(final URI endpointUri) {
+ // Other schemes need another transport, such as an HTTP GET for https,
and a location that
+ // asks for TLS must not be fetched over a plaintext connection.
+ final String scheme = endpointUri.getScheme();
+ if (!LocationSchemes.GRPC.equals(scheme)
+ && !LocationSchemes.GRPC_INSECURE.equals(scheme)
+ && !(useEncryption && LocationSchemes.GRPC_TLS.equals(scheme))) {
+ return false;
+ }
+ if (isOnHostAndPort(endpointUri, host, port)) {
+ return true;
+ }
+ if (!useEncryption || hostnameOverride == null) {
+ return false;
+ }
+ return isOnHostAndPort(endpointUri, hostnameOverride, port)
+ || (endpointUri.getPort() != -1
+ &&
hostnameOverride.equalsIgnoreCase(endpointUri.getRawAuthority()));
+ }
+
+ private static boolean isOnHostAndPort(
+ final URI endpointUri, @Nullable final String host, final int port) {
+ final String endpointHost = stripBrackets(endpointUri.getHost());
+ return endpointHost != null
+ && endpointUri.getPort() == port
+ && endpointHost.equalsIgnoreCase(stripBrackets(host));
+ }
+
/**
* Strips the brackets from an IPv6 literal. {@link URI#getHost()} keeps
them, but a host set
* through properties may not have them.
@@ -1056,6 +1108,22 @@ public final class ArrowFlightSqlClientHandler
implements AutoCloseable {
return this;
}
+ /**
+ * Sets whether getStreams() may connect to the endpoint locations
returned by the server. These
+ * connections are sent this handler's credentials, client certificate and
headers. When false,
+ * an endpoint is only fetched over this handler's connection: if it has
no locations, the
+ * {@link LocationSchemes#REUSE_CONNECTION} location, or a gRPC location
on this handler's host
+ * and port or, when encryption is enabled, on the hostname override. A
{@code grpc+tls}
+ * location is only used when encryption is enabled. Other locations are
refused.
+ *
+ * @param followEndpointLocations whether to connect to endpoint locations.
+ * @return this builder instance.
+ */
+ public Builder withFollowEndpointLocations(boolean
followEndpointLocations) {
+ this.followEndpointLocations = followEndpointLocations;
+ return this;
+ }
+
/**
* Adds the provided {@code factories} to the list of {@link
#middlewareFactories} of this
* handler.
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 8460474ba..d6fafb754 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
@@ -182,6 +182,14 @@ public final class ArrowFlightConnectionConfigImpl extends
ConnectionConfigImpl
return ArrowFlightConnectionProperty.RETAIN_AUTH.getBoolean(properties);
}
+ /**
+ * Indicates if the driver may connect to the endpoint locations returned by
the server to fetch
+ * results. When false, results are only fetched over the existing
connection.
+ */
+ public boolean followEndpointLocations() {
+ return
ArrowFlightConnectionProperty.FOLLOW_ENDPOINT_LOCATIONS.getBoolean(properties);
+ }
+
/**
* The catalog to which a connection is made.
*
@@ -289,6 +297,7 @@ public final class ArrowFlightConnectionConfigImpl extends
ConnectionConfigImpl
TOKEN("token", null, Type.STRING, false),
RETAIN_COOKIES("retainCookies", true, Type.BOOLEAN, false),
RETAIN_AUTH("retainAuth", true, Type.BOOLEAN, false),
+ FOLLOW_ENDPOINT_LOCATIONS("followEndpointLocations", true, Type.BOOLEAN,
false),
CATALOG("catalog", null, Type.STRING, false),
CONNECT_TIMEOUT_MILLIS("connectTimeoutMs", 10000, Type.NUMBER, false),
USE_CLIENT_CACHE("useClientCache", true, Type.BOOLEAN, false),
diff --git
a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ConnectionFollowEndpointLocationsTest.java
b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ConnectionFollowEndpointLocationsTest.java
new file mode 100644
index 000000000..e1608dd36
--- /dev/null
+++
b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ConnectionFollowEndpointLocationsTest.java
@@ -0,0 +1,214 @@
+/*
+ * 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.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.CoreMatchers.everyItem;
+import static org.hamcrest.CoreMatchers.startsWith;
+import static org.hamcrest.MatcherAssert.assertThat;
+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 io.grpc.Grpc;
+import io.grpc.Metadata;
+import io.grpc.ServerCall;
+import io.grpc.ServerCallHandler;
+import io.grpc.ServerInterceptor;
+import io.grpc.netty.NettyServerBuilder;
+import java.net.SocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+import org.apache.arrow.driver.jdbc.authentication.UserPasswordAuthentication;
+import org.apache.arrow.driver.jdbc.utils.FallbackFlightSqlProducer;
+import org.apache.arrow.driver.jdbc.utils.PartitionedFlightSqlProducer;
+import org.apache.arrow.flight.FlightEndpoint;
+import org.apache.arrow.flight.FlightProducer;
+import org.apache.arrow.flight.FlightServer;
+import org.apache.arrow.flight.Location;
+import org.apache.arrow.flight.Ticket;
+import org.apache.arrow.memory.BufferAllocator;
+import org.apache.arrow.memory.RootAllocator;
+import org.apache.arrow.vector.IntVector;
+import org.apache.arrow.vector.VectorSchemaRoot;
+import org.apache.arrow.vector.types.Types;
+import org.apache.arrow.vector.types.pojo.Field;
+import org.apache.arrow.vector.types.pojo.Schema;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/**
+ * Tests the followEndpointLocations connection property. The servers record
the calls they receive,
+ * so the tests can check which connection each call came from and what it was
sent.
+ */
+public class ConnectionFollowEndpointLocationsTest {
+
+ private static final String USER = "user1";
+ private static final String PASSWORD = "pass1";
+ private static final Metadata.Key<String> AUTHORIZATION =
+ Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER);
+ private static final Ticket TICKET = new
Ticket("data".getBytes(StandardCharsets.UTF_8));
+
+ private BufferAllocator allocator;
+ private VectorSchemaRoot data;
+
+ @BeforeAll
+ public static void setUpDriver() throws SQLException {
+ DriverManager.registerDriver(new ArrowFlightJdbcDriver());
+ }
+
+ @BeforeEach
+ public void setUp() {
+ allocator = new RootAllocator(Long.MAX_VALUE);
+ data =
+ VectorSchemaRoot.create(
+ new Schema(
+ Collections.singletonList(
+ Field.nullable("int_column",
Types.MinorType.INT.getType()))),
+ allocator);
+ data.setRowCount(1);
+ ((IntVector) data.getVector(0)).set(0, 1);
+ }
+
+ @AfterEach
+ public void tearDown() {
+ data.close();
+ allocator.close();
+ }
+
+ @Test
+ public void testOtherLocationIsFollowedByDefault() throws Exception {
+ final List<String> dataServerCalls = Collections.synchronizedList(new
ArrayList<>());
+ try (FlightServer dataServer = dataServer(dataServerCalls);
+ PartitionedFlightSqlProducer producer =
+ new PartitionedFlightSqlProducer(
+ data.getSchema(), new FlightEndpoint(TICKET,
dataServer.getLocation()));
+ FlightServer rootServer = server(producer, (call, headers) -> {});
+ Connection connection = DriverManager.getConnection(url(rootServer,
""));
+ Statement statement = connection.createStatement();
+ ResultSet resultSet = statement.executeQuery("SELECT 1")) {
+ assertTrue(resultSet.next());
+ // The other server is sent the bearer token from the connection's
handshake.
+ assertFalse(dataServerCalls.isEmpty());
+ assertThat(dataServerCalls, everyItem(startsWith("Bearer ")));
+ }
+ }
+
+ @Test
+ public void testOtherLocationIsNotFollowed() throws Exception {
+ final List<String> dataServerCalls = Collections.synchronizedList(new
ArrayList<>());
+ try (FlightServer dataServer = dataServer(dataServerCalls);
+ PartitionedFlightSqlProducer producer =
+ new PartitionedFlightSqlProducer(
+ data.getSchema(), new FlightEndpoint(TICKET,
dataServer.getLocation()));
+ FlightServer rootServer = server(producer, (call, headers) -> {});
+ Connection connection =
+ DriverManager.getConnection(url(rootServer,
"&followEndpointLocations=false"));
+ Statement statement = connection.createStatement()) {
+ final SQLException e =
+ assertThrows(SQLException.class, () ->
statement.executeQuery("SELECT 1"));
+ assertThat(e.getMessage(), containsString("followEndpointLocations"));
+ assertTrue(dataServerCalls.isEmpty());
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {true, false})
+ public void testOwnLocation(final boolean followEndpointLocations) throws
Exception {
+ final Set<SocketAddress> clients = ConcurrentHashMap.newKeySet();
+ try (FallbackFlightSqlProducer producer = new
FallbackFlightSqlProducer(data);
+ FlightServer rootServer =
+ server(
+ producer,
+ (call, headers) ->
+
clients.add(call.getAttributes().get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR)))) {
+ producer.setLocation(rootServer.getLocation());
+ try (Connection connection =
+ DriverManager.getConnection(
+ url(rootServer, "&followEndpointLocations=" +
followEndpointLocations));
+ Statement statement = connection.createStatement();
+ ResultSet resultSet = statement.executeQuery("own location")) {
+ assertTrue(resultSet.next());
+ assertEquals(1, resultSet.getInt(1));
+ }
+ // Following the location opens a second connection to the same server.
+ assertEquals(followEndpointLocations ? 2 : 1, clients.size());
+ }
+ }
+
+ /** Starts a server that serves {@link #TICKET} and records the
authorization of each call. */
+ private FlightServer dataServer(final List<String> calls) throws Exception {
+ return serverBuilder(
+ new PartitionedFlightSqlProducer.DataOnlyFlightSqlProducer(TICKET,
data),
+ (call, headers) ->
calls.add(String.valueOf(headers.get(AUTHORIZATION))))
+ .build()
+ .start();
+ }
+
+ /** Starts a server that requires {@link #USER} and {@link #PASSWORD}. */
+ private FlightServer server(
+ final FlightProducer producer, final BiConsumer<ServerCall<?, ?>,
Metadata> onCall)
+ throws Exception {
+ return serverBuilder(producer, onCall)
+ .headerAuthenticator(
+ new UserPasswordAuthentication.Builder().user(USER,
PASSWORD).build().authenticate())
+ .build()
+ .start();
+ }
+
+ private FlightServer.Builder serverBuilder(
+ final FlightProducer producer, final BiConsumer<ServerCall<?, ?>,
Metadata> onCall) {
+ return FlightServer.builder(allocator,
Location.forGrpcInsecure("localhost", 0), producer)
+ .transportHint(
+ "grpc.builderConsumer",
+ (Consumer<NettyServerBuilder>)
+ builder ->
+ builder.intercept(
+ new ServerInterceptor() {
+ @Override
+ public <ReqT, RespT> ServerCall.Listener<ReqT>
interceptCall(
+ final ServerCall<ReqT, RespT> call,
+ final Metadata headers,
+ final ServerCallHandler<ReqT, RespT> next) {
+ onCall.accept(call, headers);
+ return next.startCall(call, headers);
+ }
+ }));
+ }
+
+ private static String url(final FlightServer server, final String
extraParameters) {
+ return String.format(
+
"jdbc:arrow-flight-sql://%s:%d/?useEncryption=false&user=%s&password=%s%s",
+ server.getLocation().getUri().getHost(), server.getPort(), USER,
PASSWORD, extraParameters);
+ }
+}
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 58e139b58..657078404 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
@@ -145,6 +145,7 @@ public class ArrowFlightSqlClientHandlerBuilderTest {
assertNull(builder.token);
assertTrue(builder.retainAuth);
assertTrue(builder.retainCookies);
+ assertTrue(builder.followEndpointLocations);
assertNull(builder.tlsRootCertificatesPath);
assertNull(builder.clientCertificatePath);
assertNull(builder.clientKeyPath);
@@ -167,6 +168,15 @@ public class ArrowFlightSqlClientHandlerBuilderTest {
assertNull(copiedBuilder.hostnameOverride);
}
+ @Test
+ public void testFollowEndpointLocationsIsCopied() {
+ final ArrowFlightSqlClientHandler.Builder rootBuilder =
+ new
ArrowFlightSqlClientHandler.Builder().withFollowEndpointLocations(false);
+
+ // Unlike the hostname override, this applies to every location, so a copy
must keep it.
+ assertFalse(new
ArrowFlightSqlClientHandler.Builder(rootBuilder).followEndpointLocations);
+ }
+
@Test
public void testHostnameOverrideForEndpointOnSameHost() {
final ArrowFlightSqlClientHandler.Builder builder =
@@ -258,6 +268,64 @@ public class ArrowFlightSqlClientHandlerBuilderTest {
assertNull(builder.getHostnameOverrideForEndpoint(URI.create("grpc+tls://127.0.0.1:1234")));
}
+ @Test
+ public void testIsConnectionLocation() {
+ final ArrowFlightSqlClientHandler.Builder builder =
+ new ArrowFlightSqlClientHandler.Builder()
+ .withHost("Tunnel.Local")
+ .withPort(1234)
+ .withHostnameOverride("flight.example.com");
+
+
assertTrue(builder.isConnectionLocation(URI.create("grpc+tls://tunnel.local:1234")));
+
assertTrue(builder.isConnectionLocation(URI.create("grpc+tls://FLIGHT.example.com:1234")));
+
assertFalse(builder.isConnectionLocation(URI.create("grpc+tls://tunnel.local:5678")));
+
assertFalse(builder.isConnectionLocation(URI.create("grpc+tls://tunnel.local")));
+
assertFalse(builder.isConnectionLocation(URI.create("grpc+tls://other.example.com:1234")));
+
assertFalse(builder.isConnectionLocation(URI.create("grpc+unix:///tmp/flight.sock")));
+ }
+
+ @Test
+ public void testIsConnectionLocationWithHostnameOverridePort() {
+ // The override replaces the whole authority, so its own port is used
instead.
+ final ArrowFlightSqlClientHandler.Builder builder =
+ new ArrowFlightSqlClientHandler.Builder()
+ .withHost("127.0.0.1")
+ .withPort(1234)
+ .withHostnameOverride("flight.example.com:32010");
+
+
assertTrue(builder.isConnectionLocation(URI.create("grpc+tls://flight.example.com:32010")));
+
assertFalse(builder.isConnectionLocation(URI.create("grpc+tls://flight.example.com:1234")));
+
assertFalse(builder.isConnectionLocation(URI.create("grpc+tls://flight.example.com")));
+ }
+
+ @Test
+ public void testIsConnectionLocationOnIpv6Host() {
+ // The JDBC URL is parsed with URI#getHost, which keeps the brackets.
+ assertTrue(
+ new ArrowFlightSqlClientHandler.Builder()
+ .withHost(URI.create("jdbc://[::1]:1234").getHost())
+ .withPort(1234)
+ .isConnectionLocation(URI.create("grpc+tls://[::1]:1234")));
+ assertTrue(
+ new ArrowFlightSqlClientHandler.Builder()
+ .withHost("::1")
+ .withPort(1234)
+ .isConnectionLocation(URI.create("grpc+tls://[::1]:1234")));
+ }
+
+ @Test
+ public void
testIsConnectionLocationIgnoresHostnameOverrideWithoutEncryption() {
+ final ArrowFlightSqlClientHandler.Builder builder =
+ new ArrowFlightSqlClientHandler.Builder()
+ .withHost("127.0.0.1")
+ .withPort(1234)
+ .withEncryption(false)
+ .withHostnameOverride("flight.example.com");
+
+
assertTrue(builder.isConnectionLocation(URI.create("grpc+tcp://127.0.0.1:1234")));
+
assertFalse(builder.isConnectionLocation(URI.create("grpc+tcp://flight.example.com:1234")));
+ }
+
@Test
public void testBlankHostnameOverrideIsUnset() {
assertNull(new
ArrowFlightSqlClientHandler.Builder().withHostnameOverride("").hostnameOverride);
diff --git
a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandlerTest.java
b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandlerTest.java
index a885c20be..86a0a193d 100644
---
a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandlerTest.java
+++
b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandlerTest.java
@@ -18,6 +18,7 @@ package org.apache.arrow.driver.jdbc.client;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -30,8 +31,10 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
+import java.net.URI;
import java.sql.SQLException;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
@@ -96,16 +99,138 @@ public class ArrowFlightSqlClientHandlerTest {
}
}
+ @ParameterizedTest
+ @MethodSource
+ public void
testGetStreamsRefusesOtherLocationsWhenNotFollowingEndpointLocations(
+ final boolean useEncryption, final Location location) throws Exception {
+ try (BufferAllocator allocator = new RootAllocator(Long.MAX_VALUE)) {
+ final FlightSqlClient sqlClient = mock(FlightSqlClient.class);
+ try (ArrowFlightSqlClientHandler handler =
+ handler(
+ sqlClient,
+ builder(allocator)
+ .withEncryption(useEncryption)
+ .withFollowEndpointLocations(false))) {
+ final FlightInfo flightInfo = flightInfoWithLocations(location);
+
+ // A connection attempt would fail with a different error, so the
message shows that the
+ // location was refused before connecting and sending the credentials.
+ final SQLException ex =
+ assertThrows(SQLException.class, () ->
handler.getStreams(flightInfo));
+ assertTrue(ex.getMessage().contains("followEndpointLocations"),
ex.getMessage());
+ verifyNoInteractions(sqlClient);
+ }
+ }
+ }
+
+ private static Object[]
testGetStreamsRefusesOtherLocationsWhenNotFollowingEndpointLocations() {
+ return new Object[] {
+ new Object[] {true, Location.forGrpcTls("other.example.com", 443)},
+ new Object[] {true, Location.forGrpcTls("localhost", 8443)},
+ new Object[] {false, Location.forGrpcInsecure("other.example.com", 443)},
+ // On the connection's host and port, but needing another transport.
+ new Object[] {false, Location.forGrpcTls("localhost", 443)},
+ new Object[] {true, new
Location(URI.create("https://localhost:443/results"))},
+ };
+ }
+
+ @Test
+ public void
testGetStreamsKeepsFollowEndpointLocationsSettingAfterBuilderChanges()
+ throws Exception {
+ try (BufferAllocator allocator = new RootAllocator(Long.MAX_VALUE)) {
+ final FlightSqlClient sqlClient = mock(FlightSqlClient.class);
+ final ArrowFlightSqlClientHandler.Builder builder =
+ builder(allocator).withFollowEndpointLocations(false);
+ try (ArrowFlightSqlClientHandler handler = handler(sqlClient, builder)) {
+ builder.withFollowEndpointLocations(true);
+ final FlightInfo flightInfo =
+
flightInfoWithLocations(Location.forGrpcInsecure("other.example.com", 443));
+
+ final SQLException ex =
+ assertThrows(SQLException.class, () ->
handler.getStreams(flightInfo));
+ assertTrue(ex.getMessage().contains("followEndpointLocations is
false"), ex.getMessage());
+ verifyNoInteractions(sqlClient);
+ }
+ }
+ }
+
+ @Test
+ public void testGetStreamsOmitsUriDetailsWhenNotFollowingEndpointLocations()
throws Exception {
+ try (BufferAllocator allocator = new RootAllocator(Long.MAX_VALUE)) {
+ final FlightSqlClient sqlClient = mock(FlightSqlClient.class);
+ try (ArrowFlightSqlClientHandler handler =
+ handler(sqlClient,
builder(allocator).withFollowEndpointLocations(false))) {
+ final FlightInfo flightInfo =
+ flightInfoWithLocations(
+ new Location(
+
URI.create("https://[email protected]:443/results?query#fragment")));
+
+ final SQLException ex =
+ assertThrows(SQLException.class, () ->
handler.getStreams(flightInfo));
+ final String message = ex.getMessage();
+ assertTrue(message.contains("scheme=https, host=other.example.com,
port=443"), message);
+ assertFalse(message.contains("userinfo"), message);
+ assertFalse(message.contains("/results"), message);
+ assertFalse(message.contains("?query"), message);
+ assertFalse(message.contains("#fragment"), message);
+ verifyNoInteractions(sqlClient);
+ }
+ }
+ }
+
+ @ParameterizedTest
+ @MethodSource
+ public void testGetStreamsUsesConnectionWhenNotFollowingEndpointLocations(
+ final List<Location> locations) throws Exception {
+ try (BufferAllocator allocator = new RootAllocator(Long.MAX_VALUE)) {
+ final FlightSqlClient sqlClient = mock(FlightSqlClient.class);
+ final FlightStream stream = mock(FlightStream.class);
+ when(sqlClient.getStream(any(Ticket.class),
any(CallOption[].class))).thenReturn(stream);
+ try (ArrowFlightSqlClientHandler handler =
+ handler(
+ sqlClient,
+ builder(allocator)
+ .withHostnameOverride("flight.example.com")
+ .withFollowEndpointLocations(false))) {
+ final FlightInfo flightInfo =
flightInfoWithLocations(locations.toArray(new Location[0]));
+
+ final List<CloseableEndpointStreamPair> streams =
handler.getStreams(flightInfo);
+ assertEquals(1, streams.size());
+ assertSame(stream, streams.get(0).getStream());
+ AutoCloseables.close(streams);
+ }
+ }
+ }
+
+ private static Object[]
testGetStreamsUsesConnectionWhenNotFollowingEndpointLocations() {
+ return new Object[] {
+ Collections.singletonList(Location.forGrpcTls("localhost", 443)),
+ // Fetched over the encrypted connection, so this does not drop TLS.
+ Collections.singletonList(Location.forGrpcInsecure("localhost", 443)),
+ Collections.singletonList(new
Location(URI.create("grpc://localhost:443"))),
+ Collections.singletonList(Location.forGrpcTls("flight.example.com",
443)),
+ // The other location is skipped instead of failing the query.
+ Arrays.asList(Location.forGrpcTls("other.example.com", 443),
Location.reuseConnection()),
+ };
+ }
+
+ private static ArrowFlightSqlClientHandler.Builder builder(final
BufferAllocator allocator) {
+ return new ArrowFlightSqlClientHandler.Builder()
+ .withHost("localhost")
+ .withPort(443)
+ .withEncryption(true)
+ .withUsername("user")
+ .withPassword("password")
+ .withBufferAllocator(allocator);
+ }
+
private static ArrowFlightSqlClientHandler encryptedHandler(
final FlightSqlClient sqlClient, final BufferAllocator allocator) {
- final ArrowFlightSqlClientHandler.Builder builder =
- new ArrowFlightSqlClientHandler.Builder()
- .withHost("localhost")
- .withPort(443)
- .withEncryption(true)
- .withUsername("user")
- .withPassword("password")
- .withBufferAllocator(allocator);
+ return handler(sqlClient, builder(allocator));
+ }
+
+ private static ArrowFlightSqlClientHandler handler(
+ final FlightSqlClient sqlClient, final
ArrowFlightSqlClientHandler.Builder builder) {
return new ArrowFlightSqlClientHandler(
"cacheKey", sqlClient, builder, new ArrayList<>(), Optional.empty(),
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 923d98d10..1889dfab6 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
@@ -19,6 +19,7 @@ package org.apache.arrow.driver.jdbc.utils;
import static java.lang.Runtime.getRuntime;
import static
org.apache.arrow.driver.jdbc.utils.ArrowFlightConnectionConfigImpl.ArrowFlightConnectionProperty.CATALOG;
import static
org.apache.arrow.driver.jdbc.utils.ArrowFlightConnectionConfigImpl.ArrowFlightConnectionProperty.CONNECT_TIMEOUT_MILLIS;
+import static
org.apache.arrow.driver.jdbc.utils.ArrowFlightConnectionConfigImpl.ArrowFlightConnectionProperty.FOLLOW_ENDPOINT_LOCATIONS;
import static
org.apache.arrow.driver.jdbc.utils.ArrowFlightConnectionConfigImpl.ArrowFlightConnectionProperty.HOST;
import static
org.apache.arrow.driver.jdbc.utils.ArrowFlightConnectionConfigImpl.ArrowFlightConnectionProperty.HOSTNAME_OVERRIDE;
import static
org.apache.arrow.driver.jdbc.utils.ArrowFlightConnectionConfigImpl.ArrowFlightConnectionProperty.PASSWORD;
@@ -93,6 +94,11 @@ public final class ArrowFlightConnectionConfigImplTest {
assertThat(arrowFlightConnectionConfig.useEncryption(), is(false));
}
+ @Test
+ public void testFollowEndpointLocationsDefaultsToTrue() {
+ assertThat(arrowFlightConnectionConfig.followEndpointLocations(),
is(true));
+ }
+
@ParameterizedTest
@ValueSource(strings = {"", " "})
public void testBlankHostnameOverrideIsNull(String value) {
@@ -196,6 +202,12 @@ public final class ArrowFlightConnectionConfigImplTest {
false,
false,
(Function<ArrowFlightConnectionConfigImpl, ?>)
- ArrowFlightConnectionConfigImpl::useClientCache));
+ ArrowFlightConnectionConfigImpl::useClientCache),
+ Arguments.of(
+ FOLLOW_ENDPOINT_LOCATIONS,
+ false,
+ false,
+ (Function<ArrowFlightConnectionConfigImpl, ?>)
+ ArrowFlightConnectionConfigImpl::followEndpointLocations));
}
}
diff --git
a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/FallbackFlightSqlProducer.java
b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/FallbackFlightSqlProducer.java
index 670b9e3be..09b0a372c 100644
---
a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/FallbackFlightSqlProducer.java
+++
b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/FallbackFlightSqlProducer.java
@@ -35,11 +35,17 @@ import org.apache.arrow.vector.types.pojo.Schema;
public class FallbackFlightSqlProducer extends BasicFlightSqlProducer {
private final VectorSchemaRoot data;
+ private volatile Location location;
public FallbackFlightSqlProducer(VectorSchemaRoot resultData) {
this.data = resultData;
}
+ /** Sets the location of this producer's server, returned by the "own
location" query. */
+ public void setLocation(Location location) {
+ this.location = location;
+ }
+
@Override
protected <T extends Message> List<FlightEndpoint> determineEndpoints(
T request, FlightDescriptor flightDescriptor, Schema schema) {
@@ -119,6 +125,8 @@ public class FallbackFlightSqlProducer extends
BasicFlightSqlProducer {
Location.forGrpcInsecure("203.0.113.0", 9999),
Location.reuseConnection())
.build());
+ } else if (query.equals("own location")) {
+ endpoints = Collections.singletonList(FlightEndpoint.builder(ticket,
location).build());
} else {
throw
CallStatus.UNIMPLEMENTED.withDescription(query).toRuntimeException();
}