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.

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