authentik.blueprints.v1.importer

Blueprint importer

  1"""Blueprint importer"""
  2
  3from contextlib import contextmanager
  4from copy import deepcopy
  5from typing import Any
  6
  7from dacite.config import Config
  8from dacite.core import from_dict
  9from dacite.exceptions import DaciteError
 10from deepmerge import always_merger
 11from django.contrib.auth.models import Permission
 12from django.contrib.contenttypes.models import ContentType
 13from django.core.exceptions import FieldError
 14from django.db.models import Model
 15from django.db.models.query_utils import Q
 16from django.db.transaction import atomic
 17from django.db.utils import IntegrityError
 18from guardian.models import RoleObjectPermission
 19from rest_framework.exceptions import ValidationError
 20from rest_framework.serializers import BaseSerializer, Serializer
 21from structlog.stdlib import BoundLogger, get_logger
 22from yaml import load
 23from yaml.error import YAMLError
 24
 25from authentik.blueprints.v1.common import (
 26    Blueprint,
 27    BlueprintEntry,
 28    BlueprintEntryDesiredState,
 29    BlueprintEntryState,
 30    BlueprintLoader,
 31    EntryInvalidError,
 32)
 33from authentik.blueprints.v1.meta.registry import BaseMetaModel, registry
 34from authentik.core.models import (
 35    AuthenticatedSession,
 36    GroupSourceConnection,
 37    PropertyMapping,
 38    Provider,
 39    Session,
 40    Source,
 41    User,
 42    UserSourceConnection,
 43)
 44from authentik.endpoints.models import Connector
 45from authentik.events.logs import LogEvent, capture_logs
 46from authentik.events.utils import cleanse_dict
 47from authentik.flows.models import Stage
 48from authentik.lib.models import InternallyManagedMixin, SerializerModel
 49from authentik.lib.tracing.exceptions import TracingIgnoredException
 50from authentik.lib.utils.reflection import get_apps
 51from authentik.outposts.models import OutpostServiceConnection
 52from authentik.policies.models import Policy, PolicyBindingModel
 53from authentik.rbac.models import Role
 54
 55# Context set when the serializer is created in a blueprint context
 56# Update website/docs/customize/blueprints/v1/models.mdx when used
 57SERIALIZER_CONTEXT_BLUEPRINT = "blueprint_entry"
 58
 59
 60def excluded_models() -> list[type[Model]]:
 61    """Return a list of all excluded models that shouldn't be exposed via API
 62    or other means (internal only, base classes, non-used objects, etc)"""
 63
 64    from django.contrib.auth.models import Group as DjangoGroup
 65    from django.contrib.auth.models import User as DjangoUser
 66
 67    return (
 68        # Django only classes
 69        DjangoUser,
 70        DjangoGroup,
 71        ContentType,
 72        Permission,
 73        RoleObjectPermission,
 74        # Base classes
 75        Provider,
 76        Source,
 77        PropertyMapping,
 78        UserSourceConnection,
 79        GroupSourceConnection,
 80        Stage,
 81        OutpostServiceConnection,
 82        Policy,
 83        PolicyBindingModel,
 84        Connector,
 85        # Classes that have other dependencies
 86        Session,
 87        AuthenticatedSession,
 88    )
 89
 90
 91def is_model_allowed(model: type[Model]) -> bool:
 92    """Check if model is allowed"""
 93    return (
 94        model not in excluded_models()
 95        and issubclass(model, SerializerModel | BaseMetaModel)
 96        and not issubclass(model, InternallyManagedMixin)
 97    )
 98
 99
