authentik.blueprints.tests.test_v1_api

Test blueprints v1 api

  1"""Test blueprints v1 api"""
  2
  3from json import dumps, loads
  4from tempfile import NamedTemporaryFile, mkdtemp
  5
  6from django.core.files.uploadedfile import SimpleUploadedFile
  7from django.urls import reverse
  8from rest_framework.test import APITestCase
  9from yaml import dump
 10
 11from authentik.core.tests.utils import create_test_admin_user
 12from authentik.flows.models import Flow
 13from authentik.lib.config import CONFIG
 14from authentik.lib.generators import generate_id
 15from authentik.providers.oauth2.models import ScopeMapping
 16from authentik.stages.invitation.models import InvitationStage
 17from authentik.stages.user_write.models import UserWriteStage
 18
 19TMP = mkdtemp("authentik-blueprints")
 20
 21
 22class TestBlueprintsV1API(APITestCase):
 23    """Test Blueprints API"""
 24
 25    def setUp(self) -> None:
 26        self.user = create_test_admin_user()
 27        self.client.force_login(self.user)
 28
 29    @CONFIG.patch("blueprints_dir", TMP)
 30    def test_api_available(self):
 31        """Test valid file"""
 32        with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
 33            file.write(
 34                dump(
 35                    {
 36                        "version": 1,
 37                        "entries": [],
 38                    }
 39                )
 40            )
 41            file.flush()
 42            res = self.client.get(reverse("authentik_api:blueprintinstance-available"))
 43            self.assertEqual(res.status_code, 200)
 44            response = loads(res.content.decode())
 45            self.assertEqual(len(response), 1)
 46            self.assertEqual(
 47                response[0]["hash"],
 48                (
 49                    "e52bb445b03cd36057258dc9f0ce0fbed8278498ee1470e45315293e5f026d1bd1f9b352"
 50                    "6871c0003f5c07be5c3316d9d4a08444bd8fed1b3f03294e51e44522"
 51                ),
 52            )
 53
 54    def test_api_oci(self):
 55        """Test validation with OCI path"""
 56        res = self.client.post(
 57            reverse("authentik_api:blueprintinstance-list"),
 58            data={"name": "foo", "path": "oci://foo/bar"},
 59        )
 60        self.assertEqual(res.status_code, 201)
 61
 62    def test_api_blank(self):
 63        """Test blank"""
 64        res = self.client.post(
 65            reverse("authentik_api:blueprintinstance-list"),
 66            data={
 67                "name": "foo",
 68            },
 69        )
 70        self.assertEqual(res.status_code, 400)
 71        self.assertJSONEqual(
 72            res.content.decode(), {"non_field_errors": ["Either path or content must be set."]}
 73        )
 74
 75    def test_api_content(self):
 76        """Test blank"""
 77        res = self.client.post(
 78            reverse("authentik_api:blueprintinstance-list"),
 79            data={
 80                "name": "foo",
 81                "content": '{"version": 3}',
 82            },
 83        )
 84        self.assertEqual(res.status_code, 400)
 85        self.assertJSONEqual(
 86            res.content.decode(),
 87            {"content": ["Failed to validate blueprint", "- Invalid blueprint version"]},
 88        )
 89
 90    def test_api_import_with_context(self):
 91        """Test that the import endpoint applies the supplied context to the real blueprint"""
 92        slug = f"invitation-enrollment-{generate_id()}"
 93        flow_name = f"Invitation Enrollment {generate_id()}"
 94        stage_name = f"invitation-stage-{generate_id()}"
 95        user_type = "internal"
 96        continue_without_invitation = True
 97
 98        res = self.client.post(
 99            reverse("authentik_api:blueprintinstance-import"),
100            data={
101                "path": "example/flows-invitation-enrollment-minimal.yaml",
102                "context": dumps(
103                    {
104                        "flow_slug": slug,
105                        "flow_name": flow_name,
106                        "stage_name": stage_name,
107                        "continue_flow_without_invitation": continue_without_invitation,
108                        "user_type": user_type,
109                    }
110                ),
111            },
112            format="multipart",
113        )
114        self.assertEqual(res.status_code, 200)
115        self.assertTrue(res.json()["success"])
116        self.assertTrue(res.json()["imported"])
117
118        flow = Flow.objects.get(slug=slug)
119        self.assertEqual(flow.name, flow_name)
120        self.assertEqual(flow.title, flow_name)
121
122        invitation_stage = InvitationStage.objects.get(name=stage_name)
123        self.assertEqual(
124            invitation_stage.continue_flow_without_invitation,
125            continue_without_invitation,
126        )
127
128        user_write_stage = UserWriteStage.objects.get(
129            name=f"invitation-enrollment-user-write-{slug}"
130        )
131        self.assertEqual(user_write_stage.user_type, user_type)
132        self.assertEqual(user_write_stage.user_path_template, f"users/{user_type}")
133
134    def test_api_import_blank_path(self):
135        """Validator returns empty path unchanged (covers api.py:53)."""
136        with NamedTemporaryFile(mode="w+", suffix=".yaml") as file:
137            file.write(dump({"version": 1, "entries": []}))
138            file.flush()
139            file.seek(0)
140            res = self.client.post(
141                reverse("authentik_api:blueprintinstance-import"),
142                data={"path": "", "file": file},
143                format="multipart",
144            )
145        self.assertEqual(res.status_code, 200)
146
147    def test_api_import_invalid_blueprint_returns_result_payload(self):
148        """Invalid blueprint content returns a result payload instead of a 400 response."""
149        file = SimpleUploadedFile("invalid-blueprint.yaml", b'{"version": 3}')
150
151        res = self.client.post(
152            reverse("authentik_api:blueprintinstance-import"),
153            data={"file": file},
154            format="multipart",
155        )
156
157        self.assertEqual(res.status_code, 200)
158        self.assertFalse(res.json()["success"])
159        self.assertFalse(res.json()["imported"])
160        self.assertGreater(len(res.json()["logs"]), 0)
161
162    def test_api_import_invalid_blueprint_with_yaml_tag_returns_result_payload(self):
163        """An invalid entry that still holds a raw YAML tag (e.g. !KeyOf) must return
164        a result payload, not crash while sanitizing the logged entry."""
165        content = """
166            version: 1
167            entries:
168              - model: authentik_providers_oauth2.scopemapping
169                id: sm
170                identifiers: { scope_name: test-tag-scope }
171                attrs:
172                  name: test-tag-scope
173                  scope_name: test-tag-scope
174                  expression: "return {}"
175              - model: authentik_providers_oauth2.oauth2provider
176                id: provider
177                identifiers: { client_id: test-tag }
178                attrs:
179                  name: test-tag
180                  client_id: test-tag
181                  property_mappings:
182                    - !KeyOf sm
183        """
184        file = SimpleUploadedFile("invalid-blueprint-tag.yaml", content.encode())
185
186        res = self.client.post(
187            reverse("authentik_api:blueprintinstance-import"),
188            data={"file": file},
189            format="multipart",
190        )
191
192        self.assertEqual(res.status_code, 200)
193        self.assertFalse(res.json()["success"])
194        self.assertFalse(res.json()["imported"])
195        self.assertGreater(len(res.json()["logs"]), 0)
196
197    def test_api_import_unknown_path(self):
198        """Path not in available blueprints is rejected (covers api.py:56)."""
199        res = self.client.post(
200            reverse("authentik_api:blueprintinstance-import"),
201            data={"path": "does/not/exist.yaml"},
202            format="multipart",
203        )
204        self.assertEqual(res.status_code, 400)
205        self.assertIn("Blueprint file does not exist", res.content.decode())
206
207    def test_api_import_blank_context(self):
208        """Blank context is normalized to empty dict (covers api.py:62)."""
209        res = self.client.post(
210            reverse("authentik_api:blueprintinstance-import"),
211            data={
212                "path": "example/flows-invitation-enrollment-minimal.yaml",
213                "context": "",
214            },
215            format="multipart",
216        )
217        self.assertEqual(res.status_code, 200)
218
219    def test_api_import_invalid_json_context(self):
220        """Malformed JSON context raises ValidationError (covers api.py:65-66)."""
221        res = self.client.post(
222            reverse("authentik_api:blueprintinstance-import"),
223            data={
224                "path": "example/flows-invitation-enrollment-minimal.yaml",
225                "context": "{not json",
226            },
227            format="multipart",
228        )
229        self.assertEqual(res.status_code, 400)
230        self.assertIn("Context must be valid JSON", res.content.decode())
231
232    def test_api_import_non_object_context(self):
233        """JSON context that isn't an object is rejected (covers api.py:68)."""
234        res = self.client.post(
235            reverse("authentik_api:blueprintinstance-import"),
236            data={
237                "path": "example/flows-invitation-enrollment-minimal.yaml",
238                "context": "[1, 2, 3]",
239            },
240            format="multipart",
241        )
242        self.assertEqual(res.status_code, 400)
243        self.assertIn("Context must be a JSON object", res.content.decode())
244
245    def test_api_validate(self):
246        """Test that the import endpoint applies the supplied context to the real blueprint"""
247        content = """
248            version: 1
249            entries:
250              - model: authentik_providers_oauth2.scopemapping
251                id: sm
252                identifiers: { scope_name: test-tag-scope }
253                attrs:
254                  name: test-tag-scope
255                  scope_name: test-tag-scope
256                  expression: "return {}"
257        """
258        file = SimpleUploadedFile("test.yaml", content.encode())
259
260        res = self.client.post(
261            reverse("authentik_api:blueprintinstance-validate"),
262            data={"file": file},
263            format="multipart",
264        )
265
266        self.assertEqual(res.status_code, 200)
267        self.assertTrue(res.json()["success"])
268        self.assertFalse(res.json()["imported"])
269        self.assertFalse(ScopeMapping.objects.filter(scope_name="test-tag-scope"))
TMP = '/tmp/tmp_om3211tauthentik-blueprints'
class TestBlueprintsV1API(rest_framework.test.APITestCase):
 23class TestBlueprintsV1API(APITestCase):
 24    """Test Blueprints API"""
 25
 26    def setUp(self) -> None:
 27        self.user = create_test_admin_user()
 28        self.client.force_login(self.user)
 29
 30    @CONFIG.patch("blueprints_dir", TMP)
 31    def test_api_available(self):
 32        """Test valid file"""
 33        with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
 34            file.write(
 35                dump(
 36                    {
 37                        "version": 1,
 38                        "entries": [],
 39                    }
 40                )
 41            )
 42            file.flush()
 43            res = self.client.get(reverse("authentik_api:blueprintinstance-available"))
 44            self.assertEqual(res.status_code, 200)
 45            response = loads(res.content.decode())
 46            self.assertEqual(len(response), 1)
 47            self.assertEqual(
 48                response[0]["hash"],
 49                (
 50                    "e52bb445b03cd36057258dc9f0ce0fbed8278498ee1470e45315293e5f026d1bd1f9b352"
 51                    "6871c0003f5c07be5c3316d9d4a08444bd8fed1b3f03294e51e44522"
 52                ),
 53            )
 54
 55    def test_api_oci(self):
 56        """Test validation with OCI path"""
 57        res = self.client.post(
 58            reverse("authentik_api:blueprintinstance-list"),
 59            data={"name": "foo", "path": "oci://foo/bar"},
 60        )
 61        self.assertEqual(res.status_code, 201)
 62
 63    def test_api_blank(self):
 64        """Test blank"""
 65        res = self.client.post(
 66            reverse("authentik_api:blueprintinstance-list"),
 67            data={
 68                "name": "foo",
 69            },
 70        )
 71        self.assertEqual(res.status_code, 400)
 72        self.assertJSONEqual(
 73            res.content.decode(), {"non_field_errors": ["Either path or content must be set."]}
 74        )
 75
 76    def test_api_content(self):
 77        """Test blank"""
 78        res = self.client.post(
 79            reverse("authentik_api:blueprintinstance-list"),
 80            data={
 81                "name": "foo",
 82                "content": '{"version": 3}',
 83            },
 84        )
 85        self.assertEqual(res.status_code, 400)
 86        self.assertJSONEqual(
 87            res.content.decode(),
 88            {"content": ["Failed to validate blueprint", "- Invalid blueprint version"]},
 89        )
 90
 91    def test_api_import_with_context(self):
 92        """Test that the import endpoint applies the supplied context to the real blueprint"""
 93        slug = f"invitation-enrollment-{generate_id()}"
 94        flow_name = f"Invitation Enrollment {generate_id()}"
 95        stage_name = f"invitation-stage-{generate_id()}"
 96        user_type = "internal"
 97        continue_without_invitation = True
 98
 99        res = self.client.post(
100            reverse("authentik_api:blueprintinstance-import"),
101            data={
102                "path": "example/flows-invitation-enrollment-minimal.yaml",
103                "context": dumps(
104                    {
105                        "flow_slug": slug,
106                        "flow_name": flow_name,
107                        "stage_name": stage_name,
108                        "continue_flow_without_invitation": continue_without_invitation,
109                        "user_type": user_type,
110                    }
111                ),
112            },
113            format="multipart",
114        )
115        self.assertEqual(res.status_code, 200)
116        self.assertTrue(res.json()["success"])
117        self.assertTrue(res.json()["imported"])
118
119        flow = Flow.objects.get(slug=slug)
120        self.assertEqual(flow.name, flow_name)
121        self.assertEqual(flow.title, flow_name)
122
123        invitation_stage = InvitationStage.objects.get(name=stage_name)
124        self.assertEqual(
125            invitation_stage.continue_flow_without_invitation,
126            continue_without_invitation,
127        )
128
129        user_write_stage = UserWriteStage.objects.get(
130            name=f"invitation-enrollment-user-write-{slug}"
131        )
132        self.assertEqual(user_write_stage.user_type, user_type)
133        self.assertEqual(user_write_stage.user_path_template, f"users/{user_type}")
134
135    def test_api_import_blank_path(self):
136        """Validator returns empty path unchanged (covers api.py:53)."""
137        with NamedTemporaryFile(mode="w+", suffix=".yaml") as file:
138            file.write(dump({"version": 1, "entries": []}))
139            file.flush()
140            file.seek(0)
141            res = self.client.post(
142                reverse("authentik_api:blueprintinstance-import"),
143                data={"path": "", "file": file},
144                format="multipart",
145            )
146        self.assertEqual(res.status_code, 200)
147
148    def test_api_import_invalid_blueprint_returns_result_payload(self):
149        """Invalid blueprint content returns a result payload instead of a 400 response."""
150        file = SimpleUploadedFile("invalid-blueprint.yaml", b'{"version": 3}')
151
152        res = self.client.post(
153            reverse("authentik_api:blueprintinstance-import"),
154            data={"file": file},
155            format="multipart",
156        )
157
158        self.assertEqual(res.status_code, 200)
159        self.assertFalse(res.json()["success"])
160        self.assertFalse(res.json()["imported"])
161        self.assertGreater(len(res.json()["logs"]), 0)
162
163    def test_api_import_invalid_blueprint_with_yaml_tag_returns_result_payload(self):
164        """An invalid entry that still holds a raw YAML tag (e.g. !KeyOf) must return
165        a result payload, not crash while sanitizing the logged entry."""
166        content = """
167            version: 1
168            entries:
169              - model: authentik_providers_oauth2.scopemapping
170                id: sm
171                identifiers: { scope_name: test-tag-scope }
172                attrs:
173                  name: test-tag-scope
174                  scope_name: test-tag-scope
175                  expression: "return {}"
176              - model: authentik_providers_oauth2.oauth2provider
177                id: provider
178                identifiers: { client_id: test-tag }
179                attrs:
180                  name: test-tag
181                  client_id: test-tag
182                  property_mappings:
183                    - !KeyOf sm
184        """
185        file = SimpleUploadedFile("invalid-blueprint-tag.yaml", content.encode())
186
187        res = self.client.post(
188            reverse("authentik_api:blueprintinstance-import"),
189            data={"file": file},
190            format="multipart",
191        )
192
193        self.assertEqual(res.status_code, 200)
194        self.assertFalse(res.json()["success"])
195        self.assertFalse(res.json()["imported"])
196        self.assertGreater(len(res.json()["logs"]), 0)
197
198    def test_api_import_unknown_path(self):
199        """Path not in available blueprints is rejected (covers api.py:56)."""
200        res = self.client.post(
201            reverse("authentik_api:blueprintinstance-import"),
202            data={"path": "does/not/exist.yaml"},
203            format="multipart",
204        )
205        self.assertEqual(res.status_code, 400)
206        self.assertIn("Blueprint file does not exist", res.content.decode())
207
208    def test_api_import_blank_context(self):
209        """Blank context is normalized to empty dict (covers api.py:62)."""
210        res = self.client.post(
211            reverse("authentik_api:blueprintinstance-import"),
212            data={
213                "path": "example/flows-invitation-enrollment-minimal.yaml",
214                "context": "",
215            },
216            format="multipart",
217        )
218        self.assertEqual(res.status_code, 200)
219
220    def test_api_import_invalid_json_context(self):
221        """Malformed JSON context raises ValidationError (covers api.py:65-66)."""
222        res = self.client.post(
223            reverse("authentik_api:blueprintinstance-import"),
224            data={
225                "path": "example/flows-invitation-enrollment-minimal.yaml",
226                "context": "{not json",
227            },
228            format="multipart",
229        )
230        self.assertEqual(res.status_code, 400)
231        self.assertIn("Context must be valid JSON", res.content.decode())
232
233    def test_api_import_non_object_context(self):
234        """JSON context that isn't an object is rejected (covers api.py:68)."""
235        res = self.client.post(
236            reverse("authentik_api:blueprintinstance-import"),
237            data={
238                "path": "example/flows-invitation-enrollment-minimal.yaml",
239                "context": "[1, 2, 3]",
240            },
241            format="multipart",
242        )
243        self.assertEqual(res.status_code, 400)
244        self.assertIn("Context must be a JSON object", res.content.decode())
245
246    def test_api_validate(self):
247        """Test that the import endpoint applies the supplied context to the real blueprint"""
248        content = """
249            version: 1
250            entries:
251              - model: authentik_providers_oauth2.scopemapping
252                id: sm
253                identifiers: { scope_name: test-tag-scope }
254                attrs:
255                  name: test-tag-scope
256                  scope_name: test-tag-scope
257                  expression: "return {}"
258        """
259        file = SimpleUploadedFile("test.yaml", content.encode())
260
261        res = self.client.post(
262            reverse("authentik_api:blueprintinstance-validate"),
263            data={"file": file},
264            format="multipart",
265        )
266
267        self.assertEqual(res.status_code, 200)
268        self.assertTrue(res.json()["success"])
269        self.assertFalse(res.json()["imported"])
270        self.assertFalse(ScopeMapping.objects.filter(scope_name="test-tag-scope"))

