Files
cacti/tests/Unit/Core/Mailer/SymfonyMailerBugfixTest.php
Sean Mancini 96033267cb refactor(tests): reorganize unit tests into domain category folders (#7733)
* refactor(tests): reorganize unit tests into domain category folders

- Consolidate per-advisory GHSA regression tests into Security/ subfolders by vuln class
- Group all 186 test files into domain folders: DataCollection/, Ui/, Core/,
  Database/, Installer/, Scripts/, Security/, Plugin/
- Strip GitHub issue/GHSA numbers from filenames; keep IDs in test descriptions
- Fix all __DIR__ relative paths to match new folder nesting depth
- Update CI workflow path triggers and phpunit XML configs for new file locations
- Update .github/copilot-instructions.md with unit test organization guidelines
- Add tests/vendor/ to .gitignore

* add gaurds

* fix up guard for unit tests

* fix redeclaration of cacti_log in tests

* fix updates to unit tests

* fix test patjhs

* fix: update test __DIR__ paths for reorganized test structure

* fix: conditionally define read_user_setting to prevent redeclaration in tests

* fix: conditionally define functions to prevent redeclaration in tests

- Wrap clean_up_lines, raise_message, cacti_debug_backtrace, and get_debug_prefix
  with function_exists() checks to prevent conflicts when test stubs are loaded
  before lib/functions.php in the same PHP process

* fix: add unit test bootstrap to prevent function redeclaration errors

- Create tests/bootstrap-unit.php to load core libraries before tests
- Ensures lib/functions.php loads before test stubs define stub functions
- Test stubs use function_exists() checks, so they detect pre-loaded functions
- Update phpunit.xml to use bootstrap-unit.php for Unit testsuite
- Fixes 'Cannot redeclare read_user_setting()' errors when tests run in same process

* fix: load test stubs before global.php in unit test bootstrap

- Reorder bootstrap to load CactiStubs.php and UnitStubs.php first
- Ensures stub functions like __() are available when global.php loads
- global.php calls get_cacti_version_text() which needs __() for translations
- Fixes 'Call to undefined function __()' error during bootstrap

* fix: remove function conflicts from test stubs

- Remove stub definitions for functions already in lib/functions.php:
  cacti_sizeof, cacti_log, cacti_strtolower, read_config_option,
  read_user_setting, cacti_count
- Keep translation function stubs (__(), __esc()) needed by global.php
- Update bootstrap to load lib/functions.php after stubs
- This prevents function redeclaration errors while maintaining test isolation

* fix: prevent constant and variable redeclaration in bootstrap

- Remove explicit PHP_TESTING and CACTI_TEST_BOOTSTRAP defines from bootstrap
  (CactiStubs.php now handles this with guards)
- Add guards to CactiStubs.php to prevent redefinition of PHP_TESTING
- Only set CACTI_TEST_BOOTSTRAP env vars if not already set
- Fixes PHP warnings about 'Constant X already defined'

* fix: remove redundant lib/functions.php load from bootstrap

include/global.php already loads lib/functions.php at lines 287-288.
The bootstrap was trying to load it again after global.php, but global.php
needs format_cacti_version() to be available on lines 293-294 to define
CACTI_VERSION and CACTI_VERSION_FULL constants.

Solution: Let global.php handle loading lib/functions.php itself, and don't
load it separately in the bootstrap.

* fix: remove more conflicting function stubs from test helpers

- Remove stubs for functions also defined in lib/functions.php:
  raise_message, clean_up_lines, cacti_debug_backtrace, get_debug_prefix
- Remove POLLER_ID constant stub (defined unconditionally by global.php)
- Keep only translation functions and test-specific helpers
- This prevents function/constant redeclaration errors

* fix: minimize test stubs to only translation functions

Remove ALL helper functions and constants from UnitStubs.php that are:
- Defined in lib/functions.php (raise_message, clean_up_lines, etc.)
- Defined in lib/html_utility.php (srv, set_request_var)
- Defined in global_constants.php (POLLER_VERBOSITY_*, MESSAGE_LEVEL_*)
- Defined in global.php (POLLER_ID)

Keep ONLY translation functions (__(), __esc()) that are:
- Called by global.php during initialization
- Not defined elsewhere
- Required for proper bootstrap sequence

This eliminates all constant and function redeclaration errors.

* fix: remove __esc stub - already defined in global_languages.php

Keep only __() translation function stub, which is needed by global.php
and not defined elsewhere in Cacti core.

* fix: handle no-arg case in __() translation stub

The __() function may be called with just a string and no format arguments.
Previously, vsprintf() would fail with 'arguments array must contain 2 items'.
Now, if no args are provided, return the text as-is.
2026-08-16 19:23:31 -07:00

215 lines
8.3 KiB
PHP

<?php
/*
+-------------------------------------------------------------------------+
| Copyright (C) 2004-2026 The Cacti Group |
+-------------------------------------------------------------------------+
| Cacti: The Complete RRDtool-based Graphing Solution |
+-------------------------------------------------------------------------+
*/
require_once dirname(__DIR__, 4) . '/include/vendor/autoload.php';
require_once dirname(__DIR__, 4) . '/lib/CactiMailerTransport.php';
use Symfony\Component\Mailer\Exception\TransportException;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mailer\Transport\NullTransport;
use Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport;
use Symfony\Component\Mailer\Transport\Smtp\Stream\SocketStream;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\Exception\RfcComplianceException;
use Symfony\Component\Mime\Part\DataPart;
// =====================================================================
// Bug 1: inline graph image must carry a Content-ID matching the body cid
// =====================================================================
test('inline graph embed exposes a Content-ID matching the cid in the HTML body', function () {
$cid = getmypid() . '_0@localhost';
$email = new Email();
$email->from(new Address('from@example.com', 'From'));
$email->to(new Address('to@example.com', 'To'));
$email->html("<br><br><img src='cid:$cid'>");
// Mirror the production fix: explicit Content-ID, inline disposition.
$part = new DataPart('PNGDATA', 'graph.png', 'image/png');
$part->asInline()->setContentId($cid);
$email->addPart($part);
// Rendering must not fatal (pre-fix interpolated the Email object).
$rendered = $email->toString();
$attachments = $email->getAttachments();
expect($attachments)->toHaveCount(1);
expect($attachments[0]->hasContentId())->toBeTrue();
expect($attachments[0]->getContentId())->toBe($cid);
expect($rendered)->toContain('Content-Disposition: inline');
expect($rendered)->toContain($cid);
});
test('embed() returns the Email object, so its return value is not a usable cid', function () {
$email = new Email();
$ret = $email->embed('PNGDATA', 'graph.png', 'image/png');
// This is why the pre-fix `"cid:$cid"` interpolation fataled.
expect($ret)->toBeInstanceOf(Email::class);
});
// =====================================================================
// Bug 2: secure mode -> transport TLS configuration
// =====================================================================
test("'ssl' secure mode uses implicit TLS on the socket stream", function () {
$transport = new EsmtpTransport('smtp.example.com', 465, true);
$stream = $transport->getStream();
expect($stream)->toBeInstanceOf(SocketStream::class);
expect($stream->isTLS())->toBeTrue();
});
test("'tls' secure mode requires STARTTLS and starts non-implicit", function () {
$transport = new CactiRequireTlsEsmtpTransport('smtp.example.com', 587, false);
$stream = $transport->getStream();
expect($transport)->toBeInstanceOf(EsmtpTransport::class);
// 587 STARTTLS starts plaintext, then upgrades; it must not open an implicit TLS socket.
expect($stream->isTLS())->toBeFalse();
});
test("'none' secure mode attempts no TLS", function () {
$transport = new EsmtpTransport('smtp.example.com', 25, false);
$stream = $transport->getStream();
expect($stream->isTLS())->toBeFalse();
});
test('require-tls transport fails closed when the stream is still plaintext after start', function () {
// A stand-in whose parent::start() is a no-op leaves a plaintext stream,
// which models a server that never offered STARTTLS.
$transport = new class('smtp.example.com', 587, false) extends CactiRequireTlsEsmtpTransport {
public function start(): void {
// Skip the real socket connection; reuse the require-tls guard.
$stream = $this->getStream();
if ($stream instanceof SocketStream && !$stream->isTLS()) {
throw new TransportException('STARTTLS is required but the SMTP server did not offer it.');
}
}
};
expect(fn () => $transport->start())->toThrow(TransportException::class);
});
// =====================================================================
// Bug 3: malformed recipient must not throw out of the mailer
// =====================================================================
test('Address rejects a malformed recipient with RfcComplianceException, not a transport error', function () {
expect(fn () => new Address('not a valid address', 'X'))
->toThrow(RfcComplianceException::class);
try {
new Address('not a valid address', 'X');
$thrown = null;
} catch (\Throwable $e) {
$thrown = $e;
}
expect($thrown)->not->toBeInstanceOf(TransportExceptionInterface::class);
});
test('catching the address exception converts a malformed recipient into a non-empty error string', function () {
// Mirror the add_email_details() seam: build addresses, catch the Mime
// exception, and return an error string instead of letting it escape.
$addRecipient = function (string $address) : string {
try {
$email = new Email();
$email->from(new Address('from@example.com', 'From'));
$email->addTo(new Address($address, ''));
$email->text('body');
// A valid recipient reaches a (null) transport without network I/O.
(new Mailer(new NullTransport()))->send($email);
return '';
} catch (RfcComplianceException $ex) {
return 'Bad email format: ' . $address . ' - ' . $ex->getMessage();
} catch (TransportExceptionInterface $ex) {
return $ex->getMessage();
}
};
$error = $addRecipient('not a valid address');
expect($error)->not->toBe('');
expect($error)->toContain('Bad email format');
$ok = $addRecipient('good@example.com');
expect($ok)->toBe('');
});
// =====================================================================
// Source-level guards on the production helpers in lib/functions.php
// =====================================================================
test('mailer helpers map secure modes without the opportunistic STARTTLS downgrade', function () {
$src = file_get_contents(dirname(__DIR__, 4) . '/lib/functions.php');
// The fix removes the inline `($secure == 'tls') ? null` mapping that made
// STARTTLS opportunistic at every transport construction site.
expect($src)->not->toContain('? null : false');
expect($src)->toContain('function mailer_secure_tls_flag')
->toContain('function mailer_normalize_secure_mode')
->toContain('function mailer_build_esmtp_transport')
->toContain('CactiRequireTlsEsmtpTransport')
->toContain('CactiNoTlsEsmtpTransport')
->toContain('finally')
->toContain('catch (RfcComplianceException');
});
// Mirror of mailer_normalize_secure_mode() in lib/functions.php
function test_mailer_normalize_secure_mode(string $secure) : string {
$secure = strtolower(trim($secure));
if ($secure === 'ssl' || $secure === 'tls' || $secure === 'none') {
return $secure;
}
return 'none';
}
test('empty and unknown SMTP secure modes map to none', function () {
expect(test_mailer_normalize_secure_mode(''))->toBe('none');
expect(test_mailer_normalize_secure_mode(' '))->toBe('none');
expect(test_mailer_normalize_secure_mode('garbage'))->toBe('none');
expect(test_mailer_normalize_secure_mode('TLS'))->toBe('tls');
expect(test_mailer_normalize_secure_mode('ssl'))->toBe('ssl');
expect(test_mailer_normalize_secure_mode('none'))->toBe('none');
});
test('non-graph attachment disposition honours inline vs attachment flags', function () {
// attachment disposition
$email = new Email();
$email->from(new Address('from@example.com'));
$email->to(new Address('to@example.com'));
$email->attach('PAYLOAD', 'report.csv', 'text/csv');
expect($email->toString())->toContain('Content-Disposition: attachment');
// inline disposition
$email2 = new Email();
$email2->from(new Address('from@example.com'));
$email2->to(new Address('to@example.com'));
$part = new DataPart('PNGDATA', 'chart.png', 'image/png');
$part->asInline();
$email2->addPart($part);
expect($email2->toString())->toContain('Content-Disposition: inline');
});
test('mailer fails closed when attachment path is unreadable', function () {
$src = file_get_contents(dirname(__DIR__, 4) . '/lib/functions.php');
expect($src)->toContain('is_readable($attachment[\'attachment\'])')
->toContain("Error attaching file:");
});