File: validators.py

package info (click to toggle)
python-moto 5.1.18-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 116,520 kB
  • sloc: python: 636,725; javascript: 181; makefile: 39; sh: 3
file content (591 lines) | stat: -rw-r--r-- 22,918 bytes parent folder | download
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
"""
See docstring class Validator below for more details on validation
"""

from abc import abstractmethod
from copy import deepcopy
from typing import Any, Callable, Union

from moto.dynamodb.exceptions import (
    AttributeDoesNotExist,
    AttributeIsReservedKeyword,
    DuplicateUpdateExpression,
    EmptyKeyAttributeException,
    ExpressionAttributeNameNotDefined,
    ExpressionAttributeValueNotDefined,
    IncorrectOperandType,
    InvalidAttributeTypeError,
    InvalidUpdateExpressionInvalidDocumentPath,
    MockValidationException,
    ProvidedKeyDoesNotExist,
    TooManyClauses,
    UpdateHashRangeKeyException,
)
from moto.dynamodb.models.dynamo_type import DynamoType, Item
from moto.dynamodb.models.table import Table
from moto.dynamodb.parsing.ast_nodes import (  # type: ignore
    DDBTypedValue,
    DepthFirstTraverser,
    ExpressionAttribute,
    ExpressionAttributeName,
    ExpressionAttributeValue,
    ExpressionPathDescender,
    ExpressionSelector,
    ExpressionValueOperator,
    Node,
    NoneExistingPath,
    UpdateExpression,
    UpdateExpressionAddAction,
    UpdateExpressionAddClause,
    UpdateExpressionClause,
    UpdateExpressionDeleteAction,
    UpdateExpressionFunction,
    UpdateExpressionPath,
    UpdateExpressionRemoveAction,
    UpdateExpressionRemoveClause,
    UpdateExpressionSetAction,
    UpdateExpressionSetClause,
    UpdateExpressionValue,
)
from moto.dynamodb.parsing.reserved_keywords import ReservedKeywords
from moto.dynamodb.utils import find_duplicates, find_path_overlaps


class ExpressionAttributeValueProcessor(DepthFirstTraverser):  # type: ignore[misc]
    def __init__(self, expression_attribute_values: dict[str, dict[str, Any]]):
        self.expression_attribute_values = expression_attribute_values

    def _processing_map(
        self,
    ) -> dict[
        type[ExpressionAttributeValue],
        Callable[[ExpressionAttributeValue], DDBTypedValue],
    ]:
        return {
            ExpressionAttributeValue: self.replace_expression_attribute_value_with_value
        }

    def replace_expression_attribute_value_with_value(
        self, node: ExpressionAttributeValue
    ) -> DDBTypedValue:
        """A node representing an Expression Attribute Value. Resolve and replace value"""
        assert isinstance(node, ExpressionAttributeValue)
        attribute_value_name = node.get_value_name()
        try:
            target = self.expression_attribute_values[attribute_value_name]
        except KeyError:
            raise ExpressionAttributeValueNotDefined(
                attribute_value=attribute_value_name
            )
        return DDBTypedValue(DynamoType(target))


