authentik.policies.tests.test_signals

Tests for policy cache invalidation.

Policy and binding changes must invalidate cached results, while last_login- only User saves must avoid the broad cache.keys(...) invalidation.

  1"""Tests for policy cache invalidation.
  2
  3Policy and binding changes must invalidate cached results, while ``last_login``-
  4only User saves must avoid the broad ``cache.keys(...)`` invalidation.
  5"""
  6
  7from unittest import TestCase, mock
  8from uuid import UUID
  9
 10from authentik.core.models import User
 11from authentik.policies import signals
 12from authentik.policies.models import Policy, PolicyBinding
 13from authentik.policies.types import CACHE_PREFIX
 14
 15
 16class _FakeUser:
 17    pk = 1
 18
 19
 20class _FakePolicy:
 21    pk = "fake-policy-pk"
 22
 23
 24class _FakeBinding:
 25    policy_binding_uuid = UUID("12345678-1234-5678-1234-567812345678")
 26
 27
 28class TestInvalidatePolicyCache(TestCase):
 29    """Test policy and application cache invalidation."""
 30
 31    def _run_handler(self, sender, instance, update_fields, policy_bindings=()):
 32        """Run the handler with mocked cache/PolicyBinding; return the
 33        cache mock for assertions."""
 34
 35        with (
 36            mock.patch.object(signals, "cache") as mock_cache,
 37            mock.patch.object(signals, "PolicyBinding") as mock_pb,
 38        ):
 39            mock_cache.keys.return_value = []
 40            mock_pb.objects.filter.return_value = policy_bindings
 41            signals.invalidate_policy_cache(
 42                sender=sender,
 43                instance=instance,
 44                update_fields=update_fields,
 45            )
 46            return mock_cache
 47
 48    def test_user_save_with_only_last_login_does_not_invalidate(self):
 49        """User save with update_fields=["last_login"] is the per-login hot
 50        path. The handler must short-circuit without touching the cache."""
 51        mock_cache = self._run_handler(
 52            sender=User, instance=_FakeUser(), update_fields=["last_login"]
 53        )
 54        mock_cache.keys.assert_not_called()
 55        mock_cache.delete_many.assert_not_called()
 56
 57    def test_user_save_with_last_login_as_set_does_not_invalidate(self):
 58        """``update_fields`` may be a set (Django supports any iterable).
 59        The handler must treat ``{"last_login"}`` identically to
 60        ``["last_login"]``."""
 61        mock_cache = self._run_handler(
 62            sender=User, instance=_FakeUser(), update_fields={"last_login"}
 63        )
 64        mock_cache.keys.assert_not_called()
 65
 66    def test_user_save_with_other_fields_still_invalidates(self):
 67        """A User save that updates ``email`` (or any non-last_login field)
 68        must still invalidate the cache — those updates can affect policy
 69        evaluation, group membership computation, etc."""
 70        mock_cache = self._run_handler(sender=User, instance=_FakeUser(), update_fields=["email"])
 71        mock_cache.keys.assert_called()
 72        mock_cache.delete_many.assert_called()
 73
 74    def test_user_save_with_last_login_plus_other_fields_invalidates(self):
 75        """If ``update_fields`` contains ``last_login`` plus anything else,
 76        we must invalidate — the other field could have policy implications."""
 77        mock_cache = self._run_handler(
 78            sender=User,
 79            instance=_FakeUser(),
 80            update_fields=["last_login", "email"],
 81        )
 82        mock_cache.keys.assert_called()
 83
 84    def test_user_save_without_update_fields_invalidates(self):
 85        """``update_fields=None`` means a full save — anything could have
 86        changed, so we conservatively invalidate."""
 87        mock_cache = self._run_handler(sender=User, instance=_FakeUser(), update_fields=None)
 88        mock_cache.keys.assert_called()
 89
 90    def test_policy_save_still_invalidates(self):
 91        """Non-User senders are unaffected by the new short-circuit.
 92        Policy/PolicyBinding/PolicyBindingModel/Group saves must continue to
 93        invalidate as before — those changes affect access decisions for
 94        every user."""
 95        binding = _FakeBinding()
 96        mock_cache = self._run_handler(
 97            sender=Policy,
 98            instance=_FakePolicy(),
 99            update_fields=["last_login"],  # irrelevant — sender isn't User
100            policy_bindings=[binding],
101        )
102        mock_cache.keys.assert_any_call(f"{CACHE_PREFIX}{binding.policy_binding_uuid.hex}_*")
103        mock_cache.delete_many.assert_called()
104
105    def test_policy_binding_save_invalidates_binding_cache(self):
106        """Binding updates invalidate every cached result for that binding."""
107        binding = _FakeBinding()
108        with mock.patch.object(signals, "cache") as mock_cache:
109            mock_cache.keys.side_effect = [["policy-cache-key"], []]
110
111            signals.invalidate_policy_cache(
112                sender=PolicyBinding,
113                instance=binding,
114            )
115
116        mock_cache.keys.assert_any_call(f"{CACHE_PREFIX}{binding.policy_binding_uuid.hex}_*")
117        mock_cache.delete_many.assert_any_call(["policy-cache-key"])
118
119
120class TestMonitoringSetPolicies(TestCase):
121    """Test the cached policies gauge."""
122
123    def test_gauge_counts_keys_in_database(self):
124        """The gauge is set from a count query instead of fetching every key."""
125        with (
126            mock.patch.object(signals, "cache") as mock_cache,
127            mock.patch.object(signals, "GAUGE_POLICIES_CACHED") as mock_gauge,
128        ):
129            mock_cache.keys_count.return_value = 3
130
131            signals.monitoring_set_policies(sender=None)
132
133        mock_cache.keys_count.assert_called_once_with(f"{CACHE_PREFIX}*")
134        mock_cache.keys.assert_not_called()
135        mock_gauge.set.assert_called_once_with(3)
class TestInvalidatePolicyCache(unittest.case.TestCase):
 29class TestInvalidatePolicyCache(TestCase):
 30    """Test policy and application cache invalidation."""
 31
 32    def _run_handler(self, sender, instance, update_fields, policy_bindings=()):
 33        """Run the handler with mocked cache/PolicyBinding; return the
 34        cache mock for assertions."""
 35
 36        with (
 37            mock.patch.object(signals, "cache") as mock_cache,
 38            mock.patch.object(signals, "PolicyBinding") as mock_pb,
 39        ):
 40            mock_cache.keys.return_value = []
 41            mock_pb.objects.filter.return_value = policy_bindings
 42            signals.invalidate_policy_cache(
 43                sender=sender,
 44                instance=instance,
 45                update_fields=update_fields,
 46            )
 47            return mock_cache
 48
 49    def test_user_save_with_only_last_login_does_not_invalidate(self):
 50        """User save with update_fields=["last_login"] is the per-login hot
 51        path. The handler must short-circuit without touching the cache."""
 52        mock_cache = self._run_handler(
 53            sender=User, instance=_FakeUser(), update_fields=["last_login"]
 54        )
 55        mock_cache.keys.assert_not_called()
 56        mock_cache.delete_many.assert_not_called()
 57
 58    def test_user_save_with_last_login_as_set_does_not_invalidate(self):
 59        """``update_fields`` may be a set (Django supports any iterable).
 60        The handler must treat ``{"last_login"}`` identically to
 61        ``["last_login"]``."""
 62        mock_cache = self._run_handler(
 63            sender=User, instance=_FakeUser(), update_fields={"last_login"}
 64        )
 65        mock_cache.keys.assert_not_called()
 66
 67    def test_user_save_with_other_fields_still_invalidates(self):
 68        """A User save that updates ``email`` (or any non-last_login field)
 69        must still invalidate the cache — those updates can affect policy
 70        evaluation, group membership computation, etc."""
 71        mock_cache = self._run_handler(sender=User, instance=_FakeUser(), update_fields=["email"])
 72        mock_cache.keys.assert_called()
 73        mock_cache.delete_many.assert_called()
 74
 75    def test_user_save_with_last_login_plus_other_fields_invalidates(self):
 76        """If ``update_fields`` contains ``last_login`` plus anything else,
 77        we must invalidate — the other field could have policy implications."""
 78        mock_cache = self._run_handler(
 79            sender=User,
 80            instance=_FakeUser(),
 81            update_fields=["last_login", "email"],
 82        )
 83        mock_cache.keys.assert_called()
 84
 85    def test_user_save_without_update_fields_invalidates(self):
 86        """``update_fields=None`` means a full save — anything could have
 87        changed, so we conservatively invalidate."""
 88        mock_cache = self._run_handler(sender=User, instance=_FakeUser(), update_fields=None)
 89        mock_cache.keys.assert_called()
 90
 91    def test_policy_save_still_invalidates(self):
 92        """Non-User senders are unaffected by the new short-circuit.
 93        Policy/PolicyBinding/PolicyBindingModel/Group saves must continue to
 94        invalidate as before — those changes affect access decisions for
 95        every user."""
 96        binding = _FakeBinding()
 97        mock_cache = self._run_handler(
 98            sender=Policy,
 99            instance=_FakePolicy(),
100            update_fields=["last_login"],  # irrelevant — sender isn't User
101            policy_bindings=[binding],
102        )
103        mock_cache.keys.assert_any_call(f"{CACHE_PREFIX}{binding.policy_binding_uuid.hex}_*")
104        mock_cache.delete_many.assert_called()
105
106    def test_policy_binding_save_invalidates_binding_cache(self):
107        """Binding updates invalidate every cached result for that binding."""
108        binding = _FakeBinding()
109        with mock.patch.object(signals, "cache") as mock_cache:
110            mock_cache.keys.side_effect = [["policy-cache-key"], []]
111
112            signals.invalidate_policy_cache(
113                sender=PolicyBinding,
114                instance=binding,
115            )
116
117        mock_cache.keys.assert_any_call(f"{CACHE_PREFIX}{binding.policy_binding_uuid.hex}_*")
118        mock_cache.delete_many.assert_any_call(["policy-cache-key"])

