authentik.blueprints.tests.test_v1_tasks

Test blueprints v1 tasks

  1"""Test blueprints v1 tasks"""
  2
  3from hashlib import sha512
  4from pathlib import Path
  5from tempfile import NamedTemporaryFile, mkdtemp
  6from unittest.mock import patch
  7
  8from django.test import TransactionTestCase
  9from django.utils.crypto import salted_hmac
 10from yaml import dump
 11
 12from authentik.blueprints.models import BlueprintInstance, BlueprintInstanceStatus
 13from authentik.blueprints.v1.tasks import apply_blueprint, blueprints_discovery, blueprints_find
 14from authentik.lib.config import CONFIG
 15from authentik.lib.generators import generate_id
 16
 17TMP = mkdtemp("authentik-blueprints")
 18
 19
 20class TestBlueprintsV1Tasks(TransactionTestCase):
 21    """Test Blueprints v1 Tasks"""
 22
 23    @CONFIG.patch("blueprints_dir", TMP)
 24    def test_invalid_file_syntax(self):
 25        """Test syntactically invalid file"""
 26        with NamedTemporaryFile(suffix=".yaml", dir=TMP) as file:
 27            file.write(b"{")
 28            file.flush()
 29            blueprints = blueprints_find()
 30            self.assertEqual(blueprints, [])
 31
 32    @CONFIG.patch("blueprints_dir", TMP)
 33    def test_invalid_file_version(self):
 34        """Test invalid file"""
 35        with NamedTemporaryFile(suffix=".yaml", dir=TMP) as file:
 36            file.write(b"version: 2")
 37            file.flush()
 38            blueprints = blueprints_find()
 39            self.assertEqual(blueprints, [])
 40
 41    @CONFIG.patch("blueprints_dir", TMP)
 42    def test_valid(self):
 43        """Test valid file"""
 44        blueprint_id = generate_id()
 45        with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
 46            file.write(
 47                dump(
 48                    {
 49                        "version": 1,
 50                        "entries": [],
 51                        "metadata": {
 52                            "name": blueprint_id,
 53                        },
 54                    }
 55                )
 56            )
 57            file.seek(0)
 58            file_hash = sha512(file.read().encode()).hexdigest()
 59            file.flush()
 60            blueprints_discovery.send()
 61            instance = BlueprintInstance.objects.filter(name=blueprint_id).first()
 62            self.assertEqual(instance.last_applied_hash, file_hash)
 63            self.assertEqual(
 64                instance.metadata,
 65                {
 66                    "name": blueprint_id,
 67                    "labels": {},
 68                },
 69            )
 70
 71    @CONFIG.patch("blueprints_dir", TMP)
 72    def test_valid_updated(self):
 73        """Test valid file"""
 74        BlueprintInstance.objects.filter(name="foo").delete()
 75        with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
 76            file.write(
 77                dump(
 78                    {
 79                        "version": 1,
 80                        "entries": [],
 81                        "metadata": {
 82                            "name": "foo",
 83                        },
 84                    }
 85                )
 86            )
 87            file.flush()
 88            blueprints_discovery.send()
 89            blueprint = BlueprintInstance.objects.filter(name="foo").first()
 90            self.assertEqual(
 91                blueprint.last_applied_hash,
 92                (
 93                    "b86ec439b3857350714f070d2833490e736d9155d3d97b2cac13f3b352223e5a"
 94                    "1adbf8ec56fa616d46090cc4773ff9e46c4e509fde96b97de87dd21fa329ca1a"
 95                ),
 96            )
 97            self.assertEqual(blueprint.metadata, {"labels": {}, "name": "foo"})
 98            file.write(
 99                dump(
100                    {
101                        "version": 1,
102                        "entries": [],
103                        "metadata": {
104                            "name": "foo",
105                            "labels": {
106                                "foo": "bar",
107                            },
108                        },
109                    }
110                )
111            )
112            file.flush()
113            blueprints_discovery.send()
114            blueprint.refresh_from_db()
115            self.assertEqual(
116                blueprint.last_applied_hash,
117                (
118                    "87b68b10131d2c9751ed308bba38f04734b9e2cdf8532ed617bc52979b063c49"
119                    "2564f33f3d20ab9d5f0fd9e6eb77a13942e060199f147789cb7afab9690e72b5"
120                ),
121            )
122            self.assertEqual(
123                blueprint.metadata,
124                {
125                    "name": "foo",
126                    "labels": {"foo": "bar"},
127                },
128            )
129
130    @CONFIG.patch("blueprints_dir", TMP)
131    def test_valid_updated_external_values(self):
132        """Test that changing only an `!Env` or `!File` value reapplies the blueprint"""
133        name = generate_id()
134        env_key = f"AUTHENTIK_TEST_{generate_id().upper()}"
135        with (
136            NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file,
137            NamedTemporaryFile(mode="w+") as value_file,
138            patch.dict("os.environ", {env_key: "foo"}),
139        ):
140            value_file.write("foo")
141            value_file.flush()
142            content = (
143                "version: 1\n"
144                f"metadata:\n  name: {name}\n"
145                f"context:\n  env: !Env {env_key}\n  file: !File {value_file.name}\n"
146                "entries: []\n"
147            )
148            file.write(content)
149            file.flush()
150            blueprints_discovery.send()
151            instance = BlueprintInstance.objects.get(name=name)
152            first_hash = instance.last_applied_hash
153            self.assertNotEqual(first_hash, sha512(content.encode()).hexdigest())
154
155            # Unchanged values don't reapply
156            blueprints_discovery.send()
157            instance.refresh_from_db()
158            self.assertEqual(instance.last_applied_hash, first_hash)
159
160            with patch.dict("os.environ", {env_key: "bar"}):
161                blueprints_discovery.send()
162            instance.refresh_from_db()
163            env_hash = instance.last_applied_hash
164            self.assertNotEqual(env_hash, first_hash)
165
166            value_file.seek(0)
167            value_file.write("bar")
168            value_file.flush()
169            blueprints_discovery.send()
170            instance.refresh_from_db()
171            self.assertNotIn(instance.last_applied_hash, [first_hash, env_hash])
172
173    @CONFIG.patch("blueprints_dir", TMP)
174    def test_valid_disabled(self):
175        """Test valid file"""
176        with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
177            file.write(
178                dump(
179                    {
180                        "version": 1,
181                        "entries": [],
182                    }
183                )
184            )
185            file.flush()
186            instance: BlueprintInstance = BlueprintInstance.objects.create(
187                name=generate_id(),
188                path=file.name,
189                enabled=False,
190                status=BlueprintInstanceStatus.UNKNOWN,
191            )
192            instance.refresh_from_db()
193            self.assertEqual(instance.last_applied_hash, "")
194            self.assertEqual(
195                instance.status,
196                BlueprintInstanceStatus.UNKNOWN,
197            )
198            apply_blueprint.send(instance.pk).get_result(block=True)
199            instance.refresh_from_db()
200            self.assertEqual(instance.last_applied_hash, "")
201            self.assertEqual(
202                instance.status,
203                BlueprintInstanceStatus.UNKNOWN,
204            )
205
206    @CONFIG.patch("blueprints_dir", TMP)
207    def test_valid_crlf(self):
208        """Test discovered hash matches the applied hash for a file with CRLF line endings"""
209        blueprint_id = generate_id()
210        with NamedTemporaryFile(suffix=".yaml", dir=TMP) as file:
211            file.write(
212                f"version: 1\r\nentries: []\r\nmetadata:\r\n  name: {blueprint_id}\r\n".encode()
213            )
214            file.flush()
215            file_hash = sha512(Path(file.name).read_text(encoding="utf-8").encode()).hexdigest()
216            for _ in range(2):
217                blueprints_discovery.send()
218                instance = BlueprintInstance.objects.filter(name=blueprint_id).first()
219                self.assertEqual(instance.status, BlueprintInstanceStatus.SUCCESSFUL)
220                found = next(
221                    found for found in blueprints_find() if found.path == Path(file.name).name
222                )
223                self.assertEqual(found.hash, file_hash)
224                self.assertEqual(instance.last_applied_hash, found.hash)
225            file.seek(0)
226            self.assertIn(b"\r\n", file.read())
227
228    def write_blueprint(self, file, value: str):
229        file.seek(0)
230        file.truncate()
231        file.write(f"version: 1\nentries: []\ncontext:\n  secret: {value}\n")
232        file.flush()
233        return next(found for found in blueprints_find() if found.path == Path(file.name).name).hash
234
235    def write_secret(self, file, value: str):
236        file.seek(0)
237        file.truncate()
238        file.write(value)
239        file.flush()
240
241    @CONFIG.patch("blueprints_dir", TMP)
242    def test_file_tag_content_changed(self):
243        """Test hash changes when the contents of a referenced `!File` change"""
244        with NamedTemporaryFile(mode="w+", dir=TMP) as secret:
245            for label, reference in (
246                ("direct", f"!File {secret.name}"),
247                ("argument of another tag", f'!Format ["client-%s", !File {secret.name}]'),
248                ("reached through a cycle", f"&anchor [*anchor, !File {secret.name}]"),
249                ("reached through an alias", f"&anchor [!File {secret.name}]\n  other: *anchor"),
250            ):
251                with (
252                    self.subTest(label),
253                    NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file,
254                ):
255                    self.write_secret(secret, "initial")
256                    before = self.write_blueprint(file, reference)
257                    self.write_secret(secret, "rotated")
258                    self.assertNotEqual(before, self.write_blueprint(file, reference))
259
260    @CONFIG.patch("blueprints_dir", TMP)
261    def test_file_tag_created(self):
262        """Test hash changes when a referenced `!File` that was missing appears"""
263        with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
264            secret_path = Path(TMP) / generate_id()
265            reference = f"!File {secret_path}"
266            before = self.write_blueprint(file, reference)
267            secret_path.write_text("created")
268            try:
269                after = self.write_blueprint(file, reference)
270            finally:
271                secret_path.unlink()
272            self.assertNotEqual(before, after)
273
274    @CONFIG.patch("blueprints_dir", TMP)
275    def test_file_tag_removed(self):
276        """Test hash changes when a referenced `!File` that existed disappears"""
277        with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
278            secret_path = Path(TMP) / generate_id()
279            secret_path.write_text("present")
280            reference = f"!File {secret_path}"
281            try:
282                before = self.write_blueprint(file, reference)
283            finally:
284                secret_path.unlink()
285            self.assertNotEqual(before, self.write_blueprint(file, reference))
286
287    @CONFIG.patch("blueprints_dir", TMP)
288    def test_file_tag_contents_swapped(self):
289        """Test hash changes when two referenced `!File`s exchange their contents"""
290        with (
291            NamedTemporaryFile(mode="w+", dir=TMP) as first,
292            NamedTemporaryFile(mode="w+", dir=TMP) as second,
293        ):
294            self.write_secret(first, "alpha")
295            self.write_secret(second, "beta")
296            with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
297                reference = f"[!File {first.name}, !File {second.name}]"
298                before = self.write_blueprint(file, reference)
299                self.write_secret(first, "beta")
300                self.write_secret(second, "alpha")
301                self.assertNotEqual(before, self.write_blueprint(file, reference))
302
303    @CONFIG.patch("blueprints_dir", TMP)
304    def test_file_tag_missing_and_readable_swapped(self):
305        """Test hash changes when one referenced `!File` disappears as another appears
306        with the same contents"""
307        first = Path(TMP) / generate_id()
308        second = Path(TMP) / generate_id()
309        with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
310            reference = f"[!File {first}, !File {second}]"
311            second.write_text("shared")
312            try:
313                before = self.write_blueprint(file, reference)
314            finally:
315                second.unlink()
316            first.write_text("shared")
317            try:
318                after = self.write_blueprint(file, reference)
319            finally:
320                first.unlink()
321            self.assertNotEqual(before, after)
322
323    @CONFIG.patch("blueprints_dir", TMP)
324    def test_file_tag_hashed_once_per_route(self):
325        """Test a referenced `!File` is folded into the hash once for each route to it"""
326        with NamedTemporaryFile(mode="w+", dir=TMP) as secret:
327            self.write_secret(secret, "initial")
328            for label, reference, routes in (
329                ("cycle", f"&anchor [*anchor, !File {secret.name}]", 1),
330                ("alias", f"&anchor [!File {secret.name}]\n  other: *anchor", 2),
331            ):
332                with (
333                    self.subTest(label),
334                    NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file,
335                ):
336                    content = f"version: 1\nentries: []\ncontext:\n  secret: {reference}\n"
337                    expected = sha512(content.encode())
338                    expected.update(
339                        salted_hmac(
340                            "goauthentik.io/blueprints/v1/external-values",
341                            sha512(b"initial").digest() * routes,
342                            algorithm="sha512",
343                        ).digest()
344                    )
345                    self.assertEqual(self.write_blueprint(file, reference), expected.hexdigest())
346
347    @CONFIG.patch("blueprints_dir", TMP)
348    def test_file_tag_content_unchanged(self):
349        """Test hash is stable when a referenced `!File` does not change"""
350        with NamedTemporaryFile(mode="w+", dir=TMP) as secret:
351            self.write_secret(secret, "initial")
352            with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
353                reference = f"!File {secret.name}"
354                self.assertEqual(
355                    self.write_blueprint(file, reference),
356                    self.write_blueprint(file, reference),
357                )
358
359    @CONFIG.patch("blueprints_dir", TMP)
360    def test_file_tag_unreadable_hash_stable(self):
361        """Test hash is stable when a referenced `!File` cannot be read"""
362        for label, reference in (
363            ("missing file", f"!File {Path(TMP) / generate_id()}"),
364            ("path from a tag", f'!File [!Env [{generate_id()}, "{TMP}/fallback"], "default"]'),
365            ("path from a mapping", f'!File {{path: "{TMP}/fallback"}}'),
366            ("path no syscall can take", '!File "\\0"'),
367            ("deeply nested", "[" * 50 + f'!File "{TMP}/fallback"' + "]" * 50),
368        ):
369            with (
370                self.subTest(label),
371                NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file,
372            ):
373                self.assertEqual(
374                    self.write_blueprint(file, reference),
375                    self.write_blueprint(file, reference),
376                )
377
378    @CONFIG.patch("blueprints_dir", TMP)
379    def test_file_tag_unreadable_discovery_continues(self):
380        """Test a blueprint that cannot be hashed does not stop others being discovered"""
381        for label, reference in (
382            ("path from a mapping", f'!File {{path: "{TMP}/fallback"}}'),
383            ("path no syscall can take", '!File "\\0"'),
384            ("path outside the filesystem encoding", '!File "\\ud800"'),
385            ("env key with a null byte", '!Env "\\0"'),
386            ("env key outside the filesystem encoding", '!Env "\\ud800"'),
387            ("sequence containing itself", "&anchor [*anchor]"),
388            ("mapping containing itself", "&anchor {key: *anchor}"),
389            ("two anchors containing each other", "&outer [{inner: &inner [*outer]}, *inner]"),
390        ):
391            with (
392                self.subTest(label),
393                NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as broken,
394                NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as healthy,
395            ):
396                broken.write(f"version: 1\nentries: []\ncontext:\n  secret: {reference}\n")
397                broken.flush()
398                healthy.write(f"version: 1\nentries: []\nmetadata:\n  name: {generate_id()}\n")
399                healthy.flush()
400                found = [blueprint.path for blueprint in blueprints_find()]
401                self.assertIn(Path(healthy.name).name, found)
402                self.assertIn(Path(broken.name).name, found)
403
404    @CONFIG.patch("blueprints_dir", TMP)
405    def test_file_tag_applied_on_change(self):
406        """Test blueprint is re-applied when the contents of a referenced `!File` change"""
407        blueprint_id = generate_id()
408        with NamedTemporaryFile(mode="w+", dir=TMP) as secret:
409            self.write_secret(secret, "initial")
410            with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
411                file.write(
412                    f"version: 1\nentries: []\n"
413                    f"metadata:\n  name: {blueprint_id}\n"
414                    f"context:\n  secret: !File {secret.name}\n"
415                )
416                file.flush()
417                blueprints_discovery.send()
418                instance = BlueprintInstance.objects.filter(name=blueprint_id).first()
419                before = instance.last_applied_hash
420                self.assertEqual(instance.status, BlueprintInstanceStatus.SUCCESSFUL)
421                self.write_secret(secret, "rotated")
422                blueprints_discovery.send()
423                instance.refresh_from_db()
424                self.assertNotEqual(instance.last_applied_hash, before)
TMP = '/tmp/tmp_njehgwmauthentik-blueprints'
class TestBlueprintsV1Tasks(django.test.testcases.TransactionTestCase):
 21class TestBlueprintsV1Tasks(TransactionTestCase):
 22    """Test Blueprints v1 Tasks"""
 23
 24    @CONFIG.patch("blueprints_dir", TMP)
 25    def test_invalid_file_syntax(self):
 26        """Test syntactically invalid file"""
 27        with NamedTemporaryFile(suffix=".yaml", dir=TMP) as file:
 28            file.write(b"{")
 29            file.flush()
 30            blueprints = blueprints_find()
 31            self.assertEqual(blueprints, [])
 32
 33    @CONFIG.patch("blueprints_dir", TMP)
 34    def test_invalid_file_version(self):
 35        """Test invalid file"""
 36        with NamedTemporaryFile(suffix=".yaml", dir=TMP) as file:
 37            file.write(b"version: 2")
 38            file.flush()
 39            blueprints = blueprints_find()
 40            self.assertEqual(blueprints, [])
 41
 42    @CONFIG.patch("blueprints_dir", TMP)
 43    def test_valid(self):
 44        """Test valid file"""
 45        blueprint_id = generate_id()
 46        with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
 47            file.write(
 48                dump(
 49                    {
 50                        "version": 1,
 51                        "entries": [],
 52                        "metadata": {
 53                            "name": blueprint_id,
 54                        },
 55                    }
 56                )
 57            )
 58            file.seek(0)
 59            file_hash = sha512(file.read().encode()).hexdigest()
 60            file.flush()
 61            blueprints_discovery.send()
 62            instance = BlueprintInstance.objects.filter(name=blueprint_id).first()
 63            self.assertEqual(instance.last_applied_hash, file_hash)
 64            self.assertEqual(
 65                instance.metadata,
 66                {
 67                    "name": blueprint_id,
 68                    "labels": {},
 69                },
 70            )
 71
 72    @CONFIG.patch("blueprints_dir", TMP)
 73    def test_valid_updated(self):
 74        """Test valid file"""
 75        BlueprintInstance.objects.filter(name="foo").delete()
 76        with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
 77            file.write(
 78                dump(
 79                    {
 80                        "version": 1,
 81                        "entries": [],
 82                        "metadata": {
 83                            "name": "foo",
 84                        },
 85                    }
 86                )
 87            )
 88            file.flush()
 89            blueprints_discovery.send()
 90            blueprint = BlueprintInstance.objects.filter(name="foo").first()
 91            self.assertEqual(
 92                blueprint.last_applied_hash,
 93                (
 94                    "b86ec439b3857350714f070d2833490e736d9155d3d97b2cac13f3b352223e5a"
 95                    "1adbf8ec56fa616d46090cc4773ff9e46c4e509fde96b97de87dd21fa329ca1a"
 96                ),
 97            )
 98            self.assertEqual(blueprint.metadata, {"labels": {}, "name": "foo"})
 99            file.write(
100                dump(
101                    {
102                        "version": 1,
103                        "entries": [],
104                        "metadata": {
105                            "name": "foo",
106                            "labels": {
107                                "foo": "bar",
108                            },
109                        },
110                    }
111                )
112            )
113            file.flush()
114            blueprints_discovery.send()
115            blueprint.refresh_from_db()
116            self.assertEqual(
117                blueprint.last_applied_hash,
118                (
119                    "87b68b10131d2c9751ed308bba38f04734b9e2cdf8532ed617bc52979b063c49"
120                    "2564f33f3d20ab9d5f0fd9e6eb77a13942e060199f147789cb7afab9690e72b5"
121                ),
122            )
123            self.assertEqual(
124                blueprint.metadata,
125                {
126                    "name": "foo",
127                    "labels": {"foo": "bar"},
128                },
129            )
130
131    @CONFIG.patch("blueprints_dir", TMP)
132    def test_valid_updated_external_values(self):
133        """Test that changing only an `!Env` or `!File` value reapplies the blueprint"""
134        name = generate_id()
135        env_key = f"AUTHENTIK_TEST_{generate_id().upper()}"
136        with (
137            NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file,
138            NamedTemporaryFile(mode="w+") as value_file,
139            patch.dict("os.environ", {env_key: "foo"}),
140        ):
141            value_file.write("foo")
142            value_file.flush()
143            content = (
144                "version: 1\n"
145                f"metadata:\n  name: {name}\n"
146                f"context:\n  env: !Env {env_key}\n  file: !File {value_file.name}\n"
147                "entries: []\n"
148            )
149            file.write(content)
150            file.flush()
151            blueprints_discovery.send()
152            instance = BlueprintInstance.objects.get(name=name)
153            first_hash = instance.last_applied_hash
154            self.assertNotEqual(first_hash, sha512(content.encode()).hexdigest())
155
156            # Unchanged values don't reapply
157            blueprints_discovery.send()
158            instance.refresh_from_db()
159            self.assertEqual(instance.last_applied_hash, first_hash)
160
161            with patch.dict("os.environ", {env_key: "bar"}):
162                blueprints_discovery.send()
163            instance.refresh_from_db()
164            env_hash = instance.last_applied_hash
165            self.assertNotEqual(env_hash, first_hash)
166
167            value_file.seek(0)
168            value_file.write("bar")
169            value_file.flush()
170            blueprints_discovery.send()
171            instance.refresh_from_db()
172            self.assertNotIn(instance.last_applied_hash, [first_hash, env_hash])
173
174    @CONFIG.patch("blueprints_dir", TMP)
175    def test_valid_disabled(self):
176        """Test valid file"""
177        with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
178            file.write(
179                dump(
180                    {
181                        "version": 1,
182                        "entries": [],
183                    }
184                )
185            )
186            file.flush()
187            instance: BlueprintInstance = BlueprintInstance.objects.create(
188                name=generate_id(),
189                path=file.name,
190                enabled=False,
191                status=BlueprintInstanceStatus.UNKNOWN,
192            )
193            instance.refresh_from_db()
194            self.assertEqual(instance.last_applied_hash, "")
195            self.assertEqual(
196                instance.status,
197                BlueprintInstanceStatus.UNKNOWN,
198            )
199            apply_blueprint.send(instance.pk).get_result(block=True)
200            instance.refresh_from_db()
201            self.assertEqual(instance.last_applied_hash, "")
202            self.assertEqual(
203                instance.status,
204                BlueprintInstanceStatus.UNKNOWN,
205            )
206
207    @CONFIG.patch("blueprints_dir", TMP)
208    def test_valid_crlf(self):
209        """Test discovered hash matches the applied hash for a file with CRLF line endings"""
210        blueprint_id = generate_id()
211        with NamedTemporaryFile(suffix=".yaml", dir=TMP) as file:
212            file.write(
213                f"version: 1\r\nentries: []\r\nmetadata:\r\n  name: {blueprint_id}\r\n".encode()
214            )
215            file.flush()
216            file_hash = sha512(Path(file.name).read_text(encoding="utf-8").encode()).hexdigest()
217            for _ in range(2):
218                blueprints_discovery.send()
219                instance = BlueprintInstance.objects.filter(name=blueprint_id).first()
220                self.assertEqual(instance.status, BlueprintInstanceStatus.SUCCESSFUL)
221                found = next(
222                    found for found in blueprints_find() if found.path == Path(file.name).name
223                )
224                self.assertEqual(found.hash, file_hash)
225                self.assertEqual(instance.last_applied_hash, found.hash)
226            file.seek(0)
227            self.assertIn(b"\r\n", file.read())
228
229    def write_blueprint(self, file, value: str):
230        file.seek(0)
231        file.truncate()
232        file.write(f"version: 1\nentries: []\ncontext:\n  secret: {value}\n")
233        file.flush()
234        return next(found for found in blueprints_find() if found.path == Path(file.name).name).hash
235
236    def write_secret(self, file, value: str):
237        file.seek(0)
238        file.truncate()
239        file.write(value)
240        file.flush()
241
242    @CONFIG.patch("blueprints_dir", TMP)
243    def test_file_tag_content_changed(self):
244        """Test hash changes when the contents of a referenced `!File` change"""
245        with NamedTemporaryFile(mode="w+", dir=TMP) as secret:
246            for label, reference in (
247                ("direct", f"!File {secret.name}"),
248                ("argument of another tag", f'!Format ["client-%s", !File {secret.name}]'),
249                ("reached through a cycle", f"&anchor [*anchor, !File {secret.name}]"),
250                ("reached through an alias", f"&anchor [!File {secret.name}]\n  other: *anchor"),
251            ):
252                with (
253                    self.subTest(label),
254                    NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file,
255                ):
256                    self.write_secret(secret, "initial")
257                    before = self.write_blueprint(file, reference)
258                    self.write_secret(secret, "rotated")
259                    self.assertNotEqual(before, self.write_blueprint(file, reference))
260
261    @CONFIG.patch("blueprints_dir", TMP)
262    def test_file_tag_created(self):
263        """Test hash changes when a referenced `!File` that was missing appears"""
264        with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
265            secret_path = Path(TMP) / generate_id()
266            reference = f"!File {secret_path}"
267            before = self.write_blueprint(file, reference)
268            secret_path.write_text("created")
269            try:
270                after = self.write_blueprint(file, reference)
271            finally:
272                secret_path.unlink()
273            self.assertNotEqual(before, after)
274
275    @CONFIG.patch("blueprints_dir", TMP)
276    def test_file_tag_removed(self):
277        """Test hash changes when a referenced `!File` that existed disappears"""
278        with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
279            secret_path = Path(TMP) / generate_id()
280            secret_path.write_text("present")
281            reference = f"!File {secret_path}"
282            try:
283                before = self.write_blueprint(file, reference)
284            finally:
285                secret_path.unlink()
286            self.assertNotEqual(before, self.write_blueprint(file, reference))
287
288    @CONFIG.patch("blueprints_dir", TMP)
289    def test_file_tag_contents_swapped(self):
290        """Test hash changes when two referenced `!File`s exchange their contents"""
291        with (
292            NamedTemporaryFile(mode="w+", dir=TMP) as first,
293            NamedTemporaryFile(mode="w+", dir=TMP) as second,
294        ):
295            self.write_secret(first, "alpha")
296            self.write_secret(second, "beta")
297            with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
298                reference = f"[!File {first.name}, !File {second.name}]"
299                before = self.write_blueprint(file, reference)
300                self.write_secret(first, "beta")
301                self.write_secret(second, "alpha")
302                self.assertNotEqual(before, self.write_blueprint(file, reference))
303
304    @CONFIG.patch("blueprints_dir", TMP)
305    def test_file_tag_missing_and_readable_swapped(self):
306        """Test hash changes when one referenced `!File` disappears as another appears
307        with the same contents"""
308        first = Path(TMP) / generate_id()
309        second = Path(TMP) / generate_id()
310        with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
311            reference = f"[!File {first}, !File {second}]"
312            second.write_text("shared")
313            try:
314                before = self.write_blueprint(file, reference)
315            finally:
316                second.unlink()
317            first.write_text("shared")
318            try:
319                after = self.write_blueprint(file, reference)
320            finally:
321                first.unlink()
322            self.assertNotEqual(before, after)
323
324    @CONFIG.patch("blueprints_dir", TMP)
325    def test_file_tag_hashed_once_per_route(self):
326        """Test a referenced `!File` is folded into the hash once for each route to it"""
327        with NamedTemporaryFile(mode="w+", dir=TMP) as secret:
328            self.write_secret(secret, "initial")
329            for label, reference, routes in (
330                ("cycle", f"&anchor [*anchor, !File {secret.name}]", 1),
331                ("alias", f"&anchor [!File {secret.name}]\n  other: *anchor", 2),
332            ):
333                with (
334                    self.subTest(label),
335                    NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file,
336                ):
337                    content = f"version: 1\nentries: []\ncontext:\n  secret: {reference}\n"
338                    expected = sha512(content.encode())
339                    expected.update(
340                        salted_hmac(
341                            "goauthentik.io/blueprints/v1/external-values",
342                            sha512(b"initial").digest() * routes,
343                            algorithm="sha512",
344                        ).digest()
345                    )
346                    self.assertEqual(self.write_blueprint(file, reference), expected.hexdigest())
347
348    @CONFIG.patch("blueprints_dir", TMP)
349    def test_file_tag_content_unchanged(self):
350        """Test hash is stable when a referenced `!File` does not change"""
351        with NamedTemporaryFile(mode="w+", dir=TMP) as secret:
352            self.write_secret(secret, "initial")
353            with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
354                reference = f"!File {secret.name}"
355                self.assertEqual(
356                    self.write_blueprint(file, reference),
357                    self.write_blueprint(file, reference),
358                )
359
360    @CONFIG.patch("blueprints_dir", TMP)
361    def test_file_tag_unreadable_hash_stable(self):
362        """Test hash is stable when a referenced `!File` cannot be read"""
363        for label, reference in (
364            ("missing file", f"!File {Path(TMP) / generate_id()}"),
365            ("path from a tag", f'!File [!Env [{generate_id()}, "{TMP}/fallback"], "default"]'),
366            ("path from a mapping", f'!File {{path: "{TMP}/fallback"}}'),
367            ("path no syscall can take", '!File "\\0"'),
368            ("deeply nested", "[" * 50 + f'!File "{TMP}/fallback"' + "]" * 50),
369        ):
370            with (
371                self.subTest(label),
372                NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file,
373            ):
374                self.assertEqual(
375                    self.write_blueprint(file, reference),
376                    self.write_blueprint(file, reference),
377                )
378
379    @CONFIG.patch("blueprints_dir", TMP)
380    def test_file_tag_unreadable_discovery_continues(self):
381        """Test a blueprint that cannot be hashed does not stop others being discovered"""
382        for label, reference in (
383            ("path from a mapping", f'!File {{path: "{TMP}/fallback"}}'),
384            ("path no syscall can take", '!File "\\0"'),
385            ("path outside the filesystem encoding", '!File "\\ud800"'),
386            ("env key with a null byte", '!Env "\\0"'),
387            ("env key outside the filesystem encoding", '!Env "\\ud800"'),
388            ("sequence containing itself", "&anchor [*anchor]"),
389            ("mapping containing itself", "&anchor {key: *anchor}"),
390            ("two anchors containing each other", "&outer [{inner: &inner [*outer]}, *inner]"),
391        ):
392            with (
393                self.subTest(label),
394                NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as broken,
395                NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as healthy,
396            ):
397                broken.write(f"version: 1\nentries: []\ncontext:\n  secret: {reference}\n")
398                broken.flush()
399                healthy.write(f"version: 1\nentries: []\nmetadata:\n  name: {generate_id()}\n")
400                healthy.flush()
401                found = [blueprint.path for blueprint in blueprints_find()]
402                self.assertIn(Path(healthy.name).name, found)
403                self.assertIn(Path(broken.name).name, found)
404
405    @CONFIG.patch("blueprints_dir", TMP)
406    def test_file_tag_applied_on_change(self):
407        """Test blueprint is re-applied when the contents of a referenced `!File` change"""
408        blueprint_id = generate_id()
409        with NamedTemporaryFile(mode="w+", dir=TMP) as secret:
410            self.write_secret(secret, "initial")
411            with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
412                file.write(
413                    f"version: 1\nentries: []\n"
414                    f"metadata:\n  name: {blueprint_id}\n"
415                    f"context:\n  secret: !File {secret.name}\n"
416                )
417                file.flush()
418                blueprints_discovery.send()
419                instance = BlueprintInstance.objects.filter(name=blueprint_id).first()
420                before = instance.last_applied_hash
421                self.assertEqual(instance.status, BlueprintInstanceStatus.SUCCESSFUL)
422                self.write_secret(secret, "rotated")
423                blueprints_discovery.send()
424                instance.refresh_from_db()
425                self.assertNotEqual(instance.last_applied_hash, before)

