Debian Codegraph @

lib/ansible/_internal/_json/__init__.py

raw
1 """Internal utilities for serialization and deserialization."""
2
3 # DTFIX-FUTURE: most of this isn't JSON specific, find a better home
4
5 from __future__ import annotations
6
7 import enum
8 import json
9 import typing as t
10
11 from ansible.errors import AnsibleVariableTypeError
12
13 from ansible.module_utils._internal._datatag import (
14 _ANSIBLE_ALLOWED_MAPPING_VAR_TYPES,
15 _ANSIBLE_ALLOWED_NON_SCALAR_COLLECTION_VAR_TYPES,
16 _ANSIBLE_ALLOWED_VAR_TYPES,
17 _AnsibleTaggedStr,
18 AnsibleTagHelper,
19 )
20 from ansible.module_utils._internal._json._profiles import _tagless
21 from ansible.module_utils.secrets import mask_secrets
22 from ansible.parsing.vault import EncryptedString
23 from ansible._internal._datatag._tags import Origin, TrustedAsTemplate
24 from ansible._internal._templating import _transform
25 from ansible.module_utils import _internal
26 from ansible.module_utils._internal import _datatag
27
28 _sentinel = object()
29
30
31 class HasCurrent(t.Protocol):
32 """Utility protocol for mixin type safety."""
33
34 _current: t.Any
35
36
37 class StateTrackingMixIn(HasCurrent):
38 """Mixin for use with `AnsibleVariableVisitor` to track current visitation context."""
39
40 def __init__(self, *args, **kwargs) -> None:
41 super().__init__(*args, **kwargs)
42
43 self._stack: list[t.Any] = []
44
45 def __enter__(self) -> None:
46 self._stack.append(self._current)
47
48 def __exit__(self, *_args, **_kwargs) -> None:
49 self._stack.pop()
50
51 def _get_stack(self) -> list[t.Any]:
52 if not self._stack:
53 return []
54
55 return self._stack[1:] + [self._current]
56
57
58 class EncryptedStringBehavior(enum.Enum):
59 """How `AnsibleVariableVisitor` will handle instances of `EncryptedString`."""
60
61 PRESERVE = enum.auto()
62 """Preserves the unmodified `EncryptedString` instance."""
63 DECRYPT = enum.auto()
64 """Replaces the value with its decrypted plaintext."""
65 REDACT = enum.auto()
66 """Replaces the value with a placeholder string."""
67 FAIL = enum.auto()
68 """Raises an `AnsibleVariableTypeError` error."""
69
70
71 class AnsibleVariableVisitor:
72 """Utility visitor base class to recursively apply various behaviors and checks to variable object graphs."""
73
74 def __init__(
75 self,
76 *,
77 trusted_as_template: bool = False,
78 origin: Origin | None = None,
79 convert_mapping_to_dict: bool = False,
80 convert_sequence_to_list: bool = False,
81 convert_custom_scalars: bool = False,
82 convert_to_native_values: bool = False,
83 apply_transforms: bool = False,
84 visit_keys: bool = False,
85 encrypted_string_behavior: EncryptedStringBehavior = EncryptedStringBehavior.DECRYPT,
86 # deprecated: description='Remove mask_secret_values', core_version='2.27'
87 mask_secret_values: bool = False,
88 ):
89 super().__init__() # supports StateTrackingMixIn
90
91 self.trusted_as_template = trusted_as_template
92 self.origin = origin
93 self.convert_mapping_to_dict = convert_mapping_to_dict
94 self.convert_sequence_to_list = convert_sequence_to_list
95 self.convert_custom_scalars = convert_custom_scalars
96 self.convert_to_native_values = convert_to_native_values
97 self.apply_transforms = apply_transforms
98 self.visit_keys = visit_keys
99 self.encrypted_string_behavior = encrypted_string_behavior
100 self._mask_secret_values = mask_secret_values
101
102 if apply_transforms:
103 from ansible._internal._templating import _engine
104
105 self._template_engine = _engine.TemplateEngine()
106 else:
107 self._template_engine = None
108
109 self._current: t.Any = None # supports StateTrackingMixIn
110
111 def __enter__(self) -> t.Any:
112 """No-op context manager dispatcher (delegates to mixin behavior if present)."""
113 if func := getattr(super(), '__enter__', None):
114 func()
115
116 def __exit__(self, *args, **kwargs) -> t.Any:
117 """No-op context manager dispatcher (delegates to mixin behavior if present)."""
118 if func := getattr(super(), '__exit__', None):
119 func(*args, **kwargs)
120
121 def visit[T](self, value: T) -> T:
122 """
123 Enforces Ansible's variable type system restrictions before a var is accepted in inventory. Also, conditionally implements template trust
124 compatibility, depending on the plugin's declared understanding (or lack thereof). This always recursively copies inputs to fully isolate
125 inventory data from what the plugin provided, and prevent any later mutation.
126 """
127 return self._visit(None, value)
128
129 def _early_visit(self, value, value_type) -> t.Any:
130 """Overridable hook point to allow custom string handling in derived visitors."""
131 if value_type in (str, _AnsibleTaggedStr):
132 # apply compatibility behavior
133 if self.trusted_as_template:
134 result = TrustedAsTemplate().tag(value)
135 else:
136 result = value
137 else:
138 result = _sentinel
139
140 return result
141
142 def _visit_key(self, key: t.Any) -> t.Any:
143 """Internal implementation to recursively visit a key if visit_keys is enabled."""
144 if not self.visit_keys:
145 return key
146
147 return self._visit(None, key) # key=None prevents state tracking from seeing the key as value
148
149 def _visit[T](self, key: t.Any, value: T) -> T:
150 """Internal implementation to recursively visit a data structure's contents."""
151 self._current = key # supports StateTrackingMixIn
152
153 value_type: type = type(value)
154
155 # handle EncryptedString conversion before more generic transformation and native conversions
156 if value_type is EncryptedString: # pylint: disable=unidiomatic-typecheck
157 match self.encrypted_string_behavior:
158 case EncryptedStringBehavior.DECRYPT:
159 value = str(value) # type: ignore[assignment]
160 value_type = str
161 case EncryptedStringBehavior.REDACT:
162 value = "<redacted>" # type: ignore[assignment]
163 value_type = str
164 case EncryptedStringBehavior.FAIL:
165 raise AnsibleVariableTypeError.from_value(obj=value)
166 elif self.apply_transforms and value_type in _transform._type_transform_mapping:
167 value = self._template_engine.transform(value)
168 value_type = type(value)
169
170 if self.convert_to_native_values and isinstance(value, _datatag.AnsibleTaggedObject):
171 value = value._native_copy()
172 value_type = type(value)
173
174 result: T
175
176 # DTFIX-FUTURE: Visitor generally ignores dict/mapping keys by default except for debugging and schema-aware checking.
177 # It could be checking keys destined for variable storage to apply more strict rules about key shape and type.
178
179 if (result := self._early_visit(value, value_type)) is not _sentinel:
180 pass
181 # DTFIX7: de-duplicate and optimize; extract inline generator expressions and fallback function or mapping for native type calculation?
182 elif value_type in _ANSIBLE_ALLOWED_MAPPING_VAR_TYPES: # check mappings first, because they're also collections
183 with self: # supports StateTrackingMixIn
184 result = AnsibleTagHelper.tag_copy(value, ((self._visit_key(k), self._visit(k, v)) for k, v in value.items()), value_type=value_type)
185 elif value_type in _ANSIBLE_ALLOWED_NON_SCALAR_COLLECTION_VAR_TYPES:
186 with self: # supports StateTrackingMixIn
187 result = AnsibleTagHelper.tag_copy(value, (self._visit(k, v) for k, v in enumerate(t.cast(t.Iterable, value))), value_type=value_type)
188 elif self.convert_mapping_to_dict and _internal.is_intermediate_mapping(value):
189 with self: # supports StateTrackingMixIn
190 result = {self._visit_key(k): self._visit(k, v) for k, v in value.items()} # type: ignore[assignment]
191 elif self.convert_sequence_to_list and _internal.is_intermediate_iterable(value):
192 with self: # supports StateTrackingMixIn
193 result = [self._visit(k, v) for k, v in enumerate(t.cast(t.Iterable, value))] # type: ignore[assignment]
194 elif self.convert_custom_scalars and isinstance(value, str):
195 result = str(value) # type: ignore[assignment]
196 elif self.convert_custom_scalars and isinstance(value, float):
197 result = float(value) # type: ignore[assignment]
198 elif self.convert_custom_scalars and isinstance(value, int) and not isinstance(value, bool):
199 result = int(value) # type: ignore[assignment]
200 elif value_type in _ANSIBLE_ALLOWED_VAR_TYPES:
201 # supported scalar type that requires no special handling, just return as-is
202 result = value
203 elif self.encrypted_string_behavior is EncryptedStringBehavior.PRESERVE and isinstance(value, EncryptedString):
204 result = value # type: ignore[assignment]
205 else:
206 raise AnsibleVariableTypeError.from_value(obj=value)
207
208 if self.origin and not Origin.is_tagged_on(result):
209 # apply shared instance default origin tag
210 result = self.origin.tag(result)
211
212 if self._mask_secret_values and isinstance(result, str):
213 result = mask_secrets(result) # type: ignore[assignment]
214
215 return result
216
217
218 def json_dumps_formatted(value: object) -> str:
219 """Return a JSON dump of `value` with formatting and keys sorted."""
220 return json.dumps(value, cls=_tagless.Encoder, sort_keys=True, indent=4)