100class DoRollback(TracingIgnoredException):
101    """Exception to trigger a rollback"""
102
103
104@contextmanager
105def transaction_rollback():
106    """Enters an atomic transaction and always triggers a rollback at the end of the block."""
107    try:
108        with atomic():
109            yield
110            raise DoRollback()
111    except DoRollback:
112        pass
113
114
115def rbac_models() -> dict:
116    models = {}
117    for app in get_apps():
118        for model in app.get_models():
119            if not is_model_allowed(model):
120                continue
121            models[model._meta.model_name] = app.label
122    return models
123
124
125class Importer:
126    """Import Blueprint from raw dict or YAML/JSON"""
127
128    logger: BoundLogger
129    _import: Blueprint
130
131    def __init__(self, blueprint: Blueprint, context: dict | None = None):
132        self.__pk_map: dict[Any, Model] = {}
133        self._import = blueprint
134        self.logger = get_logger()
135        ctx = self.default_context()
136        always_merger.merge(ctx, self._import.context)
137        if context:
138            always_merger.merge(ctx, context)
139        self._import.context = ctx
140
141    def default_context(self):
142        """Default context"""
143        context = {
144            "goauthentik.io/rbac/models": rbac_models(),
145            "goauthentik.io/enterprise/licensed": False,
146        }
147        try:
148            from authentik.enterprise.license import LicenseKey
149
150            context["goauthentik.io/enterprise/licensed"] = LicenseKey.get_total().status().is_valid
151        except ModuleNotFoundError:
152            pass
153        return context
154
155    @staticmethod
156    def from_string(yaml_input: str, context: dict | None = None) -> Importer:
157        """Parse YAML string and create blueprint importer from it"""
158        try:
159            import_dict = load(yaml_input, BlueprintLoader)
160        except YAMLError as exc:
161            raise EntryInvalidError(exc) from exc
162        try:
163            _import = from_dict(
164                Blueprint, import_dict, config=Config(cast=[BlueprintEntryDesiredState])
165            )
166        except DaciteError as exc:
167            raise EntryInvalidError(exc) from exc
168        return Importer(_import, context)
169
170    @property
171    def blueprint(self) -> Blueprint:
172        """Get imported blueprint"""
173        return self._import
174
175    def __update_pks_for_attrs(self, attrs: dict[str, Any]) -> dict[str, Any]:
176        """Replace any value if it is a known primary key of an other object"""
177
178        def updater(value) -> Any:
179            if value in self.__pk_map:
180                self.logger.debug("Updating reference in entry", value=value)
181                return self.__pk_map[value]
182            return value
183
184        for key, value in attrs.items():
185            try:
186                if isinstance(value, dict):
187                    for _, _inner_key in enumerate(value):
188                        value[_inner_key] = updater(value[_inner_key])
189                elif isinstance(value, list):
190                    for idx, _inner_value in enumerate(value):
191                        attrs[key][idx] = updater(_inner_value)
192                else:
193                    attrs[key] = updater(value)
194            except TypeError:
195                continue
196        return attrs
197
198    def __query_from_identifier(self, attrs: dict[str, Any]) -> Q:
199        """Generate an or'd query from all identifiers in an entry"""
200        # Since identifiers can also be pk-references to other objects (see FlowStageBinding)
201        # we have to ensure those references are also replaced
202        main_query = Q()
203        if "pk" in attrs:
204            main_query = Q(pk=attrs["pk"])
205        sub_query = Q()
206        for identifier, value in attrs.items():
207            if identifier == "pk":
208                continue
209            if isinstance(value, dict):
210                sub_query &= Q(**{f"{identifier}__contains": value})
211            else:
212                sub_query &= Q(**{identifier: value})
213
214        return main_query | sub_query
215
216    def _validate_single(self, entry: BlueprintEntry) -> BaseSerializer | None:  # noqa: PLR0915
217        """Validate a single entry"""
218        if not entry.check_all_conditions_match(self._import):
219            self.logger.debug("One or more conditions of this entry are not fulfilled, skipping")
220            return None
221
222        model_app_label, model_name = entry.get_model(self._import).split(".")
223        try:
224            model: type[SerializerModel] = registry.get_model(model_app_label, model_name)
225        except LookupError as exc:
226            raise EntryInvalidError.from_entry(exc, entry) from exc
227        # Don't use isinstance since we don't want to check for inheritance
228        if not is_model_allowed(model):
229            raise EntryInvalidError.from_entry(f"Model {model} not allowed", entry)
230        if issubclass(model, BaseMetaModel):
231            serializer_class: type[Serializer] = model.serializer()
232            serializer = serializer_class(
233                data=entry.get_attrs(self._import),
234                context={
235                    SERIALIZER_CONTEXT_BLUEPRINT: entry,
236                },
237            )
238            try:
239                serializer.is_valid(raise_exception=True)
240            except ValidationError as exc:
241                raise EntryInvalidError.from_entry(
242                    f"Serializer errors {serializer.errors}",
243                    validation_error=exc,
244                    entry=entry,
245                ) from exc
246            return serializer
247
248        # If we try to validate without referencing a possible instance
249        # we'll get a duplicate error, hence we load the model here and return
250        # the full serializer for later usage
251        # Because a model might have multiple unique columns, we chain all identifiers together
252        # to create an OR query.
253        updated_identifiers = self.__update_pks_for_attrs(entry.get_identifiers(self._import))
254        for key, value in list(updated_identifiers.items()):
255            if isinstance(value, dict) and "pk" in value:
256                del updated_identifiers[key]
257                updated_identifiers[f"{key}"] = value["pk"]
258
259        query = self.__query_from_identifier(updated_identifiers)
260        if not query:
261            raise EntryInvalidError.from_entry("No or invalid identifiers", entry)
262
263        try:
264            existing_models = model.objects.filter(query)
265        except FieldError as exc:
266            raise EntryInvalidError.from_entry(f"Invalid identifier field: {exc}", entry) from exc
267
268        serializer_kwargs = {}
269        model_instance = existing_models.first()
270        override_serializer_instance = False
271        if (
272            not isinstance(model(), BaseMetaModel)
273            and model_instance
274            and entry.state != BlueprintEntryDesiredState.MUST_CREATED
275        ):
276            self.logger.debug(
277                "Initialize serializer with instance",
278                model=model,
279                instance=model_instance,
280                pk=model_instance.pk,
281            )
282            serializer_kwargs["instance"] = model_instance
283            serializer_kwargs["partial"] = True
284        elif model_instance and entry.state == BlueprintEntryDesiredState.MUST_CREATED:
285            msg = (
286                f"State is set to {BlueprintEntryDesiredState.MUST_CREATED.value} "
287                "and object exists already",
288            )
289            raise EntryInvalidError.from_entry(
290                ValidationError({k: msg for k in entry.identifiers.keys()}, "unique"),
291                entry,
292            )
293        else:
294            self.logger.debug(
295                "Initialized new serializer instance",
296                model=model,
297                **cleanse_dict(updated_identifiers),
298            )
299            override_serializer_instance = True
300        try:
301            full_data = self.__update_pks_for_attrs(entry.get_attrs(self._import))
302        except ValueError as exc:
303            raise EntryInvalidError.from_entry(exc, entry) from exc
304        always_merger.merge(full_data, updated_identifiers)
305        serializer_kwargs["data"] = full_data
306
307        serializer: Serializer = model().serializer(
308            context={
309                SERIALIZER_CONTEXT_BLUEPRINT: entry,
310            },
311            **serializer_kwargs,
312        )
313        try:
314            serializer.is_valid(raise_exception=True)
315        except ValidationError as exc:
316            raise EntryInvalidError.from_entry(
317                f"Serializer errors {serializer.errors}",
318                validation_error=exc,
319                entry=entry,
320                serializer=serializer,
321            ) from exc
322        if override_serializer_instance:
323            model_instance = model()
324            # pk needs to be set on the model instance otherwise a new one will be generated
325            if "pk" in updated_identifiers:
326                model_instance.pk = model._meta.pk.to_python(updated_identifiers["pk"])
327            serializer.instance = model_instance
328        return serializer
329
330    def _save_with_retry(
331        self, serializer: BaseSerializer, entry: BlueprintEntry, raise_errors: bool
332    ) -> Model | None:
333        """Save a serializer, retrying once on IntegrityError by re-fetching the existing instance.
334
335        Returns the saved instance, or None when recovery failed and raise_errors is False.
336        Raises EntryInvalidError / IntegrityError when raise_errors is True and recovery
337        is not possible.
338        """
339        try:
340            with atomic():
341                return serializer.save()
342        except IntegrityError:
343            self.logger.debug(
344                "Integrity error during save, retrying after re-fetching instance",
345                entry=entry,
346            )
347            # Race condition: another process committed the same object between our
348            # SELECT and INSERT. Re-validate so we pick up the now-existing instance.
349            try:
350                retry_serializer = self._validate_single(entry)
351            except EntryInvalidError as exc:
352                self.logger.warning(f"Entry invalid on retry: {exc}", entry=entry, error=exc)
353                if raise_errors:
354                    raise exc
355                return None
356            if not retry_serializer:
357                return None
358            try:
359                return retry_serializer.save()
360            except IntegrityError:
361                self.logger.warning("Integrity error persists on retry", entry=entry)
362                if raise_errors:
363                    raise
364                return None
365
366    def _apply_permissions(self, instance: Model, entry: BlueprintEntry):
367        """Apply object-level permissions for an entry"""
368        for perm in entry.get_permissions(self._import):
369            if perm.user is not None:
370                User.objects.get(pk=perm.user).assign_perms_to_managed_role(
371                    perm.permission, instance
372                )
373            if perm.role is not None:
374                role = Role.objects.get(pk=perm.role)
375                role.assign_perms(perm.permission, obj=instance)
376
377    def apply(self) -> bool:
378        """Apply (create/update) models yaml, in database transaction"""
379        try:
380            with atomic():
381                if not self._apply_models():
382                    self.logger.debug("Reverting changes due to error")
383                    raise IntegrityError
384        except IntegrityError:
385            return False
386        self.logger.debug("Committing changes")
387        return True
388
389    def _apply_models(self, raise_errors=False) -> bool:
390        """Apply (create/update) models yaml"""
391        self.__pk_map = {}
392        for entry in self._import.iter_entries():
393            model_app_label, model_name = entry.get_model(self._import).split(".")
394            try:
395                model: type[SerializerModel] = registry.get_model(model_app_label, model_name)
396            except LookupError:
397                self.logger.warning(
398                    "App or Model does not exist", app=model_app_label, model=model_name
399                )
400                return False
401            # Validate each single entry
402            serializer = None
403            try:
404                serializer = self._validate_single(entry)
405            except EntryInvalidError as exc:
406                # For deleting objects we don't need the serializer to be valid
407                if entry.get_state(self._import) == BlueprintEntryDesiredState.ABSENT:
408                    serializer = exc.serializer
409                else:
410                    self.logger.warning(f"Entry invalid: {exc}", entry=entry, error=exc)
411                    if raise_errors:
412                        raise exc
413                    return False
414            if not serializer:
415                continue
416
417            state = entry.get_state(self._import)
418            if state in [
419                BlueprintEntryDesiredState.PRESENT,
420                BlueprintEntryDesiredState.CREATED,
421                BlueprintEntryDesiredState.MUST_CREATED,
422            ]:
423                instance = serializer.instance
424                if (
425                    instance
426                    and not instance._state.adding
427                    and state == BlueprintEntryDesiredState.CREATED
428                ):
429                    self.logger.debug(
430                        "Instance exists, skipping",
431                        model=model,
432                        instance=instance,
433                        pk=instance.pk,
434                    )
435                else:
436                    instance = self._save_with_retry(serializer, entry, raise_errors)
437                    if instance is None:
438                        return False
439                    self.logger.debug("Updated model", model=instance)
440                if "pk" in entry.identifiers:
441                    self.__pk_map[entry.identifiers["pk"]] = instance.pk
442                entry._state = BlueprintEntryState(instance)
443                self._apply_permissions(instance, entry)
444            elif state == BlueprintEntryDesiredState.ABSENT:
445                instance: Model | None = serializer.instance
446                if instance and instance.pk:
447                    instance.delete()
448                    self.logger.debug("Deleted model", mode=instance)
449                    continue
450                self.logger.debug("Entry to delete with no instance, skipping")
451        return True
452
453    def validate(self, raise_validation_errors=False) -> tuple[bool, list[LogEvent]]:
454        """Validate loaded blueprint export, ensure all models are allowed
455        and serializers have no errors"""
456        self.logger.debug("Starting blueprint import validation")
457        orig_import = deepcopy(self._import)
458        if self._import.version != 1:
459            self.logger.warning("Invalid blueprint version")
460            return False, [LogEvent("Invalid blueprint version", log_level="warning", logger=None)]
461        with (
462            transaction_rollback(),
463            capture_logs() as logs,
464        ):
465            successful = self._apply_models(raise_errors=raise_validation_errors)
466            if not successful:
467                self.logger.warning("Blueprint validation failed")
468        self.logger.debug("Finished blueprint import validation")
469        self._import = orig_import
470        return successful, logs
SERIALIZER_CONTEXT_BLUEPRINT = 'blueprint_entry'
def excluded_models() -> list[type[django.db.models.base.Model]]:
61def excluded_models() -> list[type[Model]]:
62    """Return a list of all excluded models that shouldn't be exposed via API
63    or other means (internal only, base classes, non-used objects, etc)"""
64
65    from django.contrib.auth.models import Group as DjangoGroup
66    from django.contrib.auth.models import User as DjangoUser
67
68    return (
69        # Django only classes
70        DjangoUser,
71        DjangoGroup,
72        ContentType,
73        Permission,
74        RoleObjectPermission,
75        # Base classes
76        Provider,
77        Source,
78        PropertyMapping,
79        UserSourceConnection,
80        GroupSourceConnection,
81        Stage,
82        OutpostServiceConnection,
83        Policy,
84        PolicyBindingModel,
85        Connector,
86        # Classes that have other dependencies
87        Session,
88        AuthenticatedSession,
89    )