Test Blueprints v1 Tasks

@CONFIG.patch('blueprints_dir', TMP)
def test_invalid_file_syntax(self):
24    @CONFIG.patch("blueprints_dir", TMP)
25    def test_invalid_file_syntax(self):
26        """Test syntactically invalid file"""
27        with NamedTemporaryFile(suffix=".yaml", dir=TMP) as file:
28            file.write(b"{")
29            file.flush()
30            blueprints = blueprints_find()
31            self.assertEqual(blueprints, [])

Test syntactically invalid file

@CONFIG.patch('blueprints_dir', TMP)
def test_invalid_file_version(self):
33    @CONFIG.patch("blueprints_dir", TMP)
34    def test_invalid_file_version(self):
35        """Test invalid file"""
36        with NamedTemporaryFile(suffix=".yaml", dir=TMP) as file:
37            file.write(b"version: 2")
38            file.flush()
39            blueprints = blueprints_find()
40            self.assertEqual(blueprints, [])

Test invalid file

@CONFIG.patch('blueprints_dir', TMP)
def test_valid(self):
42    @CONFIG.patch("blueprints_dir", TMP)
43    def test_valid(self):
44        """Test valid file"""
45        blueprint_id = generate_id()
46        with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
47            file.write(
48                dump(
49                    {
50                        "version": 1,
51                        "entries": [],
52                        "metadata": {
53                            "name": blueprint_id,
54                        },
55                    }
56                )
57            )
58            file.seek(0)
59            file_hash = sha512(file.read().encode()).hexdigest()
60            file.flush()
61            blueprints_discovery.send()
62            instance = BlueprintInstance.objects.filter(name=blueprint_id).first()
63            self.assertEqual(instance.last_applied_hash, file_hash)
64            self.assertEqual(
65                instance.metadata,
66                {
67                    "name": blueprint_id,
68                    "labels": {},
69                },
70            )

