authentik.blueprints.tests.test_v1

Test blueprints v1

  1"""Test blueprints v1"""
  2
  3from os import chmod, environ, unlink, write
  4from pathlib import Path
  5from tempfile import mkstemp
  6from uuid import UUID
  7
  8from django.db.models.signals import post_save
  9from django.test import TransactionTestCase
 10from django.utils.text import slugify
 11from yaml import load
 12
 13from authentik.blueprints.models import BlueprintInstance
 14from authentik.blueprints.tests import apply_blueprint
 15from authentik.blueprints.v1.common import BlueprintLoader, KeyOf
 16from authentik.blueprints.v1.exporter import Exporter, FlowExporter
 17from authentik.blueprints.v1.importer import Importer, transaction_rollback
 18from authentik.core.models import Group
 19from authentik.flows.models import Flow, FlowDesignation, FlowStageBinding
 20from authentik.lib.generators import generate_id
 21from authentik.lib.tests.utils import load_fixture
 22from authentik.policies.expression.models import ExpressionPolicy
 23from authentik.policies.models import PolicyBinding
 24from authentik.sources.oauth.models import OAuthSource
 25from authentik.stages.prompt.models import FieldTypes, Prompt, PromptStage
 26from authentik.stages.user_login.models import UserLoginStage
 27
 28
 29class TestBlueprintsV1(TransactionTestCase):
 30    """Test Blueprints"""
 31
 32    def test_blueprint_invalid_format(self):
 33        """Test blueprint with invalid format"""
 34        importer = Importer.from_string('{"version": 3}')
 35        self.assertFalse(importer.validate()[0])
 36        importer = Importer.from_string(
 37            '{"version": 1,"entries":[{"identifiers":{},"attrs":{},'
 38            '"model": "authentik_core.User"}]}'
 39        )
 40        self.assertFalse(importer.validate()[0])
 41        importer = Importer.from_string(
 42            '{"version": 1, "entries": [{"attrs": {"name": "test"}, '
 43            '"identifiers": {}, '
 44            '"model": "authentik_core.Group"}]}'
 45        )
 46        self.assertFalse(importer.validate()[0])
 47
 48    def test_yaml_tag_repr_does_not_raise(self):
 49        """repr() of a YAML tag must never raise (it is used by log sanitization)."""
 50        tag = load("!KeyOf does-not-exist", Loader=BlueprintLoader)
 51        self.assertIsInstance(repr(tag), str)
 52
 53    def test_validate_invalid_entry_holding_yaml_tag(self):
 54        """An invalid entry that still holds a raw !KeyOf must return validation
 55        errors instead of raising while sanitizing the logged entry."""
 56        importer = Importer.from_string("""
 57            version: 1
 58            entries:
 59                - model: authentik_providers_oauth2.scopemapping
 60                  id: sm
 61                  identifiers: { scope_name: test-tag-scope }
 62                  attrs:
 63                      name: test-tag-scope
 64                      scope_name: test-tag-scope
 65                      expression: "return {}"
 66                - model: authentik_providers_oauth2.oauth2provider
 67                  id: provider
 68                  identifiers: { client_id: test-tag }
 69                  attrs:
 70                      name: test-tag
 71                      client_id: test-tag
 72                      property_mappings:
 73                      - !KeyOf sm
 74        """)
 75        valid, logs = importer.validate()
 76        self.assertFalse(valid)
 77        self.assertGreater(len(logs), 0)
 78
 79    def test_validated_import_dict_identifiers(self):
 80        """Test importing blueprints with dict identifiers."""
 81        Group.objects.filter(name__istartswith="test").delete()
 82
 83        Group.objects.create(
 84            name="test1",
 85            attributes={
 86                "key": ["value"],
 87                "other_key": ["a_value", "other_value"],
 88            },
 89        )
 90        Group.objects.create(
 91            name="test2",
 92            attributes={
 93                "key": ["value"],
 94                "other_key": ["diff_value", "other_diff_value"],
 95            },
 96        )
 97
 98        importer = Importer.from_string(
 99            '{"version": 1, "entries": [{"attrs": {"name": "test999", "attributes": '
100            '{"key": ["updated_value"]}}, "identifiers": {"attributes": {"other_key": '
101            '["other_value"]}}, "model": "authentik_core.Group"}]}'
102        )
103        self.assertTrue(importer.validate()[0])
104        self.assertTrue(importer.apply())
105        self.assertTrue(
106            Group.objects.filter(
107                name="test2",
108                attributes={
109                    "key": ["value"],
110                    "other_key": ["diff_value", "other_diff_value"],
111                },
112            )
113        )
114        self.assertTrue(
115            Group.objects.filter(
116                name="test999",
117                # All attributes used as identifiers are kept and merged with the
118                # new attributes declared in the blueprint
119                attributes={"key": ["updated_value"], "other_key": ["other_value"]},
120            )
121        )
122        self.assertFalse(Group.objects.filter(name="test1"))
123
124    def test_export_validate_import(self):
125        """Test export and validate it"""
126        flow_slug = generate_id()
127        with transaction_rollback():
128            login_stage = UserLoginStage.objects.create(name=generate_id())
129
130            flow = Flow.objects.create(
131                slug=flow_slug,
132                designation=FlowDesignation.AUTHENTICATION,
133                name=generate_id(),
134                title=generate_id(),
135            )
136            FlowStageBinding.objects.update_or_create(
137                target=flow,
138                stage=login_stage,
139                order=0,
140            )
141
142            exporter = FlowExporter(flow)
143            export = exporter.export()
144            self.assertEqual(len(export.entries), 3)
145            export_yaml = exporter.export_to_string()
146
147        importer = Importer.from_string(export_yaml)
148        self.assertTrue(importer.validate()[0])
149        self.assertTrue(importer.apply())
150
151        self.assertTrue(Flow.objects.filter(slug=flow_slug).exists())
152
153    def test_export_validate_import_re_import(self):
154        """Test export and import it twice"""
155        count_initial = Prompt.objects.filter(field_key="username").count()
156
157        importer = Importer.from_string(load_fixture("fixtures/static_prompt_export.yaml"))
158        self.assertTrue(importer.validate()[0])
159        self.assertTrue(importer.apply())
160
161        count_before = Prompt.objects.filter(field_key="username").count()
162        self.assertEqual(count_initial + 1, count_before)
163
164        importer = Importer.from_string(load_fixture("fixtures/static_prompt_export.yaml"))
165        self.assertTrue(importer.apply())
166
167        self.assertEqual(Prompt.objects.filter(field_key="username").count(), count_before)
168
169    def test_nested_context_keys(self):
170        """Test nested context keys resolution"""
171        importer = Importer.from_string(load_fixture("fixtures/nested_contexts.yaml"))
172        self.assertTrue(importer.validate()[0])
173        self.assertTrue(importer.apply())
174
175        self.assertTrue(Group.objects.filter(name="not-nested").exists())
176        self.assertTrue(Group.objects.filter(name="nested").exists())
177        self.assertTrue(Group.objects.filter(name="list-element").exists())
178        self.assertTrue(Group.objects.filter(name="has-priority").exists())
179        self.assertTrue(Group.objects.filter(name="ref-value").exists())
180        self.assertTrue(Group.objects.filter(name="default-value").exists())
181
182    @apply_blueprint("system/providers-oauth2.yaml")
183    def test_import_yaml_tags(self):
184        """Test some yaml tags"""
185        ExpressionPolicy.objects.filter(name="foo-bar-baz-qux").delete()
186        Group.objects.filter(name="test").delete()
187        environ["foo"] = generate_id()
188        file, file_name = mkstemp()
189        write(file, b"foo")
190        _, file_default_name = mkstemp()
191        chmod(file_default_name, 0o000)  # Remove all permissions so we can't read the file
192        importer = Importer.from_string(
193            load_fixture(
194                "fixtures/tags.yaml",
195                file_name=file_name,
196                file_default_name=file_default_name,
197            ),
198            {"bar": "baz"},
199        )
200        self.assertTrue(importer.validate()[0])
201        self.assertTrue(importer.apply())
202        policy = ExpressionPolicy.objects.filter(name="foo-bar-baz-qux").first()
203        self.assertTrue(policy)
204        group = Group.objects.filter(name="test").first()
205        self.assertIsNotNone(group)
206        self.assertEqual(
207            group.attributes,
208            {
209                "policy_pk1": str(policy.pk) + "-suffix",
210                "policy_pk2": str(policy.pk) + "-suffix",
211                "boolEq": True,
212                "boolNeq": False,
213                "boolAnd": True,
214                "boolNand": False,
215                "boolOr": True,
216                "boolNor": False,
217                "boolXor": True,
218                "boolXnor": False,
219                "boolComplex": True,
220                "if_true_complex": {
221                    "dictionary": {
222                        "with": {"keys": "and_values"},
223                        "and_nested_custom_tags": "foo-bar",
224                    }
225                },
226                "if_false_complex": ["list", "with", "items", "foo-bar"],
227                "if_true_simple": True,
228                "if_short": True,
229                "if_false_simple": 2,
230                "enumerate_mapping_to_mapping": {
231                    "prefix-key1": "other-prefix-value",
232                    "prefix-key2": "other-prefix-2",
233                },
234                "enumerate_mapping_to_sequence": [
235                    "prefixed-pair-key1-value",
236                    "prefixed-pair-key2-2",
237                ],
238                "enumerate_sequence_to_sequence": [
239                    "prefixed-items-0-foo",
240                    "prefixed-items-1-bar",
241                ],
242                "enumerate_sequence_to_mapping": {"index: 0": "foo", "index: 1": "bar"},
243                "nested_complex_enumeration": {
244                    "0": {
245                        "key1": [
246                            ["prefixed-f", "prefixed-o", "prefixed-o"],
247                            {
248                                "outer_value": "foo",
249                                "outer_index": 0,
250                                "middle_value": "value",
251                                "middle_index": "key1",
252                            },
253                        ],
254                        "key2": [
255                            ["prefixed-f", "prefixed-o", "prefixed-o"],
256                            {
257                                "outer_value": "foo",
258                                "outer_index": 0,
259                                "middle_value": 2,
260                                "middle_index": "key2",
261                            },
262                        ],
263                    },
264                    "1": {
265                        "key1": [
266                            ["prefixed-b", "prefixed-a", "prefixed-r"],
267                            {
268                                "outer_value": "bar",
269                                "outer_index": 1,
270                                "middle_value": "value",
271                                "middle_index": "key1",
272                            },
273                        ],
274                        "key2": [
275                            ["prefixed-b", "prefixed-a", "prefixed-r"],
276                            {
277                                "outer_value": "bar",
278                                "outer_index": 1,
279                                "middle_value": 2,
280                                "middle_index": "key2",
281                            },
282                        ],
283                    },
284                },
285                "nested_context": "context-nested-value",
286                "env_null": None,
287                "file_content": "foo",
288                "file_default": "default",
289                "file_non_existent": None,
290                "json_parse": {"foo": "bar"},
291                "at_index_sequence": "foo",
292                "at_index_sequence_default": "non existent",
293                "at_index_mapping": 2,
294                "at_index_mapping_default": "non existent",
295                "find_object": "goauthentik.io/providers/oauth2/scope-openid",
296            },
297        )
298        self.assertTrue(
299            OAuthSource.objects.filter(
300                slug="test",
301                consumer_key=environ["foo"],
302            )
303        )
304        unlink(file_name)
305        unlink(file_default_name)
306
307    def test_export_validate_import_policies(self):
308        """Test export and validate it"""
309        flow_slug = generate_id()
310        stage_name = generate_id()
311        with transaction_rollback():
312            flow_policy = ExpressionPolicy.objects.create(
313                name=generate_id(),
314                expression="return True",
315            )
316            flow = Flow.objects.create(
317                slug=flow_slug,
318                designation=FlowDesignation.AUTHENTICATION,
319                name=generate_id(),
320                title=generate_id(),
321            )
322            PolicyBinding.objects.create(policy=flow_policy, target=flow, order=0)
323
324            user_login = UserLoginStage.objects.create(name=stage_name)
325            fsb = FlowStageBinding.objects.create(target=flow, stage=user_login, order=0)
326            PolicyBinding.objects.create(policy=flow_policy, target=fsb, order=0)
327
328            exporter = FlowExporter(flow)
329            export_yaml = exporter.export_to_string()
330
331        binding_pks = []
332
333        def capture_binding_pk(sender, instance, **kwargs):
334            binding_pks.append(instance.policy_binding_uuid)
335
336        # Inspect the signal instance: reloading from the database would hide a string UUID.
337        post_save.connect(capture_binding_pk, sender=PolicyBinding)
338        try:
339            importer = Importer.from_string(export_yaml)
340            self.assertTrue(importer.validate()[0])
341            self.assertTrue(importer.apply())
342        finally:
343            post_save.disconnect(capture_binding_pk, sender=PolicyBinding)
344
345        self.assertTrue(binding_pks)
346        for binding_pk in binding_pks:
347            self.assertIsInstance(binding_pk, UUID)
348        self.assertTrue(UserLoginStage.objects.filter(name=stage_name).exists())
349        self.assertTrue(Flow.objects.filter(slug=flow_slug).exists())
350
351    def test_export_uses_keyof_references(self):
352        """Test that exporting a flow rewrites references between exported objects
353        as !KeyOf tags instead of raw primary keys"""
354        flow_slug = generate_id()
355        stage_name = generate_id()
356        policy_name = generate_id()
357        with transaction_rollback():
358            flow_policy = ExpressionPolicy.objects.create(
359                name=policy_name,
360                expression="return True",
361            )
362            flow = Flow.objects.create(
363                slug=flow_slug,
364                designation=FlowDesignation.AUTHENTICATION,
365                name=generate_id(),
366                title=generate_id(),
367            )
368            PolicyBinding.objects.create(policy=flow_policy, target=flow, order=0)
369
370            user_login = UserLoginStage.objects.create(name=stage_name)
371            fsb = FlowStageBinding.objects.create(target=flow, stage=user_login, order=0)
372            PolicyBinding.objects.create(policy=flow_policy, target=fsb, order=0)
373
374            exporter = FlowExporter(flow)
375            export = exporter.export()
376            export_yaml = exporter.export_to_string()
377
378        entries_by_model = {}
379        for entry in export.entries:
380            entries_by_model.setdefault(entry.model, []).append(entry)
381
382        flow_entry = entries_by_model["authentik_flows.flow"][0]
383        stage_entry = entries_by_model["authentik_stages_user_login.userloginstage"][0]
384        stage_binding_entry = entries_by_model["authentik_flows.flowstagebinding"][0]
385        policy_entry = entries_by_model["authentik_policies_expression.expressionpolicy"][0]
386        policy_binding_entries = entries_by_model["authentik_policies.policybinding"]
387
388        self.assertIsNotNone(flow_entry.id)
389        self.assertIsNotNone(stage_entry.id)
390        # ids are derived from a readable, unique, non-UUID field (slug/name) when available,
391        # rather than an opaque counter
392        self.assertEqual(flow_entry.id, f"flow-{slugify(flow_slug)}")
393        self.assertEqual(stage_entry.id, f"userloginstage-{slugify(stage_name)}")
394
395        # Policy is exported without any explicit extra identifiers, but its unique,
396        # non-UUID `name` field is still picked up automatically as a stable identifier
397        self.assertEqual(policy_entry.identifiers.get("name"), policy_name)
398        # The primary key is instance-local and not portable, so it must not be used as
399        # an identifier whenever a stable identifier could be found instead
400        for entry in (flow_entry, stage_entry, policy_entry):
401            self.assertNotIn("pk", entry.identifiers)
402
403        self.assertIsInstance(stage_binding_entry.identifiers["target"], KeyOf)
404        self.assertEqual(stage_binding_entry.identifiers["target"].id_from, flow_entry.id)
405        self.assertIsInstance(stage_binding_entry.identifiers["stage"], KeyOf)
406        self.assertEqual(stage_binding_entry.identifiers["stage"].id_from, stage_entry.id)
407
408        binding_targets = {pb.identifiers["target"].id_from for pb in policy_binding_entries}
409        self.assertIn(flow_entry.id, binding_targets)
410        self.assertIn(stage_binding_entry.id, binding_targets)
411        for policy_binding_entry in policy_binding_entries:
412            self.assertIsInstance(policy_binding_entry.identifiers["policy"], KeyOf)
413            self.assertEqual(policy_binding_entry.identifiers["policy"].id_from, policy_entry.id)
414
415        self.assertIn("!KeyOf", export_yaml)
416
417        importer = Importer.from_string(export_yaml)
418        self.assertTrue(importer.validate()[0])
419        self.assertTrue(importer.apply())
420        self.assertTrue(Flow.objects.filter(slug=flow_slug).exists())
421
422    def test_export_default_blueprints_no_static_identifiers(self):
423        """Test that exporting a full instance after applying all default blueprints
424        never falls back to an opaque, non-portable `pk` identifier, e.g. for models
425        such as FlowStageBinding that have no unique text field of their own"""
426        for blueprint_file in sorted(Path("blueprints/default").glob("*.yaml")):
427            rel_path = str(blueprint_file.relative_to("blueprints"))
428            importer = Importer.from_string(BlueprintInstance(path=rel_path).retrieve())
429            self.assertTrue(importer.validate()[0])
430            self.assertTrue(importer.apply())
431
432        export = Exporter().export()
433        for entry in export.entries:
434            self.assertNotIn(
435                "pk", entry.identifiers, f"{entry.model} entry has a static pk identifier"
436            )
437
438    def test_export_validate_import_prompt(self):
439        """Test export and validate it"""
440        with transaction_rollback():
441            # First stage fields
442            username_prompt = Prompt.objects.create(
443                name=generate_id(),
444                field_key="username",
445                label="Username",
446                order=0,
447                type=FieldTypes.TEXT,
448            )
449            password = Prompt.objects.create(
450                name=generate_id(),
451                field_key="password",
452                label="Password",
453                order=1,
454                type=FieldTypes.PASSWORD,
455            )
456            password_repeat = Prompt.objects.create(
457                name=generate_id(),
458                field_key="password_repeat",
459                label="Password (repeat)",
460                order=2,
461                type=FieldTypes.PASSWORD,
462            )
463
464            # Stages
465            first_stage = PromptStage.objects.create(name=generate_id())
466            first_stage.fields.set([username_prompt, password, password_repeat])
467            first_stage.save()
468
469            flow = Flow.objects.create(
470                name=generate_id(),
471                slug=generate_id(),
472                designation=FlowDesignation.ENROLLMENT,
473                title=generate_id(),
474            )
475
476            FlowStageBinding.objects.create(target=flow, stage=first_stage, order=0)
477
478            exporter = FlowExporter(flow)
479            export_yaml = exporter.export_to_string()
480
481        importer = Importer.from_string(export_yaml)
482
483        self.assertTrue(importer.validate()[0])
484        self.assertTrue(importer.apply())
class TestBlueprintsV1(django.test.testcases.TransactionTestCase):
 30class TestBlueprintsV1(TransactionTestCase):
 31    """Test Blueprints"""
 32
 33    def test_blueprint_invalid_format(self):
 34        """Test blueprint with invalid format"""
 35        importer = Importer.from_string('{"version": 3}')
 36        self.assertFalse(importer.validate()[0])
 37        importer = Importer.from_string(
 38            '{"version": 1,"entries":[{"identifiers":{},"attrs":{},'
 39            '"model": "authentik_core.User"}]}'
 40        )
 41        self.assertFalse(importer.validate()[0])
 42        importer = Importer.from_string(
 43            '{"version": 1, "entries": [{"attrs": {"name": "test"}, '
 44            '"identifiers": {}, '
 45            '"model": "authentik_core.Group"}]}'
 46        )
 47        self.assertFalse(importer.validate()[0])
 48
 49    def test_yaml_tag_repr_does_not_raise(self):
 50        """repr() of a YAML tag must never raise (it is used by log sanitization)."""
 51        tag = load("!KeyOf does-not-exist", Loader=BlueprintLoader)
 52        self.assertIsInstance(repr(tag), str)
 53
 54    def test_validate_invalid_entry_holding_yaml_tag(self):
 55        """An invalid entry that still holds a raw !KeyOf must return validation
 56        errors instead of raising while sanitizing the logged entry."""
 57        importer = Importer.from_string("""
 58            version: 1
 59            entries:
 60                - model: authentik_providers_oauth2.scopemapping
 61                  id: sm
 62                  identifiers: { scope_name: test-tag-scope }
 63                  attrs:
 64                      name: test-tag-scope
 65                      scope_name: test-tag-scope
 66                      expression: "return {}"
 67                - model: authentik_providers_oauth2.oauth2provider
 68                  id: provider
 69                  identifiers: { client_id: test-tag }
 70                  attrs:
 71                      name: test-tag
 72                      client_id: test-tag
 73                      property_mappings:
 74                      - !KeyOf sm
 75        """)
 76        valid, logs = importer.validate()
 77        self.assertFalse(valid)
 78        self.assertGreater(len(logs), 0)
 79
 80    def test_validated_import_dict_identifiers(self):
 81        """Test importing blueprints with dict identifiers."""
 82        Group.objects.filter(name__istartswith="test").delete()
 83
 84        Group.objects.create(
 85            name="test1",
 86            attributes={
 87                "key": ["value"],
 88                "other_key": ["a_value", "other_value"],
 89            },
 90        )
 91        Group.objects.create(
 92            name="test2",
 93            attributes={
 94                "key": ["value"],
 95                "other_key": ["diff_value", "other_diff_value"],
 96            },
 97        )
 98
 99        importer = Importer.from_string(
100            '{"version": 1, "entries": [{"attrs": {"name": "test999", "attributes": '
101            '{"key": ["updated_value"]}}, "identifiers": {"attributes": {"other_key": '
102            '["other_value"]}}, "model": "authentik_core.Group"}]}'
103        )
104        self.assertTrue(importer.validate()[0])
105        self.assertTrue(importer.apply())
106        self.assertTrue(
107            Group.objects.filter(
108                name="test2",
109                attributes={
110                    "key": ["value"],
111                    "other_key": ["diff_value", "other_diff_value"],
112                },
113            )
114        )
115        self.assertTrue(
116            Group.objects.filter(
117                name="test999",
118                # All attributes used as identifiers are kept and merged with the
119                # new attributes declared in the blueprint
120                attributes={"key": ["updated_value"], "other_key": ["other_value"]},
121            )
122        )
123        self.assertFalse(Group.objects.filter(name="test1"))
124
125    def test_export_validate_import(self):
126        """Test export and validate it"""
127        flow_slug = generate_id()
128        with transaction_rollback():
129            login_stage = UserLoginStage.objects.create(name=generate_id())
130
131            flow = Flow.objects.create(
132                slug=flow_slug,
133                designation=FlowDesignation.AUTHENTICATION,
134                name=generate_id(),
135                title=generate_id(),
136            )
137            FlowStageBinding.objects.update_or_create(
138                target=flow,
139                stage=login_stage,
140                order=0,
141            )
142
143            exporter = FlowExporter(flow)
144            export = exporter.export()
145            self.assertEqual(len(export.entries), 3)
146            export_yaml = exporter.export_to_string()
147
148        importer = Importer.from_string(export_yaml)
149        self.assertTrue(importer.validate()[0])
150        self.assertTrue(importer.apply())
151
152        self.assertTrue(Flow.objects.filter(slug=flow_slug).exists())
153
154    def test_export_validate_import_re_import(self):
155        """Test export and import it twice"""
156        count_initial = Prompt.objects.filter(field_key="username").count()
157
158        importer = Importer.from_string(load_fixture("fixtures/static_prompt_export.yaml"))
159        self.assertTrue(importer.validate()[0])
160        self.assertTrue(importer.apply())
161
162        count_before = Prompt.objects.filter(field_key="username").count()
163        self.assertEqual(count_initial + 1, count_before)
164
165        importer = Importer.from_string(load_fixture("fixtures/static_prompt_export.yaml"))
166        self.assertTrue(importer.apply())
167
168        self.assertEqual(Prompt.objects.filter(field_key="username").count(), count_before)
169
170    def test_nested_context_keys(self):
171        """Test nested context keys resolution"""
172        importer = Importer.from_string(load_fixture("fixtures/nested_contexts.yaml"))
173        self.assertTrue(importer.validate()[0])
174        self.assertTrue(importer.apply())
175
176        self.assertTrue(Group.objects.filter(name="not-nested").exists())
177        self.assertTrue(Group.objects.filter(name="nested").exists())
178        self.assertTrue(Group.objects.filter(name="list-element").exists())
179        self.assertTrue(Group.objects.filter(name="has-priority").exists())
180        self.assertTrue(Group.objects.filter(name="ref-value").exists())
181        self.assertTrue(Group.objects.filter(name="default-value").exists())
182
183    @apply_blueprint("system/providers-oauth2.yaml")
184    def test_import_yaml_tags(self):
185        """Test some yaml tags"""
186        ExpressionPolicy.objects.filter(name="foo-bar-baz-qux").delete()
187        Group.objects.filter(name="test").delete()
188        environ["foo"] = generate_id()
189        file, file_name = mkstemp()
190        write(file, b"foo")
191        _, file_default_name = mkstemp()
192        chmod(file_default_name, 0o000)  # Remove all permissions so we can't read the file
193        importer = Importer.from_string(
194            load_fixture(
195                "fixtures/tags.yaml",
196                file_name=file_name,
197                file_default_name=file_default_name,
198            ),
199            {"bar": "baz"},
200        )
201        self.assertTrue(importer.validate()[0])
202        self.assertTrue(importer.apply())
203        policy = ExpressionPolicy.objects.filter(name="foo-bar-baz-qux").first()
204        self.assertTrue(policy)
205        group = Group.objects.filter(name="test").first()
206        self.assertIsNotNone(group)
207        self.assertEqual(
208            group.attributes,
209            {
210                "policy_pk1": str(policy.pk) + "-suffix",
211                "policy_pk2": str(policy.pk) + "-suffix",
212                "boolEq": True,
213                "boolNeq": False,
214                "boolAnd": True,
215                "boolNand": False,
216                "boolOr": True,
217                "boolNor": False,
218                "boolXor": True,
219                "boolXnor": False,
220                "boolComplex": True,
221                "if_true_complex": {
222                    "dictionary": {
223                        "with": {"keys": "and_values"},
224                        "and_nested_custom_tags": "foo-bar",
225                    }
226                },
227                "if_false_complex": ["list", "with", "items", "foo-bar"],
228                "if_true_simple": True,
229                "if_short": True,
230                "if_false_simple": 2,
231                "enumerate_mapping_to_mapping": {
232                    "prefix-key1": "other-prefix-value",
233                    "prefix-key2": "other-prefix-2",
234                },
235                "enumerate_mapping_to_sequence": [
236                    "prefixed-pair-key1-value",
237                    "prefixed-pair-key2-2",
238                ],
239                "enumerate_sequence_to_sequence": [
240                    "prefixed-items-0-foo",
241                    "prefixed-items-1-bar",
242                ],
243                "enumerate_sequence_to_mapping": {"index: 0": "foo", "index: 1": "bar"},
244                "nested_complex_enumeration": {
245                    "0": {
246                        "key1": [
247                            ["prefixed-f", "prefixed-o", "prefixed-o"],
248                            {
249                                "outer_value": "foo",
250                                "outer_index": 0,
251                                "middle_value": "value",
252                                "middle_index": "key1",
253                            },
254                        ],
255                        "key2": [
256                            ["prefixed-f", "prefixed-o", "prefixed-o"],
257                            {
258                                "outer_value": "foo",
259                                "outer_index": 0,
260                                "middle_value": 2,
261                                "middle_index": "key2",
262                            },
263                        ],
264                    },
265                    "1": {
266                        "key1": [
267                            ["prefixed-b", "prefixed-a", "prefixed-r"],
268                            {
269                                "outer_value": "bar",
270                                "outer_index": 1,
271                                "middle_value": "value",
272                                "middle_index": "key1",
273                            },
274                        ],
275                        "key2": [
276                            ["prefixed-b", "prefixed-a", "prefixed-r"],
277                            {
278                                "outer_value": "bar",
279                                "outer_index": 1,
280                                "middle_value": 2,
281                                "middle_index": "key2",
282                            },
283                        ],
284                    },
285                },
286                "nested_context": "context-nested-value",
287                "env_null": None,
288                "file_content": "foo",
289                "file_default": "default",
290                "file_non_existent": None,
291                "json_parse": {"foo": "bar"},
292                "at_index_sequence": "foo",
293                "at_index_sequence_default": "non existent",
294                "at_index_mapping": 2,
295                "at_index_mapping_default": "non existent",
296                "find_object": "goauthentik.io/providers/oauth2/scope-openid",
297            },
298        )
299        self.assertTrue(
300            OAuthSource.objects.filter(
301                slug="test",
302                consumer_key=environ["foo"],
303            )
304        )
305        unlink(file_name)
306        unlink(file_default_name)
307
308    def test_export_validate_import_policies(self):
309        """Test export and validate it"""
310        flow_slug = generate_id()
311        stage_name = generate_id()
312        with transaction_rollback():
313            flow_policy = ExpressionPolicy.objects.create(
314                name=generate_id(),
315                expression="return True",
316            )
317            flow = Flow.objects.create(
318                slug=flow_slug,
319                designation=FlowDesignation.AUTHENTICATION,
320                name=generate_id(),
321                title=generate_id(),
322            )
323            PolicyBinding.objects.create(policy=flow_policy, target=flow, order=0)
324
325            user_login = UserLoginStage.objects.create(name=stage_name)
326            fsb = FlowStageBinding.objects.create(target=flow, stage=user_login, order=0)
327            PolicyBinding.objects.create(policy=flow_policy, target=fsb, order=0)
328
329            exporter = FlowExporter(flow)
330            export_yaml = exporter.export_to_string()
331
332        binding_pks = []
333
334        def capture_binding_pk(sender, instance, **kwargs):
335            binding_pks.append(instance.policy_binding_uuid)
336
337        # Inspect the signal instance: reloading from the database would hide a string UUID.
338        post_save.connect(capture_binding_pk, sender=PolicyBinding)
339        try:
340            importer = Importer.from_string(export_yaml)
341            self.assertTrue(importer.validate()[0])
342            self.assertTrue(importer.apply())
343        finally:
344            post_save.disconnect(capture_binding_pk, sender=PolicyBinding)
345
346        self.assertTrue(binding_pks)
347        for binding_pk in binding_pks:
348            self.assertIsInstance(binding_pk, UUID)
349        self.assertTrue(UserLoginStage.objects.filter(name=stage_name).exists())
350        self.assertTrue(Flow.objects.filter(slug=flow_slug).exists())
351
352    def test_export_uses_keyof_references(self):
353        """Test that exporting a flow rewrites references between exported objects
354        as !KeyOf tags instead of raw primary keys"""
355        flow_slug = generate_id()
356        stage_name = generate_id()
357        policy_name = generate_id()
358        with transaction_rollback():
359            flow_policy = ExpressionPolicy.objects.create(
360                name=policy_name,
361                expression="return True",
362            )
363            flow = Flow.objects.create(
364                slug=flow_slug,
365                designation=FlowDesignation.AUTHENTICATION,
366                name=generate_id(),
367                title=generate_id(),
368            )
369            PolicyBinding.objects.create(policy=flow_policy, target=flow, order=0)
370
371            user_login = UserLoginStage.objects.create(name=stage_name)
372            fsb = FlowStageBinding.objects.create(target=flow, stage=user_login, order=0)
373            PolicyBinding.objects.create(policy=flow_policy, target=fsb, order=0)
374
375            exporter = FlowExporter(flow)
376            export = exporter.export()
377            export_yaml = exporter.export_to_string()
378
379        entries_by_model = {}
380        for entry in export.entries:
381            entries_by_model.setdefault(entry.model, []).append(entry)
382
383        flow_entry = entries_by_model["authentik_flows.flow"][0]
384        stage_entry = entries_by_model["authentik_stages_user_login.userloginstage"][0]
385        stage_binding_entry = entries_by_model["authentik_flows.flowstagebinding"][0]
386        policy_entry = entries_by_model["authentik_policies_expression.expressionpolicy"][0]
387        policy_binding_entries = entries_by_model["authentik_policies.policybinding"]
388
389        self.assertIsNotNone(flow_entry.id)
390        self.assertIsNotNone(stage_entry.id)
391        # ids are derived from a readable, unique, non-UUID field (slug/name) when available,
392        # rather than an opaque counter
393        self.assertEqual(flow_entry.id, f"flow-{slugify(flow_slug)}")
394        self.assertEqual(stage_entry.id, f"userloginstage-{slugify(stage_name)}")
395
396        # Policy is exported without any explicit extra identifiers, but its unique,
397        # non-UUID `name` field is still picked up automatically as a stable identifier
398        self.assertEqual(policy_entry.identifiers.get("name"), policy_name)
399        # The primary key is instance-local and not portable, so it must not be used as
400        # an identifier whenever a stable identifier could be found instead
401        for entry in (flow_entry, stage_entry, policy_entry):
402            self.assertNotIn("pk", entry.identifiers)
403
404        self.assertIsInstance(stage_binding_entry.identifiers["target"], KeyOf)
405        self.assertEqual(stage_binding_entry.identifiers["target"].id_from, flow_entry.id)
406        self.assertIsInstance(stage_binding_entry.identifiers["stage"], KeyOf)
407        self.assertEqual(stage_binding_entry.identifiers["stage"].id_from, stage_entry.id)
408
409        binding_targets = {pb.identifiers["target"].id_from for pb in policy_binding_entries}
410        self.assertIn(flow_entry.id, binding_targets)
411        self.assertIn(stage_binding_entry.id, binding_targets)
412        for policy_binding_entry in policy_binding_entries:
413            self.assertIsInstance(policy_binding_entry.identifiers["policy"], KeyOf)
414            self.assertEqual(policy_binding_entry.identifiers["policy"].id_from, policy_entry.id)
415
416        self.assertIn("!KeyOf", export_yaml)
417
418        importer = Importer.from_string(export_yaml)
419        self.assertTrue(importer.validate()[0])
420        self.assertTrue(importer.apply())
421        self.assertTrue(Flow.objects.filter(slug=flow_slug).exists())
422
423    def test_export_default_blueprints_no_static_identifiers(self):
424        """Test that exporting a full instance after applying all default blueprints
425        never falls back to an opaque, non-portable `pk` identifier, e.g. for models
426        such as FlowStageBinding that have no unique text field of their own"""
427        for blueprint_file in sorted(Path("blueprints/default").glob("*.yaml")):
428            rel_path = str(blueprint_file.relative_to("blueprints"))
429            importer = Importer.from_string(BlueprintInstance(path=rel_path).retrieve())
430            self.assertTrue(importer.validate()[0])
431            self.assertTrue(importer.apply())
432
433        export = Exporter().export()
434        for entry in export.entries:
435            self.assertNotIn(
436                "pk", entry.identifiers, f"{entry.model} entry has a static pk identifier"
437            )
438
439    def test_export_validate_import_prompt(self):
440        """Test export and validate it"""
441        with transaction_rollback():
442            # First stage fields
443            username_prompt = Prompt.objects.create(
444                name=generate_id(),
445                field_key="username",
446                label="Username",
447                order=0,
448                type=FieldTypes.TEXT,
449            )
450            password = Prompt.objects.create(
451                name=generate_id(),
452                field_key="password",
453                label="Password",
454                order=1,
455                type=FieldTypes.PASSWORD,
456            )
457            password_repeat = Prompt.objects.create(
458                name=generate_id(),
459                field_key="password_repeat",
460                label="Password (repeat)",
461                order=2,
462                type=FieldTypes.PASSWORD,
463            )
464
465            # Stages
466            first_stage = PromptStage.objects.create(name=generate_id())
467            first_stage.fields.set([username_prompt, password, password_repeat])
468            first_stage.save()
469
470            flow = Flow.objects.create(
471                name=generate_id(),
472                slug=generate_id(),
473                designation=FlowDesignation.ENROLLMENT,
474                title=generate_id(),
475            )
476
477            FlowStageBinding.objects.create(target=flow, stage=first_stage, order=0)
478
479            exporter = FlowExporter(flow)
480            export_yaml = exporter.export_to_string()
481
482        importer = Importer.from_string(export_yaml)
483
484        self.assertTrue(importer.validate()[0])
485        self.assertTrue(importer.apply())

