1
0
Fork 0
mirror of https://github.com/ruby/ruby.git synced 2022-11-09 12:17:21 -05:00

Merge RubyGems upstream: 56c0bbb69e4506bda7ef7f447dfec5db820df20b

It fixed the multiple vulnerabilities.
  https://blog.rubygems.org/2019/03/05/security-advisories-2019-03.html

git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@67168 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
This commit is contained in:
hsbt 2019-03-05 03:32:58 +00:00
parent 593505ac6f
commit 08f8cfe14e
29 changed files with 653 additions and 183 deletions

View file

@ -7,6 +7,7 @@
require 'rubygems/command' require 'rubygems/command'
require 'rubygems/user_interaction' require 'rubygems/user_interaction'
require 'rubygems/text'
## ##
# The command manager registers and installs all the individual sub-commands # The command manager registers and installs all the individual sub-commands
@ -32,6 +33,7 @@ require 'rubygems/user_interaction'
class Gem::CommandManager class Gem::CommandManager
include Gem::Text
include Gem::UserInteraction include Gem::UserInteraction
BUILTIN_COMMANDS = [ # :nodoc: BUILTIN_COMMANDS = [ # :nodoc:
@ -145,12 +147,12 @@ class Gem::CommandManager
def run(args, build_args=nil) def run(args, build_args=nil)
process_args(args, build_args) process_args(args, build_args)
rescue StandardError, Timeout::Error => ex rescue StandardError, Timeout::Error => ex
alert_error "While executing gem ... (#{ex.class})\n #{ex}" alert_error clean_text("While executing gem ... (#{ex.class})\n #{ex}")
ui.backtrace ex ui.backtrace ex
terminate_interaction(1) terminate_interaction(1)
rescue Interrupt rescue Interrupt
alert_error "Interrupted" alert_error clean_text("Interrupted")
terminate_interaction(1) terminate_interaction(1)
end end
@ -167,8 +169,14 @@ class Gem::CommandManager
when '-v', '--version' then when '-v', '--version' then
say Gem::VERSION say Gem::VERSION
terminate_interaction 0 terminate_interaction 0
when '--no-ri', '--no-rdoc' then
# This was added to compensate for a deprecation warning not being shown
# in Rubygems 2.x.x.
# TODO: Remove when Rubygems 3.1 is released.
alert_error "Invalid option: #{args.first}. Use --no-document instead."
terminate_interaction 1
when /^-/ then when /^-/ then
alert_error "Invalid option: #{args.first}. See 'gem --help'." alert_error clean_text("Invalid option: #{args.first}. See 'gem --help'.")
terminate_interaction 1 terminate_interaction 1
else else
cmd_name = args.shift.downcase cmd_name = args.shift.downcase
@ -224,7 +232,7 @@ class Gem::CommandManager
rescue Exception => e rescue Exception => e
e = load_error if load_error e = load_error if load_error
alert_error "Loading command: #{command_name} (#{e.class})\n\t#{e}" alert_error clean_text("Loading command: #{command_name} (#{e.class})\n\t#{e}")
ui.backtrace e ui.backtrace e
end end
end end

View file

@ -194,65 +194,21 @@ You can use `i` command instead of `install`.
req = Gem::Requirement.create(version) req = Gem::Requirement.create(version)
if options[:ignore_dependencies] dinst = Gem::DependencyInstaller.new options
install_gem_without_dependencies name, req
else request_set = dinst.resolve_dependencies name, req
inst = Gem::DependencyInstaller.new options
request_set = inst.resolve_dependencies name, req
if options[:explain] if options[:explain]
say "Gems to install:" say "Gems to install:"
request_set.sorted_requests.each do |s| request_set.sorted_requests.each do |activation_request|
# shows platform specific gems if used say " #{activation_request.full_name}"
say (plat = s.spec.platform) == Gem::Platform::RUBY ?
" #{s.full_name}" :
" #{s.full_name}-#{plat}"
end end
return
else else
@installed_specs.concat request_set.install options @installed_specs.concat request_set.install options
end end
show_install_errors inst.errors show_install_errors dinst.errors
end
end
def install_gem_without_dependencies(name, req) # :nodoc:
gem = nil
if local?
if name =~ /\.gem$/ and File.file? name
source = Gem::Source::SpecificFile.new name
spec = source.spec
else
source = Gem::Source::Local.new
spec = source.find_gem name, req
end
gem = source.download spec if spec
end
if remote? and not gem
dependency = Gem::Dependency.new name, req
dependency.prerelease = options[:prerelease]
fetcher = Gem::RemoteFetcher.fetcher
gem = fetcher.download_to_cache dependency
end
inst = Gem::Installer.at gem, options
inst.install
require 'rubygems/dependency_installer'
dinst = Gem::DependencyInstaller.new options
dinst.installed_gems.replace [inst.spec]
Gem.done_installing_hooks.each do |hook|
hook.call dinst, [inst.spec]
end unless Gem.done_installing_hooks.empty?
@installed_specs.push(inst.spec)
end end
def install_gems # :nodoc: def install_gems # :nodoc:

View file

@ -2,9 +2,11 @@
require 'rubygems/command' require 'rubygems/command'
require 'rubygems/local_remote_options' require 'rubygems/local_remote_options'
require 'rubygems/gemcutter_utilities' require 'rubygems/gemcutter_utilities'
require 'rubygems/text'
class Gem::Commands::OwnerCommand < Gem::Command class Gem::Commands::OwnerCommand < Gem::Command
include Gem::Text
include Gem::LocalRemoteOptions include Gem::LocalRemoteOptions
include Gem::GemcutterUtilities include Gem::GemcutterUtilities
@ -68,7 +70,7 @@ permission to.
end end
with_response response do |resp| with_response response do |resp|
owners = Gem::SafeYAML.load resp.body owners = Gem::SafeYAML.load clean_text(resp.body)
say "Owners for gem: #{name}" say "Owners for gem: #{name}"
owners.each do |owner| owners.each do |owner|
@ -89,11 +91,6 @@ permission to.
owners.each do |owner| owners.each do |owner|
begin begin
response = send_owner_request(method, name, owner) response = send_owner_request(method, name, owner)
if need_otp? response
response = send_owner_request(method, name, owner, true)
end
action = method == :delete ? "Removing" : "Adding" action = method == :delete ? "Removing" : "Adding"
with_response response, "#{action} #{owner}" with_response response, "#{action} #{owner}"
@ -105,11 +102,11 @@ permission to.
private private
def send_owner_request(method, name, owner, use_otp = false) def send_owner_request(method, name, owner)
rubygems_api_request method, "api/v1/gems/#{name}/owners" do |request| rubygems_api_request method, "api/v1/gems/#{name}/owners" do |request|
request.set_form_data 'email' => owner request.set_form_data 'email' => owner
request.add_field "Authorization", api_key request.add_field "Authorization", api_key
request.add_field "OTP", options[:otp] if use_otp request.add_field "OTP", options[:otp] if options[:otp]
end end
end end

View file

@ -119,22 +119,18 @@ You can upgrade or downgrade to the latest release version with:
response = send_push_request(name, args) response = send_push_request(name, args)
if need_otp? response
response = send_push_request(name, args, true)
end
with_response response with_response response
end end
private private
def send_push_request(name, args, use_otp = false) def send_push_request(name, args)
rubygems_api_request(*args) do |request| rubygems_api_request(*args) do |request|
request.body = Gem.read_binary name request.body = Gem.read_binary name
request.add_field "Content-Length", request.body.size request.add_field "Content-Length", request.body.size
request.add_field "Content-Type", "application/octet-stream" request.add_field "Content-Type", "application/octet-stream"
request.add_field "Authorization", api_key request.add_field "Authorization", api_key
request.add_field "OTP", options[:otp] if use_otp request.add_field "OTP", options[:otp] if options[:otp]
end end
end end

View file

@ -97,8 +97,8 @@ command to remove old versions.
if options[:explain] if options[:explain]
say "Gems to update:" say "Gems to update:"
gems_to_update.each do |(name, version)| gems_to_update.each do |name_tuple|
say " #{name}-#{version}" say " #{name_tuple.full_name}"
end end
return return
@ -146,18 +146,18 @@ command to remove old versions.
hig hig
end end
def highest_remote_version(spec) # :nodoc: def highest_remote_name_tuple(spec) # :nodoc:
spec_tuples = fetch_remote_gems spec spec_tuples = fetch_remote_gems spec
matching_gems = spec_tuples.select do |g,_| matching_gems = spec_tuples.select do |g,_|
g.name == spec.name and g.match_platform? g.name == spec.name and g.match_platform?
end end
highest_remote_gem = matching_gems.max_by { |g,_| g.version } highest_remote_gem = matching_gems.max
highest_remote_gem ||= [Gem::NameTuple.null] highest_remote_gem ||= [Gem::NameTuple.null]
highest_remote_gem.first.version highest_remote_gem.first
end end
def install_rubygems(version) # :nodoc: def install_rubygems(version) # :nodoc:
@ -194,7 +194,7 @@ command to remove old versions.
} }
gems_to_update = which_to_update hig, options[:args], :system gems_to_update = which_to_update hig, options[:args], :system
_, up_ver = gems_to_update.first up_ver = gems_to_update.first.version
target = if update_latest target = if update_latest
up_ver up_ver
@ -226,8 +226,8 @@ command to remove old versions.
end end
def update_gems(gems_to_update) def update_gems(gems_to_update)
gems_to_update.uniq.sort.each do |(name, version)| gems_to_update.uniq.sort.each do |name_tuple|
update_gem name, version update_gem name_tuple.name, name_tuple.version
end end
@updated @updated
@ -271,10 +271,12 @@ command to remove old versions.
next if not gem_names.empty? and next if not gem_names.empty? and
gem_names.none? { |name| name == l_spec.name } gem_names.none? { |name| name == l_spec.name }
highest_remote_ver = highest_remote_version l_spec highest_remote_tup = highest_remote_name_tuple l_spec
highest_remote_ver = highest_remote_tup.version
highest_installed_ver = l_spec.version
if system or (l_spec.version < highest_remote_ver) if system or (highest_installed_ver < highest_remote_ver)
result << [l_spec.name, [l_spec.version, highest_remote_ver].max] result << Gem::NameTuple.new(l_spec.name, [highest_installed_ver, highest_remote_ver].max, highest_remote_tup.platform)
end end
end end

