diff --git a/.circleci/config.yml b/.circleci/config.yml index 081290d1..05079500 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -88,10 +88,27 @@ jobs: --export-url-as TESTING_INFLUXDB_URL \ --export-db-as TESTING_INFLUXDB_DATABASE \ --export-token-as TESTING_INFLUXDB_TOKEN + - run: + name: Generate self-signed certificates + command: bash ./scripts/generate-self-signed-cert.sh - run: name: "Running tests" command: | mvn -B -U clean install -DargLine="@{argLine} << parameters.arg-line >>" + - run: + name: Remove self-signed certificates + command: | + rm -f test/java/com/influxdb/v3/client/testdata/certificates/influxdb.crt \ + test/java/com/influxdb/v3/client/testdata/certificates/influxdb.key \ + test/java/com/influxdb/v3/client/testdata/certificates/influxdb.pem \ + test/java/com/influxdb/v3/client/testdata/certificates/other-server.crt \ + test/java/com/influxdb/v3/client/testdata/certificates/other-server.key \ + test/java/com/influxdb/v3/client/testdata/certificates/other-server.pem \ + test/java/com/influxdb/v3/client/testdata/certificates/client.crt \ + test/java/com/influxdb/v3/client/testdata/certificates/client.key \ + test/java/com/influxdb/v3/client/testdata/certificates/client.pem \ + test/java/com/influxdb/v3/client/testdata/certificates/client-encrypted.key + when: always - save_cache: name: Saving Maven Cache key: *cache-key diff --git a/CHANGELOG.md b/CHANGELOG.md index 1475318f..3b9864fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ ## 1.12.0 [unreleased] +### Features + +1. [#470](https://github.com/InfluxCommunity/influxdb3-java/pull/470): + - Add support for mTLS. + - Support separated .crt and .key files or bundled certificate and key in one .p12 file. + ### CI 1. [#446](https://github.com/InfluxCommunity/influxdb3-java/pull/446): Sets up automated releasing to Maven Central diff --git a/examples/src/main/java/com/influxdb/v3/TlsConfigExample.java b/examples/src/main/java/com/influxdb/v3/TlsConfigExample.java new file mode 100644 index 00000000..e35ecb94 --- /dev/null +++ b/examples/src/main/java/com/influxdb/v3/TlsConfigExample.java @@ -0,0 +1,111 @@ +/* + * The MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.influxdb.v3; + +import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; + +import com.influxdb.v3.client.InfluxDBClient; +import com.influxdb.v3.client.PointValues; +import com.influxdb.v3.client.config.ClientConfig; + +public final class TlsConfigExample { + + public static String resolveProperty(final String property, final String fallback) { + return System.getProperty(property, System.getenv(property)) == null + ? fallback : System.getProperty(property, System.getenv(property)); + } + + private TlsConfigExample() { } + + public static void main(final String[] args) { + String host = resolveProperty("INFLUX_HOST", "https://localhost:8181"); + String token = resolveProperty("INFLUX_TOKEN", "my-token"); + String database = resolveProperty("INFLUX_DATABASE", "my-database"); + + String measurement = "tls_example"; + + // ClientConfig config = configTls(host, token, database); + + // ClientConfig config = configMutualTls(host, token, database); + + try (InfluxDBClient client = InfluxDBClient.getInstance(config)) { + client.writeRecord(String.format("%s,id=0001 temp=30.14,ticks=42i", measurement)); + + TimeUnit.SECONDS.sleep(1); + String sql = String.format("SELECT * FROM %s ORDER BY time DESC", measurement); + try (Stream values = client.queryPoints(sql)) { + values.forEach(pv -> { + String sv = measurement + "," + + " id: " + pv.getTag("id") + "," + + " fVal: " + pv.getFloatField("temp") + "," + + " iVal: " + pv.getIntegerField("ticks") + "," + + " " + pv.getTimestamp(); + System.out.println(sv); + }); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public ClientConfig configTls( + @Nonnull final String host, + @Nonnull final String token, + @Nonnull final String database) { + ClientConfig.Builder configBuilder = new ClientConfig.Builder() + .host(host) + .token(token.toCharArray()) + .database(database) + .sslRootsFilePath("path/to/server.crt"); + + // Optional, set this if client certificate is password protected. + configBuilder.sslRootFilePassword("password".toCharArray()); + return configBuilder.build(); + } + + public ClientConfig configMutualTls( + @Nonnull final String host, + @Nonnull final String token, + @Nonnull final String database) { + ClientConfig.Builder configBuilder = new ClientConfig.Builder() + .host(host) + .token(token.toCharArray()) + .database(database) + .sslRootsFilePath("path/to/server.crt"); + + // Optional, set this if server certificate is password-protected. + configBuilder.sslRootFilePassword("password".toCharArray()); + + // Config client certificate send to the server by using a bundled certificate and key in one .p12 file + // or separated .crt and .key files format, but NOT both. + + // Using separated .crt and .key files format. + configBuilder.certificateFilePath("path/to/client.crt", "path/to/client.key"); + + // Using .p12 file format. + // configBuilder.certificateP12FilePath("path/to/client.p12", "password".toCharArray()); + + + return configBuilder.build(); + } +} diff --git a/pom.xml b/pom.xml index aa754db3..8bf71d6f 100644 --- a/pom.xml +++ b/pom.xml @@ -461,7 +461,7 @@ **/target/**, **/*.jar, **/.git/**, **/.*, **/*.png, **/*.iml, **/*.bolt, .idea/**, **/*nightly*/**, **/.m2/**, LICENSE, **/*.md, **/.github/**, license_header.txt, release.properties/, **/pom.xml.releaseBackup, **/pom.xml.tag, **/semantic.yml, - .circleci/config.yml, **/*.pem + .circleci/config.yml, **/*.pem, **/*.p12, **/*.crt, **/*.key diff --git a/scripts/generate-self-signed-cert.sh b/scripts/generate-self-signed-cert.sh new file mode 100644 index 00000000..922e2de4 --- /dev/null +++ b/scripts/generate-self-signed-cert.sh @@ -0,0 +1,59 @@ +#!/bin/bash +# +# The MIT License +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# + +set -euo pipefail + +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +CERTS_DIR="${CERTS_DIR:-${SCRIPT_DIR}/../src/test/java/com/influxdb/v3/client/testdata/certificates}" +mkdir -p "$CERTS_DIR" +CERTS_DIR="$(cd -- "$CERTS_DIR" && pwd)" +cd "$CERTS_DIR" + +PKCS12_PASSWORD="changeit" +INFLUXDB_SERVER_NAME="influxdb" +OTHER_SERVER_NAME="other-server" + +# Gen Server .crt and .key with SAN (Subject Alternative Names) then convert to .p12 file +for SERVER_NAME in "$INFLUXDB_SERVER_NAME" "$OTHER_SERVER_NAME"; do + echo "### Generate server key and certificate for $SERVER_NAME..." + openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 | openssl pkcs8 -topk8 -nocrypt -out "${SERVER_NAME}.key" + + openssl req -new -x509 -key "${SERVER_NAME}.key" -out "${SERVER_NAME}.crt" -days 3650 \ + -subj "/CN=localhost/O=Development/C=US" \ + -addext "subjectAltName = DNS:localhost,IP:127.0.0.1" + + openssl pkcs12 -export -in "${SERVER_NAME}.crt" -inkey "${SERVER_NAME}.key" \ + -out "${SERVER_NAME}.p12" -name "myalias" -password "pass:$PKCS12_PASSWORD" +done + +# Gen Client .crt and .key then convert to .p12 file +echo "### Generate client key..." +openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 | openssl pkcs8 -topk8 -nocrypt -out client.key +openssl req -new -x509 -key client.key -out client.crt -days 3650 \ + -subj "/CN=test-client/O=Development/C=US" +openssl pkcs12 -export -in client.crt -inkey client.key \ + -out client.p12 -name "myalias" -password "pass:$PKCS12_PASSWORD" + +#Encrypt pkcs8 for client.key for testing +openssl pkcs8 -topk8 -v2 aes-256-cbc -iter 1000000 -in client.key -out client_pkcs8.key \ + -passout "pass:$PKCS12_PASSWORD" \ No newline at end of file diff --git a/src/main/java/com/influxdb/v3/client/config/ClientConfig.java b/src/main/java/com/influxdb/v3/client/config/ClientConfig.java index a87bfab8..31165937 100644 --- a/src/main/java/com/influxdb/v3/client/config/ClientConfig.java +++ b/src/main/java/com/influxdb/v3/client/config/ClientConfig.java @@ -80,6 +80,13 @@ *
  • authenticator - HTTP proxy authenticator
  • *
  • headers - headers to be added to requests
  • *
  • sslRootsFilePath - path to the stored certificates file in PEM format
  • + *
  • sslRootFilePassword - password for a stored certificates file in PEM format
  • + *
  • certificatePath - path to the client certificate file in PEM format. Cannot be used together + * with certificateP12FilePath
  • + *
  • certificateKeyPath - path to the client certificate key file in PEM format
  • + *
  • certificateP12FilePath - path to the client certificate file in P12 format. Cannot be used + * together with certificatePath
  • + *
  • keyPassword - password for a client certificate file in P12 format
  • *
  • disableGRPCCompression - disables the default gRPC compression header
  • *
  • interceptors - list of client interceptors to be used in the query API
  • * @@ -129,7 +136,12 @@ public final class ClientConfig { private final String proxyUrl; private final Authenticator authenticator; private final Map headers; + private final String certificatePath; + private final String certificateKeyPath; + private final String certificateP12FilePath; + private final char[] keyPassword; private final String sslRootsFilePath; + private final char[] sslRootFilePassword; private final boolean disableGRPCCompression; private final List interceptors; @@ -337,6 +349,59 @@ public String sslRootsFilePath() { return sslRootsFilePath; } + /** + * Gets certificate file password. + * + * @return the certificate file password may be null + */ + @Nullable + public char[] getSslRootFilePassword() { + return sslRootFilePassword; + } + + + /** + * Get a client certificate file path. + * Cannot be used together with certificateP12FilePath. + * + * @return the client certificate file path may be null. + */ + @Nullable + public String getCertificatePath() { + return certificatePath; + } + + /** + * Get a client certificate key file path. + * + * @return the client certificate key file path may be null. + */ + @Nullable + public String getCertificateKeyPath() { + return certificateKeyPath; + } + + /** + * Get a client certificate file path in .p12 file format. + * Cannot be used together with certificatePath. + * + * @return the client certificate file path may be null. + */ + @Nullable + public String getCertificateP12FilePath() { + return certificateP12FilePath; + } + + /** + * Gets certificate file password. + * + * @return the certificate file password may be null + */ + @Nullable + public char[] getKeyPassword() { + return keyPassword; + } + /** * Gets the (proxy) authenticator. * @@ -389,6 +454,18 @@ public void validate() { if (uri.getHost() == null) { throw new URISyntaxException(host, "Invalid URL."); } + + if ("https".equals(uri.getScheme())) { + if (certificatePath != null && certificateP12FilePath != null) { + throw new IllegalArgumentException("Cannot set both certificateFilePath " + + "and certificateP12FilePath"); + } + + if (certificatePath != null && certificateKeyPath == null) { + throw new IllegalArgumentException("Cannot set certificatePath without certificateKeyPath"); + } + } + } catch (URISyntaxException e) { throw new IllegalArgumentException("Invalid URL."); } @@ -424,6 +501,11 @@ public boolean equals(final Object o) { && Objects.equals(authenticator, that.authenticator) && Objects.equals(headers, that.headers) && Objects.equals(sslRootsFilePath, that.sslRootsFilePath) + && Arrays.equals(sslRootFilePassword, that.sslRootFilePassword) + && Objects.equals(certificatePath, that.certificatePath) + && Objects.equals(certificateKeyPath, that.certificateKeyPath) + && Objects.equals(certificateP12FilePath, that.certificateP12FilePath) + && Arrays.equals(keyPassword, that.keyPassword) && disableGRPCCompression == that.disableGRPCCompression && Objects.equals(interceptors, that.interceptors); } @@ -434,7 +516,9 @@ public int hashCode() { database, writePrecision, gzipThreshold, writeNoSync, writeAcceptPartial, writeUseV2Api, timeout, writeTimeout, queryTimeout, allowHttpRedirects, disableServerCertificateValidation, proxy, proxyUrl, authenticator, headers, - defaultTags, sslRootsFilePath, disableGRPCCompression, interceptors); + defaultTags, sslRootsFilePath, Arrays.hashCode(sslRootFilePassword), certificatePath, + certificateKeyPath, certificateP12FilePath, Arrays.hashCode(keyPassword), + disableGRPCCompression, interceptors); } @Override @@ -459,6 +543,11 @@ public String toString() { .add("headers=" + headers) .add("defaultTags=" + defaultTags) .add("sslRootsFilePath=" + sslRootsFilePath) + .add("sslRootFilePassword=" + Arrays.toString(sslRootFilePassword)) + .add("certificatePath=" + certificatePath) + .add("certificateKeyPath=" + certificateKeyPath) + .add("certificateP12FilePath=" + certificateP12FilePath) + .add("keyPassword=" + Arrays.toString(keyPassword)) .add("disableGRPCCompression=" + disableGRPCCompression) .toString(); } @@ -490,7 +579,15 @@ public static final class Builder { private String proxyUrl; private Authenticator authenticator; private Map headers; + + private String certificatePath; + private String certificateKeyPath; + private String certificateP12FilePath; + private char[] keyPassword; + private String sslRootsFilePath; + private char[] sslRootFilePassword; + private boolean disableGRPCCompression; private List interceptors; @@ -805,6 +902,51 @@ public Builder sslRootsFilePath(@Nullable final String sslRootsFilePath) { return this; } + /** + * Sets certificate file password. Default is 'null'. + * + * @param sslRootFilePassword The certificate file password + * @return this + */ + @Nonnull + public Builder sslRootFilePassword(@Nullable final char[] sslRootFilePassword) { + + this.sslRootFilePassword = sslRootFilePassword; + return this; + } + + /** + * Sets the file paths for the certificate and its corresponding private key for secure connections. + * + * @param certificatePath the file path to the certificate file in PEM format, must not be null. + * @param certificateKeyPath the file path to the certificate's private key in PEM format, must not be null. + * @return this. + */ + @Nonnull + public Builder certificateFilePath(@Nonnull final String certificatePath, + @Nonnull final String certificateKeyPath) { + this.certificatePath = certificatePath; + this.certificateKeyPath = certificateKeyPath; + + return this; + } + + /** + * Sets the file paths for the certificate and in .p12 file format. + * + * @param certificateP12FilePath the file path to the certificate file in .p12 format, must not be null. + * @param password The certificate file password. + * @return this. + */ + @Nonnull + public Builder certificateP12FilePath(@Nonnull final String certificateP12FilePath, + @Nullable final char[] password) { + this.certificateP12FilePath = certificateP12FilePath; + this.keyPassword = password; + + return this; + } + /** * Sets whether to disable gRPC compression. Default is 'false'. * @@ -1023,6 +1165,11 @@ private ClientConfig(@Nonnull final Builder builder) { authenticator = builder.authenticator; headers = builder.headers; sslRootsFilePath = builder.sslRootsFilePath; + sslRootFilePassword = builder.sslRootFilePassword; + certificatePath = builder.certificatePath; + certificateKeyPath = builder.certificateKeyPath; + certificateP12FilePath = builder.certificateP12FilePath; + keyPassword = builder.keyPassword; disableGRPCCompression = builder.disableGRPCCompression; interceptors = builder.interceptors; } diff --git a/src/main/java/com/influxdb/v3/client/internal/FlightSqlClient.java b/src/main/java/com/influxdb/v3/client/internal/FlightSqlClient.java index 9880e7f2..8d8b0811 100644 --- a/src/main/java/com/influxdb/v3/client/internal/FlightSqlClient.java +++ b/src/main/java/com/influxdb/v3/client/internal/FlightSqlClient.java @@ -21,7 +21,6 @@ */ package com.influxdb.v3.client.internal; -import java.io.FileInputStream; import java.net.InetSocketAddress; import java.net.URI; import java.net.URISyntaxException; @@ -38,6 +37,8 @@ import java.util.stream.StreamSupport; import javax.annotation.Nonnull; import javax.annotation.Nullable; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.TrustManagerFactory; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; @@ -190,9 +191,28 @@ SslContext createNettySslContext(@Nonnull final ClientConfig config) { sslContextBuilder = GrpcSslContexts.forClient(); if (config.getDisableServerCertificateValidation()) { sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE); - } else if (config.sslRootsFilePath() != null) { - try (FileInputStream fileInputStream = new FileInputStream(config.sslRootsFilePath())) { - sslContextBuilder.trustManager(fileInputStream); + } else { + TrustManagerFactory tmf = null; + KeyManagerFactory kmf = null; + if (config.sslRootsFilePath() != null) { + tmf = Utils.createTmf( + config.sslRootsFilePath(), + config.getSslRootFilePassword()); + } + + if (config.getCertificatePath() != null && config.getCertificateKeyPath() != null) { + kmf = Utils.createKmf(config.getCertificatePath(), config.getCertificateKeyPath()); + } + + if (config.getCertificateP12FilePath() != null) { + kmf = Utils.createKmfP12(config.getCertificateP12FilePath(), config.getKeyPassword()); + } + + if (tmf != null) { + sslContextBuilder.trustManager(tmf); + } + if (kmf != null) { + sslContextBuilder.keyManager(kmf); } } return sslContextBuilder.build(); diff --git a/src/main/java/com/influxdb/v3/client/internal/RestClient.java b/src/main/java/com/influxdb/v3/client/internal/RestClient.java index 72de031e..210c55a1 100644 --- a/src/main/java/com/influxdb/v3/client/internal/RestClient.java +++ b/src/main/java/com/influxdb/v3/client/internal/RestClient.java @@ -42,6 +42,7 @@ import java.util.stream.Stream; import javax.annotation.Nonnull; import javax.annotation.Nullable; +import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; @@ -127,16 +128,32 @@ public void checkServerTrusted( if (baseUrl.startsWith("https")) { try { - SSLContext sslContext = SSLContext.getInstance("TLS"); if (config.getDisableServerCertificateValidation()) { + SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, TRUST_ALL_CERTS, new SecureRandom()); - } else if (config.sslRootsFilePath() != null) { - X509TrustManager x509TrustManager = getX509TrustManagerFromFile(config.sslRootsFilePath()); - sslContext.init(null, new X509TrustManager[]{x509TrustManager}, new SecureRandom()); + builder.sslContext(sslContext); } else { - sslContext.init(null, null, new SecureRandom()); + TrustManagerFactory tmf = null; + KeyManagerFactory kmf = null; + if (config.sslRootsFilePath() != null) { + tmf = Utils.createTmf( + config.sslRootsFilePath(), + config.getSslRootFilePassword()); + } + + if (config.getCertificatePath() != null && config.getCertificateKeyPath() != null) { + kmf = Utils.createKmf(config.getCertificatePath(), config.getCertificateKeyPath()); + } + + if (config.getCertificateP12FilePath() != null) { + kmf = Utils.createKmfP12(config.getCertificateP12FilePath(), config.getKeyPassword()); + } + + SSLContext sslContext = Utils.buildSslContext(kmf, tmf); + if (sslContext != null) { + builder.sslContext(sslContext); + } } - builder.sslContext(sslContext); } catch (Exception e) { throw new RuntimeException(e); } @@ -487,6 +504,7 @@ private String errNonEmptyField(@Nullable final JsonNode object, @Nonnull final return errNonEmptyText(object.get(fieldName)); } + //todo remove? private X509TrustManager getX509TrustManagerFromFile(@Nonnull final String filePath) { try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); diff --git a/src/main/java/com/influxdb/v3/client/internal/Utils.java b/src/main/java/com/influxdb/v3/client/internal/Utils.java index 70cc0eb1..1643732d 100644 --- a/src/main/java/com/influxdb/v3/client/internal/Utils.java +++ b/src/main/java/com/influxdb/v3/client/internal/Utils.java @@ -21,8 +21,33 @@ */ package com.influxdb.v3.client.internal; +import java.io.FileInputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.security.GeneralSecurityException; +import java.security.KeyFactory; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.Certificate; +import java.security.cert.CertificateFactory; +import java.security.spec.PKCS8EncodedKeySpec; +import java.util.Base64; +import java.util.Locale; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509TrustManager; + public final class Utils { + private static final String TLS = "TLS"; + private static final char[] DEFAULT_PASSWORD_CHAR_ARRAY = "".toCharArray(); + private static final String X509 = "X.509"; + private static final String PKCS12 = "PKCS12"; + private Utils() { } @@ -43,4 +68,211 @@ public static boolean isInteger(final String str) { return false; } } + + @Nullable + public static SSLContext buildSslContext(@Nullable final KeyManagerFactory kmf, + @Nullable final TrustManagerFactory tmf) throws GeneralSecurityException { + if (kmf == null && tmf == null) { + return null; + } + + SSLContext sslContext = SSLContext.getInstance(TLS); + sslContext.init(kmf != null ? kmf.getKeyManagers() : null, tmf != null ? tmf.getTrustManagers() : null, null); + return sslContext; + } + + + /** + * Creates and initializes a {@link KeyManagerFactory} using a PKCS#12 keystore file + * located at the specified path. This method loads the keystore using the provided + * password (or a default password if none is provided) and initializes a + * {@link KeyManagerFactory} with it. + * + * @param path the file path to the PKCS#12 keystore; must not be null. + * @param password the password for the keystore, or null/empty if the default password + * should be used. + * @return a {@link KeyManagerFactory} instance initialized with the provided keystore. + * @throws IOException if an error occurs while reading the file. + * @throws GeneralSecurityException if an error occurs while loading the keystore + * or initializing the {@link KeyManagerFactory}. + */ + public static KeyManagerFactory createKmfP12(@Nonnull final String path, + @Nullable final char[] password) + throws IOException, GeneralSecurityException { + char[] pass = password != null && password.length > 0 ? password : DEFAULT_PASSWORD_CHAR_ARRAY; + KeyStore keyStore = KeyStore.getInstance(PKCS12); + try (FileInputStream fis = new FileInputStream(path)) { + keyStore.load(fis, pass); + } + + KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + kmf.init(keyStore, pass); + return kmf; + } + + /** + * Creates and initializes a {@link KeyManagerFactory} using the specified certificate and private key files. + * The method loads the certificate chain from the provided `certPath` and the private key from the provided + * `keyPath`. + * These are stored in a {@link KeyStore}, which is then used to initialize the {@link KeyManagerFactory}. + * + * @param certPath the file path to the certificate chain in X.509 format; must not be null. + * @param keyPath the file path to the private key in PKCS#8 format; must not be null. + * @return a {@link KeyManagerFactory} instance initialized with the provided certificate and private key. + * @throws IOException if an error occurs while reading the files. + * @throws GeneralSecurityException if an error occurs while loading the credentials or initializing + * the {@link KeyManagerFactory}. + */ + public static KeyManagerFactory createKmf(@Nonnull final String certPath, + @Nonnull final String keyPath) + throws IOException, GeneralSecurityException { + java.util.Collection certificateChain; + try (FileInputStream fis = new FileInputStream(certPath)) { + certificateChain = CertificateFactory.getInstance(X509).generateCertificates(fis); + } + + KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); + keyStore.load(null, null); + keyStore.setKeyEntry("alias", + loadPrivateKey(keyPath), + null, + certificateChain.toArray(new Certificate[0])); + + KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + kmf.init(keyStore, null); + + return kmf; + } + + /** + * Creates and initializes a TrustManagerFactory from the provided certificate file. + * The file format is determined based on its extension. Supported formats include: + * - .p12 or .pfx: Loaded as a PKCS#12 keystore. + * - .crt, .cert, or .pem: Loaded as individual X.509 certificates. + * + * @param path the file path to the certificate or keystore; must not be null. + * @param password the password for the keystore, or null if not required. + * @return a TrustManagerFactory instance initialized with the provided certificates or keystore. + * @throws IOException if an error occurs while reading the file. + * @throws GeneralSecurityException if an error occurs while processing the certificates + * or initializing the TrustManagerFactory. + * @throws IllegalArgumentException if the provided file format is unsupported. + */ + public static TrustManagerFactory createTmf(@Nonnull final String path, + @Nullable final char[] password) + throws IOException, GeneralSecurityException { + TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + + String extension = path.toLowerCase(Locale.ROOT); + + if (extension.endsWith(".p12") || extension.endsWith(".pfx")) { + char[] pass = password != null && password.length > 0 ? password : DEFAULT_PASSWORD_CHAR_ARRAY; + tmf = createTmfP12(path, pass); + } else if (extension.endsWith(".crt") || extension.endsWith(".cert") || extension.endsWith(".pem")) { + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null, null); + + CertificateFactory certFactory = CertificateFactory.getInstance(X509); + try (FileInputStream fis = new FileInputStream(path)) { + int alias = 0; + for (Certificate certificate : certFactory.generateCertificates(fis)) { + trustStore.setCertificateEntry("alias-" + alias++, certificate); + } + } + tmf.init(trustStore); + } else { + throw new IllegalArgumentException("Unsupported certificate format"); + } + + return tmf; + } + + /** + * Creates and initializes a TrustManagerFactory from a PKCS#12 keystore located at the specified path. + * This method loads the keystore using the provided password and initializes a TrustManagerFactory with it. + * + * @param path the file path to the PKCS#12 keystore; must not be null. + * @param password the password for the keystore, or null/empty if the default password should be used. + * @return a TrustManagerFactory instance initialized with the provided keystore. + * @throws IOException if an error occurs while reading the file. + * @throws GeneralSecurityException if an error occurs while loading the keystore + * or initializing the TrustManagerFactory. + */ + public static TrustManagerFactory createTmfP12(@Nonnull final String path, + @Nullable final char[] password) + throws IOException, GeneralSecurityException { + char[] pass = password != null && password.length > 0 ? password : DEFAULT_PASSWORD_CHAR_ARRAY; + + KeyStore trustStore = KeyStore.getInstance("PKCS12"); + try (FileInputStream fis = new FileInputStream(path)) { + trustStore.load(fis, pass); + } + TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + tmf.init(trustStore); + + return tmf; + } + + /** + * Retrieves an instance of {@link X509TrustManager} from the provided {@link TrustManagerFactory}. + * If the input TrustManagerFactory is null, a default TrustManagerFactory is created and initialized. + * + * @param tmf the {@link TrustManagerFactory} to retrieve the {@link X509TrustManager} from, + * or null to use a default {@link TrustManagerFactory}. + * @return an instance of {@link X509TrustManager} initialized from the given or + * default {@link TrustManagerFactory}. + * @throws GeneralSecurityException if an error occurs during the initialization or retrieval + * of the {@link X509TrustManager}. + */ + @Nonnull + public static X509TrustManager getX509TrustManager(@Nullable final TrustManagerFactory tmf) + throws GeneralSecurityException { + TrustManagerFactory factory = tmf; + if (factory == null) { + factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + factory.init((KeyStore) null); + } + return (X509TrustManager) factory.getTrustManagers()[0]; + } + + /** + * Loads a private key from a file specified by the provided path. The key must be in PKCS#8 format and unencrypted. + * Encrypted private keys are not supported. + * + * @param path the file system path to the private key file; must not be null. + * @return the {@link PrivateKey} object loaded from the provided file path. + * @throws IllegalArgumentException if the private key is encrypted or in an unsupported format. + * @throws IOException if an error occurs during file reading. + * @throws GeneralSecurityException if an error occurs during Base64 decoding or key generation. + */ + public static PrivateKey loadPrivateKey(@Nonnull final String path) throws IOException, GeneralSecurityException { + String keyPem = Files.readString(Paths.get(path)); + if (keyPem.contains("-----BEGIN ENCRYPTED PRIVATE KEY-----")) { + throw new IllegalArgumentException("Encrypted PKCS#8 private keys are not supported. Use an unencrypted " + + "PKCS#8 key or a PKCS#12 file."); + } + + if (!keyPem.contains("-----BEGIN PRIVATE KEY-----") || !keyPem.contains("-----END PRIVATE KEY-----")) { + throw new IllegalArgumentException("Invalid private key format. Private key must be in PKCS#8 format."); + } + + String privateKeyPEM = keyPem + .replace("-----BEGIN PRIVATE KEY-----", "") + .replace("-----END PRIVATE KEY-----", "") + .replaceAll("\\s+", ""); + + byte[] encoded = Base64.getDecoder().decode(privateKeyPEM); + PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded); + GeneralSecurityException lastException = null; + for (String algorithm : new String[]{"RSA", "EC", "DSA"}) { + try { + return KeyFactory.getInstance(algorithm).generatePrivate(keySpec); + } catch (GeneralSecurityException e) { + + lastException = e; + } + } + + throw new GeneralSecurityException("Unsupported private key algorithm", lastException); + } } diff --git a/src/test/java/com/influxdb/v3/client/InfluxDBClientTest.java b/src/test/java/com/influxdb/v3/client/InfluxDBClientTest.java index de6f52a1..cddf0efb 100644 --- a/src/test/java/com/influxdb/v3/client/InfluxDBClientTest.java +++ b/src/test/java/com/influxdb/v3/client/InfluxDBClientTest.java @@ -21,16 +21,35 @@ */ package com.influxdb.v3.client; +import java.io.IOException; +import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.util.List; import java.util.Map; import java.util.Properties; +import java.util.stream.Stream; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManagerFactory; +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; +import okhttp3.Headers; +import org.apache.arrow.flight.FlightRuntimeException; +import org.apache.arrow.flight.FlightServer; +import org.apache.arrow.memory.RootAllocator; +import org.apache.arrow.vector.VectorSchemaRoot; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import com.influxdb.v3.client.config.ClientConfig; +import com.influxdb.v3.client.internal.Utils; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.catchThrowable; public class InfluxDBClientTest { @@ -40,7 +59,7 @@ void withProxyUrl() { ClientConfig.Builder builder = new ClientConfig.Builder(); builder.proxyUrl(proxyUrl); ClientConfig clientConfig = builder.build(); - Assertions.assertThat(clientConfig.getProxyUrl()).isEqualTo(proxyUrl); + assertThat(clientConfig.getProxyUrl()).isEqualTo(proxyUrl); } @Test @@ -68,7 +87,7 @@ record Test(String url, boolean isCorrect) { } else { Assertions.assertThatNoException().isThrownBy(() -> { try (var ignored = InfluxDBClient.getInstance(test.url(), "my-token".toCharArray(), "bucket0")) { - Assertions.assertThat(true); + assertThat(true); } }); } @@ -81,7 +100,7 @@ void withSslRootsFilePath() { ClientConfig.Builder builder = new ClientConfig.Builder(); builder.sslRootsFilePath(path); ClientConfig clientConfig = builder.build(); - Assertions.assertThat(clientConfig.sslRootsFilePath()).isEqualTo(path); + assertThat(clientConfig.sslRootsFilePath()).isEqualTo(path); } @Test @@ -108,7 +127,7 @@ void fromParameters() throws Exception { try (InfluxDBClient client = InfluxDBClient.getInstance("http://localhost:8086", "my-token".toCharArray(), "my-database")) { - Assertions.assertThat(client).isNotNull(); + assertThat(client).isNotNull(); } } @@ -117,7 +136,7 @@ void fromConnectionString() throws Exception { try (InfluxDBClient client = InfluxDBClient.getInstance("http://localhost:8086" + "?token=my-token&database=my-db")) { - Assertions.assertThat(client).isNotNull(); + assertThat(client).isNotNull(); } } @@ -132,7 +151,7 @@ void fromEnvOrProperties() throws Exception { System.setProperties(p); try (InfluxDBClient client = InfluxDBClient.getInstance()) { - Assertions.assertThat(client).isNotNull(); + assertThat(client).isNotNull(); } finally { System.setProperties(old); } @@ -144,11 +163,11 @@ void withDefaultTags() throws Exception { Map defaultTags = Map.of("unit", "U2", "model", "M1"); try (InfluxDBClient client = InfluxDBClient.getInstance( - "http://localhost:8086", - "MY-TOKEN".toCharArray(), - "MY-DATABASE", - defaultTags)) { - Assertions.assertThat(client).isNotNull(); + "http://localhost:8086", + "MY-TOKEN".toCharArray(), + "MY-DATABASE", + defaultTags)) { + assertThat(client).isNotNull(); } } @@ -166,4 +185,307 @@ public void unsupportedQueryParams() throws Exception { + "class com.influxdb.v3.client.internal.InfluxDBClientImpl"); } } + + String tlsDir = "src/test/java/com/influxdb/v3/client/testdata/certificates/"; + + String influxdbCertPath = tlsDir + "influxdb.crt"; + String influxdbKeyPath = tlsDir + "influxdb.key"; + String influxdbP12 = tlsDir + "influxdb.p12"; + + String otherCertPath = tlsDir + "other-server.crt"; + String otherKeyCertPath = tlsDir + "other-server.key"; + String otherP12 = tlsDir + "other-server.p12"; + + String clientCertPath = tlsDir + "client.crt"; + String clientKeyPath = tlsDir + "client.key"; + String clientP12 = tlsDir + "client.p12"; + + char[] defaultPassword = "changeit".toCharArray(); + + record TlsTest( + @Nonnull String name, + @Nullable String clientCertFilePath, + @Nullable String clientKeyFilePath, + @Nullable char[] clientKeyPassword, + @Nonnull String sslRootFilePath, + @Nullable char[] sslRootFilePathPassword, + boolean expectSuccess + ) { + } + + private List tlsCases() { + return List.of( + new TlsTest( + "Tls success with correct server certificate", + null, + null, + null, + influxdbCertPath, + null, + true + ), + new TlsTest( + "Tls success with correct .p12 server certificate", + null, + null, + null, + influxdbP12, + defaultPassword, + true + ), + new TlsTest( + "Tls fail with incorrect server certificate", + null, + null, + null, + otherCertPath, + null, + false + ), + new TlsTest( + "Tls fail with incorrect password", + null, + null, + null, + influxdbP12, + "wrong pass".toCharArray(), + false + ), + new TlsTest( + "mtls success with correct client certificate .key and .crt file", + clientCertPath, + clientKeyPath, + null, + influxdbCertPath, + null, + true + ), + new TlsTest( + "mtls success with correct client certificate .p12 file", + clientP12, + null, + defaultPassword, + influxdbCertPath, + null, + true + ), + new TlsTest( + "mtls fail with incorrect client certificate .crt and .key file", + otherCertPath, + otherKeyCertPath, + null, + influxdbCertPath, + null, + false + ), + new TlsTest( + "mtls fail with incorrect client certificate .p12 file", + otherP12, + null, + defaultPassword, + influxdbCertPath, + null, + false + ), + new TlsTest( + "mtls fail with incorrect password for client certificate .p12 file", + clientP12, + null, + "wrong password".toCharArray(), + influxdbCertPath, + null, + false + ), + new TlsTest( + "mtls fail with incorrect password for server certificate .p12 file", + clientP12, + null, + defaultPassword, + influxdbP12, + "wrong password".toCharArray(), + false + ) + ); + } + + @Test + public void testWriteSecureServer() { + // Please run generate-self-signed-cert.sh script before run these TLS/mTLS tests. + for (TlsTest tlsCase : tlsCases()) { + Throwable thrown = catchThrowable(() -> + testWriteSecureMockServer( + tlsCase.clientCertFilePath, + tlsCase.clientKeyFilePath, + tlsCase.clientKeyPassword, + tlsCase.sslRootFilePath, + tlsCase.sslRootFilePathPassword + )); + if (!tlsCase.expectSuccess) { + assertThat(thrown).isNotNull(); + assertThat(thrown).isInstanceOfAny(InfluxDBApiException.class, RuntimeException.class); + if (thrown instanceof InfluxDBApiException) { + assertThat(thrown).hasMessageContaining("ssl"); + } else if (thrown instanceof RuntimeException && thrown.getCause() instanceof IOException) { + assertThat(thrown).hasMessageContaining("keystore password was incorrect"); + } + } else { + assertThat(thrown).isNull(); + } + } + } + + @Test + public void testQuerySecureServer() throws Exception { + // Please run generate-self-signed-cert.sh script before run these TLS/mTLS tests. + for (TlsTest tlsCase : tlsCases()) { + try (var flightServer = createQuerySecureServer( + influxdbCertPath, + influxdbKeyPath, + tlsCase.clientCertFilePath != null ? clientCertPath : null)) { + flightServer.start(); + URI uri = flightServer.getLocation().getUri(); + ClientConfig clientConfig = getSecureClientConfigBuilder( + String.format("https://%s:%d", uri.getHost(), uri.getPort()), + tlsCase.sslRootFilePath, + tlsCase.sslRootFilePathPassword, + tlsCase.clientCertFilePath, + tlsCase.clientKeyFilePath, + tlsCase.clientKeyPassword + ).build(); + Throwable thrown = catchThrowable(() -> { + try (InfluxDBClient influxDBClient = InfluxDBClient.getInstance(clientConfig)) { + Stream stream = influxDBClient.query("Select * from \"nothing\""); + stream.forEach(objects -> { + assertThat(objects[0]).isEqualTo("Value"); + }); + } + }); + if (!tlsCase.expectSuccess) { + assertThat(thrown).isInstanceOfAny( + InfluxDBApiException.class, + RuntimeException.class, + FlightRuntimeException.class + ); + if (thrown instanceof InfluxDBApiException || thrown instanceof FlightRuntimeException) { + assertThat(thrown.getMessage()).containsAnyOf("ssl", "io exception"); + } else if (thrown instanceof RuntimeException && thrown.getCause() instanceof IOException) { + assertThat(thrown.getMessage()).contains("keystore password was incorrect"); + } + } else { + assertThat(thrown).isNull(); + } + } + } + } + + private void testWriteSecureMockServer(@Nullable final String clientCertFilePath, + @Nullable final String clientKeyFilePath, + @Nullable final char[] clientCertFilePassword, + @Nonnull final String trustFilePath, + @Nullable final char[] trustFilePathPassword + ) + throws Exception { + MockWebServer mockServer = null; + InfluxDBClient client = null; + try { + mockServer = createWriteSecureServer( + influxdbCertPath, + influxdbKeyPath, + clientCertFilePath != null ? clientCertPath : null); + final ClientConfig clientConfig = getSecureClientConfigBuilder( + mockServer.url("/").url().toString(), + trustFilePath, + trustFilePathPassword, + clientCertFilePath, + clientKeyFilePath, + clientCertFilePassword + ).build(); + client = InfluxDBClient.getInstance(clientConfig); + client.writeRecord("mem,tag=one value=1.0"); + } catch (Exception e) { + throw e; + } finally { + if (client != null) { + client.close(); + } + + if (mockServer != null) { + mockServer.close(); + } + } + } + + @Nonnull + private FlightServer createQuerySecureServer(@Nonnull final String serverCertFilePath, + @Nonnull final String serverKeyFilePath, + @Nullable final String clientCertPath) + throws Exception { + URI uri = URI.create("https://127.0.0.1:" + TestUtils.findFreePort()); + VectorSchemaRoot vectorSchemaRoot = TestUtils.generateVectorSchemaRootWithNull(); + return TestUtils.secureFlightServer( + uri, + new RootAllocator(Long.MAX_VALUE), + TestUtils.simpleProducer(vectorSchemaRoot), + serverCertFilePath, + serverKeyFilePath, + clientCertPath + ); + } + + private MockWebServer createWriteSecureServer( + @Nonnull final String serverCertFilePath, + @Nonnull final String serverKeyFilePath, + @Nullable final String clientCertFilePath + ) throws Exception { + KeyManagerFactory kmf = Utils.createKmf(serverCertFilePath, serverKeyFilePath); + var mockServer = new MockWebServer(); + TrustManagerFactory tmf = null; + if (clientCertFilePath != null) { + tmf = Utils.createTmf(clientCertFilePath, null); + mockServer.requireClientAuth(); + } + SSLContext sslContext = Utils.buildSslContext(kmf, tmf); + mockServer.useHttps(sslContext.getSocketFactory()); + mockServer.start(); + mockServer.enqueue(createResponse()); + + return mockServer; + } + + private ClientConfig.Builder getSecureClientConfigBuilder( + @Nonnull final String host, + @Nonnull final String trustFilePath, + @Nullable final char[] trustFilePathPassword, + @Nullable final String clientCertFilePath, + @Nullable final String clientKeyFilePath, + @Nullable final char[] clientCertFilePassword + ) { + ClientConfig.Builder configBuilder = new ClientConfig.Builder() + .token("my-token".toCharArray()) + .database("mydb") + .sslRootsFilePath(trustFilePath); + + if (trustFilePathPassword != null) { + configBuilder.sslRootFilePassword(trustFilePathPassword); + } + + if (clientCertFilePath != null) { + if (clientCertFilePath.endsWith(".p12")) { + configBuilder.certificateP12FilePath(clientCertFilePath, clientCertFilePassword); + } else { + configBuilder.certificateFilePath(clientCertFilePath, clientKeyFilePath); + } + } + + configBuilder.host(host); + return configBuilder; + } + + @Nonnull + protected MockResponse createResponse() { + return new MockResponse(200, + Headers.of("something", "something"), + "ok"); + } + } diff --git a/src/test/java/com/influxdb/v3/client/TestUtils.java b/src/test/java/com/influxdb/v3/client/TestUtils.java index 28103513..027df552 100644 --- a/src/test/java/com/influxdb/v3/client/TestUtils.java +++ b/src/test/java/com/influxdb/v3/client/TestUtils.java @@ -21,6 +21,7 @@ */ package com.influxdb.v3.client; +import java.io.File; import java.io.IOException; import java.net.ServerSocket; import java.net.URI; @@ -30,6 +31,7 @@ import java.util.List; import java.util.Map; import javax.annotation.Nonnull; +import javax.annotation.Nullable; import org.apache.arrow.flight.FlightServer; import org.apache.arrow.flight.Location; @@ -51,13 +53,37 @@ private TestUtils() { throw new IllegalStateException("Utility class"); } + @Nonnull public static FlightServer simpleFlightServer(@Nonnull final URI uri, @Nonnull final BufferAllocator allocator, - @Nonnull final NoOpFlightProducer producer) throws Exception { + @Nonnull final NoOpFlightProducer producer) { Location location = Location.forGrpcInsecure(uri.getHost(), uri.getPort()); return FlightServer.builder(allocator, location, producer).build(); } + @Nonnull + public static FlightServer secureFlightServer(@Nonnull final URI uri, + @Nonnull final BufferAllocator allocator, + @Nonnull final NoOpFlightProducer producer, + @Nonnull final String serverCertPath, + @Nonnull final String serverKeyPath, + @Nullable final String clientCertPath) throws IOException { + Location location = Location.forGrpcTls(uri.getHost(), uri.getPort()); + + var serverBuilder = FlightServer.builder(allocator, location, producer) + .useTls(new File(serverCertPath), new File(serverKeyPath)); + + if (clientCertPath != null) { + if (clientCertPath.endsWith(".p12")) { + throw new IllegalArgumentException("Client certificate path must be in PEM " + + "format likes .pem, .crt, .cert"); + } + serverBuilder.useMTlsClientVerification(new File(clientCertPath)); + } + + return serverBuilder.build(); + } + public static NoOpFlightProducer simpleProducer(@Nonnull final VectorSchemaRoot vectorSchemaRoot) { return new NoOpFlightProducer() { @Override diff --git a/src/test/java/com/influxdb/v3/client/config/ClientConfigTest.java b/src/test/java/com/influxdb/v3/client/config/ClientConfigTest.java index 573cc288..b320cf00 100644 --- a/src/test/java/com/influxdb/v3/client/config/ClientConfigTest.java +++ b/src/test/java/com/influxdb/v3/client/config/ClientConfigTest.java @@ -30,9 +30,12 @@ import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; +import com.influxdb.v3.client.InfluxDBClient; import com.influxdb.v3.client.write.WriteOptions; import com.influxdb.v3.client.write.WritePrecision; +import static org.assertj.core.api.AssertionsForClassTypes.catchThrowable; + class ClientConfigTest { private final ClientConfig.Builder configBuilder = new ClientConfig.Builder() @@ -448,4 +451,37 @@ void standardTimeoutUsedWhenWriteTimeoutUndefinedTest() { Assertions.assertThat(config.getWriteTimeout()).isEqualTo(Duration.ofSeconds(testTimeout)); } + @Test + void setBothCertFilePathAndP12FilePathTest() { + ClientConfig config = new ClientConfig.Builder() + .host("https://localhost:8086") + .token("my-token".toCharArray()) + .certificateFilePath("path/to/client.crt", "path/to/client.key") + .certificateP12FilePath("path/to/client.p12", "changeit".toCharArray()) + .build(); + + Throwable thrown = catchThrowable(() -> InfluxDBClient.getInstance(config)); + Assertions.assertThat(thrown).isNotNull(); + Assertions.assertThat(thrown).isInstanceOf(IllegalArgumentException.class); + Assertions.assertThat(thrown.getMessage()).isEqualTo("Cannot set both certificateFilePath " + + "and certificateP12FilePath"); + + } + + @Test + void setCertFileWithoutKeyfile() { + ClientConfig config = new ClientConfig.Builder() + .host("https://localhost:8086") + .token("my-token".toCharArray()) + .certificateFilePath("path/to/client.crt", null) + .build(); + + Throwable thrown = catchThrowable(() -> InfluxDBClient.getInstance(config)); + Assertions.assertThat(thrown).isNotNull(); + Assertions.assertThat(thrown).isInstanceOf(IllegalArgumentException.class); + Assertions.assertThat(thrown.getMessage()) + .isEqualTo("Cannot set certificatePath without certificateKeyPath"); + + } + } diff --git a/src/test/java/com/influxdb/v3/client/internal/UtilsTest.java b/src/test/java/com/influxdb/v3/client/internal/UtilsTest.java index a4bd023c..ba7e507b 100644 --- a/src/test/java/com/influxdb/v3/client/internal/UtilsTest.java +++ b/src/test/java/com/influxdb/v3/client/internal/UtilsTest.java @@ -21,14 +21,34 @@ */ package com.influxdb.v3.client.internal; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.GeneralSecurityException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.util.Base64; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509TrustManager; + import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.NullAndEmptySource; import org.junit.jupiter.params.provider.ValueSource; class UtilsTest { + + private final Path tempDir; + + UtilsTest(@TempDir final Path tempDir) { + this.tempDir = tempDir; + } + @ParameterizedTest @ValueSource(strings = { "0", @@ -70,4 +90,135 @@ void isIntegerInvalid(final String value) { void testEmpty() { Assertions.assertThat(Utils.isInteger("")).isFalse(); } + + @Test + void loadPrivateKeyMissingBeginHeader() throws IOException { + Path keyFile = tempDir.resolve("missing_begin.key"); + Files.writeString(keyFile, + "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC3\n-----END PRIVATE KEY-----"); + + Assertions.assertThatThrownBy(() -> Utils.loadPrivateKey(keyFile.toString())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid private key format. Private key must be in PKCS#8 format."); + } + + @Test + void loadPrivateKeyMissingEndHeader() throws IOException { + Path keyFile = tempDir.resolve("missing_end.key"); + Files.writeString(keyFile, + "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC3"); + + Assertions.assertThatThrownBy(() -> Utils.loadPrivateKey(keyFile.toString())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid private key format. Private key must be in PKCS#8 format."); + } + + @Test + void loadPrivateKeyMissingBothHeaders() throws IOException { + Path keyFile = tempDir.resolve("missing_both.key"); + Files.writeString(keyFile, "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC3"); + + Assertions.assertThatThrownBy(() -> Utils.loadPrivateKey(keyFile.toString())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid private key format. Private key must be in PKCS#8 format."); + } + + @ParameterizedTest + @ValueSource(strings = {"RSA", "EC", "DSA"}) + void loadPrivateKeySupportedAlgorithms(final String algorithm) throws Exception { + KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(algorithm); + if ("RSA".equals(algorithm)) { + keyPairGen.initialize(2048); + } else if ("EC".equals(algorithm)) { + keyPairGen.initialize(256); + } else if ("DSA".equals(algorithm)) { + keyPairGen.initialize(1024); + } + KeyPair keyPair = keyPairGen.generateKeyPair(); + String encodedKey = Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded()); + String pem = "-----BEGIN PRIVATE KEY-----\n" + encodedKey + "\n-----END PRIVATE KEY-----\n"; + Path keyFile = tempDir.resolve("valid_" + algorithm + ".key"); + Files.writeString(keyFile, pem); + + PrivateKey privateKey = Utils.loadPrivateKey(keyFile.toString()); + Assertions.assertThat(privateKey).isNotNull(); + Assertions.assertThat(privateKey.getAlgorithm()).isEqualTo(algorithm); + } + + @Test + void loadPrivateKeyUnsupportedAlgorithm() throws Exception { + KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("Ed25519"); + KeyPair keyPair = keyPairGen.generateKeyPair(); + String encodedKey = Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded()); + String pem = "-----BEGIN PRIVATE KEY-----\n" + encodedKey + "\n-----END PRIVATE KEY-----\n"; + Path keyFile = tempDir.resolve("ed25519.key"); + Files.writeString(keyFile, pem); + + Assertions.assertThatThrownBy(() -> Utils.loadPrivateKey(keyFile.toString())) + .isInstanceOf(GeneralSecurityException.class) + .hasMessage("Unsupported private key algorithm") + .hasCauseInstanceOf(GeneralSecurityException.class); + } + + @Test + void loadPrivateKeyInvalidKeyBytesThrowsUnsupportedAlgorithm() throws Exception { + String encodedKey = Base64.getEncoder().encodeToString(new byte[]{1, 2, 3, 4, 5, 6, 7, 8}); + String pem = "-----BEGIN PRIVATE KEY-----\n" + encodedKey + "\n-----END PRIVATE KEY-----\n"; + Path keyFile = tempDir.resolve("invalid_bytes.key"); + Files.writeString(keyFile, pem); + + Assertions.assertThatThrownBy(() -> Utils.loadPrivateKey(keyFile.toString())) + .isInstanceOf(GeneralSecurityException.class) + .hasMessage("Unsupported private key algorithm") + .hasCauseInstanceOf(GeneralSecurityException.class); + } + + @Test + void loadPrivateKeyEmptyFile() throws IOException { + Path keyFile = tempDir.resolve("empty.key"); + Files.writeString(keyFile, ""); + + Assertions.assertThatThrownBy(() -> Utils.loadPrivateKey(keyFile.toString())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid private key format. Private key must be in PKCS#8 format."); + } + + @Test + void loadPrivateKeyEncryptedPkcs8Rejected() throws IOException { + Path keyFile = tempDir.resolve("encrypted_pkcs8.key"); + Files.writeString(keyFile, + "-----BEGIN ENCRYPTED PRIVATE KEY-----\nMIIE...\n-----END ENCRYPTED PRIVATE KEY-----"); + + Assertions.assertThatThrownBy(() -> Utils.loadPrivateKey(keyFile.toString())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Encrypted PKCS#8 private keys are not supported. " + + "Use an unencrypted PKCS#8 key or a PKCS#12 file."); + } + + @Test + void createTmfUnsupportedType() throws IOException { + Path keyFile = tempDir.resolve("cert.java"); + Assertions.assertThatThrownBy(() -> Utils.createTmf(keyFile.toString(), null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Unsupported certificate format"); + } + + @Test + void getX509TrustManagerDefault() throws Exception { + X509TrustManager trustManager = Utils.getX509TrustManager(null); + Assertions.assertThat(trustManager).isNotNull(); + } + + @Test + void getX509TrustManagerFromFactory() throws Exception { + TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + tmf.init((KeyStore) null); + X509TrustManager trustManager = Utils.getX509TrustManager(tmf); + Assertions.assertThat(trustManager).isNotNull(); + } + + @Test + void buildSslContextNull() throws Exception { + Assertions.assertThat(Utils.buildSslContext(null, null)).isNull(); + } } diff --git a/src/test/java/com/influxdb/v3/client/testdata/docker.com.pem b/src/test/java/com/influxdb/v3/client/testdata/docker.com.pem deleted file mode 100644 index ac9ed44c..00000000 --- a/src/test/java/com/influxdb/v3/client/testdata/docker.com.pem +++ /dev/null @@ -1,33 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIFxDCCBKygAwIBAgIQDE0Qon/WHglZ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EwEB/wQC -MAAwggF+BgorBgEEAdZ5AgQCBIIBbgSCAWoBaAB3AN3cyjSV1+EWBeeVMvrHn/g9 -HFDf2wA6FBJ2Ciysu8gqAAABkWTCKI4AAAQDAEgwRgIhALzND2kn+PR4aObDiWGv -7QJZ/z4i/vhAGjd/vp2hjt4HAiEAytgsAcPUFd/Y98n5EQkMg6GBSUUygBMc7+Xk -UVJXFgcAdQDm0jFjQHeMwRBBBtdxuc7B0kD2loSG+7qHMh39HjeOUAAAAZFkwiic -AAAEAwBGMEQCIGXbP5ughe+EksczYEErOqY1LZHi9/SmXcp6/vAeuXBmAiB16Sw7 -1sPB/CpKq75/pEwb5pamTdmeEIaHtGQTkTMZ5QB2AMz7D2qFcQll/pWbU87psnwi -6YVcDZeNtql+VMD+TA2wAAABkWTCKIoAAAQDAEcwRQIgX2WsD3ThDwalMCYqmf+X -ICS9imyYmwKXJbfkSnMH/HkCIQCEkDrOAJZG1fGfyOzhSPHWPMxbuGwV18jBGe52 -D9PPQTANBgkqhkiG9w0BAQsFAAOCAQEAcW8Z3+JzqfGTYX+MBk2pQvo8msx+fINU -ZzORUcFUNV0467G/Kc780S8GRxF8dr90WaFctMvw8yDOipfj0sacGJFVFFf5XoWu -1EqYyx3hgMLCQ5DzjAoY4X1KsfPRBe2DCsqf+Nt/TVzgVjOSglURBWKV2T+Av78H -HiMjtEUZbatvuKvUg5S26dvUxXseN/8Jbbt9MCCGascPOf+zXGysoBSwglt0Nz7W -hjXnY+BPeLD38ouUGx0R+sZbXICR6BIxtT4GgOcmJJ/KT3fcMObhsihiq6lO1aql -Yo4AvWpg2tJtwFrG4ooDRyyARljHMUMIkuTz9Dypl/dnJJfzAQLjVA== ------END CERTIFICATE----- diff --git a/src/test/java/com/influxdb/v3/client/testdata/influxdb-certificate.pem b/src/test/java/com/influxdb/v3/client/testdata/influxdb-certificate.pem deleted file mode 100644 index b85c8037..00000000 --- a/src/test/java/com/influxdb/v3/client/testdata/influxdb-certificate.pem +++ /dev/null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