authentik.lib.config

authentik core config loader

  1"""authentik core config loader"""
  2
  3import base64
  4import json
  5import os
  6from collections.abc import Mapping
  7from contextlib import contextmanager
  8from copy import deepcopy
  9from dataclasses import dataclass, field
 10from enum import Enum
 11from glob import glob
 12from json import JSONEncoder, dumps, loads
 13from json.decoder import JSONDecodeError
 14from pathlib import Path
 15from sys import argv, stderr
 16from time import time
 17from typing import Any
 18from urllib.parse import urlparse
 19
 20import yaml
 21from django.conf import ImproperlyConfigured
 22from django.db.utils import DEFAULT_DB_ALIAS
 23
 24from authentik.lib.utils.dict import delete_path_in_dict, get_path_from_dict, set_path_in_dict
 25
 26SEARCH_PATHS = ["authentik/lib/default.yml", "/etc/authentik/config.yml", ""] + glob(
 27    "/etc/authentik/config.d/*.yml", recursive=True
 28)
 29ENV_PREFIX = "AUTHENTIK"
 30ENVIRONMENT = os.getenv(f"{ENV_PREFIX}_ENV", "local")
 31
 32# Old key -> new key
 33DEPRECATIONS = {
 34    "geoip": "events.context_processors.geoip",
 35    "worker.concurrency": "worker.threads",
 36}
 37
 38
 39@dataclass(slots=True)
 40class Attr:
 41    """Single configuration attribute"""
 42
 43    class Source(Enum):
 44        """Sources a configuration attribute can come from, determines what should be done with
 45        Attr.source (and if it's set at all)"""
 46
 47        UNSPECIFIED = "unspecified"
 48        ENV = "env"
 49        CONFIG_FILE = "config_file"
 50        URI = "uri"
 51
 52    value: Any
 53
 54    source_type: Source = field(default=Source.UNSPECIFIED)
 55
 56    # depending on source_type, might contain the environment variable or the path
 57    # to the config file containing this change or the file containing this value
 58    source: str | None = field(default=None)
 59
 60    def __post_init__(self):
 61        if isinstance(self.value, Attr):
 62            raise RuntimeError(f"config Attr with nested Attr for source {self.source}")
 63
 64
 65class AttrEncoder(JSONEncoder):
 66    """JSON encoder that can deal with `Attr` classes"""
 67
 68    def default(self, o: Any) -> Any:
 69        if isinstance(o, Attr):
 70            return o.value
 71        return super().default(o)
 72
 73
 74class UNSET:
 75    """Used to test whether configuration key has not been set."""
 76
 77
 78class ConfigLoader:
 79    """Search through SEARCH_PATHS and load configuration. Environment variables starting with
 80    `ENV_PREFIX` are also applied.
 81
 82    A variable like AUTHENTIK_POSTGRESQL__HOST would translate to postgresql.host"""
 83
 84    deprecations: dict[tuple[str, str], str] = {}
 85
 86    def __init__(self, **kwargs):
 87        super().__init__()
 88        self.__config = {}
 89        base_dir = Path(__file__).parent.joinpath(Path("../..")).resolve()
 90        for _path in SEARCH_PATHS:
 91            path = Path(_path)
 92            # Check if path is relative, and if so join with base_dir
 93            if not path.is_absolute():
 94                path = base_dir / path
 95            if path.is_file() and path.exists():
 96                # Path is an existing file, so we just read it and update our config with it
 97                self.update_from_file(path)
 98            elif path.is_dir() and path.exists():
 99                # Path is an existing dir, so we try to read the env config from it
100                env_paths = [
101                    path / Path(ENVIRONMENT + ".yml"),
102                    path / Path(ENVIRONMENT + ".env.yml"),
103                    path / Path(ENVIRONMENT + ".yaml"),
104                    path / Path(ENVIRONMENT + ".env.yaml"),
105                ]
106                for env_file in env_paths:
107                    if env_file.is_file() and env_file.exists():
108                        # Update config with env file
109                        self.update_from_file(env_file)
110        self.update_from_env()
111        self.update(self.__config, kwargs)
112        self.deprecations = self.check_deprecations()
113
114    def check_deprecations(self) -> dict[str, str]:
115        """Warn if any deprecated configuration options are used"""
116
117        def _pop_deprecated_key(current_obj, dot_parts, index):
118            """Recursive function to remove deprecated keys in configuration"""
119            dot_part = dot_parts[index]
120            if index == len(dot_parts) - 1:
121                return current_obj.pop(dot_part)
122            value = _pop_deprecated_key(current_obj[dot_part], dot_parts, index + 1)
123            if not current_obj[dot_part]:
124                current_obj.pop(dot_part)
125            return value
126
127        deprecation_replacements = {}
128        for deprecation, replacement in DEPRECATIONS.items():
129            if self.get(deprecation, default=UNSET) is UNSET:
130                continue
131            message = (
132                f"'{deprecation}' has been deprecated in favor of '{replacement}'! "
133                + "Please update your configuration."
134            )
135            self.log(
136                "warning",
137                message,
138            )
139            deprecation_replacements[(deprecation, replacement)] = message
140
141            deprecated_attr = _pop_deprecated_key(self.__config, deprecation.split("."), 0)
142            self.set(replacement, deprecated_attr)
143        return deprecation_replacements
144
145    def log(self, level: str, message: str, **kwargs):
146        """Custom Log method, we want to ensure ConfigLoader always logs JSON even when
147        'structlog' or 'logging' hasn't been configured yet."""
148        output = {
149            "event": message,
150            "level": level,
151            "logger": self.__class__.__module__,
152            "timestamp": time(),
153        }
154        output.update(kwargs)
155        print(dumps(output), file=stderr)
156
157    def update(self, root: dict[str, Any], updatee: dict[str, Any]) -> dict[str, Any]:
158        """Recursively update dictionary"""
159        for key, raw_value in updatee.items():
160            if isinstance(raw_value, Mapping):
161                root[key] = self.update(root.get(key, {}), raw_value)
162            else:
163                if isinstance(raw_value, str):
164                    value = self.parse_uri(raw_value)
165                elif isinstance(raw_value, Attr) and isinstance(raw_value.value, str):
166                    value = self.parse_uri(raw_value.value)
167                elif not isinstance(raw_value, Attr):
168                    value = Attr(raw_value)
169                else:
170                    value = raw_value
171                root[key] = value
172        return root
173
174    def refresh(self, key: str, default=None, sep=".") -> Any:
175        """Update a single value"""
176        attr: Attr = get_path_from_dict(self.raw, key, sep=sep, default=Attr(default))
177        if attr.source_type != Attr.Source.URI:
178            return attr.value
179        attr.value = self.parse_uri(attr.source).value
180        return attr.value
181
182    def parse_uri(self, value: str) -> Attr:
183        """Parse string values which start with a URI"""
184        url = urlparse(value)
185        parsed_value = value
186        if url.scheme == "env":
187            parsed_value = os.getenv(url.netloc, url.query)
188        if url.scheme == "file":
189            try:
190                with open(url.path, encoding="utf8") as _file:
191                    parsed_value = _file.read().strip()
192            except OSError as exc:
193                self.log("error", f"Failed to read config value from {url.path}: {exc}")
194                parsed_value = url.query
195        return Attr(parsed_value, Attr.Source.URI, value)
196
197    def update_from_file(self, path: Path):
198        """Update config from file contents"""
199        try:
200            with open(path, encoding="utf8") as file:
201                try:
202                    self.update(self.__config, yaml.safe_load(file))
203                    self.log("debug", "Loaded config", file=str(path))
204                except yaml.YAMLError as exc:
205                    raise ImproperlyConfigured from exc
206        except PermissionError as exc:
207            self.log(
208                "warning",
209                "Permission denied while reading file",
210                path=path,
211                error=str(exc),
212            )
213
214    def update_from_dict(self, update: dict):
215        """Update config from dict"""
216        self.__config.update(update)
217
218    def update_from_env(self):
219        """Check environment variables"""
220        outer = {}
221        idx = 0
222        for key, value in os.environ.items():
223            if not key.startswith(ENV_PREFIX):
224                continue
225            relative_key = key.replace(f"{ENV_PREFIX}_", "", 1).replace("__", ".").lower()
226            # Check if the value is json, and try to load it
227            try:
228                value = loads(value)  # noqa: PLW2901
229            except JSONDecodeError:
230                pass
231            attr_value = Attr(value, Attr.Source.ENV, relative_key)
232            set_path_in_dict(outer, relative_key, attr_value)
233            idx += 1
234        if idx > 0:
235            self.log("debug", "Loaded environment variables", count=idx)
236            self.update(self.__config, outer)
237
238    @contextmanager
239    def patch(self, path: str, value: Any):
240        """Context manager for unittests to patch a value"""
241        original_value = self.get(path, UNSET)
242        self.set(path, value)
243        try:
244            yield
245        finally:
246            if original_value is not UNSET:
247                self.set(path, original_value)
248            else:
249                self.delete(path)
250
251    @property
252    def raw(self) -> dict:
253        """Get raw config dictionary"""
254        return self.__config
255
256    def get(self, path: str, default=None, sep=".") -> Any:
257        """Access attribute by using yaml path"""
258        # Walk sub_dicts before parsing path
259        root = self.raw
260        # Walk each component of the path
261        attr: Attr = get_path_from_dict(root, path, sep=sep, default=Attr(default))
262        return attr.value
263
264    def get_int(self, path: str, default=0) -> int:
265        """Wrapper for get that converts value into int"""
266        try:
267            return int(self.get(path, default))
268        except ValueError as exc:
269            self.log("warning", "Failed to parse config as int", path=path, exc=str(exc))
270            return default
271
272    def get_optional_int(self, path: str, default=None) -> int | None:
273        """Wrapper for get that converts value into int or None if set"""
274        value = self.get(path, UNSET)
275        if value is UNSET:
276            return default
277        try:
278            return int(value)
279        except (ValueError, TypeError) as exc:
280            if value is None or (isinstance(value, str) and value.lower() in ("", "null", "none")):
281                return None
282            self.log("warning", "Failed to parse config as int", path=path, exc=str(exc))
283            return default
284
285    def get_bool(self, path: str, default=False) -> bool:
286        """Wrapper for get that converts value into boolean"""
287        value = self.get(path, UNSET)
288        if value is UNSET:
289            return default
290        return str(self.get(path)).lower() == "true"
291
292    def get_keys(self, path: str, sep=".") -> list[str]:
293        """List attribute keys by using yaml path"""
294        root = self.raw
295        attr: Attr = get_path_from_dict(root, path, sep=sep, default=Attr({}))
296        return attr.keys()
297
298    def get_dict_from_b64_json(self, path: str, default=None) -> dict:
299        """Wrapper for get that converts value from Base64 encoded string into dictionary"""
300        config_value = self.get(path)
301        if config_value is None:
302            return {}
303        try:
304            b64decoded_str = base64.b64decode(config_value).decode("utf-8")
305            return json.loads(b64decoded_str)
306        except (JSONDecodeError, TypeError, ValueError) as exc:
307            self.log(
308                "warning",
309                f"Ignored invalid configuration for '{path}' due to exception: {str(exc)}",
310            )
311            return default if isinstance(default, dict) else {}
312
313    def set(self, path: str, value: Any, sep="."):
314        """Set value using same syntax as get()"""
315        if not isinstance(value, Attr):
316            value = Attr(value)
317        set_path_in_dict(self.raw, path, value, sep=sep)
318
319    def delete(self, path: str, sep="."):
320        delete_path_in_dict(self.raw, path, sep=sep)
321
322
323CONFIG = ConfigLoader()
324
325
326# Reserved alias for the direct (un-pooled or session-mode-pooled) database
327# connection. Used by code that needs a stable PG backend across calls:
328# LISTEN/NOTIFY and session-scoped advisory locks. See ``django_db_config``.
329DIRECT_DB_ALIAS = "direct"
330
331
332def postgresql_direct_db_enabled(config: ConfigLoader | None = None) -> bool:
333    """Whether a dedicated direct PostgreSQL endpoint has been configured.
334
335    Returns True if any ``postgresql.direct.*`` key is set. When True, a Django
336    connection at alias ``direct`` is added; subsystems that hold server-side
337    state (LISTEN/NOTIFY, advisory locks) route through it so an operator can
338    put a transaction-pooling pooler in front of ``postgresql.host`` without
339    breaking them.
340
341    Also True when the connection pool is enabled: those long-lived connections would
342    otherwise permanently hold slots in the pool and starve it.
343    """
344    if not config:
345        config = CONFIG
346    if config.get_bool("postgresql.use_pool", False):
347        return True
348    return any(
349        config.get(f"postgresql.direct.{key}", default=UNSET) is not UNSET
350        for key in (
351            "host",
352            "port",
353            "name",
354            "user",
355            "password",
356            "sslmode",
357            "sslrootcert",
358            "sslcert",
359            "sslkey",
360            "conn_options",
361        )
362    )
363
364
365def advisory_lock_db_alias(config: ConfigLoader | None = None) -> str:
366    """Return the DB alias to use for session-scoped advisory locks.
367
368    Routes through the direct endpoint when configured so the locks survive
369    a transaction-mode pooler in front of ``postgresql.host`` (the lock and
370    its release must run on the same backend connection).
371    """
372    return DIRECT_DB_ALIAS if postgresql_direct_db_enabled(config) else DEFAULT_DB_ALIAS
373
374
375def postgresql_direct_connection_kwargs(config: ConfigLoader | None = None) -> dict:
376    """Return kwargs suitable for ``psycopg.connect()`` for the direct endpoint.
377
378    Reads ``postgresql.direct.*`` overrides, falling back to ``postgresql.*``
379    for unset keys. Used by ``lifecycle/migrate.py`` for the startup advisory
380    lock.
381    """
382    if not config:
383        config = CONFIG
384
385    def _override(field: str, default):
386        return config.get(f"postgresql.direct.{field}", default=default)
387
388    kwargs = {
389        "host": _override("host", config.get("postgresql.host")),
390        "port": _override("port", config.get_int("postgresql.port", 5432)),
391        "dbname": _override("name", config.get("postgresql.name")),
392        "user": _override("user", config.get("postgresql.user")),
393        "password": _override("password", config.get("postgresql.password")),
394        "sslmode": _override("sslmode", config.get("postgresql.sslmode")),
395        "sslrootcert": _override("sslrootcert", config.get("postgresql.sslrootcert")),
396        "sslcert": _override("sslcert", config.get("postgresql.sslcert")),
397        "sslkey": _override("sslkey", config.get("postgresql.sslkey")),
398    }
399    # direct.conn_options wins over the main conn_options when both are set.
400    conn_opts = config.get_dict_from_b64_json("postgresql.conn_options", default={})
401    direct_conn_opts = config.get_dict_from_b64_json("postgresql.direct.conn_options", default={})
402    kwargs.update(conn_opts)
403    kwargs.update(direct_conn_opts)
404    return {k: v for k, v in kwargs.items() if v is not None}
405
406
407def _build_direct_db_alias(default_db: dict, config: ConfigLoader) -> dict:
408    """Build the ``direct`` Django DB alias dict from a copy of the default
409    alias plus ``postgresql.direct.*`` overrides."""
410    direct_db = deepcopy(default_db)
411    direct_kwargs = postgresql_direct_connection_kwargs(config)
412    direct_db["HOST"] = direct_kwargs.get("host")
413    direct_db["PORT"] = direct_kwargs.get("port")
414    direct_db["NAME"] = direct_kwargs.get("dbname")
415    direct_db["USER"] = direct_kwargs.get("user")
416    direct_db["PASSWORD"] = direct_kwargs.get("password")
417    direct_db["OPTIONS"] = {
418        "sslmode": direct_kwargs.get("sslmode"),
419        "sslrootcert": direct_kwargs.get("sslrootcert"),
420        "sslcert": direct_kwargs.get("sslcert"),
421        "sslkey": direct_kwargs.get("sslkey"),
422        "pool": False,
423    }
424    # Carry over extra option keys (e.g. application_name) from direct.conn_options.
425    for key, value in direct_kwargs.items():
426        if key in ("host", "port", "dbname", "user", "password"):
427            continue
428        if key in direct_db["OPTIONS"]:
429            continue
430        direct_db["OPTIONS"][key] = value
431    # Persistent connections: managed by the broker / channel layer, not
432    # subject to per-request close_old_connections().
433    direct_db["CONN_MAX_AGE"] = None
434    direct_db["CONN_HEALTH_CHECKS"] = False
435    direct_db["DISABLE_SERVER_SIDE_CURSORS"] = True
436    direct_db["OPTIONS"] = {k: v for k, v in direct_db["OPTIONS"].items() if v is not None}
437    return direct_db
438
439
440def django_db_config(config: ConfigLoader | None = None) -> dict:
441    if not config:
442        config = CONFIG
443
444    pool_options = False
445    use_pool = config.get_bool("postgresql.use_pool", False)
446    if use_pool:
447        pool_options = config.get_dict_from_b64_json("postgresql.pool_options", True)
448        if not pool_options:
449            # psycopg's default max_size of 4 is too small for concurrent requests, and must
450            # be larger than the number of worker threads
451            pool_options = {"max_size": max(10, config.get_int("worker.threads", 2) + 1)}
452
453    conn_options = config.get_dict_from_b64_json("postgresql.conn_options", default={})
454
455    db = {
456        "default": {
457            "ENGINE": "psqlextra.backend",
458            "HOST": config.get("postgresql.host"),
459            "NAME": config.get("postgresql.name"),
460            "USER": config.get("postgresql.user"),
461            "PASSWORD": config.get("postgresql.password"),
462            "PORT": config.get("postgresql.port"),
463            "OPTIONS": {
464                "sslmode": config.get("postgresql.sslmode"),
465                "sslrootcert": config.get("postgresql.sslrootcert"),
466                "sslcert": config.get("postgresql.sslcert"),
467                "sslkey": config.get("postgresql.sslkey"),
468                "pool": pool_options,
469                **conn_options,
470            },
471            "CONN_MAX_AGE": config.get_optional_int("postgresql.conn_max_age", 0),
472            "CONN_HEALTH_CHECKS": config.get_bool("postgresql.conn_health_checks", False),
473            "DISABLE_SERVER_SIDE_CURSORS": config.get_bool(
474                "postgresql.disable_server_side_cursors", False
475            ),
476            "TEST": {
477                "NAME": config.get("postgresql.test.name"),
478            },
479        }
480    }
481
482    conn_max_age = config.get_optional_int("postgresql.conn_max_age", UNSET)
483    disable_server_side_cursors = config.get_bool("postgresql.disable_server_side_cursors", UNSET)
484    use_pgpool = config.get_bool("postgresql.use_pgpool", False)
485    use_pgbouncer = config.get_bool("postgresql.use_pgbouncer", False)
486    if use_pgpool:
487        db["default"]["DISABLE_SERVER_SIDE_CURSORS"] = True
488        if disable_server_side_cursors is not UNSET:
489            db["default"]["DISABLE_SERVER_SIDE_CURSORS"] = disable_server_side_cursors
490
491    if use_pgbouncer:
492        # https://docs.djangoproject.com/en/4.0/ref/databases/#transaction-pooling-server-side-cursors
493        db["default"]["DISABLE_SERVER_SIDE_CURSORS"] = True
494        # https://docs.djangoproject.com/en/4.0/ref/databases/#persistent-connections
495        db["default"]["CONN_MAX_AGE"] = None  # persistent
496        if disable_server_side_cursors is not UNSET:
497            db["default"]["DISABLE_SERVER_SIDE_CURSORS"] = disable_server_side_cursors
498        if conn_max_age is not UNSET:
499            db["default"]["CONN_MAX_AGE"] = conn_max_age
500
501    # Django runs `SET TimeZone` on every new connection unless the server reports exactly
502    # "UTC" (Postgres defaults to "GMT"), so set it at connect time instead. Poolers reject
503    # the `options` startup parameter; a user-provided `options` takes precedence.
504    if not use_pgpool and not use_pgbouncer:
505        db["default"]["OPTIONS"].setdefault("options", "-c TimeZone=UTC")
506
507    all_replica_conn_options = config.get_dict_from_b64_json(
508        "postgresql.replica_conn_options",
509        default={},
510    )
511
512    for replica in config.get_keys("postgresql.read_replicas"):
513        _database = deepcopy(db["default"])
514
515        for setting, current_value in db["default"].items():
516            if isinstance(current_value, dict):
517                continue
518            override = config.get(
519                f"postgresql.read_replicas.{replica}.{setting.lower()}", default=UNSET
520            )
521            if override is not UNSET:
522                _database[setting] = override
523
524        for option in conn_options.keys():
525            _database["OPTIONS"].pop(option, None)
526
527        for setting in db["default"]["OPTIONS"].keys():
528            override = config.get(
529                f"postgresql.read_replicas.{replica}.{setting.lower()}", default=UNSET
530            )
531            if override is not UNSET:
532                _database["OPTIONS"][setting] = override
533
534        _database["OPTIONS"].update(all_replica_conn_options)
535        replica_conn_options = config.get_dict_from_b64_json(
536            f"postgresql.read_replicas.{replica}.conn_options", default={}
537        )
538        _database["OPTIONS"].update(replica_conn_options)
539
540        db[f"replica_{replica}"] = _database
541
542    # Optional direct endpoint for LISTEN/NOTIFY and advisory-lock connections.
543    # Only added when operator sets ``postgresql.direct.*``; excluded from
544    # replica routing and migrations by ``authentik.root.db.router.FailoverRouter``.
545    if postgresql_direct_db_enabled(config):
546        db[DIRECT_DB_ALIAS] = _build_direct_db_alias(db["default"], config)
547
548    return db
549
550
551if __name__ == "__main__":
552    if len(argv) < 2:  # noqa: PLR2004
553        print(dumps(CONFIG.raw, indent=4, cls=AttrEncoder))
554    else:
555        for arg in argv[1:]:
556            print(CONFIG.get(arg))
SEARCH_PATHS = ['authentik/lib/default.yml', '/etc/authentik/config.yml', '']
ENV_PREFIX = 'AUTHENTIK'
ENVIRONMENT = 'local'
DEPRECATIONS = {'geoip': 'events.context_processors.geoip', 'worker.concurrency': 'worker.threads'}
@dataclass(slots=True)
class Attr:
40@dataclass(slots=True)
41class Attr:
42    """Single configuration attribute"""
43
44    class Source(Enum):
45        """Sources a configuration attribute can come from, determines what should be done with
46        Attr.source (and if it's set at all)"""
47
48        UNSPECIFIED = "unspecified"
49        ENV = "env"
50        CONFIG_FILE = "config_file"
51        URI = "uri"
52
53    value: Any
54
55    source_type: Source = field(default=Source.UNSPECIFIED)
56
57    # depending on source_type, might contain the environment variable or the path
58    # to the config file containing this change or the file containing this value
59    source: str | None = field(default=None)
60
61    def __post_init__(self):
62        if isinstance(self.value, Attr):
63            raise RuntimeError(f"config Attr with nested Attr for source {self.source}")

