clear-skies-aws 2.0.1__py3-none-any.whl → 2.0.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. {clear_skies_aws-2.0.1.dist-info → clear_skies_aws-2.0.3.dist-info}/METADATA +2 -2
  2. clear_skies_aws-2.0.3.dist-info/RECORD +63 -0
  3. {clear_skies_aws-2.0.1.dist-info → clear_skies_aws-2.0.3.dist-info}/WHEEL +1 -1
  4. clearskies_aws/__init__.py +27 -0
  5. clearskies_aws/actions/__init__.py +15 -0
  6. clearskies_aws/actions/action_aws.py +135 -0
  7. clearskies_aws/actions/assume_role.py +115 -0
  8. clearskies_aws/actions/ses.py +203 -0
  9. clearskies_aws/actions/sns.py +61 -0
  10. clearskies_aws/actions/sqs.py +81 -0
  11. clearskies_aws/actions/step_function.py +73 -0
  12. clearskies_aws/backends/__init__.py +19 -0
  13. clearskies_aws/backends/backend.py +106 -0
  14. clearskies_aws/backends/dynamo_db_backend.py +609 -0
  15. clearskies_aws/backends/dynamo_db_condition_parser.py +325 -0
  16. clearskies_aws/backends/dynamo_db_parti_ql_backend.py +965 -0
  17. clearskies_aws/backends/sqs_backend.py +61 -0
  18. clearskies_aws/configs/__init__.py +0 -0
  19. clearskies_aws/contexts/__init__.py +23 -0
  20. clearskies_aws/contexts/cli_web_socket_mock.py +20 -0
  21. clearskies_aws/contexts/lambda_alb.py +81 -0
  22. clearskies_aws/contexts/lambda_api_gateway.py +81 -0
  23. clearskies_aws/contexts/lambda_api_gateway_web_socket.py +79 -0
  24. clearskies_aws/contexts/lambda_invoke.py +138 -0
  25. clearskies_aws/contexts/lambda_sns.py +124 -0
  26. clearskies_aws/contexts/lambda_sqs_standard.py +139 -0
  27. clearskies_aws/di/__init__.py +6 -0
  28. clearskies_aws/di/aws_additional_config_auto_import.py +37 -0
  29. clearskies_aws/di/inject/__init__.py +6 -0
  30. clearskies_aws/di/inject/boto3.py +15 -0
  31. clearskies_aws/di/inject/boto3_session.py +13 -0
  32. clearskies_aws/di/inject/parameter_store.py +15 -0
  33. clearskies_aws/endpoints/__init__.py +1 -0
  34. clearskies_aws/endpoints/secrets_manager_rotation.py +194 -0
  35. clearskies_aws/endpoints/simple_body_routing.py +41 -0
  36. clearskies_aws/input_outputs/__init__.py +21 -0
  37. clearskies_aws/input_outputs/cli_web_socket_mock.py +20 -0
  38. clearskies_aws/input_outputs/lambda_alb.py +53 -0
  39. clearskies_aws/input_outputs/lambda_api_gateway.py +123 -0
  40. clearskies_aws/input_outputs/lambda_api_gateway_web_socket.py +73 -0
  41. clearskies_aws/input_outputs/lambda_input_output.py +89 -0
  42. clearskies_aws/input_outputs/lambda_invoke.py +88 -0
  43. clearskies_aws/input_outputs/lambda_sns.py +88 -0
  44. clearskies_aws/input_outputs/lambda_sqs_standard.py +86 -0
  45. clearskies_aws/mocks/__init__.py +1 -0
  46. clearskies_aws/mocks/actions/__init__.py +6 -0
  47. clearskies_aws/mocks/actions/ses.py +34 -0
  48. clearskies_aws/mocks/actions/sns.py +29 -0
  49. clearskies_aws/mocks/actions/sqs.py +29 -0
  50. clearskies_aws/mocks/actions/step_function.py +32 -0
  51. clearskies_aws/models/__init__.py +1 -0
  52. clearskies_aws/models/web_socket_connection_model.py +182 -0
  53. clearskies_aws/secrets/__init__.py +13 -0
  54. clearskies_aws/secrets/additional_configs/__init__.py +62 -0
  55. clearskies_aws/secrets/additional_configs/iam_db_auth.py +39 -0
  56. clearskies_aws/secrets/additional_configs/iam_db_auth_with_ssm.py +96 -0
  57. clearskies_aws/secrets/additional_configs/mysql_connection_dynamic_producer_via_ssh_cert_bastion.py +80 -0
  58. clearskies_aws/secrets/additional_configs/mysql_connection_dynamic_producer_via_ssm_bastion.py +162 -0
  59. clearskies_aws/secrets/akeyless_with_ssm_cache.py +60 -0
  60. clearskies_aws/secrets/parameter_store.py +52 -0
  61. clearskies_aws/secrets/secrets.py +16 -0
  62. clearskies_aws/secrets/secrets_manager.py +96 -0
  63. clear_skies_aws-2.0.1.dist-info/RECORD +0 -4
  64. {clear_skies_aws-2.0.1.dist-info → clear_skies_aws-2.0.3.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,325 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import json
5
+ import logging
6
+ from decimal import Decimal, DecimalException
7
+ from typing import Any
8
+
9
+ from clearskies import Validator
10
+
11
+ # Ensure AttributeValueTypeDef is imported from the correct boto3 types package
12
+ # This is crucial for the "ideal fix".
13
+ from types_boto3_dynamodb.type_defs import AttributeValueTypeDef
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ class DynamoDBConditionParser(Validator):
19
+ """
20
+ Parses string conditions into a structured format suitable for DynamoDB PartiQL queries.
21
+
22
+ This class handles various SQL-like operators and translates them into
23
+ PartiQL compatible expressions and parameters. It also includes a utility
24
+ to convert Python values into the DynamoDB AttributeValue format.
25
+ """
26
+
27
+ operator_lengths: dict[str, int] = {
28
+ "<>": 2,
29
+ "<=": 2,
30
+ ">=": 2,
31
+ "!=": 2,
32
+ ">": 1,
33
+ "<": 1,
34
+ "=": 1,
35
+ "in": 4,
36
+ "is not null": 12,
37
+ "is null": 8,
38
+ "is not": 8,
39
+ "is": 4,
40
+ "like": 6,
41
+ "is not missing": 15,
42
+ "is missing": 11,
43
+ "contains": 9,
44
+ "begins_with": 12,
45
+ }
46
+ operators: list[str] = [
47
+ # Longer operators first to help with matching
48
+ "is not null",
49
+ "is not missing",
50
+ "is null",
51
+ "is missing",
52
+ "begins_with",
53
+ "contains",
54
+ "<>",
55
+ "!=",
56
+ "<=",
57
+ ">=",
58
+ "is not",
59
+ "is",
60
+ "like",
61
+ ">",
62
+ "<",
63
+ "=",
64
+ "in",
65
+ ]
66
+ operators_for_matching: dict[str, str] = {
67
+ "like": " like ",
68
+ "in": " in ",
69
+ "is not missing": " is not missing",
70
+ "is missing": " is missing",
71
+ "is not null": " is not null",
72
+ "is null": " is null",
73
+ "is": " is ",
74
+ "is not": " is not ",
75
+ "begins_with": " begins_with",
76
+ "contains": " contains",
77
+ }
78
+ operators_with_simple_placeholders: dict[str, bool] = {
79
+ "<>": True,
80
+ "<=": True,
81
+ ">=": True,
82
+ "!=": True,
83
+ "=": True,
84
+ "<": True,
85
+ ">": True,
86
+ "is": True,
87
+ "is not": True,
88
+ }
89
+ operators_without_placeholders: set[str] = {
90
+ "is not missing",
91
+ "is missing",
92
+ }
93
+ operator_needs_remap: dict[str, str] = {
94
+ "is not null": "is not missing",
95
+ "is null": "is missing",
96
+ }
97
+ operators_with_special_placeholders: set[str] = {"begins_with", "contains"}
98
+
99
+ def parse_condition(self, condition: str) -> dict[str, Any]:
100
+ """
101
+ Parse a string condition into a structured dictionary.
102
+
103
+ The "values" key in the returned dictionary will contain list[AttributeValueTypeDef].
104
+
105
+ Args:
106
+ condition: The condition string to parse.
107
+
108
+ Returns:
109
+ A dictionary with keys: "table", "column", "operator", "values" (DynamoDB formatted),
110
+ and "parsed" (the SQL fragment).
111
+ """
112
+ lowercase_condition: str = condition.lower()
113
+ matching_operator: str = ""
114
+ matching_index: int = -1
115
+ current_best_match_len: int = 0
116
+
117
+ for operator in self.operators:
118
+ try:
119
+ operator_for_match: str = self.operators_for_matching.get(operator, operator)
120
+ index: int = lowercase_condition.index(operator_for_match)
121
+
122
+ if matching_index == -1 or index < matching_index:
123
+ matching_index = index
124
+ matching_operator = operator
125
+ current_best_match_len = len(operator_for_match)
126
+ elif index == matching_index:
127
+ if len(operator_for_match) > current_best_match_len:
128
+ matching_operator = operator
129
+ current_best_match_len = len(operator_for_match)
130
+ except ValueError:
131
+ continue
132
+
133
+ if not matching_operator:
134
+ raise ValueError(f"No supported operators found in condition {condition}")
135
+
136
+ column: str = condition[:matching_index].strip()
137
+ value: str = condition[matching_index + self.operator_lengths[matching_operator] :].strip()
138
+
139
+ if len(value) >= 2:
140
+ first_char = value[0]
141
+ last_char = value[-1]
142
+ if (first_char == "'" and last_char == "'") or (first_char == '"' and last_char == '"'):
143
+ value = value[1:-1]
144
+
145
+ raw_values: list[str] = []
146
+
147
+ if matching_operator == "in":
148
+ raw_values = self._parse_condition_list(value) if value else []
149
+ elif matching_operator not in self.operators_without_placeholders and not (
150
+ matching_operator in self.operator_needs_remap
151
+ and self.operator_needs_remap[matching_operator] in self.operators_without_placeholders
152
+ ):
153
+ raw_values = [value]
154
+
155
+ if matching_operator.lower() == "like":
156
+ if value.startswith("%") and value.endswith("%") and len(value) > 1:
157
+ matching_operator = "contains"
158
+ raw_values = [value[1:-1]]
159
+ elif value.endswith("%") and not value.startswith("%"):
160
+ matching_operator = "begins_with"
161
+ raw_values = [value[:-1]]
162
+ elif value.startswith("%") and not value.endswith("%"):
163
+ raise ValueError("DynamoDB PartiQL does not directly support 'ends_with'")
164
+ else:
165
+ matching_operator = "="
166
+ raw_values = [value]
167
+
168
+ matching_operator = self.operator_needs_remap.get(matching_operator.lower(), matching_operator)
169
+
170
+ table_name: str = ""
171
+ final_column_name: str = column
172
+ if "." in column:
173
+ table_prefix, column_name_part = column.split(".", 1)
174
+ table_name = table_prefix.strip().replace('"', "").replace("`", "")
175
+ final_column_name = column_name_part.strip().replace('"', "").replace("`", "")
176
+ else:
177
+ final_column_name = column.replace('"', "").replace("`", "")
178
+
179
+ # This list will now correctly be list[AttributeValueTypeDef]
180
+ parameters: list[AttributeValueTypeDef] = []
181
+ if matching_operator.lower() not in self.operators_without_placeholders:
182
+ for val_item in raw_values:
183
+ parameters.append(self.to_dynamodb_attribute_value(val_item))
184
+
185
+ column_for_parsed: str = f"{table_name}.{final_column_name}" if table_name else final_column_name
186
+
187
+ return {
188
+ "table": table_name,
189
+ "column": final_column_name,
190
+ "operator": matching_operator.upper(),
191
+ "values": parameters, # This is now correctly typed for MyPy
192
+ "parsed": self._with_placeholders(
193
+ column_for_parsed,
194
+ matching_operator,
195
+ parameters,
196
+ ),
197
+ }
198
+
199
+ def _with_placeholders(
200
+ self,
201
+ column: str,
202
+ operator: str,
203
+ values: list[AttributeValueTypeDef], # Parameter 'values' is list[AttributeValueTypeDef]
204
+ escape: bool = True,
205
+ escape_character: str = '"',
206
+ ) -> str:
207
+ """Format a SQL fragment with placeholders for a given column, operator, and parameters."""
208
+ quoted_column = column
209
+ if escape:
210
+ parts: list[str] = column.split(".", 1)
211
+ cleaned_parts: list[str] = [part.strip('"`') for part in parts]
212
+ if len(cleaned_parts) == 2:
213
+ quoted_column = (
214
+ f"{escape_character}{cleaned_parts[0]}{escape_character}"
215
+ "."
216
+ f"{escape_character}{cleaned_parts[1]}{escape_character}"
217
+ )
218
+ else:
219
+ quoted_column = f"{escape_character}{cleaned_parts[0]}{escape_character}"
220
+
221
+ upper_case_operator: str = operator.upper()
222
+ lower_case_operator: str = operator.lower()
223
+
224
+ if lower_case_operator in self.operators_with_simple_placeholders:
225
+ return f"{quoted_column} {upper_case_operator} ?"
226
+ if lower_case_operator in self.operators_without_placeholders:
227
+ return f"{quoted_column} {upper_case_operator}"
228
+ if lower_case_operator in self.operators_with_special_placeholders:
229
+ return f"{lower_case_operator}({quoted_column}, ?)"
230
+
231
+ if lower_case_operator == "in":
232
+ placeholders_str: str = ", ".join(["?" for _ in values])
233
+ return f"{quoted_column} IN ({placeholders_str})"
234
+
235
+ raise ValueError(f"Unsupported operator for placeholder generation: {operator}")
236
+
237
+ def to_dynamodb_attribute_value(self, value: Any) -> AttributeValueTypeDef: # Return type changed
238
+ """Convert a Python variable into a DynamoDB-formatted attribute value dictionary."""
239
+ if isinstance(value, str):
240
+ if value.lower() == "true":
241
+ return {"BOOL": True}
242
+ if value.lower() == "false":
243
+ return {"BOOL": False}
244
+ if value.lower() == "null":
245
+ return {"NULL": True}
246
+ try:
247
+ if value.isdigit() or (value.startswith("-") and value[1:].isdigit()):
248
+ return {"N": str(int(value))}
249
+ return {"N": str(Decimal(value))}
250
+ except (ValueError, TypeError, json.JSONDecodeError, DecimalException):
251
+ return {"S": value}
252
+ elif isinstance(value, bool):
253
+ return {"BOOL": value}
254
+ elif isinstance(value, (int, float, Decimal)):
255
+ return {"N": str(value)}
256
+ elif value is None:
257
+ return {"NULL": True}
258
+ elif isinstance(value, bytes):
259
+ return {"B": base64.b64encode(value).decode("utf-8")}
260
+ elif isinstance(value, list):
261
+ # Each item will be AttributeValueTypeDef, so the list is list[AttributeValueTypeDef]
262
+ return {"L": [self.to_dynamodb_attribute_value(item) for item in value]}
263
+ elif isinstance(value, dict):
264
+ # Each value in the map will be AttributeValueTypeDef
265
+ return {"M": {str(k): self.to_dynamodb_attribute_value(v) for k, v in value.items()}}
266
+ elif isinstance(value, set):
267
+ if not value:
268
+ raise ValueError("Cannot determine DynamoDB Set type from an empty Python set.")
269
+ if all(isinstance(item, str) for item in value):
270
+ return {"SS": sorted(list(value))}
271
+ elif all(isinstance(item, (int, float, Decimal)) for item in value):
272
+ return {"NS": sorted([str(item) for item in value])}
273
+ elif all(isinstance(item, bytes) for item in value):
274
+ return {"BS": sorted([base64.b64encode(item).decode("utf-8") for item in value])}
275
+ raise ValueError("Set contains mixed types or unsupported types for DynamoDB Sets.")
276
+ else:
277
+ raise TypeError(f"Unsupported Python type for DynamoDB conversion: {type(value)}")
278
+
279
+ def _parse_condition_list(self, list_string: str) -> list[str]:
280
+ """Parse a string representation of a list into a list of strings."""
281
+ if not list_string.strip():
282
+ return []
283
+
284
+ if list_string.startswith("(") and list_string.endswith(")"):
285
+ list_string = list_string[1:-1]
286
+ if not list_string.strip():
287
+ return []
288
+
289
+ items: list[str] = []
290
+ current_item: str = ""
291
+ in_quotes: bool = False
292
+ quote_char: str = ""
293
+ for char in list_string:
294
+ if char in ("'", '"'):
295
+ if in_quotes and char == quote_char:
296
+ in_quotes = False
297
+ elif not in_quotes:
298
+ in_quotes = True
299
+ quote_char = char
300
+ else:
301
+ current_item += char
302
+ elif char == "," and not in_quotes:
303
+ stripped_item = current_item.strip()
304
+ if stripped_item:
305
+ items.append(stripped_item)
306
+ current_item = ""
307
+ else:
308
+ current_item += char
309
+
310
+ stripped_current_item = current_item.strip()
311
+ if stripped_current_item:
312
+ items.append(stripped_current_item)
313
+
314
+ final_items = []
315
+ for item in items:
316
+ processed_item = item
317
+ if len(processed_item) >= 2:
318
+ if processed_item.startswith("'") and processed_item.endswith("'"):
319
+ processed_item = processed_item[1:-1]
320
+ elif processed_item.startswith('"') and processed_item.endswith('"'):
321
+ processed_item = processed_item[1:-1]
322
+
323
+ if processed_item:
324
+ final_items.append(processed_item)
325
+ return final_items