-
Notifications
You must be signed in to change notification settings - Fork 1
/
playbook_read.py
650 lines (522 loc) · 24.5 KB
/
playbook_read.py
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
"""TcEx Framework Module"""
# standard library
import base64
import json
import logging
import re
from collections import OrderedDict
from typing import Any
from ...app.key_value_store.key_value_store import KeyValueStore
from ...input.field_type.sensitive import Sensitive
from ...registry import registry
from ...util.util import Util
from ...util.variable import BinaryVariable, StringVariable
# get logger
_logger = logging.getLogger(__name__.split('.', maxsplit=1)[0])
class PlaybookRead:
"""Playbook Read
Args:
key_value_store: A KV store instance.
context: The KV Store context/session_id. For PB Apps the context is provided on
startup, but for service Apps each request gets a different context.
output_variables: The requested output variables. For PB Apps outputs are provided on
startup, but for service Apps each request gets different outputs.
"""
def __init__(self, context: str, key_value_store: KeyValueStore):
"""Initialize the class properties."""
self.context = context
self.key_value_store = key_value_store
# properties
self.log = _logger
self.util = Util()
def _check_variable_type(self, variable: str, type_: str):
"""Validate the correct type was passed to the method."""
if self.util.get_playbook_variable_type(variable).lower() != type_.lower():
raise RuntimeError(
f'Invalid variable provided ({variable}), variable must be of type {type_}.'
)
@staticmethod
def _coerce_string_value(value: bool | float | int | str | Sensitive) -> str | Sensitive:
"""Return a string value from an bool or int."""
# coerce bool before int as python says a bool is an int
if isinstance(value, bool):
# coerce bool to str type
value = str(value).lower()
# coerce int to str type
if isinstance(value, float | int):
value = str(value)
return value
@staticmethod
def _decode_binary(data: bytes) -> str:
"""Return decoded bytes data handling data written by java apps."""
try:
_data = data.decode('utf-8')
except UnicodeDecodeError: # pragma: no cover
# for data written an upstream java App
_data = data.decode('latin-1')
return _data
@staticmethod
def _deserialize_data(value: bytes | str) -> Any:
"""Return the loaded JSON value or raise an error."""
try:
return json.loads(value, object_pairs_hook=OrderedDict)
except ValueError as ex: # pragma: no cover
raise RuntimeError(f'Failed to JSON load data "{value}" ({ex}).') from ex
def _get_data(self, key: str) -> bytes | str | None:
"""Get the value from Redis if applicable."""
try:
return self.key_value_store.client.read(self.context, key.strip())
except RuntimeError as ex:
self.log.error(ex)
return None
@staticmethod
def _load_data(value: str) -> dict | list[dict | str] | str:
"""Return the loaded JSON value or raise an error."""
try:
return json.loads(value, object_pairs_hook=OrderedDict)
except ValueError as ex: # pragma: no cover
raise RuntimeError(f'Failed to JSON load data "{value}" ({ex}).') from ex
def _null_key_check(self, key: Any) -> bool:
"""Return False if value is not null."""
if key is None:
self.log.warning('The provided key was None.')
return True
return False
def _process_key_value(self, data: dict, resolve_embedded: bool) -> dict | None:
"""Read the value from key value store.
KeyValue data should be stored as a JSON string.
"""
# IMPORTANT:
# A Single level of nested variables is supported. There is no way
# in the TC platform to create double nested variables. Any App
# that would try and create a double nested variable is improperly
# written.
# KeyValue List Input
# -------------------------------------------------------------
# | key | value |
# =============================================================
# | my_binary | #App:7979:two!Binary |
# -------------------------------------------------------------
# | my_binary_array | #App:7979:two!BinaryArray |
# -------------------------------------------------------------
# | my_key_value | #App:7979:two!KeyValue |
# -------------------------------------------------------------
# | my_key_value_array | #App:7979:two!KeyValueArray |
# -------------------------------------------------------------
# | my_string | #App:7979:two!String |
# -------------------------------------------------------------
# | my_string_array | #App:7979:two!StringArray |
# -------------------------------------------------------------
# | my_tcentity | #App:7979:two!TCEntity |
# -------------------------------------------------------------
# | my_tcentity_array | #App:7979:two!TCEntityArray |
# -------------------------------------------------------------
# An upstream Apps KeyValue output can be used in a KeyValueList input, but
# Apps SHOULD NOT be writing KeyValueArray with nested variables. This means
# that there will only ever be 1 levels of nesting.
# KeyValueList Input -> Nested KeyValue/KeyValueArray, the nested
# KeyValue/KeyValueArray CAN NOT have nested variables since they
# have to come from an upstream App.
# check if keyvalue value is a variable
if resolve_embedded:
value = data['value']
if self.util.is_playbook_variable(value):
# any type can be nested, but no further nesting is supported
data['value'] = self.any(value)
else:
# read embedded is less efficient and has more caveats
data['value'] = self._read_embedded(value)
return data
@staticmethod
def _process_space_patterns(string: str) -> str:
r"""Return the string with \s replace with spaces."""
# replace "\s" with a space only for user input.
# using '\\s' will prevent replacement.
string = re.sub(r'(?<!\\)\\s', ' ', string)
string = re.sub(r'\\\\s', r'\\s', string)
return string
def _read_embedded(self, value: str) -> Sensitive | str:
r"""Read method for "embedded" variables.
.. Note:: The ``read()`` method will automatically determine if the input is a variable or
needs to be searched for embedded variables.
Embedded variable rules:
* Only user input can have embedded variables.
* Only String and KeyValueArray variables can have embedded variables.
* Variables can only be embedded one level deep.
This method will automatically convert variables embedded in a string with value retrieved
from DB. If there are no keys/variables the raw string will be returned.
Examples::
DB Values
#App:7979:variable_name!String:
"embedded \\"variable\\""
#App:7979:two!String:
"two"
#App:7979:variable_name!StringArray:
["one", "two", "three"]
Examples 1:
Input: "This input has a embedded #App:7979:variable_name!String"
Examples 2:
Input: ["one", #App:7979:two!String, "three"]
Examples 3:
Input: [{
"key": "embedded string",
"value": "This input has a embedded #App:7979:variable_name!String"
}, {
"key": "string array",
"value": #App:7979:variable_name!StringArray
}, {
"key": "string",
"value": #App:7979:variable_name!String
}]
Args:
value (str): The value to parsed and updated from the DB.
Returns:
(str): Results retrieved from DB
"""
if value is None: # pragma: no cover
return value
value_ = value
for match in re.finditer(self.util.variable_expansion_pattern, str(value)):
variable = match.group(0) # the full variable pattern
v = None
if match.group('origin') == '#': # pb-variable
v = self.any(variable)
elif match.group('origin') == '&': # tc-variable
v = registry.inputs.resolve_variable(variable)
# TODO: [high] should this behavior be changed in 3.0?
self.log.debug(f'embedded variable: {variable}, value: {v}')
if match.group('type') in ['Binary', 'BinaryArray']:
self.log.debug(
f'Binary types may not be embedded into strings. Could not embed: {variable}'
)
v = '<binary>'
if isinstance(v, dict | list):
v = json.dumps(v)
elif v is None:
v = '<null>'
# value.replace was chosen over re.sub due to an issue encountered while testing an app.
# re.sub will handle escaped characters like \t, value.replace would not handle these
# scenarios.
if isinstance(v, Sensitive) and value_ == variable:
# handle when tc variables are embedded in a a playbook variable and the
# type is KeyChain. a Sensitive value needs to be returned so that the
# developer can control the output of the data, protecting the value.
# this is done when the variable is an exact match to the value.
value_ = v
elif isinstance(value_, str) and isinstance(v, Sensitive):
# alternate to above this handles when tc variables is embedded in a string.
# this is NOT recommended, but still supported through this method.
value_ = value_.replace(variable, v.value)
elif isinstance(value_, str) and isinstance(v, str):
value_ = value_.replace(variable, v)
return value_
@staticmethod
def _to_array(value: list | str | None) -> list:
"""Return the provided array as a list."""
if value is None:
# Adding none value to list breaks App logic. It's better to not request
# Array and build array externally if None values are required.
value = []
elif not isinstance(value, list):
value = [value]
return value
def any(self, key: str) -> bytes | dict | list | str | None:
"""Return the value from the keystore for all types.
This is a quick helper method, for more advanced features
the individual read methods should be used (e.g., binary).
"""
if self._null_key_check(key) is True:
return None
key = key.strip() # clean up key
variable_type = self.util.get_playbook_variable_type(key).lower()
variable_type_map = {
'binary': self.binary,
'binaryarray': self.binary_array,
'keyvalue': self.key_value,
'keyvaluearray': self.key_value_array,
'string': self.string,
'stringarray': self.string_array,
'tcbatch': self.tc_batch,
'tcentity': self.tc_entity,
'tcentityarray': self.tc_entity_array,
# 'tcenhancedentity': self.tc_entity,
}
value = variable_type_map.get(variable_type, self.raw)(key)
if value is not None:
if variable_type == 'binary':
value = BinaryVariable(value)
elif variable_type == 'binaryarray':
value = [v if v is None else BinaryVariable(v) for v in value]
elif variable_type == 'string':
value = StringVariable(value)
elif variable_type == 'stringarray':
value = [v if v is None else StringVariable(v) for v in value]
return value
def binary(
self,
key: str,
b64decode: bool = True,
decode: bool = False,
) -> BinaryVariable | str | None:
"""Read the value from key value store.
The binary write method base64 encodes the data, then decodes the bytes to string, and
finally serializes the string before writing to the key value store.
This method will deserialize the string, then OPTIONALLY base64 decode the data, and
finally return the Binary data.
"""
if self._null_key_check(key) is True:
return None
# quick check to ensure an invalid key was not provided
self._check_variable_type(key, 'Binary')
# get the data from the key value store
data = self._get_data(key)
if data is None:
return None
# reverse the order of the binary create/write method
# 1. deserialize the data
# 2. base64 decode the data
# deserialize the data
data = self._deserialize_data(data)
# base64 decode the data (get_data returns multiple types, but the binary
# write method will always write a base64.encoded->bytes.decoded->serialized string)
# for the testing framework, the base64 encoded string should be returned so that
# the data can be compared to the expected value stored in the test profile.
if b64decode is True and isinstance(data, str):
data = BinaryVariable(base64.b64decode(data))
if decode is True:
# allow developer to decided if they want bytes or str
data = self._decode_binary(data)
elif isinstance(data, bytes):
# data should never be returned as bytes, but just in case an old App is using an
# older version of TcEx or if the TC Platform is writes binary data to the key value
# store, decode the bytes to a string
data = self._decode_binary(data)
return data
def binary_array(
self,
key: str,
b64decode: bool = True,
decode: bool = False,
) -> list[BinaryVariable | str] | None:
"""Read the value from key value store.
The binary array write method iterates over the BinaryArray and base64 encodes the data,
then decodes the bytes to string, and finally serializes the array before writing to the
key value store.
This method will deserialize the string, then iterate over the array and OPTIONALLY base64
decode the data, and finally return the BinaryArray.
"""
if self._null_key_check(key) is True:
return None
# quick check to ensure an invalid key was not provided
self._check_variable_type(key, 'BinaryArray')
# get the data from the key value store
data = self._get_data(key)
if data is None:
return None
# reverse the order of the binary create/write method
# 1. deserialize the data
# 2. iterate over the array
# 3. base64 decode the data
# data should be a serialized string, but in case there are any legacy Apps that are
# using an older version of TcEx, check for bytes and decode to string
if isinstance(data, bytes):
data = data.decode('utf-8')
# deserialize the data
_data: list[str] = self._deserialize_data(data)
values = []
for d in _data:
if b64decode is True and isinstance(d, str):
d = BinaryVariable(base64.b64decode(d))
if decode is True:
# allow developer to decided if they want bytes or str
d = self._decode_binary(d)
values.append(d)
return values
def key_value(
self,
key: str,
resolve_embedded: bool = True,
) -> dict | None:
"""Read the value from key value store.
KeyValue data should be stored as a JSON string.
"""
if self._null_key_check(key) is True:
return None
# quick check to ensure an invalid key was not provided
self._check_variable_type(key, 'KeyValue')
# get the data from the key value store
data = self._get_data(key)
if data is None:
return None
# deserialize the data
data = self._deserialize_data(data)
return self._process_key_value(data, resolve_embedded=resolve_embedded)
def key_value_array(
self,
key: str,
resolve_embedded: bool = True,
) -> list[dict] | None:
"""Read the value from key value store.
KeyValueArray data should be stored as serialized string.
"""
if self._null_key_check(key) is True:
return None
# quick check to ensure an invalid key was not provided
self._check_variable_type(key, 'KeyValueArray')
data = self._get_data(key)
if data is None:
return None
# data should be a serialized string, but in case there are any legacy Apps that are
# using an older version of TcEx, check for bytes and decode to string
if isinstance(data, bytes):
data = data.decode()
# Array type is serialized before writing to redis, deserialize the data
_data: list[dict] = self._deserialize_data(data)
values = []
for d in _data:
# d should be a base64 encoded string
values.append(self._process_key_value(d, resolve_embedded=resolve_embedded))
return values
def raw(self, key: str) -> Any | None:
"""Read method of CRUD operation for raw data.
Bytes input will be returned a as string as there is no way
to determine data from redis originated as bytes or string.
"""
if self._null_key_check(key) is True:
return None
return self.key_value_store.client.read(self.context, key.strip())
def string(
self,
key: str,
resolve_embedded: bool = True,
) -> Sensitive | str | None:
"""Read the value from key value store.
The string write method serializes the string before writing to the key value store.
This method will deserialize the string and finally return the StringArray data.
"""
if self._null_key_check(key) is True:
return None
# quick check to ensure an invalid key was not provided
self._check_variable_type(key, 'String')
# get the data from the key value store
data = self._get_data(key)
if data is None:
return None
# data should be a serialized string, but in case there are any legacy Apps that are
# using an older version of TcEx, check for bytes and decode to string
if isinstance(data, bytes):
data = data.decode()
# deserialize the data
data = self._deserialize_data(data)
# only resolve embedded variables if resolve_embedded is True and
# the entire string does not exactly match a variable pattern
if resolve_embedded and not self.util.is_playbook_variable(data):
data = self._read_embedded(data)
# coerce data back to string, since technically TC doesn't support bool, int, etc
return self._coerce_string_value(data)
def string_array(self, key: str) -> list[StringVariable] | None:
"""Read the value from key value store.
The string_array write method serializes the list of strings before writing to the key value
store.
This method will deserialize the list of strings and finally return the StringArray data.
"""
if self._null_key_check(key) is True:
return None
# quick check to ensure an invalid key was not provided
self._check_variable_type(key, 'StringArray')
# get the data from the key value store
data = self._get_data(key)
if data is None:
return None
# data should be a serialized string, but in case there are any legacy Apps that are
# using an older version of TcEx, check for bytes and decode to string
if isinstance(data, bytes):
data = data.decode()
# deserialize the data
_data: list[str] = self._deserialize_data(data)
# return array of StringVariables
# return [StringVariable(self._coerce_string_value(d)) for d in _data]
return [d if d is None else StringVariable(self._coerce_string_value(d)) for d in _data]
def tc_batch(self, key: str) -> dict | None:
"""Read the value from key value store.
The tc_batch write method serializes the string before writing to the key value store.
This method will deserialize the string and finally return the TCBatch data.
"""
if self._null_key_check(key) is True:
return None
# quick check to ensure an invalid key was not provided
self._check_variable_type(key, 'TCBatch')
data = self._get_data(key)
if data is None:
return None
# data should be a serialized string, but in case there are any legacy Apps that are
# using an older version of TcEx, check for bytes and decode to string
if isinstance(data, bytes):
data = data.decode()
return self._deserialize_data(data)
def tc_entity(self, key: str) -> dict[str, str] | None:
"""Read the value from key value store.
The tc_entity write method serializes the dict before writing to the key value store.
This method will deserialize the string and finally return the TCEntity data.
"""
if self._null_key_check(key) is True:
return None
# quick check to ensure an invalid key was not provided
self._check_variable_type(key, 'TCEntity')
# get the data from the key value store
data = self._get_data(key)
if data is None:
return None
# data should be a serialized string, but in case there are any legacy Apps that are
# using an older version of TcEx, check for bytes and decode to string
if isinstance(data, bytes):
data = data.decode()
# deserialize the data
return self._deserialize_data(data)
def tc_entity_array(
self,
key: str,
) -> list[dict[str, str]] | None:
"""Read the value from key value store.
The tc_entity_array write method serializes the list of dicts before writing to the key
value store.
This method will deserialize the list of dicts and finally return the TCEntityArray data.
"""
if self._null_key_check(key) is True:
return None
# quick check to ensure an invalid key was not provided
self._check_variable_type(key, 'TCEntityArray')
# get the data from the key value store
data = self._get_data(key)
if data is None:
return None
# data should be a serialized string, but in case there are any legacy Apps that are
# using an older version of TcEx, check for bytes and decode to string
if isinstance(data, bytes):
data = data.decode()
# deserialize the data
return self._deserialize_data(data)
def variable(
self, key: str | None, array: bool = False
) -> bytes | dict | list | str | Sensitive | None:
"""Read method of CRUD operation for working with KeyValue DB.
This method will automatically check to see if a single variable is passed
or if "mixed" data is passed and return the results from the DB. It will also
automatically determine the variable type to read.
"""
value = key
if value is not None and isinstance(key, str):
key = key.strip()
if re.match(self.util.variable_playbook_match, key):
value = self.any(key=key)
else:
# replace space patterns
value = self._process_space_patterns(value)
# key must be an embedded variable
value = self._read_embedded(value)
if array is True:
if isinstance(value, list | str):
value = self._to_array(value)
elif value is None:
value = []
return value