Test Blueprints

def test_blueprint_invalid_format(self):
33    def test_blueprint_invalid_format(self):
34        """Test blueprint with invalid format"""
35        importer = Importer.from_string('{"version": 3}')
36        self.assertFalse(importer.validate()[0])
37        importer = Importer.from_string(
38            '{"version": 1,"entries":[{"identifiers":{},"attrs":{},'
39            '"model": "authentik_core.User"}]}'
40        )
41        self.assertFalse(importer.validate()[0])
42        importer = Importer.from_string(
43            '{"version": 1, "entries": [{"attrs": {"name": "test"}, '
44            '"identifiers": {}, '
45            '"model": "authentik_core.Group"}]}'
46        )
47        self.assertFalse(importer.validate()[0])

Test blueprint with invalid format

def test_yaml_tag_repr_does_not_raise(self):
49    def test_yaml_tag_repr_does_not_raise(self):
50        """repr() of a YAML tag must never raise (it is used by log sanitization)."""
51        tag = load("!KeyOf does-not-exist", Loader=BlueprintLoader)
52        self.assertIsInstance(repr(tag), str)

repr() of a YAML tag must never raise (it is used by log sanitization).

def test_validate_invalid_entry_holding_yaml_tag(self):
54    def test_validate_invalid_entry_holding_yaml_tag(self):
55        """An invalid entry that still holds a raw !KeyOf must return validation
56        errors instead of raising while sanitizing the logged entry."""
57        importer = Importer.from_string("""
58            version: 1
59            entries:
60                - model: authentik_providers_oauth2.scopemapping
61                  id: sm
62                  identifiers: { scope_name: test-tag-scope }
63                  attrs:
64                      name: test-tag-scope
65                      scope_name: test-tag-scope
66                      expression: "return {}"
67                - model: authentik_providers_oauth2.oauth2provider
68                  id: provider
69                  identifiers: { client_id: test-tag }
70                  attrs:
71                      name: test-tag
72                      client_id: test-tag
73                      property_mappings:
74                      - !KeyOf sm
75        """)
76        valid, logs = importer.validate()
77        self.assertFalse(valid)
78        self.assertGreater(len(logs), 0)

