Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions api/app/settings/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -648,7 +648,7 @@
CACHE_FLAGS_SECONDS = env.int("CACHE_FLAGS_SECONDS", default=0)
FLAGS_CACHE_LOCATION = "environment-flags"
CHARGEBEE_CACHE_LOCATION = "chargebee-objects"

CACHE_KEY_PREFIX = env.str("CACHE_KEY_PREFIX", default="")
ENVIRONMENT_CACHE_SECONDS = env.int("ENVIRONMENT_CACHE_SECONDS", default=60)
ENVIRONMENT_CACHE_BACKEND = env.str(
"ENVIRONMENT_CACHE_BACKEND",
Expand Down Expand Up @@ -1037,7 +1037,11 @@
subcast=str,
default=[],
)

# Apply key prefix to all Redis-backed caches to support
# ACL-based multi-tenancy on shared Redis instances.
for _cache_config in CACHES.values():
if "redis" in _cache_config.get("BACKEND", "").lower(): # type: ignore[attr-defined]
_cache_config["KEY_PREFIX"] = CACHE_KEY_PREFIX # type: ignore[index]

WORKFLOWS_LOGIC_INSTALLED = importlib.util.find_spec("workflows_logic") is not None

Expand Down
51 changes: 51 additions & 0 deletions api/tests/unit/app/test_unit_app_settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import pytest


def test_cache_key_prefix__redis_backend__key_prefix_applied(
monkeypatch: pytest.MonkeyPatch,
) -> None:
# Given
prefix = "flagsmith"
caches = {
"redis_cache": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://localhost:6379/1",
},
"locmem_cache": {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
"LOCATION": "test",
},
"db_cache": {
"BACKEND": "django.core.cache.backends.db.DatabaseCache",
"LOCATION": "cache_table",
},
}

# When - same logic as settings
for cache_config in caches.values():
if "redis" in cache_config.get("BACKEND", "").lower():
cache_config["KEY_PREFIX"] = prefix

# Then
assert caches["redis_cache"]["KEY_PREFIX"] == prefix
assert "KEY_PREFIX" not in caches["locmem_cache"]
assert "KEY_PREFIX" not in caches["db_cache"]


def test_cache_key_prefix__empty_prefix__redis_backend_gets_empty_prefix() -> None:
# Given
prefix = ""
caches = {
"redis_cache": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://localhost:6379/1",
},
}

# When
for cache_config in caches.values():
if "redis" in cache_config.get("BACKEND", "").lower():
cache_config["KEY_PREFIX"] = prefix

# Then
assert caches["redis_cache"]["KEY_PREFIX"] == ""
Loading