【问题标题】:Disabling GraphQL introspection requests on production在生产环境中禁用 GraphQL 自省请求
【发布时间】:2019-01-06 14:33:21
【问题描述】:

出于公司政策的原因,我必须禁用 graphql-ruby gem 的自省功能(使 __schema 请求失败/返回 404)。

我如何做到这一点?

该应用程序基于 Ruby on Rails 版本 5.2.2,graphql-ruby gem 版本为 1.8.12。

【问题讨论】:

    标签: ruby-on-rails ruby graphql graphql-ruby


    【解决方案1】:

    来自graphql-ruby documentation

    您可以通过在自省命名空间中创建自定义 EntryPoints 类来重新实现这些字段或创建新字段:

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

    也就是说,只需引入 def __schema 方法重定向到 404 或显式响应 404


    FWIW,here is the original code 你要覆盖。

    【讨论】:

      【解决方案2】:

      graphql-ruby (>= 1.9.7) 支持 disable_introspection_entry_points 。

      https://github.com/rmosolgo/graphql-ruby/pull/2327

      【讨论】:

        【解决方案3】:

        如果有人正在寻找动态选项,一种方法可能是使用自定义分析器。

        1. 调用架构时传递上下文变量,例如 authorize_introspection:
        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. 然后在这里使用它
        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. 在架构上进行声明
          class MySchema < GraphQL::Schema
        
            use GraphQL::Analysis::AST
            query_analyzer QueryAnalyzer
        
            (...)
          end
        

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-04-01
          • 1970-01-01
          • 2018-03-06
          • 2021-11-10
          • 2020-10-17
          • 2021-12-25
          • 2016-05-21
          • 1970-01-01
          相关资源
          最近更新 更多