request.rb 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. # frozen_string_literal: true
  2. require 'ipaddr'
  3. require 'socket'
  4. require 'resolv'
  5. # Monkey-patch the HTTP.rb timeout class to avoid using a timeout block
  6. # around the Socket#open method, since we use our own timeout blocks inside
  7. # that method
  8. class HTTP::Timeout::PerOperation
  9. def connect(socket_class, host, port, nodelay = false)
  10. @socket = socket_class.open(host, port)
  11. @socket.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1) if nodelay
  12. end
  13. end
  14. class Request
  15. REQUEST_TARGET = '(request-target)'
  16. include RoutingHelper
  17. def initialize(verb, url, **options)
  18. raise ArgumentError if url.blank?
  19. @verb = verb
  20. @url = Addressable::URI.parse(url).normalize
  21. @options = options.merge(use_proxy? ? Rails.configuration.x.http_client_proxy : { socket_class: Socket })
  22. @headers = {}
  23. raise Mastodon::HostValidationError, 'Instance does not support hidden service connections' if block_hidden_service?
  24. set_common_headers!
  25. set_digest! if options.key?(:body)
  26. end
  27. def on_behalf_of(account, key_id_format = :acct, sign_with: nil)
  28. raise ArgumentError unless account.local?
  29. @account = account
  30. @keypair = sign_with.present? ? OpenSSL::PKey::RSA.new(sign_with) : @account.keypair
  31. @key_id_format = key_id_format
  32. self
  33. end
  34. def add_headers(new_headers)
  35. @headers.merge!(new_headers)
  36. self
  37. end
  38. def perform
  39. begin
  40. response = http_client.headers(headers).public_send(@verb, @url.to_s, @options)
  41. rescue => e
  42. raise e.class, "#{e.message} on #{@url}", e.backtrace[0]
  43. end
  44. begin
  45. yield response.extend(ClientLimit) if block_given?
  46. ensure
  47. http_client.close
  48. end
  49. end
  50. def headers
  51. (@account ? @headers.merge('Signature' => signature) : @headers).without(REQUEST_TARGET)
  52. end
  53. class << self
  54. def valid_url?(url)
  55. begin
  56. parsed_url = Addressable::URI.parse(url)
  57. rescue Addressable::URI::InvalidURIError
  58. return false
  59. end
  60. %w(http https).include?(parsed_url.scheme) && parsed_url.host.present?
  61. end
  62. end
  63. private
  64. def set_common_headers!
  65. @headers[REQUEST_TARGET] = "#{@verb} #{@url.path}"
  66. @headers['User-Agent'] = Mastodon::Version.user_agent
  67. @headers['Host'] = @url.host
  68. @headers['Date'] = Time.now.utc.httpdate
  69. @headers['Accept-Encoding'] = 'gzip' if @verb != :head
  70. end
  71. def set_digest!
  72. @headers['Digest'] = "SHA-256=#{Digest::SHA256.base64digest(@options[:body])}"
  73. end
  74. def signature
  75. algorithm = 'rsa-sha256'
  76. signature = Base64.strict_encode64(@keypair.sign(OpenSSL::Digest::SHA256.new, signed_string))
  77. "keyId=\"#{key_id}\",algorithm=\"#{algorithm}\",headers=\"#{signed_headers.keys.join(' ').downcase}\",signature=\"#{signature}\""
  78. end
  79. def signed_string
  80. signed_headers.map { |key, value| "#{key.downcase}: #{value}" }.join("\n")
  81. end
  82. def signed_headers
  83. @headers.without('User-Agent', 'Accept-Encoding')
  84. end
  85. def key_id
  86. case @key_id_format
  87. when :acct
  88. @account.to_webfinger_s
  89. when :uri
  90. [ActivityPub::TagManager.instance.uri_for(@account), '#main-key'].join
  91. end
  92. end
  93. def timeout
  94. # We enforce a 1s timeout on DNS resolving, 10s timeout on socket opening
  95. # and 5s timeout on the TLS handshake, meaning the worst case should take
  96. # about 16s in total
  97. { connect: 5, read: 10, write: 10 }
  98. end
  99. def http_client
  100. @http_client ||= HTTP.use(:auto_inflate).timeout(:per_operation, timeout).follow(max_hops: 2)
  101. end
  102. def use_proxy?
  103. Rails.configuration.x.http_client_proxy.present?
  104. end
  105. def block_hidden_service?
  106. !Rails.configuration.x.access_to_hidden_service && /\.(onion|i2p)$/.match(@url.host)
  107. end
  108. module ClientLimit
  109. def body_with_limit(limit = 1.megabyte)
  110. raise Mastodon::LengthValidationError if content_length.present? && content_length > limit
  111. if charset.nil?
  112. encoding = Encoding::BINARY
  113. else
  114. begin
  115. encoding = Encoding.find(charset)
  116. rescue ArgumentError
  117. encoding = Encoding::BINARY
  118. end
  119. end
  120. contents = String.new(encoding: encoding)
  121. while (chunk = readpartial)
  122. contents << chunk
  123. chunk.clear
  124. raise Mastodon::LengthValidationError if contents.bytesize > limit
  125. end
  126. contents
  127. end
  128. end
  129. class Socket < TCPSocket
  130. class << self
  131. def open(host, *args)
  132. return super(host, *args) if thru_hidden_service?(host)
  133. outer_e = nil
  134. Resolv::DNS.open do |dns|
  135. dns.timeouts = 1
  136. addresses = dns.getaddresses(host).take(2)
  137. time_slot = 10.0 / addresses.size
  138. addresses.each do |address|
  139. begin
  140. raise Mastodon::HostValidationError if PrivateAddressCheck.private_address?(IPAddr.new(address.to_s))
  141. ::Timeout.timeout(time_slot, HTTP::TimeoutError) do
  142. return super(address.to_s, *args)
  143. end
  144. rescue => e
  145. outer_e = e
  146. end
  147. end
  148. end
  149. if outer_e
  150. raise outer_e
  151. else
  152. raise SocketError, "No address for #{host}"
  153. end
  154. end
  155. alias new open
  156. def thru_hidden_service?(host)
  157. Rails.configuration.x.access_to_hidden_service && /\.(onion|i2p)$/.match(host)
  158. end
  159. end
  160. end
  161. private_constant :ClientLimit, :Socket
  162. end