Single configuration attribute

Attr( value: Any, source_type: Attr.Source = <Source.UNSPECIFIED: 'unspecified'>, source: str | None = None)
value: Any
source_type: Attr.Source
source: str | None
class Attr.Source(enum.Enum):
44    class Source(Enum):
45        """Sources a configuration attribute can come from, determines what should be done with
46        Attr.source (and if it's set at all)"""
47
48        UNSPECIFIED = "unspecified"
49        ENV = "env"
50        CONFIG_FILE = "config_file"
51        URI = "uri"

Sources a configuration attribute can come from, determines what should be done with Attr.source (and if it's set at all)

UNSPECIFIED = <Source.UNSPECIFIED: 'unspecified'>
ENV = <Source.ENV: 'env'>
CONFIG_FILE = <Source.CONFIG_FILE: 'config_file'>
URI = <Source.URI: 'uri'>
class AttrEncoder(json.encoder.JSONEncoder):
66class AttrEncoder(JSONEncoder):
67    """JSON encoder that can deal with `Attr` classes"""
68
69    def default(self, o: Any) -> Any:
70        if isinstance(o, Attr):
71            return o.value
72        return super().default(o)

JSON encoder that can deal with Attr classes

def default(self, o: Any) -> Any:
69    def default(self, o: Any) -> Any:
70        if isinstance(o, Attr):
71            return o.value
72        return super().default(o)

Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).