Test policy and application cache invalidation.

def test_user_save_with_only_last_login_does_not_invalidate(self):
49    def test_user_save_with_only_last_login_does_not_invalidate(self):
50        """User save with update_fields=["last_login"] is the per-login hot
51        path. The handler must short-circuit without touching the cache."""
52        mock_cache = self._run_handler(
53            sender=User, instance=_FakeUser(), update_fields=["last_login"]
54        )
55        mock_cache.keys.assert_not_called()
56        mock_cache.delete_many.assert_not_called()

User save with update_fields=["last_login"] is the per-login hot path. The handler must short-circuit without touching the cache.

def test_user_save_with_last_login_as_set_does_not_invalidate(self):
58    def test_user_save_with_last_login_as_set_does_not_invalidate(self):
59        """``update_fields`` may be a set (Django supports any iterable).
60        The handler must treat ``{"last_login"}`` identically to
61        ``["last_login"]``."""
62        mock_cache = self._run_handler(
63            sender=User, instance=_FakeUser(), update_fields={"last_login"}
64        )
65        mock_cache.keys.assert_not_called()

update_fields may be a set (Django supports any iterable). The handler must treat {"last_login"} identically to ["last_login"].

def test_user_save_with_other_fields_still_invalidates(self):
67    def test_user_save_with_other_fields_still_invalidates(self):
68        """A User save that updates ``email`` (or any non-last_login field)
69        must still invalidate the cache — those updates can affect policy
70        evaluation, group membership computation, etc."""
71        mock_cache = self._run_handler(sender=User, instance=_FakeUser(), update_fields=["email"])
72        mock_cache.keys.assert_called()
73        mock_cache.delete_many.assert_called()

