authentik.blueprints.v1.tasks

v1 blueprints tasks

  1"""v1 blueprints tasks"""
  2
  3from dataclasses import asdict, dataclass, field
  4from pathlib import Path
  5from sys import platform
  6from uuid import UUID
  7
  8from dacite.core import from_dict
  9from django.conf import settings
 10from django.db import DatabaseError, InternalError, ProgrammingError
 11from django.utils.text import slugify
 12from django.utils.timezone import now
 13from django.utils.translation import gettext_lazy as _
 14from dramatiq.actor import actor
 15from dramatiq.middleware import Middleware
 16from structlog.stdlib import get_logger
 17from watchdog.events import (
 18    FileCreatedEvent,
 19    FileModifiedEvent,
 20    FileSystemEvent,
 21    FileSystemEventHandler,
 22)
 23from watchdog.observers import Observer
 24from yaml import load
 25from yaml.error import YAMLError
 26
 27from authentik.blueprints.models import (
 28    BlueprintInstance,
 29    BlueprintInstanceStatus,
 30    BlueprintRetrievalFailed,
 31)
 32from authentik.blueprints.v1.common import BlueprintLoader, BlueprintMetadata, EntryInvalidError
 33from authentik.blueprints.v1.hash import blueprint_hash
 34from authentik.blueprints.v1.importer import Importer
 35from authentik.blueprints.v1.labels import LABEL_AUTHENTIK_INSTANTIATE
 36from authentik.blueprints.v1.oci import OCI_PREFIX
 37from authentik.events.logs import capture_logs
 38from authentik.events.utils import sanitize_dict
 39from authentik.lib.config import CONFIG
 40from authentik.tasks.apps import PRIORITY_HIGH
 41from authentik.tasks.middleware import CurrentTask
 42from authentik.tasks.schedules.models import Schedule
 43
 44LOGGER = get_logger()
 45
 46
 47@dataclass
 48class BlueprintFile:
 49    """Basic info about a blueprint file"""
 50
 51    path: str
 52    version: int
 53    hash: str
 54    last_m: int
 55    meta: BlueprintMetadata | None = field(default=None)
 56
 57
 58class BlueprintWatcherMiddleware(Middleware):
 59    def start_blueprint_watcher(self):
 60        """Start blueprint watcher"""
 61        observer = Observer()
 62        kwargs = {}
 63        if platform.startswith("linux"):
 64            kwargs["event_filter"] = (FileCreatedEvent, FileModifiedEvent)
 65        observer.schedule(
 66            BlueprintEventHandler(), CONFIG.get("blueprints_dir"), recursive=True, **kwargs
 67        )
 68        observer.start()
 69
 70    def after_worker_boot(self, broker, worker):
 71        if not settings.TEST:
 72            self.start_blueprint_watcher()
 73
 74
 75class BlueprintEventHandler(FileSystemEventHandler):
 76    """Event handler for blueprint events"""
 77
 78    # We only ever get creation and modification events.
 79    # See the creation of the Observer instance above for the event filtering.
 80
 81    # Even though we filter to only get file events, we might still get
 82    # directory events as some implementations such as inotify do not support
 83    # filtering on file/directory.
 84
 85    def dispatch(self, event: FileSystemEvent) -> None:
 86        """Call specific event handler method. Ignores directory changes."""
 87        if event.is_directory:
 88            return None
 89        return super().dispatch(event)
 90
 91    def on_created(self, event: FileSystemEvent):
 92        """Process file creation"""
 93        LOGGER.debug("new blueprint file created, starting discovery")
 94        Schedule.dispatch_by_actor(blueprints_discovery)
 95
 96    def on_modified(self, event: FileSystemEvent):
 97        """Process file modification"""
 98        path = Path(event.src_path)
 99        root = Path(CONFIG.get("blueprints_dir")).absolute()
