fetch_remote_key_service.rb 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. # frozen_string_literal: true
  2. class ActivityPub::FetchRemoteKeyService < BaseService
  3. include JsonLdHelper
  4. # Returns account that owns the key
  5. def call(uri, id: true, prefetched_body: nil)
  6. return if uri.blank?
  7. if prefetched_body.nil?
  8. if id
  9. @json = fetch_resource_without_id_validation(uri)
  10. if person?
  11. @json = fetch_resource(@json['id'], true)
  12. elsif uri != @json['id']
  13. return
  14. end
  15. else
  16. @json = fetch_resource(uri, id)
  17. end
  18. else
  19. @json = body_to_json(prefetched_body, compare_id: id ? uri : nil)
  20. end
  21. return unless supported_context?(@json) && expected_type?
  22. return find_account(@json['id'], @json) if person?
  23. @owner = fetch_resource(owner_uri, true)
  24. return unless supported_context?(@owner) && confirmed_owner?
  25. find_account(owner_uri, @owner)
  26. end
  27. private
  28. def find_account(uri, prefetched_body)
  29. account = ActivityPub::TagManager.instance.uri_to_resource(uri, Account)
  30. account ||= ActivityPub::FetchRemoteAccountService.new.call(uri, prefetched_body: prefetched_body)
  31. account
  32. end
  33. def expected_type?
  34. person? || public_key?
  35. end
  36. def person?
  37. equals_or_includes_any?(@json['type'], ActivityPub::FetchRemoteAccountService::SUPPORTED_TYPES)
  38. end
  39. def public_key?
  40. @json['publicKeyPem'].present? && @json['owner'].present?
  41. end
  42. def owner_uri
  43. @owner_uri ||= value_or_id(@json['owner'])
  44. end
  45. def confirmed_owner?
  46. equals_or_includes_any?(@owner['type'], ActivityPub::FetchRemoteAccountService::SUPPORTED_TYPES) && value_or_id(@owner['publicKey']) == @json['id']
  47. end
  48. end