Skip to content

LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows

UN-4123 [FEAT] Managed-Redis compatibility: TLS, connection health, and a configurable metrics database (#2287)

ali8333302271b5
diff --git a/backend/backend/settings/base.py b/backend/backend/settings/base.py
index 1a923bc9f..9f5148370 100644
--- a/backend/backend/settings/base.py
+++ b/backend/backend/settings/base.py
@@ -21,6 +21,16 @@ from dotenv import find_dotenv, load_dotenv
from utils.common_utils import CommonUtils
from utils.cors_origin import normalize_web_app_origin
+from unstract.core.cache.redis_client import (
+ build_socketio_redis_url,
+ ensure_tls_query_params,
+ parse_db,
+ resolve_ssl_cert_reqs,
+ resolve_ssl_check_hostname,
+ set_url_db_path,
+ url_db_path,
+)
+
# Django 5.0+ caps URLValidator at 2048 chars. S3 pre-signed URLs signed with
# temporary/STS credentials (carrying X-Amz-Security-Token) routinely exceed this,
# causing "Enter a valid URL." on the API deployment `presigned_urls` field.
@@ -104,6 +114,23 @@ REDIS_PASSWORD = os.environ.get("REDIS_PASSWORD", "")
REDIS_HOST = os.environ.get("REDIS_HOST", "localhost")
REDIS_PORT = os.environ.get("REDIS_PORT", "6379")
REDIS_DB = os.environ.get("REDIS_DB", "")
+# TLS to Redis (UN-4123). Off by default, so the in-cluster/local server is
+# untouched. `rediss://` is what actually selects TLS for both django-redis and
+# kombu; this flag only decides which scheme gets built.
+REDIS_SSL = os.environ.get("REDIS_SSL", "false").strip().lower() == "true"
+# Resolved by unstract.core, not re-read here: the raw value needs trimming,
+# lower-casing and validating, and a second copy of that logic is how this file
+# and create_redis_client came to hold two verification policies for one endpoint.
+REDIS_SSL_CERT_REQS = resolve_ssl_cert_reqs()
+REDIS_SSL_CHECK_HOSTNAME = resolve_ssl_check_hostname()
+REDIS_SSL_CA_CERTS = os.environ.get("REDIS_SSL_CA_CERTS", "").strip()
+# A full URL overrides the discrete vars above, exactly as it does in
+# unstract.core's create_redis_client — otherwise the workers would follow the URL
+# while this process stayed on REDIS_HOST, and the two would silently sit on
+# DIFFERENT servers. That split is invisible until something written by one side
+# is read by the other: an API deployment returns `result: null` because the
+# execution's cached result was written to the URL's Redis and looked up here.
+REDIS_URL = os.environ.get("REDIS_URL", "").strip()
SESSION_EXPIRATION_TIME_IN_SECOND = os.environ.get(
"SESSION_EXPIRATION_TIME_IN_SECOND", 3600
)
@@ -215,9 +242,14 @@ FILE_EXECUTION_TRACKER_COMPLETED_TTL_IN_SECOND = int(
os.environ.get("FILE_EXECUTION_TRACKER_COMPLETED_TTL_IN_SECOND", 60 * 10)
) # 10 minutes
-FILE_ACTIVE_CACHE_REDIS_DB = int(
- os.environ.get("FILE_ACTIVE_CACHE_REDIS_DB", 0)
-) # Redis DB for active file cache tracking
+# Redis DB for active file cache tracking. Parsed the same way every other
+# database var is (UN-4123): a blank value is this repo's "leave the default",
+# not a crash, and backend/sample.env ships this variable — so an operator
+# collapsing the four-key database map onto a db-0-only endpoint is exactly who
+# would hit `int("")` here.
+FILE_ACTIVE_CACHE_REDIS_DB = parse_db(
+ os.environ.get("FILE_ACTIVE_CACHE_REDIS_DB", ""), "FILE_ACTIVE_CACHE_"
+)
INSTANT_WF_POLLING_TIMEOUT = int(
os.environ.get("INSTANT_WF_POLLING_TIMEOUT", "300")
@@ -526,7 +558,7 @@ if REDIS_SENTINEL_MODE:
if REDIS_USER:
_sentinel_kwargs["username"] = REDIS_USER
- _redis_db = REDIS_DB or "0"
+ _redis_db = parse_db(REDIS_DB, "REDIS_")
# SocketIO connection manager (Kombu Sentinel URL format)
_cred_prefix = ""
@@ -551,7 +583,7 @@ if REDIS_SENTINEL_MODE:
"CONNECTION_FACTORY": "django_redis.pool.SentinelConnectionFactory",
"SENTINELS": [(REDIS_HOST, int(REDIS_PORT))],
"SENTINEL_KWARGS": _sentinel_kwargs,
- "DB": int(_redis_db),
+ "DB": _redis_db,
"PASSWORD": REDIS_PASSWORD,
"SERIALIZER": "django_redis.serializers.json.JSONSerializer",
},
@@ -559,26 +591,128 @@ if REDIS_SENTINEL_MODE:
}
}
else:
- # SocketIO connection manager (standalone)
- _cred_prefix = ""
- if REDIS_USER and REDIS_PASSWORD:
- _cred_prefix = f"{quote(REDIS_USER, safe='')}:{quote(REDIS_PASSWORD, safe='')}@"
- elif REDIS_PASSWORD:
- _cred_prefix = f":{quote(REDIS_PASSWORD, safe='')}@"
- SOCKET_IO_MANAGER_URL = f"redis://{_cred_prefix}{REDIS_HOST}:{REDIS_PORT}"
+ # Credentials for the Socket.IO URL are assembled inside
+ # build_socketio_redis_url(); only the cache LOCATION is built here.
+ _scheme = "rediss" if REDIS_SSL else "redis"
+ _cache_db = parse_db(REDIS_DB, "REDIS_")
+
+ # Both django-redis (via redis-py) and kombu read TLS settings out of the URL's
+ # query string, so one string configures both — verified against the pinned
+ # versions. The CA is appended rather than required in the URL, since it is a
+ # local path rather than part of the endpoint's identity.
+ # Same helper the Socket.IO URL uses. Hand-rolling the append here is how two
+ # copies drift: this one WOULD add only ssl_ca_certs while unstract.core added
+ # ssl_cert_reqs as well, leaving one process holding two verification policies
+ # for one endpoint. django-redis reads TLS from the LOCATION's query string
+ # AND from OPTIONS["CONNECTION_POOL_KWARGS"] — the query string wins when both
+ # set the same key (ConnectionPool.from_url ends with kwargs.update(url_options)).
+ # kombu is the URL-only one. The distinction matters: the pool-kwargs block
+ # below is the discrete-vars path's ONLY route, so reading "query string only"
+ # as "that block is dead" would drop hostname verification back to redis-py's
+ # unauthenticated default.
+ # THE DATABASE RULE, applied to the LOCATION so this cache lands where
+ # create_redis_client would put it. django-redis takes a LOCATION string and
+ # ignores OPTIONS["DB"], so rewriting the path is the only lever — and
+ # without it the backend followed the URL's own path while the workers
+ # honoured REDIS_DB. One REDIS_URL, one REDIS_DB, two different databases:
+ # workers RPUSH log_history_queue to db N, the backend LPOPs an empty db 0,
+ # and nothing errors. Same helper both sides use, so the rule has one
+ # implementation rather than two that agree today.
+ _url_db = url_db_path(REDIS_URL)
+ _redis_url = (
+ set_url_db_path(REDIS_URL, _cache_db) if (REDIS_URL and REDIS_DB) else REDIS_URL
+ )
+ _redis_url = ensure_tls_query_params(
+ _redis_url,
+ cert_reqs=REDIS_SSL_CERT_REQS,
+ ca_certs=REDIS_SSL_CA_CERTS,
+ check_hostname=REDIS_SSL_CHECK_HOSTNAME,
+ )
+
+ # Built by unstract.core, which the log-consumer worker's publisher also uses.
+ # Two hand-built URLs for one endpoint drift: one side would keep a hardcoded
+ # redis:// while the other speaks TLS, and against a TLS-only endpoint that
+ # publisher's events would never reach subscribers. The helper also pins ssl_cert_reqs
+ # (kombu defaults rediss:// to CERT_NONE) and carries ssl_ca_certs, neither of
+ # which this expression did for the discrete-vars path.
+ SOCKET_IO_MANAGER_URL = build_socketio_redis_url()
SOCKET_IO_TRANSPORT_OPTIONS = {}
+ # django-redis 5.4.0 reads only PASSWORD (plus timeouts) out of OPTIONS — its
+ # ConnectionFactory.make_connection_params ignores USERNAME and DB entirely.
+ # So the db has to travel in the URL path, or this cache silently sits on db 0
+ # while every other service honours REDIS_DB: workers would RPUSH
+ # log_history_queue to db N and the backend would LPOP an empty db 0.
+ # USERNAME and DB below are passed for readability and are DISCARDED by
+ # django-redis — they are not the mechanism for either. Auth stays password-only
+ # as the built-in `default` user (what a managed AUTH string is): a username
+ # would turn AUTH into its two-argument ACL form, and this cache never sends
+ # one. If a django-redis bump ever starts reading USERNAME, that becomes a real
+ # behaviour change rather than a silent one — which is what the assertions in
+ # tests/test_redis_settings_derivation.py pin.
+ _cache_options = {
+ "CLIENT_CLASS": "django_redis.client.DefaultClient",
+ "SERIALIZER": "django_redis.serializers.json.JSONSerializer",
+ }
+ if not _redis_url:
+ # Credentials and db travel IN the URL in URL mode; passing them again
+ # through OPTIONS risks one of them winning over the other.
+ _cache_options["DB"] = _cache_db
+ _cache_options["USERNAME"] = REDIS_USER
+ _cache_options["PASSWORD"] = REDIS_PASSWORD
+ # Gated on the EFFECTIVE scheme, not the flag. In URL mode TLS is carried by
+ # the URL (and its query string), so a plaintext REDIS_URL left behind while
+ # REDIS_SSL=true would otherwise hand ssl_cert_reqs to a plain
+ # redis.Connection — TypeError on the first cache read in a request, not at
+ # startup. Same trap the pooled standalone client hits, inverted.
+ if REDIS_SSL and not _redis_url:
+ _pool_kwargs = {"ssl_cert_reqs": REDIS_SSL_CERT_REQS}
+ # redis-py defaults ssl_check_hostname to False and overrides
+ # create_default_context()'s safe default with it, so a chain verified
+ # against a public CA still does not prove WHICH server answered. Forced
+ # off when verification itself is off, or Python's ssl module raises.
+ if REDIS_SSL_CERT_REQS != "none":
+ _pool_kwargs["ssl_check_hostname"] = REDIS_SSL_CHECK_HOSTNAME
+ if REDIS_SSL_CA_CERTS:
+ _pool_kwargs["ssl_ca_certs"] = REDIS_SSL_CA_CERTS
+ _cache_options["CONNECTION_POOL_KWARGS"] = _pool_kwargs
+
+ # Fires whenever the keyspace actually MOVES. Before the rule above reached
+ # URL mode this was gated on `not _redis_url`, so the one mode that could now
+ # relocate a live cache was the one mode that said nothing.
+ #
+ # Both sides have to be the EFFECTIVE db, not REDIS_DB: in URL mode with
+ # REDIS_DB unset the URL's own path stands, so comparing it against
+ # _cache_db's 0 default announced a move that never happens — a warning
+ # about data loss on a perfectly ordinary `redis://h/3`.
+ _previous_db = (_url_db or 0) if REDIS_URL else 0
+ _effective_db = _cache_db if (REDIS_DB or not REDIS_URL) else _previous_db
+ if _effective_db != _previous_db:
+ # Visible in the field, because this is a one-way RELOCATION of the whole
+ # CACHES["default"] keyspace. django-redis 5.4.0 ignores OPTIONS["DB"], so
+ # this cache has always sat on db 0 no matter what REDIS_DB said; carrying
+ # the db in the LOCATION path is the fix, but it MOVES live data. What
+ # moves is not only cache — CacheService wraps
+ # get_redis_connection("default"), so log_history_queue, the rate-limit
+ # counters and the dashboard caches go with it, and during a rolling
+ # deploy old pods read db 0 while new pods read db N. Drain
+ # log_history_queue before cutting over.
+ logging.getLogger(__name__).warning(
+ "Django cache is moving from Redis db %s to db %s (REDIS_DB). In "
+ "discrete mode it previously sat on db 0 regardless, because "
+ "django-redis ignores OPTIONS['DB']. Anything already in db %s — "
+ "including log_history_queue — stays there.",
+ _previous_db,
+ _effective_db,
+ _previous_db,
+ )
+
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
- "LOCATION": f"redis://{REDIS_HOST}:{REDIS_PORT}",
- "OPTIONS": {
- "CLIENT_CLASS": "django_redis.client.DefaultClient",
- "SERIALIZER": "django_redis.serializers.json.JSONSerializer",
- "DB": int(REDIS_DB) if REDIS_DB else 0,
- "USERNAME": REDIS_USER,
- "PASSWORD": REDIS_PASSWORD,
- },
+ "LOCATION": _redis_url
+ or f"{_scheme}://{REDIS_HOST}:{REDIS_PORT}/{_cache_db}",
+ "OPTIONS": _cache_options,
"KEY_FUNCTION": "utils.redis_cache.custom_key_function",
}
}
diff --git a/backend/backend/tests/test_redis_settings_derivation.py b/backend/backend/tests/test_redis_settings_derivation.py
new file mode 100644
index 000000000..67d3aa0d7
--- /dev/null
+++ b/backend/backend/tests/test_redis_settings_derivation.py
@@ -0,0 +1,440 @@
+"""How the Redis settings block derives its URLs (UN-4123).
+
+The block lives inside ``settings/base.py`` and runs at import, so it cannot be
+called directly; these tests execute that exact source range against a controlled
+environment instead of re-implementing it, which would test a copy rather than
+the thing that ships.
+
+The case that matters is REDIS_URL, because the failure it prevents is silent.
+If this module built its own URL from REDIS_HOST/REDIS_PORT while
+`create_redis_client` honoured REDIS_URL, the workers would follow the configured
+endpoint and the backend would stay behind — and nothing would error. The API
+deployment simply returns ``result: null``, because the execution's cached result
+was written to one Redis and looked up in the other. That shape was found on a
+live run against a managed endpoint, not by reading the code, which is why these
+tests execute the shipping source rather than a copy of it.
+"""
+
+from __future__ import annotations
+
+import logging
+import pathlib
+
+import pytest
+
+_SETTINGS = pathlib.Path(__file__).resolve().parents[1] / "settings" / "base.py"
+
+
+def _derive(**env: str) -> dict:
+ """Execute the standalone Redis block with the given env."""
+ source = _SETTINGS.read_text()
+ # TWO slices of the shipping file, no hand-written copies. The variable
+ # DEFINITIONS (REDIS_USER … REDIS_URL) live ~400 lines above the derivation
+ # block. Duplicating them in the prelude would mean the definitions never
+ # execute: a mutation to any of them (a flipped REDIS_SSL default, a typo'd
+ # REDIS_URI) leaves the suite green while the hand-written copy under test
+ # stays correct. Both ranges therefore come from source.
+ defs_start = source.index('REDIS_USER = os.environ.get("REDIS_USER"')
+ defs_end = (
+ source.index("\n", source.index('REDIS_URL = os.environ.get("REDIS_URL"')) + 1
+ )
+ start = source.index("REDIS_SENTINEL_MODE = (")
+ end = source.index("SESSION_ENGINE =")
+
+ # THREE slices, still no hand-written copies. The unstract.core import list is
+ # spliced rather than retyped: a hand-written copy meant that every name the
+ # settings module started importing had to be remembered here too, and the
+ # symptom was fourteen NameErrors rather than one clear failure. The Socket.IO
+ # URL and the TLS/db helpers are built by unstract.core so the backend and the
+ # log-consumer worker cannot drift; their own cases live in
+ # unstract/core/tests/test_redis_client_config.py.
+ imports_start = source.index("from unstract.core.cache.redis_client import (")
+ imports_end = source.index(")\n", imports_start) + 2
+
+ # __name__ is what the relocation warning's logging.getLogger(__name__) reads;
+ # without it that branch raises NameError instead of logging, which is part of
+ # why it went untested.
+ ns: dict = {"__name__": "backend.settings.base"}
+ prelude = (
+ "import logging\n"
+ "import os\n"
+ "from urllib.parse import quote\n" + source[imports_start:imports_end]
+ ) + source[defs_start:defs_end]
+ import os as _os
+
+ saved = {k: _os.environ.get(k) for k in list(_os.environ) if "REDIS" in k}
+ for key in saved:
+ _os.environ.pop(key, None)
+ _os.environ.update(env)
+ try:
+ exec(prelude + source[start:end], ns) # noqa: S102 - the code under test
+ finally:
+ for key in list(_os.environ):
+ if "REDIS" in key:
+ _os.environ.pop(key, None)
+ _os.environ.update({k: v for k, v in saved.items() if v is not None})
+ return ns
+
+
+def plain() -> dict:
+ return _derive(REDIS_HOST="unstract-redis", REDIS_PORT="6379")
+
+
+class TestDiscreteVars:
+ def test_plaintext_is_unchanged(self, plain):
+ assert plain["CACHES"]["default"]["LOCATION"] == "redis://unstract-redis:6379/0"
+ assert "CONNECTION_POOL_KWARGS" not in plain["CACHES"]["default"]["OPTIONS"]
+
+ def test_the_password_reaches_the_cache(self):
+ """Discrete mode is the ONLY path where the password travels in OPTIONS.
+
+ In URL mode it rides inside the URL. Dropping this assignment left the
+ whole suite green while the Django cache authenticated as nobody against
+ a password-protected Redis — every read and write failing at runtime,
+ nothing failing at import. This block is now built conditionally, so the
+ credentials are newly reachable-or-not depending on a branch.
+ """
+ derived = _derive(REDIS_HOST="h", REDIS_PASSWORD="s3cret")
+ assert derived["CACHES"]["default"]["OPTIONS"]["PASSWORD"] == "s3cret"
+
+ def test_db_and_username_are_passed_through_options(self):
+ """Pins the stated invariant so a django-redis bump is visible.
+
+ The comment beside this code says USERNAME is deliberately not honoured —
+ django-redis 5.4.0 discards it, so auth stays password-only as the
+ built-in `default` user. That holds by accident of the pinned version:
+ these assertions pin what the settings SEND, so if a bump starts reading
+ USERNAME the change is a deliberate one rather than a surprise.
+ """
+ options = _derive(REDIS_HOST="h", REDIS_DB="3", REDIS_USER="alice")["CACHES"][
+ "default"
+ ]["OPTIONS"]
+ assert options["DB"] == 3
+ assert options["USERNAME"] == "alice"
+
+ def test_url_mode_does_not_duplicate_credentials_into_options(self):
+ """They travel in the URL; passing both risks one winning over the other."""
+ options = _derive(REDIS_URL="redis://:pw@h:6379/2")["CACHES"]["default"][
+ "OPTIONS"
+ ]
+ assert "PASSWORD" not in options
+ assert "USERNAME" not in options
+ assert "DB" not in options
+
+ def test_db_travels_in_the_location(self):
+ """django-redis 5.4.0 ignores OPTIONS['DB'], so the path is the only route.
+
+ Without it this cache sits on db 0 while every other service honours
+ REDIS_DB — workers RPUSH log_history_queue to db N and the backend LPOPs
+ an empty db 0.
+ """
+ derived = _derive(REDIS_HOST="h", REDIS_DB="3")
+ assert derived["CACHES"]["default"]["LOCATION"].endswith("/3")
+
+ def test_ssl_switches_scheme_and_pool_kwargs(self):
+ derived = _derive(REDIS_HOST="h", REDIS_SSL="true", REDIS_SSL_CA_CERTS="/ca.pem")
+ cache = derived["CACHES"]["default"]
+ assert cache["LOCATION"].startswith("rediss://")
+ assert cache["OPTIONS"]["CONNECTION_POOL_KWARGS"] == {
+ "ssl_cert_reqs": "required",
+ "ssl_check_hostname": True,
+ "ssl_ca_certs": "/ca.pem",
+ }
+
+ def test_hostname_verification_is_on_by_default(self):
+ """redis-py defaults it to False and overrides ssl's safe default with it.
+
+ A chain verified against a public CA proves nothing about WHICH server
+ answered, which is the ElastiCache/Azure case this work targets.
+ """
+ derived = _derive(REDIS_HOST="h", REDIS_SSL="true")
+ pool = derived["CACHES"]["default"]["OPTIONS"]["CONNECTION_POOL_KWARGS"]
+ assert pool["ssl_check_hostname"] is True
+
+ def test_hostname_verification_is_forced_off_when_verification_is_off(self):
+ """Python's ssl raises if check_hostname is True while verify_mode is NONE."""
+ derived = _derive(REDIS_HOST="h", REDIS_SSL="true", REDIS_SSL_CERT_REQS="none")
+ pool = derived["CACHES"]["default"]["OPTIONS"]["CONNECTION_POOL_KWARGS"]
+ assert "ssl_check_hostname" not in pool
+
+
+class TestUrlMode:
+ def test_url_drives_the_cache(self):
+ """The silent split: a cache that ignores REDIS_URL while the workers honour it."""
+ url = "rediss://:[email protected]:6380/0?ssl_cert_reqs=required"
+ derived = _derive(REDIS_HOST="in-cluster", REDIS_URL=url)
+ assert derived["CACHES"]["default"]["LOCATION"].startswith(url)
+ assert "in-cluster" not in derived["CACHES"]["default"]["LOCATION"]
+
+ def test_credentials_are_not_passed_twice(self):
+ """In URL mode the URL is the single source for db and credentials."""
+ derived = _derive(REDIS_URL="rediss://:pw@h:6380/2", REDIS_PASSWORD="other")
+ options = derived["CACHES"]["default"]["OPTIONS"]
+ assert "PASSWORD" not in options
+ assert "DB" not in options
+
+ def test_ca_is_appended_for_tls_urls(self):
+ derived = _derive(
+ REDIS_URL="rediss://h:6380/0?ssl_cert_reqs=required",
+ REDIS_SSL_CA_CERTS="/etc/ssl/redis-ca.pem",
+ )
+ assert (
+ "ssl_ca_certs=/etc/ssl/redis-ca.pem"
+ in (derived["CACHES"]["default"]["LOCATION"])
+ )
+
+ def test_ca_is_not_appended_to_a_plaintext_url(self):
+ derived = _derive(
+ REDIS_URL="redis://h:6379/0", REDIS_SSL_CA_CERTS="/etc/ssl/redis-ca.pem"
+ )
+ assert "ssl_ca_certs" not in derived["CACHES"]["default"]["LOCATION"]
+
+ def test_an_explicit_ca_in_the_url_wins(self):
+ derived = _derive(
+ REDIS_URL="rediss://h:6380/0?ssl_ca_certs=/in/url.pem",
+ REDIS_SSL_CA_CERTS="/env/ca.pem",
+ )
+ location = derived["CACHES"]["default"]["LOCATION"]
+ assert location.count("ssl_ca_certs") == 1
+ assert "/in/url.pem" in location
+
+
+class TestSchemeFlagMismatch:
+ """REDIS_SSL=true left beside an older plaintext REDIS_URL.
+
+ The URL wins for the connection, so the flag alone must not decide the pool
+ kwargs: ssl_cert_reqs reaching a plain redis.Connection is a TypeError on the
+ first cache read in a request, not at startup.
+ """
+
+ def test_a_plaintext_url_does_not_get_tls_pool_kwargs(self):
+ derived = _derive(REDIS_URL="redis://h:6379/0", REDIS_SSL="true")
+ cache = derived["CACHES"]["default"]
+ assert cache["LOCATION"] == "redis://h:6379/0"
+ assert "CONNECTION_POOL_KWARGS" not in cache["OPTIONS"]
+
+ def test_a_rediss_url_still_needs_none_of_them(self):
+ """TLS travels in the URL and its query string in URL mode."""
+ derived = _derive(REDIS_URL="rediss://h:6380/0", REDIS_SSL="true")
+ assert "CONNECTION_POOL_KWARGS" not in derived["CACHES"]["default"]["OPTIONS"]
+ # ...and it is genuinely THERE. Asserting only the absence of the pool
+ # kwargs let the whole URL-mode TLS query go untested: setting
+ # check_hostname to None kept CI green while restoring redis-py's
+ # unauthenticated default on the Django cache.
+ location = derived["CACHES"]["default"]["LOCATION"]
+ assert "ssl_cert_reqs=required" in location
+ assert "ssl_check_hostname=true" in location
+
+
+class TestUrlModeTlsQuery:
+ """django-redis takes a LOCATION string, so URL mode's ONLY lever is the query.
+
+ redis-py defaults ssl_check_hostname to False and overrides
+ create_default_context()'s safe default with it, so a rediss:// LOCATION that
+ carries neither key is encrypted but never authenticates the server.
+ """
+
+ def _location(self, **env: str) -> str:
+ return _derive(**env)["CACHES"]["default"]["LOCATION"]
+
+ def test_a_bare_tls_url_gains_both_keys(self):
+ location = self._location(REDIS_URL="rediss://h:6380/0")
+ assert "ssl_cert_reqs=required" in location
+ assert "ssl_check_hostname=true" in location
+
+ def test_hostname_verification_can_be_turned_off(self):
+ """The documented escape hatch for a certificate with no matching SAN."""
+ location = self._location(
+ REDIS_URL="rediss://h:6380/0", REDIS_SSL_CHECK_HOSTNAME="false"
+ )
+ assert "ssl_check_hostname=false" in location
+
+ @pytest.mark.parametrize("raw", ["", " "])
+ def test_a_blank_escape_hatch_keeps_the_secure_default(self, raw):
+ """`FOO=` is this repo's "leave the default"; a bare == "true" read it
+ as False and silently dropped server authentication.
+ """
+ location = self._location(
+ REDIS_URL="rediss://h:6380/0", REDIS_SSL_CHECK_HOSTNAME=raw
+ )
+ assert "ssl_check_hostname=true" in location
+
+ def test_cert_reqs_none_in_the_url_suppresses_hostname_checking(self):
+ """Python's ssl module refuses the pair — this LOCATION would make every
+ cache read raise ValueError, and it is the form the TLS README documents.
+ """
+ location = self._location(REDIS_URL="rediss://h:6380/0?ssl_cert_reqs=none")
+ assert "ssl_check_hostname" not in location
+
+ def test_cert_reqs_none_in_the_env_suppresses_it_too(self):
+ location = self._location(
+ REDIS_URL="rediss://h:6380/0", REDIS_SSL_CERT_REQS="none"
+ )
+ assert "ssl_cert_reqs=none" in location
+ assert "ssl_check_hostname" not in location
+
+ def test_a_plaintext_url_gains_no_tls_query(self):
+ assert self._location(REDIS_URL="redis://h:6379/0") == "redis://h:6379/0"
+
+
+class TestTheDatabaseRuleReachesTheCache:
+ """One REDIS_URL + one REDIS_DB must mean one database, backend and workers.
+
+ django-redis ignores OPTIONS["DB"], so the LOCATION path is the only lever.
+ Without it the backend followed the URL's own path while create_redis_client
+ honoured REDIS_DB: workers RPUSH log_history_queue to db N, the backend LPOPs
+ an empty db 0, and nothing errors.
+ """
+
+ def _location(self, **env: str) -> str:
+ return _derive(**env)["CACHES"]["default"]["LOCATION"]
+
+ def test_redis_db_rewrites_the_url_path(self):
+ assert self._location(REDIS_URL="rediss://h:6380/0", REDIS_DB="2").startswith(
+ "rediss://h:6380/2"
+ )
+
+ def test_the_url_path_stands_when_no_db_is_set(self):
+ assert self._location(REDIS_URL="rediss://h:6380/3").startswith(
+ "rediss://h:6380/3"
+ )
+
+ def test_a_pathless_url_gains_the_db(self):
+ assert self._location(REDIS_URL="rediss://h:6380", REDIS_DB="4").startswith(
+ "rediss://h:6380/4"
+ )
+
+ def test_the_tls_query_survives_the_rewrite(self):
+ location = self._location(
+ REDIS_URL="rediss://h:6380/0?ssl_ca_certs=/ca.pem", REDIS_DB="1"
+ )
+ assert location.startswith("rediss://h:6380/1")
+ assert "ssl_ca_certs=/ca.pem" in location
+
+ def test_it_matches_what_create_redis_client_resolves(self):
+ """The two must not merely both be right today — same helper, same rule."""
+ import os as _os
+
+ from unstract.core.cache.redis_client import create_redis_client, url_db_path
+
+ env = {"REDIS_URL": "redis://h:6379/0", "REDIS_DB": "5"}
+ saved = {k: _os.environ.get(k) for k in list(_os.environ) if "REDIS" in k}
+ for key in saved:
+ _os.environ.pop(key, None)
+ _os.environ.update(env)
+ try:
+ client_db = create_redis_client().connection_pool.connection_kwargs["db"]
+ finally:
+ for key in list(_os.environ):
+ if "REDIS" in key:
+ _os.environ.pop(key, None)
+ _os.environ.update({k: v for k, v in saved.items() if v is not None})
+ assert url_db_path(self._location(**env)) == client_db == 5
+
+
+class TestTheRelocationWarning:
+ """It exists purely to be SEEN — a one-way move of a live keyspace.
+
+ CacheService wraps get_redis_connection("default"), so log_history_queue, the
+ rate-limit counters and the dashboard caches move with it, and during a
+ rolling deploy old pods read the old db while new pods read the new one.
+ Nothing else in the process announces that.
+ """
+
+ def test_it_fires_when_the_discrete_cache_moves_off_db_0(self, caplog):
+ with caplog.at_level(logging.WARNING):
+ _derive(REDIS_HOST="h", REDIS_DB="2")
+ assert "moving from Redis db 0 to db 2" in caplog.text
+
+ def test_it_fires_when_a_url_mode_cache_moves(self, caplog):
+ """The mode that could newly relocate was the one that said nothing."""
+ with caplog.at_level(logging.WARNING):
+ _derive(REDIS_URL="redis://h:6379/1", REDIS_DB="2")
+ assert "moving from Redis db 1 to db 2" in caplog.text
+
+ def test_it_stays_quiet_when_nothing_moves(self, caplog):
+ with caplog.at_level(logging.WARNING):
+ _derive(REDIS_URL="redis://h:6379/3")
+ _derive(REDIS_HOST="h")
+ assert "moving" not in caplog.text
+
+
+class TestTheBackendUsesTheSharedParsers:
+ """The backend must not re-implement what unstract.core already resolves.
+
+ Every one of these survived the suite until it was pinned, and each is a case
+ where the backend and create_redis_client would give different answers for the
+ same environment — the divergence class this whole change exists to remove.
+ """
+
+ def test_cert_reqs_is_normalised(self):
+ """`REQUIRED` / ` none ` reached redis-py verbatim before."""
+ location = _derive(REDIS_URL="rediss://h:6380/0", REDIS_SSL_CERT_REQS="NONE")[
+ "CACHES"
+ ]["default"]["LOCATION"]
+ assert "ssl_cert_reqs=none" in location
+ # ...and the normalised value must still drive the suppression, or the
+ # LOCATION carries the pair ssl refuses.
+ assert "ssl_check_hostname" not in location
+
+ def test_an_invalid_cert_reqs_falls_back_rather_than_shipping_it(self):
+ location = _derive(REDIS_URL="rediss://h:6380/0", REDIS_SSL_CERT_REQS="strict")[
+ "CACHES"
+ ]["default"]["LOCATION"]
+ assert "ssl_cert_reqs=required" in location
+
+ def test_an_unparseable_redis_db_warns_instead_of_killing_the_process(self, caplog):
+ """create_redis_client warns and continues on db 0; so must this.
+
+ `int(REDIS_DB)` here meant the workers kept running while the backend
+ refused to start on the same value.
+ """
+ with caplog.at_level(logging.WARNING):
+ derived = _derive(REDIS_HOST="h", REDIS_DB="one")
+ assert derived["CACHES"]["default"]["LOCATION"] == "redis://h:6379/0"
+ assert "REDIS_DB" in caplog.text
+
+ def test_a_whitespace_only_redis_db_is_unset_and_SILENT(self, caplog):
+ """This is the case that pins parse_db's own .strip().
+
+ _resolve_redis_env strips before it calls parse_db, so through
+ create_redis_client that strip is unreachable — but this module reads
+ `os.environ.get("REDIS_DB", "")` raw, so it is the only caller where it
+ does anything. Without it a whitespace-only value is not "unset" but
+ "unparseable", and the backend warns on every boot about a variable the
+ operator left blank.
+ """
+ with caplog.at_level(logging.WARNING):
+ derived = _derive(REDIS_HOST="h", REDIS_DB=" ")
+ assert derived["CACHES"]["default"]["LOCATION"] == "redis://h:6379/0"
+ assert "REDIS_DB" not in caplog.text
+
+ def test_no_database_var_is_parsed_with_a_bare_int(self):
+ """Covers the sites the exec harness cannot reach.
+
+ FILE_ACTIVE_CACHE_REDIS_DB is defined ~350 lines above the derivation
+ block, outside both slices, so no _derive() case can observe it. A source
+ check reaches it — and reaches the other two at the same time, which is
+ the point: the defect was never one line, it was the same expression
+ repeated wherever a database var is read.
+
+ `int(os.environ.get("FILE_ACTIVE_CACHE_REDIS_DB", 0))` and
+ `int(REDIS_DB)` both raise on a blank or malformed value, taking the
+ process down at import — while create_redis_client, two imports away,
+ warns and continues on db 0 for the very same variable.
+ """
+ source = _SETTINGS.read_text()
+ offenders = [
+ line.strip()
+ for line in source.splitlines()
+ if "int(" in line
+ and "REDIS_DB" in line
+ and "parse_db" not in line
+ and not line.strip().startswith("#")
+ ]
+ assert not offenders, (
+ f"{offenders} parse a Redis database with a bare int(); use "
+ "unstract.core.cache.redis_client.parse_db so the backend and the "
+ "workers agree on a malformed value."
+ )
diff --git a/backend/sample.env b/backend/sample.env
index 700422d1a..daea19134 100644
--- a/backend/sample.env
+++ b/backend/sample.env
@@ -53,6 +53,48 @@ REDIS_RETRY_BACKOFF_FACTOR=0.5
REDIS_SENTINEL_MODE=False
REDIS_SENTINEL_MASTER_NAME=mymaster
+# Managed / external Redis with TLS (UN-4123). All optional — unset means the
+# plaintext connection this file otherwise describes, unchanged.
+#
+# Two ways to configure it, pick one:
+# 1. Discrete vars (what the Helm chart and these samples use). Set REDIS_SSL=true
+# alongside REDIS_HOST/REDIS_PORT. No URL-encoding to get wrong.
+# 2. REDIS_URL, where the SCHEME carries TLS and nothing else is needed:
+# REDIS_URL=rediss://:<password>@<host>:6380/0?ssl_cert_reqs=required
+# (6380 is an EXAMPLE, not a default — the TLS port is provider-specific:
+# Memorystore 6378, ElastiCache 6379, Azure Cache 6380. A wrong port
+# hangs the connection rather than erroring, so read it off the instance.)
+# A URL wins over the discrete vars above. Percent-encode @ / + in the password.
+#
+# Auth is password-only, as Redis's built-in `default` user — that is what a managed
+# AUTH string is. Leave REDIS_USER empty for a managed endpoint; named ACL users are
+# not supported platform-wide.
+#
+# REDIS_SSL_CA_CERTS is only needed when the server's CA is not in the system trust
+# store (Memorystore). ElastiCache and Azure Cache chain to public CAs.
+# REDIS_SSL=false
+# REDIS_SSL_CERT_REQS=required
+# REDIS_SSL_CA_CERTS=
+#
+# Hostname verification is ON by default (UN-4123): a chain verified against a
+# public CA still says nothing about WHICH server answered. Set this to false for
+# an endpoint whose certificate does not cover how you address it — an IP, or an
+# internal CNAME. Forced off anyway when REDIS_SSL_CERT_REQS=none. Sentinel MASTER
+# connections skip it by default, because Sentinel returns an IP that no DNS
+# SAN covers and that changes on failover.
+# Shown as `false` because that is the only value there is a reason to set:
+# `true` is already the default, and setting it EXPLICITLY is not a no-op —
+# an explicit value is honoured on Sentinel MASTER connections too, turning
+# the compatibility default above back off.
+# REDIS_SSL_CHECK_HOSTNAME=false
+# REDIS_URL=
+
+# Proactive health check for pooled connections, in seconds (0 disables).
+# Managed Redis fails over during maintenance and reaps idle connections — Azure
+# Cache closes them at 10 minutes — so a parked connection can be dead before its
+# next command. Defaults to 30.
+# REDIS_HEALTH_CHECK_INTERVAL=30
+
# Connector OAuth
SOCIAL_AUTH_EXTRA_DATA_EXPIRATION_TIME_IN_SECOND=3600
GOOGLE_OAUTH2_KEY=
diff --git a/docker/docker-compose-redis-tls.yaml b/docker/docker-compose-redis-tls.yaml
new file mode 100644
index 000000000..1c2604508
--- /dev/null
+++ b/docker/docker-compose-redis-tls.yaml
@@ -0,0 +1,69 @@
+# A stand-in for a managed Redis, for local development only (UN-4123).
+#
+# Managed offerings differ from the plain dev Redis in exactly two ways that our
+# code has to cope with: they require AUTH, and they speak TLS. This container
+# does both, so the TLS path can be exercised end to end — execution, log
+# streaming, tool sidecars — without cloud access or a VPN.
+#
+# It runs ALONGSIDE the normal `unstract-redis`, on a different port, so nothing
+# switches until you point services at it. That is deliberate: the point of the
+# exercise is to flip between the two and confirm BOTH work.
+#
+# ./redis-tls/generate-certs.sh
+# docker compose -f docker-compose-redis-tls.yaml up -d
+#
+# See redis-tls/README.md for the env to set and what to verify.
+services:
+ redis-managed:
+ image: "redis:7.2.3"
+ container_name: unstract-redis-managed
+ restart: unless-stopped
+ # `--port 0` disables the plaintext listener entirely, which is what Azure
+ # Cache does by default. A service that fails to pick up the TLS settings
+ # therefore cannot quietly succeed over plaintext and hide the bug.
+ #
+ # `--tls-auth-clients no` mirrors the managed services: the client verifies
+ # the server, not the other way round. No mTLS, no client certs to ship.
+ command: >
+ redis-server
+ --port 0
+ --tls-port 6380
+ --tls-cert-file /certs/server.crt
+ --tls-key-file /certs/server.key
+ --tls-ca-cert-file /certs/ca.crt
+ --tls-auth-clients no
+ --requirepass ${REDIS_DEV_PASSWORD:-devpassword}
+ --loglevel notice
+ ports:
+ # Same port inside and out, so one hostname:port works from containers
+ # (unstract-redis-managed:6380) and from a backend on the host
+ # (localhost:6380).
+ - "6380:6380"
+ volumes:
+ - ./redis-tls/certs:/certs:ro
+ - redis_managed_data:/data
+ healthcheck:
+ test:
+ [
+ "CMD",
+ "redis-cli",
+ "--tls",
+ "-p", "6380",
+ "--cacert", "/certs/ca.crt",
+ "-a", "${REDIS_DEV_PASSWORD:-devpassword}",
+ "--no-auth-warning",
+ "ping",
+ ]
+ interval: 10s
+ timeout: 5s
+ retries: 5
+ labels:
+ - traefik.enable=false
+
+volumes:
+ redis_managed_data:
+
+networks:
+ default:
+ name: unstract-network
+ external: true
diff --git a/docker/redis-tls/.gitignore b/docker/redis-tls/.gitignore
new file mode 100644
index 000000000..e63f64c5c
--- /dev/null
+++ b/docker/redis-tls/.gitignore
@@ -0,0 +1,2 @@
+# Dev-only self-signed material, regenerated by generate-certs.sh.
+certs/
diff --git a/docker/redis-tls/README.md b/docker/redis-tls/README.md
new file mode 100644
index 000000000..2b982fcb4
--- /dev/null
+++ b/docker/redis-tls/README.md
@@ -0,0 +1,162 @@
+# Testing against a managed-like Redis locally (UN-4123)
+
+A managed Redis (Memorystore, ElastiCache, Azure Cache) differs from the dev Redis
+in exactly two ways our code has to handle: it **requires AUTH** and it **speaks
+TLS**. `docker-compose-redis-tls.yaml` runs a Redis that does both, so the TLS path
+can be exercised without cloud access or a VPN.
+
+It runs **alongside** the normal `unstract-redis` on port 6380, so nothing switches
+until you point services at it — the point of the exercise is to flip between the
+two and confirm both work.
+
+Its plaintext listener is disabled (`--port 0`), the same as Azure Cache's default.
+A service that fails to pick up the TLS settings therefore *cannot* quietly succeed
+over plaintext and hide the bug.
+
+## Start it
+
+```bash
+cd docker
+./redis-tls/generate-certs.sh
+docker compose -f docker-compose-redis-tls.yaml up -d
+```
+
+Certificates are self-signed and dev-only. The SAN list covers both names the same
+server answers to — `unstract-redis-managed` from inside the network,
+`localhost` from a backend on the host — because a certificate valid for only one
+fails verification from the other side, which looks like a code bug and is not one.
+
+Confirm it is up, and that plaintext is refused:
+
+```bash
+docker exec unstract-redis-managed redis-cli --tls -p 6380 \
+ --cacert /certs/ca.crt -a devpassword --no-auth-warning ping # PONG
+docker exec unstract-redis-managed redis-cli -p 6380 \
+ -a devpassword --no-auth-warning ping # I/O error
+```
+
+## Switch the platform onto it
+
+Two values differ by where the process runs: containers reach it as
+`unstract-redis-managed:6380`, a backend on the host as `localhost:6380`.
+
+**`backend/.env`** (runs on the host):
+
+```bash
+REDIS_URL=rediss://:devpassword@localhost:6380/0?ssl_cert_reqs=required
+REDIS_SSL_CA_CERTS=/abs/path/to/unstract/docker/redis-tls/certs/ca.crt
+```
+
+**`workers/.env`, `platform-service/.env`** (containers):
+
+```bash
+REDIS_URL=rediss://:devpassword@unstract-redis-managed:6380/0?ssl_cert_reqs=required
+REDIS_SSL_CA_CERTS=/certs/ca.crt
+CACHE_REDIS_URL=rediss://:devpassword@unstract-redis-managed:6380/1?ssl_cert_reqs=required
+CACHE_REDIS_DB=1
+```
+
+**`CACHE_REDIS_DB=1` is not optional here**, even though the URL already says
+`/1`. A `.env` copied from `workers/sample.env` carries `CACHE_REDIS_DB=0`
+uncommented, and an explicitly-set `{prefix}DB` beats the URL's path — so without
+this line the cache lands on db 0 and the recipe below breaks in exactly the way
+the next paragraph warns about. (Commenting `CACHE_REDIS_DB` out works too and
+lets the `/1` stand; setting it is the less surprising of the two.)
+
+The `/1` matters, and so does its partner. The workers write `file_active:*`
+through the `CACHE_REDIS_` client, and the BACKEND reads and clears those keys
+using `FILE_ACTIVE_CACHE_REDIS_DB` — which defaults to `0`. Leave it at the
+default beside the `/1` above and the two sit on different databases: active-file
+dedup finds nothing, every file is reprocessed as new, and nothing errors. That is
+the failure `workers/sample.env` warns about, so add this to `backend/.env`:
+
+```bash
+FILE_ACTIVE_CACHE_REDIS_DB=1
+```
+
+(Or put the cache on `/0` and leave both at the default. Either is fine; only the
+mismatch is not, and this recipe deliberately keeps them apart so the two-database
+layout is exercised.)
+
+Those containers need the CA mounted. Add to your `docker/compose.override.yaml`:
+
+```yaml
+services:
+ worker-pg-orchestrator-general: # repeat for each worker + platform-service
+ volumes:
+ - ./redis-tls/certs:/certs:ro
+```
+
+**`runner/.env`** — one deliberate difference:
+
+```bash
+REDIS_URL=rediss://:devpassword@unstract-redis-managed:6380/0
+REDIS_SSL_CERT_REQS=none
+```
+
+The runner forwards these to each **tool sidecar** it spawns, and sidecars get no
+CA mount — the runner builds their environment as an allowlist and mounts only the
+shared log dir. `none` keeps the connection encrypted while skipping verification,
+which still exercises the forwarding fix and the TLS handshake.
+
+`REDIS_SSL_CERT_REQS` is honoured **alongside** a URL: the setting is resolved
+once, with the generic fallback, and applied to `rediss://` URLs that carry no
+`ssl_cert_reqs=` of their own. Putting it in the URL works too and wins if both
+are set: `rediss://:devpassword@unstract-redis-managed:6380/0?ssl_cert_reqs=none`.
+
+Hostname verification follows the same setting, **whichever way it is set** — it
+is forced off when verification is off, and on otherwise. That has to hold for
+the in-URL form as well, because Python's `ssl` module raises
+`Cannot set verify_mode to CERT_NONE when check_hostname is enabled` rather than
+degrading: the two together are not a weaker connection, they are no connection
+at all, on the first command. The dev certificate carries SANs for
+`unstract-redis-managed`, `localhost` and `127.0.0.1`, so `required` works from
+containers and from the host without further configuration. Against a real
+managed endpoint this does not arise: ElastiCache and Azure chain to public CAs, and
+for Memorystore you would mount its CA into the sidecar image. If an endpoint's
+certificate does not cover how you address it — an IP, or an internal CNAME —
+`REDIS_SSL_CHECK_HOSTNAME=false` keeps verification of the chain while skipping
+the name check. Sentinel MASTER connections skip it by default, because Sentinel
+hands back an IP that no DNS SAN covers and that changes on failover.
+
+Then restart: `docker compose restart` for the containers, and your usual manual
+restart for the backend.
+
+## What to check
+
+1. **An execution completes.** Include a workflow that uses a **container-based
+ tool** (classifier or text_extractor) — a Prompt Studio structure tool runs
+ in-process in the executor and never spawns a sidecar, so it leaves the whole
+ sidecar path untested.
+2. **Logs stream in the UI and land in `execution_log`.** That is the Redis-list
+ transport end to end, the part with no unit-test coverage.
+3. **The keys are in the new server, and the old one is idle:**
+
+ ```bash
+ docker exec unstract-redis-managed redis-cli --tls -p 6380 \
+ --cacert /certs/ca.crt -a devpassword --no-auth-warning dbsize
+ docker exec unstract-redis redis-cli dbsize # should not be growing
+ ```
+
+4. **Nothing fell back to plaintext.** The TLS-only listener makes this
+ self-enforcing: a component that missed the settings fails loudly instead.
+
+## Switch back
+
+Remove the `REDIS_URL` / `REDIS_SSL_*` lines, restart, and run the same execution
+again. Both modes are supported and both must pass — that is the acceptance bar,
+not just "TLS works".
+
+## Against a real managed Redis
+
+Same env, different endpoint. Memorystore is VPC-private, so from a laptop it needs
+a tunnel:
+
+```bash
+gcloud compute ssh <bastion> -- -L 6380:<memorystore-ip>:6379
+REDIS_URL=rediss://:<auth-string>@localhost:6380/0?ssl_cert_reqs=required
+```
+
+Drop the `rediss` to `redis` when the instance has TLS disabled — an AUTH string
+without in-transit encryption is a supported configuration and worth testing too,
+since it is what a VPC-internal deployment may well run.
diff --git a/docker/redis-tls/generate-certs.sh b/docker/redis-tls/generate-certs.sh
new file mode 100755
index 000000000..f43e260e3
--- /dev/null
+++ b/docker/redis-tls/generate-certs.sh
@@ -0,0 +1,44 @@
+#!/usr/bin/env bash
+# Self-signed CA + server certificate for the local TLS Redis (UN-4123).
+#
+# Only for local development: it stands in for a managed Redis endpoint so the
+# TLS path can be exercised without cloud access or a VPN. Never use these
+# anywhere else — the private keys are written unencrypted, right here.
+#
+# The SAN list covers both names the same server answers to: containers reach it
+# as `unstract-redis-managed`, while a backend running on the host reaches the
+# published port as `localhost`. A certificate valid for only one of them fails
+# verification from the other side, which looks like a code bug and is not one.
+set -euo pipefail
+
+CERT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/certs"
+mkdir -p "$CERT_DIR"
+cd "$CERT_DIR"
+
+if [[ -f server.crt && "${FORCE:-}" != "1" ]]; then
+ echo "Certificates already exist in $CERT_DIR (FORCE=1 to regenerate)."
+ exit 0
+fi
+
+openssl genrsa -out ca.key 4096 2>/dev/null
+openssl req -x509 -new -nodes -key ca.key -sha256 -days 825 -out ca.crt \
+ -subj "/CN=Unstract Local Redis Dev CA" 2>/dev/null
+
+openssl genrsa -out server.key 2048 2>/dev/null
+openssl req -new -key server.key -out server.csr \
+ -subj "/CN=unstract-redis-managed" 2>/dev/null
+
+cat > server.ext <<'EXT'
+subjectAltName = DNS:unstract-redis-managed, DNS:localhost, IP:127.0.0.1
+extendedKeyUsage = serverAuth
+EXT
+
+openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial \
+ -out server.crt -days 825 -sha256 -extfile server.ext 2>/dev/null
+
+# Redis runs as uid 999 in the official image and must read the key.
+chmod 644 ca.crt server.crt server.key
+rm -f server.csr server.ext ca.srl
+
+echo "Wrote CA + server certificate to $CERT_DIR"
+echo " CA (for REDIS_SSL_CA_CERTS): $CERT_DIR/ca.crt"
diff --git a/platform-service/sample.env b/platform-service/sample.env
index 72ea02d19..b6ad62985 100644
--- a/platform-service/sample.env
+++ b/platform-service/sample.env
@@ -14,6 +14,20 @@ REDIS_PASSWORD=
REDIS_SENTINEL_MODE=False
REDIS_SENTINEL_MASTER_NAME=mymaster
+# Managed / external Redis with TLS (UN-4123). Optional — unset keeps the plaintext
+# connection above. Either set REDIS_SSL=true beside REDIS_HOST/REDIS_PORT, or give a
+# full URL whose scheme carries TLS:
+# REDIS_URL=rediss://:<password>@<host>:6380/0?ssl_cert_reqs=required
+# A URL wins over the discrete vars. Auth is password-only as the built-in `default`
+# user (what a managed AUTH string is), so leave the username empty for a managed
+# endpoint. REDIS_SSL_CA_CERTS is only needed when the server's CA is not publicly
+# trusted (Memorystore).
+# REDIS_SSL=false
+# REDIS_SSL_CERT_REQS=required
+# REDIS_SSL_CA_CERTS=
+# REDIS_URL=
+# REDIS_HEALTH_CHECK_INTERVAL=30
+
# Backend DB
PG_BE_HOST=unstract-db
PG_BE_PORT=5432
diff --git a/runner/sample.env b/runner/sample.env
index afb58aae1..efdf245a1 100644
--- a/runner/sample.env
+++ b/runner/sample.env
@@ -48,6 +48,61 @@ REDIS_PASSWORD=
REDIS_SENTINEL_MODE=False
REDIS_SENTINEL_MASTER_NAME=mymaster
+# Managed / external Redis with TLS (UN-4123). All optional — unset means the
+# plaintext connection this file otherwise describes, unchanged.
+#
+# Two ways to configure it, pick one:
+# 1. Discrete vars (what the Helm chart and these samples use). Set REDIS_SSL=true
+# alongside REDIS_HOST/REDIS_PORT. No URL-encoding to get wrong.
+# 2. REDIS_URL, where the SCHEME carries TLS and nothing else is needed:
+# REDIS_URL=rediss://:<password>@<host>:6380/0?ssl_cert_reqs=required
+# (6380 is an EXAMPLE, not a default — the TLS port is provider-specific:
+# Memorystore 6378, ElastiCache 6379, Azure Cache 6380. A wrong port
+# hangs the connection rather than erroring, so read it off the instance.)
+# A URL wins over the discrete vars above. Percent-encode @ / + in the password.
+#
+# Auth is password-only, as Redis's built-in `default` user — that is what a managed
+# AUTH string is. Leave REDIS_USER empty for a managed endpoint; named ACL users are
+# not supported platform-wide.
+#
+# REDIS_SSL_CA_CERTS is only needed when the server's CA is not in the system trust
+# store (Memorystore). ElastiCache and Azure Cache chain to public CAs.
+#
+# CAVEAT — it names a path INSIDE each container, and the runner mounts only the
+# shared logs volume into tool containers and sidecars. Nothing in this repo puts
+# a CA file there, so unless your images already bake one in at this exact path,
+# setting it makes those containers fail: SSLConnection calls
+# load_verify_locations() on a path that does not exist. The sidecar then cannot
+# build its LogPublisher client and tool logs are lost; in tool containers
+# MetricsMixin swallows it and timings disappear. The variable IS forwarded, so a
+# baked-in CA works — but a path that only exists on the host does not, and
+# against a publicly-trusted endpoint it turns a working connection into a failing
+# one. docker/redis-tls/README.md shows how to mount it for local development.
+# REDIS_SSL=false
+# REDIS_SSL_CERT_REQS=required
+# REDIS_SSL_CA_CERTS=
+#
+# Hostname verification is ON by default (UN-4123): a chain verified against a
+# public CA still says nothing about WHICH server answered. Set this to false for
+# an endpoint whose certificate does not cover how you address it — an IP, or an
+# internal CNAME. Forced off anyway when REDIS_SSL_CERT_REQS=none, and Sentinel
+# MASTER connections skip it by default because Sentinel returns an IP that no
+# DNS SAN covers and that changes on failover. Forwarded to each tool sidecar,
+# so a platform-wide `false` reaches them too — without that they alone would
+# keep verifying and fail the handshake while everything else recovered.
+# Shown as `false` because that is the only value there is a reason to set:
+# `true` is already the default, and setting it EXPLICITLY is not a no-op —
+# an explicit value is honoured on Sentinel MASTER connections too, turning
+# the compatibility default above back off.
+# REDIS_SSL_CHECK_HOSTNAME=false
+# REDIS_URL=
+
+# Proactive health check for pooled connections, in seconds (0 disables).
+# Managed Redis fails over during maintenance and reaps idle connections — Azure
+# Cache closes them at 10 minutes — so a parked connection can be dead before its
+# next command. Defaults to 30.
+# REDIS_HEALTH_CHECK_INTERVAL=30
+
# Flask related envs
# Can be 'production' or 'development'
FLASK_ENV=production
diff --git a/runner/src/unstract/runner/constants.py b/runner/src/unstract/runner/constants.py
index e4f7449fb..90051b4ee 100644
--- a/runner/src/unstract/runner/constants.py
+++ b/runner/src/unstract/runner/constants.py
@@ -41,6 +41,30 @@ class Env:
REDIS_PASSWORD = "REDIS_PASSWORD"
REDIS_SENTINEL_MODE = "REDIS_SENTINEL_MODE"
REDIS_SENTINEL_MASTER_NAME = "REDIS_SENTINEL_MASTER_NAME"
+ # UN-4123. Same allowlist trap as LOG_TRANSPORT below: the sidecar publishes tool
+ # logs through LogPublisher and builds its own Redis client, so without these it
+ # would keep connecting in PLAINTEXT to db 0 while every other process moved to
+ # TLS — a connection failure at best, and tool logs silently absent at worst.
+ REDIS_DB = "REDIS_DB"
+ REDIS_SSL = "REDIS_SSL"
+ REDIS_SSL_CERT_REQS = "REDIS_SSL_CERT_REQS"
+ # Forwarded as a PATH, and nothing mounts a CA into the sidecar: only the
+ # shared logs volume is. It therefore works only for an image that bakes the
+ # CA in at this path — otherwise load_verify_locations() raises on a file
+ # that is not there. Kept forwarded so the baked-in case is configurable;
+ # the caveat is spelled out in runner/sample.env.
+ REDIS_SSL_CA_CERTS = "REDIS_SSL_CA_CERTS"
+ # The ONLY way back from the on-by-default hostname verification that UN-4123
+ # introduced. An endpoint whose certificate SAN does not match how it is
+ # addressed (an IP, an internal CNAME) needs it set to false platform-wide —
+ # and without it here, these processes alone would keep verifying and fail the
+ # handshake while everything else recovered.
+ REDIS_SSL_CHECK_HOSTNAME = "REDIS_SSL_CHECK_HOSTNAME"
+ REDIS_URL = "REDIS_URL"
+ # Read by _resolve_health_check_interval in this same client, so the
+ # documented "set it to 0 to restore the old behaviour" lever has to reach
+ # here too — otherwise these processes silently keep the 30s default.
+ REDIS_HEALTH_CHECK_INTERVAL = "REDIS_HEALTH_CHECK_INTERVAL"
CELERY_BROKER_BASE_URL = "CELERY_BROKER_BASE_URL"
CELERY_BROKER_USER = "CELERY_BROKER_USER"
CELERY_BROKER_PASS = "CELERY_BROKER_PASS"
diff --git a/runner/src/unstract/runner/runner.py b/runner/src/unstract/runner/runner.py
index 2414ac754..79ea502a3 100644
--- a/runner/src/unstract/runner/runner.py
+++ b/runner/src/unstract/runner/runner.py
@@ -257,6 +257,29 @@ class UnstractRunner:
),
"CONTAINER_NAME": container_name,
}
+ # UN-4123: TLS and db settings for the sidecar's OWN Redis client. It
+ # publishes tool logs through LogPublisher and tracks tool status in Redis,
+ # and this dict is a hand-picked allowlist rather than inherited env — the
+ # same trap that made LOG_TRANSPORT above necessary. Without these the
+ # sidecar would keep connecting in plaintext to db 0 after everything else
+ # moved to TLS.
+ #
+ # Set only when present, so an unset var leaves the sidecar's environment
+ # exactly as it is today rather than introducing an empty-string value —
+ # which os.getenv() in the sidecar would treat as configured.
+ for _redis_env in (
+ Env.REDIS_DB,
+ Env.REDIS_SSL,
+ Env.REDIS_SSL_CERT_REQS,
+ Env.REDIS_SSL_CA_CERTS,
+ Env.REDIS_SSL_CHECK_HOSTNAME,
+ Env.REDIS_URL,
+ Env.REDIS_HEALTH_CHECK_INTERVAL,
+ ):
+ _redis_value = os.getenv(_redis_env)
+ if _redis_value:
+ sidecar_env[_redis_env] = _redis_value
+
sidecar_config = self.client.get_container_run_config(
command=[],
file_execution_id=file_execution_id,
diff --git a/runner/tests/test_sidecar_log_transport.py b/runner/tests/test_sidecar_log_transport.py
index 01c46280b..72e668e0c 100644
--- a/runner/tests/test_sidecar_log_transport.py
+++ b/runner/tests/test_sidecar_log_transport.py
@@ -82,3 +82,68 @@ class TestSidecarLogTransport:
# Flag-off must stay intact: the sidecar still publishes over AMQP.
envs = sidecar_env(CELERY_BROKER_BASE_URL="amqp://x")
assert envs["CELERY_BROKER_BASE_URL"] == "amqp://x"
+
+
+class TestSidecarRedisTls:
+ """TLS settings must reach the sidecar too (UN-4123).
+
+ Same allowlist trap as ``LOG_TRANSPORT`` above, one layer deeper: the sidecar
+ builds its OWN Redis client, so when the platform moves to a TLS endpoint a
+ sidecar that never learned about it keeps dialling plaintext. The failure is a
+ connection error at best; at worst it reaches a different db and tool logs go
+ missing with everything else looking healthy.
+ """
+
+ def test_tls_settings_are_forwarded(self, sidecar_env):
+ envs = sidecar_env(
+ REDIS_SSL="true",
+ REDIS_SSL_CERT_REQS="required",
+ REDIS_SSL_CA_CERTS="/etc/ssl/redis-ca.pem",
+ )
+ assert envs[Env.REDIS_SSL] == "true"
+ assert envs[Env.REDIS_SSL_CERT_REQS] == "required"
+ assert envs[Env.REDIS_SSL_CA_CERTS] == "/etc/ssl/redis-ca.pem"
+
+ def test_db_is_forwarded(self, sidecar_env):
+ """Without this the sidecar sits on db 0 while everyone else honours REDIS_DB.
+
+ Nothing errors: it simply publishes into a keyspace no consumer drains.
+ """
+ envs = sidecar_env(REDIS_DB="3")
+ assert envs[Env.REDIS_DB] == "3"
+
+ def test_url_is_forwarded(self, sidecar_env):
+ envs = sidecar_env(REDIS_URL="rediss://cache.example:6380/2")
+ assert envs[Env.REDIS_URL] == "rediss://cache.example:6380/2"
+
+ def test_unset_values_are_omitted_entirely(self, sidecar_env, monkeypatch):
+ """An empty string is NOT the same as absent.
+
+ ``os.getenv(key, fallback)`` returns "" for a key that exists but is empty,
+ which suppresses the fallback — so forwarding blanks would turn "inherit the
+ default" into "explicitly configured as nothing".
+ """
+ for key in (
+ Env.REDIS_SSL,
+ Env.REDIS_SSL_CERT_REQS,
+ Env.REDIS_SSL_CA_CERTS,
+ Env.REDIS_DB,
+ Env.REDIS_URL,
+ ):
+ monkeypatch.delenv(key, raising=False)
+ envs = sidecar_env()
+ for key in (
+ Env.REDIS_SSL,
+ Env.REDIS_SSL_CERT_REQS,
+ Env.REDIS_SSL_CA_CERTS,
+ Env.REDIS_DB,
+ Env.REDIS_URL,
+ ):
+ assert key not in envs
+
+ def test_plaintext_deployment_is_unchanged(self, sidecar_env, monkeypatch):
+ """The whole point: no TLS configured means the sidecar env is as it was."""
+ monkeypatch.delenv(Env.REDIS_SSL, raising=False)
+ envs = sidecar_env(REDIS_HOST="r", REDIS_PORT="6379")
+ assert envs["REDIS_HOST"] == "r"
+ assert Env.REDIS_SSL not in envs
diff --git a/unstract/core/src/unstract/core/cache/redis_client.py b/unstract/core/src/unstract/core/cache/redis_client.py
index c392d6a4b..dbf30ba50 100644
--- a/unstract/core/src/unstract/core/cache/redis_client.py
+++ b/unstract/core/src/unstract/core/cache/redis_client.py
@@ -5,6 +5,25 @@ Dual-mode Redis configuration:
- Sentinel mode: Sentinel.master_for() when REDIS_SENTINEL_MODE=True
Mode is detected from {prefix}SENTINEL_MODE env var (LLMW pattern).
+
+A full URL in {prefix}URL (falling back to REDIS_URL) overrides the discrete
+host/port/credential vars, and `rediss://` turns on TLS by itself — the scheme is
+the switch, so there is no separate "use TLS" flag to forget.
+
+Precedence, in one sentence, in STANDALONE mode: a URL supplies host, port and
+credentials; the database is the db var at the URL's own level — {prefix}DB for a
+{prefix}URL, {prefix}DB or REDIS_DB for an inherited REDIS_URL — when explicitly
+set, otherwise the URL's path, otherwise 0. An explicit `db=` argument beats all
+of them. Discrete vars remain the default and primary path: they need no
+URL-encoding of passwords, and they are what the Helm chart and every sample.env
+configure.
+
+Two deliberate exceptions to that sentence, both easy to trip over:
+- Sentinel mode IGNORES {prefix}URL entirely and uses the discrete host/port; a
+ Sentinel endpoint is a set of nodes, not one URL.
+- build_socketio_redis_url carries no /db path, so a Socket.IO client built from
+ discrete vars is on db 0 whatever {prefix}DB says. kombu keys are ephemeral
+ pub/sub channels, so nothing is stored there to end up in the wrong database.
In Sentinel mode, REDIS_HOST/REDIS_PORT point to the K8s Sentinel service endpoint.
Master name defaults to "mymaster" (configurable via REDIS_SENTINEL_MASTER_NAME env var).
REDIS_PASSWORD is reused for Sentinel auth.
@@ -17,6 +36,7 @@ import os
import random
import time
from typing import Any
+from urllib.parse import parse_qs, quote, urlencode, urlsplit, urlunsplit
import redis
from redis.sentinel import Sentinel
@@ -32,6 +52,203 @@ _SENTINEL_JITTER_MIN = 0.8
_SENTINEL_JITTER_MAX = 1.2
_DEFAULT_SENTINEL_MASTER_NAME = os.getenv("REDIS_SENTINEL_MASTER_NAME", "mymaster")
+# The scheme IS the TLS switch: redis-py, kombu and django-redis all select an
+# SSL connection from it, which is why nothing here has a separate "use TLS" flag
+# for URL mode.
+_TLS_SCHEME = "rediss://"
+
+# The three values redis-py accepts for ssl_cert_reqs. Anything else reaches
+# redis-py as `RedisError: Invalid SSL Certificate Requirements Flag:` at the
+# first command, so it is validated here where the variable name is still known.
+_CERT_REQS_VALUES = frozenset({"none", "optional", "required"})
+_DEFAULT_CERT_REQS = "required"
+
+# Accepted spellings for the boolean env vars. A bare `== "true"` silently reads
+# `1` and `yes` as FALSE, which for ssl_check_hostname means downgrading to an
+# unauthenticated connection without a word in the log.
+_TRUE_LITERALS = frozenset({"true", "1", "yes", "on"})
+_FALSE_LITERALS = frozenset({"false", "0", "no", "off"})
+
+# redis-py sends a PING before reusing a connection idle for longer than this, so a
+# connection killed while parked (managed-Redis failover, an idle-connection reaper —
+# Azure Cache closes at 10 minutes) is discovered and replaced by the health check
+# rather than by the next real command failing. 30s is redis-py's own documented
+# recommendation. 0 disables it, which is what every client except the two worker
+# caches used before UN-4123.
+_DEFAULT_HEALTH_CHECK_INTERVAL = 30
+
+
+def _resolve_health_check_interval(env_prefix: str, explicit: int) -> int:
+ """Explicit argument wins; otherwise env, otherwise the default above."""
+ if explicit:
+ return explicit
+ raw = os.getenv(
+ f"{env_prefix}HEALTH_CHECK_INTERVAL",
+ os.getenv("REDIS_HEALTH_CHECK_INTERVAL", str(_DEFAULT_HEALTH_CHECK_INTERVAL)),
+ )
+ try:
+ return max(int(raw), 0)
+ except ValueError:
+ logger.warning(
+ "Invalid %sHEALTH_CHECK_INTERVAL=%r; using %s",
+ env_prefix,
+ raw,
+ _DEFAULT_HEALTH_CHECK_INTERVAL,
+ )
+ return _DEFAULT_HEALTH_CHECK_INTERVAL
+
+
+def _strip_url_db_path(url: str) -> str:
+ """Drop the /<db> path from a Redis URL.
+
+ redis-py resolves the db from the URL path and IGNORES a `db=` kwarg, so a
+ caller that asks for a specific db (sdk1 metrics uses db=1) would silently get
+ the URL's db instead. Stripping the path lets the explicit argument apply.
+ """
+ parts = urlsplit(url)
+ return urlunsplit((parts.scheme, parts.netloc, "", parts.query, parts.fragment))
+
+
+def set_url_db_path(url: str, db: int) -> str:
+ """Rewrite a Redis URL's /<db> path to `db`.
+
+ The one place the database rule is applied to a URL. The backend's Django
+ cache needs it too — django-redis takes a LOCATION string and ignores
+ OPTIONS["DB"], so the only way to move that cache off the URL's own database
+ is to rewrite the path — and if it re-implemented the rewrite, the backend
+ and the workers would resolve the same REDIS_URL + REDIS_DB to DIFFERENT
+ databases. They did: the backend followed the URL's path while
+ create_redis_client honoured REDIS_DB, so workers RPUSHed log_history_queue
+ to db N and the backend LPOPped an empty db 0, silently.
+ """
+ parts = urlsplit(url)
+ return urlunsplit((parts.scheme, parts.netloc, f"/{db}", parts.query, parts.fragment))
+
+
+def url_db_path(url: str) -> int | None:
+ """The database a URL's path selects, or None when it carries no path."""
+ path = urlsplit(url).path.strip("/")
+ if not path:
+ return None
+ try:
+ return int(path)
+ except ValueError:
+ return None
+
+
+def _parse_bool(raw: str, default: bool, name: str) -> bool:
+ """Parse a boolean env var; blank means UNSET, unknown warns and defaults.
+
+ Blank-means-unset is this repo's own convention — `FOO=` in a sample.env
+ means "leave the default", and every other variable in UN-4123 treats it that
+ way. `os.getenv` does not: it reports an empty string as SET, so a bare
+ `os.getenv(...) == "true"` turns `FOO=` into False.
+ """
+ value = raw.strip().lower()
+ if not value:
+ return default
+ if value in _TRUE_LITERALS:
+ return True
+ if value in _FALSE_LITERALS:
+ return False
+ logger.warning("Invalid %s=%r; using %s", name, raw, default)
+ return default
+
+
+def parse_db(raw: str, env_prefix: str) -> int:
+ """Parse a database index; blank means UNSET, unparseable warns and uses 0.
+
+ Public because the backend reads database vars of its own — the cache db, the
+ Sentinel branch's db, and FILE_ACTIVE_CACHE_REDIS_DB. Left to `int()` there,
+ the two halves disagree on a malformed value: the workers warn and continue on
+ db 0 while the backend refuses to start.
+
+ A bare `int(os.getenv(...))` raised `ValueError: invalid literal for int()
+ with base 10: ''` on `REDIS_DB=` — the blank-means-unset spelling used
+ everywhere else in this work — out of create_redis_client, killing the
+ process at import in most consumers and degrading to no-cache / no-metrics in
+ the two that catch broadly. The message named neither the variable nor the
+ prefix.
+ """
+ value = raw.strip()
+ if not value:
+ return 0
+ try:
+ return int(value)
+ except ValueError:
+ logger.warning("Invalid %sDB=%r; using 0", env_prefix, raw)
+ return 0
+
+
+def resolve_ssl_cert_reqs(env_prefix: str = "REDIS_") -> str:
+ """{prefix}SSL_CERT_REQS, falling back to REDIS_SSL_CERT_REQS, then "required".
+
+ Normalised and validated in ONE place because the raw value used to reach
+ three consumers that disagreed about it. A blank value gave a hard
+ `RedisError` on the discrete client, a silent CERT_NONE on the kombu URL
+ (kombu's own rediss:// default) and "required" on the URL path — one
+ endpoint, three verification policies. Case and stray whitespace had the same
+ effect, since the "is verification off?" test is an equality check.
+ """
+ raw = os.getenv(
+ f"{env_prefix}SSL_CERT_REQS", os.getenv("REDIS_SSL_CERT_REQS", "")
+ ).strip()
+ value = raw.lower()
+ if not value:
+ return _DEFAULT_CERT_REQS
+ if value not in _CERT_REQS_VALUES:
+ logger.warning(
+ "Invalid %sSSL_CERT_REQS=%r; expected one of %s. Using %s.",
+ env_prefix,
+ raw,
+ ", ".join(sorted(_CERT_REQS_VALUES)),
+ _DEFAULT_CERT_REQS,
+ )
+ return _DEFAULT_CERT_REQS
+ return value
+
+
+def resolve_ssl_check_hostname(env_prefix: str = "REDIS_", default: bool = True) -> bool:
+ """{prefix}SSL_CHECK_HOSTNAME, falling back to REDIS_SSL_CHECK_HOSTNAME, then on.
+
+ Exported so the backend's settings module uses the same parse rather than
+ its own `== "true"`, which read a blank value — and `1`, and `yes` — as
+ FALSE, silently downgrading the Django cache to an encrypted but
+ unauthenticated connection.
+ """
+ return _parse_bool(
+ os.getenv(
+ f"{env_prefix}SSL_CHECK_HOSTNAME", os.getenv("REDIS_SSL_CHECK_HOSTNAME", "")
+ ),
+ default,
+ f"{env_prefix}SSL_CHECK_HOSTNAME",
+ )
+
+
+def url_cert_reqs(url: str) -> str | None:
+ """The ssl_cert_reqs already in a URL's query string, or None.
+
+ The env var is NOT the whole answer: `?ssl_cert_reqs=none` in the URL is a
+ documented form (docker/redis-tls/README.md), and it is what redis-py, kombu
+ and django-redis all actually honour. Deciding "is verification off?" from
+ the env var alone appended ssl_check_hostname=true beside a URL-borne
+ CERT_NONE, and Python's ssl module refuses that combination — every
+ connection in the process raised ValueError at first use.
+
+ Takes the FIRST value on a repeat, matching redis-py's own parse_url.
+ """
+ if not url:
+ return None
+ values = parse_qs(urlsplit(url).query).get("ssl_cert_reqs")
+ if not values:
+ return None
+ return values[0].strip().lower()
+
+
+def effective_cert_reqs(url: str, env_cert_reqs: str) -> str:
+ """What the connection will ACTUALLY use: the URL's query, else the env value."""
+ return url_cert_reqs(url) or env_cert_reqs
+
def _is_sentinel_mode(env_prefix: str) -> bool:
return os.getenv(f"{env_prefix}SENTINEL_MODE", "False").strip().lower() == "true"
@@ -59,8 +276,11 @@ def create_redis_client(
socket_connect_timeout: Connection timeout in seconds.
socket_timeout: Socket timeout in seconds.
max_connections: Optional max connections for ConnectionPool.
- health_check_interval: Proactive health check interval in seconds (0=disabled).
- db: Optional DB index override.
+ health_check_interval: Proactive health check interval in seconds. 0 means
+ "unset" and falls back to {env_prefix}HEALTH_CHECK_INTERVAL, then
+ REDIS_HEALTH_CHECK_INTERVAL, then 30s; set that env to 0 to disable.
+ db: Optional DB index override. Applied even when a URL carries its own
+ db path, which redis-py would otherwise silently prefer.
Returns:
Configured redis.Redis client (standalone or Sentinel-backed).
@@ -68,6 +288,9 @@ def create_redis_client(
Raises:
RedisSentinelConnectionError: After exhausting retries in Sentinel mode.
"""
+ health_check_interval = _resolve_health_check_interval(
+ env_prefix, health_check_interval
+ )
if _is_sentinel_mode(env_prefix):
return _create_sentinel_client(
env_prefix=env_prefix,
@@ -90,6 +313,120 @@ def create_redis_client(
)
+def ensure_tls_query_params(
+ url: str,
+ cert_reqs: str | None = None,
+ ca_certs: str | None = None,
+ check_hostname: bool | None = None,
+) -> str:
+ """Add the TLS settings a `rediss://` URL is missing, leaving present ones alone.
+
+ Anything that hands a URL to a library that reads TLS out of the query string
+ needs this: kombu's KombuManager takes a URL and NOTHING else, and
+ django-redis's LOCATION is a string too (it also reads
+ OPTIONS["CONNECTION_POOL_KWARGS"], but the query string wins on conflict).
+
+ It lives here rather than at each call site because a hand-rolled append at
+ each one WOULD drift: teach one side ssl_cert_reqs and leave the other on
+ ssl_ca_certs alone, and the same endpoint holds two verification policies
+ depending on which side built the string.
+
+ A non-TLS URL is returned untouched — there is nothing to configure.
+ """
+ if not url.startswith(_TLS_SCHEME):
+ return url
+ # What the URL already says beats what the caller resolved from the env. The
+ # suppression below used to test the CALLER's cert_reqs, so a URL carrying
+ # ?ssl_cert_reqs=none still got ssl_check_hostname=true appended, and Python's
+ # ssl module raises on that pair — every connection, on a URL form this repo
+ # documents as supported.
+ active_cert_reqs = url_cert_reqs(url) or cert_reqs
+ extra: dict[str, str] = {}
+ if cert_reqs and "ssl_cert_reqs=" not in url:
+ extra["ssl_cert_reqs"] = cert_reqs
+ if (
+ check_hostname is not None
+ and "ssl_check_hostname=" not in url
+ and active_cert_reqs != "none"
+ ):
+ # A chain verified against a public CA says nothing about WHICH server
+ # answered unless the hostname is checked.
+ extra["ssl_check_hostname"] = str(check_hostname).lower()
+ if ca_certs and "ssl_ca_certs=" not in url:
+ extra["ssl_ca_certs"] = ca_certs
+ if not extra:
+ return url
+ separator = "&" if "?" in url else "?"
+ # safe="/" keeps a CA path readable: a slash is legal in a query value, and
+ # percent-encoding it only makes the URL harder to eyeball in a log line.
+ return url + separator + urlencode(extra, safe="/", quote_via=quote)
+
+
+def _compose_redis_url(env: dict[str, Any]) -> str:
+ """Assemble a URL from the discrete vars, percent-encoding the credentials.
+
+ Split out of build_socketio_redis_url so that function stays about the TLS
+ query string rather than also being a URL builder.
+ """
+ credentials = ""
+ if env.get("username") and env.get("password"):
+ credentials = (
+ f"{quote(str(env['username']), safe='')}:"
+ f"{quote(str(env['password']), safe='')}@"
+ )
+ elif env.get("password"):
+ credentials = f":{quote(str(env['password']), safe='')}@"
+ scheme = "rediss" if env.get("ssl") else "redis"
+ return f"{scheme}://{credentials}{env['host']}:{env['port']}"
+
+
+def build_socketio_redis_url(env_prefix: str = "REDIS_") -> str:
+ """Redis URL for a Socket.IO/kombu client, TLS settings included (UN-4123).
+
+ The backend and the log-consumer worker both publish Socket.IO events through
+ kombu, and each built this URL by hand. Two hand-built URLs for one endpoint
+ drift: teach one of them TLS and the other keeps its ``redis://``, and against
+ a TLS-only endpoint that publisher simply cannot connect — no exception the
+ caller sees, just execution logs that stop reaching the UI. One builder serves
+ both so the pair cannot diverge.
+
+ kombu reads TLS out of the URL and NOTHING ELSE: ``KombuManager`` takes a URL,
+ not connection kwargs. Two consequences are handled here rather than left to
+ each caller:
+
+ * ``ssl_cert_reqs`` must be in the query string. Kombu defaults a ``rediss://``
+ URL to ``CERT_NONE`` — encrypted, but the server is never authenticated,
+ which is not what enabling TLS is understood to buy.
+ * ``ssl_ca_certs`` must be there too, or a privately-signed server (Memorystore)
+ fails verification even though the Django cache beside it succeeds.
+
+ Sentinel is deliberately out of scope HERE: it is the self-hosted HA path, its
+ URL has a different shape, and a managed endpoint is a single primary. (The
+ Sentinel CLIENT does get TLS, on both the discovery and master connections —
+ see _build_connection_kwargs; it is only this URL builder that does not.)
+ """
+ env = _resolve_redis_env(env_prefix)
+ # _resolve_redis_env always populates this now, normalised and validated.
+ # The `or os.getenv(...)` fallback that used to sit here re-stated the same
+ # resolution chain and could only fire on a blank value — which it then
+ # re-read as blank, producing a URL with NO ssl_cert_reqs and letting kombu
+ # apply its rediss:// default of CERT_NONE.
+ cert_reqs = env["ssl_cert_reqs"]
+ ca_certs = env.get("ssl_ca_certs")
+
+ url = env["url"] or _compose_redis_url(env)
+ if not url.startswith(_TLS_SCHEME):
+ return url
+
+ url = ensure_tls_query_params(
+ url,
+ cert_reqs=cert_reqs,
+ ca_certs=ca_certs,
+ check_hostname=env.get("ssl_check_hostname", True),
+ )
+ return url
+
+
def _resolve_redis_env(
env_prefix: str, default_port: str = "6379", db_override: int | None = None
) -> dict[str, Any]:
@@ -101,12 +438,23 @@ def _resolve_redis_env(
f"{env_prefix}USER",
os.getenv(f"{env_prefix}USERNAME", os.getenv("REDIS_USER")),
)
+ prefixed_db = os.getenv(f"{env_prefix}DB", "").strip()
+ generic_db = os.getenv("REDIS_DB", "").strip()
db = (
db_override
if db_override is not None
- else int(os.getenv(f"{env_prefix}DB", os.getenv("REDIS_DB", "0")))
+ else parse_db(prefixed_db or generic_db, env_prefix)
+ )
+ # Falls back to REDIS_SSL: before UN-4123 each prefix needed its own *_SSL, so
+ # turning TLS on platform-wide meant remembering CACHE_REDIS_SSL and
+ # MANUAL_REVIEW_REDIS_SSL too — and a missed one fails as a plaintext client
+ # talking to a TLS port, not as a config error.
+ ssl = (
+ os.getenv(f"{env_prefix}SSL", os.getenv("REDIS_SSL", "false")).strip().lower()
+ == "true"
)
- ssl = os.getenv(f"{env_prefix}SSL", "false").strip().lower() == "true"
+ own_url = os.getenv(f"{env_prefix}URL", "").strip()
+ generic_url = os.getenv("REDIS_URL", "").strip()
result: dict[str, Any] = {
"host": host,
"port": port,
@@ -114,12 +462,142 @@ def _resolve_redis_env(
"username": username,
"db": db,
"ssl": ssl,
+ # A full URL, when given, is authoritative for host/port/credentials/db and
+ # carries TLS in its scheme (rediss://). Everything above stays the default
+ # path, so an unset URL changes nothing.
+ "url": own_url or generic_url,
}
- if ssl:
- result["ssl_cert_reqs"] = os.getenv(f"{env_prefix}SSL_CERT_REQS", "required")
+ # A URL's scheme is authoritative and silently wins over {prefix}SSL, so say
+ # so out loud: an operator who turns REDIS_SSL on while an older plaintext
+ # REDIS_URL is still set gets cleartext on the wire believing TLS is on. The
+ # mismatch is never deliberate — a URL that means TLS says rediss://.
+ if result["url"] and ssl and not result["url"].startswith(_TLS_SCHEME):
+ logger.error(
+ "%sSSL is true but %sURL uses a plaintext scheme; the URL wins, so this "
+ "connection will NOT be encrypted. Use rediss:// in the URL, or clear it "
+ "to use the discrete host/port vars.",
+ env_prefix,
+ env_prefix,
+ )
+ # THE DATABASE RULE, in one sentence: a URL supplies host, port and
+ # credentials; the database is the db var AT THE URL'S OWN LEVEL when that is
+ # explicitly set, otherwise the URL's path, otherwise 0.
+ #
+ # It has to be stated because redis-py's own rule is different — the URL path
+ # wins and a db= kwarg is ignored — and because the two halves used to
+ # disagree with each other. An INHERITED generic URL honoured the prefix's db
+ # (the chart sets one REDIS_URL and CACHE_REDIS_DB=1, and without this the
+ # worker cache silently joined everything else on db 0), while a prefix's OWN
+ # url did not: an explicit REDIS_DB beside REDIS_URL was dropped, and beside a
+ # URL carrying no path at all the db came out as None rather than 0.
+ #
+ # "At the URL's own level" is what keeps the generic REDIS_DB from reaching
+ # across into a prefix that brought its own URL. workers/sample.env ships
+ # REDIS_DB=0 uncommented, so a plain `os.getenv({prefix}DB, os.getenv(REDIS_DB))`
+ # meant CACHE_REDIS_URL=rediss://…/1 landed on db 0 — an unrelated global
+ # silently overriding the path the operator wrote, which is not the rule the
+ # docstring, sample.env or the chart state. For env_prefix="REDIS_" the two
+ # levels are the same variable, so this reads identically there.
+ explicit_db = prefixed_db if own_url else (prefixed_db or generic_db)
+ if result["url"] and explicit_db and db_override is None:
+ result["db_from_prefix_env"] = parse_db(explicit_db, env_prefix)
+ # Read OUTSIDE the `if ssl` below: URL mode carries TLS in the scheme and never
+ # sets {prefix}SSL, so gating the CA on that flag left `rediss://` verifying
+ # against the system trust store alone — which fails for exactly the servers
+ # that need a CA. Consumers decide whether it applies.
+ #
+ # Needed where the server's CA is not publicly trusted — notably Memorystore,
+ # whose CA is Google-managed. ElastiCache and Azure chain to public CAs.
+ ca_certs = os.getenv(
+ f"{env_prefix}SSL_CA_CERTS", os.getenv("REDIS_SSL_CA_CERTS", "")
+ ).strip()
+ if ca_certs:
+ result["ssl_ca_certs"] = ca_certs
+ # Resolved OUTSIDE the ssl gate and WITH the generic fallback, for the same
+ # reason as ssl_ca_certs above. Gated on `if ssl`, URL mode would never set it
+ # at all — `rediss://` silently taking redis-py's default while the Socket.IO
+ # URL beside it carried the operator's value, one process holding two
+ # verification policies. The generic fallback closes a second gap that IS in
+ # shipped code: before UN-4123 a prefixed client ignored REDIS_SSL_CERT_REQS,
+ # so CACHE_REDIS_ stayed on "required" while REDIS_ honoured "none", and the
+ # worker cache alone failed verification and degraded to no-cache with only a
+ # warning.
+ result["ssl_cert_reqs"] = resolve_ssl_cert_reqs(env_prefix)
+ # Hostname verification. redis-py defaults ssl_check_hostname to FALSE and
+ # overrides ssl.create_default_context()'s safe default with it, so a verified
+ # chain still proves nothing about WHICH server answered: against a publicly
+ # trusted CA — the ElastiCache/Azure case — any valid certificate for any
+ # domain is accepted, and an on-path attacker can terminate the connection.
+ # Encryption without server authentication is not what enabling TLS is
+ # understood to buy, which is the same argument this module already makes for
+ # kombu's CERT_NONE default.
+ #
+ # Forced off when verification itself is off: Python's ssl module raises if
+ # check_hostname is True while verify_mode is CERT_NONE. Decided from the
+ # EFFECTIVE value — the URL's query string outranks the env var, and testing
+ # the env var alone is what produced that ValueError on every connection.
+ raw_check_hostname = os.getenv(
+ f"{env_prefix}SSL_CHECK_HOSTNAME", os.getenv("REDIS_SSL_CHECK_HOSTNAME", "")
+ )
+ # Whether the operator ASKED for a value, as opposed to inheriting the
+ # default. Sentinel's master plane needs to know the difference — see
+ # _tls_kwargs. A value that does not parse is NOT a request: it warns and
+ # falls back, so treating it as explicit would let a typo turn hostname
+ # verification back on for Sentinel masters, which is the breakage this
+ # distinction exists to avoid.
+ result["ssl_check_hostname_explicit"] = (
+ raw_check_hostname.strip().lower() in _TRUE_LITERALS | _FALSE_LITERALS
+ )
+ if effective_cert_reqs(result["url"], result["ssl_cert_reqs"]) == "none":
+ result["ssl_check_hostname"] = False
+ result["ssl_check_hostname_explicit"] = False
+ else:
+ result["ssl_check_hostname"] = resolve_ssl_check_hostname(env_prefix)
return result
+def _tls_kwargs(env: dict[str, Any], sentinel_master: bool = False) -> dict[str, Any]:
+ """TLS connection kwargs, empty when TLS is off.
+
+ Shared by BOTH branches of _build_connection_kwargs on purpose. The auth-only
+ branch builds Sentinel's DISCOVERY connections, and it used to return before
+ the TLS block below — so the master connection was encrypted while the
+ Sentinel password went out in clear against a Sentinel that still accepted
+ plaintext, and a TLS-only Sentinel failed through the full ten-attempt backoff
+ instead. One helper means the two cannot drift again.
+
+ Sentinel and master share a certificate in every deployment that enables TLS —
+ a Sentinel node IS a redis-server and takes the same tls-port configuration —
+ so this follows {prefix}SSL rather than adding a switch of its own.
+
+ Args:
+ sentinel_master: True for a Sentinel-managed MASTER connection. Those
+ connect to whatever `SENTINEL get-master-addr-by-name` returns, and
+ SentinelManagedConnection assigns that address straight to
+ ``self.host`` — which SSLConnection then passes as ``server_hostname``.
+ It is an IP, so hostname verification is checked against an IP that
+ no DNS SAN covers, and pinning an IP SAN is not a workable answer
+ because the address changes on failover. Turning hostname
+ verification on by default would therefore have broken every existing
+ REDIS_SENTINEL_MODE + REDIS_SSL deployment on upgrade, failing
+ through the full ten-attempt backoff at startup. An operator who sets
+ {prefix}SSL_CHECK_HOSTNAME explicitly still gets what they asked for.
+ """
+ if not env.get("ssl"):
+ return {}
+ check_hostname = env.get("ssl_check_hostname", True)
+ if sentinel_master and not env.get("ssl_check_hostname_explicit"):
+ check_hostname = False
+ kwargs: dict[str, Any] = {
+ "ssl": True,
+ "ssl_cert_reqs": env.get("ssl_cert_reqs", _DEFAULT_CERT_REQS),
+ "ssl_check_hostname": check_hostname,
+ }
+ if env.get("ssl_ca_certs"):
+ kwargs["ssl_ca_certs"] = env["ssl_ca_certs"]
+ return kwargs
+
+
def _build_connection_kwargs(
env: dict[str, Any],
decode_responses: bool,
@@ -128,11 +606,17 @@ def _build_connection_kwargs(
health_check_interval: int = 0,
max_connections: int | None = None,
include_auth_only: bool = False,
+ sentinel_master: bool = False,
) -> dict[str, Any]:
"""Build kwargs dict for Redis/Sentinel connections.
Args:
- include_auth_only: If True, only include password/username (for sentinel_kwargs).
+ include_auth_only: If True, omit the master-connection kwargs (db,
+ decode_responses, pool sizing) and return only what Sentinel's
+ DISCOVERY connections need: timeouts, credentials and TLS.
+ sentinel_master: True when these kwargs configure a Sentinel-managed
+ master connection rather than a standalone one. Only affects
+ hostname verification — see _tls_kwargs.
"""
if include_auth_only:
kwargs: dict[str, Any] = {
@@ -143,6 +627,8 @@ def _build_connection_kwargs(
kwargs["password"] = env["password"]
if env.get("username"):
kwargs["username"] = env["username"]
+ # The DISCOVERY connections get TLS too — see _tls_kwargs.
+ kwargs.update(_tls_kwargs(env))
return kwargs
kwargs = {
@@ -159,9 +645,7 @@ def _build_connection_kwargs(
kwargs["password"] = env["password"]
if env.get("username"):
kwargs["username"] = env["username"]
- if env.get("ssl"):
- kwargs["ssl"] = True
- kwargs["ssl_cert_reqs"] = env.get("ssl_cert_reqs", "required")
+ kwargs.update(_tls_kwargs(env, sentinel_master=sentinel_master))
return kwargs
@@ -176,6 +660,22 @@ def _create_standalone_client(
) -> redis.Redis:
env = _resolve_redis_env(env_prefix, default_port="6379", db_override=db_override)
+ if env["url"]:
+ return _create_client_from_url(
+ url=env["url"],
+ decode_responses=decode_responses,
+ socket_connect_timeout=socket_connect_timeout,
+ socket_timeout=socket_timeout,
+ max_connections=max_connections,
+ health_check_interval=health_check_interval,
+ db_override=(
+ db_override if db_override is not None else env.get("db_from_prefix_env")
+ ),
+ ssl_ca_certs=env.get("ssl_ca_certs"),
+ ssl_cert_reqs=env.get("ssl_cert_reqs"),
+ ssl_check_hostname=env.get("ssl_check_hostname"),
+ )
+
logger.info(
"Redis standalone mode enabled. Connecting to %s:%s", env["host"], env["port"]
)
@@ -191,12 +691,84 @@ def _create_standalone_client(
kwargs["port"] = env["port"]
if max_connections is not None:
- pool = redis.ConnectionPool(max_connections=max_connections, **kwargs)
+ pool_kwargs = dict(kwargs)
+ # ConnectionPool hands its kwargs to the connection class, and the plain
+ # Connection has no `ssl` parameter — passing it raises TypeError. TLS on a
+ # POOLED client (platform-service sets max_connections) therefore has to be
+ # selected by connection class, not by a flag.
+ if pool_kwargs.pop("ssl", False):
+ pool_kwargs["connection_class"] = redis.SSLConnection
+ pool = redis.ConnectionPool(max_connections=max_connections, **pool_kwargs)
return redis.Redis(connection_pool=pool)
return redis.Redis(**kwargs)
+def _create_client_from_url(
+ url: str,
+ decode_responses: bool,
+ socket_connect_timeout: int,
+ socket_timeout: int,
+ max_connections: int | None,
+ health_check_interval: int,
+ db_override: int | None,
+ ssl_ca_certs: str | None,
+ ssl_cert_reqs: str | None = None,
+ ssl_check_hostname: bool | None = None,
+) -> redis.Redis:
+ """Build a client from a full Redis URL.
+
+ `rediss://` selects TLS on its own — redis-py picks SSLConnection from the
+ scheme — so TLS needs no separate switch, and `redis://` behaves exactly as the
+ discrete host/port path does. TLS verification is tuned in the URL itself, e.g.
+ `?ssl_cert_reqs=required`, or by {prefix}SSL_CERT_REQS /
+ {prefix}SSL_CHECK_HOSTNAME, which fill in only where the URL's query string is
+ silent — the route docker/redis-tls/README.md recommends for the dev recipe.
+ """
+ kwargs: dict[str, Any] = {
+ "decode_responses": decode_responses,
+ "socket_connect_timeout": socket_connect_timeout,
+ "socket_timeout": socket_timeout,
+ }
+ if health_check_interval:
+ kwargs["health_check_interval"] = health_check_interval
+ if max_connections is not None:
+ kwargs["max_connections"] = max_connections
+ if url.startswith(_TLS_SCHEME):
+ # Set explicitly, or `rediss://` takes redis-py's defaults: verification
+ # policy diverging from the discrete path within one process, and hostname
+ # checking off. A setting already in the URL's query string wins; these
+ # only fill the gap.
+ if ssl_ca_certs:
+ kwargs["ssl_ca_certs"] = ssl_ca_certs
+ if "ssl_cert_reqs=" not in url and ssl_cert_reqs:
+ kwargs["ssl_cert_reqs"] = ssl_cert_reqs
+ # Suppressed when verification is off, decided from what the URL ACTUALLY
+ # carries rather than from the env value: a URL saying ssl_cert_reqs=none
+ # with the env at its "required" default used to get check_hostname=True
+ # bolted on, and ssl.SSLContext refuses that pair — ValueError on the
+ # first command, on every client in the process.
+ if (
+ "ssl_check_hostname=" not in url
+ and ssl_check_hostname is not None
+ and effective_cert_reqs(url, ssl_cert_reqs or _DEFAULT_CERT_REQS) != "none"
+ ):
+ kwargs["ssl_check_hostname"] = ssl_check_hostname
+ if db_override is not None:
+ # The URL path wins over a db kwarg in redis-py, so it has to go.
+ url = _strip_url_db_path(url)
+ kwargs["db"] = db_override
+
+ parts = urlsplit(url)
+ logger.info(
+ "Redis URL mode enabled. Connecting to %s:%s (tls=%s)",
+ parts.hostname,
+ parts.port,
+ parts.scheme == "rediss",
+ )
+ return redis.Redis.from_url(url, **kwargs)
+
+
def _create_sentinel_client(
env_prefix: str,
decode_responses: bool,
@@ -234,6 +806,7 @@ def _create_sentinel_client(
socket_timeout,
health_check_interval=health_check_interval,
max_connections=max_connections,
+ sentinel_master=True,
)
return _connect_with_retry(env, master_name, sentinel_kwargs, master_kwargs)
diff --git a/unstract/core/tests/test_redis_client_config.py b/unstract/core/tests/test_redis_client_config.py
new file mode 100644
index 000000000..63a0d191f
--- /dev/null
+++ b/unstract/core/tests/test_redis_client_config.py
@@ -0,0 +1,911 @@
+"""Connection configuration for the shared Redis client factory (UN-4123).
+
+These tests build clients and inspect the resulting connection kwargs. Nothing
+connects to a server: every property under test is decided at construction, which
+is exactly where the bugs being locked down lived.
+
+The recurring theme is that a MISCONFIGURED Redis client fails quietly. A missing
+TLS flag is a plaintext socket against a TLS port; an ignored db override is reads
+and writes against the wrong keyspace; an empty-string env var counts as "set" to
+``os.getenv`` and shadows the fallback that would have supplied the real value.
+None of those raise at import, so they are asserted here instead.
+"""
+
+import pathlib
+import re
+
+import pytest
+import redis
+from unstract.core.cache.redis_client import (
+ _build_connection_kwargs,
+ _resolve_redis_env,
+ build_socketio_redis_url,
+ create_redis_client,
+)
+
+_REDIS_ENV_MARKERS = ("REDIS_", "CACHE_REDIS_", "MANUAL_REVIEW_REDIS_")
+
+
[email protected](autouse=True)
+def _clean_redis_env(monkeypatch):
+ """Drop inherited REDIS_* so a developer's shell cannot change the outcome."""
+ import os
+
+ for key in list(os.environ):
+ if any(marker in key for marker in _REDIS_ENV_MARKERS):
+ monkeypatch.delenv(key, raising=False)
+
+
+def _kwargs(client: redis.Redis) -> dict:
+ return client.connection_pool.connection_kwargs
+
+
+def _connection_class(client: redis.Redis) -> str:
+ return client.connection_pool.connection_class.__name__
+
+
+class TestDefaults:
+ def test_no_env_is_plaintext_localhost_db0(self):
+ """The in-cluster/local path: unchanged by everything else in this suite."""
+ client = create_redis_client()
+ assert _connection_class(client) == "Connection"
+ assert _kwargs(client)["host"] == "localhost"
+ assert _kwargs(client)["port"] == 6379
+ assert _kwargs(client)["db"] == 0
+ assert "ssl_cert_reqs" not in _kwargs(client)
+
+ def test_health_check_is_on_by_default(self, monkeypatch):
+ """Guards against a connection killed while idle.
+
+ A managed Redis fails over during maintenance and reaps idle connections
+ (Azure Cache at 10 minutes). Without a health check the pooled connection
+ is only discovered dead when a real command fails on it.
+ """
+ assert _kwargs(create_redis_client())["health_check_interval"] == 30
+
+ monkeypatch.setenv("REDIS_HEALTH_CHECK_INTERVAL", "0")
+ # redis-py always populates this key; 0 is its "disabled" value.
+ assert _kwargs(create_redis_client())["health_check_interval"] == 0
+
+ def test_explicit_argument_beats_env(self, monkeypatch):
+ monkeypatch.setenv("REDIS_HEALTH_CHECK_INTERVAL", "45")
+ assert (
+ _kwargs(create_redis_client(health_check_interval=7))["health_check_interval"]
+ == 7
+ )
+
+ def test_unparseable_health_check_falls_back(self, monkeypatch):
+ """A typo must not take the platform's Redis down."""
+ monkeypatch.setenv("REDIS_HEALTH_CHECK_INTERVAL", "thirty")
+ assert _kwargs(create_redis_client())["health_check_interval"] == 30
+
+
+class TestDiscreteTLS:
+ def test_ssl_selects_a_tls_connection(self, monkeypatch):
+ monkeypatch.setenv("REDIS_HOST", "cache.internal")
+ monkeypatch.setenv("REDIS_SSL", "true")
+ client = create_redis_client()
+ assert _connection_class(client) == "SSLConnection"
+ assert _kwargs(client)["ssl_cert_reqs"] == "required"
+
+ def test_pooled_tls_client_is_usable(self, monkeypatch):
+ """Regression: TLS + max_connections used to fail on the FIRST COMMAND.
+
+ ``ConnectionPool`` hands its kwargs to the connection class, and the plain
+ ``Connection`` has no ``ssl`` parameter. Construction succeeded, the pool
+ kept the non-TLS class, and the first command raised
+ ``TypeError: AbstractConnection.__init__() got an unexpected keyword
+ argument 'ssl'`` — so platform-service (max_connections=10) would have
+ started healthy and broken on first use.
+ """
+ monkeypatch.setenv("REDIS_SSL", "true")
+ client = create_redis_client(max_connections=10)
+ pool = client.connection_pool
+ assert _connection_class(client) == "SSLConnection"
+ assert "ssl" not in _kwargs(client)
+ # Instantiating the connection is the step that used to raise; redis-py
+ # opens the socket lazily, so this stays offline.
+ assert pool.connection_class(**pool.connection_kwargs) is not None
+
+ def test_prefixed_client_inherits_the_global_ssl_flag(self, monkeypatch):
+ """CACHE_REDIS_* and MANUAL_REVIEW_* must not need their own SSL flag.
+
+ Before this fell back, enabling TLS platform-wide meant remembering every
+ prefix, and a forgotten one is a plaintext client against a TLS port.
+ """
+ monkeypatch.setenv("REDIS_SSL", "true")
+ for prefix in ("CACHE_REDIS_", "MANUAL_REVIEW_REDIS_"):
+ assert _connection_class(create_redis_client(env_prefix=prefix)) == (
+ "SSLConnection"
+ )
+
+ def test_prefix_can_still_override_the_global_flag(self, monkeypatch):
+ monkeypatch.setenv("REDIS_SSL", "true")
+ monkeypatch.setenv("CACHE_REDIS_SSL", "false")
+ assert _connection_class(create_redis_client(env_prefix="CACHE_REDIS_")) == (
+ "Connection"
+ )
+
+ def test_ca_certs_reach_the_connection(self, monkeypatch):
+ """Needed for Memorystore, whose CA is not in the system trust store."""
+ monkeypatch.setenv("REDIS_SSL", "true")
+ monkeypatch.setenv("REDIS_SSL_CA_CERTS", "/etc/ssl/redis-ca.pem")
+ assert _kwargs(create_redis_client())["ssl_ca_certs"] == "/etc/ssl/redis-ca.pem"
+
+ def test_ca_certs_ignored_without_tls(self, monkeypatch):
+ monkeypatch.setenv("REDIS_SSL_CA_CERTS", "/etc/ssl/redis-ca.pem")
+ assert "ssl_ca_certs" not in _kwargs(create_redis_client())
+
+
+class TestUrlMode:
+ def test_rediss_scheme_turns_on_tls_without_a_flag(self, monkeypatch):
+ monkeypatch.setenv(
+ "REDIS_URL", "rediss://cache.example:6380/2?ssl_cert_reqs=required"
+ )
+ client = create_redis_client()
+ assert _connection_class(client) == "SSLConnection"
+ assert _kwargs(client)["ssl_cert_reqs"] == "required"
+ assert _kwargs(client)["db"] == 2
+
+ def test_plain_scheme_stays_plaintext(self, monkeypatch):
+ monkeypatch.setenv("REDIS_URL", "redis://cache.example:6379")
+ assert _connection_class(create_redis_client()) == "Connection"
+
+ def test_password_is_url_decoded(self, monkeypatch):
+ """Generated passwords contain @ / +, so they arrive percent-encoded."""
+ monkeypatch.setenv("REDIS_URL", "rediss://:p%40ss%[email protected]:6380")
+ assert _kwargs(create_redis_client())["password"] == "p@ss/word"
+
+ def test_explicit_db_argument_beats_the_url_path(self, monkeypatch):
+ """redis-py lets the URL path win over a ``db`` kwarg — silently.
+
+ sdk1's metrics client asks for db=1 explicitly. Without stripping the path
+ it would land in the URL's db instead, writing metrics into another
+ service's keyspace with nothing to indicate it.
+ """
+ monkeypatch.setenv("REDIS_URL", "rediss://cache.example:6380/5")
+ assert _kwargs(create_redis_client(db=1))["db"] == 1
+
+ def test_url_db_applies_when_no_override_is_given(self, monkeypatch):
+ monkeypatch.setenv("REDIS_URL", "rediss://cache.example:6380/5")
+ assert _kwargs(create_redis_client())["db"] == 5
+
+ def test_url_takes_precedence_over_discrete_vars(self, monkeypatch):
+ monkeypatch.setenv("REDIS_HOST", "in-cluster")
+ monkeypatch.setenv("REDIS_URL", "redis://managed.example:6379")
+ assert _kwargs(create_redis_client())["host"] == "managed.example"
+
+ def test_prefixed_url_is_used_for_that_prefix_only(self, monkeypatch):
+ monkeypatch.setenv("REDIS_URL", "redis://shared.example:6379")
+ monkeypatch.setenv("CACHE_REDIS_URL", "redis://cache.example:6379")
+ assert _kwargs(create_redis_client())["host"] == "shared.example"
+ assert (
+ _kwargs(create_redis_client(env_prefix="CACHE_REDIS_"))["host"]
+ == "cache.example"
+ )
+
+ def test_ca_certs_apply_in_url_mode(self, monkeypatch):
+ """Found by a live run against a TLS Redis, not by reading the code.
+
+ URL mode carries TLS in the scheme and never sets REDIS_SSL, so while the
+ CA was read only inside that flag's branch, `rediss://` verified against
+ the system trust store alone — and failed for precisely the servers a CA
+ is needed for (Memorystore's CA is not publicly trusted).
+ """
+ monkeypatch.setenv("REDIS_URL", "rediss://cache.example:6380/0")
+ monkeypatch.setenv("REDIS_SSL_CA_CERTS", "/etc/ssl/redis-ca.pem")
+ assert _kwargs(create_redis_client())["ssl_ca_certs"] == "/etc/ssl/redis-ca.pem"
+
+ def test_ca_certs_ignored_for_a_plaintext_url(self, monkeypatch):
+ monkeypatch.setenv("REDIS_URL", "redis://cache.example:6379/0")
+ monkeypatch.setenv("REDIS_SSL_CA_CERTS", "/etc/ssl/redis-ca.pem")
+ assert "ssl_ca_certs" not in _kwargs(create_redis_client())
+
+ def test_prefix_db_wins_over_an_inherited_url(self, monkeypatch):
+ """The Helm chart's shape: one REDIS_URL, plus CACHE_REDIS_DB=1.
+
+ The cache prefix inherits the generic URL for its endpoint, but its own
+ db must still apply — otherwise the worker cache silently moves to the
+ URL's db and lands beside everything else on db 0.
+ """
+ monkeypatch.setenv("REDIS_URL", "rediss://cache.example:6380/0")
+ monkeypatch.setenv("CACHE_REDIS_DB", "1")
+ assert _kwargs(create_redis_client(env_prefix="CACHE_REDIS_"))["db"] == 1
+ assert _kwargs(create_redis_client())["db"] == 0
+
+ def test_an_explicit_db_beats_even_this_prefixs_own_url(self, monkeypatch):
+ """Changed deliberately: {prefix}DB wins over ANY url's path.
+
+ This used to assert 3 — a URL written for this prefix kept its own db,
+ while an INHERITED url lost to {prefix}DB. Two rules for one question, and
+ no way to state either without naming which url it came from. The uniform
+ rule is: a url supplies host/port/credentials, {prefix}DB supplies the
+ database when set. An operator who wants the url's db simply leaves
+ {prefix}DB unset, which is covered by the case above.
+ """
+ monkeypatch.setenv("REDIS_URL", "rediss://cache.example:6380/0")
+ monkeypatch.setenv("CACHE_REDIS_URL", "rediss://cache.example:6380/3")
+ monkeypatch.setenv("CACHE_REDIS_DB", "1")
+ assert _kwargs(create_redis_client(env_prefix="CACHE_REDIS_"))["db"] == 1
+
+ def test_a_prefix_url_path_applies_when_no_db_is_set(self, monkeypatch):
+ monkeypatch.setenv("CACHE_REDIS_URL", "rediss://cache.example:6380/3")
+ assert _kwargs(create_redis_client(env_prefix="CACHE_REDIS_"))["db"] == 3
+
+ def test_explicit_argument_still_wins(self, monkeypatch):
+ monkeypatch.setenv("REDIS_URL", "rediss://cache.example:6380/0")
+ monkeypatch.setenv("CACHE_REDIS_DB", "1")
+ assert _kwargs(create_redis_client(env_prefix="CACHE_REDIS_", db=7))["db"] == 7
+
+ def test_pool_size_survives_url_mode(self, monkeypatch):
+ monkeypatch.setenv("REDIS_URL", "rediss://cache.example:6380")
+ client = create_redis_client(max_connections=10)
+ assert client.connection_pool.max_connections == 10
+ assert _connection_class(client) == "SSLConnection"
+
+
+class TestAuth:
+ def test_password_only_auth_sends_no_username(self, monkeypatch):
+ """Managed AUTH strings authenticate the built-in ``default`` user.
+
+ Named ACL users are not supported platform-wide — django-redis discards
+ the username — so an empty REDIS_USER must stay empty rather than
+ defaulting to something that turns AUTH into its two-argument form.
+ """
+ monkeypatch.setenv("REDIS_PASSWORD", "s3cr3t")
+ kwargs = _kwargs(create_redis_client())
+ assert kwargs["password"] == "s3cr3t"
+ assert kwargs.get("username") is None
+
+ def test_prefixed_client_inherits_the_global_password(self, monkeypatch):
+ monkeypatch.setenv("REDIS_PASSWORD", "s3cr3t")
+ assert _kwargs(create_redis_client(env_prefix="CACHE_REDIS_"))["password"] == (
+ "s3cr3t"
+ )
+
+ def test_empty_prefixed_password_shadows_the_fallback(self, monkeypatch):
+ """Documents a trap rather than endorsing it.
+
+ ``os.getenv(key, fallback)`` returns "" when the key exists but is empty,
+ so an empty CACHE_REDIS_PASSWORD suppresses REDIS_PASSWORD and the client
+ connects UNAUTHENTICATED. The Helm chart must therefore never render an
+ empty credential; this test fails if that behaviour ever changes, so the
+ chart-side guarantee can be revisited.
+ """
+ monkeypatch.setenv("REDIS_PASSWORD", "s3cr3t")
+ monkeypatch.setenv("CACHE_REDIS_PASSWORD", "")
+ kwargs = _kwargs(create_redis_client(env_prefix="CACHE_REDIS_"))
+ assert kwargs.get("password") is None
+
+
+class TestSocketIoUrl:
+ """The URL kombu gets for Socket.IO (UN-4123).
+
+ kombu takes a URL and nothing else, so every TLS setting has to survive in the
+ query string. The backend and the log-consumer worker both publish through it;
+ they each built this by hand until they drifted, so these cases pin what the
+ shared builder must produce.
+ """
+
+ def test_plaintext_default(self, monkeypatch):
+ monkeypatch.setenv("REDIS_HOST", "unstract-redis")
+ assert build_socketio_redis_url() == "redis://unstract-redis:6379"
+
+ def test_password_only_is_url_encoded(self, monkeypatch):
+ monkeypatch.setenv("REDIS_HOST", "h")
+ monkeypatch.setenv("REDIS_PASSWORD", "p@ss/word")
+ assert build_socketio_redis_url() == "redis://:p%40ss%2Fword@h:6379"
+
+ def test_tls_switches_scheme_and_pins_verification(self, monkeypatch):
+ """Kombu defaults rediss:// to CERT_NONE — encrypted but unauthenticated.
+
+ Without ssl_cert_reqs in the query, enabling TLS would buy encryption
+ against an unverified server, which is not what operators understand it
+ to mean.
+ """
+ monkeypatch.setenv("REDIS_HOST", "h")
+ monkeypatch.setenv("REDIS_SSL", "true")
+ url = build_socketio_redis_url()
+ assert url.startswith("rediss://")
+ assert "ssl_cert_reqs=required" in url
+
+ def test_ca_certs_travel_in_the_query(self, monkeypatch):
+ """The Django cache gets the CA through pool kwargs; kombu has only this.
+
+ Without it, cache access succeeds while the Socket.IO connection cannot
+ verify the same server — so WebSocket delivery dies on its own.
+ """
+ monkeypatch.setenv("REDIS_HOST", "h")
+ monkeypatch.setenv("REDIS_SSL", "true")
+ monkeypatch.setenv("REDIS_SSL_CA_CERTS", "/etc/ssl/redis-ca.pem")
+ assert "ssl_ca_certs=/etc/ssl/redis-ca.pem" in build_socketio_redis_url()
+
+ def test_url_mode_is_used_as_given(self, monkeypatch):
+ monkeypatch.setenv("REDIS_HOST", "in-cluster")
+ monkeypatch.setenv("REDIS_URL", "redis://managed.example:6379/0")
+ assert build_socketio_redis_url() == "redis://managed.example:6379/0"
+
+ def test_a_tls_url_without_cert_reqs_gets_them(self, monkeypatch):
+ """A rediss:// URL alone would leave kombu on CERT_NONE."""
+ monkeypatch.setenv("REDIS_URL", "rediss://:[email protected]:6380/0")
+ url = build_socketio_redis_url()
+ assert "ssl_cert_reqs=required" in url
+
+ def test_an_explicit_cert_reqs_in_the_url_is_respected(self, monkeypatch):
+ monkeypatch.setenv("REDIS_URL", "rediss://h:6380/0?ssl_cert_reqs=none")
+ url = build_socketio_redis_url()
+ assert "ssl_cert_reqs=none" in url
+ assert url.count("ssl_cert_reqs") == 1
+
+ def test_ca_is_added_to_a_tls_url(self, monkeypatch):
+ monkeypatch.setenv("REDIS_URL", "rediss://h:6380/0?ssl_cert_reqs=required")
+ monkeypatch.setenv("REDIS_SSL_CA_CERTS", "/ca.pem")
+ assert "ssl_ca_certs=/ca.pem" in build_socketio_redis_url()
+
+ def test_a_plaintext_url_gains_no_tls_query(self, monkeypatch):
+ monkeypatch.setenv("REDIS_URL", "redis://h:6379/0")
+ monkeypatch.setenv("REDIS_SSL_CA_CERTS", "/ca.pem")
+ assert build_socketio_redis_url() == "redis://h:6379/0"
+
+
+class TestCertReqsAndHostname:
+ """ssl_cert_reqs used to be resolved three different ways in one module.
+
+ URL mode never read it, and a prefixed client had no fallback to the generic
+ REDIS_SSL_CERT_REQS — so one process could hold two verification policies.
+ """
+
+ def test_prefix_inherits_the_generic_cert_reqs(self, monkeypatch):
+ monkeypatch.setenv("REDIS_HOST", "h")
+ monkeypatch.setenv("REDIS_SSL", "true")
+ monkeypatch.setenv("REDIS_SSL_CERT_REQS", "none")
+ for prefix in ("REDIS_", "CACHE_REDIS_", "MANUAL_REVIEW_REDIS_"):
+ assert _kwargs(create_redis_client(env_prefix=prefix))["ssl_cert_reqs"] == (
+ "none"
+ ), prefix
+
+ def test_url_mode_carries_cert_reqs(self, monkeypatch):
+ """`rediss://` with no query used to take redis-py's default silently."""
+ monkeypatch.setenv("REDIS_URL", "rediss://h:6380/0")
+ monkeypatch.setenv("REDIS_SSL_CERT_REQS", "none")
+ assert _kwargs(create_redis_client())["ssl_cert_reqs"] == "none"
+
+ def test_a_cert_reqs_in_the_url_still_wins(self, monkeypatch):
+ monkeypatch.setenv("REDIS_URL", "rediss://h:6380/0?ssl_cert_reqs=required")
+ monkeypatch.setenv("REDIS_SSL_CERT_REQS", "none")
+ assert _kwargs(create_redis_client())["ssl_cert_reqs"] == "required"
+
+ def test_hostname_verification_is_on_by_default(self, monkeypatch):
+ """redis-py defaults this to False, which leaves TLS unauthenticated."""
+ monkeypatch.setenv("REDIS_HOST", "h")
+ monkeypatch.setenv("REDIS_SSL", "true")
+ assert _kwargs(create_redis_client())["ssl_check_hostname"] is True
+
+ def test_hostname_verification_is_on_in_url_mode_too(self, monkeypatch):
+ monkeypatch.setenv("REDIS_URL", "rediss://h:6380/0")
+ assert _kwargs(create_redis_client())["ssl_check_hostname"] is True
+
+ def test_hostname_verification_is_forced_off_without_verification(self, monkeypatch):
+ """Ssl raises if check_hostname is True while verify_mode is CERT_NONE."""
+ monkeypatch.setenv("REDIS_HOST", "h")
+ monkeypatch.setenv("REDIS_SSL", "true")
+ monkeypatch.setenv("REDIS_SSL_CERT_REQS", "none")
+ assert _kwargs(create_redis_client())["ssl_check_hostname"] is False
+
+ def test_hostname_verification_can_be_turned_off(self, monkeypatch):
+ monkeypatch.setenv("REDIS_HOST", "h")
+ monkeypatch.setenv("REDIS_SSL", "true")
+ monkeypatch.setenv("REDIS_SSL_CHECK_HOSTNAME", "false")
+ assert _kwargs(create_redis_client())["ssl_check_hostname"] is False
+
+ def test_socketio_url_carries_both(self, monkeypatch):
+ monkeypatch.setenv("REDIS_HOST", "h")
+ monkeypatch.setenv("REDIS_SSL", "true")
+ url = build_socketio_redis_url()
+ assert "ssl_cert_reqs=required" in url
+ assert "ssl_check_hostname=true" in url
+
+
+class TestSentinelTls:
+ """Sentinel's DISCOVERY connections used to stay plaintext under REDIS_SSL.
+
+ redis-py builds the Sentinel clients from sentinel_kwargs alone, so the master
+ connection was encrypted while the Sentinel password went out in clear — one
+ switch, two answers.
+ """
+
+ def _clients(self, monkeypatch):
+ from redis.sentinel import Sentinel
+
+ monkeypatch.setenv("REDIS_HOST", "sentinel-svc")
+ monkeypatch.setenv("REDIS_PORT", "26379")
+ monkeypatch.setenv("REDIS_PASSWORD", "pw")
+ env = _resolve_redis_env("REDIS_", default_port="26379")
+ sentinel = Sentinel(
+ [("sentinel-svc", 26379)],
+ sentinel_kwargs=_build_connection_kwargs(
+ env, True, 5, 5, include_auth_only=True
+ ),
+ )
+ master = sentinel.master_for(
+ "mymaster", **_build_connection_kwargs(env, True, 5, 5)
+ )
+ return sentinel, master
+
+ def test_tls_reaches_both_planes(self, monkeypatch):
+ monkeypatch.setenv("REDIS_SSL", "true")
+ sentinel, master = self._clients(monkeypatch)
+ assert (
+ sentinel.sentinels[0].connection_pool.connection_class.__name__
+ == "SSLConnection"
+ )
+ assert (
+ master.connection_pool.connection_class.__name__
+ == "SentinelManagedSSLConnection"
+ )
+
+ def test_plaintext_sentinel_is_unchanged(self, monkeypatch):
+ sentinel, master = self._clients(monkeypatch)
+ assert (
+ sentinel.sentinels[0].connection_pool.connection_class.__name__
+ == "Connection"
+ )
+ assert (
+ master.connection_pool.connection_class.__name__
+ == "SentinelManagedConnection"
+ )
+
+
+class TestDatabaseRule:
+ """A URL supplies host/port/credentials; the db is {prefix}DB if explicitly
+ set, else the URL's path, else 0.
+
+ The two halves used to disagree: an INHERITED generic URL honoured the
+ prefix's db, while a prefix's OWN url did not — an explicit REDIS_DB beside
+ REDIS_URL was dropped, and beside a URL with no path the db came out None.
+ """
+
+ def test_url_path_applies_when_no_db_is_set(self, monkeypatch):
+ monkeypatch.setenv("REDIS_URL", "redis://h:6379/2")
+ assert _kwargs(create_redis_client())["db"] == 2
+
+ def test_an_explicit_db_beats_the_url_path(self, monkeypatch):
+ monkeypatch.setenv("REDIS_URL", "redis://h:6379/2")
+ monkeypatch.setenv("REDIS_DB", "3")
+ assert _kwargs(create_redis_client())["db"] == 3
+
+ def test_an_explicit_db_applies_to_a_pathless_url(self, monkeypatch):
+ """This used to yield db=None — neither the env nor a sane default."""
+ monkeypatch.setenv("REDIS_URL", "redis://h:6379")
+ monkeypatch.setenv("REDIS_DB", "3")
+ assert _kwargs(create_redis_client())["db"] == 3
+
+ def test_a_prefix_db_survives_an_inherited_url(self, monkeypatch):
+ """The chart's shape: one REDIS_URL, CACHE_REDIS_DB=1 beside it."""
+ monkeypatch.setenv("REDIS_URL", "redis://h:6379/0")
+ monkeypatch.setenv("CACHE_REDIS_DB", "1")
+ assert _kwargs(create_redis_client(env_prefix="CACHE_REDIS_"))["db"] == 1
+
+ def test_an_explicit_argument_still_wins(self, monkeypatch):
+ monkeypatch.setenv("REDIS_URL", "redis://h:6379/2")
+ monkeypatch.setenv("REDIS_DB", "3")
+ assert _kwargs(create_redis_client(db=7))["db"] == 7
+
+
+class TestContainerAllowlists:
+ """The two hand-maintained env allowlists must carry what this module READS,
+ AND must actually copy it into the container.
+
+ Tool containers and sidecars get a hand-picked environment, not an inherited
+ one, so a variable missing from a list applies everywhere EXCEPT the processes
+ doing the work — silently, because the default is a working value. Both
+ omissions found in review (REDIS_HEALTH_CHECK_INTERVAL from both lists) were
+ of exactly this shape, and nothing kept the two lists in step.
+
+ TWO mechanisms, both checked. Declaring the name on Env / ToolRuntimeVariable
+ does nothing on its own: a separate loop copies a fixed tuple of those
+ constants into the child environment, and a name can be declared and left out
+ of the tuple. The first version of this class asserted only the declaration,
+ so deleting `Env.REDIS_HEALTH_CHECK_INTERVAL` from runner.py's tuple — the
+ exact omission the class was written for — left the suite green.
+
+ _SHARED is DERIVED from redis_client.py's source rather than hand-listed, so a
+ variable added to the module fails this guard instead of needing a third list
+ to be remembered. REDIS_SSL_CHECK_HOSTNAME was added by the same commit that
+ introduced the hand-written version and was missing from it.
+
+ Read as text rather than imported: neither package is installable in this
+ environment, and the question is what the source declares and forwards.
+ """
+
+ _ROOT = pathlib.Path(__file__).resolve().parents[3]
+ _SIDECAR = _ROOT / "runner/src/unstract/runner/constants.py"
+ _SIDECAR_FORWARD = _ROOT / "runner/src/unstract/runner/runner.py"
+ _TOOL = (
+ _ROOT / "unstract/workflow-execution/src/unstract/workflow_execution/constants.py"
+ )
+ _TOOL_FORWARD = (
+ _ROOT
+ / "unstract/workflow-execution/src/unstract/workflow_execution/tools_utils.py"
+ )
+ _CLIENT = _ROOT / "unstract/core/src/unstract/core/cache/redis_client.py"
+
+ # Variables that are per-PROCESS rather than per-endpoint, so a container
+ # deliberately does not inherit them. Listing them here (with the reason) is
+ # what keeps the derivation below honest: anything else new must be forwarded
+ # or explicitly excused.
+ _NOT_FORWARDED = {
+ # Sentinel is the self-hosted HA path; a sidecar or tool container is
+ # handed the resolved endpoint, it does not do discovery itself.
+ "REDIS_SENTINEL_MODE",
+ "REDIS_SENTINEL_MASTER_NAME",
+ # Host/port/credentials were already forwarded before UN-4123 under their
+ # own names; they are not part of this TLS-era set.
+ "REDIS_HOST",
+ "REDIS_PORT",
+ "REDIS_USER",
+ "REDIS_USERNAME",
+ "REDIS_PASSWORD",
+ }
+
+ @classmethod
+ def _shared(cls) -> set[str]:
+ """Every REDIS_* env var redis_client.py reads, minus the excused ones."""
+ source = cls._CLIENT.read_text()
+ names = set(re.findall(r'os\.getenv\(\s*"(REDIS_[A-Z_]+)"', source))
+ names |= {
+ f"REDIS_{suffix}"
+ for suffix in re.findall(r'os\.getenv\(\s*f"\{env_prefix\}([A-Z_]+)"', source)
+ }
+ return names - cls._NOT_FORWARDED
+
+ def test_the_derived_set_is_not_empty(self):
+ """A regex that silently matches nothing would make every case below pass."""
+ shared = self._shared()
+ assert len(shared) >= 6, shared
+ assert "REDIS_SSL_CHECK_HOSTNAME" in shared
+
+ @pytest.mark.parametrize("which", ["sidecar", "tool"])
+ def test_every_variable_this_module_reads_is_declared(self, which):
+ path = self._SIDECAR if which == "sidecar" else self._TOOL
+ declared = path.read_text()
+ missing = [name for name in sorted(self._shared()) if f'"{name}"' not in declared]
+ assert not missing, (
+ f"{path.name} does not declare {missing}; create_redis_client reads "
+ "them, so the setting would apply everywhere except this container."
+ )
+
+ # The exact region of each file that copies constants into the child
+ # environment. Searching the WHOLE file instead would accept any occurrence —
+ # a comment, a docstring, a different tuple — which is the same
+ # "present somewhere != present where it matters" weakness this class was
+ # rewritten to remove, one level down. Mutation-proved: with a whole-file
+ # search, COMMENTING OUT a tuple entry survived.
+ _FORWARD_REGIONS = {
+ "sidecar": ("for _redis_env in (", ")"),
+ "tool": ("for name in (", ")"),
+ }
+
+ @classmethod
+ def _forwarding_tuple(cls, which: str) -> str:
+ """The tuple's LIVE lines — commented-out entries do not forward anything."""
+ path = cls._SIDECAR_FORWARD if which == "sidecar" else cls._TOOL_FORWARD
+ source = path.read_text()
+ opener, closer = cls._FORWARD_REGIONS[which]
+ start = source.index(opener)
+ region = source[start : source.index(closer, start)]
+ return "\n".join(
+ line for line in region.splitlines() if not line.strip().startswith("#")
+ )
+
+ @pytest.mark.parametrize("which", ["sidecar", "tool"])
+ def test_the_forwarding_tuple_is_locatable(self, which):
+ """If the anchor stops matching, every case below would search an empty
+ string and fail loudly — but say so here, where the cause is obvious.
+ """
+ region = self._forwarding_tuple(which)
+ assert "REDIS_" in region, region
+
+ @pytest.mark.parametrize("which", ["sidecar", "tool"])
+ def test_every_declared_variable_is_actually_copied_into_the_container(self, which):
+ """The tuple, not the constants file, is what reaches the child process."""
+ alias = "Env." if which == "sidecar" else "ToolRV."
+ region = self._forwarding_tuple(which)
+ missing = [
+ name for name in sorted(self._shared()) if f"{alias}{name}," not in region
+ ]
+ assert not missing, (
+ f"{which} declares but never forwards {missing}: the constant exists "
+ "and the loop that copies it into the container skips it (or has it "
+ "commented out), so the variable silently stops at the parent process."
+ )
+
+ def test_the_tool_list_also_carries_the_sdk1_metrics_database(self):
+ """sdk1 runs in tool containers; the sidecar never imports it."""
+ assert '"METRICS_REDIS_DB"' in self._TOOL.read_text()
+ assert '"METRICS_REDIS_DB"' not in self._SIDECAR.read_text()
+
+
+class TestCertReqsNoneInTheUrl:
+ """A URL carrying ?ssl_cert_reqs=none must not also get ssl_check_hostname.
+
+ Python's ssl module raises `Cannot set verify_mode to CERT_NONE when
+ check_hostname is enabled`, so the pair is not a degraded connection — it is
+ NO connection, on every client in the process, at the first command rather
+ than at startup. The suppression used to test the ENV value only, so a URL
+ saying `none` with the env at its "required" default got check_hostname
+ bolted on. docker/redis-tls/README.md documents that exact URL.
+
+ The older test for this input asserted only that ssl_cert_reqs=none was
+ PRESENT, which the broken output also satisfied.
+ """
+
+ _URL = "rediss://h:6380/0?ssl_cert_reqs=none"
+
+ def _assert_compatible(self, cert_reqs, check_hostname):
+ """The combination the ssl module actually refuses."""
+ assert not (check_hostname and cert_reqs == "none"), (
+ f"ssl_cert_reqs={cert_reqs!r} with ssl_check_hostname={check_hostname!r} "
+ "raises ValueError at handshake setup"
+ )
+
+ def test_the_client_kwargs_are_not_contradictory(self, monkeypatch):
+ monkeypatch.setenv("REDIS_URL", self._URL)
+ kwargs = _kwargs(create_redis_client())
+ self._assert_compatible(
+ kwargs.get("ssl_cert_reqs"), kwargs.get("ssl_check_hostname")
+ )
+
+ def test_the_client_builds_a_usable_ssl_context(self, monkeypatch):
+ """End to end: what redis-py does with those kwargs at connect time."""
+ import ssl as _ssl
+
+ monkeypatch.setenv("REDIS_URL", self._URL)
+ conn = create_redis_client().connection_pool.make_connection()
+ context = _ssl.create_default_context()
+ # redis-py's SSLConnection._wrap_socket_with_ssl, in the order it does it.
+ context.check_hostname = conn.check_hostname
+ context.verify_mode = conn.cert_reqs
+
+ def test_the_socketio_url_gains_no_check_hostname(self, monkeypatch):
+ monkeypatch.setenv("REDIS_URL", self._URL)
+ url = build_socketio_redis_url()
+ assert "ssl_check_hostname" not in url, url
+ assert url.count("ssl_cert_reqs") == 1
+
+ def test_an_optional_cert_reqs_in_the_url_still_gets_hostname_checking(
+ self, monkeypatch
+ ):
+ """Only `none` suppresses it — the guard must not be a blanket opt-out."""
+ monkeypatch.setenv("REDIS_URL", "rediss://h:6380/0?ssl_cert_reqs=optional")
+ assert "ssl_check_hostname=true" in build_socketio_redis_url()
+
+
+class TestBlankAndMalformedTlsValues:
+ """Blank means UNSET, and a value that is neither blank nor valid says so.
+
+ `os.getenv` reports "" as SET, so a bare `== "true"` read the repo's own
+ "leave the default" spelling as False — turning hostname verification OFF
+ while the operator believed they were on the new secure default.
+ """
+
+ @pytest.mark.parametrize("raw", ["", " "])
+ def test_blank_check_hostname_keeps_the_secure_default(
+ self, monkeypatch, raw, caplog
+ ):
+ monkeypatch.setenv("REDIS_SSL", "true")
+ monkeypatch.setenv("REDIS_SSL_CHECK_HOSTNAME", raw)
+ assert _resolve_redis_env("REDIS_")["ssl_check_hostname"] is True
+ # Blank is the CONVENTION, not a malformed value. Without this the test
+ # cannot tell "unset" from "unparseable, warned, fell back" — both give
+ # True, but only one of them is silent.
+ assert "REDIS_SSL_CHECK_HOSTNAME" not in caplog.text
+
+ @pytest.mark.parametrize("raw", ["1", "yes", "TRUE", "On"])
+ def test_other_truthy_spellings_are_accepted(self, monkeypatch, raw):
+ monkeypatch.setenv("REDIS_SSL", "true")
+ monkeypatch.setenv("REDIS_SSL_CHECK_HOSTNAME", raw)
+ assert _resolve_redis_env("REDIS_")["ssl_check_hostname"] is True
+
+ @pytest.mark.parametrize("raw", ["0", "no", "FALSE", "Off"])
+ def test_other_falsy_spellings_are_accepted(self, monkeypatch, raw):
+ monkeypatch.setenv("REDIS_SSL", "true")
+ monkeypatch.setenv("REDIS_SSL_CHECK_HOSTNAME", raw)
+ assert _resolve_redis_env("REDIS_")["ssl_check_hostname"] is False
+
+ def test_an_unknown_check_hostname_warns_and_stays_secure(self, monkeypatch, caplog):
+ monkeypatch.setenv("REDIS_SSL", "true")
+ monkeypatch.setenv("REDIS_SSL_CHECK_HOSTNAME", "maybe")
+ assert _resolve_redis_env("REDIS_")["ssl_check_hostname"] is True
+ assert "REDIS_SSL_CHECK_HOSTNAME" in caplog.text
+
+ @pytest.mark.parametrize("raw", ["", " "])
+ def test_blank_cert_reqs_falls_back_to_required(self, monkeypatch, raw, caplog):
+ """Blank used to resolve THREE ways: RedisError on the discrete client,
+ a silent CERT_NONE on the kombu URL, and "required" on the URL path.
+ """
+ monkeypatch.setenv("REDIS_SSL", "true")
+ monkeypatch.setenv("REDIS_SSL_CERT_REQS", raw)
+ assert _resolve_redis_env("REDIS_")["ssl_cert_reqs"] == "required"
+ assert "ssl_cert_reqs=required" in build_socketio_redis_url()
+ assert "REDIS_SSL_CERT_REQS" not in caplog.text
+
+ @pytest.mark.parametrize("raw", ["None", "none ", "REQUIRED"])
+ def test_cert_reqs_is_normalised(self, monkeypatch, raw):
+ """The "is verification off?" test is an equality check, so case and
+ whitespace decided whether ssl_check_hostname was suppressed.
+ """
+ monkeypatch.setenv("REDIS_SSL", "true")
+ monkeypatch.setenv("REDIS_SSL_CERT_REQS", raw)
+ assert _resolve_redis_env("REDIS_")["ssl_cert_reqs"] == raw.strip().lower()
+
+ def test_an_invalid_cert_reqs_warns_and_falls_back(self, monkeypatch, caplog):
+ monkeypatch.setenv("REDIS_SSL", "true")
+ monkeypatch.setenv("REDIS_SSL_CERT_REQS", "strict")
+ assert _resolve_redis_env("REDIS_")["ssl_cert_reqs"] == "required"
+ assert "REDIS_SSL_CERT_REQS" in caplog.text
+
+ @pytest.mark.parametrize("raw", ["", " "])
+ def test_a_blank_db_does_not_raise(self, monkeypatch, raw, caplog):
+ """int("") used to escape create_redis_client as a bare ValueError that
+ named neither the variable nor the prefix.
+ """
+ monkeypatch.setenv("REDIS_DB", raw)
+ assert _kwargs(create_redis_client())["db"] == 0
+ assert "REDIS_DB" not in caplog.text
+
+ def test_an_unparseable_db_warns_rather_than_raising(self, monkeypatch, caplog):
+ monkeypatch.setenv("REDIS_DB", "two")
+ assert _kwargs(create_redis_client())["db"] == 0
+ assert "REDIS_DB" in caplog.text
+
+ def test_a_plaintext_url_beside_ssl_true_is_announced(self, monkeypatch, caplog):
+ """The operator believes TLS is on; the wire is cleartext."""
+ monkeypatch.setenv("REDIS_SSL", "true")
+ monkeypatch.setenv("REDIS_URL", "redis://h:6379/0")
+ _resolve_redis_env("REDIS_")
+ assert "will NOT be encrypted" in caplog.text
+
+
+class TestSentinelHostnameVerification:
+ """Sentinel masters are reached by the IP `get-master-addr-by-name` returns.
+
+ SentinelManagedConnection.connect_to assigns that address to self.host, and
+ SSLConnection passes self.host as server_hostname — so hostname verification
+ on a master connection is checked against an IP that no DNS SAN covers, and
+ an IP SAN is not a workable answer because the address changes on failover.
+ Defaulting it on would have broken every existing REDIS_SENTINEL_MODE +
+ REDIS_SSL deployment on upgrade, through the full ten-attempt backoff.
+
+ The DISCOVERY connections do use the configured service name, so they keep
+ verification on.
+ """
+
+ def _planes(self, prefix="REDIS_"):
+ env = _resolve_redis_env(prefix, default_port="26379")
+ discovery = _build_connection_kwargs(env, True, 5, 5, include_auth_only=True)
+ master = _build_connection_kwargs(env, True, 5, 5, sentinel_master=True)
+ return discovery, master
+
+ def test_the_master_plane_does_not_verify_the_hostname_by_default(self, monkeypatch):
+ monkeypatch.setenv("REDIS_SENTINEL_MODE", "true")
+ monkeypatch.setenv("REDIS_SSL", "true")
+ discovery, master = self._planes()
+ assert discovery["ssl_check_hostname"] is True
+ assert master["ssl_check_hostname"] is False
+
+ def test_an_explicit_request_is_honoured_on_both_planes(self, monkeypatch):
+ """The default is a compatibility choice, not a ceiling."""
+ monkeypatch.setenv("REDIS_SENTINEL_MODE", "true")
+ monkeypatch.setenv("REDIS_SSL", "true")
+ monkeypatch.setenv("REDIS_SSL_CHECK_HOSTNAME", "true")
+ discovery, master = self._planes()
+ assert discovery["ssl_check_hostname"] is True
+ assert master["ssl_check_hostname"] is True
+
+ def test_an_explicit_false_still_turns_discovery_off(self, monkeypatch):
+ monkeypatch.setenv("REDIS_SENTINEL_MODE", "true")
+ monkeypatch.setenv("REDIS_SSL", "true")
+ monkeypatch.setenv("REDIS_SSL_CHECK_HOSTNAME", "false")
+ discovery, master = self._planes()
+ assert discovery["ssl_check_hostname"] is False
+ assert master["ssl_check_hostname"] is False
+
+ def test_a_typo_does_not_count_as_an_explicit_request(self, monkeypatch):
+ """Otherwise a typo re-breaks the Sentinel masters this default protects."""
+ monkeypatch.setenv("REDIS_SENTINEL_MODE", "true")
+ monkeypatch.setenv("REDIS_SSL", "true")
+ monkeypatch.setenv("REDIS_SSL_CHECK_HOSTNAME", "ture")
+ _, master = self._planes()
+ assert master["ssl_check_hostname"] is False
+
+ def test_the_standalone_path_is_unaffected(self, monkeypatch):
+ monkeypatch.setenv("REDIS_SSL", "true")
+ assert _kwargs(create_redis_client())["ssl_check_hostname"] is True
+
+
+class TestGenericDbDoesNotCrossIntoAPrefixUrl:
+ """A prefix that brought its OWN url owns its own database.
+
+ workers/sample.env ships REDIS_DB=0 uncommented, so reading the generic var
+ as a fallback meant CACHE_REDIS_URL=rediss://…/1 silently landed on db 0 —
+ an unrelated global overriding the path the operator wrote, which is not the
+ rule the docstring, sample.env or the chart state. An INHERITED generic URL
+ still honours the prefix's db: that is the chart's shape (one REDIS_URL,
+ CACHE_REDIS_DB=1) and the reason the rule exists at all.
+ """
+
+ def test_a_prefix_url_keeps_its_path_against_the_generic_db(self, monkeypatch):
+ monkeypatch.setenv("REDIS_DB", "0")
+ monkeypatch.setenv("CACHE_REDIS_URL", "redis://h:6380/1")
+ assert _kwargs(create_redis_client("CACHE_REDIS_"))["db"] == 1
+
+ def test_the_prefixs_own_db_still_wins(self, monkeypatch):
+ monkeypatch.setenv("REDIS_DB", "0")
+ monkeypatch.setenv("CACHE_REDIS_URL", "redis://h:6380/1")
+ monkeypatch.setenv("CACHE_REDIS_DB", "2")
+ assert _kwargs(create_redis_client("CACHE_REDIS_"))["db"] == 2
+
+ def test_an_inherited_url_still_honours_the_prefix_db(self, monkeypatch):
+ monkeypatch.setenv("REDIS_URL", "redis://h:6379/0")
+ monkeypatch.setenv("CACHE_REDIS_DB", "1")
+ assert _kwargs(create_redis_client("CACHE_REDIS_"))["db"] == 1
+
+ def test_an_inherited_url_still_honours_the_generic_db(self, monkeypatch):
+ """A prefix with NEITHER its own URL nor its own DB inherits both generics.
+
+ (The REDIS_-prefix case — where the two levels are literally the same
+ variable — is covered by TestDatabaseRule.)
+ """
+ monkeypatch.setenv("REDIS_URL", "redis://h:6379/0")
+ monkeypatch.setenv("REDIS_DB", "3")
+ assert _kwargs(create_redis_client("CACHE_REDIS_"))["db"] == 3
+
+
+class TestUrlCertReqsParsing:
+ """`url_cert_reqs` is what decides whether hostname checking is suppressed.
+
+ Each of these survived the suite before it was pinned.
+ """
+
+ def test_it_takes_the_first_value_on_a_repeat(self, monkeypatch):
+ """Matching redis-py's parse_url, which does `unquote(value[0])`.
+
+ Taking the last instead would disagree with the connection the URL
+ actually builds — the suppression decision and the wire would differ.
+ """
+ monkeypatch.setenv(
+ "REDIS_URL", "rediss://h:6380/0?ssl_cert_reqs=none&ssl_cert_reqs=required"
+ )
+ assert _resolve_redis_env("REDIS_")["ssl_check_hostname"] is False
+
+ @pytest.mark.parametrize("raw", ["NONE", "None", "%20none%20"])
+ def test_it_normalises_case_and_whitespace(self, monkeypatch, raw):
+ monkeypatch.setenv("REDIS_URL", f"rediss://h:6380/0?ssl_cert_reqs={raw}")
+ assert _resolve_redis_env("REDIS_")["ssl_check_hostname"] is False
+
+ def test_a_url_without_cert_reqs_leaves_the_env_in_charge(self, monkeypatch):
+ monkeypatch.setenv("REDIS_URL", "rediss://h:6380/0")
+ monkeypatch.setenv("REDIS_SSL_CERT_REQS", "none")
+ assert _resolve_redis_env("REDIS_")["ssl_check_hostname"] is False
+
+
+class TestDiscreteModeStillInheritsTheGenericDb:
+ """No URL anywhere: a prefixed client falls back to REDIS_DB as it always did.
+
+ The "at the URL's own level" rule narrows the fallback for a prefix that
+ brought its OWN url. It must not narrow the plain discrete path, where there
+ is no URL to own anything — that would silently move every prefixed client
+ onto db 0.
+ """
+
+ def test_a_prefix_without_its_own_db_uses_the_generic_one(self, monkeypatch):
+ monkeypatch.setenv("REDIS_HOST", "h")
+ monkeypatch.setenv("REDIS_DB", "3")
+ assert _kwargs(create_redis_client("CACHE_REDIS_"))["db"] == 3
+
+ def test_the_prefixs_own_db_still_wins(self, monkeypatch):
+ monkeypatch.setenv("REDIS_HOST", "h")
+ monkeypatch.setenv("REDIS_DB", "3")
+ monkeypatch.setenv("CACHE_REDIS_DB", "1")
+ assert _kwargs(create_redis_client("CACHE_REDIS_"))["db"] == 1
diff --git a/unstract/sdk1/src/unstract/sdk1/utils/metrics_mixin.py b/unstract/sdk1/src/unstract/sdk1/utils/metrics_mixin.py
index 857a54ba5..dd831e8c6 100644
--- a/unstract/sdk1/src/unstract/sdk1/utils/metrics_mixin.py
+++ b/unstract/sdk1/src/unstract/sdk1/utils/metrics_mixin.py
@@ -1,4 +1,5 @@
import logging
+import os
import time
import uuid
from typing import Any
@@ -7,6 +8,46 @@ from unstract.core.cache.redis_client import create_redis_client
logger = logging.getLogger(__name__)
+_DEFAULT_DB = 1
+
+
+def _metrics_redis_db() -> int:
+ """Which logical database the `metrics:*` keys live on (UN-4123).
+
+ Default 1 is the database this has always used, so an unset var leaves every
+ existing deployment exactly as it was. It exists so a SINGLE-DATABASE endpoint
+ can be supported: the non-clustered tiers of Azure Managed Redis and Redis
+ Enterprise expose db 0 only, and this was the last place in the codebase where
+ a database was chosen in code rather than in configuration. (Cluster mode is
+ unsupported for a different reason entirely — plain redis.Redis gets MOVED
+ redirects regardless of how many databases the service offers.)
+
+ It is one of FOUR keys in Unstract's on-prem database map; workers/sample.env
+ carries the list and the collapsing recipe. REDIS_DB is the one that is easy
+ to forget, because it is already set.
+
+ An explicit db argument beats a REDIS_URL's /<db> path — create_redis_client
+ strips the path for exactly this caller — so this works in URL mode too.
+
+ A blank value means UNSET, not malformed: a declared-but-empty variable is this
+ repo's own convention for "leave the default" (CACHE_REDIS_PASSWORD=,
+ REDIS_SSL_CA_CERTS=), and every other variable in this work treats it that way.
+ Without that, int("") raised inside __init__'s try/except and every LLM timing
+ metric went silently missing platform-wide, once per instrumented call, behind
+ a log line that named Redis rather than this variable.
+
+ A genuinely unparseable value falls back to the default and says so, for the
+ same reason: losing every metric is a bad trade for a typo.
+ """
+ raw = os.getenv("METRICS_REDIS_DB", "").strip() or str(_DEFAULT_DB)
+ try:
+ return int(raw)
+ except ValueError:
+ logger.warning(
+ "Invalid METRICS_REDIS_DB=%r; falling back to db %s", raw, _DEFAULT_DB
+ )
+ return _DEFAULT_DB
+
class MetricsMixin:
TIME_TAKEN_KEY = "time_taken(s)"
@@ -21,7 +62,7 @@ class MetricsMixin:
self.op_id = str(uuid.uuid4()) # Unique identifier for this instance
self.redis_client = None
try:
- self.redis_client = create_redis_client(db=1)
+ self.redis_client = create_redis_client(db=_metrics_redis_db())
except Exception as e:
logger.error(f"Failed to initialize Redis client for run_id={run_id}: {e}")
diff --git a/unstract/sdk1/tests/test_metrics_redis_db.py b/unstract/sdk1/tests/test_metrics_redis_db.py
new file mode 100644
index 000000000..bc2d001a9
--- /dev/null
+++ b/unstract/sdk1/tests/test_metrics_redis_db.py
@@ -0,0 +1,87 @@
+"""Which Redis database the sdk1 metrics keys land on (UN-4123).
+
+This was the last place in the codebase that chose a database in code rather than
+in configuration, which is what blocked single-database endpoints: the
+non-clustered tiers of Azure Managed Redis and Redis Enterprise offer db 0 only.
+(Cluster mode is a different, unsupported thing — a plain redis.Redis gets MOVED
+redirects however many databases the service has.)
+"""
+
+import pytest
+from unstract.sdk1.utils import metrics_mixin
+from unstract.sdk1.utils.metrics_mixin import MetricsMixin, _metrics_redis_db
+
+
+class TestMetricsRedisDb:
+ def test_defaults_to_one(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """The value that was hardcoded, so an unset var changes nothing."""
+ monkeypatch.delenv("METRICS_REDIS_DB", raising=False)
+ assert _metrics_redis_db() == 1
+
+ def test_env_selects_the_database(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("METRICS_REDIS_DB", "0")
+ assert _metrics_redis_db() == 0
+
+ @pytest.mark.parametrize("raw", ["", " "])
+ def test_blank_means_unset(
+ self, monkeypatch: pytest.MonkeyPatch, raw: str, caplog: pytest.LogCaptureFixture
+ ) -> None:
+ """A declared-but-empty variable is this repo's convention for "default".
+
+ int("") used to raise inside __init__'s try/except, so every LLM timing
+ metric went silently missing platform-wide — once per instrumented call,
+ behind a log line that named Redis rather than this variable.
+ """
+ monkeypatch.setenv("METRICS_REDIS_DB", raw)
+ assert _metrics_redis_db() == 1
+ # Without this the test cannot tell "blank is UNSET" from "blank is
+ # unparseable, warn and fall back" — both return 1, but only one of them
+ # is the convention, and the other logs on every instrumented call.
+ assert "METRICS_REDIS_DB" not in caplog.text
+
+ @pytest.mark.parametrize("raw", ["zero", "1.5"])
+ def test_unparseable_falls_back_rather_than_losing_every_metric(
+ self, monkeypatch: pytest.MonkeyPatch, raw: str, caplog: pytest.LogCaptureFixture
+ ) -> None:
+ """And the warning names the variable, so it is not read as a Redis outage."""
+ monkeypatch.setenv("METRICS_REDIS_DB", raw)
+ assert _metrics_redis_db() == 1
+ assert "METRICS_REDIS_DB" in caplog.text
+
+ def test_metrics_stay_enabled_through_a_bad_value(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """Enabled means a client was built, on the fallback db, and kept.
+
+ Asserting on ``redis_key`` proved nothing: __init__ assigns it after the
+ try/except, so it held whatever happened — including the pre-fix state
+ where _metrics_redis_db() raised and redis_client was left None. The
+ factory is patched rather than reached, so this neither needs a live
+ server nor writes 24h-TTL keys to whatever REDIS_URL the shell happens to
+ export.
+ """
+ monkeypatch.setenv("METRICS_REDIS_DB", "zero")
+ calls: list[dict] = []
+ sentinel = _FakeRedis()
+
+ def _factory(**kwargs: object) -> "_FakeRedis":
+ calls.append(kwargs)
+ return sentinel
+
+ monkeypatch.setattr(metrics_mixin, "create_redis_client", _factory)
+ metrics = MetricsMixin(run_id="run-1")
+
+ assert calls == [{"db": 1}], "the fallback database must still be used"
+ assert metrics.redis_client is sentinel, "the client must be kept, not dropped"
+ assert metrics.redis_key.startswith("metrics:run-1:")
+ assert sentinel.sets, "set_start_time must have written the start marker"
+
+
+class _FakeRedis:
+ """Just enough of redis.Redis for MetricsMixin.__init__'s set_start_time()."""
+
+ def __init__(self) -> None:
+ self.sets: list[tuple] = []
+
+ def set(self, *args: object, **kwargs: object) -> None:
+ self.sets.append((args, kwargs))
diff --git a/unstract/workflow-execution/src/unstract/workflow_execution/constants.py b/unstract/workflow-execution/src/unstract/workflow_execution/constants.py
index 3786706cd..5236cd16d 100644
--- a/unstract/workflow-execution/src/unstract/workflow_execution/constants.py
+++ b/unstract/workflow-execution/src/unstract/workflow_execution/constants.py
@@ -28,6 +28,31 @@ class ToolRuntimeVariable:
REDIS_PASSWORD = "REDIS_PASSWORD"
REDIS_SENTINEL_MODE = "REDIS_SENTINEL_MODE"
REDIS_SENTINEL_MASTER_NAME = "REDIS_SENTINEL_MASTER_NAME"
+ # UN-4123 — TLS settings for tool containers, which build their own Redis
+ # client (sdk1 metrics). Same allowlist trap as the sidecar's.
+ REDIS_DB = "REDIS_DB"
+ REDIS_SSL = "REDIS_SSL"
+ REDIS_SSL_CERT_REQS = "REDIS_SSL_CERT_REQS"
+ # Forwarded as a PATH, and nothing mounts a CA into the tool container: only the
+ # shared logs volume is. It therefore works only for an image that bakes the
+ # CA in at this path — otherwise load_verify_locations() raises on a file
+ # that is not there. Kept forwarded so the baked-in case is configurable;
+ # the caveat is spelled out in runner/sample.env.
+ REDIS_SSL_CA_CERTS = "REDIS_SSL_CA_CERTS"
+ # The ONLY way back from the on-by-default hostname verification that UN-4123
+ # introduced. An endpoint whose certificate SAN does not match how it is
+ # addressed (an IP, an internal CNAME) needs it set to false platform-wide —
+ # and without it here, these processes alone would keep verifying and fail the
+ # handshake while everything else recovered.
+ REDIS_SSL_CHECK_HOSTNAME = "REDIS_SSL_CHECK_HOSTNAME"
+ REDIS_URL = "REDIS_URL"
+ # Read by _resolve_health_check_interval in this same client, so the
+ # documented "set it to 0 to restore the old behaviour" lever has to reach
+ # here too — otherwise these processes silently keep the 30s default.
+ REDIS_HEALTH_CHECK_INTERVAL = "REDIS_HEALTH_CHECK_INTERVAL"
+ # Single-database deployments move the sdk1 metrics keys off db 1; the tool
+ # builds its own client, so the choice has to reach it through this allowlist.
+ METRICS_REDIS_DB = "METRICS_REDIS_DB"
class WorkflowFileType:
diff --git a/unstract/workflow-execution/src/unstract/workflow_execution/tools_utils.py b/unstract/workflow-execution/src/unstract/workflow_execution/tools_utils.py
index 040c9485c..44b73595b 100644
--- a/unstract/workflow-execution/src/unstract/workflow_execution/tools_utils.py
+++ b/unstract/workflow-execution/src/unstract/workflow_execution/tools_utils.py
@@ -240,6 +240,23 @@ class ToolsUtils:
ToolRV.REDIS_SENTINEL_MODE: self.redis_sentinel_mode or "False",
ToolRV.REDIS_SENTINEL_MASTER_NAME: self.redis_sentinel_master_name
or "mymaster",
+ # UN-4123: only the keys actually set, so an unset var leaves the tool's
+ # environment unchanged instead of gaining an empty string that
+ # os.getenv() would read as configured.
+ **{
+ name: os.environ[name]
+ for name in (
+ ToolRV.REDIS_DB,
+ ToolRV.REDIS_SSL,
+ ToolRV.REDIS_SSL_CERT_REQS,
+ ToolRV.REDIS_SSL_CA_CERTS,
+ ToolRV.REDIS_SSL_CHECK_HOSTNAME,
+ ToolRV.REDIS_URL,
+ ToolRV.REDIS_HEALTH_CHECK_INTERVAL,
+ ToolRV.METRICS_REDIS_DB,
+ )
+ if os.environ.get(name)
+ },
}
# For async LLM Whisperer extraction
if self.llmw_poll_interval:
diff --git a/workers/log_consumer/tasks.py b/workers/log_consumer/tasks.py
index 809b63c08..865fc499c 100644
--- a/workers/log_consumer/tasks.py
+++ b/workers/log_consumer/tasks.py
@@ -14,6 +14,7 @@ from shared.infrastructure.config import WorkerConfig
from shared.infrastructure.logging import WorkerLogger
from shared.utils.api_client_singleton import get_singleton_api_client
+from unstract.core.cache.redis_client import build_socketio_redis_url
from unstract.core.cache.redis_queue_client import RedisQueueClient
from unstract.core.constants import LogEventArgument, LogProcessingTask
from unstract.core.log_utils import store_execution_log
@@ -51,7 +52,11 @@ if _sentinel_mode:
_sentinel_master_name = os.getenv("REDIS_SENTINEL_MASTER_NAME", "mymaster")
_transport_options = {"master_name": _sentinel_master_name}
else:
- socket_io_manager_url = f"redis://{_cred_prefix}{_redis_host}:{_redis_port}"
+ # UN-4123: built by unstract.core so this cannot drift from the backend.
+ # Hand-building it here would hardcode a scheme, and a publisher stuck on
+ # redis:// cannot reach a TLS-only endpoint — execution logs would simply stop
+ # arriving in the UI, with nothing failing loudly.
+ socket_io_manager_url = build_socketio_redis_url()
sio = socketio.Server(
async_mode="threading",
diff --git a/workers/sample.env b/workers/sample.env
index abb09255f..375a62d2a 100644
--- a/workers/sample.env
+++ b/workers/sample.env
@@ -78,6 +78,59 @@ REDIS_DB=0
REDIS_SENTINEL_MODE=False
REDIS_SENTINEL_MASTER_NAME=mymaster
+# Managed / external Redis with TLS (UN-4123). Optional — unset keeps the plaintext
+# connection above. Either set REDIS_SSL=true beside REDIS_HOST/REDIS_PORT, or give a
+# full URL whose scheme carries TLS:
+# REDIS_URL=rediss://:<password>@<host>:6380/0?ssl_cert_reqs=required
+# A URL wins over the discrete vars. Auth is password-only as the built-in `default`
+# user (what a managed AUTH string is), so leave the username empty for a managed
+# endpoint. REDIS_SSL_CA_CERTS is only needed when the server's CA is not publicly
+# trusted (Memorystore).
+# REDIS_SSL=false
+# REDIS_SSL_CERT_REQS=required
+# REDIS_SSL_CA_CERTS=
+# REDIS_URL=
+# REDIS_HEALTH_CHECK_INTERVAL=30
+#
+# Hostname verification is ON by default (UN-4123): a chain verified against a
+# public CA still says nothing about WHICH server answered. Set this to false for
+# an endpoint whose certificate does not cover how you address it — an IP, or an
+# internal CNAME. It is forced off anyway when REDIS_SSL_CERT_REQS=none, and
+# Sentinel MASTER connections skip it by default because Sentinel returns an IP
+# that no DNS SAN covers and that changes on failover.
+# Shown as `false` because that is the only value there is a reason to set:
+# `true` is already the default, and setting it EXPLICITLY is not a no-op —
+# an explicit value is honoured on Sentinel MASTER connections too, turning
+# the compatibility default above back off.
+# REDIS_SSL_CHECK_HOSTNAME=false
+
+# Single-database endpoints (UN-4123). Some NON-CLUSTERED managed tiers expose db 0
+# ONLY — Azure Managed Redis, a single-shard Redis Cloud database. (Cluster mode is
+# a different, unsupported thing: the client is a plain redis.Redis, so a clustered
+# endpoint returns MOVED no matter how many databases are in use.)
+#
+# FOUR keys select a database, and they live in TWO processes. Set each in the
+# environment that reads it — a value set where nothing reads it is inert, and
+# leaves you believing the map is aligned when it is not:
+#
+# THIS file (workers): REDIS_DB=0 CACHE_REDIS_DB=0 METRICS_REDIS_DB=0
+# backend/.env: REDIS_DB=0 FILE_ACTIVE_CACHE_REDIS_DB=0
+# METRICS_REDIS_DB=0
+#
+# FILE_ACTIVE_CACHE_REDIS_DB is read ONLY by the backend (settings/base.py), so
+# setting it here does nothing. REDIS_DB is easy to forget because it is set
+# already, above — it selects the database for the Django cache LOCATION and for
+# every REDIS_-prefixed client, so collapsing the other three while it stays
+# non-zero still leaves clients on a database a db-0-only endpoint does not have.
+#
+# Leave them alone for the default multi-database layout — no configuration needed.
+#
+# CACHE_REDIS_DB (here) and FILE_ACTIVE_CACHE_REDIS_DB (backend) must ALWAYS match:
+# the workers write file_active:* to one and the backend reads them from the other.
+# Split them and active-file dedup silently finds nothing — no error, just files
+# reprocessed as new.
+# METRICS_REDIS_DB=1
+
# Cache-Specific Redis Configuration
CACHE_REDIS_ENABLED=true
CACHE_REDIS_HOST=unstract-redis
@@ -85,8 +138,29 @@ CACHE_REDIS_PORT=6379
CACHE_REDIS_DB=0
CACHE_REDIS_PASSWORD=
CACHE_REDIS_USERNAME=
-CACHE_REDIS_SSL=false
-CACHE_REDIS_SSL_CERT_REQS=required
+# Commented out DELIBERATELY: both fall back to the generic REDIS_SSL /
+# REDIS_SSL_CERT_REQS when unset (UN-4123), so TLS does not have to be repeated
+# per prefix — and shipping them SET defeated that fallback for every deployment
+# derived from this file. A platform-wide REDIS_SSL=true then applied everywhere
+# except the worker cache, which is the one client that degrades to no-cache on a
+# handshake failure rather than crashing. Uncomment only to pin this prefix to
+# something different from the platform.
+# CACHE_REDIS_SSL=false
+# CACHE_REDIS_SSL_CERT_REQS=required
+# CACHE_REDIS_SSL_CHECK_HOSTNAME=
+# CACHE_REDIS_URL=
+#
+# Precedence when both a URL and discrete vars are set: the URL supplies host,
+# port and credentials, and the DATABASE comes from the db var AT THE URL'S OWN
+# LEVEL when that is explicitly set, otherwise from the URL's path, otherwise 0.
+# So setting CACHE_REDIS_DB=1 keeps the worker cache on db 1 even while it
+# inherits a platform-wide REDIS_URL ending in /0 — which is the shape the Helm
+# chart ships.
+#
+# "At the URL's own level" is the part that bites: a CACHE_REDIS_URL of its own
+# is governed by CACHE_REDIS_DB ALONE. The generic REDIS_DB above does NOT reach
+# across into it — otherwise the REDIS_DB=0 this file ships would silently
+# override the path in any CACHE_REDIS_URL you wrote.
# Cache Redis Sentinel mode for worker execution cache backend
# When True: point CACHE_REDIS_HOST to Sentinel K8s service DNS, CACHE_REDIS_PORT to 26379