Test Blueprints API

def setUp(self) -> None:
26    def setUp(self) -> None:
27        self.user = create_test_admin_user()
28        self.client.force_login(self.user)

Hook method for setting up the test fixture before exercising it.

@CONFIG.patch('blueprints_dir', TMP)
def test_api_available(self):
30    @CONFIG.patch("blueprints_dir", TMP)
31    def test_api_available(self):
32        """Test valid file"""
33        with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
34            file.write(
35                dump(
36                    {
37                        "version": 1,
38                        "entries": [],
39                    }
40                )
41            )
42            file.flush()
43            res = self.client.get(reverse("authentik_api:blueprintinstance-available"))
44            self.assertEqual(res.status_code, 200)
45            response = loads(res.content.decode())
46            self.assertEqual(len(response), 1)
47            self.assertEqual(
48                response[0]["hash"],
49                (
50                    "e52bb445b03cd36057258dc9f0ce0fbed8278498ee1470e45315293e5f026d1bd1f9b352"
51                    "6871c0003f5c07be5c3316d9d4a08444bd8fed1b3f03294e51e44522"
52                ),
53            )

Test valid file

def test_api_oci(self):
55    def test_api_oci(self):
56        """Test validation with OCI path"""
57        res = self.client.post(
58            reverse("authentik_api:blueprintinstance-list"),
59            data={"name": "foo", "path": "oci://foo/bar"},
60        )
61        self.assertEqual(res.status_code, 201)