100        rel_path = str(path.relative_to(root))
101        for instance in BlueprintInstance.objects.filter(path=rel_path, enabled=True):
102            LOGGER.debug("modified blueprint file, starting apply", instance=instance)
103            apply_blueprint.send_with_options(args=(instance.pk,), rel_obj=instance)
104
105
106@actor(
107    description=_("Find blueprints as `blueprints_find` does, but return a safe dict."),
108    priority=PRIORITY_HIGH,
109)
110def blueprints_find_dict():
111    blueprints = []
112    for blueprint in blueprints_find():
113        blueprints.append(sanitize_dict(asdict(blueprint)))
114    return blueprints
115
116
117def blueprints_find() -> list[BlueprintFile]:
118    """Find blueprints and return valid ones"""
119    blueprints = []
120    root = Path(CONFIG.get("blueprints_dir"))
121    for path in root.rglob("**/*.yaml"):
122        rel_path = path.relative_to(root)
123        # Check if any part in the path starts with a dot and assume a hidden file
124        if any(part for part in rel_path.parts if part.startswith(".")):
125            continue
126        with open(path, encoding="utf-8") as blueprint_file:
127            content = blueprint_file.read()
128            try:
129                raw_blueprint = load(content, BlueprintLoader)
130            except YAMLError as exc:
131                raw_blueprint = None
132                LOGGER.warning("failed to parse blueprint", exc=exc, path=str(rel_path))
133            if not raw_blueprint:
134                continue
135            metadata = raw_blueprint.get("metadata", None)
136            version = raw_blueprint.get("version", 1)
137            if version != 1:
138                LOGGER.warning("invalid blueprint version", version=version, path=str(rel_path))
139                continue
140        file_hash = blueprint_hash(content)
141        blueprint = BlueprintFile(str(rel_path), version, file_hash, int(path.stat().st_mtime))
142        blueprint.meta = from_dict(BlueprintMetadata, metadata) if metadata else None
143        blueprints.append(blueprint)
144    return blueprints
145
146
147@actor(description=_("Find blueprints and check if they need to be created in the database."))
148def blueprints_discovery(path: str | None = None):
149    self = CurrentTask.get_task()
150    count = 0
151    for blueprint in blueprints_find():
152        if path and blueprint.path != path:
153            continue
154        check_blueprint_v1_file(blueprint)
155        count += 1
156    self.info(f"Successfully imported {count} files.")
157
158
159def check_blueprint_v1_file(blueprint: BlueprintFile):
160    """Check if blueprint should be imported"""
161    instance: BlueprintInstance = BlueprintInstance.objects.filter(path=blueprint.path).first()
162    if (
163        blueprint.meta
164        and blueprint.meta.labels.get(LABEL_AUTHENTIK_INSTANTIATE, "").lower() == "false"
165    ):
166        return
167    if not instance:
168        instance = BlueprintInstance(
169            name=blueprint.meta.name if blueprint.meta else str(blueprint.path),
170            path=blueprint.path,
171            context={},
172            status=BlueprintInstanceStatus.UNKNOWN,
173            enabled=True,
174            managed_models=[],
175            metadata={},
176        )
177        instance.save()
178        LOGGER.info(
179            "Creating new blueprint instance from file", instance=instance, path=instance.path
180        )
181    if instance.last_applied_hash != blueprint.hash:
182        LOGGER.info("Applying blueprint due to changed file", instance=instance, path=instance.path)
183        apply_blueprint.send_with_options(args=(instance.pk,), rel_obj=instance)
184
185
186@actor(description=_("Apply single blueprint."))
187def apply_blueprint(instance_pk: UUID):
188    self = CurrentTask.get_task()
189    self.set_uid(str(instance_pk))
190    instance: BlueprintInstance | None = None
191    try:
192        instance: BlueprintInstance = BlueprintInstance.objects.filter(pk=instance_pk).first()
193        if not instance:
194            self.warning(f"Could not find blueprint {instance_pk}, skipping")
195            return
196        self.set_uid(slugify(instance.name))
197        if not instance.enabled:
198            self.info(f"Blueprint {instance.name} is disabled, skipping")
199            return
200        blueprint_content = instance.retrieve()
201        file_hash = blueprint_hash(blueprint_content)
202        importer = Importer.from_string(blueprint_content, instance.context)
203        if importer.blueprint.metadata:
204            instance.metadata = asdict(importer.blueprint.metadata)
205        valid, logs = importer.validate()
206        if not valid:
207            instance.status = BlueprintInstanceStatus.ERROR
208            instance.save()
209            self.logs(logs)
210            return
211        with capture_logs() as logs:
212            applied = importer.apply()
213            if not applied:
214                instance.status = BlueprintInstanceStatus.ERROR
215                instance.save()
216                self.logs(logs)
217                return
218        instance.status = BlueprintInstanceStatus.SUCCESSFUL
219        instance.last_applied_hash = file_hash
220        instance.last_applied = now()
221    except (
222        OSError,
223        DatabaseError,
224        ProgrammingError,
225        InternalError,
226        BlueprintRetrievalFailed,
227        EntryInvalidError,
228    ) as exc:
229        if instance:
230            instance.status = BlueprintInstanceStatus.ERROR
231        self.error(exc)
232    finally:
233        if instance:
234            instance.save()
235
236
237@actor(description=_("Remove blueprints which couldn't be fetched."))
238def clear_failed_blueprints():
239    # Exclude OCI blueprints as those might be temporarily unavailable
240    for blueprint in BlueprintInstance.objects.exclude(path__startswith=OCI_PREFIX):
241        try:
242            blueprint.retrieve()
243        except BlueprintRetrievalFailed:
244            blueprint.delete()
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
@dataclass
class BlueprintFile:
48@dataclass
49class BlueprintFile:
50    """Basic info about a blueprint file"""
51
52    path: str
53    version: int
54    hash: str
55    last_m: int
56    meta: BlueprintMetadata | None = field(default=None)

