authentik.blueprints.apps

authentik Blueprints app

  1"""authentik Blueprints app"""
  2
  3import traceback
  4from collections.abc import Callable
  5from importlib import import_module
  6
  7from django.apps import AppConfig
  8from django.conf import settings
  9from django.db import DatabaseError, InternalError, ProgrammingError
 10from dramatiq.broker import get_broker
 11from structlog.stdlib import BoundLogger, get_logger
 12
 13from authentik.lib.utils.time import fqdn_rand
 14from authentik.root.signals import startup
 15from authentik.tasks.schedules.common import ScheduleSpec
 16
 17
 18class ManagedAppConfig(AppConfig):
 19    """Basic reconciliation logic for apps"""
 20
 21    logger: BoundLogger
 22
 23    def __init__(self, app_name: str, *args, **kwargs) -> None:
 24        super().__init__(app_name, *args, **kwargs)
 25        self.logger = get_logger().bind(app_name=app_name)
 26
 27    def ready(self) -> None:
 28        self.import_related()
 29        startup.connect(self._on_startup_callback, dispatch_uid=self.label)
 30        return super().ready()
 31
 32    def _on_startup_callback(self, sender, **_):
 33        self._reconcile()
 34
 35    def import_related(self):
 36        """Automatically import related modules which rely on just being imported
 37        to register themselves (mainly django signals and tasks)"""
 38
 39        def import_relative(rel_module: str):
 40            try:
 41                module_name = f"{self.name}.{rel_module}"
 42                import_module(module_name)
 43                self.logger.info("Imported related module", module=module_name)
 44            except ModuleNotFoundError as exc:
 45                if settings.DEBUG:
 46                    # This is a heuristic for determining whether the exception was caused
 47                    # "directly" by the `import_module` call or whether the initial import
 48                    # succeeded and a later import (within the existing module) failed.
 49                    # 1. <the calling function>
 50                    # 2. importlib.import_module
 51                    # 3. importlib._bootstrap._gcd_import
 52                    # 4. importlib._bootstrap._find_and_load
 53                    # 5. importlib._bootstrap._find_and_load_unlocked
 54                    STACK_LENGTH_HEURISTIC = 5
 55
 56                    stack_length = len(traceback.extract_tb(exc.__traceback__))
 57                    if stack_length > STACK_LENGTH_HEURISTIC:
 58                        raise
 59
 60        import_relative("checks")
 61        import_relative("tasks")
 62        import_relative("signals")
 63
 64    def import_module(self, path: str):
 65        """Load module"""
 66        import_module(path)
 67
 68    def _reconcile(self) -> None:
 69        for name in dir(self):
 70            # Check the attribute on the class to avoid evaluating @property descriptors.
 71            # Using getattr(self, ...) on a @property would evaluate it, which can trigger
 72            # expensive side effects (e.g. schedule_specs iterating all providers
 73            # and running PolicyEngine queries for every user).
 74            class_attr = getattr(type(self), name, None)
 75            if class_attr is None or isinstance(class_attr, property):
 76                continue
 77            if not callable(class_attr):
 78                continue
 79            if not getattr(class_attr, "_authentik_managed_reconcile", False):
 80                continue
 81            meth = getattr(self, name)
 82            try:
 83                self.logger.debug("Starting reconciler", name=name)
 84                meth()
 85                self.logger.debug("Successfully reconciled", name=name)
 86            except (DatabaseError, ProgrammingError, InternalError) as exc:
 87                self.logger.warning("Failed to run reconcile", name=name, exc=exc)
 88
 89    @staticmethod
 90    def reconcile(func: Callable):
 91        """Mark a function to be called on startup"""
 92        func._authentik_managed_reconcile = True
 93        return func
 94
 95    @property
 96    def schedule_specs(self) -> list[ScheduleSpec]:
 97        """Get a list of schedule specs that must exist"""
 98        return []
 99
100
101class AuthentikBlueprintsConfig(ManagedAppConfig):
102    """authentik Blueprints app"""
103
104    name = "authentik.blueprints"
105    label = "authentik_blueprints"
106    verbose_name = "authentik Blueprints"
107    default = True
108
109    def import_models(self):
110        super().import_models()
111        self.import_module("authentik.blueprints.v1.meta.apply_blueprint")
112
113    @ManagedAppConfig.reconcile
114    def tasks_middlewares(self):
115        from authentik.blueprints.v1.tasks import BlueprintWatcherMiddleware
116
117        get_broker().add_middleware(BlueprintWatcherMiddleware())
118
119    @property
120    def schedule_specs(self) -> list[ScheduleSpec]:
121        from authentik.blueprints.v1.tasks import blueprints_discovery, clear_failed_blueprints
122
123        return [
124            ScheduleSpec(
125                actor=blueprints_discovery,
126                crontab=f"{fqdn_rand('blueprints_v1_discover')} * * * *",
127                send_on_startup=True,
128            ),
129            ScheduleSpec(
130                actor=clear_failed_blueprints,
131                crontab=f"{fqdn_rand('blueprints_v1_cleanup')} * * * *",
132                send_on_startup=True,
133            ),
134        ]
class ManagedAppConfig(django.apps.config.AppConfig):
19class ManagedAppConfig(AppConfig):
20    """Basic reconciliation logic for apps"""
21
22    logger: BoundLogger
23
24    def __init__(self, app_name: str, *args, **kwargs) -> None:
25        super().__init__(app_name, *args, **kwargs)
26        self.logger = get_logger().bind(app_name=app_name)
27
28    def ready(self) -> None:
29        self.import_related()
30        startup.connect(self._on_startup_callback, dispatch_uid=self.label)
31        return super().ready()
32
33    def _on_startup_callback(self, sender, **_):
34        self._reconcile()
35
36    def import_related(self):
37        """Automatically import related modules which rely on just being imported
38        to register themselves (mainly django signals and tasks)"""
39
40        def import_relative(rel_module: str):
41            try:
42                module_name = f"{self.name}.{rel_module}"
43                import_module(module_name)
44                self.logger.info("Imported related module", module=module_name)
45            except ModuleNotFoundError as exc:
46                if settings.DEBUG:
47                    # This is a heuristic for determining whether the exception was caused
48                    # "directly" by the `import_module` call or whether the initial import
49                    # succeeded and a later import (within the existing module) failed.
50                    # 1. <the calling function>
51                    # 2. importlib.import_module
52                    # 3. importlib._bootstrap._gcd_import
53                    # 4. importlib._bootstrap._find_and_load
54                    # 5. importlib._bootstrap._find_and_load_unlocked
55                    STACK_LENGTH_HEURISTIC = 5
56
57                    stack_length = len(traceback.extract_tb(exc.__traceback__))
58                    if stack_length > STACK_LENGTH_HEURISTIC:
59                        raise
60
61        import_relative("checks")
62        import_relative("tasks")
63        import_relative("signals")
64
65    def import_module(self, path: str):
66        """Load module"""
67        import_module(path)
68
69    def _reconcile(self) -> None:
70        for name in dir(self):
71            # Check the attribute on the class to avoid evaluating @property descriptors.
72            # Using getattr(self, ...) on a @property would evaluate it, which can trigger
73            # expensive side effects (e.g. schedule_specs iterating all providers
74            # and running PolicyEngine queries for every user).
75            class_attr = getattr(type(self), name, None)
76            if class_attr is None or isinstance(class_attr, property):
77                continue
78            if not callable(class_attr):
79                continue
80            if not getattr(class_attr, "_authentik_managed_reconcile", False):
81                continue
82            meth = getattr(self, name)
83            try:
84                self.logger.debug("Starting reconciler", name=name)
85                meth()
86                self.logger.debug("Successfully reconciled", name=name)
87            except (DatabaseError, ProgrammingError, InternalError) as exc:
88                self.logger.warning("Failed to run reconcile", name=name, exc=exc)
89
90    @staticmethod
91    def reconcile(func: Callable):
92        """Mark a function to be called on startup"""
93        func._authentik_managed_reconcile = True
94        return func
95
96    @property
97    def schedule_specs(self) -> list[ScheduleSpec]:
98        """Get a list of schedule specs that must exist"""
99        return []

