authentik.root.tests.test_db_router

Tests for the FailoverRouter and the direct database alias.

 1"""Tests for the FailoverRouter and the direct database alias."""
 2
 3from types import SimpleNamespace
 4from unittest.mock import patch
 5
 6from django.db import DEFAULT_DB_ALIAS
 7from django.test import TestCase
 8
 9from authentik.lib.config import DIRECT_DB_ALIAS
10from authentik.root.db.router import FailoverRouter
11
12
13class TestFailoverRouter(TestCase):
14    """The ``direct`` alias is wired up by ``django_db_config`` and used
15    directly by the broker / channel layer. The router must not pull it into
16    the read-replica pool, must not route ORM reads/writes to it, and must
17    block migrations against it (the same database is migrated via
18    ``default``)."""
19
20    def _router_with_databases(self, *aliases: str) -> FailoverRouter:
21        databases = {alias: {"ENGINE": "django.db.backends.postgresql"} for alias in aliases}
22        with patch("authentik.root.db.router.settings") as mock_settings:
23            mock_settings.DATABASES = databases
24            return FailoverRouter()
25
26    def test_direct_alias_excluded_from_replica_pool(self):
27        """The direct alias must never be treated as a read replica."""
28        router = self._router_with_databases(DEFAULT_DB_ALIAS, DIRECT_DB_ALIAS, "replica_0")
29        self.assertNotIn(DIRECT_DB_ALIAS, router.read_replica_aliases)
30        self.assertIn("replica_0", router.read_replica_aliases)
31        self.assertTrue(router.replica_enabled)
32
33    def test_direct_alias_only_does_not_enable_replicas(self):
34        """A deployment with only ``default`` + ``direct`` (no real replicas)
35        must report ``replica_enabled = False`` so ``db_for_read`` keeps
36        returning ``default`` instead of picking from an empty list."""
37        router = self._router_with_databases(DEFAULT_DB_ALIAS, DIRECT_DB_ALIAS)
38        self.assertEqual(router.read_replica_aliases, [])
39        self.assertFalse(router.replica_enabled)
40
41    def test_allow_migrate_blocks_direct_alias(self):
42        """Migrations against the direct alias must be blocked — they would
43        otherwise run twice (once via default, once via direct, both pointing
44        at the same database) or try to acquire the migration advisory lock
45        against a transaction pooler that can't hold it."""
46        router = self._router_with_databases(DEFAULT_DB_ALIAS, DIRECT_DB_ALIAS)
47        self.assertIs(router.allow_migrate(DIRECT_DB_ALIAS, "authentik_core"), False)
48
49    def test_allow_migrate_passes_through_for_other_aliases(self):
50        """Migrations against ``default`` and replicas defer to the downstream
51        ``TenantSyncRouter`` (return None to indicate no opinion)."""
52        router = self._router_with_databases(DEFAULT_DB_ALIAS, DIRECT_DB_ALIAS, "replica_0")
53        self.assertIsNone(router.allow_migrate(DEFAULT_DB_ALIAS, "authentik_core"))
54        self.assertIsNone(router.allow_migrate("replica_0", "authentik_core"))
55
56    def test_db_for_write_is_always_default(self):
57        """Writes never go to the direct alias even when it's configured."""
58        router = self._router_with_databases(DEFAULT_DB_ALIAS, DIRECT_DB_ALIAS, "replica_0")
59        self.assertEqual(router.db_for_write(None), DEFAULT_DB_ALIAS)
60
61    def test_db_for_read_follows_instance(self):
62        """An instance's related objects are read from the database the instance came from,
63        unless that is the direct alias."""
64        router = self._router_with_databases(
65            DEFAULT_DB_ALIAS, DIRECT_DB_ALIAS, "replica_0", "replica_1"
66        )
67        with patch("authentik.root.db.router.connections") as connections:
68            connections.__getitem__.return_value.in_atomic_block = False
69            for alias in (DEFAULT_DB_ALIAS, "replica_0", "replica_1"):
70                instance = SimpleNamespace(_state=SimpleNamespace(db=alias))
71                self.assertEqual(router.db_for_read(None, instance=instance), alias)
72            instance = SimpleNamespace(_state=SimpleNamespace(db=DIRECT_DB_ALIAS))
73            self.assertIn(router.db_for_read(None, instance=instance), router.read_replica_aliases)
74            self.assertIn(router.db_for_read(None), router.read_replica_aliases)
class TestFailoverRouter(django.test.testcases.TestCase):
14class TestFailoverRouter(TestCase):
15    """The ``direct`` alias is wired up by ``django_db_config`` and used
16    directly by the broker / channel layer. The router must not pull it into
17    the read-replica pool, must not route ORM reads/writes to it, and must
18    block migrations against it (the same database is migrated via
19    ``default``)."""
20
21    def _router_with_databases(self, *aliases: str) -> FailoverRouter:
22        databases = {alias: {"ENGINE": "django.db.backends.postgresql"} for alias in aliases}
23        with patch("authentik.root.db.router.settings") as mock_settings:
24            mock_settings.DATABASES = databases
25            return FailoverRouter()
26
27    def test_direct_alias_excluded_from_replica_pool(self):
28        """The direct alias must never be treated as a read replica."""
29        router = self._router_with_databases(DEFAULT_DB_ALIAS, DIRECT_DB_ALIAS, "replica_0")
30        self.assertNotIn(DIRECT_DB_ALIAS, router.read_replica_aliases)
31        self.assertIn("replica_0", router.read_replica_aliases)
32        self.assertTrue(router.replica_enabled)
33
34    def test_direct_alias_only_does_not_enable_replicas(self):
35        """A deployment with only ``default`` + ``direct`` (no real replicas)
36        must report ``replica_enabled = False`` so ``db_for_read`` keeps
37        returning ``default`` instead of picking from an empty list."""
38        router = self._router_with_databases(DEFAULT_DB_ALIAS, DIRECT_DB_ALIAS)
39        self.assertEqual(router.read_replica_aliases, [])
40        self.assertFalse(router.replica_enabled)
41
42    def test_allow_migrate_blocks_direct_alias(self):
43        """Migrations against the direct alias must be blocked — they would
44        otherwise run twice (once via default, once via direct, both pointing
45        at the same database) or try to acquire the migration advisory lock
46        against a transaction pooler that can't hold it."""
47        router = self._router_with_databases(DEFAULT_DB_ALIAS, DIRECT_DB_ALIAS)
48        self.assertIs(router.allow_migrate(DIRECT_DB_ALIAS, "authentik_core"), False)
49
50    def test_allow_migrate_passes_through_for_other_aliases(self):
51        """Migrations against ``default`` and replicas defer to the downstream
52        ``TenantSyncRouter`` (return None to indicate no opinion)."""
53        router = self._router_with_databases(DEFAULT_DB_ALIAS, DIRECT_DB_ALIAS, "replica_0")
54        self.assertIsNone(router.allow_migrate(DEFAULT_DB_ALIAS, "authentik_core"))
55        self.assertIsNone(router.allow_migrate("replica_0", "authentik_core"))
56
57    def test_db_for_write_is_always_default(self):
58        """Writes never go to the direct alias even when it's configured."""
59        router = self._router_with_databases(DEFAULT_DB_ALIAS, DIRECT_DB_ALIAS, "replica_0")
60        self.assertEqual(router.db_for_write(None), DEFAULT_DB_ALIAS)
61
62    def test_db_for_read_follows_instance(self):
63        """An instance's related objects are read from the database the instance came from,
64        unless that is the direct alias."""
65        router = self._router_with_databases(
66            DEFAULT_DB_ALIAS, DIRECT_DB_ALIAS, "replica_0", "replica_1"
67        )
68        with patch("authentik.root.db.router.connections") as connections:
69            connections.__getitem__.return_value.in_atomic_block = False
70            for alias in (DEFAULT_DB_ALIAS, "replica_0", "replica_1"):
71                instance = SimpleNamespace(_state=SimpleNamespace(db=alias))
72                self.assertEqual(router.db_for_read(None, instance=instance), alias)
73            instance = SimpleNamespace(_state=SimpleNamespace(db=DIRECT_DB_ALIAS))
74            self.assertIn(router.db_for_read(None, instance=instance), router.read_replica_aliases)
75            self.assertIn(router.db_for_read(None), router.read_replica_aliases)