class ExpressionPathResolver:
    def __init__(self, expression_attribute_names: dict[str, str]):
        self.expression_attribute_names = expression_attribute_names

    @classmethod
    def raise_exception_if_keyword(cls, attribute: Any) -> None:  # type: ignore[misc]
        if attribute.upper() in ReservedKeywords.get_reserved_keywords():
            raise AttributeIsReservedKeyword(attribute)

    def resolve_expression_path(
        self, item: Item, update_expression_path: UpdateExpressionPath
    ) -> Union[NoneExistingPath, DDBTypedValue]:
        assert isinstance(update_expression_path, UpdateExpressionPath)
        return self.resolve_expression_path_nodes(item, update_expression_path.children)

    def resolve_expression_path_nodes(
        self, item: Item, update_expression_path_nodes: list[Node]
    ) -> Union[NoneExistingPath, DDBTypedValue]:
        target = item.attrs

        for child in update_expression_path_nodes:
            # First replace placeholder with attribute_name
            attr_name = None
            if isinstance(child, ExpressionAttributeName):
                attr_placeholder = child.get_attribute_name_placeholder()
                try:
                    attr_name = self.expression_attribute_names[attr_placeholder]
                except KeyError:
                    raise ExpressionAttributeNameNotDefined(attr_placeholder)
            elif isinstance(child, ExpressionAttribute):
                attr_name = child.get_attribute_name()
                self.raise_exception_if_keyword(attr_name)
            if attr_name is not None:
                # Resolv attribute_name
                try:
                    target = target[attr_name]
                except (KeyError, TypeError):
                    if child == update_expression_path_nodes[-1]:
                        return NoneExistingPath(creatable=True)
                    return NoneExistingPath()
            else:
                if isinstance(child, ExpressionPathDescender):
                    continue
                elif isinstance(child, ExpressionSelector):
                    index = child.get_index()
                    if target.is_list():  # type: ignore
                        try:
                            target = target[index]
                        except IndexError:
                            # When a list goes out of bounds when assigning that is no problem when at the assignment
                            # side. It will just append to the list.
                            if child == update_expression_path_nodes[-1]:
                                return NoneExistingPath(creatable=True)
                            return NoneExistingPath()
                    else:
                        raise InvalidUpdateExpressionInvalidDocumentPath
                else:
                    raise NotImplementedError(f"Path resolution for {type(child)}")
        return DDBTypedValue(target)

    def resolve_expression_path_nodes_to_dynamo_type(
        self, item: Item, update_expression_path_nodes: list[Node]
    ) -> Any:
        node = self.resolve_expression_path_nodes(item, update_expression_path_nodes)
        if isinstance(node, NoneExistingPath):
            raise ProvidedKeyDoesNotExist()
        assert isinstance(node, DDBTypedValue)
        return node.get_value()


class ExpressionAttributeResolvingProcessor(DepthFirstTraverser):  # type: ignore[misc]
    def _processing_map(
        self,
    ) -> dict[type[UpdateExpressionClause], Callable[[DDBTypedValue], DDBTypedValue]]:
        return {
            UpdateExpressionSetAction: self.disable_resolving,
            UpdateExpressionPath: self.process_expression_path_node,
        }

    def __init__(self, expression_attribute_names: dict[str, str], item: Item):
        self.expression_attribute_names = expression_attribute_names
        self.item = item
        self.resolving = False

    def pre_processing_of_child(
        self,
        parent_node: Union[
            UpdateExpressionSetAction,
            UpdateExpressionRemoveAction,
            UpdateExpressionDeleteAction,
            UpdateExpressionAddAction,
        ],
        child_id: int,
    ) -> None:
        """
        We have to enable resolving if we are processing a child of UpdateExpressionSetAction that is not first.
        Because first argument is path to be set, 2nd argument would be the value.
        """
        if isinstance(
            parent_node,
            (
                UpdateExpressionSetAction,
                UpdateExpressionRemoveAction,
                UpdateExpressionDeleteAction,
                UpdateExpressionAddAction,
            ),
        ):
            if child_id == 0:
                self.resolving = False
            else:
                self.resolving = True

    def disable_resolving(self, node: DDBTypedValue) -> DDBTypedValue:
        self.resolving = False
        return node

    def process_expression_path_node(self, node: DDBTypedValue) -> DDBTypedValue:
        """Resolve ExpressionAttribute if not part of a path and resolving is enabled."""
        if self.resolving:
            return self.resolve_expression_path(node)
        else:
            # Still resolve but return original note to make sure path is correct Just make sure nodes are creatable.
            result_node = self.resolve_expression_path(node)
            if (
                isinstance(result_node, NoneExistingPath)
                and not result_node.is_creatable()
            ):
                raise InvalidUpdateExpressionInvalidDocumentPath()

            return node

    def resolve_expression_path(
        self, node: DDBTypedValue
    ) -> Union[NoneExistingPath, DDBTypedValue]:
        return ExpressionPathResolver(
            self.expression_attribute_names
        ).resolve_expression_path(self.item, node)