Return a list of all excluded models that shouldn't be exposed via API or other means (internal only, base classes, non-used objects, etc)

def is_model_allowed(model: type[django.db.models.base.Model]) -> bool:
92def is_model_allowed(model: type[Model]) -> bool:
93    """Check if model is allowed"""
94    return (
95        model not in excluded_models()
96        and issubclass(model, SerializerModel | BaseMetaModel)
97        and not issubclass(model, InternallyManagedMixin)
98    )

Check if model is allowed

101class DoRollback(TracingIgnoredException):
102    """Exception to trigger a rollback"""

Exception to trigger a rollback

@contextmanager
def transaction_rollback():
105@contextmanager
106def transaction_rollback():
107    """Enters an atomic transaction and always triggers a rollback at the end of the block."""
108    try:
109        with atomic():
110            yield
111            raise DoRollback()
112    except DoRollback:
113        pass

Enters an atomic transaction and always triggers a rollback at the end of the block.

def rbac_models() -> dict:
116def rbac_models() -> dict:
117    models = {}
118    for app in get_apps():
119        for model in app.get_models():
120            if not is_model_allowed(model):
121                continue
122            models[model._meta.model_name] = app.label
123    return models
class Importer:
126class Importer:
127    """Import Blueprint from raw dict or YAML/JSON"""
128
129    logger: BoundLogger
130    _import: Blueprint
131
132    def __init__(self, blueprint: Blueprint, context: dict | None = None):
133        self.__pk_map: dict[Any, Model] = {}
134        self._import = blueprint
135        self.logger = get_logger()
136        ctx = self.default_context()
137        always_merger.merge(ctx, self._import.context)
138        if context:
139            always_merger.merge(ctx, context)
140        self._import.context = ctx
141
142    def default_context(self):
143        """Default context"""
144        context = {
145            "goauthentik.io/rbac/models": rbac_models(),
146            "goauthentik.io/enterprise/licensed": False,
147        }
148        try:
149            from authentik.enterprise.license import LicenseKey
150
151            context["goauthentik.io/enterprise/licensed"] = LicenseKey.get_total().status().is_valid
152        except ModuleNotFoundError:
153            pass
154        return context
155
156    @staticmethod
157    def from_string(yaml_input: str, context: dict | None = None) -> Importer:
158        """Parse YAML string and create blueprint importer from it"""
159        try:
160            import_dict = load(yaml_input, BlueprintLoader)
161        except YAMLError as exc:
162            raise EntryInvalidError(exc) from exc
163        try:
164            _import = from_dict(
165                Blueprint, import_dict, config=Config(cast=[BlueprintEntryDesiredState])
166            )
167        except DaciteError as exc:
168            raise EntryInvalidError(exc) from exc
169        return Importer(_import, context)
170
171    @property
172    def blueprint(self) -> Blueprint:
173        """Get imported blueprint"""
174        return self._import
175
176    def __update_pks_for_attrs(self, attrs: dict[str, Any]) -> dict[str, Any]:
177        """Replace any value if it is a known primary key of an other object"""
178
179        def updater(value) -> Any:
180            if value in self.__pk_map:
181                self.logger.debug("Updating reference in entry", value=value)
182                return self.__pk_map[value]
183            return value
184
185        for key, value in attrs.items():
186            try:
187                if isinstance(value, dict):
188                    for _, _inner_key in enumerate(value):
189                        value[_inner_key] = updater(value[_inner_key])
190                elif isinstance(value, list):
191                    for idx, _inner_value in enumerate(value):
192                        attrs[key][idx] = updater(_inner_value)
193                else:
194                    attrs[key] = updater(value)
195            except TypeError:
196                continue
197        return attrs
198
199    def __query_from_identifier(self, attrs: dict[str, Any]) -> Q:
200        """Generate an or'd query from all identifiers in an entry"""
201        # Since identifiers can also be pk-references to other objects (see FlowStageBinding)
202        # we have to ensure those references are also replaced
203        main_query = Q()
204        if "pk" in attrs:
205            main_query = Q(pk=attrs["pk"])
206        sub_query = Q()
207        for identifier, value in attrs.items():
208            if identifier == "pk":
209                continue
210            if isinstance(value, dict):
211                sub_query &= Q(**{f"{identifier}__contains": value})
212            else:
213                sub_query &= Q(**{identifier: value})
214
215        return main_query | sub_query
216
217    def _validate_single(self, entry: BlueprintEntry) -> BaseSerializer | None:  # noqa: PLR0915
218        """Validate a single entry"""
219        if not entry.check_all_conditions_match(self._import):
220            self.logger.debug("One or more conditions of this entry are not fulfilled, skipping")
221            return None
222
223        model_app_label, model_name = entry.get_model(self._import).split(".")
224        try:
225            model: type[SerializerModel] = registry.get_model(model_app_label, model_name)
226        except LookupError as exc:
227            raise EntryInvalidError.from_entry(exc, entry) from exc
228        # Don't use isinstance since we don't want to check for inheritance
229        if not is_model_allowed(model):
230            raise EntryInvalidError.from_entry(f"Model {model} not allowed", entry)
231        if issubclass(model, BaseMetaModel):
232            serializer_class: type[Serializer] = model.serializer()
233            serializer = serializer_class(
234                data=entry.get_attrs(self._import),
235                context={
236                    SERIALIZER_CONTEXT_BLUEPRINT: entry,
237                },
238            )
239            try:
240                serializer.is_valid(raise_exception=True)
241            except ValidationError as exc:
242                raise EntryInvalidError.from_entry(
243                    f"Serializer errors {serializer.errors}",
244                    validation_error=exc,
245                    entry=entry,
246                ) from exc
247            return serializer
248
249        # If we try to validate without referencing a possible instance
250        # we'll get a duplicate error, hence we load the model here and return
251        # the full serializer for later usage
252        # Because a model might have multiple unique columns, we chain all identifiers together
253        # to create an OR query.
254        updated_identifiers = self.__update_pks_for_attrs(entry.get_identifiers(self._import))
255        for key, value in list(updated_identifiers.items()):
256            if isinstance(value, dict) and "pk" in value:
257                del updated_identifiers[key]
258                updated_identifiers[f"{key}"] = value["pk"]
259
260        query = self.__query_from_identifier(updated_identifiers)
261        if not query:
262            raise EntryInvalidError.from_entry("No or invalid identifiers", entry)
263
264        try:
265            existing_models = model.objects.filter(query)
266        except FieldError as exc:
267            raise EntryInvalidError.from_entry(f"Invalid identifier field: {exc}", entry) from exc
268
269        serializer_kwargs = {}
270        model_instance = existing_models.first()
271        override_serializer_instance = False
272        if (
273            not isinstance(model(), BaseMetaModel)
274            and model_instance
275            and entry.state != BlueprintEntryDesiredState.MUST_CREATED
276        ):
277            self.logger.debug(
278                "Initialize serializer with instance",
279                model=model,
280                instance=model_instance,
281                pk=model_instance.pk,
282            )
283            serializer_kwargs["instance"] = model_instance
284            serializer_kwargs["partial"] = True
285        elif model_instance and entry.state == BlueprintEntryDesiredState.MUST_CREATED:
286            msg = (
287                f"State is set to {BlueprintEntryDesiredState.MUST_CREATED.value} "
288                "and object exists already",
289            )
290            raise EntryInvalidError.from_entry(
291                ValidationError({k: msg for k in entry.identifiers.keys()}, "unique"),
292                entry,
293            )
294        else:
295            self.logger.debug(
296                "Initialized new serializer instance",
297                model=model,
298                **cleanse_dict(updated_identifiers),
299            )
300            override_serializer_instance = True
301        try:
302            full_data = self.__update_pks_for_attrs(entry.get_attrs(self._import))
303        except ValueError as exc:
304            raise EntryInvalidError.from_entry(exc, entry) from exc
305        always_merger.merge(full_data, updated_identifiers)
306        serializer_kwargs["data"] = full_data
307
308        serializer: Serializer = model().serializer(
309            context={
310                SERIALIZER_CONTEXT_BLUEPRINT: entry,
311            },
312            **serializer_kwargs,
313        )
314        try:
315            serializer.is_valid(raise_exception=True)
316        except ValidationError as exc:
317            raise EntryInvalidError.from_entry(
318                f"Serializer errors {serializer.errors}",
319                validation_error=exc,
320                entry=entry,
321                serializer=serializer,
322            ) from exc
323        if override_serializer_instance:
324            model_instance = model()
325            # pk needs to be set on the model instance otherwise a new one will be generated
326            if "pk" in updated_identifiers:
327                model_instance.pk = model._meta.pk.to_python(updated_identifiers["pk"])
328            serializer.instance = model_instance
329        return serializer
330
331    def _save_with_retry(
332        self, serializer: BaseSerializer, entry: BlueprintEntry, raise_errors: bool
333    ) -> Model | None:
334        """Save a serializer, retrying once on IntegrityError by re-fetching the existing instance.
335
336        Returns the saved instance, or None when recovery failed and raise_errors is False.
337        Raises EntryInvalidError / IntegrityError when raise_errors is True and recovery
338        is not possible.
339        """
340        try:
341            with atomic():
342                return serializer.save()
343        except IntegrityError:
344            self.logger.debug(
345                "Integrity error during save, retrying after re-fetching instance",
346                entry=entry,
347            )
348            # Race condition: another process committed the same object between our
349            # SELECT and INSERT. Re-validate so we pick up the now-existing instance.
350            try:
351                retry_serializer = self._validate_single(entry)
352            except EntryInvalidError as exc:
353                self.logger.warning(f"Entry invalid on retry: {exc}", entry=entry, error=exc)
354                if raise_errors:
355                    raise exc
356                return None
357            if not retry_serializer:
358                return None
359            try:
360                return retry_serializer.save()
361            except IntegrityError:
362                self.logger.warning("Integrity error persists on retry", entry=entry)
363                if raise_errors:
364                    raise
365                return None
366
367    def _apply_permissions(self, instance: Model, entry: BlueprintEntry):
368        """Apply object-level permissions for an entry"""
369        for perm in entry.get_permissions(self._import):
370            if perm.user is not None:
371                User.objects.get(pk=perm.user).assign_perms_to_managed_role(
372                    perm.permission, instance
373                )
374            if perm.role is not None:
375                role = Role.objects.get(pk=perm.role)
376                role.assign_perms(perm.permission, obj=instance)
377
378    def apply(self) -> bool:
379        """Apply (create/update) models yaml, in database transaction"""
380        try:
381            with atomic():
382                if not self._apply_models():
383                    self.logger.debug("Reverting changes due to error")
384                    raise IntegrityError
385        except IntegrityError:
386            return False
387        self.logger.debug("Committing changes")
388        return True
389
390    def _apply_models(self, raise_errors=False) -> bool:
391        """Apply (create/update) models yaml"""
392        self.__pk_map = {}
393        for entry in self._import.iter_entries():
394            model_app_label, model_name = entry.get_model(self._import).split(".")
395            try:
396                model: type[SerializerModel] = registry.get_model(model_app_label, model_name)
397            except LookupError:
398                self.logger.warning(
399                    "App or Model does not exist", app=model_app_label, model=model_name
400                )
401                return False
402            # Validate each single entry
403            serializer = None
404            try:
405                serializer = self._validate_single(entry)
406            except EntryInvalidError as exc:
407                # For deleting objects we don't need the serializer to be valid
408                if entry.get_state(self._import) == BlueprintEntryDesiredState.ABSENT:
409                    serializer = exc.serializer
410                else:
411                    self.logger.warning(f"Entry invalid: {exc}", entry=entry, error=exc)
412                    if raise_errors:
413                        raise exc
414                    return False
415            if not serializer:
416                continue
417
418            state = entry.get_state(self._import)
419            if state in [
420                BlueprintEntryDesiredState.PRESENT,
421                BlueprintEntryDesiredState.CREATED,
422                BlueprintEntryDesiredState.MUST_CREATED,
423            ]:
424                instance = serializer.instance
425                if (
426                    instance
427                    and not instance._state.adding
428                    and state == BlueprintEntryDesiredState.CREATED
429                ):
430                    self.logger.debug(
431                        "Instance exists, skipping",
432                        model=model,
433                        instance=instance,
434                        pk=instance.pk,
435                    )
436                else:
437                    instance = self._save_with_retry(serializer, entry, raise_errors)
438                    if instance is None:
439                        return False
440                    self.logger.debug("Updated model", model=instance)
441                if "pk" in entry.identifiers:
442                    self.__pk_map[entry.identifiers["pk"]] = instance.pk
443                entry._state = BlueprintEntryState(instance)
444                self._apply_permissions(instance, entry)
445            elif state == BlueprintEntryDesiredState.ABSENT:
446                instance: Model | None = serializer.instance
447                if instance and instance.pk:
448                    instance.delete()
449                    self.logger.debug("Deleted model", mode=instance)
450                    continue
451                self.logger.debug("Entry to delete with no instance, skipping")
452        return True
453
454    def validate(self, raise_validation_errors=False) -> tuple[bool, list[LogEvent]]:
455        """Validate loaded blueprint export, ensure all models are allowed
456        and serializers have no errors"""
457        self.logger.debug("Starting blueprint import validation")
458        orig_import = deepcopy(self._import)
459        if self._import.version != 1:
460            self.logger.warning("Invalid blueprint version")
461            return False, [LogEvent("Invalid blueprint version", log_level="warning", logger=None)]
462        with (
463            transaction_rollback(),
464            capture_logs() as logs,
465        ):
466            successful = self._apply_models(raise_errors=raise_validation_errors)
467            if not successful:
468                self.logger.warning("Blueprint validation failed")
469        self.logger.debug("Finished blueprint import validation")
470        self._import = orig_import
471        return successful, logs