Test valid file

@CONFIG.patch('blueprints_dir', TMP)
def test_valid_updated(self):
 72    @CONFIG.patch("blueprints_dir", TMP)
 73    def test_valid_updated(self):
 74        """Test valid file"""
 75        BlueprintInstance.objects.filter(name="foo").delete()
 76        with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
 77            file.write(
 78                dump(
 79                    {
 80                        "version": 1,
 81                        "entries": [],
 82                        "metadata": {
 83                            "name": "foo",
 84                        },
 85                    }
 86                )
 87            )
 88            file.flush()
 89            blueprints_discovery.send()
 90            blueprint = BlueprintInstance.objects.filter(name="foo").first()
 91            self.assertEqual(
 92                blueprint.last_applied_hash,
 93                (
 94                    "b86ec439b3857350714f070d2833490e736d9155d3d97b2cac13f3b352223e5a"
 95                    "1adbf8ec56fa616d46090cc4773ff9e46c4e509fde96b97de87dd21fa329ca1a"
 96                ),
 97            )
 98            self.assertEqual(blueprint.metadata, {"labels": {}, "name": "foo"})
 99            file.write(
100                dump(
101                    {
102                        "version": 1,
103                        "entries": [],
104                        "metadata": {
105                            "name": "foo",
106                            "labels": {
107                                "foo": "bar",
108                            },
109                        },
110                    }
111                )
112            )
113            file.flush()
114            blueprints_discovery.send()
115            blueprint.refresh_from_db()
116            self.assertEqual(
117                blueprint.last_applied_hash,
118                (
119                    "87b68b10131d2c9751ed308bba38f04734b9e2cdf8532ed617bc52979b063c49"
120                    "2564f33f3d20ab9d5f0fd9e6eb77a13942e060199f147789cb7afab9690e72b5"
121                ),
122            )
123            self.assertEqual(
124                blueprint.metadata,
125                {
126                    "name": "foo",
127                    "labels": {"foo": "bar"},
128                },
129            )

