graphql-python / graphene-django

Build powerful, efficient, and flexible GraphQL APIs with seamless Django integration.

Home Page:http://docs.graphene-python.org/projects/django/en/latest/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to disable introspection via validation rules?

smac89 opened this issue · comments

Is your feature request related to a problem? Please describe.
I need to disable introspection for graphql, how would I do that using the method described here

Describe the solution you'd like
An example of accomplishing this would be nice

Describe alternatives you've considered
I am thinking to either create a subclass of GraphQLView or graphene.Schema and add the query validation there, but I don't know if that's the recommended approach

Additional context

I ended up going with this:

from graphql import ExecutionResult, parse, validate
from graphql.validation import NoSchemaIntrospectionCustomRule

class ValidatingSchema(graphene.Schema):
    def __init__(self, *args, validation_rules=(), **kwargs):
        super().__init__(*args, **kwargs)
        self.validation_rules = validation_rules

    def execute(self, *args, **kwargs):
        return self.validate(*args, **kwargs) or super().execute(*args, **kwargs)

    async def execute_async(self, *args, **kwargs):
        return self.validate(*args, **kwargs) or await super().execute_async(*args, **kwargs)

    def validate(self, *args, **kwargs):
        if query := (kwargs.get("source") or kwargs.get("request_string")):
            errors = validate(self.graphql_schema, parse(query), rules=self.validation_rules, max_errors=3)
            if errors:
                return ExecutionResult(errors=errors)


schema = ValidatingSchema(
    query=...,
    mutation=...,
    directives=...,
    validation_rules=(
        *filter(None, (NoSchemaIntrospectionCustomRule if not settings.DEBUG else None,)),
    ),
)