safemode 1.3.1 → 2.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,10 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require File.join(File.dirname(__FILE__), 'test_helper')
2
4
 
3
5
  class TestERBEval < Test::Unit::TestCase
4
6
  include TestHelper
5
-
7
+
6
8
  def setup
7
9
  @box = Safemode::Box.new
8
10
  @locals = { :article => Article.new }
@@ -18,61 +20,59 @@ class TestERBEval < Test::Unit::TestCase
18
20
  assert_nothing_raised{ @box.eval code }
19
21
  end
20
22
  end
21
-
23
+
22
24
  def test_should_turn_assigns_to_jails
23
25
  assert_raise_no_method "@article.system", @assigns, &@erb_parse
24
26
  end
25
-
27
+
26
28
  def test_should_turn_locals_to_jails
27
29
  code = @erb_parse.call "article.system"
28
30
  assert_raise(Safemode::NoMethodError){ @box.eval code, {}, @locals }
29
31
  end
30
-
32
+
31
33
  def test_should_allow_method_access_on_assigns
32
34
  code = @erb_parse.call "@article.title"
33
35
  assert_nothing_raised{ @box.eval code, @assigns }
34
36
  end
35
-
37
+
36
38
  def test_should_allow_method_access_on_locals
37
39
  code = @erb_parse.call "article.title"
38
40
  assert_nothing_raised{ @box.eval code, {}, @locals }
39
41
  end
40
-
42
+
41
43
  def test_should_not_raise_on_if_using_return_values
42
44
  code = @erb_parse.call "if @article.is_article?\n 1\n end"
43
45
  assert_nothing_raised{ @box.eval code, @assigns }
44
46
  end
45
-
47
+
46
48
  def test_should_work_with_if_using_return_values
47
49
  code = @erb_parse.call "if @article.is_article? then 1 end"
48
50
  assert_equal @box.eval(code, @assigns), "1" # ERB calls to_s on the result of the if block
49
51
  end
50
-
52
+
51
53
  def test__FILE__should_not_render_filename
52
54
  code = @erb_parse.call "__FILE__"
53
55
  assert_equal '(string)', @box.eval(code)
54
56
  end
55
-
57
+
56
58
  def test_interpolated_xstr_should_raise_security
57
59
  assert_raise_security '"#{`ls -a`}"'
58
- end
59
-
60
+ end
61
+
60
62
  TestHelper.no_method_error_raising_calls.each do |call|
61
- call.gsub!('"', '\\\\"')
62
63
  class_eval %Q(
63
64
  def test_calling_#{call.gsub(/[\W]/, '_')}_should_raise_no_method
64
- assert_raise_no_method "#{call}", @assigns, @locals
65
+ assert_raise_no_method "#{call.gsub('"', '\\\\"')}", @assigns, @locals
65
66
  end
66
67
  )
67
68
  end
68
-
69
+
69
70
  TestHelper.security_error_raising_calls.each do |call|
70
- call.gsub!('"', '\\\\"')
71
71
  class_eval %Q(
72
72
  def test_calling_#{call.gsub(/[\W]/, '_')}_should_raise_security
73
- assert_raise_security "#{call}", @assigns, @locals
73
+ assert_raise_security "#{call.gsub('"', '\\\\"')}", @assigns, @locals
74
74
  end
75
75
  )
76
- end
76
+ end
77
77
 
78
78
  end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+ require_relative 'test_helper'
3
+
4
+ class TestForLoopJail < Test::Unit::TestCase
5
+ class Host
6
+ attr_reader :calls
7
+
8
+ def initialize
9
+ @calls = []
10
+ end
11
+
12
+ def each
13
+ @calls << :each
14
+ yield 'secret'
15
+ end
16
+ end
17
+
18
+ def test_for_loop_checks_each_permission
19
+ host = Host.new
20
+ assert_raise(Safemode::NoMethodError) do
21
+ Safemode::Box.new.eval('for x in @host; x; end', host: host)
22
+ end
23
+ assert_empty host.calls
24
+ assert_equal 3, Safemode::Box.new.eval('sum = 0; for x in [1, 2]; sum += x; end; sum')
25
+ assert_equal 2, Safemode::Box.new.eval('for x in [1, 2]; end; x')
26
+ end
27
+ end
data/test/test_helper.rb CHANGED
@@ -1,4 +1,6 @@
1
- if RUBY_VERSION >= '1.9'and ENV['COVERAGE']
1
+ # frozen_string_literal: true
2
+
3
+ if ENV['COVERAGE']
2
4
  require 'simplecov'
3
5
  SimpleCov.start {add_filter 'test_'}
4
6
  end
@@ -22,7 +24,7 @@ module TestHelper
22
24
  '@article.comment_class.new',
23
25
  'String.instance_variable_set :@a, :a' ]
24
26
  end
25
-
27
+
26
28
  def security_error_raising_calls
27
29
  [ "class A\n end",
28
30
  'File.open("/etc/passwd")',
@@ -42,10 +44,10 @@ module TestHelper
42
44
  "attr_reader :a",
43
45
  'URI("http://google.com")',
44
46
  "`ls -a`", "exec('echo *')", "syscall 4, 1, 'hello', 5", "system('touch /tmp/helloworld')",
45
- "abort",
47
+ "abort",
46
48
  "exit(0)", "exit!(0)", "at_exit{'goodbye'}",
47
49
  "autoload(::MyModule, 'my_module.rb')",
48
- "binding",
50
+ "binding",
49
51
  "callcc{|cont| cont.call}",
50
52
  'eval %Q(send(:system, "ls -a"))',
51
53
  "fork",
@@ -58,12 +60,12 @@ module TestHelper
58
60
  "open('/etc/passwd'){|f| f.read}",
59
61
  "p 'text'", "pretty_inspect",
60
62
  # "print 'text'", "puts 'text'", allowed and buffered these (see ScopeObject)
61
- "printf 'text'", "putc 'a'",
63
+ "printf 'text'", "putc 'a'",
62
64
  "raise RuntimeError, 'should not happen'",
63
- "rand(0)", "srand(0)",
65
+ "rand(0)", "srand(0)",
64
66
  "set_trace_func proc{|event| puts event}", "trace_var :$_, proc {|v| puts v }", "untrace_var :$_",
65
- "sleep", "sleep(0)",
66
- "test(1, a, b)",
67
+ "sleep", "sleep(0)",
68
+ "test(1, a, b)",
67
69
  "Signal.trap(0, proc { puts 'Terminating: #{$$}' })",
68
70
  "warn 'warning'",
69
71
  'Array.new' ]
@@ -77,31 +79,31 @@ module TestHelper
77
79
  def assert_raise_security(code = nil, assigns = {}, locals = {}, &block)
78
80
  assert_raise_safemode_error(Safemode::SecurityError, code, assigns, locals, &block)
79
81
  end
80
-
82
+
81
83
  def assert_raise_safemode_error(error, code, assigns = {}, locals = {})
82
84
  code = yield(code) if block_given?
83
85
  assert_raise(error, code) { safebox_eval(code, assigns, locals) }
84
86
  end
85
-
87
+
86
88
  def safebox_eval(code, assigns = {}, locals = {})
87
89
  # puts Safemode::Parser.jail(code)
88
90
  Safemode::Box.new.eval code, assigns, locals
89
- end
91
+ end
90
92
  end
91
93
 
92
94
  class Article
93
95
  def is_article?
94
96
  true
95
97
  end
96
-
98
+
97
99
  def title
98
100
  'an article title'
99
101
  end
100
-
102
+
101
103
  def to_jail
102
104
  Article::Jail.new self
103
105
  end
104
-
106
+
105
107
  def comments
106
108
  [Comment.new(self), Comment.new(self)]
107
109
  end
@@ -110,22 +112,28 @@ class Article
110
112
  Comment
111
113
  end
112
114
 
113
- def method_missing(method, *args, &block)
114
- super(method, *args, &block)
115
+ attr_accessor :status
116
+
117
+ def method_with_kwargs(a_keyword: false)
118
+ a_keyword
119
+ end
120
+
121
+ def method_missing(method, *args, **kwargs, &block)
122
+ super
115
123
  end
116
124
  end
117
125
 
