1
0

claim_service.rb 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. # frozen_string_literal: true
  2. class Keys::ClaimService < BaseService
  3. HEADERS = { 'Content-Type' => 'application/activity+json' }.freeze
  4. class Result < ActiveModelSerializers::Model
  5. attributes :account, :device_id, :key_id,
  6. :key, :signature
  7. def initialize(account, device_id, key_attributes = {})
  8. @account = account
  9. @device_id = device_id
  10. @key_id = key_attributes[:key_id]
  11. @key = key_attributes[:key]
  12. @signature = key_attributes[:signature]
  13. end
  14. end
  15. def call(source_account, target_account_id, device_id)
  16. @source_account = source_account
  17. @target_account = Account.find(target_account_id)
  18. @device_id = device_id
  19. if @target_account.local?
  20. claim_local_key!
  21. else
  22. claim_remote_key!
  23. end
  24. rescue ActiveRecord::RecordNotFound
  25. nil
  26. end
  27. private
  28. def claim_local_key!
  29. device = @target_account.devices.find_by(device_id: @device_id)
  30. key = nil
  31. ApplicationRecord.transaction do
  32. key = device.one_time_keys.order(Arel.sql('random()')).first!
  33. key.destroy!
  34. end
  35. @result = Result.new(@target_account, @device_id, key)
  36. end
  37. def claim_remote_key!
  38. query_result = QueryService.new.call(@target_account)
  39. device = query_result.find(@device_id)
  40. return unless device.present? && device.valid_claim_url?
  41. json = fetch_resource_with_post(device.claim_url)
  42. return unless json.present? && json['publicKeyBase64'].present?
  43. @result = Result.new(@target_account, @device_id, key_id: json['id'], key: json['publicKeyBase64'], signature: json.dig('signature', 'signatureValue'))
  44. rescue HTTP::Error, OpenSSL::SSL::SSLError, Mastodon::Error => e
  45. Rails.logger.debug "Claiming one-time key for #{@target_account.acct}:#{@device_id} failed: #{e}"
  46. nil
  47. end
  48. def fetch_resource_with_post(uri)
  49. build_post_request(uri).perform do |response|
  50. raise Mastodon::UnexpectedResponseError, response unless response_successful?(response) || response_error_unsalvageable?(response)
  51. body_to_json(response.body_with_limit) if response.code == 200
  52. end
  53. end
  54. def build_post_request(uri)
  55. Request.new(:post, uri).tap do |request|
  56. request.on_behalf_of(@source_account, :uri)
  57. request.add_headers(HEADERS)
  58. end
  59. end
  60. end