From d91163e53746e5c4119f1f3f7d901313e9a6b093 Mon Sep 17 00:00:00 2001 From: Fred Park Date: Wed, 25 Nov 2026 16:46:03 -0700 Subject: [PATCH 1/5] GH-1526: [JDBC] Allow disabling connections to server-advertised endpoint locations Add a followEndpointLocations connection property, defaulting to true so existing behavior is unchanged. When false, getStreams never opens a new connection for an endpoint, so the connection's credentials are only sent to the host the application connected to. Endpoints with no locations, the arrow-flight-reuse-connection location, or a location on the connection's own host (or hostnameOverride, when TLS is enabled) and port are fetched over the existing connection. Other locations are refused through the existing per-location error path, so an endpoint's remaining locations are still tried, and the query fails with an SQLException if none can be used. Closes #1526. --- docs/source/flight_sql_jdbc_driver.rst | 13 +++ .../driver/jdbc/ArrowFlightConnection.java | 1 + .../client/ArrowFlightSqlClientHandler.java | 52 ++++++++++- .../ArrowFlightConnectionConfigImpl.java | 9 ++ .../arrow/driver/jdbc/ResultSetTest.java | 84 +++++++++++++++++ ...rrowFlightSqlClientHandlerBuilderTest.java | 38 ++++++++ .../ArrowFlightSqlClientHandlerTest.java | 90 +++++++++++++++++-- .../ArrowFlightConnectionConfigImplTest.java | 14 ++- 8 files changed, 291 insertions(+), 10 deletions(-) diff --git a/docs/source/flight_sql_jdbc_driver.rst b/docs/source/flight_sql_jdbc_driver.rst index a685e2a799..984a6889d9 100644 --- a/docs/source/flight_sql_jdbc_driver.rst +++ b/docs/source/flight_sql_jdbc_driver.rst @@ -172,6 +172,19 @@ 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. When false, an endpoint is only fetched + over the existing connection: if it has no locations, the + ``arrow-flight-reuse-connection://?`` location, or a location on + **HOSTNAME** (or ``hostnameOverride``, when TLS is enabled) and + **PORT**. Other locations are refused, and the query fails with an + ``SQLException`` if an endpoint has no location that can be used. + 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 5338bfdc8a..d3485171b7 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 @@ private static ArrowFlightSqlClientHandler createNewClientHandler( .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 96bbe39fef..7b1ce68829 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 @@ -193,12 +193,24 @@ public List getStreams(final FlightInfo flightInfo) 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) + || (!builder.followEndpointLocations + && builder.isConnectionLocation(endpointUri))) { stream = new CloseableEndpointStreamPair( sqlClient.getStream(endpoint.getTicket(), getOptions()), null); break; } + if (!builder.followEndpointLocations) { + exceptions.add( + new SQLException( + String.format( + "Refusing to connect to endpoint location %s because " + + "followEndpointLocations is false and it is not on the host and " + + "port of the connection to %s.", + endpointUri, builder.getLocation().getUri()))); + continue; + } final boolean encryptEndpoint = endpointUri.getScheme().equals(LocationSchemes.GRPC_TLS); if (builder.useEncryption && !encryptEndpoint) { @@ -752,6 +764,8 @@ public static final class Builder { @VisibleForTesting boolean retainAuth = true; + @VisibleForTesting boolean followEndpointLocations = true; + @VisibleForTesting Optional catalog = Optional.empty(); // Copies (getStreams endpoint handlers) authenticate as the connection; on servers that key @@ -807,6 +821,7 @@ public Builder() {} this.catalog = original.catalog; this.oauthConfig = original.oauthConfig; this.ownsSession = false; + this.followEndpointLocations = original.followEndpointLocations; if (original.retainCookies) { this.cookieFactory = original.cookieFactory; @@ -950,6 +965,26 @@ public Builder withHostnameOverride(@Nullable final String hostnameOverride) { return hostnameOverride; } + /** + * Checks whether an endpoint location names the host and port this handler connects to, or the + * hostname override and that port. As for the connection, the override is ignored when + * encryption is disabled. + * + * @param endpointUri the endpoint location. + * @return whether the endpoint can be fetched over this handler's connection. + */ + @VisibleForTesting + boolean isConnectionLocation(final URI endpointUri) { + final String endpointHost = stripBrackets(endpointUri.getHost()); + if (endpointHost == null || endpointUri.getPort() != port) { + return false; + } + return endpointHost.equalsIgnoreCase(stripBrackets(host)) + || (useEncryption + && hostnameOverride != null + && endpointHost.equalsIgnoreCase(stripBrackets(hostnameOverride))); + } + /** * Strips the brackets from an IPv6 literal. {@link URI#getHost()} keeps them, but a host set * through properties may not have them. @@ -1056,6 +1091,21 @@ public Builder withRetainAuth(boolean retainAuth) { return this; } + /** + * Sets whether getStreams() may connect to the endpoint locations returned by the server. These + * connections are sent this handler's credentials. 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 location on this handler's host (or hostname + * override) and port. 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 8460474ba8..d6fafb7543 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 boolean retainAuth() { 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 enum ArrowFlightConnectionProperty implements ConnectionProperty { 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/ResultSetTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ResultSetTest.java index c5c6a4fbb2..43a66ea027 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ResultSetTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ResultSetTest.java @@ -673,6 +673,90 @@ public void testPartitionedFlightServerAllFailure() throws Exception { } } + @Test + public void testPartitionedFlightServerWithoutFollowingEndpointLocations() throws Exception { + final Schema schema = + new Schema( + Collections.singletonList( + Field.nullablePrimitive("int_column", new ArrowType.Int(32, true)))); + try (BufferAllocator allocator = new RootAllocator(Long.MAX_VALUE); + VectorSchemaRoot partition = VectorSchemaRoot.create(schema, allocator)) { + final Ticket ticket = new Ticket("first".getBytes(StandardCharsets.UTF_8)); + final AtomicInteger dataRequests = new AtomicInteger(); + final FlightProducer dataProducer = + new PartitionedFlightSqlProducer.DataOnlyFlightSqlProducer(ticket, partition) { + @Override + public void getStream( + CallContext context, Ticket ticket, ServerStreamListener listener) { + dataRequests.incrementAndGet(); + super.getStream(context, ticket, listener); + } + }; + + try (FlightServer dataServer = + FlightServer.builder(allocator, forGrpcInsecure("localhost", 0), dataProducer) + .build() + .start()) { + final FlightEndpoint endpoint = new FlightEndpoint(ticket, dataServer.getLocation()); + try (final PartitionedFlightSqlProducer rootProducer = + new PartitionedFlightSqlProducer(schema, endpoint); + FlightServer rootServer = + FlightServer.builder(allocator, forGrpcInsecure("localhost", 0), rootProducer) + .build() + .start(); + Connection newConnection = + DriverManager.getConnection( + String.format( + "jdbc:arrow-flight-sql://%s:%d/?useEncryption=false" + + "&followEndpointLocations=false", + rootServer.getLocation().getUri().getHost(), rootServer.getPort())); + Statement newStatement = newConnection.createStatement()) { + final SQLException e = + assertThrows( + SQLException.class, () -> newStatement.executeQuery("Select partitioned_data")); + assertThat(e.getMessage(), containsString("followEndpointLocations")); + assertEquals(0, dataRequests.get()); + } + } + } + } + + @Test + public void testFallbackFlightServerWithoutFollowingEndpointLocations() throws Exception { + final Schema schema = + new Schema( + Collections.singletonList(Field.nullable("int_column", Types.MinorType.INT.getType()))); + try (BufferAllocator allocator = new RootAllocator(Long.MAX_VALUE); + VectorSchemaRoot resultData = VectorSchemaRoot.create(schema, allocator)) { + resultData.setRowCount(1); + ((IntVector) resultData.getVector(0)).set(0, 1); + + try (final FallbackFlightSqlProducer rootProducer = + new FallbackFlightSqlProducer(resultData); + FlightServer rootServer = + FlightServer.builder(allocator, forGrpcInsecure("localhost", 0), rootProducer) + .build() + .start(); + Connection newConnection = + DriverManager.getConnection( + String.format( + "jdbc:arrow-flight-sql://%s:%d/?useEncryption=false" + + "&followEndpointLocations=false", + rootServer.getLocation().getUri().getHost(), rootServer.getPort())); + Statement newStatement = newConnection.createStatement(); + // The endpoint's first location is on another port, so it is skipped for the + // arrow-flight-reuse-connection location. + ResultSet result = newStatement.executeQuery("fallback with error")) { + List actualData = new ArrayList<>(); + while (result.next()) { + actualData.add(result.getInt(1)); + } + + assertEquals(Collections.singletonList(1), actualData); + } + } + } + @Test public void testFallbackFlightServer() throws Exception { final Schema schema = 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 58e139b58a..e87bdf0bb4 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 void testDefaults() { assertNull(builder.token); assertTrue(builder.retainAuth); assertTrue(builder.retainCookies); + assertTrue(builder.followEndpointLocations); assertNull(builder.tlsRootCertificatesPath); assertNull(builder.clientCertificatePath); assertNull(builder.clientKeyPath); @@ -258,6 +259,43 @@ public void testHostnameOverrideForEndpointWithoutEncryption() { 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 testIsConnectionLocationOnIpv6Host() { + final ArrowFlightSqlClientHandler.Builder builder = + new ArrowFlightSqlClientHandler.Builder().withHost("::1").withPort(1234); + + assertTrue(builder.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 a885c20be7..4c13d564ec 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 @@ -32,6 +32,7 @@ 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 +97,89 @@ public void testGetStreamsFallsBackToNextLocationAfterUnencryptedEndpoint() thro } } + @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)}, + }; + } + + @ParameterizedTest + @MethodSource + public void testGetStreamsUsesConnectionWhenNotFollowingEndpointLocations( + final List 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 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(Location.forGrpcTls("flight.example.com", 443)), + 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 923d98d10b..1889dfab69 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 @@ 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 void testUseEncryptionRejectsFalsyValues(String value) { 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 static Stream provideParameters() { false, false, (Function) - ArrowFlightConnectionConfigImpl::useClientCache)); + ArrowFlightConnectionConfigImpl::useClientCache), + Arguments.of( + FOLLOW_ENDPOINT_LOCATIONS, + false, + false, + (Function) + ArrowFlightConnectionConfigImpl::followEndpointLocations)); } } From 16c24df05bb199e73fe8ba83df8c1e16382594ab Mon Sep 17 00:00:00 2001 From: Fred Park Date: Wed, 25 Nov 2026 17:08:02 -0700 Subject: [PATCH 2/5] Match hostnameOverride with a port and tighten docs and tests An override that includes a port (flight.example.com:32010) never matched, though the docs allow one; it now matches locations on that host and port. Share the host and port check with getHostnameOverrideForEndpoint. Note in the docs that the scheme is ignored, that followed connections also get the client certificate and headers, and that retainCookies and retainAuth have no effect when false. Replace the fallback end-to-end test, which passed with the flag ignored, with one where the server advertises its own location, and cover bracketed IPv6 hosts. --- docs/source/flight_sql_jdbc_driver.rst | 17 ++++---- .../client/ArrowFlightSqlClientHandler.java | 42 ++++++++++--------- .../arrow/driver/jdbc/ResultSetTest.java | 34 +++++++-------- ...rrowFlightSqlClientHandlerBuilderTest.java | 27 ++++++++++-- .../ArrowFlightSqlClientHandlerTest.java | 1 + .../jdbc/utils/FallbackFlightSqlProducer.java | 8 ++++ 6 files changed, 83 insertions(+), 46 deletions(-) diff --git a/docs/source/flight_sql_jdbc_driver.rst b/docs/source/flight_sql_jdbc_driver.rst index 984a6889d9..686d36d493 100644 --- a/docs/source/flight_sql_jdbc_driver.rst +++ b/docs/source/flight_sql_jdbc_driver.rst @@ -176,14 +176,17 @@ case-sensitive. The supported parameters are: - true - Whether to connect to the endpoint locations returned by the server to retrieve query results. These connections are sent the - connection's credentials. When false, an endpoint is only fetched - over the existing connection: if it has no locations, the + connection's credentials, client certificate and headers. When + false, an endpoint is only fetched over the existing connection, + whatever the location's scheme: if it has no locations, the ``arrow-flight-reuse-connection://?`` location, or a location on - **HOSTNAME** (or ``hostnameOverride``, when TLS is enabled) and - **PORT**. Other locations are refused, and the query fails with an - ``SQLException`` if an endpoint has no location that can be used. - Set this to false when the server is not trusted to choose which - hosts the driver connects to and sends credentials to. + **HOSTNAME** and **PORT**. 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/client/ArrowFlightSqlClientHandler.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java index 7b1ce68829..e9d363dff2 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 @@ -954,35 +954,39 @@ public Builder withHostnameOverride(@Nullable final String hostnameOverride) { */ @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 names the host and port this handler connects to, or the - * hostname override and that port. As for the connection, the override is ignored when - * encryption is disabled. + * Checks whether an endpoint location 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. * * @param endpointUri the endpoint location. * @return whether the endpoint can be fetched over this handler's connection. */ @VisibleForTesting boolean isConnectionLocation(final URI endpointUri) { - final String endpointHost = stripBrackets(endpointUri.getHost()); - if (endpointHost == null || endpointUri.getPort() != port) { + if (isOnHostAndPort(endpointUri, host, port)) { + return true; + } + if (!useEncryption || hostnameOverride == null) { return false; } - return endpointHost.equalsIgnoreCase(stripBrackets(host)) - || (useEncryption - && hostnameOverride != null - && endpointHost.equalsIgnoreCase(stripBrackets(hostnameOverride))); + 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)); } /** @@ -1093,10 +1097,10 @@ public Builder withRetainAuth(boolean retainAuth) { /** * Sets whether getStreams() may connect to the endpoint locations returned by the server. These - * connections are sent this handler's credentials. 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 location on this handler's host (or hostname - * override) and port. Other locations are refused. + * 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 location on this handler's host and + * port or, when encryption is enabled, on the hostname override. Other locations are refused. * * @param followEndpointLocations whether to connect to endpoint locations. * @return this builder instance. diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ResultSetTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ResultSetTest.java index 43a66ea027..ecfc41f36e 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ResultSetTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ResultSetTest.java @@ -722,7 +722,7 @@ public void getStream( } @Test - public void testFallbackFlightServerWithoutFollowingEndpointLocations() throws Exception { + public void testOwnLocationWithoutFollowingEndpointLocations() throws Exception { final Schema schema = new Schema( Collections.singletonList(Field.nullable("int_column", Types.MinorType.INT.getType()))); @@ -736,23 +736,23 @@ public void testFallbackFlightServerWithoutFollowingEndpointLocations() throws E FlightServer rootServer = FlightServer.builder(allocator, forGrpcInsecure("localhost", 0), rootProducer) .build() - .start(); - Connection newConnection = - DriverManager.getConnection( - String.format( - "jdbc:arrow-flight-sql://%s:%d/?useEncryption=false" - + "&followEndpointLocations=false", - rootServer.getLocation().getUri().getHost(), rootServer.getPort())); - Statement newStatement = newConnection.createStatement(); - // The endpoint's first location is on another port, so it is skipped for the - // arrow-flight-reuse-connection location. - ResultSet result = newStatement.executeQuery("fallback with error")) { - List actualData = new ArrayList<>(); - while (result.next()) { - actualData.add(result.getInt(1)); - } + .start()) { + rootProducer.setLocation(rootServer.getLocation()); + try (Connection newConnection = + DriverManager.getConnection( + String.format( + "jdbc:arrow-flight-sql://%s:%d/?useEncryption=false" + + "&followEndpointLocations=false", + rootServer.getLocation().getUri().getHost(), rootServer.getPort())); + Statement newStatement = newConnection.createStatement(); + ResultSet result = newStatement.executeQuery("own location")) { + List actualData = new ArrayList<>(); + while (result.next()) { + actualData.add(result.getInt(1)); + } - assertEquals(Collections.singletonList(1), actualData); + assertEquals(Collections.singletonList(1), actualData); + } } } } 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 e87bdf0bb4..cf10816339 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 @@ -276,11 +276,32 @@ public void testIsConnectionLocation() { } @Test - public void testIsConnectionLocationOnIpv6Host() { + public void testIsConnectionLocationWithHostnameOverridePort() { + // The override replaces the whole authority, so its own port is used instead. final ArrowFlightSqlClientHandler.Builder builder = - new ArrowFlightSqlClientHandler.Builder().withHost("::1").withPort(1234); + new ArrowFlightSqlClientHandler.Builder() + .withHost("127.0.0.1") + .withPort(1234) + .withHostnameOverride("flight.example.com:32010"); - assertTrue(builder.isConnectionLocation(URI.create("grpc+tls://[::1]:1234"))); + 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 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 4c13d564ec..b6d57612be 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 @@ -159,6 +159,7 @@ private static Object[] testGetStreamsUsesConnectionWhenNotFollowingEndpointLoca // Fetched over the encrypted connection, so this does not drop TLS. Collections.singletonList(Location.forGrpcInsecure("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()), }; } 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 670b9e3be0..75e95b7d73 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 @@ public class FallbackFlightSqlProducer extends BasicFlightSqlProducer { private final VectorSchemaRoot data; + private 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 List determineEndpoints( T request, FlightDescriptor flightDescriptor, Schema schema) { @@ -119,6 +125,8 @@ private FlightInfo getFlightInfo(FlightDescriptor descriptor, String query) { 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(); } From 9f0845b7e424a7f973127a8fa072d37ae962332c Mon Sep 17 00:00:00 2001 From: Fred Park Date: Wed, 25 Nov 2026 17:27:02 -0700 Subject: [PATCH 3/5] Check what servers receive in followEndpointLocations tests Move the end-to-end tests into ConnectionFollowEndpointLocationsTest, whose servers record the calls they receive. With credentials set, the other server is sent the connection's bearer token by default and receives no calls at all when followEndpointLocations is false. For a server that advertises its own location, the calls come from one client connection instead of two. Also check that a builder copy keeps the setting, and document that hosts are compared without DNS resolution. --- docs/source/flight_sql_jdbc_driver.rst | 3 +- ...ConnectionFollowEndpointLocationsTest.java | 214 ++++++++++++++++++ .../arrow/driver/jdbc/ResultSetTest.java | 84 ------- ...rrowFlightSqlClientHandlerBuilderTest.java | 9 + 4 files changed, 225 insertions(+), 85 deletions(-) create mode 100644 flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ConnectionFollowEndpointLocationsTest.java diff --git a/docs/source/flight_sql_jdbc_driver.rst b/docs/source/flight_sql_jdbc_driver.rst index 686d36d493..f02bb748cd 100644 --- a/docs/source/flight_sql_jdbc_driver.rst +++ b/docs/source/flight_sql_jdbc_driver.rst @@ -180,7 +180,8 @@ case-sensitive. The supported parameters are: false, an endpoint is only fetched over the existing connection, whatever the location's scheme: if it has no locations, the ``arrow-flight-reuse-connection://?`` location, or a location on - **HOSTNAME** and **PORT**. When TLS is enabled, a location on + **HOSTNAME** and **PORT**. 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 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 0000000000..e1608dd368 --- /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 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 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 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 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 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, 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, Metadata> onCall) { + return FlightServer.builder(allocator, Location.forGrpcInsecure("localhost", 0), producer) + .transportHint( + "grpc.builderConsumer", + (Consumer) + builder -> + builder.intercept( + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + final ServerCall call, + final Metadata headers, + final ServerCallHandler 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/ResultSetTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ResultSetTest.java index ecfc41f36e..c5c6a4fbb2 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ResultSetTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ResultSetTest.java @@ -673,90 +673,6 @@ public void testPartitionedFlightServerAllFailure() throws Exception { } } - @Test - public void testPartitionedFlightServerWithoutFollowingEndpointLocations() throws Exception { - final Schema schema = - new Schema( - Collections.singletonList( - Field.nullablePrimitive("int_column", new ArrowType.Int(32, true)))); - try (BufferAllocator allocator = new RootAllocator(Long.MAX_VALUE); - VectorSchemaRoot partition = VectorSchemaRoot.create(schema, allocator)) { - final Ticket ticket = new Ticket("first".getBytes(StandardCharsets.UTF_8)); - final AtomicInteger dataRequests = new AtomicInteger(); - final FlightProducer dataProducer = - new PartitionedFlightSqlProducer.DataOnlyFlightSqlProducer(ticket, partition) { - @Override - public void getStream( - CallContext context, Ticket ticket, ServerStreamListener listener) { - dataRequests.incrementAndGet(); - super.getStream(context, ticket, listener); - } - }; - - try (FlightServer dataServer = - FlightServer.builder(allocator, forGrpcInsecure("localhost", 0), dataProducer) - .build() - .start()) { - final FlightEndpoint endpoint = new FlightEndpoint(ticket, dataServer.getLocation()); - try (final PartitionedFlightSqlProducer rootProducer = - new PartitionedFlightSqlProducer(schema, endpoint); - FlightServer rootServer = - FlightServer.builder(allocator, forGrpcInsecure("localhost", 0), rootProducer) - .build() - .start(); - Connection newConnection = - DriverManager.getConnection( - String.format( - "jdbc:arrow-flight-sql://%s:%d/?useEncryption=false" - + "&followEndpointLocations=false", - rootServer.getLocation().getUri().getHost(), rootServer.getPort())); - Statement newStatement = newConnection.createStatement()) { - final SQLException e = - assertThrows( - SQLException.class, () -> newStatement.executeQuery("Select partitioned_data")); - assertThat(e.getMessage(), containsString("followEndpointLocations")); - assertEquals(0, dataRequests.get()); - } - } - } - } - - @Test - public void testOwnLocationWithoutFollowingEndpointLocations() throws Exception { - final Schema schema = - new Schema( - Collections.singletonList(Field.nullable("int_column", Types.MinorType.INT.getType()))); - try (BufferAllocator allocator = new RootAllocator(Long.MAX_VALUE); - VectorSchemaRoot resultData = VectorSchemaRoot.create(schema, allocator)) { - resultData.setRowCount(1); - ((IntVector) resultData.getVector(0)).set(0, 1); - - try (final FallbackFlightSqlProducer rootProducer = - new FallbackFlightSqlProducer(resultData); - FlightServer rootServer = - FlightServer.builder(allocator, forGrpcInsecure("localhost", 0), rootProducer) - .build() - .start()) { - rootProducer.setLocation(rootServer.getLocation()); - try (Connection newConnection = - DriverManager.getConnection( - String.format( - "jdbc:arrow-flight-sql://%s:%d/?useEncryption=false" - + "&followEndpointLocations=false", - rootServer.getLocation().getUri().getHost(), rootServer.getPort())); - Statement newStatement = newConnection.createStatement(); - ResultSet result = newStatement.executeQuery("own location")) { - List actualData = new ArrayList<>(); - while (result.next()) { - actualData.add(result.getInt(1)); - } - - assertEquals(Collections.singletonList(1), actualData); - } - } - } - } - @Test public void testFallbackFlightServer() throws Exception { final Schema schema = 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 cf10816339..657078404c 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 @@ -168,6 +168,15 @@ public void testHostnameOverrideIsNotCopied() { 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 = From 5432dde16b28864a749a3a419876738c26276dbf Mon Sep 17 00:00:00 2001 From: Fred Park Date: Thu, 26 Nov 2026 12:25:01 -0700 Subject: [PATCH 4/5] Tidy followEndpointLocations docs wording and test producer field Move "whatever its scheme" to the location it applies to, and make the test producer's location volatile, since it is set after the server starts and read on server threads. --- docs/source/flight_sql_jdbc_driver.rst | 22 +++++++++---------- .../jdbc/utils/FallbackFlightSqlProducer.java | 2 +- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/docs/source/flight_sql_jdbc_driver.rst b/docs/source/flight_sql_jdbc_driver.rst index f02bb748cd..d847977904 100644 --- a/docs/source/flight_sql_jdbc_driver.rst +++ b/docs/source/flight_sql_jdbc_driver.rst @@ -177,17 +177,17 @@ case-sensitive. The supported parameters are: - 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, - whatever the location's scheme: if it has no locations, the - ``arrow-flight-reuse-connection://?`` location, or a location on - **HOSTNAME** and **PORT**. 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. + false, an endpoint is only fetched over the existing connection: + if it has no locations, the ``arrow-flight-reuse-connection://?`` + location, or a location on **HOSTNAME** and **PORT**, whatever its + scheme. 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/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 75e95b7d73..09b0a372c1 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,7 +35,7 @@ public class FallbackFlightSqlProducer extends BasicFlightSqlProducer { private final VectorSchemaRoot data; - private Location location; + private volatile Location location; public FallbackFlightSqlProducer(VectorSchemaRoot resultData) { this.data = resultData; From e93d2e70f0e918f5cf4d115834fa55149ac83fc1 Mon Sep 17 00:00:00 2001 From: Fred Park Date: Thu, 26 Nov 2026 13:12:11 -0700 Subject: [PATCH 5/5] Keep the endpoint policy, check the transport, and redact refusals Snapshot followEndpointLocations when the handler is built, so changing the builder afterwards can't re-enable following. Only fetch gRPC locations over the existing connection, and grpc+tls ones only over an encrypted connection, since other schemes need another transport, such as an HTTP GET for https. Show only the scheme, host and port of a refused location, since its other parts can hold credentials, such as a presigned URL's signature. --- docs/source/flight_sql_jdbc_driver.rst | 19 +++---- .../client/ArrowFlightSqlClientHandler.java | 38 +++++++++----- .../ArrowFlightSqlClientHandlerTest.java | 50 +++++++++++++++++++ 3 files changed, 86 insertions(+), 21 deletions(-) diff --git a/docs/source/flight_sql_jdbc_driver.rst b/docs/source/flight_sql_jdbc_driver.rst index d847977904..6fee6ad5b7 100644 --- a/docs/source/flight_sql_jdbc_driver.rst +++ b/docs/source/flight_sql_jdbc_driver.rst @@ -179,15 +179,16 @@ case-sensitive. The supported parameters are: 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 location on **HOSTNAME** and **PORT**, whatever its - scheme. 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. + 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/client/ArrowFlightSqlClientHandler.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java index e9d363dff2..e91dce8e83 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 options = new HashSet<>(); private final Builder builder; + private final boolean followEndpointLocations; private final Optional 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; } @@ -194,21 +196,23 @@ public List getStreams(final FlightInfo flightInfo) Location location = locations.next(); final URI endpointUri = location.getUri(); if (endpointUri.getScheme().equals(LocationSchemes.REUSE_CONNECTION) - || (!builder.followEndpointLocations - && builder.isConnectionLocation(endpointUri))) { + || (!followEndpointLocations && builder.isConnectionLocation(endpointUri))) { stream = new CloseableEndpointStreamPair( sqlClient.getStream(endpoint.getTicket(), getOptions()), null); break; } - if (!builder.followEndpointLocations) { + if (!followEndpointLocations) { exceptions.add( new SQLException( String.format( - "Refusing to connect to endpoint location %s because " - + "followEndpointLocations is false and it is not on the host and " - + "port of the connection to %s.", - endpointUri, builder.getLocation().getUri()))); + "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 = @@ -961,15 +965,24 @@ public Builder withHostnameOverride(@Nullable final String hostnameOverride) { } /** - * Checks whether an endpoint location 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. + * 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; } @@ -1099,8 +1112,9 @@ public Builder withRetainAuth(boolean retainAuth) { * 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 location on this handler's host and - * port or, when encryption is enabled, on the hostname override. Other locations are refused. + * {@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. 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 b6d57612be..86a0a193dc 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 @@ 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,6 +31,7 @@ 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; @@ -126,9 +128,56 @@ private static Object[] testGetStreamsRefusesOtherLocationsWhenNotFollowingEndpo 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://userinfo@other.example.com: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( @@ -158,6 +207,7 @@ private static Object[] testGetStreamsUsesConnectionWhenNotFollowingEndpointLoca 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()),