Test validation with OCI path

def test_api_blank(self):
63    def test_api_blank(self):
64        """Test blank"""
65        res = self.client.post(
66            reverse("authentik_api:blueprintinstance-list"),
67            data={
68                "name": "foo",
69            },
70        )
71        self.assertEqual(res.status_code, 400)
72        self.assertJSONEqual(
73            res.content.decode(), {"non_field_errors": ["Either path or content must be set."]}
74        )

Test blank

def test_api_content(self):
76    def test_api_content(self):
77        """Test blank"""
78        res = self.client.post(
79            reverse("authentik_api:blueprintinstance-list"),
80            data={
81                "name": "foo",
82                "content": '{"version": 3}',
83            },
84        )
85        self.assertEqual(res.status_code, 400)
86        self.assertJSONEqual(
87            res.content.decode(),
88            {"content": ["Failed to validate blueprint", "- Invalid blueprint version"]},
89        )

Test blank

def test_api_import_with_context(self):
 91    def test_api_import_with_context(self):
 92        """Test that the import endpoint applies the supplied context to the real blueprint"""
 93        slug = f"invitation-enrollment-{generate_id()}"
 94        flow_name = f"Invitation Enrollment {generate_id()}"
 95        stage_name = f"invitation-stage-{generate_id()}"
 96        user_type = "internal"
 97        continue_without_invitation = True
 98
 99        res = self.client.post(
100            reverse("authentik_api:blueprintinstance-import"),
101            data={
102                "path": "example/flows-invitation-enrollment-minimal.yaml",
103                "context": dumps(
104                    {
105                        "flow_slug": slug,
106                        "flow_name": flow_name,
107                        "stage_name": stage_name,
108                        "continue_flow_without_invitation": continue_without_invitation,
109                        "user_type": user_type,
110                    }
111                ),
112            },
113            format="multipart",
114        )
115        self.assertEqual(res.status_code, 200)
116        self.assertTrue(res.json()["success"])
117        self.assertTrue(res.json()["imported"])
118
119        flow = Flow.objects.get(slug=slug)
120        self.assertEqual(flow.name, flow_name)
121        self.assertEqual(flow.title, flow_name)
122
123        invitation_stage = InvitationStage.objects.get(name=stage_name)
124        self.assertEqual(
125            invitation_stage.continue_flow_without_invitation,
126            continue_without_invitation,
127        )
128
129        user_write_stage = UserWriteStage.objects.get(
130            name=f"invitation-enrollment-user-write-{slug}"
131        )
132        self.assertEqual(user_write_stage.user_type, user_type)
133        self.assertEqual(user_write_stage.user_path_template, f"users/{user_type}")