For example, to support arbitrary iterators, you could implement default like this::

def default(self, o):
    try:
        iterable = iter(o)
    except TypeError:
        pass
    else:
        return list(iterable)
    # Let the base class default method raise the TypeError
    return super().default(o)
class UNSET:
75class UNSET:
76    """Used to test whether configuration key has not been set."""

Used to test whether configuration key has not been set.

class ConfigLoader:
 79class ConfigLoader:
 80    """Search through SEARCH_PATHS and load configuration. Environment variables starting with
 81    `ENV_PREFIX` are also applied.
 82
 83    A variable like AUTHENTIK_POSTGRESQL__HOST would translate to postgresql.host"""
 84
 85    deprecations: dict[tuple[str, str], str] = {}
 86
 87    def __init__(self, **kwargs):
 88        super().__init__()
 89        self.__config = {}
 90        base_dir = Path(__file__).parent.joinpath(Path("../..")).resolve()
 91        for _path in SEARCH_PATHS:
 92            path = Path(_path)
 93            # Check if path is relative, and if so join with base_dir
 94            if not path.is_absolute():
 95                path = base_dir / path
 96            if path.is_file() and path.exists():
 97                # Path is an existing file, so we just read it and update our config with it
 98                self.update_from_file(path)
 99            elif path.is_dir() and path.exists():