class UpdateExpressionFunctionEvaluator(DepthFirstTraverser):  # type: ignore[misc]
    """
    At time of writing there are only 2 functions for DDB UpdateExpressions. They both are specific to the SET
    expression as per the official AWS docs:
        https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/
        Expressions.UpdateExpressions.html#Expressions.UpdateExpressions.SET
    """

    def _processing_map(
        self,
    ) -> dict[
        type[UpdateExpressionFunction],
        Callable[[UpdateExpressionFunction], DDBTypedValue],
    ]:
        return {UpdateExpressionFunction: self.process_function}

    def process_function(self, node: UpdateExpressionFunction) -> DDBTypedValue:
        assert isinstance(node, UpdateExpressionFunction)
        function_name = node.get_function_name()
        first_arg = node.get_nth_argument(1)
        second_arg = node.get_nth_argument(2)

        if function_name == "if_not_exists":
            if isinstance(first_arg, NoneExistingPath):
                result = second_arg
            else:
                result = first_arg
            assert isinstance(result, (DDBTypedValue, NoneExistingPath))
            return result
        elif function_name == "list_append":
            if isinstance(first_arg, NoneExistingPath):
                raise MockValidationException(
                    "The provided expression refers to an attribute that does not exist in the item"
                )
            first_arg = deepcopy(
                self.get_list_from_ddb_typed_value(first_arg, function_name)
            )
            second_arg = self.get_list_from_ddb_typed_value(second_arg, function_name)
            for list_element in second_arg.value:
                first_arg.value.append(list_element)
            return DDBTypedValue(first_arg)
        else:
            raise NotImplementedError(f"Unsupported function for moto {function_name}")

    @classmethod
    def get_list_from_ddb_typed_value(  # type: ignore[misc]
        cls, node: DDBTypedValue, function_name: str
    ) -> DynamoType:
        assert isinstance(node, DDBTypedValue)
        dynamo_value = node.get_value()
        assert isinstance(dynamo_value, DynamoType)
        if not dynamo_value.is_list():
            raise IncorrectOperandType(function_name, dynamo_value.type)
        return dynamo_value


class NoneExistingPathChecker(DepthFirstTraverser):  # type: ignore[misc]
    """
    Pass through the AST and make sure there are no none-existing paths.
    """

    def _processing_map(self) -> dict[type[NoneExistingPath], Callable[[Node], None]]:
        return {NoneExistingPath: self.raise_none_existing_path}

    def raise_none_existing_path(self, node: Node) -> None:
        raise AttributeDoesNotExist


class ExecuteOperations(DepthFirstTraverser):  # type: ignore[misc]
    def _processing_map(
        self,
    ) -> dict[type[UpdateExpressionValue], Callable[[Node], DDBTypedValue]]:
        return {UpdateExpressionValue: self.process_update_expression_value}

    def process_update_expression_value(self, node: Node) -> DDBTypedValue:
        """
        If an UpdateExpressionValue only has a single child the node will be replaced with the childe.
        Otherwise it has 3 children and the middle one is an ExpressionValueOperator which details how to combine them
        Args:
            node(Node):

        Returns:
            Node: The resulting node of the operation if present or the child.
        """
        assert isinstance(node, UpdateExpressionValue)
        if len(node.children) == 1:
            return node.children[0]
        elif len(node.children) == 3:
            operator_node = node.children[1]
            assert isinstance(operator_node, ExpressionValueOperator)
            operator = operator_node.get_operator()
            left_operand = self.get_dynamo_value_from_ddb_typed_value(node.children[0])
            right_operand = self.get_dynamo_value_from_ddb_typed_value(node.children[2])
            if operator == "+":
                return self.get_sum(left_operand, right_operand)
            elif operator == "-":
                return self.get_subtraction(left_operand, right_operand)
            else:
                raise NotImplementedError(f"Moto does not support operator {operator}")
        else:
            raise NotImplementedError(
                "UpdateExpressionValue only has implementations for 1 or 3 children."
            )

    @classmethod
    def get_dynamo_value_from_ddb_typed_value(cls, node: DDBTypedValue) -> DynamoType:  # type: ignore[misc]
        assert isinstance(node, DDBTypedValue)
        dynamo_value = node.get_value()
        assert isinstance(dynamo_value, DynamoType)
        return dynamo_value

    @classmethod
    def get_sum(  # type: ignore[misc]
        cls, left_operand: DynamoType, right_operand: DynamoType
    ) -> DDBTypedValue:
        """
        Args:
            left_operand(DynamoType):
            right_operand(DynamoType):

        Returns:
            DDBTypedValue:
        """
        try:
            return DDBTypedValue(left_operand + right_operand)
        except TypeError:
            raise IncorrectOperandType("+", left_operand.type)

    @classmethod
    def get_subtraction(  # type: ignore[misc]
        cls, left_operand: DynamoType, right_operand: DynamoType
    ) -> DDBTypedValue:
        """
        Args:
            left_operand(DynamoType):
            right_operand(DynamoType):

        Returns:
            DDBTypedValue:
        """
        try:
            return DDBTypedValue(left_operand - right_operand)
        except TypeError:
            raise IncorrectOperandType("-", left_operand.type)


