authentik.lib.tests.test_config

Test config loader

  1"""Test config loader"""
  2
  3import base64
  4from json import dumps
  5from os import chmod, environ, unlink, write
  6from tempfile import mkstemp
  7from unittest import mock
  8
  9from django.conf import ImproperlyConfigured
 10from django.test import TestCase
 11
 12from authentik.lib.config import (
 13    DIRECT_DB_ALIAS,
 14    ENV_PREFIX,
 15    UNSET,
 16    Attr,
 17    AttrEncoder,
 18    ConfigLoader,
 19    advisory_lock_db_alias,
 20    django_db_config,
 21    postgresql_direct_connection_kwargs,
 22    postgresql_direct_db_enabled,
 23)
 24
 25
 26class TestConfig(TestCase):
 27    """Test config loader"""
 28
 29    check_deprecations_env_vars = {
 30        ENV_PREFIX + "_WORKER__CONCURRENCY": "2",
 31    }
 32
 33    @mock.patch.dict(environ, {ENV_PREFIX + "_test__test": "bar"})
 34    def test_env(self):
 35        """Test simple instance"""
 36        config = ConfigLoader()
 37        config.update_from_env()
 38        self.assertEqual(config.get("test.test"), "bar")
 39
 40    def test_patch(self):
 41        """Test patch decorator"""
 42        config = ConfigLoader()
 43        config.set("foo.bar", "bar")
 44        self.assertEqual(config.get("foo.bar"), "bar")
 45        with config.patch("foo.bar", "baz"):
 46            self.assertEqual(config.get("foo.bar"), "baz")
 47        self.assertEqual(config.get("foo.bar"), "bar")
 48
 49    @mock.patch.dict(environ, {"foo": "bar"})
 50    def test_uri_env(self):
 51        """Test URI parsing (environment)"""
 52        config = ConfigLoader()
 53        foo_uri = "env://foo"
 54        foo_parsed = config.parse_uri(foo_uri)
 55        self.assertEqual(foo_parsed.value, "bar")
 56        self.assertEqual(foo_parsed.source_type, Attr.Source.URI)
 57        self.assertEqual(foo_parsed.source, foo_uri)
 58        foo_bar_uri = "env://foo?bar"
 59        foo_bar_parsed = config.parse_uri(foo_bar_uri)
 60        self.assertEqual(foo_bar_parsed.value, "bar")
 61        self.assertEqual(foo_bar_parsed.source_type, Attr.Source.URI)
 62        self.assertEqual(foo_bar_parsed.source, foo_bar_uri)
 63
 64    def test_uri_file(self):
 65        """Test URI parsing (file load)"""
 66        config = ConfigLoader()
 67        file, file_name = mkstemp()
 68        write(file, b"foo")
 69        _, file2_name = mkstemp()
 70        chmod(file2_name, 0o000)  # Remove all permissions so we can't read the file
 71        self.assertEqual(config.parse_uri(f"file://{file_name}").value, "foo")
 72        self.assertEqual(config.parse_uri(f"file://{file2_name}?def").value, "def")
 73        unlink(file_name)
 74        unlink(file2_name)
 75
 76    def test_uri_file_update(self):
 77        """Test URI parsing (file load and update)"""
 78        file, file_name = mkstemp()
 79        write(file, b"foo")
 80        config = ConfigLoader(file_test=f"file://{file_name}")
 81        self.assertEqual(config.get("file_test"), "foo")
 82
 83        # Update config file
 84        write(file, b"bar")
 85        config.refresh("file_test")
 86        self.assertEqual(config.get("file_test"), "foobar")
 87
 88        unlink(file_name)
 89
 90    def test_uri_env_full(self):
 91        """Test URI set as env variable"""
 92        environ["AUTHENTIK_TEST_VAR"] = "file:///foo?bar"
 93        config = ConfigLoader()
 94        self.assertEqual(config.get("test_var"), "bar")
 95
 96    def test_file_update(self):
 97        """Test update_from_file"""
 98        config = ConfigLoader()
 99        file, file_name = mkstemp()