Test that the import endpoint applies the supplied context to the real blueprint

def test_api_import_blank_path(self):
135    def test_api_import_blank_path(self):
136        """Validator returns empty path unchanged (covers api.py:53)."""
137        with NamedTemporaryFile(mode="w+", suffix=".yaml") as file:
138            file.write(dump({"version": 1, "entries": []}))
139            file.flush()
140            file.seek(0)
141            res = self.client.post(
142                reverse("authentik_api:blueprintinstance-import"),
143                data={"path": "", "file": file},
144                format="multipart",
145            )
146        self.assertEqual(res.status_code, 200)

Validator returns empty path unchanged (covers api.py:53).

def test_api_import_invalid_blueprint_returns_result_payload(self):
148    def test_api_import_invalid_blueprint_returns_result_payload(self):
149        """Invalid blueprint content returns a result payload instead of a 400 response."""
150        file = SimpleUploadedFile("invalid-blueprint.yaml", b'{"version": 3}')
151
152        res = self.client.post(
153            reverse("authentik_api:blueprintinstance-import"),
154            data={"file": file},
155            format="multipart",
156        )
157
158        self.assertEqual(res.status_code, 200)
159        self.assertFalse(res.json()["success"])
160        self.assertFalse(res.json()["imported"])
161        self.assertGreater(len(res.json()["logs"]), 0)