Test valid file

@CONFIG.patch('blueprints_dir', TMP)
def test_valid_updated_external_values(self):
131    @CONFIG.patch("blueprints_dir", TMP)
132    def test_valid_updated_external_values(self):
133        """Test that changing only an `!Env` or `!File` value reapplies the blueprint"""
134        name = generate_id()
135        env_key = f"AUTHENTIK_TEST_{generate_id().upper()}"
136        with (
137            NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file,
138            NamedTemporaryFile(mode="w+") as value_file,
139            patch.dict("os.environ", {env_key: "foo"}),
140        ):
141            value_file.write("foo")
142            value_file.flush()
143            content = (
144                "version: 1\n"
145                f"metadata:\n  name: {name}\n"
146                f"context:\n  env: !Env {env_key}\n  file: !File {value_file.name}\n"
147                "entries: []\n"
148            )
149            file.write(content)
150            file.flush()
151            blueprints_discovery.send()
152            instance = BlueprintInstance.objects.get(name=name)
153            first_hash = instance.last_applied_hash
154            self.assertNotEqual(first_hash, sha512(content.encode()).hexdigest())
155
156            # Unchanged values don't reapply
157            blueprints_discovery.send()
158            instance.refresh_from_db()
159            self.assertEqual(instance.last_applied_hash, first_hash)
160
161            with patch.dict("os.environ", {env_key: "bar"}):
162                blueprints_discovery.send()
163            instance.refresh_from_db()
164            env_hash = instance.last_applied_hash
165            self.assertNotEqual(env_hash, first_hash)
166
167            value_file.seek(0)
168            value_file.write("bar")
169            value_file.flush()
170            blueprints_discovery.send()
171            instance.refresh_from_db()
172            self.assertNotIn(instance.last_applied_hash, [first_hash, env_hash])