Basic info about a blueprint file

BlueprintFile( path: str, version: int, hash: str, last_m: int, meta: authentik.blueprints.v1.common.BlueprintMetadata | None = None)
path: str
version: int
hash: str
last_m: int
class BlueprintWatcherMiddleware(dramatiq.middleware.middleware.Middleware):
59class BlueprintWatcherMiddleware(Middleware):
60    def start_blueprint_watcher(self):
61        """Start blueprint watcher"""
62        observer = Observer()
63        kwargs = {}
64        if platform.startswith("linux"):
65            kwargs["event_filter"] = (FileCreatedEvent, FileModifiedEvent)
66        observer.schedule(
67            BlueprintEventHandler(), CONFIG.get("blueprints_dir"), recursive=True, **kwargs
68        )
69        observer.start()
70
71    def after_worker_boot(self, broker, worker):
72        if not settings.TEST:
73            self.start_blueprint_watcher()

Base class for broker middleware. The default implementations for all hooks are no-ops and subclasses may implement whatever subset of hooks they like.

def start_blueprint_watcher(self):
60    def start_blueprint_watcher(self):
61        """Start blueprint watcher"""
62        observer = Observer()
63        kwargs = {}
64        if platform.startswith("linux"):
65            kwargs["event_filter"] = (FileCreatedEvent, FileModifiedEvent)
66        observer.schedule(
67            BlueprintEventHandler(), CONFIG.get("blueprints_dir"), recursive=True, **kwargs
68        )
69        observer.start()

Start blueprint watcher

def after_worker_boot(self, broker, worker):
71    def after_worker_boot(self, broker, worker):
72        if not settings.TEST:
73            self.start_blueprint_watcher()

Called after the worker process has started up.

class BlueprintEventHandler(watchdog.events.FileSystemEventHandler):
 76class BlueprintEventHandler(FileSystemEventHandler):
 77    """Event handler for blueprint events"""
 78
 79    # We only ever get creation and modification events.
 80    # See the creation of the Observer instance above for the event filtering.
 81
 82    # Even though we filter to only get file events, we might still get
 83    # directory events as some implementations such as inotify do not support
 84    # filtering on file/directory.
 85
 86    def dispatch(self, event: FileSystemEvent) -> None:
 87        """Call specific event handler method. Ignores directory changes."""
 88        if event.is_directory:
 89            return None
 90        return super().dispatch(event)
 91
 92    def on_created(self, event: FileSystemEvent):
 93        """Process file creation"""
 94        LOGGER.debug("new blueprint file created, starting discovery")
 95        Schedule.dispatch_by_actor(blueprints_discovery)
 96
 97    def on_modified(self, event: FileSystemEvent):
 98        """Process file modification"""
 99        path = Path(event.src_path)
