Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
Expand Down Expand Up @@ -175,27 +176,25 @@ public List<CloseableEndpointStreamPair> getStreams(final FlightInfo flightInfo)
} else {
// Clone the builder and then set the new endpoint on it.

// GH-38574: Currently a new FlightClient will be made for each partition that
// returns a
// non-empty Location then disposed of. It may be better to cache clients
// because a server
// may report the same Locations. It would also be good to identify when the
// reported
// location
// is the same as the original connection's Location and skip creating a
// FlightClient in
// that scenario.
// Also copy the cache to the client so we can share a cache. Cache needs to
// cache
// negative attempts too.
// GH-38574: A new FlightClient is made for each partition that returns a non-empty
// Location, then disposed of. The FlightClientCache shared with these clients only
// tracks which locations are reachable, so clients are not reused when a server
// reports the same Locations. When followEndpointLocations is false, a location that
// is this connection's (see Builder#isConnectionLocation) is fetched over it instead,
// but by default it still gets a new FlightClient.
List<Exception> exceptions = new ArrayList<>();
CloseableEndpointStreamPair stream = null;
FlightLocationQueue locations =
new FlightLocationQueue(flightClientCache, endpoint.getLocations());
while (locations.hasNext()) {
Location location = locations.next();
final URI endpointUri = location.getUri();
if (endpointUri.getScheme().equals(LocationSchemes.REUSE_CONNECTION)
final String scheme = schemeOf(endpointUri);
if (scheme == null) {
exceptions.add(new SQLException("Refusing endpoint location without a scheme."));
continue;
}
if (scheme.equals(LocationSchemes.REUSE_CONNECTION)
|| (!followEndpointLocations && builder.isConnectionLocation(endpointUri))) {
stream =
new CloseableEndpointStreamPair(
Expand All @@ -209,14 +208,13 @@ public List<CloseableEndpointStreamPair> getStreams(final FlightInfo flightInfo)
"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(),
scheme,
endpointUri.getHost(),
endpointUri.getPort(),
builder.getLocation().getUri())));
continue;
}
final boolean encryptEndpoint =
endpointUri.getScheme().equals(LocationSchemes.GRPC_TLS);
final boolean encryptEndpoint = scheme.equals(LocationSchemes.GRPC_TLS);
if (builder.useEncryption && !encryptEndpoint) {
exceptions.add(
new SQLException(
Expand Down Expand Up @@ -301,6 +299,15 @@ public List<CloseableEndpointStreamPair> getStreams(final FlightInfo flightInfo)
return endpoints;
}

/**
* Returns the scheme of an endpoint location in lower case, since URI schemes are
* case-insensitive, or null if it has none.
*/
private static @Nullable String schemeOf(final URI endpointUri) {
final String scheme = endpointUri.getScheme();
return scheme == null ? null : scheme.toLowerCase(Locale.ROOT);
}

/**
* Makes an RPC "getInfo" request based on the provided {@code query} object.
*
Expand Down Expand Up @@ -977,7 +984,7 @@ public Builder withHostnameOverride(@Nullable final String hostnameOverride) {
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();
final String scheme = schemeOf(endpointUri);
if (!LocationSchemes.GRPC.equals(scheme)
&& !LocationSchemes.GRPC_INSECURE.equals(scheme)
&& !(useEncryption && LocationSchemes.GRPC_TLS.equals(scheme))) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,10 @@
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.netty.NettyServerBuilder;
import java.io.IOException;
import java.net.SocketAddress;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
Expand All @@ -46,7 +49,9 @@
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.ArrowFlightConnectionConfigImpl.ArrowFlightConnectionProperty;
import org.apache.arrow.driver.jdbc.utils.FallbackFlightSqlProducer;
import org.apache.arrow.driver.jdbc.utils.FlightSqlTestCertificates;
import org.apache.arrow.driver.jdbc.utils.PartitionedFlightSqlProducer;
import org.apache.arrow.flight.FlightEndpoint;
import org.apache.arrow.flight.FlightProducer;
Expand Down Expand Up @@ -78,6 +83,9 @@ public class ConnectionFollowEndpointLocationsTest {
private static final Metadata.Key<String> AUTHORIZATION =
Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER);
private static final Ticket TICKET = new Ticket("data".getBytes(StandardCharsets.UTF_8));
// Issued for localhost, which the servers bind to.
private static final FlightSqlTestCertificates.CertKeyPair CERT_KEY =
FlightSqlTestCertificates.exampleTlsCerts().get(0);

private BufferAllocator allocator;
private VectorSchemaRoot data;
Expand Down Expand Up @@ -166,6 +174,55 @@ public void testOwnLocation(final boolean followEndpointLocations) throws Except
}
}

@Test
public void testPlaintextOwnLocationIsFetchedOverTlsConnection() throws Exception {
final Set<SocketAddress> clients = ConcurrentHashMap.newKeySet();
try (FallbackFlightSqlProducer producer = new FallbackFlightSqlProducer(data);
FlightServer rootServer =
tlsServer(
producer,
(call, headers) ->
clients.add(call.getAttributes().get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR)))) {
// The server only accepts TLS, so fetching this location over plaintext would fail.
producer.setLocation(Location.forGrpcInsecure("localhost", rootServer.getPort()));
try (Connection connection =
DriverManager.getConnection(tlsUrl(rootServer, "&followEndpointLocations=false"));
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("own location")) {
assertTrue(resultSet.next());
assertEquals(1, resultSet.getInt(1));
}
assertEquals(1, clients.size());
}
}

@Test
public void testUpperCaseTlsLocationIsFollowedOverTls() throws Exception {
final List<String> dataServerCalls = Collections.synchronizedList(new ArrayList<>());
try (FlightServer dataServer =
tlsServerBuilder(
new PartitionedFlightSqlProducer.DataOnlyFlightSqlProducer(TICKET, data),
(call, headers) ->
dataServerCalls.add(String.valueOf(headers.get(AUTHORIZATION))))
.build()
.start();
PartitionedFlightSqlProducer producer =
new PartitionedFlightSqlProducer(
data.getSchema(),
new FlightEndpoint(
TICKET,
new Location(URI.create("GRPC+TLS://localhost:" + dataServer.getPort()))));
FlightServer rootServer = tlsServer(producer, (call, headers) -> {});
Connection connection = DriverManager.getConnection(tlsUrl(rootServer, ""));
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT 1")) {
// Schemes are case-insensitive, so this is not refused as an unencrypted location.
assertTrue(resultSet.next());
assertEquals(1, resultSet.getInt(1));
assertFalse(dataServerCalls.isEmpty());
}
}

/** Starts a server that serves {@link #TICKET} and records the authorization of each call. */
private FlightServer dataServer(final List<String> calls) throws Exception {
return serverBuilder(
Expand All @@ -186,9 +243,34 @@ private FlightServer server(
.start();
}

/** Starts a TLS server that requires {@link #USER} and {@link #PASSWORD}. */
private FlightServer tlsServer(
final FlightProducer producer, final BiConsumer<ServerCall<?, ?>, Metadata> onCall)
throws Exception {
return tlsServerBuilder(producer, onCall)
.headerAuthenticator(
new UserPasswordAuthentication.Builder().user(USER, PASSWORD).build().authenticate())
.build()
.start();
}

private FlightServer.Builder tlsServerBuilder(
final FlightProducer producer, final BiConsumer<ServerCall<?, ?>, Metadata> onCall)
throws IOException {
return serverBuilder(Location.forGrpcTls("localhost", 0), producer, onCall)
.useTls(CERT_KEY.cert, CERT_KEY.key);
}

private FlightServer.Builder serverBuilder(
final FlightProducer producer, final BiConsumer<ServerCall<?, ?>, Metadata> onCall) {
return FlightServer.builder(allocator, Location.forGrpcInsecure("localhost", 0), producer)
return serverBuilder(Location.forGrpcInsecure("localhost", 0), producer, onCall);
}

private FlightServer.Builder serverBuilder(
final Location location,
final FlightProducer producer,
final BiConsumer<ServerCall<?, ?>, Metadata> onCall) {
return FlightServer.builder(allocator, location, producer)
.transportHint(
"grpc.builderConsumer",
(Consumer<NettyServerBuilder>)
Expand All @@ -211,4 +293,18 @@ private static String url(final FlightServer server, final String extraParameter
"jdbc:arrow-flight-sql://%s:%d/?useEncryption=false&user=%s&password=%s%s",
server.getLocation().getUri().getHost(), server.getPort(), USER, PASSWORD, extraParameters);
}

private static String tlsUrl(final FlightServer server, final String extraParameters)
throws Exception {
return String.format(
"jdbc:arrow-flight-sql://%s:%d/?useEncryption=true&useSystemTrustStore=false&%s=%s"
+ "&user=%s&password=%s%s",
server.getLocation().getUri().getHost(),
server.getPort(),
ArrowFlightConnectionProperty.TLS_ROOT_CERTS.camelName(),
URLEncoder.encode(CERT_KEY.cert.getPath(), "UTF-8"),
USER,
PASSWORD,
extraParameters);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,21 @@ public void testIsConnectionLocation() {
assertFalse(builder.isConnectionLocation(URI.create("grpc+unix:///tmp/flight.sock")));
}

@Test
public void testIsConnectionLocationIgnoresSchemeCase() {
final ArrowFlightSqlClientHandler.Builder builder =
new ArrowFlightSqlClientHandler.Builder().withHost("localhost").withPort(1234);

assertTrue(builder.isConnectionLocation(URI.create("GRPC+TLS://localhost:1234")));
assertTrue(builder.isConnectionLocation(URI.create("Grpc+Tcp://localhost:1234")));
assertTrue(builder.isConnectionLocation(URI.create("GRPC://localhost:1234")));
assertFalse(builder.isConnectionLocation(URI.create("//localhost:1234")));
assertFalse(
builder
.withEncryption(false)
.isConnectionLocation(URI.create("GRPC+TLS://localhost:1234")));
}

@Test
public void testIsConnectionLocationWithHostnameOverridePort() {
// The override replaces the whole authority, so its own port is used instead.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;

public class ArrowFlightSqlClientHandlerTest {

Expand Down Expand Up @@ -209,11 +210,57 @@ private static Object[] testGetStreamsUsesConnectionWhenNotFollowingEndpointLoca
Collections.singletonList(Location.forGrpcInsecure("localhost", 443)),
Collections.singletonList(new Location(URI.create("grpc://localhost:443"))),
Collections.singletonList(Location.forGrpcTls("flight.example.com", 443)),
// Schemes are case-insensitive.
Collections.singletonList(new Location(URI.create("GRPC+TLS://localhost:443"))),
Collections.singletonList(new Location(URI.create("ARROW-FLIGHT-REUSE-CONNECTION://?"))),
// The other location is skipped instead of failing the query.
Arrays.asList(Location.forGrpcTls("other.example.com", 443), Location.reuseConnection()),
};
}

@ParameterizedTest
@ValueSource(booleans = {true, false})
public void testGetStreamsSkipsLocationWithoutScheme(final boolean followEndpointLocations)
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).withFollowEndpointLocations(followEndpointLocations))) {
final FlightInfo flightInfo =
flightInfoWithLocations(
new Location(URI.create("//localhost:443")), Location.reuseConnection());

final List<CloseableEndpointStreamPair> streams = handler.getStreams(flightInfo);
assertEquals(1, streams.size());
assertSame(stream, streams.get(0).getStream());
AutoCloseables.close(streams);
}
}
}

@ParameterizedTest
@ValueSource(booleans = {true, false})
public void testGetStreamsRefusesLocationWithoutScheme(final boolean followEndpointLocations)
throws Exception {
try (BufferAllocator allocator = new RootAllocator(Long.MAX_VALUE)) {
final FlightSqlClient sqlClient = mock(FlightSqlClient.class);
try (ArrowFlightSqlClientHandler handler =
handler(
sqlClient, builder(allocator).withFollowEndpointLocations(followEndpointLocations))) {
final FlightInfo flightInfo =
flightInfoWithLocations(new Location(URI.create("//localhost:443")));

final SQLException ex =
assertThrows(SQLException.class, () -> handler.getStreams(flightInfo));
assertTrue(ex.getMessage().contains("without a scheme"), ex.getMessage());
verifyNoInteractions(sqlClient);
}
}
}

private static ArrowFlightSqlClientHandler.Builder builder(final BufferAllocator allocator) {
return new ArrowFlightSqlClientHandler.Builder()
.withHost("localhost")
Expand Down
Loading