DEV: Allow webmock to intercept FinalDestination::HTTP requests (#20575)

This commit is contained in:
Alan Guo Xiang Tan 2023-03-08 10:40:01 +08:00 committed by GitHub
parent a252022117
commit 500d0f6daf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 44 additions and 29 deletions

View File

@ -1,6 +1,7 @@
# frozen_string_literal: true
class FinalDestination::HTTP < Net::HTTP
class FinalDestination
module SSRFSafeNetHTTP
def connect
original_open_timeout = @open_timeout
return super if @ipaddr
@ -10,7 +11,8 @@ class FinalDestination::HTTP < Net::HTTP
# This iteration through addresses would normally happen in Socket#tcp
# We do it here because we're tightly controlling addresses rather than
# handing Socket#tcp a hostname
ips = FinalDestination::SSRFDetector.lookup_and_filter_ips(@address, timeout: @connect_timeout)
ips =
FinalDestination::SSRFDetector.lookup_and_filter_ips(@address, timeout: @connect_timeout)
ips.each_with_index do |ip, index|
debug "[FinalDestination] Attempting connection to #{ip}..."
@ -37,4 +39,9 @@ class FinalDestination::HTTP < Net::HTTP
def current_time
Process.clock_gettime(Process::CLOCK_MONOTONIC)
end
end
class HTTP < ::Net::HTTP
include SSRFSafeNetHTTP
end
end

View File

@ -7,7 +7,15 @@ WebMock::HttpLibAdapterRegistry.instance.register(
def self.enable!
FinalDestination.send(:remove_const, :HTTP)
FinalDestination.send(:const_set, :HTTP, Net::HTTP)
# At this point, `Net::HTTP` has already been patched by WebMock so we need to re-declare `FinalDestination::HTTP`
# but inherit from the patched `Net::HTTP` class. This is to allow requests made using `FinalDestination::HTTP` to be
# intercepted by WebMock.
FinalDestination.send(
:const_set,
:HTTP,
Class.new(Net::HTTP) { include FinalDestination::SSRFSafeNetHTTP },
)
end
def self.disable!