An invalid entry that still holds a raw !KeyOf must return validation errors instead of raising while sanitizing the logged entry.

def test_validated_import_dict_identifiers(self):
 80    def test_validated_import_dict_identifiers(self):
 81        """Test importing blueprints with dict identifiers."""
 82        Group.objects.filter(name__istartswith="test").delete()
 83
 84        Group.objects.create(
 85            name="test1",
 86            attributes={
 87                "key": ["value"],
 88                "other_key": ["a_value", "other_value"],
 89            },
 90        )
 91        Group.objects.create(
 92            name="test2",
 93            attributes={
 94                "key": ["value"],
 95                "other_key": ["diff_value", "other_diff_value"],
 96            },
 97        )
 98
 99        importer = Importer.from_string(
100            '{"version": 1, "entries": [{"attrs": {"name": "test999", "attributes": '
101            '{"key": ["updated_value"]}}, "identifiers": {"attributes": {"other_key": '
102            '["other_value"]}}, "model": "authentik_core.Group"}]}'
103        )
104        self.assertTrue(importer.validate()[0])
105        self.assertTrue(importer.apply())
106        self.assertTrue(
107            Group.objects.filter(
108                name="test2",
109                attributes={
110                    "key": ["value"],
111                    "other_key": ["diff_value", "other_diff_value"],
112                },
113            )
114        )
115        self.assertTrue(
116            Group.objects.filter(
117                name="test999",
118                # All attributes used as identifiers are kept and merged with the
119                # new attributes declared in the blueprint
120                attributes={"key": ["updated_value"], "other_key": ["other_value"]},
121            )
122        )
123        self.assertFalse(Group.objects.filter(name="test1"))