Invalid blueprint content returns a result payload instead of a 400 response.

def test_api_import_invalid_blueprint_with_yaml_tag_returns_result_payload(self):
163    def test_api_import_invalid_blueprint_with_yaml_tag_returns_result_payload(self):
164        """An invalid entry that still holds a raw YAML tag (e.g. !KeyOf) must return
165        a result payload, not crash while sanitizing the logged entry."""
166        content = """
167            version: 1
168            entries:
169              - model: authentik_providers_oauth2.scopemapping
170                id: sm
171                identifiers: { scope_name: test-tag-scope }
172                attrs:
173                  name: test-tag-scope
174                  scope_name: test-tag-scope
175                  expression: "return {}"
176              - model: authentik_providers_oauth2.oauth2provider
177                id: provider
178                identifiers: { client_id: test-tag }
179                attrs:
180                  name: test-tag
181                  client_id: test-tag
182                  property_mappings:
183                    - !KeyOf sm
184        """
185        file = SimpleUploadedFile("invalid-blueprint-tag.yaml", content.encode())
186
187        res = self.client.post(
188            reverse("authentik_api:blueprintinstance-import"),
189            data={"file": file},
190            format="multipart",
191        )
192
193        self.assertEqual(res.status_code, 200)
194        self.assertFalse(res.json()["success"])
195        self.assertFalse(res.json()["imported"])
196        self.assertGreater(len(res.json()["logs"]), 0)

An invalid entry that still holds a raw YAML tag (e.g. !KeyOf) must return a result payload, not crash while sanitizing the logged entry.

def test_api_import_unknown_path(self):
198    def test_api_import_unknown_path(self):
199        """Path not in available blueprints is rejected (covers api.py:56)."""
200        res = self.client.post(
201            reverse("authentik_api:blueprintinstance-import"),
202            data={"path": "does/not/exist.yaml"},
203            format="multipart",
204        )
205        self.assertEqual(res.status_code, 400)
206        self.assertIn("Blueprint file does not exist", res.content.decode())

Path not in available blueprints is rejected (covers api.py:56).

def test_api_import_blank_context(self):
208    def test_api_import_blank_context(self):
209        """Blank context is normalized to empty dict (covers api.py:62)."""
210        res = self.client.post(
211            reverse("authentik_api:blueprintinstance-import"),
212            data={
213                "path": "example/flows-invitation-enrollment-minimal.yaml",
214                "context": "",
215            },
216            format="multipart",
217        )
218        self.assertEqual(res.status_code, 200)

Blank context is normalized to empty dict (covers api.py:62).

def test_api_import_invalid_json_context(self):
220    def test_api_import_invalid_json_context(self):
221        """Malformed JSON context raises ValidationError (covers api.py:65-66)."""
222        res = self.client.post(
223            reverse("authentik_api:blueprintinstance-import"),
224            data={
225                "path": "example/flows-invitation-enrollment-minimal.yaml",
226                "context": "{not json",
227            },
228            format="multipart",
229        )
230        self.assertEqual(res.status_code, 400)
231        self.assertIn("Context must be valid JSON", res.content.decode())