class EmptyStringKeyValueValidator(DepthFirstTraverser):  # type: ignore[misc]
    def __init__(self, key_attributes: list[str]):
        self.key_attributes = key_attributes

    def _processing_map(
        self,
    ) -> dict[
        type[UpdateExpressionSetAction],
        Callable[[UpdateExpressionSetAction], UpdateExpressionSetAction],
    ]:
        return {UpdateExpressionSetAction: self.check_for_empty_string_key_value}

    def check_for_empty_string_key_value(
        self, node: UpdateExpressionSetAction
    ) -> UpdateExpressionSetAction:
        """A node representing a SET action. Check that keys are not being assigned empty strings"""
        assert isinstance(node, UpdateExpressionSetAction)
        assert len(node.children) == 2
        key = node.children[0].children[0].children[0]
        val_node = node.children[1].children[0]
        if (
            not val_node.value
            and val_node.type in ["S", "B"]
            and key in self.key_attributes
        ):
            raise EmptyKeyAttributeException(key_in_index=True)
        return node


class TypeMismatchValidator(DepthFirstTraverser):  # type: ignore[misc]
    def __init__(self, key_attributes_type: list[dict[str, str]]):
        self.key_attributes_type = key_attributes_type

    def _processing_map(
        self,
    ) -> dict[
        type[UpdateExpressionSetAction],
        Callable[[UpdateExpressionSetAction], UpdateExpressionSetAction],
    ]:
        return {UpdateExpressionSetAction: self.check_for_type_mismatch}

    def check_for_type_mismatch(
        self, node: UpdateExpressionSetAction
    ) -> UpdateExpressionSetAction:
        """A node representing a SET action. Check that type matches with the definition"""
        assert isinstance(node, UpdateExpressionSetAction)
        assert len(node.children) == 2
        key = node.children[0].children[0].children[0]
        val_node = node.children[1].children[0]
        for dct in self.key_attributes_type:
            if dct["AttributeName"] == key and dct["AttributeType"] != val_node.type:
                raise InvalidAttributeTypeError(
                    key, dct["AttributeType"], val_node.type
                )
        return node


class UpdateHashRangeKeyValidator(DepthFirstTraverser):  # type: ignore[misc]
    def __init__(
        self,
        table_key_attributes: list[str],
        expression_attribute_names: dict[str, str],
    ):
        self.table_key_attributes = table_key_attributes
        self.expression_attribute_names = expression_attribute_names

    def _processing_map(
        self,
    ) -> dict[
        type[UpdateExpressionPath],
        Callable[[UpdateExpressionPath], UpdateExpressionPath],
    ]:
        return {UpdateExpressionPath: self.check_for_hash_or_range_key}

    def check_for_hash_or_range_key(
        self, node: UpdateExpressionPath
    ) -> UpdateExpressionPath:
        """Check that hash and range keys are not updated"""
        key_to_update = node.children[0].children[0]
        key_to_update = self.expression_attribute_names.get(
            key_to_update, key_to_update
        )
        if key_to_update in self.table_key_attributes:
            raise UpdateHashRangeKeyException(key_to_update)
        return node


