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.

337 lines
11 KiB

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