100        write(file, b"{")
101        file2, file2_name = mkstemp()
102        write(file2, b"{")
103        chmod(file2_name, 0o000)  # Remove all permissions so we can't read the file
104        with self.assertRaises(ImproperlyConfigured):
105            config.update_from_file(file_name)
106        config.update_from_file(file2_name)
107        unlink(file_name)
108        unlink(file2_name)
109
110    def test_get_int(self):
111        """Test get_int"""
112        config = ConfigLoader()
113        config.set("foo", 1234)
114        self.assertEqual(config.get_int("foo"), 1234)
115
116    def test_get_int_invalid(self):
117        """Test get_int"""
118        config = ConfigLoader()
119        config.set("foo", "bar")
120        self.assertEqual(config.get_int("foo", 1234), 1234)
121
122    def test_get_dict_from_b64_json(self):
123        """Test get_dict_from_b64_json"""
124        config = ConfigLoader()
125        test_value = b'  { "foo": "bar"   }   '
126        b64_value = base64.b64encode(test_value)
127        config.set("foo", b64_value)
128        self.assertEqual(config.get_dict_from_b64_json("foo"), {"foo": "bar"})
129
130    def test_get_dict_from_b64_json_missing_brackets(self):
131        """Test get_dict_from_b64_json with missing brackets"""
132        config = ConfigLoader()
133        test_value = b' "foo": "bar"     '
134        b64_value = base64.b64encode(test_value)
135        config.set("foo", b64_value)
136        self.assertEqual(config.get_dict_from_b64_json("foo"), {})
137
138    def test_get_dict_from_b64_json_invalid(self):
139        """Test get_dict_from_b64_json with invalid value"""
140        config = ConfigLoader()
141        config.set("foo", "bar")
142        self.assertEqual(config.get_dict_from_b64_json("foo"), {})
143
144    def test_attr_json_encoder(self):
145        """Test AttrEncoder"""
146        test_attr = Attr("foo", Attr.Source.ENV, "AUTHENTIK_POSTGRESQL__USERNAME")
147        json_attr = dumps(test_attr, indent=4, cls=AttrEncoder)
148        self.assertEqual(json_attr, '"foo"')
149
150    def test_attr_json_encoder_no_attr(self):
151        """Test AttrEncoder if no Attr is passed"""
152
153        class Test:
154            """Non Attr class"""
155
156        with self.assertRaises(TypeError):
157            test_obj = Test()
158            dumps(test_obj, indent=4, cls=AttrEncoder)
159
160    def test_get_optional_int(self):
161        config = ConfigLoader()
162        self.assertEqual(config.get_optional_int("foo", 21), 21)
163        self.assertEqual(config.get_optional_int("foo"), None)
164        config.set("foo", "21")
165        self.assertEqual(config.get_optional_int("foo"), 21)
166        self.assertEqual(config.get_optional_int("foo", 0), 21)
167        self.assertEqual(config.get_optional_int("foo", "null"), 21)
168        config.set("foo", "null")
169        self.assertEqual(config.get_optional_int("foo"), None)
170        self.assertEqual(config.get_optional_int("foo", 21), None)
171
172    @mock.patch.dict(environ, check_deprecations_env_vars)
173    def test_check_deprecations(self):
174        """Test config key re-write for deprecated env vars"""
175        config = ConfigLoader()
176        config.update_from_env()
177        config.check_deprecations()
178        self.assertEqual(config.get("worker.concurrency", UNSET), UNSET)
179        self.assertEqual(config.get("worker.threads"), 2)
180
181    def test_get_keys(self):
182        """Test get_keys"""
183        config = ConfigLoader()
184        config.set("foo.bar", "baz")
185        self.assertEqual(list(config.get_keys("foo")), ["bar"])
186
187    def test_db_default(self):
188        """Test default DB Config"""
189        config = ConfigLoader()
190        config.set("postgresql.host", "foo")
191        config.set("postgresql.name", "foo")
192        config.set("postgresql.user", "foo")
193        config.set("postgresql.password", "foo")
194        config.set("postgresql.port", "foo")
195        config.set("postgresql.sslmode", "foo")
196        config.set("postgresql.sslrootcert", "foo")
197        config.set("postgresql.sslcert", "foo")
198        config.set("postgresql.sslkey", "foo")
199        config.set("postgresql.test.name", "foo")
200        conf = django_db_config(config)
201        self.assertEqual(
202            conf,
203            {
204                "default": {
205                    "ENGINE": "psqlextra.backend",
206                    "HOST": "foo",
207                    "NAME": "foo",
208                    "OPTIONS": {
209                        "pool": False,
210                        "options": "-c TimeZone=UTC",
211                        "sslcert": "foo",
212                        "sslkey": "foo",
213                        "sslmode": "foo",
214                        "sslrootcert": "foo",
215                    },
216                    "PASSWORD": "foo",
217                    "PORT": "foo",
218                    "TEST": {"NAME": "foo"},
219                    "USER": "foo",
220                    "CONN_MAX_AGE": 0,
221                    "CONN_HEALTH_CHECKS": False,
222                    "DISABLE_SERVER_SIDE_CURSORS": False,
223                }
224            },
225        )
226
227    def test_db_conn_max_age(self):
228        """Test DB conn_max_age Config"""
229        config = ConfigLoader()
230        config.set("postgresql.conn_max_age", "null")
231        conf = django_db_config(config)
232        self.assertEqual(
233            conf["default"]["CONN_MAX_AGE"],
234            None,
235        )
236
237    def test_db_read_replicas(self):
238        """Test read replicas"""
239        config = ConfigLoader()
240        config.set("postgresql.host", "foo")
241        config.set("postgresql.name", "foo")
242        config.set("postgresql.user", "foo")
243        config.set("postgresql.password", "foo")
244        config.set("postgresql.port", "foo")
245        config.set("postgresql.sslmode", "foo")
246        config.set("postgresql.sslrootcert", "foo")
247        config.set("postgresql.sslcert", "foo")
248        config.set("postgresql.sslkey", "foo")
249        config.set("postgresql.test.name", "foo")
250        # Read replica
251        config.set("postgresql.read_replicas.0.host", "bar")
252        conf = django_db_config(config)
253        self.assertEqual(
254            conf,
255            {
256                "default": {
257                    "ENGINE": "psqlextra.backend",
258                    "HOST": "foo",
259                    "NAME": "foo",
260                    "OPTIONS": {
261                        "pool": False,
262                        "options": "-c TimeZone=UTC",
263                        "sslcert": "foo",
264                        "sslkey": "foo",
265                        "sslmode": "foo",
266                        "sslrootcert": "foo",
267                    },
268                    "PASSWORD": "foo",
269                    "PORT": "foo",
270                    "TEST": {"NAME": "foo"},
271                    "USER": "foo",
272                    "CONN_MAX_AGE": 0,
273                    "CONN_HEALTH_CHECKS": False,
274                    "DISABLE_SERVER_SIDE_CURSORS": False,
275                },
276                "replica_0": {
277                    "ENGINE": "psqlextra.backend",
278                    "HOST": "bar",
279                    "NAME": "foo",
280                    "OPTIONS": {
281                        "pool": False,
282                        "options": "-c TimeZone=UTC",
283                        "sslcert": "foo",
284                        "sslkey": "foo",
285                        "sslmode": "foo",
286                        "sslrootcert": "foo",
287                    },
288                    "PASSWORD": "foo",
289                    "PORT": "foo",
290                    "TEST": {"NAME": "foo"},
291                    "USER": "foo",
292                    "CONN_MAX_AGE": 0,
293                    "CONN_HEALTH_CHECKS": False,
294                    "DISABLE_SERVER_SIDE_CURSORS": False,
295                },
296            },
297        )
298
299    def test_db_read_replicas_pgbouncer(self):
300        """Test read replicas"""
301        config = ConfigLoader()
302        config.set("postgresql.host", "foo")
303        config.set("postgresql.name", "foo")
304        config.set("postgresql.user", "foo")
305        config.set("postgresql.password", "foo")
306        config.set("postgresql.port", "foo")
307        config.set("postgresql.sslmode", "foo")
308        config.set("postgresql.sslrootcert", "foo")
309        config.set("postgresql.sslcert", "foo")
310        config.set("postgresql.sslkey", "foo")
311        config.set("postgresql.test.name", "foo")
312        config.set("postgresql.use_pgbouncer", True)
313        # Read replica
314        config.set("postgresql.read_replicas.0.host", "bar")
315        # Override conn_max_age
316        config.set("postgresql.read_replicas.0.conn_max_age", 10)
317        # This isn't supported
318        config.set("postgresql.read_replicas.0.use_pgbouncer", False)
319        conf = django_db_config(config)
320        self.assertEqual(
321            conf,
322            {
323                "default": {
324                    "DISABLE_SERVER_SIDE_CURSORS": True,
325                    "CONN_MAX_AGE": 0,
326                    "CONN_HEALTH_CHECKS": False,
327                    "ENGINE": "psqlextra.backend",
328                    "HOST": "foo",
329                    "NAME": "foo",
330                    "OPTIONS": {
331                        "pool": False,
332                        "sslcert": "foo",
333                        "sslkey": "foo",
334                        "sslmode": "foo",
335                        "sslrootcert": "foo",
336                    },
337                    "PASSWORD": "foo",
338                    "PORT": "foo",
339                    "TEST": {"NAME": "foo"},
340                    "USER": "foo",
341                },
342                "replica_0": {
343                    "DISABLE_SERVER_SIDE_CURSORS": True,
344                    "CONN_MAX_AGE": 10,
345                    "CONN_HEALTH_CHECKS": False,
346                    "ENGINE": "psqlextra.backend",
347                    "HOST": "bar",
348                    "NAME": "foo",
349                    "OPTIONS": {
350                        "pool": False,
351                        "sslcert": "foo",
352                        "sslkey": "foo",
353                        "sslmode": "foo",
354                        "sslrootcert": "foo",
355                    },
356                    "PASSWORD": "foo",
357                    "PORT": "foo",
358                    "TEST": {"NAME": "foo"},
359                    "USER": "foo",
360                },
361            },
362        )
363
364    def test_db_read_replicas_pgpool(self):
365        """Test read replicas"""
366        config = ConfigLoader()
367        config.set("postgresql.host", "foo")
368        config.set("postgresql.name", "foo")
369        config.set("postgresql.user", "foo")
370        config.set("postgresql.password", "foo")
371        config.set("postgresql.port", "foo")
372        config.set("postgresql.sslmode", "foo")
373        config.set("postgresql.sslrootcert", "foo")
374        config.set("postgresql.sslcert", "foo")
375        config.set("postgresql.sslkey", "foo")
376        config.set("postgresql.test.name", "foo")
377        config.set("postgresql.use_pgpool", True)
378        # Read replica
379        config.set("postgresql.read_replicas.0.host", "bar")
380        # This isn't supported
381        config.set("postgresql.read_replicas.0.use_pgpool", False)
382        conf = django_db_config(config)
383        self.assertEqual(
384            conf,
385            {
386                "default": {
387                    "DISABLE_SERVER_SIDE_CURSORS": True,
388                    "CONN_MAX_AGE": 0,
389                    "CONN_HEALTH_CHECKS": False,
390                    "ENGINE": "psqlextra.backend",
391                    "HOST": "foo",
392                    "NAME": "foo",
393                    "OPTIONS": {
394                        "pool": False,
395                        "sslcert": "foo",
396                        "sslkey": "foo",
397                        "sslmode": "foo",
398                        "sslrootcert": "foo",
399                    },
400                    "PASSWORD": "foo",
401                    "PORT": "foo",
402                    "TEST": {"NAME": "foo"},
403                    "USER": "foo",
404                },
405                "replica_0": {
406                    "DISABLE_SERVER_SIDE_CURSORS": True,
407                    "CONN_MAX_AGE": 0,
408                    "CONN_HEALTH_CHECKS": False,
409                    "ENGINE": "psqlextra.backend",
410                    "HOST": "bar",
411                    "NAME": "foo",
412                    "OPTIONS": {
413                        "pool": False,
414                        "sslcert": "foo",
415                        "sslkey": "foo",
416                        "sslmode": "foo",
417                        "sslrootcert": "foo",
418                    },
419                    "PASSWORD": "foo",
420                    "PORT": "foo",
421                    "TEST": {"NAME": "foo"},
422                    "USER": "foo",
423                },
424            },
425        )
426
427    def test_db_read_replicas_diff_ssl(self):
428        """Test read replicas (with different SSL Settings)"""
429        """Test read replicas"""
430        config = ConfigLoader()
431        config.set("postgresql.host", "foo")
432        config.set("postgresql.name", "foo")
433        config.set("postgresql.user", "foo")
434        config.set("postgresql.password", "foo")
435        config.set("postgresql.port", "foo")
436        config.set("postgresql.sslmode", "foo")
437        config.set("postgresql.sslrootcert", "foo")
438        config.set("postgresql.sslcert", "foo")
439        config.set("postgresql.sslkey", "foo")
440        config.set("postgresql.test.name", "foo")
441        # Read replica
442        config.set("postgresql.read_replicas.0.host", "bar")
443        config.set("postgresql.read_replicas.0.sslcert", "bar")
444        conf = django_db_config(config)
445        self.assertEqual(
446            conf,
447            {
448                "default": {
449                    "ENGINE": "psqlextra.backend",
450                    "HOST": "foo",
451                    "NAME": "foo",
452                    "OPTIONS": {
453                        "pool": False,
454                        "options": "-c TimeZone=UTC",
455                        "sslcert": "foo",
456                        "sslkey": "foo",
457                        "sslmode": "foo",
458                        "sslrootcert": "foo",
459                    },
460                    "PASSWORD": "foo",
461                    "PORT": "foo",
462                    "TEST": {"NAME": "foo"},
463                    "USER": "foo",
464                    "DISABLE_SERVER_SIDE_CURSORS": False,
465                    "CONN_MAX_AGE": 0,
466                    "CONN_HEALTH_CHECKS": False,
467                },
468                "replica_0": {
469                    "ENGINE": "psqlextra.backend",
470                    "HOST": "bar",
471                    "NAME": "foo",
472                    "OPTIONS": {
473                        "pool": False,
474                        "options": "-c TimeZone=UTC",
475                        "sslcert": "bar",
476                        "sslkey": "foo",
477                        "sslmode": "foo",
478                        "sslrootcert": "foo",
479                    },
480                    "PASSWORD": "foo",
481                    "PORT": "foo",
482                    "TEST": {"NAME": "foo"},
483                    "USER": "foo",
484                    "DISABLE_SERVER_SIDE_CURSORS": False,
485                    "CONN_MAX_AGE": 0,
486                    "CONN_HEALTH_CHECKS": False,
487                },
488            },
489        )
490
491    def test_db_conn_options(self):
492        config = ConfigLoader()
493        config.set(
494            "postgresql.conn_options",
495            base64.b64encode(
496                dumps(
497                    {
498                        "connect_timeout": "10",
499                    }
500                ).encode()
501            ).decode(),
502        )
503        config.set("postgresql.read_replicas.0.host", "bar")
504
505        conf = django_db_config(config)
506
507        self.assertEqual(
508            conf["default"]["OPTIONS"]["connect_timeout"],
509            "10",
510        )
511        self.assertNotIn("connect_timeout", conf["replica_0"]["OPTIONS"])
512
513    def test_db_timezone_option(self):
514        """Test TimeZone connect option is skipped for poolers and doesn't override user options"""
515        for pooler in ("postgresql.use_pgbouncer", "postgresql.use_pgpool"):
516            config = ConfigLoader()
517            config.set(pooler, True)
518            self.assertNotIn("options", django_db_config(config)["default"]["OPTIONS"])
519        config = ConfigLoader()
520        config.set(
521            "postgresql.conn_options",
522            base64.b64encode(dumps({"options": "-c search_path=foo"}).encode()).decode(),
523        )
524        self.assertEqual(
525            django_db_config(config)["default"]["OPTIONS"]["options"], "-c search_path=foo"
526        )
527
528    def test_db_conn_options_read_replicas(self):
529        config = ConfigLoader()
530        config.set(
531            "postgresql.replica_conn_options",
532            base64.b64encode(
533                dumps(
534                    {
535                        "connect_timeout": "10",
536                    }
537                ).encode()
538            ).decode(),
539        )
540        config.set("postgresql.read_replicas.0.host", "bar")
541        config.set("postgresql.read_replicas.1.host", "bar")
542        config.set(
543            "postgresql.read_replicas.1.conn_options",
544            base64.b64encode(
545                dumps(
546                    {
547                        "connect_timeout": "20",
548                    }
549                ).encode()
550            ).decode(),
551        )
552
553        conf = django_db_config(config)
554
555        self.assertNotIn("connect_timeout", conf["default"]["OPTIONS"])
556        self.assertEqual(
557            conf["replica_0"]["OPTIONS"]["connect_timeout"],
558            "10",
559        )
560        self.assertEqual(
561            conf["replica_1"]["OPTIONS"]["connect_timeout"],
562            "20",
563        )
564
565    def test_db_pool(self):
566        """Test DB Config with pool"""
567        config = ConfigLoader()
568        config.set("postgresql.use_pool", True)
569        conf = django_db_config(config)
570        self.assertEqual(conf["default"]["OPTIONS"]["pool"], {"max_size": 10})
571        self.assertEqual(conf["default"]["CONN_MAX_AGE"], 0)
572        # Long-lived connections (LISTEN, advisory locks) must not hold pool slots
573        self.assertTrue(postgresql_direct_db_enabled(config))
574        self.assertFalse(conf[DIRECT_DB_ALIAS]["OPTIONS"]["pool"])
575
576    def test_db_pool_worker_threads(self):
577        """Test DB Config with pool sized for worker threads"""
578        config = ConfigLoader()
579        config.set("postgresql.use_pool", True)
580        config.set("worker.threads", 16)
581        conf = django_db_config(config)
582        self.assertEqual(conf["default"]["OPTIONS"]["pool"], {"max_size": 17})
583
584    def test_db_pool_options(self):
585        """Test DB Config with pool options"""
586        config = ConfigLoader()
587        config.set("postgresql.use_pool", True)
588        config.set(
589            "postgresql.pool_options",
590            base64.b64encode(dumps({"max_size": 15}).encode()).decode(),
591        )
592        conf = django_db_config(config)
593        self.assertEqual(conf["default"]["OPTIONS"]["pool"], {"max_size": 15})
594
595    # --- Session-mode PostgreSQL endpoint ---
596
597    def _set_main_postgres(self, config: ConfigLoader) -> None:
598        config.set("postgresql.host", "main-host")
599        config.set("postgresql.name", "main-db")
600        config.set("postgresql.user", "main-user")
601        config.set("postgresql.password", "main-pass")
602        config.set("postgresql.port", 6432)
603        config.set("postgresql.sslmode", "require")
604        config.set("postgresql.sslrootcert", "main-ca.pem")
605        config.set("postgresql.sslcert", "main-client.pem")
606        config.set("postgresql.sslkey", "main-client.key")
607        config.set("postgresql.test.name", "test_main")
608
609    def test_postgresql_direct_db_disabled_by_default(self):
610        """With no postgresql.direct.* keys, the direct alias is not added."""
611        config = ConfigLoader()
612        self._set_main_postgres(config)
613        self.assertFalse(postgresql_direct_db_enabled(config))
614        conf = django_db_config(config)
615        self.assertNotIn(DIRECT_DB_ALIAS, conf)
616
617    def test_postgresql_direct_kwargs_fallback(self):
618        """Without overrides, direct connection kwargs mirror the main params."""
619        config = ConfigLoader()
620        self._set_main_postgres(config)
621        kwargs = postgresql_direct_connection_kwargs(config)
622        self.assertEqual(
623            kwargs,
624            {
625                "host": "main-host",
626                "port": 6432,
627                "dbname": "main-db",
628                "user": "main-user",
629                "password": "main-pass",
630                "sslmode": "require",
631                "sslrootcert": "main-ca.pem",
632                "sslcert": "main-client.pem",
633                "sslkey": "main-client.key",
634            },
635        )
636
637    def test_postgresql_direct_kwargs_override(self):
638        """Direct keys override the corresponding main keys; others fall through."""
639        config = ConfigLoader()
640        self._set_main_postgres(config)
641        # Operator scenario: transaction-pool pgbouncer on 6432 + direct PG on 5432.
642        config.set("postgresql.direct.host", "direct-pg")
643        config.set("postgresql.direct.port", 5432)
644        kwargs = postgresql_direct_connection_kwargs(config)
645        self.assertEqual(kwargs["host"], "direct-pg")
646        self.assertEqual(kwargs["port"], 5432)
647        self.assertEqual(kwargs["dbname"], "main-db")
648        self.assertEqual(kwargs["user"], "main-user")
649        self.assertEqual(kwargs["password"], "main-pass")
650        self.assertEqual(kwargs["sslmode"], "require")
651
652    def test_postgresql_direct_kwargs_strips_none(self):
653        """None values are stripped so libpq applies defaults — without this,
654        ``psycopg.connect(sslmode=None)`` would raise."""
655        config = ConfigLoader()
656        config.set("postgresql.host", "main-host")
657        config.set("postgresql.name", "main-db")
658        config.set("postgresql.user", "main-user")
659        config.set("postgresql.password", "main-pass")
660        config.set("postgresql.port", 5432)
661        config.set("postgresql.sslmode", None)
662        config.set("postgresql.sslrootcert", None)
663        config.set("postgresql.sslcert", None)
664        config.set("postgresql.sslkey", None)
665        kwargs = postgresql_direct_connection_kwargs(config)
666        for ssl_key in ("sslmode", "sslrootcert", "sslcert", "sslkey"):
667            self.assertNotIn(ssl_key, kwargs)
668
669    def test_postgresql_direct_db_adds_alias(self):
670        """Setting any postgresql.direct.* key adds the direct Django alias."""
671        config = ConfigLoader()
672        self._set_main_postgres(config)
673        config.set("postgresql.direct.host", "direct-pg")
674        config.set("postgresql.direct.port", 5432)
675        self.assertTrue(postgresql_direct_db_enabled(config))
676        conf = django_db_config(config)
677        self.assertIn(DIRECT_DB_ALIAS, conf)
678        direct = conf[DIRECT_DB_ALIAS]
679        self.assertEqual(direct["HOST"], "direct-pg")
680        self.assertEqual(direct["PORT"], 5432)
681        self.assertEqual(direct["NAME"], "main-db")
682        self.assertEqual(direct["USER"], "main-user")
683        self.assertEqual(direct["PASSWORD"], "main-pass")
684        # Managed manually by broker / channel layer
685        self.assertIsNone(direct["CONN_MAX_AGE"])
686        self.assertFalse(direct["CONN_HEALTH_CHECKS"])
687        # Default alias unaffected
688        self.assertEqual(conf["default"]["HOST"], "main-host")
689        self.assertEqual(conf["default"]["PORT"], 6432)
690
691    def test_postgresql_direct_db_with_replicas(self):
692        """The direct alias is added alongside read replicas without conflict."""
693        config = ConfigLoader()
694        self._set_main_postgres(config)
695        config.set("postgresql.read_replicas.0.host", "replica-0")
696        config.set("postgresql.direct.host", "direct-pg")
697        conf = django_db_config(config)
698        self.assertIn("default", conf)
699        self.assertIn("replica_0", conf)
700        self.assertIn(DIRECT_DB_ALIAS, conf)
701        self.assertEqual(conf[DIRECT_DB_ALIAS]["HOST"], "direct-pg")
702        self.assertEqual(conf["replica_0"]["HOST"], "replica-0")
703
704    def test_postgresql_direct_kwargs_merges_conn_options(self):
705        """postgresql.direct.conn_options takes precedence over postgresql.conn_options."""
706        config = ConfigLoader()
707        self._set_main_postgres(config)
708        config.set(
709            "postgresql.conn_options",
710            base64.b64encode(
711                dumps({"application_name": "authentik", "keepalives": 1}).encode()
712            ).decode(),
713        )
714        config.set(
715            "postgresql.direct.conn_options",
716            base64.b64encode(dumps({"application_name": "authentik-direct"}).encode()).decode(),
717        )
718        kwargs = postgresql_direct_connection_kwargs(config)
719        self.assertEqual(kwargs["application_name"], "authentik-direct")
720        self.assertEqual(kwargs["keepalives"], 1)
721
722    def test_advisory_lock_db_alias_defaults_to_default(self):
723        """Without postgresql.direct.*, advisory locks stay on the default alias."""
724        config = ConfigLoader()
725        self._set_main_postgres(config)
726        self.assertEqual(advisory_lock_db_alias(config), "default")
727
728    def test_advisory_lock_db_alias_uses_direct_when_enabled(self):
729        """With a direct endpoint configured, advisory locks route through it
730        so they survive a transaction-mode pooler in front of ``postgresql.host``."""
731        config = ConfigLoader()
732        self._set_main_postgres(config)
733        config.set("postgresql.direct.host", "direct-pg")
734        self.assertEqual(advisory_lock_db_alias(config), DIRECT_DB_ALIAS)
class TestConfig(django.test.testcases.TestCase):
 27class TestConfig(TestCase):
 28    """Test config loader"""
 29
 30    check_deprecations_env_vars = {
 31        ENV_PREFIX + "_WORKER__CONCURRENCY": "2",
 32    }
 33
 34    @mock.patch.dict(environ, {ENV_PREFIX + "_test__test": "bar"})
 35    def test_env(self):
 36        """Test simple instance"""
 37        config = ConfigLoader()
 38        config.update_from_env()
 39        self.assertEqual(config.get("test.test"), "bar")
 40
 41    def test_patch(self):
 42        """Test patch decorator"""
 43        config = ConfigLoader()
 44        config.set("foo.bar", "bar")
 45        self.assertEqual(config.get("foo.bar"), "bar")
 46        with config.patch("foo.bar", "baz"):
 47            self.assertEqual(config.get("foo.bar"), "baz")
 48        self.assertEqual(config.get("foo.bar"), "bar")
 49
 50    @mock.patch.dict(environ, {"foo": "bar"})
 51    def test_uri_env(self):
 52        """Test URI parsing (environment)"""
 53        config = ConfigLoader()
 54        foo_uri = "env://foo"
 55        foo_parsed = config.parse_uri(foo_uri)
 56        self.assertEqual(foo_parsed.value, "bar")
 57        self.assertEqual(foo_parsed.source_type, Attr.Source.URI)
 58        self.assertEqual(foo_parsed.source, foo_uri)
 59        foo_bar_uri = "env://foo?bar"
 60        foo_bar_parsed = config.parse_uri(foo_bar_uri)
 61        self.assertEqual(foo_bar_parsed.value, "bar")
 62        self.assertEqual(foo_bar_parsed.source_type, Attr.Source.URI)
 63        self.assertEqual(foo_bar_parsed.source, foo_bar_uri)
 64
 65    def test_uri_file(self):
 66        """Test URI parsing (file load)"""
 67        config = ConfigLoader()
 68        file, file_name = mkstemp()
 69        write(file, b"foo")
 70        _, file2_name = mkstemp()
 71        chmod(file2_name, 0o000)  # Remove all permissions so we can't read the file
 72        self.assertEqual(config.parse_uri(f"file://{file_name}").value, "foo")
 73        self.assertEqual(config.parse_uri(f"file://{file2_name}?def").value, "def")
 74        unlink(file_name)
 75        unlink(file2_name)
 76
 77    def test_uri_file_update(self):
 78        """Test URI parsing (file load and update)"""
 79        file, file_name = mkstemp()
 80        write(file, b"foo")
 81        config = ConfigLoader(file_test=f"file://{file_name}")
 82        self.assertEqual(config.get("file_test"), "foo")
 83
 84        # Update config file
 85        write(file, b"bar")
 86        config.refresh("file_test")
 87        self.assertEqual(config.get("file_test"), "foobar")
 88
 89        unlink(file_name)
 90
 91    def test_uri_env_full(self):
 92        """Test URI set as env variable"""
 93        environ["AUTHENTIK_TEST_VAR"] = "file:///foo?bar"
 94        config = ConfigLoader()
 95        self.assertEqual(config.get("test_var"), "bar")
 96
 97    def test_file_update(self):
 98        """Test update_from_file"""
 99        config = ConfigLoader()
100        file, file_name = mkstemp()
101        write(file, b"{")
102        file2, file2_name = mkstemp()
103        write(file2, b"{")
104        chmod(file2_name, 0o000)  # Remove all permissions so we can't read the file
105        with self.assertRaises(ImproperlyConfigured):
106            config.update_from_file(file_name)
107        config.update_from_file(file2_name)
108        unlink(file_name)
109        unlink(file2_name)
110
111    def test_get_int(self):
112        """Test get_int"""
113        config = ConfigLoader()
114        config.set("foo", 1234)
115        self.assertEqual(config.get_int("foo"), 1234)
116
117    def test_get_int_invalid(self):
118        """Test get_int"""
119        config = ConfigLoader()
120        config.set("foo", "bar")
121        self.assertEqual(config.get_int("foo", 1234), 1234)
122
123    def test_get_dict_from_b64_json(self):
124        """Test get_dict_from_b64_json"""
125        config = ConfigLoader()
126        test_value = b'  { "foo": "bar"   }   '
127        b64_value = base64.b64encode(test_value)
128        config.set("foo", b64_value)
129        self.assertEqual(config.get_dict_from_b64_json("foo"), {"foo": "bar"})
130
131    def test_get_dict_from_b64_json_missing_brackets(self):
132        """Test get_dict_from_b64_json with missing brackets"""
133        config = ConfigLoader()
134        test_value = b' "foo": "bar"     '
135        b64_value = base64.b64encode(test_value)
136        config.set("foo", b64_value)
137        self.assertEqual(config.get_dict_from_b64_json("foo"), {})
138
139    def test_get_dict_from_b64_json_invalid(self):
140        """Test get_dict_from_b64_json with invalid value"""
141        config = ConfigLoader()
142        config.set("foo", "bar")
143        self.assertEqual(config.get_dict_from_b64_json("foo"), {})
144
145    def test_attr_json_encoder(self):
146        """Test AttrEncoder"""
147        test_attr = Attr("foo", Attr.Source.ENV, "AUTHENTIK_POSTGRESQL__USERNAME")
148        json_attr = dumps(test_attr, indent=4, cls=AttrEncoder)
149        self.assertEqual(json_attr, '"foo"')
150
151    def test_attr_json_encoder_no_attr(self):
152        """Test AttrEncoder if no Attr is passed"""
153
154        class Test:
155            """Non Attr class"""
156
157        with self.assertRaises(TypeError):
158            test_obj = Test()
159            dumps(test_obj, indent=4, cls=AttrEncoder)
160
161    def test_get_optional_int(self):
162        config = ConfigLoader()
163        self.assertEqual(config.get_optional_int("foo", 21), 21)
164        self.assertEqual(config.get_optional_int("foo"), None)
165        config.set("foo", "21")
166        self.assertEqual(config.get_optional_int("foo"), 21)
167        self.assertEqual(config.get_optional_int("foo", 0), 21)
168        self.assertEqual(config.get_optional_int("foo", "null"), 21)
169        config.set("foo", "null")
170        self.assertEqual(config.get_optional_int("foo"), None)
171        self.assertEqual(config.get_optional_int("foo", 21), None)
172
173    @mock.patch.dict(environ, check_deprecations_env_vars)
174    def test_check_deprecations(self):
175        """Test config key re-write for deprecated env vars"""
176        config = ConfigLoader()
177        config.update_from_env()
178        config.check_deprecations()
179        self.assertEqual(config.get("worker.concurrency", UNSET), UNSET)
180        self.assertEqual(config.get("worker.threads"), 2)
181
182    def test_get_keys(self):
183        """Test get_keys"""
184        config = ConfigLoader()
185        config.set("foo.bar", "baz")
186        self.assertEqual(list(config.get_keys("foo")), ["bar"])
187
188    def test_db_default(self):
189        """Test default DB Config"""
190        config = ConfigLoader()
191        config.set("postgresql.host", "foo")
192        config.set("postgresql.name", "foo")
193        config.set("postgresql.user", "foo")
194        config.set("postgresql.password", "foo")
195        config.set("postgresql.port", "foo")
196        config.set("postgresql.sslmode", "foo")
197        config.set("postgresql.sslrootcert", "foo")
198        config.set("postgresql.sslcert", "foo")
199        config.set("postgresql.sslkey", "foo")
200        config.set("postgresql.test.name", "foo")
201        conf = django_db_config(config)
202        self.assertEqual(
203            conf,
204            {
205                "default": {
206                    "ENGINE": "psqlextra.backend",
207                    "HOST": "foo",
208                    "NAME": "foo",
209                    "OPTIONS": {
210                        "pool": False,
211                        "options": "-c TimeZone=UTC",
212                        "sslcert": "foo",
213                        "sslkey": "foo",
214                        "sslmode": "foo",
215                        "sslrootcert": "foo",
216                    },
217                    "PASSWORD": "foo",
218                    "PORT": "foo",
219                    "TEST": {"NAME": "foo"},
220                    "USER": "foo",
221                    "CONN_MAX_AGE": 0,
222                    "CONN_HEALTH_CHECKS": False,
223                    "DISABLE_SERVER_SIDE_CURSORS": False,
224                }
225            },
226        )
227
228    def test_db_conn_max_age(self):
229        """Test DB conn_max_age Config"""
230        config = ConfigLoader()
231        config.set("postgresql.conn_max_age", "null")
232        conf = django_db_config(config)
233        self.assertEqual(
234            conf["default"]["CONN_MAX_AGE"],
235            None,
236        )
237
238    def test_db_read_replicas(self):
239        """Test read replicas"""
240        config = ConfigLoader()
241        config.set("postgresql.host", "foo")
242        config.set("postgresql.name", "foo")
243        config.set("postgresql.user", "foo")
244        config.set("postgresql.password", "foo")
245        config.set("postgresql.port", "foo")
246        config.set("postgresql.sslmode", "foo")
247        config.set("postgresql.sslrootcert", "foo")
248        config.set("postgresql.sslcert", "foo")
249        config.set("postgresql.sslkey", "foo")
250        config.set("postgresql.test.name", "foo")
251        # Read replica
252        config.set("postgresql.read_replicas.0.host", "bar")
253        conf = django_db_config(config)
254        self.assertEqual(
255            conf,
256            {
257                "default": {
258                    "ENGINE": "psqlextra.backend",
259                    "HOST": "foo",
260                    "NAME": "foo",
261                    "OPTIONS": {
262                        "pool": False,
263                        "options": "-c TimeZone=UTC",
264                        "sslcert": "foo",
265                        "sslkey": "foo",
266                        "sslmode": "foo",
267                        "sslrootcert": "foo",
268                    },
269                    "PASSWORD": "foo",
270                    "PORT": "foo",
271                    "TEST": {"NAME": "foo"},
272                    "USER": "foo",
273                    "CONN_MAX_AGE": 0,
274                    "CONN_HEALTH_CHECKS": False,
275                    "DISABLE_SERVER_SIDE_CURSORS": False,
276                },
277                "replica_0": {
278                    "ENGINE": "psqlextra.backend",
279                    "HOST": "bar",
280                    "NAME": "foo",
281                    "OPTIONS": {
282                        "pool": False,
283                        "options": "-c TimeZone=UTC",
284                        "sslcert": "foo",
285                        "sslkey": "foo",
286                        "sslmode": "foo",
287                        "sslrootcert": "foo",
288                    },
289                    "PASSWORD": "foo",
290                    "PORT": "foo",
291                    "TEST": {"NAME": "foo"},
292                    "USER": "foo",
293                    "CONN_MAX_AGE": 0,
294                    "CONN_HEALTH_CHECKS": False,
295                    "DISABLE_SERVER_SIDE_CURSORS": False,
296                },
297            },
298        )
299
300    def test_db_read_replicas_pgbouncer(self):
301        """Test read replicas"""
302        config = ConfigLoader()
303        config.set("postgresql.host", "foo")
304        config.set("postgresql.name", "foo")
305        config.set("postgresql.user", "foo")
306        config.set("postgresql.password", "foo")
307        config.set("postgresql.port", "foo")
308        config.set("postgresql.sslmode", "foo")
309        config.set("postgresql.sslrootcert", "foo")
310        config.set("postgresql.sslcert", "foo")
311        config.set("postgresql.sslkey", "foo")
312        config.set("postgresql.test.name", "foo")
313        config.set("postgresql.use_pgbouncer", True)
314        # Read replica
315        config.set("postgresql.read_replicas.0.host", "bar")
316        # Override conn_max_age
317        config.set("postgresql.read_replicas.0.conn_max_age", 10)
318        # This isn't supported
319        config.set("postgresql.read_replicas.0.use_pgbouncer", False)
320        conf = django_db_config(config)
321        self.assertEqual(
322            conf,
323            {
324                "default": {
325                    "DISABLE_SERVER_SIDE_CURSORS": True,
326                    "CONN_MAX_AGE": 0,
327                    "CONN_HEALTH_CHECKS": False,
328                    "ENGINE": "psqlextra.backend",
329                    "HOST": "foo",
330                    "NAME": "foo",
331                    "OPTIONS": {
332                        "pool": False,
333                        "sslcert": "foo",
334                        "sslkey": "foo",
335                        "sslmode": "foo",
336                        "sslrootcert": "foo",
337                    },
338                    "PASSWORD": "foo",
339                    "PORT": "foo",
340                    "TEST": {"NAME": "foo"},
341                    "USER": "foo",
342                },
343                "replica_0": {
344                    "DISABLE_SERVER_SIDE_CURSORS": True,
345                    "CONN_MAX_AGE": 10,
346                    "CONN_HEALTH_CHECKS": False,
347                    "ENGINE": "psqlextra.backend",
348                    "HOST": "bar",
349                    "NAME": "foo",
350                    "OPTIONS": {
351                        "pool": False,
352                        "sslcert": "foo",
353                        "sslkey": "foo",
354                        "sslmode": "foo",
355                        "sslrootcert": "foo",
356                    },
357                    "PASSWORD": "foo",
358                    "PORT": "foo",
359                    "TEST": {"NAME": "foo"},
360                    "USER": "foo",
361                },
362            },
363        )
364
365    def test_db_read_replicas_pgpool(self):
366        """Test read replicas"""
367        config = ConfigLoader()
368        config.set("postgresql.host", "foo")
369        config.set("postgresql.name", "foo")
370        config.set("postgresql.user", "foo")
371        config.set("postgresql.password", "foo")
372        config.set("postgresql.port", "foo")
373        config.set("postgresql.sslmode", "foo")
374        config.set("postgresql.sslrootcert", "foo")
375        config.set("postgresql.sslcert", "foo")
376        config.set("postgresql.sslkey", "foo")
377        config.set("postgresql.test.name", "foo")
378        config.set("postgresql.use_pgpool", True)
379        # Read replica
380        config.set("postgresql.read_replicas.0.host", "bar")
381        # This isn't supported
382        config.set("postgresql.read_replicas.0.use_pgpool", False)
383        conf = django_db_config(config)
384        self.assertEqual(
385            conf,
386            {
387                "default": {
388                    "DISABLE_SERVER_SIDE_CURSORS": True,
389                    "CONN_MAX_AGE": 0,
390                    "CONN_HEALTH_CHECKS": False,
391                    "ENGINE": "psqlextra.backend",
392                    "HOST": "foo",
393                    "NAME": "foo",
394                    "OPTIONS": {
395                        "pool": False,
396                        "sslcert": "foo",
397                        "sslkey": "foo",
398                        "sslmode": "foo",
399                        "sslrootcert": "foo",
400                    },
401                    "PASSWORD": "foo",
402                    "PORT": "foo",
403                    "TEST": {"NAME": "foo"},
404                    "USER": "foo",
405                },
406                "replica_0": {
407                    "DISABLE_SERVER_SIDE_CURSORS": True,
408                    "CONN_MAX_AGE": 0,
409                    "CONN_HEALTH_CHECKS": False,
410                    "ENGINE": "psqlextra.backend",
411                    "HOST": "bar",
412                    "NAME": "foo",
413                    "OPTIONS": {
414                        "pool": False,
415                        "sslcert": "foo",
416                        "sslkey": "foo",
417                        "sslmode": "foo",
418                        "sslrootcert": "foo",
419                    },
420                    "PASSWORD": "foo",
421                    "PORT": "foo",
422                    "TEST": {"NAME": "foo"},
423                    "USER": "foo",
424                },
425            },
426        )
427
428    def test_db_read_replicas_diff_ssl(self):
429        """Test read replicas (with different SSL Settings)"""
430        """Test read replicas"""
431        config = ConfigLoader()
432        config.set("postgresql.host", "foo")
433        config.set("postgresql.name", "foo")
434        config.set("postgresql.user", "foo")
435        config.set("postgresql.password", "foo")
436        config.set("postgresql.port", "foo")
437        config.set("postgresql.sslmode", "foo")
438        config.set("postgresql.sslrootcert", "foo")
439        config.set("postgresql.sslcert", "foo")
440        config.set("postgresql.sslkey", "foo")
441        config.set("postgresql.test.name", "foo")
442        # Read replica
443        config.set("postgresql.read_replicas.0.host", "bar")
444        config.set("postgresql.read_replicas.0.sslcert", "bar")
445        conf = django_db_config(config)
446        self.assertEqual(
447            conf,
448            {
449                "default": {
450                    "ENGINE": "psqlextra.backend",
451                    "HOST": "foo",
452                    "NAME": "foo",
453                    "OPTIONS": {
454                        "pool": False,
455                        "options": "-c TimeZone=UTC",
456                        "sslcert": "foo",
457                        "sslkey": "foo",
458                        "sslmode": "foo",
459                        "sslrootcert": "foo",
460                    },
461                    "PASSWORD": "foo",
462                    "PORT": "foo",
463                    "TEST": {"NAME": "foo"},
464                    "USER": "foo",
465                    "DISABLE_SERVER_SIDE_CURSORS": False,
466                    "CONN_MAX_AGE": 0,
467                    "CONN_HEALTH_CHECKS": False,
468                },
469                "replica_0": {
470                    "ENGINE": "psqlextra.backend",
471                    "HOST": "bar",
472                    "NAME": "foo",
473                    "OPTIONS": {
474                        "pool": False,
475                        "options": "-c TimeZone=UTC",
476                        "sslcert": "bar",
477                        "sslkey": "foo",
478                        "sslmode": "foo",
479                        "sslrootcert": "foo",
480                    },
481                    "PASSWORD": "foo",
482                    "PORT": "foo",
483                    "TEST": {"NAME": "foo"},
484                    "USER": "foo",
485                    "DISABLE_SERVER_SIDE_CURSORS": False,
486                    "CONN_MAX_AGE": 0,
487                    "CONN_HEALTH_CHECKS": False,
488                },
489            },
490        )
491
492    def test_db_conn_options(self):
493        config = ConfigLoader()
494        config.set(
495            "postgresql.conn_options",
496            base64.b64encode(
497                dumps(
498                    {
499                        "connect_timeout": "10",
500                    }
501                ).encode()
502            ).decode(),
503        )
504        config.set("postgresql.read_replicas.0.host", "bar")
505
506        conf = django_db_config(config)
507
508        self.assertEqual(
509            conf["default"]["OPTIONS"]["connect_timeout"],
510            "10",
511        )
512        self.assertNotIn("connect_timeout", conf["replica_0"]["OPTIONS"])
513
514    def test_db_timezone_option(self):
515        """Test TimeZone connect option is skipped for poolers and doesn't override user options"""
516        for pooler in ("postgresql.use_pgbouncer", "postgresql.use_pgpool"):
517            config = ConfigLoader()
518            config.set(pooler, True)
519            self.assertNotIn("options", django_db_config(config)["default"]["OPTIONS"])
520        config = ConfigLoader()
521        config.set(
522            "postgresql.conn_options",
523            base64.b64encode(dumps({"options": "-c search_path=foo"}).encode()).decode(),
524        )
525        self.assertEqual(
526            django_db_config(config)["default"]["OPTIONS"]["options"], "-c search_path=foo"
527        )
528
529    def test_db_conn_options_read_replicas(self):
530        config = ConfigLoader()
531        config.set(
532            "postgresql.replica_conn_options",
533            base64.b64encode(
534                dumps(
535                    {
536                        "connect_timeout": "10",
537                    }
538                ).encode()
539            ).decode(),
540        )
541        config.set("postgresql.read_replicas.0.host", "bar")
542        config.set("postgresql.read_replicas.1.host", "bar")
543        config.set(
544            "postgresql.read_replicas.1.conn_options",
545            base64.b64encode(
546                dumps(
547                    {
548                        "connect_timeout": "20",
549                    }
550                ).encode()
551            ).decode(),
552        )
553
554        conf = django_db_config(config)
555
556        self.assertNotIn("connect_timeout", conf["default"]["OPTIONS"])
557        self.assertEqual(
558            conf["replica_0"]["OPTIONS"]["connect_timeout"],
559            "10",
560        )
561        self.assertEqual(
562            conf["replica_1"]["OPTIONS"]["connect_timeout"],
563            "20",
564        )
565
566    def test_db_pool(self):
567        """Test DB Config with pool"""
568        config = ConfigLoader()
569        config.set("postgresql.use_pool", True)
570        conf = django_db_config(config)
571        self.assertEqual(conf["default"]["OPTIONS"]["pool"], {"max_size": 10})
572        self.assertEqual(conf["default"]["CONN_MAX_AGE"], 0)
573        # Long-lived connections (LISTEN, advisory locks) must not hold pool slots
574        self.assertTrue(postgresql_direct_db_enabled(config))
575        self.assertFalse(conf[DIRECT_DB_ALIAS]["OPTIONS"]["pool"])
576
577    def test_db_pool_worker_threads(self):
578        """Test DB Config with pool sized for worker threads"""
579        config = ConfigLoader()
580        config.set("postgresql.use_pool", True)
581        config.set("worker.threads", 16)
582        conf = django_db_config(config)
583        self.assertEqual(conf["default"]["OPTIONS"]["pool"], {"max_size": 17})
584
585    def test_db_pool_options(self):
586        """Test DB Config with pool options"""
587        config = ConfigLoader()
588        config.set("postgresql.use_pool", True)
589        config.set(
590            "postgresql.pool_options",
591            base64.b64encode(dumps({"max_size": 15}).encode()).decode(),
592        )
593        conf = django_db_config(config)
594        self.assertEqual(conf["default"]["OPTIONS"]["pool"], {"max_size": 15})
595
596    # --- Session-mode PostgreSQL endpoint ---
597
598    def _set_main_postgres(self, config: ConfigLoader) -> None:
599        config.set("postgresql.host", "main-host")
600        config.set("postgresql.name", "main-db")
601        config.set("postgresql.user", "main-user")
602        config.set("postgresql.password", "main-pass")
603        config.set("postgresql.port", 6432)
604        config.set("postgresql.sslmode", "require")
605        config.set("postgresql.sslrootcert", "main-ca.pem")
606        config.set("postgresql.sslcert", "main-client.pem")
607        config.set("postgresql.sslkey", "main-client.key")
608        config.set("postgresql.test.name", "test_main")
609
610    def test_postgresql_direct_db_disabled_by_default(self):
611        """With no postgresql.direct.* keys, the direct alias is not added."""
612        config = ConfigLoader()
613        self._set_main_postgres(config)
614        self.assertFalse(postgresql_direct_db_enabled(config))
615        conf = django_db_config(config)
616        self.assertNotIn(DIRECT_DB_ALIAS, conf)
617
618    def test_postgresql_direct_kwargs_fallback(self):
619        """Without overrides, direct connection kwargs mirror the main params."""
620        config = ConfigLoader()
621        self._set_main_postgres(config)
622        kwargs = postgresql_direct_connection_kwargs(config)
623        self.assertEqual(
624            kwargs,
625            {
626                "host": "main-host",
627                "port": 6432,
628                "dbname": "main-db",
629                "user": "main-user",
630                "password": "main-pass",
631                "sslmode": "require",
632                "sslrootcert": "main-ca.pem",
633                "sslcert": "main-client.pem",
634                "sslkey": "main-client.key",
635            },
636        )
637
638    def test_postgresql_direct_kwargs_override(self):
639        """Direct keys override the corresponding main keys; others fall through."""
640        config = ConfigLoader()
641        self._set_main_postgres(config)
642        # Operator scenario: transaction-pool pgbouncer on 6432 + direct PG on 5432.
643        config.set("postgresql.direct.host", "direct-pg")
644        config.set("postgresql.direct.port", 5432)
645        kwargs = postgresql_direct_connection_kwargs(config)
646        self.assertEqual(kwargs["host"], "direct-pg")
647        self.assertEqual(kwargs["port"], 5432)
648        self.assertEqual(kwargs["dbname"], "main-db")
649        self.assertEqual(kwargs["user"], "main-user")
650        self.assertEqual(kwargs["password"], "main-pass")
651        self.assertEqual(kwargs["sslmode"], "require")
652
653    def test_postgresql_direct_kwargs_strips_none(self):
654        """None values are stripped so libpq applies defaults — without this,
655        ``psycopg.connect(sslmode=None)`` would raise."""
656        config = ConfigLoader()
657        config.set("postgresql.host", "main-host")
658        config.set("postgresql.name", "main-db")
659        config.set("postgresql.user", "main-user")
660        config.set("postgresql.password", "main-pass")
661        config.set("postgresql.port", 5432)
662        config.set("postgresql.sslmode", None)
663        config.set("postgresql.sslrootcert", None)
664        config.set("postgresql.sslcert", None)
665        config.set("postgresql.sslkey", None)
666        kwargs = postgresql_direct_connection_kwargs(config)
667        for ssl_key in ("sslmode", "sslrootcert", "sslcert", "sslkey"):
668            self.assertNotIn(ssl_key, kwargs)
669
670    def test_postgresql_direct_db_adds_alias(self):
671        """Setting any postgresql.direct.* key adds the direct Django alias."""
672        config = ConfigLoader()
673        self._set_main_postgres(config)
674        config.set("postgresql.direct.host", "direct-pg")
675        config.set("postgresql.direct.port", 5432)
676        self.assertTrue(postgresql_direct_db_enabled(config))
677        conf = django_db_config(config)
678        self.assertIn(DIRECT_DB_ALIAS, conf)
679        direct = conf[DIRECT_DB_ALIAS]
680        self.assertEqual(direct["HOST"], "direct-pg")
681        self.assertEqual(direct["PORT"], 5432)
682        self.assertEqual(direct["NAME"], "main-db")
683        self.assertEqual(direct["USER"], "main-user")
684        self.assertEqual(direct["PASSWORD"], "main-pass")
685        # Managed manually by broker / channel layer
686        self.assertIsNone(direct["CONN_MAX_AGE"])
687        self.assertFalse(direct["CONN_HEALTH_CHECKS"])
688        # Default alias unaffected
689        self.assertEqual(conf["default"]["HOST"], "main-host")
690        self.assertEqual(conf["default"]["PORT"], 6432)
691
692    def test_postgresql_direct_db_with_replicas(self):
693        """The direct alias is added alongside read replicas without conflict."""
694        config = ConfigLoader()
695        self._set_main_postgres(config)
696        config.set("postgresql.read_replicas.0.host", "replica-0")
697        config.set("postgresql.direct.host", "direct-pg")
698        conf = django_db_config(config)
699        self.assertIn("default", conf)
700        self.assertIn("replica_0", conf)
701        self.assertIn(DIRECT_DB_ALIAS, conf)
702        self.assertEqual(conf[DIRECT_DB_ALIAS]["HOST"], "direct-pg")
703        self.assertEqual(conf["replica_0"]["HOST"], "replica-0")
704
705    def test_postgresql_direct_kwargs_merges_conn_options(self):
706        """postgresql.direct.conn_options takes precedence over postgresql.conn_options."""
707        config = ConfigLoader()
708        self._set_main_postgres(config)
709        config.set(
710            "postgresql.conn_options",
711            base64.b64encode(
712                dumps({"application_name": "authentik", "keepalives": 1}).encode()
713            ).decode(),
714        )
715        config.set(
716            "postgresql.direct.conn_options",
717            base64.b64encode(dumps({"application_name": "authentik-direct"}).encode()).decode(),
718        )
719        kwargs = postgresql_direct_connection_kwargs(config)
720        self.assertEqual(kwargs["application_name"], "authentik-direct")
721        self.assertEqual(kwargs["keepalives"], 1)
722
723    def test_advisory_lock_db_alias_defaults_to_default(self):
724        """Without postgresql.direct.*, advisory locks stay on the default alias."""
725        config = ConfigLoader()
726        self._set_main_postgres(config)
727        self.assertEqual(advisory_lock_db_alias(config), "default")
728
729    def test_advisory_lock_db_alias_uses_direct_when_enabled(self):
730        """With a direct endpoint configured, advisory locks route through it
731        so they survive a transaction-mode pooler in front of ``postgresql.host``."""
732        config = ConfigLoader()
733        self._set_main_postgres(config)
734        config.set("postgresql.direct.host", "direct-pg")
735        self.assertEqual(advisory_lock_db_alias(config), DIRECT_DB_ALIAS)