Test importing blueprints with dict identifiers.

def test_export_validate_import(self):
125    def test_export_validate_import(self):
126        """Test export and validate it"""
127        flow_slug = generate_id()
128        with transaction_rollback():
129            login_stage = UserLoginStage.objects.create(name=generate_id())
130
131            flow = Flow.objects.create(
132                slug=flow_slug,
133                designation=FlowDesignation.AUTHENTICATION,
134                name=generate_id(),
135                title=generate_id(),
136            )
137            FlowStageBinding.objects.update_or_create(
138                target=flow,
139                stage=login_stage,
140                order=0,
141            )
142
143            exporter = FlowExporter(flow)
144            export = exporter.export()
145            self.assertEqual(len(export.entries), 3)
146            export_yaml = exporter.export_to_string()
147
148        importer = Importer.from_string(export_yaml)
149        self.assertTrue(importer.validate()[0])
150        self.assertTrue(importer.apply())
151
152        self.assertTrue(Flow.objects.filter(slug=flow_slug).exists())

Test export and validate it

def test_export_validate_import_re_import(self):
154    def test_export_validate_import_re_import(self):
155        """Test export and import it twice"""
156        count_initial = Prompt.objects.filter(field_key="username").count()
157
158        importer = Importer.from_string(load_fixture("fixtures/static_prompt_export.yaml"))
159        self.assertTrue(importer.validate()[0])
160        self.assertTrue(importer.apply())
161
162        count_before = Prompt.objects.filter(field_key="username").count()
163        self.assertEqual(count_initial + 1, count_before)
164
165        importer = Importer.from_string(load_fixture("fixtures/static_prompt_export.yaml"))
166        self.assertTrue(importer.apply())
167
168        self.assertEqual(Prompt.objects.filter(field_key="username").count(), count_before)

