process_account_service.rb 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. # frozen_string_literal: true
  2. class ActivityPub::ProcessAccountService < BaseService
  3. include JsonLdHelper
  4. include DomainControlHelper
  5. include Redisable
  6. include Lockable
  7. SUBDOMAINS_RATELIMIT = 10
  8. DISCOVERIES_PER_REQUEST = 400
  9. # Should be called with confirmed valid JSON
  10. # and WebFinger-resolved username and domain
  11. def call(username, domain, json, options = {})
  12. return if json['inbox'].blank? || unsupported_uri_scheme?(json['id']) || domain_not_allowed?(domain)
  13. @options = options
  14. @json = json
  15. @uri = @json['id']
  16. @username = username
  17. @domain = TagManager.instance.normalize_domain(domain)
  18. @collections = {}
  19. # The key does not need to be unguessable, it just needs to be somewhat unique
  20. @options[:request_id] ||= "#{Time.now.utc.to_i}-#{username}@#{domain}"
  21. with_lock("process_account:#{@uri}") do
  22. @account = Account.remote.find_by(uri: @uri) if @options[:only_key]
  23. @account ||= Account.find_remote(@username, @domain)
  24. @old_public_key = @account&.public_key
  25. @old_protocol = @account&.protocol
  26. @suspension_changed = false
  27. if @account.nil?
  28. with_redis do |redis|
  29. return nil if redis.pfcount("unique_subdomains_for:#{PublicSuffix.domain(@domain, ignore_private: true)}") >= SUBDOMAINS_RATELIMIT
  30. discoveries = redis.incr("discovery_per_request:#{@options[:request_id]}")
  31. redis.expire("discovery_per_request:#{@options[:request_id]}", 5.minutes.seconds)
  32. return nil if discoveries > DISCOVERIES_PER_REQUEST
  33. end
  34. create_account
  35. end
  36. update_account
  37. process_tags
  38. process_duplicate_accounts! if @options[:verified_webfinger]
  39. end
  40. return if @account.nil?
  41. after_protocol_change! if protocol_changed?
  42. after_key_change! if key_changed? && !@options[:signed_with_known_key]
  43. clear_tombstones! if key_changed?
  44. after_suspension_change! if suspension_changed?
  45. unless @options[:only_key] || @account.suspended?
  46. check_featured_collection! if @account.featured_collection_url.present?
  47. check_links! unless @account.fields.empty?
  48. end
  49. @account
  50. rescue Oj::ParseError
  51. nil
  52. end
  53. private
  54. def create_account
  55. @account = Account.new
  56. @account.protocol = :activitypub
  57. @account.username = @username
  58. @account.domain = @domain
  59. @account.private_key = nil
  60. @account.suspended_at = domain_block.created_at if auto_suspend?
  61. @account.suspension_origin = :local if auto_suspend?
  62. @account.silenced_at = domain_block.created_at if auto_silence?
  63. set_immediate_protocol_attributes!
  64. @account.save
  65. end
  66. def update_account
  67. @account.last_webfingered_at = Time.now.utc unless @options[:only_key]
  68. @account.protocol = :activitypub
  69. set_suspension!
  70. set_immediate_protocol_attributes!
  71. set_fetchable_key! unless @account.suspended? && @account.suspension_origin_local?
  72. set_immediate_attributes! unless @account.suspended?
  73. set_fetchable_attributes! unless @options[:only_key] || @account.suspended?
  74. @account.save_with_optional_media!
  75. end
  76. def set_immediate_protocol_attributes!
  77. @account.inbox_url = @json['inbox'] || ''
  78. @account.outbox_url = @json['outbox'] || ''
  79. @account.shared_inbox_url = (@json['endpoints'].is_a?(Hash) ? @json['endpoints']['sharedInbox'] : @json['sharedInbox']) || ''
  80. @account.followers_url = @json['followers'] || ''
  81. @account.url = url || @uri
  82. @account.uri = @uri
  83. @account.actor_type = actor_type
  84. @account.created_at = @json['published'] if @json['published'].present?
  85. end
  86. def set_immediate_attributes!
  87. @account.featured_collection_url = @json['featured'] || ''
  88. @account.devices_url = @json['devices'] || ''
  89. @account.display_name = @json['name'] || ''
  90. @account.note = @json['summary'] || ''
  91. @account.locked = @json['manuallyApprovesFollowers'] || false
  92. @account.fields = property_values || {}
  93. @account.also_known_as = as_array(@json['alsoKnownAs'] || []).map { |item| value_or_id(item) }
  94. @account.discoverable = @json['discoverable'] || false
  95. end
  96. def set_fetchable_key!
  97. @account.public_key = public_key || ''
  98. end
  99. def set_fetchable_attributes!
  100. begin
  101. @account.avatar_remote_url = image_url('icon') || '' unless skip_download?
  102. rescue Mastodon::UnexpectedResponseError, HTTP::TimeoutError, HTTP::ConnectionError, OpenSSL::SSL::SSLError
  103. RedownloadAvatarWorker.perform_in(rand(30..600).seconds, @account.id)
  104. end
  105. begin
  106. @account.header_remote_url = image_url('image') || '' unless skip_download?
  107. rescue Mastodon::UnexpectedResponseError, HTTP::TimeoutError, HTTP::ConnectionError, OpenSSL::SSL::SSLError
  108. RedownloadHeaderWorker.perform_in(rand(30..600).seconds, @account.id)
  109. end
  110. @account.statuses_count = outbox_total_items if outbox_total_items.present?
  111. @account.following_count = following_total_items if following_total_items.present?
  112. @account.followers_count = followers_total_items if followers_total_items.present?
  113. @account.hide_collections = following_private? || followers_private?
  114. @account.moved_to_account = @json['movedTo'].present? ? moved_account : nil
  115. end
  116. def set_suspension!
  117. return if @account.suspended? && @account.suspension_origin_local?
  118. if @account.suspended? && !@json['suspended']
  119. @account.unsuspend!
  120. @suspension_changed = true
  121. elsif !@account.suspended? && @json['suspended']
  122. @account.suspend!(origin: :remote)
  123. @suspension_changed = true
  124. end
  125. end
  126. def after_protocol_change!
  127. ActivityPub::PostUpgradeWorker.perform_async(@account.domain)
  128. end
  129. def after_key_change!
  130. RefollowWorker.perform_async(@account.id)
  131. end
  132. def after_suspension_change!
  133. if @account.suspended?
  134. Admin::SuspensionWorker.perform_async(@account.id)
  135. else
  136. Admin::UnsuspensionWorker.perform_async(@account.id)
  137. end
  138. end
  139. def check_featured_collection!
  140. ActivityPub::SynchronizeFeaturedCollectionWorker.perform_async(@account.id, { 'request_id' => @options[:request_id] })
  141. end
  142. def check_links!
  143. VerifyAccountLinksWorker.perform_async(@account.id)
  144. end
  145. def process_duplicate_accounts!
  146. return unless Account.where(uri: @account.uri).where.not(id: @account.id).exists?
  147. AccountMergingWorker.perform_async(@account.id)
  148. end
  149. def actor_type
  150. if @json['type'].is_a?(Array)
  151. @json['type'].find { |type| ActivityPub::FetchRemoteAccountService::SUPPORTED_TYPES.include?(type) }
  152. else
  153. @json['type']
  154. end
  155. end
  156. def image_url(key)
  157. value = first_of_value(@json[key])
  158. return if value.nil?
  159. return value['url'] if value.is_a?(Hash)
  160. image = fetch_resource_without_id_validation(value)
  161. image['url'] if image
  162. end
  163. def public_key
  164. value = first_of_value(@json['publicKey'])
  165. return if value.nil?
  166. return value['publicKeyPem'] if value.is_a?(Hash)
  167. key = fetch_resource_without_id_validation(value)
  168. key['publicKeyPem'] if key
  169. end
  170. def url
  171. return if @json['url'].blank?
  172. url_candidate = url_to_href(@json['url'], 'text/html')
  173. if unsupported_uri_scheme?(url_candidate) || mismatching_origin?(url_candidate)
  174. nil
  175. else
  176. url_candidate
  177. end
  178. end
  179. def property_values
  180. return unless @json['attachment'].is_a?(Array)
  181. as_array(@json['attachment']).select { |attachment| attachment['type'] == 'PropertyValue' }.map { |attachment| attachment.slice('name', 'value') }
  182. end
  183. def mismatching_origin?(url)
  184. needle = Addressable::URI.parse(url).host
  185. haystack = Addressable::URI.parse(@uri).host
  186. !haystack.casecmp(needle).zero?
  187. end
  188. def outbox_total_items
  189. collection_info('outbox').first
  190. end
  191. def following_total_items
  192. collection_info('following').first
  193. end
  194. def followers_total_items
  195. collection_info('followers').first
  196. end
  197. def following_private?
  198. !collection_info('following').last
  199. end
  200. def followers_private?
  201. !collection_info('followers').last
  202. end
  203. def collection_info(type)
  204. return [nil, nil] if @json[type].blank?
  205. return @collections[type] if @collections.key?(type)
  206. collection = fetch_resource_without_id_validation(@json[type])
  207. total_items = collection.is_a?(Hash) && collection['totalItems'].present? && collection['totalItems'].is_a?(Numeric) ? collection['totalItems'] : nil
  208. has_first_page = collection.is_a?(Hash) && collection['first'].present?
  209. @collections[type] = [total_items, has_first_page]
  210. rescue HTTP::Error, OpenSSL::SSL::SSLError, Mastodon::LengthValidationError
  211. @collections[type] = [nil, nil]
  212. end
  213. def moved_account
  214. account = ActivityPub::TagManager.instance.uri_to_resource(@json['movedTo'], Account)
  215. account ||= ActivityPub::FetchRemoteAccountService.new.call(@json['movedTo'], break_on_redirect: true, request_id: @options[:request_id])
  216. account
  217. end
  218. def skip_download?
  219. @account.suspended? || domain_block&.reject_media?
  220. end
  221. def auto_suspend?
  222. domain_block&.suspend?
  223. end
  224. def auto_silence?
  225. domain_block&.silence?
  226. end
  227. def domain_block
  228. return @domain_block if defined?(@domain_block)
  229. @domain_block = DomainBlock.rule_for(@domain)
  230. end
  231. def key_changed?
  232. !@old_public_key.nil? && @old_public_key != @account.public_key
  233. end
  234. def suspension_changed?
  235. @suspension_changed
  236. end
  237. def clear_tombstones!
  238. Tombstone.where(account_id: @account.id).delete_all
  239. end
  240. def protocol_changed?
  241. !@old_protocol.nil? && @old_protocol != @account.protocol
  242. end
  243. def process_tags
  244. return if @json['tag'].blank?
  245. as_array(@json['tag']).each do |tag|
  246. process_emoji tag if equals_or_includes?(tag['type'], 'Emoji')
  247. end
  248. end
  249. def process_emoji(tag)
  250. return if skip_download?
  251. return if tag['name'].blank? || tag['icon'].blank? || tag['icon']['url'].blank?
  252. shortcode = tag['name'].delete(':')
  253. image_url = tag['icon']['url']
  254. uri = tag['id']
  255. updated = tag['updated']
  256. emoji = CustomEmoji.find_by(shortcode: shortcode, domain: @account.domain)
  257. return unless emoji.nil? || image_url != emoji.image_remote_url || (updated && updated >= emoji.updated_at)
  258. emoji ||= CustomEmoji.new(domain: @account.domain, shortcode: shortcode, uri: uri)
  259. emoji.image_remote_url = image_url
  260. emoji.save
  261. end
  262. end