Skip to content

How to disable introspection via validation rules? #1342

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
smac89 opened this issue Aug 29, 2022 · 1 comment · Fixed by #1475
Closed

How to disable introspection via validation rules? #1342

smac89 opened this issue Aug 29, 2022 · 1 comment · Fixed by #1475

Comments

@smac89
Copy link

smac89 commented Aug 29, 2022

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

@smac89
Copy link
Author

smac89 commented Aug 29, 2022

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,)),
    ),
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants