Search code examples
python-3.xmongoenginesanitization

MongoEngine: if and how to sanitize search & data input?


I'm using MongoEngine in a project, and I was wondering if and how I need to sanitize user input when creating documents and searching them.

For example, when I'm creating a document by providing data from resources like scraped RSS feeds (with feedparser), they can have almost any type of string as data:

RSS(
    rss_link=news.link,
    link=news.feed.link,
    title=news.feed.title,
    subtitle=news.feed.subtitle,
    summary=news.feed.summary,
).save()

Or, when I'm exposing said collection for user queries to find relevant RSS resources:

objects = RSS.objects.search_text(user_input).order_by('$text_score')

Does any type of input sanitization need to be done? Is it different for both cases? The documentation doesn't seem to be discussing this.


Solution

  • When saving a document, MongoEngine will run the field validation. If you use a user_input in a query, you need to sanitize it, in this case I believe ensuring that user_input is a string should be sufficient (if you are concerned about injection). As discussed here, injection can be achieved by using dictionaries so its important to sanitize