authentik.blueprints.tests.test_schema

Test blueprint JSON Schema generation

 1"""Test blueprint JSON Schema generation"""
 2
 3from json import dumps, loads
 4
 5from django.test import TestCase
 6from jsonschema import Draft7Validator
 7from jsonschema.exceptions import SchemaError
 8
 9from authentik.blueprints.v1.schema import SchemaBuilder
10
11
12class TestSchema(TestCase):
13    """Test blueprint schema generation"""
14
15    def setUp(self) -> None:
16        self.builder = SchemaBuilder()
17        self.builder.build()
18        # Validate the artifact consumers actually get. `build_schema` dumps with
19        # `json_default` to resolve gettext_lazy proxies into strings, so the
20        # in-memory dict still holds lazy objects that no JSON Schema validator
21        # would accept. Round-tripping here matches the published schema.json.
22        self.schema = loads(dumps(self.builder.schema, default=SchemaBuilder.json_default))
23
24    def test_schema_declares_a_dialect(self):
25        """The generated schema must say which dialect it is written in"""
26        self.assertIn("$schema", self.schema)
27
28    def test_schema_is_valid_against_its_declared_dialect(self):
29        """Regression for #24248.
30
31        The schema declared draft-07 but used `$defs`, which is 2020-12
32        vocabulary — draft-07 spells it `definitions`. A validator honouring the
33        declared dialect therefore could not resolve `#/$defs/...` references,
34        so nothing that consumed the published schema.json could validate a
35        blueprint.
36        """
37        self.assertEqual(self.schema["$schema"], "http://json-schema.org/draft-07/schema")
38        try:
39            Draft7Validator.check_schema(self.schema)
40        except SchemaError as exc:  # pragma: no cover - failure path
41            self.fail(f"generated schema is not valid draft-07: {exc}")
42
43    def test_schema_uses_draft_07_definitions_keyword(self):
44        """`$defs` is 2020-12; under the declared draft-07 dialect it is inert.
45
46        Keeping it would leave every definition unreachable while looking
47        correct in the emitted file.
48        """
49        self.assertIn("definitions", self.schema)
50        self.assertNotIn("$defs", self.schema)
51
52    def test_every_ref_resolves(self):
53        """A `$ref` pointing at a keyword the dialect does not define is dead.
54
55        This is what the issue actually reported: refs into `#/$defs/...` that
56        no draft-07 validator could follow.
57        """
58        refs = self._collect_refs(self.schema)
59        self.assertGreater(len(refs), 0, "expected the schema to contain $refs")
60        for ref in refs:
61            self.assertTrue(
62                ref.startswith("#/definitions/"),
63                f"$ref {ref!r} does not point into #/definitions/",
64            )
65            pointer = ref.removeprefix("#/definitions/")
66            self.assertIn(
67                pointer,
68                self.schema["definitions"],
69                f"$ref {ref!r} does not resolve to a definition",
70            )
71
72    def test_blueprint_entry_definition_is_populated(self):
73        """The entry oneOf is what blueprints are actually validated against."""
74        self.assertGreater(len(self.schema["definitions"]["blueprint_entry"]["oneOf"]), 0)
75
76    def _collect_refs(self, node) -> list[str]:
77        """Every `$ref` value anywhere in the schema."""
78        found = []
79        if isinstance(node, dict):
80            for key, value in node.items():
81                if key == "$ref" and isinstance(value, str):
82                    found.append(value)
83                else:
84                    found.extend(self._collect_refs(value))
85        elif isinstance(node, list):
86            for item in node:
87                found.extend(self._collect_refs(item))
88        return found
class TestSchema(django.test.testcases.TestCase):
13class TestSchema(TestCase):
14    """Test blueprint schema generation"""
15
16    def setUp(self) -> None:
17        self.builder = SchemaBuilder()
18        self.builder.build()
19        # Validate the artifact consumers actually get. `build_schema` dumps with
20        # `json_default` to resolve gettext_lazy proxies into strings, so the
21        # in-memory dict still holds lazy objects that no JSON Schema validator
22        # would accept. Round-tripping here matches the published schema.json.
23        self.schema = loads(dumps(self.builder.schema, default=SchemaBuilder.json_default))
24
25    def test_schema_declares_a_dialect(self):
26        """The generated schema must say which dialect it is written in"""
27        self.assertIn("$schema", self.schema)
28
29    def test_schema_is_valid_against_its_declared_dialect(self):
30        """Regression for #24248.
31
32        The schema declared draft-07 but used `$defs`, which is 2020-12
33        vocabulary — draft-07 spells it `definitions`. A validator honouring the
34        declared dialect therefore could not resolve `#/$defs/...` references,
35        so nothing that consumed the published schema.json could validate a
36        blueprint.
37        """
38        self.assertEqual(self.schema["$schema"], "http://json-schema.org/draft-07/schema")
39        try:
40            Draft7Validator.check_schema(self.schema)
41        except SchemaError as exc:  # pragma: no cover - failure path
42            self.fail(f"generated schema is not valid draft-07: {exc}")
43
44    def test_schema_uses_draft_07_definitions_keyword(self):
45        """`$defs` is 2020-12; under the declared draft-07 dialect it is inert.
46
47        Keeping it would leave every definition unreachable while looking
48        correct in the emitted file.
49        """
50        self.assertIn("definitions", self.schema)
51        self.assertNotIn("$defs", self.schema)
52
53    def test_every_ref_resolves(self):
54        """A `$ref` pointing at a keyword the dialect does not define is dead.
55
56        This is what the issue actually reported: refs into `#/$defs/...` that
57        no draft-07 validator could follow.
58        """
59        refs = self._collect_refs(self.schema)
60        self.assertGreater(len(refs), 0, "expected the schema to contain $refs")
61        for ref in refs:
62            self.assertTrue(
63                ref.startswith("#/definitions/"),
64                f"$ref {ref!r} does not point into #/definitions/",
65            )
66            pointer = ref.removeprefix("#/definitions/")
67            self.assertIn(
68                pointer,
69                self.schema["definitions"],
70                f"$ref {ref!r} does not resolve to a definition",
71            )
72
73    def test_blueprint_entry_definition_is_populated(self):
74        """The entry oneOf is what blueprints are actually validated against."""
75        self.assertGreater(len(self.schema["definitions"]["blueprint_entry"]["oneOf"]), 0)
76
77    def _collect_refs(self, node) -> list[str]:
78        """Every `$ref` value anywhere in the schema."""
79        found = []
80        if isinstance(node, dict):
81            for key, value in node.items():
82                if key == "$ref" and isinstance(value, str):
83                    found.append(value)
84                else:
85                    found.extend(self._collect_refs(value))
86        elif isinstance(node, list):
87            for item in node:
88                found.extend(self._collect_refs(item))
89        return found

