forked from aws-powertools/powertools-lambda-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidator.py
226 lines (168 loc) · 7.95 KB
/
validator.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
import logging
from typing import Any, Callable, Dict, Optional, Union
from ...middleware_factory import lambda_handler_decorator
from ...shared import jmespath_utils
from .base import validate_data_against_schema
logger = logging.getLogger(__name__)
@lambda_handler_decorator
def validator(
handler: Callable,
event: Union[Dict, str],
context: Any,
inbound_schema: Optional[Dict] = None,
inbound_formats: Optional[Dict] = None,
outbound_schema: Optional[Dict] = None,
outbound_formats: Optional[Dict] = None,
envelope: str = "",
jmespath_options: Optional[Dict] = None,
) -> Any:
"""Lambda handler decorator to validate incoming/outbound data using a JSON Schema
Parameters
----------
handler : Callable
Method to annotate on
event : Dict
Lambda event to be validated
context : Any
Lambda context object
inbound_schema : Dict
JSON Schema to validate incoming event
outbound_schema : Dict
JSON Schema to validate outbound event
envelope : Dict
JMESPath expression to filter data against
jmespath_options : Dict
Alternative JMESPath options to be included when filtering expr
inbound_formats: Dict
Custom formats containing a key (e.g. int64) and a value expressed as regex or callback returning bool
outbound_formats: Dict
Custom formats containing a key (e.g. int64) and a value expressed as regex or callback returning bool
Example
-------
**Validate incoming event**
from aws_lambda_powertools.utilities.validation import validator
@validator(inbound_schema=json_schema_dict)
def handler(event, context):
return event
**Validate incoming and outgoing event**
from aws_lambda_powertools.utilities.validation import validator
@validator(inbound_schema=json_schema_dict, outbound_schema=response_json_schema_dict)
def handler(event, context):
return event
**Unwrap event before validating against actual payload - using built-in envelopes**
from aws_lambda_powertools.utilities.validation import validator, envelopes
@validator(inbound_schema=json_schema_dict, envelope=envelopes.API_GATEWAY_REST)
def handler(event, context):
return event
**Unwrap event before validating against actual payload - using custom JMESPath expression**
from aws_lambda_powertools.utilities.validation import validator
@validator(inbound_schema=json_schema_dict, envelope="payload[*].my_data")
def handler(event, context):
return event
**Unwrap and deserialize JSON string event before validating against actual payload - using built-in functions**
from aws_lambda_powertools.utilities.validation import validator
@validator(inbound_schema=json_schema_dict, envelope="Records[*].powertools_json(body)")
def handler(event, context):
return event
**Unwrap, decode base64 and deserialize JSON string event before validating against actual payload - using built-in functions** # noqa: E501
from aws_lambda_powertools.utilities.validation import validator
@validator(inbound_schema=json_schema_dict, envelope="Records[*].kinesis.powertools_json(powertools_base64(data))")
def handler(event, context):
return event
**Unwrap, decompress ZIP archive and deserialize JSON string event before validating against actual payload - using built-in functions** # noqa: E501
from aws_lambda_powertools.utilities.validation import validator
@validator(inbound_schema=json_schema_dict, envelope="awslogs.powertools_base64_gzip(data) | powertools_json(@).logEvents[*]")
def handler(event, context):
return event
Returns
-------
Any
Lambda handler response
Raises
------
SchemaValidationError
When schema validation fails against data set
InvalidSchemaFormatError
When JSON schema provided is invalid
InvalidEnvelopeExpressionError
When JMESPath expression to unwrap event is invalid
"""
if envelope:
event = jmespath_utils.extract_data_from_envelope(
data=event, envelope=envelope, jmespath_options=jmespath_options
)
if inbound_schema:
logger.debug("Validating inbound event")
validate_data_against_schema(data=event, schema=inbound_schema, formats=inbound_formats)
response = handler(event, context)
if outbound_schema:
logger.debug("Validating outbound event")
validate_data_against_schema(data=response, schema=outbound_schema, formats=outbound_formats)
return response
def validate(
event: Any,
schema: Dict,
formats: Optional[Dict] = None,
envelope: Optional[str] = None,
jmespath_options: Optional[Dict] = None,
):
"""Standalone function to validate event data using a JSON Schema
Typically used when you need more control over the validation process.
Parameters
----------
event : Dict
Lambda event to be validated
schema : Dict
JSON Schema to validate incoming event
envelope : Dict
JMESPath expression to filter data against
jmespath_options : Dict
Alternative JMESPath options to be included when filtering expr
formats: Dict
Custom formats containing a key (e.g. int64) and a value expressed as regex or callback returning bool
Example
-------
**Validate event**
from aws_lambda_powertools.utilities.validation import validate
def handler(event, context):
validate(event=event, schema=json_schema_dict)
return event
**Unwrap event before validating against actual payload - using built-in envelopes**
from aws_lambda_powertools.utilities.validation import validate, envelopes
def handler(event, context):
validate(event=event, schema=json_schema_dict, envelope=envelopes.API_GATEWAY_REST)
return event
**Unwrap event before validating against actual payload - using custom JMESPath expression**
from aws_lambda_powertools.utilities.validation import validate
def handler(event, context):
validate(event=event, schema=json_schema_dict, envelope="payload[*].my_data")
return event
**Unwrap and deserialize JSON string event before validating against actual payload - using built-in functions**
from aws_lambda_powertools.utilities.validation import validate
def handler(event, context):
validate(event=event, schema=json_schema_dict, envelope="Records[*].powertools_json(body)")
return event
**Unwrap, decode base64 and deserialize JSON string event before validating against actual payload - using built-in functions**
from aws_lambda_powertools.utilities.validation import validate
def handler(event, context):
validate(event=event, schema=json_schema_dict, envelope="Records[*].kinesis.powertools_json(powertools_base64(data))")
return event
**Unwrap, decompress ZIP archive and deserialize JSON string event before validating against actual payload - using built-in functions** # noqa: E501
from aws_lambda_powertools.utilities.validation import validate
def handler(event, context):
validate(event=event, schema=json_schema_dict, envelope="awslogs.powertools_base64_gzip(data) | powertools_json(@).logEvents[*]")
return event
Raises
------
SchemaValidationError
When schema validation fails against data set
InvalidSchemaFormatError
When JSON schema provided is invalid
InvalidEnvelopeExpressionError
When JMESPath expression to unwrap event is invalid
"""
if envelope:
event = jmespath_utils.extract_data_from_envelope(
data=event, envelope=envelope, jmespath_options=jmespath_options
)
validate_data_against_schema(data=event, schema=schema, formats=formats)