- TLS Refactoring

This commit is contained in:
Josako
2025-09-04 15:22:45 +02:00
parent af8b5f54cd
commit 54a9641440
5 changed files with 80 additions and 67 deletions

View File

@@ -1,7 +1,4 @@
import atexit
import os
import ssl
import tempfile
from celery import Celery
from kombu import Queue
@@ -9,26 +6,6 @@ from werkzeug.local import LocalProxy
from redbeat import RedBeatScheduler
celery_app = Celery()
_tmp_paths = []
def _create_ssl_cert_file(cert_data: str) -> str:
"""Create temporary certificate file for Celery SSL"""
if not cert_data:
return None
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.pem') as cert_file:
cert_file.write(cert_data)
path = cert_file.name
_tmp_paths.append(path) # track for cleanup
return path
def _cleanup_tmp():
for p in _tmp_paths:
try:
os.remove(p)
except Exception:
pass
atexit.register(_cleanup_tmp)
def init_celery(celery, app, is_beat=False):
@@ -67,25 +44,20 @@ def init_celery(celery, app, is_beat=False):
# celery_config['result_backend_transport_options'] = result_backend_transport_options
# TLS (only when cert is provided or your URLs are rediss://)
cert_data = app.config.get('REDIS_CERT_DATA')
ssl_opts = None
if cert_data:
try:
ca_path = _create_ssl_cert_file(cert_data)
if ca_path:
ssl_opts = {
'ssl_cert_reqs': ssl.CERT_REQUIRED, # <— constant, not string
'ssl_ca_certs': ca_path,
# 'ssl_check_hostname': True, # kombu/redis doesnt consistently honor this; CERT_REQUIRED is the key
}
app.logger.info("SSL configured for Celery Redis connection (CA provided)")
except Exception as e:
app.logger.error(f"Failed to configure SSL for Celery: {e}")
if ssl_opts is None:
ssl_opts = {'ssl_cert_reqs': ssl.CERT_REQUIRED}
cert_path = app.config.get('REDIS_CA_CERT_PATH')
if cert_path:
ssl_opts = {
'ssl_cert_reqs': ssl.CERT_REQUIRED,
'ssl_ca_certs': cert_path,
'ssl_check_hostname': app.config.get('REDIS_SSL_CHECK_HOSTNAME', True),
}
app.logger.info(
"SSL configured for Celery Redis connection (CA: %s, hostname-check: %s)",
cert_path,
'enabled' if app.config.get('REDIS_SSL_CHECK_HOSTNAME', True) else 'disabled (IP)'
)
celery_config['broker_use_ssl'] = ssl_opts
# Redis result backend needs its own key:
celery_config['redis_backend_use_ssl'] = ssl_opts
# Beat/RedBeat