Test export and import it twice

def test_nested_context_keys(self):
170    def test_nested_context_keys(self):
171        """Test nested context keys resolution"""
172        importer = Importer.from_string(load_fixture("fixtures/nested_contexts.yaml"))
173        self.assertTrue(importer.validate()[0])
174        self.assertTrue(importer.apply())
175
176        self.assertTrue(Group.objects.filter(name="not-nested").exists())
177        self.assertTrue(Group.objects.filter(name="nested").exists())
178        self.assertTrue(Group.objects.filter(name="list-element").exists())
179        self.assertTrue(Group.objects.filter(name="has-priority").exists())
180        self.assertTrue(Group.objects.filter(name="ref-value").exists())
181        self.assertTrue(Group.objects.filter(name="default-value").exists())

Test nested context keys resolution

@apply_blueprint('system/providers-oauth2.yaml')
def test_import_yaml_tags(self):
183    @apply_blueprint("system/providers-oauth2.yaml")
184    def test_import_yaml_tags(self):
185        """Test some yaml tags"""
186        ExpressionPolicy.objects.filter(name="foo-bar-baz-qux").delete()
187        Group.objects.filter(name="test").delete()
188        environ["foo"] = generate_id()
189        file, file_name = mkstemp()
190        write(file, b"foo")
191        _, file_default_name = mkstemp()
192        chmod(file_default_name, 0o000)  # Remove all permissions so we can't read the file
193        importer = Importer.from_string(
194            load_fixture(
195                "fixtures/tags.yaml",
196                file_name=file_name,
197                file_default_name=file_default_name,
198            ),
199            {"bar": "baz"},
200        )
201        self.assertTrue(importer.validate()[0])
202        self.assertTrue(importer.apply())
203        policy = ExpressionPolicy.objects.filter(name="foo-bar-baz-qux").first()
204        self.assertTrue(policy)
205        group = Group.objects.filter(name="test").first()
206        self.assertIsNotNone(group)
207        self.assertEqual(
208            group.attributes,
209            {
210                "policy_pk1": str(policy.pk) + "-suffix",
211                "policy_pk2": str(policy.pk) + "-suffix",
212                "boolEq": True,
213                "boolNeq": False,
214                "boolAnd": True,
215                "boolNand": False,
216                "boolOr": True,
217                "boolNor": False,
218                "boolXor": True,
219                "boolXnor": False,
220                "boolComplex": True,
221                "if_true_complex": {
222                    "dictionary": {
223                        "with": {"keys": "and_values"},
224                        "and_nested_custom_tags": "foo-bar",
225                    }
226                },
227                "if_false_complex": ["list", "with", "items", "foo-bar"],
228                "if_true_simple": True,
229                "if_short": True,
230                "if_false_simple": 2,
231                "enumerate_mapping_to_mapping": {
232                    "prefix-key1": "other-prefix-value",
233                    "prefix-key2": "other-prefix-2",
234                },
235                "enumerate_mapping_to_sequence": [
236                    "prefixed-pair-key1-value",
237                    "prefixed-pair-key2-2",
238                ],
239                "enumerate_sequence_to_sequence": [
240                    "prefixed-items-0-foo",
241                    "prefixed-items-1-bar",
242                ],
243                "enumerate_sequence_to_mapping": {"index: 0": "foo", "index: 1": "bar"},
244                "nested_complex_enumeration": {
245                    "0": {
246                        "key1": [
247                            ["prefixed-f", "prefixed-o", "prefixed-o"],
248                            {
249                                "outer_value": "foo",
250                                "outer_index": 0,
251                                "middle_value": "value",
252                                "middle_index": "key1",
253                            },
254                        ],
255                        "key2": [
256                            ["prefixed-f", "prefixed-o", "prefixed-o"],
257                            {
258                                "outer_value": "foo",
259                                "outer_index": 0,
260                                "middle_value": 2,
261                                "middle_index": "key2",
262                            },
263                        ],
264                    },
265                    "1": {
266                        "key1": [
267                            ["prefixed-b", "prefixed-a", "prefixed-r"],
268                            {
269                                "outer_value": "bar",
270                                "outer_index": 1,
271                                "middle_value": "value",
272                                "middle_index": "key1",
273                            },
274                        ],
275                        "key2": [
276                            ["prefixed-b", "prefixed-a", "prefixed-r"],
277                            {
278                                "outer_value": "bar",
279                                "outer_index": 1,
280                                "middle_value": 2,
281                                "middle_index": "key2",
282                            },
283                        ],
284                    },
285                },
286                "nested_context": "context-nested-value",
287                "env_null": None,
288                "file_content": "foo",
289                "file_default": "default",
290                "file_non_existent": None,
291                "json_parse": {"foo": "bar"},
292                "at_index_sequence": "foo",
293                "at_index_sequence_default": "non existent",
294                "at_index_mapping": 2,
295                "at_index_mapping_default": "non existent",
296                "find_object": "goauthentik.io/providers/oauth2/scope-openid",
297            },
298        )
299        self.assertTrue(
300            OAuthSource.objects.filter(
301                slug="test",
302                consumer_key=environ["foo"],
303            )
304        )
305        unlink(file_name)
306        unlink(file_default_name)