100                # Path is an existing dir, so we try to read the env config from it
101                env_paths = [
102                    path / Path(ENVIRONMENT + ".yml"),
103                    path / Path(ENVIRONMENT + ".env.yml"),
104                    path / Path(ENVIRONMENT + ".yaml"),
105                    path / Path(ENVIRONMENT + ".env.yaml"),
106                ]
107                for env_file in env_paths:
108                    if env_file.is_file() and env_file.exists():
109                        # Update config with env file
110                        self.update_from_file(env_file)
111        self.update_from_env()
112        self.update(self.__config, kwargs)
113        self.deprecations = self.check_deprecations()
114
115    def check_deprecations(self) -> dict[str, str]:
116        """Warn if any deprecated configuration options are used"""
117
118        def _pop_deprecated_key(current_obj, dot_parts, index):
119            """Recursive function to remove deprecated keys in configuration"""
120            dot_part = dot_parts[index]
121            if index == len(dot_parts) - 1:
122                return current_obj.pop(dot_part)
123            value = _pop_deprecated_key(current_obj[dot_part], dot_parts, index + 1)
124            if not current_obj[dot_part]:
125                current_obj.pop(dot_part)
126            return value
127
128        deprecation_replacements = {}
129        for deprecation, replacement in DEPRECATIONS.items():
130            if self.get(deprecation, default=UNSET) is UNSET:
131                continue
132            message = (
133                f"'{deprecation}' has been deprecated in favor of '{replacement}'! "
134                + "Please update your configuration."
135            )
136            self.log(
137                "warning",
138                message,
139            )
140            deprecation_replacements[(deprecation, replacement)] = message
141
142            deprecated_attr = _pop_deprecated_key(self.__config, deprecation.split("."), 0)
143            self.set(replacement, deprecated_attr)
144        return deprecation_replacements
145
146    def log(self, level: str, message: str, **kwargs):
147        """Custom Log method, we want to ensure ConfigLoader always logs JSON even when
148        'structlog' or 'logging' hasn't been configured yet."""
149        output = {
150            "event": message,
151            "level": level,
152            "logger": self.__class__.__module__,
153            "timestamp": time(),
154        }
155        output.update(kwargs)
156        print(dumps(output), file=stderr)
157
158    def update(self, root: dict[str, Any], updatee: dict[str, Any]) -> dict[str, Any]:
159        """Recursively update dictionary"""
160        for key, raw_value in updatee.items():
161            if isinstance(raw_value, Mapping):
162                root[key] = self.update(root.get(key, {}), raw_value)
163            else:
164                if isinstance(raw_value, str):
165                    value = self.parse_uri(raw_value)
166                elif isinstance(raw_value, Attr) and isinstance(raw_value.value, str):
167                    value = self.parse_uri(raw_value.value)
168                elif not isinstance(raw_value, Attr):
169                    value = Attr(raw_value)
170                else:
171                    value = raw_value
172                root[key] = value
173        return root
174
175    def refresh(self, key: str, default=None, sep=".") -> Any:
176        """Update a single value"""
177        attr: Attr = get_path_from_dict(self.raw, key, sep=sep, default=Attr(default))
178        if attr.source_type != Attr.Source.URI:
179            return attr.value
180        attr.value = self.parse_uri(attr.source).value
181        return attr.value
182
183    def parse_uri(self, value: str) -> Attr:
184        """Parse string values which start with a URI"""
185        url = urlparse(value)
186        parsed_value = value
187        if url.scheme == "env":
188            parsed_value = os.getenv(url.netloc, url.query)
189        if url.scheme == "file":
190            try:
191                with open(url.path, encoding="utf8") as _file:
192                    parsed_value = _file.read().strip()
193            except OSError as exc:
194                self.log("error", f"Failed to read config value from {url.path}: {exc}")
195                parsed_value = url.query
196        return Attr(parsed_value, Attr.Source.URI, value)
197
198    def update_from_file(self, path: Path):
199        """Update config from file contents"""
200        try:
201            with open(path, encoding="utf8") as file:
202                try:
203                    self.update(self.__config, yaml.safe_load(file))
204                    self.log("debug", "Loaded config", file=str(path))
205                except yaml.YAMLError as exc:
206                    raise ImproperlyConfigured from exc
207        except PermissionError as exc:
208            self.log(
209                "warning",
210                "Permission denied while reading file",
211                path=path,
212                error=str(exc),
213            )
214
215    def update_from_dict(self, update: dict):
216        """Update config from dict"""
217        self.__config.update(update)
218
219    def update_from_env(self):
220        """Check environment variables"""
221        outer = {}
222        idx = 0
223        for key, value in os.environ.items():
224            if not key.startswith(ENV_PREFIX):
225                continue
226            relative_key = key.replace(f"{ENV_PREFIX}_", "", 1).replace("__", ".").lower()
227            # Check if the value is json, and try to load it
228            try:
229                value = loads(value)  # noqa: PLW2901
230            except JSONDecodeError:
231                pass
232            attr_value = Attr(value, Attr.Source.ENV, relative_key)
233            set_path_in_dict(outer, relative_key, attr_value)
234            idx += 1
235        if idx > 0:
236            self.log("debug", "Loaded environment variables", count=idx)
237            self.update(self.__config, outer)
238
239    @contextmanager
240    def patch(self, path: str, value: Any):
241        """Context manager for unittests to patch a value"""
242        original_value = self.get(path, UNSET)
243        self.set(path, value)
244        try:
245            yield
246        finally:
247            if original_value is not UNSET:
248                self.set(path, original_value)
249            else:
250                self.delete(path)
251
252    @property
253    def raw(self) -> dict:
254        """Get raw config dictionary"""
255        return self.__config
256
257    def get(self, path: str, default=None, sep=".") -> Any:
258        """Access attribute by using yaml path"""
259        # Walk sub_dicts before parsing path
260        root = self.raw
261        # Walk each component of the path
262        attr: Attr = get_path_from_dict(root, path, sep=sep, default=Attr(default))
263        return attr.value
264
265    def get_int(self, path: str, default=0) -> int:
266        """Wrapper for get that converts value into int"""
267        try:
268            return int(self.get(path, default))
269        except ValueError as exc:
270            self.log("warning", "Failed to parse config as int", path=path, exc=str(exc))
271            return default
272
273    def get_optional_int(self, path: str, default=None) -> int | None:
274        """Wrapper for get that converts value into int or None if set"""
275        value = self.get(path, UNSET)
276        if value is UNSET:
277            return default
278        try:
279            return int(value)
280        except (ValueError, TypeError) as exc:
281            if value is None or (isinstance(value, str) and value.lower() in ("", "null", "none")):
282                return None
283            self.log("warning", "Failed to parse config as int", path=path, exc=str(exc))
284            return default
285
286    def get_bool(self, path: str, default=False) -> bool:
287        """Wrapper for get that converts value into boolean"""
288        value = self.get(path, UNSET)
289        if value is UNSET:
290            return default
291        return str(self.get(path)).lower() == "true"
292
293    def get_keys(self, path: str, sep=".") -> list[str]:
294        """List attribute keys by using yaml path"""
295        root = self.raw
296        attr: Attr = get_path_from_dict(root, path, sep=sep, default=Attr({}))
297        return attr.keys()
298
299    def get_dict_from_b64_json(self, path: str, default=None) -> dict:
300        """Wrapper for get that converts value from Base64 encoded string into dictionary"""
301        config_value = self.get(path)
302        if config_value is None:
303            return {}
304        try:
305            b64decoded_str = base64.b64decode(config_value).decode("utf-8")
306            return json.loads(b64decoded_str)
307        except (JSONDecodeError, TypeError, ValueError) as exc:
308            self.log(
309                "warning",
310                f"Ignored invalid configuration for '{path}' due to exception: {str(exc)}",
311            )
312            return default if isinstance(default, dict) else {}
313
314    def set(self, path: str, value: Any, sep="."):
315        """Set value using same syntax as get()"""
316        if not isinstance(value, Attr):
317            value = Attr(value)
318        set_path_in_dict(self.raw, path, value, sep=sep)
319
320    def delete(self, path: str, sep="."):
321        delete_path_in_dict(self.raw, path, sep=sep)

