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.

86 lines
2.3 KiB

  1. require 'rails_helper'
  2. RSpec.describe ActivityPub::LinkedDataSignature do
  3. include JsonLdHelper
  4. let!(:sender) { Fabricate(:account, uri: 'http://example.com/alice') }
  5. let(:raw_json) do
  6. {
  7. '@context' => 'https://www.w3.org/ns/activitystreams',
  8. 'id' => 'http://example.com/hello-world',
  9. }
  10. end
  11. let(:json) { raw_json.merge('signature' => signature) }
  12. subject { described_class.new(json) }
  13. before do
  14. stub_jsonld_contexts!
  15. end
  16. describe '#verify_account!' do
  17. context 'when signature matches' do
  18. let(:raw_signature) do
  19. {
  20. 'creator' => 'http://example.com/alice',
  21. 'created' => '2017-09-23T20:21:34Z',
  22. }
  23. end
  24. let(:signature) { raw_signature.merge('type' => 'RsaSignature2017', 'signatureValue' => sign(sender, raw_signature, raw_json)) }
  25. it 'returns creator' do
  26. expect(subject.verify_account!).to eq sender
  27. end
  28. end
  29. context 'when signature is missing' do
  30. let(:signature) { nil }
  31. it 'returns nil' do
  32. expect(subject.verify_account!).to be_nil
  33. end
  34. end
  35. context 'when signature is tampered' do
  36. let(:raw_signature) do
  37. {
  38. 'creator' => 'http://example.com/alice',
  39. 'created' => '2017-09-23T20:21:34Z',
  40. }
  41. end
  42. let(:signature) { raw_signature.merge('type' => 'RsaSignature2017', 'signatureValue' => 's69F3mfddd99dGjmvjdjjs81e12jn121Gkm1') }
  43. it 'returns nil' do
  44. expect(subject.verify_account!).to be_nil
  45. end
  46. end
  47. end
  48. describe '#sign!' do
  49. subject { described_class.new(raw_json).sign!(sender) }
  50. it 'returns a hash' do
  51. expect(subject).to be_a Hash
  52. end
  53. it 'contains signature' do
  54. expect(subject['signature']).to be_a Hash
  55. expect(subject['signature']['signatureValue']).to be_present
  56. end
  57. it 'can be verified again' do
  58. expect(described_class.new(subject).verify_account!).to eq sender
  59. end
  60. end
  61. def sign(from_account, options, document)
  62. options_hash = Digest::SHA256.hexdigest(canonicalize(options.merge('@context' => ActivityPub::LinkedDataSignature::CONTEXT)))
  63. document_hash = Digest::SHA256.hexdigest(canonicalize(document))
  64. to_be_verified = options_hash + document_hash
  65. Base64.strict_encode64(from_account.keypair.sign(OpenSSL::Digest.new('SHA256'), to_be_verified))
  66. end
  67. end