authentik.blueprints.v1.exporter

Blueprint exporter

  1"""Blueprint exporter"""
  2
  3from collections.abc import Iterable
  4from typing import Any
  5from uuid import UUID
  6
  7from django.apps import apps
  8from django.contrib.auth import get_user_model
  9from django.db.models import Model, Q, QuerySet
 10from django.utils.timezone import now
 11from django.utils.translation import gettext as _
 12from yaml import dump
 13
 14from authentik.blueprints.v1.common import (
 15    Blueprint,
 16    BlueprintDumper,
 17    BlueprintEntry,
 18    BlueprintMetadata,
 19    ReferenceIndex,
 20)
 21from authentik.blueprints.v1.importer import is_model_allowed
 22from authentik.blueprints.v1.labels import LABEL_AUTHENTIK_GENERATED
 23from authentik.events.models import Event
 24from authentik.flows.models import Flow, FlowStageBinding, Stage
 25from authentik.policies.models import Policy, PolicyBinding
 26from authentik.stages.prompt.models import Prompt, PromptStage
 27
 28
 29class Exporter:
 30    """Export flow with attached stages into yaml"""
 31
 32    excluded_models: list[type[Model]] = []
 33
 34    def __init__(self):
 35        self.excluded_models = [
 36            Event,
 37        ]
 38
 39    def get_entries(self) -> Iterable[BlueprintEntry]:
 40        """Get blueprint entries"""
 41        reference_index = ReferenceIndex()
 42        instances: list[Model] = []
 43        for model in apps.get_models():
 44            if not is_model_allowed(model):
 45                continue
 46            if model in self.excluded_models:
 47                continue
 48            for obj in self.get_model_instances(model):
 49                instances.append(obj)
 50                reference_index.register(obj)
 51        entries = [
 52            BlueprintEntry.from_model(obj, reference_index=reference_index) for obj in instances
 53        ]
 54        reference_index.clear_unused_ids(entries, instances)
 55        return entries
 56
 57    def get_model_instances(self, model: type[Model]) -> QuerySet:
 58        """Return a queryset for `model`. Can be used to filter some
 59        objects on some models"""
 60        if model == get_user_model():
 61            return model.objects.exclude_anonymous()
 62        return model.objects.all()
 63
 64    def _pre_export(self, blueprint: Blueprint):
 65        """Hook to run anything pre-export"""
 66
 67    def export(self) -> Blueprint:
 68        """Create a list of all objects and create a blueprint"""
 69        blueprint = Blueprint()
 70        self._pre_export(blueprint)
 71        blueprint.metadata = BlueprintMetadata(
 72            name=_("authentik Export - {date}").format(date=str(now())),
 73            labels={
 74                LABEL_AUTHENTIK_GENERATED: "true",
 75            },
 76        )
 77        blueprint.entries = list(self.get_entries())
 78        return blueprint
 79
 80    def export_to_string(self) -> str:
 81        """Call export and convert it to yaml"""
 82        blueprint = self.export()
 83        return dump(blueprint, Dumper=BlueprintDumper)
 84
 85
 86class FlowExporter(Exporter):
 87    """Exporter customized to only return objects related to `flow`"""
 88
 89    flow: Flow
 90    with_policies: bool
 91    with_stage_prompts: bool
 92
 93    pbm_uuids: list[UUID]
 94
 95    def __init__(self, flow: Flow):
 96        super().__init__()
 97        self.flow = flow
 98        self.with_policies = True
 99        self.with_stage_prompts = True