118
126
  class Comment
119
127
  attr_reader :article
120
-
128
+
121
129
  def initialize(article)
122
130
  @article = article
123
131
  end
124
-
132
+
125
133
  def text
126
134
  "comment #{object_id}"
127
135
  end
128
-
136
+
129
137
  def to_jail
130
138
  Comment::Jail.new self
131
139
  end
@@ -144,8 +152,8 @@ class Comment
144
152
  end
145
153
 
146
154
  class Article::Jail < Safemode::Jail
147
- allow :title, :comments, :is_article?, :comment_class
148
-
155
+ allow :title, :comments, :is_article?, :comment_class, :method_with_kwargs, :status
156
+
149
157
  def author_name
150
158
  "this article's author name"
151
159
  end
@@ -155,6 +163,21 @@ class Article::ExtendedJail < Article::Jail
155
163
  end
156
164
 
157
165
  class Comment::Jail < Safemode::Jail
158
- allow :article, :text
166
+ allow :article, :text, :object_id
159
167
  allow_class_method :all
160
168
  end
169
+
170
+ class ExtendedComment < Comment
171
+ def extended_text
172
+ "extended comment #{object_id}"
173
+ end
174
+
175
+ def to_jail
176
+ ExtendedComment::Jail.new self
177
+ end
178
+
179
+ class Jail < Comment::Jail
180
+ allow :extended_text
181
+ end
182
+ end
183
+
data/test/test_jail.rb CHANGED
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require File.join(File.dirname(__FILE__), 'test_helper')
2
4
 
3
5
  class TestJail < Test::Unit::TestCase
@@ -5,6 +7,7 @@ class TestJail < Test::Unit::TestCase
5
7
  @article = Article.new.to_jail
6
8
  @comment = @article.comments.first
7
9
  @comment_class = Comment.to_jail
10
+ @extended_comment = ExtendedComment.new(@article).to_jail
8
11
  end
9
12
 
10
13
  def test_explicitly_allowed_instance_methods_should_be_accessible
@@ -23,9 +26,18 @@ class TestJail < Test::Unit::TestCase
23
26
  assert_equal "Article::Jail", @article.class.name
24
27
  end
25
28
 
29
+ def test_sending_of_kwargs_works
30
+ assert @article.method_with_kwargs(a_keyword: true)
31
+ end
32
+
33
+ def test_sending_to_method_missing
34
+ assert_raise_with_message(Safemode::NoMethodError, /#no_such_method/) do
35
+ @article.no_such_method('arg', key: 'value')
36
+ end
37
+ end
38
+
26
39
  def test_jail_instances_should_have_limited_methods
27
- expected = ["class", "method_missing", "methods", "respond_to?", "respond_to_missing?", "to_jail", "to_s", "instance_variable_get"]
28
- expected.delete('respond_to_missing?') if RUBY_VERSION > '1.9.3' # respond_to_missing? is private in rubies above 1.9.3
40
+ expected = ["class", "method_missing", "methods", "respond_to?", "to_jail", "to_s"]
29
41
  objects.each do |object|
30
42
  assert_equal expected.sort, reject_pretty_methods(object.to_jail.methods.map(&:to_s).sort)
31
43
  end
@@ -37,8 +49,13 @@ class TestJail < Test::Unit::TestCase
37
49
  "allow_instance_method", "allow_class_method", "allowed_instance_method?",
38
50
  "allowed_class_method?", "allowed_instance_methods", "allowed_class_methods",
39
51
  "<", # < needed in Rails Object#subclasses_of
40
- "ancestors", "==" # ancestors and == needed in Rails::Generator::Spec#lookup_class
41
- ]
52
+ "ancestors", "==", # ancestors and == needed in Rails::Generator::Spec#lookup_class
53
+ "singleton_class?" ]
54
+
55
+ if defined?(JRUBY_VERSION)
56
+ (expected << ['method_missing', 'singleton_method_undefined', 'singleton_method_added']).flatten! # needed for running under jruby
57
+ end
58
+
42
59
  objects.each do |object|
43
60
  assert_equal expected.sort, reject_pretty_methods(object.to_jail.class.methods.map(&:to_s).sort)