Test config loader

check_deprecations_env_vars = {'AUTHENTIK_WORKER__CONCURRENCY': '2'}
@mock.patch.dict(environ, {ENV_PREFIX + '_test__test': 'bar'})
def test_env(self):
34    @mock.patch.dict(environ, {ENV_PREFIX + "_test__test": "bar"})
35    def test_env(self):
36        """Test simple instance"""
37        config = ConfigLoader()
38        config.update_from_env()
39        self.assertEqual(config.get("test.test"), "bar")

Test simple instance

def test_patch(self):
41    def test_patch(self):
42        """Test patch decorator"""
43        config = ConfigLoader()
44        config.set("foo.bar", "bar")
45        self.assertEqual(config.get("foo.bar"), "bar")
46        with config.patch("foo.bar", "baz"):
47            self.assertEqual(config.get("foo.bar"), "baz")
48        self.assertEqual(config.get("foo.bar"), "bar")

Test patch decorator

@mock.patch.dict(environ, {'foo': 'bar'})
def test_uri_env(self):
50    @mock.patch.dict(environ, {"foo": "bar"})
51    def test_uri_env(self):
52        """Test URI parsing (environment)"""
53        config = ConfigLoader()
54        foo_uri = "env://foo"
55        foo_parsed = config.parse_uri(foo_uri)
56        self.assertEqual(foo_parsed.value, "bar")
57        self.assertEqual(foo_parsed.source_type, Attr.Source.URI)
58        self.assertEqual(foo_parsed.source, foo_uri)
59        foo_bar_uri = "env://foo?bar"
60        foo_bar_parsed = config.parse_uri(foo_bar_uri)
61        self.assertEqual(foo_bar_parsed.value, "bar")
62        self.assertEqual(foo_bar_parsed.source_type, Attr.Source.URI)
63        self.assertEqual(foo_bar_parsed.source, foo_bar_uri)