100
101    def _pre_export(self, blueprint: Blueprint):
102        if not self.with_policies:
103            return
104        self.pbm_uuids = [self.flow.pbm_uuid]
105        self.pbm_uuids += FlowStageBinding.objects.filter(target=self.flow).values_list(
106            "pbm_uuid", flat=True
107        )
108
109    def _stages(self) -> Iterable[Stage]:
110        """Get all stages attached to self.flow"""
111        return Stage.objects.filter(flow=self.flow).select_related().select_subclasses()
112
113    def _stage_bindings(self) -> Iterable[FlowStageBinding]:
114        """Get all bindings attached to self.flow"""
115        return FlowStageBinding.objects.filter(target=self.flow).select_related()
116
117    def _policies(self) -> Iterable[Policy]:
118        """Get all policies. This is done at the beginning of the export for stages that have
119        a direct foreign key to a policy."""
120        # Special case for PromptStage as that has a direct M2M to policy, we have to ensure
121        # all policies referenced in there we also include here
122        prompt_stages = PromptStage.objects.filter(flow=self.flow).values_list("pk", flat=True)
123        query = Q(bindings__in=self.pbm_uuids) | Q(promptstage__in=prompt_stages)
124        return Policy.objects.filter(query).select_related()
125
126    def _policy_bindings(self) -> Iterable[PolicyBinding]:
127        """Get all policybindings relative to us. This is run at the end of the export, as
128        we are sure all objects exist now."""
129        return PolicyBinding.objects.filter(target__in=self.pbm_uuids).select_related()
130
131    def _stage_prompts(self) -> Iterable[Prompt]:
132        """Get all prompts associated with any PromptStages, deduplicated as multiple stages
133        may share the same prompt"""
134        prompt_stages = PromptStage.objects.filter(flow=self.flow)
135        prompts: dict[Any, Prompt] = {}
136        for stage in prompt_stages:
137            for prompt in stage.fields.all():
138                prompts[prompt.pk] = prompt
139        return prompts.values()
140
141    def get_entries(self) -> Iterable[BlueprintEntry]:
142        reference_index = ReferenceIndex()
143        reference_index.register(self.flow)
144
145        prompts = list(self._stage_prompts()) if self.with_stage_prompts else []
146        policies = list(self._policies()) if self.with_policies else []
147        stages = list(self._stages())
148        stage_bindings = list(self._stage_bindings())
149        policy_bindings = list(self._policy_bindings()) if self.with_policies else []
150
151        for obj in (*prompts, *policies, *stages, *stage_bindings, *policy_bindings):
152            reference_index.register(obj)
153
154        objects = [self.flow, *prompts, *policies, *stages, *stage_bindings, *policy_bindings]
155        entries = [
156            BlueprintEntry.from_model(self.flow, reference_index=reference_index),
157            *(
158                BlueprintEntry.from_model(prompt, reference_index=reference_index)
159                for prompt in prompts
160            ),
161            *(
162                BlueprintEntry.from_model(policy, reference_index=reference_index)
163                for policy in policies
164            ),
165            *(
166                BlueprintEntry.from_model(stage, reference_index=reference_index)
167                for stage in stages
168            ),
169            *(
170                BlueprintEntry.from_model(binding, reference_index=reference_index)
171                for binding in stage_bindings
172            ),
173            *(
174                BlueprintEntry.from_model(binding, reference_index=reference_index)
175                for binding in policy_bindings
176            ),
177        ]
178        reference_index.clear_unused_ids(entries, objects)
179        return entries
class Exporter:
30class Exporter:
31    """Export flow with attached stages into yaml"""
32
33    excluded_models: list[type[Model]] = []
34
35    def __init__(self):
36        self.excluded_models = [
37            Event,
38        ]
39
40    def get_entries(self) -> Iterable[BlueprintEntry]:
41        """Get blueprint entries"""
42        reference_index = ReferenceIndex()
43        instances: list[Model] = []
44        for model in apps.get_models():
45            if not is_model_allowed(model):
46                continue
47            if model in self.excluded_models:
48                continue
49            for obj in self.get_model_instances(model):
50                instances.append(obj)
51                reference_index.register(obj)
52        entries = [
53            BlueprintEntry.from_model(obj, reference_index=reference_index) for obj in instances
54        ]
55        reference_index.clear_unused_ids(entries, instances)
56        return entries
57
58    def get_model_instances(self, model: type[Model]) -> QuerySet:
59        """Return a queryset for `model`. Can be used to filter some
60        objects on some models"""
61        if model == get_user_model():
62            return model.objects.exclude_anonymous()
63        return model.objects.all()
64
65    def _pre_export(self, blueprint: Blueprint):
66        """Hook to run anything pre-export"""
67
68    def export(self) -> Blueprint:
69        """Create a list of all objects and create a blueprint"""
70        blueprint = Blueprint()
71        self._pre_export(blueprint)
72        blueprint.metadata = BlueprintMetadata(
73            name=_("authentik Export - {date}").format(date=str(now())),
74            labels={
75                LABEL_AUTHENTIK_GENERATED: "true",
76            },
77        )
78        blueprint.entries = list(self.get_entries())
79        return blueprint
80
81    def export_to_string(self) -> str:
82        """Call export and convert it to yaml"""
83        blueprint = self.export()
84        return dump(blueprint, Dumper=BlueprintDumper)