Test that changing only an !Env or !File value reapplies the blueprint

@CONFIG.patch('blueprints_dir', TMP)
def test_valid_disabled(self):
174    @CONFIG.patch("blueprints_dir", TMP)
175    def test_valid_disabled(self):
176        """Test valid file"""
177        with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
178            file.write(
179                dump(
180                    {
181                        "version": 1,
182                        "entries": [],
183                    }
184                )
185            )
186            file.flush()
187            instance: BlueprintInstance = BlueprintInstance.objects.create(
188                name=generate_id(),
189                path=file.name,
190                enabled=False,
191                status=BlueprintInstanceStatus.UNKNOWN,
192            )
193            instance.refresh_from_db()
194            self.assertEqual(instance.last_applied_hash, "")
195            self.assertEqual(
196                instance.status,
197                BlueprintInstanceStatus.UNKNOWN,
198            )
199            apply_blueprint.send(instance.pk).get_result(block=True)
200            instance.refresh_from_db()
201            self.assertEqual(instance.last_applied_hash, "")
202            self.assertEqual(
203                instance.status,
204                BlueprintInstanceStatus.UNKNOWN,
205            )

Test valid file

@CONFIG.patch('blueprints_dir', TMP)
def test_valid_crlf(self):
207    @CONFIG.patch("blueprints_dir", TMP)
208    def test_valid_crlf(self):
209        """Test discovered hash matches the applied hash for a file with CRLF line endings"""
210        blueprint_id = generate_id()
211        with NamedTemporaryFile(suffix=".yaml", dir=TMP) as file:
212            file.write(
213                f"version: 1\r\nentries: []\r\nmetadata:\r\n  name: {blueprint_id}\r\n".encode()
214            )
215            file.flush()
216            file_hash = sha512(Path(file.name).read_text(encoding="utf-8").encode()).hexdigest()
217            for _ in range(2):
218                blueprints_discovery.send()
219                instance = BlueprintInstance.objects.filter(name=blueprint_id).first()
220                self.assertEqual(instance.status, BlueprintInstanceStatus.SUCCESSFUL)
221                found = next(
222                    found for found in blueprints_find() if found.path == Path(file.name).name
223                )
224                self.assertEqual(found.hash, file_hash)
225                self.assertEqual(instance.last_applied_hash, found.hash)
226            file.seek(0)
227            self.assertIn(b"\r\n", file.read())