Basic reconciliation logic for apps

ManagedAppConfig(app_name: str, *args, **kwargs)
24    def __init__(self, app_name: str, *args, **kwargs) -> None:
25        super().__init__(app_name, *args, **kwargs)
26        self.logger = get_logger().bind(app_name=app_name)
logger: structlog.stdlib.BoundLogger
def ready(self) -> None:
28    def ready(self) -> None:
29        self.import_related()
30        startup.connect(self._on_startup_callback, dispatch_uid=self.label)
31        return super().ready()

Override this method in subclasses to run code when Django starts.

def import_module(self, path: str):
65    def import_module(self, path: str):
66        """Load module"""
67        import_module(path)

Load module

@staticmethod
def reconcile(func: Callable):
90    @staticmethod
91    def reconcile(func: Callable):
92        """Mark a function to be called on startup"""
93        func._authentik_managed_reconcile = True
94        return func

Mark a function to be called on startup

schedule_specs: list[authentik.tasks.schedules.common.ScheduleSpec]
96    @property
97    def schedule_specs(self) -> list[ScheduleSpec]:
98        """Get a list of schedule specs that must exist"""
99        return []

Get a list of schedule specs that must exist

class AuthentikBlueprintsConfig(ManagedAppConfig):
102class AuthentikBlueprintsConfig(ManagedAppConfig):
103    """authentik Blueprints app"""
104
105    name = "authentik.blueprints"
106    label = "authentik_blueprints"
107    verbose_name = "authentik Blueprints"
108    default = True
109
110    def import_models(self):
111        super().import_models()
112        self.import_module("authentik.blueprints.v1.meta.apply_blueprint")
113
114    @ManagedAppConfig.reconcile
115    def tasks_middlewares(self):
116        from authentik.blueprints.v1.tasks import BlueprintWatcherMiddleware
117
118        get_broker().add_middleware(BlueprintWatcherMiddleware())
119
120    @property
121    def schedule_specs(self) -> list[ScheduleSpec]:
122        from authentik.blueprints.v1.tasks import blueprints_discovery, clear_failed_blueprints
123
124        return [
125            ScheduleSpec(
126                actor=blueprints_discovery,
127                crontab=f"{fqdn_rand('blueprints_v1_discover')} * * * *",
128                send_on_startup=True,
129            ),
130            ScheduleSpec(
131                actor=clear_failed_blueprints,
132                crontab=f"{fqdn_rand('blueprints_v1_cleanup')} * * * *",
133                send_on_startup=True,
134            ),
135        ]

authentik Blueprints app

label = 'authentik_blueprints'
verbose_name = 'authentik Blueprints'
default = True
def import_models(self):
110    def import_models(self):
111        super().import_models()
112        self.import_module("authentik.blueprints.v1.meta.apply_blueprint")
@ManagedAppConfig.reconcile
def tasks_middlewares(self):
114    @ManagedAppConfig.reconcile
115    def tasks_middlewares(self):
116        from authentik.blueprints.v1.tasks import BlueprintWatcherMiddleware
117
118        get_broker().add_middleware(BlueprintWatcherMiddleware())
schedule_specs: list[authentik.tasks.schedules.common.ScheduleSpec]
120    @property
121    def schedule_specs(self) -> list[ScheduleSpec]:
122        from authentik.blueprints.v1.tasks import blueprints_discovery, clear_failed_blueprints
123
124        return [
125            ScheduleSpec(
126                actor=blueprints_discovery,
127                crontab=f"{fqdn_rand('blueprints_v1_discover')} * * * *",
128                send_on_startup=True,
129            ),
130            ScheduleSpec(
131                actor=clear_failed_blueprints,
132                crontab=f"{fqdn_rand('blueprints_v1_cleanup')} * * * *",
133                send_on_startup=True,
134            ),
135        ]

Get a list of schedule specs that must exist