Skip to content

Commit b4429d1

Browse files
committed
Handle unbalanced quotes in environment field
Shellwords.split raises ArgumentError on malformed input (e.g. an unbalanced quote like FOO="bar). Since build_rake_command runs in the request thread before the fork, an unhandled raise surfaced as a 500. Rescue the ArgumentError and treat malformed input as no usable env tokens, then add a test covering the case.
1 parent 8f44fd0 commit b4429d1

2 files changed

Lines changed: 26 additions & 1 deletion

File tree

app/models/rake_ui/rake_task.rb

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,17 @@ def build_rake_command(args: nil, environment: nil)
115115
if environment
116116
# Safely escape environment variables to prevent shell injection
117117
# Only accept KEY=VALUE pairs; reject malicious tokens
118-
escaped_env = Shellwords.split(environment).map do |token|
118+
#
119+
# Shellwords.split raises ArgumentError on malformed input (e.g. an
120+
# unbalanced quote like FOO="bar). Treat that as no usable env tokens
121+
# rather than letting the exception bubble up as a 500.
122+
tokens = begin
123+
Shellwords.split(environment)
124+
rescue ArgumentError
125+
[]
126+
end
127+
128+
escaped_env = tokens.map do |token|
119129
next unless token.match?(/\A[A-Z_][A-Z0-9_]*=.+\z/i)
120130

121131
# Valid KEY=VALUE pattern - escape only the value

test/rake_ui/rake_task_test.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,21 @@ class RakeTaskTest < ActiveSupport::TestCase
4949
assert_includes command, "rake", "Should include rake command"
5050
end
5151

52+
test "does not raise when environment contains an unbalanced quote" do
53+
task = get_double_nested_task
54+
55+
# Shellwords.split raises ArgumentError on unbalanced quotes; this is called
56+
# in the request thread before the fork, so an unhandled raise would 500.
57+
unbalanced = 'FOO="bar'
58+
command = nil
59+
assert_nothing_raised do
60+
command = task.build_rake_command(environment: unbalanced)
61+
end
62+
63+
# Malformed env is dropped; the rake command is still produced.
64+
assert_equal "rake #{task.name}", command
65+
end
66+
5267
test "escapes special shell characters in args" do
5368
task = get_double_nested_task
5469

0 commit comments

Comments
 (0)