You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

167 lines
4.1 KiB

  1. # frozen_string_literal: true
  2. require 'ipaddr'
  3. require 'socket'
  4. class Request
  5. REQUEST_TARGET = '(request-target)'
  6. include RoutingHelper
  7. def initialize(verb, url, **options)
  8. raise ArgumentError if url.blank?
  9. @verb = verb
  10. @url = Addressable::URI.parse(url).normalize
  11. @options = options.merge(use_proxy? ? Rails.configuration.x.http_client_proxy : { socket_class: Socket })
  12. @headers = {}
  13. raise Mastodon::HostValidationError, 'Instance does not support hidden service connections' if block_hidden_service?
  14. set_common_headers!
  15. set_digest! if options.key?(:body)
  16. end
  17. def on_behalf_of(account, key_id_format = :acct)
  18. raise ArgumentError unless account.local?
  19. @account = account
  20. @key_id_format = key_id_format
  21. self
  22. end
  23. def add_headers(new_headers)
  24. @headers.merge!(new_headers)
  25. self
  26. end
  27. def perform
  28. begin
  29. response = http_client.headers(headers).public_send(@verb, @url.to_s, @options)
  30. rescue => e
  31. raise e.class, "#{e.message} on #{@url}", e.backtrace[0]
  32. end
  33. begin
  34. yield response.extend(ClientLimit)
  35. ensure
  36. http_client.close
  37. end
  38. end
  39. def headers
  40. (@account ? @headers.merge('Signature' => signature) : @headers).without(REQUEST_TARGET)
  41. end
  42. private
  43. def set_common_headers!
  44. @headers[REQUEST_TARGET] = "#{@verb} #{@url.path}"
  45. @headers['User-Agent'] = user_agent
  46. @headers['Host'] = @url.host
  47. @headers['Date'] = Time.now.utc.httpdate
  48. @headers['Accept-Encoding'] = 'gzip' if @verb != :head
  49. end
  50. def set_digest!
  51. @headers['Digest'] = "SHA-256=#{Digest::SHA256.base64digest(@options[:body])}"
  52. end
  53. def signature
  54. algorithm = 'rsa-sha256'
  55. signature = Base64.strict_encode64(@account.keypair.sign(OpenSSL::Digest::SHA256.new, signed_string))
  56. "keyId=\"#{key_id}\",algorithm=\"#{algorithm}\",headers=\"#{signed_headers}\",signature=\"#{signature}\""
  57. end
  58. def signed_string
  59. @headers.map { |key, value| "#{key.downcase}: #{value}" }.join("\n")
  60. end
  61. def signed_headers
  62. @headers.keys.join(' ').downcase
  63. end
  64. def user_agent
  65. @user_agent ||= "#{HTTP::Request::USER_AGENT} (Mastodon/#{Mastodon::Version}; +#{root_url})"
  66. end
  67. def key_id
  68. case @key_id_format
  69. when :acct
  70. @account.to_webfinger_s
  71. when :uri
  72. [ActivityPub::TagManager.instance.uri_for(@account), '#main-key'].join
  73. end
  74. end
  75. def timeout
  76. { write: 10, connect: 10, read: 10 }
  77. end
  78. def http_client
  79. @http_client ||= HTTP.use(:auto_inflate).timeout(:per_operation, timeout).follow(max_hops: 2)
  80. end
  81. def use_proxy?
  82. Rails.configuration.x.http_client_proxy.present?
  83. end
  84. def block_hidden_service?
  85. !Rails.configuration.x.access_to_hidden_service && /\.(onion|i2p)$/.match(@url.host)
  86. end
  87. module ClientLimit
  88. def body_with_limit(limit = 1.megabyte)
  89. raise Mastodon::LengthValidationError if content_length.present? && content_length > limit
  90. if charset.nil?
  91. encoding = Encoding::BINARY
  92. else
  93. begin
  94. encoding = Encoding.find(charset)
  95. rescue ArgumentError
  96. encoding = Encoding::BINARY
  97. end
  98. end
  99. contents = String.new(encoding: encoding)
  100. while (chunk = readpartial)
  101. contents << chunk
  102. chunk.clear
  103. raise Mastodon::LengthValidationError if contents.bytesize > limit
  104. end
  105. contents
  106. end
  107. end
  108. class Socket < TCPSocket
  109. class << self
  110. def open(host, *args)
  111. return super host, *args if thru_hidden_service? host
  112. outer_e = nil
  113. Addrinfo.foreach(host, nil, nil, :SOCK_STREAM) do |address|
  114. begin
  115. raise Mastodon::HostValidationError if PrivateAddressCheck.private_address? IPAddr.new(address.ip_address)
  116. return super address.ip_address, *args
  117. rescue => e
  118. outer_e = e
  119. end
  120. end
  121. raise outer_e if outer_e
  122. end
  123. alias new open
  124. def thru_hidden_service?(host)
  125. Rails.configuration.x.hidden_service_via_transparent_proxy && /\.(onion|i2p)$/.match(host)
  126. end
  127. end
  128. end
  129. private_constant :ClientLimit, :Socket
  130. end