# Copyright (C) 2012-2026 Zammad Foundation, https://zammad-foundation.org/

require 'rails_helper'

RSpec.describe SecureMailing::SMIME do
  before do
    Setting.set('smime_integration', true)
  end

  let(:raw_body) { 'Some text' }

  let(:system_email_address)      { 'smime1@example.com' }
  let(:customer_email_address)    { 'smime2@example.com' }
  let(:cc_customer_email_address) { 'smime3@example.com' }

  let(:sender_certificate_subject)       { "/C=DE/ST=Berlin/L=Berlin/O=Example Security/OU=IT Department/CN=example.com/emailAddress=#{sender_email_address}" }
  let(:recipient_certificate_subject)    { "/C=DE/ST=Berlin/L=Berlin/O=Example Security/OU=IT Department/CN=example.com/emailAddress=#{recipient_email_address}" }
  let(:cc_recipient_certificate_subject) { "/C=DE/ST=Berlin/L=Berlin/O=Example Security/OU=IT Department/CN=example.com/emailAddress=#{cc_recipient_email_address}" }

  let(:expired_email_address) { 'expiredsmime1@example.com' }

  let(:ca_certificate_subject) { '/emailAddress=RootCA@example.com/C=DE/ST=Berlin/L=Berlin/O=Example Security/OU=IT Department/CN=example.com' }

  let(:intermediate_ca_certificate_subject) { '/C=DE/ST=Berlin/O=Example Security/OU=IT Department/CN=example.com/emailAddress=IntermediateCA@example.com' }

  let(:content_type) { 'text/plain' }

  def build_mail
    Channel::EmailBuild.build(
      from:         sender_email_address,
      to:           recipient_email_address,
      cc:           cc_recipient_email_address,
      body:         raw_body,
      content_type: content_type,
      security:     security_preferences
    )
  end

  describe '.outgoing' do

    shared_examples 'HttpLog writer' do |status|

      it "logs #{status}" do
        expect do
          build_mail
        rescue
          # allow failures
        end.to change(HttpLog, :count).by(1)
        expect(HttpLog.last.attributes).to include('direction' => 'out', 'status' => status)
      end
    end

    let(:sender_email_address)       { system_email_address }
    let(:recipient_email_address)    { customer_email_address }
    let(:cc_recipient_email_address) { cc_customer_email_address }

    context 'without security' do
      let(:security_preferences) do
        nil
      end

      it 'builds mail' do
        expect(build_mail.body).not_to match(SecureMailing::SMIME::Incoming::EXPRESSION_SIGNATURE)
        expect(build_mail.body).not_to match(SecureMailing::SMIME::Incoming::EXPRESSION_MIME)
        expect(build_mail.body).to eq(raw_body)
      end
    end

    context 'signing' do

      let(:security_preferences) do
        {
          type:       'S/MIME',
          sign:       {
            success: true,
          },
          encryption: {
            success: false,
          },
        }
      end

      context 'private key present' do

        let!(:sender_certificate) do
          create(:smime_certificate, :with_private, fixture: system_email_address)
        end

        it 'builds mail' do
          expect(build_mail.body).to match(SecureMailing::SMIME::Incoming::EXPRESSION_SIGNATURE)
        end

        it_behaves_like 'HttpLog writer', 'success'

        context 'expired certificate' do
          let(:system_email_address) { expired_email_address }

          it 'raises exception' do
            expect { build_mail }.to raise_error SecureMailing::Backend::Handler::SigningError
          end

          it_behaves_like 'HttpLog writer', 'failed'
        end

        context 'when message is 7bit or 8bit encoded' do

          let(:mail) do
            smime_mail = build_mail

            mail = Channel::EmailParser.new.parse(smime_mail.to_s)
            SecureMailing.incoming(mail)

            mail
          end

          context 'when Content-Type is text/plain' do
            let(:raw_body) { "\r\n\r\n@john.doe, now known as John Dóe has accepted your invitation to join the Administrator / htmltest project.\r\n\r\nhttp://169.254.169.254:3000/root/htmltest\r\n\r\n-- \r\nYou're receiving this email because of your account on 169.254.169.254.\r\n\r\n\r\n\r\n" }

            it 'verifies' do
              expect(mail['x-zammad-article-preferences']['security']['sign']['success']).to be true
            end
          end

          context 'when Content-Type is text/html' do
            let(:content_type) { 'text/html' }
            let(:raw_body) { "<div><ul><li><p>an \nexample „Text“ with ümläütß. </p></li></ul></div>" }

            it 'verifies' do
              expect(mail['x-zammad-article-preferences']['security']['sign']['success']).to be true
            end
          end
        end

        context 'when attachment has message/rfc822 content type' do

          let(:mail) do
            smime_mail = Channel::EmailBuild.build(
              from:         sender_email_address,
              to:           recipient_email_address,
              body:         raw_body,
              content_type: 'text/plain',
              security:     security_preferences,
              attachments:  [
                {
                  content_type: 'message/rfc822',
                  content:      "From: other@example.com\r\nSubject: Nested\r\n\r\nNested body",
                  filename:     'nested.eml',
                },
              ],
            )

            mail = Channel::EmailParser.new.parse(smime_mail.to_s)
            SecureMailing.incoming(mail)

            mail
          end

          it 'verifies the signature' do
            expect(mail['x-zammad-article-preferences']['security']['sign']['success']).to be true
          end
        end

        context 'when certificate chain is present' do
          let(:system_email_address) { 'chain@example.com' }

          let!(:chain) do
            [
              sender_certificate,
              create(:smime_certificate, fixture: 'IntermediateCA'),
              create(:smime_certificate, fixture: 'RootCA'),
            ]
          end

          let(:p7enc) do
            mail = Channel::EmailParser.new.parse(build_mail.to_s)
            OpenSSL::PKCS7.read_smime(mail[:raw])
          end

          it 'is included in the generated mail' do
            expect(p7enc.certificates.map(&:subject).sort).to eq(chain.map { |x| x.parsed.subject }.sort)
          end
        end
      end

      context 'no private key present' do
        before do
          create(:smime_certificate, fixture: system_email_address)
        end

        it 'raises exception' do
          expect { build_mail }.to raise_error SecureMailing::Backend::Handler::SigningError
        end

        it_behaves_like 'HttpLog writer', 'failed'
      end
    end

    context 'encryption' do

      let(:security_preferences) do
        {
          type:       'S/MIME',
          sign:       {
            success: false,
          },
          encryption: {
            success: true,
          },
        }
      end

      context 'public key present' do
        before do
          create(:smime_certificate, fixture: recipient_email_address)
          create(:smime_certificate, fixture: cc_recipient_email_address)
        end

        it 'builds mail' do
          mail = build_mail

          expect(mail['Content-Type'].value).to match(SecureMailing::SMIME::Incoming::EXPRESSION_MIME)
          expect(mail.body).not_to include(raw_body)
        end

        it_behaves_like 'HttpLog writer', 'success'

        context 'expired certificate' do

          let(:recipient_email_address) { expired_email_address }

          it 'raises exception' do
            expect { build_mail }.to raise_error RuntimeError
          end

          it_behaves_like 'HttpLog writer', 'failed'
        end
      end

      context 'no public key present' do

        it 'raises exception' do
          expect { build_mail }.to raise_error ActiveRecord::RecordNotFound
        end

        it_behaves_like 'HttpLog writer', 'failed'
      end
    end
  end

  describe '.incoming' do

    shared_examples 'HttpLog writer' do |status|

      it "logs #{status}" do
        expect do
          mail
        rescue
          # allow failures
        end.to change(HttpLog, :count).by(2)
        expect(HttpLog.last.attributes).to include('direction' => 'in', 'status' => status)
      end
    end

    let(:sender_email_address)       { customer_email_address }
    let(:recipient_email_address)    { system_email_address }
    let(:cc_recipient_email_address) { cc_customer_email_address }

    context 'signature verification' do

      let(:allow_expired) { false }

      let(:security_preferences) do
        {
          type:       'S/MIME',
          sign:       {
            success:       true,
            allow_expired: allow_expired,
          },
          encryption: {
            success: false,
          },
        }
      end

      context 'opaque signature, sender certificate not in store' do
        let(:mail) do
          smime_mail = Rails.root.join('spec/fixtures/files/smime/opaque_sender_not_in_store.eml').read
          mail = Channel::EmailParser.new.parse(smime_mail.to_s)
          SecureMailing.incoming(mail)

          mail
        end

        it 'shows the content and marks the signature as unverified' do
          expect(mail[:body]).to include('Some text')
          expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be false
          expect(mail['x-zammad-article-preferences'][:security][:sign][:comment]).to eq('The certificate for verification could not be found.')
          expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be false
          expect(mail['x-zammad-article-preferences'][:security][:encryption][:comment]).to be_nil
        end
      end

      context 'opaque signature, signer certificate not bundled in the mail' do
        let(:mail) do
          smime_mail = Rails.root.join('spec/fixtures/files/smime/opaque_no_bundled_signer_cert.eml').read
          mail = Channel::EmailParser.new.parse(smime_mail.to_s)
          SecureMailing.incoming(mail)

          mail
        end

        it 'still shows the content and marks the signature as unverified' do
          expect(mail[:body]).to include('Some text')
          expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be false
          expect(mail['x-zammad-article-preferences'][:security][:sign][:comment]).to eq('The certificate for verification could not be found.')
        end
      end

      # The encapsulated content of an opaque signature is parsed and shown even for an unknown
      # signer; X-Zammad headers are not taken from that content.
      context 'opaque signature with X-Zammad headers in the content' do
        let(:mail) do
          signer_key  = OpenSSL::PKey::RSA.new(2048)
          signer_cert = OpenSSL::X509::Certificate.new
          signer_cert.version    = 2
          signer_cert.serial     = 1
          signer_cert.subject    = OpenSSL::X509::Name.parse("/CN=example.com/emailAddress=#{sender_email_address}")
          signer_cert.issuer     = signer_cert.subject
          signer_cert.public_key = signer_key.public_key
          signer_cert.not_before = Time.zone.now
          signer_cert.not_after  = 1.hour.from_now
          signer_cert.sign(signer_key, OpenSSL::Digest.new('SHA256'))

          # The signed content is a MIME entity that also carries X-Zammad headers.
          signed_content = <<~SIGNED.gsub(%r{\n}, "\r\n")
            Content-Type: text/plain
            X-Zammad-Ticket-Id: 99999
            X-Zammad-Session-User-Id: 1
            X-Zammad-Ticket-Followup-Customer: customer@example.com
            X-Zammad-Article-Internal: true

            Secured opaque body
          SIGNED

          # Flag 0 (no DETACHED) produces an opaque signature with the content embedded.
          p7         = OpenSSL::PKCS7.sign(signer_cert, signer_key, signed_content, [], 0)
          smime_body = OpenSSL::PKCS7.write_smime(p7)
          smime_mail = "From: #{sender_email_address}\r\nTo: #{recipient_email_address}\r\nSubject: test\r\n#{smime_body}"

          mail = Channel::EmailParser.new.parse(smime_mail)
          SecureMailing.incoming(mail)

          mail
        end

        it 'shows the content but does not adopt its X-Zammad headers' do
          expect(mail[:body]).to include('Secured opaque body')
          expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be false
          expect(mail[:'x-zammad-ticket-id']).to be_nil
          expect(mail[:'x-zammad-session-user-id']).to be_nil
          expect(mail[:'x-zammad-ticket-followup-customer']).to be_nil
          expect(mail[:'x-zammad-article-internal']).to be_nil
          # The `raw-*` header twins are not adopted either.
          expect(mail['raw-x-zammad-ticket-id']).to be_nil
        end
      end

      # Sender and routing headers are kept from the original mail, while the subject is still
      # taken from the content (RFC 8551 protected headers).
      context 'opaque signature with sender and routing headers in the content' do
        let(:mail) do
          signer_key  = OpenSSL::PKey::RSA.new(2048)
          signer_cert = OpenSSL::X509::Certificate.new
          signer_cert.version    = 2
          signer_cert.serial     = 1
          signer_cert.subject    = OpenSSL::X509::Name.parse("/CN=example.com/emailAddress=#{sender_email_address}")
          signer_cert.issuer     = signer_cert.subject
          signer_cert.public_key = signer_key.public_key
          signer_cert.not_before = Time.zone.now
          signer_cert.not_after  = 1.hour.from_now
          signer_cert.sign(signer_key, OpenSSL::Digest.new('SHA256'))

          signed_content = <<~SIGNED.gsub(%r{\n}, "\r\n")
            Content-Type: text/plain
            From: inner@example.com
            Reply-To: inner@example.com
            To: other-group@example.com
            References: <inner-thread@example.com>
            Message-ID: <inner-msgid@example.com>
            Subject: protected inner subject

            Secured opaque body
          SIGNED

          p7         = OpenSSL::PKCS7.sign(signer_cert, signer_key, signed_content, [], 0)
          smime_body = OpenSSL::PKCS7.write_smime(p7)
          smime_mail = "From: #{sender_email_address}\r\nTo: #{recipient_email_address}\r\nSubject: outer subject\r\n#{smime_body}"

          mail = Channel::EmailParser.new.parse(smime_mail)
          SecureMailing.incoming(mail)

          mail
        end

        it 'keeps the outer sender and routing but still adopts the protected subject' do
          expect(mail[:body]).to include('Secured opaque body')
          # Sender / routing identity is kept from the original mail.
          expect(mail[:from]).to eq(sender_email_address)
          expect(mail[:from_email]).to eq(sender_email_address)
          expect(mail[:'reply-to']).to be_nil
          expect(mail[:to]).to eq(recipient_email_address)
          # Threading identity (used to select/link tickets) is not taken from the content.
          expect(mail[:references]).to be_nil
          expect(mail[:message_id]).not_to include('inner-msgid')
          # The encrypted Subject is a protected header and is still adopted.
          expect(mail[:subject]).to eq('protected inner subject')
        end
      end

      # A case-variant X-Zammad name and its raw- twin are not adopted either.
      context 'opaque signature with a case-variant X-Zammad header' do
        let(:mail) do
          signer_key  = OpenSSL::PKey::RSA.new(2048)
          signer_cert = OpenSSL::X509::Certificate.new
          signer_cert.version    = 2
          signer_cert.serial     = 1
          signer_cert.subject    = OpenSSL::X509::Name.parse("/CN=example.com/emailAddress=#{sender_email_address}")
          signer_cert.issuer     = signer_cert.subject
          signer_cert.public_key = signer_key.public_key
          signer_cert.not_before = Time.zone.now
          signer_cert.not_after  = 1.hour.from_now
          signer_cert.sign(signer_key, OpenSSL::Digest.new('SHA256'))

          signed_content = <<~SIGNED.gsub(%r{\n}, "\r\n")
            Content-Type: text/plain
            X-ZaMmAd-Ticket-Id: 88888

            Secured opaque body
          SIGNED

          p7         = OpenSSL::PKCS7.sign(signer_cert, signer_key, signed_content, [], 0)
          smime_body = OpenSSL::PKCS7.write_smime(p7)
          smime_mail = "From: #{sender_email_address}\r\nTo: #{recipient_email_address}\r\nSubject: test\r\n#{smime_body}"

          mail = Channel::EmailParser.new.parse(smime_mail)
          SecureMailing.incoming(mail)

          mail
        end

        it 'does not adopt case-variant or raw- X-Zammad headers' do
          expect(mail[:body]).to include('Secured opaque body')
          expect(mail[:'x-zammad-ticket-id']).to be_nil
          expect(mail['raw-x-zammad-ticket-id']).to be_nil
        end
      end

      context 'opaque signature mislabelled as signed-data but actually encrypted' do
        before do
          create(:smime_certificate, fixture: recipient_email_address)
        end

        let(:mail) do
          smime_mail = Channel::EmailBuild.build(
            from:         sender_email_address,
            to:           recipient_email_address,
            body:         raw_body,
            content_type: 'text/plain',
            security:     {
              type:       'S/MIME',
              sign:       { success: false },
              encryption: { success: true },
            },
          )
          smime_mail.header['Content-Type'] = 'application/pkcs7-mime; smime-type=signed-data; name="smime.p7m"'

          mail = Channel::EmailParser.new.parse(smime_mail.to_s)
          SecureMailing.incoming(mail)

          mail
        end

        it 'keeps the payload reachable as attachment instead of wiping the mail' do
          expect(mail[:attachments].any? { |attachment| attachment[:filename] == 'smime.p7m' }).to be(true)
          expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be(false)
        end
      end

      context 'opaque signature with mixed-case smime-type' do
        before do
          create(:smime_certificate, :with_private, fixture: sender_email_address)
          stub_const('OpenSSL::PKCS7::DETACHED', nil)
        end

        let(:mail) do
          smime_mail = build_mail
          smime_mail.header['Content-Type'] = smime_mail.header['Content-Type'].to_s.sub('signed-data', 'Signed-Data')

          mail = Channel::EmailParser.new.parse(smime_mail.to_s)
          SecureMailing.incoming(mail)

          mail
        end

        it 'treats it as signed instead of encrypted' do
          expect(mail[:body]).to include(raw_body)
          expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be(true)
          expect(mail['x-zammad-article-preferences'][:security][:encryption][:comment]).to be_nil
        end
      end

      context 'sender certificate present' do

        before do
          create(:smime_certificate, :with_private, fixture: sender_email_address)
        end

        let(:mail) do
          smime_mail = build_mail
          mail = Channel::EmailParser.new.parse(smime_mail.to_s)
          SecureMailing.incoming(mail)

          mail
        end

        it 'verifies' do
          expect(mail[:body]).to include(raw_body)
          expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be true
          expect(mail['x-zammad-article-preferences'][:security][:sign][:comment]).to eq(sender_certificate_subject)
          expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be false
          expect(mail['x-zammad-article-preferences'][:security][:encryption][:comment]).to be_nil
        end

        it_behaves_like 'HttpLog writer', 'success'

        context 'expired' do

          # required to build mail with expired certificate
          let(:allow_expired)        { true }
          let(:sender_email_address) { expired_email_address }

          it 'verifies with comment' do
            expect(mail[:body]).to include(raw_body)
            expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be true
            expect(mail['x-zammad-article-preferences'][:security][:sign][:comment]).to include(expired_email_address).and include('expired')
            # The signer certificate is also the directly-stored `existing_cert` here, so it must
            # only be annotated once, not once from `existing_certs` and again as the signer.
            expect(mail['x-zammad-article-preferences'][:security][:sign][:comment].scan('expired!').size).to eq(1)
            expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be false
            expect(mail['x-zammad-article-preferences'][:security][:encryption][:comment]).to be_nil
          end

          it_behaves_like 'HttpLog writer', 'success'
        end

        context 'with wrapped mime-type S/MIME signature (e.g. for Microsoft Outlook)' do
          before do
            # We need to disable the open ssl detached flag, to force the smime-type with 'signed-data'.
            stub_const('OpenSSL::PKCS7::DETACHED', nil)
          end

          it 'check that mail was verified' do
            expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be true
          end

          it 'check that signe comment exists' do
            expect(mail['x-zammad-article-preferences'][:security][:sign][:comment]).to eq(sender_certificate_subject)
          end

          it 'check that body was verified' do
            expect(mail[:body]).to include(raw_body)
          end

          it 'check that it is not treated as encrypted' do
            expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be false
            expect(mail['x-zammad-article-preferences'][:security][:encryption][:comment]).to be_nil
          end
        end

        context 'sender is signer' do
          let(:sender_email_address) { system_email_address }
          let(:mail) do
            smime_mail = Rails.root.join('spec/fixtures/files/smime/sender_is_signer.eml').read
            mail = Channel::EmailParser.new.parse(smime_mail.to_s)
            SecureMailing.incoming(mail)

            mail
          end

          it 'verifies' do
            expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be true
            expect(mail['x-zammad-article-preferences'][:security][:sign][:comment]).to eq(sender_certificate_subject)
            expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be false
            expect(mail['x-zammad-article-preferences'][:security][:encryption][:comment]).to be_nil
          end
        end

        context 'sender is signer, with upcased sender address' do
          let(:sender_email_address) { system_email_address }
          let(:mail) do
            smime_mail = Rails.root.join('spec/fixtures/files/smime/sender_is_signer.eml').read.sub('smime1@example.com', 'SMIME1@example.com')
            mail = Channel::EmailParser.new.parse(smime_mail.to_s)
            SecureMailing.incoming(mail)

            mail
          end

          it 'verifies' do
            expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be true
            expect(mail['x-zammad-article-preferences'][:security][:sign][:comment]).to eq(sender_certificate_subject)
            expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be false
            expect(mail['x-zammad-article-preferences'][:security][:encryption][:comment]).to be_nil
          end
        end

        context 'sender is not signer' do
          before do
            create(:smime_certificate, :with_private, fixture: system_email_address)
          end

          let(:mail) do
            smime_mail = Rails.root.join('spec/fixtures/files/smime/sender_not_signer.eml').read
            mail = Channel::EmailParser.new.parse(smime_mail.to_s)
            SecureMailing.incoming(mail)

            mail
          end

          it 'verifies with comment' do
            expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be false
            expect(mail['x-zammad-article-preferences'][:security][:sign][:comment]).to eq('This message was not signed by its sender.')
            expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be false
            expect(mail['x-zammad-article-preferences'][:security][:encryption][:comment]).to be_nil
          end
        end

        # The sender comparison uses the envelope From, which is also what the article is
        # attributed to, and not the From of the re-parsed content.
        context 'opaque signature with a From header in the content' do
          let(:mail) do
            signer_key  = OpenSSL::PKey::RSA.new(Rails.root.join("spec/fixtures/files/smime/#{sender_email_address}.key").read,
                                                 Rails.root.join("spec/fixtures/files/smime/#{sender_email_address}.secret").read.strip)
            signer_cert = OpenSSL::X509::Certificate.new(Rails.root.join("spec/fixtures/files/smime/#{sender_email_address}.crt").read)

            signed_content = <<~SIGNED.gsub(%r{\n}, "\r\n")
              Content-Type: text/plain
              From: #{sender_email_address}
              Subject: protected inner subject

              #{raw_body}
            SIGNED

            p7         = OpenSSL::PKCS7.sign(signer_cert, signer_key, signed_content, [], 0)
            smime_body = OpenSSL::PKCS7.write_smime(p7)
            smime_mail = "From: #{cc_customer_email_address}\r\nTo: #{recipient_email_address}\r\nSubject: outer subject\r\n#{smime_body}"

            mail = Channel::EmailParser.new.parse(smime_mail)
            SecureMailing.incoming(mail)

            mail
          end

          it 'compares the signer against the envelope sender' do
            expect(mail[:from]).to eq(cc_customer_email_address)
            expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be false
            expect(mail['x-zammad-article-preferences'][:security][:sign][:comment]).to eq('This message was not signed by its sender.')
            expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be false
            expect(mail['x-zammad-article-preferences'][:security][:encryption][:comment]).to be_nil
          end
        end

        context 'sender certificate with another sender name signed by trusted CA (#4457)' do
          before do
            create(:smime_certificate, fixture: 'SenderCA')
          end

          let(:mail) do
            smime_mail = Rails.root.join('spec/fixtures/files/smime/sender_is_signer_with_ca.eml').read
            mail = Channel::EmailParser.new.parse(smime_mail.to_s)
            SecureMailing.incoming(mail)

            mail
          end

          it 'verifies' do
            expect(mail[:from]).to include('Zammad Helpdesk <smime-sender-ca@example.com>')
            expect(mail[:body]).to include(raw_body)
            expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be true
            expect(mail['x-zammad-article-preferences'][:security][:sign][:comment]).to eq('/emailAddress=SenderCA@example.com/C=DE/ST=Berlin/L=Berlin/O=Example Security/OU=IT Department/CN=example.com')
            expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be false
            expect(mail['x-zammad-article-preferences'][:security][:encryption][:comment]).to be_nil
          end
        end

        context 'forged certificate cloning a stored subject and email' do
          let(:sender_email_address) { system_email_address }

          let(:mail) do
            smime_mail = Rails.root.join('spec/fixtures/files/smime/forged_cloned_subject.eml').read
            mail = Channel::EmailParser.new.parse(smime_mail.to_s)
            SecureMailing.incoming(mail)

            mail
          end

          it 'does not verify, even though the forged certificate reuses the trusted subject and email' do
            expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be false
            expect(mail['x-zammad-article-preferences'][:security][:sign][:comment]).to eq('The certificate for verification could not be found.')
            expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be false
            expect(mail['x-zammad-article-preferences'][:security][:encryption][:comment]).to be_nil
          end
        end

        context 'genuinely signed mail bundling an extra forged certificate that clones a different trusted subject' do
          before do
            create(:smime_certificate, fixture: system_email_address)
          end

          let(:mail) do
            smime_mail = Rails.root.join('spec/fixtures/files/smime/forged_extra_certificate.eml').read
            mail = Channel::EmailParser.new.parse(smime_mail.to_s)
            SecureMailing.incoming(mail)

            mail
          end

          it 'does not verify, even though the message is genuinely signed by its own trusted certificate' do
            expect(mail[:from]).to include('Attacker <smime1@example.com>')
            expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be false
            expect(mail['x-zammad-article-preferences'][:security][:sign][:comment]).to eq('This message was not signed by its sender.')
            expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be false
            expect(mail['x-zammad-article-preferences'][:security][:encryption][:comment]).to be_nil
          end
        end

        context 'excessive number of bundled certificates (potential DoS)' do
          let(:sender_email_address) { system_email_address }

          let(:mail) do
            body       = raw_body
            signer_key = OpenSSL::PKey::RSA.new(Rails.root.join('spec/fixtures/files/smime/smime1@example.com.key').read, '1234')

            signer_cert = OpenSSL::X509::Certificate.new(Rails.root.join('spec/fixtures/files/smime/smime1@example.com.crt').read)

            filler_certs = Array.new(SecureMailing::SMIME::Incoming::MAX_BUNDLED_CERTIFICATES + 1) do |i|
              key  = OpenSSL::PKey::RSA.new(512)
              cert = OpenSSL::X509::Certificate.new
              cert.version     = 2
              cert.serial      = i + 100
              cert.subject     = OpenSSL::X509::Name.parse("/CN=filler-#{i}")
              cert.issuer      = cert.subject
              cert.public_key  = key.public_key
              cert.not_before  = Time.zone.now
              cert.not_after   = 1.hour.from_now
              cert.sign(key, OpenSSL::Digest.new('SHA256'))
              cert
            end

            p7         = OpenSSL::PKCS7.sign(signer_cert, signer_key, body, filler_certs, OpenSSL::PKCS7::DETACHED)
            smime_body = OpenSSL::PKCS7.write_smime(p7, body)
            smime_mail = "From: #{sender_email_address}\r\nTo: #{recipient_email_address}\r\nSubject: test\r\n#{smime_body}"

            mail = Channel::EmailParser.new.parse(smime_mail)
            SecureMailing.incoming(mail)

            mail
          end

          it 'fails closed instead of running the expensive per-certificate check on every bundled certificate' do
            expect(Timeout.timeout(5) { mail }).to be_present
            expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be false
          end
        end

        context 'expired signer certificate trusted via a still-valid CA chain' do
          before do
            create(:smime_certificate, fixture: 'SenderCA')
            create(:smime_certificate, fixture: 'SenderIntermediateCA')
          end

          let(:mail) do
            body       = raw_body
            inter_key  = OpenSSL::PKey::RSA.new(Rails.root.join('spec/fixtures/files/smime/SenderIntermediateCA.key').read)
            inter_cert = OpenSSL::X509::Certificate.new(Rails.root.join('spec/fixtures/files/smime/SenderIntermediateCA.crt').read)

            leaf_key = OpenSSL::PKey::RSA.new(2048)
            leaf     = OpenSSL::X509::Certificate.new
            leaf.version    = 2
            leaf.serial     = 555
            leaf.subject    = OpenSSL::X509::Name.parse('/C=DE/ST=Berlin/L=Berlin/O=Example Security/OU=IT Department/CN=example.com/emailAddress=expired-leaf@example.com')
            leaf.issuer     = inter_cert.subject
            leaf.public_key = leaf_key.public_key
            leaf.not_before = Time.utc(2010, 1, 1)
            leaf.not_after  = Time.utc(2011, 1, 1)

            extension_factory = OpenSSL::X509::ExtensionFactory.new
            extension_factory.subject_certificate = leaf
            extension_factory.issuer_certificate  = inter_cert
            leaf.add_extension(extension_factory.create_extension('subjectAltName', 'email:expired-leaf@example.com'))
            leaf.sign(inter_key, OpenSSL::Digest.new('SHA256'))

            p7         = OpenSSL::PKCS7.sign(leaf, leaf_key, body, [inter_cert], OpenSSL::PKCS7::DETACHED)
            smime_body = OpenSSL::PKCS7.write_smime(p7, body)
            smime_mail = "From: expired-leaf@example.com\r\nTo: #{recipient_email_address}\r\nSubject: test\r\n#{smime_body}"

            mail = Channel::EmailParser.new.parse(smime_mail)
            SecureMailing.incoming(mail)

            mail
          end

          it 'verifies, but reports the actual signer certificate as expired' do
            expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be true
            expect(mail['x-zammad-article-preferences'][:security][:sign][:comment]).to include('SenderIntermediateCA@example.com').and include('expired!')
          end
        end
      end

      context 'no sender certificate' do

        let!(:sender_certificate) { create(:smime_certificate, :with_private, fixture: sender_email_address) }

        let(:mail) do
          smime_mail = build_mail
          mail       = Channel::EmailParser.new.parse(smime_mail.to_s)

          sender_certificate.destroy!

          SecureMailing.incoming(mail)

          mail
        end

        it 'fails' do
          expect(mail[:body]).to include(raw_body)
          expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be false
          expect(mail['x-zammad-article-preferences'][:security][:sign][:comment]).to eq('The certificate for verification could not be found.')
          expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be false
          expect(mail['x-zammad-article-preferences'][:security][:encryption][:comment]).to be_nil
        end

        context 'when the mail is not containing the certificate chain but Intermediate CA is present on incoming mails (#5357)' do
          let(:ca_fixture) { 'IntermediateCA' }

          context 'when present in the SMIME store' do
            let(:mail) do
              smime_mail = build_mail
              mail       = Channel::EmailParser.new.parse(smime_mail.to_s)

              sender_certificate.destroy!
              create(:smime_certificate, fixture: ca_fixture)

              SecureMailing.incoming(mail)

              mail
            end

            it 'does verify' do
              expect(mail[:body]).to include(raw_body)
              expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be true
              expect(mail['x-zammad-article-preferences'][:security][:sign][:comment]).to eq(intermediate_ca_certificate_subject)
              expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be false
              expect(mail['x-zammad-article-preferences'][:security][:encryption][:comment]).to be_nil
            end
          end

          context 'when present in the SSL store' do
            let(:mail) do
              smime_mail = build_mail
              mail       = Channel::EmailParser.new.parse(smime_mail.to_s)

              sender_certificate.destroy!
              create(:ssl_certificate, fixture: ca_fixture)

              SecureMailing.incoming(mail)

              mail
            end

            it 'does verify' do
              expect(mail[:body]).to include(raw_body)
              expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be true
              expect(mail['x-zammad-article-preferences'][:security][:sign][:comment]).to eq(intermediate_ca_certificate_subject)
              expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be false
              expect(mail['x-zammad-article-preferences'][:security][:encryption][:comment]).to be_nil
            end
          end
        end

        context 'public key present in signature' do

          let(:not_related_fixture)      { 'smime3@example.com' }
          let!(:not_related_certificate) { create(:smime_certificate, fixture: not_related_fixture) }

          context 'not related certificate present' do

            it 'fails' do
              expect(mail[:body]).to include(raw_body)
              expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be false
              expect(mail['x-zammad-article-preferences'][:security][:sign][:comment]).to eq('The certificate for verification could not be found.')
              expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be false
              expect(mail['x-zammad-article-preferences'][:security][:encryption][:comment]).to be_nil
            end

            it_behaves_like 'HttpLog writer', 'failed'

            context 'CA' do

              let(:not_related_fixture) { 'ExpiredCA' }

              it 'fails' do
                expect(mail[:body]).to include(raw_body)
                expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be false
                expect(mail['x-zammad-article-preferences'][:security][:sign][:comment]).to eq('The certificate for verification could not be found.')
                expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be false
                expect(mail['x-zammad-article-preferences'][:security][:encryption][:comment]).to be_nil
              end

              it_behaves_like 'HttpLog writer', 'failed'
            end
          end

          context 'usage not prevented' do

            before do
              # remove OpenSSL::PKCS7::NOINTERN
              stub_const('SecureMailing::SMIME::Incoming::OPENSSL_PKCS7_VERIFY_FLAGS', OpenSSL::PKCS7::NOVERIFY)
            end

            it 'does not perform verification' do
              expect(mail[:body]).to include(raw_body)
              expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be false
              expect(mail['x-zammad-article-preferences'][:security][:sign][:comment]).to eq('The certificate for verification could not be found.')
              expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be false
              expect(mail['x-zammad-article-preferences'][:security][:encryption][:comment]).to be_nil
            end
          end
        end

        context 'intermediate CA present' do

          before do
            create(:smime_certificate, fixture: ca_fixture)
          end

          let(:ca_fixture) { 'IntermediateCA' }

          it 'verifies' do
            expect(mail[:body]).to include(raw_body)
            expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be true
            expect(mail['x-zammad-article-preferences'][:security][:sign][:comment]).to eq(intermediate_ca_certificate_subject)
            expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be false
            expect(mail['x-zammad-article-preferences'][:security][:encryption][:comment]).to be_nil
          end

          it_behaves_like 'HttpLog writer', 'success'

          context 'expired' do
            let(:ca_fixture) { 'ExpiredIntermediateCA' }

            it 'fails' do
              expect(mail[:body]).to include(raw_body)
              expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be false
              expect(mail['x-zammad-article-preferences'][:security][:sign][:comment]).to eq('The certificate for verification could not be found.')
              expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be false
              expect(mail['x-zammad-article-preferences'][:security][:encryption][:comment]).to be_nil
            end

            it_behaves_like 'HttpLog writer', 'failed'

            context 'allowed' do

              let(:allow_expired) { true }

              # ATTENTION: expired CA is a special case where `allow_expired` does not count
              it 'fails' do
                expect(mail[:body]).to include(raw_body)
                expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be false
                expect(mail['x-zammad-article-preferences'][:security][:sign][:comment]).to eq('The certificate for verification could not be found.')
                expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be false
                expect(mail['x-zammad-article-preferences'][:security][:encryption][:comment]).to be_nil
              end

              it_behaves_like 'HttpLog writer', 'failed'
            end
          end
        end

        context 'certificate chain' do
          let(:sender_email_address) { 'chain@example.com' }
          let(:ca_subject_chain) { ca_chain.reverse.map { |cert| cert.parsed.subject }.join(', ') }

          context 'incomplete certificate chain present' do

            before do
              create(:smime_certificate, fixture: 'RootCA')
            end

            it 'fails' do
              expect(mail[:body]).to include(raw_body)
              expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be false
              expect(mail['x-zammad-article-preferences'][:security][:sign][:comment]).to eq('The certificate for verification could not be found.')
              expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be false
              expect(mail['x-zammad-article-preferences'][:security][:encryption][:comment]).to be_nil
            end
          end

          context 'certificate chain only partly present' do
            let(:ca_certificate_subject) { subject_chain }

            let!(:ca_chain) do
              create_list(:smime_certificate, 1, fixture: 'IntermediateCA')
            end

            it 'verifies' do
              expect(mail[:body]).to include(raw_body)
              expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be true
              expect(mail['x-zammad-article-preferences'][:security][:sign][:comment]).to eq(ca_subject_chain)
              expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be false
              expect(mail['x-zammad-article-preferences'][:security][:encryption][:comment]).to be_nil
            end
          end

          context 'complete certificate chain present' do
            let!(:ca_chain) do
              create_list(:smime_certificate, 1, fixture: 'ChainCA')
            end

            it 'verifies' do
              allow(Rails.logger).to receive(:warn)

              expect(mail[:body]).to include(raw_body)
              expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be true
              expect(mail['x-zammad-article-preferences'][:security][:sign][:comment]).to eq(ca_subject_chain)
              expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be false
              expect(mail['x-zammad-article-preferences'][:security][:encryption][:comment]).to be_nil

              expect(Rails.logger).not_to have_received(:warn).with(%r{#{Regexp.escape(ca_certificate_subject)}})
            end
          end
        end
      end

      context 'when verification encounters an error (#6217)' do
        let(:raw_body) do
          <<~BODY
            Some text

            Test Admin Agent

            --
            Super Support - Waterford Business Park
            5201 Blue Lagoon Drive - 8th Floor & 9th Floor - Miami, 33126 USA
            Email: hot@example.com - Web: [1] http://www.example.com/
            --
          BODY
        end

        let(:mail) do
          smime_mail = Rails.root.join('spec/fixtures/files/smime/wrong_mime_type.eml').read
          mail = Channel::EmailParser.new.parse(smime_mail.to_s)
          SecureMailing.incoming(mail)

          mail
        end

        it 'fails' do
          expect(mail[:body]).to include(raw_body)
          expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be false
          expect(mail['x-zammad-article-preferences'][:security][:sign][:comment]).to eq('Error while verifying signature, please contact your administrator.')
          expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be false
          expect(mail['x-zammad-article-preferences'][:security][:encryption][:comment]).to be_nil
        end
      end
    end

    context 'decryption' do

      let(:allow_expired) { false }
      let(:security_preferences) do
        {
          type:       'S/MIME',
          sign:       {
            success: false,
          },
          encryption: {
            success:       true,
            allow_expired: allow_expired,
          },
        }
      end

      let!(:sender_certificate)       { create(:smime_certificate, :with_private, fixture: sender_email_address) }
      let!(:recipient_certificate)    { create(:smime_certificate, :with_private, fixture: recipient_email_address) }
      let!(:cc_recipient_certificate) { create(:smime_certificate, :with_private, fixture: cc_recipient_email_address) }

      # X-Zammad headers are not taken from decrypted content.
      context 'enveloped message with X-Zammad headers in the content' do
        let(:mail) do
          recipient_cert = OpenSSL::X509::Certificate.new(Rails.root.join("spec/fixtures/files/smime/#{recipient_email_address}.crt").read)

          # The encrypted content is a MIME entity that also carries X-Zammad headers.
          inner = <<~INNER.gsub(%r{\n}, "\r\n")
            Content-Type: text/plain
            X-Zammad-Ticket-Id: 99999
            X-Zammad-Session-User-Id: 1
            X-Zammad-Ticket-Followup-Customer: customer@example.com
            X-Zammad-Article-Internal: true

            Secured enveloped body
          INNER

          p7         = OpenSSL::PKCS7.encrypt([recipient_cert], inner, OpenSSL::Cipher.new('AES-128-CBC'))
          smime_body = OpenSSL::PKCS7.write_smime(p7)
          smime_mail = "From: #{sender_email_address}\r\nTo: #{recipient_email_address}\r\nSubject: test\r\n#{smime_body}"

          mail = Channel::EmailParser.new.parse(smime_mail)
          SecureMailing.incoming(mail)

          mail
        end

        it 'decrypts and shows the content but does not adopt its X-Zammad headers' do
          expect(mail[:body]).to include('Secured enveloped body')
          expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be true
          expect(mail[:'x-zammad-ticket-id']).to be_nil
          expect(mail[:'x-zammad-session-user-id']).to be_nil
          expect(mail[:'x-zammad-ticket-followup-customer']).to be_nil
          expect(mail[:'x-zammad-article-internal']).to be_nil
          # The `raw-*` header twins are not adopted either.
          expect(mail['raw-x-zammad-ticket-id']).to be_nil
        end
      end

      # Sender and routing headers are kept from the original mail, while the subject is still
      # taken from the content (RFC 8551 protected headers).
      context 'enveloped message with sender and routing headers in the content' do
        let(:mail) do
          recipient_cert = OpenSSL::X509::Certificate.new(Rails.root.join("spec/fixtures/files/smime/#{recipient_email_address}.crt").read)

          inner = <<~INNER.gsub(%r{\n}, "\r\n")
            Content-Type: text/plain
            From: inner@example.com
            Reply-To: inner@example.com
            To: other-group@example.com
            References: <inner-thread@example.com>
            Message-ID: <inner-msgid@example.com>
            Subject: protected inner subject

            Secured enveloped body
          INNER

          p7         = OpenSSL::PKCS7.encrypt([recipient_cert], inner, OpenSSL::Cipher.new('AES-128-CBC'))
          smime_body = OpenSSL::PKCS7.write_smime(p7)
          smime_mail = "From: #{sender_email_address}\r\nTo: #{recipient_email_address}\r\nSubject: outer subject\r\n#{smime_body}"

          mail = Channel::EmailParser.new.parse(smime_mail)
          SecureMailing.incoming(mail)

          mail
        end

        it 'keeps the outer sender and routing but still adopts the protected subject' do
          expect(mail[:body]).to include('Secured enveloped body')
          expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be true
          # Sender / routing identity is kept from the original mail.
          expect(mail[:from]).to eq(sender_email_address)
          expect(mail[:from_email]).to eq(sender_email_address)
          expect(mail[:'reply-to']).to be_nil
          expect(mail[:to]).to eq(recipient_email_address)
          # Threading identity (used to select/link tickets) is not taken from the content.
          expect(mail[:references]).to be_nil
          expect(mail[:message_id]).not_to include('inner-msgid')
          # The encrypted Subject is a protected header and is still adopted.
          expect(mail[:subject]).to eq('protected inner subject')
        end
      end

      context 'private key present' do

        let(:mail) do
          smime_mail = build_mail

          mail = Channel::EmailParser.new.parse(smime_mail.to_s)
          SecureMailing.incoming(mail)

          mail
        end

        it 'decrypts' do
          expect(mail[:body]).to include(raw_body)
          expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be false
          expect(mail['x-zammad-article-preferences'][:security][:sign][:comment]).to be_nil
          expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be true
          expect(mail['x-zammad-article-preferences'][:security][:encryption][:comment]).to eq(recipient_certificate_subject)
        end

        context 'when recipient is only present in Delivered-To (#6357)' do
          let(:mail) do
            smime_mail = build_mail

            smime_mail.to = 'forwarding-address@example.com'
            smime_mail.cc = nil
            smime_mail['Delivered-To'] = recipient_email_address

            mail = Channel::EmailParser.new.parse(smime_mail.to_s)
            SecureMailing.incoming(mail)

            mail
          end

          it 'decrypts' do
            expect(mail[:body]).to include(raw_body)
            expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be true
            expect(mail['x-zammad-article-preferences'][:security][:encryption][:comment]).to eq(recipient_certificate_subject)
          end

          context 'when the address is wrapped in angle brackets' do
            let(:mail) do
              smime_mail = build_mail

              smime_mail.to = 'forwarding-address@example.com'
              smime_mail.cc = nil
              smime_mail['Delivered-To'] = "<#{recipient_email_address}>"

              mail = Channel::EmailParser.new.parse(smime_mail.to_s)
              SecureMailing.incoming(mail)

              mail
            end

            it 'decrypts' do
              expect(mail[:body]).to include(raw_body)
              expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be true
              expect(mail['x-zammad-article-preferences'][:security][:encryption][:comment]).to eq(recipient_certificate_subject)
            end
          end

          context 'when the mail was forwarded over multiple hops' do
            let(:mail) do
              smime_mail = build_mail

              smime_mail.to = 'forwarding-address@example.com'
              smime_mail.cc = nil
              smime_mail['Delivered-To'] = 'forwarding-address@example.com'
              smime_mail['Delivered-To'] = recipient_email_address

              mail = Channel::EmailParser.new.parse(smime_mail.to_s)
              SecureMailing.incoming(mail)

              mail
            end

            it 'decrypts' do
              expect(mail[:body]).to include(raw_body)
              expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be true
              expect(mail['x-zammad-article-preferences'][:security][:encryption][:comment]).to eq(recipient_certificate_subject)
            end
          end
        end

        it_behaves_like 'HttpLog writer', 'success'

        context 'expired allowed' do
          let(:allow_expired) { true }
          let(:system_email_address) { expired_email_address }

          it 'decrypts with comment' do
            expect(mail[:body]).to include(raw_body)
            expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be false
            expect(mail['x-zammad-article-preferences'][:security][:sign][:comment]).to be_nil
            expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be true
            expect(mail['x-zammad-article-preferences'][:security][:encryption][:comment]).to include(expired_email_address).and include('expired')
          end

          it_behaves_like 'HttpLog writer', 'success'
        end
      end

      context 'no private key present' do

        let(:mail) do
          smime_mail = build_mail

          mail = Channel::EmailParser.new.parse(smime_mail.to_s)

          sender_certificate.destroy!
          recipient_certificate.destroy!
          cc_recipient_certificate.destroy!

          SecureMailing.incoming(mail)

          mail
        end

        it 'fails' do
          expect(mail[:body]).to include('no visible content')
          expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be false
          expect(mail['x-zammad-article-preferences'][:security][:sign][:comment]).to be_nil
          expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be false
          expect(mail['x-zammad-article-preferences'][:security][:encryption][:comment]).to eq('The private key for decryption could not be found.')
        end

        it_behaves_like 'HttpLog writer', 'failed'
      end
    end

    context 'with signature verification and decryption' do
      let!(:sender_certificate)       { create(:smime_certificate, :with_private, fixture: sender_email_address) }
      let!(:recipient_certificate)    { create(:smime_certificate, :with_private, fixture: recipient_email_address) }
      let!(:cc_recipient_certificate) { create(:smime_certificate, :with_private, fixture: cc_recipient_email_address) }

      let(:security_preferences) do
        {
          type:       'S/MIME',
          sign:       {
            success: true,
          },
          encryption: {
            success: true,
          },
        }
      end

      let(:mail) do
        smime_mail = build_mail

        mail = Channel::EmailParser.new.parse(smime_mail.to_s)
        SecureMailing.incoming(mail)

        mail
      end

      context 'with wrapped mime-type S/MIME signature (e.g. for Microsoft Outlook)' do
        before do
          # We need to disable the open ssl detached flag, to force the smime-type with 'signed-data'.
          stub_const('OpenSSL::PKCS7::DETACHED', nil)
        end

        it 'check that mail was decrypted' do
          expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be true
        end

        it 'check that encryption comment exists' do
          expect(mail['x-zammad-article-preferences'][:security][:encryption][:comment]).to eq(recipient_certificate_subject)
        end

        it 'check that mail was verified' do
          expect(mail['x-zammad-article-preferences'][:security][:sign][:success]).to be true
        end

        it 'check that signe comment exists' do
          expect(mail['x-zammad-article-preferences'][:security][:sign][:comment]).to eq(sender_certificate_subject)
        end

        it 'check that body was encrypted and verified' do
          expect(mail[:body]).to include(raw_body)
        end
      end
    end
  end

  describe '.retry' do
    let(:sender_email_address)       { customer_email_address }
    let(:recipient_email_address)    { system_email_address }
    let(:cc_recipient_email_address) { system_email_address }

    let(:security_preferences) do
      {
        type:       'S/MIME',
        sign:       {
          success: true,
        },
        encryption: {
          success: true,
        },
      }
    end

    let(:mail) do
      sender_certificate    = create(:smime_certificate, :with_private, fixture: sender_email_address)
      recipient_certificate = create(:smime_certificate, :with_private, fixture: system_email_address)

      smime_mail = Channel::EmailBuild.build(
        from:         sender_email_address,
        to:           recipient_email_address,
        body:         raw_body,
        content_type: 'text/plain',
        security:     security_preferences,
        attachments:  [
          {
            content_type: 'text/plain',
            content:      'blub',
            filename:     'test-file1.txt',
          },
        ],
      )
      mail = Channel::EmailParser.new.parse(smime_mail.to_s)

      sender_certificate.destroy
      recipient_certificate.destroy

      mail
    end

    let!(:article) do
      _ticket, article, _user, _mail = Channel::EmailParser.new.process({}, mail['raw'])
      article
    end

    context 'private key added' do
      before do
        create(:smime_certificate, :with_private, fixture: recipient_email_address)
        create(:smime_certificate, fixture: sender_email_address)
      end

      it 'succeeds' do
        SecureMailing.retry(article)

        expect(article.preferences[:security][:sign][:success]).to be true
        expect(article.preferences[:security][:sign][:comment]).to eq(sender_certificate_subject)
        expect(article.preferences[:security][:encryption][:success]).to be true
        expect(article.preferences[:security][:encryption][:comment]).to eq(recipient_certificate_subject)
        expect(article.body).to include(raw_body)
        expect(article.attachments.count).to eq(1)
        expect(article.attachments.first.filename).to eq('test-file1.txt')
      end

      context 'S/MIME activated' do

        before do
          Setting.set('smime_integration', false)
        end

        it 'succeeds' do
          Setting.set('smime_integration', true)

          SecureMailing.retry(article)

          expect(article.preferences[:security][:sign][:success]).to be true
          expect(article.preferences[:security][:sign][:comment]).to eq(sender_certificate_subject)
          expect(article.preferences[:security][:encryption][:success]).to be true
          expect(article.preferences[:security][:encryption][:comment]).to eq(recipient_certificate_subject)
          expect(article.body).to include(raw_body)
          expect(article.attachments.count).to eq(1)
          expect(article.attachments.first.filename).to eq('test-file1.txt')
        end
      end
    end
  end
end
