SleepyShiba
SleepyShiba

Reputation: 23

Disabling GraphQL introspection requests on production

For company policies reasons I must disable the introspection feature of graphql-ruby gem (making the __schema requests fail / return 404).

How do I achieve this?

The application is based on Ruby on Rails version 5.2.2 and the graphql-ruby gem version is 1.8.12.

Upvotes: 2

Views: 2489

Answers (3)

Yosuke Kurami
Yosuke Kurami

Reputation: 86

graphql-ruby (>= 1.9.7) now supports setting disable_introspection_entry_points on your schema:

Upvotes: 3

Kiko Castro
Kiko Castro

Reputation: 632

If someone is looking for a dynamic option, an approach might be to use a custom Analyzer.

  1. Pass a context variable such as authorize_introspection when calling your schema:
class GraphqlController < ApplicationController

  def execute
    context = context.merge(authorize_introspection: admin?)

    result = MySchema.execute(query, 
      variables: variables, 
      context: context, 
      operation_name: operation_name, 
      root_value: root_value
    )
    render json: result.to_json
  end

 (...)
  1. Then use it here
class QueryAnalyzer < GraphQL::Analysis::AST::Analyzer

  def on_leave_field(_node, _parent, visitor)
    introspection_field_names = %w[__schema __type]
    field_def = visitor.field_definition

    if field_def.introspection? && introspection_field_names.include?(field_def.graphql_name)
      @introspection_present = true
    end

    super
  end

  def result
    return if introspection?

    GraphQL::AnalysisError.new('Not authorized to query schema internals')
  end

  private

  def introspection?
    @introspection_present && introspection_authorized?
  end

  def introspection_authorized?
    ENV['DISABLE_INTROSPECTION_ENTRY_POINTS'] != 'true' && query.context[:authorize_introspection]
  end
end
  1. Make the declaration on the schema
  class MySchema < GraphQL::Schema

    use GraphQL::Analysis::AST
    query_analyzer QueryAnalyzer

    (...)
  end

source: https://github.com/rmosolgo/graphql-ruby/issues/1240#issuecomment-393936456

Upvotes: 1

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

From the graphql-ruby documentation:

You can re-implement these fields or create new ones by creating a custom EntryPoints class in your introspection namespace:

module Introspection
  class EntryPoints < GraphQL::Introspection::EntryPoints
    # ...
  end
end

That said, just introduce def __schema method redirecting to 404 or explicitly responding with 404.


FWIW, here is the original code you are to overwrite.

Upvotes: 2

Related Questions