Malformed JSON context raises ValidationError (covers api.py:65-66).

def test_api_import_non_object_context(self):
233    def test_api_import_non_object_context(self):
234        """JSON context that isn't an object is rejected (covers api.py:68)."""
235        res = self.client.post(
236            reverse("authentik_api:blueprintinstance-import"),
237            data={
238                "path": "example/flows-invitation-enrollment-minimal.yaml",
239                "context": "[1, 2, 3]",
240            },
241            format="multipart",
242        )
243        self.assertEqual(res.status_code, 400)
244        self.assertIn("Context must be a JSON object", res.content.decode())

JSON context that isn't an object is rejected (covers api.py:68).

def test_api_validate(self):
246    def test_api_validate(self):
247        """Test that the import endpoint applies the supplied context to the real blueprint"""
248        content = """
249            version: 1
250            entries:
251              - model: authentik_providers_oauth2.scopemapping
252                id: sm
253                identifiers: { scope_name: test-tag-scope }
254                attrs:
255                  name: test-tag-scope
256                  scope_name: test-tag-scope
257                  expression: "return {}"
258        """
259        file = SimpleUploadedFile("test.yaml", content.encode())
260
261        res = self.client.post(
262            reverse("authentik_api:blueprintinstance-validate"),
263            data={"file": file},
264            format="multipart",
265        )
266
267        self.assertEqual(res.status_code, 200)
268        self.assertTrue(res.json()["success"])
269        self.assertFalse(res.json()["imported"])
270        self.assertFalse(ScopeMapping.objects.filter(scope_name="test-tag-scope"))

Test that the import endpoint applies the supplied context to the real blueprint