Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork136
Description
Suggested Behavior
Hello, I am currently using OpenAPI-core with my Flask app and I am customizing validation error responses as perfollowing comment.
The issue I am facing is that there are some fields in request which holds sensitive information, e.g credentials, Auth-tokens.
When the validation fails on these fields we get an error string which includes value of these sensitive fields.
E.g consider following response,
{ "errors": [ { "class": "<class 'openapi_core.validation.schemas.exceptions.InvalidSchemaValue'>", "status": 400, "title": "Value {'flag': 'MyPassword1234'} not valid for schema of type object: (<ValidationError: \"'MyPassword1234' is too short\">,)" } ]}
As we can see in above example, the password of user is exposed as part of response.
I do want to add validation for these fields however I don't want the values of these fields to be send as a response.
For that I checked whether there is a flag in OpenAPI which marks a field as sensitive and foundthis issue which suggested usingx-pii: true
field in the yaml
Also I usedFlaskOpenAPIErrorsHandler
to fetch the error object and see if we get details of the flags which are set for the field where the validation failed.
Following is my Flask code
#!/usr/bin/python3"""Test server."""fromflaskimportFlask,request,jsonifyfromopenapi_core.contrib.flask.decoratorsimportFlaskOpenAPIViewDecorator,FlaskOpenAPIErrorsHandlerfromopenapi_coreimportSpec# Custom Error Handler blockclassErrorHandler(FlaskOpenAPIErrorsHandler):""""Custom Error Handler"""defhandle(self,errors:list):returnjsonify({"causedBy" : [self.handle_error(error)forerrorinerrors] }),self.OPENAPI_ERROR_STATUS.get(errors[0].__class__,400)defhandle_error(self,error):""" Converts error object into error string message :param error: Error object which stores exception message :type error: Exception object :return: Error message string corresponding to error object :rtype: str """iferror.__cause__isnotNone:error=error.__cause__# TODO: If the field in error object has x-pii: true, return a generic string which does not include it's valueifnot (hasattr(error,"value")andhasattr(error,"type")andhasattr(error,"schema_errors")):returnstr(error)returnf"Value(s){error.value} not valid for schema of type{error.type} errors:{', '.join([err.messageforerrinerror.schema_errors])}"SPEC="test.yaml"obj=ErrorHandler()openapi=FlaskOpenAPIViewDecorator.from_spec(Spec.from_file_path(SPEC),openapi_errors_handler=obj)app=Flask(__name__)@app.route("/test",methods=["POST"])@openapidefread_permission():"""Test function"""returnjsonify({"flag stri_normal_json":request.json.get("flag",1) })if__name__=="__main__":app.run(host="0.0.0.0",port=345,debug=True)
And following is the Yaml file
openapi:'3.0.2'info:title:Test Titleversion:'1.0'servers: -url:http://localhost:345/paths:/test:post:requestBody:content:application/json:schema:type:objectrequired: -flagproperties:flag:x-pii:truetype:stringpattern:"^[\\w.-]*$"minLength:6maxLength:20responses:200:description:Sample responsecontent:application/json:schema:type:objectproperties:flag stri_json:type:stringminLength:6maxLength:20
Please check the TODO comment inside handle_error method.
If the validation of fieldflag
fails and if we have access to attributes offlag
yaml properties e.g below properties
flag: x-pii: true type: string pattern: "^[\\w.-]*$" minLength: 6 maxLength: 20
Then we would be able to have better customization and control over the response message.
Why is this needed?
Many times we need to have better control over the response generated on the failure of validation.
Current error messages generated by openapi-core exposes the field contents as part of response which makes openapi-core useless if there are sensitive fields in request body which needs to be validated.1
Having access to OpenAPI attributes of any field would be very helpful in generating custom response messages and would help us to perform validation on fields with sensitive data and also not expose the sensitive information to the response.
References
OAI/OpenAPI-Specification#2190
Would you like to implement a feature?
Yes