Setting up TLS
Connecting to your Valkey database securely is crucial, especially when transmitting sensitive data over a network. TLS encrypts the data in transit, preventing eavesdropping or “man-in-the-middle” attacks.
Valkey GLIDE supports TLS connections out-of-the-box. It uses rusttls under the hood to handle the secure connection handshake and encryption. When you enable TLS in the client, GLIDE ensures that it verifies the server’s identity and encrypts all communication.
This tutorial will guide you step-by-step through configuring the Valkey GLIDE client to connect to a TLS-enabled Valkey instance.
What You’ll Learn
Section titled “What You’ll Learn”This tutorial will go over:
- Enabling a basic TLS connection.
- Connecting to a server that uses a custom root certificate (like a self-signed certificate).
By the end of this tutorial, you’ll be able to securely connect your Python application to any TLS-enabled Valkey database using GLIDE.
Prerequisites
Section titled “Prerequisites”Before you begin, please ensure you have the following set up:
- Python 3.9-3.13.
- Valkey GLIDE installed: You can install it using pip:
Terminal window pip install glide-core - A running Valkey instance with TLS enabled. This tutorial assumes your server is already configured for TLS. See the following on how to enable TLS:
Enabling TLS Connections
Section titled “Enabling TLS Connections”We’ll start with the simplest case: connecting to a Valkey server that has TLS enabled and is using a certificate from a trusted public Certificate Authority (CA).
Basic TLS Connection
Section titled “Basic TLS Connection”Enabling TLS is as simple as setting use_tls=True in your configuration.
The client will use your system’s default certificate trust store to verify the server.
client_config = GlideClientConfiguration( addresses, use_tls=True)Full Example
import asynciofrom glide import GlideClient, GlideClientConfiguration, NodeAddress
async def main(): # Define the address addresses = [NodeAddress(host="your-valkey-server.example.com", port=6379)]
# Configure the client to use TLS client_config = GlideClientConfiguration( addresses, use_tls=True )
client = None try: # Create the client client = await GlideClient.create(client_config)
# Test the connection response = await client.ping() print(f"Connected successfully! Server responded: {response}")
except Exception as e: print(f"Failed to connect or run command: {e}") finally: if client: await client.close()
if __name__ == "__main__": asyncio.run(main())Connecting with a Custom Root Certificate
Section titled “Connecting with a Custom Root Certificate”A common scenario is when you might use self-signed certificates or an internal Certificate Authority (CA) for development or an internal network.
GLIDE allows you to provide your own root certificate (or a chain of certificates) in PEM format.
This is handled by configuring the TlsAdvancedConfiguration and AdvancedGlideClientConfiguration classes.
-
Load your root certificate file
You must read your certificate file (e.g.,
ca-cert.pem) as bytes using the"rb"(read binary) mode when opening the file.# Path to your custom certificate filecert_file_path = "/path/to/your/ca-cert.pem"with open(cert_file_path, "rb") as f:root_cert_bytes = f.read() -
Create the advanced TLS configuration
Create an instance of
TlsAdvancedConfigurationand pass your certificate bytes to theroot_pem_cacertsparameter.tls_config = TlsAdvancedConfiguration(root_pem_cacerts=root_cert_bytes) -
Create the advanced client configuration
Wrap your
tls_configin anAdvancedGlideClientConfiguration.advanced_config = AdvancedGlideClientConfiguration(tls_advanced_configuration=tls_config) -
Configure the main client
Finally, create your main
GlideClientConfiguration. This time, you must provide bothuse_tls=Trueand your newadvanced_configuration.addresses = [NodeAddress(host="your-self-signed-server.example.com", port=6379)]client_config = GlideClientConfiguration(addresses,use_tls=True, # Still required!advanced_configuration=advanced_config)
Full Example
Let’s put it all together in a runnable example.
import asynciofrom glide import ( GlideClient, GlideClientConfiguration, NodeAddress, TlsAdvancedConfiguration, AdvancedGlideClientConfiguration)
async def main_with_custom_cert(): # Replace with your server's address and TLS port addresses = [NodeAddress(host="your-self-signed-server.example.com", port=6379)]
# 1. Load the certificate as bytes cert_file_path = "/path/to/your/ca-cert.pem" try: with open(cert_file_path, "rb") as f: root_cert_bytes = f.read() except FileNotFoundError: print(f"Error: Certificate file not found at {cert_file_path}") return except Exception as e: print(f"Error reading certificate file: {e}") return
# 2. Create TLS advanced configuration tls_config = TlsAdvancedConfiguration(root_pem_cacerts=root_cert_bytes)
# 3. Create advanced client configuration advanced_config = AdvancedGlideClientConfiguration( tls_advanced_configuration=tls_config )
# 4. Create main client configuration client_config = GlideClientConfiguration( addresses, use_tls=True, # Don't forget this! advanced_configuration=advanced_config )
try: # 5. Create the client client = await GlideClient.create(client_config)
response = await client.ping() print(f"Connected successfully with custom cert! Server responded: {response}")
except Exception as e: print(f"Failed to connect with custom cert: {e}") finally: if 'client' in locals() and client.is_connected(): await client.close()
if __name__ == "__main__": asyncio.run(main_with_custom_cert())Common Pitfalls
Section titled “Common Pitfalls”- Reading Certificate in Text Mode: Always read certificate files in binary mode (
"rb"). The client requires a bytes object, not a string from reading in text mode ("r"). - Certificate Verification Errors: An error like
CERTIFICATE_VERIFY_FAILEDorTlsErrormeans the server’s identity check failed. Verify:- Hostname Mismatch: The
NodeAddresshost must exactly match the name on the server’s certificate. - Incorrect/Expired Certificate: Ensure you are using the correct and valid root CA file.
- Hostname Mismatch: The
- Forgetting
await: GLIDE is anasynclibrary. Forgetting toawaitclient methods (likeGlideClient.create(),client.ping(), etc.) will cause your code to hang or raise aRuntimeWarning.
Summary
Section titled “Summary”You have now learned how to:
- Enable a basic TLS connection using the
use_tls=Trueflag, which relies on the system’s trust store. - Connect using a custom root certificate with
TlsAdvancedConfigurationto handle self-signed or internal CAs.