Test URI parsing (environment)

def test_uri_file(self):
65    def test_uri_file(self):
66        """Test URI parsing (file load)"""
67        config = ConfigLoader()
68        file, file_name = mkstemp()
69        write(file, b"foo")
70        _, file2_name = mkstemp()
71        chmod(file2_name, 0o000)  # Remove all permissions so we can't read the file
72        self.assertEqual(config.parse_uri(f"file://{file_name}").value, "foo")
73        self.assertEqual(config.parse_uri(f"file://{file2_name}?def").value, "def")
74        unlink(file_name)
75        unlink(file2_name)

Test URI parsing (file load)

def test_uri_file_update(self):
77    def test_uri_file_update(self):
78        """Test URI parsing (file load and update)"""
79        file, file_name = mkstemp()
80        write(file, b"foo")
81        config = ConfigLoader(file_test=f"file://{file_name}")
82        self.assertEqual(config.get("file_test"), "foo")
83
84        # Update config file
85        write(file, b"bar")
86        config.refresh("file_test")
87        self.assertEqual(config.get("file_test"), "foobar")
88
89        unlink(file_name)

Test URI parsing (file load and update)

def test_uri_env_full(self):
91    def test_uri_env_full(self):
92        """Test URI set as env variable"""
93        environ["AUTHENTIK_TEST_VAR"] = "file:///foo?bar"
94        config = ConfigLoader()
95        self.assertEqual(config.get("test_var"), "bar")

