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.

166 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).reverse_merge('Accept-Encoding' => 'gzip').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. end
  49. def set_digest!
  50. @headers['Digest'] = "SHA-256=#{Digest::SHA256.base64digest(@options[:body])}"
  51. end
  52. def signature
  53. algorithm = 'rsa-sha256'
  54. signature = Base64.strict_encode64(@account.keypair.sign(OpenSSL::Digest::SHA256.new, signed_string))
  55. "keyId=\"#{key_id}\",algorithm=\"#{algorithm}\",headers=\"#{signed_headers}\",signature=\"#{signature}\""
  56. end
  57. def signed_string
  58. @headers.map { |key, value| "#{key.downcase}: #{value}" }.join("\n")
  59. end
  60. def signed_headers
  61. @headers.keys.join(' ').downcase
  62. end
  63. def user_agent
  64. @user_agent ||= "#{HTTP::Request::USER_AGENT} (Mastodon/#{Mastodon::Version}; +#{root_url})"
  65. end
  66. def key_id
  67. case @key_id_format
  68. when :acct
  69. @account.to_webfinger_s
  70. when :uri
  71. [ActivityPub::TagManager.instance.uri_for(@account), '#main-key'].join
  72. end
  73. end
  74. def timeout
  75. { write: 10, connect: 10, read: 10 }
  76. end
  77. def http_client
  78. @http_client ||= HTTP.use(:auto_inflate).timeout(:per_operation, timeout).follow(max_hops: 2)
  79. end
  80. def use_proxy?
  81. Rails.configuration.x.http_client_proxy.present?
  82. end
  83. def block_hidden_service?
  84. !Rails.configuration.x.access_to_hidden_service && /\.(onion|i2p)$/.match(@url.host)
  85. end
  86. module ClientLimit
  87. def body_with_limit(limit = 1.megabyte)
  88. raise Mastodon::LengthValidationError if content_length.present? && content_length > limit
  89. if charset.nil?
  90. encoding = Encoding::BINARY
  91. else
  92. begin
  93. encoding = Encoding.find(charset)
  94. rescue ArgumentError
  95. encoding = Encoding::BINARY
  96. end
  97. end
  98. contents = String.new(encoding: encoding)
  99. while (chunk = readpartial)
  100. contents << chunk
  101. chunk.clear
  102. raise Mastodon::LengthValidationError if contents.bytesize > limit
  103. end
  104. contents
  105. end
  106. end
  107. class Socket < TCPSocket
  108. class << self
  109. def open(host, *args)
  110. return super host, *args if thru_hidden_service? host
  111. outer_e = nil
  112. Addrinfo.foreach(host, nil, nil, :SOCK_STREAM) do |address|
  113. begin
  114. raise Mastodon::HostValidationError if PrivateAddressCheck.private_address? IPAddr.new(address.ip_address)
  115. return super address.ip_address, *args
  116. rescue => e
  117. outer_e = e
  118. end
  119. end
  120. raise outer_e if outer_e
  121. end
  122. alias new open
  123. def thru_hidden_service?(host)
  124. Rails.configuration.x.hidden_service_via_transparent_proxy && /\.(onion|i2p)$/.match(host)
  125. end
  126. end
  127. end
  128. private_constant :ClientLimit, :Socket
  129. end