44
61
  end
@@ -53,6 +70,14 @@ class TestJail < Test::Unit::TestCase
53
70
  assert !@article.respond_to?(:bogus)
54
71
  end
55
72
 
73
+ def test_methodcall_comment
74
+ assert_equal "comment #{@comment.object_id}", @comment.text
75
+ end
76
+
77
+ def test_methodcall_extended_comment
78
+ assert_equal "extended comment #{@extended_comment.object_id}", @extended_comment.extended_text
79
+ end
80
+
56
81
  private
57
82
 
58
83
  def objects
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+ require_relative 'test_helper'
3
+
4
+ class TestParserNodeAllowlist < Test::Unit::TestCase
5
+ def test_new_dependency_node_handlers_are_not_implicitly_trusted
6
+ parser = Class.new(Safemode::Parser) do
7
+ def process_unreviewed_node(exp)
8
+ '42'
9
+ end
10
+ end
11
+ assert_raise(Safemode::SecurityError) { parser.new.process(Sexp.new(:unreviewed_node)) }
12
+ end
13
+ end
@@ -1,8 +1,10 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require File.join(File.dirname(__FILE__), 'test_helper')
2
4
 
3
5
  class TestSafemodeEval < Test::Unit::TestCase
4
6
  include TestHelper
5
-
7
+
6
8
  def setup
7
9
  @box = Safemode::Box.new
8
10
  @locals = { :article => Article.new }
@@ -17,15 +19,15 @@ class TestSafemodeEval < Test::Unit::TestCase
17
19
  end
18
20
  end
19
21
 
22
+ def test_safe_navigation_operator
23
+ assert_equal "1", @box.eval('x = 1; x&.to_s')
24
+ end
25
+
20
26
  def test_unary_operators_on_instances_of_boolean_vars
21
- if RUBY_VERSION != "1.8.7"
22
- assert @box.eval('not false')
23
- assert @box.eval('!false')
24
- assert !@box.eval('not true')
25
- assert !@box.eval('!true')
26
- else
27
- p "no unary ops under 1.8.7!"
28
- end
27
+ assert @box.eval('not false')
28
+ assert @box.eval('!false')
29
+ assert !@box.eval('not true')
30
+ assert !@box.eval('!true')
29
31
  end
30
32
 
31
33
  def test_false_class_ops
@@ -55,51 +57,210 @@ class TestSafemodeEval < Test::Unit::TestCase
55
57
  def test_should_turn_assigns_to_jails
56
58
  assert_raise_no_method "@article.system", @assigns
57
59
  end
58
-
60
+
59
61
  def test_should_turn_locals_to_jails
60
62
  assert_raise(Safemode::NoMethodError){ @box.eval "article.system", {}, @locals }
61
63
  end
62
-
64
+
63
65
  def test_should_allow_method_access_on_assigns
64
66
  assert_nothing_raised{ @box.eval "@article.title", @assigns }
65
67
  end
66
-
68
+
67
69
  def test_should_allow_method_access_on_locals
68
70
  assert_nothing_raised{ @box.eval("article.title", {}, @locals) }
69
71
  end
70
-
72
+
71
73
  def test_should_not_raise_on_if_using_return_values
72
74
  assert_nothing_raised{ @box.eval "if @article.is_article? then 1 end", @assigns }
73
75
  end
74
-
76
+
75
77
  def test_should_work_with_if_using_return_values
76
78
  assert_equal @box.eval("if @article.is_article? then 1 end", @assigns), 1
77
79
  end
78
-
80
+
79
81
  def test__FILE__should_not_render_filename
80
82
  assert_equal '(string)', @box.eval("__FILE__")
81
83
  end
82
-
84
+
83
85
  def test_interpolated_xstr_should_raise_security
84
86
  assert_raise_security '"#{`ls -a`}"'
