Module: Legate::Generators::CodeValidator

Defined in:
lib/legate/generators/code_validator.rb

Defined Under Namespace

Classes: UnsafeCodeError

Constant Summary collapse

BLOCKED_IDENTS =
%w[system exec eval instance_eval class_eval module_eval popen].freeze
BLOCKED_CONSTS =
%w[Open3].freeze

Class Method Summary collapse

Class Method Details

.validate!(code) ⇒ Object



15
16
17
18
# File 'lib/legate/generators/code_validator.rb', line 15

def validate!(code)
  validate_syntax!(code)
  validate_no_dangerous_calls!(code)
end

.validate_no_dangerous_calls!(code) ⇒ Object

Raises:



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/legate/generators/code_validator.rb', line 25

def validate_no_dangerous_calls!(code)
  tokens = Ripper.lex(code)
  dangerous = []

  tokens.each do |(_, type, token, _)|
    case type
    when :on_backtick
      dangerous << 'backtick command execution'
    when :on_ident
      dangerous << "`#{token}`" if BLOCKED_IDENTS.include?(token)
    when :on_const
      dangerous << "`#{token}`" if BLOCKED_CONSTS.include?(token)
    end
  end

  return if dangerous.empty?

  raise UnsafeCodeError,
        "Generated code contains potentially dangerous calls: #{dangerous.uniq.join(', ')}. " \
        'Review the code manually before saving.'
end

.validate_syntax!(code) ⇒ Object

Raises:



20
21
22
23
# File 'lib/legate/generators/code_validator.rb', line 20

def validate_syntax!(code)
  sexp = Ripper.sexp(code)
  raise UnsafeCodeError, 'Generated code has Ruby syntax errors and cannot be saved.' unless sexp
end