Security News
Research
Data Theft Repackaged: A Case Study in Malicious Wrapper Packages on npm
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
Decorator for REST endpoints in flask. Validate JSON request data.
When building json REST services I find myself already specifying json-schema for POST data while defining swagger spec. This package brings json validation to flask. It omits the need to validate the data yourself while profiting from an already established standard (http://json-schema.org/). Defining the schema right before the route helps the self-documentation of an endpoint (see usage).
This package uses jsonschema to for validation: https://pypi.python.org/pypi/jsonschema
Use pip to install the package from PyPI:
pip install flask-expects-json
If you are intending to install async version:
pip install flask-expects-json[async]
Note: the above command is not necessary in order to install a version
of flask-expect-json that supports async, however, the above command
will ensure flask[async]
is installed as a dependency.
This package provides a flask route decorator to validate json payload.
from flask import Flask, jsonify, g, url_for
from flask_expects_json import expects_json
# example imports
from models import User
from orm import NotUniqueError
app = Flask(__name__)
schema = {
'type': 'object',
'properties': {
'name': {'type': 'string'},
'email': {'type': 'string'},
'password': {'type': 'string'}
},
'required': ['email', 'password']
}
@app.route('/register', methods=['POST'])
@expects_json(schema)
def register():
# if payload is invalid, request will be aborted with error code 400
# if payload is valid it is stored in g.data
# do something with your data
user = User().from_dict(g.data)
try:
user.save()
except NotUniqueError as e:
# exception path: duplicate database entry
return jsonify(dict(message=e.message)), 409
# happy path: json response
resp = jsonify(dict(auth_token=user.encode_auth_token(), user=user.to_dict()))
resp.headers['Location'] = url_for('users.get_user', user_id=user.id)
return resp, 201
The expected json payload is recognizable through "schema". If schema is not met the requests aborts (400) with a hinting error message.
As of 1.2.0 this decorator uses flask.request.get_json(force=False)
to get the data. This means the mimetype of the request has to be 'application/json'. Can be disabled by setting force=False
. Be aware that this creates a major security vulnerability to CSRF since CORS is not enforced for certain mimetypes. Thanks to Argishti Rostamian for noticing.
@app.route('/strict')
@expects_json()
def strict():
return 'This view will return 400 if mimetype is not \'application/json\'
@app.route('/insecure')
@expects_json({}, force=False)
def insecure():
return 'This view will validate the data no matter the mimetype.'
As of 1.6.0 you can set check_formats=True
or check_formats=['list of format']
to enable validating formats such as email
date-time
. This is set to False
by default.
Normally validators wont touch the data. By default this package will not fill in missing default values provided in the schema. If you want to you can set fill_defaults=True
explicitly. The validation will be performed after this action, so default values can lead to invalid data.
If you want to skip the validation for certain HTTP methods, specify them with ignore_for=[]
. Typical methods that do not expect a body are GET, HEAD and DELETE. Thanks to @mtheos for implementing this.
@app.route('/', methods=['GET', 'POST'])
@expects_json(schema, ignore_for=['GET'])
def register():
return
On validation failure the library calls flask.abort
and passes an 400 error code and the validation error.
By default this creates an HTML error page and displays the error message.
To customize the behavior use the error handling provided by flask (docs).
This can be useful to e.g hide the validation message from users or provide a JSON response.
The original ValidationError is passed to flask.abort
, which itself passes arguments to werkzeug.exceptions.HTTPException
so it can be retrieved on error.description
like this:
from flask import make_response, jsonify
from jsonschema import ValidationError
@app.errorhandler(400)
def bad_request(error):
if isinstance(error.description, ValidationError):
original_error = error.description
return make_response(jsonify({'error': original_error.message}), 400)
# handle other "Bad Request"-errors
return error
The following are the steps to create a virtual environment into a folder named "venv" and install the requirements.
# Create virtualenv
python3 -m venv venv
# activate virtualenv
source venv/bin/activate
# update packages
pip install --upgrade pip setuptools wheel
# install requirements
python setup.py install
Tests can be run with python setup.py test
when the virtualenv is active.
FAQs
Decorator for REST endpoints in flask. Validate JSON request data.
We found that flask-expects-json demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Research
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
Research
Security News
Attackers used a malicious npm package typosquatting a popular ESLint plugin to steal sensitive data, execute commands, and exploit developer systems.
Security News
The Ultralytics' PyPI Package was compromised four times in one weekend through GitHub Actions cache poisoning and failure to rotate previously compromised API tokens.