View file

@ -33,6 +33,7 @@ data you will need to change them immediately and yank your gem.
add_version_option("remove") add_version_option("remove")
add_platform_option("remove") add_platform_option("remove")
add_otp_option
add_option('--host HOST', add_option('--host HOST',
'Yank from another gemcutter-compatible host', 'Yank from another gemcutter-compatible host',
@ -62,7 +63,10 @@ data you will need to change them immediately and yank your gem.
def yank_gem(version, platform) def yank_gem(version, platform)
say "Yanking gem from #{self.host}..." say "Yanking gem from #{self.host}..."
yank_api_request(:delete, version, platform, "api/v1/gems/yank") args = [:delete, version, platform, "api/v1/gems/yank"]
response = yank_api_request(*args)
say response.body
end end
private private
@ -71,6 +75,7 @@ data you will need to change them immediately and yank your gem.
name = get_one_gem_name name = get_one_gem_name
response = rubygems_api_request(method, api, host) do |request| response = rubygems_api_request(method, api, host) do |request|
request.add_field("Authorization", api_key) request.add_field("Authorization", api_key)
request.add_field("OTP", options[:otp]) if options[:otp]
data = { data = {
'gem_name' => name, 'gem_name' => name,
@ -80,7 +85,7 @@ data you will need to change them immediately and yank your gem.
request.set_form_data data request.set_form_data data
end end
say response.body response
end end
def get_version_from_requirements(requirements) def get_version_from_requirements(requirements)

View file

@ -135,7 +135,7 @@ class Gem::DependencyList
end end
## ##
# Is is ok to remove a gemspec from the dependency list? # It is ok to remove a gemspec from the dependency list?
# #
# If removing the gemspec creates breaks a currently ok dependency, then it # If removing the gemspec creates breaks a currently ok dependency, then it
# is NOT ok to remove the gemspec. # is NOT ok to remove the gemspec.

View file

@ -1,11 +1,14 @@
# frozen_string_literal: true # frozen_string_literal: true
require 'rubygems/remote_fetcher' require 'rubygems/remote_fetcher'
require 'rubygems/text'
## ##
# Utility methods for using the RubyGems API. # Utility methods for using the RubyGems API.
module Gem::GemcutterUtilities module Gem::GemcutterUtilities
include Gem::Text
# TODO: move to Gem::Command # TODO: move to Gem::Command
OptionParser.accept Symbol do |value| OptionParser.accept Symbol do |value|
value.to_sym value.to_sym
@ -94,8 +97,22 @@ module Gem::GemcutterUtilities
uri = URI.parse "#{self.host}/#{path}" uri = URI.parse "#{self.host}/#{path}"
request_method = Net::HTTP.const_get method.to_s.capitalize request_method = Net::HTTP.const_get method.to_s.capitalize
response = Gem::RemoteFetcher.fetcher.request(uri, request_method, &block)
return response unless mfa_unauthorized?(response)
Gem::RemoteFetcher.fetcher.request(uri, request_method, &block) Gem::RemoteFetcher.fetcher.request(uri, request_method) do |req|
req.add_field "OTP", get_otp
block.call(req)
end
end
def mfa_unauthorized?(response)
response.kind_of?(Net::HTTPUnauthorized) && response.body.start_with?('You have enabled multifactor authentication')
end
def get_otp
say 'You have enabled multi-factor authentication. Please enter OTP code.'
ask 'Code: '
end end
## ##
@ -123,13 +140,7 @@ module Gem::GemcutterUtilities
response = rubygems_api_request(:get, "api/v1/api_key", response = rubygems_api_request(:get, "api/v1/api_key",
sign_in_host) do |request| sign_in_host) do |request|
request.basic_auth email, password request.basic_auth email, password
end request.add_field "OTP", options[:otp] if options[:otp]
if need_otp? response
response = rubygems_api_request(:get, "api/v1/api_key", sign_in_host) do |request|
request.basic_auth email, password
request.add_field "OTP", options[:otp]
end
end end
with_response response do |resp| with_response response do |resp|
@ -164,30 +175,24 @@ module Gem::GemcutterUtilities
if block_given? if block_given?
yield response yield response
else else
say response.body say clean_text(response.body)
end end
else else
message = response.body message = response.body
message = "#{error_prefix}: #{message}" if error_prefix message = "#{error_prefix}: #{message}" if error_prefix
say message say clean_text(message)
terminate_interaction 1 # TODO: question this terminate_interaction 1 # TODO: question this
end end
end end
## ##
# Returns true when the user has enabled multifactor authentication from # Returns true when the user has enabled multifactor authentication from
# +response+ text. # +response+ text and no otp provided by options.
def need_otp?(response)
return unless response.kind_of?(Net::HTTPUnauthorized) &&
response.body.start_with?('You have enabled multifactor authentication')
return true if options[:otp]
say 'You have enabled multi-factor authentication. Please enter OTP code.'
options[:otp] = ask 'Code: '
true
end
def set_api_key(host, key) def set_api_key(host, key)
if host == Gem::DEFAULT_HOST if host == Gem::DEFAULT_HOST

View file

@ -729,11 +729,28 @@ class Gem::Installer
unpack or File.writable?(gem_home) unpack or File.writable?(gem_home)
end end
def verify_spec_name def verify_spec
return if spec.name =~ Gem::Specification::VALID_NAME_PATTERN unless spec.name =~ Gem::Specification::VALID_NAME_PATTERN
raise Gem::InstallError, "#{spec} has an invalid name" raise Gem::InstallError, "#{spec} has an invalid name"
end end
if spec.raw_require_paths.any?{|path| path =~ /\R/ }
raise Gem::InstallError, "#{spec} has an invalid require_paths"
end
if spec.extensions.any?{|ext| ext =~ /\R/ }
raise Gem::InstallError, "#{spec} has an invalid extensions"
end
unless spec.specification_version.to_s =~ /\A\d+\z/
raise Gem::InstallError, "#{spec} has an invalid specification_version"
end
if spec.dependencies.any? {|dep| dep.type =~ /\R/ || dep.name =~ /\R/ }
raise Gem::InstallError, "#{spec} has an invalid dependencies"
end
end
## ##
# Return the text for an application file. # Return the text for an application file.
@ -844,7 +861,7 @@ TEXT
# without the full gem installed. # without the full gem installed.
def extract_bin def extract_bin
@package.extract_files gem_dir, "bin/*" @package.extract_files gem_dir, "#{spec.bindir}/*"
end end
## ##
@ -880,9 +897,11 @@ TEXT
def pre_install_checks def pre_install_checks
verify_gem_home options[:unpack] verify_gem_home options[:unpack]
ensure_loadable_spec # The name and require_paths must be verified first, since it could contain
# ruby code that would be eval'ed in #ensure_loadable_spec
verify_spec
verify_spec_name ensure_loadable_spec
if options[:install_as_default] if options[:install_as_default]
Gem.ensure_default_gem_subdirectories gem_home Gem.ensure_default_gem_subdirectories gem_home

View file

@ -120,9 +120,9 @@ class Gem::InstallerTestCase < Gem::TestCase
# The executable is also written to the bin dir in @tmpdir and the installed # The executable is also written to the bin dir in @tmpdir and the installed
# gem directory for +spec+. # gem directory for +spec+.
def util_make_exec(spec = @spec, shebang = "#!/usr/bin/ruby") def util_make_exec(spec = @spec, shebang = "#!/usr/bin/ruby", bindir = "bin")
spec.executables = %w[executable] spec.executables = %w[executable]
spec.files << 'bin/executable' spec.bindir = bindir
exec_path = spec.bin_file "executable" exec_path = spec.bin_file "executable"
write_file exec_path do |io| write_file exec_path do |io|

View file

@ -459,6 +459,16 @@ EOM
raise Gem::Package::PathError.new(destination, destination_dir) unless raise Gem::Package::PathError.new(destination, destination_dir) unless
destination.start_with? destination_dir + '/' destination.start_with? destination_dir + '/'
begin
real_destination = File.expand_path(File.realpath(destination))
rescue
# it's fine if the destination doesn't exist, because rm -rf'ing it can't cause any damage
nil
else
raise Gem::Package::PathError.new(real_destination, destination_dir) unless
real_destination.start_with? destination_dir + '/'
end
destination.untaint destination.untaint
destination destination
end end

View file

@ -130,7 +130,6 @@ class Gem::Requirement
@requirements = [DefaultRequirement] @requirements = [DefaultRequirement]
else else
@requirements = requirements.map! { |r| self.class.parse r } @requirements = requirements.map! { |r| self.class.parse r }
sort_requirements!
end end
end end
@ -144,7 +143,6 @@ class Gem::Requirement
new = new.map { |r| self.class.parse r } new = new.map { |r| self.class.parse r }
@requirements.concat new @requirements.concat new
sort_requirements!
end end
## ##
@ -186,7 +184,7 @@ class Gem::Requirement
end end
def hash # :nodoc: def hash # :nodoc:
requirements.hash requirements.sort.hash
end end
def marshal_dump # :nodoc: def marshal_dump # :nodoc:
@ -295,14 +293,6 @@ class Gem::Requirement
end end
end end
def sort_requirements! # :nodoc:
@requirements.sort! do |l, r|
comp = l.last <=> r.last # first, sort by the requirement's version
next comp unless comp == 0
l.first <=> r.first # then, sort by the operator (for stability)
end
end
end end
class Gem::Version class Gem::Version

View file

@ -77,7 +77,7 @@ class Gem::Resolver::ActivationRequest
# The full name of the specification to be activated. # The full name of the specification to be activated.
def full_name def full_name
@spec.full_name name_tuple.full_name
end end
alias_method :to_s, :full_name alias_method :to_s, :full_name
@ -183,4 +183,17 @@ class Gem::Resolver::ActivationRequest
@spec.version @spec.version
end end
##
# The platform of this activation request's specification
def platform
@spec.platform
end
private
def name_tuple
@name_tuple ||= Gem::NameTuple.new(name, version, platform)
end
end end

View file

@ -134,6 +134,12 @@ class Gem::TestCase < (defined?(Minitest::Test) ? Minitest::Test : MiniTest::Uni
assert File.exist?(path), msg assert File.exist?(path), msg
end end
def assert_directory_exists(path, msg = nil)
msg = message(msg) { "Expected path '#{path}' to be a directory" }
assert_path_exists path
assert File.directory?(path), msg
end
## ##
# Sets the ENABLE_SHARED entry in RbConfig::CONFIG to +value+ and restores # Sets the ENABLE_SHARED entry in RbConfig::CONFIG to +value+ and restores
# the original value when the block ends # the original value when the block ends

View file

@ -13,6 +13,13 @@ require 'rubygems/remote_fetcher'
# @fetcher.data['http://gems.example.com/yaml'] = source_index.to_yaml # @fetcher.data['http://gems.example.com/yaml'] = source_index.to_yaml
# Gem::RemoteFetcher.fetcher = @fetcher # Gem::RemoteFetcher.fetcher = @fetcher
# #
# use nested array if multiple response is needed
#
# @fetcher.data['http://gems.example.com/sequence'] = [['Success', 200, 'OK'], ['Failed', 401, 'Unauthorized']]
#
# @fetcher.fetch_path('http://gems.example.com/sequence') # => ['Success', 200, 'OK']
# @fetcher.fetch_path('http://gems.example.com/sequence') # => ['Failed', 401, 'Unauthorized']
#
# # invoke RubyGems code # # invoke RubyGems code
# #
# paths = @fetcher.paths # paths = @fetcher.paths
@ -32,7 +39,7 @@ class Gem::FakeFetcher
@paths = [] @paths = []
end end
def find_data(path) def find_data(path, nargs = 3)
return File.read path.path if URI === path and 'file' == path.scheme return File.read path.path if URI === path and 'file' == path.scheme
if URI === path and "URI::#{path.scheme.upcase}" != path.class.name if URI === path and "URI::#{path.scheme.upcase}" != path.class.name
@ -48,7 +55,10 @@ class Gem::FakeFetcher
raise Gem::RemoteFetcher::FetchError.new("no data for #{path}", path) raise Gem::RemoteFetcher::FetchError.new("no data for #{path}", path)
end end
@data[path] data = @data[path]
data.flatten! and return data.shift(nargs) if data.respond_to?(:flatten!)
data
end end
def fetch_path(path, mtime = nil, head = false) def fetch_path(path, mtime = nil, head = false)
@ -60,7 +70,6 @@ class Gem::FakeFetcher
if path.to_s =~ /gz$/ and not data.nil? and not data.empty? if path.to_s =~ /gz$/ and not data.nil? and not data.empty?
data = Gem::Util.gunzip data data = Gem::Util.gunzip data
end end
data data
end end
end end

View file

@ -7,6 +7,7 @@
require 'rubygems/util' require 'rubygems/util'
require 'rubygems/deprecate' require 'rubygems/deprecate'
require 'rubygems/text'
## ##
# Module that defines the default UserInteraction. Any class including this # Module that defines the default UserInteraction. Any class including this
@ -14,6 +15,8 @@ require 'rubygems/deprecate'
module Gem::DefaultUserInteraction module Gem::DefaultUserInteraction
include Gem::Text
## ##
# The default UI is a class variable of the singleton class for this # The default UI is a class variable of the singleton class for this
# module. # module.
@ -162,7 +165,7 @@ module Gem::UserInteraction
# is true. # is true.
def verbose(msg = nil) def verbose(msg = nil)
say(msg || yield) if Gem.configuration.really_verbose say(clean_text(msg || yield)) if Gem.configuration.really_verbose
end end
end end

View file

@ -155,9 +155,11 @@ class TestGem < Gem::TestCase
def test_self_install_permissions_with_format_executable_and_non_standard_ruby_install_name def test_self_install_permissions_with_format_executable_and_non_standard_ruby_install_name
Gem::Installer.exec_format = nil Gem::Installer.exec_format = nil
with_clean_path_to_ruby do
ruby_install_name 'ruby27' do ruby_install_name 'ruby27' do
assert_self_install_permissions(format_executable: true) assert_self_install_permissions(format_executable: true)
end end
end
ensure ensure
Gem::Installer.exec_format = nil Gem::Installer.exec_format = nil
end end
@ -553,7 +555,7 @@ class TestGem < Gem::TestCase
Gem.ensure_gem_subdirectories @gemhome, 0750 Gem.ensure_gem_subdirectories @gemhome, 0750
assert File.directory? File.join(@gemhome, "cache") assert_directory_exists File.join(@gemhome, "cache")
assert_equal 0750, File::Stat.new(@gemhome).mode & 0777 assert_equal 0750, File::Stat.new(@gemhome).mode & 0777
assert_equal 0750, File::Stat.new(File.join(@gemhome, "cache")).mode & 0777 assert_equal 0750, File::Stat.new(File.join(@gemhome, "cache")).mode & 0777
@ -582,7 +584,7 @@ class TestGem < Gem::TestCase
Gem.ensure_gem_subdirectories gemdir Gem.ensure_gem_subdirectories gemdir
assert File.directory?(util_cache_dir) assert_directory_exists util_cache_dir
end end
unless win_platform? || Process.uid.zero? # only for FS that support write protection unless win_platform? || Process.uid.zero? # only for FS that support write protection
@ -952,40 +954,36 @@ class TestGem < Gem::TestCase
end end
def test_self_ruby_escaping_spaces_in_path def test_self_ruby_escaping_spaces_in_path
orig_ruby = Gem.ruby
orig_bindir = RbConfig::CONFIG['bindir'] orig_bindir = RbConfig::CONFIG['bindir']
orig_ruby_install_name = RbConfig::CONFIG['ruby_install_name']
orig_exe_ext = RbConfig::CONFIG['EXEEXT'] orig_exe_ext = RbConfig::CONFIG['EXEEXT']
RbConfig::CONFIG['bindir'] = "C:/Ruby 1.8/bin" RbConfig::CONFIG['bindir'] = "C:/Ruby 1.8/bin"
RbConfig::CONFIG['ruby_install_name'] = "ruby"
RbConfig::CONFIG['EXEEXT'] = ".exe" RbConfig::CONFIG['EXEEXT'] = ".exe"
Gem.instance_variable_set("@ruby", nil)
ruby_install_name "ruby" do
with_clean_path_to_ruby do
assert_equal "\"C:/Ruby 1.8/bin/ruby.exe\"", Gem.ruby assert_equal "\"C:/Ruby 1.8/bin/ruby.exe\"", Gem.ruby
end
end
ensure ensure
Gem.instance_variable_set("@ruby", orig_ruby)
RbConfig::CONFIG['bindir'] = orig_bindir RbConfig::CONFIG['bindir'] = orig_bindir
RbConfig::CONFIG['ruby_install_name'] = orig_ruby_install_name
RbConfig::CONFIG['EXEEXT'] = orig_exe_ext RbConfig::CONFIG['EXEEXT'] = orig_exe_ext
end end
def test_self_ruby_path_without_spaces def test_self_ruby_path_without_spaces
orig_ruby = Gem.ruby
orig_bindir = RbConfig::CONFIG['bindir'] orig_bindir = RbConfig::CONFIG['bindir']
orig_ruby_install_name = RbConfig::CONFIG['ruby_install_name']
orig_exe_ext = RbConfig::CONFIG['EXEEXT'] orig_exe_ext = RbConfig::CONFIG['EXEEXT']
RbConfig::CONFIG['bindir'] = "C:/Ruby18/bin" RbConfig::CONFIG['bindir'] = "C:/Ruby18/bin"
RbConfig::CONFIG['ruby_install_name'] = "ruby"
RbConfig::CONFIG['EXEEXT'] = ".exe" RbConfig::CONFIG['EXEEXT'] = ".exe"
Gem.instance_variable_set("@ruby", nil)
ruby_install_name "ruby" do
with_clean_path_to_ruby do
assert_equal "C:/Ruby18/bin/ruby.exe", Gem.ruby assert_equal "C:/Ruby18/bin/ruby.exe", Gem.ruby
end
end
ensure ensure
Gem.instance_variable_set("@ruby", orig_ruby)
RbConfig::CONFIG['bindir'] = orig_bindir RbConfig::CONFIG['bindir'] = orig_bindir
RbConfig::CONFIG['ruby_install_name'] = orig_ruby_install_name
RbConfig::CONFIG['EXEEXT'] = orig_exe_ext RbConfig::CONFIG['EXEEXT'] = orig_exe_ext
end end
@ -1904,6 +1902,16 @@ You may need to `gem install -g` to install missing gems
end end
end end
def with_clean_path_to_ruby
orig_ruby = Gem.ruby
Gem.instance_variable_set :@ruby, nil
yield
ensure
Gem.instance_variable_set("@ruby", orig_ruby)
end
def with_plugin(path) def with_plugin(path)
test_plugin_path = File.expand_path("test/rubygems/plugin/#{path}", test_plugin_path = File.expand_path("test/rubygems/plugin/#{path}",
@@project_dir) @@project_dir)

View file

@ -103,6 +103,16 @@ class TestGemCommandManager < Gem::TestCase
assert_match(/invalid option: --bad-arg/i, @ui.error) assert_match(/invalid option: --bad-arg/i, @ui.error)
end end
def test_process_args_bad_no_ri
use_ui @ui do
assert_raises Gem::MockGemUi::TermError do
@command_manager.process_args %w[--no-ri]
end
end
assert_match(/invalid option: --no-ri. Use --no-document instead./i, @ui.error)
end
# HACK move to install command test # HACK move to install command test
def test_process_args_install def test_process_args_install
#capture all install options #capture all install options

View file

@ -96,6 +96,64 @@ class TestGemCommandsInstallCommand < Gem::TestCase
assert_match "1 gem installed", @ui.output assert_match "1 gem installed", @ui.output
end end
def test_execute_local_dependency_nonexistent
specs = spec_fetcher do |fetcher|
fetcher.gem 'foo', 2, 'bar' => '0.5'
end
@cmd.options[:domain] = :local
FileUtils.mv specs['foo-2'].cache_file, @tempdir
@cmd.options[:args] = ['foo']
use_ui @ui do
orig_dir = Dir.pwd
begin
Dir.chdir @tempdir
e = assert_raises Gem::MockGemUi::TermError do
@cmd.execute
end
assert_equal 2, e.exit_code
ensure
Dir.chdir orig_dir
end
end
expected = <<-EXPECTED
ERROR: Could not find a valid gem 'bar' (= 0.5) (required by 'foo' (>= 0)) in any repository
EXPECTED
assert_equal expected, @ui.error
end
def test_execute_local_dependency_nonexistent_ignore_dependencies
specs = spec_fetcher do |fetcher|
fetcher.gem 'foo', 2, 'bar' => '0.5'
end
@cmd.options[:domain] = :local
@cmd.options[:ignore_dependencies] = true
FileUtils.mv specs['foo-2'].cache_file, @tempdir
@cmd.options[:args] = ['foo']
use_ui @ui do
orig_dir = Dir.pwd
begin
Dir.chdir orig_dir
assert_raises Gem::MockGemUi::SystemExitException, @ui.error do
@cmd.execute
end
ensure
Dir.chdir orig_dir
end
end
assert_match "1 gem installed", @ui.output
end
def test_execute_local_transitive_prerelease def test_execute_local_transitive_prerelease
specs = spec_fetcher do |fetcher| specs = spec_fetcher do |fetcher|
fetcher.download 'a', 2, 'b' => "2.a", 'c' => '3' fetcher.download 'a', 2, 'b' => "2.a", 'c' => '3'
@ -178,6 +236,25 @@ class TestGemCommandsInstallCommand < Gem::TestCase
assert_match(/ould not find a valid gem 'no_such_gem'/, @ui.error) assert_match(/ould not find a valid gem 'no_such_gem'/, @ui.error)
end end
def test_execute_local_missing_ignore_dependencies
spec_fetcher
@cmd.options[:domain] = :local
@cmd.options[:ignore_dependencies] = true
@cmd.options[:args] = %w[no_such_gem]
use_ui @ui do
e = assert_raises Gem::MockGemUi::TermError do
@cmd.execute
end
assert_equal 2, e.exit_code
end
# HACK no repository was checked
assert_match(/ould not find a valid gem 'no_such_gem'/, @ui.error)
end
def test_execute_no_gem def test_execute_no_gem
@cmd.options[:args] = %w[] @cmd.options[:args] = %w[]
@ -753,6 +830,23 @@ ERROR: Possible alternatives: non_existent_with_hint
assert_equal %w[a-2], @cmd.installed_specs.map { |spec| spec.full_name } assert_equal %w[a-2], @cmd.installed_specs.map { |spec| spec.full_name }
end end
def test_install_gem_ignore_dependencies_remote_platform_local
local = Gem::Platform.local
spec_fetcher do |fetcher|
fetcher.gem 'a', 3
fetcher.gem 'a', 3 do |s|
s.platform = local
end
end
@cmd.options[:ignore_dependencies] = true
@cmd.install_gem 'a', '>= 0'
assert_equal %W[a-3-#{local}], @cmd.installed_specs.map { |spec| spec.full_name }
end
def test_install_gem_ignore_dependencies_specific_file def test_install_gem_ignore_dependencies_specific_file
spec = util_spec 'a', 2 spec = util_spec 'a', 2
@ -1168,6 +1262,33 @@ ERROR: Possible alternatives: non_existent_with_hint
assert_empty out assert_empty out
end end
def test_explain_platform_local_ignore_dependencies
local = Gem::Platform.local
spec_fetcher do |fetcher|
fetcher.spec 'a', 3
fetcher.spec 'a', 3 do |s|
s.platform = local
end
end
@cmd.options[:ignore_dependencies] = true
@cmd.options[:explain] = true
@cmd.options[:args] = %w[a]
use_ui @ui do
assert_raises Gem::MockGemUi::SystemExitException, @ui.error do
@cmd.execute
end
end
out = @ui.output.split "\n"
assert_equal "Gems to install:", out.shift
assert_equal " a-3-#{local}", out.shift
assert_empty out
end
def test_explain_platform_ruby def test_explain_platform_ruby
local = Gem::Platform.local local = Gem::Platform.local
spec_fetcher do |fetcher| spec_fetcher do |fetcher|
@ -1197,4 +1318,34 @@ ERROR: Possible alternatives: non_existent_with_hint
assert_empty out assert_empty out
end end
def test_explain_platform_ruby_ignore_dependencies
local = Gem::Platform.local
spec_fetcher do |fetcher|
fetcher.spec 'a', 3
fetcher.spec 'a', 3 do |s|
s.platform = local
end
end
# equivalent to --platform=ruby
Gem.platforms = [Gem::Platform::RUBY]
@cmd.options[:ignore_dependencies] = true
@cmd.options[:explain] = true
@cmd.options[:args] = %w[a]
use_ui @ui do
assert_raises Gem::MockGemUi::SystemExitException, @ui.error do
@cmd.execute
end
end
out = @ui.output.split "\n"
assert_equal "Gems to install:", out.shift
assert_equal " a-3", out.shift
assert_empty out
end
end end

View file

@ -239,10 +239,10 @@ EOF
response_fail = "You have enabled multifactor authentication but your request doesn't have the correct OTP code. Please check it and retry." response_fail = "You have enabled multifactor authentication but your request doesn't have the correct OTP code. Please check it and retry."
response_success = "Owner added successfully." response_success = "Owner added successfully."
@stub_fetcher.data["#{Gem.host}/api/v1/gems/freewill/owners"] = proc do @stub_fetcher.data["#{Gem.host}/api/v1/gems/freewill/owners"] = [
@call_count ||= 0 [response_fail, 401, 'Unauthorized'],
(@call_count += 1).odd? ? [response_fail, 401, 'Unauthorized'] : [response_success, 200, 'OK'] [response_success, 200, 'OK']
end ]
@otp_ui = Gem::MockGemUi.new "111111\n" @otp_ui = Gem::MockGemUi.new "111111\n"
use_ui @otp_ui do use_ui @otp_ui do

View file

@ -372,10 +372,10 @@ class TestGemCommandsPushCommand < Gem::TestCase
response_fail = "You have enabled multifactor authentication but your request doesn't have the correct OTP code. Please check it and retry." response_fail = "You have enabled multifactor authentication but your request doesn't have the correct OTP code. Please check it and retry."
response_success = 'Successfully registered gem: freewill (1.0.0)' response_success = 'Successfully registered gem: freewill (1.0.0)'
@fetcher.data["#{Gem.host}/api/v1/gems"] = proc do @fetcher.data["#{Gem.host}/api/v1/gems"] = [
@call_count ||= 0 [response_fail, 401, 'Unauthorized'],
(@call_count += 1).odd? ? [response_fail, 401, 'Unauthorized'] : [response_success, 200, 'OK'] [response_success, 200, 'OK']
end ]
@otp_ui = Gem::MockGemUi.new "111111\n" @otp_ui = Gem::MockGemUi.new "111111\n"
use_ui @otp_ui do use_ui @otp_ui do

View file

@ -543,4 +543,59 @@ class TestGemCommandsUpdateCommand < Gem::TestCase
assert_empty out assert_empty out
end end
def test_explain_platform_local
local = Gem::Platform.local
spec_fetcher do |fetcher|
fetcher.download 'a', 2
fetcher.download 'a', 2 do |s|
s.platform = local
end
fetcher.spec 'a', 1
end
@cmd.options[:explain] = true
@cmd.options[:args] = %w[a]
use_ui @ui do
@cmd.execute
end
out = @ui.output.split "\n"
assert_equal "Gems to update:", out.shift
assert_equal " a-2-#{local}", out.shift
assert_empty out
end
def test_explain_platform_ruby
local = Gem::Platform.local
spec_fetcher do |fetcher|
fetcher.download 'a', 2
fetcher.download 'a', 2 do |s|
s.platform = local
end
fetcher.spec 'a', 1
end
# equivalent to --platform=ruby
Gem.platforms = [Gem::Platform::RUBY]
@cmd.options[:explain] = true
@cmd.options[:args] = %w[a]
use_ui @ui do
@cmd.execute
end
out = @ui.output.split "\n"
assert_equal "Gems to update:", out.shift
assert_equal " a-2", out.shift
assert_empty out
end
end end

View file

@ -49,6 +49,7 @@ class TestGemCommandsYankCommand < Gem::TestCase
assert_match %r%Yanking gem from http://example%, @ui.output assert_match %r%Yanking gem from http://example%, @ui.output
assert_match %r%Successfully yanked%, @ui.output assert_match %r%Successfully yanked%, @ui.output
platform = Gem.platforms[1] platform = Gem.platforms[1]
body = @fetcher.last_request.body.split('&').sort body = @fetcher.last_request.body.split('&').sort
assert_equal %W[gem_name=a platform=#{platform} version=1.0], body assert_equal %W[gem_name=a platform=#{platform} version=1.0], body
@ -58,6 +59,50 @@ class TestGemCommandsYankCommand < Gem::TestCase
assert_equal [yank_uri], @fetcher.paths assert_equal [yank_uri], @fetcher.paths
end end
def test_execute_with_otp_success
response_fail = 'You have enabled multifactor authentication but your request doesn\'t have the correct OTP code. Please check it and retry.'
yank_uri = 'http://example/api/v1/gems/yank'
@fetcher.data[yank_uri] = [
[response_fail, 401, 'Unauthorized'],
['Successfully yanked', 200, 'OK']
]
@cmd.options[:args] = %w[a]
@cmd.options[:added_platform] = true
@cmd.options[:version] = req('= 1.0')
@otp_ui = Gem::MockGemUi.new "111111\n"
use_ui @otp_ui do
@cmd.execute
end
assert_match 'You have enabled multi-factor authentication. Please enter OTP code.', @otp_ui.output
assert_match 'Code: ', @otp_ui.output
assert_match %r%Yanking gem from http://example%, @otp_ui.output
assert_match %r%Successfully yanked%, @otp_ui.output
assert_equal '111111', @fetcher.last_request['OTP']
end
def test_execute_with_otp_failure
response = 'You have enabled multifactor authentication but your request doesn\'t have the correct OTP code. Please check it and retry.'
yank_uri = 'http://example/api/v1/gems/yank'
@fetcher.data[yank_uri] = [response, 401, 'Unauthorized']
@cmd.options[:args] = %w[a]
@cmd.options[:added_platform] = true
@cmd.options[:version] = req('= 1.0')
@otp_ui = Gem::MockGemUi.new "111111\n"
use_ui @otp_ui do
@cmd.execute
end
assert_match 'You have enabled multi-factor authentication. Please enter OTP code.', @otp_ui.output
assert_match response, @otp_ui.output
assert_match 'Code: ', @otp_ui.output
assert_equal '111111', @fetcher.last_request['OTP']
end
def test_execute_key def test_execute_key
yank_uri = 'http://example/api/v1/gems/yank' yank_uri = 'http://example/api/v1/gems/yank'
@fetcher.data[yank_uri] = ['Successfully yanked', 200, 'OK'] @fetcher.data[yank_uri] = ['Successfully yanked', 200, 'OK']

View file

@ -103,8 +103,8 @@ class TestGemIndexer < Gem::TestCase
quickdir = File.join @tempdir, 'quick' quickdir = File.join @tempdir, 'quick'
marshal_quickdir = File.join quickdir, "Marshal.#{@marshal_version}" marshal_quickdir = File.join quickdir, "Marshal.#{@marshal_version}"
assert File.directory?(quickdir) assert_directory_exists quickdir
assert File.directory?(marshal_quickdir) assert_directory_exists marshal_quickdir
assert_indexed marshal_quickdir, "#{File.basename(@a1.spec_file)}.rz" assert_indexed marshal_quickdir, "#{File.basename(@a1.spec_file)}.rz"
assert_indexed marshal_quickdir, "#{File.basename(@a2.spec_file)}.rz" assert_indexed marshal_quickdir, "#{File.basename(@a2.spec_file)}.rz"
@ -133,8 +133,8 @@ class TestGemIndexer < Gem::TestCase
quickdir = File.join @tempdir, 'quick' quickdir = File.join @tempdir, 'quick'
marshal_quickdir = File.join quickdir, "Marshal.#{@marshal_version}" marshal_quickdir = File.join quickdir, "Marshal.#{@marshal_version}"
assert File.directory?(quickdir), 'quickdir should be directory' assert_directory_exists quickdir, 'quickdir should be directory'
assert File.directory?(marshal_quickdir) assert_directory_exists marshal_quickdir
refute_indexed quickdir, "index" refute_indexed quickdir, "index"
refute_indexed quickdir, "index.rz" refute_indexed quickdir, "index.rz"
@ -179,8 +179,8 @@ class TestGemIndexer < Gem::TestCase
quickdir = File.join @tempdir, 'quick' quickdir = File.join @tempdir, 'quick'
marshal_quickdir = File.join quickdir, "Marshal.#{@marshal_version}" marshal_quickdir = File.join quickdir, "Marshal.#{@marshal_version}"
assert File.directory?(quickdir) assert_directory_exists quickdir
assert File.directory?(marshal_quickdir) assert_directory_exists marshal_quickdir
assert_indexed marshal_quickdir, "#{File.basename(@a1.spec_file)}.rz" assert_indexed marshal_quickdir, "#{File.basename(@a1.spec_file)}.rz"
assert_indexed marshal_quickdir, "#{File.basename(@a2.spec_file)}.rz" assert_indexed marshal_quickdir, "#{File.basename(@a2.spec_file)}.rz"
@ -315,8 +315,8 @@ class TestGemIndexer < Gem::TestCase
quickdir = File.join @tempdir, 'quick' quickdir = File.join @tempdir, 'quick'
marshal_quickdir = File.join quickdir, "Marshal.#{@marshal_version}" marshal_quickdir = File.join quickdir, "Marshal.#{@marshal_version}"
assert File.directory?(quickdir) assert_directory_exists quickdir
assert File.directory?(marshal_quickdir) assert_directory_exists marshal_quickdir
@d2_1 = util_spec 'd', '2.1' @d2_1 = util_spec 'd', '2.1'
util_build_gem @d2_1 util_build_gem @d2_1

View file

@ -314,7 +314,7 @@ gem 'other', version
@installer.wrappers = true @installer.wrappers = true
@spec.executables = %w[executable] @spec.executables = %w[executable]
@spec.bindir = '.' @spec.bindir = 'bin'
exec_file = @installer.formatted_program_filename 'executable' exec_file = @installer.formatted_program_filename 'executable'
exec_path = File.join @spec.gem_dir, exec_file exec_path = File.join @spec.gem_dir, exec_file
@ -326,7 +326,7 @@ gem 'other', version
@installer.generate_bin @installer.generate_bin
assert_equal true, File.directory?(util_inst_bindir) assert_directory_exists (util_inst_bindir)
installed_exec = File.join(util_inst_bindir, 'executable') installed_exec = File.join(util_inst_bindir, 'executable')
assert_path_exists installed_exec assert_path_exists installed_exec
assert_equal mask, File.stat(installed_exec).mode unless win_platform? assert_equal mask, File.stat(installed_exec).mode unless win_platform?
@ -367,7 +367,7 @@ gem 'other', version
@installer.gem_dir = @spec.gem_dir @installer.gem_dir = @spec.gem_dir
@installer.generate_bin @installer.generate_bin
assert File.directory? util_inst_bindir assert_directory_exists util_inst_bindir
installed_exec = File.join util_inst_bindir, 'executable' installed_exec = File.join util_inst_bindir, 'executable'
assert_path_exists installed_exec assert_path_exists installed_exec
assert_equal mask, File.stat(installed_exec).mode unless win_platform? assert_equal mask, File.stat(installed_exec).mode unless win_platform?
@ -384,7 +384,7 @@ gem 'other', version
Gem::Installer.exec_format = 'foo-%s-bar' Gem::Installer.exec_format = 'foo-%s-bar'
@installer.generate_bin @installer.generate_bin
assert_equal true, File.directory?(util_inst_bindir) assert_directory_exists util_inst_bindir
installed_exec = File.join util_inst_bindir, 'foo-executable-bar' installed_exec = File.join util_inst_bindir, 'foo-executable-bar'
assert_path_exists installed_exec assert_path_exists installed_exec
ensure ensure
@ -398,7 +398,7 @@ gem 'other', version
Gem::Installer.exec_format = 'foo-%s-bar' Gem::Installer.exec_format = 'foo-%s-bar'
@installer.generate_bin @installer.generate_bin
assert_equal true, File.directory?(util_inst_bindir) assert_directory_exists util_inst_bindir
installed_exec = File.join util_inst_bindir, 'executable' installed_exec = File.join util_inst_bindir, 'executable'
assert_path_exists installed_exec assert_path_exists installed_exec
ensure ensure
@ -497,7 +497,7 @@ gem 'other', version
end end
@installer.generate_bin @installer.generate_bin
assert_equal true, File.directory?(util_inst_bindir) assert_directory_exists util_inst_bindir
assert_path_exists installed_exec assert_path_exists installed_exec
assert_equal mask, File.stat(installed_exec).mode unless win_platform? assert_equal mask, File.stat(installed_exec).mode unless win_platform?
@ -515,7 +515,7 @@ gem 'other', version
@installer.gem_dir = @spec.gem_dir @installer.gem_dir = @spec.gem_dir
@installer.generate_bin @installer.generate_bin
assert_equal true, File.directory?(util_inst_bindir) assert_directory_exists util_inst_bindir
installed_exec = File.join util_inst_bindir, 'executable' installed_exec = File.join util_inst_bindir, 'executable'
assert_equal true, File.symlink?(installed_exec) assert_equal true, File.symlink?(installed_exec)
assert_equal(File.join(@spec.gem_dir, 'bin', 'executable'), assert_equal(File.join(@spec.gem_dir, 'bin', 'executable'),
@ -667,7 +667,7 @@ gem 'other', version
@installer.generate_bin @installer.generate_bin
end end
assert_equal true, File.directory?(util_inst_bindir) assert_directory_exists util_inst_bindir
installed_exec = File.join(util_inst_bindir, 'executable') installed_exec = File.join(util_inst_bindir, 'executable')
assert_path_exists installed_exec assert_path_exists installed_exec
@ -984,16 +984,16 @@ gem 'other', version
def test_install_missing_dirs def test_install_missing_dirs
FileUtils.rm_f File.join(Gem.dir, 'cache') FileUtils.rm_f File.join(Gem.dir, 'cache')
FileUtils.rm_f File.join(Gem.dir, 'docs') FileUtils.rm_f File.join(Gem.dir, 'doc')
FileUtils.rm_f File.join(Gem.dir, 'specifications') FileUtils.rm_f File.join(Gem.dir, 'specifications')
use_ui @ui do use_ui @ui do
@installer.install @installer.install
end end
File.directory? File.join(Gem.dir, 'cache') assert_directory_exists File.join(Gem.dir, 'cache')
File.directory? File.join(Gem.dir, 'docs') assert_directory_exists File.join(Gem.dir, 'doc')
File.directory? File.join(Gem.dir, 'specifications') assert_directory_exists File.join(Gem.dir, 'specifications')
assert_path_exists File.join @gemhome, 'cache', @spec.file_name assert_path_exists File.join @gemhome, 'cache', @spec.file_name
assert_path_exists File.join @gemhome, 'specifications', @spec.spec_name assert_path_exists File.join @gemhome, 'specifications', @spec.spec_name
@ -1455,6 +1455,112 @@ gem 'other', version
end end
end end
def test_pre_install_checks_malicious_name_before_eval
spec = util_spec "malicious\n::Object.const_set(:FROM_EVAL, true)#", '1'
def spec.full_name # so the spec is buildable
"malicious-1"
end
def spec.validate(*args); end
util_build_gem spec
gem = File.join(@gemhome, 'cache', spec.file_name)
use_ui @ui do
@installer = Gem::Installer.at gem
e = assert_raises Gem::InstallError do
@installer.pre_install_checks
end
assert_equal "#<Gem::Specification name=malicious\n::Object.const_set(:FROM_EVAL, true)# version=1> has an invalid name", e.message
end
refute defined?(::Object::FROM_EVAL)
end
def test_pre_install_checks_malicious_require_paths_before_eval
spec = util_spec "malicious", '1'
def spec.full_name # so the spec is buildable
"malicious-1"
end
def spec.validate(*args); end
spec.require_paths = ["malicious\n``"]
util_build_gem spec
gem = File.join(@gemhome, 'cache', spec.file_name)
use_ui @ui do
@installer = Gem::Installer.at gem
e = assert_raises Gem::InstallError do
@installer.pre_install_checks
end
assert_equal "#<Gem::Specification name=malicious version=1> has an invalid require_paths", e.message
end
end
def test_pre_install_checks_malicious_extensions_before_eval
spec = util_spec "malicious", '1'
def spec.full_name # so the spec is buildable
"malicious-1"
end
def spec.validate(*args); end
spec.extensions = ["malicious\n``"]
util_build_gem spec
gem = File.join(@gemhome, 'cache', spec.file_name)
use_ui @ui do
@installer = Gem::Installer.at gem
e = assert_raises Gem::InstallError do
@installer.pre_install_checks
end
assert_equal "#<Gem::Specification name=malicious version=1> has an invalid extensions", e.message
end
end
def test_pre_install_checks_malicious_specification_version_before_eval
spec = util_spec "malicious", '1'
def spec.full_name # so the spec is buildable
"malicious-1"
end
def spec.validate(*args); end
spec.specification_version = "malicious\n``"
util_build_gem spec
gem = File.join(@gemhome, 'cache', spec.file_name)
use_ui @ui do
@installer = Gem::Installer.at gem
e = assert_raises Gem::InstallError do
@installer.pre_install_checks
end
assert_equal "#<Gem::Specification name=malicious version=1> has an invalid specification_version", e.message
end
end
def test_pre_install_checks_malicious_dependencies_before_eval
spec = util_spec "malicious", '1'
def spec.full_name # so the spec is buildable
"malicious-1"
end
def spec.validate(*args); end
spec.add_dependency "b\nfoo", '> 5'
util_build_gem spec
gem = File.join(@gemhome, 'cache', spec.file_name)
use_ui @ui do
@installer = Gem::Installer.at gem
@installer.ignore_dependencies = true
e = assert_raises Gem::InstallError do
@installer.pre_install_checks
end
assert_equal "#<Gem::Specification name=malicious version=1> has an invalid dependencies", e.message
end
end
def test_shebang def test_shebang
util_make_exec @spec, "#!/usr/bin/ruby" util_make_exec @spec, "#!/usr/bin/ruby"
@ -1727,24 +1833,55 @@ gem 'other', version
@installer.wrappers = true @installer.wrappers = true
@installer.options[:install_as_default] = true @installer.options[:install_as_default] = true
@installer.gem_dir = @spec.gem_dir @installer.gem_dir = @spec.gem_dir
@installer.generate_bin
use_ui @ui do use_ui @ui do
@installer.install @installer.install
end end
assert File.directory? util_inst_bindir assert_directory_exists File.join(@spec.gem_dir, 'bin')
installed_exec = File.join util_inst_bindir, 'executable' installed_exec = File.join @spec.gem_dir, 'bin', 'executable'
assert_path_exists installed_exec assert_path_exists installed_exec
assert File.directory? File.join(Gem.default_dir, 'specifications') assert_directory_exists File.join(Gem.default_dir, 'specifications')
assert File.directory? File.join(Gem.default_dir, 'specifications', 'default') assert_directory_exists File.join(Gem.default_dir, 'specifications', 'default')
default_spec = eval File.read File.join(Gem.default_dir, 'specifications', 'default', 'a-2.gemspec') default_spec = eval File.read File.join(Gem.default_dir, 'specifications', 'default', 'a-2.gemspec')
assert_equal Gem::Version.new("2"), default_spec.version assert_equal Gem::Version.new("2"), default_spec.version
assert_equal ['bin/executable'], default_spec.files assert_equal ['bin/executable'], default_spec.files
end end
def test_default_gem_with_exe_as_bindir
FileUtils.rm_f File.join(Gem.dir, 'specifications')
@spec = quick_gem 'c' do |spec|
util_make_exec spec, '#!/usr/bin/ruby', 'exe'
end
util_build_gem @spec
@spec.cache_file
installer = util_installer @spec, @gemhome
installer.options[:install_as_default] = true
installer.gem_dir = @spec.gem_dir
use_ui @ui do
installer.install
end
assert_directory_exists File.join(@spec.gem_dir, 'exe')
installed_exec = File.join @spec.gem_dir, 'exe', 'executable'
assert_path_exists installed_exec
assert_directory_exists File.join(Gem.default_dir, 'specifications')
assert_directory_exists File.join(Gem.default_dir, 'specifications', 'default')
default_spec = eval File.read File.join(Gem.default_dir, 'specifications', 'default', 'c-2.gemspec')
assert_equal Gem::Version.new("2"), default_spec.version
assert_equal ['exe/executable'], default_spec.files
end
def old_ruby_required(requirement) def old_ruby_required(requirement)
spec = util_spec 'old_ruby_required', '1' do |s| spec = util_spec 'old_ruby_required', '1' do |s|
s.required_ruby_version = requirement s.required_ruby_version = requirement

View file

@ -544,6 +544,40 @@ class TestGemPackage < Gem::Package::TarTestCase
end end
end end
def test_extract_symlink_parent_doesnt_delete_user_dir
package = Gem::Package.new @gem
# Extract into a subdirectory of @destination; if this test fails it writes
# a file outside destination_subdir, but we want the file to remain inside
# @destination so it will be cleaned up.
destination_subdir = File.join @destination, 'subdir'
FileUtils.mkdir_p destination_subdir
destination_user_dir = File.join @destination, 'user'
destination_user_subdir = File.join destination_user_dir, 'dir'
FileUtils.mkdir_p destination_user_subdir
tgz_io = util_tar_gz do |tar|
tar.add_symlink 'link', destination_user_dir, 16877
tar.add_symlink 'link/dir', '.', 16877
end
e = assert_raises(Gem::Package::PathError, Errno::EACCES) do
package.extract_tar_gz tgz_io, destination_subdir
end
assert_path_exists destination_user_subdir
if Gem::Package::PathError === e
assert_equal("installing into parent path #{destination_user_subdir} of " +
"#{destination_subdir} is not allowed", e.message)
elsif win_platform?
skip "symlink - must be admin with no UAC on Windows"
else
raise e
end
end
def test_extract_tar_gz_directory def test_extract_tar_gz_directory
package = Gem::Package.new @gem package = Gem::Package.new @gem

View file

@ -35,7 +35,6 @@ class TestGemRequirement < Gem::TestCase
assert_requirement_equal "= 2", ["2"] assert_requirement_equal "= 2", ["2"]
assert_requirement_equal "= 2", v(2) assert_requirement_equal "= 2", v(2)
assert_requirement_equal "2.0", "2" assert_requirement_equal "2.0", "2"
assert_requirement_equal ["= 2", ">= 2"], [">= 2", "= 2"]
end end
def test_create def test_create

View file

@ -2544,6 +2544,14 @@ end
assert_equal @c1, same_spec assert_equal @c1, same_spec
end end
def test_to_ruby_keeps_requirements_as_originally_specified
spec = util_spec 'a', '1' do |s|
s.add_dependency 'b', ['~> 1.0', '>= 1.0.0']
end
assert_includes spec.to_ruby, '"~> 1.0", ">= 1.0.0"'
end
def test_to_ruby_legacy def test_to_ruby_legacy
gemspec1 = Gem::Deprecate.skip_during do gemspec1 = Gem::Deprecate.skip_during do
eval LEGACY_RUBY_SPEC eval LEGACY_RUBY_SPEC

View file

@ -91,4 +91,8 @@ Without the wrapping, the text might not look good in the RSS feed.
assert_equal "Truncating desc to 1,000,000 characters:\n#{s[0, 1_000_000]}", truncate_text(s, "desc", 1_000_000) assert_equal "Truncating desc to 1,000,000 characters:\n#{s[0, 1_000_000]}", truncate_text(s, "desc", 1_000_000)
end end
def test_clean_text
assert_equal ".]2;nyan.", clean_text("\e]2;nyan\a")
end
end end