diff --git a/.circleci/config.yml b/.circleci/config.yml index 455ee3c5..1c5eff8e 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -114,9 +114,26 @@ 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 - client-test: python-image: << parameters.python-image >> pytest-marker: << parameters.pytest-marker >> + - run: + name: Remove self-signed certificates + command: | + rm -f tests/data/certificates/influxdb.crt \ + tests/data/certificates/influxdb.key \ + tests/data/certificates/influxdb.pem \ + tests/data/certificates/other-server.crt \ + tests/data/certificates/other-server.key \ + tests/data/certificates/other-server.pem \ + tests/data/certificates/client.crt \ + tests/data/certificates/client.key \ + tests/data/certificates/client.pem \ + tests/data/certificates/client-encrypted.key + when: always - store_test_results: path: test-reports - when: diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d53d98e..e0424e59 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## 0.22.0 [unreleased] +### Features + +1. [#254](https://github.com/InfluxCommunity/influxdb3-python/pull/254): + - Add support for mTLS in query api. + - Add examples for config mTLS. + ### Breaking Changes 1. [#238](https://github.com/InfluxCommunity/influxdb3-python/pull/238): Drop support for Python 3.9. Python 3.10 or newer is now required. diff --git a/examples/core/basic_ssl.py b/examples/core/basic_ssl.py index 3ef86b60..6ad39710 100644 --- a/examples/core/basic_ssl.py +++ b/examples/core/basic_ssl.py @@ -78,6 +78,9 @@ def main() -> None: query_with_verify_ssl_off(temp_cert_file) remove_cert(temp_cert_file) + # This is not a completed examples, please change the paths to your real certificates path. + # config_mtls() + def write_and_query_with_explicit_sys_cert(): print("\nwrite and query with typical linux system cert\n") @@ -105,11 +108,46 @@ def query_with_verify_ssl_off(cert): database=DATABASE, ssl_ca_cert=cert, verify_ssl=False) as _client: - query = "SELECT * FROM \"escooter\" ORDER BY time DESC" reader: pyarrow.Table = _client.query(query, mode="") print_results(reader.to_pylist()) +# Please change these paths with your real path to your certificates. +path_client_cert_file = "path/to/cert_file.crt" +path_client_key_file = "path/to/cert_file.key" +path_client_cert_file_pem = "path/to/cert_file.pem" +path_server_cert = "path/to/server_cert.crt" +key_file_password = "password" + + +def config_mtls(): + print("\nConfig tls/mtls for client\n") + + # Config mTLS with client send certificate to the server with separated .crt file and .key file. + # `ssl_ca_cert` is optional. + with InfluxDBClient3(token=TOKEN, + host=HOST, + database=DATABASE, + ssl_ca_cert=path_server_cert, + cert_file=path_client_cert_file, + cert_key_file=path_client_key_file, + cert_key_password=key_file_password, # Optional + verify_ssl=True) as _client: + result = _client.get_server_version() + print(result) + + # Config mTLS with client send a certificate to the server with both certificate and key bundled inside a .pem file. + # `ssl_ca_cert` is optional. + with InfluxDBClient3(token=TOKEN, + host=HOST, + database=DATABASE, + ssl_ca_cert=path_server_cert, + cert_file=path_client_cert_file_pem, + verify_ssl=True) as _client: + result = _client.get_server_version() + print(result) + + if __name__ == "__main__": main() diff --git a/influxdb_client_3/__init__.py b/influxdb_client_3/__init__.py index 25c7896c..96d1acea 100644 --- a/influxdb_client_3/__init__.py +++ b/influxdb_client_3/__init__.py @@ -373,6 +373,12 @@ def __init__( q_opts_builder.disable_grpc_compression(True) if kw_keys.__contains__('ssl_ca_cert'): q_opts_builder.root_certs(kwargs.get('ssl_ca_cert', None)) + if kw_keys.__contains__('cert_file'): + q_opts_builder.cert_chain(kwargs.get('cert_file', None)) + if kw_keys.__contains__('cert_key_file'): + q_opts_builder.private_key(kwargs.get('cert_key_file', None)) + if kw_keys.__contains__('cert_key_password'): + q_opts_builder.private_key_password(kwargs.get('cert_key_password', None)) if kw_keys.__contains__('verify_ssl'): q_opts_builder.tls_verify(kwargs.get('verify_ssl', True)) if kw_keys.__contains__('proxy'): diff --git a/influxdb_client_3/query/query_api.py b/influxdb_client_3/query/query_api.py index d2c4d17b..3cfb9bef 100644 --- a/influxdb_client_3/query/query_api.py +++ b/influxdb_client_3/query/query_api.py @@ -6,6 +6,7 @@ from pyarrow.flight import FlightClient, Ticket, FlightCallOptions, FlightStreamReader from influxdb_client_3.version import USER_AGENT +from influxdb_client_3.write_client.client.util.helpers import read_certs class QueryApiOptions(object): @@ -14,7 +15,9 @@ class QueryApiOptions(object): Attributes ---------- - tls_root_certs (bytes): contents of an SSL root certificate or chain read as bytes + tls_root_certs (bytes): contents of an SSL root certificate or chain read as bytes + cert_chain (bytes): client certificate if using mutual TLS + private_key (bytes): client private key for cert_chain is using mutual TLS tls_verify (bool): whether to verify SSL certificates or not proxy (str): URL to a proxy server flight_client_options (dict): base set of flight client options passed to internal pyarrow.flight.FlightClient @@ -24,6 +27,9 @@ class QueryApiOptions(object): """ _DEFAULT_TIMEOUT = 300.0 tls_root_certs: bytes = None + cert_chain: bytes = None + private_key: bytes = None + private_key_password: str = None tls_verify: bool = None proxy: str = None flight_client_options: dict = None @@ -37,11 +43,17 @@ def __init__(self, root_certs_path: str, flight_client_options: dict, timeout: float = _DEFAULT_TIMEOUT, disable_grpc_compression: bool = False, - middleware: list = None): + middleware: list = None, + cert_chain: str = None, + private_key: str = None, + private_key_password: str = None): """ Initialize a set of QueryApiOptions :param root_certs_path: path to a certificate .pem file. + :param cert_chain: client certificate if using mutual TLS + :param private_key: client private key for cert_chain is using mutual TLS + :param private_key_password: password for private_key if using mutual TLS :param verify: whether to verify SSL certificates or not. :param proxy: URL of a proxy server, if required. :param flight_client_options: set of flight_client_options @@ -51,7 +63,14 @@ def __init__(self, root_certs_path: str, :param middleware: list of middleware functions to be applied to Flight calls. """ if root_certs_path: - self.tls_root_certs = self._read_certs(root_certs_path) + self.tls_root_certs = read_certs(root_certs_path) + if cert_chain: + self.cert_chain = read_certs(cert_chain) + if private_key: + if private_key_password: + self.private_key = read_certs(private_key, private_key_password) + else: + self.private_key = read_certs(private_key) self.tls_verify = verify self.proxy = proxy self.flight_client_options = flight_client_options @@ -59,12 +78,6 @@ def __init__(self, root_certs_path: str, self.disable_grpc_compression = disable_grpc_compression self.middleware = middleware - def _read_certs(self, path: str) -> bytes: - with open(path, "rb") as certs_file: - certs = certs_file.read() - # Normalize PEM line endings so behavior is stable across platforms. - return certs.replace(b"\r\n", b"\n").replace(b"\r", b"\n") - class QueryApiOptionsBuilder(object): """ @@ -76,13 +89,19 @@ class QueryApiOptionsBuilder(object): options = QueryApiOptionsBuilder()\ .proxy("http://internal.tunnel.proxy:8080") \ - .root_certs("/home/fred/.etc/ssl/alt_certs.pem") \ + .root_certs("/home/.etc/ssl/alt_certs.pem") \ + .cert_chain("/home/.etc/ssl/client.crt") \ + .private_key("/home/.etc/ssl/client.key") \ + .private_key_password("password") \ .tls_verify(True) \ .build() client = QueryApi(connection, token, None, None, options) """ _root_certs_path: str = None + _cert_chain: str = None + _private_key: str = None + _private_key_password: str = None _tls_verify: bool = True _proxy: str = None _flight_client_options: dict = None @@ -94,6 +113,18 @@ def root_certs(self, path: str): self._root_certs_path = path return self + def cert_chain(self, path: str): + self._cert_chain = path + return self + + def private_key(self, path: str): + self._private_key = path + return self + + def private_key_password(self, password: str): + self._private_key_password = password + return self + def tls_verify(self, verify: bool): self._tls_verify = verify return self @@ -123,6 +154,9 @@ def build(self) -> QueryApiOptions: """Build a QueryApiOptions object with previously set values""" return QueryApiOptions( root_certs_path=self._root_certs_path, + cert_chain=self._cert_chain, + private_key=self._private_key, + private_key_password=self._private_key_password, verify=self._tls_verify, proxy=self._proxy, flight_client_options=self._flight_client_options, @@ -180,8 +214,35 @@ def __init__(self, if ('generic_options' in options.flight_client_options and 'grpc.secondary_user_agent' in dict(options.flight_client_options["generic_options"]).keys()): self._flight_client_options['generic_options'].remove(default_user_agent) + if options.tls_root_certs: self._flight_client_options["tls_root_certs"] = options.tls_root_certs + if options.cert_chain: + self._flight_client_options["cert_chain"] = options.cert_chain + if options.private_key: + self._flight_client_options["private_key"] = options.private_key + elif (options.private_key is None and options.cert_chain and + not self._flight_client_options.get("private_key")): + # Only fall back to using cert_chain as private_key if the provided PEM + # content clearly includes a private key block (common in combined PEM files). + pem = options.cert_chain + if isinstance(pem, (bytes, bytearray)): + pem_text = pem.decode("utf-8", errors="ignore") + else: + pem_text = str(pem) + has_private_key = ("BEGIN PRIVATE KEY" in pem_text or + "BEGIN RSA PRIVATE KEY" in pem_text or + "BEGIN EC PRIVATE KEY" in pem_text or + "BEGIN ENCRYPTED PRIVATE KEY" in pem_text + ) + if has_private_key: + self._flight_client_options["private_key"] = options.cert_chain + else: + raise ValueError( + "mTLS misconfiguration: 'cert_chain' was provided without a " + "'private_key'. Provide 'private_key' explicitly, or pass a " + "combined PEM that includes a private key block." + ) if options.proxy: self._proxy = options.proxy if options.tls_verify is not None: diff --git a/influxdb_client_3/write_client/client/util/helpers.py b/influxdb_client_3/write_client/client/util/helpers.py index ada5be43..984608d6 100644 --- a/influxdb_client_3/write_client/client/util/helpers.py +++ b/influxdb_client_3/write_client/client/util/helpers.py @@ -1,4 +1,7 @@ """Functions to share utility across client classes.""" +from typing import Optional, Union + +from cryptography.hazmat.primitives import serialization def _is_id(value): @@ -47,3 +50,41 @@ def get_org_query_param(org, client, required_id=False): raise e return _org + + +def read_certs(path: str, password: Optional[Union[str, bytes]] = None) -> bytes: + """ + Read PEM certificate or key data from a file and produce a stable byte + representation suitable for downstream cryptographic operations. Encrypted + private key material is decrypted when credentials are provided, and PEM line + endings are normalized so the resulting bytes are consistent across operating + systems. + + :param path: Filesystem path to the PEM certificate or private key file. + :param password: Optional password used to decrypt encrypted PEM private key + material. + :return: PEM data as bytes with normalized line endings. + :raises OSError: If the file cannot be opened or read. + :raises ValueError: If encrypted key material cannot be decrypted or the PEM + data is invalid. + :raises TypeError: If the provided password is not accepted by the + cryptographic loader. + :raises cryptography.exceptions.UnsupportedAlgorithm: If the PEM data uses an + unsupported key type or encryption algorithm. + """ + with open(path, "rb") as certs_file: + data = certs_file.read() + if password is not None: + password_bytes = password.encode() if isinstance(password, str) else password + private_key_obj = serialization.load_pem_private_key( + data, + password=password_bytes, + ) + data = private_key_obj.private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.TraditionalOpenSSL, + encryption_algorithm=serialization.NoEncryption(), + ) + + # Normalize PEM line endings so behavior is stable across platforms. + return data.replace(b"\r\n", b"\n").replace(b"\r", b"\n") diff --git a/scripts/generate-self-signed-cert.sh b/scripts/generate-self-signed-cert.sh new file mode 100644 index 00000000..38c4e030 --- /dev/null +++ b/scripts/generate-self-signed-cert.sh @@ -0,0 +1,58 @@ +#!/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}/../tests/data/certificates}" +mkdir -p "$CERTS_DIR" +CERTS_DIR="$(cd -- "$CERTS_DIR" && pwd)" + +KEY_PASSWORD="changeit" +INFLUXDB_SERVER_NAME="influxdb" +OTHER_SERVER_NAME="other-server" + +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 "$CERTS_DIR/${SERVER_NAME}.key" + + openssl req -new -x509 -key "$CERTS_DIR/${SERVER_NAME}.key" -out "$CERTS_DIR/${SERVER_NAME}.crt" -days 3650 \ + -subj "/CN=localhost/O=Development/C=US" \ + -addext "subjectAltName = DNS:localhost,IP:127.0.0.1" + + cat "$CERTS_DIR/${SERVER_NAME}.crt" "$CERTS_DIR/${SERVER_NAME}.key" > "$CERTS_DIR/${SERVER_NAME}.pem" + +# openssl pkcs12 -export -in "$CERTS_DIR/${SERVER_NAME}.crt" -inkey "$CERTS_DIR/${SERVER_NAME}.key" \ +# -out "$CERTS_DIR/${SERVER_NAME}.p12" -name "myalias" -password "pass:$KEY_PASSWORD" +done + +echo "### Generate client key..." +openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 | openssl pkcs8 -topk8 -nocrypt -out "$CERTS_DIR/client.key" +openssl req -new -x509 -key "$CERTS_DIR/client.key" -out "$CERTS_DIR/client.crt" -days 3650 \ + -subj "/CN=test-client/O=Development/C=US" +openssl rsa -in "$CERTS_DIR/client.key" -aes256 -passout "pass:$KEY_PASSWORD" -out "$CERTS_DIR/client-encrypted.key" + +cat "$CERTS_DIR/client.crt" "$CERTS_DIR/client.key" > "$CERTS_DIR/client.pem" + +#openssl pkcs12 -export -in "$CERTS_DIR/client.crt" -inkey "$CERTS_DIR/client.key" \ +# -out "$CERTS_DIR/client.p12" -name "myalias" -password "pass:$KEY_PASSWORD" diff --git a/setup.py b/setup.py index 630d88e8..d45722a0 100644 --- a/setup.py +++ b/setup.py @@ -7,7 +7,8 @@ 'certifi >= 14.05.14', 'python_dateutil >= 2.5.3', 'urllib3 >= 1.26.0', - 'pyarrow >= 8.0.0' + 'pyarrow >= 8.0.0', + 'cryptography>=3.4.0', ] with open("./README.md", "r", encoding="utf-8") as fh: @@ -56,7 +57,6 @@ def get_version(): 'pytest-cov', 'pytest-httpserver', 'h2>=4.0.0,<5.0.0', - 'cryptography>=3.4.0', ] }, install_requires=requires, diff --git a/tests/test_influxdb_client_3.py b/tests/test_influxdb_client_3.py index a8660640..a419b11b 100644 --- a/tests/test_influxdb_client_3.py +++ b/tests/test_influxdb_client_3.py @@ -1,6 +1,10 @@ +import os import re +import ssl import unittest from collections import defaultdict +from dataclasses import dataclass +from typing import Optional from unittest.mock import patch import pandas as pd @@ -603,6 +607,191 @@ def test_get_version_fail(self): ).get_server_version() +class TestTlsInfluxDBClient3(unittest.TestCase): + # Please run generate-self-signed-cert.sh script before run these TLS/mTLS tests. + + dir_path = os.path.dirname(os.path.realpath(__file__)) + certs_dir = os.path.join(dir_path, "data", "certificates") + + server_cert = os.path.join(certs_dir, "influxdb.crt") + server_key = os.path.join(certs_dir, "influxdb.key") + server_cert_pem = os.path.join(certs_dir, "influxdb.pem") + other_cert = os.path.join(certs_dir, "other-server.crt") + other_cert_key = os.path.join(certs_dir, "other-server.key") + other_cert_pem = os.path.join(certs_dir, "other-server.pem") + client_cert = os.path.join(certs_dir, "client.crt") + client_cert_key = os.path.join(certs_dir, "client.key") + client_cert_key_encrypted = os.path.join(certs_dir, "client-encrypted.key") + client_cert_pem = os.path.join(certs_dir, "client.pem") + + @dataclass + class TlsTestCase: + __test__ = False + name: str + server_cert: str + client_cert: Optional[str] = None + client_key: Optional[str] = None + client_key_password: Optional[str] = None + expect_success: bool = True + + def __str__(self): + return self.name + + TEST_CASES = [ + TlsTestCase( + name="Tls success with correct server certificate", + server_cert=server_cert, + ), + TlsTestCase( + name="Tls success with correct server certificate pem", + server_cert=server_cert_pem, + ), + TlsTestCase( + name="Tls fail with incorrect server certificate", + server_cert=other_cert, + expect_success=False, + ), + TlsTestCase( + name="mtls success with correct client certificate and client key files", + server_cert=server_cert, + client_cert=client_cert, + client_key=client_cert_key, + ), + TlsTestCase( + name="mtls success with correct client certificate and encrypted client key files", + server_cert=server_cert, + client_cert=client_cert, + client_key=client_cert_key_encrypted, + client_key_password="changeit", + ), + TlsTestCase( + name="mtls fail with incorrect password for encrypted client key file", + server_cert=server_cert, + client_cert=client_cert, + client_key=client_cert_key_encrypted, + client_key_password="wrongpassword", + expect_success=False, + ), + TlsTestCase( + name="mtls success with correct client certificate and client key bundled in pem file", + server_cert=server_cert, + client_cert=client_cert_pem, + ), + TlsTestCase( + name="mtls fail with incorrect client certificate and client key bundled in a pem file", + server_cert=server_cert, + client_cert=other_cert_pem, + expect_success=False, + ), + TlsTestCase( + name="mtls fail with incorrect client certificate and client key files", + server_cert=server_cert, + client_cert=other_cert, + client_key=other_cert_key, + expect_success=False, + ), + TlsTestCase( + name="mtls fail with incorrect server certificate file", + server_cert=other_cert, + client_cert=client_cert, + client_key=client_cert_key, + expect_success=False, + ), + ] + + def create_write_secure_server(self, is_mtls): + ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + ssl_context.load_cert_chain(certfile=self.server_cert, keyfile=self.server_key) + if is_mtls: + ssl_context.verify_mode = ssl.CERT_REQUIRED + ssl_context.load_verify_locations(cafile=self.client_cert) + server = HTTPServer(ssl_context=ssl_context) + server.expect_request("/api/v2/write").respond_with_json( + response_json={"data": "success"}, + status=204 + ) + return server + + def create_query_secure_server(self, is_mtls): + verify_client = False + tls_ca_cert = None + if is_mtls: + verify_client = True + tls_ca_cert = self.client_cert + return ConstantFlightServer( + root_certificates=tls_ca_cert, + server_cert=self.server_cert, + server_cert_key=self.server_key, + verify_client=verify_client, + ) + + def _create_client(self, host: str, test_case: TlsTestCase) -> InfluxDBClient3: + return InfluxDBClient3( + host=host, + org="my_org", + database="my_db", + token="my_token", + auth_scheme="my_scheme", + ssl_ca_cert=test_case.server_cert, + cert_file=test_case.client_cert, + cert_key_file=test_case.client_key, + cert_key_password=test_case.client_key_password, + ) + + def test_write_with_secure_server(self): + for test_case in self.TEST_CASES: + with self.subTest(test_case=test_case.name): + server = None + client = None + try: + server = self.create_write_secure_server(test_case.client_cert is not None) + server.start() + if not test_case.expect_success: + with self.assertRaises(Exception) as err: + client = self._create_client(f"https://{server.host}:{server.port}", test_case) + client.write(record="data,foo=bar val=3.14") + if isinstance(err.exception, ValueError): + self.assertIn("Incorrect password, could not decrypt key", str(err.exception)) + else: + error_msg = str(err.exception).lower() + self.assertTrue("ssl" in error_msg or "grpc_status:14" in error_msg) + else: + client = self._create_client(f"https://{server.host}:{server.port}", test_case) + client.write(record="data,foo=bar val=3.14") + finally: + if server is not None: + server.stop() + if client is not None: + client.close() + + def test_query_with_secure_server(self): + for test_case in self.TEST_CASES: + with self.subTest(test_case=test_case.name): + server = None + client = None + try: + server = self.create_query_secure_server(test_case.client_cert is not None) + if not test_case.expect_success: + with self.assertRaises(Exception) as err: + client = self._create_client(f"https://localhost:{server.port}", test_case) + client.query("SELECT * FROM test") + exc = err.exception + if isinstance(exc, ValueError): + self.assertIn("Incorrect password, could not decrypt key", str(exc)) + else: + error_msg = str(exc).lower() + self.assertTrue("ssl" in error_msg or "server never sent a data message" in error_msg) + else: + client = self._create_client(f"https://localhost:{server.port}", test_case) + result = client.query("SELECT * FROM test") + self.assertIsNotNone(result) + finally: + if server is not None: + server.shutdown() + if client is not None: + client.close() + + class TestWriteDataFrame(unittest.TestCase): """Tests for the write_dataframe() method.""" diff --git a/tests/util/mocks.py b/tests/util/mocks.py index 088fcb87..8f4d4604 100644 --- a/tests/util/mocks.py +++ b/tests/util/mocks.py @@ -18,6 +18,8 @@ ServerAuthHandler ) +from influxdb_client_3.write_client.client.util.helpers import read_certs + class NoopAuthHandler(ServerAuthHandler): """A no-op auth handler - as seen in pyarrow tests""" @@ -85,8 +87,41 @@ def to_list(self): class ConstantFlightServer(FlightServerBase): - def __init__(self, location=None, options=None, **kwargs): - super().__init__(location, **kwargs) + def __init__(self, + location=None, + options=None, + server_cert=None, + server_cert_key=None, + verify_client=None, + root_certificates=None, + **kwargs): + server_cert_bytes = None + if server_cert is not None: + server_cert_bytes = read_certs(server_cert) + + server_cert_key_bytes = None + if server_cert_key is not None: + server_cert_key_bytes = read_certs(server_cert_key) + + tls_certificates = None + if (server_cert_bytes is None) != (server_cert_key_bytes is None): + raise ValueError( + "Both server_cert and server_cert_key must be provided together to enable TLS." + ) + if server_cert_bytes is not None and server_cert_key_bytes is not None: + tls_certificates = [(server_cert_bytes, server_cert_key_bytes)] + + root_cert_bytes = None + if root_certificates is not None: + root_cert_bytes = read_certs(root_certificates) + + super().__init__( + location=location, + verify_client=verify_client, + tls_certificates=tls_certificates, + root_certificates=root_cert_bytes, + **kwargs + ) self.cd = ConstantData() self.options = options