Import Blueprint from raw dict or YAML/JSON

Importer( blueprint: authentik.blueprints.v1.common.Blueprint, context: dict | None = None)
132    def __init__(self, blueprint: Blueprint, context: dict | None = None):
133        self.__pk_map: dict[Any, Model] = {}
134        self._import = blueprint
135        self.logger = get_logger()
136        ctx = self.default_context()
137        always_merger.merge(ctx, self._import.context)
138        if context:
139            always_merger.merge(ctx, context)
140        self._import.context = ctx
logger: structlog.stdlib.BoundLogger
def default_context(self):
142    def default_context(self):
143        """Default context"""
144        context = {
145            "goauthentik.io/rbac/models": rbac_models(),
146            "goauthentik.io/enterprise/licensed": False,
147        }
148        try:
149            from authentik.enterprise.license import LicenseKey
150
151            context["goauthentik.io/enterprise/licensed"] = LicenseKey.get_total().status().is_valid
152        except ModuleNotFoundError:
153            pass
154        return context

Default context

@staticmethod
def from_string( yaml_input: str, context: dict | None = None) -> Importer:
156    @staticmethod
157    def from_string(yaml_input: str, context: dict | None = None) -> Importer:
158        """Parse YAML string and create blueprint importer from it"""
159        try:
160            import_dict = load(yaml_input, BlueprintLoader)
161        except YAMLError as exc:
162            raise EntryInvalidError(exc) from exc
163        try:
164            _import = from_dict(
165                Blueprint, import_dict, config=Config(cast=[BlueprintEntryDesiredState])
166            )
167        except DaciteError as exc:
168            raise EntryInvalidError(exc) from exc
169        return Importer(_import, context)