Search through SEARCH_PATHS and load configuration. Environment variables starting with ENV_PREFIX are also applied.

A variable like AUTHENTIK_POSTGRESQL__HOST would translate to postgresql.host

ConfigLoader(**kwargs)
 87    def __init__(self, **kwargs):
 88        super().__init__()
 89        self.__config = {}
 90        base_dir = Path(__file__).parent.joinpath(Path("../..")).resolve()
 91        for _path in SEARCH_PATHS:
 92            path = Path(_path)
 93            # Check if path is relative, and if so join with base_dir
 94            if not path.is_absolute():
 95                path = base_dir / path
 96            if path.is_file() and path.exists():
 97                # Path is an existing file, so we just read it and update our config with it
 98                self.update_from_file(path)
 99            elif path.is_dir() and path.exists():
100                # Path is an existing dir, so we try to read the env config from it
101                env_paths = [
102                    path / Path(ENVIRONMENT + ".yml"),
103                    path / Path(ENVIRONMENT + ".env.yml"),
104                    path / Path(ENVIRONMENT + ".yaml"),
105                    path / Path(ENVIRONMENT + ".env.yaml"),
106                ]
107                for env_file in env_paths:
108                    if env_file.is_file() and env_file.exists():
109                        # Update config with env file
110                        self.update_from_file(env_file)
111        self.update_from_env()
112        self.update(self.__config, kwargs)
113        self.deprecations = self.check_deprecations()
deprecations: dict[tuple[str, str], str] = {}
def check_deprecations(self) -> dict[str, str]:
115    def check_deprecations(self) -> dict[str, str]:
116        """Warn if any deprecated configuration options are used"""
117
118        def _pop_deprecated_key(current_obj, dot_parts, index):
119            """Recursive function to remove deprecated keys in configuration"""
120            dot_part = dot_parts[index]
121            if index == len(dot_parts) - 1:
122                return current_obj.pop(dot_part)
123            value = _pop_deprecated_key(current_obj[dot_part], dot_parts, index + 1)
124            if not current_obj[dot_part]:
125                current_obj.pop(dot_part)
126            return value
127
128        deprecation_replacements = {}
129        for deprecation, replacement in DEPRECATIONS.items():
130            if self.get(deprecation, default=UNSET) is UNSET:
131                continue
132            message = (
133                f"'{deprecation}' has been deprecated in favor of '{replacement}'! "
134                + "Please update your configuration."
135            )
136            self.log(
137                "warning",
138                message,
139            )
140            deprecation_replacements[(deprecation, replacement)] = message
141
142            deprecated_attr = _pop_deprecated_key(self.__config, deprecation.split("."), 0)
143            self.set(replacement, deprecated_attr)
144        return deprecation_replacements

Warn if any deprecated configuration options are used

def log(self, level: str, message: str, **kwargs):
146    def log(self, level: str, message: str, **kwargs):
147        """Custom Log method, we want to ensure ConfigLoader always logs JSON even when
148        'structlog' or 'logging' hasn't been configured yet."""
149        output = {
150            "event": message,
151            "level": level,
152            "logger": self.__class__.__module__,
153            "timestamp": time(),
154        }
155        output.update(kwargs)
156        print(dumps(output), file=stderr)

Custom Log method, we want to ensure ConfigLoader always logs JSON even when 'structlog' or 'logging' hasn't been configured yet.

def update( self, root: dict[str, typing.Any], updatee: dict[str, typing.Any]) -> dict[str, typing.Any]:
158    def update(self, root: dict[str, Any], updatee: dict[str, Any]) -> dict[str, Any]:
159        """Recursively update dictionary"""
160        for key, raw_value in updatee.items():
161            if isinstance(raw_value, Mapping):
162                root[key] = self.update(root.get(key, {}), raw_value)
163            else:
164                if isinstance(raw_value, str):
165                    value = self.parse_uri(raw_value)
166                elif isinstance(raw_value, Attr) and isinstance(raw_value.value, str):
167                    value = self.parse_uri(raw_value.value)
168                elif not isinstance(raw_value, Attr):
169                    value = Attr(raw_value)
170                else:
171                    value = raw_value
172                root[key] = value
173        return root

Recursively update dictionary

def refresh(self, key: str, default=None, sep='.') -> Any:
175    def refresh(self, key: str, default=None, sep=".") -> Any:
176        """Update a single value"""
177        attr: Attr = get_path_from_dict(self.raw, key, sep=sep, default=Attr(default))
178        if attr.source_type != Attr.Source.URI:
179            return attr.value
180        attr.value = self.parse_uri(attr.source).value
181        return attr.value

Update a single value

def parse_uri(self, value: str) -> Attr:
183    def parse_uri(self, value: str) -> Attr:
184        """Parse string values which start with a URI"""
185        url = urlparse(value)
186        parsed_value = value
187        if url.scheme == "env":
188            parsed_value = os.getenv(url.netloc, url.query)
189        if url.scheme == "file":
190            try:
191                with open(url.path, encoding="utf8") as _file:
192                    parsed_value = _file.read().strip()
193            except OSError as exc:
194                self.log("error", f"Failed to read config value from {url.path}: {exc}")
195                parsed_value = url.query
196        return Attr(parsed_value, Attr.Source.URI, value)

Parse string values which start with a URI

def update_from_file(self, path: pathlib.Path):
198    def update_from_file(self, path: Path):
199        """Update config from file contents"""
200        try:
201            with open(path, encoding="utf8") as file:
202                try:
203                    self.update(self.__config, yaml.safe_load(file))
204                    self.log("debug", "Loaded config", file=str(path))
205                except yaml.YAMLError as exc:
206                    raise ImproperlyConfigured from exc
207        except PermissionError as exc:
208            self.log(
209                "warning",
210                "Permission denied while reading file",
211                path=path,
212                error=str(exc),
213            )

Update config from file contents

def update_from_dict(self, update: dict):
215    def update_from_dict(self, update: dict):
216        """Update config from dict"""
217        self.__config.update(update)

Update config from dict

def update_from_env(self):
219    def update_from_env(self):
220        """Check environment variables"""
221        outer = {}
222        idx = 0
223        for key, value in os.environ.items():
224            if not key.startswith(ENV_PREFIX):
225                continue
226            relative_key = key.replace(f"{ENV_PREFIX}_", "", 1).replace("__", ".").lower()
227            # Check if the value is json, and try to load it
228            try:
229                value = loads(value)  # noqa: PLW2901
230            except JSONDecodeError:
231                pass
232            attr_value = Attr(value, Attr.Source.ENV, relative_key)
233            set_path_in_dict(outer, relative_key, attr_value)
234            idx += 1
235        if idx > 0:
236            self.log("debug", "Loaded environment variables", count=idx)
237            self.update(self.__config, outer)