100        root = Path(CONFIG.get("blueprints_dir")).absolute()
101        rel_path = str(path.relative_to(root))
102        for instance in BlueprintInstance.objects.filter(path=rel_path, enabled=True):
103            LOGGER.debug("modified blueprint file, starting apply", instance=instance)
104            apply_blueprint.send_with_options(args=(instance.pk,), rel_obj=instance)

Event handler for blueprint events

def dispatch(self, event: watchdog.events.FileSystemEvent) -> None:
86    def dispatch(self, event: FileSystemEvent) -> None:
87        """Call specific event handler method. Ignores directory changes."""
88        if event.is_directory:
89            return None
90        return super().dispatch(event)

Call specific event handler method. Ignores directory changes.

def on_created(self, event: watchdog.events.FileSystemEvent):
92    def on_created(self, event: FileSystemEvent):
93        """Process file creation"""
94        LOGGER.debug("new blueprint file created, starting discovery")
95        Schedule.dispatch_by_actor(blueprints_discovery)

Process file creation

def on_modified(self, event: watchdog.events.FileSystemEvent):
 97    def on_modified(self, event: FileSystemEvent):
 98        """Process file modification"""
 99        path = Path(event.src_path)
100        root = Path(CONFIG.get("blueprints_dir")).absolute()
101        rel_path = str(path.relative_to(root))
102        for instance in BlueprintInstance.objects.filter(path=rel_path, enabled=True):
103            LOGGER.debug("modified blueprint file, starting apply", instance=instance)
104            apply_blueprint.send_with_options(args=(instance.pk,), rel_obj=instance)

Process file modification

def blueprints_find() -> list[BlueprintFile]:
118def blueprints_find() -> list[BlueprintFile]:
119    """Find blueprints and return valid ones"""
120    blueprints = []
121    root = Path(CONFIG.get("blueprints_dir"))
122    for path in root.rglob("**/*.yaml"):
123        rel_path = path.relative_to(root)
124        # Check if any part in the path starts with a dot and assume a hidden file
125        if any(part for part in rel_path.parts if part.startswith(".")):
126            continue
127        with open(path, encoding="utf-8") as blueprint_file:
128            content = blueprint_file.read()
129            try:
130                raw_blueprint = load(content, BlueprintLoader)
131            except YAMLError as exc:
132                raw_blueprint = None
133                LOGGER.warning("failed to parse blueprint", exc=exc, path=str(rel_path))
134            if not raw_blueprint:
135                continue
136            metadata = raw_blueprint.get("metadata", None)
137            version = raw_blueprint.get("version", 1)
138            if version != 1:
139                LOGGER.warning("invalid blueprint version", version=version, path=str(rel_path))
140                continue
141        file_hash = blueprint_hash(content)
142        blueprint = BlueprintFile(str(rel_path), version, file_hash, int(path.stat().st_mtime))
143        blueprint.meta = from_dict(BlueprintMetadata, metadata) if metadata else None
144        blueprints.append(blueprint)
145    return blueprints

Find blueprints and return valid ones

def check_blueprint_v1_file(blueprint: BlueprintFile):
160def check_blueprint_v1_file(blueprint: BlueprintFile):
161    """Check if blueprint should be imported"""
162    instance: BlueprintInstance = BlueprintInstance.objects.filter(path=blueprint.path).first()
163    if (
164        blueprint.meta
165        and blueprint.meta.labels.get(LABEL_AUTHENTIK_INSTANTIATE, "").lower() == "false"
166    ):
167        return
168    if not instance:
169        instance = BlueprintInstance(
170            name=blueprint.meta.name if blueprint.meta else str(blueprint.path),
171            path=blueprint.path,
172            context={},
173            status=BlueprintInstanceStatus.UNKNOWN,
174            enabled=True,
175            managed_models=[],
176            metadata={},
177        )
178        instance.save()
179        LOGGER.info(
180            "Creating new blueprint instance from file", instance=instance, path=instance.path
181        )
182    if instance.last_applied_hash != blueprint.hash:
183        LOGGER.info("Applying blueprint due to changed file", instance=instance, path=instance.path)
184        apply_blueprint.send_with_options(args=(instance.pk,), rel_obj=instance)

Check if blueprint should be imported