summaryrefslogtreecommitdiff
path: root/lib/ansible/utils/unsafe_proxy.py
blob: 683f6e27df6a5d1367abfde4ca0431b967d21ba6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
# PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
# --------------------------------------------
#
# 1. This LICENSE AGREEMENT is between the Python Software Foundation
# ("PSF"), and the Individual or Organization ("Licensee") accessing and
# otherwise using this software ("Python") in source or binary form and
# its associated documentation.
#
# 2. Subject to the terms and conditions of this License Agreement, PSF hereby
# grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
# analyze, test, perform and/or display publicly, prepare derivative works,
# distribute, and otherwise use Python alone or in any derivative version,
# provided, however, that PSF's License Agreement and PSF's notice of copyright,
# i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
# 2011, 2012, 2013, 2014 Python Software Foundation; All Rights Reserved" are
# retained in Python alone or in any derivative version prepared by Licensee.
#
# 3. In the event Licensee prepares a derivative work that is based on
# or incorporates Python or any part thereof, and wants to make
# the derivative work available to others as provided herein, then
# Licensee hereby agrees to include in any such work a brief summary of
# the changes made to Python.
#
# 4. PSF is making Python available to Licensee on an "AS IS"
# basis.  PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
# IMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
# DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
# FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
# INFRINGE ANY THIRD PARTY RIGHTS.
#
# 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
# FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
# A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
# OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
#
# 6. This License Agreement will automatically terminate upon a material
# breach of its terms and conditions.
#
# 7. Nothing in this License Agreement shall be deemed to create any
# relationship of agency, partnership, or joint venture between PSF and
# Licensee.  This License Agreement does not grant permission to use PSF
# trademarks or trade name in a trademark sense to endorse or promote
# products or services of Licensee, or any third party.
#
# 8. By copying, installing or otherwise using Python, Licensee
# agrees to be bound by the terms and conditions of this License
# Agreement.
#
# Original Python Recipe for Proxy:
# http://code.activestate.com/recipes/496741-object-proxying/
# Author: Tomer Filiba

from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

from collections.abc import Mapping, Set

from ansible.module_utils._text import to_bytes, to_text
from ansible.module_utils.common.collections import is_sequence
from ansible.utils.native_jinja import NativeJinjaText


__all__ = ['AnsibleUnsafe', 'wrap_var']


class AnsibleUnsafe(object):
    __UNSAFE__ = True


class AnsibleUnsafeBytes(bytes, AnsibleUnsafe):
    def _strip_unsafe(self):
        return super().__bytes__()

    def __reduce__(self, /):
        return (self.__class__, (self._strip_unsafe(),))

    def __str__(self, /):  # pylint: disable=invalid-str-returned
        return self.decode()

    def __bytes__(self, /):  # pylint: disable=invalid-bytes-returned
        return self

    def __repr__(self, /):  # pylint: disable=invalid-repr-returned
        return AnsibleUnsafeText(super().__repr__())

    def __format__(self, format_spec, /):  # pylint: disable=invalid-format-returned
        return AnsibleUnsafeText(super().__format__(format_spec))

    def __getitem__(self, key, /):
        if isinstance(key, int):
            return super().__getitem__(key)
        return self.__class__(super().__getitem__(key))

    def __reversed__(self, /):
        return self[::-1]

    def __add__(self, value, /):
        return self.__class__(super().__add__(value))

    def __radd__(self, value, /):
        return self.__class__(value.__add__(self))

    def __mul__(self, value, /):
        return self.__class__(super().__mul__(value))

    __rmul__ = __mul__

    def __mod__(self, value, /):
        return self.__class__(super().__mod__(value))

    def __rmod__(self, value, /):
        return self.__class__(super().__rmod__(value))

    def capitalize(self, /):
        return self.__class__(super().capitalize())

    def center(self, width, fillchar=b' ', /):
        return self.__class__(super().center(width, fillchar))

    def decode(self, /, encoding='utf-8', errors='strict'):
        return AnsibleUnsafeText(super().decode(encoding=encoding, errors=errors))

    def removeprefix(self, prefix, /):
        return self.__class__(super().removeprefix(prefix))

    def removesuffix(self, suffix, /):
        return self.__class__(super().removesuffix(suffix))

    def expandtabs(self, /, tabsize=8):
        return self.__class__(super().expandtabs(tabsize))

    def join(self, iterable_of_bytes, /):
        return self.__class__(super().join(iterable_of_bytes))

    def ljust(self, width, fillchar=b' ', /):
        return self.__class__(super().ljust(width, fillchar))

    def lower(self, /):
        return self.__class__(super().lower())

    def lstrip(self, chars=None, /):
        return self.__class__(super().lstrip(chars))

    def partition(self, sep, /):
        cls = self.__class__
        return tuple(cls(e) for e in super().partition(sep))

    def replace(self, old, new, count=-1, /):
        return self.__class__(super().replace(old, new, count))

    def rjust(self, width, fillchar=b' ', /):
        return self.__class__(super().rjust(width, fillchar))

    def rpartition(self, sep, /):
        cls = self.__class__
        return tuple(cls(e) for e in super().rpartition(sep))

    def rstrip(self, chars=None, /):
        return self.__class__(super().rstrip(chars))

    def split(self, /, sep=None, maxsplit=-1):
        cls = self.__class__
        return [cls(e) for e in super().split(sep=sep, maxsplit=maxsplit)]

    def rsplit(self, /, sep=None, maxsplit=-1):
        cls = self.__class__
        return [cls(e) for e in super().rsplit(sep=sep, maxsplit=maxsplit)]

    def splitlines(self, /, keepends=False):
        cls = self.__class__
        return [cls(e) for e in super().splitlines(keepends=keepends)]

    def strip(self, chars=None, /):
        return self.__class__(super().strip(chars))

    def swapcase(self, /):
        return self.__class__(super().swapcase())

    def title(self, /):
        return self.__class__(super().title())

    def translate(self, table, /, delete=b''):
        return self.__class__(super().translate(table, delete=delete))

    def upper(self, /):
        return self.__class__(super().upper())

    def zfill(self, width, /):
        return self.__class__(super().zfill(width))