Check environment variables

@contextmanager
def patch(self, path: str, value: Any):
239    @contextmanager
240    def patch(self, path: str, value: Any):
241        """Context manager for unittests to patch a value"""
242        original_value = self.get(path, UNSET)
243        self.set(path, value)
244        try:
245            yield
246        finally:
247            if original_value is not UNSET:
248                self.set(path, original_value)
249            else:
250                self.delete(path)

Context manager for unittests to patch a value

raw: dict
252    @property
253    def raw(self) -> dict:
254        """Get raw config dictionary"""
255        return self.__config

Get raw config dictionary

def get(self, path: str, default=None, sep='.') -> Any:
257    def get(self, path: str, default=None, sep=".") -> Any:
258        """Access attribute by using yaml path"""
259        # Walk sub_dicts before parsing path
260        root = self.raw
261        # Walk each component of the path
262        attr: Attr = get_path_from_dict(root, path, sep=sep, default=Attr(default))
263        return attr.value

Access attribute by using yaml path

def get_int(self, path: str, default=0) -> int:
265    def get_int(self, path: str, default=0) -> int:
266        """Wrapper for get that converts value into int"""
267        try:
268            return int(self.get(path, default))
269        except ValueError as exc:
270            self.log("warning", "Failed to parse config as int", path=path, exc=str(exc))
271            return default

Wrapper for get that converts value into int

def get_optional_int(self, path: str, default=None) -> int | None:
273    def get_optional_int(self, path: str, default=None) -> int | None:
274        """Wrapper for get that converts value into int or None if set"""
275        value = self.get(path, UNSET)
276        if value is UNSET:
277            return default
278        try:
279            return int(value)
280        except (ValueError, TypeError) as exc:
281            if value is None or (isinstance(value, str) and value.lower() in ("", "null", "none")):
282                return None
283            self.log("warning", "Failed to parse config as int", path=path, exc=str(exc))
284            return default

Wrapper for get that converts value into int or None if set

def get_bool(self, path: str, default=False) -> bool:
286    def get_bool(self, path: str, default=False) -> bool:
287        """Wrapper for get that converts value into boolean"""
288        value = self.get(path, UNSET)
289        if value is UNSET:
290            return default
291        return str(self.get(path)).lower() == "true"

Wrapper for get that converts value into boolean

def get_keys(self, path: str, sep='.') -> list[str]:
293    def get_keys(self, path: str, sep=".") -> list[str]:
294        """List attribute keys by using yaml path"""
295        root = self.raw
296        attr: Attr = get_path_from_dict(root, path, sep=sep, default=Attr({}))
297        return attr.keys()

List attribute keys by using yaml path

def get_dict_from_b64_json(self, path: str, default=None) -> dict:
299    def get_dict_from_b64_json(self, path: str, default=None) -> dict:
300        """Wrapper for get that converts value from Base64 encoded string into dictionary"""
301        config_value = self.get(path)
302        if config_value is None:
303            return {}
304        try:
305            b64decoded_str = base64.b64decode(config_value).decode("utf-8")
306            return json.loads(b64decoded_str)
307        except (JSONDecodeError, TypeError, ValueError) as exc:
308            self.log(
309                "warning",
310                f"Ignored invalid configuration for '{path}' due to exception: {str(exc)}",
311            )
312            return default if isinstance(default, dict) else {}

Wrapper for get that converts value from Base64 encoded string into dictionary

def set(self, path: str, value: Any, sep='.'):
314    def set(self, path: str, value: Any, sep="."):
315        """Set value using same syntax as get()"""
316        if not isinstance(value, Attr):
317            value = Attr(value)
318        set_path_in_dict(self.raw, path, value, sep=sep)

Set value using same syntax as get()

def delete(self, path: str, sep='.'):
320    def delete(self, path: str, sep="."):
321        delete_path_in_dict(self.raw, path, sep=sep)
CONFIG = <ConfigLoader object>
DIRECT_DB_ALIAS = 'direct'
def postgresql_direct_db_enabled(config: ConfigLoader | None = None) -> bool:
333def postgresql_direct_db_enabled(config: ConfigLoader | None = None) -> bool:
334    """Whether a dedicated direct PostgreSQL endpoint has been configured.
335
336    Returns True if any ``postgresql.direct.*`` key is set. When True, a Django
337    connection at alias ``direct`` is added; subsystems that hold server-side
338    state (LISTEN/NOTIFY, advisory locks) route through it so an operator can
339    put a transaction-pooling pooler in front of ``postgresql.host`` without
340    breaking them.
341
342    Also True when the connection pool is enabled: those long-lived connections would
343    otherwise permanently hold slots in the pool and starve it.
344    """
345    if not config:
346        config = CONFIG
347    if config.get_bool("postgresql.use_pool", False):
348        return True
349    return any(
350        config.get(f"postgresql.direct.{key}", default=UNSET) is not UNSET
351        for key in (
352            "host",
353            "port",
354            "name",
355            "user",
356            "password",
357            "sslmode",
358            "sslrootcert",
359            "sslcert",
360            "sslkey",
361            "conn_options",
362        )
363    )

Whether a dedicated direct PostgreSQL endpoint has been configured.

Returns True if any postgresql.direct.* key is set. When True, a Django connection at alias direct is added; subsystems that hold server-side state (LISTEN/NOTIFY, advisory locks) route through it so an operator can put a transaction-pooling pooler in front of postgresql.host without breaking them.

Also True when the connection pool is enabled: those long-lived connections would otherwise permanently hold slots in the pool and starve it.

def advisory_lock_db_alias(config: ConfigLoader | None = None) -> str:
366def advisory_lock_db_alias(config: ConfigLoader | None = None) -> str:
367    """Return the DB alias to use for session-scoped advisory locks.
368
369    Routes through the direct endpoint when configured so the locks survive
370    a transaction-mode pooler in front of ``postgresql.host`` (the lock and
371    its release must run on the same backend connection).
372    """
373    return DIRECT_DB_ALIAS if postgresql_direct_db_enabled(config) else DEFAULT_DB_ALIAS

Return the DB alias to use for session-scoped advisory locks.

Routes through the direct endpoint when configured so the locks survive a transaction-mode pooler in front of postgresql.host (the lock and its release must run on the same backend connection).