85
- end
86
-
87
+ end
88
+
89
+ def test_should_not_allow_access_to_bind
90
+ assert_raise_security "self.bind('an arg')"
91
+ end
92
+
93
+ def test_sending_of_kwargs_works
94
+ assert @box.eval("@article.method_with_kwargs(a_keyword: true)", @assigns)
95
+ end
96
+
97
+ def test_pattern_matching_with_literal
98
+ assert_equal "matched", @box.eval('case 1; in 1; "matched"; in 2; "nope"; end')
99
+ end
100
+
101
+ def test_pattern_matching_with_array_destructuring
102
+ assert_equal 1, @box.eval('case [1, 2, 3]; in [a, b, c]; a; end')
103
+ end
104
+
105
+ def test_pattern_matching_with_hash_destructuring
106
+ assert_equal 1, @box.eval('case({a: 1, b: 2}); in {a:}; a; end')
107
+ end
108
+
109
+ def test_pattern_matching_with_assign
110
+ assert_equal "two", @box.eval('case @val; in 1; "one"; in 2; "two"; end', { val: 2 })
111
+ end
112
+
113
+ def test_pattern_matching_with_find_pattern
114
+ assert_equal "found", @box.eval('case [1, 2, 3]; in [*, 2, *]; "found"; end')
115
+ end
116
+
117
+ def test_pattern_matching_with_pin_operator
118
+ assert_equal "matched", @box.eval('y = 1; case 1; in ^y; "matched"; end')
119
+ end
120
+
121
+ def test_pattern_matching_with_multiple_clauses
122
+ assert_equal "second", @box.eval('case [3, 4]; in [1, 2]; "first"; in [3, 4]; "second"; end')
123
+ end
124
+
125
+ def test_pattern_matching_no_match_returns_nil
126
+ assert_nil @box.eval('case 3; in 1; "one"; in 2; "two"; else; nil; end')
127
+ end
128
+
129
+ def test_pattern_matching_with_if_guard
130
+ assert_equal "positive", @box.eval('case 1; in x if x > 0; "positive"; end')
131
+ end
132
+
133
+ def test_pattern_matching_with_unless_guard
134
+ assert_equal "not negative", @box.eval('case 1; in x unless x < 0; "not negative"; end')
135
+ end
136
+
137
+ def test_pattern_matching_guard_no_match
138
+ assert_nil @box.eval('case 1; in x if x < 0; "negative"; else; nil; end')
139
+ end
140
+
141
+ def test_pattern_matching_guard_with_array_pattern
142
+ assert_equal "yes", @box.eval('case [1, 2]; in [a, b] if a > 0; "yes"; end')
143
+ end
144
+
145
+ def test_pattern_matching_guard_with_hash_pattern
146
+ assert_equal "alice", @box.eval('case({name: "alice"}); in {name:} if name.start_with?("a"); name; end')
147
+ end
148
+
149
+ def test_rightward_assignment
150
+ assert_equal 1, @box.eval('[1, 2] => [a, b]; a')
151
+ end
152
+
153
+ def test_pattern_matching_with_jailed_hash
154
+ assert_equal "an article title", @box.eval('case @data; in {title:}; title; end', { data: { title: "an article title" } })
155
+ end
156
+
157
+ def test_hash_shorthand
158
+ # TODO: Remove the check once Ruby 3.1 is the minimum
159
+ if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('3.1')
160
+ assert_equal({ a: 1, b: 2 }, @box.eval('a = 1; b = 2; { a:, b: }'))
161
+ end
162
+ end
163
+
164
+ def test_endless_range
165
+ assert_equal [3, 4, 5], @box.eval('[1,2,3,4,5][2..]')
166
+ end
167
+
168
+ def test_beginless_range
169
+ assert_equal [1, 2, 3], @box.eval('[1,2,3,4,5][..2]')
170
+ end
171
+
172
+ # attrasgn (@article.status = val) is blocked at parse time
173
+ def test_attrasgn_is_blocked
174
+ assert_raise(Safemode::SecurityError) { @box.eval('@article.status = "new_value"', @assigns) }
175
+ end
176
+
177
+ def test_safe_attrasgn_is_blocked
178
+ assert_raise(Safemode::SecurityError) { @box.eval('@article&.status = "new_value"', @assigns) }
179
+ end
180
+
181
+ # op_asgn2 (@article.status ||= val) is NOT blocked at parse time.
182
+ # NOTE: .to_jail is not inserted on the receiver, so the setter is called
183
+ # directly on the real object, bypassing the Jail whitelist.
184
+ def test_op_asgn2_bypasses_jail
185
+ article = Article.new
186
+ assert_nil article.status
187
+ @box.eval('@article.status ||= "new_value"', { article: article })
188
+ assert_equal "new_value", article.status
189
+ end
190
+
191
+ def test_safe_op_asgn2_bypasses_jail
192
+ article = Article.new
193
+ assert_nil article.status
194
+ @box.eval('@article&.status ||= "new_value"', { article: article })
195
+ assert_equal "new_value", article.status
196
+ end
197
+
198
+ def test_instance_variable_get_blocked_on_jail
199
+ assert_raise(Safemode::NoMethodError) do
200
+ @box.eval('@article.instance_variable_get(:@source)', @assigns)
201
+ end
202
+ end
203
+
204
+ def test_freeze_on_jailed_object_is_blocked
205
+ string = String.new('host value')
206
+ assert_raise(Safemode::NoMethodError) { @box.eval('@value.freeze', value: string) }
207
+ assert_false string.frozen?
208
+ assert_raise(Safemode::NoMethodError) do
209
+ @box.eval('@arr.freeze', { arr: [1, 2, 3] })
210
+ end
211
+ end
212
+
213
+ def test_freeze_on_literal_strings_supports_erb
214
+ assert_predicate @box.eval('"literal".freeze'), :frozen?
215
+ assert_equal 'Hello world', @box.eval(ERB.new('Hello <%= @name %>').src, name: 'world')
216
+ end
217
+
218
+ def test_lambda_is_blocked
219
+ assert_raise(Safemode::SecurityError) { @box.eval('-> { 1 }') }
220
+ end
221
+
222
+ def test_sending_to_method_missing
223
+ assert_raise_with_message(Safemode::NoMethodError, /#no_such_method/) do
224
+ @box.eval("@article.no_such_method('arg', key: 'value')", @assigns)
225
+ end
226
+ end
227
+
228
+ if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('3.2')
229
+ def test_pattern_matching_with_data_subclass
230
+ point_class = Data.define(:x, :y)
231
+ point = point_class.new(x: 10, y: 20)
232
+ assert_equal 10, @box.eval('case @point; in {x:}; x; end', { point: point })
233
+ end
234
+
235
+ def test_data_subclass_inherits_data_jail
236
+ point_class = Data.define(:x, :y)
237
+ point = point_class.new(x: 10, y: 20)
238
+ assert_equal [:x, :y], @box.eval('@point.members', { point: point })
239
+ assert_equal [10, 20], @box.eval('@point.deconstruct', { point: point })
240
+ assert_equal({ x: 10 }, @box.eval('@point.deconstruct_keys([:x])', { point: point }))
241
+ end
242
+
243
+ def test_data_subclass_jail_blocks_non_whitelisted_methods
244
+ point_class = Data.define(:x, :y)
245
+ point = point_class.new(x: 10, y: 20)
246
+ assert_raise(Safemode::NoMethodError) { @box.eval('@point.instance_variables', { point: point }) }
247
+ end
248
+ end
249
+
87
250
  TestHelper.no_method_error_raising_calls.each do |call|
88
- call.gsub!('"', '\\\\"')
89
251
  class_eval %Q(
90
252
  def test_calling_#{call.gsub(/[\W]/, '_')}_should_raise_no_method
91
- assert_raise_no_method "#{call}", @assigns, @locals
253
+ assert_raise_no_method "#{call.gsub('"', '\\\\"')}", @assigns, @locals
92
254
  end
93
255
  )
94
256
  end
95
257
 
96
258
  TestHelper.security_error_raising_calls.each do |call|
97
- call.gsub!('"', '\\\\"')
98
259
  class_eval %Q(
99
260
  def test_calling_#{call.gsub(/[\W]/, '_')}_should_raise_security
100
- assert_raise_security "#{call}", @assigns, @locals
261
+ assert_raise_security "#{call.gsub('"', '\\\\"')}", @assigns, @locals
101
262
  end
102
263
  )
103
- end
264
+ end
104
265
 
105
266
  end