Test discovered hash matches the applied hash for a file with CRLF line endings

def write_blueprint(self, file, value: str):
229    def write_blueprint(self, file, value: str):
230        file.seek(0)
231        file.truncate()
232        file.write(f"version: 1\nentries: []\ncontext:\n  secret: {value}\n")
233        file.flush()
234        return next(found for found in blueprints_find() if found.path == Path(file.name).name).hash
def write_secret(self, file, value: str):
236    def write_secret(self, file, value: str):
237        file.seek(0)
238        file.truncate()
239        file.write(value)
240        file.flush()
@CONFIG.patch('blueprints_dir', TMP)
def test_file_tag_content_changed(self):
242    @CONFIG.patch("blueprints_dir", TMP)
243    def test_file_tag_content_changed(self):
244        """Test hash changes when the contents of a referenced `!File` change"""
245        with NamedTemporaryFile(mode="w+", dir=TMP) as secret:
246            for label, reference in (
247                ("direct", f"!File {secret.name}"),
248                ("argument of another tag", f'!Format ["client-%s", !File {secret.name}]'),
249                ("reached through a cycle", f"&anchor [*anchor, !File {secret.name}]"),
250                ("reached through an alias", f"&anchor [!File {secret.name}]\n  other: *anchor"),
251            ):
252                with (
253                    self.subTest(label),
254                    NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file,
255                ):
256                    self.write_secret(secret, "initial")
257                    before = self.write_blueprint(file, reference)
258                    self.write_secret(secret, "rotated")
259                    self.assertNotEqual(before, self.write_blueprint(file, reference))