class OverlappingPathsValidator(DepthFirstTraverser):  # type: ignore[misc]
    def __init__(self, expression_attribute_names: dict[str, str]):
        self.expression_attribute_names = expression_attribute_names

    def _processing_map(
        self,
    ) -> dict[
        type[UpdateExpression],
        Callable[[UpdateExpression], UpdateExpression],
    ]:
        return {UpdateExpression: self.check_for_overlapping_paths}

    def check_for_overlapping_paths(self, node: UpdateExpression) -> UpdateExpression:
        actions = node.find_clauses(
            [
                UpdateExpressionSetAction,
                UpdateExpressionAddAction,
                UpdateExpressionRemoveAction,
                UpdateExpressionDeleteAction,
            ]
        )
        expression_attribute_name_paths = []
        plaintext_paths = []
        for action in actions:
            path = action.children[0]
            path_name = path.children[0]
            # for some reason, if we only have a root expression ('#path1', '#path2'),
            # AWS only checks for direct matches, not path overlaps
            if (
                isinstance(path_name, ExpressionAttributeName)
                and len(path.children) == 1
            ):
                expression_attribute_name_paths.append(
                    self.expression_attribute_names[
                        path_name.get_attribute_name_placeholder()
                    ]
                )
            else:
                plaintext_paths.append(path.to_str())

        overlapping_paths = find_path_overlaps(plaintext_paths)
        if overlapping_paths:
            # There might be more than one attribute duplicated:
            # they may get mixed up in the Error Message which is inline with actual boto3 Error Messages
            raise DuplicateUpdateExpression(*overlapping_paths)

        duplicates = find_duplicates(plaintext_paths + expression_attribute_name_paths)
        if duplicates:
            raise DuplicateUpdateExpression(*duplicates)
        return node


class ActionCountValidator(DepthFirstTraverser):  # type: ignore[misc]
    def _processing_map(
        self,
    ) -> dict[
        type[UpdateExpression],
        Callable[[UpdateExpression], UpdateExpression],
    ]:
        return {UpdateExpression: self.verify_action_counts}

    def verify_action_counts(self, node: UpdateExpression) -> UpdateExpression:
        add_clauses = node.find_clauses([UpdateExpressionAddClause])
        remove_clauses = node.find_clauses([UpdateExpressionRemoveClause])
        set_clauses = node.find_clauses([UpdateExpressionSetClause])

        # Only allow single ADD/REMOVE clauses
        if len(add_clauses) > 1:
            raise TooManyClauses("ADD")
        if len(remove_clauses) > 1:
            raise TooManyClauses("REMOVE")
        if len(set_clauses) > 1:
            raise TooManyClauses("SET")
        return node


class Validator:
    """
    A validator is used to validate expressions which are passed in as an AST.
    """

    def __init__(
        self,
        expression: Node,
        expression_attribute_names: dict[str, str],
        expression_attribute_values: dict[str, dict[str, Any]],
        item: Item,
        table: Table,
    ):
        """
        Besides validation the Validator should also replace referenced parts of an item which is cheapest upon
        validation.

        Args:
            expression(Node): The root node of the AST representing the expression to be validated
            expression_attribute_names(ExpressionAttributeNames):
            expression_attribute_values(ExpressionAttributeValues):
            item(Item): The item which will be updated (pointed to by Key of update_item)
        """
        self.expression_attribute_names = expression_attribute_names
        self.expression_attribute_values = expression_attribute_values
        self.item = item
        self.table = table
        self.processors = self.get_ast_processors()
        self.node_to_validate = deepcopy(expression)

    @abstractmethod
    def get_ast_processors(self) -> list[DepthFirstTraverser]:  # type: ignore[misc]
        """Get the different processors that go through the AST tree and processes the nodes."""

    def validate(self) -> Node:
        n = self.node_to_validate
        for processor in self.processors:
            n = processor.traverse(n)
        return n


class UpdateExpressionValidator(Validator):
    def get_ast_processors(self) -> list[DepthFirstTraverser]:
        """Get the different processors that go through the AST tree and processes the nodes."""
        processors = [
            ActionCountValidator(),
            OverlappingPathsValidator(self.expression_attribute_names),
            UpdateHashRangeKeyValidator(
                self.table.table_key_attrs, self.expression_attribute_names or {}
            ),
            ExpressionAttributeValueProcessor(self.expression_attribute_values),
            ExpressionAttributeResolvingProcessor(
                self.expression_attribute_names, self.item
            ),
            UpdateExpressionFunctionEvaluator(),
            NoneExistingPathChecker(),
            ExecuteOperations(),
            TypeMismatchValidator(self.table.attr),
            EmptyStringKeyValueValidator(self.table.attribute_keys),
        ]
        return processors