Test some yaml tags

def test_export_validate_import_policies(self):
308    def test_export_validate_import_policies(self):
309        """Test export and validate it"""
310        flow_slug = generate_id()
311        stage_name = generate_id()
312        with transaction_rollback():
313            flow_policy = ExpressionPolicy.objects.create(
314                name=generate_id(),
315                expression="return True",
316            )
317            flow = Flow.objects.create(
318                slug=flow_slug,
319                designation=FlowDesignation.AUTHENTICATION,
320                name=generate_id(),
321                title=generate_id(),
322            )
323            PolicyBinding.objects.create(policy=flow_policy, target=flow, order=0)
324
325            user_login = UserLoginStage.objects.create(name=stage_name)
326            fsb = FlowStageBinding.objects.create(target=flow, stage=user_login, order=0)
327            PolicyBinding.objects.create(policy=flow_policy, target=fsb, order=0)
328
329            exporter = FlowExporter(flow)
330            export_yaml = exporter.export_to_string()
331
332        binding_pks = []
333
334        def capture_binding_pk(sender, instance, **kwargs):
335            binding_pks.append(instance.policy_binding_uuid)
336
337        # Inspect the signal instance: reloading from the database would hide a string UUID.
338        post_save.connect(capture_binding_pk, sender=PolicyBinding)
339        try:
340            importer = Importer.from_string(export_yaml)
341            self.assertTrue(importer.validate()[0])
342            self.assertTrue(importer.apply())
343        finally:
344            post_save.disconnect(capture_binding_pk, sender=PolicyBinding)
345
346        self.assertTrue(binding_pks)
347        for binding_pk in binding_pks:
348            self.assertIsInstance(binding_pk, UUID)
349        self.assertTrue(UserLoginStage.objects.filter(name=stage_name).exists())
350        self.assertTrue(Flow.objects.filter(slug=flow_slug).exists())