Test hash changes when the contents of a referenced !File change

@CONFIG.patch('blueprints_dir', TMP)
def test_file_tag_created(self):
261    @CONFIG.patch("blueprints_dir", TMP)
262    def test_file_tag_created(self):
263        """Test hash changes when a referenced `!File` that was missing appears"""
264        with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
265            secret_path = Path(TMP) / generate_id()
266            reference = f"!File {secret_path}"
267            before = self.write_blueprint(file, reference)
268            secret_path.write_text("created")
269            try:
270                after = self.write_blueprint(file, reference)
271            finally:
272                secret_path.unlink()
273            self.assertNotEqual(before, after)

Test hash changes when a referenced !File that was missing appears

@CONFIG.patch('blueprints_dir', TMP)
def test_file_tag_removed(self):
275    @CONFIG.patch("blueprints_dir", TMP)
276    def test_file_tag_removed(self):
277        """Test hash changes when a referenced `!File` that existed disappears"""
278        with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
279            secret_path = Path(TMP) / generate_id()
280            secret_path.write_text("present")
281            reference = f"!File {secret_path}"
282            try:
283                before = self.write_blueprint(file, reference)
284            finally:
285                secret_path.unlink()
286            self.assertNotEqual(before, self.write_blueprint(file, reference))

Test hash changes when a referenced !File that existed disappears

@CONFIG.patch('blueprints_dir', TMP)
def test_file_tag_contents_swapped(self):
288    @CONFIG.patch("blueprints_dir", TMP)
289    def test_file_tag_contents_swapped(self):
290        """Test hash changes when two referenced `!File`s exchange their contents"""
291        with (
292            NamedTemporaryFile(mode="w+", dir=TMP) as first,
293            NamedTemporaryFile(mode="w+", dir=TMP) as second,
294        ):
295            self.write_secret(first, "alpha")
296            self.write_secret(second, "beta")
297            with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
298                reference = f"[!File {first.name}, !File {second.name}]"
299                before = self.write_blueprint(file, reference)
300                self.write_secret(first, "beta")
301                self.write_secret(second, "alpha")
302                self.assertNotEqual(before, self.write_blueprint(file, reference))

Test hash changes when two referenced !Files exchange their contents

