10000 [Mailer][Mime] Refactor S/MIME encryption handling in `SMimeEncryptionListener` by Spomky · Pull Request #59831 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[Mailer][Mime] Refactor S/MIME encryption handling in SMimeEncryptionListener #59831

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2314,8 +2314,8 @@ private function addMailerSection(ArrayNodeDefinition $rootNode, callable $enabl
->canBeEnabled()
->info('S/MIME encrypter configuration')
->children()
->scalarNode('certificate')
->info('Path to certificate (in PEM format without the `file://` prefix)')
->scalarNode('repository')
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For reviewers, this change is fine as this feature has been introduced in 7.3, so not yet released

->info('Path to the S/MIME certificate repository. Shall implement the `Symfony\Component\Mailer\EventListener\SmimeCertificateRepositoryInterface`.')
->defaultValue('')
->cannotBeEmpty()
->end()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2893,11 +2893,9 @@ private function registerMailerConfiguration(array $config, ContainerBuilder $co
if (!class_exists(SmimeEncryptedMessageListener::class)) {
throw new LogicException('S/MIME encrypted messages support cannot be enabled as this version of the Mailer component does not support it.');
}
$smimeDecrypter = $container->getDefinition('mailer.smime_encrypter');
$smimeDecrypter->setArgument(0, $config['smime_encrypter']['certificate']);
$smimeDecrypter->setArgument(1, $config['smime_encrypter']['cipher']);
$container->setAlias('mailer.smime_encrypter.repository', $config['smime_encrypter']['repository']);
$container->setParameter('mailer.smime_encrypter.cipher', $config['smime_encrypter']['cipher']);
} else {
$container->removeDefinition('mailer.smime_encrypter');
$container->removeDefinition('mailer.smime_encrypter.listener');
}

Expand Down
10 changes: 2 additions & 8 deletions src/Symfony/Bundle/FrameworkBundle/Resources/config/mailer.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
use Symfony\Component\Mailer\Transport\TransportInterface;
use Symfony\Component\Mailer\Transport\Transports;
use Symfony\Component\Mime\Crypto\DkimSigner;
use Symfony\Component\Mime\Crypto\SMimeEncrypter;
use Symfony\Component\Mime\Crypto\SMimeSigner;

return static function (ContainerConfigurator $container) {
Expand Down Expand Up @@ -102,12 +101,6 @@
abstract_arg('signOptions'),
])

->set('mailer.smime_encrypter', SMimeEncrypter::class)
->args([
abstract_arg('certificate'),
abstract_arg('cipher'),
])

->set('mailer.dkim_signer.listener', DkimSignedMessageListener::class)
->args([
service(DkimSigner::class),
Expand All @@ -122,7 +115,8 @@

->set('mailer.smime_encrypter.listener', SmimeEncryptedMessageListener::class)
->args([
service('mailer.smime_encrypter'),
service('mailer.smime_encrypter.repository'),
param('mailer.smime_encrypter.cipher'),
])
->tag('kernel.event_subscriber')

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -836,7 +836,7 @@
</xsd:complexType>

<xsd:complexType name="mailer_smime_encrypter">
<xsd:attribute name="certificate" type="xsd:string"/>
<xsd:attribute name="repository" type="xsd:string" />
<xsd:attribute name="cipher" type="xsd:integer" />
</xsd:complexType>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -941,7 +941,7 @@ class_exists(SemaphoreStore::class) && SemaphoreStore::isSupported() ? 'semaphor
],
'smime_encrypter' => [
'enabled' => false,
'certificate' => '',
'repository' => '',
'cipher' => null,
],
],
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Mailer\EventListener;

/**
* Encrypts messages using S/MIME.
*
* @author Florent Morselli <florent.morselli@spomky-labs.com>
*/
interface SmimeCertificateRepositoryInterface
{
/**
* @return ?string The path to the certificate. null if not found
*/
public function findCertificatePathFor(string $email): ?string;
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,11 @@
*
* @author Elías Fernández
*/
class SmimeEncryptedMessageListener implements EventSubscriberInterface
final class SmimeEncryptedMessageListener implements EventSubscriberInterface
{
public function __construct(
private SMimeEncrypter $encrypter,
private readonly SmimeCertificateRepositoryInterface $smimeRepository,
private readonly ?int $cipher = null,
) {
}

Expand All @@ -34,8 +35,24 @@ public function onMessage(MessageEvent $event): void
if (!$message instanceof Message) {
return;
}
if (!$message->getHeaders()->has('X-SMime-Encrypt')) {
return;
}
$message->getHeaders()->remove('X-SMime-Encrypt');
$certificatePaths = [];
foreach ($event->getEnvelope()->getRecipients() as $recipient) {
$certificatePath = $this->smimeRepository->findCertificatePathFor($recipient->getAddress());
if (null === $certificatePath) {
return;
}
$certificatePaths[] = $certificatePath;
}
if (0 === \count($certificatePaths)) {
return;
}
$encrypter = new SMimeEncrypter($certificatePaths, $this->cipher);

$event->setMessage($this->encrypter->encrypt($message));
$event->setMessage($encrypter->encrypt($message));
}

public static function getSubscribedEvents(): array
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,12 @@
use PHPUnit\Framework\TestCase;
use Symfony\Component\Mailer\Envelope;
use Symfony\Component\Mailer\Event\MessageEvent;
use Symfony\Component\Mailer\EventListener\SmimeCertificateRepositoryInterface;
use Symfony\Component\Mailer\EventListener\SmimeEncryptedMessageListener;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Crypto\SMimeEncrypter;
use Symfony\Component\Mime\Header\Headers;
use Symfony\Component\Mime\Header\MailboxListHeader;
use Symfony\Component\Mime\Header\UnstructuredHeader;
use Symfony\Component\Mime\Message;
use Symfony\Component\Mime\Part\SMimePart;
use Symfony\Component\Mime\Part\TextPart;
Expand All @@ -28,13 +29,15 @@ class SmimeEncryptedMessageListenerTest extends TestCase
/**
* @requires extension openssl
*/
public function testSmimeMessageSigningProcess()
public function testSmimeMessageEncryptionProcess()
{
$encrypter = new SMimeEncrypter(\dirname(__DIR__).'/Fixtures/sign.crt');
$listener = new SmimeEncryptedMessageListener($encrypter);
$repository = $this->createMock(SmimeCertificateRepositoryInterface::class);
$repository->method('findCertificatePathFor')->willReturn(\dirname(__DIR__).'/Fixtures/sign.crt');
$listener = new SmimeEncryptedMessageListener($repository);
$message = new Message(
new Headers(
new MailboxListHeader('From', [new Address('sender@example.com')])
new MailboxListHeader('From', [new Address('sender@example.com')]),
new UnstructuredHeader('X-SMime-Encrypt', 'true'),
),
new TextPart('hello')
);
Expand All @@ -45,5 +48,59 @@ public function testSmimeMessageSigningProcess()
$this->assertNotSame($message, $event->getMessage());
$this->assertInstanceOf(TextPart::class, $message->getBody());
$this->assertInstanceOf(SMimePart::class, $event->getMessage()->getBody());
$this->assertFalse($event->getMessage()->getHeaders()->has('X-SMime-Encrypt'));
}

/**
* @requires extension openssl
*/
public function testMessageNotEncryptedWhenOneRecipientCertificateIsMissing()
{
$repository = $this->createMock(SmimeCertificateRepositoryInterface::class);
$repository->method('findCertificatePathFor')->willReturnOnConsecutiveCalls(\dirname(__DIR__).'/Fixtures/sign.crt', null);
$listener = new SmimeEncryptedMessageListener($repository);
$message = new Message(
new Headers(
new MailboxListHeader('From', [new Address('sender@example.com')]),
new UnstructuredHeader('X-SMime-Encrypt', 'true'),
),
new TextPart('hello')
);
$envelope = new Envelope(new Address('sender@example.com'), [
new Address('r1@example.com'),
new Address('r2@example.com'),
]);
$event = new MessageEvent($message, $envelope, 'default');

$listener->onMessage($event);
$this->assertSame($message, $event->getMessage());
$this->assertInstanceOf(TextPart::class, $message->getBody());
$this->assertInstanceOf(TextPart::class, $event->getMessage()->getBody());
}

/**
* @requires extension openssl
*/
public function testMessageNotExplicitlyAskedForNonEncryption()
{
$repository = $this->createMock(SmimeCertificateRepositoryInterface::class);
$repository->method('findCertificatePathFor')->willReturn(\dirname(__DIR__).'/Fixtures/sign.crt');
$listener = new SmimeEncryptedMessageListener($repository);
$message = new Message(
new Headers(
new MailboxListHeader('From', [new Address('sender@example.com')]),
),
new TextPart('hello')
);
$envelope = new Envelope(new Address('sender@example.com'), [
new Address('r1@example.com'),
new Address('r2@example.com'),
]);
$event = new MessageEvent($message, $envelope, 'default');

$listener->onMessage($event);
$this->assertSame($message, $event->getMessage());
$this->assertInstanceOf(TextPart::class, $message->getBody());
$this->assertInstanceOf(TextPart::class, $event->getMessage()->getBody());
}
}
Loading
0