Sha256: 01a17540ceaefd53147793f06b7a51f1f371aa7a93a0710216478399aeb9f364

Contents?: true

Size: 1.63 KB

Versions: 5

Compression:

Stored size: 1.63 KB

Contents

require 'ruby_cop'
module Alf
  module Lang
    module Parser
      class Safer
        include Parser

        def initialize(helpers = [], connection = nil)
          @lispy = Lispy.new(helpers, connection)
        end

        def parse(expr = nil, *rest, &bl)
          if expr.nil? and bl
            raise SecurityError, "Parsing of ruby blocks forbidden"
          end
          return expr if expr.is_a?(Algebra::Operand)
          check_safety!(expr.to_s)
          @lispy.parse(expr.to_s, *rest, &bl)
        end

      private

        def check_safety!(query)
          policy = Policy.new
          ast    = RubyCop::NodeBuilder.build(query)
          unless ast.accept(policy)
            raise SecurityError, "Forbidden for security reasons"
          end
          query
        end

        class Policy < RubyCop::Policy

          ALF_CALL_BLACKLIST = %w[
            gem
            puts
            to_cog
            to_relvar
            to_relation
            insert
            delete
            update
            affect
            upsert
          ].to_set.freeze

          def visit_Call(node)
            super && !ALF_CALL_BLACKLIST.include?(node.identifier.token.to_s)
          end

          ALF_CONSTANT_WHITELIST = %w[
            DEE
            DUM
          ].to_set.freeze

          def visit_Constant(node)
            ALF_CONSTANT_WHITELIST.include?(node.token.to_s)
          end

          def visit_ConstantAssignment(node)
            raise SecurityError, "Forbidden: constant assignment"
          end

        end # class Policy

      end # class Safer
    end # module Parser
  end # module Lang
end # module Alf

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
alf-core-0.16.3 lib/alf/lang/parser/safer.rb
alf-core-0.16.2 lib/alf/lang/parser/safer.rb
alf-core-0.16.1 lib/alf/lang/parser/safer.rb
alf-core-0.16.0 lib/alf/lang/parser/safer.rb
alf-core-0.15.0 lib/alf/lang/parser/safer.rb