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

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

* add gaurds

* fix up guard for unit tests

* fix redeclaration of cacti_log in tests

* fix updates to unit tests

* fix test patjhs

* fix: update test __DIR__ paths for reorganized test structure

* fix: conditionally define read_user_setting to prevent redeclaration in tests

* fix: conditionally define functions to prevent redeclaration in tests

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

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

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

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

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

* fix: remove function conflicts from test stubs

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

* fix: prevent constant and variable redeclaration in bootstrap

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

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

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

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

* fix: remove more conflicting function stubs from test helpers

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

* fix: minimize test stubs to only translation functions

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

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

This eliminates all constant and function redeclaration errors.

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

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

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

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

115 lines
6.3 KiB
PHP

<?php
/*
+-------------------------------------------------------------------------+
| Copyright (C) 2004-2026 The Cacti Group |
| |
| This program is free software; you can redistribute it and/or |
| modify it under the terms of the GNU General Public License |
| as published by the Free Software Foundation; either version 2 |
| of the License, or (at your option) any later version. |
+-------------------------------------------------------------------------+
| Cacti: The Complete RRDtool-based Graphing Solution |
+-------------------------------------------------------------------------+
*/
$root = dirname(__DIR__, 4);
test('remember-me restored sessions still require 2fa when enabled', function () use ($root) {
$auth = file_get_contents($root . '/include/auth.php');
$auth_lib = file_get_contents($root . '/lib/auth.php');
expect($auth)->toContain('if (empty($_SESSION[SESS_USER_2FA]) && db_column_exists(\'user_auth\', \'tfa_enabled\'))')
->and($auth)->not->toContain('if (!$cookie_user && empty($_SESSION[SESS_USER_2FA])')
->and($auth_lib)->toContain('auth_cookie_user_currently_allowed($user_info)')
->and($auth_lib)->toContain('function auth_cookie_user_currently_allowed(array $user_info) : bool')
->and($auth_lib)->toContain("if ((\$user_info['enabled'] ?? '') != 'on')")
->and($auth_lib)->toContain('return auth_user_has_access($user_info);');
});
test('2fa lifetime uses configured token lifetime in minutes', function () use ($root) {
$tfa = file_get_contents($root . '/auth_2fa.php');
expect($tfa)->toContain("read_config_option('secpass_2fatime')")
->and($tfa)->toContain('$tfaTime = time() - ($tfaMins * 60);')
->and($tfa)->toContain("explode(':', \$_COOKIE[session_name() . '_otp'], 2)")
->and($tfa)->not->toContain('secpass_mfatime')
->and($tfa)->not->toContain('$tfaBase =');
});
test('password reset token validation rejects expired and invalid hashes before use', function () use ($root) {
$reset = file_get_contents($root . '/auth_resetpassword.php');
expect($reset)->toContain('AND expiry > NOW()')
->and($reset)->toContain('$action = \'formidentity\';' . "\n\n\t\t\tbreak;")
->and($reset)->toContain('Password reset is not available for this account.')
->and($reset)->toContain('AND realm = 0');
});
test('reset-link consumption does not gate the account lookup on password_change', function () use ($root) {
$reset = file_get_contents($root . '/auth_resetpassword.php');
// admin-issued links (user_admin.php) target accounts without password_change set;
// the consumption query must accept any account that legitimately received a link.
$consume = substr($reset, strpos($reset, "case 'resetpassword'"));
$consume = substr($consume, 0, strpos($consume, '// Get passwords entered for change'));
expect($consume)->toContain('FROM user_auth')
->and($consume)->toContain('AND enabled = "on"')
->and($consume)->not->toContain('AND password_change = "on"');
});
test('logout clears the remember-me and otp cookies by their actual names', function () use ($root) {
$functions = file_get_contents($root . '/lib/functions.php');
expect($functions)->toContain("'cacti_remembers'")
->and($functions)->toContain("(string) session_name() . '_otp'")
->and($functions)->not->toContain('cacti_rembers');
});
test('basic auth shortcut checks disabled accounts and effective access before creating a session', function () use ($root) {
$auth = file_get_contents($root . '/include/auth.php');
expect($auth)->toContain("if (\$current_user['enabled'] != 'on')")
->and($auth)->toContain('if (!auth_user_has_access($current_user))')
->and(strpos($auth, "if (\$current_user['enabled'] != 'on')"))->toBeLessThan(strpos($auth, '$_SESSION[SESS_USER_ID] = $current_user[\'id\'];'))
->and(strpos($auth, 'if (!auth_user_has_access($current_user))'))->toBeLessThan(strpos($auth, '$_SESSION[SESS_USER_ID] = $current_user[\'id\'];'));
});
test('2fa profile mutations require post requests and csrf-bearing ajax calls', function () use ($root) {
$profile = file_get_contents($root . '/auth_profile.php');
$auth = file_get_contents($root . '/lib/auth.php');
expect($profile)->toContain('function auth_profile_require_post()')
->and($profile)->toContain('REQUEST_METHOD')
->and($profile)->toContain('$.post(\'auth_profile.php?action=enable_2fa\', {__csrf_magic: csrfMagicToken}')
->and($profile)->toContain('$.post(\'auth_profile.php?action=disable_2fa\', {__csrf_magic: csrfMagicToken}')
->and($profile)->toContain('$.post(\'auth_profile.php?action=verify_2fa\', {code: code, __csrf_magic: csrfMagicToken}')
->and($profile)->not->toContain('$.getJSON(\'auth_profile.php?action=enable_2fa')
->and($profile)->not->toContain('$.getJSON(\'auth_profile.php?action=disable_2fa')
->and($profile)->not->toContain('$.getJSON(\'auth_profile.php?action=verify_2fa')
->and($auth)->not->toContain('$result[\'secret\']');
});
test('remote agent authorization fails closed on fcrdns mismatch', function () use ($root) {
$remote_agent = file_get_contents($root . '/remote_agent.php');
// a PTR that exists but does not forward-confirm must still reject after the
// inline loop was extracted into remote_agent_fcrdns_confirmed().
expect($remote_agent)->toContain('but forward lookup does not match. Rejecting.')
->and($remote_agent)->toContain('remote_agent_fcrdns_confirmed($client_addr, $forward_records)')
->and($remote_agent)->not->toContain('Hostname checks will be ignored for this request.')
->and($remote_agent)->not->toContain('$client_name = $client_addr;');
});
test('basic authentication only trusts a forwarded user header behind a configured trusted-proxy check', function () use ($root) {
$auth = file_get_contents($root . '/lib/auth.php');
// HTTP_X_FORWARDED_USER is client-supplied and must never be honored on its
// own; it's only read when $trusted is true, and $trusted comes from
// is_trusted_proxy(), which matches REMOTE_ADDR against the server-side
// $config['trusted_proxies'] list -- never from request input.
expect($auth)->toContain("elseif (\$trusted && isset(\$_SERVER['HTTP_X_FORWARDED_USER']))")
->and($auth)->toContain('$trusted = is_trusted_proxy();')
->and($auth)->toContain("\$trusted = \$config['trusted_proxies'] ?? [];");
});