question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Create a middleware to sanitize the request body

See original GitHub issue

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn’t find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google “How to X in FastAPI” and didn’t find any information.
  • I already read and followed all the tutorial in the docs and didn’t find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

from starlette.middleware.base import BaseHTTPMiddleware
from starlette.types import Message
from fastapi import Request
import bleach
import json


class SanitizeMiddleware(BaseHTTPMiddleware):

    def __init__(self, app):
        super().__init__(app)

    @staticmethod
    def __sanitize_array(array_values):
        for index, value in enumerate(array_values):
            if isinstance(value, dict):
                array_values[index] = {key: bleach.clean(
                    value) for key, value in value.items()}
            else:
                array_values[index] = bleach.clean(value)
        return array_values

    async def set_body(self, request: Request):
        receive_ = await request._receive()
        async def receive() -> Message:
            return receive_

        request._receive = receive

    async def dispatch(self, request: Request, call_next):
        await self.set_body(request)

        if request.method == 'POST' or request.method == 'PUT':
            json_body = await request.json()
            sanitize_body = {key: self.__sanitize_array(value) if isinstance(
                value, list) else bleach.clean(value) for key, value in json_body.items()}
            request._body = json.dumps(
                sanitize_body, indent=2).encode('utf-8')
            await self.set_body(request)

        response = await call_next(request)
        return response

Description

Hello guys, I’m facing an issue while trying to sanitize the request body from POST and PUT methods. The idea is to sanitize the request.body() before it even reachs the view. For instance, I would like to pass bleach on it to avoid security issues that might appear under the body that is sent. I’ve built a middleware that inherit from BaseHTTPMiddleware, to sanetize the body, but I’ve notived that I’m not changing the original request element:

Operating System

Linux

Operating System Details

No response

FastAPI Version

0.73.0

Python Version

3.8.10

Additional Context

No response

Issue Analytics

  • State:open
  • Created a year ago
  • Reactions:2
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

2reactions
XingDongZhecommented, Oct 6, 2022

@MarcelFox You are right for this

I’ve noticed that the id for both are different

In BaseHTTPMiddleware, It will be new a request instance pass to next middleware or route endpoint At this point, we only need the same request instance, so @casluxd you can do this two ways:

  • pass request to scope: scope["request"]=sanitized_reqeust
  • use contextvars: sanitized_request_context=contextvars.Contexvars("request"), sanitized_request_context.set(sanitized_reqeust)

So you can get middlerware request in your route endpoint

1reaction
JarroVGITcommented, Jul 30, 2022

Hmm I did not expect that… 🤔 I am tinkering around with this and I notice that there is a custom request being send to the next ASGI app, but the body is unsanitized. If I include a custom key in the request.scope, then that key (and value) is available in my endpoint.

Somewhere, Starlette (or FastAPI but I am thinking Starlette) is unsanitizing the body. Which is very weird!

Read more comments on GitHub >

github_iconTop Results From Across the Web

Sanitize or encode a request body in middleware?
Now, when I create a pull request on Github, Checkmark will complain about sending req.body un-sanitized or not encoded.
Read more >
Sanitization middlewares - express-validator
Creates a sanitization chain for one or more fields. They may be located in any of the following request objects: req.body; req.cookies; req.params ......
Read more >
Modifying Request body using Owin Middleware
I am trying to sanitize the requests body coming to an Asp.net (.Net 4.6) application with WebAPI 2 using OWIN/Katana.
Read more >
How to Validate and Sanitize an ExpressJS Form | heynode.com
const express = require('express'). // Include ExpressJS const app = express(). // Create an ExpressJS app const bodyParser = require('body-parser'); // ...
Read more >
A laravel middleware to sanitize the incoming Http request ...
Laravel provides one of the best mechanisms to filter your incoming HTTP request parameters. In this blog, we will build one such middleware...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found