Search code examples
djangopostgresqlsecuritysql-injectionjsonb

Security concerns with user defined postgres jsonb queries in Django


We have a postgres jsonb field in Django that allows users to store arbitrary user data. We wish to allow users to query this field but are unsure about the security implications.

The model

from django.db import models

class Item(models.Model):
    user = models.ForeignKey("user", null=False)
    meta = JSONField()

Query

def custom_query(operation, value):
    qs = Item.objects.filter(user=user)

    params = {
        "meta__" + operation: value
    }

    qs = qs.filter(**params)

Usage:

Assuming meta is {"a": 1}.

custom_query(operation="contains", value={"a": 1})
custom_query(operation="a", value=1)

The above should be valid and equivalent queries.

Is this a secure way to perform the query?


Solution

  • I'd suggest adding an allowlist for valid operations and maybe checking the value is suitably simple (only strings, for example), but in the presence of other filters that ensure the rows that can be selected are those the user can see, I don't see a problem with this.