Export flow with attached stages into yaml

excluded_models: list[type[django.db.models.base.Model]] = []
def get_entries(self) -> Iterable[authentik.blueprints.v1.common.BlueprintEntry]:
40    def get_entries(self) -> Iterable[BlueprintEntry]:
41        """Get blueprint entries"""
42        reference_index = ReferenceIndex()
43        instances: list[Model] = []
44        for model in apps.get_models():
45            if not is_model_allowed(model):
46                continue
47            if model in self.excluded_models:
48                continue
49            for obj in self.get_model_instances(model):
50                instances.append(obj)
51                reference_index.register(obj)
52        entries = [
53            BlueprintEntry.from_model(obj, reference_index=reference_index) for obj in instances
54        ]
55        reference_index.clear_unused_ids(entries, instances)
56        return entries

Get blueprint entries

def get_model_instances( self, model: type[django.db.models.base.Model]) -> django.db.models.query.QuerySet:
58    def get_model_instances(self, model: type[Model]) -> QuerySet:
59        """Return a queryset for `model`. Can be used to filter some
60        objects on some models"""
61        if model == get_user_model():
62            return model.objects.exclude_anonymous()
63        return model.objects.all()

Return a queryset for model. Can be used to filter some objects on some models

def export(self) -> authentik.blueprints.v1.common.Blueprint:
68    def export(self) -> Blueprint:
69        """Create a list of all objects and create a blueprint"""
70        blueprint = Blueprint()
71        self._pre_export(blueprint)
72        blueprint.metadata = BlueprintMetadata(
73            name=_("authentik Export - {date}").format(date=str(now())),
74            labels={
75                LABEL_AUTHENTIK_GENERATED: "true",
76            },
77        )
78        blueprint.entries = list(self.get_entries())
79        return blueprint

Create a list of all objects and create a blueprint

def export_to_string(self) -> str:
81    def export_to_string(self) -> str:
82        """Call export and convert it to yaml"""
83        blueprint = self.export()
84        return dump(blueprint, Dumper=BlueprintDumper)

Call export and convert it to yaml

class FlowExporter(Exporter):
 87class FlowExporter(Exporter):
 88    """Exporter customized to only return objects related to `flow`"""
 89
 90    flow: Flow
 91    with_policies: bool
 92    with_stage_prompts: bool
 93
 94    pbm_uuids: list[UUID]
 95
 96    def __init__(self, flow: Flow):
 97        super().__init__()
 98        self.flow = flow
 99        self.with_policies = True
