fetch_remote_key_service.rb 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # frozen_string_literal: true
  2. class ActivityPub::FetchRemoteKeyService < BaseService
  3. include JsonLdHelper
  4. class Error < StandardError; end
  5. # Returns actor that owns the key
  6. def call(uri, id: true, prefetched_body: nil, suppress_errors: true)
  7. raise Error, 'No key URI given' if uri.blank?
  8. if prefetched_body.nil?
  9. if id
  10. @json = fetch_resource_without_id_validation(uri)
  11. if actor_type?
  12. @json = fetch_resource(@json['id'], true)
  13. elsif uri != @json['id']
  14. raise Error, "Fetched URI #{uri} has wrong id #{@json['id']}"
  15. end
  16. else
  17. @json = fetch_resource(uri, id)
  18. end
  19. else
  20. @json = body_to_json(prefetched_body, compare_id: id ? uri : nil)
  21. end
  22. raise Error, "Unable to fetch key JSON at #{uri}" if @json.nil?
  23. raise Error, "Unsupported JSON-LD context for document #{uri}" unless supported_context?(@json)
  24. raise Error, "Unexpected object type for key #{uri}" unless expected_type?
  25. return find_actor(@json['id'], @json, suppress_errors) if actor_type?
  26. @owner = fetch_resource(owner_uri, true)
  27. raise Error, "Unable to fetch actor JSON #{owner_uri}" if @owner.nil?
  28. raise Error, "Unsupported JSON-LD context for document #{owner_uri}" unless supported_context?(@owner)
  29. raise Error, "Unexpected object type for actor #{owner_uri} (expected any of: #{SUPPORTED_TYPES})" unless expected_owner_type?
  30. raise Error, "publicKey id for #{owner_uri} does not correspond to #{@json['id']}" unless confirmed_owner?
  31. find_actor(owner_uri, @owner, suppress_errors)
  32. rescue Error => e
  33. Rails.logger.debug { "Fetching key #{uri} failed: #{e.message}" }
  34. raise unless suppress_errors
  35. end
  36. private
  37. def find_actor(uri, prefetched_body, suppress_errors)
  38. actor = ActivityPub::TagManager.instance.uri_to_actor(uri)
  39. actor ||= ActivityPub::FetchRemoteActorService.new.call(uri, prefetched_body: prefetched_body, suppress_errors: suppress_errors)
  40. actor
  41. end
  42. def expected_type?
  43. actor_type? || public_key?
  44. end
  45. def actor_type?
  46. equals_or_includes_any?(@json['type'], ActivityPub::FetchRemoteActorService::SUPPORTED_TYPES)
  47. end
  48. def public_key?
  49. @json['publicKeyPem'].present? && @json['owner'].present?
  50. end
  51. def owner_uri
  52. @owner_uri ||= value_or_id(@json['owner'])
  53. end
  54. def expected_owner_type?
  55. equals_or_includes_any?(@owner['type'], ActivityPub::FetchRemoteActorService::SUPPORTED_TYPES)
  56. end
  57. def confirmed_owner?
  58. value_or_id(@owner['publicKey']) == @json['id']
  59. end
  60. end