class AnsibleUnsafeText(str, AnsibleUnsafe):
    def _strip_unsafe(self, /):
        return super().__str__()

    def __reduce__(self, /):
        return (self.__class__, (self._strip_unsafe(),))

    def __str__(self, /):  # pylint: disable=invalid-str-returned
        return self

    def __repr__(self, /):  # pylint: disable=invalid-repr-returned
        return self.__class__(super().__repr__())

    def __format__(self, format_spec, /):  # pylint: disable=invalid-format-returned
        return self.__class__(super().__format__(format_spec))

    def __getitem__(self, key, /):
        return self.__class__(super().__getitem__(key))

    def __iter__(self, /):
        cls = self.__class__
        return (cls(c) for c in super().__iter__())

    def __reversed__(self, /):
        return self[::-1]

    def __add__(self, value, /):
        return self.__class__(super().__add__(value))

    def __radd__(self, value, /):
        return self.__class__(value.__add__(self))

    def __mul__(self, value, /):
        return self.__class__(super().__mul__(value))

    __rmul__ = __mul__

    def __mod__(self, value, /):
        return self.__class__(super().__mod__(value))

    def __rmod__(self, value, /):
        return self.__class__(super().__rmod__(value))

    def capitalize(self, /):
        return self.__class__(super().capitalize())

    def casefold(self, /):
        return self.__class__(super().casefold())

    def center(self, width, fillchar=' ', /):
        return self.__class__(super().center(width, fillchar))

    def encode(self, /, encoding='utf-8', errors='strict'):
        return AnsibleUnsafeBytes(super().encode(encoding=encoding, errors=errors))

    def removeprefix(self, prefix, /):
        return self.__class__(super().removeprefix(prefix))

    def removesuffix(self, suffix, /):
        return self.__class__(super().removesuffix(suffix))

    def expandtabs(self, /, tabsize=8):
        return self.__class__(super().expandtabs(tabsize))

    def format(self, /, *args, **kwargs):
        return self.__class__(super().format(*args, **kwargs))

    def format_map(self, mapping, /):
        return self.__class__(super().format_map(mapping))

    def join(self, iterable, /):
        return self.__class__(super().join(iterable))

    def ljust(self, width, fillchar=' ', /):
        return self.__class__(super().ljust(width, fillchar))

    def lower(self, /):
        return self.__class__(super().lower())

    def lstrip(self, chars=None, /):
        return self.__class__(super().lstrip(chars))

    def partition(self, sep, /):
        cls = self.__class__
        return tuple(cls(e) for e in super().partition(sep))

    def replace(self, old, new, count=-1, /):
        return self.__class__(super().replace(old, new, count))

    def rjust(self, width, fillchar=' ', /):
        return self.__class__(super().rjust(width, fillchar))

    def rpartition(self, sep, /):
        cls = self.__class__
        return tuple(cls(e) for e in super().rpartition(sep))

    def rstrip(self, chars=None, /):
        return self.__class__(super().rstrip(chars))

    def split(self, /, sep=None, maxsplit=-1):
        cls = self.__class__
        return [cls(e) for e in super().split(sep=sep, maxsplit=maxsplit)]

    def rsplit(self, /, sep=None, maxsplit=-1):
        cls = self.__class__
        return [cls(e) for e in super().rsplit(sep=sep, maxsplit=maxsplit)]

    def splitlines(self, /, keepends=False):
        cls = self.__class__
        return [cls(e) for e in super().splitlines(keepends=keepends)]

    def strip(self, chars=None, /):
        return self.__class__(super().strip(chars))

    def swapcase(self, /):
        return self.__class__(super().swapcase())

    def title(self, /):
        return self.__class__(super().title())

    def translate(self, table, /):
        return self.__class__(super().translate(table))

    def upper(self, /):
        return self.__class__(super().upper())

    def zfill(self, width, /):
        return self.__class__(super().zfill(width))


class NativeJinjaUnsafeText(NativeJinjaText, AnsibleUnsafeText):
    pass


def _wrap_dict(v):
    return dict((wrap_var(k), wrap_var(item)) for k, item in v.items())


def _wrap_sequence(v):
    """Wraps a sequence with unsafe, not meant for strings, primarily
    ``tuple`` and ``list``
    """
    v_type = type(v)
    return v_type(wrap_var(item) for item in v)


def _wrap_set(v):
    return set(wrap_var(item) for item in v)


def wrap_var(v):
    if v is None or isinstance(v, AnsibleUnsafe):
        return v

    if isinstance(v, Mapping):
        v = _wrap_dict(v)
    elif isinstance(v, Set):
        v = _wrap_set(v)
    elif is_sequence(v):
        v = _wrap_sequence(v)
    elif isinstance(v, NativeJinjaText):
        v = NativeJinjaUnsafeText(v)
    elif isinstance(v, bytes):
        v = AnsibleUnsafeBytes(v)
    elif isinstance(v, str):
        v = AnsibleUnsafeText(v)

    return v


def to_unsafe_bytes(*args, **kwargs):
    return wrap_var(to_bytes(*args, **kwargs))


def to_unsafe_text(*args, **kwargs):
    return wrap_var(to_text(*args, **kwargs))


def _is_unsafe(obj):
    return getattr(obj, '__UNSAFE__', False) is True