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. 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'] = Mastodon::Version.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 key_id
  65. case @key_id_format
  66. when :acct
  67. @account.to_webfinger_s
  68. when :uri
  69. [ActivityPub::TagManager.instance.uri_for(@account), '#main-key'].join
  70. end
  71. end
  72. def timeout
  73. { write: 10, connect: 10, read: 10 }
  74. end
  75. def http_client
  76. @http_client ||= HTTP.use(:auto_inflate).timeout(:per_operation, timeout).follow(max_hops: 2)
  77. end
  78. def use_proxy?
  79. Rails.configuration.x.http_client_proxy.present?
  80. end
  81. def block_hidden_service?
  82. !Rails.configuration.x.access_to_hidden_service && /\.(onion|i2p)$/.match(@url.host)
  83. end
  84. module ClientLimit
  85. def body_with_limit(limit = 1.megabyte)
  86. raise Mastodon::LengthValidationError if content_length.present? && content_length > limit
  87. if charset.nil?
  88. encoding = Encoding::BINARY
  89. else
  90. begin
  91. encoding = Encoding.find(charset)
  92. rescue ArgumentError
  93. encoding = Encoding::BINARY
  94. end
  95. end
  96. contents = String.new(encoding: encoding)
  97. while (chunk = readpartial)
  98. contents << chunk
  99. chunk.clear
  100. raise Mastodon::LengthValidationError if contents.bytesize > limit
  101. end
  102. contents
  103. end
  104. end
  105. class Socket < TCPSocket
  106. class << self
  107. def open(host, *args)
  108. return super host, *args if thru_hidden_service? host
  109. outer_e = nil
  110. Addrinfo.foreach(host, nil, nil, :SOCK_STREAM) do |address|
  111. begin
  112. raise Mastodon::HostValidationError if PrivateAddressCheck.private_address? IPAddr.new(address.ip_address)
  113. return super address.ip_address, *args
  114. rescue => e
  115. outer_e = e
  116. end
  117. end
  118. raise outer_e if outer_e
  119. end
  120. alias new open
  121. def thru_hidden_service?(host)
  122. Rails.configuration.x.hidden_service_via_transparent_proxy && /\.(onion|i2p)$/.match(host)
  123. end
  124. end
  125. end
  126. private_constant :ClientLimit, :Socket
  127. end