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.

164 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, sign_with: nil)
  18. raise ArgumentError unless account.local?
  19. @account = account
  20. @keypair = sign_with.present? ? OpenSSL::PKey::RSA.new(sign_with) : @account.keypair
  21. @key_id_format = key_id_format
  22. self
  23. end
  24. def add_headers(new_headers)
  25. @headers.merge!(new_headers)
  26. self
  27. end
  28. def perform
  29. begin
  30. response = http_client.headers(headers).public_send(@verb, @url.to_s, @options)
  31. rescue => e
  32. raise e.class, "#{e.message} on #{@url}", e.backtrace[0]
  33. end
  34. begin
  35. yield response.extend(ClientLimit)
  36. ensure
  37. http_client.close
  38. end
  39. end
  40. def headers
  41. (@account ? @headers.merge('Signature' => signature) : @headers).without(REQUEST_TARGET)
  42. end
  43. private
  44. def set_common_headers!
  45. @headers[REQUEST_TARGET] = "#{@verb} #{@url.path}"
  46. @headers['User-Agent'] = Mastodon::Version.user_agent
  47. @headers['Host'] = @url.host
  48. @headers['Date'] = Time.now.utc.httpdate
  49. @headers['Accept-Encoding'] = 'gzip' if @verb != :head
  50. end
  51. def set_digest!
  52. @headers['Digest'] = "SHA-256=#{Digest::SHA256.base64digest(@options[:body])}"
  53. end
  54. def signature
  55. algorithm = 'rsa-sha256'
  56. signature = Base64.strict_encode64(@keypair.sign(OpenSSL::Digest::SHA256.new, signed_string))
  57. "keyId=\"#{key_id}\",algorithm=\"#{algorithm}\",headers=\"#{signed_headers.keys.join(' ').downcase}\",signature=\"#{signature}\""
  58. end
  59. def signed_string
  60. signed_headers.map { |key, value| "#{key.downcase}: #{value}" }.join("\n")
  61. end
  62. def signed_headers
  63. @headers.without('User-Agent', 'Accept-Encoding')
  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.use(:auto_inflate).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.access_to_hidden_service && /\.(onion|i2p)$/.match(host)
  124. end
  125. end
  126. end
  127. private_constant :ClientLimit, :Socket
  128. end