Debian Codegraph @

lib/ansible/utils/unsafe_proxy.py

raw
1 # Copyright: (c) 2023, Ansible Project
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 # deprecated: description="deprecate unsafe_proxy module" core_version="2.23"
5 # DTFIX5: add full unit test coverage
6 from __future__ import annotations
7
8 from collections.abc import Mapping, Set
9
10 from ansible.module_utils._internal import _no_six
11 from ansible.module_utils.common.text.converters import to_bytes, to_text
12 from ansible.module_utils.common.collections import is_sequence
13 from ansible._internal._datatag._tags import TrustedAsTemplate
14
15 __all__ = ['AnsibleUnsafe', 'wrap_var']
16
17
18 class AnsibleUnsafe:
19 def __new__(cls, value):
20 return TrustedAsTemplate.untag(value)
21
22
23 class AnsibleUnsafeBytes(bytes):
24 def __new__(cls, value):
25 return TrustedAsTemplate.untag(value)
26
27
28 class AnsibleUnsafeText(str):
29 def __new__(cls, value):
30 return TrustedAsTemplate.untag(value)
31
32
33 class NativeJinjaUnsafeText(str):
34 def __new__(cls, value):
35 return TrustedAsTemplate.untag(value)
36
37
38 def _wrap_dict(v):
39 return dict((wrap_var(k), wrap_var(item)) for k, item in v.items())
40
41
42 def _wrap_sequence(v):
43 """Wraps a sequence with unsafe, not meant for strings, primarily
44 ``tuple`` and ``list``
45 """
46 v_type = type(v)
47 return v_type(wrap_var(item) for item in v)
48
49
50 def _wrap_set(v):
51 return set(wrap_var(item) for item in v)
52
53
54 def wrap_var(v):
55 # maintain backward compat by recursively *un* marking TrustedAsTemplate
56 if v is None or isinstance(v, AnsibleUnsafe):
57 return v
58
59 if isinstance(v, Mapping):
60 v = _wrap_dict(v)
61 elif isinstance(v, Set):
62 v = _wrap_set(v)
63 elif is_sequence(v):
64 v = _wrap_sequence(v)
65 elif isinstance(v, bytes):
66 v = AnsibleUnsafeBytes(v)
67 elif isinstance(v, str):
68 v = AnsibleUnsafeText(v)
69
70 return v
71
72
73 def to_unsafe_bytes(*args, **kwargs):
74 return wrap_var(to_bytes(*args, **kwargs))
75
76
77 def to_unsafe_text(*args, **kwargs):
78 return wrap_var(to_text(*args, **kwargs))
79
80
81 def __getattr__(importable_name):
82 return _no_six.deprecate(importable_name, __name__, "binary_type", "text_type")