authentik.blueprints.v1.common
transfer common classes
1"""transfer common classes""" 2 3from collections import OrderedDict 4from collections.abc import Generator, Iterable, Mapping, Sequence 5from copy import copy 6from dataclasses import asdict, dataclass, field, is_dataclass 7from enum import Enum 8from functools import reduce 9from itertools import count 10from json import JSONDecodeError, loads 11from operator import ixor 12from os import getenv 13from typing import Any, Literal 14from uuid import UUID 15 16from deepmerge import always_merger 17from django.apps import apps 18from django.db.models import CharField, Model, Q, TextField, UniqueConstraint 19from django.utils.text import slugify 20from rest_framework.exceptions import ValidationError 21from rest_framework.fields import Field 22from rest_framework.relations import ManyRelatedField, PrimaryKeyRelatedField 23from rest_framework.serializers import Serializer 24from structlog.stdlib import get_logger 25from yaml import SafeDumper, SafeLoader, ScalarNode, SequenceNode 26 27from authentik.lib.models import SerializerModel 28from authentik.lib.tracing.exceptions import TracingIgnoredException 29from authentik.policies.models import PolicyBindingModel 30 31LOGGER = get_logger() 32 33 34class UNSET: 35 """Used to test whether a key has not been set.""" 36 37 38def get_attrs(obj: SerializerModel) -> tuple[dict[str, Any], dict[str, Field]]: 39 """Get object's attributes via their serializer, and convert it to a normal dict""" 40 serializer: Serializer = obj.serializer(obj) 41 data = dict(serializer.data) 42 43 for field_name, _field in serializer.fields.items(): 44 _field: Field 45 if field_name not in data: 46 continue 47 if _field.read_only: 48 data.pop(field_name, None) 49 if field_name.endswith("_set"): 50 data.pop(field_name, None) 51 return data, serializer.fields 52 53 54def _relation_target_model(ser_field: Field) -> type[Model] | None: 55 """Get the model a relational serializer field points to, if any""" 56 if isinstance(ser_field, ManyRelatedField): 57 ser_field = ser_field.child_relation 58 if isinstance(ser_field, PrimaryKeyRelatedField) and ser_field.queryset is not None: 59 return ser_field.queryset.model 60 return None 61 62 63def resolve_references( 64 attrs: dict[str, Any], fields: dict[str, Field], reference_index: ReferenceIndex 65) -> dict[str, Any]: 66 """Replace any attrs value that references another exported object with a `KeyOf` tag""" 67 for name, _field in fields.items(): 68 if name not in attrs or attrs[name] is None: 69 continue 70 target_model = _relation_target_model(_field) 71 if target_model is None: 72 continue 73 if isinstance(_field, ManyRelatedField): 74 attrs[name] = [ 75 ( 76 KeyOf(id_from=entry_id) 77 if (entry_id := reference_index.lookup(value, target_model)) 78 else value 79 ) 80 for value in attrs[name] 81 ] 82 else: 83 entry_id = reference_index.lookup(attrs[name], target_model) 84 if entry_id: 85 attrs[name] = KeyOf(id_from=entry_id) 86 return attrs 87 88 89def _stable_identifier_fields(model_class: type[Model]) -> list[str]: 90 """List the names of unique, non-relational text fields on a model (other than its 91 primary key) that could serve as stable identifiers, portable across authentik instances""" 92 return [ 93 model_field.attname 94 for model_field in model_class._meta.fields 95 if not model_field.primary_key 96 and isinstance(model_field, CharField | TextField) 97 and model_field.unique 98 ] 99 100 101def _is_stable_value(value: Any) -> bool: 102 """A value is considered stable (portable across instances) if it's a non-empty 103 string that isn't a UUID, which is almost always instance-local (e.g. a random default)""" 104 if not value or not isinstance(value, str): 105 return False 106 try: 107 UUID(value) 108 return False 109 except ValueError: 110 return True 111 112 113def _readable_key(obj: Model) -> str | None: 114 """Find a unique, human-readable text field on `obj` (not a UUID) to make 115 a !KeyOf id easier to read than a bare counter, e.g. a slug or name.""" 116 for field_name in _stable_identifier_fields(type(obj)): 117 value = getattr(obj, field_name, None) 118 if not _is_stable_value(value): 119 continue 120 slug = slugify(value) 121 if slug: 122 return slug 123 return None 124 125 126def _unique_together_groups(model_class: type[Model]) -> Iterable[tuple[str, ...]]: 127 """Field-name groups declared unique together on a model, via either the legacy 128 Meta.unique_together or a plain (unconditional) Meta.constraints UniqueConstraint""" 129 yield from model_class._meta.unique_together 130 for constraint in model_class._meta.constraints: 131 if not isinstance(constraint, UniqueConstraint): 132 continue 133 if not constraint.condition and constraint.fields: 134 yield constraint.fields 135 136 137def _composite_identifier_fields( 138 model_class: type[Model], all_attrs: dict[str, Any], fields: dict[str, Field] 139) -> list[str]: 140 """When no single field can serve as a stable identifier, fall back to a composite 141 of fields that together identify the instance: a declared unique-together group if 142 one is fully known, otherwise every populated relation to another exported object 143 (e.g. a binding's target and policy), mirroring how such join objects are naturally 144 keyed. Portable across instances, as relations are resolved to !KeyOf tags.""" 145 for group in _unique_together_groups(model_class): 146 if all(name in all_attrs and all_attrs[name] is not None for name in group): 147 return list(group) 148 return [ 149 name 150 for name, ser_field in fields.items() 151 if name in all_attrs 152 and all_attrs[name] is not None 153 and _relation_target_model(ser_field) is not None 154 ] 155 156 157class ReferenceIndex: 158 """Tracks exported model instances so relations between them can be 159 rewritten as !KeyOf references instead of raw primary keys.""" 160 161 def __init__(self): 162 self._entries: dict[Any, tuple[type[Model], str]] = {} 163 self._used: set[str] = set() 164 self._seen_ids: set[str] = set() 165 self._counter = count(1) 166 167 def register(self, obj: Model) -> str: 168 """Register an exported model instance, returning the id assigned to it""" 169 readable_key = _readable_key(obj) 170 entry_id = f"{obj._meta.model_name}-{readable_key or next(self._counter)}" 171 if entry_id in self._seen_ids: 172 entry_id = f"{entry_id}-{next(self._counter)}" 173 self._seen_ids.add(entry_id) 174 self._entries[obj.pk] = (type(obj), entry_id) 175 return entry_id 176 177 def id_for(self, obj: Model) -> str | None: 178 """Get the id assigned to a previously registered model instance, if any""" 179 entry = self._entries.get(obj.pk) 180 return entry[1] if entry else None 181 182 def lookup(self, value: Any, target_model: type[Model]) -> str | None: 183 """Look up the id of a registered model instance by its primary key, 184 provided it is an instance of `target_model`""" 185 entry = self._entries.get(value) 186 if entry and issubclass(entry[0], target_model): 187 self._used.add(entry[1]) 188 return entry[1] 189 return None 190 191 def clear_unused_ids(self, entries: Iterable[BlueprintEntry], objects: Iterable[Model]) -> None: 192 """Strip the id from any entry that is never referenced by a !KeyOf tag""" 193 for entry, obj in zip(entries, objects, strict=True): 194 if self.id_for(obj) not in self._used: 195 entry.id = None 196 197 198@dataclass 199class BlueprintEntryState: 200 """State of a single instance""" 201 202 instance: Model | None = None 203 204 205class BlueprintEntryDesiredState(Enum): 206 """State an entry should be reconciled to""" 207 208 ABSENT = "absent" 209 PRESENT = "present" 210 CREATED = "created" 211 MUST_CREATED = "must_created" 212 213 214@dataclass 215class BlueprintEntryPermission: 216 """Describe object-level permissions""" 217 218 permission: str | YAMLTag 219 user: int | YAMLTag | None = field(default=None) 220 role: str | YAMLTag | None = field(default=None) 221 222 223@dataclass 224class BlueprintEntry: 225 """Single entry of a blueprint""" 226 227 model: str | YAMLTag 228 state: BlueprintEntryDesiredState | YAMLTag = field(default=BlueprintEntryDesiredState.PRESENT) 229 conditions: list[Any] = field(default_factory=list) 230 identifiers: dict[str, Any] = field(default_factory=dict) 231 attrs: dict[str, Any] | None = field(default_factory=dict) 232 permissions: list[BlueprintEntryPermission] = field(default_factory=list) 233 234 id: str | None = None 235 236 _state: BlueprintEntryState = field(default_factory=BlueprintEntryState) 237 238 def __post_init__(self, *args, **kwargs) -> None: 239 self.__tag_contexts: list[YAMLTagContext] = [] 240 241 @staticmethod 242 def from_model( 243 model: SerializerModel, 244 reference_index: ReferenceIndex | None = None, 245 ) -> BlueprintEntry: 246 """Convert a SerializerModel instance to a blueprint Entry""" 247 all_attrs, fields = get_attrs(model) 248 if reference_index is not None: 249 all_attrs = resolve_references(all_attrs, fields, reference_index) 250 251 identifier_names = [ 252 field_name 253 for field_name in _stable_identifier_fields(type(model)) 254 if field_name in all_attrs and _is_stable_value(all_attrs[field_name]) 255 ] 256 257 if not identifier_names: 258 identifier_names = _composite_identifier_fields(type(model), all_attrs, fields) 259 260 identifiers = {} 261 for identifier_name in identifier_names: 262 identifiers[identifier_name] = all_attrs.pop(identifier_name, None) 263 # Only fall back to the (instance-local, non-portable) primary key when no other 264 # stable identifier could be found 265 if not identifiers: 266 identifiers["pk"] = model.pk 267 entry = BlueprintEntry( 268 identifiers=identifiers, 269 model=f"{model._meta.app_label}.{model._meta.model_name}", 270 attrs=all_attrs, 271 ) 272 if reference_index is not None: 273 entry.id = reference_index.id_for(model) 274 return entry 275 276 def get_tag_context( 277 self, 278 depth: int = 0, 279 context_tag_type: type[YAMLTagContext] | tuple[YAMLTagContext, ...] | None = None, 280 ) -> YAMLTagContext: 281 """Get a YAMLTagContext object located at a certain depth in the tag tree""" 282 if depth < 0: 283 raise ValueError("depth must be a positive number or zero") 284 285 if context_tag_type: 286 contexts = [x for x in self.__tag_contexts if isinstance(x, context_tag_type)] 287 else: 288 contexts = self.__tag_contexts 289 290 try: 291 return contexts[-(depth + 1)] 292 except IndexError as exc: 293 raise ValueError(f"invalid depth: {depth}. Max depth: {len(contexts) - 1}") from exc 294 295 def tag_resolver(self, value: Any, blueprint: Blueprint) -> Any: 296 """Check if we have any special tags that need handling""" 297 val = copy(value) 298 299 if isinstance(value, YAMLTagContext): 300 self.__tag_contexts.append(value) 301 302 if isinstance(value, YAMLTag): 303 val = value.resolve(self, blueprint) 304 305 if isinstance(value, dict): 306 for key, inner_value in value.items(): 307 val[key] = self.tag_resolver(inner_value, blueprint) 308 if isinstance(value, list): 309 for idx, inner_value in enumerate(value): 310 val[idx] = self.tag_resolver(inner_value, blueprint) 311 312 if isinstance(value, YAMLTagContext): 313 self.__tag_contexts.pop() 314 315 return val 316 317 def get_attrs(self, blueprint: Blueprint) -> dict[str, Any]: 318 """Get attributes of this entry, with all yaml tags resolved""" 319 return self.tag_resolver(self.attrs, blueprint) 320 321 def get_identifiers(self, blueprint: Blueprint) -> dict[str, Any]: 322 """Get attributes of this entry, with all yaml tags resolved""" 323 return self.tag_resolver(self.identifiers, blueprint) 324 325 def get_state(self, blueprint: Blueprint) -> BlueprintEntryDesiredState: 326 """Get the blueprint state, with yaml tags resolved if present""" 327 return BlueprintEntryDesiredState(self.tag_resolver(self.state, blueprint)) 328 329 def get_model(self, blueprint: Blueprint) -> str: 330 """Get the blueprint model, with yaml tags resolved if present""" 331 return str(self.tag_resolver(self.model, blueprint)) 332 333 def get_permissions(self, blueprint: Blueprint) -> Generator[BlueprintEntryPermission]: 334 """Get permissions of this entry, with all yaml tags resolved""" 335 for perm in self.permissions: 336 yield BlueprintEntryPermission( 337 permission=self.tag_resolver(perm.permission, blueprint), 338 user=self.tag_resolver(perm.user, blueprint), 339 role=self.tag_resolver(perm.role, blueprint), 340 ) 341 342 def check_all_conditions_match(self, blueprint: Blueprint) -> bool: 343 """Check all conditions of this entry match (evaluate to True)""" 344 return all(self.tag_resolver(self.conditions, blueprint)) 345 346 347@dataclass 348class BlueprintMetadata: 349 """Optional blueprint metadata""" 350 351 name: str 352 labels: dict[str, str] = field(default_factory=dict) 353 354 355@dataclass 356class Blueprint: 357 """Dataclass used for a full export""" 358 359 version: int = field(default=1) 360 entries: list[BlueprintEntry] | dict[str, list[BlueprintEntry]] = field(default_factory=list) 361 context: dict = field(default_factory=dict) 362 363 metadata: BlueprintMetadata | None = field(default=None) 364 365 def iter_entries(self) -> Iterable[BlueprintEntry]: 366 if isinstance(self.entries, dict): 367 for _section, entries in self.entries.items(): 368 yield from entries 369 else: 370 yield from self.entries 371 372 373class YAMLTag: 374 """Base class for all YAML Tags""" 375 376 def __repr__(self) -> str: 377 # resolve() may raise; a repr must never raise (called by the log sanitizer). 378 try: 379 return str(self.resolve(BlueprintEntry(""), Blueprint())) 380 except Exception as exc: # noqa: BLE001 - a repr must never raise 381 return f"<{self.__class__.__name__}> (failed to resolve: {exc})" 382 383 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 384 """Implement yaml tag logic""" 385 raise NotImplementedError 386 387 388class YAMLTagContext: 389 """Base class for all YAML Tag Contexts""" 390 391 def get_context(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 392 """Implement yaml tag context logic""" 393 raise NotImplementedError 394 395 396class KeyOf(YAMLTag): 397 """Reference another object by their ID""" 398 399 id_from: str 400 401 def __init__( 402 self, 403 loader: BlueprintLoader | None = None, 404 node: ScalarNode | None = None, 405 id_from: str | None = None, 406 ) -> None: 407 super().__init__() 408 self.id_from = node.value if node is not None else id_from 409 410 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 411 for _entry in blueprint.iter_entries(): 412 if _entry.id == self.id_from and _entry._state.instance: 413 # Special handling for PolicyBindingModels, as they'll have a different PK 414 # which is used when creating policy bindings 415 if ( 416 isinstance(_entry._state.instance, PolicyBindingModel) 417 and entry.model.lower() == "authentik_policies.policybinding" 418 ): 419 return _entry._state.instance.pbm_uuid 420 return _entry._state.instance.pk 421 raise EntryInvalidError.from_entry( 422 f"KeyOf: failed to find entry with `id` of `{self.id_from}` and a model instance", entry 423 ) 424 425 426class Env(YAMLTag): 427 """Lookup environment variable with optional default""" 428 429 key: str 430 default: Any | None 431 432 def __init__(self, loader: BlueprintLoader, node: ScalarNode | SequenceNode) -> None: 433 super().__init__() 434 self.default = None 435 if isinstance(node, ScalarNode): 436 self.key = node.value 437 if isinstance(node, SequenceNode): 438 self.key = loader.construct_object(node.value[0]) 439 self.default = loader.construct_object(node.value[1]) 440 441 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 442 if env := getenv(self.key): 443 return env 444 if isinstance(self.default, YAMLTag): 445 return self.default.resolve(entry, blueprint) 446 return self.default 447 448 449class File(YAMLTag): 450 """Lookup file with optional default""" 451 452 path: str 453 default: Any | None 454 455 def __init__(self, loader: BlueprintLoader, node: ScalarNode | SequenceNode) -> None: 456 super().__init__() 457 self.default = None 458 if isinstance(node, ScalarNode): 459 self.path = node.value 460 if isinstance(node, SequenceNode): 461 self.path = loader.construct_object(node.value[0]) 462 self.default = loader.construct_object(node.value[1]) 463 464 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 465 try: 466 with open(self.path, encoding="utf8") as _file: 467 return _file.read().strip() 468 except OSError as exc: 469 LOGGER.warning( 470 "Failed to read file. Falling back to default value", 471 path=self.path, 472 exc=exc, 473 ) 474 return self.default 475 476 477class Context(YAMLTag): 478 """Lookup key from instance context""" 479 480 key: str 481 default: Any | None 482 483 def __init__(self, loader: BlueprintLoader, node: ScalarNode | SequenceNode) -> None: 484 super().__init__() 485 self.default = None 486 if isinstance(node, ScalarNode): 487 self.key = node.value 488 if isinstance(node, SequenceNode): 489 self.key = loader.construct_object(node.value[0]) 490 self.default = loader.construct_object(node.value[1]) 491 492 def _resolve( 493 self, 494 entry: BlueprintEntry, 495 blueprint: Blueprint, 496 context: Sequence | Mapping, 497 path: str, 498 _segment: str | int | None = None, 499 ) -> Any: 500 """Recursively resolve context""" 501 if _segment is not None: 502 context = context[_segment] 503 504 if isinstance(context, YAMLTag): 505 context = context.resolve(entry, blueprint) 506 507 value = UNSET 508 509 if isinstance(context, Sequence) and not isinstance(context, (str, bytes)): 510 if path.isdigit() and 0 <= int(path) < len(context): 511 value = context[int(path)] 512 elif path in context: 513 value = context[path] 514 515 if value is not UNSET: 516 if isinstance(value, YAMLTag): 517 value = value.resolve(entry, blueprint) 518 return value 519 520 if "." in path: 521 new_head, new_key = path.split(".", 1) 522 523 if isinstance(context, Sequence) and not isinstance(context, (str, bytes)): 524 if new_head.isdigit() and 0 <= int(new_head) < len(context): 525 return self._resolve(entry, blueprint, context, new_key, int(new_head)) 526 elif new_head in context: 527 return self._resolve(entry, blueprint, context, new_key, new_head) 528 529 return self.default 530 531 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 532 return self._resolve(entry, blueprint, blueprint.context, self.key) 533 534 535class ParseJSON(YAMLTag): 536 """Parse JSON from context/env/etc value""" 537 538 raw: str 539 540 def __init__(self, loader: BlueprintLoader, node: ScalarNode) -> None: 541 super().__init__() 542 self.raw = node.value 543 544 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 545 try: 546 return loads(self.raw) 547 except JSONDecodeError as exc: 548 raise EntryInvalidError.from_entry(exc, entry) from exc 549 550 551class Format(YAMLTag): 552 """Format a string""" 553 554 format_string: str 555 args: list[Any] 556 557 def __init__(self, loader: BlueprintLoader, node: SequenceNode) -> None: 558 super().__init__() 559 self.format_string = loader.construct_object(node.value[0]) 560 self.args = [] 561 for raw_node in node.value[1:]: 562 self.args.append(loader.construct_object(raw_node)) 563 564 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 565 args = [] 566 for arg in self.args: 567 if isinstance(arg, YAMLTag): 568 args.append(arg.resolve(entry, blueprint)) 569 else: 570 args.append(arg) 571 572 try: 573 return self.format_string % tuple(args) 574 except TypeError as exc: 575 raise EntryInvalidError.from_entry(exc, entry) from exc 576 577 578class Find(YAMLTag): 579 """Find any object primary key""" 580 581 model_name: str | YAMLTag 582 conditions: list[list] 583 584 def __init__(self, loader: BlueprintLoader, node: SequenceNode) -> None: 585 super().__init__() 586 self.model_name = loader.construct_object(node.value[0]) 587 self.conditions = [] 588 for raw_node in node.value[1:]: 589 values = [] 590 for node_values in raw_node.value: 591 values.append(loader.construct_object(node_values)) 592 self.conditions.append(values) 593 594 def _get_instance(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 595 if isinstance(self.model_name, YAMLTag): 596 model_name = self.model_name.resolve(entry, blueprint) 597 else: 598 model_name = self.model_name 599 600 try: 601 model_class = apps.get_model(*model_name.split(".")) 602 except LookupError as exc: 603 raise EntryInvalidError.from_entry(exc, entry) from exc 604 605 query = Q() 606 for cond in self.conditions: 607 if isinstance(cond[0], YAMLTag): 608 query_key = cond[0].resolve(entry, blueprint) 609 else: 610 query_key = cond[0] 611 if isinstance(cond[1], YAMLTag): 612 query_value = cond[1].resolve(entry, blueprint) 613 else: 614 query_value = cond[1] 615 query &= Q(**{query_key: query_value}) 616 return model_class.objects.filter(query).first() 617 618 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 619 instance = self._get_instance(entry, blueprint) 620 if instance: 621 return instance.pk 622 return None 623 624 625class FindObject(Find): 626 """Find any object""" 627 628 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 629 instance = self._get_instance(entry, blueprint) 630 if not instance: 631 return None 632 if not isinstance(instance, SerializerModel): 633 raise EntryInvalidError.from_entry( 634 f"Model {self.model_name} is not resolvable through FindObject", entry 635 ) 636 return instance.serializer(instance=instance).data 637 638 639class Condition(YAMLTag): 640 """Convert all values to a single boolean""" 641 642 mode: Literal["EQ", "NEQ", "AND", "NAND", "OR", "NOR", "XOR", "XNOR"] 643 args: list[Any] 644 645 _COMPARATORS = { 646 # Using all and any here instead of from operator import iand, ior 647 # to improve performance 648 "EQ": lambda args: all(x == args[0] for x in args), 649 "NEQ": lambda args: not all(x == args[0] for x in args), 650 "AND": all, 651 "NAND": lambda args: not all(args), 652 "OR": any, 653 "NOR": lambda args: not any(args), 654 "XOR": lambda args: reduce(ixor, args) if len(args) > 1 else args[0], 655 "XNOR": lambda args: not (reduce(ixor, args) if len(args) > 1 else args[0]), 656 } 657 658 def __init__(self, loader: BlueprintLoader, node: SequenceNode) -> None: 659 super().__init__() 660 self.mode = loader.construct_object(node.value[0]) 661 self.args = [] 662 for raw_node in node.value[1:]: 663 self.args.append(loader.construct_object(raw_node)) 664 665 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 666 args = [] 667 for arg in self.args: 668 if isinstance(arg, YAMLTag): 669 args.append(arg.resolve(entry, blueprint)) 670 else: 671 args.append(arg) 672 673 if not args: 674 raise EntryInvalidError.from_entry( 675 "At least one value is required after mode selection.", entry 676 ) 677 678 try: 679 comparator = self._COMPARATORS[self.mode.upper()] 680 return comparator(tuple(bool(x) for x in args)) 681 except (TypeError, KeyError) as exc: 682 raise EntryInvalidError.from_entry(exc, entry) from exc 683 684 685class If(YAMLTag): 686 """Select YAML to use based on condition""" 687 688 condition: Any 689 when_true: Any 690 when_false: Any 691 692 def __init__(self, loader: BlueprintLoader, node: SequenceNode) -> None: 693 super().__init__() 694 self.condition = loader.construct_object(node.value[0]) 695 if len(node.value) == 1: 696 self.when_true = True 697 self.when_false = False 698 else: 699 self.when_true = loader.construct_object(node.value[1]) 700 self.when_false = loader.construct_object(node.value[2]) 701 702 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 703 if isinstance(self.condition, YAMLTag): 704 condition = self.condition.resolve(entry, blueprint) 705 else: 706 condition = self.condition 707 708 try: 709 return entry.tag_resolver( 710 self.when_true if condition else self.when_false, 711 blueprint, 712 ) 713 except TypeError as exc: 714 raise EntryInvalidError.from_entry(exc, entry) from exc 715 716 717class Enumerate(YAMLTag, YAMLTagContext): 718 """Iterate over an iterable.""" 719 720 iterable: YAMLTag | Iterable 721 item_body: Any 722 output_body: Literal["SEQ", "MAP"] 723 724 _OUTPUT_BODIES = { 725 "SEQ": (list, lambda a, b: [*a, b]), 726 "MAP": ( 727 dict, 728 lambda a, b: always_merger.merge(a, {b[0]: b[1]} if isinstance(b, tuple | list) else b), 729 ), 730 } 731 732 def __init__(self, loader: BlueprintLoader, node: SequenceNode) -> None: 733 super().__init__() 734 self.iterable = loader.construct_object(node.value[0]) 735 self.output_body = loader.construct_object(node.value[1]) 736 self.item_body = loader.construct_object(node.value[2]) 737 self.__current_context: tuple[Any, Any] = tuple() 738 739 def get_context(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 740 return self.__current_context 741 742 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 743 if isinstance(self.iterable, EnumeratedItem) and self.iterable.depth == 0: 744 raise EntryInvalidError.from_entry( 745 f"{self.__class__.__name__} tag's iterable references this tag's context. " 746 "This is a noop. Check you are setting depth bigger than 0.", 747 entry, 748 ) 749 750 if isinstance(self.iterable, YAMLTag): 751 iterable = self.iterable.resolve(entry, blueprint) 752 else: 753 iterable = self.iterable 754 755 if not isinstance(iterable, Iterable): 756 raise EntryInvalidError.from_entry( 757 f"{self.__class__.__name__}'s iterable must be an iterable " 758 "such as a sequence or a mapping", 759 entry, 760 ) 761 762 if isinstance(iterable, Mapping): 763 iterable = tuple(iterable.items()) 764 else: 765 iterable = tuple(enumerate(iterable)) 766 767 try: 768 output_class, add_fn = self._OUTPUT_BODIES[self.output_body.upper()] 769 except KeyError as exc: 770 raise EntryInvalidError.from_entry(exc, entry) from exc 771 772 result = output_class() 773 774 self.__current_context = tuple() 775 776 try: 777 for item in iterable: 778 self.__current_context = item 779 resolved_body = entry.tag_resolver(self.item_body, blueprint) 780 result = add_fn(result, resolved_body) 781 if not isinstance(result, output_class): 782 raise EntryInvalidError.from_entry( 783 f"Invalid {self.__class__.__name__} item found: {resolved_body}", entry 784 ) 785 finally: 786 self.__current_context = tuple() 787 788 return result 789 790 791class EnumeratedItem(YAMLTag): 792 """Get the current item value and index provided by an Enumerate tag context""" 793 794 depth: int 795 796 _SUPPORTED_CONTEXT_TAGS = (Enumerate,) 797 798 def __init__(self, _loader: BlueprintLoader, node: ScalarNode) -> None: 799 super().__init__() 800 self.depth = int(node.value) 801 802 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 803 try: 804 context_tag: Enumerate = entry.get_tag_context( 805 depth=self.depth, 806 context_tag_type=EnumeratedItem._SUPPORTED_CONTEXT_TAGS, 807 ) 808 except ValueError as exc: 809 if self.depth == 0: 810 raise EntryInvalidError.from_entry( 811 f"{self.__class__.__name__} tags are only usable " 812 f"inside an {Enumerate.__name__} tag", 813 entry, 814 ) from exc 815 816 raise EntryInvalidError.from_entry( 817 f"{self.__class__.__name__} tag: {exc}", entry 818 ) from exc 819 820 return context_tag.get_context(entry, blueprint) 821 822 823class Index(EnumeratedItem): 824 """Get the current item index provided by an Enumerate tag context""" 825 826 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 827 context = super().resolve(entry, blueprint) 828 829 try: 830 return context[0] 831 except IndexError as exc: # pragma: no cover 832 raise EntryInvalidError.from_entry(f"Empty/invalid context: {context}", entry) from exc 833 834 835class Value(EnumeratedItem): 836 """Get the current item value provided by an Enumerate tag context""" 837 838 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 839 context = super().resolve(entry, blueprint) 840 841 try: 842 return context[1] 843 except IndexError as exc: # pragma: no cover 844 raise EntryInvalidError.from_entry(f"Empty/invalid context: {context}", entry) from exc 845 846 847class AtIndex(YAMLTag): 848 """Get value at index of a sequence or mapping""" 849 850 obj: YAMLTag | dict | list | tuple 851 attribute: int | str | YAMLTag 852 default: Any | UNSET 853 854 def __init__(self, loader: BlueprintLoader, node: SequenceNode) -> None: 855 super().__init__() 856 self.obj = loader.construct_object(node.value[0]) 857 self.attribute = loader.construct_object(node.value[1]) 858 if len(node.value) == 2: # noqa: PLR2004 859 self.default = UNSET 860 else: 861 self.default = loader.construct_object(node.value[2]) 862 863 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 864 if isinstance(self.obj, YAMLTag): 865 obj = self.obj.resolve(entry, blueprint) 866 else: 867 obj = self.obj 868 if isinstance(self.attribute, YAMLTag): 869 attribute = self.attribute.resolve(entry, blueprint) 870 else: 871 attribute = self.attribute 872 873 if isinstance(obj, list | tuple): 874 try: 875 return obj[attribute] 876 except TypeError as exc: 877 raise EntryInvalidError.from_entry( 878 f"Invalid index for list: {attribute}", entry 879 ) from exc 880 except IndexError as exc: 881 if self.default is UNSET: 882 raise EntryInvalidError.from_entry( 883 f"Index out of range: {attribute}", entry 884 ) from exc 885 return self.default 886 if attribute in obj: 887 return obj[attribute] 888 else: 889 if self.default is UNSET: 890 raise EntryInvalidError.from_entry(f"Key does not exist: {attribute}", entry) 891 return self.default 892 893 894class BlueprintDumper(SafeDumper): 895 """Dump dataclasses to yaml""" 896 897 default_flow_style = False 898 899 def __init__(self, *args, **kwargs): 900 super().__init__(*args, **kwargs) 901 self.add_representer(UUID, lambda self, data: self.represent_str(str(data))) 902 self.add_representer(OrderedDict, lambda self, data: self.represent_dict(dict(data))) 903 self.add_representer(Enum, lambda self, data: self.represent_str(data.value)) 904 self.add_representer( 905 BlueprintEntryDesiredState, lambda self, data: self.represent_str(data.value) 906 ) 907 self.add_representer( 908 KeyOf, lambda self, data: self.represent_scalar("!KeyOf", data.id_from) 909 ) 910 self.add_representer(None, lambda self, data: self.represent_str(str(data))) 911 912 def ignore_aliases(self, data): 913 """Don't use any YAML anchors""" 914 return True 915 916 def represent(self, data) -> None: 917 if is_dataclass(data): 918 919 def factory(items): 920 final_dict = dict(items) 921 # Remove internal state variables 922 final_dict.pop("_state", None) 923 # Future-proof to only remove the ID if we don't set a value 924 if "id" in final_dict and final_dict.get("id") is None: 925 final_dict.pop("id") 926 return final_dict 927 928 data = asdict(data, dict_factory=factory) 929 return super().represent(data) 930 931 932class BlueprintLoader(SafeLoader): 933 """Loader for blueprints with custom tag support""" 934 935 def __init__(self, *args, **kwargs): 936 super().__init__(*args, **kwargs) 937 self.add_constructor("!KeyOf", KeyOf) 938 self.add_constructor("!Find", Find) 939 self.add_constructor("!FindObject", FindObject) 940 self.add_constructor("!Context", Context) 941 self.add_constructor("!Format", Format) 942 self.add_constructor("!Condition", Condition) 943 self.add_constructor("!If", If) 944 self.add_constructor("!Env", Env) 945 self.add_constructor("!File", File) 946 self.add_constructor("!Enumerate", Enumerate) 947 self.add_constructor("!Value", Value) 948 self.add_constructor("!Index", Index) 949 self.add_constructor("!AtIndex", AtIndex) 950 self.add_constructor("!ParseJSON", ParseJSON) 951 952 953class EntryInvalidError(TracingIgnoredException): 954 """Error raised when an entry is invalid""" 955 956 entry_model: str | None 957 entry_id: str | None 958 validation_error: ValidationError | None 959 serializer: Serializer | None = None 960 961 def __init__( 962 self, *args: object, validation_error: ValidationError | None = None, **kwargs 963 ) -> None: 964 super().__init__(*args) 965 self.entry_model = None 966 self.entry_id = None 967 self.validation_error = validation_error 968 for key, value in kwargs.items(): 969 setattr(self, key, value) 970 971 @staticmethod 972 def from_entry( 973 msg_or_exc: str | Exception, entry: BlueprintEntry, *args, **kwargs 974 ) -> EntryInvalidError: 975 """Create EntryInvalidError with the context of an entry""" 976 error = EntryInvalidError(msg_or_exc, *args, **kwargs) 977 if isinstance(msg_or_exc, ValidationError): 978 error.validation_error = msg_or_exc 979 # Make sure the model and id are strings, depending where the error happens 980 # they might still be YAMLTag instances 981 error.entry_model = str(entry.model) 982 error.entry_id = str(entry.id) 983 return error
Used to test whether a key has not been set.
39def get_attrs(obj: SerializerModel) -> tuple[dict[str, Any], dict[str, Field]]: 40 """Get object's attributes via their serializer, and convert it to a normal dict""" 41 serializer: Serializer = obj.serializer(obj) 42 data = dict(serializer.data) 43 44 for field_name, _field in serializer.fields.items(): 45 _field: Field 46 if field_name not in data: 47 continue 48 if _field.read_only: 49 data.pop(field_name, None) 50 if field_name.endswith("_set"): 51 data.pop(field_name, None) 52 return data, serializer.fields
Get object's attributes via their serializer, and convert it to a normal dict
64def resolve_references( 65 attrs: dict[str, Any], fields: dict[str, Field], reference_index: ReferenceIndex 66) -> dict[str, Any]: 67 """Replace any attrs value that references another exported object with a `KeyOf` tag""" 68 for name, _field in fields.items(): 69 if name not in attrs or attrs[name] is None: 70 continue 71 target_model = _relation_target_model(_field) 72 if target_model is None: 73 continue 74 if isinstance(_field, ManyRelatedField): 75 attrs[name] = [ 76 ( 77 KeyOf(id_from=entry_id) 78 if (entry_id := reference_index.lookup(value, target_model)) 79 else value 80 ) 81 for value in attrs[name] 82 ] 83 else: 84 entry_id = reference_index.lookup(attrs[name], target_model) 85 if entry_id: 86 attrs[name] = KeyOf(id_from=entry_id) 87 return attrs
Replace any attrs value that references another exported object with a KeyOf tag
158class ReferenceIndex: 159 """Tracks exported model instances so relations between them can be 160 rewritten as !KeyOf references instead of raw primary keys.""" 161 162 def __init__(self): 163 self._entries: dict[Any, tuple[type[Model], str]] = {} 164 self._used: set[str] = set() 165 self._seen_ids: set[str] = set() 166 self._counter = count(1) 167 168 def register(self, obj: Model) -> str: 169 """Register an exported model instance, returning the id assigned to it""" 170 readable_key = _readable_key(obj) 171 entry_id = f"{obj._meta.model_name}-{readable_key or next(self._counter)}" 172 if entry_id in self._seen_ids: 173 entry_id = f"{entry_id}-{next(self._counter)}" 174 self._seen_ids.add(entry_id) 175 self._entries[obj.pk] = (type(obj), entry_id) 176 return entry_id 177 178 def id_for(self, obj: Model) -> str | None: 179 """Get the id assigned to a previously registered model instance, if any""" 180 entry = self._entries.get(obj.pk) 181 return entry[1] if entry else None 182 183 def lookup(self, value: Any, target_model: type[Model]) -> str | None: 184 """Look up the id of a registered model instance by its primary key, 185 provided it is an instance of `target_model`""" 186 entry = self._entries.get(value) 187 if entry and issubclass(entry[0], target_model): 188 self._used.add(entry[1]) 189 return entry[1] 190 return None 191 192 def clear_unused_ids(self, entries: Iterable[BlueprintEntry], objects: Iterable[Model]) -> None: 193 """Strip the id from any entry that is never referenced by a !KeyOf tag""" 194 for entry, obj in zip(entries, objects, strict=True): 195 if self.id_for(obj) not in self._used: 196 entry.id = None
Tracks exported model instances so relations between them can be rewritten as !KeyOf references instead of raw primary keys.
168 def register(self, obj: Model) -> str: 169 """Register an exported model instance, returning the id assigned to it""" 170 readable_key = _readable_key(obj) 171 entry_id = f"{obj._meta.model_name}-{readable_key or next(self._counter)}" 172 if entry_id in self._seen_ids: 173 entry_id = f"{entry_id}-{next(self._counter)}" 174 self._seen_ids.add(entry_id) 175 self._entries[obj.pk] = (type(obj), entry_id) 176 return entry_id
Register an exported model instance, returning the id assigned to it
178 def id_for(self, obj: Model) -> str | None: 179 """Get the id assigned to a previously registered model instance, if any""" 180 entry = self._entries.get(obj.pk) 181 return entry[1] if entry else None
Get the id assigned to a previously registered model instance, if any
183 def lookup(self, value: Any, target_model: type[Model]) -> str | None: 184 """Look up the id of a registered model instance by its primary key, 185 provided it is an instance of `target_model`""" 186 entry = self._entries.get(value) 187 if entry and issubclass(entry[0], target_model): 188 self._used.add(entry[1]) 189 return entry[1] 190 return None
Look up the id of a registered model instance by its primary key,
provided it is an instance of target_model
192 def clear_unused_ids(self, entries: Iterable[BlueprintEntry], objects: Iterable[Model]) -> None: 193 """Strip the id from any entry that is never referenced by a !KeyOf tag""" 194 for entry, obj in zip(entries, objects, strict=True): 195 if self.id_for(obj) not in self._used: 196 entry.id = None
Strip the id from any entry that is never referenced by a !KeyOf tag
199@dataclass 200class BlueprintEntryState: 201 """State of a single instance""" 202 203 instance: Model | None = None
State of a single instance
206class BlueprintEntryDesiredState(Enum): 207 """State an entry should be reconciled to""" 208 209 ABSENT = "absent" 210 PRESENT = "present" 211 CREATED = "created" 212 MUST_CREATED = "must_created"
State an entry should be reconciled to
215@dataclass 216class BlueprintEntryPermission: 217 """Describe object-level permissions""" 218 219 permission: str | YAMLTag 220 user: int | YAMLTag | None = field(default=None) 221 role: str | YAMLTag | None = field(default=None)
Describe object-level permissions
224@dataclass 225class BlueprintEntry: 226 """Single entry of a blueprint""" 227 228 model: str | YAMLTag 229 state: BlueprintEntryDesiredState | YAMLTag = field(default=BlueprintEntryDesiredState.PRESENT) 230 conditions: list[Any] = field(default_factory=list) 231 identifiers: dict[str, Any] = field(default_factory=dict) 232 attrs: dict[str, Any] | None = field(default_factory=dict) 233 permissions: list[BlueprintEntryPermission] = field(default_factory=list) 234 235 id: str | None = None 236 237 _state: BlueprintEntryState = field(default_factory=BlueprintEntryState) 238 239 def __post_init__(self, *args, **kwargs) -> None: 240 self.__tag_contexts: list[YAMLTagContext] = [] 241 242 @staticmethod 243 def from_model( 244 model: SerializerModel, 245 reference_index: ReferenceIndex | None = None, 246 ) -> BlueprintEntry: 247 """Convert a SerializerModel instance to a blueprint Entry""" 248 all_attrs, fields = get_attrs(model) 249 if reference_index is not None: 250 all_attrs = resolve_references(all_attrs, fields, reference_index) 251 252 identifier_names = [ 253 field_name 254 for field_name in _stable_identifier_fields(type(model)) 255 if field_name in all_attrs and _is_stable_value(all_attrs[field_name]) 256 ] 257 258 if not identifier_names: 259 identifier_names = _composite_identifier_fields(type(model), all_attrs, fields) 260 261 identifiers = {} 262 for identifier_name in identifier_names: 263 identifiers[identifier_name] = all_attrs.pop(identifier_name, None) 264 # Only fall back to the (instance-local, non-portable) primary key when no other 265 # stable identifier could be found 266 if not identifiers: 267 identifiers["pk"] = model.pk 268 entry = BlueprintEntry( 269 identifiers=identifiers, 270 model=f"{model._meta.app_label}.{model._meta.model_name}", 271 attrs=all_attrs, 272 ) 273 if reference_index is not None: 274 entry.id = reference_index.id_for(model) 275 return entry 276 277 def get_tag_context( 278 self, 279 depth: int = 0, 280 context_tag_type: type[YAMLTagContext] | tuple[YAMLTagContext, ...] | None = None, 281 ) -> YAMLTagContext: 282 """Get a YAMLTagContext object located at a certain depth in the tag tree""" 283 if depth < 0: 284 raise ValueError("depth must be a positive number or zero") 285 286 if context_tag_type: 287 contexts = [x for x in self.__tag_contexts if isinstance(x, context_tag_type)] 288 else: 289 contexts = self.__tag_contexts 290 291 try: 292 return contexts[-(depth + 1)] 293 except IndexError as exc: 294 raise ValueError(f"invalid depth: {depth}. Max depth: {len(contexts) - 1}") from exc 295 296 def tag_resolver(self, value: Any, blueprint: Blueprint) -> Any: 297 """Check if we have any special tags that need handling""" 298 val = copy(value) 299 300 if isinstance(value, YAMLTagContext): 301 self.__tag_contexts.append(value) 302 303 if isinstance(value, YAMLTag): 304 val = value.resolve(self, blueprint) 305 306 if isinstance(value, dict): 307 for key, inner_value in value.items(): 308 val[key] = self.tag_resolver(inner_value, blueprint) 309 if isinstance(value, list): 310 for idx, inner_value in enumerate(value): 311 val[idx] = self.tag_resolver(inner_value, blueprint) 312 313 if isinstance(value, YAMLTagContext): 314 self.__tag_contexts.pop() 315 316 return val 317 318 def get_attrs(self, blueprint: Blueprint) -> dict[str, Any]: 319 """Get attributes of this entry, with all yaml tags resolved""" 320 return self.tag_resolver(self.attrs, blueprint) 321 322 def get_identifiers(self, blueprint: Blueprint) -> dict[str, Any]: 323 """Get attributes of this entry, with all yaml tags resolved""" 324 return self.tag_resolver(self.identifiers, blueprint) 325 326 def get_state(self, blueprint: Blueprint) -> BlueprintEntryDesiredState: 327 """Get the blueprint state, with yaml tags resolved if present""" 328 return BlueprintEntryDesiredState(self.tag_resolver(self.state, blueprint)) 329 330 def get_model(self, blueprint: Blueprint) -> str: 331 """Get the blueprint model, with yaml tags resolved if present""" 332 return str(self.tag_resolver(self.model, blueprint)) 333 334 def get_permissions(self, blueprint: Blueprint) -> Generator[BlueprintEntryPermission]: 335 """Get permissions of this entry, with all yaml tags resolved""" 336 for perm in self.permissions: 337 yield BlueprintEntryPermission( 338 permission=self.tag_resolver(perm.permission, blueprint), 339 user=self.tag_resolver(perm.user, blueprint), 340 role=self.tag_resolver(perm.role, blueprint), 341 ) 342 343 def check_all_conditions_match(self, blueprint: Blueprint) -> bool: 344 """Check all conditions of this entry match (evaluate to True)""" 345 return all(self.tag_resolver(self.conditions, blueprint))
Single entry of a blueprint
242 @staticmethod 243 def from_model( 244 model: SerializerModel, 245 reference_index: ReferenceIndex | None = None, 246 ) -> BlueprintEntry: 247 """Convert a SerializerModel instance to a blueprint Entry""" 248 all_attrs, fields = get_attrs(model) 249 if reference_index is not None: 250 all_attrs = resolve_references(all_attrs, fields, reference_index) 251 252 identifier_names = [ 253 field_name 254 for field_name in _stable_identifier_fields(type(model)) 255 if field_name in all_attrs and _is_stable_value(all_attrs[field_name]) 256 ] 257 258 if not identifier_names: 259 identifier_names = _composite_identifier_fields(type(model), all_attrs, fields) 260 261 identifiers = {} 262 for identifier_name in identifier_names: 263 identifiers[identifier_name] = all_attrs.pop(identifier_name, None) 264 # Only fall back to the (instance-local, non-portable) primary key when no other 265 # stable identifier could be found 266 if not identifiers: 267 identifiers["pk"] = model.pk 268 entry = BlueprintEntry( 269 identifiers=identifiers, 270 model=f"{model._meta.app_label}.{model._meta.model_name}", 271 attrs=all_attrs, 272 ) 273 if reference_index is not None: 274 entry.id = reference_index.id_for(model) 275 return entry
Convert a SerializerModel instance to a blueprint Entry
277 def get_tag_context( 278 self, 279 depth: int = 0, 280 context_tag_type: type[YAMLTagContext] | tuple[YAMLTagContext, ...] | None = None, 281 ) -> YAMLTagContext: 282 """Get a YAMLTagContext object located at a certain depth in the tag tree""" 283 if depth < 0: 284 raise ValueError("depth must be a positive number or zero") 285 286 if context_tag_type: 287 contexts = [x for x in self.__tag_contexts if isinstance(x, context_tag_type)] 288 else: 289 contexts = self.__tag_contexts 290 291 try: 292 return contexts[-(depth + 1)] 293 except IndexError as exc: 294 raise ValueError(f"invalid depth: {depth}. Max depth: {len(contexts) - 1}") from exc
Get a YAMLTagContext object located at a certain depth in the tag tree
296 def tag_resolver(self, value: Any, blueprint: Blueprint) -> Any: 297 """Check if we have any special tags that need handling""" 298 val = copy(value) 299 300 if isinstance(value, YAMLTagContext): 301 self.__tag_contexts.append(value) 302 303 if isinstance(value, YAMLTag): 304 val = value.resolve(self, blueprint) 305 306 if isinstance(value, dict): 307 for key, inner_value in value.items(): 308 val[key] = self.tag_resolver(inner_value, blueprint) 309 if isinstance(value, list): 310 for idx, inner_value in enumerate(value): 311 val[idx] = self.tag_resolver(inner_value, blueprint) 312 313 if isinstance(value, YAMLTagContext): 314 self.__tag_contexts.pop() 315 316 return val
Check if we have any special tags that need handling
318 def get_attrs(self, blueprint: Blueprint) -> dict[str, Any]: 319 """Get attributes of this entry, with all yaml tags resolved""" 320 return self.tag_resolver(self.attrs, blueprint)
Get attributes of this entry, with all yaml tags resolved
322 def get_identifiers(self, blueprint: Blueprint) -> dict[str, Any]: 323 """Get attributes of this entry, with all yaml tags resolved""" 324 return self.tag_resolver(self.identifiers, blueprint)
Get attributes of this entry, with all yaml tags resolved
326 def get_state(self, blueprint: Blueprint) -> BlueprintEntryDesiredState: 327 """Get the blueprint state, with yaml tags resolved if present""" 328 return BlueprintEntryDesiredState(self.tag_resolver(self.state, blueprint))
Get the blueprint state, with yaml tags resolved if present
330 def get_model(self, blueprint: Blueprint) -> str: 331 """Get the blueprint model, with yaml tags resolved if present""" 332 return str(self.tag_resolver(self.model, blueprint))
Get the blueprint model, with yaml tags resolved if present
334 def get_permissions(self, blueprint: Blueprint) -> Generator[BlueprintEntryPermission]: 335 """Get permissions of this entry, with all yaml tags resolved""" 336 for perm in self.permissions: 337 yield BlueprintEntryPermission( 338 permission=self.tag_resolver(perm.permission, blueprint), 339 user=self.tag_resolver(perm.user, blueprint), 340 role=self.tag_resolver(perm.role, blueprint), 341 )
Get permissions of this entry, with all yaml tags resolved
348@dataclass 349class BlueprintMetadata: 350 """Optional blueprint metadata""" 351 352 name: str 353 labels: dict[str, str] = field(default_factory=dict)
Optional blueprint metadata
356@dataclass 357class Blueprint: 358 """Dataclass used for a full export""" 359 360 version: int = field(default=1) 361 entries: list[BlueprintEntry] | dict[str, list[BlueprintEntry]] = field(default_factory=list) 362 context: dict = field(default_factory=dict) 363 364 metadata: BlueprintMetadata | None = field(default=None) 365 366 def iter_entries(self) -> Iterable[BlueprintEntry]: 367 if isinstance(self.entries, dict): 368 for _section, entries in self.entries.items(): 369 yield from entries 370 else: 371 yield from self.entries
Dataclass used for a full export
374class YAMLTag: 375 """Base class for all YAML Tags""" 376 377 def __repr__(self) -> str: 378 # resolve() may raise; a repr must never raise (called by the log sanitizer). 379 try: 380 return str(self.resolve(BlueprintEntry(""), Blueprint())) 381 except Exception as exc: # noqa: BLE001 - a repr must never raise 382 return f"<{self.__class__.__name__}> (failed to resolve: {exc})" 383 384 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 385 """Implement yaml tag logic""" 386 raise NotImplementedError
Base class for all YAML Tags
389class YAMLTagContext: 390 """Base class for all YAML Tag Contexts""" 391 392 def get_context(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 393 """Implement yaml tag context logic""" 394 raise NotImplementedError
Base class for all YAML Tag Contexts
397class KeyOf(YAMLTag): 398 """Reference another object by their ID""" 399 400 id_from: str 401 402 def __init__( 403 self, 404 loader: BlueprintLoader | None = None, 405 node: ScalarNode | None = None, 406 id_from: str | None = None, 407 ) -> None: 408 super().__init__() 409 self.id_from = node.value if node is not None else id_from 410 411 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 412 for _entry in blueprint.iter_entries(): 413 if _entry.id == self.id_from and _entry._state.instance: 414 # Special handling for PolicyBindingModels, as they'll have a different PK 415 # which is used when creating policy bindings 416 if ( 417 isinstance(_entry._state.instance, PolicyBindingModel) 418 and entry.model.lower() == "authentik_policies.policybinding" 419 ): 420 return _entry._state.instance.pbm_uuid 421 return _entry._state.instance.pk 422 raise EntryInvalidError.from_entry( 423 f"KeyOf: failed to find entry with `id` of `{self.id_from}` and a model instance", entry 424 )
Reference another object by their ID
411 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 412 for _entry in blueprint.iter_entries(): 413 if _entry.id == self.id_from and _entry._state.instance: 414 # Special handling for PolicyBindingModels, as they'll have a different PK 415 # which is used when creating policy bindings 416 if ( 417 isinstance(_entry._state.instance, PolicyBindingModel) 418 and entry.model.lower() == "authentik_policies.policybinding" 419 ): 420 return _entry._state.instance.pbm_uuid 421 return _entry._state.instance.pk 422 raise EntryInvalidError.from_entry( 423 f"KeyOf: failed to find entry with `id` of `{self.id_from}` and a model instance", entry 424 )
Implement yaml tag logic
427class Env(YAMLTag): 428 """Lookup environment variable with optional default""" 429 430 key: str 431 default: Any | None 432 433 def __init__(self, loader: BlueprintLoader, node: ScalarNode | SequenceNode) -> None: 434 super().__init__() 435 self.default = None 436 if isinstance(node, ScalarNode): 437 self.key = node.value 438 if isinstance(node, SequenceNode): 439 self.key = loader.construct_object(node.value[0]) 440 self.default = loader.construct_object(node.value[1]) 441 442 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 443 if env := getenv(self.key): 444 return env 445 if isinstance(self.default, YAMLTag): 446 return self.default.resolve(entry, blueprint) 447 return self.default
Lookup environment variable with optional default
433 def __init__(self, loader: BlueprintLoader, node: ScalarNode | SequenceNode) -> None: 434 super().__init__() 435 self.default = None 436 if isinstance(node, ScalarNode): 437 self.key = node.value 438 if isinstance(node, SequenceNode): 439 self.key = loader.construct_object(node.value[0]) 440 self.default = loader.construct_object(node.value[1])
450class File(YAMLTag): 451 """Lookup file with optional default""" 452 453 path: str 454 default: Any | None 455 456 def __init__(self, loader: BlueprintLoader, node: ScalarNode | SequenceNode) -> None: 457 super().__init__() 458 self.default = None 459 if isinstance(node, ScalarNode): 460 self.path = node.value 461 if isinstance(node, SequenceNode): 462 self.path = loader.construct_object(node.value[0]) 463 self.default = loader.construct_object(node.value[1]) 464 465 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 466 try: 467 with open(self.path, encoding="utf8") as _file: 468 return _file.read().strip() 469 except OSError as exc: 470 LOGGER.warning( 471 "Failed to read file. Falling back to default value", 472 path=self.path, 473 exc=exc, 474 ) 475 return self.default
Lookup file with optional default
456 def __init__(self, loader: BlueprintLoader, node: ScalarNode | SequenceNode) -> None: 457 super().__init__() 458 self.default = None 459 if isinstance(node, ScalarNode): 460 self.path = node.value 461 if isinstance(node, SequenceNode): 462 self.path = loader.construct_object(node.value[0]) 463 self.default = loader.construct_object(node.value[1])
465 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 466 try: 467 with open(self.path, encoding="utf8") as _file: 468 return _file.read().strip() 469 except OSError as exc: 470 LOGGER.warning( 471 "Failed to read file. Falling back to default value", 472 path=self.path, 473 exc=exc, 474 ) 475 return self.default
Implement yaml tag logic
478class Context(YAMLTag): 479 """Lookup key from instance context""" 480 481 key: str 482 default: Any | None 483 484 def __init__(self, loader: BlueprintLoader, node: ScalarNode | SequenceNode) -> None: 485 super().__init__() 486 self.default = None 487 if isinstance(node, ScalarNode): 488 self.key = node.value 489 if isinstance(node, SequenceNode): 490 self.key = loader.construct_object(node.value[0]) 491 self.default = loader.construct_object(node.value[1]) 492 493 def _resolve( 494 self, 495 entry: BlueprintEntry, 496 blueprint: Blueprint, 497 context: Sequence | Mapping, 498 path: str, 499 _segment: str | int | None = None, 500 ) -> Any: 501 """Recursively resolve context""" 502 if _segment is not None: 503 context = context[_segment] 504 505 if isinstance(context, YAMLTag): 506 context = context.resolve(entry, blueprint) 507 508 value = UNSET 509 510 if isinstance(context, Sequence) and not isinstance(context, (str, bytes)): 511 if path.isdigit() and 0 <= int(path) < len(context): 512 value = context[int(path)] 513 elif path in context: 514 value = context[path] 515 516 if value is not UNSET: 517 if isinstance(value, YAMLTag): 518 value = value.resolve(entry, blueprint) 519 return value 520 521 if "." in path: 522 new_head, new_key = path.split(".", 1) 523 524 if isinstance(context, Sequence) and not isinstance(context, (str, bytes)): 525 if new_head.isdigit() and 0 <= int(new_head) < len(context): 526 return self._resolve(entry, blueprint, context, new_key, int(new_head)) 527 elif new_head in context: 528 return self._resolve(entry, blueprint, context, new_key, new_head) 529 530 return self.default 531 532 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 533 return self._resolve(entry, blueprint, blueprint.context, self.key)
Lookup key from instance context
484 def __init__(self, loader: BlueprintLoader, node: ScalarNode | SequenceNode) -> None: 485 super().__init__() 486 self.default = None 487 if isinstance(node, ScalarNode): 488 self.key = node.value 489 if isinstance(node, SequenceNode): 490 self.key = loader.construct_object(node.value[0]) 491 self.default = loader.construct_object(node.value[1])
536class ParseJSON(YAMLTag): 537 """Parse JSON from context/env/etc value""" 538 539 raw: str 540 541 def __init__(self, loader: BlueprintLoader, node: ScalarNode) -> None: 542 super().__init__() 543 self.raw = node.value 544 545 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 546 try: 547 return loads(self.raw) 548 except JSONDecodeError as exc: 549 raise EntryInvalidError.from_entry(exc, entry) from exc
Parse JSON from context/env/etc value
552class Format(YAMLTag): 553 """Format a string""" 554 555 format_string: str 556 args: list[Any] 557 558 def __init__(self, loader: BlueprintLoader, node: SequenceNode) -> None: 559 super().__init__() 560 self.format_string = loader.construct_object(node.value[0]) 561 self.args = [] 562 for raw_node in node.value[1:]: 563 self.args.append(loader.construct_object(raw_node)) 564 565 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 566 args = [] 567 for arg in self.args: 568 if isinstance(arg, YAMLTag): 569 args.append(arg.resolve(entry, blueprint)) 570 else: 571 args.append(arg) 572 573 try: 574 return self.format_string % tuple(args) 575 except TypeError as exc: 576 raise EntryInvalidError.from_entry(exc, entry) from exc
Format a string
565 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 566 args = [] 567 for arg in self.args: 568 if isinstance(arg, YAMLTag): 569 args.append(arg.resolve(entry, blueprint)) 570 else: 571 args.append(arg) 572 573 try: 574 return self.format_string % tuple(args) 575 except TypeError as exc: 576 raise EntryInvalidError.from_entry(exc, entry) from exc
Implement yaml tag logic
579class Find(YAMLTag): 580 """Find any object primary key""" 581 582 model_name: str | YAMLTag 583 conditions: list[list] 584 585 def __init__(self, loader: BlueprintLoader, node: SequenceNode) -> None: 586 super().__init__() 587 self.model_name = loader.construct_object(node.value[0]) 588 self.conditions = [] 589 for raw_node in node.value[1:]: 590 values = [] 591 for node_values in raw_node.value: 592 values.append(loader.construct_object(node_values)) 593 self.conditions.append(values) 594 595 def _get_instance(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 596 if isinstance(self.model_name, YAMLTag): 597 model_name = self.model_name.resolve(entry, blueprint) 598 else: 599 model_name = self.model_name 600 601 try: 602 model_class = apps.get_model(*model_name.split(".")) 603 except LookupError as exc: 604 raise EntryInvalidError.from_entry(exc, entry) from exc 605 606 query = Q() 607 for cond in self.conditions: 608 if isinstance(cond[0], YAMLTag): 609 query_key = cond[0].resolve(entry, blueprint) 610 else: 611 query_key = cond[0] 612 if isinstance(cond[1], YAMLTag): 613 query_value = cond[1].resolve(entry, blueprint) 614 else: 615 query_value = cond[1] 616 query &= Q(**{query_key: query_value}) 617 return model_class.objects.filter(query).first() 618 619 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 620 instance = self._get_instance(entry, blueprint) 621 if instance: 622 return instance.pk 623 return None
Find any object primary key
585 def __init__(self, loader: BlueprintLoader, node: SequenceNode) -> None: 586 super().__init__() 587 self.model_name = loader.construct_object(node.value[0]) 588 self.conditions = [] 589 for raw_node in node.value[1:]: 590 values = [] 591 for node_values in raw_node.value: 592 values.append(loader.construct_object(node_values)) 593 self.conditions.append(values)
626class FindObject(Find): 627 """Find any object""" 628 629 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 630 instance = self._get_instance(entry, blueprint) 631 if not instance: 632 return None 633 if not isinstance(instance, SerializerModel): 634 raise EntryInvalidError.from_entry( 635 f"Model {self.model_name} is not resolvable through FindObject", entry 636 ) 637 return instance.serializer(instance=instance).data
Find any object
629 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 630 instance = self._get_instance(entry, blueprint) 631 if not instance: 632 return None 633 if not isinstance(instance, SerializerModel): 634 raise EntryInvalidError.from_entry( 635 f"Model {self.model_name} is not resolvable through FindObject", entry 636 ) 637 return instance.serializer(instance=instance).data
Implement yaml tag logic
Inherited Members
640class Condition(YAMLTag): 641 """Convert all values to a single boolean""" 642 643 mode: Literal["EQ", "NEQ", "AND", "NAND", "OR", "NOR", "XOR", "XNOR"] 644 args: list[Any] 645 646 _COMPARATORS = { 647 # Using all and any here instead of from operator import iand, ior 648 # to improve performance 649 "EQ": lambda args: all(x == args[0] for x in args), 650 "NEQ": lambda args: not all(x == args[0] for x in args), 651 "AND": all, 652 "NAND": lambda args: not all(args), 653 "OR": any, 654 "NOR": lambda args: not any(args), 655 "XOR": lambda args: reduce(ixor, args) if len(args) > 1 else args[0], 656 "XNOR": lambda args: not (reduce(ixor, args) if len(args) > 1 else args[0]), 657 } 658 659 def __init__(self, loader: BlueprintLoader, node: SequenceNode) -> None: 660 super().__init__() 661 self.mode = loader.construct_object(node.value[0]) 662 self.args = [] 663 for raw_node in node.value[1:]: 664 self.args.append(loader.construct_object(raw_node)) 665 666 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 667 args = [] 668 for arg in self.args: 669 if isinstance(arg, YAMLTag): 670 args.append(arg.resolve(entry, blueprint)) 671 else: 672 args.append(arg) 673 674 if not args: 675 raise EntryInvalidError.from_entry( 676 "At least one value is required after mode selection.", entry 677 ) 678 679 try: 680 comparator = self._COMPARATORS[self.mode.upper()] 681 return comparator(tuple(bool(x) for x in args)) 682 except (TypeError, KeyError) as exc: 683 raise EntryInvalidError.from_entry(exc, entry) from exc
Convert all values to a single boolean
666 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 667 args = [] 668 for arg in self.args: 669 if isinstance(arg, YAMLTag): 670 args.append(arg.resolve(entry, blueprint)) 671 else: 672 args.append(arg) 673 674 if not args: 675 raise EntryInvalidError.from_entry( 676 "At least one value is required after mode selection.", entry 677 ) 678 679 try: 680 comparator = self._COMPARATORS[self.mode.upper()] 681 return comparator(tuple(bool(x) for x in args)) 682 except (TypeError, KeyError) as exc: 683 raise EntryInvalidError.from_entry(exc, entry) from exc
Implement yaml tag logic
686class If(YAMLTag): 687 """Select YAML to use based on condition""" 688 689 condition: Any 690 when_true: Any 691 when_false: Any 692 693 def __init__(self, loader: BlueprintLoader, node: SequenceNode) -> None: 694 super().__init__() 695 self.condition = loader.construct_object(node.value[0]) 696 if len(node.value) == 1: 697 self.when_true = True 698 self.when_false = False 699 else: 700 self.when_true = loader.construct_object(node.value[1]) 701 self.when_false = loader.construct_object(node.value[2]) 702 703 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 704 if isinstance(self.condition, YAMLTag): 705 condition = self.condition.resolve(entry, blueprint) 706 else: 707 condition = self.condition 708 709 try: 710 return entry.tag_resolver( 711 self.when_true if condition else self.when_false, 712 blueprint, 713 ) 714 except TypeError as exc: 715 raise EntryInvalidError.from_entry(exc, entry) from exc
Select YAML to use based on condition
693 def __init__(self, loader: BlueprintLoader, node: SequenceNode) -> None: 694 super().__init__() 695 self.condition = loader.construct_object(node.value[0]) 696 if len(node.value) == 1: 697 self.when_true = True 698 self.when_false = False 699 else: 700 self.when_true = loader.construct_object(node.value[1]) 701 self.when_false = loader.construct_object(node.value[2])
703 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 704 if isinstance(self.condition, YAMLTag): 705 condition = self.condition.resolve(entry, blueprint) 706 else: 707 condition = self.condition 708 709 try: 710 return entry.tag_resolver( 711 self.when_true if condition else self.when_false, 712 blueprint, 713 ) 714 except TypeError as exc: 715 raise EntryInvalidError.from_entry(exc, entry) from exc
Implement yaml tag logic
718class Enumerate(YAMLTag, YAMLTagContext): 719 """Iterate over an iterable.""" 720 721 iterable: YAMLTag | Iterable 722 item_body: Any 723 output_body: Literal["SEQ", "MAP"] 724 725 _OUTPUT_BODIES = { 726 "SEQ": (list, lambda a, b: [*a, b]), 727 "MAP": ( 728 dict, 729 lambda a, b: always_merger.merge(a, {b[0]: b[1]} if isinstance(b, tuple | list) else b), 730 ), 731 } 732 733 def __init__(self, loader: BlueprintLoader, node: SequenceNode) -> None: 734 super().__init__() 735 self.iterable = loader.construct_object(node.value[0]) 736 self.output_body = loader.construct_object(node.value[1]) 737 self.item_body = loader.construct_object(node.value[2]) 738 self.__current_context: tuple[Any, Any] = tuple() 739 740 def get_context(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 741 return self.__current_context 742 743 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 744 if isinstance(self.iterable, EnumeratedItem) and self.iterable.depth == 0: 745 raise EntryInvalidError.from_entry( 746 f"{self.__class__.__name__} tag's iterable references this tag's context. " 747 "This is a noop. Check you are setting depth bigger than 0.", 748 entry, 749 ) 750 751 if isinstance(self.iterable, YAMLTag): 752 iterable = self.iterable.resolve(entry, blueprint) 753 else: 754 iterable = self.iterable 755 756 if not isinstance(iterable, Iterable): 757 raise EntryInvalidError.from_entry( 758 f"{self.__class__.__name__}'s iterable must be an iterable " 759 "such as a sequence or a mapping", 760 entry, 761 ) 762 763 if isinstance(iterable, Mapping): 764 iterable = tuple(iterable.items()) 765 else: 766 iterable = tuple(enumerate(iterable)) 767 768 try: 769 output_class, add_fn = self._OUTPUT_BODIES[self.output_body.upper()] 770 except KeyError as exc: 771 raise EntryInvalidError.from_entry(exc, entry) from exc 772 773 result = output_class() 774 775 self.__current_context = tuple() 776 777 try: 778 for item in iterable: 779 self.__current_context = item 780 resolved_body = entry.tag_resolver(self.item_body, blueprint) 781 result = add_fn(result, resolved_body) 782 if not isinstance(result, output_class): 783 raise EntryInvalidError.from_entry( 784 f"Invalid {self.__class__.__name__} item found: {resolved_body}", entry 785 ) 786 finally: 787 self.__current_context = tuple() 788 789 return result
Iterate over an iterable.
733 def __init__(self, loader: BlueprintLoader, node: SequenceNode) -> None: 734 super().__init__() 735 self.iterable = loader.construct_object(node.value[0]) 736 self.output_body = loader.construct_object(node.value[1]) 737 self.item_body = loader.construct_object(node.value[2]) 738 self.__current_context: tuple[Any, Any] = tuple()
740 def get_context(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 741 return self.__current_context
Implement yaml tag context logic
743 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 744 if isinstance(self.iterable, EnumeratedItem) and self.iterable.depth == 0: 745 raise EntryInvalidError.from_entry( 746 f"{self.__class__.__name__} tag's iterable references this tag's context. " 747 "This is a noop. Check you are setting depth bigger than 0.", 748 entry, 749 ) 750 751 if isinstance(self.iterable, YAMLTag): 752 iterable = self.iterable.resolve(entry, blueprint) 753 else: 754 iterable = self.iterable 755 756 if not isinstance(iterable, Iterable): 757 raise EntryInvalidError.from_entry( 758 f"{self.__class__.__name__}'s iterable must be an iterable " 759 "such as a sequence or a mapping", 760 entry, 761 ) 762 763 if isinstance(iterable, Mapping): 764 iterable = tuple(iterable.items()) 765 else: 766 iterable = tuple(enumerate(iterable)) 767 768 try: 769 output_class, add_fn = self._OUTPUT_BODIES[self.output_body.upper()] 770 except KeyError as exc: 771 raise EntryInvalidError.from_entry(exc, entry) from exc 772 773 result = output_class() 774 775 self.__current_context = tuple() 776 777 try: 778 for item in iterable: 779 self.__current_context = item 780 resolved_body = entry.tag_resolver(self.item_body, blueprint) 781 result = add_fn(result, resolved_body) 782 if not isinstance(result, output_class): 783 raise EntryInvalidError.from_entry( 784 f"Invalid {self.__class__.__name__} item found: {resolved_body}", entry 785 ) 786 finally: 787 self.__current_context = tuple() 788 789 return result
Implement yaml tag logic
792class EnumeratedItem(YAMLTag): 793 """Get the current item value and index provided by an Enumerate tag context""" 794 795 depth: int 796 797 _SUPPORTED_CONTEXT_TAGS = (Enumerate,) 798 799 def __init__(self, _loader: BlueprintLoader, node: ScalarNode) -> None: 800 super().__init__() 801 self.depth = int(node.value) 802 803 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 804 try: 805 context_tag: Enumerate = entry.get_tag_context( 806 depth=self.depth, 807 context_tag_type=EnumeratedItem._SUPPORTED_CONTEXT_TAGS, 808 ) 809 except ValueError as exc: 810 if self.depth == 0: 811 raise EntryInvalidError.from_entry( 812 f"{self.__class__.__name__} tags are only usable " 813 f"inside an {Enumerate.__name__} tag", 814 entry, 815 ) from exc 816 817 raise EntryInvalidError.from_entry( 818 f"{self.__class__.__name__} tag: {exc}", entry 819 ) from exc 820 821 return context_tag.get_context(entry, blueprint)
Get the current item value and index provided by an Enumerate tag context
803 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 804 try: 805 context_tag: Enumerate = entry.get_tag_context( 806 depth=self.depth, 807 context_tag_type=EnumeratedItem._SUPPORTED_CONTEXT_TAGS, 808 ) 809 except ValueError as exc: 810 if self.depth == 0: 811 raise EntryInvalidError.from_entry( 812 f"{self.__class__.__name__} tags are only usable " 813 f"inside an {Enumerate.__name__} tag", 814 entry, 815 ) from exc 816 817 raise EntryInvalidError.from_entry( 818 f"{self.__class__.__name__} tag: {exc}", entry 819 ) from exc 820 821 return context_tag.get_context(entry, blueprint)
Implement yaml tag logic
824class Index(EnumeratedItem): 825 """Get the current item index provided by an Enumerate tag context""" 826 827 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 828 context = super().resolve(entry, blueprint) 829 830 try: 831 return context[0] 832 except IndexError as exc: # pragma: no cover 833 raise EntryInvalidError.from_entry(f"Empty/invalid context: {context}", entry) from exc
Get the current item index provided by an Enumerate tag context
827 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 828 context = super().resolve(entry, blueprint) 829 830 try: 831 return context[0] 832 except IndexError as exc: # pragma: no cover 833 raise EntryInvalidError.from_entry(f"Empty/invalid context: {context}", entry) from exc
Implement yaml tag logic
Inherited Members
836class Value(EnumeratedItem): 837 """Get the current item value provided by an Enumerate tag context""" 838 839 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 840 context = super().resolve(entry, blueprint) 841 842 try: 843 return context[1] 844 except IndexError as exc: # pragma: no cover 845 raise EntryInvalidError.from_entry(f"Empty/invalid context: {context}", entry) from exc
Get the current item value provided by an Enumerate tag context
839 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 840 context = super().resolve(entry, blueprint) 841 842 try: 843 return context[1] 844 except IndexError as exc: # pragma: no cover 845 raise EntryInvalidError.from_entry(f"Empty/invalid context: {context}", entry) from exc
Implement yaml tag logic
Inherited Members
848class AtIndex(YAMLTag): 849 """Get value at index of a sequence or mapping""" 850 851 obj: YAMLTag | dict | list | tuple 852 attribute: int | str | YAMLTag 853 default: Any | UNSET 854 855 def __init__(self, loader: BlueprintLoader, node: SequenceNode) -> None: 856 super().__init__() 857 self.obj = loader.construct_object(node.value[0]) 858 self.attribute = loader.construct_object(node.value[1]) 859 if len(node.value) == 2: # noqa: PLR2004 860 self.default = UNSET 861 else: 862 self.default = loader.construct_object(node.value[2]) 863 864 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 865 if isinstance(self.obj, YAMLTag): 866 obj = self.obj.resolve(entry, blueprint) 867 else: 868 obj = self.obj 869 if isinstance(self.attribute, YAMLTag): 870 attribute = self.attribute.resolve(entry, blueprint) 871 else: 872 attribute = self.attribute 873 874 if isinstance(obj, list | tuple): 875 try: 876 return obj[attribute] 877 except TypeError as exc: 878 raise EntryInvalidError.from_entry( 879 f"Invalid index for list: {attribute}", entry 880 ) from exc 881 except IndexError as exc: 882 if self.default is UNSET: 883 raise EntryInvalidError.from_entry( 884 f"Index out of range: {attribute}", entry 885 ) from exc 886 return self.default 887 if attribute in obj: 888 return obj[attribute] 889 else: 890 if self.default is UNSET: 891 raise EntryInvalidError.from_entry(f"Key does not exist: {attribute}", entry) 892 return self.default
Get value at index of a sequence or mapping
855 def __init__(self, loader: BlueprintLoader, node: SequenceNode) -> None: 856 super().__init__() 857 self.obj = loader.construct_object(node.value[0]) 858 self.attribute = loader.construct_object(node.value[1]) 859 if len(node.value) == 2: # noqa: PLR2004 860 self.default = UNSET 861 else: 862 self.default = loader.construct_object(node.value[2])
864 def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any: 865 if isinstance(self.obj, YAMLTag): 866 obj = self.obj.resolve(entry, blueprint) 867 else: 868 obj = self.obj 869 if isinstance(self.attribute, YAMLTag): 870 attribute = self.attribute.resolve(entry, blueprint) 871 else: 872 attribute = self.attribute 873 874 if isinstance(obj, list | tuple): 875 try: 876 return obj[attribute] 877 except TypeError as exc: 878 raise EntryInvalidError.from_entry( 879 f"Invalid index for list: {attribute}", entry 880 ) from exc 881 except IndexError as exc: 882 if self.default is UNSET: 883 raise EntryInvalidError.from_entry( 884 f"Index out of range: {attribute}", entry 885 ) from exc 886 return self.default 887 if attribute in obj: 888 return obj[attribute] 889 else: 890 if self.default is UNSET: 891 raise EntryInvalidError.from_entry(f"Key does not exist: {attribute}", entry) 892 return self.default
Implement yaml tag logic
895class BlueprintDumper(SafeDumper): 896 """Dump dataclasses to yaml""" 897 898 default_flow_style = False 899 900 def __init__(self, *args, **kwargs): 901 super().__init__(*args, **kwargs) 902 self.add_representer(UUID, lambda self, data: self.represent_str(str(data))) 903 self.add_representer(OrderedDict, lambda self, data: self.represent_dict(dict(data))) 904 self.add_representer(Enum, lambda self, data: self.represent_str(data.value)) 905 self.add_representer( 906 BlueprintEntryDesiredState, lambda self, data: self.represent_str(data.value) 907 ) 908 self.add_representer( 909 KeyOf, lambda self, data: self.represent_scalar("!KeyOf", data.id_from) 910 ) 911 self.add_representer(None, lambda self, data: self.represent_str(str(data))) 912 913 def ignore_aliases(self, data): 914 """Don't use any YAML anchors""" 915 return True 916 917 def represent(self, data) -> None: 918 if is_dataclass(data): 919 920 def factory(items): 921 final_dict = dict(items) 922 # Remove internal state variables 923 final_dict.pop("_state", None) 924 # Future-proof to only remove the ID if we don't set a value 925 if "id" in final_dict and final_dict.get("id") is None: 926 final_dict.pop("id") 927 return final_dict 928 929 data = asdict(data, dict_factory=factory) 930 return super().represent(data)
Dump dataclasses to yaml
900 def __init__(self, *args, **kwargs): 901 super().__init__(*args, **kwargs) 902 self.add_representer(UUID, lambda self, data: self.represent_str(str(data))) 903 self.add_representer(OrderedDict, lambda self, data: self.represent_dict(dict(data))) 904 self.add_representer(Enum, lambda self, data: self.represent_str(data.value)) 905 self.add_representer( 906 BlueprintEntryDesiredState, lambda self, data: self.represent_str(data.value) 907 ) 908 self.add_representer( 909 KeyOf, lambda self, data: self.represent_scalar("!KeyOf", data.id_from) 910 ) 911 self.add_representer(None, lambda self, data: self.represent_str(str(data)))
917 def represent(self, data) -> None: 918 if is_dataclass(data): 919 920 def factory(items): 921 final_dict = dict(items) 922 # Remove internal state variables 923 final_dict.pop("_state", None) 924 # Future-proof to only remove the ID if we don't set a value 925 if "id" in final_dict and final_dict.get("id") is None: 926 final_dict.pop("id") 927 return final_dict 928 929 data = asdict(data, dict_factory=factory) 930 return super().represent(data)
933class BlueprintLoader(SafeLoader): 934 """Loader for blueprints with custom tag support""" 935 936 def __init__(self, *args, **kwargs): 937 super().__init__(*args, **kwargs) 938 self.add_constructor("!KeyOf", KeyOf) 939 self.add_constructor("!Find", Find) 940 self.add_constructor("!FindObject", FindObject) 941 self.add_constructor("!Context", Context) 942 self.add_constructor("!Format", Format) 943 self.add_constructor("!Condition", Condition) 944 self.add_constructor("!If", If) 945 self.add_constructor("!Env", Env) 946 self.add_constructor("!File", File) 947 self.add_constructor("!Enumerate", Enumerate) 948 self.add_constructor("!Value", Value) 949 self.add_constructor("!Index", Index) 950 self.add_constructor("!AtIndex", AtIndex) 951 self.add_constructor("!ParseJSON", ParseJSON)
Loader for blueprints with custom tag support
936 def __init__(self, *args, **kwargs): 937 super().__init__(*args, **kwargs) 938 self.add_constructor("!KeyOf", KeyOf) 939 self.add_constructor("!Find", Find) 940 self.add_constructor("!FindObject", FindObject) 941 self.add_constructor("!Context", Context) 942 self.add_constructor("!Format", Format) 943 self.add_constructor("!Condition", Condition) 944 self.add_constructor("!If", If) 945 self.add_constructor("!Env", Env) 946 self.add_constructor("!File", File) 947 self.add_constructor("!Enumerate", Enumerate) 948 self.add_constructor("!Value", Value) 949 self.add_constructor("!Index", Index) 950 self.add_constructor("!AtIndex", AtIndex) 951 self.add_constructor("!ParseJSON", ParseJSON)
Initialize the scanner.
954class EntryInvalidError(TracingIgnoredException): 955 """Error raised when an entry is invalid""" 956 957 entry_model: str | None 958 entry_id: str | None 959 validation_error: ValidationError | None 960 serializer: Serializer | None = None 961 962 def __init__( 963 self, *args: object, validation_error: ValidationError | None = None, **kwargs 964 ) -> None: 965 super().__init__(*args) 966 self.entry_model = None 967 self.entry_id = None 968 self.validation_error = validation_error 969 for key, value in kwargs.items(): 970 setattr(self, key, value) 971 972 @staticmethod 973 def from_entry( 974 msg_or_exc: str | Exception, entry: BlueprintEntry, *args, **kwargs 975 ) -> EntryInvalidError: 976 """Create EntryInvalidError with the context of an entry""" 977 error = EntryInvalidError(msg_or_exc, *args, **kwargs) 978 if isinstance(msg_or_exc, ValidationError): 979 error.validation_error = msg_or_exc 980 # Make sure the model and id are strings, depending where the error happens 981 # they might still be YAMLTag instances 982 error.entry_model = str(entry.model) 983 error.entry_id = str(entry.id) 984 return error
Error raised when an entry is invalid
962 def __init__( 963 self, *args: object, validation_error: ValidationError | None = None, **kwargs 964 ) -> None: 965 super().__init__(*args) 966 self.entry_model = None 967 self.entry_id = None 968 self.validation_error = validation_error 969 for key, value in kwargs.items(): 970 setattr(self, key, value)
972 @staticmethod 973 def from_entry( 974 msg_or_exc: str | Exception, entry: BlueprintEntry, *args, **kwargs 975 ) -> EntryInvalidError: 976 """Create EntryInvalidError with the context of an entry""" 977 error = EntryInvalidError(msg_or_exc, *args, **kwargs) 978 if isinstance(msg_or_exc, ValidationError): 979 error.validation_error = msg_or_exc 980 # Make sure the model and id are strings, depending where the error happens 981 # they might still be YAMLTag instances 982 error.entry_model = str(entry.model) 983 error.entry_id = str(entry.id) 984 return error
Create EntryInvalidError with the context of an entry