Test export and validate it

def test_export_uses_keyof_references(self):
352    def test_export_uses_keyof_references(self):
353        """Test that exporting a flow rewrites references between exported objects
354        as !KeyOf tags instead of raw primary keys"""
355        flow_slug = generate_id()
356        stage_name = generate_id()
357        policy_name = generate_id()
358        with transaction_rollback():
359            flow_policy = ExpressionPolicy.objects.create(
360                name=policy_name,
361                expression="return True",
362            )
363            flow = Flow.objects.create(
364                slug=flow_slug,
365                designation=FlowDesignation.AUTHENTICATION,
366                name=generate_id(),
367                title=generate_id(),
368            )
369            PolicyBinding.objects.create(policy=flow_policy, target=flow, order=0)
370
371            user_login = UserLoginStage.objects.create(name=stage_name)
372            fsb = FlowStageBinding.objects.create(target=flow, stage=user_login, order=0)
373            PolicyBinding.objects.create(policy=flow_policy, target=fsb, order=0)
374
375            exporter = FlowExporter(flow)
376            export = exporter.export()
377            export_yaml = exporter.export_to_string()
378
379        entries_by_model = {}
380        for entry in export.entries:
381            entries_by_model.setdefault(entry.model, []).append(entry)
382
383        flow_entry = entries_by_model["authentik_flows.flow"][0]
384        stage_entry = entries_by_model["authentik_stages_user_login.userloginstage"][0]
385        stage_binding_entry = entries_by_model["authentik_flows.flowstagebinding"][0]
386        policy_entry = entries_by_model["authentik_policies_expression.expressionpolicy"][0]
387        policy_binding_entries = entries_by_model["authentik_policies.policybinding"]
388
389        self.assertIsNotNone(flow_entry.id)
390        self.assertIsNotNone(stage_entry.id)
391        # ids are derived from a readable, unique, non-UUID field (slug/name) when available,
392        # rather than an opaque counter
393        self.assertEqual(flow_entry.id, f"flow-{slugify(flow_slug)}")
394        self.assertEqual(stage_entry.id, f"userloginstage-{slugify(stage_name)}")
395
396        # Policy is exported without any explicit extra identifiers, but its unique,
397        # non-UUID `name` field is still picked up automatically as a stable identifier
398        self.assertEqual(policy_entry.identifiers.get("name"), policy_name)
399        # The primary key is instance-local and not portable, so it must not be used as
400        # an identifier whenever a stable identifier could be found instead
401        for entry in (flow_entry, stage_entry, policy_entry):
402            self.assertNotIn("pk", entry.identifiers)
403
404        self.assertIsInstance(stage_binding_entry.identifiers["target"], KeyOf)
405        self.assertEqual(stage_binding_entry.identifiers["target"].id_from, flow_entry.id)
406        self.assertIsInstance(stage_binding_entry.identifiers["stage"], KeyOf)
407        self.assertEqual(stage_binding_entry.identifiers["stage"].id_from, stage_entry.id)
408
409        binding_targets = {pb.identifiers["target"].id_from for pb in policy_binding_entries}
410        self.assertIn(flow_entry.id, binding_targets)
411        self.assertIn(stage_binding_entry.id, binding_targets)
412        for policy_binding_entry in policy_binding_entries:
413            self.assertIsInstance(policy_binding_entry.identifiers["policy"], KeyOf)
414            self.assertEqual(policy_binding_entry.identifiers["policy"].id_from, policy_entry.id)
415
416        self.assertIn("!KeyOf", export_yaml)
417
418        importer = Importer.from_string(export_yaml)
419        self.assertTrue(importer.validate()[0])
420        self.assertTrue(importer.apply())
421        self.assertTrue(Flow.objects.filter(slug=flow_slug).exists())

