fix: move debug mode to config (#3324)

* fix: move debug mode to config

* fix: also move debug_whitelist to .ini config

* fix: move logic back to Debug class

* docs

* docs

* fix: disable debug mode by default

* fix: restore previous behavior for alerts

* fix: center-align alert text
This commit is contained in:
Dag 2023-06-02 20:22:09 +02:00 committed by GitHub
parent c5cd229445
commit ee498eadf9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
18 changed files with 121 additions and 158 deletions

View file

@ -114,6 +114,15 @@ final class Configuration
}
}
if (file_exists(__DIR__ . '/../DEBUG')) {
// The debug mode has been moved to config. Preserve existing installs which has this DEBUG file.
self::setConfig('system', 'enable_debug_mode', true);
$debug = trim(file_get_contents(__DIR__ . '/../DEBUG'));
if ($debug) {
self::setConfig('system', 'debug_mode_whitelist', explode("\n", str_replace("\r", '', $debug)));
}
}
if (
!is_string(self::getConfig('system', 'timezone'))
|| !in_array(self::getConfig('system', 'timezone'), timezone_identifiers_list(DateTimeZone::ALL_WITH_BC))
@ -121,6 +130,13 @@ final class Configuration
self::throwConfigError('system', 'timezone');
}
if (!is_bool(self::getConfig('system', 'enable_debug_mode'))) {
self::throwConfigError('system', 'enable_debug_mode', 'Is not a valid Boolean');
}
if (!is_array(self::getConfig('system', 'debug_mode_whitelist') ?: [])) {
self::throwConfigError('system', 'debug_mode_whitelist', 'Is not a valid array');
}
if (!is_string(self::getConfig('proxy', 'url'))) {
self::throwConfigError('proxy', 'url', 'Is not a valid string');
}

View file

@ -1,106 +1,23 @@
<?php
/**
* This file is part of RSS-Bridge, a PHP project capable of generating RSS and
* Atom feeds for websites that don't have one.
*
* For the full license information, please view the UNLICENSE file distributed
* with this source code.
*
* @package Core
* @license http://unlicense.org/ UNLICENSE
* @link https://github.com/rss-bridge/rss-bridge
*/
/**
* Implements functions for debugging purposes. Debugging can be enabled by
* placing a file named DEBUG in {@see PATH_ROOT}.
*
* The file specifies a whitelist of IP addresses on which debug mode will be
* enabled. An empty file enables debug mode for everyone (highly discouraged
* for public servers!). Each line in the file specifies one client in the
* whitelist. For example:
*
* * `192.168.1.72`
* * `127.0.0.1`
* * `::1`
*
* Notice: If you are running RSS-Bridge on your local machine, you need to add
* localhost (either `127.0.0.1` for IPv4 or `::1` for IPv6) to your whitelist!
*
* Warning: In debug mode your server may display sensitive information! For
* security reasons it is recommended to whitelist only specific IP addresses.
*/
class Debug
{
/**
* Indicates if debug mode is enabled.
*
* Do not access this property directly!
* Use {@see Debug::isEnabled()} instead.
*
* @var bool
* Convenience function for Configuration::getConfig('system', 'enable_debug_mode')
*/
private static $enabled = false;
/**
* Indicates if debug mode is secure.
*
* Do not access this property directly!
* Use {@see Debug::isSecure()} instead.
*
* @var bool
*/
private static $secure = false;
/**
* Returns true if debug mode is enabled
*
* If debug mode is enabled, sets `display_errors = 1` and `error_reporting = E_ALL`
*
* @return bool True if enabled.
*/
public static function isEnabled()
public static function isEnabled(): bool
{
static $firstCall = true; // Initialized on first call
if ($firstCall && file_exists(__DIR__ . '/../DEBUG')) {
$debug_whitelist = trim(file_get_contents(__DIR__ . '/../DEBUG'));
self::$enabled = empty($debug_whitelist) || in_array(
$_SERVER['REMOTE_ADDR'],
explode("\n", str_replace("\r", '', $debug_whitelist))
);
if (self::$enabled) {
self::$secure = !empty($debug_whitelist);
}
$firstCall = false; // Skip check on next call
$ip = $_SERVER['REMOTE_ADDR'];
$enableDebugMode = Configuration::getConfig('system', 'enable_debug_mode');
$debugModeWhitelist = Configuration::getConfig('system', 'debug_mode_whitelist') ?: [];
if ($enableDebugMode && ($debugModeWhitelist === [] || in_array($ip, $debugModeWhitelist))) {
return true;
}
return self::$enabled;
}
/**
* Returns true if debug mode is enabled only for specific IP addresses.
*
* Notice: The security flag is set by {@see Debug::isEnabled()}. If this
* function is called before {@see Debug::isEnabled()}, the default value is
* false!
*
* @return bool True if debug mode is secure
*/
public static function isSecure()
{
return self::$secure;
return false;
}
public static function log($message)
{
if (!self::isEnabled()) {
return;
}
$e = new \Exception();
$trace = trace_from_exception($e);
// Drop the current frame

View file

@ -113,9 +113,7 @@ abstract class FeedExpander extends BridgeAbstract
if ($rssContent === false) {
$xmlErrors = libxml_get_errors();
foreach ($xmlErrors as $xmlError) {
if (Debug::isEnabled()) {
Debug::log(trim($xmlError->message));
}
Logger::debug(trim($xmlError->message));
}
if ($xmlErrors) {
// Render only the first error into exception message

View file

@ -6,9 +6,7 @@ final class Logger
{
public static function debug(string $message, array $context = [])
{
if (Debug::isEnabled()) {
self::log('DEBUG', $message, $context);
}
self::log('DEBUG', $message, $context);
}
public static function info(string $message, array $context = []): void
@ -28,6 +26,11 @@ final class Logger
private static function log(string $level, string $message, array $context = []): void
{
if (!Debug::isEnabled() && $level === 'DEBUG') {
// Don't log this debug log record because debug mode is disabled
return;
}
if (isset($context['e'])) {
/** @var \Throwable $e */
$e = $context['e'];
@ -66,7 +69,13 @@ final class Logger
$message,
$context ? Json::encode($context) : ''
);
// Log to stderr/stdout whatever that is
// todo: extract to log handler
error_log($text);
// Log to file
// todo: extract to log handler
//file_put_contents('/tmp/rss-bridge.log', $text, FILE_APPEND);
}
}

View file

@ -42,6 +42,7 @@ final class RssBridge
);
Logger::warning($text);
if (Debug::isEnabled()) {
// todo: extract to log handler
print sprintf("<pre>%s</pre>\n", e($text));
}
});
@ -59,6 +60,7 @@ final class RssBridge
);
Logger::error($message);
if (Debug::isEnabled()) {
// todo: extract to log handler
print sprintf("<pre>%s</pre>\n", e($message));
}
}

View file

@ -40,6 +40,7 @@ const WHITELIST_DEFAULT = __DIR__ . '/../whitelist.default.txt';
const REPOSITORY = 'https://github.com/RSS-Bridge/rss-bridge/';
// Allow larger files for simple_html_dom
// todo: extract to config (if possible)
const MAX_FILE_SIZE = 10000000;
// Files

View file

@ -438,14 +438,17 @@ function getSimpleHTMLDOMCached(
$time !== false
&& (time() - $duration < $time)
&& !Debug::isEnabled()
) { // Contents within duration
) {
// Contents within duration and debug mode is disabled
$content = $cache->loadData();
} else { // Content not within duration
} else {
// Contents not within duration, or debug mode is enabled
$content = getContents(
$url,
$header ?? [],
$opts ?? []
);
// todo: fix bad if statement
if ($content !== false) {
$cache->saveData($content);
}

View file

@ -1,23 +1,34 @@
<?php
/**
* This file is part of RSS-Bridge, a PHP project capable of generating RSS and
* Atom feeds for websites that don't have one.
*
* For the full license information, please view the UNLICENSE file distributed
* with this source code.
*
* @package Core
* @license http://unlicense.org/ UNLICENSE
* @link https://github.com/rss-bridge/rss-bridge
* Render template using base.html.php as base
*/
function render(string $template, array $context = []): string
{
if ($template === 'base.html.php') {
throw new \Exception('Do not render base.html.php into itself');
}
$context['system_message'] = Configuration::getConfig('system', 'message');
$context['messages'] = $context['messages'] ?? [];
if (Configuration::getConfig('system', 'message')) {
$context['messages'][] = [
'body' => Configuration::getConfig('system', 'message'),
'level' => 'info',
];
}
if (Debug::isEnabled()) {
$debugModeWhitelist = Configuration::getConfig('system', 'debug_mode_whitelist') ?: [];
if ($debugModeWhitelist === []) {
$context['messages'][] = [
'body' => 'Warning : Debug mode is active from any location, make sure only you can access RSS-Bridge.',
'level' => 'error'
];
} else {
$context['messages'][] = [
'body' => 'Warning : Debug mode is active from your IP address, your requests will bypass the cache.',
'level' => 'warning'
];
}
}
$context['page'] = render_template($template, $context);
return render_template('base.html.php', $context);
}