summaryrefslogtreecommitdiff
path: root/spec/lib/gitlab/email/hook/smime_signature_interceptor_spec.rb
blob: 35aa663b0a52ea571d0c19114ce09e5fb26e3084 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
require 'spec_helper'

describe Gitlab::Email::Hook::SmimeSignatureInterceptor do
  include SmimeHelper

  # cert generation is an expensive operation and they are used read-only,
  # so we share them as instance variables in all tests
  before :context do
    @root_ca = generate_root
    @cert = generate_cert(root_ca: @root_ca)
  end

  let(:root_certificate) do
    Gitlab::Email::Smime::Certificate.new(@root_ca[:key], @root_ca[:cert])
  end

  let(:certificate) do
    Gitlab::Email::Smime::Certificate.new(@cert[:key], @cert[:cert])
  end

  let(:mail) do
    ActionMailer::Base.mail(to: 'test@example.com', from: 'info@example.com', body: 'signed hello')
  end

  before do
    allow(Gitlab::Email::Smime::Certificate).to receive_messages(from_files: certificate)

    Mail.register_interceptor(described_class)
    mail.deliver_now
  end

  after do
    Mail.unregister_interceptor(described_class)
  end

  it 'signs the email appropriately with SMIME' do
    expect(mail.header['To'].value).to eq('test@example.com')
    expect(mail.header['From'].value).to eq('info@example.com')
    expect(mail.header['Content-Type'].value).to match('multipart/signed').and match('protocol="application/x-pkcs7-signature"')

    # verify signature and obtain pkcs7 encoded content
    p7enc = Gitlab::Email::Smime::Signer.verify_signature(
      cert: certificate.cert,
      ca_cert: root_certificate.cert,
      signed_data: mail.encoded)

    # envelope in a Mail object and obtain the body
    decoded_mail = Mail.new(p7enc.data)

    expect(decoded_mail.body.encoded).to eq('signed hello')
  end
end