A User save that updates email (or any non-last_login field) must still invalidate the cache — those updates can affect policy evaluation, group membership computation, etc.

def test_user_save_with_last_login_plus_other_fields_invalidates(self):
75    def test_user_save_with_last_login_plus_other_fields_invalidates(self):
76        """If ``update_fields`` contains ``last_login`` plus anything else,
77        we must invalidate — the other field could have policy implications."""
78        mock_cache = self._run_handler(
79            sender=User,
80            instance=_FakeUser(),
81            update_fields=["last_login", "email"],
82        )
83        mock_cache.keys.assert_called()

If update_fields contains last_login plus anything else, we must invalidate — the other field could have policy implications.

def test_user_save_without_update_fields_invalidates(self):
85    def test_user_save_without_update_fields_invalidates(self):
86        """``update_fields=None`` means a full save — anything could have
87        changed, so we conservatively invalidate."""
88        mock_cache = self._run_handler(sender=User, instance=_FakeUser(), update_fields=None)
89        mock_cache.keys.assert_called()

update_fields=None means a full save — anything could have changed, so we conservatively invalidate.

def test_policy_save_still_invalidates(self):
 91    def test_policy_save_still_invalidates(self):
 92        """Non-User senders are unaffected by the new short-circuit.
 93        Policy/PolicyBinding/PolicyBindingModel/Group saves must continue to
 94        invalidate as before — those changes affect access decisions for
 95        every user."""
 96        binding = _FakeBinding()
 97        mock_cache = self._run_handler(
 98            sender=Policy,
 99            instance=_FakePolicy(),
100            update_fields=["last_login"],  # irrelevant — sender isn't User
101            policy_bindings=[binding],
102        )
103        mock_cache.keys.assert_any_call(f"{CACHE_PREFIX}{binding.policy_binding_uuid.hex}_*")
104        mock_cache.delete_many.assert_called()