Test blueprint schema generation

def setUp(self) -> None:
16    def setUp(self) -> None:
17        self.builder = SchemaBuilder()
18        self.builder.build()
19        # Validate the artifact consumers actually get. `build_schema` dumps with
20        # `json_default` to resolve gettext_lazy proxies into strings, so the
21        # in-memory dict still holds lazy objects that no JSON Schema validator
22        # would accept. Round-tripping here matches the published schema.json.
23        self.schema = loads(dumps(self.builder.schema, default=SchemaBuilder.json_default))

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

def test_schema_declares_a_dialect(self):
25    def test_schema_declares_a_dialect(self):
26        """The generated schema must say which dialect it is written in"""
27        self.assertIn("$schema", self.schema)

The generated schema must say which dialect it is written in

def test_schema_is_valid_against_its_declared_dialect(self):
29    def test_schema_is_valid_against_its_declared_dialect(self):
30        """Regression for #24248.
31
32        The schema declared draft-07 but used `$defs`, which is 2020-12
33        vocabulary — draft-07 spells it `definitions`. A validator honouring the
34        declared dialect therefore could not resolve `#/$defs/...` references,
35        so nothing that consumed the published schema.json could validate a
36        blueprint.
37        """
38        self.assertEqual(self.schema["$schema"], "http://json-schema.org/draft-07/schema")
39        try:
40            Draft7Validator.check_schema(self.schema)
41        except SchemaError as exc:  # pragma: no cover - failure path
42            self.fail(f"generated schema is not valid draft-07: {exc}")

Regression for #24248.

The schema declared draft-07 but used $defs, which is 2020-12 vocabulary — draft-07 spells it definitions. A validator honouring the declared dialect therefore could not resolve #/$defs/... references, so nothing that consumed the published schema.json could validate a blueprint.

def test_schema_uses_draft_07_definitions_keyword(self):
44    def test_schema_uses_draft_07_definitions_keyword(self):
45        """`$defs` is 2020-12; under the declared draft-07 dialect it is inert.
46
47        Keeping it would leave every definition unreachable while looking
48        correct in the emitted file.
49        """
50        self.assertIn("definitions", self.schema)
51        self.assertNotIn("$defs", self.schema)

$defs is 2020-12; under the declared draft-07 dialect it is inert.

Keeping it would leave every definition unreachable while looking correct in the emitted file.

def test_every_ref_resolves(self):
53    def test_every_ref_resolves(self):
54        """A `$ref` pointing at a keyword the dialect does not define is dead.
55
56        This is what the issue actually reported: refs into `#/$defs/...` that
57        no draft-07 validator could follow.
58        """
59        refs = self._collect_refs(self.schema)
60        self.assertGreater(len(refs), 0, "expected the schema to contain $refs")
61        for ref in refs:
62            self.assertTrue(
63                ref.startswith("#/definitions/"),
64                f"$ref {ref!r} does not point into #/definitions/",
65            )
66            pointer = ref.removeprefix("#/definitions/")
67            self.assertIn(
68                pointer,
69                self.schema["definitions"],
70                f"$ref {ref!r} does not resolve to a definition",
71            )

A $ref pointing at a keyword the dialect does not define is dead.

This is what the issue actually reported: refs into #/$defs/... that no draft-07 validator could follow.

def test_blueprint_entry_definition_is_populated(self):
73    def test_blueprint_entry_definition_is_populated(self):
74        """The entry oneOf is what blueprints are actually validated against."""
75        self.assertGreater(len(self.schema["definitions"]["blueprint_entry"]["oneOf"]), 0)

The entry oneOf is what blueprints are actually validated against.