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.

278 lines
8.4 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.find_remote(@username, @domain)
  18. @old_public_key = @account&.public_key
  19. @old_protocol = @account&.protocol
  20. create_account if @account.nil?
  21. update_account
  22. process_tags
  23. process_attachments
  24. else
  25. raise Mastodon::RaceConditionError
  26. end
  27. end
  28. return if @account.nil?
  29. after_protocol_change! if protocol_changed?
  30. after_key_change! if key_changed? && !@options[:signed_with_known_key]
  31. clear_tombstones! if key_changed?
  32. unless @options[:only_key]
  33. check_featured_collection! if @account.featured_collection_url.present?
  34. check_links! unless @account.fields.empty?
  35. end
  36. @account
  37. rescue Oj::ParseError
  38. nil
  39. end
  40. private
  41. def create_account
  42. @account = Account.new
  43. @account.protocol = :activitypub
  44. @account.username = @username
  45. @account.domain = @domain
  46. @account.private_key = nil
  47. @account.suspended_at = domain_block.created_at if auto_suspend?
  48. @account.silenced_at = domain_block.created_at if auto_silence?
  49. end
  50. def update_account
  51. @account.last_webfingered_at = Time.now.utc unless @options[:only_key]
  52. @account.protocol = :activitypub
  53. set_immediate_attributes!
  54. set_fetchable_attributes! unless @options[:only_keys]
  55. @account.save_with_optional_media!
  56. end
  57. def set_immediate_attributes!
  58. @account.inbox_url = @json['inbox'] || ''
  59. @account.outbox_url = @json['outbox'] || ''
  60. @account.shared_inbox_url = (@json['endpoints'].is_a?(Hash) ? @json['endpoints']['sharedInbox'] : @json['sharedInbox']) || ''
  61. @account.followers_url = @json['followers'] || ''
  62. @account.featured_collection_url = @json['featured'] || ''
  63. @account.url = url || @uri
  64. @account.uri = @uri
  65. @account.display_name = @json['name'] || ''
  66. @account.note = @json['summary'] || ''
  67. @account.locked = @json['manuallyApprovesFollowers'] || false
  68. @account.fields = property_values || {}
  69. @account.also_known_as = as_array(@json['alsoKnownAs'] || []).map { |item| value_or_id(item) }
  70. @account.actor_type = actor_type
  71. @account.discoverable = @json['discoverable'] || false
  72. end
  73. def set_fetchable_attributes!
  74. @account.avatar_remote_url = image_url('icon') unless skip_download?
  75. @account.header_remote_url = image_url('image') unless skip_download?
  76. @account.public_key = public_key || ''
  77. @account.statuses_count = outbox_total_items if outbox_total_items.present?
  78. @account.following_count = following_total_items if following_total_items.present?
  79. @account.followers_count = followers_total_items if followers_total_items.present?
  80. @account.moved_to_account = @json['movedTo'].present? ? moved_account : nil
  81. end
  82. def after_protocol_change!
  83. ActivityPub::PostUpgradeWorker.perform_async(@account.domain)
  84. end
  85. def after_key_change!
  86. RefollowWorker.perform_async(@account.id)
  87. end
  88. def check_featured_collection!
  89. ActivityPub::SynchronizeFeaturedCollectionWorker.perform_async(@account.id)
  90. end
  91. def check_links!
  92. VerifyAccountLinksWorker.perform_async(@account.id)
  93. end
  94. def actor_type
  95. if @json['type'].is_a?(Array)
  96. @json['type'].find { |type| ActivityPub::FetchRemoteAccountService::SUPPORTED_TYPES.include?(type) }
  97. else
  98. @json['type']
  99. end
  100. end
  101. def image_url(key)
  102. value = first_of_value(@json[key])
  103. return if value.nil?
  104. return value['url'] if value.is_a?(Hash)
  105. image = fetch_resource_without_id_validation(value)
  106. image['url'] if image
  107. end
  108. def public_key
  109. value = first_of_value(@json['publicKey'])
  110. return if value.nil?
  111. return value['publicKeyPem'] if value.is_a?(Hash)
  112. key = fetch_resource_without_id_validation(value)
  113. key['publicKeyPem'] if key
  114. end
  115. def url
  116. return if @json['url'].blank?
  117. url_candidate = url_to_href(@json['url'], 'text/html')
  118. if unsupported_uri_scheme?(url_candidate) || mismatching_origin?(url_candidate)
  119. nil
  120. else
  121. url_candidate
  122. end
  123. end
  124. def property_values
  125. return unless @json['attachment'].is_a?(Array)
  126. as_array(@json['attachment']).select { |attachment| attachment['type'] == 'PropertyValue' }.map { |attachment| attachment.slice('name', 'value') }
  127. end
  128. def mismatching_origin?(url)
  129. needle = Addressable::URI.parse(url).host
  130. haystack = Addressable::URI.parse(@uri).host
  131. !haystack.casecmp(needle).zero?
  132. end
  133. def outbox_total_items
  134. collection_total_items('outbox')
  135. end
  136. def following_total_items
  137. collection_total_items('following')
  138. end
  139. def followers_total_items
  140. collection_total_items('followers')
  141. end
  142. def collection_total_items(type)
  143. return if @json[type].blank?
  144. return @collections[type] if @collections.key?(type)
  145. collection = fetch_resource_without_id_validation(@json[type])
  146. @collections[type] = collection.is_a?(Hash) && collection['totalItems'].present? && collection['totalItems'].is_a?(Numeric) ? collection['totalItems'] : nil
  147. rescue HTTP::Error, OpenSSL::SSL::SSLError
  148. @collections[type] = nil
  149. end
  150. def moved_account
  151. account = ActivityPub::TagManager.instance.uri_to_resource(@json['movedTo'], Account)
  152. account ||= ActivityPub::FetchRemoteAccountService.new.call(@json['movedTo'], id: true, break_on_redirect: true)
  153. account
  154. end
  155. def skip_download?
  156. @account.suspended? || domain_block&.reject_media?
  157. end
  158. def auto_suspend?
  159. domain_block&.suspend?
  160. end
  161. def auto_silence?
  162. domain_block&.silence?
  163. end
  164. def domain_block
  165. return @domain_block if defined?(@domain_block)
  166. @domain_block = DomainBlock.rule_for(@domain)
  167. end
  168. def key_changed?
  169. !@old_public_key.nil? && @old_public_key != @account.public_key
  170. end
  171. def clear_tombstones!
  172. Tombstone.where(account_id: @account.id).delete_all
  173. end
  174. def protocol_changed?
  175. !@old_protocol.nil? && @old_protocol != @account.protocol
  176. end
  177. def lock_options
  178. { redis: Redis.current, key: "process_account:#{@uri}" }
  179. end
  180. def process_tags
  181. return if @json['tag'].blank?
  182. as_array(@json['tag']).each do |tag|
  183. process_emoji tag if equals_or_includes?(tag['type'], 'Emoji')
  184. end
  185. end
  186. def process_attachments
  187. return if @json['attachment'].blank?
  188. previous_proofs = @account.identity_proofs.to_a
  189. current_proofs = []
  190. as_array(@json['attachment']).each do |attachment|
  191. next unless equals_or_includes?(attachment['type'], 'IdentityProof')
  192. current_proofs << process_identity_proof(attachment)
  193. end
  194. previous_proofs.each do |previous_proof|
  195. next if current_proofs.any? { |current_proof| current_proof.id == previous_proof.id }
  196. previous_proof.delete
  197. end
  198. end
  199. def process_emoji(tag)
  200. return if skip_download?
  201. return if tag['name'].blank? || tag['icon'].blank? || tag['icon']['url'].blank?
  202. shortcode = tag['name'].delete(':')
  203. image_url = tag['icon']['url']
  204. uri = tag['id']
  205. updated = tag['updated']
  206. emoji = CustomEmoji.find_by(shortcode: shortcode, domain: @account.domain)
  207. return unless emoji.nil? || image_url != emoji.image_remote_url || (updated && updated >= emoji.updated_at)
  208. emoji ||= CustomEmoji.new(domain: @account.domain, shortcode: shortcode, uri: uri)
  209. emoji.image_remote_url = image_url
  210. emoji.save
  211. end
  212. def process_identity_proof(attachment)
  213. provider = attachment['signatureAlgorithm']
  214. provider_username = attachment['name']
  215. token = attachment['signatureValue']
  216. @account.identity_proofs.where(provider: provider, provider_username: provider_username).find_or_create_by(provider: provider, provider_username: provider_username, token: token)
  217. end
  218. end