-
Notifications
You must be signed in to change notification settings - Fork 2.4k
feat: Add ValidateBody/ValidateParameters attribute to setup API model validators #2026
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
+1 |
@Rondineli How would the model validator work with a GET? I thought we could use it only to validate body on POST and PATCH I never really passed a body to a GET so that is why I am asking. |
Exist a possibility of passing a body request trouh a get, yes: example: curl -XGET https://<apigw id>.execute-api.us-east-1.amazonaws.com/test/ -H "Content-Type: application/json" -d '{"message": "foo"}' Then on lambda event: {'resource': '/', 'path': '/', 'httpMethod': 'GET', 'headers': {'accept': '*/*', 'content-type': 'application/json', ..., 'body': '{"message": "foo"}', 'isBase64Encoded': False} If you define a model you can validate the body on those methods. |
@Rondineli Unfortunately we cannot accept this in the current state. The In order to not break existing customers (magically add validation into their API), this needs to be a separate property within the Spec. Are you still interesting in contributing this? We will want to understand the design of the property at a high level, could be done in a comment here, and then we can go with code changes once we agree on the Spec design. |
@jfuss Got it! Under the issue comments there are comments around maybe inside of the Model block, adding two new parameters: |
would be something like: Resources:
HtmlFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: s3://sam-demo-bucket/member_portal.zip
Handler: index.gethtml
Runtime: nodejs12.x
Events:
GetHtml:
Type: Api
Properties:
RestApiId: HtmlApi
Path: /
Method: get
RequestModel:
Model: User
Required: true
ValidateBody: true
ValidateRequest: true if they are not present on the config, I don't add the validator. |
That looks reasonable to me. I think that makes sense. It's possible to condense this into one property too.
I think I like your a little better. Less conditional logic to handle and makes intrinsic a little cleaner. Side note: |
ok! Will make a PR with those 2 fields and to set only booleans, I like the idea of not having an intrinsics better as there is a way of setting up customised validators trough swagger body definitions. I think set those two fields (as the validators only supports those two anyways) the only case I would see set a custom validator is to change the name of it, and it can be done trough swagger definitions. Ok, will change my PR to achieve this then! Thanks! |
…d case where a validator could have a / only and changed it to translate as 'root'
…ients with model required
…ients with model required
Codecov Report
@@ Coverage Diff @@
## develop #2026 +/- ##
===========================================
+ Coverage 93.58% 93.87% +0.28%
===========================================
Files 90 91 +1
Lines 6124 6201 +77
Branches 1260 1272 +12
===========================================
+ Hits 5731 5821 +90
+ Misses 183 175 -8
+ Partials 210 205 -5
Continue to review full report at Codecov.
|
@jfuss PR is ready to a re-review. :) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
would be great to have this reviewed and merged
@Rondineli Thanks for updating the PR. I haven't gotten a chance to review yet but on my list to do by the end of the week (6/4). |
…lidateParameters also renamed everything from validator_request. Moved validators names according with the comum use.
Thanks for reviewing this and pointing out the improvements. I fixed every comment! |
On the subject of "adding N validators" and not knowing what validation API Gateway might add in the future: Why not at just add RequestValidatorId to the event and let the user reference a validator that's defined in the template? This way, if API Gateway adds to the RequestValidator's capabilities, SAM doesn't have to worry about keeping up. As you mentioned, there are limited combinations so the user would at most need to define 3 validator resources. What's the point of auto-generating the validator(s)? |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@Rondineli I appreciate the patience from our end and working through everything. I have one additional comment (based upon some other changes going on). If you could address that, I think we will be in really good shape to get this approved on our side and work through our release process (doc updates, service updates, etc).
samtranslator/swagger/swagger.py
Outdated
self._doc[self._X_APIGW_REQUEST_VALIDATORS].update(request_validator_definition) | ||
|
||
# It is possible that the method could have two definitions in a Fn::If block. | ||
for method_definition in self.get_method_contents(self.get_path(path)[normalized_method_name]): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We have been moving away from this kind of access pattern and moving towards what is in this pr: https://github.com/aws/serverless-application-model/pull/2031/files
The reason is the normalization causes KeyErrors
when methods like "any" are used, since that will get translated to x-amazon-apigateway-any-method
. Can you match what is in the PR I linked? for method_definition in self.get_method_contents(method):
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@jfuss done!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@jfuss thinking a bit more about this last change, it doesn't seems right to me:
for method_name, method in self.get_path(path).items():
# It is possible that the method could have two definitions in a Fn::If block.
for method_definition in self.get_method_contents(method):
# If no integration given, then we don't need to process this
So, it would be something like:
for method_name, method in self.get_path(path).items():
# Adding it to only path
if method_name == normalized_method_name:
for method_definition in self.get_method_contents(method):
right?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
without checking the method_name with the normalized_method_name it would add this to all methods for the given path.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Seems reasonable to me. I am more comfortable with this since it is a new code path (unlikely to accidentally break existing customers for something we are unaware of).
@Rondineli Thank you for all the effort and time spent on the contribution. It is very much appreciated. As for next steps: I need to kick of some processes internally (docs for example). I will eventually merge this into develop (later this week). Just giving you the heads up and communicate no further action on you. |
this will be only for the requestmodel or also for requestparameter ? |
ValidateRequestBody and validateRequestParams: ValidateBody: true
ValidateParameters: true |
Congratulations @Rondineli |
…s#2026) * Added validators to the swagger definitions when a model is required * Remove approach of trying an extra field for validators * WIP - tests deps not working * Finished and fixed all tests to make pr command was complaining. Fixed case where a validator could have a / only and changed it to translate as 'root' * py2.7 complaint * Fix py2.7 order of validators on output folder * WIP - adding validator fields * Set another strategy to set the validators without affect existent clients with model required * Set another strategy to set the validators without affect existent clients with model required * Remove mistaken file pushed * Remove mistaken file pushed * Partial coments fixes * Implemented case where we can set a only limited combinations on the specs * Fix case test when multiple path are using same validator * Added openapi3 specific tests * Added openapi3 specific tests * Fix requested changes from review: Renamed from ValidateRequest -> ValidateParameters also renamed everything from validator_request. Moved validators names according with the comum use. * new approach to not cause KeyErrors * Setting validator to the only given method not all methods on the path * removed extra space on comment - lint * Normalized method name path that comes from the template Co-authored-by: Rondineli Gomes de Araujo <[email protected]> Co-authored-by: Rondineli <[email protected]> Co-authored-by: Rondineli <[email protected]>
* chore: don't install integration tests (#1964) * Remove unnecessary use of comprehension (#1805) * fix: Grammatical error in README.md (#1965) * fix: Added SAR Support Check (#1972) * Added SAR Support Check * Added docstring and Removed Instance Initialization for Class Method * update pyyaml version to get the security update (#1974) * fix the request parameter parsing, the value can contain dots (#1975) * fix the request parameter parsing, the value can contain dots * fix the unit test for python 2.7 * use built in split, instead of concatenating the string * Documentation: fix incorrect header (#1979) Fixed the incorrectly formatted header for HTTP API section * fix: mutable default values in method definitions (#1997) * fix: remove explicit logging level set in single module (#1998) * fix: Fail when Intrinsics are in SourceVPC list instead of IntrinsicsSourceVPC (#1999) * feat: Adding support for metric publishing. (#2062) * Adding support for metric publishing, manually tested and tests pending. * Adding make action for running test with html coverage. * Adding unit tests for metrics. * Writing integration tests for metrics publishing. * Black reformatting * Fixing unit test. * Addressing PR comments. * Clearing __init__py from test module. * Updating documentation for publish method. Co-authored-by: Tarun Mall <[email protected]> * Update AppConfig boto3 client config to shorten timeout (#2070) * Update AppConfig boto3 client config to shorten timeout * Update timeout config of AppConfig boto3 client * feat: Add ValidateBody/ValidateParameters attribute to API models (#2026) * Added validators to the swagger definitions when a model is required * Remove approach of trying an extra field for validators * WIP - tests deps not working * Finished and fixed all tests to make pr command was complaining. Fixed case where a validator could have a / only and changed it to translate as 'root' * py2.7 complaint * Fix py2.7 order of validators on output folder * WIP - adding validator fields * Set another strategy to set the validators without affect existent clients with model required * Set another strategy to set the validators without affect existent clients with model required * Remove mistaken file pushed * Remove mistaken file pushed * Partial coments fixes * Implemented case where we can set a only limited combinations on the specs * Fix case test when multiple path are using same validator * Added openapi3 specific tests * Added openapi3 specific tests * Fix requested changes from review: Renamed from ValidateRequest -> ValidateParameters also renamed everything from validator_request. Moved validators names according with the comum use. * new approach to not cause KeyErrors * Setting validator to the only given method not all methods on the path * removed extra space on comment - lint * Normalized method name path that comes from the template Co-authored-by: Rondineli Gomes de Araujo <[email protected]> Co-authored-by: Rondineli <[email protected]> Co-authored-by: Rondineli <[email protected]> * fix: fail with invalid resource, when RetentionPolicy has unresolved intrinsic value (#2074) * fix: fail with invalid resource, when RetentionPolicy has unresolved intrinsic value * make black * remove extra formatting * add test case for !ref * test: Migration of combination integration tests (#1970) * fix: Compare integration tests results using hash of file content instead of image compare (#2086) * change yaml.load to yaml.safe_load for the security best practice * use yaml_parse for consistant style * remove pillow library for image comparing, use hash instead * make it compatible with py2 * Remove logging of SAR service call response (#2064) * Test CloudWatchEvent Properties With Intrinsic Functions (#2090) * Add headers whenever cors is set * Add cw event success cases * Replace GetAtt with condition * Cleanup test yaml * Cleanup test yaml * Remove files * Add intrinsic to pattern field * Fix wrong files committed * test: Added intrinsic tests for Function SNS Event (#2101) * fix: Validate Trigger field and test Cognito properties with intrinsic functions (#2092) * Add headers whenever cors is set * Fix Cognito trigger validation * Make templates deployable * Removed trigger value validation * Fix Python2 string matching test issue * Use PropertyType mechanism to exclude intrinsics * Remove unused import * feat(Intrinsic Tests): Added Tests for Kinesis Event Source with Intrinsics (#2103) * Added Tests for Kinesis EventSource with Intrinsics * Fixed Formatting with Black * fix: Don't attempt to refetch a swagger method object by its name as we already have it (#2031) * Fix a bad logic where a hash key is modified then refetched which results in KeyError * add unit tests and update other instance of same usage on line 534 * fix: Fix the same code in open_api.py Co-authored-by: Mehmet Nuri Deveci <[email protected]> Co-authored-by: Mathieu Grandis <[email protected]> * test: Adding intrinsic tests for Function S3 Event (#2100) * fix(bug): Check if Identity.ReauthorizeEvery equals zero (#2105) * Revert "Revert "Issue 1508 remove check requiring identity ... (#1577)" (#2038)" This reverts commit ed3c283. * Update implementation to support intrinsics/ add more tests to validate changes * Fixing hashes for py2 * Run make black * Handle pr feedback * Add another unit tests to cover the original issue Co-authored-by: Jacob Fuss <[email protected]> * chore: Update PR Checklist to include writing intrinsic tests (#2106) * Update PR Checklist to include writing intrinsic tests * Handle pr feedback Co-authored-by: Jacob Fuss <[email protected]> * Delete .travis.yml (#2102) * fix: Correct grammar in the waiting for changeset message (#2027) * chore: bump version to 1.39.0 (#2128) Co-authored-by: Chih-Hsuan Yen <[email protected]> Co-authored-by: Harsh Mishra <[email protected]> Co-authored-by: Pranav <[email protected]> Co-authored-by: Cosh_ <[email protected]> Co-authored-by: Mohamed Elasmar <[email protected]> Co-authored-by: Ben <[email protected]> Co-authored-by: Mehmet Nuri Deveci <[email protected]> Co-authored-by: Jacob Fuss <[email protected]> Co-authored-by: Tarun <[email protected]> Co-authored-by: Tarun Mall <[email protected]> Co-authored-by: Wing Fung Lau <[email protected]> Co-authored-by: Rondineli <[email protected]> Co-authored-by: Rondineli Gomes de Araujo <[email protected]> Co-authored-by: Rondineli <[email protected]> Co-authored-by: Rondineli <[email protected]> Co-authored-by: mingkun2020 <[email protected]> Co-authored-by: Daniel Mil <[email protected]> Co-authored-by: Ahmed Elbayaa <[email protected]> Co-authored-by: Jacob Fuss <[email protected]> Co-authored-by: Ichinose Shogo <[email protected]> Co-authored-by: Ryan Parman <[email protected]>
* Release/v1.39.0 (#2141) * chore: don't install integration tests (#1964) * Remove unnecessary use of comprehension (#1805) * fix: Grammatical error in README.md (#1965) * fix: Added SAR Support Check (#1972) * Added SAR Support Check * Added docstring and Removed Instance Initialization for Class Method * update pyyaml version to get the security update (#1974) * fix the request parameter parsing, the value can contain dots (#1975) * fix the request parameter parsing, the value can contain dots * fix the unit test for python 2.7 * use built in split, instead of concatenating the string * Documentation: fix incorrect header (#1979) Fixed the incorrectly formatted header for HTTP API section * fix: mutable default values in method definitions (#1997) * fix: remove explicit logging level set in single module (#1998) * fix: Fail when Intrinsics are in SourceVPC list instead of IntrinsicsSourceVPC (#1999) * feat: Adding support for metric publishing. (#2062) * Adding support for metric publishing, manually tested and tests pending. * Adding make action for running test with html coverage. * Adding unit tests for metrics. * Writing integration tests for metrics publishing. * Black reformatting * Fixing unit test. * Addressing PR comments. * Clearing __init__py from test module. * Updating documentation for publish method. Co-authored-by: Tarun Mall <[email protected]> * Update AppConfig boto3 client config to shorten timeout (#2070) * Update AppConfig boto3 client config to shorten timeout * Update timeout config of AppConfig boto3 client * feat: Add ValidateBody/ValidateParameters attribute to API models (#2026) * Added validators to the swagger definitions when a model is required * Remove approach of trying an extra field for validators * WIP - tests deps not working * Finished and fixed all tests to make pr command was complaining. Fixed case where a validator could have a / only and changed it to translate as 'root' * py2.7 complaint * Fix py2.7 order of validators on output folder * WIP - adding validator fields * Set another strategy to set the validators without affect existent clients with model required * Set another strategy to set the validators without affect existent clients with model required * Remove mistaken file pushed * Remove mistaken file pushed * Partial coments fixes * Implemented case where we can set a only limited combinations on the specs * Fix case test when multiple path are using same validator * Added openapi3 specific tests * Added openapi3 specific tests * Fix requested changes from review: Renamed from ValidateRequest -> ValidateParameters also renamed everything from validator_request. Moved validators names according with the comum use. * new approach to not cause KeyErrors * Setting validator to the only given method not all methods on the path * removed extra space on comment - lint * Normalized method name path that comes from the template Co-authored-by: Rondineli Gomes de Araujo <[email protected]> Co-authored-by: Rondineli <[email protected]> Co-authored-by: Rondineli <[email protected]> * fix: fail with invalid resource, when RetentionPolicy has unresolved intrinsic value (#2074) * fix: fail with invalid resource, when RetentionPolicy has unresolved intrinsic value * make black * remove extra formatting * add test case for !ref * test: Migration of combination integration tests (#1970) * fix: Compare integration tests results using hash of file content instead of image compare (#2086) * change yaml.load to yaml.safe_load for the security best practice * use yaml_parse for consistant style * remove pillow library for image comparing, use hash instead * make it compatible with py2 * Remove logging of SAR service call response (#2064) * Test CloudWatchEvent Properties With Intrinsic Functions (#2090) * Add headers whenever cors is set * Add cw event success cases * Replace GetAtt with condition * Cleanup test yaml * Cleanup test yaml * Remove files * Add intrinsic to pattern field * Fix wrong files committed * test: Added intrinsic tests for Function SNS Event (#2101) * fix: Validate Trigger field and test Cognito properties with intrinsic functions (#2092) * Add headers whenever cors is set * Fix Cognito trigger validation * Make templates deployable * Removed trigger value validation * Fix Python2 string matching test issue * Use PropertyType mechanism to exclude intrinsics * Remove unused import * feat(Intrinsic Tests): Added Tests for Kinesis Event Source with Intrinsics (#2103) * Added Tests for Kinesis EventSource with Intrinsics * Fixed Formatting with Black * fix: Don't attempt to refetch a swagger method object by its name as we already have it (#2031) * Fix a bad logic where a hash key is modified then refetched which results in KeyError * add unit tests and update other instance of same usage on line 534 * fix: Fix the same code in open_api.py Co-authored-by: Mehmet Nuri Deveci <[email protected]> Co-authored-by: Mathieu Grandis <[email protected]> * test: Adding intrinsic tests for Function S3 Event (#2100) * fix(bug): Check if Identity.ReauthorizeEvery equals zero (#2105) * Revert "Revert "Issue 1508 remove check requiring identity ... (#1577)" (#2038)" This reverts commit ed3c283. * Update implementation to support intrinsics/ add more tests to validate changes * Fixing hashes for py2 * Run make black * Handle pr feedback * Add another unit tests to cover the original issue Co-authored-by: Jacob Fuss <[email protected]> * chore: Update PR Checklist to include writing intrinsic tests (#2106) * Update PR Checklist to include writing intrinsic tests * Handle pr feedback Co-authored-by: Jacob Fuss <[email protected]> * Delete .travis.yml (#2102) * fix: Correct grammar in the waiting for changeset message (#2027) * chore: bump version to 1.39.0 (#2128) Co-authored-by: Chih-Hsuan Yen <[email protected]> Co-authored-by: Harsh Mishra <[email protected]> Co-authored-by: Pranav <[email protected]> Co-authored-by: Cosh_ <[email protected]> Co-authored-by: Mohamed Elasmar <[email protected]> Co-authored-by: Ben <[email protected]> Co-authored-by: Mehmet Nuri Deveci <[email protected]> Co-authored-by: Jacob Fuss <[email protected]> Co-authored-by: Tarun <[email protected]> Co-authored-by: Tarun Mall <[email protected]> Co-authored-by: Wing Fung Lau <[email protected]> Co-authored-by: Rondineli <[email protected]> Co-authored-by: Rondineli Gomes de Araujo <[email protected]> Co-authored-by: Rondineli <[email protected]> Co-authored-by: Rondineli <[email protected]> Co-authored-by: mingkun2020 <[email protected]> Co-authored-by: Daniel Mil <[email protected]> Co-authored-by: Ahmed Elbayaa <[email protected]> Co-authored-by: Jacob Fuss <[email protected]> Co-authored-by: Ichinose Shogo <[email protected]> Co-authored-by: Ryan Parman <[email protected]> * feat: ARM support (#2163) * feat: ARM architecture support for Function and Layer * Add docs/tests for Globals Architectures (#85) Co-authored-by: Renato Valenzuela <[email protected]> Co-authored-by: Chih-Hsuan Yen <[email protected]> Co-authored-by: Harsh Mishra <[email protected]> Co-authored-by: Pranav <[email protected]> Co-authored-by: Cosh_ <[email protected]> Co-authored-by: Mohamed Elasmar <[email protected]> Co-authored-by: Ben <[email protected]> Co-authored-by: Mehmet Nuri Deveci <[email protected]> Co-authored-by: Jacob Fuss <[email protected]> Co-authored-by: Tarun <[email protected]> Co-authored-by: Tarun Mall <[email protected]> Co-authored-by: Wing Fung Lau <[email protected]> Co-authored-by: Rondineli <[email protected]> Co-authored-by: Rondineli Gomes de Araujo <[email protected]> Co-authored-by: Rondineli <[email protected]> Co-authored-by: Rondineli <[email protected]> Co-authored-by: mingkun2020 <[email protected]> Co-authored-by: Daniel Mil <[email protected]> Co-authored-by: Ahmed Elbayaa <[email protected]> Co-authored-by: Jacob Fuss <[email protected]> Co-authored-by: Ichinose Shogo <[email protected]> Co-authored-by: Ryan Parman <[email protected]> Co-authored-by: Renato Valenzuela <[email protected]>
Hey guys, if I understand this code correctly, no validator will be created if Does this mean in a scenario where I just want to validate if a user is passing in a query param that I have to create a "fake" model anyway to create this? e.g Properties:
Method: get
RequestParameters:
- method.request.querystring.query:
Required: true
RequestModel:
ValidateParameters: true ^ This creates the parameter but no validator. If I create a dummy model, however, then it works. Is this something that should be added (open a new issue)? Just trying to gauge if it was the intention of this PR to support this. |
@iRoachie how are you using these changes if they are still on aws:develop branch? |
@AllanOricil by the looks of the release notes, this is released no? https://github.com/aws/serverless-application-model/releases/tag/v1.39.0 |
@iRoachie great. I will give it a try :D |
@Rondineli in the console or using cdk (which I ended up using), no model is needed to validate the presence of a query string parameter. I should be able to perform the same in sam but the implementation of this PR requires a model to be created. |
I have a question regarding the implementation of Models. Our architecture uses the implicitly created AWS::Serverless::Api resource rather than creating the resource manually and adding every Function (70-80) to it. I'm trying to create a AWS::ApiGateway::Model resource and set the RestApiId to the implicit resource (ServerlessRestApi). This fails the sam validation with the following error "the related API does not contain valid Models". Is the only way to implement this to explicitly create a AWS::Serverless::Api resource, add the models, then add everything to the explicit resource rather than using the implicitly created one. |
I'm having the same issue as @iRoachie. On a GET method you typically want to validate only requestParameters, not RequestModel. Nevertheless you have to define a Model in orther to activate de parameter validation. Unless you can somehow use a Model to define querystringparameters, which is unclear to me. |
Issue #, if available: #1403
Description of changes: Adding a request validator to the method when a model is defined and set required to True
Description of how you validated changes:
Create a sam template like the following:
Then on the swagger definitions it should create a validation definition with the

path-method-validator
format and set it on the integration. Then on the console, we should see this flagged:Checklist:
make pr
passesExamples?
Please reach out in the comments, if you want to add an example. Examples will be
added to
sam init
through https://github.com/awslabs/aws-sam-cli-app-templates/By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.