process_account_service.rb 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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_redis_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. after_protocol_change! if protocol_changed?
  41. after_key_change! if key_changed? && !@options[:signed_with_known_key]
  42. clear_tombstones! if key_changed?
  43. after_suspension_change! if suspension_changed?
  44. unless @options[:only_key] || @account.suspended?
  45. check_featured_collection! if @account.featured_collection_url.present?
  46. check_featured_tags_collection! if @json['featuredTags'].present?
  47. check_links! if @account.fields.any?(&:requires_verification?)
  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. @account.indexable = @json['indexable'] || false
  96. @account.memorial = @json['memorial'] || false
  97. end
  98. def set_fetchable_key!
  99. @account.public_key = public_key || ''
  100. end
  101. def set_fetchable_attributes!
  102. begin
  103. @account.avatar_remote_url = image_url('icon') || '' unless skip_download?
  104. @account.avatar = nil if @account.avatar_remote_url.blank?
  105. rescue Mastodon::UnexpectedResponseError, HTTP::TimeoutError, HTTP::ConnectionError, OpenSSL::SSL::SSLError
  106. RedownloadAvatarWorker.perform_in(rand(30..600).seconds, @account.id)
  107. end
  108. begin
  109. @account.header_remote_url = image_url('image') || '' unless skip_download?
  110. @account.header = nil if @account.header_remote_url.blank?
  111. rescue Mastodon::UnexpectedResponseError, HTTP::TimeoutError, HTTP::ConnectionError, OpenSSL::SSL::SSLError
  112. RedownloadHeaderWorker.perform_in(rand(30..600).seconds, @account.id)
  113. end
  114. @account.statuses_count = outbox_total_items if outbox_total_items.present?
  115. @account.following_count = following_total_items if following_total_items.present?
  116. @account.followers_count = followers_total_items if followers_total_items.present?
  117. @account.hide_collections = following_private? || followers_private?
  118. @account.moved_to_account = @json['movedTo'].present? ? moved_account : nil
  119. end
  120. def set_suspension!
  121. return if @account.suspended? && @account.suspension_origin_local?
  122. if @account.suspended? && !@json['suspended']
  123. @account.unsuspend!
  124. @suspension_changed = true
  125. elsif !@account.suspended? && @json['suspended']
  126. @account.suspend!(origin: :remote)
  127. @suspension_changed = true
  128. end
  129. end
  130. def after_protocol_change!
  131. ActivityPub::PostUpgradeWorker.perform_async(@account.domain)
  132. end
  133. def after_key_change!
  134. RefollowWorker.perform_async(@account.id)
  135. end
  136. def after_suspension_change!
  137. if @account.suspended?
  138. Admin::SuspensionWorker.perform_async(@account.id)
  139. else
  140. Admin::UnsuspensionWorker.perform_async(@account.id)
  141. end
  142. end
  143. def check_featured_collection!
  144. ActivityPub::SynchronizeFeaturedCollectionWorker.perform_async(@account.id, { 'hashtag' => @json['featuredTags'].blank?, 'request_id' => @options[:request_id] })
  145. end
  146. def check_featured_tags_collection!
  147. ActivityPub::SynchronizeFeaturedTagsCollectionWorker.perform_async(@account.id, @json['featuredTags'])
  148. end
  149. def check_links!
  150. VerifyAccountLinksWorker.perform_async(@account.id)
  151. end
  152. def process_duplicate_accounts!
  153. return unless Account.where(uri: @account.uri).where.not(id: @account.id).exists?
  154. AccountMergingWorker.perform_async(@account.id)
  155. end
  156. def actor_type
  157. if @json['type'].is_a?(Array)
  158. @json['type'].find { |type| ActivityPub::FetchRemoteAccountService::SUPPORTED_TYPES.include?(type) }
  159. else
  160. @json['type']
  161. end
  162. end
  163. def image_url(key)
  164. value = first_of_value(@json[key])
  165. return if value.nil?
  166. return value['url'] if value.is_a?(Hash)
  167. image = fetch_resource_without_id_validation(value)
  168. image['url'] if image
  169. end
  170. def public_key
  171. value = first_of_value(@json['publicKey'])
  172. return if value.nil?
  173. return value['publicKeyPem'] if value.is_a?(Hash)
  174. key = fetch_resource_without_id_validation(value)
  175. key['publicKeyPem'] if key
  176. end
  177. def url
  178. return if @json['url'].blank?
  179. url_candidate = url_to_href(@json['url'], 'text/html')
  180. if unsupported_uri_scheme?(url_candidate) || mismatching_origin?(url_candidate)
  181. nil
  182. else
  183. url_candidate
  184. end
  185. end
  186. def property_values
  187. return unless @json['attachment'].is_a?(Array)
  188. as_array(@json['attachment']).select { |attachment| attachment['type'] == 'PropertyValue' }.map { |attachment| attachment.slice('name', 'value') }
  189. end
  190. def mismatching_origin?(url)
  191. needle = Addressable::URI.parse(url).host
  192. haystack = Addressable::URI.parse(@uri).host
  193. !haystack.casecmp(needle).zero?
  194. end
  195. def outbox_total_items
  196. collection_info('outbox').first
  197. end
  198. def following_total_items
  199. collection_info('following').first
  200. end
  201. def followers_total_items
  202. collection_info('followers').first
  203. end
  204. def following_private?
  205. !collection_info('following').last
  206. end
  207. def followers_private?
  208. !collection_info('followers').last
  209. end
  210. def collection_info(type)
  211. return [nil, nil] if @json[type].blank?
  212. return @collections[type] if @collections.key?(type)
  213. collection = fetch_resource_without_id_validation(@json[type])
  214. total_items = collection.is_a?(Hash) && collection['totalItems'].present? && collection['totalItems'].is_a?(Numeric) ? collection['totalItems'] : nil
  215. has_first_page = collection.is_a?(Hash) && collection['first'].present?
  216. @collections[type] = [total_items, has_first_page]
  217. rescue HTTP::Error, OpenSSL::SSL::SSLError, Mastodon::LengthValidationError
  218. @collections[type] = [nil, nil]
  219. end
  220. def moved_account
  221. account = ActivityPub::TagManager.instance.uri_to_resource(@json['movedTo'], Account)
  222. account ||= ActivityPub::FetchRemoteAccountService.new.call(@json['movedTo'], id: true, break_on_redirect: true, request_id: @options[:request_id])
  223. account
  224. end
  225. def skip_download?
  226. @account.suspended? || domain_block&.reject_media?
  227. end
  228. def auto_suspend?
  229. domain_block&.suspend?
  230. end
  231. def auto_silence?
  232. domain_block&.silence?
  233. end
  234. def domain_block
  235. return @domain_block if defined?(@domain_block)
  236. @domain_block = DomainBlock.rule_for(@domain)
  237. end
  238. def key_changed?
  239. !@old_public_key.nil? && @old_public_key != @account.public_key
  240. end
  241. def suspension_changed?
  242. @suspension_changed
  243. end
  244. def clear_tombstones!
  245. Tombstone.where(account_id: @account.id).delete_all
  246. end
  247. def protocol_changed?
  248. !@old_protocol.nil? && @old_protocol != @account.protocol
  249. end
  250. def process_tags
  251. return if @json['tag'].blank?
  252. as_array(@json['tag']).each do |tag|
  253. process_emoji tag if equals_or_includes?(tag['type'], 'Emoji')
  254. end
  255. end
  256. def process_emoji(tag)
  257. return if skip_download?
  258. return if tag['name'].blank? || tag['icon'].blank? || tag['icon']['url'].blank?
  259. shortcode = tag['name'].delete(':')
  260. image_url = tag['icon']['url']
  261. uri = tag['id']
  262. updated = tag['updated']
  263. emoji = CustomEmoji.find_by(shortcode: shortcode, domain: @account.domain)
  264. return unless emoji.nil? || image_url != emoji.image_remote_url || (updated && updated >= emoji.updated_at)
  265. emoji ||= CustomEmoji.new(domain: @account.domain, shortcode: shortcode, uri: uri)
  266. emoji.image_remote_url = image_url
  267. emoji.save
  268. end
  269. end