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.

336 lines
10 KiB

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