Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion lib/hammer_cli/utils.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
require 'highline'
require 'shellwords'
require 'tempfile'

class String
Expand Down Expand Up @@ -91,7 +92,8 @@ def self.open_in_editor(content, content_type: '', tempdir: '/tmp', suffix: '.tm
Tempfile.open([content_type, suffix], tempdir) do |f|
f.write(content)
f.rewind
system("#{ENV['EDITOR'] || 'vi'} #{f.path}")
editor = Shellwords.split(ENV['EDITOR'] || 'vi')
system(*editor, f.path)
result = f.read
end
result
Expand Down
2 changes: 1 addition & 1 deletion lib/hammer_cli/version.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
module HammerCLI
def self.version
@version ||= Gem::Version.new "5.0.0"
@version ||= Gem::Version.new "5.0.1"
end
end
35 changes: 35 additions & 0 deletions test/unit/utils_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -195,4 +195,39 @@ class X
assert_equal(arr, [:a, 1, 2, 3, :b, :c])
end
end

describe 'open_in_editor' do
it 'uses array-based system call to prevent shell injection' do
ENV.stubs(:[]).with('EDITOR').returns('vi')
HammerCLI.expects(:system).with('vi', anything).once.returns(true)
HammerCLI.open_in_editor('test content')
end

it 'splits EDITOR with arguments into array form' do
ENV.stubs(:[]).with('EDITOR').returns('code --wait')
HammerCLI.expects(:system).with('code', '--wait', anything).once.returns(true)
HammerCLI.open_in_editor('test content')
end

it 'falls back to vi when EDITOR is not set' do
ENV.stubs(:[]).with('EDITOR').returns(nil)
HammerCLI.expects(:system).with('vi', anything).once.returns(true)
HammerCLI.open_in_editor('test content')
end

it 'does not pass shell metacharacters to a shell interpreter' do
ENV.stubs(:[]).with('EDITOR').returns('vi; echo INJECTED')
# Shellwords.split treats the semicolon as a literal character,
# producing ["vi;", "echo", "INJECTED"] - no shell is invoked
HammerCLI.expects(:system).with('vi;', 'echo', 'INJECTED', anything).once.returns(true)
HammerCLI.open_in_editor('test content')
end

it 'returns original content when editor does not modify the file' do
ENV.stubs(:[]).with('EDITOR').returns('true')
HammerCLI.stubs(:system).returns(true)
result = HammerCLI.open_in_editor('original content')
assert_equal 'original content', result
end
end
end
Loading