Parse YAML string and create blueprint importer from it

171    @property
172    def blueprint(self) -> Blueprint:
173        """Get imported blueprint"""
174        return self._import

Get imported blueprint

def apply(self) -> bool:
378    def apply(self) -> bool:
379        """Apply (create/update) models yaml, in database transaction"""
380        try:
381            with atomic():
382                if not self._apply_models():
383                    self.logger.debug("Reverting changes due to error")
384                    raise IntegrityError
385        except IntegrityError:
386            return False
387        self.logger.debug("Committing changes")
388        return True

Apply (create/update) models yaml, in database transaction

def validate( self, raise_validation_errors=False) -> tuple[bool, list[authentik.events.logs.LogEvent]]:
454    def validate(self, raise_validation_errors=False) -> tuple[bool, list[LogEvent]]:
455        """Validate loaded blueprint export, ensure all models are allowed
456        and serializers have no errors"""
457        self.logger.debug("Starting blueprint import validation")
458        orig_import = deepcopy(self._import)
459        if self._import.version != 1:
460            self.logger.warning("Invalid blueprint version")
461            return False, [LogEvent("Invalid blueprint version", log_level="warning", logger=None)]
462        with (
463            transaction_rollback(),
464            capture_logs() as logs,
465        ):
466            successful = self._apply_models(raise_errors=raise_validation_errors)
467            if not successful:
468                self.logger.warning("Blueprint validation failed")
469        self.logger.debug("Finished blueprint import validation")
470        self._import = orig_import
471        return successful, logs

Validate loaded blueprint export, ensure all models are allowed and serializers have no errors