The direct alias is wired up by django_db_config and used directly by the broker / channel layer. The router must not pull it into the read-replica pool, must not route ORM reads/writes to it, and must block migrations against it (the same database is migrated via default).

def test_direct_alias_excluded_from_replica_pool(self):
27    def test_direct_alias_excluded_from_replica_pool(self):
28        """The direct alias must never be treated as a read replica."""
29        router = self._router_with_databases(DEFAULT_DB_ALIAS, DIRECT_DB_ALIAS, "replica_0")
30        self.assertNotIn(DIRECT_DB_ALIAS, router.read_replica_aliases)
31        self.assertIn("replica_0", router.read_replica_aliases)
32        self.assertTrue(router.replica_enabled)

The direct alias must never be treated as a read replica.

def test_direct_alias_only_does_not_enable_replicas(self):
34    def test_direct_alias_only_does_not_enable_replicas(self):
35        """A deployment with only ``default`` + ``direct`` (no real replicas)
36        must report ``replica_enabled = False`` so ``db_for_read`` keeps
37        returning ``default`` instead of picking from an empty list."""
38        router = self._router_with_databases(DEFAULT_DB_ALIAS, DIRECT_DB_ALIAS)
39        self.assertEqual(router.read_replica_aliases, [])
40        self.assertFalse(router.replica_enabled)