Test that exporting a flow rewrites references between exported objects as !KeyOf tags instead of raw primary keys

def test_export_default_blueprints_no_static_identifiers(self):
423    def test_export_default_blueprints_no_static_identifiers(self):
424        """Test that exporting a full instance after applying all default blueprints
425        never falls back to an opaque, non-portable `pk` identifier, e.g. for models
426        such as FlowStageBinding that have no unique text field of their own"""
427        for blueprint_file in sorted(Path("blueprints/default").glob("*.yaml")):
428            rel_path = str(blueprint_file.relative_to("blueprints"))
429            importer = Importer.from_string(BlueprintInstance(path=rel_path).retrieve())
430            self.assertTrue(importer.validate()[0])
431            self.assertTrue(importer.apply())
432
433        export = Exporter().export()
434        for entry in export.entries:
435            self.assertNotIn(
436                "pk", entry.identifiers, f"{entry.model} entry has a static pk identifier"
437            )

Test that exporting a full instance after applying all default blueprints never falls back to an opaque, non-portable pk identifier, e.g. for models such as FlowStageBinding that have no unique text field of their own

def test_export_validate_import_prompt(self):
439    def test_export_validate_import_prompt(self):
440        """Test export and validate it"""
441        with transaction_rollback():
442            # First stage fields
443            username_prompt = Prompt.objects.create(
444                name=generate_id(),
445                field_key="username",
446                label="Username",
447                order=0,
448                type=FieldTypes.TEXT,
449            )
450            password = Prompt.objects.create(
451                name=generate_id(),
452                field_key="password",
453                label="Password",
454                order=1,
455                type=FieldTypes.PASSWORD,
456            )
457            password_repeat = Prompt.objects.create(
458                name=generate_id(),
459                field_key="password_repeat",
460                label="Password (repeat)",
461                order=2,
462                type=FieldTypes.PASSWORD,
463            )
464
465            # Stages
466            first_stage = PromptStage.objects.create(name=generate_id())
467            first_stage.fields.set([username_prompt, password, password_repeat])
468            first_stage.save()
469
470            flow = Flow.objects.create(
471                name=generate_id(),
472                slug=generate_id(),
473                designation=FlowDesignation.ENROLLMENT,
474                title=generate_id(),
475            )
476
477            FlowStageBinding.objects.create(target=flow, stage=first_stage, order=0)
478
479            exporter = FlowExporter(flow)
480            export_yaml = exporter.export_to_string()
481
482        importer = Importer.from_string(export_yaml)
483
484        self.assertTrue(importer.validate()[0])
485        self.assertTrue(importer.apply())

Test export and validate it