This is an automated email from the ASF dual-hosted git repository.
jbonofre pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-java.git
The following commit(s) were added to refs/heads/main by this push:
new 613fe8095 GH-1319: [JDBC] Add hostnameOverride connection property for
TLS certificate verification and SNI (#1363)
613fe8095 is described below
commit 613fe8095524ac30eb3452aa02b1bd31554bb1b5
Author: j00n <[email protected]>
AuthorDate: Wed Nov 4 10:26:33 2026 -0700
GH-1319: [JDBC] Add hostnameOverride connection property for TLS
certificate verification and SNI (#1363)
## What's Changed
Adds an optional `hostnameOverride` connection property to the Flight
SQL JDBC driver. When TLS is enabled, the driver verifies the server
certificate against this hostname and sends it for SNI and as the gRPC
`:authority`, instead of using the host in the JDBC URL. This lets the
driver connect with full certificate verification through SSH tunnels,
port-forwarding, private endpoints, or IP addresses that don't match the
server certificate. Today the only option in those cases is
`disableCertificateVerification=true`.
- New property `hostnameOverride` (string, default unset) in
`ArrowFlightConnectionProperty`, passed from `ArrowFlightConnection` to
`ArrowFlightSqlClientHandler.Builder`.
- `Builder.build()` calls `NettyClientBuilder.overrideHostname(...)`
when encryption is on. The property is ignored when
`useEncryption=false`, and a blank value is treated as unset.
- Extra endpoint locations in `getStreams()`: the override is applied
only when the endpoint host and port match the original connection (host
compared case-insensitively, IPv6 brackets ignored). Endpoints at any
other location, or any endpoint when the original connection isn't
encrypted, are verified against their own hostname, as they are today.
This logic is in `Builder.getHostnameOverrideForEndpoint(URI)` so it can
be unit-tested.
- Documented in `docs/source/flight_sql_jdbc_driver.rst` next to
`tlsRootCerts`.
Example:
```
jdbc:arrow-flight-sql://192.0.2.10:443?useEncryption=true&tlsRootCerts=/path/ca.pem&hostnameOverride=flight.example.com
```
## Tests
- New `ConnectionTlsHostnameOverrideTest`. It uses the existing test
certificate, which is issued for `localhost` and has no IP SAN. Its
servers bind to `127.0.0.1` and the tests connect there, so they don't
depend on how `localhost` resolves. Failure cases assert that the cause
is a `CertificateException`, not just any `SQLException`:
- without the property, the connection fails (`No subject alternative
names present`);
- with `hostnameOverride=localhost`, set in the URL or in `Properties`,
it succeeds with full verification;
- a non-matching override fails, which shows verification uses the
override;
- a blank `hostnameOverride=` behaves as unset;
- the property is ignored for unencrypted connections;
- a partitioned query whose endpoint is at the connection's host and
port succeeds, which shows the override reaches endpoint clients;
- a partitioned query whose endpoint is on the connection's IP but a
different port fails, which shows the override is not applied there.
- `ArrowFlightSqlClientHandlerBuilderTest`: the default is unset and the
builder copy keeps the value. The endpoint rule is covered for same host
and port, different port, no port, different case, IPv6 with and without
brackets, different host, unencrypted connection, blank value, and no
override set.
- `ArrowFlightConnectionConfigImplTest`: the property is parsed.
This change is additive and has no breaking changes.
Closes #1319.
---------
Co-authored-by: Fred Park <[email protected]>
---
docs/source/flight_sql_jdbc_driver.rst | 11 +
.../arrow/driver/jdbc/ArrowFlightConnection.java | 1 +
.../jdbc/client/ArrowFlightSqlClientHandler.java | 56 ++++
.../utils/ArrowFlightConnectionConfigImpl.java | 10 +
.../jdbc/ConnectionTlsHostnameOverrideTest.java | 336 +++++++++++++++++++++
.../ArrowFlightSqlClientHandlerBuilderTest.java | 128 ++++++++
.../utils/ArrowFlightConnectionConfigImplTest.java | 7 +
7 files changed, 549 insertions(+)
diff --git a/docs/source/flight_sql_jdbc_driver.rst
b/docs/source/flight_sql_jdbc_driver.rst
index 6d40434a2..0c6be0a2d 100644
--- a/docs/source/flight_sql_jdbc_driver.rst
+++ b/docs/source/flight_sql_jdbc_driver.rst
@@ -118,6 +118,17 @@ case-sensitive. The supported parameters are:
- Path to PEM-encoded root certificates for TLS - use this as
an alternative to ``trustStore``
+ * - hostnameOverride
+ - null
+ - When TLS is enabled, the hostname to verify the server certificate
+ against and to send for SNI and as the gRPC ``:authority`` header,
+ instead of **HOSTNAME**. Use this when
+ connecting through a tunnel, a private endpoint, or an IP address
+ that does not match the server certificate. Endpoints returned by
+ the server are only verified against this hostname if they are on
+ the same host and port as the connection. Ignored when
+ ``useEncryption`` is false.
+
* - clientCertificate
- null
- Path to PEM-encoded client mTLS certificate when the Flight
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 623c2b81b..a5c453176 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
@@ -119,6 +119,7 @@ public final class ArrowFlightConnection extends
AvaticaConnection {
.withBufferAllocator(allocator)
.withEncryption(config.useEncryption())
.withDisableCertificateVerification(config.getDisableCertificateVerification())
+ .withHostnameOverride(config.getHostnameOverride())
.withToken(config.getToken())
.withCallOptions(config.toCallOption())
.withRetainCookies(config.retainCookies())
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 719cc38a2..346b0c032 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
@@ -188,6 +188,7 @@ public final class ArrowFlightSqlClientHandler implements
AutoCloseable {
.withHost(endpointUri.getHost())
.withPort(endpointUri.getPort())
.withEncryption(endpointUri.getScheme().equals(LocationSchemes.GRPC_TLS))
+
.withHostnameOverride(builder.getHostnameOverrideForEndpoint(endpointUri))
.withClientCache(flightClientCache)
.withConnectTimeout(builder.connectTimeout);
@@ -677,6 +678,8 @@ public final class ArrowFlightSqlClientHandler implements
AutoCloseable {
@VisibleForTesting boolean disableCertificateVerification;
+ @VisibleForTesting @Nullable String hostnameOverride;
+
@VisibleForTesting boolean useSystemTrustStore = true;
@VisibleForTesting String tlsRootCertificatesPath;
@@ -732,6 +735,7 @@ public final class ArrowFlightSqlClientHandler implements
AutoCloseable {
this.token = original.token;
this.useEncryption = original.useEncryption;
this.disableCertificateVerification =
original.disableCertificateVerification;
+ this.hostnameOverride = original.hostnameOverride;
this.useSystemTrustStore = original.useSystemTrustStore;
this.tlsRootCertificatesPath = original.tlsRootCertificatesPath;
this.clientCertificatePath = original.clientCertificatePath;
@@ -840,6 +844,54 @@ public final class ArrowFlightSqlClientHandler implements
AutoCloseable {
return this;
}
+ /**
+ * Sets the hostname to use for TLS certificate verification and SNI
instead of the host this
+ * handler connects to. It is also sent as the gRPC authority ({@code
:authority} header).
+ * Ignored when encryption is disabled.
+ *
+ * @param hostnameOverride the hostname to verify the server certificate
against, or null or
+ * blank to use the host.
+ * @return this instance.
+ */
+ public Builder withHostnameOverride(@Nullable final String
hostnameOverride) {
+ final String trimmed = hostnameOverride == null ? null :
hostnameOverride.trim();
+ this.hostnameOverride = trimmed == null || trimmed.isEmpty() ? null :
trimmed;
+ return this;
+ }
+
+ /**
+ * Gets the hostname override to use when connecting to an endpoint
location. The override is
+ * only valid for the host and port it was configured for, so endpoints at
any other location
+ * are verified against their own hostname. Like the override itself, it
is ignored when the
+ * original connection does not use encryption.
+ *
+ * @param endpointUri the endpoint location.
+ * @return the hostname override if the endpoint is on the original host
and port, otherwise
+ * null.
+ */
+ @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))) {
+ return null;
+ }
+ return hostnameOverride;
+ }
+
+ /**
+ * Strips the brackets from an IPv6 literal. {@link URI#getHost()} keeps
them, but a host set
+ * through properties may not have them.
+ */
+ private static @Nullable String stripBrackets(@Nullable final String host)
{
+ return host != null && host.startsWith("[") && host.endsWith("]")
+ ? host.substring(1, host.length() - 1)
+ : host;
+ }
+
/**
* Sets whether to use the certificates from the operating system.
*
@@ -1070,6 +1122,10 @@ public final class ArrowFlightSqlClientHandler
implements AutoCloseable {
clientBuilder.location(location);
if (useEncryption) {
+ if (hostnameOverride != null) {
+ clientBuilder.overrideHostname(hostnameOverride);
+ }
+
if (disableCertificateVerification) {
clientBuilder.verifyServer(false);
} else {
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 812f189bc..929d6241f 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
@@ -112,6 +112,15 @@ public final class ArrowFlightConnectionConfigImpl extends
ConnectionConfigImpl
return ArrowFlightConnectionProperty.TLS_ROOT_CERTS.getString(properties);
}
+ /**
+ * Gets the hostname to use for TLS certificate verification and SNI instead
of the host.
+ *
+ * @return the hostname override, or null if not set.
+ */
+ public String getHostnameOverride() {
+ return
ArrowFlightConnectionProperty.HOSTNAME_OVERRIDE.getString(properties);
+ }
+
public String getClientCertificatePath() {
return
ArrowFlightConnectionProperty.CLIENT_CERTIFICATE.getString(properties);
}
@@ -258,6 +267,7 @@ public final class ArrowFlightConnectionConfigImpl extends
ConnectionConfigImpl
TRUST_STORE_PASSWORD("trustStorePassword", null, Type.STRING, false),
USE_SYSTEM_TRUST_STORE("useSystemTrustStore", true, Type.BOOLEAN, false),
TLS_ROOT_CERTS("tlsRootCerts", null, Type.STRING, false),
+ HOSTNAME_OVERRIDE("hostnameOverride", null, Type.STRING, false),
CLIENT_CERTIFICATE("clientCertificate", null, Type.STRING, false),
CLIENT_KEY("clientKey", null, Type.STRING, false),
THREAD_POOL_SIZE("threadPoolSize", 1, Type.NUMBER, false),
diff --git
a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ConnectionTlsHostnameOverrideTest.java
b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ConnectionTlsHostnameOverrideTest.java
new file mode 100644
index 000000000..67bfcd186
--- /dev/null
+++
b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ConnectionTlsHostnameOverrideTest.java
@@ -0,0 +1,336 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.arrow.driver.jdbc;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.security.cert.CertificateException;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayDeque;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Deque;
+import java.util.Properties;
+import org.apache.arrow.driver.jdbc.authentication.UserPasswordAuthentication;
+import
org.apache.arrow.driver.jdbc.utils.ArrowFlightConnectionConfigImpl.ArrowFlightConnectionProperty;
+import org.apache.arrow.driver.jdbc.utils.FlightSqlTestCertificates;
+import org.apache.arrow.driver.jdbc.utils.MockFlightSqlProducer;
+import org.apache.arrow.driver.jdbc.utils.PartitionedFlightSqlProducer;
+import org.apache.arrow.flight.FlightDescriptor;
+import org.apache.arrow.flight.FlightEndpoint;
+import org.apache.arrow.flight.FlightInfo;
+import org.apache.arrow.flight.FlightServer;
+import org.apache.arrow.flight.Location;
+import org.apache.arrow.flight.Ticket;
+import org.apache.arrow.flight.sql.impl.FlightSql;
+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.pojo.ArrowType;
+import org.apache.arrow.vector.types.pojo.Field;
+import org.apache.arrow.vector.types.pojo.Schema;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Tests the hostnameOverride connection property. The test certificate is
issued for {@code
+ * localhost} and has no IP address in its subject alternative names, so
connecting by IP address
+ * only passes verification when the hostname override is used. Servers bind
to the IP address
+ * explicitly so the tests don't depend on how {@code localhost} resolves.
+ */
+public class ConnectionTlsHostnameOverrideTest {
+
+ private static final String IP_ADDRESS = "127.0.0.1";
+ private static final String CERTIFICATE_HOSTNAME = "localhost";
+ // Connecting with credentials performs a handshake, so the TLS connection
is made eagerly.
+ private static final String USER = "user1";
+ private static final String PASSWORD = "pass1";
+
+ private static final FlightSqlTestCertificates.CertKeyPair certKey =
+ FlightSqlTestCertificates.exampleTlsCerts().get(0);
+ private static final String tlsRootCertsPath = certKey.cert.getPath();
+
+ private static BufferAllocator allocator;
+ private static FlightServer tlsServer;
+
+ @BeforeAll
+ public static void setUp() throws Exception {
+ DriverManager.registerDriver(new ArrowFlightJdbcDriver());
+ allocator = new RootAllocator(Long.MAX_VALUE);
+ tlsServer =
+ FlightServer.builder(
+ allocator, Location.forGrpcTls(IP_ADDRESS, 0), new
MockFlightSqlProducer())
+ .headerAuthenticator(
+ new UserPasswordAuthentication.Builder()
+ .user(USER, PASSWORD)
+ .build()
+ .authenticate())
+ .useTls(certKey.cert, certKey.key)
+ .build()
+ .start();
+ }
+
+ @AfterAll
+ public static void tearDown() throws Exception {
+ tlsServer.close();
+ allocator.close();
+ }
+
+ private static String tlsUrl(final String host, final int port) throws
Exception {
+ return String.format(
+
"jdbc:arrow-flight-sql://%s:%d?useEncryption=true&useSystemTrustStore=false&%s=%s",
+ host,
+ port,
+ ArrowFlightConnectionProperty.TLS_ROOT_CERTS.camelName(),
+ URLEncoder.encode(tlsRootCertsPath, "UTF-8"));
+ }
+
+ private static String serverUrl(final String host) throws Exception {
+ return tlsUrl(host, tlsServer.getPort())
+ + String.format("&user=%s&password=%s", USER, PASSWORD);
+ }
+
+ /** Asserts that connecting fails because the server certificate was
rejected. */
+ private static void assertCertificateRejected(final String url) {
+ final SQLException exception =
+ assertThrows(
+ SQLException.class,
+ () -> {
+ try (Connection connection = DriverManager.getConnection(url)) {
+ connection.isValid(0);
+ }
+ });
+ assertCausedByCertificateException(exception);
+ }
+
+ /** Asserts that the server certificate being rejected caused {@code
exception}. */
+ private static void assertCausedByCertificateException(final Throwable
exception) {
+ final Deque<Throwable> pending = new ArrayDeque<>();
+ pending.add(exception);
+ while (!pending.isEmpty()) {
+ final Throwable throwable = pending.pop();
+ if (throwable instanceof CertificateException) {
+ return;
+ }
+ if (throwable.getCause() != null) {
+ pending.add(throwable.getCause());
+ }
+ pending.addAll(Arrays.asList(throwable.getSuppressed()));
+ }
+ fail("Expected the server certificate to be rejected", exception);
+ }
+
+ @Test
+ public void testConnectionByIpAddressFailsWithoutHostnameOverride() throws
Exception {
+ assertCertificateRejected(serverUrl(IP_ADDRESS));
+ }
+
+ @Test
+ public void testConnectionByIpAddressSucceedsWithHostnameOverrideInUrl()
throws Exception {
+ try (Connection connection =
+ DriverManager.getConnection(
+ serverUrl(IP_ADDRESS) + "&hostnameOverride=" +
CERTIFICATE_HOSTNAME)) {
+ assertTrue(connection.isValid(0));
+ }
+ }
+
+ @Test
+ public void
testConnectionByIpAddressSucceedsWithHostnameOverrideInProperties() throws
Exception {
+ final Properties properties = new Properties();
+ properties.setProperty(
+ ArrowFlightConnectionProperty.HOSTNAME_OVERRIDE.camelName(),
CERTIFICATE_HOSTNAME);
+
+ try (Connection connection =
DriverManager.getConnection(serverUrl(IP_ADDRESS), properties)) {
+ assertTrue(connection.isValid(0));
+ }
+ }
+
+ @Test
+ public void testServerCertificateIsVerifiedAgainstHostnameOverride() throws
Exception {
+ // Same connection as the passing override tests, but the override doesn't
match the
+ // certificate, so verification must use the override's value.
+ assertCertificateRejected(serverUrl(IP_ADDRESS) +
"&hostnameOverride=other.example.com");
+ }
+
+ @Test
+ public void testBlankHostnameOverrideIsIgnored() throws Exception {
+ // A blank value behaves as if the property were unset rather than being
sent to gRPC.
+ assertCertificateRejected(serverUrl(IP_ADDRESS) + "&hostnameOverride=");
+ }
+
+ @Test
+ public void testHostnameOverrideIsIgnoredWithoutEncryption() throws
Exception {
+ try (FlightServer server =
+ FlightServer.builder(
+ allocator, Location.forGrpcInsecure(IP_ADDRESS, 0), new
MockFlightSqlProducer())
+ .build()
+ .start();
+ Connection connection =
+ DriverManager.getConnection(
+ String.format(
+
"jdbc:arrow-flight-sql://%s:%d?useEncryption=false&hostnameOverride=%s",
+ IP_ADDRESS, server.getPort(), "other.example.com"))) {
+ assertTrue(connection.isValid(0));
+ }
+ }
+
+ @Test
+ public void testHostnameOverrideIsAppliedToEndpointOnConnectionLocation()
throws Exception {
+ final Schema schema =
+ new Schema(
+ Arrays.asList(Field.nullablePrimitive("int_column", new
ArrowType.Int(32, true))));
+ final Ticket ticket = new
Ticket("partition".getBytes(StandardCharsets.UTF_8));
+
+ try (VectorSchemaRoot partition = VectorSchemaRoot.create(schema,
allocator)) {
+ partition.setRowCount(1);
+ ((IntVector) partition.getVector(0)).set(0, 42);
+
+ try (SelfServingFlightSqlProducer producer =
+ new SelfServingFlightSqlProducer(schema, ticket, partition);
+ FlightServer server =
+ FlightServer.builder(allocator, Location.forGrpcTls(IP_ADDRESS,
0), producer)
+ .useTls(certKey.cert, certKey.key)
+ .build()
+ .start()) {
+ // The endpoint is at the same location as the connection, so it must
be verified against
+ // the hostname override as well.
+ producer.location = Location.forGrpcTls(IP_ADDRESS, server.getPort());
+
+ try (Connection connection =
+ DriverManager.getConnection(
+ tlsUrl(IP_ADDRESS, server.getPort())
+ + "&hostnameOverride="
+ + CERTIFICATE_HOSTNAME);
+ Statement statement = connection.createStatement();
+ ResultSet resultSet = statement.executeQuery("SELECT
partitioned_data")) {
+ assertTrue(resultSet.next());
+ assertEquals(42, resultSet.getInt(1));
+ assertFalse(resultSet.next());
+ }
+ }
+ }
+ }
+
+ @Test
+ public void testHostnameOverrideIsNotAppliedToEndpointOnDifferentPort()
throws Exception {
+ final Schema schema =
+ new Schema(
+ Arrays.asList(Field.nullablePrimitive("int_column", new
ArrowType.Int(32, true))));
+ final Ticket ticket = new
Ticket("partition".getBytes(StandardCharsets.UTF_8));
+
+ try (VectorSchemaRoot partition = VectorSchemaRoot.create(schema,
allocator);
+ FlightServer dataServer =
+ FlightServer.builder(
+ allocator,
+ Location.forGrpcTls(IP_ADDRESS, 0),
+ new
PartitionedFlightSqlProducer.DataOnlyFlightSqlProducer(ticket, partition))
+ .useTls(certKey.cert, certKey.key)
+ .build()
+ .start()) {
+ partition.setRowCount(1);
+ ((IntVector) partition.getVector(0)).set(0, 42);
+
+ // The endpoint is on the connection's IP address but another port, so
it is verified
+ // against the IP address, which the certificate does not cover.
+ final FlightEndpoint endpoint =
+ new FlightEndpoint(ticket, Location.forGrpcTls(IP_ADDRESS,
dataServer.getPort()));
+
+ try (PartitionedFlightSqlProducer rootProducer =
+ new PartitionedFlightSqlProducer(schema, endpoint);
+ FlightServer rootServer =
+ FlightServer.builder(allocator, Location.forGrpcTls(IP_ADDRESS,
0), rootProducer)
+ .useTls(certKey.cert, certKey.key)
+ .build()
+ .start();
+ Connection connection =
+ DriverManager.getConnection(
+ tlsUrl(IP_ADDRESS, rootServer.getPort())
+ + "&hostnameOverride="
+ + CERTIFICATE_HOSTNAME);
+ Statement statement = connection.createStatement()) {
+ final SQLException exception =
+ assertThrows(
+ SQLException.class,
+ () -> {
+ try (ResultSet resultSet = statement.executeQuery("SELECT
partitioned_data")) {
+ resultSet.next();
+ }
+ });
+ assertCausedByCertificateException(exception);
+ }
+ }
+ }
+
+ /**
+ * Returns a single endpoint at {@link #location}, which is set once the
server has started, and
+ * serves its data, so the endpoint is at the same location as the
connection.
+ */
+ private static final class SelfServingFlightSqlProducer extends
PartitionedFlightSqlProducer {
+ private final Schema schema;
+ private final Ticket ticket;
+ private final PartitionedFlightSqlProducer.DataOnlyFlightSqlProducer
dataProducer;
+ private volatile Location location;
+
+ SelfServingFlightSqlProducer(
+ final Schema schema, final Ticket ticket, final VectorSchemaRoot data)
{
+ super(schema);
+ this.schema = schema;
+ this.ticket = ticket;
+ this.dataProducer = new
PartitionedFlightSqlProducer.DataOnlyFlightSqlProducer(ticket, data);
+ }
+
+ private FlightInfo flightInfo(final FlightDescriptor descriptor) {
+ return FlightInfo.builder(
+ schema, descriptor, Collections.singletonList(new
FlightEndpoint(ticket, location)))
+ .build();
+ }
+
+ @Override
+ public FlightInfo getFlightInfoStatement(
+ final FlightSql.CommandStatementQuery command,
+ final CallContext context,
+ final FlightDescriptor descriptor) {
+ return flightInfo(descriptor);
+ }
+
+ @Override
+ public FlightInfo getFlightInfoPreparedStatement(
+ final FlightSql.CommandPreparedStatementQuery command,
+ final CallContext context,
+ final FlightDescriptor descriptor) {
+ return flightInfo(descriptor);
+ }
+
+ @Override
+ public void getStream(
+ final CallContext context, final Ticket ticket, final
ServerStreamListener listener) {
+ dataProducer.getStream(context, ticket, listener);
+ }
+ }
+}
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 a60a71f23..9de00009a 100644
---
a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandlerBuilderTest.java
+++
b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandlerBuilderTest.java
@@ -23,6 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import java.net.URI;
import java.util.Optional;
import org.apache.arrow.driver.jdbc.FlightServerTestExtension;
import org.apache.arrow.driver.jdbc.utils.CoreMockedSqlProducers;
@@ -137,6 +138,7 @@ public class ArrowFlightSqlClientHandlerBuilderTest {
assertNull(builder.password);
assertTrue(builder.useEncryption);
assertFalse(builder.disableCertificateVerification);
+ assertNull(builder.hostnameOverride);
assertNull(builder.trustStorePath);
assertNull(builder.trustStorePassword);
assertTrue(builder.useSystemTrustStore);
@@ -152,6 +154,132 @@ public class ArrowFlightSqlClientHandlerBuilderTest {
assertNull(builder.driverVersion);
}
+ @Test
+ public void testHostnameOverrideIsCopied() {
+ final ArrowFlightSqlClientHandler.Builder rootBuilder =
+ new
ArrowFlightSqlClientHandler.Builder().withHostnameOverride("flight.example.com");
+
+ final ArrowFlightSqlClientHandler.Builder copiedBuilder =
+ new ArrowFlightSqlClientHandler.Builder(rootBuilder);
+
+ assertEquals("flight.example.com", copiedBuilder.hostnameOverride);
+ }
+
+ @Test
+ public void testHostnameOverrideForEndpointOnSameHost() {
+ final ArrowFlightSqlClientHandler.Builder builder =
+ new ArrowFlightSqlClientHandler.Builder()
+ .withHost("127.0.0.1")
+ .withPort(1234)
+ .withHostnameOverride("flight.example.com");
+
+ assertEquals(
+ "flight.example.com",
+
builder.getHostnameOverrideForEndpoint(URI.create("grpc+tls://127.0.0.1:1234")));
+ }
+
+ @Test
+ public void testHostnameOverrideForEndpointOnDifferentPortIsCleared() {
+ final ArrowFlightSqlClientHandler.Builder builder =
+ new ArrowFlightSqlClientHandler.Builder()
+ .withHost("127.0.0.1")
+ .withPort(1234)
+ .withHostnameOverride("flight.example.com");
+
+
assertNull(builder.getHostnameOverrideForEndpoint(URI.create("grpc+tls://127.0.0.1:5678")));
+
assertNull(builder.getHostnameOverrideForEndpoint(URI.create("grpc+tls://127.0.0.1")));
+ }
+
+ @Test
+ public void testHostnameOverrideForEndpointMatchesHostCaseInsensitively() {
+ final ArrowFlightSqlClientHandler.Builder builder =
+ new ArrowFlightSqlClientHandler.Builder()
+ .withHost("Tunnel.Local")
+ .withPort(1234)
+ .withHostnameOverride("flight.example.com");
+
+ assertEquals(
+ "flight.example.com",
+
builder.getHostnameOverrideForEndpoint(URI.create("grpc+tls://tunnel.local:1234")));
+ }
+
+ @Test
+ public void testHostnameOverrideForEndpointOnIpv6Host() {
+ // The JDBC URL is parsed with URI#getHost, which keeps the brackets, like
endpoint locations.
+ final ArrowFlightSqlClientHandler.Builder builder =
+ new ArrowFlightSqlClientHandler.Builder()
+ .withHost(URI.create("jdbc://[::1]:1234").getHost())
+ .withPort(1234)
+ .withHostnameOverride("flight.example.com");
+
+ assertEquals(
+ "flight.example.com",
+
builder.getHostnameOverrideForEndpoint(URI.create("grpc+tls://[::1]:1234")));
+ }
+
+ @Test
+ public void testHostnameOverrideForEndpointOnIpv6HostWithoutBrackets() {
+ // A host set through properties or a DataSource may not have brackets.
+ final ArrowFlightSqlClientHandler.Builder builder =
+ new ArrowFlightSqlClientHandler.Builder()
+ .withHost("::1")
+ .withPort(1234)
+ .withHostnameOverride("flight.example.com");
+
+ assertEquals(
+ "flight.example.com",
+
builder.getHostnameOverrideForEndpoint(URI.create("grpc+tls://[::1]:1234")));
+ }
+
+ @Test
+ public void testHostnameOverrideForEndpointOnDifferentHostIsCleared() {
+ final ArrowFlightSqlClientHandler.Builder builder =
+ new ArrowFlightSqlClientHandler.Builder()
+ .withHost("127.0.0.1")
+ .withPort(1234)
+ .withHostnameOverride("flight.example.com");
+
+
assertNull(builder.getHostnameOverrideForEndpoint(URI.create("grpc+tls://10.0.0.1:1234")));
+ assertNull(
+
builder.getHostnameOverrideForEndpoint(URI.create("grpc+tls://other.example.com:1234")));
+ }
+
+ @Test
+ public void testHostnameOverrideForEndpointWithoutEncryption() {
+ final ArrowFlightSqlClientHandler.Builder builder =
+ new ArrowFlightSqlClientHandler.Builder()
+ .withHost("127.0.0.1")
+ .withPort(1234)
+ .withEncryption(false)
+ .withHostnameOverride("flight.example.com");
+
+
assertNull(builder.getHostnameOverrideForEndpoint(URI.create("grpc+tls://127.0.0.1:1234")));
+ }
+
+ @Test
+ public void testBlankHostnameOverrideIsUnset() {
+ assertNull(new
ArrowFlightSqlClientHandler.Builder().withHostnameOverride("").hostnameOverride);
+ assertNull(
+ new ArrowFlightSqlClientHandler.Builder().withHostnameOverride("
").hostnameOverride);
+ }
+
+ @Test
+ public void testHostnameOverrideIsTrimmed() {
+ assertEquals(
+ "flight.example.com",
+ new ArrowFlightSqlClientHandler.Builder()
+ .withHostnameOverride(" flight.example.com ")
+ .hostnameOverride);
+ }
+
+ @Test
+ public void testHostnameOverrideForEndpointWithoutOverride() {
+ final ArrowFlightSqlClientHandler.Builder builder =
+ new
ArrowFlightSqlClientHandler.Builder().withHost("127.0.0.1").withPort(1234);
+
+
assertNull(builder.getHostnameOverrideForEndpoint(URI.create("grpc+tls://127.0.0.1:1234")));
+ }
+
@Test
public void testCatalog() {
ArrowFlightSqlClientHandler.Builder rootBuilder = new
ArrowFlightSqlClientHandler.Builder();
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 ef7126d1c..13b98b3d2 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
@@ -20,6 +20,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.HOST;
+import static
org.apache.arrow.driver.jdbc.utils.ArrowFlightConnectionConfigImpl.ArrowFlightConnectionProperty.HOSTNAME_OVERRIDE;
import static
org.apache.arrow.driver.jdbc.utils.ArrowFlightConnectionConfigImpl.ArrowFlightConnectionProperty.PASSWORD;
import static
org.apache.arrow.driver.jdbc.utils.ArrowFlightConnectionConfigImpl.ArrowFlightConnectionProperty.PORT;
import static
org.apache.arrow.driver.jdbc.utils.ArrowFlightConnectionConfigImpl.ArrowFlightConnectionProperty.THREAD_POOL_SIZE;
@@ -123,6 +124,12 @@ public final class ArrowFlightConnectionConfigImplTest {
useEncryption,
(Function<ArrowFlightConnectionConfigImpl, ?>)
ArrowFlightConnectionConfigImpl::useEncryption),
+ Arguments.of(
+ HOSTNAME_OVERRIDE,
+ "flight.example.com",
+ "flight.example.com",
+ (Function<ArrowFlightConnectionConfigImpl, ?>)
+ ArrowFlightConnectionConfigImpl::getHostnameOverride),
Arguments.of(
THREAD_POOL_SIZE,
threadPoolSize,