Test URI set as env variable

def test_file_update(self):
 97    def test_file_update(self):
 98        """Test update_from_file"""
 99        config = ConfigLoader()
100        file, file_name = mkstemp()
101        write(file, b"{")
102        file2, file2_name = mkstemp()
103        write(file2, b"{")
104        chmod(file2_name, 0o000)  # Remove all permissions so we can't read the file
105        with self.assertRaises(ImproperlyConfigured):
106            config.update_from_file(file_name)
107        config.update_from_file(file2_name)
108        unlink(file_name)
109        unlink(file2_name)

Test update_from_file

def test_get_int(self):
111    def test_get_int(self):
112        """Test get_int"""
113        config = ConfigLoader()
114        config.set("foo", 1234)
115        self.assertEqual(config.get_int("foo"), 1234)

Test get_int

def test_get_int_invalid(self):
117    def test_get_int_invalid(self):
118        """Test get_int"""
119        config = ConfigLoader()
120        config.set("foo", "bar")
121        self.assertEqual(config.get_int("foo", 1234), 1234)

Test get_int

def test_get_dict_from_b64_json(self):
123    def test_get_dict_from_b64_json(self):
124        """Test get_dict_from_b64_json"""
125        config = ConfigLoader()
126        test_value = b'  { "foo": "bar"   }   '
127        b64_value = base64.b64encode(test_value)
128        config.set("foo", b64_value)
129        self.assertEqual(config.get_dict_from_b64_json("foo"), {"foo": "bar"})

Test get_dict_from_b64_json

def test_get_dict_from_b64_json_missing_brackets(self):
131    def test_get_dict_from_b64_json_missing_brackets(self):
132        """Test get_dict_from_b64_json with missing brackets"""
133        config = ConfigLoader()
134        test_value = b' "foo": "bar"     '
135        b64_value = base64.b64encode(test_value)
136        config.set("foo", b64_value)
137        self.assertEqual(config.get_dict_from_b64_json("foo"), {})

Test get_dict_from_b64_json with missing brackets

def test_get_dict_from_b64_json_invalid(self):
139    def test_get_dict_from_b64_json_invalid(self):
140        """Test get_dict_from_b64_json with invalid value"""
141        config = ConfigLoader()
142        config.set("foo", "bar")
143        self.assertEqual(config.get_dict_from_b64_json("foo"), {})

Test get_dict_from_b64_json with invalid value

def test_attr_json_encoder(self):
145    def test_attr_json_encoder(self):
146        """Test AttrEncoder"""
147        test_attr = Attr("foo", Attr.Source.ENV, "AUTHENTIK_POSTGRESQL__USERNAME")
148        json_attr = dumps(test_attr, indent=4, cls=AttrEncoder)
149        self.assertEqual(json_attr, '"foo"')

Test AttrEncoder

def test_attr_json_encoder_no_attr(self):
151    def test_attr_json_encoder_no_attr(self):
152        """Test AttrEncoder if no Attr is passed"""
153
154        class Test:
155            """Non Attr class"""
156
157        with self.assertRaises(TypeError):
158            test_obj = Test()
159            dumps(test_obj, indent=4, cls=AttrEncoder)

Test AttrEncoder if no Attr is passed

def test_get_optional_int(self):
161    def test_get_optional_int(self):
162        config = ConfigLoader()
163        self.assertEqual(config.get_optional_int("foo", 21), 21)
164        self.assertEqual(config.get_optional_int("foo"), None)
165        config.set("foo", "21")
166        self.assertEqual(config.get_optional_int("foo"), 21)
167        self.assertEqual(config.get_optional_int("foo", 0), 21)
168        self.assertEqual(config.get_optional_int("foo", "null"), 21)
169        config.set("foo", "null")
170        self.assertEqual(config.get_optional_int("foo"), None)
171        self.assertEqual(config.get_optional_int("foo", 21), None)
@mock.patch.dict(environ, check_deprecations_env_vars)
def test_check_deprecations(self):
173    @mock.patch.dict(environ, check_deprecations_env_vars)
174    def test_check_deprecations(self):
175        """Test config key re-write for deprecated env vars"""
176        config = ConfigLoader()
177        config.update_from_env()
178        config.check_deprecations()
179        self.assertEqual(config.get("worker.concurrency", UNSET), UNSET)
180        self.assertEqual(config.get("worker.threads"), 2)

Test config key re-write for deprecated env vars

def test_get_keys(self):
182    def test_get_keys(self):
183        """Test get_keys"""
184        config = ConfigLoader()
185        config.set("foo.bar", "baz")
186        self.assertEqual(list(config.get_keys("foo")), ["bar"])

Test get_keys

