Skip to content

Instantly share code, notes, and snippets.

@thbar
Forked from nelhage/make_yaml_safe.rb
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thbar/9770758 to your computer and use it in GitHub Desktop.
Save thbar/9770758 to your computer and use it in GitHub Desktop.
# Attempt at porting https://gist.github.com/nelhage/4507129 to ruby 2.0
#
# I just removed all traces of Syck
def self.make_yaml_safe!
if defined?(Psych)
Psych.const_set("UnsafeYAML", Class.new(StandardError))
Psych.module_eval do
def self.load(yaml, *args)
result = parse(yaml, *args)
check_safety(result)
result ? result.to_ruby : result
end
private
def self.check_safety(o)
check_node(o)
case o
when Psych::Nodes::Scalar
when Psych::Nodes::Sequence
o.children.each {|child| check_safety(child)}
when Psych::Nodes::Mapping
o.children.each {|child| check_safety(child)}
when Psych::Nodes::Document
check_safety(o.root)
when Psych::Nodes::Stream
o.children.each {|child| check_safety(child)}
when Psych::Nodes::Alias
else
raise Psych::UnsafeYAML.new("Found unknown node type: #{o.class}")
end
end
def self.check_node(n)
# Note thbar: we're allowing HashWithIndifferentAccess here
# to cope with https://www.pivotaltracker.com/s/projects/971396
unless n.tag.nil? || ['!ruby/sym', '!ruby/symbol', '!map:HashWithIndifferentAccess', '!map:ActiveSupport::HashWithIndifferentAccess', '!ruby/hash:ActiveSupport::HashWithIndifferentAccess', '!binary', '!'].include?(n.tag)
raise Psych::UnsafeYAML.new("Found node with tag: #{n.tag}")
end
end
end
end
end
make_yaml_safe!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment