2019-07-25 01:27:42 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2019-04-21 06:03:26 -04:00
|
|
|
module StubRequests
|
2021-03-23 08:09:33 -04:00
|
|
|
IP_ADDRESS_STUB = '8.8.8.9'
|
2019-04-21 06:03:26 -04:00
|
|
|
|
|
|
|
# Fully stubs a request using WebMock class. This class also
|
|
|
|
# stubs the IP address the URL is translated to (DNS lookup).
|
|
|
|
#
|
|
|
|
# It expects the final request to go to the `ip_address` instead the given url.
|
|
|
|
# That's primarily a DNS rebind attack prevention of Gitlab::HTTP
|
|
|
|
# (see: Gitlab::UrlBlocker).
|
|
|
|
#
|
|
|
|
def stub_full_request(url, ip_address: IP_ADDRESS_STUB, port: 80, method: :get)
|
|
|
|
stub_dns(url, ip_address: ip_address, port: port)
|
|
|
|
|
|
|
|
url = stubbed_hostname(url, hostname: ip_address)
|
|
|
|
WebMock.stub_request(method, url)
|
|
|
|
end
|
|
|
|
|
|
|
|
def stub_dns(url, ip_address:, port: 80)
|
2021-02-17 07:09:26 -05:00
|
|
|
url = parse_url(url)
|
2019-04-21 06:03:26 -04:00
|
|
|
socket = Socket.sockaddr_in(port, ip_address)
|
|
|
|
addr = Addrinfo.new(socket)
|
|
|
|
|
2021-02-17 07:09:26 -05:00
|
|
|
# See Gitlab::UrlBlocker
|
2019-04-21 06:03:26 -04:00
|
|
|
allow(Addrinfo).to receive(:getaddrinfo)
|
2021-02-17 07:09:26 -05:00
|
|
|
.with(url.hostname, url.port, nil, :STREAM)
|
|
|
|
.and_return([addr])
|
2019-04-21 06:03:26 -04:00
|
|
|
end
|
|
|
|
|
2019-07-23 23:48:44 -04:00
|
|
|
def stub_all_dns(url, ip_address:)
|
|
|
|
url = URI(url)
|
|
|
|
port = 80 # arbitarily chosen, does not matter as we are not going to connect
|
|
|
|
socket = Socket.sockaddr_in(port, ip_address)
|
|
|
|
addr = Addrinfo.new(socket)
|
|
|
|
|
2021-02-17 07:09:26 -05:00
|
|
|
# See Gitlab::UrlBlocker
|
|
|
|
allow(Addrinfo).to receive(:getaddrinfo).and_call_original
|
2019-07-23 23:48:44 -04:00
|
|
|
allow(Addrinfo).to receive(:getaddrinfo)
|
2021-02-17 07:09:26 -05:00
|
|
|
.with(url.hostname, anything, nil, :STREAM)
|
2019-07-23 23:48:44 -04:00
|
|
|
.and_return([addr])
|
|
|
|
end
|
|
|
|
|
2019-04-21 06:03:26 -04:00
|
|
|
def stubbed_hostname(url, hostname: IP_ADDRESS_STUB)
|
2021-02-17 07:09:26 -05:00
|
|
|
url = parse_url(url)
|
2019-04-21 06:03:26 -04:00
|
|
|
url.hostname = hostname
|
|
|
|
url.to_s
|
|
|
|
end
|
2021-02-17 07:09:26 -05:00
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def parse_url(url)
|
|
|
|
url.is_a?(URI) ? url : URI(url)
|
|
|
|
end
|
2019-04-21 06:03:26 -04:00
|
|
|
end
|