def postgresql_direct_connection_kwargs(config: ConfigLoader | None = None) -> dict:
376def postgresql_direct_connection_kwargs(config: ConfigLoader | None = None) -> dict:
377    """Return kwargs suitable for ``psycopg.connect()`` for the direct endpoint.
378
379    Reads ``postgresql.direct.*`` overrides, falling back to ``postgresql.*``
380    for unset keys. Used by ``lifecycle/migrate.py`` for the startup advisory
381    lock.
382    """
383    if not config:
384        config = CONFIG
385
386    def _override(field: str, default):
387        return config.get(f"postgresql.direct.{field}", default=default)
388
389    kwargs = {
390        "host": _override("host", config.get("postgresql.host")),
391        "port": _override("port", config.get_int("postgresql.port", 5432)),
392        "dbname": _override("name", config.get("postgresql.name")),
393        "user": _override("user", config.get("postgresql.user")),
394        "password": _override("password", config.get("postgresql.password")),
395        "sslmode": _override("sslmode", config.get("postgresql.sslmode")),
396        "sslrootcert": _override("sslrootcert", config.get("postgresql.sslrootcert")),
397        "sslcert": _override("sslcert", config.get("postgresql.sslcert")),
398        "sslkey": _override("sslkey", config.get("postgresql.sslkey")),
399    }
400    # direct.conn_options wins over the main conn_options when both are set.
401    conn_opts = config.get_dict_from_b64_json("postgresql.conn_options", default={})
402    direct_conn_opts = config.get_dict_from_b64_json("postgresql.direct.conn_options", default={})
403    kwargs.update(conn_opts)
404    kwargs.update(direct_conn_opts)
405    return {k: v for k, v in kwargs.items() if v is not None}

Return kwargs suitable for psycopg.connect() for the direct endpoint.

Reads postgresql.direct.* overrides, falling back to postgresql.* for unset keys. Used by lifecycle/migrate.py for the startup advisory lock.

def django_db_config(config: ConfigLoader | None = None) -> dict:
441def django_db_config(config: ConfigLoader | None = None) -> dict:
442    if not config:
443        config = CONFIG
444
445    pool_options = False
446    use_pool = config.get_bool("postgresql.use_pool", False)
447    if use_pool:
448        pool_options = config.get_dict_from_b64_json("postgresql.pool_options", True)
449        if not pool_options:
450            # psycopg's default max_size of 4 is too small for concurrent requests, and must
451            # be larger than the number of worker threads
452            pool_options = {"max_size": max(10, config.get_int("worker.threads", 2) + 1)}
453
454    conn_options = config.get_dict_from_b64_json("postgresql.conn_options", default={})
455
456    db = {
457        "default": {
458            "ENGINE": "psqlextra.backend",
459            "HOST": config.get("postgresql.host"),
460            "NAME": config.get("postgresql.name"),
461            "USER": config.get("postgresql.user"),
462            "PASSWORD": config.get("postgresql.password"),
463            "PORT": config.get("postgresql.port"),
464            "OPTIONS": {
465                "sslmode": config.get("postgresql.sslmode"),
466                "sslrootcert": config.get("postgresql.sslrootcert"),
467                "sslcert": config.get("postgresql.sslcert"),
468                "sslkey": config.get("postgresql.sslkey"),
469                "pool": pool_options,
470                **conn_options,
471            },
472            "CONN_MAX_AGE": config.get_optional_int("postgresql.conn_max_age", 0),
473            "CONN_HEALTH_CHECKS": config.get_bool("postgresql.conn_health_checks", False),
474            "DISABLE_SERVER_SIDE_CURSORS": config.get_bool(
475                "postgresql.disable_server_side_cursors", False
476            ),
477            "TEST": {
478                "NAME": config.get("postgresql.test.name"),
479            },
480        }
481    }
482
483    conn_max_age = config.get_optional_int("postgresql.conn_max_age", UNSET)
484    disable_server_side_cursors = config.get_bool("postgresql.disable_server_side_cursors", UNSET)
485    use_pgpool = config.get_bool("postgresql.use_pgpool", False)
486    use_pgbouncer = config.get_bool("postgresql.use_pgbouncer", False)
487    if use_pgpool:
488        db["default"]["DISABLE_SERVER_SIDE_CURSORS"] = True
489        if disable_server_side_cursors is not UNSET:
490            db["default"]["DISABLE_SERVER_SIDE_CURSORS"] = disable_server_side_cursors
491
492    if use_pgbouncer:
493        # https://docs.djangoproject.com/en/4.0/ref/databases/#transaction-pooling-server-side-cursors
494        db["default"]["DISABLE_SERVER_SIDE_CURSORS"] = True
495        # https://docs.djangoproject.com/en/4.0/ref/databases/#persistent-connections
496        db["default"]["CONN_MAX_AGE"] = None  # persistent
497        if disable_server_side_cursors is not UNSET:
498            db["default"]["DISABLE_SERVER_SIDE_CURSORS"] = disable_server_side_cursors
499        if conn_max_age is not UNSET:
500            db["default"]["CONN_MAX_AGE"] = conn_max_age
501
502    # Django runs `SET TimeZone` on every new connection unless the server reports exactly
503    # "UTC" (Postgres defaults to "GMT"), so set it at connect time instead. Poolers reject
504    # the `options` startup parameter; a user-provided `options` takes precedence.
505    if not use_pgpool and not use_pgbouncer:
506        db["default"]["OPTIONS"].setdefault("options", "-c TimeZone=UTC")
507
508    all_replica_conn_options = config.get_dict_from_b64_json(
509        "postgresql.replica_conn_options",
510        default={},
511    )
512
513    for replica in config.get_keys("postgresql.read_replicas"):
514        _database = deepcopy(db["default"])
515
516        for setting, current_value in db["default"].items():
517            if isinstance(current_value, dict):
518                continue
519            override = config.get(
520                f"postgresql.read_replicas.{replica}.{setting.lower()}", default=UNSET
521            )
522            if override is not UNSET:
523                _database[setting] = override
524
525        for option in conn_options.keys():
526            _database["OPTIONS"].pop(option, None)
527
528        for setting in db["default"]["OPTIONS"].keys():
529            override = config.get(
530                f"postgresql.read_replicas.{replica}.{setting.lower()}", default=UNSET
531            )
532            if override is not UNSET:
533                _database["OPTIONS"][setting] = override
534
535        _database["OPTIONS"].update(all_replica_conn_options)
536        replica_conn_options = config.get_dict_from_b64_json(
537            f"postgresql.read_replicas.{replica}.conn_options", default={}
538        )
539        _database["OPTIONS"].update(replica_conn_options)
540
541        db[f"replica_{replica}"] = _database
542
543    # Optional direct endpoint for LISTEN/NOTIFY and advisory-lock connections.
544    # Only added when operator sets ``postgresql.direct.*``; excluded from
545    # replica routing and migrations by ``authentik.root.db.router.FailoverRouter``.
546    if postgresql_direct_db_enabled(config):
547        db[DIRECT_DB_ALIAS] = _build_direct_db_alias(db["default"], config)
548
549    return db