From 88a231b24352bb5bfe7a16a5fe91cb141f46367f Mon Sep 17 00:00:00 2001 From: Tim van Dijen Date: Sat, 28 Aug 2021 21:10:33 +0200 Subject: [PATCH] First run at migrating all the static calls to the Logger --- lib/SimpleSAML/Auth/State.php | 16 +++--- lib/SimpleSAML/Error/Exception.php | 15 ++++-- lib/SimpleSAML/Locale/Language.php | 12 ++++- lib/SimpleSAML/Locale/Localization.php | 24 ++++++--- lib/SimpleSAML/Locale/Translate.php | 18 +++++-- lib/SimpleSAML/Logger.php | 23 +++++---- .../Metadata/MetaDataStorageHandler.php | 6 ++- lib/SimpleSAML/Metadata/SAMLParser.php | 6 ++- lib/SimpleSAML/Session.php | 47 +++++++++-------- lib/SimpleSAML/Utils/HTTP.php | 25 ++++++++-- modules/admin/lib/Controller/Federation.php | 8 ++- .../core/lib/Auth/Process/AttributeLimit.php | 11 +++- .../lib/Auth/Process/AttributeValueMap.php | 15 ++++-- .../lib/Auth/Process/ScopeFromAttribute.php | 12 ++++- modules/core/lib/Auth/UserPassBase.php | 26 ++++++++-- modules/cron/lib/Cron.php | 14 +++++- .../saml/lib/Auth/Process/FilterScopes.php | 14 +++++- modules/saml/lib/Auth/Source/SP.php | 27 +++++++--- modules/saml/lib/IdP/SAML2.php | 50 +++++++++++-------- modules/saml/lib/IdP/SQLNameID.php | 4 +- tests/lib/SimpleSAML/LoggerTest.php | 43 ++++++++++------ .../core/lib/Auth/UserPassBaseTest.php | 3 ++ 22 files changed, 296 insertions(+), 123 deletions(-) diff --git a/lib/SimpleSAML/Auth/State.php b/lib/SimpleSAML/Auth/State.php index 596ce65b9e..a852f0e0c8 100644 --- a/lib/SimpleSAML/Auth/State.php +++ b/lib/SimpleSAML/Auth/State.php @@ -213,7 +213,8 @@ public static function saveState(array &$state, string $stage, bool $rawId = fal $session = Session::getSessionFromRequest(); $session->setData('\SimpleSAML\Auth\State', $id, $serializedState, self::getStateTimeout()); - Logger::debug('Saved state: ' . var_export($return, true)); + $logger = new Logger(); + $logger->debug('Saved state: ' . var_export($return, true)); return $return; } @@ -232,13 +233,14 @@ public static function cloneState(array $state): array { $clonedState = $state; + $logger = new Logger(); if (array_key_exists(self::ID, $state)) { $clonedState[self::CLONE_ORIGINAL_ID] = $state[self::ID]; unset($clonedState[self::ID]); - Logger::debug('Cloned state: ' . var_export($state[self::ID], true)); + $this->logger->debug('Cloned state: ' . var_export($state[self::ID], true)); } else { - Logger::debug('Cloned state with undefined id.'); + $this->logger->debug('Cloned state with undefined id.'); } return $clonedState; @@ -263,7 +265,8 @@ public static function cloneState(array $state): array */ public static function loadState(string $id, string $stage, bool $allowMissing = false): ?array { - Logger::debug('Loading state: ' . var_export($id, true)); + $logger = new Logger(); + $logger->debug('Loading state: ' . var_export($id, true)); $sid = self::parseStateID($id); @@ -299,7 +302,7 @@ public static function loadState(string $id, string $stage, bool $allowMissing = $msg = 'Wrong stage in state. Was \'' . $state[self::STAGE] . '\', should be \'' . $stage . '\'.'; - Logger::warning($msg); + $logger->warning($msg); if ($sid['url'] === null) { throw new \Exception($msg); @@ -326,7 +329,8 @@ public static function deleteState(array &$state): void return; } - Logger::debug('Deleting state: ' . var_export($state[self::ID], true)); + $logger = new Logger(); + $logger->debug('Deleting state: ' . var_export($state[self::ID], true)); $session = Session::getSessionFromRequest(); $session->deleteData('\SimpleSAML\Auth\State', $state[self::ID]); diff --git a/lib/SimpleSAML/Error/Exception.php b/lib/SimpleSAML/Error/Exception.php index a080418e90..7303b0336e 100644 --- a/lib/SimpleSAML/Error/Exception.php +++ b/lib/SimpleSAML/Error/Exception.php @@ -37,6 +37,13 @@ class Exception extends \Exception */ private ?Exception $cause = null; + /** + * The Logger to use. + * + * @var \SimpleSAML\Logger + */ + private Logger $logger; + /** * Constructor for this error. @@ -245,7 +252,7 @@ public function log(string $default_level): void */ public function logError(): void { - Logger::error($this->getClass() . ': ' . $this->getMessage()); + $this->logger->error($this->getClass() . ': ' . $this->getMessage()); $this->logBacktrace(LogLevel::ERROR); } @@ -257,7 +264,7 @@ public function logError(): void */ public function logWarning(): void { - Logger::warning($this->getClass() . ': ' . $this->getMessage()); + $this->logger->warning($this->getClass() . ': ' . $this->getMessage()); $this->logBacktrace(LogLevel::WARNING); } @@ -269,7 +276,7 @@ public function logWarning(): void */ public function logInfo(): void { - Logger::info($this->getClass() . ': ' . $this->getMessage()); + $this->logger->info($this->getClass() . ': ' . $this->getMessage()); $this->logBacktrace(LogLevel::INFO); } @@ -281,7 +288,7 @@ public function logInfo(): void */ public function logDebug(): void { - Logger::debug($this->getClass() . ': ' . $this->getMessage()); + $this->logger->debug($this->getClass() . ': ' . $this->getMessage()); $this->logBacktrace(LogLevel::DEBUG); } diff --git a/lib/SimpleSAML/Locale/Language.php b/lib/SimpleSAML/Locale/Language.php index 6d3cd9d5dc..af33418350 100644 --- a/lib/SimpleSAML/Locale/Language.php +++ b/lib/SimpleSAML/Locale/Language.php @@ -136,6 +136,13 @@ class Language 'nn' => 'nn_NO', ]; + /** + * The Logger to use + * + * @var \SimpleSAML\Logger + */ + private Logger $logger; + /** * Constructor @@ -145,6 +152,7 @@ class Language public function __construct(Configuration $configuration) { $this->configuration = $configuration; + $this->logger = new Logger(); $this->availableLanguages = $this->getInstalledLanguages(); $this->defaultLanguage = $this->configuration->getString('language.default', 'en'); $this->languageParameterName = $this->configuration->getString('language.parameter.name', 'language'); @@ -172,7 +180,7 @@ private function getInstalledLanguages(): array if (array_key_exists($code, self::$language_names) && isset(self::$language_names[$code])) { $availableLanguages[] = $code; } else { - Logger::error("Language \"$code\" not installed. Check config."); + $this->logger->error("Language \"$code\" not installed. Check config."); } } return $availableLanguages; @@ -266,7 +274,7 @@ public function getLanguageLocalizedName(string $code): ?string if (array_key_exists($code, self::$language_names) && isset(self::$language_names[$code])) { return self::$language_names[$code]; } - Logger::error("Name for language \"$code\" not found. Check config."); + $this->logger->error("Name for language \"$code\" not found. Check config."); return null; } diff --git a/lib/SimpleSAML/Locale/Localization.php b/lib/SimpleSAML/Locale/Localization.php index 21c6060627..83ea2df2c7 100644 --- a/lib/SimpleSAML/Locale/Localization.php +++ b/lib/SimpleSAML/Locale/Localization.php @@ -88,6 +88,13 @@ class Localization */ public string $i18nBackend; + /** + * The Logger to use + * + * @var\SimpleSAML\Logger + */ + private Logger $logger; + /** * Constructor @@ -97,6 +104,7 @@ class Localization public function __construct(Configuration $configuration) { $this->configuration = $configuration; + $this->logger = new Logger(); /** @var string $locales */ $locales = $this->configuration->resolvePath('locales'); $this->localeDir = $locales; @@ -160,7 +168,7 @@ public function addModuleDomain(string $module, string $localeDir = null): void public function addDomain(string $localeDir, string $domain): void { $this->localeDomainMap[$domain] = $localeDir; - Logger::debug("Localization: load domain '$domain' at '$localeDir'"); + $this->logger->debug("Localization: load domain '$domain' at '$localeDir'"); $this->loadGettextGettextFromPO($domain); } @@ -179,7 +187,7 @@ public function getLangPath(string $domain = self::DEFAULT_DOMAIN): string $langcode = $langcode[0]; $localeDir = $this->localeDomainMap[$domain]; $langPath = $localeDir . '/' . $langcode . '/LC_MESSAGES/'; - Logger::debug("Trying langpath for '$langcode' as '$langPath'"); + $this->logger->debug("Trying langpath for '$langcode' as '$langPath'"); if (is_dir($langPath) && is_readable($langPath)) { return $langPath; } @@ -188,7 +196,7 @@ public function getLangPath(string $domain = self::DEFAULT_DOMAIN): string $alias = $this->language->getLanguageCodeAlias($langcode); if (isset($alias)) { $langPath = $localeDir . '/' . $alias . '/LC_MESSAGES/'; - Logger::debug("Trying langpath for alternative '$alias' as '$langPath'"); + $this->logger->debug("Trying langpath for alternative '$alias' as '$langPath'"); if (is_dir($langPath) && is_readable($langPath)) { return $langPath; } @@ -201,13 +209,13 @@ public function getLangPath(string $domain = self::DEFAULT_DOMAIN): string // Report that the localization for the preferred language is missing $error = "Localization not found for langcode '$langcode' at '$langPath', falling back to langcode '" . $defLangcode . "'"; - Logger::error($_SERVER['PHP_SELF'] . ' - ' . $error); + $this->logger->error($_SERVER['PHP_SELF'] . ' - ' . $error); return $langPath; } // Locale for default language missing even, error out $error = "Localization directory missing/broken for langcode '$langcode' and domain '$domain'"; - Logger::critical($_SERVER['PHP_SELF'] . ' - ' . $error); + $this->logger->critical($_SERVER['PHP_SELF'] . ' - ' . $error); throw new \Exception($error); } @@ -241,7 +249,7 @@ private function loadGettextGettextFromPO( $langPath = $this->getLangPath($domain); } catch (\Exception $e) { $error = "Something went wrong when trying to get path to language file, cannot load domain '$domain'."; - Logger::debug($_SERVER['PHP_SELF'] . ' - ' . $error); + $this->logger->debug($_SERVER['PHP_SELF'] . ' - ' . $error); if ($catchException) { // bail out! return; @@ -256,7 +264,7 @@ private function loadGettextGettextFromPO( $this->translator->loadTranslations($translations); } else { $error = "Localization file '$poFile' not found in '$langPath', falling back to default"; - Logger::debug($_SERVER['PHP_SELF'] . ' - ' . $error); + $this->logger->debug($_SERVER['PHP_SELF'] . ' - ' . $error); } } @@ -283,7 +291,7 @@ public function isI18NBackendDefault(): bool private function setupL10N(): void { if ($this->i18nBackend === self::SSP_I18N_BACKEND) { - Logger::debug("Localization: using old system"); + $this->logger->debug("Localization: using old system"); return; } diff --git a/lib/SimpleSAML/Locale/Translate.php b/lib/SimpleSAML/Locale/Translate.php index 4c26b670da..69123af660 100644 --- a/lib/SimpleSAML/Locale/Translate.php +++ b/lib/SimpleSAML/Locale/Translate.php @@ -53,6 +53,13 @@ class Translate */ private Language $language; + /** + * The Logger to use + * + * @var \SimpleSAML\Logger + */ + private Logger $logger; + /** * Constructor @@ -65,6 +72,7 @@ public function __construct(Configuration $configuration, ?string $defaultDictio $this->configuration = $configuration; $this->language = new Language($configuration); $this->defaultDictionary = $defaultDictionary; + $this->logger = new Logger(); } @@ -209,7 +217,7 @@ public function includeInlineTranslation(string $tag, $translation): void ); } - Logger::debug('Translate: Adding inline language translation for tag [' . $tag . ']'); + $this->logger->debug('Translate: Adding inline language translation for tag [' . $tag . ']'); $this->langtext[$tag] = $translation; } @@ -233,7 +241,7 @@ public function includeLanguageFile(string $file, Configuration $otherConfig = n $filebase = $filebase ?: 'dictionaries/'; $lang = $this->readDictionaryFile($filebase . $file); - Logger::debug('Translate: Merging language array. Loading [' . $file . ']'); + $this->logger->debug('Translate: Merging language array. Loading [' . $file . ']'); $this->langtext = array_merge($this->langtext, $lang); } @@ -254,7 +262,7 @@ private function readDictionaryJSON(string $filename): array $lang = json_decode($fileContent, true); if (empty($lang)) { - Logger::error('Invalid dictionary definition file [' . $definitionFile . ']'); + $this->logger->error('Invalid dictionary definition file [' . $definitionFile . ']'); return []; } @@ -303,7 +311,7 @@ private function readDictionaryPHP(string $filename): array */ private function readDictionaryFile(string $filename): array { - Logger::debug('Translate: Reading dictionary [' . $filename . ']'); + $this->logger->debug('Translate: Reading dictionary [' . $filename . ']'); $jsonFile = $filename . '.definition.json'; if (file_exists($jsonFile)) { @@ -315,7 +323,7 @@ private function readDictionaryFile(string $filename): array return $this->readDictionaryPHP($filename); } - Logger::error( + $this->logger->error( $_SERVER['PHP_SELF'] . ' - Translate: Could not find dictionary file at [' . $filename . ']' ); return []; diff --git a/lib/SimpleSAML/Logger.php b/lib/SimpleSAML/Logger.php index 51e3b0f2d9..5f5fd39fd5 100644 --- a/lib/SimpleSAML/Logger.php +++ b/lib/SimpleSAML/Logger.php @@ -135,12 +135,12 @@ class Logger extends AbstractLogger /** * Statistics. * - * @param string|\Stringable $message + * @param string $message * @param array $context * * @return void */ - public function stats(string|\Stringable $message, array $context = []): void + public function stats($message, array $context = []): void { $context['statsLog'] = true; $this->log(LogLevel::EMERGENCY, $message, $context); @@ -196,7 +196,7 @@ public static function setTrackId(string $trackId): void public static function flush(): void { foreach (self::$earlyLog as $msg) { - $this->:log($msg['level'], $msg['string'], $msg['statsLog']); + $this->log($msg['level'], $msg['string'], $msg['statsLog']); } self::$earlyLog = []; } @@ -384,12 +384,13 @@ private static function createLoggingHandler(?string $handler = null): void /** * System is unusable. * - * @param string|\Stringable $message + * @param string $level + * @param string $message * @param array $context * * @return void */ - public function log(string|\Stringable $message, array $context = []): void + public function log($level, $message, array $context = []): void { $statsLog = false; if (array_key_exists('statsLog', $context)) { @@ -398,7 +399,7 @@ public function log(string|\Stringable $message, array $context = []): void if (self::$initializing) { // some error occurred while initializing logging - self::defer($level, $string, $statsLog); + self::defer($level, $message, $statsLog); return; } elseif (php_sapi_name() === 'cli' || defined('STDIN')) { $_SERVER['REMOTE_ADDR'] = "CLI"; @@ -420,12 +421,12 @@ public function log(string|\Stringable $message, array $context = []): void $usec = substr($msecs, 2, 3); $ts = gmdate('H:i:s', $time) . '.' . $usec . 'Z'; - self::$capturedLog[] = $ts . ' ' . $string; + self::$capturedLog[] = $ts . ' ' . $message; } if (self::$logLevel >= $level || $statsLog) { $formats = ['%trackid', '%msg', '%srcip', '%stat']; - $replacements = [self::$trackid, $string, $_SERVER['REMOTE_ADDR']]; + $replacements = [self::$trackid, $message, $_SERVER['REMOTE_ADDR']]; $stat = ''; if ($statsLog) { @@ -435,7 +436,7 @@ public function log(string|\Stringable $message, array $context = []): void if (self::$trackid === self::NO_TRACKID && !self::$shuttingDown) { // we have a log without track ID and we are not still shutting down, so defer logging - self::defer($level, $string, $statsLog); + self::defer($level, $message, $statsLog); return; } elseif (self::$trackid === self::NO_TRACKID) { // shutting down without a track ID, prettify it @@ -444,8 +445,8 @@ public function log(string|\Stringable $message, array $context = []): void } // we either have a track ID or we are shutting down, so just log the message - $string = str_replace($formats, $replacements, self::$format); - self::$loggingHandler->log($level, $string); + $message = str_replace($formats, $replacements, self::$format); + self::$loggingHandler->log($level, $message); } } } diff --git a/lib/SimpleSAML/Metadata/MetaDataStorageHandler.php b/lib/SimpleSAML/Metadata/MetaDataStorageHandler.php index 4291327288..7267395f58 100644 --- a/lib/SimpleSAML/Metadata/MetaDataStorageHandler.php +++ b/lib/SimpleSAML/Metadata/MetaDataStorageHandler.php @@ -148,6 +148,7 @@ public function getList(string $set = 'saml20-idp-remote', bool $showExpired = f { $result = []; $timeUtils = new Utils\Time(); + $logger = new Logger(); foreach ($this->sources as $source) { $srcList = $source->getMetadataSet($set); @@ -156,7 +157,7 @@ public function getList(string $set = 'saml20-idp-remote', bool $showExpired = f foreach ($srcList as $key => $le) { if (array_key_exists('expire', $le) && ($le['expire'] < time())) { unset($srcList[$key]); - Logger::warning( + $this->logger->warning( "Dropping metadata entity " . var_export($key, true) . ", expired " . $timeUtils->generateTimestamp($le['expire']) . "." ); @@ -270,6 +271,7 @@ public function getPreferredEntityIdFromCIDRhint(string $set, string $ip): ?stri public function getMetaDataForEntities(array $entityIds, string $set): array { $result = []; + $logger = new Logger(); $timeUtils = new Utils\Time(); foreach ($this->sources as $source) { $srcList = $source->getMetaDataForEntities($entityIds, $set); @@ -277,7 +279,7 @@ public function getMetaDataForEntities(array $entityIds, string $set): array if (array_key_exists('expire', $le)) { if ($le['expire'] < time()) { unset($srcList[$key]); - Logger::warning( + $logger->warning( "Dropping metadata entity " . var_export($key, true) . ", expired " . $timeUtils->generateTimestamp($le['expire']) . "." ); diff --git a/lib/SimpleSAML/Metadata/SAMLParser.php b/lib/SimpleSAML/Metadata/SAMLParser.php index 92d7a5e6eb..9943c873f1 100644 --- a/lib/SimpleSAML/Metadata/SAMLParser.php +++ b/lib/SimpleSAML/Metadata/SAMLParser.php @@ -904,6 +904,7 @@ private static function processExtensions($element, array $parentExtensions = [] $ret['RegistrationInfo'] = $parentExtensions['RegistrationInfo']; } + $logger = new Logger(); foreach ($element->getExtensions() as $e) { if ($e instanceof Scope) { $ret['scope'][] = $e->getScope(); @@ -921,7 +922,7 @@ private static function processExtensions($element, array $parentExtensions = [] isset($ret['RegistrationInfo']['registrationAuthority']) && $ret['RegistrationInfo']['registrationAuthority'] !== $e->getRegistrationAuthority() ) { - Logger::warning( + $logger->warning( 'Invalid attempt to override registrationAuthority \'' . $ret['RegistrationInfo']['registrationAuthority'] . "' with '{$e->getRegistrationAuthority()}'" @@ -1327,7 +1328,8 @@ public function validateSignature(array $certificates): bool } } } - Logger::debug('Could not validate signature'); + $logger = new Logger(); + $logger->debug('Could not validate signature'); return false; } } diff --git a/lib/SimpleSAML/Session.php b/lib/SimpleSAML/Session.php index 4d8360f4a5..f937450dea 100644 --- a/lib/SimpleSAML/Session.php +++ b/lib/SimpleSAML/Session.php @@ -154,10 +154,11 @@ class Session implements Serializable, Utils\ClearableState private function __construct(bool $transient = false) { $this->setConfiguration(Configuration::getInstance()); + $logger = new Logger(); if (php_sapi_name() === 'cli' || defined('STDIN')) { $this->trackid = 'CL' . bin2hex(openssl_random_pseudo_bytes(4)); - Logger::setTrackId($this->trackid); + $logger::setTrackId($this->trackid); $this->transient = $transient; return; } @@ -165,7 +166,7 @@ private function __construct(bool $transient = false) if ($transient) { // transient session $this->trackid = 'TR' . bin2hex(openssl_random_pseudo_bytes(4)); - Logger::setTrackId($this->trackid); + $logger::setTrackId($this->trackid); $this->transient = true; } else { // regular session @@ -175,7 +176,7 @@ private function __construct(bool $transient = false) $this->trackid = bin2hex(openssl_random_pseudo_bytes(5)); - Logger::setTrackId($this->trackid); + $logger::setTrackId($this->trackid); $this->markDirty(); @@ -257,6 +258,8 @@ public function unserialize($serialized) */ public static function getSessionFromRequest(): Session { + $logger = new Logger(); + // check if we already have initialized the session /** @psalm-suppress RedundantCondition */ if (self::$instance !== null) { @@ -274,7 +277,7 @@ public static function getSessionFromRequest(): Session * it. */ self::useTransientSession(); - Logger::error('Error loading session: ' . $e->getMessage()); + $logger->error('Error loading session: ' . $e->getMessage()); if ($e instanceof Error\Exception) { $cause = $e->getCause(); if ($cause instanceof \Exception) { @@ -316,7 +319,7 @@ public static function getSessionFromRequest(): Session $c->toArray() ); } - Logger::error('Error creating session: ' . $e->getMessage()); + $logger->error('Error creating session: ' . $e->getMessage()); } // we must have a session now, either regular or transient @@ -358,6 +361,7 @@ public static function getSession(string $sessionId = null): ?Session if ($checkToken) { $globalConfig = Configuration::getInstance(); + $logger = new Logger(); if ($session->authToken !== null) { $authTokenCookieName = $globalConfig->getString( @@ -365,12 +369,12 @@ public static function getSession(string $sessionId = null): ?Session 'SimpleSAMLAuthToken' ); if (!isset($_COOKIE[$authTokenCookieName])) { - Logger::warning('Missing AuthToken cookie.'); + $logger->warning('Missing AuthToken cookie.'); return null; } $cryptoUtils = new Utils\Crypto(); if (!$cryptoUtils->secureCompare($session->authToken, $_COOKIE[$authTokenCookieName])) { - Logger::warning('Invalid AuthToken cookie.'); + $logger->warning('Invalid AuthToken cookie.'); return null; } } @@ -380,7 +384,7 @@ public static function getSession(string $sessionId = null): ?Session if (is_callable($checkFunction)) { $check = call_user_func($checkFunction, $session); if ($check !== true) { - Logger::warning('Session did not pass check function.'); + $logger->warning('Session did not pass check function.'); return null; } } @@ -404,7 +408,8 @@ public static function getSession(string $sessionId = null): ?Session */ private static function load(Session $session): Session { - Logger::setTrackId($session->getTrackID()); + $logger = new Logger(); + $logger::setTrackId($session->getTrackID()); self::$instance = $session; return self::$instance; } @@ -463,14 +468,14 @@ public function save(): void $this->callback_registered = false; $sh = SessionHandler::getSessionHandler(); - + $logger = new Logger(); try { $sh->saveSession($this); } catch (\Exception $e) { if (!($e instanceof Error\Exception)) { $e = new Error\UnserializableException($e); } - Logger::error('Unable to save session.'); + $logger->error('Unable to save session.'); $e->logError(); } } @@ -601,7 +606,8 @@ public function setRememberMeExpire(int $lifetime = null): void */ public function doLogin(string $authority, array $data = []): void { - Logger::debug('Session: doLogin("' . $authority . '")'); + $logger = new Logger(); + $logger->debug('Session: doLogin("' . $authority . '")'); $this->markDirty(); @@ -677,7 +683,7 @@ public function doLogin(string $authority, array $data = []): void */ unset($this->authToken); unset($this->authData[$authority]); - Logger::error('Cannot set authentication token cookie: ' . $e->getMessage()); + $logger->error('Cannot set authentication token cookie: ' . $e->getMessage()); throw $e; } } @@ -693,10 +699,11 @@ public function doLogin(string $authority, array $data = []): void */ public function doLogout(string $authority): void { - Logger::debug('Session: doLogout(' . var_export($authority, true) . ')'); + $logger = new Logger(); + $logger->debug('Session: doLogout(' . var_export($authority, true) . ')'); if (!isset($this->authData[$authority])) { - Logger::debug('Session: Already logged out of ' . $authority . '.'); + $logger->debug('Session: Already logged out of ' . $authority . '.'); return; } @@ -757,20 +764,20 @@ private function callLogoutHandlers(string $authority): void */ public function isValid(string $authority): bool { + $logger = new Logger(); if (!isset($this->authData[$authority])) { - Logger::debug( - 'Session: ' . var_export($authority, true) . - ' not valid because we are not authenticated.' + $logger->debug( + 'Session: ' . var_export($authority, true) . ' not valid because we are not authenticated.' ); return false; } if ($this->authData[$authority]['Expire'] <= time()) { - Logger::debug('Session: ' . var_export($authority, true) . ' not valid because it is expired.'); + $logger->debug('Session: ' . var_export($authority, true) . ' not valid because it is expired.'); return false; } - Logger::debug('Session: Valid session found with ' . var_export($authority, true) . '.'); + $logger->debug('Session: Valid session found with ' . var_export($authority, true) . '.'); return true; } diff --git a/lib/SimpleSAML/Utils/HTTP.php b/lib/SimpleSAML/Utils/HTTP.php index dbddd18b4c..4f3f896f1d 100644 --- a/lib/SimpleSAML/Utils/HTTP.php +++ b/lib/SimpleSAML/Utils/HTTP.php @@ -18,6 +18,23 @@ */ class HTTP { + /** + * The Logger to use. + * + * @var \SimpleSAML\Logger + */ + private Logger $logger; + + + /** + * Constructor. + */ + public function __construct() + { + $this->logger = new Logger(); + } + + /** * Determine if the user agent can support cookies being sent with SameSite equal to "None". * Browsers without support may drop the cookie and or treat it as stricter setting @@ -239,7 +256,7 @@ private function redirect(string $url, array $parameters = []): void } if (strlen($url) > 2048) { - Logger::warning('Redirecting to a URL longer than 2048 bytes.'); + $this->logger->warning('Redirecting to a URL longer than 2048 bytes.'); } if (!headers_sent()) { @@ -501,7 +518,7 @@ public function fetch(string $url, array $context = [], bool $getHeaders = false 'SNI_enabled' => true, ]; } else { - Logger::warning('Invalid URL format or local URL used through a proxy'); + $this->logger->warning('Invalid URL format or local URL used through a proxy'); } } } @@ -1134,7 +1151,7 @@ public function setCookie(string $name, ?string $value, array $params = null, bo Error\CannotSetCookie::SECURE_COOKIE ); } - Logger::warning('Error setting cookie: setting secure cookie on plain HTTP is not allowed.'); + $this->logger->warning('Error setting cookie: setting secure cookie on plain HTTP is not allowed.'); return; } @@ -1186,7 +1203,7 @@ public function setCookie(string $name, ?string $value, array $params = null, bo Error\CannotSetCookie::HEADERS_SENT ); } - Logger::warning('Error setting cookie: headers already sent.'); + $this->logger->warning('Error setting cookie: headers already sent.'); } } diff --git a/modules/admin/lib/Controller/Federation.php b/modules/admin/lib/Controller/Federation.php index 949b6aeb90..c2544fe455 100644 --- a/modules/admin/lib/Controller/Federation.php +++ b/modules/admin/lib/Controller/Federation.php @@ -36,6 +36,9 @@ class Federation /** @var \SimpleSAML\Configuration */ protected Configuration $config; + /** @var \SimpleSAML\Logger */ + protected Logger $logger; + /** * @var \SimpleSAML\Auth\Source|string * @psalm-var \SimpleSAML\Auth\Source|class-string @@ -63,6 +66,7 @@ class Federation public function __construct(Configuration $config) { $this->config = $config; + $this->logger = new Logger(); $this->menu = new Menu(); $this->mdHandler = MetaDataStorageHandler::getMetadataHandler(); $this->authUtils = new Utils\Auth(); @@ -252,7 +256,7 @@ private function getHostedIdP(): array $entities[$index] = $entity; } } catch (\Exception $e) { - Logger::error('Federation: Error loading saml20-idp: ' . $e->getMessage()); + $this->logger->error('Federation: Error loading saml20-idp: ' . $e->getMessage()); } } @@ -295,7 +299,7 @@ private function getHostedIdP(): array $entities[$index] = $entity; } } catch (\Exception $e) { - Logger::error('Federation: Error loading adfs-idp: ' . $e->getMessage()); + $this->logger->error('Federation: Error loading adfs-idp: ' . $e->getMessage()); } } diff --git a/modules/core/lib/Auth/Process/AttributeLimit.php b/modules/core/lib/Auth/Process/AttributeLimit.php index 490940f308..ef314c9d87 100644 --- a/modules/core/lib/Auth/Process/AttributeLimit.php +++ b/modules/core/lib/Auth/Process/AttributeLimit.php @@ -29,6 +29,13 @@ class AttributeLimit extends Auth\ProcessingFilter */ private bool $isDefault = false; + /** + * The Logger to use + * + * @var \SimpleSAML\Logger + */ + private Logger $logger; + /** * Initialize this filter. @@ -41,6 +48,8 @@ public function __construct(array &$config, $reserved) { parent::__construct($config, $reserved); + $this->logger = new Logger(); + foreach ($config as $index => $value) { if ($index === 'default') { $this->isDefault = (bool) $value; @@ -151,7 +160,7 @@ private function filterAttributeValues(array $values, array $allowedConfigValues */ $regexResult = @preg_match($pattern, $attributeValue); if ($regexResult === false) { - Logger::warning("Error processing regex '$pattern' on value '$attributeValue'"); + $this->logger->warning("Error processing regex '$pattern' on value '$attributeValue'"); break; } elseif ($regexResult === 1) { $matchedValues[] = $attributeValue; diff --git a/modules/core/lib/Auth/Process/AttributeValueMap.php b/modules/core/lib/Auth/Process/AttributeValueMap.php index 26636d35bb..aff53c0e57 100644 --- a/modules/core/lib/Auth/Process/AttributeValueMap.php +++ b/modules/core/lib/Auth/Process/AttributeValueMap.php @@ -46,6 +46,13 @@ class AttributeValueMap extends Auth\ProcessingFilter */ private bool $replace = false; + /** + * The Logger to use + * + * @var \SimpleSAML\Logger + */ + private Logger $logger; + /** * Initialize the filter. @@ -58,6 +65,8 @@ public function __construct(array &$config, $reserved) { parent::__construct($config, $reserved); + $this->logger = new Logger(); + // parse configuration foreach ($config as $name => $value) { if (is_int($name)) { @@ -68,7 +77,7 @@ public function __construct(array &$config, $reserved) $this->keep = true; } else { // unknown configuration option, log it and ignore the error - Logger::warning( + $this->logger->warning( "AttributeValueMap: unknown configuration flag '" . var_export($value, true) . "'" ); } @@ -111,7 +120,7 @@ public function __construct(array &$config, $reserved) */ public function process(array &$request): void { - Logger::debug('Processing the AttributeValueMap filter.'); + $this->logger->debug('Processing the AttributeValueMap filter.'); Assert::keyExists($request, 'Attributes'); $attributes = &$request['Attributes']; @@ -130,7 +139,7 @@ public function process(array &$request): void $values = [$values]; } if (count(array_intersect($values, $sourceattribute)) > 0) { - Logger::debug("AttributeValueMap: intersect match for '$value'"); + $this->logger->debug("AttributeValueMap: intersect match for '$value'"); $targetvalues[] = $value; } } diff --git a/modules/core/lib/Auth/Process/ScopeFromAttribute.php b/modules/core/lib/Auth/Process/ScopeFromAttribute.php index 7734cacb42..8c43944305 100644 --- a/modules/core/lib/Auth/Process/ScopeFromAttribute.php +++ b/modules/core/lib/Auth/Process/ScopeFromAttribute.php @@ -41,6 +41,13 @@ class ScopeFromAttribute extends Auth\ProcessingFilter */ private string $targetAttribute; + /** + * The Logger to use + * + * @var \SimpleSAML\Logger + */ + private Logger $logger; + /** * Initialize this filter, parse configuration @@ -55,6 +62,7 @@ public function __construct(array &$config, $reserved) $cfg = Configuration::loadFromArray($config, 'ScopeFromAttribute'); $this->targetAttribute = $cfg->getString('targetAttribute'); $this->sourceAttribute = $cfg->getString('sourceAttribute'); + $this->logger = new Logger(); } @@ -88,11 +96,11 @@ public function process(array &$request): void $attributes[$this->targetAttribute] = []; $scope = substr($sourceAttrVal, $scopeIndex + 1); $attributes[$this->targetAttribute][] = $scope; - Logger::debug( + $this->logger->debug( 'ScopeFromAttribute: Inserted new attribute ' . $this->targetAttribute . ', with scope ' . $scope ); } else { - Logger::warning('ScopeFromAttribute: The configured source attribute ' . $this->sourceAttribute + $this->logger->warning('ScopeFromAttribute: The configured source attribute ' . $this->sourceAttribute . ' does not have a scope. Did not add attribute ' . $this->targetAttribute . '.'); } } diff --git a/modules/core/lib/Auth/UserPassBase.php b/modules/core/lib/Auth/UserPassBase.php index 11f18f1d44..8e5f76fdcd 100644 --- a/modules/core/lib/Auth/UserPassBase.php +++ b/modules/core/lib/Auth/UserPassBase.php @@ -89,6 +89,13 @@ abstract class UserPassBase extends Auth\Source */ protected bool $rememberMeChecked = false; + /** + * The Logger to use + * + * @var \SimpleSAML\Logger + */ + private Logger $logger; + /** * Constructor for this authentication source. @@ -122,6 +129,19 @@ public function __construct(array $info, array &$config) $sspcnf = Configuration::getInstance(); $this->rememberMeEnabled = $sspcnf->getBoolean('session.rememberme.enable', false); $this->rememberMeChecked = $sspcnf->getBoolean('session.rememberme.checked', false); + + $this->logger = new Logger(); + } + + + /** + * Set Logger. + * + * @param \SimpleSAML\Logger $logger The Logger + */ + public function setLogger(Logger $logger): void + { + $this->logger = $logger; } @@ -219,7 +239,7 @@ public function authenticate(array &$state): void // other use cases. if (isset($state['saml:Binding']) && $state['saml:Binding'] === Constants::BINDING_PAOS) { if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) { - Logger::error("ECP AuthnRequest did not contain Basic Authentication header"); + $this->logger->error("ECP AuthnRequest did not contain Basic Authentication header"); // TODO Return a SOAP fault instead of using the current binding? throw new Error\Error("WRONGUSERPASS"); } @@ -305,11 +325,11 @@ public static function handleLogin(string $authStateId, string $username, string try { $attributes = $source->login($username, $password); } catch (\Exception $e) { - Logger::stats('Unsuccessful login attempt from ' . $_SERVER['REMOTE_ADDR'] . '.'); + $this->logger->stats('Unsuccessful login attempt from ' . $_SERVER['REMOTE_ADDR'] . '.'); throw $e; } - Logger::stats('User \'' . $username . '\' successfully authenticated from ' . $_SERVER['REMOTE_ADDR']); + $this->logger->stats('User \'' . $username . '\' successfully authenticated from ' . $_SERVER['REMOTE_ADDR']); // Save the attributes we received from the login-function in the $state-array $state['Attributes'] = $attributes; diff --git a/modules/cron/lib/Cron.php b/modules/cron/lib/Cron.php index b6f7b43f9a..f020130c2b 100644 --- a/modules/cron/lib/Cron.php +++ b/modules/cron/lib/Cron.php @@ -21,8 +21,15 @@ class Cron */ private Configuration $cronconfig; + /** + * The Logger to use + * + * @var \SimpleSAML\Logger + */ + private Logger $logger; + - /* + /** * @param \SimpleSAML\Configuration $cronconfig The cron configuration to use. If not specified defaults * to `config/module_cron.php` */ @@ -32,8 +39,10 @@ public function __construct(Configuration $cronconfig = null) $cronconfig = Configuration::getConfig('module_cron.php'); } $this->cronconfig = $cronconfig; + $this->logger = new Logger(); } + /** * Invoke the cron hook for the given tag * @param string $tag The tag to use. Must be valid in the cronConfig @@ -56,13 +65,14 @@ public function runTag(string $tag): array Assert::isArray($croninfo); foreach ($summary as $s) { - Logger::debug('Cron - Summary: ' . $s); + $this->logger->debug('Cron - Summary: ' . $s); } /** @psalm-suppress NullableReturnStatement */ return $croninfo; } + /** * @param string $tag * @return bool diff --git a/modules/saml/lib/Auth/Process/FilterScopes.php b/modules/saml/lib/Auth/Process/FilterScopes.php index b0fb75237d..ce57db0223 100644 --- a/modules/saml/lib/Auth/Process/FilterScopes.php +++ b/modules/saml/lib/Auth/Process/FilterScopes.php @@ -25,6 +25,14 @@ class FilterScopes extends ProcessingFilter 'eduPersonPrincipalName' ]; + /** + * The Logger to use + * + * @var \SimpleSAML\Logger + */ + private Logger $logger; + + /** * Constructor for the processing filter. * @@ -38,6 +46,8 @@ public function __construct(array &$config, $reserved) if (array_key_exists('attributes', $config) && !empty($config['attributes'])) { $this->scopedAttributes = $config['attributes']; } + + $this->logger = new Logger(); } /** @@ -77,12 +87,12 @@ public function process(array &$request): void } elseif (strpos($host, $scope) === strlen($host) - strlen($scope)) { $newValues[] = $value; } else { - Logger::warning("Removing value '$value' for attribute '$attribute'. Undeclared scope."); + $this->logger->warning("Removing value '$value' for attribute '$attribute'. Undeclared scope."); } } if (empty($newValues)) { - Logger::warning("No suitable values for attribute '$attribute', removing it."); + $this->logger->warning("No suitable values for attribute '$attribute', removing it."); unset($request['Attributes'][$attribute]); // remove empty attributes } else { $request['Attributes'][$attribute] = $newValues; diff --git a/modules/saml/lib/Auth/Source/SP.php b/modules/saml/lib/Auth/Source/SP.php index 1a6f8db573..a7a9aa3210 100644 --- a/modules/saml/lib/Auth/Source/SP.php +++ b/modules/saml/lib/Auth/Source/SP.php @@ -64,6 +64,13 @@ class SP extends \SimpleSAML\Auth\Source */ private array $protocols = [Constants::NS_SAMLP]; + /** + * The Logger to use + * + * @var \SimpleSAML\Logger + */ + private Logger $logger; + /** * Constructor for SAML SP authentication source. @@ -96,6 +103,8 @@ public function __construct(array $info, array $config) if (empty($this->discoURL) && Module::isModuleEnabled('discojuice')) { $this->discoURL = Module::getModuleURL('discojuice/central.php'); } + + $this->logger = new Logger(); } @@ -366,7 +375,7 @@ private function getACSEndpoints(): array ]; break; default: - Logger::warning('Unknown acs.Binding value specified, ignoring: ' . $service); + $this->logger->warning('Unknown acs.Binding value specified, ignoring: ' . $service); continue 2; } $acs['index'] = $index; @@ -550,7 +559,7 @@ private function startSSO2(Configuration $idpMetadata, array $state): void $requesterID[] = $state['core:SP']; } } else { - Logger::debug('Disabling samlp:Scoping for ' . var_export($idpMetadata->getString('entityid'), true)); + $this->logger->debug('Disabling samlp:Scoping for ' . var_export($idpMetadata->getString('entityid'), true)); } $ar->setIDPList( @@ -585,7 +594,7 @@ private function startSSO2(Configuration $idpMetadata, array $state): void $id = Auth\State::saveState($state, 'saml:sp:sso', true); $ar->setId($id); - Logger::debug( + $this->logger->debug( 'Sending SAML 2 AuthnRequest to ' . var_export($idpMetadata->getString('entityid'), true) ); @@ -811,7 +820,7 @@ public function reauthenticate(array &$state): void * starting the authentication process again with a different IdP, or * cancel the current SSO attempt. */ - Logger::warning( + $this->Logger->warning( "Reauthentication after logout is needed. The IdP '${state['saml:sp:IdP']}' is not in the IDPList " . "provided by the Service Provider '${state['core:SP']}'." ); @@ -876,7 +885,8 @@ public static function askForIdPChange(array &$state): void */ public static function reauthLogout(array $state): void { - Logger::debug('Proxy: logging the user out before re-authentication.'); + $logger = new Logger(); + $logger->debug('Proxy: logging the user out before re-authentication.'); if (isset($state['Responder'])) { $state['saml:proxy:reauthLogout:PrevResponder'] = $state['Responder']; @@ -921,7 +931,8 @@ public static function reauthPostLogout(IdP $idp, array $state): void { Assert::keyExists($state, 'saml:sp:AuthId'); - Logger::debug('Proxy: logout completed.'); + $logger = new Logger(); + $logger->debug('Proxy: logout completed.'); if (isset($state['saml:proxy:reauthLogout:PrevResponder'])) { $state['Responder'] = $state['saml:proxy:reauthLogout:PrevResponder']; @@ -930,7 +941,7 @@ public static function reauthPostLogout(IdP $idp, array $state): void /** @var \SimpleSAML\Module\saml\Auth\Source\SP $sp */ $sp = Auth\Source::getById($state['saml:sp:AuthId'], Module\saml\Auth\Source\SP::class); - Logger::debug('Proxy: logging in again.'); + $this->logger->debug('Proxy: logging in again.'); $sp->authenticate($state); Assert::true(false); } @@ -965,7 +976,7 @@ public function startSLO2(array &$state): void false ); if ($endpoint === false) { - Logger::info('No logout endpoint for IdP ' . var_export($idp, true) . '.'); + $this->logger->info('No logout endpoint for IdP ' . var_export($idp, true) . '.'); return; } diff --git a/modules/saml/lib/IdP/SAML2.php b/modules/saml/lib/IdP/SAML2.php index 84ec8e2ed3..57aa401e3c 100644 --- a/modules/saml/lib/IdP/SAML2.php +++ b/modules/saml/lib/IdP/SAML2.php @@ -64,7 +64,8 @@ public static function sendResponse(array $state): void '$metadata[' . var_export($spEntityId, true) . ']' ); - Logger::info('Sending SAML 2.0 Response to ' . var_export($spEntityId, true)); + $logger = new Logger(); + $logger->info('Sending SAML 2.0 Response to ' . var_export($spEntityId, true)); $requestId = $state['saml:RequestId']; $relayState = $state['saml:RelayState']; @@ -152,8 +153,9 @@ public static function handleAuthError(Error\Exception $exception, array $state) /** @var \SimpleSAML\Module\saml\Error $error */ $error = \SimpleSAML\Module\saml\Error::fromException($exception); - Logger::warning("Returning error to SP with entity ID '" . var_export($spEntityId, true) . "'."); - $exception->log(Logger::WARNING); + $logger = new Logger(); + $logger->warning("Returning error to SP with entity ID '" . var_export($spEntityId, true) . "'."); + $exception->log(LogLevel::WARNING); $ar = self::buildResponse($idpMetadata, $spMetadata, $consumerURL); $ar->setInResponseTo($requestId); @@ -251,15 +253,16 @@ private static function getAssertionConsumerService( return $firstFalse; } - Logger::warning('Authentication request specifies invalid AssertionConsumerService:'); + $logger = new Logger(); + $logger->warning('Authentication request specifies invalid AssertionConsumerService:'); if ($AssertionConsumerServiceURL !== null) { - Logger::warning('AssertionConsumerServiceURL: ' . var_export($AssertionConsumerServiceURL, true)); + $logger->warning('AssertionConsumerServiceURL: ' . var_export($AssertionConsumerServiceURL, true)); } if ($ProtocolBinding !== null) { - Logger::warning('ProtocolBinding: ' . var_export($ProtocolBinding, true)); + $logger->warning('ProtocolBinding: ' . var_export($ProtocolBinding, true)); } if ($AssertionConsumerServiceIndex !== null) { - Logger::warning( + $logger->warning( 'AssertionConsumerServiceIndex: ' . var_export($AssertionConsumerServiceIndex, true) ); } @@ -292,6 +295,7 @@ public static function receiveAuthnRequest(IdP $idp): void $supportedBindings[] = Constants::BINDING_PAOS; } + $logger = new Logger(); if (isset($_REQUEST['spentityid']) || isset($_REQUEST['providerId'])) { /* IdP initiated authentication. */ @@ -350,7 +354,7 @@ public static function receiveAuthnRequest(IdP $idp): void $idpInit = true; - Logger::info( + $logger->info( 'SAML2.0 - IdP.SSOService: IdP initiated authentication: ' . var_export($spEntityId, true) ); } else { @@ -410,7 +414,7 @@ public static function receiveAuthnRequest(IdP $idp): void $idpInit = false; - Logger::info( + $logger->info( 'SAML2.0 - IdP.SSOService: incoming authentication request: ' . var_export($spEntityId, true) ); } @@ -499,7 +503,8 @@ public static function receiveAuthnRequest(IdP $idp): void */ public static function sendLogoutRequest(IdP $idp, array $association, string $relayState = null): void { - Logger::info('Sending SAML 2.0 LogoutRequest to: ' . var_export($association['saml:entityID'], true)); + $logger = new Logger(); + $logger->info('Sending SAML 2.0 LogoutRequest to: ' . var_export($association['saml:entityID'], true)); $metadata = MetaDataStorageHandler::getMetadataHandler(); $idpMetadata = $idp->getConfig(); @@ -548,16 +553,17 @@ public static function sendLogoutResponse(IdP $idp, array $state): void $lr->setInResponseTo($state['saml:RequestId']); $lr->setRelayState($state['saml:RelayState']); + $logger = new Logger(); if (isset($state['core:Failed']) && $state['core:Failed']) { $partial = true; $lr->setStatus([ 'Code' => Constants::STATUS_SUCCESS, 'SubCode' => Constants::STATUS_PARTIAL_LOGOUT, ]); - Logger::info('Sending logout response for partial logout to SP ' . var_export($spEntityId, true)); + $logger->info('Sending logout response for partial logout to SP ' . var_export($spEntityId, true)); } else { $partial = false; - Logger::debug('Sending logout response to SP ' . var_export($spEntityId, true)); + $logger->debug('Sending logout response to SP ' . var_export($spEntityId, true)); } Stats::log('saml:idp:LogoutResponse:sent', [ @@ -611,8 +617,9 @@ public static function receiveLogoutMessage(IdP $idp): void \SimpleSAML\Module\saml\Message::validateMessage($spMetadata, $idpMetadata, $message); + $logger = new Logger(); if ($message instanceof LogoutResponse) { - Logger::info('Received SAML 2.0 LogoutResponse from: ' . var_export($spEntityId, true)); + $logger->info('Received SAML 2.0 LogoutResponse from: ' . var_export($spEntityId, true)); $statsData = [ 'spEntityID' => $spEntityId, 'idpEntityID' => $idpMetadata->getString('entityid'), @@ -626,7 +633,7 @@ public static function receiveLogoutMessage(IdP $idp): void if (!$message->isSuccess()) { $logoutError = \SimpleSAML\Module\saml\Message::getResponseError($message); - Logger::warning('Unsuccessful logout. Status was: ' . $logoutError); + $logger->warning('Unsuccessful logout. Status was: ' . $logoutError); } else { $logoutError = null; } @@ -635,14 +642,14 @@ public static function receiveLogoutMessage(IdP $idp): void $idp->handleLogoutResponse($assocId, $relayState, $logoutError); } elseif ($message instanceof LogoutRequest) { - Logger::info('Received SAML 2.0 LogoutRequest from: ' . var_export($spEntityId, true)); + $logger->info('Received SAML 2.0 LogoutRequest from: ' . var_export($spEntityId, true)); Stats::log('saml:idp:LogoutRequest:recv', [ 'spEntityID' => $spEntityId, 'idpEntityID' => $idpMetadata->getString('entityid'), ]); $spStatsId = $spMetadata->getString('core:statistics-id', $spEntityId); - Logger::stats('saml20-idp-SLO spinit ' . $spStatsId . ' ' . $idpMetadata->getString('entityid')); + $logger->stats('saml20-idp-SLO spinit ' . $spStatsId . ' ' . $idpMetadata->getString('entityid')); $state = [ 'Responder' => ['\SimpleSAML\Module\saml\IdP\SAML2', 'sendLogoutResponse'], @@ -670,7 +677,8 @@ public static function receiveLogoutMessage(IdP $idp): void */ public static function getLogoutURL(IdP $idp, array $association, string $relayState = null): string { - Logger::info('Sending SAML 2.0 LogoutRequest to: ' . var_export($association['saml:entityID'], true)); + $logger = new Logger(); + $logger->info('Sending SAML 2.0 LogoutRequest to: ' . var_export($association['saml:entityID'], true)); $metadata = MetaDataStorageHandler::getMetadataHandler(); $idpMetadata = $idp->getConfig(); @@ -936,18 +944,19 @@ private static function generateNameIdValue( Configuration $spMetadata, array &$state ): ?string { + $logger = new Logger(); $attribute = $spMetadata->getString('simplesaml.nameidattribute', null); if ($attribute === null) { $attribute = $idpMetadata->getString('simplesaml.nameidattribute', null); if ($attribute === null) { - Logger::error('Unable to generate NameID. Check the simplesaml.nameidattribute option.'); + $logger->error('Unable to generate NameID. Check the simplesaml.nameidattribute option.'); return null; } } $attributes = $state['Attributes']; if (!array_key_exists($attribute, $attributes)) { - Logger::error('Unable to add NameID: Missing ' . var_export($attribute, true) . + $logger->error('Unable to add NameID: Missing ' . var_export($attribute, true) . ' in the attributes of the user.'); return null; } @@ -1248,7 +1257,8 @@ private static function buildAssertion( or random id if not assigned/configured */ $nameIdValue = self::generateNameIdValue($idpMetadata, $spMetadata, $state); if ($nameIdValue === null) { - Logger::warning('Falling back to transient NameID.'); + $logger = new Logger(); + $logger->warning('Falling back to transient NameID.'); $nameIdFormat = Constants::NAMEID_TRANSIENT; $nameIdValue = $randomUtils->generateID(); } diff --git a/modules/saml/lib/IdP/SQLNameID.php b/modules/saml/lib/IdP/SQLNameID.php index 45623212a5..76a7c5f723 100644 --- a/modules/saml/lib/IdP/SQLNameID.php +++ b/modules/saml/lib/IdP/SQLNameID.php @@ -8,6 +8,7 @@ use PDOStatement; use SimpleSAML\Assert\Assert; use SimpleSAML\Error; +use SimpleSAML\Logger; use SimpleSAML\Store; use SimpleSAML\Database; use SimpleSAML\Configuration; @@ -90,7 +91,8 @@ private static function create(array $config = []) try { self::createTable($table, $config); } catch (\Exception $e) { - \SimpleSAML\Logger::debug('SQL persistent NameID table already exists.'); + $logger = new Logger(); + $logger->debug('SQL persistent NameID table already exists.'); } } elseif ($store->getTableVersion('saml_PersistentNameID') !== self::TABLE_VERSION) { self::createTable($table); diff --git a/tests/lib/SimpleSAML/LoggerTest.php b/tests/lib/SimpleSAML/LoggerTest.php index a32aa008f5..1574467638 100644 --- a/tests/lib/SimpleSAML/LoggerTest.php +++ b/tests/lib/SimpleSAML/LoggerTest.php @@ -18,13 +18,18 @@ class LoggerTest extends TestCase */ protected $originalLogger; + /** + * @var \SimpleSAML\Logger + */ + protected $logger; + /** * @param string $handler */ protected function setLoggingHandler(string $handler): void { - $this->originalLogger = Logger::getLoggingHandler(); + $this->originalLogger = $this->logger::getLoggingHandler(); $config = [ 'logging.handler' => $handler, 'logging.level' => LogLevel::DEBUG @@ -32,7 +37,15 @@ protected function setLoggingHandler(string $handler): void // testing statics is slightly painful Configuration::loadFromArray($config, '[ARRAY]', 'simplesaml'); - Logger::setLoggingHandler(null); + $this->logger::setLoggingHandler(null); + } + + + /** + */ + protected function setUp(): void + { + $this->logger = new Logger(); } @@ -43,9 +56,9 @@ protected function tearDown(): void if (isset($this->originalLogger)) { // reset the logger and Configuration Configuration::clearInternalState(); - Logger::clearCapturedLog(); - Logger::setLogLevel(LogLevel::INFO); - Logger::setLoggingHandler($this->originalLogger); + $this->logger::clearCapturedLog(); + $this->logger::setLogLevel(LogLevel::INFO); + $this->logger::setLoggingHandler($this->originalLogger); } } @@ -56,9 +69,9 @@ public function testCreateLoggingHandlerHonorsCustomHandler(): void { $this->setLoggingHandler(ArrayLogger::class); - Logger::critical('array logger'); + $this->logger->critical('array logger'); - $logger = Logger::getLoggingHandler(); + $logger = $this->logger::getLoggingHandler(); self::assertInstanceOf(ArrayLogger::class, $logger); } @@ -71,14 +84,14 @@ public function testCaptureLog(): void $this->setLoggingHandler(ArrayLogger::class); $payload = "catch this error"; - Logger::setCaptureLog(); - Logger::critical($payload); + $this->logger::setCaptureLog(); + $this->logger->critical($payload); // turn logging off - Logger::setCaptureLog(false); - Logger::critical("do not catch this"); + $this->logger::setCaptureLog(false); + $this->logger->critical("do not catch this"); - $log = Logger::getCapturedLog(); + $log = $this->logger::getCapturedLog(); self::assertCount(1, $log); self::assertMatchesRegularExpression("/^[0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{3}Z\ {$payload}$/", $log[0]); } @@ -95,7 +108,7 @@ public function testExceptionThrownOnInvalidLoggingHandler(): void "Invalid value for the 'logging.handler' configuration option. Unknown handler 'nohandler'." ); - Logger::critical('should throw exception'); + $this->logger->critical('should throw exception'); } @@ -126,9 +139,9 @@ public function testLevelMethods(string $method, string $level): void { $this->setLoggingHandler(ArrayLogger::class); - Logger::{$method}($payload = "test {$method}"); + $this->logger->{$method}($payload = "test {$method}"); - $logger = Logger::getLoggingHandler(); + $logger = $this->logger::getLoggingHandler(); self::assertMatchesRegularExpression("/\[CL[0-9a-f]{8}\]\ {$payload}$/", $logger->logs[$level][0]); } } diff --git a/tests/modules/core/lib/Auth/UserPassBaseTest.php b/tests/modules/core/lib/Auth/UserPassBaseTest.php index ec8bcbfdf8..ee06d82791 100644 --- a/tests/modules/core/lib/Auth/UserPassBaseTest.php +++ b/tests/modules/core/lib/Auth/UserPassBaseTest.php @@ -7,6 +7,7 @@ use PHPUnit\Framework\TestCase; use SAML2\Constants; use SimpleSAML\Error\Error as SspError; +use SimpleSAML\Logger; use SimpleSAML\Module\core\Auth\UserPassBase; /** @@ -60,6 +61,7 @@ public function testAuthenticateECPMissingUsername(): void $stub = $this->getMockBuilder(UserPassBase::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); + $stub->setLogger(new Logger()); /** @var \SimpleSAML\Module\core\Auth\UserPassBase $stub */ $stub->authenticate($state); @@ -83,6 +85,7 @@ public function testAuthenticateECPMissingPassword(): void $stub = $this->getMockBuilder(UserPassBase::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); + $stub->setLogger(new Logger()); /** @var \SimpleSAML\Module\core\Auth\UserPassBase $stub */ $stub->authenticate($state);