@CONFIG.patch('blueprints_dir', TMP)
def test_file_tag_missing_and_readable_swapped(self):
304    @CONFIG.patch("blueprints_dir", TMP)
305    def test_file_tag_missing_and_readable_swapped(self):
306        """Test hash changes when one referenced `!File` disappears as another appears
307        with the same contents"""
308        first = Path(TMP) / generate_id()
309        second = Path(TMP) / generate_id()
310        with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
311            reference = f"[!File {first}, !File {second}]"
312            second.write_text("shared")
313            try:
314                before = self.write_blueprint(file, reference)
315            finally:
316                second.unlink()
317            first.write_text("shared")
318            try:
319                after = self.write_blueprint(file, reference)
320            finally:
321                first.unlink()
322            self.assertNotEqual(before, after)

Test hash changes when one referenced !File disappears as another appears with the same contents

@CONFIG.patch('blueprints_dir', TMP)
def test_file_tag_hashed_once_per_route(self):
324    @CONFIG.patch("blueprints_dir", TMP)
325    def test_file_tag_hashed_once_per_route(self):
326        """Test a referenced `!File` is folded into the hash once for each route to it"""
327        with NamedTemporaryFile(mode="w+", dir=TMP) as secret:
328            self.write_secret(secret, "initial")
329            for label, reference, routes in (
330                ("cycle", f"&anchor [*anchor, !File {secret.name}]", 1),
331                ("alias", f"&anchor [!File {secret.name}]\n  other: *anchor", 2),
332            ):
333                with (
334                    self.subTest(label),
335                    NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file,
336                ):
337                    content = f"version: 1\nentries: []\ncontext:\n  secret: {reference}\n"
338                    expected = sha512(content.encode())
339                    expected.update(
340                        salted_hmac(
341                            "goauthentik.io/blueprints/v1/external-values",
342                            sha512(b"initial").digest() * routes,
343                            algorithm="sha512",
344                        ).digest()
345                    )
346                    self.assertEqual(self.write_blueprint(file, reference), expected.hexdigest())

Test a referenced !File is folded into the hash once for each route to it

@CONFIG.patch('blueprints_dir', TMP)
def test_file_tag_content_unchanged(self):
348    @CONFIG.patch("blueprints_dir", TMP)
349    def test_file_tag_content_unchanged(self):
350        """Test hash is stable when a referenced `!File` does not change"""
351        with NamedTemporaryFile(mode="w+", dir=TMP) as secret:
352            self.write_secret(secret, "initial")
353            with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
354                reference = f"!File {secret.name}"
355                self.assertEqual(
356                    self.write_blueprint(file, reference),
357                    self.write_blueprint(file, reference),
358                )

Test hash is stable when a referenced !File does not change

@CONFIG.patch('blueprints_dir', TMP)
def test_file_tag_unreadable_hash_stable(self):
360    @CONFIG.patch("blueprints_dir", TMP)
361    def test_file_tag_unreadable_hash_stable(self):
362        """Test hash is stable when a referenced `!File` cannot be read"""
363        for label, reference in (
364            ("missing file", f"!File {Path(TMP) / generate_id()}"),
365            ("path from a tag", f'!File [!Env [{generate_id()}, "{TMP}/fallback"], "default"]'),
366            ("path from a mapping", f'!File {{path: "{TMP}/fallback"}}'),
367            ("path no syscall can take", '!File "\\0"'),
368            ("deeply nested", "[" * 50 + f'!File "{TMP}/fallback"' + "]" * 50),
369        ):
370            with (
371                self.subTest(label),
372                NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file,
373            ):
374                self.assertEqual(
375                    self.write_blueprint(file, reference),
376                    self.write_blueprint(file, reference),
377                )

Test hash is stable when a referenced !File cannot be read

@CONFIG.patch('blueprints_dir', TMP)
def test_file_tag_unreadable_discovery_continues(self):
379    @CONFIG.patch("blueprints_dir", TMP)
380    def test_file_tag_unreadable_discovery_continues(self):
381        """Test a blueprint that cannot be hashed does not stop others being discovered"""
382        for label, reference in (
383            ("path from a mapping", f'!File {{path: "{TMP}/fallback"}}'),
384            ("path no syscall can take", '!File "\\0"'),
385            ("path outside the filesystem encoding", '!File "\\ud800"'),
386            ("env key with a null byte", '!Env "\\0"'),
387            ("env key outside the filesystem encoding", '!Env "\\ud800"'),
388            ("sequence containing itself", "&anchor [*anchor]"),
389            ("mapping containing itself", "&anchor {key: *anchor}"),
390            ("two anchors containing each other", "&outer [{inner: &inner [*outer]}, *inner]"),
391        ):
392            with (
393                self.subTest(label),
394                NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as broken,
395                NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as healthy,
396            ):
397                broken.write(f"version: 1\nentries: []\ncontext:\n  secret: {reference}\n")
398                broken.flush()
399                healthy.write(f"version: 1\nentries: []\nmetadata:\n  name: {generate_id()}\n")
400                healthy.flush()
401                found = [blueprint.path for blueprint in blueprints_find()]
402                self.assertIn(Path(healthy.name).name, found)
403                self.assertIn(Path(broken.name).name, found)

Test a blueprint that cannot be hashed does not stop others being discovered

@CONFIG.patch('blueprints_dir', TMP)
def test_file_tag_applied_on_change(self):
405    @CONFIG.patch("blueprints_dir", TMP)
406    def test_file_tag_applied_on_change(self):
407        """Test blueprint is re-applied when the contents of a referenced `!File` change"""
408        blueprint_id = generate_id()
409        with NamedTemporaryFile(mode="w+", dir=TMP) as secret:
410            self.write_secret(secret, "initial")
411            with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
412                file.write(
413                    f"version: 1\nentries: []\n"
414                    f"metadata:\n  name: {blueprint_id}\n"
415                    f"context:\n  secret: !File {secret.name}\n"
416                )
417                file.flush()
418                blueprints_discovery.send()
419                instance = BlueprintInstance.objects.filter(name=blueprint_id).first()
420                before = instance.last_applied_hash
421                self.assertEqual(instance.status, BlueprintInstanceStatus.SUCCESSFUL)
422                self.write_secret(secret, "rotated")
423                blueprints_discovery.send()
424                instance.refresh_from_db()
425                self.assertNotEqual(instance.last_applied_hash, before)

Test blueprint is re-applied when the contents of a referenced !File change