A deployment with only default + direct (no real replicas) must report replica_enabled = False so db_for_read keeps returning default instead of picking from an empty list.

def test_allow_migrate_blocks_direct_alias(self):
42    def test_allow_migrate_blocks_direct_alias(self):
43        """Migrations against the direct alias must be blocked — they would
44        otherwise run twice (once via default, once via direct, both pointing
45        at the same database) or try to acquire the migration advisory lock
46        against a transaction pooler that can't hold it."""
47        router = self._router_with_databases(DEFAULT_DB_ALIAS, DIRECT_DB_ALIAS)
48        self.assertIs(router.allow_migrate(DIRECT_DB_ALIAS, "authentik_core"), False)

Migrations against the direct alias must be blocked — they would otherwise run twice (once via default, once via direct, both pointing at the same database) or try to acquire the migration advisory lock against a transaction pooler that can't hold it.

def test_allow_migrate_passes_through_for_other_aliases(self):
50    def test_allow_migrate_passes_through_for_other_aliases(self):
51        """Migrations against ``default`` and replicas defer to the downstream
52        ``TenantSyncRouter`` (return None to indicate no opinion)."""
53        router = self._router_with_databases(DEFAULT_DB_ALIAS, DIRECT_DB_ALIAS, "replica_0")
54        self.assertIsNone(router.allow_migrate(DEFAULT_DB_ALIAS, "authentik_core"))
55        self.assertIsNone(router.allow_migrate("replica_0", "authentik_core"))

Migrations against default and replicas defer to the downstream TenantSyncRouter (return None to indicate no opinion).

def test_db_for_write_is_always_default(self):
57    def test_db_for_write_is_always_default(self):
58        """Writes never go to the direct alias even when it's configured."""
59        router = self._router_with_databases(DEFAULT_DB_ALIAS, DIRECT_DB_ALIAS, "replica_0")
60        self.assertEqual(router.db_for_write(None), DEFAULT_DB_ALIAS)

Writes never go to the direct alias even when it's configured.

def test_db_for_read_follows_instance(self):
62    def test_db_for_read_follows_instance(self):
63        """An instance's related objects are read from the database the instance came from,
64        unless that is the direct alias."""
65        router = self._router_with_databases(
66            DEFAULT_DB_ALIAS, DIRECT_DB_ALIAS, "replica_0", "replica_1"
67        )
68        with patch("authentik.root.db.router.connections") as connections:
69            connections.__getitem__.return_value.in_atomic_block = False
70            for alias in (DEFAULT_DB_ALIAS, "replica_0", "replica_1"):
71                instance = SimpleNamespace(_state=SimpleNamespace(db=alias))
72                self.assertEqual(router.db_for_read(None, instance=instance), alias)
73            instance = SimpleNamespace(_state=SimpleNamespace(db=DIRECT_DB_ALIAS))
74            self.assertIn(router.db_for_read(None, instance=instance), router.read_replica_aliases)
75            self.assertIn(router.db_for_read(None), router.read_replica_aliases)

An instance's related objects are read from the database the instance came from, unless that is the direct alias.