100        self.with_stage_prompts = True
101
102    def _pre_export(self, blueprint: Blueprint):
103        if not self.with_policies:
104            return
105        self.pbm_uuids = [self.flow.pbm_uuid]
106        self.pbm_uuids += FlowStageBinding.objects.filter(target=self.flow).values_list(
107            "pbm_uuid", flat=True
108        )
109
110    def _stages(self) -> Iterable[Stage]:
111        """Get all stages attached to self.flow"""
112        return Stage.objects.filter(flow=self.flow).select_related().select_subclasses()
113
114    def _stage_bindings(self) -> Iterable[FlowStageBinding]:
115        """Get all bindings attached to self.flow"""
116        return FlowStageBinding.objects.filter(target=self.flow).select_related()
117
118    def _policies(self) -> Iterable[Policy]:
119        """Get all policies. This is done at the beginning of the export for stages that have
120        a direct foreign key to a policy."""
121        # Special case for PromptStage as that has a direct M2M to policy, we have to ensure
122        # all policies referenced in there we also include here
123        prompt_stages = PromptStage.objects.filter(flow=self.flow).values_list("pk", flat=True)
124        query = Q(bindings__in=self.pbm_uuids) | Q(promptstage__in=prompt_stages)
125        return Policy.objects.filter(query).select_related()
126
127    def _policy_bindings(self) -> Iterable[PolicyBinding]:
128        """Get all policybindings relative to us. This is run at the end of the export, as
129        we are sure all objects exist now."""
130        return PolicyBinding.objects.filter(target__in=self.pbm_uuids).select_related()
131
132    def _stage_prompts(self) -> Iterable[Prompt]:
133        """Get all prompts associated with any PromptStages, deduplicated as multiple stages
134        may share the same prompt"""
135        prompt_stages = PromptStage.objects.filter(flow=self.flow)
136        prompts: dict[Any, Prompt] = {}
137        for stage in prompt_stages:
138            for prompt in stage.fields.all():
139                prompts[prompt.pk] = prompt
140        return prompts.values()
141
142    def get_entries(self) -> Iterable[BlueprintEntry]:
143        reference_index = ReferenceIndex()
144        reference_index.register(self.flow)
145
146        prompts = list(self._stage_prompts()) if self.with_stage_prompts else []
147        policies = list(self._policies()) if self.with_policies else []
148        stages = list(self._stages())
149        stage_bindings = list(self._stage_bindings())
150        policy_bindings = list(self._policy_bindings()) if self.with_policies else []
151
152        for obj in (*prompts, *policies, *stages, *stage_bindings, *policy_bindings):
153            reference_index.register(obj)
154
155        objects = [self.flow, *prompts, *policies, *stages, *stage_bindings, *policy_bindings]
156        entries = [
157            BlueprintEntry.from_model(self.flow, reference_index=reference_index),
158            *(
159                BlueprintEntry.from_model(prompt, reference_index=reference_index)
160                for prompt in prompts
161            ),
162            *(
163                BlueprintEntry.from_model(policy, reference_index=reference_index)
164                for policy in policies
165            ),
166            *(
167                BlueprintEntry.from_model(stage, reference_index=reference_index)
168                for stage in stages
169            ),
170            *(
171                BlueprintEntry.from_model(binding, reference_index=reference_index)
172                for binding in stage_bindings
173            ),
174            *(
175                BlueprintEntry.from_model(binding, reference_index=reference_index)
176                for binding in policy_bindings
177            ),
178        ]
179        reference_index.clear_unused_ids(entries, objects)
180        return entries

Exporter customized to only return objects related to flow

FlowExporter(flow: authentik.flows.models.Flow)
 96    def __init__(self, flow: Flow):
 97        super().__init__()
 98        self.flow = flow
 99        self.with_policies = True
100        self.with_stage_prompts = True
with_policies: bool
with_stage_prompts: bool
pbm_uuids: list[uuid.UUID]
def get_entries(self) -> Iterable[authentik.blueprints.v1.common.BlueprintEntry]:
142    def get_entries(self) -> Iterable[BlueprintEntry]:
143        reference_index = ReferenceIndex()
144        reference_index.register(self.flow)
145
146        prompts = list(self._stage_prompts()) if self.with_stage_prompts else []
147        policies = list(self._policies()) if self.with_policies else []
148        stages = list(self._stages())
149        stage_bindings = list(self._stage_bindings())
150        policy_bindings = list(self._policy_bindings()) if self.with_policies else []
151
152        for obj in (*prompts, *policies, *stages, *stage_bindings, *policy_bindings):
153            reference_index.register(obj)
154
155        objects = [self.flow, *prompts, *policies, *stages, *stage_bindings, *policy_bindings]
156        entries = [
157            BlueprintEntry.from_model(self.flow, reference_index=reference_index),
158            *(
159                BlueprintEntry.from_model(prompt, reference_index=reference_index)
160                for prompt in prompts
161            ),
162            *(
163                BlueprintEntry.from_model(policy, reference_index=reference_index)
164                for policy in policies
165            ),
166            *(
167                BlueprintEntry.from_model(stage, reference_index=reference_index)
168                for stage in stages
169            ),
170            *(
171                BlueprintEntry.from_model(binding, reference_index=reference_index)
172                for binding in stage_bindings
173            ),
174            *(
175                BlueprintEntry.from_model(binding, reference_index=reference_index)
176                for binding in policy_bindings
177            ),
178        ]
179        reference_index.clear_unused_ids(entries, objects)
180        return entries

Get blueprint entries