def test_db_default(self):
188    def test_db_default(self):
189        """Test default DB Config"""
190        config = ConfigLoader()
191        config.set("postgresql.host", "foo")
192        config.set("postgresql.name", "foo")
193        config.set("postgresql.user", "foo")
194        config.set("postgresql.password", "foo")
195        config.set("postgresql.port", "foo")
196        config.set("postgresql.sslmode", "foo")
197        config.set("postgresql.sslrootcert", "foo")
198        config.set("postgresql.sslcert", "foo")
199        config.set("postgresql.sslkey", "foo")
200        config.set("postgresql.test.name", "foo")
201        conf = django_db_config(config)
202        self.assertEqual(
203            conf,
204            {
205                "default": {
206                    "ENGINE": "psqlextra.backend",
207                    "HOST": "foo",
208                    "NAME": "foo",
209                    "OPTIONS": {
210                        "pool": False,
211                        "options": "-c TimeZone=UTC",
212                        "sslcert": "foo",
213                        "sslkey": "foo",
214                        "sslmode": "foo",
215                        "sslrootcert": "foo",
216                    },
217                    "PASSWORD": "foo",
218                    "PORT": "foo",
219                    "TEST": {"NAME": "foo"},
220                    "USER": "foo",
221                    "CONN_MAX_AGE": 0,
222                    "CONN_HEALTH_CHECKS": False,
223                    "DISABLE_SERVER_SIDE_CURSORS": False,
224                }
225            },
226        )

Test default DB Config

def test_db_conn_max_age(self):
228    def test_db_conn_max_age(self):
229        """Test DB conn_max_age Config"""
230        config = ConfigLoader()
231        config.set("postgresql.conn_max_age", "null")
232        conf = django_db_config(config)
233        self.assertEqual(
234            conf["default"]["CONN_MAX_AGE"],
235            None,
236        )

Test DB conn_max_age Config

def test_db_read_replicas(self):
238    def test_db_read_replicas(self):
239        """Test read replicas"""
240        config = ConfigLoader()
241        config.set("postgresql.host", "foo")
242        config.set("postgresql.name", "foo")
243        config.set("postgresql.user", "foo")
244        config.set("postgresql.password", "foo")
245        config.set("postgresql.port", "foo")
246        config.set("postgresql.sslmode", "foo")
247        config.set("postgresql.sslrootcert", "foo")
248        config.set("postgresql.sslcert", "foo")
249        config.set("postgresql.sslkey", "foo")
250        config.set("postgresql.test.name", "foo")
251        # Read replica
252        config.set("postgresql.read_replicas.0.host", "bar")
253        conf = django_db_config(config)
254        self.assertEqual(
255            conf,
256            {
257                "default": {
258                    "ENGINE": "psqlextra.backend",
259                    "HOST": "foo",
260                    "NAME": "foo",
261                    "OPTIONS": {
262                        "pool": False,
263                        "options": "-c TimeZone=UTC",
264                        "sslcert": "foo",
265                        "sslkey": "foo",
266                        "sslmode": "foo",
267                        "sslrootcert": "foo",
268                    },
269                    "PASSWORD": "foo",
270                    "PORT": "foo",
271                    "TEST": {"NAME": "foo"},
272                    "USER": "foo",
273                    "CONN_MAX_AGE": 0,
274                    "CONN_HEALTH_CHECKS": False,
275                    "DISABLE_SERVER_SIDE_CURSORS": False,
276                },
277                "replica_0": {
278                    "ENGINE": "psqlextra.backend",
279                    "HOST": "bar",
280                    "NAME": "foo",
281                    "OPTIONS": {
282                        "pool": False,
283                        "options": "-c TimeZone=UTC",
284                        "sslcert": "foo",
285                        "sslkey": "foo",
286                        "sslmode": "foo",
287                        "sslrootcert": "foo",
288                    },
289                    "PASSWORD": "foo",
290                    "PORT": "foo",
291                    "TEST": {"NAME": "foo"},
292                    "USER": "foo",
293                    "CONN_MAX_AGE": 0,
294                    "CONN_HEALTH_CHECKS": False,
295                    "DISABLE_SERVER_SIDE_CURSORS": False,
296                },
297            },
298        )

Test read replicas

def test_db_read_replicas_pgbouncer(self):
300    def test_db_read_replicas_pgbouncer(self):
301        """Test read replicas"""
302        config = ConfigLoader()
303        config.set("postgresql.host", "foo")
304        config.set("postgresql.name", "foo")
305        config.set("postgresql.user", "foo")
306        config.set("postgresql.password", "foo")
307        config.set("postgresql.port", "foo")
308        config.set("postgresql.sslmode", "foo")
309        config.set("postgresql.sslrootcert", "foo")
310        config.set("postgresql.sslcert", "foo")
311        config.set("postgresql.sslkey", "foo")
312        config.set("postgresql.test.name", "foo")
313        config.set("postgresql.use_pgbouncer", True)
314        # Read replica
315        config.set("postgresql.read_replicas.0.host", "bar")
316        # Override conn_max_age
317        config.set("postgresql.read_replicas.0.conn_max_age", 10)
318        # This isn't supported
319        config.set("postgresql.read_replicas.0.use_pgbouncer", False)
320        conf = django_db_config(config)
321        self.assertEqual(
322            conf,
323            {
324                "default": {
325                    "DISABLE_SERVER_SIDE_CURSORS": True,
326                    "CONN_MAX_AGE": 0,
327                    "CONN_HEALTH_CHECKS": False,
328                    "ENGINE": "psqlextra.backend",
329                    "HOST": "foo",
330                    "NAME": "foo",
331                    "OPTIONS": {
332                        "pool": False,
333                        "sslcert": "foo",
334                        "sslkey": "foo",
335                        "sslmode": "foo",
336                        "sslrootcert": "foo",
337                    },
338                    "PASSWORD": "foo",
339                    "PORT": "foo",
340                    "TEST": {"NAME": "foo"},
341                    "USER": "foo",
342                },
343                "replica_0": {
344                    "DISABLE_SERVER_SIDE_CURSORS": True,
345                    "CONN_MAX_AGE": 10,
346                    "CONN_HEALTH_CHECKS": False,
347                    "ENGINE": "psqlextra.backend",
348                    "HOST": "bar",
349                    "NAME": "foo",
350                    "OPTIONS": {
351                        "pool": False,
352                        "sslcert": "foo",
353                        "sslkey": "foo",
354                        "sslmode": "foo",
355                        "sslrootcert": "foo",
356                    },
357                    "PASSWORD": "foo",
358                    "PORT": "foo",
359                    "TEST": {"NAME": "foo"},
360                    "USER": "foo",
361                },
362            },
363        )

Test read replicas

def test_db_read_replicas_pgpool(self):
365    def test_db_read_replicas_pgpool(self):
366        """Test read replicas"""
367        config = ConfigLoader()
368        config.set("postgresql.host", "foo")
369        config.set("postgresql.name", "foo")
370        config.set("postgresql.user", "foo")
371        config.set("postgresql.password", "foo")
372        config.set("postgresql.port", "foo")
373        config.set("postgresql.sslmode", "foo")
374        config.set("postgresql.sslrootcert", "foo")
375        config.set("postgresql.sslcert", "foo")
376        config.set("postgresql.sslkey", "foo")
377        config.set("postgresql.test.name", "foo")
378        config.set("postgresql.use_pgpool", True)
379        # Read replica
380        config.set("postgresql.read_replicas.0.host", "bar")
381        # This isn't supported
382        config.set("postgresql.read_replicas.0.use_pgpool", False)
383        conf = django_db_config(config)
384        self.assertEqual(
385            conf,
386            {
387                "default": {
388                    "DISABLE_SERVER_SIDE_CURSORS": True,
389                    "CONN_MAX_AGE": 0,
390                    "CONN_HEALTH_CHECKS": False,
391                    "ENGINE": "psqlextra.backend",
392                    "HOST": "foo",
393                    "NAME": "foo",
394                    "OPTIONS": {
395                        "pool": False,
396                        "sslcert": "foo",
397                        "sslkey": "foo",
398                        "sslmode": "foo",
399                        "sslrootcert": "foo",
400                    },
401                    "PASSWORD": "foo",
402                    "PORT": "foo",
403                    "TEST": {"NAME": "foo"},
404                    "USER": "foo",
405                },
406                "replica_0": {
407                    "DISABLE_SERVER_SIDE_CURSORS": True,
408                    "CONN_MAX_AGE": 0,
409                    "CONN_HEALTH_CHECKS": False,
410                    "ENGINE": "psqlextra.backend",
411                    "HOST": "bar",
412                    "NAME": "foo",
413                    "OPTIONS": {
414                        "pool": False,
415                        "sslcert": "foo",
416                        "sslkey": "foo",
417                        "sslmode": "foo",
418                        "sslrootcert": "foo",
419                    },
420                    "PASSWORD": "foo",
421                    "PORT": "foo",
422                    "TEST": {"NAME": "foo"},
423                    "USER": "foo",
424                },
425            },
426        )

Test read replicas

def test_db_read_replicas_diff_ssl(self):
428    def test_db_read_replicas_diff_ssl(self):
429        """Test read replicas (with different SSL Settings)"""
430        """Test read replicas"""
431        config = ConfigLoader()
432        config.set("postgresql.host", "foo")
433        config.set("postgresql.name", "foo")
434        config.set("postgresql.user", "foo")
435        config.set("postgresql.password", "foo")
436        config.set("postgresql.port", "foo")
437        config.set("postgresql.sslmode", "foo")
438        config.set("postgresql.sslrootcert", "foo")
439        config.set("postgresql.sslcert", "foo")
440        config.set("postgresql.sslkey", "foo")
441        config.set("postgresql.test.name", "foo")
442        # Read replica
443        config.set("postgresql.read_replicas.0.host", "bar")
444        config.set("postgresql.read_replicas.0.sslcert", "bar")
445        conf = django_db_config(config)
446        self.assertEqual(
447            conf,
448            {
449                "default": {
450                    "ENGINE": "psqlextra.backend",
451                    "HOST": "foo",
452                    "NAME": "foo",
453                    "OPTIONS": {
454                        "pool": False,
455                        "options": "-c TimeZone=UTC",
456                        "sslcert": "foo",
457                        "sslkey": "foo",
458                        "sslmode": "foo",
459                        "sslrootcert": "foo",
460                    },
461                    "PASSWORD": "foo",
462                    "PORT": "foo",
463                    "TEST": {"NAME": "foo"},
464                    "USER": "foo",
465                    "DISABLE_SERVER_SIDE_CURSORS": False,
466                    "CONN_MAX_AGE": 0,
467                    "CONN_HEALTH_CHECKS": False,
468                },
469                "replica_0": {
470                    "ENGINE": "psqlextra.backend",
471                    "HOST": "bar",
472                    "NAME": "foo",
473                    "OPTIONS": {
474                        "pool": False,
475                        "options": "-c TimeZone=UTC",
476                        "sslcert": "bar",
477                        "sslkey": "foo",
478                        "sslmode": "foo",
479                        "sslrootcert": "foo",
480                    },
481                    "PASSWORD": "foo",
482                    "PORT": "foo",
483                    "TEST": {"NAME": "foo"},
484                    "USER": "foo",
485                    "DISABLE_SERVER_SIDE_CURSORS": False,
486                    "CONN_MAX_AGE": 0,
487                    "CONN_HEALTH_CHECKS": False,
488                },
489            },
490        )

Test read replicas (with different SSL Settings)

