From f2274cfd094332a4ff313d5b70122b1155e749b1 Mon Sep 17 00:00:00 2001 From: Brian Mitchell Date: Thu, 15 Oct 2026 12:18:32 +0200 Subject: [PATCH 01/29] Add Site Information health check support data and EOL rules Co-Authored-By: Claude Haiku 5.5 --- plugins/healthcheck/siteinfo/siteinfo.xml | 34 +++ .../siteinfo/src/Support/SupportData.php | 236 ++++++++++++++++++ .../Siteinfo/Support/SupportDataTest.php | 161 ++++++++++++ 3 files changed, 431 insertions(+) create mode 100644 plugins/healthcheck/siteinfo/siteinfo.xml create mode 100644 plugins/healthcheck/siteinfo/src/Support/SupportData.php create mode 100644 tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php diff --git a/plugins/healthcheck/siteinfo/siteinfo.xml b/plugins/healthcheck/siteinfo/siteinfo.xml new file mode 100644 index 00000000000..30e98485dd2 --- /dev/null +++ b/plugins/healthcheck/siteinfo/siteinfo.xml @@ -0,0 +1,34 @@ + + + plg_healthcheck_siteinfo + Joomla! Project + 2026-10 + (C) 2026 Open Source Matters, Inc. + GNU General Public License version 2 or later; see LICENSE.txt + admin@joomla.org + www.joomla.org + 6.2.0 + PLG_HEALTHCHECK_SITEINFO_XML_DESCRIPTION + Joomla\Plugin\Healthcheck\Siteinfo + + services + src + + + language/en-GB/plg_healthcheck_siteinfo.ini + language/en-GB/plg_healthcheck_siteinfo.sys.ini + + + +
+ +
+
+
+
diff --git a/plugins/healthcheck/siteinfo/src/Support/SupportData.php b/plugins/healthcheck/siteinfo/src/Support/SupportData.php new file mode 100644 index 00000000000..92478c40e68 --- /dev/null +++ b/plugins/healthcheck/siteinfo/src/Support/SupportData.php @@ -0,0 +1,236 @@ + + * @license GNU General Public License version 2 or later; see LICENSE.txt + */ + +namespace Joomla\Plugin\Healthcheck\Siteinfo\Support; + +// phpcs:disable PSR1.Files.SideEffects +\defined('_JEXEC') or die; +// phpcs:enable PSR1.Files.SideEffects + +/** + * Support data (vendor end of life and Joomla requirements) and the rules that classify a version. + * + * Built-in values come from endoflife.date and the Joomla manual's Technical Requirements page. + * Refresh them with every Joomla release. Requirements can also be refreshed at runtime from the manual. + * + * @since __DEPLOY_VERSION__ + */ +final class SupportData +{ + /** + * Status values + * + * @since __DEPLOY_VERSION__ + */ + public const STATUS_CRITICAL = 'critical'; + public const STATUS_WARNING = 'warning'; + public const STATUS_HEALTHY = 'healthy'; + public const STATUS_NONE = 'none'; + + /** + * Months before end of life when a supported version starts to warn + * + * @since __DEPLOY_VERSION__ + */ + public const WARNING_MONTHS = 6; + + /** + * Built-in release cycles: active = end of full support (null if not published), eol = end of security fixes. + * Source: https://endoflife.date (retrieved 2026-10-15) + * + * @since __DEPLOY_VERSION__ + */ + private const CYCLES = [ + 'php' => [ + '7.4' => ['active' => '2021-11-28', 'eol' => '2022-11-28'], + '8.0' => ['active' => '2022-11-26', 'eol' => '2023-11-26'], + '8.1' => ['active' => '2023-11-25', 'eol' => '2025-12-31'], + '8.2' => ['active' => '2024-12-31', 'eol' => '2026-12-31'], + '8.3' => ['active' => '2025-12-31', 'eol' => '2027-12-31'], + '8.4' => ['active' => '2026-12-31', 'eol' => '2028-12-31'], + '8.5' => ['active' => '2027-12-31', 'eol' => '2029-12-31'], + ], + 'mysql' => [ + '5.7' => ['active' => '2020-10-31', 'eol' => '2023-10-31'], + '8.0' => ['active' => '2025-04-30', 'eol' => '2026-04-30'], + '8.1' => ['active' => '2023-10-25', 'eol' => '2023-10-25'], + '8.2' => ['active' => '2024-01-16', 'eol' => '2024-01-16'], + '8.3' => ['active' => '2024-04-30', 'eol' => '2024-04-30'], + '8.4' => ['active' => '2029-04-30', 'eol' => '2032-04-30'], + '9.0' => ['active' => '2024-10-15', 'eol' => '2024-10-15'], + '9.1' => ['active' => '2025-01-21', 'eol' => '2025-01-21'], + '9.2' => ['active' => '2025-04-15', 'eol' => '2025-04-15'], + '9.3' => ['active' => '2025-07-22', 'eol' => '2025-07-22'], + '9.4' => ['active' => '2025-10-21', 'eol' => '2025-10-21'], + '9.5' => ['active' => '2026-01-20', 'eol' => '2026-01-20'], + '9.6' => ['active' => '2026-04-21', 'eol' => '2026-04-21'], + '9.7' => ['active' => '2031-04-30', 'eol' => '2034-04-30'], + ], + 'mariadb' => [ + '10.4' => ['active' => null, 'eol' => '2024-06-18'], + '10.5' => ['active' => null, 'eol' => '2025-06-24'], + '10.6' => ['active' => null, 'eol' => '2026-07-06'], + '10.11' => ['active' => null, 'eol' => '2028-02-16'], + '11.4' => ['active' => null, 'eol' => '2029-05-29'], + '11.8' => ['active' => null, 'eol' => '2028-06-04'], + '12.0' => ['active' => null, 'eol' => '2025-11-18'], + '12.1' => ['active' => null, 'eol' => '2026-02-13'], + '12.2' => ['active' => null, 'eol' => '2026-05-28'], + '12.3' => ['active' => null, 'eol' => '2029-06-12'], + '13.0' => ['active' => null, 'eol' => '2026-12-31'], + ], + 'postgresql' => [ + '12' => ['active' => null, 'eol' => '2024-11-21'], + '13' => ['active' => null, 'eol' => '2025-11-13'], + '14' => ['active' => null, 'eol' => '2026-11-12'], + '15' => ['active' => null, 'eol' => '2027-11-11'], + '16' => ['active' => null, 'eol' => '2028-11-09'], + '17' => ['active' => null, 'eol' => '2029-11-08'], + '18' => ['active' => null, 'eol' => '2030-11-14'], + ], + 'joomla' => [ + '3' => ['active' => '2021-08-17', 'eol' => '2023-08-17'], + '4' => ['active' => '2024-10-15', 'eol' => '2025-10-14'], + '5' => ['active' => '2026-10-13', 'eol' => '2027-10-12'], + '6' => ['active' => '2028-10-17', 'eol' => '2029-10-16'], + ], + ]; + + /** + * Strip vendor and pre-release suffixes, keeping the leading numeric version. + * + * @param string $version The raw version string + * + * @return string The numeric version, or an empty string if there is none + * + * @since __DEPLOY_VERSION__ + */ + public static function normalize(string $version): string + { + return preg_match('/^\d+(?:\.\d+)*/', trim($version), $matches) ? $matches[0] : ''; + } + + /** + * Get the release cycle a version belongs to. + * + * @param string $product The product name + * @param string $version The version + * + * @return string + * + * @since __DEPLOY_VERSION__ + */ + public static function cycleFor(string $product, string $version): string + { + $parts = explode('.', self::normalize($version)); + + if ($product === 'joomla' || ($product === 'postgresql' && (int) $parts[0] >= 10)) { + return $parts[0]; + } + + return $parts[0] . '.' . ($parts[1] ?? '0'); + } + + /** + * Whether end of life data exists for a product. + * + * @param string $product The product name + * + * @return boolean + * + * @since __DEPLOY_VERSION__ + */ + public function hasEolData(string $product): bool + { + return isset(self::CYCLES[$product]); + } + + /** + * Get the dates of one release cycle. + * + * @param string $product The product name + * @param string $cycle The cycle key + * + * @return array|null ['active' => ?string, 'eol' => string] or null if unknown + * + * @since __DEPLOY_VERSION__ + */ + public function getCycle(string $product, string $cycle): ?array + { + return self::CYCLES[$product][$cycle] ?? null; + } + + /** + * Classify a version by its vendor end of life. + * + * @param string $product The product name + * @param string $version The detected version + * @param \DateTimeImmutable $today The current date + * + * @return array ['status' => string, 'key' => language key, 'args' => list, 'eol' => string] + * + * @since __DEPLOY_VERSION__ + */ + public function getEolStatus(string $product, string $version, \DateTimeImmutable $today): array + { + $cycle = self::cycleFor($product, $version); + $dates = $this->getCycle($product, $cycle); + + if ($dates === null) { + $known = array_keys(self::CYCLES[$product] ?? []); + usort($known, 'version_compare'); + + if ($known && version_compare($cycle, $known[0], '<')) { + return $this->result(self::STATUS_CRITICAL, 'EOL_OLD'); + } + + if ($known && version_compare($cycle, end($known), '>')) { + return $this->result(self::STATUS_HEALTHY, 'NEWER'); + } + + return $this->result(self::STATUS_NONE, 'NO_DATA'); + } + + $eol = $dates['eol']; + $day = $today->format('Y-m-d'); + $soon = $today->modify('+' . self::WARNING_MONTHS . ' months')->format('Y-m-d'); + + if ($eol < $day) { + return $this->result(self::STATUS_CRITICAL, 'EOL_PAST', [$eol], $eol); + } + + if ($eol <= $soon) { + return $this->result(self::STATUS_WARNING, 'EOL_SOON', [$eol], $eol); + } + + if ($dates['active'] !== null && $dates['active'] < $day) { + return $this->result(self::STATUS_WARNING, 'SECURITY_ONLY', [$eol], $eol); + } + + return $this->result(self::STATUS_HEALTHY, 'SUPPORTED', [$eol], $eol); + } + + /** + * Build a status result. + * + * @param string $status The status + * @param string $key Language key suffix after PLG_HEALTHCHECK_SITEINFO_STATUS_ + * @param array $args Arguments for Text::sprintf + * @param string $eol End of life date, if known + * + * @return array + * + * @since __DEPLOY_VERSION__ + */ + private function result(string $status, string $key, array $args = [], string $eol = ''): array + { + return ['status' => $status, 'key' => 'PLG_HEALTHCHECK_SITEINFO_STATUS_' . $key, 'args' => $args, 'eol' => $eol]; + } +} diff --git a/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php b/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php new file mode 100644 index 00000000000..b1730b71167 --- /dev/null +++ b/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php @@ -0,0 +1,161 @@ + + * @license GNU General Public License version 2 or later; see LICENSE.txt + */ + +namespace Joomla\Tests\Unit\Plugin\Healthcheck\Siteinfo\Support; + +use Joomla\Plugin\Healthcheck\Siteinfo\Support\SupportData; +use Joomla\Plugin\Quickicon\Eos\Extension\Eos; +use Joomla\Tests\Unit\UnitTestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\TestDox; + +/** + * Test class for the Site Information support data + * + * @since __DEPLOY_VERSION__ + */ +#[TestDox('The Site Information support data')] +class SupportDataTest extends UnitTestCase +{ + /** + * Fixed "today" for all status tests. + * + * @return \DateTimeImmutable + * + * @since __DEPLOY_VERSION__ + */ + private function today(): \DateTimeImmutable + { + return new \DateTimeImmutable('2026-10-15', new \DateTimeZone('UTC')); + } + + /** + * @return array + * + * @since __DEPLOY_VERSION__ + */ + public static function normalizeProvider(): array + { + return [ + 'plain' => ['8.4.1', '8.4.1'], + 'mariadb suffix' => ['11.8.3-MariaDB-ubu2404', '11.8.3'], + 'ubuntu mysql' => ['8.0.36-0ubuntu0.22.04.1', '8.0.36'], + 'joomla dev' => ['6.2.1-dev', '6.2.1'], + 'joomla alpha' => ['6.3.0-alpha1', '6.3.0'], + 'not a version' => ['unknown', ''], + 'empty' => ['', ''], + ]; + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[DataProvider('normalizeProvider')] + #[TestDox('normalizes $version to $expected')] + public function testNormalize(string $version, string $expected): void + { + $this->assertSame($expected, SupportData::normalize($version)); + } + + /** + * @return array + * + * @since __DEPLOY_VERSION__ + */ + public static function cycleProvider(): array + { + return [ + ['php', '8.4.1', '8.4'], + ['mysql', '8.4.3', '8.4'], + ['mariadb', '10.11.6', '10.11'], + ['mariadb', '11.8.3-MariaDB-ubu2404', '11.8'], + ['postgresql', '17.4', '17'], + ['postgresql', '9.6.24', '9.6'], + ['joomla', '6.2.1-dev', '6'], + ]; + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[DataProvider('cycleProvider')] + #[TestDox('resolves $product $version to cycle $expected')] + public function testCycleFor(string $product, string $version, string $expected): void + { + $this->assertSame($expected, SupportData::cycleFor($product, $version)); + } + + /** + * @return array + * + * @since __DEPLOY_VERSION__ + */ + public static function eolProvider(): array + { + return [ + 'eol passed' => ['php', '8.1.2', 'critical', 'PLG_HEALTHCHECK_SITEINFO_STATUS_EOL_PAST', ['2025-12-31']], + 'eol within 6 months' => ['php', '8.2.5', 'warning', 'PLG_HEALTHCHECK_SITEINFO_STATUS_EOL_SOON', ['2026-12-31']], + 'security fixes only' => ['php', '8.3.10', 'warning', 'PLG_HEALTHCHECK_SITEINFO_STATUS_SECURITY_ONLY', ['2027-12-31']], + 'supported' => ['mariadb', '11.8.3', 'healthy', 'PLG_HEALTHCHECK_SITEINFO_STATUS_SUPPORTED', ['2028-06-04']], + 'mariadb dev site' => ['mariadb', '12.2.2-MariaDB', 'critical', 'PLG_HEALTHCHECK_SITEINFO_STATUS_EOL_PAST', ['2026-05-28']], + 'older than known' => ['php', '5.6.40', 'critical', 'PLG_HEALTHCHECK_SITEINFO_STATUS_EOL_OLD', []], + 'newer than known' => ['php', '9.0.0', 'healthy', 'PLG_HEALTHCHECK_SITEINFO_STATUS_NEWER', []], + 'gap in known cycles' => ['mysql', '8.5.0', 'none', 'PLG_HEALTHCHECK_SITEINFO_STATUS_NO_DATA', []], + 'joomla dev version' => ['joomla', '6.2.1-dev', 'healthy', 'PLG_HEALTHCHECK_SITEINFO_STATUS_SUPPORTED', ['2029-10-16']], + ]; + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[DataProvider('eolProvider')] + #[TestDox('reports $product $version as $status')] + public function testEolStatus(string $product, string $version, string $status, string $key, array $args): void + { + $result = (new SupportData())->getEolStatus($product, $version, $this->today()); + + $this->assertSame($status, $result['status']); + $this->assertSame($key, $result['key']); + $this->assertSame($args, $result['args']); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('uses the same Joomla 6 end of support date as the EOS quickicon')] + public function testJoomlaEolMatchesEosQuickicon(): void + { + $eosDate = (new \ReflectionClassConstant(Eos::class, 'EOS_DATE'))->getValue(); + + $this->assertSame($eosDate, (new SupportData())->getCycle('joomla', '6')['eol']); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('knows which products have end of life data')] + public function testHasEolData(): void + { + $data = new SupportData(); + + $this->assertTrue($data->hasEolData('postgresql')); + $this->assertFalse($data->hasEolData('nginx')); + } +} From 51ca4618bb10ac6f857a615f9fbad209693ddf66 Mon Sep 17 00:00:00 2001 From: Brian Mitchell Date: Thu, 15 Oct 2026 12:19:58 +0200 Subject: [PATCH 02/29] Report unparseable Site Information versions as no data, not critical Co-Authored-By: Claude Haiku 5.5 --- plugins/healthcheck/siteinfo/src/Support/SupportData.php | 4 ++++ .../Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php | 2 ++ 2 files changed, 6 insertions(+) diff --git a/plugins/healthcheck/siteinfo/src/Support/SupportData.php b/plugins/healthcheck/siteinfo/src/Support/SupportData.php index 92478c40e68..f389e7406ca 100644 --- a/plugins/healthcheck/siteinfo/src/Support/SupportData.php +++ b/plugins/healthcheck/siteinfo/src/Support/SupportData.php @@ -180,6 +180,10 @@ public function getCycle(string $product, string $cycle): ?array */ public function getEolStatus(string $product, string $version, \DateTimeImmutable $today): array { + if (self::normalize($version) === '') { + return $this->result(self::STATUS_NONE, 'NO_DATA'); + } + $cycle = self::cycleFor($product, $version); $dates = $this->getCycle($product, $cycle); diff --git a/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php b/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php index b1730b71167..0cdbe72b5ba 100644 --- a/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php +++ b/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php @@ -113,6 +113,8 @@ public static function eolProvider(): array 'newer than known' => ['php', '9.0.0', 'healthy', 'PLG_HEALTHCHECK_SITEINFO_STATUS_NEWER', []], 'gap in known cycles' => ['mysql', '8.5.0', 'none', 'PLG_HEALTHCHECK_SITEINFO_STATUS_NO_DATA', []], 'joomla dev version' => ['joomla', '6.2.1-dev', 'healthy', 'PLG_HEALTHCHECK_SITEINFO_STATUS_SUPPORTED', ['2029-10-16']], + 'empty version' => ['mysql', '', 'none', 'PLG_HEALTHCHECK_SITEINFO_STATUS_NO_DATA', []], + 'unparseable version' => ['php', 'unknown', 'none', 'PLG_HEALTHCHECK_SITEINFO_STATUS_NO_DATA', []], ]; } From b769b0d7d499d71a18b8eeb7b8bafe96c065d681 Mon Sep 17 00:00:00 2001 From: Brian Mitchell Date: Thu, 15 Oct 2026 12:21:50 +0200 Subject: [PATCH 03/29] Add Joomla requirement check and manual page parser to Site Information Co-Authored-By: Claude Haiku 5.5 --- .../siteinfo/src/Support/SupportData.php | 161 ++++++++++++++++++ .../Siteinfo/Support/SupportDataTest.php | 116 +++++++++++++ .../fixtures/technical-requirements.html | 36 ++++ 3 files changed, 313 insertions(+) create mode 100644 tests/Unit/Plugin/Healthcheck/Siteinfo/Support/fixtures/technical-requirements.html diff --git a/plugins/healthcheck/siteinfo/src/Support/SupportData.php b/plugins/healthcheck/siteinfo/src/Support/SupportData.php index f389e7406ca..2fd852dba57 100644 --- a/plugins/healthcheck/siteinfo/src/Support/SupportData.php +++ b/plugins/healthcheck/siteinfo/src/Support/SupportData.php @@ -103,6 +103,64 @@ final class SupportData ], ]; + /** + * Joomla 6.x requirements: [recommended, supported, minimum]. Minimum null = not enforced. + * Source: https://manual.joomla.org/docs/next/get-started/technical-requirements/ (retrieved 2026-10-15) + * + * @since __DEPLOY_VERSION__ + */ + private const REQUIREMENTS = [ + 'php' => ['8.4', '8.3.0', '8.3.0'], + 'mysql' => ['8.4', '8.0.13', '8.0.13'], + 'mariadb' => ['12.0', '10.6', '10.4'], + 'postgresql' => ['17.6', '14.0', '12.0'], + 'apache' => ['2.4', '2.4', null], + 'nginx' => ['1.29', '1.26', null], + 'iis' => ['10', '10', null], + ]; + + /** + * The manual page holding Joomla's technical requirements + * + * @since __DEPLOY_VERSION__ + */ + public const MANUAL_URL = 'https://manual.joomla.org/docs/get-started/technical-requirements/'; + + /** + * Row names on the manual page mapped to products + * + * @since __DEPLOY_VERSION__ + */ + private const MANUAL_PRODUCTS = [ + 'php' => 'php', + 'mysql' => 'mysql', + 'mariadb' => 'mariadb', + 'postgresql' => 'postgresql', + 'apache' => 'apache', + 'nginx' => 'nginx', + 'microsoft iis' => 'iis', + ]; + + /** + * Requirements in use (built-in, with refreshed products replaced) + * + * @var array + * @since __DEPLOY_VERSION__ + */ + private array $requirements; + + /** + * Constructor + * + * @param array $requirements Refreshed requirements, [product => [recommended, supported, ?minimum]] + * + * @since __DEPLOY_VERSION__ + */ + public function __construct(array $requirements = []) + { + $this->requirements = array_merge(self::REQUIREMENTS, array_intersect_key($requirements, self::REQUIREMENTS)); + } + /** * Strip vendor and pre-release suffixes, keeping the leading numeric version. * @@ -221,6 +279,93 @@ public function getEolStatus(string $product, string $version, \DateTimeImmutabl return $this->result(self::STATUS_HEALTHY, 'SUPPORTED', [$eol], $eol); } + /** + * Classify a version against Joomla's own requirements. + * + * @param string $product The product name + * @param string $version The detected version + * + * @return array|null ['status' => string, 'key' => language key, 'args' => list], null if nothing to report + * + * @since __DEPLOY_VERSION__ + */ + public function getRequirementStatus(string $product, string $version): ?array + { + $version = self::normalize($version); + + if ($version === '' || !isset($this->requirements[$product])) { + return null; + } + + [$recommended, $supported, $minimum] = $this->requirements[$product]; + + if ($minimum !== null && version_compare($version, $minimum, '<')) { + return $this->requirement(self::STATUS_CRITICAL, 'BELOW_MINIMUM', $minimum); + } + + if (version_compare($version, $supported, '<')) { + return $this->requirement(self::STATUS_WARNING, 'BELOW_SUPPORTED', $supported); + } + + if (version_compare($version, $recommended, '<')) { + return $this->requirement(self::STATUS_NONE, 'BELOW_RECOMMENDED', $recommended); + } + + return null; + } + + /** + * Read Joomla's requirements for one major version from the manual's Technical Requirements page. + * + * This is the only place that knows the page's structure. Replace it if the manual publishes structured data. + * + * @param string $html The page HTML + * @param integer $major The Joomla major version + * + * @return array ['requirements' => [product => [recommended, supported, ?minimum]], 'memory' => ?string] + * + * @throws \UnexpectedValueException + * + * @since __DEPLOY_VERSION__ + */ + public static function parseManual(string $html, int $major): array + { + $document = new \DOMDocument(); + $previous = libxml_use_internal_errors(true); + $document->loadHTML($html); + libxml_clear_errors(); + libxml_use_internal_errors($previous); + + $xpath = new \DOMXPath($document); + $heading = 'Requirements for Joomla! ' . $major . '.x'; + $table = $xpath->query('(//h2|//h3)[contains(normalize-space(.), "' . $heading . '")]/following-sibling::table[1]')->item(0); + + if ($table === null) { + throw new \UnexpectedValueException('No "' . $heading . '" table on the manual page'); + } + + $requirements = []; + + foreach ($xpath->query('.//tbody/tr', $table) as $row) { + $cells = array_map(static fn (\DOMNode $cell): string => trim($cell->textContent), iterator_to_array($xpath->query('./td', $row))); + $product = self::MANUAL_PRODUCTS[strtolower($cells[0] ?? '')] ?? null; + + if ($product === null || \count($cells) < 4 || $cells[1] === '' || $cells[2] === '') { + continue; + } + + $requirements[$product] = [$cells[1], $cells[2], $cells[3] === '' ? null : $cells[3]]; + } + + if (!isset($requirements['php'])) { + throw new \UnexpectedValueException('No PHP row in the "' . $heading . '" table'); + } + + $memory = preg_match('/Recommended PHP Memory Limit:\s*at least\s*(\d+)\s*MB/i', $document->textContent, $matches) ? $matches[1] . 'M' : null; + + return ['requirements' => $requirements, 'memory' => $memory]; + } + /** * Build a status result. * @@ -237,4 +382,20 @@ private function result(string $status, string $key, array $args = [], string $e { return ['status' => $status, 'key' => 'PLG_HEALTHCHECK_SITEINFO_STATUS_' . $key, 'args' => $args, 'eol' => $eol]; } + + /** + * Build a requirement result. + * + * @param string $status The status + * @param string $key Language key suffix after PLG_HEALTHCHECK_SITEINFO_REQUIREMENT_ + * @param string $version The threshold version + * + * @return array + * + * @since __DEPLOY_VERSION__ + */ + private function requirement(string $status, string $key, string $version): array + { + return ['status' => $status, 'key' => 'PLG_HEALTHCHECK_SITEINFO_REQUIREMENT_' . $key, 'args' => [$version]]; + } } diff --git a/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php b/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php index 0cdbe72b5ba..f6997f505d1 100644 --- a/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php +++ b/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php @@ -160,4 +160,120 @@ public function testHasEolData(): void $this->assertTrue($data->hasEolData('postgresql')); $this->assertFalse($data->hasEolData('nginx')); } + + /** + * @return array + * + * @since __DEPLOY_VERSION__ + */ + public static function requirementProvider(): array + { + return [ + 'below minimum' => ['mariadb', '10.3.39', 'critical', 'PLG_HEALTHCHECK_SITEINFO_REQUIREMENT_BELOW_MINIMUM', ['10.4']], + 'below supported' => ['mariadb', '10.4.34', 'warning', 'PLG_HEALTHCHECK_SITEINFO_REQUIREMENT_BELOW_SUPPORTED', ['10.6']], + 'below recommended' => ['mariadb', '11.8.3-MariaDB', 'none', 'PLG_HEALTHCHECK_SITEINFO_REQUIREMENT_BELOW_RECOMMENDED', ['12.0']], + 'web server note' => ['nginx', '1.26.0', 'none', 'PLG_HEALTHCHECK_SITEINFO_REQUIREMENT_BELOW_RECOMMENDED', ['1.29']], + 'web server old' => ['nginx', '1.24.0', 'warning', 'PLG_HEALTHCHECK_SITEINFO_REQUIREMENT_BELOW_SUPPORTED', ['1.26']], + 'php minimum' => ['php', '8.2.29', 'critical', 'PLG_HEALTHCHECK_SITEINFO_REQUIREMENT_BELOW_MINIMUM', ['8.3.0']], + ]; + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[DataProvider('requirementProvider')] + #[TestDox('checks $product $version against Joomla requirements as $status')] + public function testRequirementStatus(string $product, string $version, string $status, string $key, array $args): void + { + $result = (new SupportData())->getRequirementStatus($product, $version); + + $this->assertSame($status, $result['status']); + $this->assertSame($key, $result['key']); + $this->assertSame($args, $result['args']); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('has no requirement message for recommended or unknown products')] + public function testRequirementStatusNull(): void + { + $data = new SupportData(); + + $this->assertNull($data->getRequirementStatus('mariadb', '12.0.2')); + $this->assertNull($data->getRequirementStatus('apache', '2.4.62')); + $this->assertNull($data->getRequirementStatus('php', '8.4.1')); + $this->assertNull($data->getRequirementStatus('litespeed', '6.3')); + $this->assertNull($data->getRequirementStatus('mariadb', '')); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('lets refreshed requirements replace built-in ones per product')] + public function testRequirementOverride(): void + { + $data = new SupportData(['mariadb' => ['12.3', '11.4', '10.6']]); + + $this->assertSame('critical', $data->getRequirementStatus('mariadb', '10.5.27')['status']); + $this->assertSame(['8.3.0'], $data->getRequirementStatus('php', '8.2.29')['args']); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('parses the manual Technical Requirements page')] + public function testParseManual(): void + { + $html = file_get_contents(__DIR__ . '/fixtures/technical-requirements.html'); + $result = SupportData::parseManual($html, 6); + + $this->assertSame( + [ + 'php' => ['8.4', '8.3.0', '8.3.0'], + 'mysql' => ['8.4', '8.0.13', '8.0.13'], + 'mariadb' => ['12.0', '10.6', '10.4'], + 'postgresql' => ['17.6', '14.0', '12.0'], + 'apache' => ['2.4', '2.4', null], + 'nginx' => ['1.29', '1.26', null], + 'iis' => ['10', '10', null], + ], + $result['requirements'] + ); + $this->assertSame('256M', $result['memory']); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('rejects a manual page without requirements for the running major version')] + public function testParseManualMissingMajor(): void + { + $this->expectException(\UnexpectedValueException::class); + + SupportData::parseManual(file_get_contents(__DIR__ . '/fixtures/technical-requirements.html'), 7); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('rejects a manual page whose heading has no table')] + public function testParseManualMissingTable(): void + { + $this->expectException(\UnexpectedValueException::class); + + SupportData::parseManual('

Requirements for Joomla! 6.x

Moved.

', 6); + } } diff --git a/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/fixtures/technical-requirements.html b/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/fixtures/technical-requirements.html new file mode 100644 index 00000000000..bee062a7e92 --- /dev/null +++ b/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/fixtures/technical-requirements.html @@ -0,0 +1,36 @@ +
Version: 6.1 (Current)

Technical Requirements

+

Requirements for Supported Software​

+
    +
  • You should use at least the version listed in the Recommended column.
  • +
  • The minimum supported version is listed in the Supported column.
  • +
  • The version in the Minimum column is the absolute minimum, +but if it is below the Supported version then if you choose to use it, you are responsible for resolving any issues that may arise.
  • +
+

Requirements for Joomla! 6.x​

+
SoftwareRecommendedSupportedMinimum
PHP8.48.3.08.3.0
Databases
MySQL8.48.0.138.0.13
MariaDB12.010.610.4
PostgreSQL17.614.012.0
Web Servers
Apache2.42.4
Nginx1.291.26
Microsoft IIS1010
+

Required PHP Modules: json, simplexml, dom, zlib, gd, mysqlnd or pdo_mysql or pdo_pgsql
+Recommended PHP Modules: mbstring
+Recommended PHP Memory Limit: at least 256MB
+Optional Apache Modules: mod_rewrite extension to use SEO URLs
+Optional Microsoft IIS Modules: URL Rewrite Module to use SEO URLs

+

Additional Information​

+
    +
  • PHP A popular general-purpose scripting language that is especially suited to web development.
  • +
  • MySQL is available in several editions. It is normal to install a GPL Community Edition for your software platform.
  • +
  • MariaDB is also available in several editions. It is normal to install a free Community Edition for your software platform.
  • +
  • PostgreSQL is open source and available in numerous editions.
  • +
  • Apache HTTP Server Project is an effort to develop and maintain an open-source HTTP server for modern operating systems including UNIX and Windows.
  • +
  • Nginx is an HTTP web server, reverse proxy, content cache and load balancer.
  • +
  • Microsoft IIS (Internet Information Services) for Windows® Server is a flexible, secure and manageable Web server for hosting anything on the Web.
  • +
+

Glossary​

+ +

This column describes which version the Joomla! Project recommends to use for the selected Joomla version.

+

Supported​

+

This column describes which version the Joomla! Project has set as the minimum supported version. +This means any bug found in this version or higher will be considered for fixing. This version might +not be enforced.

+

Minimum​

+

This column describes the minimum version enforced by the CMS or the framework in use. That means you may sometimes use +a lower version than the supported version, but not lower than the minimum version. For versions below +the supported version, you might not receive support from the Joomla maintainers.

From cb2d6e353cba02f085d43262bea3976732feac79 Mon Sep 17 00:00:00 2001 From: Brian Mitchell Date: Thu, 15 Oct 2026 12:23:16 +0200 Subject: [PATCH 04/29] Reject empty and PHP-less manual pages with UnexpectedValueException Co-Authored-By: Claude Haiku 5.5 --- .../siteinfo/src/Support/SupportData.php | 4 +++ .../Siteinfo/Support/SupportDataTest.php | 26 +++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/plugins/healthcheck/siteinfo/src/Support/SupportData.php b/plugins/healthcheck/siteinfo/src/Support/SupportData.php index 2fd852dba57..3118426fd80 100644 --- a/plugins/healthcheck/siteinfo/src/Support/SupportData.php +++ b/plugins/healthcheck/siteinfo/src/Support/SupportData.php @@ -330,6 +330,10 @@ public function getRequirementStatus(string $product, string $version): ?array */ public static function parseManual(string $html, int $major): array { + if (trim($html) === '') { + throw new \UnexpectedValueException('Empty manual page'); + } + $document = new \DOMDocument(); $previous = libxml_use_internal_errors(true); $document->loadHTML($html); diff --git a/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php b/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php index f6997f505d1..c63c4bf21c8 100644 --- a/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php +++ b/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php @@ -276,4 +276,30 @@ public function testParseManualMissingTable(): void SupportData::parseManual('

Requirements for Joomla! 6.x

Moved.

', 6); } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('rejects an empty manual page')] + public function testParseManualEmpty(): void + { + $this->expectException(\UnexpectedValueException::class); + + SupportData::parseManual('', 6); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('rejects a requirements table without a PHP row')] + public function testParseManualMissingPhpRow(): void + { + $this->expectException(\UnexpectedValueException::class); + + SupportData::parseManual('

Requirements for Joomla! 6.x

SoftwareRecommendedSupportedMinimum
MySQL8.48.0.138.0.13
', 6); + } } From 4d64c10b0be44c24b253d9761af2dd96161dc0e3 Mon Sep 17 00:00:00 2001 From: Brian Mitchell Date: Thu, 15 Oct 2026 12:24:47 +0200 Subject: [PATCH 05/29] Add Site Information system report rows Co-Authored-By: Claude Haiku 5.5 --- .../siteinfo/src/Support/SystemReport.php | 209 ++++++++++++++++ .../Siteinfo/Support/SystemReportTest.php | 231 ++++++++++++++++++ 2 files changed, 440 insertions(+) create mode 100644 plugins/healthcheck/siteinfo/src/Support/SystemReport.php create mode 100644 tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SystemReportTest.php diff --git a/plugins/healthcheck/siteinfo/src/Support/SystemReport.php b/plugins/healthcheck/siteinfo/src/Support/SystemReport.php new file mode 100644 index 00000000000..371be3e7b57 --- /dev/null +++ b/plugins/healthcheck/siteinfo/src/Support/SystemReport.php @@ -0,0 +1,209 @@ + + * @license GNU General Public License version 2 or later; see LICENSE.txt + */ + +namespace Joomla\Plugin\Healthcheck\Siteinfo\Support; + +// phpcs:disable PSR1.Files.SideEffects +\defined('_JEXEC') or die; +// phpcs:enable PSR1.Files.SideEffects + +/** + * Turns detected versions and PHP settings into report rows. + * + * @since __DEPLOY_VERSION__ + */ +final class SystemReport +{ + /** + * Status order, worst first + * + * @since __DEPLOY_VERSION__ + */ + private const SEVERITY = [ + SupportData::STATUS_CRITICAL, + SupportData::STATUS_WARNING, + SupportData::STATUS_HEALTHY, + SupportData::STATUS_NONE, + ]; + + /** + * Web server names in SERVER_SOFTWARE mapped to requirement products + * + * @since __DEPLOY_VERSION__ + */ + private const WEB_SERVERS = ['apache' => 'apache', 'nginx' => 'nginx', 'microsoft-iis' => 'iis']; + + /** + * Recommended PHP memory limit (Joomla manual, Technical Requirements) + * + * @since __DEPLOY_VERSION__ + */ + public const MEMORY_LIMIT = '256M'; + + /** + * Constructor + * + * @param SupportData $data The support data + * @param \DateTimeImmutable $today The current date + * + * @since __DEPLOY_VERSION__ + */ + public function __construct(private readonly SupportData $data, private readonly \DateTimeImmutable $today) + { + } + + /** + * Build the row for one product. + * + * @param string $product The product name (php, mysql, mariadb, postgresql, joomla, apache, nginx, iis) + * @param string $version The detected version, empty if unknown + * + * @return array ['product', 'version', 'status', 'messages' => list of [language key, args], 'ends'] + * + * @since __DEPLOY_VERSION__ + */ + public function versionRow(string $product, string $version): array + { + $row = ['product' => $product, 'version' => $version, 'status' => SupportData::STATUS_NONE, 'messages' => [], 'ends' => '']; + + if (SupportData::normalize($version) === '') { + $row['messages'][] = ['PLG_HEALTHCHECK_SITEINFO_STATUS_UNKNOWN', []]; + + return $row; + } + + $statuses = []; + + if ($this->data->hasEolData($product)) { + $eol = $this->data->getEolStatus($product, $version, $this->today); + $statuses[] = $eol['status']; + $row['messages'][] = [$eol['key'], $eol['args']]; + $row['ends'] = $eol['eol']; + } + + $requirement = $this->data->getRequirementStatus($product, $version); + + if ($requirement !== null) { + $statuses[] = $requirement['status']; + $row['messages'][] = [$requirement['key'], $requirement['args']]; + } + + $row['status'] = self::worst($statuses); + + return $row; + } + + /** + * Split SERVER_SOFTWARE into a known product, its display name and version. + * + * @param string $software The SERVER_SOFTWARE value + * + * @return array ['product' => ?string, 'name' => string, 'version' => string] + * + * @since __DEPLOY_VERSION__ + */ + public static function parseServerSoftware(string $software): array + { + if (!preg_match('#^([A-Za-z][\w.-]*)(?:/(\d+(?:\.\d+)*))?#', trim($software), $matches)) { + return ['product' => null, 'name' => '', 'version' => '']; + } + + return [ + 'product' => self::WEB_SERVERS[strtolower($matches[1])] ?? null, + 'name' => $matches[1], + 'version' => $matches[2] ?? '', + ]; + } + + /** + * Check PHP settings against Joomla recommendations. + * + * @param array $ini Values of memory_limit, max_execution_time, post_max_size, upload_max_filesize, display_errors + * @param boolean $opcacheEnabled Whether OPcache is enabled + * @param string $memoryLimit Recommended memory limit (built-in or refreshed from the manual) + * + * @return array List of ['setting', 'current', 'recommended' => [language key, args], 'status'] + * + * @since __DEPLOY_VERSION__ + */ + public static function settingsRows(array $ini, bool $opcacheEnabled, string $memoryLimit = self::MEMORY_LIMIT): array + { + $memory = self::toBytes((string) ($ini['memory_limit'] ?? '')); + $execution = (int) ($ini['max_execution_time'] ?? 0); + $post = self::toBytes((string) ($ini['post_max_size'] ?? '')); + $upload = self::toBytes((string) ($ini['upload_max_filesize'] ?? '')); + $errors = \in_array(strtolower((string) ($ini['display_errors'] ?? '')), ['1', 'on', 'true', 'yes', 'stderr'], true); + + $rows = [ + ['memory_limit', (string) ($ini['memory_limit'] ?? ''), ['MEMORY', [$memoryLimit]], $memory !== -1 && $memory < self::toBytes($memoryLimit)], + ['max_execution_time', (string) $execution, ['EXECUTION', []], $execution > 0 && $execution < 30], + ['post_max_size', (string) ($ini['post_max_size'] ?? ''), ['POST', [(string) ($ini['upload_max_filesize'] ?? '')]], $post !== -1 && $upload !== -1 && $post < $upload], + ['opcache.enable', $opcacheEnabled ? 'JENABLED' : 'JDISABLED', ['OPCACHE', []], !$opcacheEnabled], + ['display_errors', $errors ? 'JON' : 'JOFF', ['DISPLAY_ERRORS', []], $errors], + ]; + + return array_map( + static fn (array $row): array => [ + 'setting' => $row[0], + 'current' => $row[1], + 'recommended' => ['PLG_HEALTHCHECK_SITEINFO_RECOMMENDED_' . $row[2][0], $row[2][1]], + 'status' => $row[3] ? SupportData::STATUS_WARNING : SupportData::STATUS_HEALTHY, + ], + $rows + ); + } + + /** + * Convert a PHP shorthand byte value to bytes. + * + * @param string $value The value, e.g. 128M, 1G, -1 + * + * @return integer Bytes, or -1 for unlimited + * + * @since __DEPLOY_VERSION__ + */ + public static function toBytes(string $value): int + { + $value = trim($value); + + if ($value === '-1') { + return -1; + } + + $number = (int) $value; + + return match (strtolower(substr($value, -1))) { + 'g' => $number * 1024 ** 3, + 'm' => $number * 1024 ** 2, + 'k' => $number * 1024, + default => $number, + }; + } + + /** + * Get the worst of several statuses. + * + * @param array $statuses Status values + * + * @return string + * + * @since __DEPLOY_VERSION__ + */ + public static function worst(array $statuses): string + { + foreach (self::SEVERITY as $status) { + if (\in_array($status, $statuses, true)) { + return $status; + } + } + + return SupportData::STATUS_NONE; + } +} diff --git a/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SystemReportTest.php b/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SystemReportTest.php new file mode 100644 index 00000000000..f62b805dfad --- /dev/null +++ b/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SystemReportTest.php @@ -0,0 +1,231 @@ + + * @license GNU General Public License version 2 or later; see LICENSE.txt + */ + +namespace Joomla\Tests\Unit\Plugin\Healthcheck\Siteinfo\Support; + +use Joomla\Plugin\Healthcheck\Siteinfo\Support\SupportData; +use Joomla\Plugin\Healthcheck\Siteinfo\Support\SystemReport; +use Joomla\Tests\Unit\UnitTestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\TestDox; + +/** + * Test class for the Site Information system report + * + * @since __DEPLOY_VERSION__ + */ +#[TestDox('The Site Information system report')] +class SystemReportTest extends UnitTestCase +{ + /** + * @return SystemReport + * + * @since __DEPLOY_VERSION__ + */ + private function report(): SystemReport + { + return new SystemReport(new SupportData(), new \DateTimeImmutable('2026-10-15', new \DateTimeZone('UTC'))); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('reports an end-of-life database as critical with its end date')] + public function testVersionRowEol(): void + { + $row = $this->report()->versionRow('mariadb', '12.2.2-MariaDB'); + + $this->assertSame('critical', $row['status']); + $this->assertSame('2026-05-28', $row['ends']); + $this->assertSame([['PLG_HEALTHCHECK_SITEINFO_STATUS_EOL_PAST', ['2026-05-28']]], $row['messages']); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('takes the worse of the EOL and requirement statuses and shows both messages')] + public function testVersionRowCombined(): void + { + $row = $this->report()->versionRow('mariadb', '10.5.27'); + + $this->assertSame('critical', $row['status']); + $this->assertSame( + [ + ['PLG_HEALTHCHECK_SITEINFO_STATUS_EOL_PAST', ['2025-06-24']], + ['PLG_HEALTHCHECK_SITEINFO_REQUIREMENT_BELOW_SUPPORTED', ['10.6']], + ], + $row['messages'] + ); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('checks a web server only against Joomla requirements')] + public function testVersionRowWebServer(): void + { + $row = $this->report()->versionRow('nginx', '1.24.0'); + + $this->assertSame('warning', $row['status']); + $this->assertSame('', $row['ends']); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('shows Unknown when a version could not be detected')] + public function testVersionRowUnknown(): void + { + $row = $this->report()->versionRow('mysql', ''); + + $this->assertSame('none', $row['status']); + $this->assertSame([['PLG_HEALTHCHECK_SITEINFO_STATUS_UNKNOWN', []]], $row['messages']); + } + + /** + * @return array + * + * @since __DEPLOY_VERSION__ + */ + public static function serverProvider(): array + { + return [ + 'apache' => ['Apache/2.4.62 (Unix) OpenSSL/3.0.13', 'apache', 'Apache', '2.4.62'], + 'nginx' => ['nginx/1.27.3', 'nginx', 'nginx', '1.27.3'], + 'iis' => ['Microsoft-IIS/10.0', 'iis', 'Microsoft-IIS', '10.0'], + 'litespeed' => ['LiteSpeed', null, 'LiteSpeed', ''], + 'hidden version' => ['Apache', 'apache', 'Apache', ''], + 'empty' => ['', null, '', ''], + ]; + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[DataProvider('serverProvider')] + #[TestDox('parses SERVER_SOFTWARE "$software"')] + public function testParseServerSoftware(string $software, ?string $product, string $name, string $version): void + { + $this->assertSame( + ['product' => $product, 'name' => $name, 'version' => $version], + SystemReport::parseServerSoftware($software) + ); + } + + /** + * @return array + * + * @since __DEPLOY_VERSION__ + */ + public static function bytesProvider(): array + { + return [['-1', -1], ['128M', 134217728], ['512m', 536870912], ['1G', 1073741824], ['2048K', 2097152], ['1000', 1000]]; + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[DataProvider('bytesProvider')] + #[TestDox('converts $value to $bytes bytes')] + public function testToBytes(string $value, int $bytes): void + { + $this->assertSame($bytes, SystemReport::toBytes($value)); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('warns about PHP settings below Joomla recommendations')] + public function testSettingsRowsWarnings(): void + { + $rows = SystemReport::settingsRows( + [ + 'memory_limit' => '128M', + 'max_execution_time' => '20', + 'post_max_size' => '8M', + 'upload_max_filesize' => '16M', + 'display_errors' => 'stderr', + ], + false + ); + + $this->assertSame( + ['warning', 'warning', 'warning', 'warning', 'warning'], + array_column($rows, 'status') + ); + $this->assertSame( + ['memory_limit', 'max_execution_time', 'post_max_size', 'opcache.enable', 'display_errors'], + array_column($rows, 'setting') + ); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('accepts unlimited and generous PHP settings')] + public function testSettingsRowsHealthy(): void + { + $rows = SystemReport::settingsRows( + [ + 'memory_limit' => '-1', + 'max_execution_time' => '0', + 'post_max_size' => '1G', + 'upload_max_filesize' => '512m', + 'display_errors' => 'Off', + ], + true + ); + + $this->assertSame(['healthy', 'healthy', 'healthy', 'healthy', 'healthy'], array_column($rows, 'status')); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('uses a refreshed memory limit')] + public function testSettingsRowsRefreshedMemory(): void + { + $rows = SystemReport::settingsRows(['memory_limit' => '384M'], true, '512M'); + + $this->assertSame('warning', $rows[0]['status']); + $this->assertSame(['PLG_HEALTHCHECK_SITEINFO_RECOMMENDED_MEMORY', ['512M']], $rows[0]['recommended']); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('picks the worst status')] + public function testWorst(): void + { + $this->assertSame('critical', SystemReport::worst(['healthy', 'critical', 'warning'])); + $this->assertSame('warning', SystemReport::worst(['none', 'warning'])); + $this->assertSame('none', SystemReport::worst([])); + } +} From 676a03028391b6858fc2012cf9e7c90834280a30 Mon Sep 17 00:00:00 2001 From: Brian Mitchell Date: Thu, 15 Oct 2026 12:26:13 +0200 Subject: [PATCH 06/29] Treat post_max_size 0 as unlimited and accept display_errors stdout Co-Authored-By: Claude Haiku 5.5 --- .../siteinfo/src/Support/SystemReport.php | 4 ++-- .../Siteinfo/Support/SystemReportTest.php | 23 +++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/plugins/healthcheck/siteinfo/src/Support/SystemReport.php b/plugins/healthcheck/siteinfo/src/Support/SystemReport.php index 371be3e7b57..d224dc30e6f 100644 --- a/plugins/healthcheck/siteinfo/src/Support/SystemReport.php +++ b/plugins/healthcheck/siteinfo/src/Support/SystemReport.php @@ -139,12 +139,12 @@ public static function settingsRows(array $ini, bool $opcacheEnabled, string $me $execution = (int) ($ini['max_execution_time'] ?? 0); $post = self::toBytes((string) ($ini['post_max_size'] ?? '')); $upload = self::toBytes((string) ($ini['upload_max_filesize'] ?? '')); - $errors = \in_array(strtolower((string) ($ini['display_errors'] ?? '')), ['1', 'on', 'true', 'yes', 'stderr'], true); + $errors = \in_array(strtolower((string) ($ini['display_errors'] ?? '')), ['1', 'on', 'true', 'yes', 'stdout', 'stderr'], true); $rows = [ ['memory_limit', (string) ($ini['memory_limit'] ?? ''), ['MEMORY', [$memoryLimit]], $memory !== -1 && $memory < self::toBytes($memoryLimit)], ['max_execution_time', (string) $execution, ['EXECUTION', []], $execution > 0 && $execution < 30], - ['post_max_size', (string) ($ini['post_max_size'] ?? ''), ['POST', [(string) ($ini['upload_max_filesize'] ?? '')]], $post !== -1 && $upload !== -1 && $post < $upload], + ['post_max_size', (string) ($ini['post_max_size'] ?? ''), ['POST', [(string) ($ini['upload_max_filesize'] ?? '')]], $post > 0 && $upload !== -1 && $post < $upload], ['opcache.enable', $opcacheEnabled ? 'JENABLED' : 'JDISABLED', ['OPCACHE', []], !$opcacheEnabled], ['display_errors', $errors ? 'JON' : 'JOFF', ['DISPLAY_ERRORS', []], $errors], ]; diff --git a/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SystemReportTest.php b/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SystemReportTest.php index f62b805dfad..851bbf8e9f2 100644 --- a/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SystemReportTest.php +++ b/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SystemReportTest.php @@ -110,6 +110,7 @@ public static function serverProvider(): array 'iis' => ['Microsoft-IIS/10.0', 'iis', 'Microsoft-IIS', '10.0'], 'litespeed' => ['LiteSpeed', null, 'LiteSpeed', ''], 'hidden version' => ['Apache', 'apache', 'Apache', ''], + 'cloudflare' => ['cloudflare', null, 'cloudflare', ''], 'empty' => ['', null, '', ''], ]; } @@ -202,6 +203,28 @@ public function testSettingsRowsHealthy(): void $this->assertSame(['healthy', 'healthy', 'healthy', 'healthy', 'healthy'], array_column($rows, 'status')); } + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('treats post_max_size 0 as unlimited and display_errors stdout as on')] + public function testSettingsRowsEdgeValues(): void + { + $rows = SystemReport::settingsRows( + [ + 'memory_limit' => '256M', + 'max_execution_time' => '30', + 'post_max_size' => '0', + 'upload_max_filesize' => '64M', + 'display_errors' => 'stdout', + ], + true + ); + + $this->assertSame(['healthy', 'healthy', 'healthy', 'healthy', 'warning'], array_column($rows, 'status')); + } + /** * @return void * From b0b5cf3be8aa007d43b1ec1676a4f09d65868c4a Mon Sep 17 00:00:00 2001 From: Brian Mitchell Date: Thu, 15 Oct 2026 12:27:56 +0200 Subject: [PATCH 07/29] Add Site Information health check plugin with versions and PHP settings tables Co-Authored-By: Claude Sonnet 5.5 --- .../sql/updates/mysql/6.2.0-2026-10-15.sql | 3 + .../updates/postgresql/6.2.0-2026-10-15.sql | 3 + .../en-GB/plg_healthcheck_siteinfo.ini | 48 +++ .../en-GB/plg_healthcheck_siteinfo.sys.ini | 7 + installation/sql/mysql/base.sql | 1 + installation/sql/postgresql/base.sql | 1 + libraries/src/Extension/ExtensionHelper.php | 1 + .../siteinfo/services/provider.php | 51 +++ .../siteinfo/src/Extension/Siteinfo.php | 367 ++++++++++++++++++ 9 files changed, 482 insertions(+) create mode 100644 administrator/components/com_admin/sql/updates/mysql/6.2.0-2026-10-15.sql create mode 100644 administrator/components/com_admin/sql/updates/postgresql/6.2.0-2026-10-15.sql create mode 100644 administrator/language/en-GB/plg_healthcheck_siteinfo.ini create mode 100644 administrator/language/en-GB/plg_healthcheck_siteinfo.sys.ini create mode 100644 plugins/healthcheck/siteinfo/services/provider.php create mode 100644 plugins/healthcheck/siteinfo/src/Extension/Siteinfo.php diff --git a/administrator/components/com_admin/sql/updates/mysql/6.2.0-2026-10-15.sql b/administrator/components/com_admin/sql/updates/mysql/6.2.0-2026-10-15.sql new file mode 100644 index 00000000000..60ea7190cc7 --- /dev/null +++ b/administrator/components/com_admin/sql/updates/mysql/6.2.0-2026-10-15.sql @@ -0,0 +1,3 @@ +INSERT INTO `#__extensions` (`package_id`, `name`, `type`, `element`, `folder`, `client_id`, `enabled`, `access`, `protected`, `locked`, `manifest_cache`, `params`, `custom_data`, `ordering`, `state`) +SELECT 0, 'plg_healthcheck_siteinfo', 'plugin', 'siteinfo', 'healthcheck', 0, 0, 1, 0, 1, '', '{"context":"general"}', '', 0, 0 +WHERE NOT EXISTS (SELECT * FROM `#__extensions` g WHERE g.`element` = 'siteinfo' AND g.`folder` = 'healthcheck'); diff --git a/administrator/components/com_admin/sql/updates/postgresql/6.2.0-2026-10-15.sql b/administrator/components/com_admin/sql/updates/postgresql/6.2.0-2026-10-15.sql new file mode 100644 index 00000000000..64f9336589e --- /dev/null +++ b/administrator/components/com_admin/sql/updates/postgresql/6.2.0-2026-10-15.sql @@ -0,0 +1,3 @@ +INSERT INTO "#__extensions" ("package_id", "name", "type", "element", "folder", "client_id", "enabled", "access", "protected", "locked", "manifest_cache", "params", "custom_data", "ordering", "state") +SELECT 0, 'plg_healthcheck_siteinfo', 'plugin', 'siteinfo', 'healthcheck', 0, 0, 1, 0, 1, '', '{"context":"general"}', '', 0, 0 +WHERE NOT EXISTS (SELECT * FROM "#__extensions" g WHERE g."element" = 'siteinfo' AND g."folder" = 'healthcheck'); diff --git a/administrator/language/en-GB/plg_healthcheck_siteinfo.ini b/administrator/language/en-GB/plg_healthcheck_siteinfo.ini new file mode 100644 index 00000000000..2d62b957349 --- /dev/null +++ b/administrator/language/en-GB/plg_healthcheck_siteinfo.ini @@ -0,0 +1,48 @@ +; Joomla! Project +; (C) 2026 Open Source Matters, Inc. +; License GNU General Public License version 2 or later; see LICENSE.txt +; Note : All ini files need to be saved as UTF-8 + +PLG_HEALTHCHECK_SITEINFO="Health Check - Site Information" +PLG_HEALTHCHECK_SITEINFO_COLUMN_COMPONENT="Component" +PLG_HEALTHCHECK_SITEINFO_COLUMN_CURRENT="Current Value" +PLG_HEALTHCHECK_SITEINFO_COLUMN_ENDS="Support Ends" +PLG_HEALTHCHECK_SITEINFO_COLUMN_RECOMMENDED="Recommended" +PLG_HEALTHCHECK_SITEINFO_COLUMN_SETTING="Setting" +PLG_HEALTHCHECK_SITEINFO_COLUMN_STATUS="Support Status" +PLG_HEALTHCHECK_SITEINFO_COLUMN_VERSION="Version" +PLG_HEALTHCHECK_SITEINFO_COMPONENT_DATABASE="Database" +PLG_HEALTHCHECK_SITEINFO_COMPONENT_OS="Operating System" +PLG_HEALTHCHECK_SITEINFO_COMPONENT_WEBSERVER="Web Server" +PLG_HEALTHCHECK_SITEINFO_GROUP_DESC="Health Check modules with the same group show this plugin's results." +PLG_HEALTHCHECK_SITEINFO_GROUP_LABEL="Health Check Group" +PLG_HEALTHCHECK_SITEINFO_ICON_REFRESH="Refresh Requirements" +PLG_HEALTHCHECK_SITEINFO_ICON_TEXT="Software Support" +PLG_HEALTHCHECK_SITEINFO_PRODUCT_JOOMLA="Joomla" +PLG_HEALTHCHECK_SITEINFO_PRODUCT_MARIADB="MariaDB" +PLG_HEALTHCHECK_SITEINFO_PRODUCT_MYSQL="MySQL" +PLG_HEALTHCHECK_SITEINFO_PRODUCT_PHP="PHP" +PLG_HEALTHCHECK_SITEINFO_PRODUCT_POSTGRESQL="PostgreSQL" +PLG_HEALTHCHECK_SITEINFO_RECOMMENDED_DISPLAY_ERRORS="Off on live sites" +PLG_HEALTHCHECK_SITEINFO_RECOMMENDED_EXECUTION="30 or more (0 is unlimited)" +PLG_HEALTHCHECK_SITEINFO_RECOMMENDED_MEMORY="%s or more" +PLG_HEALTHCHECK_SITEINFO_RECOMMENDED_OPCACHE="Enabled" +PLG_HEALTHCHECK_SITEINFO_RECOMMENDED_POST="At least upload_max_filesize (%s)" +PLG_HEALTHCHECK_SITEINFO_REFRESH_DONE="Joomla requirements refreshed from manual.joomla.org." +PLG_HEALTHCHECK_SITEINFO_REFRESH_FAILED="Could not refresh Joomla requirements from manual.joomla.org. The previous values are still used. %s" +PLG_HEALTHCHECK_SITEINFO_REFRESH_RECENT="Joomla requirements were refreshed less than an hour ago, so they were not fetched again." +PLG_HEALTHCHECK_SITEINFO_REQUIREMENT_BELOW_MINIMUM="Below Joomla's minimum version %s" +PLG_HEALTHCHECK_SITEINFO_REQUIREMENT_BELOW_RECOMMENDED="Joomla recommends %s" +PLG_HEALTHCHECK_SITEINFO_REQUIREMENT_BELOW_SUPPORTED="Below Joomla's supported version %s" +PLG_HEALTHCHECK_SITEINFO_STATUS_EOL_OLD="End of life" +PLG_HEALTHCHECK_SITEINFO_STATUS_EOL_PAST="End of life since %s" +PLG_HEALTHCHECK_SITEINFO_STATUS_EOL_SOON="End of life on %s" +PLG_HEALTHCHECK_SITEINFO_STATUS_NEWER="Newer than known support data" +PLG_HEALTHCHECK_SITEINFO_STATUS_NO_DATA="No support data" +PLG_HEALTHCHECK_SITEINFO_STATUS_SECURITY_ONLY="Security fixes only until %s" +PLG_HEALTHCHECK_SITEINFO_STATUS_SUPPORTED="Supported until %s" +PLG_HEALTHCHECK_SITEINFO_STATUS_UNKNOWN="Unknown" +PLG_HEALTHCHECK_SITEINFO_TABLE_SETTINGS="PHP Settings" +PLG_HEALTHCHECK_SITEINFO_TABLE_VERSIONS_BUILTIN="Software Versions. Joomla requirements: shipped with Joomla." +PLG_HEALTHCHECK_SITEINFO_TABLE_VERSIONS_MANUAL="Software Versions. Joomla requirements: manual.joomla.org, retrieved %s." +PLG_HEALTHCHECK_SITEINFO_XML_DESCRIPTION="Shows the versions of PHP, the database, Joomla, the web server and the operating system, whether each is still supported, and checks PHP settings against Joomla's recommendations." diff --git a/administrator/language/en-GB/plg_healthcheck_siteinfo.sys.ini b/administrator/language/en-GB/plg_healthcheck_siteinfo.sys.ini new file mode 100644 index 00000000000..6938a08f504 --- /dev/null +++ b/administrator/language/en-GB/plg_healthcheck_siteinfo.sys.ini @@ -0,0 +1,7 @@ +; Joomla! Project +; (C) 2026 Open Source Matters, Inc. +; License GNU General Public License version 2 or later; see LICENSE.txt +; Note : All ini files need to be saved as UTF-8 + +PLG_HEALTHCHECK_SITEINFO="Health Check - Site Information" +PLG_HEALTHCHECK_SITEINFO_XML_DESCRIPTION="Shows the versions of PHP, the database, Joomla, the web server and the operating system, whether each is still supported, and checks PHP settings against Joomla's recommendations." diff --git a/installation/sql/mysql/base.sql b/installation/sql/mysql/base.sql index 469264ea804..b69b9b51bef 100644 --- a/installation/sql/mysql/base.sql +++ b/installation/sql/mysql/base.sql @@ -318,6 +318,7 @@ INSERT INTO `#__extensions` (`package_id`, `name`, `type`, `element`, `folder`, (0, 'plg_finder_newsfeeds', 'plugin', 'newsfeeds', 'finder', 0, 1, 1, 0, 1, '', '', '', 4, 0), (0, 'plg_finder_tags', 'plugin', 'tags', 'finder', 0, 1, 1, 0, 1, '', '', '', 5, 0), (0, 'plg_healthcheck_usermaintenance', 'plugin', 'usermaintenance', 'healthcheck', 0, 0, 1, 0, 1, '', '{"context":"general"}', '', 1, 0), +(0, 'plg_healthcheck_siteinfo', 'plugin', 'siteinfo', 'healthcheck', 0, 0, 1, 0, 1, '', '{"context":"general"}', '', 2, 0), (0, 'plg_installer_folderinstaller', 'plugin', 'folderinstaller', 'installer', 0, 1, 1, 0, 1, '', '', '', 2, 0), (0, 'plg_installer_override', 'plugin', 'override', 'installer', 0, 1, 1, 0, 1, '', '', '', 4, 0), (0, 'plg_installer_packageinstaller', 'plugin', 'packageinstaller', 'installer', 0, 1, 1, 0, 1, '', '', '', 1, 0), diff --git a/installation/sql/postgresql/base.sql b/installation/sql/postgresql/base.sql index 232e7c6633b..f1185b9d196 100644 --- a/installation/sql/postgresql/base.sql +++ b/installation/sql/postgresql/base.sql @@ -324,6 +324,7 @@ INSERT INTO "#__extensions" ("package_id", "name", "type", "element", "folder", (0, 'plg_finder_newsfeeds', 'plugin', 'newsfeeds', 'finder', 0, 1, 1, 0, 1, '', '', '', 4, 0), (0, 'plg_finder_tags', 'plugin', 'tags', 'finder', 0, 1, 1, 0, 1, '', '', '', 5, 0), (0, 'plg_healthcheck_usermaintenance', 'plugin', 'usermaintenance', 'healthcheck', 0, 0, 1, 0, 1, '', '{"context":"general"}', '', 1, 0), +(0, 'plg_healthcheck_siteinfo', 'plugin', 'siteinfo', 'healthcheck', 0, 0, 1, 0, 1, '', '{"context":"general"}', '', 2, 0), (0, 'plg_installer_folderinstaller', 'plugin', 'folderinstaller', 'installer', 0, 1, 1, 0, 1, '', '', '', 2, 0), (0, 'plg_installer_override', 'plugin', 'override', 'installer', 0, 1, 1, 0, 1, '', '', '', 4, 0), (0, 'plg_installer_packageinstaller', 'plugin', 'packageinstaller', 'installer', 0, 1, 1, 0, 1, '', '', '', 1, 0), diff --git a/libraries/src/Extension/ExtensionHelper.php b/libraries/src/Extension/ExtensionHelper.php index 7a744b00b1c..9e9bd4bddbe 100644 --- a/libraries/src/Extension/ExtensionHelper.php +++ b/libraries/src/Extension/ExtensionHelper.php @@ -246,6 +246,7 @@ class ExtensionHelper // Core plugin extensions - healthcheck ['plugin', 'usermaintenance', 'healthcheck', 0], + ['plugin', 'siteinfo', 'healthcheck', 0], // Core plugin extensions - installer ['plugin', 'folderinstaller', 'installer', 0], diff --git a/plugins/healthcheck/siteinfo/services/provider.php b/plugins/healthcheck/siteinfo/services/provider.php new file mode 100644 index 00000000000..2e2bdcb338e --- /dev/null +++ b/plugins/healthcheck/siteinfo/services/provider.php @@ -0,0 +1,51 @@ + + * @license GNU General Public License version 2 or later; see LICENSE.txt + */ + +\defined('_JEXEC') or die; + +use Joomla\CMS\Cache\CacheControllerFactoryInterface; +use Joomla\CMS\Extension\PluginInterface; +use Joomla\CMS\Factory; +use Joomla\CMS\Plugin\PluginHelper; +use Joomla\Database\DatabaseInterface; +use Joomla\DI\Container; +use Joomla\DI\ServiceProviderInterface; +use Joomla\Http\HttpFactory; +use Joomla\Plugin\Healthcheck\Siteinfo\Extension\Siteinfo; + +return new class () implements ServiceProviderInterface { + /** + * Registers the service provider with a DI container. + * + * @param Container $container The DI container. + * + * @return void + * + * @since __DEPLOY_VERSION__ + */ + public function register(Container $container): void + { + $container->set( + PluginInterface::class, + $container->lazy(Siteinfo::class, function (Container $container): Siteinfo { + $plugin = new Siteinfo( + (array) PluginHelper::getPlugin('healthcheck', 'siteinfo'), + new HttpFactory() + ); + + $plugin->setApplication(Factory::getApplication()); + $plugin->setDatabase($container->get(DatabaseInterface::class)); + $plugin->setCacheControllerFactory($container->get(CacheControllerFactoryInterface::class)); + + return $plugin; + }) + ); + } +}; diff --git a/plugins/healthcheck/siteinfo/src/Extension/Siteinfo.php b/plugins/healthcheck/siteinfo/src/Extension/Siteinfo.php new file mode 100644 index 00000000000..8a2b3b499b9 --- /dev/null +++ b/plugins/healthcheck/siteinfo/src/Extension/Siteinfo.php @@ -0,0 +1,367 @@ + + * @license GNU General Public License version 2 or later; see LICENSE.txt + */ + +namespace Joomla\Plugin\Healthcheck\Siteinfo\Extension; + +use Joomla\CMS\Cache\CacheControllerFactoryAwareTrait; +use Joomla\CMS\Cache\Controller\OutputController; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Plugin\CMSPlugin; +use Joomla\CMS\Session\Session; +use Joomla\CMS\Uri\Uri; +use Joomla\Database\DatabaseAwareTrait; +use Joomla\Event\SubscriberInterface; +use Joomla\Http\HttpFactory; +use Joomla\Module\Healthcheck\Administrator\Event\HealthChecksEvent; +use Joomla\Plugin\Healthcheck\Siteinfo\Support\SupportData; +use Joomla\Plugin\Healthcheck\Siteinfo\Support\SystemReport; + +// phpcs:disable PSR1.Files.SideEffects +\defined('_JEXEC') or die; +// phpcs:enable PSR1.Files.SideEffects + +/** + * Health Check plugin reporting software versions, their support status and PHP settings + * + * @since __DEPLOY_VERSION__ + */ +final class Siteinfo extends CMSPlugin implements SubscriberInterface +{ + use CacheControllerFactoryAwareTrait; + use DatabaseAwareTrait; + + /** + * Cache group and id of the requirements refreshed from the manual + * + * @since __DEPLOY_VERSION__ + */ + private const CACHE_GROUP = 'plg_healthcheck_siteinfo'; + private const STORE_ID = 'requirements'; + + /** + * Constructor + * + * @param array $config The plugin configuration + * @param HttpFactory $httpFactory The HTTP factory used to refresh requirements from the manual + * + * @since __DEPLOY_VERSION__ + */ + public function __construct(array $config, private readonly HttpFactory $httpFactory) + { + parent::__construct($config); + } + + /** + * Returns an array of events this subscriber will listen to. + * + * @return array + * + * @since __DEPLOY_VERSION__ + */ + public static function getSubscribedEvents(): array + { + return [ + 'onHealthcheckGetIcons' => 'onHealthcheckGetIcons', + 'onHealthcheckGetTables' => 'onHealthcheckGetTables', + ]; + } + + /** + * Adds the Software Support icon and the Refresh Requirements button. + * + * @param HealthChecksEvent $event The health-check event object. + * + * @return void + * + * @since __DEPLOY_VERSION__ + */ + public function onHealthcheckGetIcons(HealthChecksEvent $event): void + { + if (!$this->isAllowed($event)) { + return; + } + + $rows = $this->collectVersionRows($this->readStored()); + $attention = array_filter($rows, static fn (array $row): bool => \in_array($row['status'], [SupportData::STATUS_CRITICAL, SupportData::STATUS_WARNING], true)); + $return = base64_encode(Uri::getInstance()->toString()); + + $result = $event->getArgument('result', []); + $result[] = [ + [ + 'link' => '#plg_healthcheck_siteinfo_versions', + 'icon' => 'fas fa-server', + 'amount' => \count($attention), + 'text' => Text::_('PLG_HEALTHCHECK_SITEINFO_ICON_TEXT'), + 'id' => 'plg_healthcheck_siteinfo_support', + 'status' => $this->tableStatus(array_column($rows, 'status')), + ], + [ + 'link' => 'index.php?option=com_ajax&group=healthcheck&plugin=siteinfo&format=raw&' . Session::getFormToken() . '=1&return=' . urlencode($return), + 'icon' => 'fas fa-rotate', + 'text' => Text::_('PLG_HEALTHCHECK_SITEINFO_ICON_REFRESH'), + 'id' => 'plg_healthcheck_siteinfo_refresh', + ], + ]; + + $event->setArgument('result', $result); + } + + /** + * Adds the Software Versions and PHP Settings tables. + * + * @param HealthChecksEvent $event The health-check event object. + * + * @return void + * + * @since __DEPLOY_VERSION__ + */ + public function onHealthcheckGetTables(HealthChecksEvent $event): void + { + if (!$this->isAllowed($event)) { + return; + } + + $stored = $this->readStored(); + $rows = $this->collectVersionRows($stored); + + $versions = [ + 'id' => 'plg_healthcheck_siteinfo_versions', + 'caption' => $stored ? Text::sprintf('PLG_HEALTHCHECK_SITEINFO_TABLE_VERSIONS_MANUAL', $stored['retrieved']) : Text::_('PLG_HEALTHCHECK_SITEINFO_TABLE_VERSIONS_BUILTIN'), + 'status' => $this->tableStatus(array_column($rows, 'status')), + 'columns' => [ + ['key' => 'label', 'title' => Text::_('PLG_HEALTHCHECK_SITEINFO_COLUMN_COMPONENT')], + ['key' => 'version', 'title' => Text::_('PLG_HEALTHCHECK_SITEINFO_COLUMN_VERSION')], + [ + 'key' => 'text', + 'title' => Text::_('PLG_HEALTHCHECK_SITEINFO_COLUMN_STATUS'), + 'type' => 'badge', + 'badgeClass' => static fn ($value, $item): string => self::badgeClass($item['status']), + ], + ['key' => 'ends', 'title' => Text::_('PLG_HEALTHCHECK_SITEINFO_COLUMN_ENDS')], + ], + 'data' => $rows, + ]; + + $settings = $this->collectSettingsRows($stored['memory'] ?? null); + + $settingsTable = [ + 'id' => 'plg_healthcheck_siteinfo_settings', + 'caption' => Text::_('PLG_HEALTHCHECK_SITEINFO_TABLE_SETTINGS'), + 'status' => $this->tableStatus(array_column($settings, 'status')), + 'columns' => [ + ['key' => 'setting', 'title' => Text::_('PLG_HEALTHCHECK_SITEINFO_COLUMN_SETTING')], + [ + 'key' => 'current', + 'title' => Text::_('PLG_HEALTHCHECK_SITEINFO_COLUMN_CURRENT'), + 'type' => 'badge', + 'badgeClass' => static fn ($value, $item): string => self::badgeClass($item['status']), + ], + ['key' => 'recommended', 'title' => Text::_('PLG_HEALTHCHECK_SITEINFO_COLUMN_RECOMMENDED')], + ], + 'data' => $settings, + ]; + + $result = $event->getArgument('result', []); + $result[] = [$versions, $settingsTable]; + + $event->setArgument('result', $result); + } + + /** + * Whether this plugin should answer the event: right group and a user allowed to see server details. + * + * @param HealthChecksEvent $event The health-check event object. + * + * @return boolean + * + * @since __DEPLOY_VERSION__ + */ + private function isAllowed(HealthChecksEvent $event): bool + { + if ($event->getContext() !== $this->params->get('context', 'general')) { + return false; + } + + if (!$this->getApplication()->getIdentity()->authorise('core.admin')) { + return false; + } + + $this->loadLanguage(); + + return true; + } + + /** + * Detect versions and build translated table rows. + * + * @param array|null $stored Requirements refreshed from the manual, if any + * + * @return array List of ['label', 'version', 'status', 'text', 'ends'] + * + * @since __DEPLOY_VERSION__ + */ + private function collectVersionRows(?array $stored): array + { + $report = new SystemReport(new SupportData($stored['requirements'] ?? []), new \DateTimeImmutable('today', new \DateTimeZone('UTC'))); + $rows = []; + + $rows[] = $this->translateRow(Text::_('PLG_HEALTHCHECK_SITEINFO_PRODUCT_PHP'), $report->versionRow('php', PHP_VERSION)); + + try { + $db = $this->getDatabase(); + $product = $db->getServerType() === 'postgresql' ? 'postgresql' : (method_exists($db, 'isMariaDb') && $db->isMariaDb() ? 'mariadb' : 'mysql'); + $label = Text::_('PLG_HEALTHCHECK_SITEINFO_PRODUCT_' . strtoupper($product)); + $rows[] = $this->translateRow($label, $report->versionRow($product, (string) $db->getVersion())); + } catch (\Throwable $e) { + $rows[] = $this->translateRow(Text::_('PLG_HEALTHCHECK_SITEINFO_COMPONENT_DATABASE'), $report->versionRow('mysql', '')); + } + + $rows[] = $this->translateRow(Text::_('PLG_HEALTHCHECK_SITEINFO_PRODUCT_JOOMLA'), $report->versionRow('joomla', JVERSION)); + + $server = SystemReport::parseServerSoftware($this->getApplication()->getInput()->server->getString('SERVER_SOFTWARE', '')); + $label = Text::_('PLG_HEALTHCHECK_SITEINFO_COMPONENT_WEBSERVER') . ($server['name'] !== '' ? ' (' . $server['name'] . ')' : ''); + + if ($server['product'] !== null) { + $rows[] = $this->translateRow($label, $report->versionRow($server['product'], $server['version'])); + } else { + $rows[] = ['label' => $label, 'version' => $server['version'], 'status' => SupportData::STATUS_NONE, 'text' => '', 'ends' => '']; + } + + $rows[] = [ + 'label' => Text::_('PLG_HEALTHCHECK_SITEINFO_COMPONENT_OS'), + 'version' => PHP_OS_FAMILY . ' ' . php_uname('r'), + 'status' => SupportData::STATUS_NONE, + 'text' => '', + 'ends' => '', + ]; + + return $rows; + } + + /** + * Translate the messages of a report row. + * + * @param string $label The component label + * @param array $row A row from SystemReport::versionRow() + * + * @return array ['label', 'version', 'status', 'text', 'ends'] + * + * @since __DEPLOY_VERSION__ + */ + private function translateRow(string $label, array $row): array + { + $messages = array_map(static fn (array $message): string => Text::sprintf($message[0], ...$message[1]), $row['messages']); + + return [ + 'label' => $label, + 'version' => $row['version'], + 'status' => $row['status'], + 'text' => implode('. ', $messages), + 'ends' => $row['ends'], + ]; + } + + /** + * Read PHP settings and build translated table rows. + * + * @param string|null $memoryLimit Memory limit refreshed from the manual, if any + * + * @return array List of ['setting', 'current', 'recommended', 'status'] + * + * @since __DEPLOY_VERSION__ + */ + private function collectSettingsRows(?string $memoryLimit): array + { + $ini = []; + + foreach (['memory_limit', 'max_execution_time', 'post_max_size', 'upload_max_filesize', 'display_errors'] as $setting) { + $ini[$setting] = (string) \ini_get($setting); + } + + $opcache = \function_exists('opcache_get_status') && \is_array(@opcache_get_status(false)) && (bool) \ini_get('opcache.enable'); + $rows = SystemReport::settingsRows($ini, $opcache, $memoryLimit ?? SystemReport::MEMORY_LIMIT); + + foreach ($rows as &$row) { + if (str_starts_with($row['current'], 'J')) { + $row['current'] = Text::_($row['current']); + } + + $row['recommended'] = Text::sprintf($row['recommended'][0], ...$row['recommended'][1]); + } + + return $rows; + } + + /** + * Map a plugin status to the table layout status. + * + * @param array $statuses Row statuses + * + * @return string success, warning or error + * + * @since __DEPLOY_VERSION__ + */ + private function tableStatus(array $statuses): string + { + return match (SystemReport::worst($statuses)) { + SupportData::STATUS_CRITICAL => 'error', + SupportData::STATUS_WARNING => 'warning', + default => 'success', + }; + } + + /** + * Map a plugin status to a Bootstrap badge colour. + * + * @param string $status The status + * + * @return string + * + * @since __DEPLOY_VERSION__ + */ + private static function badgeClass(string $status): string + { + return match ($status) { + SupportData::STATUS_CRITICAL => 'danger', + SupportData::STATUS_WARNING => 'warning', + SupportData::STATUS_HEALTHY => 'success', + default => 'secondary', + }; + } + + /** + * Get the cache controller holding requirements refreshed from the manual. + * + * @return OutputController + * + * @since __DEPLOY_VERSION__ + */ + private function store(): OutputController + { + return $this->getCacheControllerFactory()->createCacheController( + 'output', + ['defaultgroup' => self::CACHE_GROUP, 'caching' => true, 'lifetime' => 43200] + ); + } + + /** + * Read requirements refreshed from the manual, without fetching. + * + * @return array|null ['fetched' => int, 'retrieved' => 'Y-m-d', 'requirements' => array, 'memory' => ?string] or null + * + * @since __DEPLOY_VERSION__ + */ + private function readStored(): ?array + { + $stored = $this->store()->get(self::STORE_ID); + + return \is_array($stored) ? $stored : null; + } +} From 23cb870f90f50405f1726ef4b1e7665eaadc9ab6 Mon Sep 17 00:00:00 2001 From: Brian Mitchell Date: Thu, 15 Oct 2026 12:30:46 +0200 Subject: [PATCH 08/29] Refresh Site Information requirements from the Joomla manual on demand Co-Authored-By: Claude Sonnet 5.5 --- .../siteinfo/src/Extension/Siteinfo.php | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/plugins/healthcheck/siteinfo/src/Extension/Siteinfo.php b/plugins/healthcheck/siteinfo/src/Extension/Siteinfo.php index 8a2b3b499b9..f9db8e5488d 100644 --- a/plugins/healthcheck/siteinfo/src/Extension/Siteinfo.php +++ b/plugins/healthcheck/siteinfo/src/Extension/Siteinfo.php @@ -12,7 +12,9 @@ use Joomla\CMS\Cache\CacheControllerFactoryAwareTrait; use Joomla\CMS\Cache\Controller\OutputController; +use Joomla\CMS\Event\Plugin\AjaxEvent; use Joomla\CMS\Language\Text; +use Joomla\CMS\Log\Log; use Joomla\CMS\Plugin\CMSPlugin; use Joomla\CMS\Session\Session; use Joomla\CMS\Uri\Uri; @@ -70,6 +72,7 @@ public static function getSubscribedEvents(): array return [ 'onHealthcheckGetIcons' => 'onHealthcheckGetIcons', 'onHealthcheckGetTables' => 'onHealthcheckGetTables', + 'onAjaxSiteinfo' => 'onAjaxSiteinfo', ]; } @@ -174,6 +177,54 @@ public function onHealthcheckGetTables(HealthChecksEvent $event): void $event->setArgument('result', $result); } + /** + * Refreshes Joomla's requirements from the manual when a Super User clicks Refresh Requirements. + * + * @param AjaxEvent $event The Ajax event + * + * @return void + * + * @throws \RuntimeException On a missing token or permission + * + * @since __DEPLOY_VERSION__ + */ + public function onAjaxSiteinfo(AjaxEvent $event): void + { + $app = $this->getApplication(); + + if (!Session::checkToken('get') || !$app->getIdentity()->authorise('core.admin')) { + throw new \RuntimeException(Text::_('JERROR_ALERTNOAUTHOR'), 403); + } + + $this->loadLanguage(); + + $stored = $this->readStored(); + + if ($stored !== null && time() - $stored['fetched'] < 3600) { + $app->enqueueMessage(Text::_('PLG_HEALTHCHECK_SITEINFO_REFRESH_RECENT'), 'info'); + } else { + try { + $response = $this->httpFactory->getHttp()->get(SupportData::MANUAL_URL, [], 5); + + if ($response->getStatusCode() !== 200) { + throw new \RuntimeException('HTTP ' . $response->getStatusCode()); + } + + $parsed = SupportData::parseManual((string) $response->getBody(), (int) JVERSION); + + $this->store()->store(['fetched' => time(), 'retrieved' => gmdate('Y-m-d')] + $parsed, self::STORE_ID); + $app->enqueueMessage(Text::_('PLG_HEALTHCHECK_SITEINFO_REFRESH_DONE'), 'success'); + } catch (\Throwable $e) { + Log::add('Site Information: could not refresh requirements from the manual: ' . $e->getMessage(), Log::WARNING, 'healthcheck'); + $app->enqueueMessage(Text::sprintf('PLG_HEALTHCHECK_SITEINFO_REFRESH_FAILED', $e->getMessage()), 'warning'); + } + } + + $return = base64_decode($app->getInput()->getBase64('return', '')); + + $app->redirect(Uri::isInternal($return) ? $return : 'index.php?option=com_cpanel&view=cpanel&dashboard=healthcheck'); + } + /** * Whether this plugin should answer the event: right group and a user allowed to see server details. * From ef29c187e009526e4934c18c9206c74aa28b5441 Mon Sep 17 00:00:00 2001 From: Brian Mitchell Date: Thu, 15 Oct 2026 12:34:17 +0200 Subject: [PATCH 09/29] Apply coding standards to Site Information plugin Co-Authored-By: Claude Sonnet 5.5 --- .../Siteinfo/Support/SupportDataTest.php | 48 +++++++++---------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php b/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php index c63c4bf21c8..cffadba12de 100644 --- a/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php +++ b/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php @@ -44,13 +44,13 @@ private function today(): \DateTimeImmutable public static function normalizeProvider(): array { return [ - 'plain' => ['8.4.1', '8.4.1'], - 'mariadb suffix' => ['11.8.3-MariaDB-ubu2404', '11.8.3'], - 'ubuntu mysql' => ['8.0.36-0ubuntu0.22.04.1', '8.0.36'], - 'joomla dev' => ['6.2.1-dev', '6.2.1'], - 'joomla alpha' => ['6.3.0-alpha1', '6.3.0'], - 'not a version' => ['unknown', ''], - 'empty' => ['', ''], + 'plain' => ['8.4.1', '8.4.1'], + 'mariadb suffix' => ['11.8.3-MariaDB-ubu2404', '11.8.3'], + 'ubuntu mysql' => ['8.0.36-0ubuntu0.22.04.1', '8.0.36'], + 'joomla dev' => ['6.2.1-dev', '6.2.1'], + 'joomla alpha' => ['6.3.0-alpha1', '6.3.0'], + 'not a version' => ['unknown', ''], + 'empty' => ['', ''], ]; } @@ -104,17 +104,17 @@ public function testCycleFor(string $product, string $version, string $expected) public static function eolProvider(): array { return [ - 'eol passed' => ['php', '8.1.2', 'critical', 'PLG_HEALTHCHECK_SITEINFO_STATUS_EOL_PAST', ['2025-12-31']], - 'eol within 6 months' => ['php', '8.2.5', 'warning', 'PLG_HEALTHCHECK_SITEINFO_STATUS_EOL_SOON', ['2026-12-31']], - 'security fixes only' => ['php', '8.3.10', 'warning', 'PLG_HEALTHCHECK_SITEINFO_STATUS_SECURITY_ONLY', ['2027-12-31']], - 'supported' => ['mariadb', '11.8.3', 'healthy', 'PLG_HEALTHCHECK_SITEINFO_STATUS_SUPPORTED', ['2028-06-04']], - 'mariadb dev site' => ['mariadb', '12.2.2-MariaDB', 'critical', 'PLG_HEALTHCHECK_SITEINFO_STATUS_EOL_PAST', ['2026-05-28']], - 'older than known' => ['php', '5.6.40', 'critical', 'PLG_HEALTHCHECK_SITEINFO_STATUS_EOL_OLD', []], - 'newer than known' => ['php', '9.0.0', 'healthy', 'PLG_HEALTHCHECK_SITEINFO_STATUS_NEWER', []], - 'gap in known cycles' => ['mysql', '8.5.0', 'none', 'PLG_HEALTHCHECK_SITEINFO_STATUS_NO_DATA', []], - 'joomla dev version' => ['joomla', '6.2.1-dev', 'healthy', 'PLG_HEALTHCHECK_SITEINFO_STATUS_SUPPORTED', ['2029-10-16']], - 'empty version' => ['mysql', '', 'none', 'PLG_HEALTHCHECK_SITEINFO_STATUS_NO_DATA', []], - 'unparseable version' => ['php', 'unknown', 'none', 'PLG_HEALTHCHECK_SITEINFO_STATUS_NO_DATA', []], + 'eol passed' => ['php', '8.1.2', 'critical', 'PLG_HEALTHCHECK_SITEINFO_STATUS_EOL_PAST', ['2025-12-31']], + 'eol within 6 months' => ['php', '8.2.5', 'warning', 'PLG_HEALTHCHECK_SITEINFO_STATUS_EOL_SOON', ['2026-12-31']], + 'security fixes only' => ['php', '8.3.10', 'warning', 'PLG_HEALTHCHECK_SITEINFO_STATUS_SECURITY_ONLY', ['2027-12-31']], + 'supported' => ['mariadb', '11.8.3', 'healthy', 'PLG_HEALTHCHECK_SITEINFO_STATUS_SUPPORTED', ['2028-06-04']], + 'mariadb dev site' => ['mariadb', '12.2.2-MariaDB', 'critical', 'PLG_HEALTHCHECK_SITEINFO_STATUS_EOL_PAST', ['2026-05-28']], + 'older than known' => ['php', '5.6.40', 'critical', 'PLG_HEALTHCHECK_SITEINFO_STATUS_EOL_OLD', []], + 'newer than known' => ['php', '9.0.0', 'healthy', 'PLG_HEALTHCHECK_SITEINFO_STATUS_NEWER', []], + 'gap in known cycles' => ['mysql', '8.5.0', 'none', 'PLG_HEALTHCHECK_SITEINFO_STATUS_NO_DATA', []], + 'joomla dev version' => ['joomla', '6.2.1-dev', 'healthy', 'PLG_HEALTHCHECK_SITEINFO_STATUS_SUPPORTED', ['2029-10-16']], + 'empty version' => ['mysql', '', 'none', 'PLG_HEALTHCHECK_SITEINFO_STATUS_NO_DATA', []], + 'unparseable version' => ['php', 'unknown', 'none', 'PLG_HEALTHCHECK_SITEINFO_STATUS_NO_DATA', []], ]; } @@ -169,12 +169,12 @@ public function testHasEolData(): void public static function requirementProvider(): array { return [ - 'below minimum' => ['mariadb', '10.3.39', 'critical', 'PLG_HEALTHCHECK_SITEINFO_REQUIREMENT_BELOW_MINIMUM', ['10.4']], - 'below supported' => ['mariadb', '10.4.34', 'warning', 'PLG_HEALTHCHECK_SITEINFO_REQUIREMENT_BELOW_SUPPORTED', ['10.6']], - 'below recommended' => ['mariadb', '11.8.3-MariaDB', 'none', 'PLG_HEALTHCHECK_SITEINFO_REQUIREMENT_BELOW_RECOMMENDED', ['12.0']], - 'web server note' => ['nginx', '1.26.0', 'none', 'PLG_HEALTHCHECK_SITEINFO_REQUIREMENT_BELOW_RECOMMENDED', ['1.29']], - 'web server old' => ['nginx', '1.24.0', 'warning', 'PLG_HEALTHCHECK_SITEINFO_REQUIREMENT_BELOW_SUPPORTED', ['1.26']], - 'php minimum' => ['php', '8.2.29', 'critical', 'PLG_HEALTHCHECK_SITEINFO_REQUIREMENT_BELOW_MINIMUM', ['8.3.0']], + 'below minimum' => ['mariadb', '10.3.39', 'critical', 'PLG_HEALTHCHECK_SITEINFO_REQUIREMENT_BELOW_MINIMUM', ['10.4']], + 'below supported' => ['mariadb', '10.4.34', 'warning', 'PLG_HEALTHCHECK_SITEINFO_REQUIREMENT_BELOW_SUPPORTED', ['10.6']], + 'below recommended' => ['mariadb', '11.8.3-MariaDB', 'none', 'PLG_HEALTHCHECK_SITEINFO_REQUIREMENT_BELOW_RECOMMENDED', ['12.0']], + 'web server note' => ['nginx', '1.26.0', 'none', 'PLG_HEALTHCHECK_SITEINFO_REQUIREMENT_BELOW_RECOMMENDED', ['1.29']], + 'web server old' => ['nginx', '1.24.0', 'warning', 'PLG_HEALTHCHECK_SITEINFO_REQUIREMENT_BELOW_SUPPORTED', ['1.26']], + 'php minimum' => ['php', '8.2.29', 'critical', 'PLG_HEALTHCHECK_SITEINFO_REQUIREMENT_BELOW_MINIMUM', ['8.3.0']], ]; } From c3d09ee8a6dd1a0ce63e6657d24ff0f3d9d77604 Mon Sep 17 00:00:00 2001 From: Brian Mitchell Date: Thu, 15 Oct 2026 12:52:09 +0200 Subject: [PATCH 10/29] Siteinfo: complete MariaDB cycles and harden manual parsing Add the missing MariaDB cycles (10.7-10.10, 11.0-11.3, 11.5-11.7), parse only a table that directly follows its heading, reject non-numeric version cells, and cite the manual page the refresh actually reads. Co-Authored-By: Claude Sonnet 5.5 --- .../siteinfo/src/Support/SupportData.php | 28 ++++++-- .../Siteinfo/Support/SupportDataTest.php | 71 +++++++++++++++++++ 2 files changed, 95 insertions(+), 4 deletions(-) diff --git a/plugins/healthcheck/siteinfo/src/Support/SupportData.php b/plugins/healthcheck/siteinfo/src/Support/SupportData.php index 3118426fd80..0d8482158fe 100644 --- a/plugins/healthcheck/siteinfo/src/Support/SupportData.php +++ b/plugins/healthcheck/siteinfo/src/Support/SupportData.php @@ -43,7 +43,8 @@ final class SupportData /** * Built-in release cycles: active = end of full support (null if not published), eol = end of security fixes. - * Source: https://endoflife.date (retrieved 2026-10-15) + * Source: https://endoflife.date (retrieved 2026-10-15). Include every cycle at or above Joomla's minimum + * supported version (PHP 8.3, MySQL 8.0, MariaDB 10.4, PostgreSQL 12), including cycles already end of life. * * @since __DEPLOY_VERSION__ */ @@ -77,8 +78,19 @@ final class SupportData '10.4' => ['active' => null, 'eol' => '2024-06-18'], '10.5' => ['active' => null, 'eol' => '2025-06-24'], '10.6' => ['active' => null, 'eol' => '2026-07-06'], + '10.7' => ['active' => null, 'eol' => '2023-02-09'], + '10.8' => ['active' => null, 'eol' => '2023-05-20'], + '10.9' => ['active' => null, 'eol' => '2023-08-22'], + '10.10' => ['active' => null, 'eol' => '2023-11-17'], '10.11' => ['active' => null, 'eol' => '2028-02-16'], + '11.0' => ['active' => null, 'eol' => '2024-06-06'], + '11.1' => ['active' => null, 'eol' => '2024-08-21'], + '11.2' => ['active' => null, 'eol' => '2024-11-21'], + '11.3' => ['active' => null, 'eol' => '2024-05-29'], '11.4' => ['active' => null, 'eol' => '2029-05-29'], + '11.5' => ['active' => null, 'eol' => '2024-11-21'], + '11.6' => ['active' => null, 'eol' => '2025-02-13'], + '11.7' => ['active' => null, 'eol' => '2025-05-12'], '11.8' => ['active' => null, 'eol' => '2028-06-04'], '12.0' => ['active' => null, 'eol' => '2025-11-18'], '12.1' => ['active' => null, 'eol' => '2026-02-13'], @@ -105,7 +117,7 @@ final class SupportData /** * Joomla 6.x requirements: [recommended, supported, minimum]. Minimum null = not enforced. - * Source: https://manual.joomla.org/docs/next/get-started/technical-requirements/ (retrieved 2026-10-15) + * Source: https://manual.joomla.org/docs/get-started/technical-requirements/ (the page SupportData::MANUAL_URL refreshes from, retrieved 2026-10-15) * * @since __DEPLOY_VERSION__ */ @@ -342,7 +354,7 @@ public static function parseManual(string $html, int $major): array $xpath = new \DOMXPath($document); $heading = 'Requirements for Joomla! ' . $major . '.x'; - $table = $xpath->query('(//h2|//h3)[contains(normalize-space(.), "' . $heading . '")]/following-sibling::table[1]')->item(0); + $table = $xpath->query('(//h2|//h3)[contains(normalize-space(.), "' . $heading . '")]/following-sibling::*[self::table or self::h2 or self::h3][1][self::table]')->item(0); if ($table === null) { throw new \UnexpectedValueException('No "' . $heading . '" table on the manual page'); @@ -358,7 +370,15 @@ public static function parseManual(string $html, int $major): array continue; } - $requirements[$product] = [$cells[1], $cells[2], $cells[3] === '' ? null : $cells[3]]; + $minimum = $cells[3] === '' ? null : $cells[3]; + + foreach ([$cells[1], $cells[2], $minimum] as $value) { + if ($value !== null && !preg_match('/^\d+(\.\d+)*$/', $value)) { + throw new \UnexpectedValueException('Unexpected version "' . $value . '" for ' . $cells[0] . ' in the "' . $heading . '" table'); + } + } + + $requirements[$product] = [$cells[1], $cells[2], $minimum]; } if (!isset($requirements['php'])) { diff --git a/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php b/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php index cffadba12de..d4ea7f07e81 100644 --- a/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php +++ b/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php @@ -108,6 +108,8 @@ public static function eolProvider(): array 'eol within 6 months' => ['php', '8.2.5', 'warning', 'PLG_HEALTHCHECK_SITEINFO_STATUS_EOL_SOON', ['2026-12-31']], 'security fixes only' => ['php', '8.3.10', 'warning', 'PLG_HEALTHCHECK_SITEINFO_STATUS_SECURITY_ONLY', ['2027-12-31']], 'supported' => ['mariadb', '11.8.3', 'healthy', 'PLG_HEALTHCHECK_SITEINFO_STATUS_SUPPORTED', ['2028-06-04']], + 'mariadb 11.2 eol' => ['mariadb', '11.2.4', 'critical', 'PLG_HEALTHCHECK_SITEINFO_STATUS_EOL_PAST', ['2024-11-21']], + 'mariadb 10.9 eol' => ['mariadb', '10.9.8', 'critical', 'PLG_HEALTHCHECK_SITEINFO_STATUS_EOL_PAST', ['2023-08-22']], 'mariadb dev site' => ['mariadb', '12.2.2-MariaDB', 'critical', 'PLG_HEALTHCHECK_SITEINFO_STATUS_EOL_PAST', ['2026-05-28']], 'older than known' => ['php', '5.6.40', 'critical', 'PLG_HEALTHCHECK_SITEINFO_STATUS_EOL_OLD', []], 'newer than known' => ['php', '9.0.0', 'healthy', 'PLG_HEALTHCHECK_SITEINFO_STATUS_NEWER', []], @@ -302,4 +304,73 @@ public function testParseManualMissingPhpRow(): void SupportData::parseManual('

Requirements for Joomla! 6.x

SoftwareRecommendedSupportedMinimum
MySQL8.48.0.138.0.13
', 6); } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('knows every MariaDB cycle from 10.4 to 13.0')] + public function testEveryMariadbCycleResolves(): void + { + $cycles = ['10.4', '10.5', '10.6', '10.7', '10.8', '10.9', '10.10', '10.11', '11.0', '11.1', '11.2', '11.3', '11.4', '11.5', '11.6', '11.7', '11.8', '12.0', '12.1', '12.2', '12.3', '13.0']; + + foreach ($cycles as $cycle) { + $this->assertSame($cycle, SupportData::cycleFor('mariadb', $cycle . '.1'), 'MariaDB ' . $cycle); + $this->assertNotSame('none', (new SupportData())->getEolStatus('mariadb', $cycle . '.1', $this->today())['status'], 'MariaDB ' . $cycle); + } + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('keeps the built-in requirements in step with the manual fixture')] + public function testBuiltInRequirementsMatchFixture(): void + { + $builtIn = (new \ReflectionClassConstant(SupportData::class, 'REQUIREMENTS'))->getValue(); + $parsed = SupportData::parseManual(file_get_contents(__DIR__ . '/fixtures/technical-requirements.html'), 6); + + $this->assertSame($parsed['requirements'], $builtIn); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('does not read the next section table when the heading has none')] + public function testParseManualDoesNotSkipToNextSection(): void + { + $this->expectException(\UnexpectedValueException::class); + + SupportData::parseManual('

Requirements for Joomla! 6.x

TBD

Requirements for Joomla! 5.x

PHP8.28.1.08.1.0
', 6); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('rejects non-numeric version cells')] + public function testParseManualRejectsNonNumericCells(): void + { + $this->expectException(\UnexpectedValueException::class); + + SupportData::parseManual('

Requirements for Joomla! 6.x

PHP8.48.3.08.3.0
MySQLTBD8.0.138.0.13
', 6); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('rejects a non-numeric minimum')] + public function testParseManualRejectsNonNumericMinimum(): void + { + $this->expectException(\UnexpectedValueException::class); + + SupportData::parseManual('

Requirements for Joomla! 6.x

PHP8.48.3.0N/A
', 6); + } } From 95c59f3d5ffbf5ff9a9a15aac276745ed90656d7 Mon Sep 17 00:00:00 2001 From: Brian Mitchell Date: Thu, 15 Oct 2026 12:52:42 +0200 Subject: [PATCH 11/29] Siteinfo: harden plugin cache, ajax and settings handling Guard and validate the stored copy, use a fixed cache language so every Super User sees the same copy, restrict the ajax task to the administrator, memoize the stored copy and version rows, detect OPcache without opcache_get_status(), and tidy the settings rows and constant docblocks. Co-Authored-By: Claude Sonnet 5.5 --- .../siteinfo/src/Extension/Siteinfo.php | 101 ++++++++++++++---- 1 file changed, 80 insertions(+), 21 deletions(-) diff --git a/plugins/healthcheck/siteinfo/src/Extension/Siteinfo.php b/plugins/healthcheck/siteinfo/src/Extension/Siteinfo.php index f9db8e5488d..d30f24be4ec 100644 --- a/plugins/healthcheck/siteinfo/src/Extension/Siteinfo.php +++ b/plugins/healthcheck/siteinfo/src/Extension/Siteinfo.php @@ -40,12 +40,42 @@ final class Siteinfo extends CMSPlugin implements SubscriberInterface use DatabaseAwareTrait; /** - * Cache group and id of the requirements refreshed from the manual + * Cache group of the requirements refreshed from the manual * * @since __DEPLOY_VERSION__ */ private const CACHE_GROUP = 'plg_healthcheck_siteinfo'; - private const STORE_ID = 'requirements'; + + /** + * Cache id of the requirements refreshed from the manual + * + * @since __DEPLOY_VERSION__ + */ + private const STORE_ID = 'requirements'; + + /** + * The stored copy of the requirements, read once per request + * + * @var array|null + * @since __DEPLOY_VERSION__ + */ + private ?array $storedCopy = null; + + /** + * Whether the stored copy has been read in this request + * + * @var boolean + * @since __DEPLOY_VERSION__ + */ + private bool $storedRead = false; + + /** + * The software version rows, built once per request + * + * @var array|null + * @since __DEPLOY_VERSION__ + */ + private ?array $versionRows = null; /** * Constructor @@ -91,7 +121,7 @@ public function onHealthcheckGetIcons(HealthChecksEvent $event): void return; } - $rows = $this->collectVersionRows($this->readStored()); + $rows = $this->collectVersionRows(); $attention = array_filter($rows, static fn (array $row): bool => \in_array($row['status'], [SupportData::STATUS_CRITICAL, SupportData::STATUS_WARNING], true)); $return = base64_encode(Uri::getInstance()->toString()); @@ -132,7 +162,7 @@ public function onHealthcheckGetTables(HealthChecksEvent $event): void } $stored = $this->readStored(); - $rows = $this->collectVersionRows($stored); + $rows = $this->collectVersionRows(); $versions = [ 'id' => 'plg_healthcheck_siteinfo_versions', @@ -192,7 +222,7 @@ public function onAjaxSiteinfo(AjaxEvent $event): void { $app = $this->getApplication(); - if (!Session::checkToken('get') || !$app->getIdentity()->authorise('core.admin')) { + if (!$app->isClient('administrator') || !Session::checkToken('get') || !$app->getIdentity()->authorise('core.admin')) { throw new \RuntimeException(Text::_('JERROR_ALERTNOAUTHOR'), 403); } @@ -213,6 +243,7 @@ public function onAjaxSiteinfo(AjaxEvent $event): void $parsed = SupportData::parseManual((string) $response->getBody(), (int) JVERSION); $this->store()->store(['fetched' => time(), 'retrieved' => gmdate('Y-m-d')] + $parsed, self::STORE_ID); + $this->storedRead = false; $app->enqueueMessage(Text::_('PLG_HEALTHCHECK_SITEINFO_REFRESH_DONE'), 'success'); } catch (\Throwable $e) { Log::add('Site Information: could not refresh requirements from the manual: ' . $e->getMessage(), Log::WARNING, 'healthcheck'); @@ -250,16 +281,19 @@ private function isAllowed(HealthChecksEvent $event): bool } /** - * Detect versions and build translated table rows. - * - * @param array|null $stored Requirements refreshed from the manual, if any + * Detect versions and build translated table rows, once per request. * * @return array List of ['label', 'version', 'status', 'text', 'ends'] * * @since __DEPLOY_VERSION__ */ - private function collectVersionRows(?array $stored): array + private function collectVersionRows(): array { + if ($this->versionRows !== null) { + return $this->versionRows; + } + + $stored = $this->readStored(); $report = new SystemReport(new SupportData($stored['requirements'] ?? []), new \DateTimeImmutable('today', new \DateTimeZone('UTC'))); $rows = []; @@ -293,7 +327,7 @@ private function collectVersionRows(?array $stored): array 'ends' => '', ]; - return $rows; + return $this->versionRows = $rows; } /** @@ -336,18 +370,21 @@ private function collectSettingsRows(?string $memoryLimit): array $ini[$setting] = (string) \ini_get($setting); } - $opcache = \function_exists('opcache_get_status') && \is_array(@opcache_get_status(false)) && (bool) \ini_get('opcache.enable'); + $opcache = \extension_loaded('Zend OPcache') && filter_var(\ini_get('opcache.enable'), FILTER_VALIDATE_BOOLEAN); $rows = SystemReport::settingsRows($ini, $opcache, $memoryLimit ?? SystemReport::MEMORY_LIMIT); - foreach ($rows as &$row) { - if (str_starts_with($row['current'], 'J')) { - $row['current'] = Text::_($row['current']); - } + return array_map( + static function (array $row): array { + if (\in_array($row['current'], ['JENABLED', 'JDISABLED', 'JON', 'JOFF'], true)) { + $row['current'] = Text::_($row['current']); + } - $row['recommended'] = Text::sprintf($row['recommended'][0], ...$row['recommended'][1]); - } + $row['recommended'] = Text::sprintf($row['recommended'][0], ...$row['recommended'][1]); - return $rows; + return $row; + }, + $rows + ); } /** @@ -398,7 +435,7 @@ private function store(): OutputController { return $this->getCacheControllerFactory()->createCacheController( 'output', - ['defaultgroup' => self::CACHE_GROUP, 'caching' => true, 'lifetime' => 43200] + ['defaultgroup' => self::CACHE_GROUP, 'caching' => true, 'lifetime' => 43200, 'language' => 'en-GB'] ); } @@ -411,8 +448,30 @@ private function store(): OutputController */ private function readStored(): ?array { - $stored = $this->store()->get(self::STORE_ID); + if ($this->storedRead) { + return $this->storedCopy; + } + + $this->storedRead = true; + $this->storedCopy = null; + + try { + $stored = $this->store()->get(self::STORE_ID); + } catch (\Throwable $e) { + return null; + } + + if ( + \is_array($stored) + && isset($stored['fetched'], $stored['retrieved'], $stored['requirements']) + && \is_int($stored['fetched']) + && \is_string($stored['retrieved']) + && \is_array($stored['requirements']) + && (!isset($stored['memory']) || \is_string($stored['memory'])) + ) { + $this->storedCopy = $stored; + } - return \is_array($stored) ? $stored : null; + return $this->storedCopy; } } From bb37ee7e9821ee895d1b669d5be7ff6782b30005 Mon Sep 17 00:00:00 2001 From: Brian Mitchell Date: Thu, 15 Oct 2026 14:42:27 +0200 Subject: [PATCH 12/29] Fix typo in Site Information test data key Co-Authored-By: Claude Opus 5.5 --- .../Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php b/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php index d4ea7f07e81..2fd55f18d7e 100644 --- a/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php +++ b/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php @@ -116,7 +116,7 @@ public static function eolProvider(): array 'gap in known cycles' => ['mysql', '8.5.0', 'none', 'PLG_HEALTHCHECK_SITEINFO_STATUS_NO_DATA', []], 'joomla dev version' => ['joomla', '6.2.1-dev', 'healthy', 'PLG_HEALTHCHECK_SITEINFO_STATUS_SUPPORTED', ['2029-10-16']], 'empty version' => ['mysql', '', 'none', 'PLG_HEALTHCHECK_SITEINFO_STATUS_NO_DATA', []], - 'unparseable version' => ['php', 'unknown', 'none', 'PLG_HEALTHCHECK_SITEINFO_STATUS_NO_DATA', []], + 'unparsable version' => ['php', 'unknown', 'none', 'PLG_HEALTHCHECK_SITEINFO_STATUS_NO_DATA', []], ]; } From 5164a92d9758b66ecdfbca41df3923d59afed003 Mon Sep 17 00:00:00 2001 From: Brian Mitchell Date: Thu, 15 Oct 2026 14:42:30 +0200 Subject: [PATCH 13/29] Add SSL certificate Health Check status rules Co-Authored-By: Claude Opus 5.5 --- .../ssl/src/Certificate/CertificateStatus.php | 186 ++++++++++ plugins/healthcheck/ssl/ssl.xml | 62 ++++ .../Ssl/Certificate/CertificateStatusTest.php | 319 ++++++++++++++++++ 3 files changed, 567 insertions(+) create mode 100644 plugins/healthcheck/ssl/src/Certificate/CertificateStatus.php create mode 100644 plugins/healthcheck/ssl/ssl.xml create mode 100644 tests/Unit/Plugin/Healthcheck/Ssl/Certificate/CertificateStatusTest.php diff --git a/plugins/healthcheck/ssl/src/Certificate/CertificateStatus.php b/plugins/healthcheck/ssl/src/Certificate/CertificateStatus.php new file mode 100644 index 00000000000..2d6147941f1 --- /dev/null +++ b/plugins/healthcheck/ssl/src/Certificate/CertificateStatus.php @@ -0,0 +1,186 @@ + + * @license GNU General Public License version 2 or later; see LICENSE.txt + */ + +namespace Joomla\Plugin\Healthcheck\Ssl\Certificate; + +// phpcs:disable PSR1.Files.SideEffects +\defined('_JEXEC') or die; +// phpcs:enable PSR1.Files.SideEffects + +/** + * Status rules for the site's TLS certificate. Pure: no I/O, the current time is passed in. + * + * @since __DEPLOY_VERSION__ + */ +final class CertificateStatus +{ + public const SUCCESS = 'success'; + + public const WARNING = 'warning'; + + public const ERROR = 'error'; + + public const NONE = 'none'; + + public const DEFAULT_WARNING_DAYS = 14; + + public const DEFAULT_ERROR_DAYS = 7; + + public const DEFAULT_TIMEOUT = 3; + + /** + * Seconds a successful probe result is reused + * + * @since __DEPLOY_VERSION__ + */ + public const SUCCESS_TTL = 86400; + + /** + * Seconds a failed probe result is reused, so an unreachable host does not stall every dashboard load + * + * @since __DEPLOY_VERSION__ + */ + public const FAILURE_TTL = 3600; + + /** + * Sanitise the threshold params. If the error threshold is at or above the warning threshold, the warning window is empty. + * + * @param mixed $warning Raw warning_days param + * @param mixed $error Raw error_days param + * + * @return array [int warningDays, int errorDays] + * + * @since __DEPLOY_VERSION__ + */ + public static function thresholds(mixed $warning, mixed $error): array + { + $warning = is_numeric($warning) && (int) $warning >= 1 ? (int) $warning : self::DEFAULT_WARNING_DAYS; + $error = is_numeric($error) && (int) $error >= 0 ? (int) $error : self::DEFAULT_ERROR_DAYS; + + return [max($warning, $error), $error]; + } + + /** + * Sanitise the timeout param. + * + * @param mixed $timeout Raw timeout param + * + * @return integer Seconds, 1 to 10 + * + * @since __DEPLOY_VERSION__ + */ + public static function timeout(mixed $timeout): int + { + return is_numeric($timeout) ? min(10, max(1, (int) $timeout)) : self::DEFAULT_TIMEOUT; + } + + /** + * Whether a cached probe result is well formed and still fresh. + * + * @param mixed $cached What the cache returned (false on a miss) + * @param integer $now Current Unix time + * + * @return boolean + * + * @since __DEPLOY_VERSION__ + */ + public static function isUsable(mixed $cached, int $now): bool + { + if ( + !\is_array($cached) + || !isset($cached['ok'], $cached['trusted'], $cached['reason'], $cached['issuer'], $cached['checkedAt']) + || !\array_key_exists('validFrom', $cached) + || !\array_key_exists('validTo', $cached) + || !\is_bool($cached['ok']) + || !\is_bool($cached['trusted']) + || !\is_string($cached['reason']) + || !\is_string($cached['issuer']) + || !\is_int($cached['checkedAt']) + ) { + return false; + } + + if ($cached['ok'] && (!\is_int($cached['validFrom']) || !\is_int($cached['validTo']))) { + return false; + } + + $age = $now - $cached['checkedAt']; + + return $age >= 0 && $age < ($cached['ok'] ? self::SUCCESS_TTL : self::FAILURE_TTL); + } + + /** + * Map a probe result to a status, message key and day count. + * + * @param ?array $probe Probe result, or null when the site is not served over HTTPS + * @param integer $now Current Unix time + * @param integer $warningDays Warn at or below this many days + * @param integer $errorDays Error at or below this many days + * + * @return array ['status' => string, 'key' => string, 'days' => ?int, 'date' => ?int, 'plural' => bool] + * + * @since __DEPLOY_VERSION__ + */ + public static function evaluate(?array $probe, int $now, int $warningDays, int $errorDays): array + { + if ($probe === null) { + return self::result(self::WARNING, 'NO_HTTPS'); + } + + if (empty($probe['ok'])) { + return self::result(self::NONE, 'UNCHECKED'); + } + + $validTo = (int) $probe['validTo']; + $validFrom = (int) $probe['validFrom']; + + if ($validTo < $now) { + return self::result(self::ERROR, 'EXPIRED', null, $validTo); + } + + if ($validFrom > $now) { + return self::result(self::ERROR, 'NOT_YET_VALID', null, $validFrom); + } + + $days = intdiv($validTo - $now, 86400); + + if (empty($probe['trusted'])) { + return self::result(self::ERROR, 'UNTRUSTED', $days, $validTo); + } + + if ($days <= $errorDays) { + return self::result(self::ERROR, 'EXPIRES_N', $days, $validTo, true); + } + + if ($days <= $warningDays) { + return self::result(self::WARNING, 'RENEW_SOON_N', $days, $validTo, true); + } + + return self::result(self::SUCCESS, 'VALID_N', $days, $validTo, true); + } + + /** + * Build an evaluate() result. + * + * @param string $status One of the status constants + * @param string $suffix Message key suffix after PLG_HEALTHCHECK_SSL_STATUS_ + * @param ?int $days Days left + * @param ?int $date Timestamp shown in the message + * @param boolean $plural Whether the key is used with Text::plural() + * + * @return array + * + * @since __DEPLOY_VERSION__ + */ + private static function result(string $status, string $suffix, ?int $days = null, ?int $date = null, bool $plural = false): array + { + return ['status' => $status, 'key' => 'PLG_HEALTHCHECK_SSL_STATUS_' . $suffix, 'days' => $days, 'date' => $date, 'plural' => $plural]; + } +} diff --git a/plugins/healthcheck/ssl/ssl.xml b/plugins/healthcheck/ssl/ssl.xml new file mode 100644 index 00000000000..ebc11631ab8 --- /dev/null +++ b/plugins/healthcheck/ssl/ssl.xml @@ -0,0 +1,62 @@ + + + plg_healthcheck_ssl + Joomla! Project + 2026-10 + (C) 2026 Open Source Matters, Inc. + GNU General Public License version 2 or later; see LICENSE.txt + admin@joomla.org + www.joomla.org + 6.2.0 + PLG_HEALTHCHECK_SSL_XML_DESCRIPTION + Joomla\Plugin\Healthcheck\Ssl + + services + src + + + language/en-GB/plg_healthcheck_ssl.ini + language/en-GB/plg_healthcheck_ssl.sys.ini + + + +
+ + + + +
+
+
+
diff --git a/tests/Unit/Plugin/Healthcheck/Ssl/Certificate/CertificateStatusTest.php b/tests/Unit/Plugin/Healthcheck/Ssl/Certificate/CertificateStatusTest.php new file mode 100644 index 00000000000..bec29dacd0a --- /dev/null +++ b/tests/Unit/Plugin/Healthcheck/Ssl/Certificate/CertificateStatusTest.php @@ -0,0 +1,319 @@ + + * @license GNU General Public License version 2 or later; see LICENSE.txt + */ + +namespace Joomla\Tests\Unit\Plugin\Healthcheck\Ssl\Certificate; + +use Joomla\Plugin\Healthcheck\Ssl\Certificate\CertificateStatus; +use Joomla\Tests\Unit\UnitTestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\TestDox; + +/** + * Test class for the SSL certificate status rules + * + * @since __DEPLOY_VERSION__ + */ +#[TestDox('The SSL certificate status rules')] +class CertificateStatusTest extends UnitTestCase +{ + private const NOW = 1800000000; + + private const DAY = 86400; + + /** + * A successful probe result expiring at the given time. + * + * @param int $validTo Expiry timestamp + * @param boolean $trusted Whether verification passed + * @param ?int $validFrom Start timestamp, default 60 days before NOW + * + * @return array + * + * @since __DEPLOY_VERSION__ + */ + private function probe(int $validTo, bool $trusted = true, ?int $validFrom = null): array + { + return [ + 'ok' => true, + 'trusted' => $trusted, + 'reason' => $trusted ? '' : 'certificate verify failed', + 'validFrom' => $validFrom ?? self::NOW - 60 * self::DAY, + 'validTo' => $validTo, + 'issuer' => 'Test CA', + 'checkedAt' => self::NOW, + ]; + } + + /** + * @return array + * + * @since __DEPLOY_VERSION__ + */ + public static function expiryProvider(): array + { + $now = self::NOW; + $day = self::DAY; + + return [ + '90 days' => [$now + 90 * $day, 'success', 'PLG_HEALTHCHECK_SSL_STATUS_VALID_N', 90], + '15 days' => [$now + 15 * $day, 'success', 'PLG_HEALTHCHECK_SSL_STATUS_VALID_N', 15], + '14 days' => [$now + 14 * $day, 'warning', 'PLG_HEALTHCHECK_SSL_STATUS_RENEW_SOON_N', 14], + '14 days and an hour' => [$now + 14 * $day + 3600, 'warning', 'PLG_HEALTHCHECK_SSL_STATUS_RENEW_SOON_N', 14], + '8 days' => [$now + 8 * $day, 'warning', 'PLG_HEALTHCHECK_SSL_STATUS_RENEW_SOON_N', 8], + '7 days' => [$now + 7 * $day, 'error', 'PLG_HEALTHCHECK_SSL_STATUS_EXPIRES_N', 7], + 'later today' => [$now + 3600, 'error', 'PLG_HEALTHCHECK_SSL_STATUS_EXPIRES_N', 0], + 'this very second' => [$now, 'error', 'PLG_HEALTHCHECK_SSL_STATUS_EXPIRES_N', 0], + ]; + } + + /** + * @param int $validTo Expiry timestamp + * @param string $status Expected status + * @param string $key Expected message key + * @param int $days Expected days left + * + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[DataProvider('expiryProvider')] + #[TestDox('maps days to expiry to a stoplight at the default 14/7 thresholds')] + public function testDefaultThresholds(int $validTo, string $status, string $key, int $days): void + { + $result = CertificateStatus::evaluate($this->probe($validTo), self::NOW, 14, 7); + + $this->assertSame(['status' => $status, 'key' => $key, 'days' => $days, 'date' => $validTo, 'plural' => true], $result); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('reports an expired certificate as an error with its expiry date')] + public function testExpired(): void + { + $validTo = self::NOW - 1; + + $this->assertSame( + ['status' => 'error', 'key' => 'PLG_HEALTHCHECK_SSL_STATUS_EXPIRED', 'days' => null, 'date' => $validTo, 'plural' => false], + CertificateStatus::evaluate($this->probe($validTo), self::NOW, 14, 7) + ); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('says expired, not untrusted, for an expired certificate that failed verification')] + public function testExpiredBeatsUntrusted(): void + { + $result = CertificateStatus::evaluate($this->probe(self::NOW - 5 * self::DAY, false), self::NOW, 14, 7); + + $this->assertSame('PLG_HEALTHCHECK_SSL_STATUS_EXPIRED', $result['key']); + $this->assertSame('error', $result['status']); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('reports a certificate that is not valid yet as an error with its start date')] + public function testNotYetValid(): void + { + $validFrom = self::NOW + self::DAY; + + $this->assertSame( + ['status' => 'error', 'key' => 'PLG_HEALTHCHECK_SSL_STATUS_NOT_YET_VALID', 'days' => null, 'date' => $validFrom, 'plural' => false], + CertificateStatus::evaluate($this->probe(self::NOW + 90 * self::DAY, true, $validFrom), self::NOW, 14, 7) + ); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('reports an untrusted certificate as an error even with plenty of days left')] + public function testUntrusted(): void + { + $validTo = self::NOW + 60 * self::DAY; + + $this->assertSame( + ['status' => 'error', 'key' => 'PLG_HEALTHCHECK_SSL_STATUS_UNTRUSTED', 'days' => 60, 'date' => $validTo, 'plural' => false], + CertificateStatus::evaluate($this->probe($validTo, false), self::NOW, 14, 7) + ); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('warns when the site is not served over HTTPS')] + public function testNoHttps(): void + { + $this->assertSame( + ['status' => 'warning', 'key' => 'PLG_HEALTHCHECK_SSL_STATUS_NO_HTTPS', 'days' => null, 'date' => null, 'plural' => false], + CertificateStatus::evaluate(null, self::NOW, 14, 7) + ); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('stays neutral when the certificate could not be read')] + public function testUnchecked(): void + { + $probe = ['ok' => false, 'trusted' => false, 'reason' => 'Connection refused', 'validFrom' => null, 'validTo' => null, 'issuer' => '', 'checkedAt' => self::NOW]; + + $this->assertSame( + ['status' => 'none', 'key' => 'PLG_HEALTHCHECK_SSL_STATUS_UNCHECKED', 'days' => null, 'date' => null, 'plural' => false], + CertificateStatus::evaluate($probe, self::NOW, 14, 7) + ); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('applies custom thresholds')] + public function testCustomThresholds(): void + { + $this->assertSame('warning', CertificateStatus::evaluate($this->probe(self::NOW + 20 * self::DAY), self::NOW, 30, 14)['status']); + $this->assertSame('error', CertificateStatus::evaluate($this->probe(self::NOW + 14 * self::DAY), self::NOW, 30, 14)['status']); + $this->assertSame('success', CertificateStatus::evaluate($this->probe(self::NOW + 31 * self::DAY), self::NOW, 30, 14)['status']); + } + + /** + * @return array + * + * @since __DEPLOY_VERSION__ + */ + public static function thresholdsProvider(): array + { + return [ + 'defaults from null' => [null, null, [14, 7]], + 'strings from the form' => ['30', '14', [30, 14]], + 'garbage' => ['abc', 'x', [14, 7]], + 'negative' => ['-3', '-1', [14, 7]], + 'zero warning is invalid' => ['0', '0', [14, 0]], + 'error above warning' => ['5', '10', [10, 10]], + 'error equals warning' => [7, 7, [7, 7]], + ]; + } + + /** + * @param mixed $warning Raw warning_days param + * @param mixed $error Raw error_days param + * @param array $expected [warningDays, errorDays] + * + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[DataProvider('thresholdsProvider')] + #[TestDox('sanitises threshold params and never inverts the windows')] + public function testThresholds(mixed $warning, mixed $error, array $expected): void + { + $this->assertSame($expected, CertificateStatus::thresholds($warning, $error)); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('turns an inverted configuration into an empty warning window')] + public function testInvertedThresholdsEvaluate(): void + { + [$warning, $error] = CertificateStatus::thresholds('5', '10'); + + $this->assertSame('error', CertificateStatus::evaluate($this->probe(self::NOW + 8 * self::DAY), self::NOW, $warning, $error)['status']); + $this->assertSame('success', CertificateStatus::evaluate($this->probe(self::NOW + 11 * self::DAY), self::NOW, $warning, $error)['status']); + } + + /** + * @return array + * + * @since __DEPLOY_VERSION__ + */ + public static function timeoutProvider(): array + { + return [ + 'null' => [null, 3], + 'string' => ['5', 5], + 'zero' => ['0', 1], + 'too big' => ['99', 10], + 'garbage' => ['x', 3], + ]; + } + + /** + * @param mixed $raw Raw timeout param + * @param int $expected Seconds + * + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[DataProvider('timeoutProvider')] + #[TestDox('clamps the timeout to 1 to 10 seconds')] + public function testTimeout(mixed $raw, int $expected): void + { + $this->assertSame($expected, CertificateStatus::timeout($raw)); + } + + /** + * @return array + * + * @since __DEPLOY_VERSION__ + */ + public static function usableProvider(): array + { + $now = self::NOW; + $success = ['ok' => true, 'trusted' => true, 'reason' => '', 'validFrom' => $now - 86400, 'validTo' => $now + 86400 * 60, 'issuer' => 'CA', 'checkedAt' => $now - 3600]; + $failure = ['ok' => false, 'trusted' => false, 'reason' => 'refused', 'validFrom' => null, 'validTo' => null, 'issuer' => '', 'checkedAt' => $now - 600]; + + return [ + 'fresh success' => [$success, true], + 'success at 23 hours' => [['checkedAt' => $now - 82800] + $success, true], + 'success at 24 hours' => [['checkedAt' => $now - 86400] + $success, false], + 'fresh failure' => [$failure, true], + 'failure at one hour' => [['checkedAt' => $now - 3600] + $failure, false], + 'checked in the future' => [['checkedAt' => $now + 60] + $success, false], + 'cache miss' => [false, false], + 'not an array' => ['x', false], + 'missing key' => [array_diff_key($success, ['issuer' => true]), false], + 'string timestamp' => [['validTo' => '1800000000'] + $success, false], + 'ok without dates' => [['validTo' => null] + $success, false], + ]; + } + + /** + * @param mixed $cached What the cache returned + * @param boolean $expected Whether it may be used + * + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[DataProvider('usableProvider')] + #[TestDox('reuses well-formed cached results for 24 hours, failures for 1 hour')] + public function testIsUsable(mixed $cached, bool $expected): void + { + $this->assertSame($expected, CertificateStatus::isUsable($cached, self::NOW)); + } +} From edbe58c462e27f4e49a26dd8c348bc2dde91cb40 Mon Sep 17 00:00:00 2001 From: Brian Mitchell Date: Thu, 15 Oct 2026 14:45:05 +0200 Subject: [PATCH 14/29] Add SSL certificate probe for the Health Check Co-Authored-By: Claude Opus 5.5 --- .../ssl/src/Certificate/CertificateProbe.php | 230 ++++++++++++++++++ .../Ssl/Certificate/CertificateProbeTest.php | 140 +++++++++++ 2 files changed, 370 insertions(+) create mode 100644 plugins/healthcheck/ssl/src/Certificate/CertificateProbe.php create mode 100644 tests/Unit/Plugin/Healthcheck/Ssl/Certificate/CertificateProbeTest.php diff --git a/plugins/healthcheck/ssl/src/Certificate/CertificateProbe.php b/plugins/healthcheck/ssl/src/Certificate/CertificateProbe.php new file mode 100644 index 00000000000..d9ca7a23ced --- /dev/null +++ b/plugins/healthcheck/ssl/src/Certificate/CertificateProbe.php @@ -0,0 +1,230 @@ + + * @license GNU General Public License version 2 or later; see LICENSE.txt + */ + +namespace Joomla\Plugin\Healthcheck\Ssl\Certificate; + +// phpcs:disable PSR1.Files.SideEffects +\defined('_JEXEC') or die; +// phpcs:enable PSR1.Files.SideEffects + +/** + * Reads the TLS certificate the site's own host presents. The only class in this plugin that uses the network. + * + * @since __DEPLOY_VERSION__ + */ +final class CertificateProbe +{ + /** + * Derive the host, port and scheme to check from the site root URL. + * + * @param string $rootUrl The site root URL, as from Uri::root() + * + * @return array|null ['https' => bool, 'host' => string, 'port' => int], or null without a host + * + * @since __DEPLOY_VERSION__ + */ + public static function target(string $rootUrl): ?array + { + $parts = parse_url($rootUrl); + + if (!\is_array($parts) || empty($parts['host'])) { + return null; + } + + return [ + 'https' => strtolower($parts['scheme'] ?? '') === 'https', + 'host' => strtolower(trim($parts['host'], '[]')), + 'port' => isset($parts['port']) ? (int) $parts['port'] : 443, + ]; + } + + /** + * Read validity dates and issuer from a certificate. + * + * @param \OpenSSLCertificate|string $certificate Certificate object or PEM string + * + * @return array|null ['validFrom' => int, 'validTo' => int, 'issuer' => string], or null if unreadable + * + * @since __DEPLOY_VERSION__ + */ + public static function parse(\OpenSSLCertificate|string $certificate): ?array + { + set_error_handler(static fn (): bool => true); + + try { + $info = openssl_x509_parse($certificate); + } finally { + restore_error_handler(); + } + + if (!\is_array($info) || !isset($info['validFrom_time_t'], $info['validTo_time_t'])) { + return null; + } + + $issuer = $info['issuer']['O'] ?? $info['issuer']['CN'] ?? ''; + + return [ + 'validFrom' => (int) $info['validFrom_time_t'], + 'validTo' => (int) $info['validTo_time_t'], + 'issuer' => \is_array($issuer) ? implode(', ', $issuer) : (string) $issuer, + ]; + } + + /** + * Turn a PHP stream warning into a one-line reason. + * + * @param string $message Warning text + * + * @return string + * + * @since __DEPLOY_VERSION__ + */ + public static function cleanReason(string $message): string + { + $message = preg_replace('/^\s*\w+\(\):\s*/', '', $message); + + return trim(preg_replace('/\s+/', ' ', $message)); + } + + /** + * A probe result for a certificate that could not be read. + * + * @param string $reason Why + * @param integer $checkedAt Unix time of the attempt + * + * @return array + * + * @since __DEPLOY_VERSION__ + */ + public static function failure(string $reason, int $checkedAt): array + { + return ['ok' => false, 'trusted' => false, 'reason' => $reason, 'validFrom' => null, 'validTo' => null, 'issuer' => '', 'checkedAt' => $checkedAt]; + } + + /** + * Connect to the host, complete a TLS handshake and read its certificate. + * Verification failures are retried once without verification so the expiry date can still be reported. + * + * @param string $host Host name or IP address + * @param integer $port TCP port + * @param integer $timeout Seconds for the connect and for the handshake + * + * @return array ['ok', 'trusted', 'reason', 'validFrom', 'validTo', 'issuer', 'checkedAt'] + * + * @since __DEPLOY_VERSION__ + */ + public function probe(string $host, int $port, int $timeout): array + { + $checkedAt = time(); + + if (!\extension_loaded('openssl')) { + return self::failure('The PHP OpenSSL extension is not available.', $checkedAt); + } + + $verified = $this->handshake($host, $port, $timeout, true); + + if ($verified['certificate'] !== null) { + return $this->result($verified['certificate'], true, '', $checkedAt); + } + + // Only a failed verification is worth a second attempt; a refused or timed-out connection would just fail again. + if (!$verified['connected'] || !preg_match('/certificate|did not match/i', $verified['error'])) { + return self::failure(self::cleanReason($verified['error']), $checkedAt); + } + + $unverified = $this->handshake($host, $port, $timeout, false); + + if ($unverified['certificate'] === null) { + return self::failure(self::cleanReason($verified['error']), $checkedAt); + } + + return $this->result($unverified['certificate'], false, self::cleanReason($verified['error']), $checkedAt); + } + + /** + * Build a probe result from a captured certificate. + * + * @param \OpenSSLCertificate $certificate The peer certificate + * @param boolean $trusted Whether verification passed + * @param string $reason Why it is not trusted + * @param integer $checkedAt Unix time of the attempt + * + * @return array + * + * @since __DEPLOY_VERSION__ + */ + private function result(\OpenSSLCertificate $certificate, bool $trusted, string $reason, int $checkedAt): array + { + $parsed = self::parse($certificate); + + if ($parsed === null) { + return self::failure('The certificate could not be read.', $checkedAt); + } + + return ['ok' => true, 'trusted' => $trusted, 'reason' => $reason] + $parsed + ['checkedAt' => $checkedAt]; + } + + /** + * One TCP connect plus TLS handshake. Warnings are captured, never shown. No HTTP request is sent. + * + * @param string $host Host name or IP address + * @param integer $port TCP port + * @param integer $timeout Seconds + * @param boolean $verify Whether to verify the peer and its name + * + * @return array ['connected' => bool, 'certificate' => ?\OpenSSLCertificate, 'error' => string] + * + * @since __DEPLOY_VERSION__ + */ + private function handshake(string $host, int $port, int $timeout, bool $verify): array + { + $error = ''; + + set_error_handler(static function (int $errno, string $message) use (&$error): bool { + $error = $message; + + return true; + }); + + try { + $context = stream_context_create([ + 'ssl' => [ + 'capture_peer_cert' => true, + 'verify_peer' => $verify, + 'verify_peer_name' => $verify, + 'allow_self_signed' => !$verify, + 'peer_name' => $host, + 'SNI_enabled' => true, + ], + ]); + + $address = 'tcp://' . (str_contains($host, ':') ? '[' . $host . ']' : $host) . ':' . $port; + $stream = stream_socket_client($address, $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $context); + + if ($stream === false) { + return ['connected' => false, 'certificate' => null, 'error' => $errstr !== '' ? $errstr : $error]; + } + + stream_set_timeout($stream, $timeout); + + $certificate = null; + + if (stream_socket_enable_crypto($stream, true, STREAM_CRYPTO_METHOD_TLS_CLIENT) === true) { + $certificate = stream_context_get_options($stream)['ssl']['peer_certificate'] ?? null; + } + + fclose($stream); + + return ['connected' => true, 'certificate' => $certificate, 'error' => $error]; + } finally { + restore_error_handler(); + } + } +} diff --git a/tests/Unit/Plugin/Healthcheck/Ssl/Certificate/CertificateProbeTest.php b/tests/Unit/Plugin/Healthcheck/Ssl/Certificate/CertificateProbeTest.php new file mode 100644 index 00000000000..f268c88ad6d --- /dev/null +++ b/tests/Unit/Plugin/Healthcheck/Ssl/Certificate/CertificateProbeTest.php @@ -0,0 +1,140 @@ + + * @license GNU General Public License version 2 or later; see LICENSE.txt + */ + +namespace Joomla\Tests\Unit\Plugin\Healthcheck\Ssl\Certificate; + +use Joomla\Plugin\Healthcheck\Ssl\Certificate\CertificateProbe; +use Joomla\Tests\Unit\UnitTestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\TestDox; + +/** + * Test class for the SSL certificate probe (no outbound network) + * + * @since __DEPLOY_VERSION__ + */ +#[TestDox('The SSL certificate probe')] +class CertificateProbeTest extends UnitTestCase +{ + /** + * @return array + * + * @since __DEPLOY_VERSION__ + */ + public static function targetProvider(): array + { + return [ + 'plain https' => ['https://www.example.org/', ['https' => true, 'host' => 'www.example.org', 'port' => 443]], + 'subfolder' => ['https://example.org/joomla/', ['https' => true, 'host' => 'example.org', 'port' => 443]], + 'custom port' => ['https://example.org:8443/', ['https' => true, 'host' => 'example.org', 'port' => 8443]], + 'uppercase' => ['HTTPS://Example.ORG/', ['https' => true, 'host' => 'example.org', 'port' => 443]], + 'ipv6' => ['https://[2001:db8::1]/', ['https' => true, 'host' => '2001:db8::1', 'port' => 443]], + 'http' => ['http://example.org/', ['https' => false, 'host' => 'example.org', 'port' => 443]], + 'no host' => ['/joomla/', null], + 'garbage' => ['http://', null], + ]; + } + + /** + * @param string $url Root URL + * @param ?array $expected Target + * + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[DataProvider('targetProvider')] + #[TestDox('derives host, port and scheme from the site root URL')] + public function testTarget(string $url, ?array $expected): void + { + $this->assertSame($expected, CertificateProbe::target($url)); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('reads validity dates and issuer from a certificate')] + public function testParse(): void + { + $key = openssl_pkey_new(['private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA]); + $csr = openssl_csr_new(['commonName' => 'example.test', 'organizationName' => 'Test Issuer'], $key); + $cert = openssl_csr_sign($csr, null, $key, 30); + + $parsed = CertificateProbe::parse($cert); + + $this->assertSame('Test Issuer', $parsed['issuer']); + $this->assertSame(30 * 86400, $parsed['validTo'] - $parsed['validFrom']); + $this->assertEqualsWithDelta(time(), $parsed['validFrom'], 120); + + openssl_x509_export($cert, $pem); + + $this->assertSame($parsed, CertificateProbe::parse($pem)); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('falls back to the issuer common name without an organisation')] + public function testParseIssuerFallback(): void + { + $key = openssl_pkey_new(['private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA]); + $csr = openssl_csr_new(['commonName' => 'only-cn.test'], $key); + $cert = openssl_csr_sign($csr, null, $key, 1); + + $this->assertSame('only-cn.test', CertificateProbe::parse($cert)['issuer']); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('returns null for something that is not a certificate')] + public function testParseGarbage(): void + { + $this->assertNull(CertificateProbe::parse('not a certificate')); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('turns PHP stream warnings into a one-line reason')] + public function testCleanReason(): void + { + $this->assertSame( + 'SSL operation failed with code 1. OpenSSL Error messages: error:0A000086:SSL routines::certificate verify failed', + CertificateProbe::cleanReason("stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages:\nerror:0A000086:SSL routines::certificate verify failed") + ); + $this->assertSame('Connection refused', CertificateProbe::cleanReason(' Connection refused ')); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('reports a refused connection as a failure, not an exception')] + public function testRefused(): void + { + $result = (new CertificateProbe())->probe('127.0.0.1', 1, 1); + + $this->assertFalse($result['ok']); + $this->assertFalse($result['trusted']); + $this->assertNotSame('', $result['reason']); + $this->assertNull($result['validTo']); + $this->assertEqualsWithDelta(time(), $result['checkedAt'], 5); + } +} From fa451460a6563d481dabd05fa0c80472d753acd8 Mon Sep 17 00:00:00 2001 From: Brian Mitchell Date: Thu, 15 Oct 2026 14:47:29 +0200 Subject: [PATCH 15/29] Add SSL Certificate Health Check plugin Co-Authored-By: Claude Opus 5.5 --- .../sql/updates/mysql/6.2.0-2026-10-16.sql | 3 + .../updates/postgresql/6.2.0-2026-10-16.sql | 3 + .../language/en-GB/plg_healthcheck_ssl.ini | 38 +++ .../en-GB/plg_healthcheck_ssl.sys.ini | 7 + installation/sql/mysql/base.sql | 1 + installation/sql/postgresql/base.sql | 1 + libraries/src/Extension/ExtensionHelper.php | 1 + plugins/healthcheck/ssl/services/provider.php | 49 +++ plugins/healthcheck/ssl/src/Extension/Ssl.php | 281 ++++++++++++++++++ 9 files changed, 384 insertions(+) create mode 100644 administrator/components/com_admin/sql/updates/mysql/6.2.0-2026-10-16.sql create mode 100644 administrator/components/com_admin/sql/updates/postgresql/6.2.0-2026-10-16.sql create mode 100644 administrator/language/en-GB/plg_healthcheck_ssl.ini create mode 100644 administrator/language/en-GB/plg_healthcheck_ssl.sys.ini create mode 100644 plugins/healthcheck/ssl/services/provider.php create mode 100644 plugins/healthcheck/ssl/src/Extension/Ssl.php diff --git a/administrator/components/com_admin/sql/updates/mysql/6.2.0-2026-10-16.sql b/administrator/components/com_admin/sql/updates/mysql/6.2.0-2026-10-16.sql new file mode 100644 index 00000000000..aeb8a31c1e8 --- /dev/null +++ b/administrator/components/com_admin/sql/updates/mysql/6.2.0-2026-10-16.sql @@ -0,0 +1,3 @@ +INSERT INTO `#__extensions` (`package_id`, `name`, `type`, `element`, `folder`, `client_id`, `enabled`, `access`, `protected`, `locked`, `manifest_cache`, `params`, `custom_data`, `ordering`, `state`) +SELECT 0, 'plg_healthcheck_ssl', 'plugin', 'ssl', 'healthcheck', 0, 0, 1, 0, 1, '', '{"context":"security"}', '', 0, 0 +WHERE NOT EXISTS (SELECT * FROM `#__extensions` g WHERE g.`element` = 'ssl' AND g.`folder` = 'healthcheck'); diff --git a/administrator/components/com_admin/sql/updates/postgresql/6.2.0-2026-10-16.sql b/administrator/components/com_admin/sql/updates/postgresql/6.2.0-2026-10-16.sql new file mode 100644 index 00000000000..e12a599aaf0 --- /dev/null +++ b/administrator/components/com_admin/sql/updates/postgresql/6.2.0-2026-10-16.sql @@ -0,0 +1,3 @@ +INSERT INTO "#__extensions" ("package_id", "name", "type", "element", "folder", "client_id", "enabled", "access", "protected", "locked", "manifest_cache", "params", "custom_data", "ordering", "state") +SELECT 0, 'plg_healthcheck_ssl', 'plugin', 'ssl', 'healthcheck', 0, 0, 1, 0, 1, '', '{"context":"security"}', '', 0, 0 +WHERE NOT EXISTS (SELECT * FROM "#__extensions" g WHERE g."element" = 'ssl' AND g."folder" = 'healthcheck'); diff --git a/administrator/language/en-GB/plg_healthcheck_ssl.ini b/administrator/language/en-GB/plg_healthcheck_ssl.ini new file mode 100644 index 00000000000..873251eded3 --- /dev/null +++ b/administrator/language/en-GB/plg_healthcheck_ssl.ini @@ -0,0 +1,38 @@ +; Joomla! Project +; (C) 2026 Open Source Matters, Inc. +; License GNU General Public License version 2 or later; see LICENSE.txt +; Note : All ini files need to be saved as UTF-8 + +PLG_HEALTHCHECK_SSL="Health Check - SSL Certificate" +; Your own advice shown under the message for each status. Set these with System > Language Overrides (Administrator). +PLG_HEALTHCHECK_SSL_CUSTOM_ERROR="" +PLG_HEALTHCHECK_SSL_CUSTOM_NONE="" +PLG_HEALTHCHECK_SSL_CUSTOM_SUCCESS="" +PLG_HEALTHCHECK_SSL_CUSTOM_WARNING="" +PLG_HEALTHCHECK_SSL_ERROR_DAYS_DESC="Show an error when the certificate expires in this many days or fewer." +PLG_HEALTHCHECK_SSL_ERROR_DAYS_LABEL="Error Threshold (days)" +PLG_HEALTHCHECK_SSL_GROUP_DESC="Health Check modules with the same group show this plugin's results." +PLG_HEALTHCHECK_SSL_GROUP_LABEL="Health Check Group" +PLG_HEALTHCHECK_SSL_ICON_NAME="SSL Certificate" +PLG_HEALTHCHECK_SSL_STATUS_EXPIRED="Expired on %s" +PLG_HEALTHCHECK_SSL_STATUS_EXPIRES_N="Expires in %1$s days (%2$s)" +PLG_HEALTHCHECK_SSL_STATUS_EXPIRES_N_0="Expires today (%2$s)" +PLG_HEALTHCHECK_SSL_STATUS_EXPIRES_N_1="Expires in 1 day (%2$s)" +PLG_HEALTHCHECK_SSL_STATUS_NOT_YET_VALID="Not valid until %s" +PLG_HEALTHCHECK_SSL_STATUS_NO_HTTPS="Site is not served over HTTPS" +PLG_HEALTHCHECK_SSL_STATUS_RENEW_SOON_N="Expires in %1$s days (%2$s). Renew soon." +PLG_HEALTHCHECK_SSL_STATUS_RENEW_SOON_N_0="Expires today (%2$s). Renew now." +PLG_HEALTHCHECK_SSL_STATUS_RENEW_SOON_N_1="Expires in 1 day (%2$s). Renew soon." +PLG_HEALTHCHECK_SSL_STATUS_UNCHECKED="Could not check the certificate" +PLG_HEALTHCHECK_SSL_STATUS_UNTRUSTED="Certificate not trusted (expires %s)" +PLG_HEALTHCHECK_SSL_STATUS_VALID_N="Expires in %1$s days (%2$s)" +PLG_HEALTHCHECK_SSL_STATUS_VALID_N_1="Expires in 1 day (%2$s)" +PLG_HEALTHCHECK_SSL_TIMEOUT_DESC="How long to wait, in seconds, when connecting to the site to read its certificate." +PLG_HEALTHCHECK_SSL_TIMEOUT_LABEL="Timeout (seconds)" +PLG_HEALTHCHECK_SSL_TITLE_CHECKED="Last checked: %s. Select to check again." +PLG_HEALTHCHECK_SSL_TITLE_ISSUER="Issuer: %s." +PLG_HEALTHCHECK_SSL_TITLE_NO_HTTPS="Install a certificate and enable Force HTTPS in Global Configuration." +PLG_HEALTHCHECK_SSL_TITLE_REASON="Reason: %s." +PLG_HEALTHCHECK_SSL_WARNING_DAYS_DESC="Show a warning when the certificate expires in this many days or fewer." +PLG_HEALTHCHECK_SSL_WARNING_DAYS_LABEL="Warning Threshold (days)" +PLG_HEALTHCHECK_SSL_XML_DESCRIPTION="Shows how many days are left before the site's SSL/TLS certificate expires, and whether it is trusted." diff --git a/administrator/language/en-GB/plg_healthcheck_ssl.sys.ini b/administrator/language/en-GB/plg_healthcheck_ssl.sys.ini new file mode 100644 index 00000000000..ece44fa925c --- /dev/null +++ b/administrator/language/en-GB/plg_healthcheck_ssl.sys.ini @@ -0,0 +1,7 @@ +; Joomla! Project +; (C) 2026 Open Source Matters, Inc. +; License GNU General Public License version 2 or later; see LICENSE.txt +; Note : All ini files need to be saved as UTF-8 + +PLG_HEALTHCHECK_SSL="Health Check - SSL Certificate" +PLG_HEALTHCHECK_SSL_XML_DESCRIPTION="Shows how many days are left before the site's SSL/TLS certificate expires, and whether it is trusted." diff --git a/installation/sql/mysql/base.sql b/installation/sql/mysql/base.sql index 469264ea804..72957b69e13 100644 --- a/installation/sql/mysql/base.sql +++ b/installation/sql/mysql/base.sql @@ -318,6 +318,7 @@ INSERT INTO `#__extensions` (`package_id`, `name`, `type`, `element`, `folder`, (0, 'plg_finder_newsfeeds', 'plugin', 'newsfeeds', 'finder', 0, 1, 1, 0, 1, '', '', '', 4, 0), (0, 'plg_finder_tags', 'plugin', 'tags', 'finder', 0, 1, 1, 0, 1, '', '', '', 5, 0), (0, 'plg_healthcheck_usermaintenance', 'plugin', 'usermaintenance', 'healthcheck', 0, 0, 1, 0, 1, '', '{"context":"general"}', '', 1, 0), +(0, 'plg_healthcheck_ssl', 'plugin', 'ssl', 'healthcheck', 0, 0, 1, 0, 1, '', '{"context":"security"}', '', 3, 0), (0, 'plg_installer_folderinstaller', 'plugin', 'folderinstaller', 'installer', 0, 1, 1, 0, 1, '', '', '', 2, 0), (0, 'plg_installer_override', 'plugin', 'override', 'installer', 0, 1, 1, 0, 1, '', '', '', 4, 0), (0, 'plg_installer_packageinstaller', 'plugin', 'packageinstaller', 'installer', 0, 1, 1, 0, 1, '', '', '', 1, 0), diff --git a/installation/sql/postgresql/base.sql b/installation/sql/postgresql/base.sql index 232e7c6633b..6ee6203db99 100644 --- a/installation/sql/postgresql/base.sql +++ b/installation/sql/postgresql/base.sql @@ -324,6 +324,7 @@ INSERT INTO "#__extensions" ("package_id", "name", "type", "element", "folder", (0, 'plg_finder_newsfeeds', 'plugin', 'newsfeeds', 'finder', 0, 1, 1, 0, 1, '', '', '', 4, 0), (0, 'plg_finder_tags', 'plugin', 'tags', 'finder', 0, 1, 1, 0, 1, '', '', '', 5, 0), (0, 'plg_healthcheck_usermaintenance', 'plugin', 'usermaintenance', 'healthcheck', 0, 0, 1, 0, 1, '', '{"context":"general"}', '', 1, 0), +(0, 'plg_healthcheck_ssl', 'plugin', 'ssl', 'healthcheck', 0, 0, 1, 0, 1, '', '{"context":"security"}', '', 3, 0), (0, 'plg_installer_folderinstaller', 'plugin', 'folderinstaller', 'installer', 0, 1, 1, 0, 1, '', '', '', 2, 0), (0, 'plg_installer_override', 'plugin', 'override', 'installer', 0, 1, 1, 0, 1, '', '', '', 4, 0), (0, 'plg_installer_packageinstaller', 'plugin', 'packageinstaller', 'installer', 0, 1, 1, 0, 1, '', '', '', 1, 0), diff --git a/libraries/src/Extension/ExtensionHelper.php b/libraries/src/Extension/ExtensionHelper.php index 7a744b00b1c..752689f6607 100644 --- a/libraries/src/Extension/ExtensionHelper.php +++ b/libraries/src/Extension/ExtensionHelper.php @@ -246,6 +246,7 @@ class ExtensionHelper // Core plugin extensions - healthcheck ['plugin', 'usermaintenance', 'healthcheck', 0], + ['plugin', 'ssl', 'healthcheck', 0], // Core plugin extensions - installer ['plugin', 'folderinstaller', 'installer', 0], diff --git a/plugins/healthcheck/ssl/services/provider.php b/plugins/healthcheck/ssl/services/provider.php new file mode 100644 index 00000000000..f8240b62a80 --- /dev/null +++ b/plugins/healthcheck/ssl/services/provider.php @@ -0,0 +1,49 @@ + + * @license GNU General Public License version 2 or later; see LICENSE.txt + */ + +\defined('_JEXEC') or die; + +use Joomla\CMS\Cache\CacheControllerFactoryInterface; +use Joomla\CMS\Extension\PluginInterface; +use Joomla\CMS\Factory; +use Joomla\CMS\Plugin\PluginHelper; +use Joomla\DI\Container; +use Joomla\DI\ServiceProviderInterface; +use Joomla\Plugin\Healthcheck\Ssl\Certificate\CertificateProbe; +use Joomla\Plugin\Healthcheck\Ssl\Extension\Ssl; + +return new class () implements ServiceProviderInterface { + /** + * Registers the service provider with a DI container. + * + * @param Container $container The DI container. + * + * @return void + * + * @since __DEPLOY_VERSION__ + */ + public function register(Container $container): void + { + $container->set( + PluginInterface::class, + $container->lazy(Ssl::class, function (Container $container): Ssl { + $plugin = new Ssl( + (array) PluginHelper::getPlugin('healthcheck', 'ssl'), + new CertificateProbe() + ); + + $plugin->setApplication(Factory::getApplication()); + $plugin->setCacheControllerFactory($container->get(CacheControllerFactoryInterface::class)); + + return $plugin; + }) + ); + } +}; diff --git a/plugins/healthcheck/ssl/src/Extension/Ssl.php b/plugins/healthcheck/ssl/src/Extension/Ssl.php new file mode 100644 index 00000000000..173ed6040b1 --- /dev/null +++ b/plugins/healthcheck/ssl/src/Extension/Ssl.php @@ -0,0 +1,281 @@ + + * @license GNU General Public License version 2 or later; see LICENSE.txt + */ + +namespace Joomla\Plugin\Healthcheck\Ssl\Extension; + +use Joomla\CMS\Cache\CacheControllerFactoryAwareTrait; +use Joomla\CMS\Cache\Controller\OutputController; +use Joomla\CMS\Event\Plugin\AjaxEvent; +use Joomla\CMS\HTML\HTMLHelper; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Log\Log; +use Joomla\CMS\Plugin\CMSPlugin; +use Joomla\CMS\Session\Session; +use Joomla\CMS\Uri\Uri; +use Joomla\Event\SubscriberInterface; +use Joomla\Module\Healthcheck\Administrator\Event\HealthChecksEvent; +use Joomla\Plugin\Healthcheck\Ssl\Certificate\CertificateProbe; +use Joomla\Plugin\Healthcheck\Ssl\Certificate\CertificateStatus; + +// phpcs:disable PSR1.Files.SideEffects +\defined('_JEXEC') or die; +// phpcs:enable PSR1.Files.SideEffects + +/** + * Health Check plugin showing the expiry and trust of the site's TLS certificate + * + * @since __DEPLOY_VERSION__ + */ +final class Ssl extends CMSPlugin implements SubscriberInterface +{ + use CacheControllerFactoryAwareTrait; + + /** + * Cache group of the probe results + * + * @since __DEPLOY_VERSION__ + */ + private const CACHE_GROUP = 'plg_healthcheck_ssl'; + + /** + * Constructor + * + * @param array $config The plugin configuration + * @param CertificateProbe $probe Reads the certificate from the site's host + * + * @since __DEPLOY_VERSION__ + */ + public function __construct(array $config, private readonly CertificateProbe $probe) + { + parent::__construct($config); + } + + /** + * Returns an array of events this subscriber will listen to. + * + * @return array + * + * @since __DEPLOY_VERSION__ + */ + public static function getSubscribedEvents(): array + { + return [ + 'onHealthcheckGetIcons' => 'onHealthcheckGetIcons', + 'onAjaxSsl' => 'onAjaxSsl', + ]; + } + + /** + * Adds the SSL Certificate icon. + * + * @param HealthChecksEvent $event The health-check event object. + * + * @return void + * + * @since __DEPLOY_VERSION__ + */ + public function onHealthcheckGetIcons(HealthChecksEvent $event): void + { + if ( + $event->getContext() !== $this->params->get('context', 'security') + || !$this->getApplication()->getIdentity()->authorise('core.admin') + ) { + return; + } + + $this->loadLanguage(); + + $now = time(); + $target = CertificateProbe::target(Uri::root()); + + if ($target === null) { + $probe = CertificateProbe::failure('The site URL has no host name.', $now); + } else { + $probe = $target['https'] ? $this->lookup($target['host'], $target['port'], $now) : null; + } + + [$warningDays, $errorDays] = CertificateStatus::thresholds($this->params->get('warning_days'), $this->params->get('error_days')); + + $result = CertificateStatus::evaluate($probe, $now, $warningDays, $errorDays); + $open = \in_array($result['key'], ['PLG_HEALTHCHECK_SSL_STATUS_NO_HTTPS', 'PLG_HEALTHCHECK_SSL_STATUS_UNTRUSTED'], true); + $return = base64_encode(Uri::getInstance()->toString()); + + $icon = [ + 'link' => 'index.php?option=com_ajax&group=healthcheck&plugin=ssl&format=raw&' . Session::getFormToken() . '=1&return=' . urlencode($return), + 'icon' => $open ? 'fas fa-lock-open' : 'fas fa-lock', + 'name' => 'PLG_HEALTHCHECK_SSL_ICON_NAME', + 'text' => $this->message($result), + 'title' => $this->title($probe), + 'id' => 'plg_healthcheck_ssl', + ]; + + if ($result['days'] !== null) { + $icon['amount'] = $result['days']; + } + + if ($result['status'] !== CertificateStatus::NONE) { + $icon['status'] = $result['status']; + } + + $results = $event->getArgument('result', []); + $results[] = [$icon]; + + $event->setArgument('result', $results); + } + + /** + * Forget the stored result so the next dashboard load checks the certificate again. + * + * @param AjaxEvent $event The Ajax event + * + * @return void + * + * @throws \RuntimeException On a missing token or permission + * + * @since __DEPLOY_VERSION__ + */ + public function onAjaxSsl(AjaxEvent $event): void + { + $app = $this->getApplication(); + + if (!$app->isClient('administrator') || !Session::checkToken('get') || !$app->getIdentity()->authorise('core.admin')) { + throw new \RuntimeException(Text::_('JERROR_ALERTNOAUTHOR'), 403); + } + + $target = CertificateProbe::target(Uri::root()); + + if ($target !== null) { + try { + $this->cache()->remove($target['host'] . ':' . $target['port']); + } catch (\Throwable $e) { + Log::add('SSL Health Check: could not clear the stored result: ' . $e->getMessage(), Log::WARNING, 'healthcheck'); + } + } + + $return = base64_decode($app->getInput()->getBase64('return', '')); + + $app->redirect(Uri::isInternal($return) ? $return : 'index.php?option=com_cpanel&view=cpanel&dashboard=healthcheck'); + } + + /** + * Get a fresh cached probe result, or probe and store it. + * + * @param string $host Host name + * @param integer $port Port + * @param integer $now Current Unix time + * + * @return array Probe result + * + * @since __DEPLOY_VERSION__ + */ + private function lookup(string $host, int $port, int $now): array + { + $id = $host . ':' . $port; + + try { + $cached = $this->cache()->get($id); + } catch (\Throwable $e) { + $cached = false; + } + + if (CertificateStatus::isUsable($cached, $now)) { + return $cached; + } + + $probe = $this->probe->probe($host, $port, CertificateStatus::timeout($this->params->get('timeout'))); + + try { + $this->cache()->store($probe, $id); + } catch (\Throwable $e) { + Log::add('SSL Health Check: could not store the result: ' . $e->getMessage(), Log::WARNING, 'healthcheck'); + } + + return $probe; + } + + /** + * The status message, followed by the site's own message for this status if one is set in a language override. + * + * @param array $result CertificateStatus::evaluate() result + * + * @return string HTML from trusted language strings only + * + * @since __DEPLOY_VERSION__ + */ + private function message(array $result): string + { + $date = $result['date'] === null ? '' : HTMLHelper::_('date', gmdate('Y-m-d H:i:s', $result['date']), Text::_('DATE_FORMAT_LC4')); + + if ($result['plural']) { + $text = Text::plural($result['key'], $result['days'], $date); + } elseif ($result['date'] !== null) { + $text = Text::sprintf($result['key'], $date); + } else { + $text = Text::_($result['key']); + } + + $customKey = 'PLG_HEALTHCHECK_SSL_CUSTOM_' . strtoupper($result['status']); + $custom = trim(Text::_($customKey)); + + if ($custom !== '' && $custom !== $customKey) { + $text .= '
' . $custom; + } + + return $text; + } + + /** + * Tooltip: issuer, why the certificate is not trusted or could not be read, and when it was checked. + * + * @param ?array $probe Probe result, or null when the site is not served over HTTPS + * + * @return string Plain text (the layout escapes it) + * + * @since __DEPLOY_VERSION__ + */ + private function title(?array $probe): string + { + if ($probe === null) { + return Text::_('PLG_HEALTHCHECK_SSL_TITLE_NO_HTTPS'); + } + + $parts = []; + + if ($probe['issuer'] !== '') { + $parts[] = Text::sprintf('PLG_HEALTHCHECK_SSL_TITLE_ISSUER', $probe['issuer']); + } + + if ($probe['reason'] !== '') { + $parts[] = Text::sprintf('PLG_HEALTHCHECK_SSL_TITLE_REASON', $probe['reason']); + } + + $parts[] = Text::sprintf( + 'PLG_HEALTHCHECK_SSL_TITLE_CHECKED', + HTMLHelper::_('date', gmdate('Y-m-d H:i:s', $probe['checkedAt']), Text::_('DATE_FORMAT_LC2')) + ); + + return implode(' ', $parts); + } + + /** + * Get the cache controller holding probe results. + * + * @return OutputController + * + * @since __DEPLOY_VERSION__ + */ + private function cache(): OutputController + { + return $this->getCacheControllerFactory()->createCacheController( + 'output', + ['defaultgroup' => self::CACHE_GROUP, 'caching' => true, 'lifetime' => 1440, 'language' => 'en-GB'] + ); + } +} From 148e95472dd1051b6f328cb061d6bf87a3c3482e Mon Sep 17 00:00:00 2001 From: Brian Mitchell Date: Thu, 15 Oct 2026 14:58:03 +0200 Subject: [PATCH 16/29] Harden SSL Health Check probe and messages Co-Authored-By: Claude Opus 5.5 --- .../language/en-GB/plg_healthcheck_ssl.ini | 9 +- installation/sql/mysql/base.sql | 2 +- installation/sql/postgresql/base.sql | 2 +- libraries/src/Extension/ExtensionHelper.php | 2 +- .../ssl/src/Certificate/CertificateProbe.php | 83 +++++++++++++++++-- plugins/healthcheck/ssl/src/Extension/Ssl.php | 13 ++- .../Ssl/Certificate/CertificateProbeTest.php | 13 +++ 7 files changed, 108 insertions(+), 16 deletions(-) diff --git a/administrator/language/en-GB/plg_healthcheck_ssl.ini b/administrator/language/en-GB/plg_healthcheck_ssl.ini index 873251eded3..e4aa717729f 100644 --- a/administrator/language/en-GB/plg_healthcheck_ssl.ini +++ b/administrator/language/en-GB/plg_healthcheck_ssl.ini @@ -14,6 +14,12 @@ PLG_HEALTHCHECK_SSL_ERROR_DAYS_LABEL="Error Threshold (days)" PLG_HEALTHCHECK_SSL_GROUP_DESC="Health Check modules with the same group show this plugin's results." PLG_HEALTHCHECK_SSL_GROUP_LABEL="Health Check Group" PLG_HEALTHCHECK_SSL_ICON_NAME="SSL Certificate" +PLG_HEALTHCHECK_SSL_REASON_HANDSHAKE="The TLS handshake failed without an error message." +PLG_HEALTHCHECK_SSL_REASON_NO_HOST="The site URL has no host name." +PLG_HEALTHCHECK_SSL_REASON_NO_OPENSSL="The PHP OpenSSL extension is not available." +PLG_HEALTHCHECK_SSL_REASON_NO_STREAMS="PHP stream socket functions are disabled on this server." +PLG_HEALTHCHECK_SSL_REASON_PROBE_ERROR="The certificate check failed unexpectedly." +PLG_HEALTHCHECK_SSL_REASON_UNREADABLE="The certificate could not be read." PLG_HEALTHCHECK_SSL_STATUS_EXPIRED="Expired on %s" PLG_HEALTHCHECK_SSL_STATUS_EXPIRES_N="Expires in %1$s days (%2$s)" PLG_HEALTHCHECK_SSL_STATUS_EXPIRES_N_0="Expires today (%2$s)" @@ -21,7 +27,6 @@ PLG_HEALTHCHECK_SSL_STATUS_EXPIRES_N_1="Expires in 1 day (%2$s)" PLG_HEALTHCHECK_SSL_STATUS_NOT_YET_VALID="Not valid until %s" PLG_HEALTHCHECK_SSL_STATUS_NO_HTTPS="Site is not served over HTTPS" PLG_HEALTHCHECK_SSL_STATUS_RENEW_SOON_N="Expires in %1$s days (%2$s). Renew soon." -PLG_HEALTHCHECK_SSL_STATUS_RENEW_SOON_N_0="Expires today (%2$s). Renew now." PLG_HEALTHCHECK_SSL_STATUS_RENEW_SOON_N_1="Expires in 1 day (%2$s). Renew soon." PLG_HEALTHCHECK_SSL_STATUS_UNCHECKED="Could not check the certificate" PLG_HEALTHCHECK_SSL_STATUS_UNTRUSTED="Certificate not trusted (expires %s)" @@ -31,7 +36,7 @@ PLG_HEALTHCHECK_SSL_TIMEOUT_DESC="How long to wait, in seconds, when connecting PLG_HEALTHCHECK_SSL_TIMEOUT_LABEL="Timeout (seconds)" PLG_HEALTHCHECK_SSL_TITLE_CHECKED="Last checked: %s. Select to check again." PLG_HEALTHCHECK_SSL_TITLE_ISSUER="Issuer: %s." -PLG_HEALTHCHECK_SSL_TITLE_NO_HTTPS="Install a certificate and enable Force HTTPS in Global Configuration." +PLG_HEALTHCHECK_SSL_TITLE_NO_HTTPS="If a proxy or CDN provides HTTPS for this site, enable Behind Load Balancer in Global Configuration. Otherwise install a certificate, then enable Force HTTPS." PLG_HEALTHCHECK_SSL_TITLE_REASON="Reason: %s." PLG_HEALTHCHECK_SSL_WARNING_DAYS_DESC="Show a warning when the certificate expires in this many days or fewer." PLG_HEALTHCHECK_SSL_WARNING_DAYS_LABEL="Warning Threshold (days)" diff --git a/installation/sql/mysql/base.sql b/installation/sql/mysql/base.sql index 72957b69e13..cbd4f34145d 100644 --- a/installation/sql/mysql/base.sql +++ b/installation/sql/mysql/base.sql @@ -317,8 +317,8 @@ INSERT INTO `#__extensions` (`package_id`, `name`, `type`, `element`, `folder`, (0, 'plg_finder_content', 'plugin', 'content', 'finder', 0, 1, 1, 0, 1, '', '', '', 3, 0), (0, 'plg_finder_newsfeeds', 'plugin', 'newsfeeds', 'finder', 0, 1, 1, 0, 1, '', '', '', 4, 0), (0, 'plg_finder_tags', 'plugin', 'tags', 'finder', 0, 1, 1, 0, 1, '', '', '', 5, 0), -(0, 'plg_healthcheck_usermaintenance', 'plugin', 'usermaintenance', 'healthcheck', 0, 0, 1, 0, 1, '', '{"context":"general"}', '', 1, 0), (0, 'plg_healthcheck_ssl', 'plugin', 'ssl', 'healthcheck', 0, 0, 1, 0, 1, '', '{"context":"security"}', '', 3, 0), +(0, 'plg_healthcheck_usermaintenance', 'plugin', 'usermaintenance', 'healthcheck', 0, 0, 1, 0, 1, '', '{"context":"general"}', '', 1, 0), (0, 'plg_installer_folderinstaller', 'plugin', 'folderinstaller', 'installer', 0, 1, 1, 0, 1, '', '', '', 2, 0), (0, 'plg_installer_override', 'plugin', 'override', 'installer', 0, 1, 1, 0, 1, '', '', '', 4, 0), (0, 'plg_installer_packageinstaller', 'plugin', 'packageinstaller', 'installer', 0, 1, 1, 0, 1, '', '', '', 1, 0), diff --git a/installation/sql/postgresql/base.sql b/installation/sql/postgresql/base.sql index 6ee6203db99..a21b237369a 100644 --- a/installation/sql/postgresql/base.sql +++ b/installation/sql/postgresql/base.sql @@ -323,8 +323,8 @@ INSERT INTO "#__extensions" ("package_id", "name", "type", "element", "folder", (0, 'plg_finder_content', 'plugin', 'content', 'finder', 0, 1, 1, 0, 1, '', '', '', 3, 0), (0, 'plg_finder_newsfeeds', 'plugin', 'newsfeeds', 'finder', 0, 1, 1, 0, 1, '', '', '', 4, 0), (0, 'plg_finder_tags', 'plugin', 'tags', 'finder', 0, 1, 1, 0, 1, '', '', '', 5, 0), -(0, 'plg_healthcheck_usermaintenance', 'plugin', 'usermaintenance', 'healthcheck', 0, 0, 1, 0, 1, '', '{"context":"general"}', '', 1, 0), (0, 'plg_healthcheck_ssl', 'plugin', 'ssl', 'healthcheck', 0, 0, 1, 0, 1, '', '{"context":"security"}', '', 3, 0), +(0, 'plg_healthcheck_usermaintenance', 'plugin', 'usermaintenance', 'healthcheck', 0, 0, 1, 0, 1, '', '{"context":"general"}', '', 1, 0), (0, 'plg_installer_folderinstaller', 'plugin', 'folderinstaller', 'installer', 0, 1, 1, 0, 1, '', '', '', 2, 0), (0, 'plg_installer_override', 'plugin', 'override', 'installer', 0, 1, 1, 0, 1, '', '', '', 4, 0), (0, 'plg_installer_packageinstaller', 'plugin', 'packageinstaller', 'installer', 0, 1, 1, 0, 1, '', '', '', 1, 0), diff --git a/libraries/src/Extension/ExtensionHelper.php b/libraries/src/Extension/ExtensionHelper.php index 752689f6607..6bab8f495a4 100644 --- a/libraries/src/Extension/ExtensionHelper.php +++ b/libraries/src/Extension/ExtensionHelper.php @@ -245,8 +245,8 @@ class ExtensionHelper ['plugin', 'tags', 'finder', 0], // Core plugin extensions - healthcheck - ['plugin', 'usermaintenance', 'healthcheck', 0], ['plugin', 'ssl', 'healthcheck', 0], + ['plugin', 'usermaintenance', 'healthcheck', 0], // Core plugin extensions - installer ['plugin', 'folderinstaller', 'installer', 0], diff --git a/plugins/healthcheck/ssl/src/Certificate/CertificateProbe.php b/plugins/healthcheck/ssl/src/Certificate/CertificateProbe.php index d9ca7a23ced..d632466ea33 100644 --- a/plugins/healthcheck/ssl/src/Certificate/CertificateProbe.php +++ b/plugins/healthcheck/ssl/src/Certificate/CertificateProbe.php @@ -21,6 +21,48 @@ */ final class CertificateProbe { + /** + * Reason: the TLS handshake failed without any message. + * + * @since __DEPLOY_VERSION__ + */ + public const REASON_HANDSHAKE = 'PLG_HEALTHCHECK_SSL_REASON_HANDSHAKE'; + + /** + * Reason: the site URL has no host name. + * + * @since __DEPLOY_VERSION__ + */ + public const REASON_NO_HOST = 'PLG_HEALTHCHECK_SSL_REASON_NO_HOST'; + + /** + * Reason: the PHP OpenSSL extension is missing. + * + * @since __DEPLOY_VERSION__ + */ + public const REASON_NO_OPENSSL = 'PLG_HEALTHCHECK_SSL_REASON_NO_OPENSSL'; + + /** + * Reason: the PHP stream socket functions are disabled. + * + * @since __DEPLOY_VERSION__ + */ + public const REASON_NO_STREAMS = 'PLG_HEALTHCHECK_SSL_REASON_NO_STREAMS'; + + /** + * Reason: the probe threw unexpectedly. + * + * @since __DEPLOY_VERSION__ + */ + public const REASON_PROBE_ERROR = 'PLG_HEALTHCHECK_SSL_REASON_PROBE_ERROR'; + + /** + * Reason: the certificate was received but could not be parsed. + * + * @since __DEPLOY_VERSION__ + */ + public const REASON_UNREADABLE = 'PLG_HEALTHCHECK_SSL_REASON_UNREADABLE'; + /** * Derive the host, port and scheme to check from the site root URL. * @@ -93,6 +135,22 @@ public static function cleanReason(string $message): string return trim(preg_replace('/\s+/', ' ', $message)); } + /** + * Clean a raw warning into a reason, falling back to the generic handshake reason when nothing is left. + * + * @param string $message Warning text, possibly empty + * + * @return string Cleaned text, or a language key + * + * @since __DEPLOY_VERSION__ + */ + public static function reasonFrom(string $message): string + { + $reason = self::cleanReason($message); + + return $reason === '' ? self::REASON_HANDSHAKE : $reason; + } + /** * A probe result for a certificate that could not be read. * @@ -110,7 +168,8 @@ public static function failure(string $reason, int $checkedAt): array /** * Connect to the host, complete a TLS handshake and read its certificate. - * Verification failures are retried once without verification so the expiry date can still be reported. + * When the verified handshake connects but returns no certificate, it is retried once without verification + * so the expiry date can still be reported. A connection that fails is not retried. * * @param string $host Host name or IP address * @param integer $port TCP port @@ -125,7 +184,13 @@ public function probe(string $host, int $port, int $timeout): array $checkedAt = time(); if (!\extension_loaded('openssl')) { - return self::failure('The PHP OpenSSL extension is not available.', $checkedAt); + return self::failure(self::REASON_NO_OPENSSL, $checkedAt); + } + + foreach (['stream_socket_client', 'stream_socket_enable_crypto', 'stream_context_create', 'stream_context_get_options'] as $function) { + if (!\function_exists($function)) { + return self::failure(self::REASON_NO_STREAMS, $checkedAt); + } } $verified = $this->handshake($host, $port, $timeout, true); @@ -134,18 +199,20 @@ public function probe(string $host, int $port, int $timeout): array return $this->result($verified['certificate'], true, '', $checkedAt); } - // Only a failed verification is worth a second attempt; a refused or timed-out connection would just fail again. - if (!$verified['connected'] || !preg_match('/certificate|did not match/i', $verified['error'])) { - return self::failure(self::cleanReason($verified['error']), $checkedAt); + $reason = self::reasonFrom($verified['error']); + + // A connection that failed would just fail again; only a connected but unverified handshake is retried. + if (!$verified['connected']) { + return self::failure($reason, $checkedAt); } $unverified = $this->handshake($host, $port, $timeout, false); if ($unverified['certificate'] === null) { - return self::failure(self::cleanReason($verified['error']), $checkedAt); + return self::failure($reason, $checkedAt); } - return $this->result($unverified['certificate'], false, self::cleanReason($verified['error']), $checkedAt); + return $this->result($unverified['certificate'], false, $reason, $checkedAt); } /** @@ -165,7 +232,7 @@ private function result(\OpenSSLCertificate $certificate, bool $trusted, string $parsed = self::parse($certificate); if ($parsed === null) { - return self::failure('The certificate could not be read.', $checkedAt); + return self::failure(self::REASON_UNREADABLE, $checkedAt); } return ['ok' => true, 'trusted' => $trusted, 'reason' => $reason] + $parsed + ['checkedAt' => $checkedAt]; diff --git a/plugins/healthcheck/ssl/src/Extension/Ssl.php b/plugins/healthcheck/ssl/src/Extension/Ssl.php index 173ed6040b1..2075e2799f4 100644 --- a/plugins/healthcheck/ssl/src/Extension/Ssl.php +++ b/plugins/healthcheck/ssl/src/Extension/Ssl.php @@ -96,7 +96,7 @@ public function onHealthcheckGetIcons(HealthChecksEvent $event): void $target = CertificateProbe::target(Uri::root()); if ($target === null) { - $probe = CertificateProbe::failure('The site URL has no host name.', $now); + $probe = CertificateProbe::failure(CertificateProbe::REASON_NO_HOST, $now); } else { $probe = $target['https'] ? $this->lookup($target['host'], $target['port'], $now) : null; } @@ -189,7 +189,13 @@ private function lookup(string $host, int $port, int $now): array return $cached; } - $probe = $this->probe->probe($host, $port, CertificateStatus::timeout($this->params->get('timeout'))); + try { + $probe = $this->probe->probe($host, $port, CertificateStatus::timeout($this->params->get('timeout'))); + } catch (\Throwable $e) { + Log::add('SSL Health Check: the probe failed: ' . $e->getMessage(), Log::WARNING, 'healthcheck'); + + $probe = CertificateProbe::failure(CertificateProbe::REASON_PROBE_ERROR, $now); + } try { $this->cache()->store($probe, $id); @@ -253,7 +259,8 @@ private function title(?array $probe): string } if ($probe['reason'] !== '') { - $parts[] = Text::sprintf('PLG_HEALTHCHECK_SSL_TITLE_REASON', $probe['reason']); + $reason = str_starts_with($probe['reason'], 'PLG_HEALTHCHECK_SSL_REASON_') ? Text::_($probe['reason']) : $probe['reason']; + $parts[] = Text::sprintf('PLG_HEALTHCHECK_SSL_TITLE_REASON', $reason); } $parts[] = Text::sprintf( diff --git a/tests/Unit/Plugin/Healthcheck/Ssl/Certificate/CertificateProbeTest.php b/tests/Unit/Plugin/Healthcheck/Ssl/Certificate/CertificateProbeTest.php index f268c88ad6d..64066748f3e 100644 --- a/tests/Unit/Plugin/Healthcheck/Ssl/Certificate/CertificateProbeTest.php +++ b/tests/Unit/Plugin/Healthcheck/Ssl/Certificate/CertificateProbeTest.php @@ -121,6 +121,19 @@ public function testCleanReason(): void $this->assertSame('Connection refused', CertificateProbe::cleanReason(' Connection refused ')); } + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('uses the generic handshake reason when a warning is empty')] + public function testReasonFrom(): void + { + $this->assertSame(CertificateProbe::REASON_HANDSHAKE, CertificateProbe::reasonFrom('')); + $this->assertSame(CertificateProbe::REASON_HANDSHAKE, CertificateProbe::reasonFrom(" stream_socket_enable_crypto(): \n ")); + $this->assertSame('Connection refused', CertificateProbe::reasonFrom('Connection refused')); + } + /** * @return void * From 00237982677c33f049697ab924b1d103a8ef1cb0 Mon Sep 17 00:00:00 2001 From: Brian Mitchell Date: Thu, 15 Oct 2026 15:24:59 +0200 Subject: [PATCH 17/29] Show the certificate name in the SSL Health Check tooltip Co-Authored-By: Claude Opus 5.5 --- .../language/en-GB/plg_healthcheck_ssl.ini | 1 + .../ssl/src/Certificate/CertificateProbe.php | 43 +++++++++++++++++-- .../ssl/src/Certificate/CertificateStatus.php | 3 +- plugins/healthcheck/ssl/src/Extension/Ssl.php | 6 ++- .../Ssl/Certificate/CertificateProbeTest.php | 34 +++++++++++++++ .../Ssl/Certificate/CertificateStatusTest.php | 30 +++++++------ 6 files changed, 97 insertions(+), 20 deletions(-) diff --git a/administrator/language/en-GB/plg_healthcheck_ssl.ini b/administrator/language/en-GB/plg_healthcheck_ssl.ini index e4aa717729f..e08c81d5d18 100644 --- a/administrator/language/en-GB/plg_healthcheck_ssl.ini +++ b/administrator/language/en-GB/plg_healthcheck_ssl.ini @@ -38,6 +38,7 @@ PLG_HEALTHCHECK_SSL_TITLE_CHECKED="Last checked: %s. Select to check again." PLG_HEALTHCHECK_SSL_TITLE_ISSUER="Issuer: %s." PLG_HEALTHCHECK_SSL_TITLE_NO_HTTPS="If a proxy or CDN provides HTTPS for this site, enable Behind Load Balancer in Global Configuration. Otherwise install a certificate, then enable Force HTTPS." PLG_HEALTHCHECK_SSL_TITLE_REASON="Reason: %s." +PLG_HEALTHCHECK_SSL_TITLE_SUBJECT="Issued for: %s." PLG_HEALTHCHECK_SSL_WARNING_DAYS_DESC="Show a warning when the certificate expires in this many days or fewer." PLG_HEALTHCHECK_SSL_WARNING_DAYS_LABEL="Warning Threshold (days)" PLG_HEALTHCHECK_SSL_XML_DESCRIPTION="Shows how many days are left before the site's SSL/TLS certificate expires, and whether it is trusted." diff --git a/plugins/healthcheck/ssl/src/Certificate/CertificateProbe.php b/plugins/healthcheck/ssl/src/Certificate/CertificateProbe.php index d632466ea33..bf13034c8ca 100644 --- a/plugins/healthcheck/ssl/src/Certificate/CertificateProbe.php +++ b/plugins/healthcheck/ssl/src/Certificate/CertificateProbe.php @@ -88,11 +88,11 @@ public static function target(string $rootUrl): ?array } /** - * Read validity dates and issuer from a certificate. + * Read validity dates, issuer and subject name from a certificate. * * @param \OpenSSLCertificate|string $certificate Certificate object or PEM string * - * @return array|null ['validFrom' => int, 'validTo' => int, 'issuer' => string], or null if unreadable + * @return array|null ['validFrom' => int, 'validTo' => int, 'issuer' => string, 'subject' => string], or null if unreadable * * @since __DEPLOY_VERSION__ */ @@ -116,9 +116,44 @@ public static function parse(\OpenSSLCertificate|string $certificate): ?array 'validFrom' => (int) $info['validFrom_time_t'], 'validTo' => (int) $info['validTo_time_t'], 'issuer' => \is_array($issuer) ? implode(', ', $issuer) : (string) $issuer, + 'subject' => self::subjectName($info), ]; } + /** + * The name a certificate was issued for: the common name, else the first DNS name in the subject alternative names. + * + * @param array $info An openssl_x509_parse() array + * + * @return string The name, or an empty string when there is none + * + * @since __DEPLOY_VERSION__ + */ + public static function subjectName(array $info): string + { + $common = $info['subject']['CN'] ?? ''; + + foreach ((array) $common as $name) { + if (\is_string($name) && $name !== '') { + return $name; + } + } + + $alternatives = $info['extensions']['subjectAltName'] ?? ''; + + if (\is_string($alternatives)) { + foreach (explode(',', $alternatives) as $entry) { + $entry = trim($entry); + + if (str_starts_with($entry, 'DNS:') && trim(substr($entry, 4)) !== '') { + return trim(substr($entry, 4)); + } + } + } + + return ''; + } + /** * Turn a PHP stream warning into a one-line reason. * @@ -163,7 +198,7 @@ public static function reasonFrom(string $message): string */ public static function failure(string $reason, int $checkedAt): array { - return ['ok' => false, 'trusted' => false, 'reason' => $reason, 'validFrom' => null, 'validTo' => null, 'issuer' => '', 'checkedAt' => $checkedAt]; + return ['ok' => false, 'trusted' => false, 'reason' => $reason, 'validFrom' => null, 'validTo' => null, 'issuer' => '', 'subject' => '', 'checkedAt' => $checkedAt]; } /** @@ -175,7 +210,7 @@ public static function failure(string $reason, int $checkedAt): array * @param integer $port TCP port * @param integer $timeout Seconds for the connect and for the handshake * - * @return array ['ok', 'trusted', 'reason', 'validFrom', 'validTo', 'issuer', 'checkedAt'] + * @return array ['ok', 'trusted', 'reason', 'validFrom', 'validTo', 'issuer', 'subject', 'checkedAt'] * * @since __DEPLOY_VERSION__ */ diff --git a/plugins/healthcheck/ssl/src/Certificate/CertificateStatus.php b/plugins/healthcheck/ssl/src/Certificate/CertificateStatus.php index 2d6147941f1..d307f828141 100644 --- a/plugins/healthcheck/ssl/src/Certificate/CertificateStatus.php +++ b/plugins/healthcheck/ssl/src/Certificate/CertificateStatus.php @@ -95,13 +95,14 @@ public static function isUsable(mixed $cached, int $now): bool { if ( !\is_array($cached) - || !isset($cached['ok'], $cached['trusted'], $cached['reason'], $cached['issuer'], $cached['checkedAt']) + || !isset($cached['ok'], $cached['trusted'], $cached['reason'], $cached['issuer'], $cached['subject'], $cached['checkedAt']) || !\array_key_exists('validFrom', $cached) || !\array_key_exists('validTo', $cached) || !\is_bool($cached['ok']) || !\is_bool($cached['trusted']) || !\is_string($cached['reason']) || !\is_string($cached['issuer']) + || !\is_string($cached['subject']) || !\is_int($cached['checkedAt']) ) { return false; diff --git a/plugins/healthcheck/ssl/src/Extension/Ssl.php b/plugins/healthcheck/ssl/src/Extension/Ssl.php index 2075e2799f4..20523524314 100644 --- a/plugins/healthcheck/ssl/src/Extension/Ssl.php +++ b/plugins/healthcheck/ssl/src/Extension/Ssl.php @@ -238,7 +238,7 @@ private function message(array $result): string } /** - * Tooltip: issuer, why the certificate is not trusted or could not be read, and when it was checked. + * Tooltip: the name the certificate was issued for, the issuer, why the certificate is not trusted or could not be read, and when it was checked. * * @param ?array $probe Probe result, or null when the site is not served over HTTPS * @@ -254,6 +254,10 @@ private function title(?array $probe): string $parts = []; + if ($probe['subject'] !== '') { + $parts[] = Text::sprintf('PLG_HEALTHCHECK_SSL_TITLE_SUBJECT', $probe['subject']); + } + if ($probe['issuer'] !== '') { $parts[] = Text::sprintf('PLG_HEALTHCHECK_SSL_TITLE_ISSUER', $probe['issuer']); } diff --git a/tests/Unit/Plugin/Healthcheck/Ssl/Certificate/CertificateProbeTest.php b/tests/Unit/Plugin/Healthcheck/Ssl/Certificate/CertificateProbeTest.php index 64066748f3e..f2a196f60bb 100644 --- a/tests/Unit/Plugin/Healthcheck/Ssl/Certificate/CertificateProbeTest.php +++ b/tests/Unit/Plugin/Healthcheck/Ssl/Certificate/CertificateProbeTest.php @@ -57,6 +57,38 @@ public function testTarget(string $url, ?array $expected): void $this->assertSame($expected, CertificateProbe::target($url)); } + /** + * @return array + * + * @since __DEPLOY_VERSION__ + */ + public static function subjectProvider(): array + { + return [ + 'common name' => [['subject' => ['CN' => 'example.org']], 'example.org'], + 'common name as array' => [['subject' => ['CN' => ['', 'first.example', 'second.example']]], 'first.example'], + 'empty name uses SAN' => [['subject' => ['CN' => ''], 'extensions' => ['subjectAltName' => 'DNS:a.example, DNS:b.example']], 'a.example'], + 'SAN skips non-DNS' => [['subject' => [], 'extensions' => ['subjectAltName' => 'IP Address:10.0.0.1, DNS:c.example']], 'c.example'], + 'no name at all' => [['subject' => ['O' => 'Org']], ''], + 'SAN without DNS entry' => [['extensions' => ['subjectAltName' => 'IP Address:10.0.0.1, email:a@example.org']], ''], + ]; + } + + /** + * @param array $info An openssl_x509_parse() array + * @param string $expected The name + * + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[DataProvider('subjectProvider')] + #[TestDox('finds the name a certificate was issued for')] + public function testSubjectName(array $info, string $expected): void + { + $this->assertSame($expected, CertificateProbe::subjectName($info)); + } + /** * @return void * @@ -72,6 +104,7 @@ public function testParse(): void $parsed = CertificateProbe::parse($cert); $this->assertSame('Test Issuer', $parsed['issuer']); + $this->assertSame('example.test', $parsed['subject']); $this->assertSame(30 * 86400, $parsed['validTo'] - $parsed['validFrom']); $this->assertEqualsWithDelta(time(), $parsed['validFrom'], 120); @@ -147,6 +180,7 @@ public function testRefused(): void $this->assertFalse($result['ok']); $this->assertFalse($result['trusted']); $this->assertNotSame('', $result['reason']); + $this->assertSame('', $result['subject']); $this->assertNull($result['validTo']); $this->assertEqualsWithDelta(time(), $result['checkedAt'], 5); } diff --git a/tests/Unit/Plugin/Healthcheck/Ssl/Certificate/CertificateStatusTest.php b/tests/Unit/Plugin/Healthcheck/Ssl/Certificate/CertificateStatusTest.php index bec29dacd0a..1bbbfd40a0d 100644 --- a/tests/Unit/Plugin/Healthcheck/Ssl/Certificate/CertificateStatusTest.php +++ b/tests/Unit/Plugin/Healthcheck/Ssl/Certificate/CertificateStatusTest.php @@ -47,6 +47,7 @@ private function probe(int $validTo, bool $trusted = true, ?int $validFrom = nul 'validFrom' => $validFrom ?? self::NOW - 60 * self::DAY, 'validTo' => $validTo, 'issuer' => 'Test CA', + 'subject' => 'example.test', 'checkedAt' => self::NOW, ]; } @@ -176,7 +177,7 @@ public function testNoHttps(): void #[TestDox('stays neutral when the certificate could not be read')] public function testUnchecked(): void { - $probe = ['ok' => false, 'trusted' => false, 'reason' => 'Connection refused', 'validFrom' => null, 'validTo' => null, 'issuer' => '', 'checkedAt' => self::NOW]; + $probe = ['ok' => false, 'trusted' => false, 'reason' => 'Connection refused', 'validFrom' => null, 'validTo' => null, 'issuer' => '', 'subject' => '', 'checkedAt' => self::NOW]; $this->assertSame( ['status' => 'none', 'key' => 'PLG_HEALTHCHECK_SSL_STATUS_UNCHECKED', 'days' => null, 'date' => null, 'plural' => false], @@ -284,21 +285,22 @@ public function testTimeout(mixed $raw, int $expected): void public static function usableProvider(): array { $now = self::NOW; - $success = ['ok' => true, 'trusted' => true, 'reason' => '', 'validFrom' => $now - 86400, 'validTo' => $now + 86400 * 60, 'issuer' => 'CA', 'checkedAt' => $now - 3600]; - $failure = ['ok' => false, 'trusted' => false, 'reason' => 'refused', 'validFrom' => null, 'validTo' => null, 'issuer' => '', 'checkedAt' => $now - 600]; + $success = ['ok' => true, 'trusted' => true, 'reason' => '', 'validFrom' => $now - 86400, 'validTo' => $now + 86400 * 60, 'issuer' => 'CA', 'subject' => 'example.org', 'checkedAt' => $now - 3600]; + $failure = ['ok' => false, 'trusted' => false, 'reason' => 'refused', 'validFrom' => null, 'validTo' => null, 'issuer' => '', 'subject' => '', 'checkedAt' => $now - 600]; return [ - 'fresh success' => [$success, true], - 'success at 23 hours' => [['checkedAt' => $now - 82800] + $success, true], - 'success at 24 hours' => [['checkedAt' => $now - 86400] + $success, false], - 'fresh failure' => [$failure, true], - 'failure at one hour' => [['checkedAt' => $now - 3600] + $failure, false], - 'checked in the future' => [['checkedAt' => $now + 60] + $success, false], - 'cache miss' => [false, false], - 'not an array' => ['x', false], - 'missing key' => [array_diff_key($success, ['issuer' => true]), false], - 'string timestamp' => [['validTo' => '1800000000'] + $success, false], - 'ok without dates' => [['validTo' => null] + $success, false], + 'fresh success' => [$success, true], + 'success at 23 hours' => [['checkedAt' => $now - 82800] + $success, true], + 'success at 24 hours' => [['checkedAt' => $now - 86400] + $success, false], + 'fresh failure' => [$failure, true], + 'failure at one hour' => [['checkedAt' => $now - 3600] + $failure, false], + 'checked in the future' => [['checkedAt' => $now + 60] + $success, false], + 'cache miss' => [false, false], + 'not an array' => ['x', false], + 'missing key' => [array_diff_key($success, ['issuer' => true]), false], + 'missing subject (old cache shape)' => [array_diff_key($success, ['subject' => true]), false], + 'string timestamp' => [['validTo' => '1800000000'] + $success, false], + 'ok without dates' => [['validTo' => null] + $success, false], ]; } From e327e964ad22aa0e588a588e31566e43d0f4cdc5 Mon Sep 17 00:00:00 2001 From: Brian Mitchell Date: Thu, 15 Oct 2026 16:05:12 +0200 Subject: [PATCH 18/29] Trim the manual page fixture for the Site Information tests Keep only what parseManual() reads (headings with their anchor markup, the requirements table with its section rows, the memory limit line), add line breaks, and note the source page and retrieval date. Co-Authored-By: Claude Opus 5.5 --- .../fixtures/technical-requirements.html | 63 ++++++++++--------- 1 file changed, 32 insertions(+), 31 deletions(-) diff --git a/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/fixtures/technical-requirements.html b/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/fixtures/technical-requirements.html index bee062a7e92..64348a7b8dd 100644 --- a/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/fixtures/technical-requirements.html +++ b/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/fixtures/technical-requirements.html @@ -1,36 +1,37 @@ -
Version: 6.1 (Current)

Technical Requirements

+ + + + + +
+

Technical Requirements

Requirements for Supported Software​

-
    -
  • You should use at least the version listed in the Recommended column.
  • -
  • The minimum supported version is listed in the Supported column.
  • -
  • The version in the Minimum column is the absolute minimum, -but if it is below the Supported version then if you choose to use it, you are responsible for resolving any issues that may arise.
  • -

Requirements for Joomla! 6.x​

-
SoftwareRecommendedSupportedMinimum
PHP8.48.3.08.3.0
Databases
MySQL8.48.0.138.0.13
MariaDB12.010.610.4
PostgreSQL17.614.012.0
Web Servers
Apache2.42.4
Nginx1.291.26
Microsoft IIS1010
+ + + + + + + + + + + + + +
SoftwareRecommendedSupportedMinimum
PHP8.48.3.08.3.0
Databases
MySQL8.48.0.138.0.13
MariaDB12.010.610.4
PostgreSQL17.614.012.0
Web Servers
Apache2.42.4
Nginx1.291.26
Microsoft IIS1010

Required PHP Modules: json, simplexml, dom, zlib, gd, mysqlnd or pdo_mysql or pdo_pgsql
Recommended PHP Modules: mbstring
-Recommended PHP Memory Limit: at least 256MB
-Optional Apache Modules: mod_rewrite extension to use SEO URLs
-Optional Microsoft IIS Modules: URL Rewrite Module to use SEO URLs

+Recommended PHP Memory Limit: at least 256MB

Additional Information​

-
    -
  • PHP A popular general-purpose scripting language that is especially suited to web development.
  • -
  • MySQL is available in several editions. It is normal to install a GPL Community Edition for your software platform.
  • -
  • MariaDB is also available in several editions. It is normal to install a free Community Edition for your software platform.
  • -
  • PostgreSQL is open source and available in numerous editions.
  • -
  • Apache HTTP Server Project is an effort to develop and maintain an open-source HTTP server for modern operating systems including UNIX and Windows.
  • -
  • Nginx is an HTTP web server, reverse proxy, content cache and load balancer.
  • -
  • Microsoft IIS (Internet Information Services) for Windows® Server is a flexible, secure and manageable Web server for hosting anything on the Web.
  • -
-

Glossary​

- -

This column describes which version the Joomla! Project recommends to use for the selected Joomla version.

-

Supported​

-

This column describes which version the Joomla! Project has set as the minimum supported version. -This means any bug found in this version or higher will be considered for fixing. This version might -not be enforced.

-

Minimum​

-

This column describes the minimum version enforced by the CMS or the framework in use. That means you may sometimes use -a lower version than the supported version, but not lower than the minimum version. For versions below -the supported version, you might not receive support from the Joomla maintainers.

+ + + From 4bc4b3d707210d7555c528251e456167eb6d7404 Mon Sep 17 00:00:00 2001 From: Brian Mitchell Date: Thu, 15 Oct 2026 16:05:39 +0200 Subject: [PATCH 19/29] Apply coding standards to Site Information test data Co-Authored-By: Claude Opus 5.5 --- .../Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php b/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php index 2fd55f18d7e..d4c4741a6e8 100644 --- a/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php +++ b/tests/Unit/Plugin/Healthcheck/Siteinfo/Support/SupportDataTest.php @@ -116,7 +116,7 @@ public static function eolProvider(): array 'gap in known cycles' => ['mysql', '8.5.0', 'none', 'PLG_HEALTHCHECK_SITEINFO_STATUS_NO_DATA', []], 'joomla dev version' => ['joomla', '6.2.1-dev', 'healthy', 'PLG_HEALTHCHECK_SITEINFO_STATUS_SUPPORTED', ['2029-10-16']], 'empty version' => ['mysql', '', 'none', 'PLG_HEALTHCHECK_SITEINFO_STATUS_NO_DATA', []], - 'unparsable version' => ['php', 'unknown', 'none', 'PLG_HEALTHCHECK_SITEINFO_STATUS_NO_DATA', []], + 'unparsable version' => ['php', 'unknown', 'none', 'PLG_HEALTHCHECK_SITEINFO_STATUS_NO_DATA', []], ]; } From 38c0585a0779c0256de9edcbb025bcfe2f11b7a9 Mon Sep 17 00:00:00 2001 From: Brian Mitchell Date: Thu, 15 Oct 2026 16:51:01 +0200 Subject: [PATCH 20/29] Add security headers score for the Health Check Co-Authored-By: Claude Opus 5.5 --- .../securityheaders/securityheaders.xml | 44 +++ .../src/Headers/HeaderScore.php | 261 +++++++++++++ .../Headers/HeaderScoreTest.php | 344 ++++++++++++++++++ 3 files changed, 649 insertions(+) create mode 100644 plugins/healthcheck/securityheaders/securityheaders.xml create mode 100644 plugins/healthcheck/securityheaders/src/Headers/HeaderScore.php create mode 100644 tests/Unit/Plugin/Healthcheck/Securityheaders/Headers/HeaderScoreTest.php diff --git a/plugins/healthcheck/securityheaders/securityheaders.xml b/plugins/healthcheck/securityheaders/securityheaders.xml new file mode 100644 index 00000000000..664b1a74950 --- /dev/null +++ b/plugins/healthcheck/securityheaders/securityheaders.xml @@ -0,0 +1,44 @@ + + + plg_healthcheck_securityheaders + Joomla! Project + 2026-10 + (C) 2026 Open Source Matters, Inc. + GNU General Public License version 2 or later; see LICENSE.txt + admin@joomla.org + www.joomla.org + 6.2.0 + PLG_HEALTHCHECK_SECURITYHEADERS_XML_DESCRIPTION + Joomla\Plugin\Healthcheck\Securityheaders + + services + src + + + language/en-GB/plg_healthcheck_securityheaders.ini + language/en-GB/plg_healthcheck_securityheaders.sys.ini + + + +
+ + +
+
+
+
diff --git a/plugins/healthcheck/securityheaders/src/Headers/HeaderScore.php b/plugins/healthcheck/securityheaders/src/Headers/HeaderScore.php new file mode 100644 index 00000000000..22e0eedcef8 --- /dev/null +++ b/plugins/healthcheck/securityheaders/src/Headers/HeaderScore.php @@ -0,0 +1,261 @@ + + * @license GNU General Public License version 2 or later; see LICENSE.txt + */ + +namespace Joomla\Plugin\Healthcheck\Securityheaders\Headers; + +// phpcs:disable PSR1.Files.SideEffects +\defined('_JEXEC') or die; +// phpcs:enable PSR1.Files.SideEffects + +/** + * Scores HTTP security headers with fixed weights. Pure: no I/O. + * + * @since __DEPLOY_VERSION__ + */ +final class HeaderScore +{ + /** + * Minimum HSTS max-age for full marks: 180 days + * + * @since __DEPLOY_VERSION__ + */ + public const HSTS_MIN_AGE = 15552000; + + /** + * Every Referrer-Policy token browsers recognise + * + * @since __DEPLOY_VERSION__ + */ + private const REFERRER_TOKENS = [ + 'no-referrer', 'no-referrer-when-downgrade', 'origin', 'origin-when-cross-origin', + 'same-origin', 'strict-origin', 'strict-origin-when-cross-origin', 'unsafe-url', + ]; + + /** + * Referrer-Policy values that do not leak full URLs to other sites + * + * @since __DEPLOY_VERSION__ + */ + private const REFERRER_SAFE = [ + 'no-referrer', 'origin', 'origin-when-cross-origin', 'same-origin', 'strict-origin', 'strict-origin-when-cross-origin', + ]; + + /** + * Score a set of response headers. + * + * @param array $headers Lower-cased header names to values, repeated headers joined with ", " + * @param boolean $https Whether the scored response came from an https URL + * + * @return array ['score' => int, 'status' => string, 'items' => list] + * + * @since __DEPLOY_VERSION__ + */ + public static function evaluate(array $headers, bool $https): array + { + $get = static fn (string $name): string => trim((string) ($headers[$name] ?? '')); + + $items = [ + self::hsts($get('strict-transport-security'), $https), + self::csp($get('content-security-policy'), $get('content-security-policy-report-only')), + self::frame($get('x-frame-options'), $get('content-security-policy')), + self::single('nosniff', 15, $get('x-content-type-options'), ['nosniff']), + self::referrer($get('referrer-policy')), + self::present('permissions', 5, $get('permissions-policy')), + self::present('coop', 5, $get('cross-origin-opener-policy')), + self::leak($get('server'), $get('x-powered-by')), + ]; + + $score = max(0, min(100, array_sum(array_column($items, 'points')))); + + return [ + 'score' => $score, + 'status' => $score >= 80 ? 'success' : ($score >= 50 ? 'warning' : 'error'), + 'items' => $items, + ]; + } + + /** + * Strict-Transport-Security: full marks from 180 days, partial below, nothing on plain http. + * + * @param string $value Header value + * @param boolean $https Whether the response came over https + * + * @return array + * + * @since __DEPLOY_VERSION__ + */ + private static function hsts(string $value, bool $https): array + { + if (!$https) { + return self::item('hsts', 0, 25, $value, 'PLG_HEALTHCHECK_SECURITYHEADERS_FIX_HSTS_HTTP'); + } + + $age = preg_match('/(?:^|;)\s*max-age\s*=\s*"?(\d+)"?\s*(?:;|$)/i', $value, $matches) ? (int) $matches[1] : 0; + + return self::item('hsts', $age >= self::HSTS_MIN_AGE ? 25 : ($age > 0 ? 10 : 0), 25, $value); + } + + /** + * Content-Security-Policy: enforced is full marks, report-only is partial. + * + * @param string $enforced Content-Security-Policy value + * @param string $reportOnly Content-Security-Policy-Report-Only value + * + * @return array + * + * @since __DEPLOY_VERSION__ + */ + private static function csp(string $enforced, string $reportOnly): array + { + if ($enforced !== '') { + return self::item('csp', 25, 25, $enforced); + } + + return self::item('csp', $reportOnly !== '' ? 10 : 0, 25, $reportOnly); + } + + /** + * Frame protection: X-Frame-Options DENY or SAMEORIGIN, or an enforced CSP frame-ancestors directive. + * + * @param string $xfo X-Frame-Options value + * @param string $csp Content-Security-Policy value + * + * @return array + * + * @since __DEPLOY_VERSION__ + */ + private static function frame(string $xfo, string $csp): array + { + $item = self::single('frame', 15, $xfo, ['deny', 'sameorigin']); + + if ($item['points'] === 0 && preg_match('/(?:^|;)\s*(frame-ancestors\b[^;]*)/i', $csp, $matches)) { + return self::item('frame', 15, 15, trim($matches[1])); + } + + return $item; + } + + /** + * Referrer-Policy: the last recognised token is the one browsers apply. + * + * @param string $value Header value + * + * @return array + * + * @since __DEPLOY_VERSION__ + */ + private static function referrer(string $value): array + { + $effective = ''; + + foreach (self::tokens($value) as $token) { + if (\in_array($token, self::REFERRER_TOKENS, true)) { + $effective = $token; + } + } + + return self::item('referrer', \in_array($effective, self::REFERRER_SAFE, true) ? 10 : 0, 10, $value); + } + + /** + * A header that must carry exactly one of the accepted values (duplicates of the same value are fine). + * + * @param string $key Item key + * @param integer $max Points for an accepted value + * @param string $value Header value + * @param string[] $accepted Accepted lower-case values + * + * @return array + * + * @since __DEPLOY_VERSION__ + */ + private static function single(string $key, int $max, string $value, array $accepted): array + { + $tokens = array_values(array_unique(self::tokens($value))); + $ok = \count($tokens) === 1 && \in_array($tokens[0], $accepted, true); + + return self::item($key, $ok ? $max : 0, $max, $value); + } + + /** + * A header that only needs to be present. + * + * @param string $key Item key + * @param integer $max Points when present + * @param string $value Header value + * + * @return array + * + * @since __DEPLOY_VERSION__ + */ + private static function present(string $key, int $max, string $value): array + { + return self::item($key, $value !== '' ? $max : 0, $max, $value); + } + + /** + * Version numbers in Server or X-Powered-By cost 5 points. + * + * @param string $server Server value + * @param string $poweredBy X-Powered-By value + * + * @return array + * + * @since __DEPLOY_VERSION__ + */ + private static function leak(string $server, string $poweredBy): array + { + $leaks = array_values(array_filter([$server, $poweredBy], static fn (string $value): bool => (bool) preg_match('/\d+\.\d+/', $value))); + + return self::item('leak', $leaks === [] ? 0 : -5, 0, implode(', ', $leaks)); + } + + /** + * Comma-separated, trimmed, lower-case tokens. + * + * @param string $value Header value + * + * @return string[] + * + * @since __DEPLOY_VERSION__ + */ + private static function tokens(string $value): array + { + return array_values(array_filter(array_map(static fn (string $token): string => strtolower(trim($token)), explode(',', $value)), 'strlen')); + } + + /** + * Build one scored item; status and fix key follow from the points. + * + * @param string $key Item key + * @param integer $points Points earned + * @param integer $max Points available (0 for the leak penalty) + * @param string $value Header value as sent + * @param ?string $fix Fix key override + * + * @return array + * + * @since __DEPLOY_VERSION__ + */ + private static function item(string $key, int $points, int $max, string $value, ?string $fix = null): array + { + if ($max === 0) { + $status = $points < 0 ? 'error' : 'success'; + } else { + $status = $points >= $max ? 'success' : ($points > 0 ? 'warning' : 'error'); + } + + if ($fix === null && $status !== 'success') { + $fix = 'PLG_HEALTHCHECK_SECURITYHEADERS_FIX_' . strtoupper($key); + } + + return ['key' => $key, 'points' => $points, 'max' => $max, 'status' => $status, 'value' => $value, 'fix' => $fix]; + } +} diff --git a/tests/Unit/Plugin/Healthcheck/Securityheaders/Headers/HeaderScoreTest.php b/tests/Unit/Plugin/Healthcheck/Securityheaders/Headers/HeaderScoreTest.php new file mode 100644 index 00000000000..908744c0388 --- /dev/null +++ b/tests/Unit/Plugin/Healthcheck/Securityheaders/Headers/HeaderScoreTest.php @@ -0,0 +1,344 @@ + + * @license GNU General Public License version 2 or later; see LICENSE.txt + */ + +namespace Joomla\Tests\Unit\Plugin\Healthcheck\Securityheaders\Headers; + +use Joomla\Plugin\Healthcheck\Securityheaders\Headers\HeaderScore; +use Joomla\Tests\Unit\UnitTestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\TestDox; + +/** + * Test class for the security headers score + * + * @since __DEPLOY_VERSION__ + */ +#[TestDox('The security headers score')] +class HeaderScoreTest extends UnitTestCase +{ + /** + * A complete, well-configured header set. + * + * @return array + * + * @since __DEPLOY_VERSION__ + */ + private static function complete(): array + { + return [ + 'strict-transport-security' => 'max-age=31536000; includeSubDomains', + 'content-security-policy' => "default-src 'self'", + 'x-frame-options' => 'SAMEORIGIN', + 'x-content-type-options' => 'nosniff', + 'referrer-policy' => 'strict-origin-when-cross-origin', + 'permissions-policy' => 'camera=()', + 'cross-origin-opener-policy' => 'same-origin', + 'server' => 'Caddy', + ]; + } + + /** + * Find one item by key. + * + * @param array $result evaluate() result + * @param string $key Item key + * + * @return array + * + * @since __DEPLOY_VERSION__ + */ + private static function item(array $result, string $key): array + { + foreach ($result['items'] as $item) { + if ($item['key'] === $key) { + return $item; + } + } + + throw new \LogicException('No item ' . $key); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('gives a complete header set 100 points and success')] + public function testComplete(): void + { + $result = HeaderScore::evaluate(self::complete(), true); + + $this->assertSame(100, $result['score']); + $this->assertSame('success', $result['status']); + $this->assertSame(['hsts', 'csp', 'frame', 'nosniff', 'referrer', 'permissions', 'coop', 'leak'], array_column($result['items'], 'key')); + $this->assertSame([null], array_values(array_unique(array_column($result['items'], 'fix')))); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('gives an empty header set 0 points and error')] + public function testEmpty(): void + { + $result = HeaderScore::evaluate([], true); + + $this->assertSame(0, $result['score']); + $this->assertSame('error', $result['status']); + $this->assertSame('PLG_HEALTHCHECK_SECURITYHEADERS_FIX_CSP', self::item($result, 'csp')['fix']); + $this->assertSame('success', self::item($result, 'leak')['status']); + } + + /** + * @return array + * + * @since __DEPLOY_VERSION__ + */ + public static function hstsProvider(): array + { + return [ + 'one year' => ['max-age=31536000', true, 25, 'success'], + 'exactly 180 days' => ['max-age=15552000', true, 25, 'success'], + 'one second short' => ['max-age=15551999', true, 10, 'warning'], + 'quoted' => ['max-age="31536000"', true, 25, 'success'], + 'directives first' => ['includeSubDomains; preload; max-age=63072000', true, 25, 'success'], + 'upper case' => ['MAX-AGE=31536000', true, 25, 'success'], + 'zero' => ['max-age=0', true, 0, 'error'], + 'unparsable' => ['max-age=forever', true, 0, 'error'], + 'missing' => ['', true, 0, 'error'], + 'plain http' => ['max-age=31536000', false, 0, 'error'], + ]; + } + + /** + * @param string $value HSTS header + * @param boolean $https Final URL is https + * @param integer $points Expected points + * @param string $status Expected status + * + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[DataProvider('hstsProvider')] + #[TestDox('scores Strict-Transport-Security by max-age')] + public function testHsts(string $value, bool $https, int $points, string $status): void + { + $headers = $value === '' ? [] : ['strict-transport-security' => $value]; + $item = self::item(HeaderScore::evaluate($headers, $https), 'hsts'); + + $this->assertSame([$points, 25, $status], [$item['points'], $item['max'], $item['status']]); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('points plain-http sites to HTTPS instead of the HSTS header')] + public function testHstsHttpFix(): void + { + $this->assertSame('PLG_HEALTHCHECK_SECURITYHEADERS_FIX_HSTS_HTTP', self::item(HeaderScore::evaluate([], false), 'hsts')['fix']); + $this->assertSame('PLG_HEALTHCHECK_SECURITYHEADERS_FIX_HSTS', self::item(HeaderScore::evaluate([], true), 'hsts')['fix']); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('scores an enforced CSP above a report-only one')] + public function testCsp(): void + { + $this->assertSame(25, self::item(HeaderScore::evaluate(['content-security-policy' => "default-src 'self'"], true), 'csp')['points']); + + $reportOnly = self::item(HeaderScore::evaluate(['content-security-policy-report-only' => "default-src 'self'"], true), 'csp'); + + $this->assertSame([10, 'warning', "default-src 'self'"], [$reportOnly['points'], $reportOnly['status'], $reportOnly['value']]); + } + + /** + * @return array + * + * @since __DEPLOY_VERSION__ + */ + public static function frameProvider(): array + { + return [ + 'sameorigin' => [['x-frame-options' => 'SAMEORIGIN'], 15], + 'deny lower case' => [['x-frame-options' => 'deny'], 15], + 'sent twice' => [['x-frame-options' => 'SAMEORIGIN, SAMEORIGIN'], 15], + 'conflicting duplicates' => [['x-frame-options' => 'DENY, SAMEORIGIN'], 0], + 'allow-from' => [['x-frame-options' => 'ALLOW-FROM https://example.org'], 0], + 'csp frame-ancestors' => [['content-security-policy' => "default-src 'self'; frame-ancestors 'self'"], 15], + 'report-only only' => [['content-security-policy-report-only' => "frame-ancestors 'self'"], 0], + 'missing' => [[], 0], + ]; + } + + /** + * @param array $headers Headers + * @param integer $points Expected points + * + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[DataProvider('frameProvider')] + #[TestDox('scores frame protection from X-Frame-Options or CSP frame-ancestors')] + public function testFrame(array $headers, int $points): void + { + $this->assertSame($points, self::item(HeaderScore::evaluate($headers, true), 'frame')['points']); + } + + /** + * @return array + * + * @since __DEPLOY_VERSION__ + */ + public static function nosniffProvider(): array + { + return [ + 'nosniff' => ['nosniff', 15], + 'upper case' => ['NoSniff', 15], + 'sent twice' => ['nosniff, nosniff', 15], + 'other' => ['sniff', 0], + 'missing' => ['', 0], + ]; + } + + /** + * @param string $value Header value + * @param integer $points Expected points + * + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[DataProvider('nosniffProvider')] + #[TestDox('scores X-Content-Type-Options')] + public function testNosniff(string $value, int $points): void + { + $headers = $value === '' ? [] : ['x-content-type-options' => $value]; + + $this->assertSame($points, self::item(HeaderScore::evaluate($headers, true), 'nosniff')['points']); + } + + /** + * @return array + * + * @since __DEPLOY_VERSION__ + */ + public static function referrerProvider(): array + { + return [ + 'strict-origin-when-cross-origin' => ['strict-origin-when-cross-origin', 10], + 'no-referrer' => ['no-referrer', 10], + 'same-origin upper case' => ['Same-Origin', 10], + 'unsafe-url' => ['unsafe-url', 0], + 'no-referrer-when-downgrade' => ['no-referrer-when-downgrade', 0], + 'fallback list, safe last' => ['no-referrer, strict-origin-when-cross-origin', 10], + 'fallback list, unsafe last' => ['strict-origin, unsafe-url', 0], + 'unknown last token ignored' => ['strict-origin, some-future-value', 10], + 'only unknown' => ['some-future-value', 0], + ]; + } + + /** + * @param string $value Header value + * @param integer $points Expected points + * + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[DataProvider('referrerProvider')] + #[TestDox('scores the effective Referrer-Policy')] + public function testReferrer(string $value, int $points): void + { + $this->assertSame($points, self::item(HeaderScore::evaluate(['referrer-policy' => $value], true), 'referrer')['points']); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('scores Permissions-Policy and COOP by presence')] + public function testPresence(): void + { + $result = HeaderScore::evaluate(['permissions-policy' => 'geolocation=()', 'cross-origin-opener-policy' => 'same-origin'], true); + + $this->assertSame([5, 5], [self::item($result, 'permissions')['points'], self::item($result, 'coop')['points']]); + + $blank = HeaderScore::evaluate(['permissions-policy' => ' ', 'cross-origin-opener-policy' => ''], true); + + $this->assertSame([0, 0], [self::item($blank, 'permissions')['points'], self::item($blank, 'coop')['points']]); + } + + /** + * @return array + * + * @since __DEPLOY_VERSION__ + */ + public static function leakProvider(): array + { + return [ + 'caddy' => [['server' => 'Caddy'], 0], + 'cloudflare' => [['server' => 'cloudflare'], 0], + 'php without number' => [['x-powered-by' => 'PHP'], 0], + 'apache version' => [['server' => 'Apache/2.4.62 (Debian)'], -5], + 'php version' => [['x-powered-by' => 'PHP/8.3.1'], -5], + 'both' => [['server' => 'nginx/1.27.0', 'x-powered-by' => 'PHP/8.3.1'], -5], + ]; + } + + /** + * @param array $headers Headers + * @param integer $points Expected points + * + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[DataProvider('leakProvider')] + #[TestDox('deducts 5 points when Server or X-Powered-By leaks a version')] + public function testLeak(array $headers, int $points): void + { + $item = self::item(HeaderScore::evaluate($headers, true), 'leak'); + + $this->assertSame([$points, 0, $points < 0 ? 'error' : 'success'], [$item['points'], $item['max'], $item['status']]); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('never goes below 0 and maps the score to the gauge status')] + public function testClampAndStatus(): void + { + $this->assertSame(0, HeaderScore::evaluate(['server' => 'Apache/2.4.62'], true)['score']); + + $warning = ['content-security-policy' => "default-src 'self'", 'x-frame-options' => 'DENY', 'x-content-type-options' => 'nosniff']; + + $this->assertSame([55, 'warning'], array_values(array_intersect_key(HeaderScore::evaluate($warning, true), ['score' => 0, 'status' => 0]))); + + $error = ['x-frame-options' => 'DENY', 'x-content-type-options' => 'nosniff', 'referrer-policy' => 'no-referrer', 'permissions-policy' => 'a=()']; + + $this->assertSame([45, 'error'], array_values(array_intersect_key(HeaderScore::evaluate($error, true), ['score' => 0, 'status' => 0]))); + + $success = self::complete(); + unset($success['permissions-policy'], $success['cross-origin-opener-policy'], $success['referrer-policy']); + + $this->assertSame([80, 'success'], array_values(array_intersect_key(HeaderScore::evaluate($success, true), ['score' => 0, 'status' => 0]))); + } +} From b5fe666040fe3d7a70966bd6e355990c77c9822d Mon Sep 17 00:00:00 2001 From: Brian Mitchell Date: Thu, 15 Oct 2026 16:53:44 +0200 Subject: [PATCH 21/29] Add security headers fetcher for the Health Check Co-Authored-By: Claude Opus 5.5 --- .../src/Headers/HeaderFetcher.php | 277 ++++++++++++++++++ .../Headers/HeaderFetcherTest.php | 143 +++++++++ 2 files changed, 420 insertions(+) create mode 100644 plugins/healthcheck/securityheaders/src/Headers/HeaderFetcher.php create mode 100644 tests/Unit/Plugin/Healthcheck/Securityheaders/Headers/HeaderFetcherTest.php diff --git a/plugins/healthcheck/securityheaders/src/Headers/HeaderFetcher.php b/plugins/healthcheck/securityheaders/src/Headers/HeaderFetcher.php new file mode 100644 index 00000000000..6ddff19e047 --- /dev/null +++ b/plugins/healthcheck/securityheaders/src/Headers/HeaderFetcher.php @@ -0,0 +1,277 @@ + + * @license GNU General Public License version 2 or later; see LICENSE.txt + */ + +namespace Joomla\Plugin\Healthcheck\Securityheaders\Headers; + +use Joomla\Http\Http; +use Joomla\Http\HttpFactory; +use Joomla\Http\Response; +use Joomla\Http\Transport\Curl; + +// phpcs:disable PSR1.Files.SideEffects +\defined('_JEXEC') or die; +// phpcs:enable PSR1.Files.SideEffects + +/** + * Requests the site's own homepage and returns its response headers. The only class in this plugin that uses the network. + * + * @since __DEPLOY_VERSION__ + */ +final class HeaderFetcher +{ + public const MAX_REDIRECTS = 3; + + public const SUCCESS_TTL = 86400; + + public const FAILURE_TTL = 3600; + + public const DEFAULT_TIMEOUT = 5; + + public const REASON_NO_CURL = 'PLG_HEALTHCHECK_SECURITYHEADERS_REASON_NO_CURL'; + + public const REASON_NO_HEADERS = 'PLG_HEALTHCHECK_SECURITYHEADERS_REASON_NO_HEADERS'; + + public const REASON_REDIRECTS = 'PLG_HEALTHCHECK_SECURITYHEADERS_REASON_REDIRECTS'; + + /** + * Redirect status codes the fetcher follows + * + * @since __DEPLOY_VERSION__ + */ + private const REDIRECTS = [301, 302, 303, 307, 308]; + + /** + * Constructor + * + * @param HttpFactory $httpFactory Creates the HTTP client + * + * @since __DEPLOY_VERSION__ + */ + public function __construct(private readonly HttpFactory $httpFactory) + { + } + + /** + * Request the URL (HEAD, falling back to GET), following up to three redirects, and return the final response's headers. + * + * @param string $url The site root URL + * @param integer $timeout Seconds per request + * + * @return array ['ok', 'url', 'status', 'headers', 'reason', 'checkedAt'] + * + * @since __DEPLOY_VERSION__ + */ + public function fetch(string $url, int $timeout): array + { + $checkedAt = time(); + $start = $url; + + if (!Curl::isSupported()) { + return self::failure($start, self::REASON_NO_CURL, $checkedAt); + } + + try { + $http = $this->httpFactory->getHttp( + [ + 'follow_location' => false, + 'userAgent' => 'Joomla Health Check', + // Certificate trust is the SSL Health Check's job; read the headers even from a local or self-signed certificate. + 'transport.curl' => [ + CURLOPT_SSL_VERIFYPEER => false, + CURLOPT_SSL_VERIFYHOST => false, + CURLOPT_PROXY => null, + ], + ], + 'curl' + ); + + for ($hop = 0; $hop <= self::MAX_REDIRECTS; $hop++) { + $response = $this->request($http, $url, $timeout); + $headers = self::normalise($response->getHeaders()); + $status = $response->getStatusCode(); + + if (\in_array($status, self::REDIRECTS, true) && isset($headers['location'])) { + $next = self::resolve($url, $headers['location']); + + if ($next !== null) { + $url = $next; + + continue; + } + } + + if ($headers === []) { + return self::failure($url, self::REASON_NO_HEADERS, $checkedAt); + } + + return ['ok' => true, 'url' => $url, 'status' => $status, 'headers' => $headers, 'reason' => '', 'checkedAt' => $checkedAt]; + } + + return self::failure($url, self::REASON_REDIRECTS, $checkedAt); + } catch (\Throwable $e) { + $reason = trim(preg_replace('/\s+/', ' ', $e->getMessage()) ?? ''); + + return self::failure($start, $reason !== '' ? $reason : self::REASON_NO_HEADERS, $checkedAt); + } + } + + /** + * Lower-case header names and join repeated values with ", ". + * + * @param array $raw Header name to value or list of values + * + * @return array + * + * @since __DEPLOY_VERSION__ + */ + public static function normalise(array $raw): array + { + $headers = []; + + foreach ($raw as $name => $values) { + $name = strtolower(trim((string) $name)); + + if ($name === '') { + continue; + } + + $value = implode(', ', array_map(static fn ($v): string => trim((string) $v), (array) $values)); + + $headers[$name] = isset($headers[$name]) ? $headers[$name] . ', ' . $value : $value; + } + + return $headers; + } + + /** + * Resolve a Location header against the URL that was requested. + * + * @param string $base The requested URL + * @param string $location The Location header + * + * @return string|null Absolute http(s) URL, or null if it cannot be followed + * + * @since __DEPLOY_VERSION__ + */ + public static function resolve(string $base, string $location): ?string + { + $location = trim($location); + $parts = parse_url($base); + + if ($location === '' || !\is_array($parts) || empty($parts['scheme']) || empty($parts['host'])) { + return null; + } + + if (preg_match('#^[a-z][a-z0-9+.-]*:#i', $location)) { + return preg_match('#^https?://#i', $location) ? $location : null; + } + + if (str_starts_with($location, '//')) { + return $parts['scheme'] . ':' . $location; + } + + $origin = $parts['scheme'] . '://' . $parts['host'] . (isset($parts['port']) ? ':' . $parts['port'] : ''); + + if (str_starts_with($location, '/')) { + return $origin . $location; + } + + $path = $parts['path'] ?? '/'; + $dir = substr($path, 0, (int) strrpos($path, '/') + 1); + + return $origin . ($dir === '' ? '/' : $dir) . $location; + } + + /** + * A response result for a request that did not produce headers. + * + * @param string $url The URL requested + * @param string $reason Language key or raw transport message + * @param integer $checkedAt Unix time of the attempt + * + * @return array + * + * @since __DEPLOY_VERSION__ + */ + public static function failure(string $url, string $reason, int $checkedAt): array + { + return ['ok' => false, 'url' => $url, 'status' => 0, 'headers' => [], 'reason' => $reason, 'checkedAt' => $checkedAt]; + } + + /** + * Whether a cached response is well formed and still fresh. + * + * @param mixed $cached Cache content (false on a miss) + * @param integer $now Current Unix time + * + * @return boolean + * + * @since __DEPLOY_VERSION__ + */ + public static function isUsable(mixed $cached, int $now): bool + { + if ( + !\is_array($cached) + || !isset($cached['ok'], $cached['url'], $cached['status'], $cached['headers'], $cached['reason'], $cached['checkedAt']) + || !\is_bool($cached['ok']) + || !\is_string($cached['url']) + || !\is_int($cached['status']) + || !\is_array($cached['headers']) + || !\is_string($cached['reason']) + || !\is_int($cached['checkedAt']) + ) { + return false; + } + + $age = $now - $cached['checkedAt']; + + return $age >= 0 && $age < ($cached['ok'] ? self::SUCCESS_TTL : self::FAILURE_TTL); + } + + /** + * Sanitise the timeout param. + * + * @param mixed $raw Raw param value + * + * @return integer Seconds, 1 to 10 + * + * @since __DEPLOY_VERSION__ + */ + public static function timeout(mixed $raw): int + { + return is_numeric($raw) ? min(10, max(1, (int) $raw)) : self::DEFAULT_TIMEOUT; + } + + /** + * HEAD the URL; fall back to one GET if HEAD fails, is refused, or returns no headers. + * + * @param Http $http Client + * @param string $url URL + * @param integer $timeout Seconds + * + * @return Response + * + * @since __DEPLOY_VERSION__ + */ + private function request(Http $http, string $url, int $timeout): Response + { + try { + $response = $http->head($url, [], $timeout); + + if (!\in_array($response->getStatusCode(), [405, 501], true) && $response->getHeaders() !== []) { + return $response; + } + } catch (\Throwable $e) { + // Some servers reject HEAD outright; GET below is the fallback. + } + + return $http->get($url, [], $timeout); + } +} diff --git a/tests/Unit/Plugin/Healthcheck/Securityheaders/Headers/HeaderFetcherTest.php b/tests/Unit/Plugin/Healthcheck/Securityheaders/Headers/HeaderFetcherTest.php new file mode 100644 index 00000000000..63a8baccb24 --- /dev/null +++ b/tests/Unit/Plugin/Healthcheck/Securityheaders/Headers/HeaderFetcherTest.php @@ -0,0 +1,143 @@ + + * @license GNU General Public License version 2 or later; see LICENSE.txt + */ + +namespace Joomla\Tests\Unit\Plugin\Healthcheck\Securityheaders\Headers; + +use Joomla\Http\HttpFactory; +use Joomla\Plugin\Healthcheck\Securityheaders\Headers\HeaderFetcher; +use Joomla\Tests\Unit\UnitTestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\TestDox; + +/** + * Test class for the security headers fetcher (no outbound network) + * + * @since __DEPLOY_VERSION__ + */ +#[TestDox('The security headers fetcher')] +class HeaderFetcherTest extends UnitTestCase +{ + private const NOW = 1800000000; + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('lower-cases names and joins repeated headers')] + public function testNormalise(): void + { + $this->assertSame( + ['x-frame-options' => 'SAMEORIGIN, SAMEORIGIN', 'server' => 'Caddy', 'x-empty' => ''], + HeaderFetcher::normalise(['X-Frame-Options' => ['SAMEORIGIN', ' SAMEORIGIN '], 'Server' => 'Caddy', 'X-Empty' => [''], '' => ['dropped']]) + ); + $this->assertSame(['set-cookie' => 'a=1, b=2'], HeaderFetcher::normalise(['Set-Cookie' => ['a=1'], 'set-cookie' => ['b=2']])); + } + + /** + * @return array + * + * @since __DEPLOY_VERSION__ + */ + public static function resolveProvider(): array + { + return [ + 'absolute' => ['http://example.org/', 'https://example.org/', 'https://example.org/'], + 'scheme-relative' => ['https://example.org/', '//www.example.org/', 'https://www.example.org/'], + 'root-relative' => ['https://example.org:8443/joomla/', '/joomla/en/', 'https://example.org:8443/joomla/en/'], + 'path-relative' => ['https://example.org/joomla/', 'en/', 'https://example.org/joomla/en/'], + 'path-relative no dir' => ['https://example.org', 'en/', 'https://example.org/en/'], + 'empty' => ['https://example.org/', ' ', null], + 'other scheme' => ['https://example.org/', 'ftp://example.org/', null], + ]; + } + + /** + * @param string $base Requested URL + * @param string $location Location header + * @param ?string $expected Resolved URL + * + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[DataProvider('resolveProvider')] + #[TestDox('resolves redirect locations against the requested URL')] + public function testResolve(string $base, string $location, ?string $expected): void + { + $this->assertSame($expected, HeaderFetcher::resolve($base, $location)); + } + + /** + * @return array + * + * @since __DEPLOY_VERSION__ + */ + public static function usableProvider(): array + { + $now = self::NOW; + $success = ['ok' => true, 'url' => 'https://example.org/', 'status' => 200, 'headers' => ['server' => 'x'], 'reason' => '', 'checkedAt' => $now - 3600]; + $failure = ['ok' => false, 'url' => 'https://example.org/', 'status' => 0, 'headers' => [], 'reason' => 'refused', 'checkedAt' => $now - 600]; + + return [ + 'fresh success' => [$success, true], + 'success at 24 hours' => [['checkedAt' => $now - 86400] + $success, false], + 'fresh failure' => [$failure, true], + 'failure at one hour' => [['checkedAt' => $now - 3600] + $failure, false], + 'checked in the future' => [['checkedAt' => $now + 60] + $success, false], + 'cache miss' => [false, false], + 'missing key' => [array_diff_key($success, ['headers' => true]), false], + 'headers not an array' => [['headers' => 'x'] + $success, false], + 'status as string' => [['status' => '200'] + $success, false], + ]; + } + + /** + * @param mixed $cached Cache content + * @param boolean $expected Usable + * + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[DataProvider('usableProvider')] + #[TestDox('reuses well-formed cached responses for 24 hours, failures for 1 hour')] + public function testIsUsable(mixed $cached, bool $expected): void + { + $this->assertSame($expected, HeaderFetcher::isUsable($cached, self::NOW)); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('clamps the timeout to 1 to 10 seconds')] + public function testTimeout(): void + { + $this->assertSame([5, 7, 1, 10, 5], array_map([HeaderFetcher::class, 'timeout'], [null, '7', '0', '99', 'x'])); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('reports a refused connection as a failure, not an exception')] + public function testRefused(): void + { + $result = (new HeaderFetcher(new HttpFactory()))->fetch('http://127.0.0.1:1/', 1); + + $this->assertFalse($result['ok']); + $this->assertSame([], $result['headers']); + $this->assertNotSame('', $result['reason']); + $this->assertSame('http://127.0.0.1:1/', $result['url']); + } +} From 53e052a7885ff3615c392e99d59f0e68763f8987 Mon Sep 17 00:00:00 2001 From: Brian Mitchell Date: Thu, 15 Oct 2026 16:56:31 +0200 Subject: [PATCH 22/29] Add Security Headers Health Check plugin Co-Authored-By: Claude Opus 5.5 --- .../sql/updates/mysql/6.2.0-2026-10-17.sql | 3 + .../updates/postgresql/6.2.0-2026-10-17.sql | 3 + .../en-GB/plg_healthcheck_securityheaders.ini | 34 ++ .../plg_healthcheck_securityheaders.sys.ini | 7 + installation/sql/mysql/base.sql | 1 + installation/sql/postgresql/base.sql | 1 + libraries/src/Extension/ExtensionHelper.php | 1 + .../securityheaders/services/provider.php | 50 +++ .../src/Extension/Securityheaders.php | 397 ++++++++++++++++++ 9 files changed, 497 insertions(+) create mode 100644 administrator/components/com_admin/sql/updates/mysql/6.2.0-2026-10-17.sql create mode 100644 administrator/components/com_admin/sql/updates/postgresql/6.2.0-2026-10-17.sql create mode 100644 administrator/language/en-GB/plg_healthcheck_securityheaders.ini create mode 100644 administrator/language/en-GB/plg_healthcheck_securityheaders.sys.ini create mode 100644 plugins/healthcheck/securityheaders/services/provider.php create mode 100644 plugins/healthcheck/securityheaders/src/Extension/Securityheaders.php diff --git a/administrator/components/com_admin/sql/updates/mysql/6.2.0-2026-10-17.sql b/administrator/components/com_admin/sql/updates/mysql/6.2.0-2026-10-17.sql new file mode 100644 index 00000000000..f8dfdc68aba --- /dev/null +++ b/administrator/components/com_admin/sql/updates/mysql/6.2.0-2026-10-17.sql @@ -0,0 +1,3 @@ +INSERT INTO `#__extensions` (`package_id`, `name`, `type`, `element`, `folder`, `client_id`, `enabled`, `access`, `protected`, `locked`, `manifest_cache`, `params`, `custom_data`, `ordering`, `state`) +SELECT 0, 'plg_healthcheck_securityheaders', 'plugin', 'securityheaders', 'healthcheck', 0, 0, 1, 0, 1, '', '{"context":"security"}', '', 0, 0 +WHERE NOT EXISTS (SELECT * FROM `#__extensions` g WHERE g.`element` = 'securityheaders' AND g.`folder` = 'healthcheck'); diff --git a/administrator/components/com_admin/sql/updates/postgresql/6.2.0-2026-10-17.sql b/administrator/components/com_admin/sql/updates/postgresql/6.2.0-2026-10-17.sql new file mode 100644 index 00000000000..04949874410 --- /dev/null +++ b/administrator/components/com_admin/sql/updates/postgresql/6.2.0-2026-10-17.sql @@ -0,0 +1,3 @@ +INSERT INTO "#__extensions" ("package_id", "name", "type", "element", "folder", "client_id", "enabled", "access", "protected", "locked", "manifest_cache", "params", "custom_data", "ordering", "state") +SELECT 0, 'plg_healthcheck_securityheaders', 'plugin', 'securityheaders', 'healthcheck', 0, 0, 1, 0, 1, '', '{"context":"security"}', '', 0, 0 +WHERE NOT EXISTS (SELECT * FROM "#__extensions" g WHERE g."element" = 'securityheaders' AND g."folder" = 'healthcheck'); diff --git a/administrator/language/en-GB/plg_healthcheck_securityheaders.ini b/administrator/language/en-GB/plg_healthcheck_securityheaders.ini new file mode 100644 index 00000000000..1949b70b2ff --- /dev/null +++ b/administrator/language/en-GB/plg_healthcheck_securityheaders.ini @@ -0,0 +1,34 @@ +; Joomla! Project +; (C) 2026 Open Source Matters, Inc. +; License GNU General Public License version 2 or later; see LICENSE.txt +; Note : All ini files need to be saved as UTF-8 + +PLG_HEALTHCHECK_SECURITYHEADERS="Health Check - Security Headers" +PLG_HEALTHCHECK_SECURITYHEADERS_CHECKED="Last checked: %s. Select to check again." +PLG_HEALTHCHECK_SECURITYHEADERS_CHECK_NOW="Check the security headers again" +PLG_HEALTHCHECK_SECURITYHEADERS_COLUMN_FIX="How to Fix" +PLG_HEALTHCHECK_SECURITYHEADERS_COLUMN_HEADER="Header" +PLG_HEALTHCHECK_SECURITYHEADERS_COLUMN_POINTS="Points" +PLG_HEALTHCHECK_SECURITYHEADERS_COLUMN_VALUE="Value Sent" +PLG_HEALTHCHECK_SECURITYHEADERS_FIX_COOP="Send Cross-Origin-Opener-Policy, for example same-origin. The System - HTTP Headers plugin can set it." +PLG_HEALTHCHECK_SECURITYHEADERS_FIX_CSP="Send a Content-Security-Policy. The System - HTTP Headers plugin can set one; test it in report-only mode first." +PLG_HEALTHCHECK_SECURITYHEADERS_FIX_FRAME="Send X-Frame-Options SAMEORIGIN or DENY, or a CSP frame-ancestors directive. The System - HTTP Headers plugin can set both." +PLG_HEALTHCHECK_SECURITYHEADERS_FIX_HSTS="Send Strict-Transport-Security with a max-age of at least 180 days (15552000). The System - HTTP Headers plugin can set it." +PLG_HEALTHCHECK_SECURITYHEADERS_FIX_HSTS_HTTP="The homepage is not served over HTTPS, so browsers ignore HSTS. Install a certificate and serve the site over HTTPS first." +PLG_HEALTHCHECK_SECURITYHEADERS_FIX_LEAK="Hide version numbers in the Server and X-Powered-By headers (for example ServerTokens Prod in Apache, server_tokens off in nginx, expose_php = Off in PHP)." +PLG_HEALTHCHECK_SECURITYHEADERS_FIX_NOSNIFF="Send X-Content-Type-Options: nosniff, for example in .htaccess or the server configuration." +PLG_HEALTHCHECK_SECURITYHEADERS_FIX_PERMISSIONS="Send a Permissions-Policy that turns off browser features the site does not use, for example camera=(), microphone=(), geolocation=()." +PLG_HEALTHCHECK_SECURITYHEADERS_FIX_REFERRER="Send Referrer-Policy strict-origin-when-cross-origin (or stricter). The System - HTTP Headers plugin can set it." +PLG_HEALTHCHECK_SECURITYHEADERS_GAUGE_LABEL="Security Headers" +PLG_HEALTHCHECK_SECURITYHEADERS_GAUGE_SUBLABEL="%d of 100 points" +PLG_HEALTHCHECK_SECURITYHEADERS_GROUP_DESC="Health Check modules with the same group show this plugin's results." +PLG_HEALTHCHECK_SECURITYHEADERS_GROUP_LABEL="Health Check Group" +PLG_HEALTHCHECK_SECURITYHEADERS_REASON_NO_CURL="The PHP cURL extension is not available." +PLG_HEALTHCHECK_SECURITYHEADERS_REASON_NO_HEADERS="The site answered without any headers." +PLG_HEALTHCHECK_SECURITYHEADERS_REASON_REDIRECTS="The homepage redirected more than three times." +PLG_HEALTHCHECK_SECURITYHEADERS_TABLE_CAPTION="Security headers sent by %1$s (HTTP %2$s)" +PLG_HEALTHCHECK_SECURITYHEADERS_TIMEOUT_DESC="How long to wait, in seconds, for the site's homepage." +PLG_HEALTHCHECK_SECURITYHEADERS_TIMEOUT_LABEL="Timeout (seconds)" +PLG_HEALTHCHECK_SECURITYHEADERS_TITLE_REASON="Reason: %s." +PLG_HEALTHCHECK_SECURITYHEADERS_UNCHECKED="Could not check the headers" +PLG_HEALTHCHECK_SECURITYHEADERS_XML_DESCRIPTION="Scores the HTTP security headers the site's homepage sends, from 0 to 100, and explains how to improve each one." diff --git a/administrator/language/en-GB/plg_healthcheck_securityheaders.sys.ini b/administrator/language/en-GB/plg_healthcheck_securityheaders.sys.ini new file mode 100644 index 00000000000..c1b1850a9cd --- /dev/null +++ b/administrator/language/en-GB/plg_healthcheck_securityheaders.sys.ini @@ -0,0 +1,7 @@ +; Joomla! Project +; (C) 2026 Open Source Matters, Inc. +; License GNU General Public License version 2 or later; see LICENSE.txt +; Note : All ini files need to be saved as UTF-8 + +PLG_HEALTHCHECK_SECURITYHEADERS="Health Check - Security Headers" +PLG_HEALTHCHECK_SECURITYHEADERS_XML_DESCRIPTION="Scores the HTTP security headers the site's homepage sends, from 0 to 100, and explains how to improve each one." diff --git a/installation/sql/mysql/base.sql b/installation/sql/mysql/base.sql index 469264ea804..91252f758af 100644 --- a/installation/sql/mysql/base.sql +++ b/installation/sql/mysql/base.sql @@ -317,6 +317,7 @@ INSERT INTO `#__extensions` (`package_id`, `name`, `type`, `element`, `folder`, (0, 'plg_finder_content', 'plugin', 'content', 'finder', 0, 1, 1, 0, 1, '', '', '', 3, 0), (0, 'plg_finder_newsfeeds', 'plugin', 'newsfeeds', 'finder', 0, 1, 1, 0, 1, '', '', '', 4, 0), (0, 'plg_finder_tags', 'plugin', 'tags', 'finder', 0, 1, 1, 0, 1, '', '', '', 5, 0), +(0, 'plg_healthcheck_securityheaders', 'plugin', 'securityheaders', 'healthcheck', 0, 0, 1, 0, 1, '', '{"context":"security"}', '', 4, 0), (0, 'plg_healthcheck_usermaintenance', 'plugin', 'usermaintenance', 'healthcheck', 0, 0, 1, 0, 1, '', '{"context":"general"}', '', 1, 0), (0, 'plg_installer_folderinstaller', 'plugin', 'folderinstaller', 'installer', 0, 1, 1, 0, 1, '', '', '', 2, 0), (0, 'plg_installer_override', 'plugin', 'override', 'installer', 0, 1, 1, 0, 1, '', '', '', 4, 0), diff --git a/installation/sql/postgresql/base.sql b/installation/sql/postgresql/base.sql index 232e7c6633b..b7ac366f41e 100644 --- a/installation/sql/postgresql/base.sql +++ b/installation/sql/postgresql/base.sql @@ -323,6 +323,7 @@ INSERT INTO "#__extensions" ("package_id", "name", "type", "element", "folder", (0, 'plg_finder_content', 'plugin', 'content', 'finder', 0, 1, 1, 0, 1, '', '', '', 3, 0), (0, 'plg_finder_newsfeeds', 'plugin', 'newsfeeds', 'finder', 0, 1, 1, 0, 1, '', '', '', 4, 0), (0, 'plg_finder_tags', 'plugin', 'tags', 'finder', 0, 1, 1, 0, 1, '', '', '', 5, 0), +(0, 'plg_healthcheck_securityheaders', 'plugin', 'securityheaders', 'healthcheck', 0, 0, 1, 0, 1, '', '{"context":"security"}', '', 4, 0), (0, 'plg_healthcheck_usermaintenance', 'plugin', 'usermaintenance', 'healthcheck', 0, 0, 1, 0, 1, '', '{"context":"general"}', '', 1, 0), (0, 'plg_installer_folderinstaller', 'plugin', 'folderinstaller', 'installer', 0, 1, 1, 0, 1, '', '', '', 2, 0), (0, 'plg_installer_override', 'plugin', 'override', 'installer', 0, 1, 1, 0, 1, '', '', '', 4, 0), diff --git a/libraries/src/Extension/ExtensionHelper.php b/libraries/src/Extension/ExtensionHelper.php index 7a744b00b1c..c95cbcec51e 100644 --- a/libraries/src/Extension/ExtensionHelper.php +++ b/libraries/src/Extension/ExtensionHelper.php @@ -245,6 +245,7 @@ class ExtensionHelper ['plugin', 'tags', 'finder', 0], // Core plugin extensions - healthcheck + ['plugin', 'securityheaders', 'healthcheck', 0], ['plugin', 'usermaintenance', 'healthcheck', 0], // Core plugin extensions - installer diff --git a/plugins/healthcheck/securityheaders/services/provider.php b/plugins/healthcheck/securityheaders/services/provider.php new file mode 100644 index 00000000000..5d9b0c0b5db --- /dev/null +++ b/plugins/healthcheck/securityheaders/services/provider.php @@ -0,0 +1,50 @@ + + * @license GNU General Public License version 2 or later; see LICENSE.txt + */ + +\defined('_JEXEC') or die; + +use Joomla\CMS\Cache\CacheControllerFactoryInterface; +use Joomla\CMS\Extension\PluginInterface; +use Joomla\CMS\Factory; +use Joomla\CMS\Plugin\PluginHelper; +use Joomla\DI\Container; +use Joomla\DI\ServiceProviderInterface; +use Joomla\Http\HttpFactory; +use Joomla\Plugin\Healthcheck\Securityheaders\Extension\Securityheaders; +use Joomla\Plugin\Healthcheck\Securityheaders\Headers\HeaderFetcher; + +return new class () implements ServiceProviderInterface { + /** + * Registers the service provider with a DI container. + * + * @param Container $container The DI container. + * + * @return void + * + * @since __DEPLOY_VERSION__ + */ + public function register(Container $container): void + { + $container->set( + PluginInterface::class, + $container->lazy(Securityheaders::class, function (Container $container): Securityheaders { + $plugin = new Securityheaders( + (array) PluginHelper::getPlugin('healthcheck', 'securityheaders'), + new HeaderFetcher(new HttpFactory()) + ); + + $plugin->setApplication(Factory::getApplication()); + $plugin->setCacheControllerFactory($container->get(CacheControllerFactoryInterface::class)); + + return $plugin; + }) + ); + } +}; diff --git a/plugins/healthcheck/securityheaders/src/Extension/Securityheaders.php b/plugins/healthcheck/securityheaders/src/Extension/Securityheaders.php new file mode 100644 index 00000000000..c6e5ff55c98 --- /dev/null +++ b/plugins/healthcheck/securityheaders/src/Extension/Securityheaders.php @@ -0,0 +1,397 @@ + + * @license GNU General Public License version 2 or later; see LICENSE.txt + */ + +namespace Joomla\Plugin\Healthcheck\Securityheaders\Extension; + +use Joomla\CMS\Cache\CacheControllerFactoryAwareTrait; +use Joomla\CMS\Cache\Controller\OutputController; +use Joomla\CMS\Event\Plugin\AjaxEvent; +use Joomla\CMS\HTML\HTMLHelper; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Log\Log; +use Joomla\CMS\Plugin\CMSPlugin; +use Joomla\CMS\Session\Session; +use Joomla\CMS\Uri\Uri; +use Joomla\Event\SubscriberInterface; +use Joomla\Module\Healthcheck\Administrator\Event\HealthChecksEvent; +use Joomla\Plugin\Healthcheck\Securityheaders\Headers\HeaderFetcher; +use Joomla\Plugin\Healthcheck\Securityheaders\Headers\HeaderScore; + +// phpcs:disable PSR1.Files.SideEffects +\defined('_JEXEC') or die; +// phpcs:enable PSR1.Files.SideEffects + +/** + * Health Check plugin scoring the HTTP security headers of the site's homepage + * + * @since __DEPLOY_VERSION__ + */ +final class Securityheaders extends CMSPlugin implements SubscriberInterface +{ + use CacheControllerFactoryAwareTrait; + + /** + * Cache group of the fetched responses + * + * @since __DEPLOY_VERSION__ + */ + private const CACHE_GROUP = 'plg_healthcheck_securityheaders'; + + /** + * Display names of the scored items + * + * @since __DEPLOY_VERSION__ + */ + private const NAMES = [ + 'hsts' => 'Strict-Transport-Security', + 'csp' => 'Content-Security-Policy', + 'frame' => 'X-Frame-Options / frame-ancestors', + 'nosniff' => 'X-Content-Type-Options', + 'referrer' => 'Referrer-Policy', + 'permissions' => 'Permissions-Policy', + 'coop' => 'Cross-Origin-Opener-Policy', + 'leak' => 'Server / X-Powered-By', + ]; + + /** + * The response used for this request, looked up once + * + * @var array|null + * @since __DEPLOY_VERSION__ + */ + private ?array $response = null; + + /** + * Constructor + * + * @param array $config The plugin configuration + * @param HeaderFetcher $fetcher Requests the homepage + * + * @since __DEPLOY_VERSION__ + */ + public function __construct(array $config, private readonly HeaderFetcher $fetcher) + { + parent::__construct($config); + } + + /** + * Returns an array of events this subscriber will listen to. + * + * @return array + * + * @since __DEPLOY_VERSION__ + */ + public static function getSubscribedEvents(): array + { + return [ + 'onHealthcheckGetGauges' => 'onHealthcheckGetGauges', + 'onHealthcheckGetTables' => 'onHealthcheckGetTables', + 'onHealthcheckGetIcons' => 'onHealthcheckGetIcons', + 'onAjaxSecurityheaders' => 'onAjaxSecurityheaders', + ]; + } + + /** + * Adds the score gauge when the headers could be read. + * + * @param HealthChecksEvent $event The health-check event object. + * + * @return void + * + * @since __DEPLOY_VERSION__ + */ + public function onHealthcheckGetGauges(HealthChecksEvent $event): void + { + if (!$this->isAllowed($event) || !$this->response()['ok']) { + return; + } + + $score = $this->score(); + + $this->append($event, [[ + 'id' => 'plg_healthcheck_securityheaders_gauge', + 'label' => Text::_('PLG_HEALTHCHECK_SECURITYHEADERS_GAUGE_LABEL'), + 'sublabel' => Text::sprintf('PLG_HEALTHCHECK_SECURITYHEADERS_GAUGE_SUBLABEL', $score['score']), + 'note' => Text::sprintf('PLG_HEALTHCHECK_SECURITYHEADERS_CHECKED', $this->date($this->response()['checkedAt'])), + 'score' => $score['score'], + 'unit' => '', + 'score_min' => 0, + 'score_max' => 100, + 'score_threshold_warning' => 50, + 'score_threshold_success' => 80, + 'status' => $score['status'], + 'link' => $this->refreshLink(), + 'linktitle' => Text::_('PLG_HEALTHCHECK_SECURITYHEADERS_CHECK_NOW'), + ]]); + } + + /** + * Adds the per-header table when the headers could be read. + * + * @param HealthChecksEvent $event The health-check event object. + * + * @return void + * + * @since __DEPLOY_VERSION__ + */ + public function onHealthcheckGetTables(HealthChecksEvent $event): void + { + if (!$this->isAllowed($event) || !$this->response()['ok']) { + return; + } + + $response = $this->response(); + $score = $this->score(); + $rows = []; + + foreach ($score['items'] as $item) { + $rows[] = [ + 'header' => self::NAMES[$item['key']], + 'value' => self::shorten($item['value']), + 'points' => $item['max'] === 0 ? (string) $item['points'] : $item['points'] . ' / ' . $item['max'], + 'fix' => $item['fix'] === null ? '' : Text::_($item['fix']), + 'status' => $item['status'], + ]; + } + + $statuses = array_column($rows, 'status'); + + $this->append($event, [[ + 'id' => 'plg_healthcheck_securityheaders_table', + 'caption' => Text::sprintf('PLG_HEALTHCHECK_SECURITYHEADERS_TABLE_CAPTION', $response['url'], $response['status']), + 'status' => \in_array('error', $statuses, true) ? 'error' : (\in_array('warning', $statuses, true) ? 'warning' : 'success'), + 'columns' => [ + ['key' => 'header', 'title' => Text::_('PLG_HEALTHCHECK_SECURITYHEADERS_COLUMN_HEADER')], + ['key' => 'value', 'title' => Text::_('PLG_HEALTHCHECK_SECURITYHEADERS_COLUMN_VALUE')], + [ + 'key' => 'points', + 'title' => Text::_('PLG_HEALTHCHECK_SECURITYHEADERS_COLUMN_POINTS'), + 'type' => 'badge', + 'badgeClass' => static fn ($value, $item): string => match ($item['status']) { + 'success' => 'success', + 'warning' => 'warning', + default => 'danger', + }, + ], + ['key' => 'fix', 'title' => Text::_('PLG_HEALTHCHECK_SECURITYHEADERS_COLUMN_FIX')], + ], + 'data' => $rows, + ]]); + } + + /** + * Adds a neutral icon when the headers could not be read. + * + * @param HealthChecksEvent $event The health-check event object. + * + * @return void + * + * @since __DEPLOY_VERSION__ + */ + public function onHealthcheckGetIcons(HealthChecksEvent $event): void + { + if (!$this->isAllowed($event) || $this->response()['ok']) { + return; + } + + $response = $this->response(); + $reason = str_starts_with($response['reason'], 'PLG_HEALTHCHECK_SECURITYHEADERS_REASON_') ? Text::_($response['reason']) : $response['reason']; + + $this->append($event, [[ + 'link' => $this->refreshLink(), + 'icon' => 'fas fa-shield-halved', + 'name' => 'PLG_HEALTHCHECK_SECURITYHEADERS_GAUGE_LABEL', + 'text' => Text::_('PLG_HEALTHCHECK_SECURITYHEADERS_UNCHECKED'), + 'title' => Text::sprintf('PLG_HEALTHCHECK_SECURITYHEADERS_TITLE_REASON', $reason) . ' ' + . Text::sprintf('PLG_HEALTHCHECK_SECURITYHEADERS_CHECKED', $this->date($response['checkedAt'])), + 'id' => 'plg_healthcheck_securityheaders', + ]]); + } + + /** + * Forget the stored response so the next dashboard load fetches the headers again. + * + * @param AjaxEvent $event The Ajax event + * + * @return void + * + * @throws \RuntimeException On a missing token or permission + * + * @since __DEPLOY_VERSION__ + */ + public function onAjaxSecurityheaders(AjaxEvent $event): void + { + $app = $this->getApplication(); + + if (!$app->isClient('administrator') || !Session::checkToken('get') || !$app->getIdentity()->authorise('core.admin')) { + throw new \RuntimeException(Text::_('JERROR_ALERTNOAUTHOR'), 403); + } + + try { + $this->cache()->remove(Uri::root()); + } catch (\Throwable $e) { + Log::add('Security Headers Health Check: could not clear the stored result: ' . $e->getMessage(), Log::WARNING, 'healthcheck'); + } + + $return = base64_decode($app->getInput()->getBase64('return', '')); + + $app->redirect(Uri::isInternal($return) ? $return : 'index.php?option=com_cpanel&view=cpanel&dashboard=healthcheck'); + } + + /** + * Right group and a Super User. + * + * @param HealthChecksEvent $event The health-check event object. + * + * @return boolean + * + * @since __DEPLOY_VERSION__ + */ + private function isAllowed(HealthChecksEvent $event): bool + { + if ($event->getContext() !== $this->params->get('context', 'security') || !$this->getApplication()->getIdentity()->authorise('core.admin')) { + return false; + } + + $this->loadLanguage(); + + return true; + } + + /** + * The response for this request: a fresh cached one, or a new fetch that is then stored. + * + * @return array + * + * @since __DEPLOY_VERSION__ + */ + private function response(): array + { + if ($this->response !== null) { + return $this->response; + } + + $url = Uri::root(); + $now = time(); + + try { + $cached = $this->cache()->get($url); + } catch (\Throwable $e) { + $cached = false; + } + + if (HeaderFetcher::isUsable($cached, $now)) { + return $this->response = $cached; + } + + try { + $response = $this->fetcher->fetch($url, HeaderFetcher::timeout($this->params->get('timeout'))); + } catch (\Throwable $e) { + Log::add('Security Headers Health Check: fetch failed: ' . $e->getMessage(), Log::WARNING, 'healthcheck'); + $response = HeaderFetcher::failure($url, HeaderFetcher::REASON_NO_HEADERS, $now); + } + + try { + $this->cache()->store($response, $url); + } catch (\Throwable $e) { + Log::add('Security Headers Health Check: could not store the result: ' . $e->getMessage(), Log::WARNING, 'healthcheck'); + } + + return $this->response = $response; + } + + /** + * Score of the current response. + * + * @return array HeaderScore::evaluate() result + * + * @since __DEPLOY_VERSION__ + */ + private function score(): array + { + $response = $this->response(); + + return HeaderScore::evaluate($response['headers'], str_starts_with(strtolower($response['url']), 'https://')); + } + + /** + * Append one group of layout items to the event result. + * + * @param HealthChecksEvent $event The event + * @param array $items Items for the layout + * + * @return void + * + * @since __DEPLOY_VERSION__ + */ + private function append(HealthChecksEvent $event, array $items): void + { + $result = $event->getArgument('result', []); + $result[] = $items; + + $event->setArgument('result', $result); + } + + /** + * The token-protected "check now" link back to this dashboard. + * + * @return string + * + * @since __DEPLOY_VERSION__ + */ + private function refreshLink(): string + { + return 'index.php?option=com_ajax&group=healthcheck&plugin=securityheaders&format=raw&' . Session::getFormToken() . '=1&return=' + . urlencode(base64_encode(Uri::getInstance()->toString())); + } + + /** + * Format a Unix time for display in the user's time zone. + * + * @param integer $time Unix time + * + * @return string + * + * @since __DEPLOY_VERSION__ + */ + private function date(int $time): string + { + return HTMLHelper::_('date', gmdate('Y-m-d H:i:s', $time), Text::_('DATE_FORMAT_LC2')); + } + + /** + * Shorten a header value for the table. + * + * @param string $value Header value + * + * @return string + * + * @since __DEPLOY_VERSION__ + */ + private static function shorten(string $value): string + { + return mb_strlen($value) > 80 ? mb_substr($value, 0, 79) . '…' : $value; + } + + /** + * Get the cache controller holding fetched responses. + * + * @return OutputController + * + * @since __DEPLOY_VERSION__ + */ + private function cache(): OutputController + { + return $this->getCacheControllerFactory()->createCacheController( + 'output', + ['defaultgroup' => self::CACHE_GROUP, 'caching' => true, 'lifetime' => 1440, 'language' => 'en-GB'] + ); + } +} From fde604e4bfdab368df4c1d26acb8f25c98c192c1 Mon Sep 17 00:00:00 2001 From: Brian Mitchell Date: Thu, 15 Oct 2026 17:07:54 +0200 Subject: [PATCH 23/29] Harden Security Headers fetch and scoring after review Co-Authored-By: Claude Opus 5.5 --- .../en-GB/plg_healthcheck_securityheaders.ini | 8 +- .../src/Extension/Securityheaders.php | 2 + .../src/Headers/HeaderFetcher.php | 17 +- .../src/Headers/HeaderScore.php | 32 +++- .../Headers/HeaderFetcherTest.php | 148 ++++++++++++++++++ .../Headers/HeaderScoreTest.php | 70 +++++++++ 6 files changed, 261 insertions(+), 16 deletions(-) diff --git a/administrator/language/en-GB/plg_healthcheck_securityheaders.ini b/administrator/language/en-GB/plg_healthcheck_securityheaders.ini index 1949b70b2ff..5adcfb61edc 100644 --- a/administrator/language/en-GB/plg_healthcheck_securityheaders.ini +++ b/administrator/language/en-GB/plg_healthcheck_securityheaders.ini @@ -13,10 +13,10 @@ PLG_HEALTHCHECK_SECURITYHEADERS_COLUMN_VALUE="Value Sent" PLG_HEALTHCHECK_SECURITYHEADERS_FIX_COOP="Send Cross-Origin-Opener-Policy, for example same-origin. The System - HTTP Headers plugin can set it." PLG_HEALTHCHECK_SECURITYHEADERS_FIX_CSP="Send a Content-Security-Policy. The System - HTTP Headers plugin can set one; test it in report-only mode first." PLG_HEALTHCHECK_SECURITYHEADERS_FIX_FRAME="Send X-Frame-Options SAMEORIGIN or DENY, or a CSP frame-ancestors directive. The System - HTTP Headers plugin can set both." -PLG_HEALTHCHECK_SECURITYHEADERS_FIX_HSTS="Send Strict-Transport-Security with a max-age of at least 180 days (15552000). The System - HTTP Headers plugin can set it." -PLG_HEALTHCHECK_SECURITYHEADERS_FIX_HSTS_HTTP="The homepage is not served over HTTPS, so browsers ignore HSTS. Install a certificate and serve the site over HTTPS first." +PLG_HEALTHCHECK_SECURITYHEADERS_FIX_HSTS="Send Strict-Transport-Security with a max-age of at least 180 days (15552000). Browsers remember it, so start with a short max-age and raise it once every page works over HTTPS. The System - HTTP Headers plugin can set it." +PLG_HEALTHCHECK_SECURITYHEADERS_FIX_HSTS_HTTP="The homepage is not served over HTTPS, so browsers ignore HSTS. Install a certificate, serve the site over HTTPS, then turn on Force HTTPS in Global Configuration (Server)." PLG_HEALTHCHECK_SECURITYHEADERS_FIX_LEAK="Hide version numbers in the Server and X-Powered-By headers (for example ServerTokens Prod in Apache, server_tokens off in nginx, expose_php = Off in PHP)." -PLG_HEALTHCHECK_SECURITYHEADERS_FIX_NOSNIFF="Send X-Content-Type-Options: nosniff, for example in .htaccess or the server configuration." +PLG_HEALTHCHECK_SECURITYHEADERS_FIX_NOSNIFF="Joomla's htaccess.txt (Apache) and web.config.txt (IIS) already send X-Content-Type-Options: nosniff; rename the file to .htaccess or web.config. On nginx, add: add_header X-Content-Type-Options nosniff always;" PLG_HEALTHCHECK_SECURITYHEADERS_FIX_PERMISSIONS="Send a Permissions-Policy that turns off browser features the site does not use, for example camera=(), microphone=(), geolocation=()." PLG_HEALTHCHECK_SECURITYHEADERS_FIX_REFERRER="Send Referrer-Policy strict-origin-when-cross-origin (or stricter). The System - HTTP Headers plugin can set it." PLG_HEALTHCHECK_SECURITYHEADERS_GAUGE_LABEL="Security Headers" @@ -29,6 +29,6 @@ PLG_HEALTHCHECK_SECURITYHEADERS_REASON_REDIRECTS="The homepage redirected more t PLG_HEALTHCHECK_SECURITYHEADERS_TABLE_CAPTION="Security headers sent by %1$s (HTTP %2$s)" PLG_HEALTHCHECK_SECURITYHEADERS_TIMEOUT_DESC="How long to wait, in seconds, for the site's homepage." PLG_HEALTHCHECK_SECURITYHEADERS_TIMEOUT_LABEL="Timeout (seconds)" -PLG_HEALTHCHECK_SECURITYHEADERS_TITLE_REASON="Reason: %s." +PLG_HEALTHCHECK_SECURITYHEADERS_TITLE_REASON="Reason: %s" PLG_HEALTHCHECK_SECURITYHEADERS_UNCHECKED="Could not check the headers" PLG_HEALTHCHECK_SECURITYHEADERS_XML_DESCRIPTION="Scores the HTTP security headers the site's homepage sends, from 0 to 100, and explains how to improve each one." diff --git a/plugins/healthcheck/securityheaders/src/Extension/Securityheaders.php b/plugins/healthcheck/securityheaders/src/Extension/Securityheaders.php index c6e5ff55c98..8ceddd0cbda 100644 --- a/plugins/healthcheck/securityheaders/src/Extension/Securityheaders.php +++ b/plugins/healthcheck/securityheaders/src/Extension/Securityheaders.php @@ -204,6 +204,8 @@ public function onHealthcheckGetIcons(HealthChecksEvent $event): void $response = $this->response(); $reason = str_starts_with($response['reason'], 'PLG_HEALTHCHECK_SECURITYHEADERS_REASON_') ? Text::_($response['reason']) : $response['reason']; + $reason = rtrim($reason, '. ') . '.'; + $this->append($event, [[ 'link' => $this->refreshLink(), 'icon' => 'fas fa-shield-halved', diff --git a/plugins/healthcheck/securityheaders/src/Headers/HeaderFetcher.php b/plugins/healthcheck/securityheaders/src/Headers/HeaderFetcher.php index 6ddff19e047..1c1e7a7d93f 100644 --- a/plugins/healthcheck/securityheaders/src/Headers/HeaderFetcher.php +++ b/plugins/healthcheck/securityheaders/src/Headers/HeaderFetcher.php @@ -59,7 +59,7 @@ public function __construct(private readonly HttpFactory $httpFactory) } /** - * Request the URL (HEAD, falling back to GET), following up to three redirects, and return the final response's headers. + * Request the URL (HEAD, with one GET fallback when HEAD is refused with 405 or 501 or returns no headers), following up to three redirects, and return the final response's headers. * * @param string $url The site root URL * @param integer $timeout Seconds per request @@ -250,7 +250,8 @@ public static function timeout(mixed $raw): int } /** - * HEAD the URL; fall back to one GET if HEAD fails, is refused, or returns no headers. + * HEAD the URL; fall back to one GET only if HEAD answered 405 or 501 or returned no headers. A HEAD that throws + * (timeout, refused connection) propagates, so a dead host is waited on once, not twice. * * @param Http $http Client * @param string $url URL @@ -258,18 +259,16 @@ public static function timeout(mixed $raw): int * * @return Response * + * @throws \Throwable When the HEAD request fails + * * @since __DEPLOY_VERSION__ */ private function request(Http $http, string $url, int $timeout): Response { - try { - $response = $http->head($url, [], $timeout); + $response = $http->head($url, [], $timeout); - if (!\in_array($response->getStatusCode(), [405, 501], true) && $response->getHeaders() !== []) { - return $response; - } - } catch (\Throwable $e) { - // Some servers reject HEAD outright; GET below is the fallback. + if (!\in_array($response->getStatusCode(), [405, 501], true) && $response->getHeaders() !== []) { + return $response; } return $http->get($url, [], $timeout); diff --git a/plugins/healthcheck/securityheaders/src/Headers/HeaderScore.php b/plugins/healthcheck/securityheaders/src/Headers/HeaderScore.php index 22e0eedcef8..29c8bd7505c 100644 --- a/plugins/healthcheck/securityheaders/src/Headers/HeaderScore.php +++ b/plugins/healthcheck/securityheaders/src/Headers/HeaderScore.php @@ -97,7 +97,9 @@ private static function hsts(string $value, bool $https): array return self::item('hsts', 0, 25, $value, 'PLG_HEALTHCHECK_SECURITYHEADERS_FIX_HSTS_HTTP'); } - $age = preg_match('/(?:^|;)\s*max-age\s*=\s*"?(\d+)"?\s*(?:;|$)/i', $value, $matches) ? (int) $matches[1] : 0; + // Browsers process only the first Strict-Transport-Security header (RFC 6797 section 8.1); repeats are joined with a comma. + $value = explode(',', $value, 2)[0]; + $age = preg_match('/(?:^|;)\s*max-age\s*=\s*"?(\d+)"?\s*(?:;|$)/i', $value, $matches) ? (int) $matches[1] : 0; return self::item('hsts', $age >= self::HSTS_MIN_AGE ? 25 : ($age > 0 ? 10 : 0), 25, $value); } @@ -135,13 +137,37 @@ private static function frame(string $xfo, string $csp): array { $item = self::single('frame', 15, $xfo, ['deny', 'sameorigin']); - if ($item['points'] === 0 && preg_match('/(?:^|;)\s*(frame-ancestors\b[^;]*)/i', $csp, $matches)) { - return self::item('frame', 15, 15, trim($matches[1])); + if ( + $item['points'] === 0 + && preg_match('/(?:^|[;,])\s*frame-ancestors(?=\s|;|,|$)([^;,]*)/i', $csp, $matches) + && self::restrictsFraming(trim($matches[1])) + ) { + return self::item('frame', 15, 15, 'frame-ancestors ' . trim($matches[1])); } return $item; } + /** + * Whether a frame-ancestors source list limits who can embed the page: not empty, not "*", not only bare schemes. + * + * @param string $sources The directive's source list + * + * @return boolean + * + * @since __DEPLOY_VERSION__ + */ + private static function restrictsFraming(string $sources): bool + { + foreach (preg_split('/\s+/', $sources, -1, PREG_SPLIT_NO_EMPTY) ?: [] as $source) { + if ($source !== '*' && !preg_match('/^[a-z][a-z0-9+.-]*:$/i', $source)) { + return true; + } + } + + return false; + } + /** * Referrer-Policy: the last recognised token is the one browsers apply. * diff --git a/tests/Unit/Plugin/Healthcheck/Securityheaders/Headers/HeaderFetcherTest.php b/tests/Unit/Plugin/Healthcheck/Securityheaders/Headers/HeaderFetcherTest.php index 63a8baccb24..f03091b6ab2 100644 --- a/tests/Unit/Plugin/Healthcheck/Securityheaders/Headers/HeaderFetcherTest.php +++ b/tests/Unit/Plugin/Healthcheck/Securityheaders/Headers/HeaderFetcherTest.php @@ -10,9 +10,13 @@ namespace Joomla\Tests\Unit\Plugin\Healthcheck\Securityheaders\Headers; +use Joomla\Http\Http; use Joomla\Http\HttpFactory; +use Joomla\Http\Response; +use Joomla\Http\TransportInterface; use Joomla\Plugin\Healthcheck\Securityheaders\Headers\HeaderFetcher; use Joomla\Tests\Unit\UnitTestCase; +use Joomla\Uri\UriInterface; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestDox; @@ -140,4 +144,148 @@ public function testRefused(): void $this->assertNotSame('', $result['reason']); $this->assertSame('http://127.0.0.1:1/', $result['url']); } + + /** + * Build a fetcher whose HTTP client replays canned responses and records the calls. + * + * @param array $script One entry per request: a Response, or a Throwable to throw + * @param array $calls Receives "METHOD url" for each request + * + * @return HeaderFetcher + * + * @since __DEPLOY_VERSION__ + */ + private static function scripted(array $script, array &$calls): HeaderFetcher + { + $transport = new class ($script, $calls) implements TransportInterface { + public function __construct(private array $script, private array &$calls) + { + } + + public function request($method, UriInterface $uri, $data = null, array $headers = [], $timeout = null, $userAgent = null) + { + $this->calls[] = $method . ' ' . $uri; + $next = array_shift($this->script); + + if ($next instanceof \Throwable) { + throw $next; + } + + return $next; + } + + public static function isSupported() + { + return true; + } + }; + + $factory = new class (new Http([], $transport)) extends HttpFactory { + public function __construct(private Http $http) + { + } + + public function getHttp($options = [], $adapters = null) + { + return $this->http; + } + }; + + return new HeaderFetcher($factory); + } + + /** + * @param integer $status Status code + * @param array $headers Headers + * + * @return Response + * + * @since __DEPLOY_VERSION__ + */ + private static function response(int $status, array $headers): Response + { + $response = new Response(); + $response = $response->withStatus($status); + + foreach ($headers as $name => $value) { + $response = $response->withHeader($name, $value); + } + + return $response; + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('does not retry with GET when HEAD throws (one timeout, not two)')] + public function testHeadThrowsNoGet(): void + { + $calls = []; + $fetcher = self::scripted([new \RuntimeException('Operation timed out')], $calls); + $result = $fetcher->fetch('https://example.org/', 1); + + $this->assertSame(['HEAD https://example.org/'], $calls); + $this->assertFalse($result['ok']); + $this->assertSame('Operation timed out', $result['reason']); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('falls back to one GET when HEAD answers 405 and uses the GET headers')] + public function testHead405FallsBackToGet(): void + { + $calls = []; + $fetcher = self::scripted( + [self::response(405, ['Allow' => 'GET']), self::response(200, ['X-Frame-Options' => 'DENY'])], + $calls + ); + $result = $fetcher->fetch('https://example.org/', 1); + + $this->assertSame(['HEAD https://example.org/', 'GET https://example.org/'], $calls); + $this->assertTrue($result['ok']); + $this->assertSame(['x-frame-options' => 'DENY'], $result['headers']); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('follows a relative Location and reports the final URL')] + public function testFollowsRelativeRedirect(): void + { + $calls = []; + $fetcher = self::scripted( + [self::response(301, ['Location' => '/en/']), self::response(200, ['Server' => 'Caddy'])], + $calls + ); + $result = $fetcher->fetch('https://example.org/', 1); + + $this->assertSame(['HEAD https://example.org/', 'HEAD https://example.org/en/'], $calls); + $this->assertTrue($result['ok']); + $this->assertSame('https://example.org/en/', $result['url']); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('gives up after following three redirects')] + public function testRedirectLimit(): void + { + $calls = []; + $redirect = self::response(302, ['Location' => '/next']); + $fetcher = self::scripted([$redirect, $redirect, $redirect, $redirect], $calls); + $result = $fetcher->fetch('https://example.org/', 1); + + $this->assertCount(4, $calls); + $this->assertFalse($result['ok']); + $this->assertSame(HeaderFetcher::REASON_REDIRECTS, $result['reason']); + } } diff --git a/tests/Unit/Plugin/Healthcheck/Securityheaders/Headers/HeaderScoreTest.php b/tests/Unit/Plugin/Healthcheck/Securityheaders/Headers/HeaderScoreTest.php index 908744c0388..d707828215f 100644 --- a/tests/Unit/Plugin/Healthcheck/Securityheaders/Headers/HeaderScoreTest.php +++ b/tests/Unit/Plugin/Healthcheck/Securityheaders/Headers/HeaderScoreTest.php @@ -179,6 +179,15 @@ public static function frameProvider(): array 'conflicting duplicates' => [['x-frame-options' => 'DENY, SAMEORIGIN'], 0], 'allow-from' => [['x-frame-options' => 'ALLOW-FROM https://example.org'], 0], 'csp frame-ancestors' => [['content-security-policy' => "default-src 'self'; frame-ancestors 'self'"], 15], + 'fa none' => [['content-security-policy' => "frame-ancestors 'none'"], 15], + 'fa host' => [['content-security-policy' => 'frame-ancestors https://example.org'], 15], + 'fa two headers' => [['content-security-policy' => "default-src 'self', frame-ancestors 'self'"], 15], + 'fa wildcard' => [['content-security-policy' => 'frame-ancestors *'], 0], + 'fa bare scheme' => [['content-security-policy' => 'frame-ancestors https:'], 0], + 'fa bare schemes' => [['content-security-policy' => 'frame-ancestors http: https:'], 0], + 'fa wildcard + scheme' => [['content-security-policy' => 'frame-ancestors * https:'], 0], + 'fa empty' => [['content-security-policy' => 'frame-ancestors; default-src \'self\''], 0], + 'fa lookalike' => [['content-security-policy' => "frame-ancestors-x 'self'"], 0], 'report-only only' => [['content-security-policy-report-only' => "frame-ancestors 'self'"], 0], 'missing' => [[], 0], ]; @@ -341,4 +350,65 @@ public function testClampAndStatus(): void $this->assertSame([80, 'success'], array_values(array_intersect_key(HeaderScore::evaluate($success, true), ['score' => 0, 'status' => 0]))); } + + /** + * @return array + * + * @since __DEPLOY_VERSION__ + */ + public static function hstsRepeatProvider(): array + { + return [ + 'identical twice' => ['max-age=31536000, max-age=31536000', 25], + 'first is full' => ['max-age=31536000, max-age=63072000; includeSubDomains; preload', 25], + 'first wins' => ['max-age=100, max-age=31536000', 10], + ]; + } + + /** + * @param string $value HSTS header value + * @param integer $points Expected points + * + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[DataProvider('hstsRepeatProvider')] + #[TestDox('scores only the first of repeated Strict-Transport-Security headers')] + public function testHstsRepeated(string $value, int $points): void + { + $result = HeaderScore::evaluate(['strict-transport-security' => $value], true); + + $this->assertSame($points, self::item($result, 'hsts')['points']); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('switches status exactly at the 50 and 80 boundaries')] + public function testStatusBoundaries(): void + { + $csp = ['content-security-policy' => "default-src 'self'"]; + $frame = ['x-frame-options' => 'DENY']; + $referrer = ['referrer-policy' => 'no-referrer']; + $nosniff = ['x-content-type-options' => 'nosniff']; + $hsts = ['strict-transport-security' => 'max-age=31536000']; + $leak = ['server' => 'Apache/2.4.62']; + + $cases = [ + // 25 + 15 + 5 (permissions) = 45; scores move in steps of 5, so 49 and 79 cannot occur. + [$csp + $frame + ['permissions-policy' => 'a=()'], 45, 'error'], + [$csp + $frame + $referrer, 50, 'warning'], + [$hsts + $csp + $frame + $nosniff + $leak, 75, 'warning'], + [$hsts + $csp + $frame + $nosniff, 80, 'success'], + ]; + + foreach ($cases as [$headers, $score, $status]) { + $result = HeaderScore::evaluate($headers, true); + + $this->assertSame([$score, $status], [$result['score'], $result['status']]); + } + } } From 2e5df97c6ec61747e10ac6efe1f259cb25808eee Mon Sep 17 00:00:00 2001 From: Brian Mitchell Date: Thu, 15 Oct 2026 17:17:47 +0200 Subject: [PATCH 24/29] Link failing security headers to the Joomla screen that sets them Co-Authored-By: Claude Opus 5.5 --- .../en-GB/plg_healthcheck_securityheaders.ini | 2 + .../securityheaders/services/provider.php | 2 + .../src/Extension/Securityheaders.php | 89 +++++++++++++++++-- .../securityheaders/src/Headers/FixLink.php | 67 ++++++++++++++ .../Securityheaders/Headers/FixLinkTest.php | 69 ++++++++++++++ 5 files changed, 223 insertions(+), 6 deletions(-) create mode 100644 plugins/healthcheck/securityheaders/src/Headers/FixLink.php create mode 100644 tests/Unit/Plugin/Healthcheck/Securityheaders/Headers/FixLinkTest.php diff --git a/administrator/language/en-GB/plg_healthcheck_securityheaders.ini b/administrator/language/en-GB/plg_healthcheck_securityheaders.ini index 5adcfb61edc..6912ed32bb2 100644 --- a/administrator/language/en-GB/plg_healthcheck_securityheaders.ini +++ b/administrator/language/en-GB/plg_healthcheck_securityheaders.ini @@ -23,6 +23,8 @@ PLG_HEALTHCHECK_SECURITYHEADERS_GAUGE_LABEL="Security Headers" PLG_HEALTHCHECK_SECURITYHEADERS_GAUGE_SUBLABEL="%d of 100 points" PLG_HEALTHCHECK_SECURITYHEADERS_GROUP_DESC="Health Check modules with the same group show this plugin's results." PLG_HEALTHCHECK_SECURITYHEADERS_GROUP_LABEL="Health Check Group" +PLG_HEALTHCHECK_SECURITYHEADERS_OPEN_CONFIG="Open Global Configuration" +PLG_HEALTHCHECK_SECURITYHEADERS_OPEN_HTTPHEADERS="Open HTTP Headers settings" PLG_HEALTHCHECK_SECURITYHEADERS_REASON_NO_CURL="The PHP cURL extension is not available." PLG_HEALTHCHECK_SECURITYHEADERS_REASON_NO_HEADERS="The site answered without any headers." PLG_HEALTHCHECK_SECURITYHEADERS_REASON_REDIRECTS="The homepage redirected more than three times." diff --git a/plugins/healthcheck/securityheaders/services/provider.php b/plugins/healthcheck/securityheaders/services/provider.php index 5d9b0c0b5db..d0c10c96fc2 100644 --- a/plugins/healthcheck/securityheaders/services/provider.php +++ b/plugins/healthcheck/securityheaders/services/provider.php @@ -14,6 +14,7 @@ use Joomla\CMS\Extension\PluginInterface; use Joomla\CMS\Factory; use Joomla\CMS\Plugin\PluginHelper; +use Joomla\Database\DatabaseInterface; use Joomla\DI\Container; use Joomla\DI\ServiceProviderInterface; use Joomla\Http\HttpFactory; @@ -41,6 +42,7 @@ public function register(Container $container): void ); $plugin->setApplication(Factory::getApplication()); + $plugin->setDatabase($container->get(DatabaseInterface::class)); $plugin->setCacheControllerFactory($container->get(CacheControllerFactoryInterface::class)); return $plugin; diff --git a/plugins/healthcheck/securityheaders/src/Extension/Securityheaders.php b/plugins/healthcheck/securityheaders/src/Extension/Securityheaders.php index 8ceddd0cbda..491c21d3293 100644 --- a/plugins/healthcheck/securityheaders/src/Extension/Securityheaders.php +++ b/plugins/healthcheck/securityheaders/src/Extension/Securityheaders.php @@ -19,8 +19,10 @@ use Joomla\CMS\Plugin\CMSPlugin; use Joomla\CMS\Session\Session; use Joomla\CMS\Uri\Uri; +use Joomla\Database\DatabaseAwareTrait; use Joomla\Event\SubscriberInterface; use Joomla\Module\Healthcheck\Administrator\Event\HealthChecksEvent; +use Joomla\Plugin\Healthcheck\Securityheaders\Headers\FixLink; use Joomla\Plugin\Healthcheck\Securityheaders\Headers\HeaderFetcher; use Joomla\Plugin\Healthcheck\Securityheaders\Headers\HeaderScore; @@ -36,6 +38,7 @@ final class Securityheaders extends CMSPlugin implements SubscriberInterface { use CacheControllerFactoryAwareTrait; + use DatabaseAwareTrait; /** * Cache group of the fetched responses @@ -68,6 +71,22 @@ final class Securityheaders extends CMSPlugin implements SubscriberInterface */ private ?array $response = null; + /** + * Extension id of the System - HTTP Headers plugin, looked up once + * + * @var integer|null + * @since __DEPLOY_VERSION__ + */ + private ?int $httpHeadersId = null; + + /** + * Whether the extension id was looked up + * + * @var boolean + * @since __DEPLOY_VERSION__ + */ + private bool $httpHeadersIdLoaded = false; + /** * Constructor * @@ -152,12 +171,16 @@ public function onHealthcheckGetTables(HealthChecksEvent $event): void $rows = []; foreach ($score['items'] as $item) { + $link = FixLink::for($item, $this->httpHeadersId()); + $rows[] = [ - 'header' => self::NAMES[$item['key']], - 'value' => self::shorten($item['value']), - 'points' => $item['max'] === 0 ? (string) $item['points'] : $item['points'] . ' / ' . $item['max'], - 'fix' => $item['fix'] === null ? '' : Text::_($item['fix']), - 'status' => $item['status'], + 'header' => self::NAMES[$item['key']], + 'value' => self::shorten($item['value']), + 'points' => $item['max'] === 0 ? (string) $item['points'] : $item['points'] . ' / ' . $item['max'], + 'fix' => $item['fix'] === null ? '' : Text::_($item['fix']), + 'status' => $item['status'], + 'link' => $link === null ? '' : $link['url'], + 'linkLabel' => $link === null ? '' : Text::_($link['label']), ]; } @@ -180,7 +203,21 @@ public function onHealthcheckGetTables(HealthChecksEvent $event): void default => 'danger', }, ], - ['key' => 'fix', 'title' => Text::_('PLG_HEALTHCHECK_SECURITYHEADERS_COLUMN_FIX')], + [ + 'key' => 'fix', + 'title' => Text::_('PLG_HEALTHCHECK_SECURITYHEADERS_COLUMN_FIX'), + 'type' => 'custom', + 'renderer' => static function ($value, $item): string { + $html = htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8'); + + if (($item['link'] ?? '') !== '') { + $html .= '
' + . htmlspecialchars($item['linkLabel'], ENT_QUOTES, 'UTF-8') . ''; + } + + return $html; + }, + ], ], 'data' => $rows, ]]); @@ -323,6 +360,46 @@ private function score(): array return HeaderScore::evaluate($response['headers'], str_starts_with(strtolower($response['url']), 'https://')); } + /** + * Extension id of the System - HTTP Headers plugin, enabled or not. + * + * @return integer|null Null when it cannot be found + * + * @since __DEPLOY_VERSION__ + */ + private function httpHeadersId(): ?int + { + if ($this->httpHeadersIdLoaded) { + return $this->httpHeadersId; + } + + $this->httpHeadersIdLoaded = true; + + try { + $db = $this->getDatabase(); + $type = 'plugin'; + $folder = 'system'; + $element = 'httpheaders'; + $query = $db->createQuery() + ->select($db->quoteName('extension_id')) + ->from($db->quoteName('#__extensions')) + ->where($db->quoteName('type') . ' = :type') + ->where($db->quoteName('folder') . ' = :folder') + ->where($db->quoteName('element') . ' = :element') + ->bind(':type', $type) + ->bind(':folder', $folder) + ->bind(':element', $element); + + $id = (int) $db->setQuery($query)->loadResult(); + + $this->httpHeadersId = $id > 0 ? $id : null; + } catch (\Throwable $e) { + Log::add('Security Headers Health Check: could not find the HTTP Headers plugin: ' . $e->getMessage(), Log::WARNING, 'healthcheck'); + } + + return $this->httpHeadersId; + } + /** * Append one group of layout items to the event result. * diff --git a/plugins/healthcheck/securityheaders/src/Headers/FixLink.php b/plugins/healthcheck/securityheaders/src/Headers/FixLink.php new file mode 100644 index 00000000000..5e822fb1a90 --- /dev/null +++ b/plugins/healthcheck/securityheaders/src/Headers/FixLink.php @@ -0,0 +1,67 @@ + + * @license GNU General Public License version 2 or later; see LICENSE.txt + */ + +namespace Joomla\Plugin\Healthcheck\Securityheaders\Headers; + +// phpcs:disable PSR1.Files.SideEffects +\defined('_JEXEC') or die; +// phpcs:enable PSR1.Files.SideEffects + +/** + * Finds the Joomla screen where a failing header can be fixed. Pure: no I/O. + * + * @since __DEPLOY_VERSION__ + */ +final class FixLink +{ + /** + * Tab of the System - HTTP Headers plugin holding each header + * + * @since __DEPLOY_VERSION__ + */ + private const PLUGIN_TABS = [ + 'hsts' => 'attrib-hsts', + 'csp' => 'attrib-csp', + 'frame' => 'attrib-basic', + 'referrer' => 'attrib-basic', + 'coop' => 'attrib-basic', + 'permissions' => 'attrib-basic', + ]; + + /** + * The link for a scored item. + * + * @param array $item A HeaderScore item (key, fix) + * @param ?integer $httpHeadersId Extension id of the System - HTTP Headers plugin, if found + * + * @return array|null ['url' => string, 'label' => language key], or null when there is no screen + * + * @since __DEPLOY_VERSION__ + */ + public static function for(array $item, ?int $httpHeadersId): ?array + { + if ($item['fix'] === null) { + return null; + } + + if ($item['fix'] === 'PLG_HEALTHCHECK_SECURITYHEADERS_FIX_HSTS_HTTP') { + return ['url' => 'index.php?option=com_config#page-server', 'label' => 'PLG_HEALTHCHECK_SECURITYHEADERS_OPEN_CONFIG']; + } + + if ($httpHeadersId === null || !isset(self::PLUGIN_TABS[$item['key']])) { + return null; + } + + return [ + 'url' => 'index.php?option=com_plugins&task=plugin.edit&extension_id=' . $httpHeadersId . '#' . self::PLUGIN_TABS[$item['key']], + 'label' => 'PLG_HEALTHCHECK_SECURITYHEADERS_OPEN_HTTPHEADERS', + ]; + } +} diff --git a/tests/Unit/Plugin/Healthcheck/Securityheaders/Headers/FixLinkTest.php b/tests/Unit/Plugin/Healthcheck/Securityheaders/Headers/FixLinkTest.php new file mode 100644 index 00000000000..f14e1d39d47 --- /dev/null +++ b/tests/Unit/Plugin/Healthcheck/Securityheaders/Headers/FixLinkTest.php @@ -0,0 +1,69 @@ + + * @license GNU General Public License version 2 or later; see LICENSE.txt + */ + +namespace Joomla\Tests\Unit\Plugin\Healthcheck\Securityheaders\Headers; + +use Joomla\Plugin\Healthcheck\Securityheaders\Headers\FixLink; +use Joomla\Tests\Unit\UnitTestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\TestDox; + +/** + * Test class for the security headers fix links + * + * @since __DEPLOY_VERSION__ + */ +#[TestDox('The security headers fix link')] +class FixLinkTest extends UnitTestCase +{ + private const PLUGIN = 'index.php?option=com_plugins&task=plugin.edit&extension_id=188'; + + /** + * Rows and the link they get. + * + * @return array + * + * @since __DEPLOY_VERSION__ + */ + public static function linkProvider(): array + { + $config = ['url' => 'index.php?option=com_config#page-server', 'label' => 'PLG_HEALTHCHECK_SECURITYHEADERS_OPEN_CONFIG']; + $plugin = static fn (string $tab): array => [ + 'url' => self::PLUGIN . '#' . $tab, + 'label' => 'PLG_HEALTHCHECK_SECURITYHEADERS_OPEN_HTTPHEADERS', + ]; + + return [ + 'hsts' => ['hsts', 'PLG_HEALTHCHECK_SECURITYHEADERS_FIX_HSTS', 188, $plugin('attrib-hsts')], + 'csp' => ['csp', 'PLG_HEALTHCHECK_SECURITYHEADERS_FIX_CSP', 188, $plugin('attrib-csp')], + 'frame' => ['frame', 'PLG_HEALTHCHECK_SECURITYHEADERS_FIX_FRAME', 188, $plugin('attrib-basic')], + 'referrer' => ['referrer', 'PLG_HEALTHCHECK_SECURITYHEADERS_FIX_REFERRER', 188, $plugin('attrib-basic')], + 'coop' => ['coop', 'PLG_HEALTHCHECK_SECURITYHEADERS_FIX_COOP', 188, $plugin('attrib-basic')], + 'permissions' => ['permissions', 'PLG_HEALTHCHECK_SECURITYHEADERS_FIX_PERMISSIONS', 188, $plugin('attrib-basic')], + 'hsts http' => ['hsts', 'PLG_HEALTHCHECK_SECURITYHEADERS_FIX_HSTS_HTTP', 188, $config], + 'hsts http without plugin id' => ['hsts', 'PLG_HEALTHCHECK_SECURITYHEADERS_FIX_HSTS_HTTP', null, $config], + 'nosniff' => ['nosniff', 'PLG_HEALTHCHECK_SECURITYHEADERS_FIX_NOSNIFF', 188, null], + 'leak' => ['leak', 'PLG_HEALTHCHECK_SECURITYHEADERS_FIX_LEAK', 188, null], + 'hsts full marks' => ['hsts', null, 188, null], + 'csp full marks' => ['csp', null, 188, null], + 'hsts no id' => ['hsts', 'PLG_HEALTHCHECK_SECURITYHEADERS_FIX_HSTS', null, null], + 'csp no id' => ['csp', 'PLG_HEALTHCHECK_SECURITYHEADERS_FIX_CSP', null, null], + 'frame no id' => ['frame', 'PLG_HEALTHCHECK_SECURITYHEADERS_FIX_FRAME', null, null], + 'coop no id' => ['coop', 'PLG_HEALTHCHECK_SECURITYHEADERS_FIX_COOP', null, null], + ]; + } + + #[DataProvider('linkProvider')] + #[TestDox('maps $key with fix $fix and plugin id $id')] + public function testFor(string $key, ?string $fix, ?int $id, ?array $expected): void + { + $this->assertSame($expected, FixLink::for(['key' => $key, 'fix' => $fix], $id)); + } +} From e5d99d617464e9f1f0de5e6b05885b5f1cb6b5ad Mon Sep 17 00:00:00 2001 From: Brian Mitchell Date: Fri, 16 Oct 2026 09:04:01 +0200 Subject: [PATCH 25/29] Group Health Check items into sections and summarise their status Co-Authored-By: Claude Opus 5.5 --- .../src/Helper/HealthCheckHelper.php | 123 +++++++++++++- .../Helper/HealthCheckHelperTest.php | 151 ++++++++++++++++++ 2 files changed, 270 insertions(+), 4 deletions(-) create mode 100644 tests/Unit/Module/Healthcheck/Administrator/Helper/HealthCheckHelperTest.php diff --git a/administrator/modules/mod_healthcheck/src/Helper/HealthCheckHelper.php b/administrator/modules/mod_healthcheck/src/Helper/HealthCheckHelper.php index 227f0f8e449..4961e79b9c8 100644 --- a/administrator/modules/mod_healthcheck/src/Helper/HealthCheckHelper.php +++ b/administrator/modules/mod_healthcheck/src/Helper/HealthCheckHelper.php @@ -190,6 +190,7 @@ public function getGauges(Registry $params, ?CMSApplication $application = null) 'access' => true, 'class' => null, 'group' => 'general', + 'section' => null, ]; $requiredFields = [ @@ -233,6 +234,7 @@ public function getButtons(Registry $params, ?CMSApplication $application = null 'access' => true, 'status' => null, 'group' => 'general', + 'section' => null, ]; $requiredFields = [ @@ -266,10 +268,11 @@ public function getButtons(Registry $params, ?CMSApplication $application = null public function getLists(Registry $params, ?CMSApplication $application = null) { $defaults = [ - 'items' => null, - 'access' => true, - 'class' => null, - 'group' => 'general', + 'items' => null, + 'access' => true, + 'class' => null, + 'group' => 'general', + 'section' => null, ]; $requiredFields = [ @@ -308,6 +311,7 @@ public function getTables(Registry $params, ?CMSApplication $application = null) 'access' => true, 'class' => null, 'group' => 'general', + 'section' => null, ]; $requiredFields = [ @@ -390,4 +394,115 @@ public function getFooter(Registry $params, ?CMSApplication $application = null) $application ); } + + /** + * Group items of every type into panels by their optional 'section' title. + * Panels keep the order in which their title first appears (gauges, then buttons, lists, tables); + * items without a usable section go into one panel titled $otherLabel, always last. + * + * @param array $gauges Gauge items + * @param array $buttons Icon items + * @param array $lists List items + * @param array $tables Table items + * @param string $otherLabel Title of the panel for items without a section + * + * @return array List of ['title' => string, 'gauges' => array, 'buttons' => array, 'lists' => array, 'tables' => array] + * + * @since __DEPLOY_VERSION__ + */ + public static function groupBySection(array $gauges, array $buttons, array $lists, array $tables, string $otherLabel): array + { + $empty = ['gauges' => [], 'buttons' => [], 'lists' => [], 'tables' => []]; + $sections = []; + $other = ['title' => $otherLabel] + $empty; + + foreach (['gauges' => $gauges, 'buttons' => $buttons, 'lists' => $lists, 'tables' => $tables] as $type => $items) { + foreach ($items as $item) { + $title = \is_array($item) && \is_string($item['section'] ?? null) ? trim($item['section']) : ''; + + if ($title === '') { + $other[$type][] = $item; + + continue; + } + + $sections[$title] ??= ['title' => $title] + $empty; + $sections[$title][$type][] = $item; + } + } + + $result = array_values($sections); + + if ($other['gauges'] || $other['buttons'] || $other['lists'] || $other['tables']) { + $result[] = $other; + } + + return $result; + } + + /** + * Summarise a panel: how many items are critical, warning and healthy, and the worst of them. + * Statuses are mapped exactly as the layouts map them; a gauge without a status takes it from its score. + * + * @param array $section One panel from groupBySection() + * + * @return array ['worst' => string, 'counts' => ['critical' => int, 'warning' => int, 'healthy' => int]] + * + * @since __DEPLOY_VERSION__ + */ + public static function summarise(array $section): array + { + $counts = ['critical' => 0, 'warning' => 0, 'healthy' => 0]; + + foreach (['gauges', 'buttons', 'lists', 'tables'] as $type) { + foreach ($section[$type] ?? [] as $item) { + $counts[$type === 'gauges' ? self::gaugeStatus($item) : self::itemStatus($item['status'] ?? null)]++; + } + } + + return [ + 'worst' => $counts['critical'] ? 'critical' : ($counts['warning'] ? 'warning' : 'healthy'), + 'counts' => $counts, + ]; + } + + /** + * Map an item status the way the icon, list and table layouts do. + * + * @param mixed $status The item's status + * + * @return string critical, warning or healthy + * + * @since __DEPLOY_VERSION__ + */ + private static function itemStatus(mixed $status): string + { + return match ($status) { + 'error' => 'critical', + 'warning' => 'warning', + default => 'healthy', + }; + } + + /** + * Map a gauge status the way the gauge layout does: an explicit status wins, otherwise the score decides. + * + * @param array $gauge Gauge item + * + * @return string critical, warning or healthy + * + * @since __DEPLOY_VERSION__ + */ + private static function gaugeStatus(array $gauge): string + { + if (isset($gauge['status']) && $gauge['status'] !== '') { + return self::itemStatus($gauge['status']); + } + + $score = (float) ($gauge['score'] ?? 0); + $warning = (float) ($gauge['score_threshold_warning'] ?? 50); + $success = (float) ($gauge['score_threshold_success'] ?? 90); + + return $score < $warning ? 'critical' : ($score < $success ? 'warning' : 'healthy'); + } } diff --git a/tests/Unit/Module/Healthcheck/Administrator/Helper/HealthCheckHelperTest.php b/tests/Unit/Module/Healthcheck/Administrator/Helper/HealthCheckHelperTest.php new file mode 100644 index 00000000000..0a47d1cfa5f --- /dev/null +++ b/tests/Unit/Module/Healthcheck/Administrator/Helper/HealthCheckHelperTest.php @@ -0,0 +1,151 @@ + + * @license GNU General Public License version 2 or later; see LICENSE.txt + */ + +namespace Joomla\Tests\Unit\Module\Healthcheck\Administrator\Helper; + +use Joomla\Module\Healthcheck\Administrator\Helper\HealthCheckHelper; +use Joomla\Tests\Unit\UnitTestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\TestDox; + +/** + * Test class for the Health Check section grouping and summary + * + * @since __DEPLOY_VERSION__ + */ +#[TestDox('The Health Check section grouping')] +class HealthCheckHelperTest extends UnitTestCase +{ + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('groups items of every type by section, in order of first appearance')] + public function testGroupsInOrder(): void + { + $sections = HealthCheckHelper::groupBySection( + [['id' => 'g1', 'section' => 'Security Headers']], + [['id' => 'b1', 'section' => 'SSL Certificate'], ['id' => 'b2', 'section' => 'Security Headers']], + [], + [['id' => 't1', 'section' => 'Security Headers']], + 'Other checks' + ); + + $this->assertSame(['Security Headers', 'SSL Certificate'], array_column($sections, 'title')); + $this->assertSame(['g1'], array_column($sections[0]['gauges'], 'id')); + $this->assertSame(['b2'], array_column($sections[0]['buttons'], 'id')); + $this->assertSame(['t1'], array_column($sections[0]['tables'], 'id')); + $this->assertSame(['b1'], array_column($sections[1]['buttons'], 'id')); + $this->assertSame([], $sections[1]['gauges']); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('puts items without a section into one fallback panel, always last')] + public function testFallbackLast(): void + { + $sections = HealthCheckHelper::groupBySection( + [['id' => 'g1'], ['id' => 'g2', 'section' => null]], + [['id' => 'b1', 'section' => ' '], ['id' => 'b2', 'section' => 'Site Information']], + [['id' => 'l1', 'section' => 42]], + [], + 'Other checks' + ); + + $this->assertSame(['Site Information', 'Other checks'], array_column($sections, 'title')); + $this->assertSame(['g1', 'g2'], array_column($sections[1]['gauges'], 'id')); + $this->assertSame(['b1'], array_column($sections[1]['buttons'], 'id')); + $this->assertSame(['l1'], array_column($sections[1]['lists'], 'id')); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('returns no panels when there are no items')] + public function testEmpty(): void + { + $this->assertSame([], HealthCheckHelper::groupBySection([], [], [], [], 'Other checks')); + } + + /** + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[TestDox('counts each item once by its status and reports the worst')] + public function testSummarise(): void + { + $section = [ + 'title' => 'X', + 'gauges' => [], + 'buttons' => [['status' => 'error'], ['status' => 'warning'], ['status' => 'success'], ['status' => null], ['status' => 'info']], + 'lists' => [['status' => 'warning']], + 'tables' => [['status' => 'success']], + ]; + + $this->assertSame( + ['worst' => 'critical', 'counts' => ['critical' => 1, 'warning' => 2, 'healthy' => 4]], + HealthCheckHelper::summarise($section) + ); + + $section['buttons'] = [['status' => 'success']]; + + $this->assertSame('warning', HealthCheckHelper::summarise($section)['worst']); + + $this->assertSame( + ['worst' => 'healthy', 'counts' => ['critical' => 0, 'warning' => 0, 'healthy' => 0]], + HealthCheckHelper::summarise(['title' => 'Empty', 'gauges' => [], 'buttons' => [], 'lists' => [], 'tables' => []]) + ); + } + + /** + * @return array + * + * @since __DEPLOY_VERSION__ + */ + public static function gaugeProvider(): array + { + return [ + 'explicit error' => [['status' => 'error', 'score' => 99], 'critical'], + 'explicit success wins' => [['status' => 'success', 'score' => 1], 'healthy'], + 'score below default warning' => [['score' => 49], 'critical'], + 'score at default warning' => [['score' => 50], 'warning'], + 'score below default success' => [['score' => 89], 'warning'], + 'score at default success' => [['score' => 90], 'healthy'], + 'custom thresholds' => [['score' => 75, 'score_threshold_warning' => 50, 'score_threshold_success' => 80], 'warning'], + 'null thresholds use defaults' => [['score' => 95, 'score_threshold_warning' => null, 'score_threshold_success' => null], 'healthy'], + 'empty status uses score' => [['status' => '', 'score' => 10], 'critical'], + ]; + } + + /** + * @param array $gauge Gauge item + * @param string $expected Status + * + * @return void + * + * @since __DEPLOY_VERSION__ + */ + #[DataProvider('gaugeProvider')] + #[TestDox('derives a gauge status the way the gauge layout does')] + public function testGaugeStatus(array $gauge, string $expected): void + { + $summary = HealthCheckHelper::summarise(['title' => 'G', 'gauges' => [$gauge], 'buttons' => [], 'lists' => [], 'tables' => []]); + + $this->assertSame($expected, $summary['worst']); + $this->assertSame(1, $summary['counts'][$expected]); + } +} From 07a233e576343988cec027e6a003f8c8cbcf9b38 Mon Sep 17 00:00:00 2001 From: Brian Mitchell Date: Fri, 16 Oct 2026 09:04:44 +0200 Subject: [PATCH 26/29] Treat an empty gauge status as explicit, as the gauge layout does Co-Authored-By: Claude Opus 5.5 --- .../src/Helper/HealthCheckHelper.php | 2 +- .../Helper/HealthCheckHelperTest.php | 19 ++++++++++--------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/administrator/modules/mod_healthcheck/src/Helper/HealthCheckHelper.php b/administrator/modules/mod_healthcheck/src/Helper/HealthCheckHelper.php index 4961e79b9c8..814a5ed5e11 100644 --- a/administrator/modules/mod_healthcheck/src/Helper/HealthCheckHelper.php +++ b/administrator/modules/mod_healthcheck/src/Helper/HealthCheckHelper.php @@ -495,7 +495,7 @@ private static function itemStatus(mixed $status): string */ private static function gaugeStatus(array $gauge): string { - if (isset($gauge['status']) && $gauge['status'] !== '') { + if (isset($gauge['status'])) { return self::itemStatus($gauge['status']); } diff --git a/tests/Unit/Module/Healthcheck/Administrator/Helper/HealthCheckHelperTest.php b/tests/Unit/Module/Healthcheck/Administrator/Helper/HealthCheckHelperTest.php index 0a47d1cfa5f..84f6a858208 100644 --- a/tests/Unit/Module/Healthcheck/Administrator/Helper/HealthCheckHelperTest.php +++ b/tests/Unit/Module/Healthcheck/Administrator/Helper/HealthCheckHelperTest.php @@ -119,15 +119,16 @@ public function testSummarise(): void public static function gaugeProvider(): array { return [ - 'explicit error' => [['status' => 'error', 'score' => 99], 'critical'], - 'explicit success wins' => [['status' => 'success', 'score' => 1], 'healthy'], - 'score below default warning' => [['score' => 49], 'critical'], - 'score at default warning' => [['score' => 50], 'warning'], - 'score below default success' => [['score' => 89], 'warning'], - 'score at default success' => [['score' => 90], 'healthy'], - 'custom thresholds' => [['score' => 75, 'score_threshold_warning' => 50, 'score_threshold_success' => 80], 'warning'], - 'null thresholds use defaults' => [['score' => 95, 'score_threshold_warning' => null, 'score_threshold_success' => null], 'healthy'], - 'empty status uses score' => [['status' => '', 'score' => 10], 'critical'], + 'explicit error' => [['status' => 'error', 'score' => 99], 'critical'], + 'explicit success wins' => [['status' => 'success', 'score' => 1], 'healthy'], + 'score below default warning' => [['score' => 49], 'critical'], + 'score at default warning' => [['score' => 50], 'warning'], + 'score below default success' => [['score' => 89], 'warning'], + 'score at default success' => [['score' => 90], 'healthy'], + 'custom thresholds' => [['score' => 75, 'score_threshold_warning' => 50, 'score_threshold_success' => 80], 'warning'], + 'null thresholds use defaults' => [['score' => 95, 'score_threshold_warning' => null, 'score_threshold_success' => null], 'healthy'], + 'empty status is explicit (healthy, like the layout)' => [['status' => '', 'score' => 10], 'healthy'], + 'null status uses score' => [['status' => null, 'score' => 10], 'critical'], ]; } From 9ee9656bceca833fbe130e6e6b797a3d6a935083 Mon Sep 17 00:00:00 2001 From: Brian Mitchell Date: Fri, 16 Oct 2026 09:06:49 +0200 Subject: [PATCH 27/29] Show Health Check items in collapsible per-plugin sections Co-Authored-By: Claude Opus 5.5 --- .../language/en-GB/mod_healthcheck.ini | 4 ++ .../modules/mod_healthcheck/tmpl/default.php | 67 ++++++++++--------- .../joomla/healthchecks/section_header.php | 40 +++++++++++ .../js/healthcheck-filter.es6.js | 29 ++++++++ 4 files changed, 108 insertions(+), 32 deletions(-) create mode 100644 layouts/joomla/healthchecks/section_header.php diff --git a/administrator/language/en-GB/mod_healthcheck.ini b/administrator/language/en-GB/mod_healthcheck.ini index 9e5400701ea..9fe021df9c9 100644 --- a/administrator/language/en-GB/mod_healthcheck.ini +++ b/administrator/language/en-GB/mod_healthcheck.ini @@ -53,6 +53,10 @@ MOD_HEALTHCHECK_NAV_LABEL="Health Check" MOD_HEALTHCHECK_NO_DATA="No health check data available" MOD_HEALTHCHECK_NO_MATCHING_RESULTS="All good! Nothing to report here." MOD_HEALTHCHECK_REFRESH="Refresh" +MOD_HEALTHCHECK_SECTION_COUNT_CRITICAL="%d Needs Attention" +MOD_HEALTHCHECK_SECTION_COUNT_HEALTHY="%d Healthy" +MOD_HEALTHCHECK_SECTION_COUNT_WARNING="%d Needs Review" +MOD_HEALTHCHECK_SECTION_OTHER="Other checks" MOD_HEALTHCHECK_STATUS_ERROR="Error" MOD_HEALTHCHECK_STATUS_INFO="Information" MOD_HEALTHCHECK_STATUS_OK="OK" diff --git a/administrator/modules/mod_healthcheck/tmpl/default.php b/administrator/modules/mod_healthcheck/tmpl/default.php index 0501097e83c..d2c7b89046b 100644 --- a/administrator/modules/mod_healthcheck/tmpl/default.php +++ b/administrator/modules/mod_healthcheck/tmpl/default.php @@ -13,6 +13,7 @@ use Joomla\CMS\HTML\HTMLHelper; use Joomla\CMS\Language\Text; use Joomla\CMS\Layout\LayoutHelper; +use Joomla\Module\Healthcheck\Administrator\Helper\HealthCheckHelper; /** @var Joomla\CMS\WebAsset\WebAssetManager $wa */ $wa = $app->getDocument()->getWebAssetManager(); @@ -32,14 +33,30 @@ // Label for the close button of the code modal opened by the async script. Text::script('JCLOSE'); -$gauges_html = HTMLHelper::_('healthchecks.gauges', $gauges); -$buttons_html = HTMLHelper::_('healthchecks.buttons', $buttons); -$lists_html = HTMLHelper::_('healthchecks.lists', $lists); -$tables_html = HTMLHelper::_('healthchecks.tables', $tables); $leading_html = HTMLHelper::_('healthchecks.leadings', $leading); $footer_html = HTMLHelper::_('healthchecks.footers', $footer); -$has_data = !empty($gauges_html) || !empty($buttons_html) || !empty($lists_html) || !empty($tables_html); +// One panel per plugin section; panels whose items all render empty (e.g. no access) are skipped. +$panels = []; + +foreach (HealthCheckHelper::groupBySection($gauges, $buttons, $lists, $tables, Text::_('MOD_HEALTHCHECK_SECTION_OTHER')) as $section) { + $body = ''; + $html = HTMLHelper::_('healthchecks.gauges', $section['gauges']); + $body .= $html ? '' : ''; + $html = HTMLHelper::_('healthchecks.buttons', $section['buttons']); + $body .= $html ? '' : ''; + $html = HTMLHelper::_('healthchecks.lists', $section['lists']); + $body .= $html ? '
    ' . $html . '
' : ''; + $html = HTMLHelper::_('healthchecks.tables', $section['tables']); + $body .= $html ? '
' . $html . '
' : ''; + + if ($body !== '') { + $panels[] = ['section' => $section, 'body' => $body]; + } +} + +$has_data = $panels !== []; +$accordionId = 'healthcheck-sections-' . (int) $module->id; ?> @@ -71,33 +88,19 @@