diff --git a/docs/source/flight_sql_jdbc_driver.rst b/docs/source/flight_sql_jdbc_driver.rst index a685e2a799..6fee6ad5b7 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 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..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; } @@ -193,12 +195,26 @@ 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) + || (!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 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 +825,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; @@ -939,17 +958,50 @@ 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 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 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, 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 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/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/client/ArrowFlightSqlClientHandlerBuilderTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandlerBuilderTest.java index 58e139b58a..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 @@ -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); @@ -167,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 = @@ -258,6 +268,64 @@ 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 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 a885c20be7..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,8 +31,10 @@ 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 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)}, + // 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( + 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(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 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)); } } 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..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,11 +35,17 @@ 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 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(); }