def test_db_conn_options(self):
492    def test_db_conn_options(self):
493        config = ConfigLoader()
494        config.set(
495            "postgresql.conn_options",
496            base64.b64encode(
497                dumps(
498                    {
499                        "connect_timeout": "10",
500                    }
501                ).encode()
502            ).decode(),
503        )
504        config.set("postgresql.read_replicas.0.host", "bar")
505
506        conf = django_db_config(config)
507
508        self.assertEqual(
509            conf["default"]["OPTIONS"]["connect_timeout"],
510            "10",
511        )
512        self.assertNotIn("connect_timeout", conf["replica_0"]["OPTIONS"])
def test_db_timezone_option(self):
514    def test_db_timezone_option(self):
515        """Test TimeZone connect option is skipped for poolers and doesn't override user options"""
516        for pooler in ("postgresql.use_pgbouncer", "postgresql.use_pgpool"):
517            config = ConfigLoader()
518            config.set(pooler, True)
519            self.assertNotIn("options", django_db_config(config)["default"]["OPTIONS"])
520        config = ConfigLoader()
521        config.set(
522            "postgresql.conn_options",
523            base64.b64encode(dumps({"options": "-c search_path=foo"}).encode()).decode(),
524        )
525        self.assertEqual(
526            django_db_config(config)["default"]["OPTIONS"]["options"], "-c search_path=foo"
527        )

Test TimeZone connect option is skipped for poolers and doesn't override user options

def test_db_conn_options_read_replicas(self):
529    def test_db_conn_options_read_replicas(self):
530        config = ConfigLoader()
531        config.set(
532            "postgresql.replica_conn_options",
533            base64.b64encode(
534                dumps(
535                    {
536                        "connect_timeout": "10",
537                    }
538                ).encode()
539            ).decode(),
540        )
541        config.set("postgresql.read_replicas.0.host", "bar")
542        config.set("postgresql.read_replicas.1.host", "bar")
543        config.set(
544            "postgresql.read_replicas.1.conn_options",
545            base64.b64encode(
546                dumps(
547                    {
548                        "connect_timeout": "20",
549                    }
550                ).encode()
551            ).decode(),
552        )
553
554        conf = django_db_config(config)
555
556        self.assertNotIn("connect_timeout", conf["default"]["OPTIONS"])
557        self.assertEqual(
558            conf["replica_0"]["OPTIONS"]["connect_timeout"],
559            "10",
560        )
561        self.assertEqual(
562            conf["replica_1"]["OPTIONS"]["connect_timeout"],
563            "20",
564        )
def test_db_pool(self):
566    def test_db_pool(self):
567        """Test DB Config with pool"""
568        config = ConfigLoader()
569        config.set("postgresql.use_pool", True)
570        conf = django_db_config(config)
571        self.assertEqual(conf["default"]["OPTIONS"]["pool"], {"max_size": 10})
572        self.assertEqual(conf["default"]["CONN_MAX_AGE"], 0)
573        # Long-lived connections (LISTEN, advisory locks) must not hold pool slots
574        self.assertTrue(postgresql_direct_db_enabled(config))
575        self.assertFalse(conf[DIRECT_DB_ALIAS]["OPTIONS"]["pool"])

Test DB Config with pool

def test_db_pool_worker_threads(self):
577    def test_db_pool_worker_threads(self):
578        """Test DB Config with pool sized for worker threads"""
579        config = ConfigLoader()
580        config.set("postgresql.use_pool", True)
581        config.set("worker.threads", 16)
582        conf = django_db_config(config)
583        self.assertEqual(conf["default"]["OPTIONS"]["pool"], {"max_size": 17})

Test DB Config with pool sized for worker threads

def test_db_pool_options(self):
585    def test_db_pool_options(self):
586        """Test DB Config with pool options"""
587        config = ConfigLoader()
588        config.set("postgresql.use_pool", True)
589        config.set(
590            "postgresql.pool_options",
591            base64.b64encode(dumps({"max_size": 15}).encode()).decode(),
592        )
593        conf = django_db_config(config)
594        self.assertEqual(conf["default"]["OPTIONS"]["pool"], {"max_size": 15})

Test DB Config with pool options

def test_postgresql_direct_db_disabled_by_default(self):
610    def test_postgresql_direct_db_disabled_by_default(self):
611        """With no postgresql.direct.* keys, the direct alias is not added."""
612        config = ConfigLoader()
613        self._set_main_postgres(config)
614        self.assertFalse(postgresql_direct_db_enabled(config))
615        conf = django_db_config(config)
616        self.assertNotIn(DIRECT_DB_ALIAS, conf)

With no postgresql.direct.* keys, the direct alias is not added.

def test_postgresql_direct_kwargs_fallback(self):
618    def test_postgresql_direct_kwargs_fallback(self):
619        """Without overrides, direct connection kwargs mirror the main params."""
620        config = ConfigLoader()
621        self._set_main_postgres(config)
622        kwargs = postgresql_direct_connection_kwargs(config)
623        self.assertEqual(
624            kwargs,
625            {
626                "host": "main-host",
627                "port": 6432,
628                "dbname": "main-db",
629                "user": "main-user",
630                "password": "main-pass",
631                "sslmode": "require",
632                "sslrootcert": "main-ca.pem",
633                "sslcert": "main-client.pem",
634                "sslkey": "main-client.key",
635            },
636        )

Without overrides, direct connection kwargs mirror the main params.

def test_postgresql_direct_kwargs_override(self):
638    def test_postgresql_direct_kwargs_override(self):
639        """Direct keys override the corresponding main keys; others fall through."""
640        config = ConfigLoader()
641        self._set_main_postgres(config)
642        # Operator scenario: transaction-pool pgbouncer on 6432 + direct PG on 5432.
643        config.set("postgresql.direct.host", "direct-pg")
644        config.set("postgresql.direct.port", 5432)
645        kwargs = postgresql_direct_connection_kwargs(config)
646        self.assertEqual(kwargs["host"], "direct-pg")
647        self.assertEqual(kwargs["port"], 5432)
648        self.assertEqual(kwargs["dbname"], "main-db")
649        self.assertEqual(kwargs["user"], "main-user")
650        self.assertEqual(kwargs["password"], "main-pass")
651        self.assertEqual(kwargs["sslmode"], "require")

Direct keys override the corresponding main keys; others fall through.

def test_postgresql_direct_kwargs_strips_none(self):
653    def test_postgresql_direct_kwargs_strips_none(self):
654        """None values are stripped so libpq applies defaults — without this,
655        ``psycopg.connect(sslmode=None)`` would raise."""
656        config = ConfigLoader()
657        config.set("postgresql.host", "main-host")
658        config.set("postgresql.name", "main-db")
659        config.set("postgresql.user", "main-user")
660        config.set("postgresql.password", "main-pass")
661        config.set("postgresql.port", 5432)
662        config.set("postgresql.sslmode", None)
663        config.set("postgresql.sslrootcert", None)
664        config.set("postgresql.sslcert", None)
665        config.set("postgresql.sslkey", None)
666        kwargs = postgresql_direct_connection_kwargs(config)
667        for ssl_key in ("sslmode", "sslrootcert", "sslcert", "sslkey"):
668            self.assertNotIn(ssl_key, kwargs)

None values are stripped so libpq applies defaults — without this, psycopg.connect(sslmode=None) would raise.

def test_postgresql_direct_db_adds_alias(self):
670    def test_postgresql_direct_db_adds_alias(self):
671        """Setting any postgresql.direct.* key adds the direct Django alias."""
672        config = ConfigLoader()
673        self._set_main_postgres(config)
674        config.set("postgresql.direct.host", "direct-pg")
675        config.set("postgresql.direct.port", 5432)
676        self.assertTrue(postgresql_direct_db_enabled(config))
677        conf = django_db_config(config)
678        self.assertIn(DIRECT_DB_ALIAS, conf)
679        direct = conf[DIRECT_DB_ALIAS]
680        self.assertEqual(direct["HOST"], "direct-pg")
681        self.assertEqual(direct["PORT"], 5432)
682        self.assertEqual(direct["NAME"], "main-db")
683        self.assertEqual(direct["USER"], "main-user")
684        self.assertEqual(direct["PASSWORD"], "main-pass")
685        # Managed manually by broker / channel layer
686        self.assertIsNone(direct["CONN_MAX_AGE"])
687        self.assertFalse(direct["CONN_HEALTH_CHECKS"])
688        # Default alias unaffected
689        self.assertEqual(conf["default"]["HOST"], "main-host")
690        self.assertEqual(conf["default"]["PORT"], 6432)

Setting any postgresql.direct.* key adds the direct Django alias.

def test_postgresql_direct_db_with_replicas(self):
692    def test_postgresql_direct_db_with_replicas(self):
693        """The direct alias is added alongside read replicas without conflict."""
694        config = ConfigLoader()
695        self._set_main_postgres(config)
696        config.set("postgresql.read_replicas.0.host", "replica-0")
697        config.set("postgresql.direct.host", "direct-pg")
698        conf = django_db_config(config)
699        self.assertIn("default", conf)
700        self.assertIn("replica_0", conf)
701        self.assertIn(DIRECT_DB_ALIAS, conf)
702        self.assertEqual(conf[DIRECT_DB_ALIAS]["HOST"], "direct-pg")
703        self.assertEqual(conf["replica_0"]["HOST"], "replica-0")

The direct alias is added alongside read replicas without conflict.

def test_postgresql_direct_kwargs_merges_conn_options(self):
705    def test_postgresql_direct_kwargs_merges_conn_options(self):
706        """postgresql.direct.conn_options takes precedence over postgresql.conn_options."""
707        config = ConfigLoader()
708        self._set_main_postgres(config)
709        config.set(
710            "postgresql.conn_options",
711            base64.b64encode(
712                dumps({"application_name": "authentik", "keepalives": 1}).encode()
713            ).decode(),
714        )
715        config.set(
716            "postgresql.direct.conn_options",
717            base64.b64encode(dumps({"application_name": "authentik-direct"}).encode()).decode(),
718        )
719        kwargs = postgresql_direct_connection_kwargs(config)
720        self.assertEqual(kwargs["application_name"], "authentik-direct")
721        self.assertEqual(kwargs["keepalives"], 1)

postgresql.direct.conn_options takes precedence over postgresql.conn_options.

def test_advisory_lock_db_alias_defaults_to_default(self):
723    def test_advisory_lock_db_alias_defaults_to_default(self):
724        """Without postgresql.direct.*, advisory locks stay on the default alias."""
725        config = ConfigLoader()
726        self._set_main_postgres(config)
727        self.assertEqual(advisory_lock_db_alias(config), "default")

Without postgresql.direct.*, advisory locks stay on the default alias.

def test_advisory_lock_db_alias_uses_direct_when_enabled(self):
729    def test_advisory_lock_db_alias_uses_direct_when_enabled(self):
730        """With a direct endpoint configured, advisory locks route through it
731        so they survive a transaction-mode pooler in front of ``postgresql.host``."""
732        config = ConfigLoader()
733        self._set_main_postgres(config)
734        config.set("postgresql.direct.host", "direct-pg")
735        self.assertEqual(advisory_lock_db_alias(config), DIRECT_DB_ALIAS)

With a direct endpoint configured, advisory locks route through it so they survive a transaction-mode pooler in front of postgresql.host.