Files
plugi/plugi-core/tests/MailerTest.php
T
deepDiverPaul dfe1e40e58 add configurable SMTP mail delivery
Add a core SMTP mailer with configurable transport, authentication, and sender settings. Route form confirmation and admin notifications through the core mailer, and add tests for SMTP delivery, failure cases, and finisher integration.
2026-11-24 11:48:31 +01:00

186 lines
8.0 KiB
PHP

<?php
require_once dirname(__DIR__) . '/src/Core/Mailer.php';
use Plugi\Core\Mailer;
function assertMailerSame($expected, $actual, string $message): void
{
if ($expected !== $actual) {
throw new RuntimeException($message . ': expected ' . var_export($expected, true) . ', got ' . var_export($actual, true));
}
}
function smtpReadLine($socket): ?string
{
$line = fgets($socket, 2048);
return is_string($line) && str_ends_with($line, "\r\n") ? substr($line, 0, -2) : null;
}
function smtpReply($socket, string $reply): bool
{
return fwrite($socket, $reply . "\r\n") === strlen($reply) + 2;
}
function runSmtpPeer(array $scenario): array
{
$server = stream_socket_server('tcp://127.0.0.1:0', $errorCode, $errorMessage);
if (!is_resource($server)) {
throw new RuntimeException('Could not start the local SMTP test peer.');
}
$address = stream_socket_get_name($server, false);
$port = (int) substr(strrchr($address, ':'), 1);
$pid = pcntl_fork();
if ($pid === -1) {
fclose($server);
throw new RuntimeException('Could not start the local SMTP test peer process.');
}
if ($pid === 0) {
$client = stream_socket_accept($server, 5);
fclose($server);
if (!is_resource($client)) {
exit(1);
}
stream_set_timeout($client, 5);
$passed = smtpReply($client, '220 local.test ESMTP');
$passed = $passed && smtpReadLine($client) === 'EHLO localhost' && smtpReply($client, '250 local.test');
if ($passed && !empty($scenario['auth'])) {
$passed = smtpReadLine($client) === 'AUTH PLAIN' && smtpReply($client, '334 ');
$credentials = smtpReadLine($client);
$expectedCredentials = base64_encode("\0test-user\0test-password");
if ($passed && empty($scenario['reject_auth'])) {
$passed = $credentials === $expectedCredentials && smtpReply($client, '235 authenticated');
} elseif ($passed) {
$passed = $credentials === $expectedCredentials && smtpReply($client, '535 authentication rejected');
$passed = $passed && smtpReadLine($client) === null;
fclose($client);
exit($passed ? 0 : 1);
}
}
if ($passed) {
$passed = smtpReadLine($client) === 'MAIL FROM:<sender@example.test>' && smtpReply($client, '250 sender accepted');
}
if ($passed) {
$passed = smtpReadLine($client) === 'RCPT TO:<recipient@example.test>';
if ($passed && !empty($scenario['reject_recipient'])) {
$passed = smtpReply($client, '550 recipient rejected') && smtpReadLine($client) === null;
fclose($client);
exit($passed ? 0 : 1);
}
$passed = $passed && smtpReply($client, '250 recipient accepted');
}
if ($passed) {
$passed = smtpReadLine($client) === 'DATA' && smtpReply($client, '354 send message');
}
$data = '';
if ($passed) {
$terminated = false;
while (($line = smtpReadLine($client)) !== null) {
if ($line === '.') {
$terminated = true;
break;
}
$data .= $line . "\r\n";
}
$passed = $terminated
&& str_contains($data, 'From: =?UTF-8?B?UGx1Z2kgVGVzdA==?= <sender@example.test>')
&& str_contains($data, 'To: recipient@example.test')
&& str_contains($data, 'Subject: =?UTF-8?B?U3RhdHVzIHVwZGF0ZQ==?=')
&& str_contains($data, "..leading dot\r\n");
}
if ($passed) {
$reply = !empty($scenario['reject_message']) ? '554 message rejected' : '250 message accepted';
$passed = smtpReply($client, $reply) && smtpReadLine($client) === 'QUIT' && smtpReply($client, '221 closing');
}
fclose($client);
exit($passed ? 0 : 1);
}
fclose($server);
$config = [
'transport' => 'smtp',
'host' => '127.0.0.1',
'port' => $port,
'encryption' => 'none',
'username' => !empty($scenario['auth']) ? 'test-user' : '',
'password' => !empty($scenario['auth']) ? 'test-password' : '',
'from_address' => 'sender@example.test',
'from_name' => 'Plugi Test',
'timeout' => 3,
];
$result = (new Mailer($config))->send('recipient@example.test', 'Status update', "First line\r\n.leading dot\r\nLast line");
pcntl_waitpid($pid, $status);
if (!pcntl_wifexited($status) || pcntl_wexitstatus($status) !== 0) {
throw new RuntimeException('The scripted SMTP peer observed an unexpected protocol exchange.');
}
return [$result, $config];
}
function baseMailerConfig(): array
{
return [
'transport' => 'smtp',
'host' => '127.0.0.1',
'port' => 587,
'encryption' => 'tls',
'username' => '',
'password' => '',
'from_address' => 'sender@example.test',
'from_name' => 'Plugi Test',
'timeout' => 1,
];
}
[$success, $config] = runSmtpPeer(['auth' => true]);
assertMailerSame(true, $success, 'Authenticated SMTP delivery must succeed');
[$authFailure] = runSmtpPeer(['auth' => true, 'reject_auth' => true]);
assertMailerSame(false, $authFailure, 'Rejected SMTP authentication must fail');
[$recipientFailure] = runSmtpPeer(['reject_recipient' => true]);
assertMailerSame(false, $recipientFailure, 'A rejected SMTP recipient must fail');
[$messageFailure] = runSmtpPeer(['reject_message' => true]);
assertMailerSame(false, $messageFailure, 'A rejected SMTP message must fail');
$invalidConfig = baseMailerConfig();
$invalidConfig['host'] = '';
assertMailerSame(false, (new Mailer($invalidConfig))->send('recipient@example.test', 'Subject', 'Body'), 'Incomplete SMTP configuration must fail safely');
$invalidConfig = baseMailerConfig();
$invalidConfig['username'] = 'only-a-username';
assertMailerSame(false, (new Mailer($invalidConfig))->send('recipient@example.test', 'Subject', 'Body'), 'Incomplete SMTP authentication settings must fail safely');
assertMailerSame(false, (new Mailer(baseMailerConfig()))->send('not-an-email', 'Subject', 'Body'), 'Invalid recipients must fail safely');
assertMailerSame(false, (new Mailer(baseMailerConfig()))->send('recipient@example.test', "Subject\r\nBcc: other@example.test", 'Body'), 'Header injection must fail safely');
$unavailableServer = stream_socket_server('tcp://127.0.0.1:0', $errorCode, $errorMessage);
if (!is_resource($unavailableServer)) {
throw new RuntimeException('Could not allocate a port for the SMTP connection-failure check.');
}
$unavailableAddress = stream_socket_get_name($unavailableServer, false);
$unavailablePort = (int) substr(strrchr($unavailableAddress, ':'), 1);
fclose($unavailableServer);
$unavailableConfig = baseMailerConfig();
$unavailableConfig['host'] = '127.0.0.1';
$unavailableConfig['port'] = $unavailablePort;
$unavailableConfig['encryption'] = 'none';
assertMailerSame(false, (new Mailer($unavailableConfig))->send('recipient@example.test', 'Subject', 'Body'), 'Connection refusal must fail safely');
$rootConfig = require dirname(__DIR__, 2) . '/config.php';
$templateConfig = require dirname(__DIR__, 2) . '/config.dist.php';
$mailKeys = ['class', 'transport', 'host', 'port', 'encryption', 'username', 'password', 'from_address', 'from_name', 'timeout'];
assertMailerSame($mailKeys, array_keys($rootConfig['mail']), 'Root SMTP settings must expose the documented keys');
assertMailerSame($mailKeys, array_keys($templateConfig['mail']), 'Template SMTP settings must expose the documented keys');
assertMailerSame(Plugi\Core\Mailer::class, $rootConfig['mail']['class'], 'Root configuration must select the core mailer');
assertMailerSame('', $templateConfig['mail']['username'], 'Template SMTP username must not contain credentials');
assertMailerSame('', $templateConfig['mail']['password'], 'Template SMTP password must not contain credentials');
fwrite(STDOUT, "Mailer tests passed.\n");