Non-User senders are unaffected by the new short-circuit. Policy/PolicyBinding/PolicyBindingModel/Group saves must continue to invalidate as before — those changes affect access decisions for every user.

def test_policy_binding_save_invalidates_binding_cache(self):
106    def test_policy_binding_save_invalidates_binding_cache(self):
107        """Binding updates invalidate every cached result for that binding."""
108        binding = _FakeBinding()
109        with mock.patch.object(signals, "cache") as mock_cache:
110            mock_cache.keys.side_effect = [["policy-cache-key"], []]
111
112            signals.invalidate_policy_cache(
113                sender=PolicyBinding,
114                instance=binding,
115            )
116
117        mock_cache.keys.assert_any_call(f"{CACHE_PREFIX}{binding.policy_binding_uuid.hex}_*")
118        mock_cache.delete_many.assert_any_call(["policy-cache-key"])

Binding updates invalidate every cached result for that binding.

class TestMonitoringSetPolicies(unittest.case.TestCase):
121class TestMonitoringSetPolicies(TestCase):
122    """Test the cached policies gauge."""
123
124    def test_gauge_counts_keys_in_database(self):
125        """The gauge is set from a count query instead of fetching every key."""
126        with (
127            mock.patch.object(signals, "cache") as mock_cache,
128            mock.patch.object(signals, "GAUGE_POLICIES_CACHED") as mock_gauge,
129        ):
130            mock_cache.keys_count.return_value = 3
131
132            signals.monitoring_set_policies(sender=None)
133
134        mock_cache.keys_count.assert_called_once_with(f"{CACHE_PREFIX}*")
135        mock_cache.keys.assert_not_called()
136        mock_gauge.set.assert_called_once_with(3)

Test the cached policies gauge.

def test_gauge_counts_keys_in_database(self):
124    def test_gauge_counts_keys_in_database(self):
125        """The gauge is set from a count query instead of fetching every key."""
126        with (
127            mock.patch.object(signals, "cache") as mock_cache,
128            mock.patch.object(signals, "GAUGE_POLICIES_CACHED") as mock_gauge,
129        ):
130            mock_cache.keys_count.return_value = 3
131
132            signals.monitoring_set_policies(sender=None)
133
134        mock_cache.keys_count.assert_called_once_with(f"{CACHE_PREFIX}*")
135        mock_cache.keys.assert_not_called()
136        mock_gauge.set.assert_called_once_with(3)

The gauge is set from a count query instead of fetching every key.