strawberry-graphql / strawberry

A GraphQL library for Python that leverages type annotations 🍓
https://strawberry.rocks
MIT License
4.01k stars 531 forks source link

How to disable GraphQL Introspection in Strawberry-graphql? #1329

Open sumitsharansatsangi opened 3 years ago

sumitsharansatsangi commented 3 years ago

I have tried the following to achieve it, but didn't get success.

graphql_app = GraphQL(schema, graphiql=False, debug=False)

I am using Fastapi. Maybe in other framework syntax will be different.

It is related to the security concern and must be taken in high preference. Thank you.

Upvote & Fund

Fund with Polar

ossareh commented 3 years ago

On Discord @sumitsharansatsangi noted that Ariadne has this in place, here are links to the relevant implementation:

We have everything needed to implement this as a ASTValidationRule 🎉

jkimbo commented 3 years ago

GraphQL-Core already has a no introspection validation rule: https://github.com/graphql-python/graphql-core/blob/v3.1.6/src/graphql/validation/rules/custom/no_schema_introspection.py

So using the AddValidationRule extension you can disable introspection like this:

from graphql.validation import NoSchemaIntrospectionCustomRule
import strawberry
from strawberry.extensions import AddValidationRules

schema = strawberry.Schema(
    Query,
    extensions=[
        AddValidationRules([NoSchemaIntrospectionCustomRule]),
    ]
)

I think we should probably package this up into a DisableIntrospection extension so it's easier to find.

patrick91 commented 2 years ago

@jkimbo we have documented this in our docs https://strawberry.rocks/docs/extensions/add-validation-rules#more-examples

jkimbo commented 2 years ago

@jkimbo we have documented this in our docs https://strawberry.rocks/docs/extensions/add-validation-rules#more-examples

@patrick91 that's true but do you think it warrants a dedicated extension?

patrick91 commented 2 years ago

definitely 😊 that should also make it easier to find it

mecampbellsoup commented 1 year ago

Is it possible to make introspection only possible for clients that are, e.g., authenticated?

jkimbo commented 1 year ago

@mecampbellsoup you should be able to access the schema context inside the on_validation_start() hook where you can also set what validation rules to run. For example using the Django integration (I haven't tested this):

from strawberry.extensions.base_extension import Extension
from graphql.validation import NoSchemaIntrospectionCustomRule

class DisableAnonymousIntrospection(Extension):
    def on_validation_start(self) -> None:
        schema_context = self.exection_context.context
        request = schema_context.request

        if not request.user.is_authenticated:
            self.execution_context.validation_rules = (
                self.execution_context.validation_rules + tuple([NoSchemaIntrospectionCustomRule])
            )