mirror of
https://github.com/Combodo/iTop.git
synced 2026-11-30 18:48:57 +01:00
Compare commits
4 Commits
support/3.
...
feature/10
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0a9541545c | ||
|
|
f412c13b9a | ||
|
|
eac5d7864b | ||
|
|
3c9cbdd9d7 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -165,3 +165,4 @@ local.properties
|
||||
# Windows
|
||||
Thumbs.db
|
||||
|
||||
/docs/
|
||||
|
||||
@@ -51,6 +51,9 @@ define('ACCESS_READONLY', 0);
|
||||
require_once('attributedef.class.inc.php'); // For the defines
|
||||
require_once('simplecrypt.class.inc.php');
|
||||
|
||||
use Combodo\iTop\Core\Config\Sensitive\SensitiveConfigStore;
|
||||
use Combodo\iTop\Core\Config\Sensitive\SensitiveParameters;
|
||||
|
||||
// was utf8 but it only supports BMP chars (https://dev.mysql.com/doc/refman/5.5/en/charset-unicode-utf8mb4.html)
|
||||
// so we switched to utf8mb4 in iTop 2.5, adding dependency to MySQL 5.5.3
|
||||
// The config params db_character_set and db_collation were introduced as a temporary workaround and removed in iTop 2.5
|
||||
@@ -105,6 +108,16 @@ class Config
|
||||
//for each conf entry, whether the non interpreted value can be kept in case is is written back to the disk.
|
||||
private $m_aCanOverrideSettings;
|
||||
|
||||
/** @var \Combodo\iTop\Core\Config\Sensitive\SensitiveConfigStore|null store bound to this config (N°10293) */
|
||||
private ?SensitiveConfigStore $oSensitiveStore = null;
|
||||
/** @var bool whether the bound store exists (opt-in) */
|
||||
private bool $bSensitiveStoreActive = false;
|
||||
private ?SensitiveParameters $oSensitiveParameters = null;
|
||||
/** @var bool write guard on sensitive keys (disabled while loading the file) */
|
||||
private bool $bSensitiveGuardEnabled = false;
|
||||
/** @var string[] sensitive keys found in the config file and ignored */
|
||||
private array $aShadowedSensitiveKeys = [];
|
||||
|
||||
/**
|
||||
* New way to store the settings !
|
||||
*
|
||||
@@ -233,6 +246,7 @@ class Config
|
||||
],
|
||||
'db_pwd' => [
|
||||
'type' => 'string',
|
||||
'sensitive' => true,
|
||||
'default' => null,
|
||||
'value' => '',
|
||||
'source_of_value' => '',
|
||||
@@ -659,6 +673,7 @@ class Config
|
||||
'email_transport_smtp.password' => [
|
||||
'type' => 'string',
|
||||
'description' => 'Authentication password (optional)',
|
||||
'sensitive' => true,
|
||||
'default' => "",
|
||||
'value' => "",
|
||||
'source_of_value' => '',
|
||||
@@ -1890,24 +1905,14 @@ class Config
|
||||
$sType = $this->m_aSettings[$sPropCode]['type'];
|
||||
|
||||
$value = $this->oConfigPlaceholdersResolver->Resolve($value);
|
||||
$value = static::CastSettingValue($sPropCode, $sType, $value);
|
||||
|
||||
switch ($sType) {
|
||||
case 'bool':
|
||||
$value = (bool)$value;
|
||||
break;
|
||||
case 'string':
|
||||
$value = (string)$value;
|
||||
break;
|
||||
case 'integer':
|
||||
$value = (int)$value;
|
||||
break;
|
||||
case 'float':
|
||||
$value = (float)$value;
|
||||
break;
|
||||
case 'array':
|
||||
break;
|
||||
default:
|
||||
throw new CoreException('Unknown type for setting', ['property' => $sPropCode, 'type' => $sType]);
|
||||
if ($this->IsSensitiveGuarded($sPropCode)) {
|
||||
// N°10293: no-op when unchanged (setup replays the same values), refused otherwise
|
||||
if ($value !== static::CastSettingValue($sPropCode, $sType, $this->GetSensitiveEffectiveValue($sPropCode))) {
|
||||
throw new ConfigException('This parameter is managed in the sensitive configuration file and cannot be modified here', ['key' => $sPropCode]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if ($this->m_aSettings[$sPropCode]['value'] == $value) {
|
||||
@@ -1920,6 +1925,27 @@ class Config
|
||||
$this->m_aCanOverrideSettings[$sPropCode] = $bCanOverride;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws \CoreException
|
||||
*/
|
||||
protected static function CastSettingValue(string $sPropCode, string $sType, $value)
|
||||
{
|
||||
switch ($sType) {
|
||||
case 'bool':
|
||||
return (bool)$value;
|
||||
case 'string':
|
||||
return (string)$value;
|
||||
case 'integer':
|
||||
return (int)$value;
|
||||
case 'float':
|
||||
return (float)$value;
|
||||
case 'array':
|
||||
return $value;
|
||||
default:
|
||||
throw new CoreException('Unknown type for setting', ['property' => $sPropCode, 'type' => $sType]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $sPropCode
|
||||
*
|
||||
@@ -2042,7 +2068,7 @@ class Config
|
||||
* @throws \ConfigException
|
||||
* @throws \CoreException
|
||||
*/
|
||||
public function __construct($sConfigFile = null, $bLoadConfig = true)
|
||||
public function __construct($sConfigFile = null, $bLoadConfig = true, ?SensitiveConfigStore $oSensitiveStore = null)
|
||||
{
|
||||
$this->oConfigPlaceholdersResolver = new ConfigPlaceholdersResolver();
|
||||
|
||||
@@ -2083,10 +2109,16 @@ class Config
|
||||
|
||||
$this->m_aModuleSettings = [];
|
||||
|
||||
$oSensitiveStore ??= $this->ResolveSensitiveStoreForFile($sConfigFile);
|
||||
if ($oSensitiveStore !== null) {
|
||||
$this->DoBindSensitiveConfigStore($oSensitiveStore);
|
||||
}
|
||||
|
||||
if ($bLoadConfig) {
|
||||
$this->Load($sConfigFile);
|
||||
$this->Verify();
|
||||
}
|
||||
$this->bSensitiveGuardEnabled = true;
|
||||
|
||||
// Application root url: set a default value, then normalize it
|
||||
/*
|
||||
@@ -2194,6 +2226,9 @@ class Config
|
||||
$this->m_aAddons = $MyModules['addons'];
|
||||
|
||||
foreach ($MySettings as $sPropCode => $rawvalue) {
|
||||
if ($this->IsSensitive($sPropCode)) {
|
||||
continue; // N°10293: ignored, read from the sensitive store (see ApplySensitiveStore)
|
||||
}
|
||||
if ($this->IsProperty($sPropCode)) {
|
||||
if (is_string($rawvalue)) {
|
||||
$value = trim($rawvalue);
|
||||
@@ -2229,6 +2264,295 @@ class Config
|
||||
$this->m_aCharsets = isset($MySettings['csv_import_charsets']) ? $MySettings['csv_import_charsets'] : [];
|
||||
$this->m_iPasswordHashAlgo = isset($MySettings['password_hash_algo']) ? $MySettings['password_hash_algo'] : $this->m_iPasswordHashAlgo;
|
||||
$this->m_sAppSecret = isset($MySettings['application.secret']) ? trim($MySettings['application.secret']) : $this->m_sAppSecret;
|
||||
|
||||
if ($this->bSensitiveStoreActive) {
|
||||
$this->ApplySensitiveStore($MySettings, $MyModuleSettings ?? []);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* N°10293 strict mode: a sensitive parameter is always read from the sensitive store, never from the config file.
|
||||
* Values of the config file for those parameters are dropped (and reported as "shadowed").
|
||||
*
|
||||
* @throws \ConfigException
|
||||
* @throws \CoreException
|
||||
*/
|
||||
private function ApplySensitiveStore(array $aFileSettings, array $aFileModuleSettings): void
|
||||
{
|
||||
$aShadowed = [];
|
||||
foreach ($this->oSensitiveParameters->GetEffective() as $sId) {
|
||||
$aKind = $this->GetSensitiveIdKind($sId);
|
||||
switch ($aKind[0]) {
|
||||
case 'core':
|
||||
if (array_key_exists($sId, $aFileSettings)) {
|
||||
$aShadowed[] = $sId;
|
||||
}
|
||||
$this->m_aSettings[$sId]['value'] = static::CastSettingValue($sId, $this->m_aSettings[$sId]['type'], $this->GetSensitiveEffectiveValue($sId));
|
||||
$this->m_aSettings[$sId]['source_of_value'] = $this->oSensitiveStore->Has($sId) ? $this->oSensitiveStore->GetPath() : '';
|
||||
$this->m_aCanOverrideSettings[$sId] = false;
|
||||
break;
|
||||
|
||||
case 'legacy':
|
||||
if (array_key_exists($sId, $aFileSettings)) {
|
||||
$aShadowed[] = $sId;
|
||||
}
|
||||
$this->m_sEncryptionKey = $this->GetSensitiveEffectiveValue($sId);
|
||||
break;
|
||||
|
||||
case 'module':
|
||||
[, $sModule, $sProperty] = $aKind;
|
||||
if (isset($aFileModuleSettings[$sModule]) && is_array($aFileModuleSettings[$sModule]) && array_key_exists($sProperty, $aFileModuleSettings[$sModule])) {
|
||||
$aShadowed[] = $sId;
|
||||
}
|
||||
if ($this->oSensitiveStore->Has($sId)) {
|
||||
$this->m_aModuleSettings[$sModule][$sProperty] = $this->oSensitiveStore->Get($sId);
|
||||
} else {
|
||||
unset($this->m_aModuleSettings[$sModule][$sProperty]);
|
||||
if (empty($this->m_aModuleSettings[$sModule])) {
|
||||
unset($this->m_aModuleSettings[$sModule]);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
sort($aShadowed);
|
||||
$this->aShadowedSensitiveKeys = $aShadowed;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0: string, 1?: string, 2?: string} ['core'] | ['legacy'] | ['module', module, property] | ['unknown']
|
||||
*/
|
||||
private function GetSensitiveIdKind(string $sId): array
|
||||
{
|
||||
if ($this->IsProperty($sId)) {
|
||||
return ['core'];
|
||||
}
|
||||
if (in_array($sId, SensitiveParameters::LEGACY_BASELINE, true)) {
|
||||
return ['legacy'];
|
||||
}
|
||||
$iPos = strpos($sId, '.');
|
||||
if ($iPos > 0 && $iPos < strlen($sId) - 1) {
|
||||
return ['module', substr($sId, 0, $iPos), substr($sId, $iPos + 1)];
|
||||
}
|
||||
|
||||
return ['unknown'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Value that a sensitive parameter must have: the store value, or the declared default when absent (D-014)
|
||||
*
|
||||
* @throws \ConfigException when encryption_key is absent from the store (a random default would corrupt encrypted data)
|
||||
*/
|
||||
private function GetSensitiveEffectiveValue(string $sId)
|
||||
{
|
||||
$aKind = $this->GetSensitiveIdKind($sId);
|
||||
if ($this->oSensitiveStore->Has($sId)) {
|
||||
$value = $this->oSensitiveStore->Get($sId);
|
||||
|
||||
return ($aKind[0] === 'legacy') ? (string)$value : $value;
|
||||
}
|
||||
switch ($aKind[0]) {
|
||||
case 'core':
|
||||
return $this->m_aSettings[$sId]['default'];
|
||||
case 'legacy':
|
||||
throw new ConfigException('Missing mandatory sensitive parameter in the sensitive configuration file', ['key' => $sId, 'file' => $this->oSensitiveStore->GetPath()]);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook allowing to resolve the sensitive store bound to a config file
|
||||
*
|
||||
* @throws \ConfigException
|
||||
*/
|
||||
protected function ResolveSensitiveStoreForFile(?string $sConfigFile): ?SensitiveConfigStore
|
||||
{
|
||||
$sEnv = SensitiveConfigStore::GetEnvironmentFromConfigFile($sConfigFile);
|
||||
|
||||
return ($sEnv === null) ? null : SensitiveConfigStore::ForEnvironment($sEnv);
|
||||
}
|
||||
|
||||
private function DoBindSensitiveConfigStore(SensitiveConfigStore $oStore): void
|
||||
{
|
||||
$this->oSensitiveStore = $oStore;
|
||||
$this->bSensitiveStoreActive = $oStore->IsActive();
|
||||
if ($this->bSensitiveStoreActive) {
|
||||
// Validate the store right away (fail closed) and read the local overrides
|
||||
$oStore->GetValues();
|
||||
$this->oSensitiveParameters = SensitiveParameters::FromLocalFile($this->GetCoreSensitiveKeys(), $oStore->GetLocalFilePath());
|
||||
} else {
|
||||
$this->oSensitiveParameters = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Late binding (e.g. setup writing a config built from scratch): values are NOT applied,
|
||||
* but the write guard becomes active and {@see WriteToFile()} checks the values against the store.
|
||||
*
|
||||
* @throws \ConfigException
|
||||
* @since 3.2.4 N°10293
|
||||
*/
|
||||
public function BindSensitiveConfigStore(SensitiveConfigStore $oStore): void
|
||||
{
|
||||
$this->DoBindSensitiveConfigStore($oStore);
|
||||
$this->bSensitiveGuardEnabled = true;
|
||||
}
|
||||
|
||||
/** @since 3.2.4 N°10293 */
|
||||
public function GetSensitiveConfigStore(): ?SensitiveConfigStore
|
||||
{
|
||||
return $this->oSensitiveStore;
|
||||
}
|
||||
|
||||
/** @since 3.2.4 N°10293 */
|
||||
public function IsSensitiveStoreActive(): bool
|
||||
{
|
||||
return $this->bSensitiveStoreActive;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string[] keys of $m_aSettings flagged as sensitive in the code
|
||||
* @since 3.2.4 N°10293
|
||||
*/
|
||||
public function GetCoreSensitiveKeys(): array
|
||||
{
|
||||
return array_keys(array_filter($this->m_aSettings, fn ($aInfo) => !empty($aInfo['sensitive'])));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $sId core key, legacy key or "<module>.<property>"
|
||||
*
|
||||
* @return bool true if the store is active and the parameter belongs to the effective sensitive set
|
||||
* @since 3.2.4 N°10293
|
||||
*/
|
||||
public function IsSensitive(string $sId): bool
|
||||
{
|
||||
return $this->bSensitiveStoreActive && $this->oSensitiveParameters->IsSensitive($sId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string[] effective sensitive set (names only), empty when the store is inactive
|
||||
* @since 3.2.4 N°10293
|
||||
*/
|
||||
public function GetSensitiveKeys(): array
|
||||
{
|
||||
return $this->bSensitiveStoreActive ? $this->oSensitiveParameters->GetEffective() : [];
|
||||
}
|
||||
|
||||
/** @since 3.2.4 N°10293 */
|
||||
public function GetSensitiveParameters(): ?SensitiveParameters
|
||||
{
|
||||
return $this->oSensitiveParameters;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string[] sensitive keys present in the loaded config file (their values were ignored)
|
||||
* @since 3.2.4 N°10293
|
||||
*/
|
||||
public function GetShadowedSensitiveKeys(): array
|
||||
{
|
||||
return $this->aShadowedSensitiveKeys;
|
||||
}
|
||||
|
||||
/**
|
||||
* Values to write to a new sensitive store, so that the sensitive parameters leave the config file (N°10293).
|
||||
*
|
||||
* Placeholders written in the config file (%env()%, %server()%) are kept unevaluated, so that no secret held by the
|
||||
* environment ends up in the store. Parameters without any value are skipped (they keep their default).
|
||||
*
|
||||
* @param string[] $aIds sensitive identifiers (core, legacy or "<module>.<property>")
|
||||
*
|
||||
* @return array<string, mixed> identifier => value
|
||||
* @throws \ConfigException if a value is computed by a PHP expression in the config file: it cannot be moved without evaluating it
|
||||
* @since 3.2.4 N°10293
|
||||
*/
|
||||
public function GetSensitiveValuesForStore(array $aIds): array
|
||||
{
|
||||
$sConfig = ($this->m_sFile !== null && is_file($this->m_sFile)) ? file_get_contents($this->m_sFile) : null;
|
||||
$oParser = new iTopConfigParser($sConfig === false ? null : $sConfig);
|
||||
|
||||
$aValues = [];
|
||||
foreach ($aIds as $sId) {
|
||||
$aKind = $this->GetSensitiveIdKind($sId);
|
||||
switch ($aKind[0]) {
|
||||
case 'core':
|
||||
$value = $this->m_aSettings[$sId]['value'];
|
||||
$aParserValue = $oParser->GetVarValue('MySettings', $sId);
|
||||
if ($aParserValue['found']) {
|
||||
$rawValue = static::ParseLiteralExpression($sId, $aParserValue['value']);
|
||||
if (!empty($this->m_aCanOverrideSettings[$sId])) {
|
||||
// Value of the config file: keep its placeholders (trimmed, as in Load())
|
||||
$value = is_string($rawValue) ? trim($rawValue) : $rawValue;
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'legacy':
|
||||
$aParserValue = $oParser->GetVarValue('MySettings', $sId);
|
||||
if ($aParserValue['found']) {
|
||||
static::ParseLiteralExpression($sId, $aParserValue['value']);
|
||||
}
|
||||
$value = $this->m_sEncryptionKey;
|
||||
break;
|
||||
|
||||
case 'module':
|
||||
[, $sModule, $sProperty] = $aKind;
|
||||
if (!isset($this->m_aModuleSettings[$sModule]) || !array_key_exists($sProperty, $this->m_aModuleSettings[$sModule])) {
|
||||
continue 2;
|
||||
}
|
||||
// The parser indexes module settings by property name only: checking that the expression is a literal is enough
|
||||
$aParserValue = $oParser->GetVarValue('MyModuleSettings', $sProperty);
|
||||
if ($aParserValue['found']) {
|
||||
static::ParseLiteralExpression($sId, $aParserValue['value']);
|
||||
}
|
||||
$value = $this->m_aModuleSettings[$sModule][$sProperty];
|
||||
break;
|
||||
|
||||
default:
|
||||
continue 2;
|
||||
}
|
||||
if ($value !== null) {
|
||||
$aValues[$sId] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return $aValues;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $sId parameter, for the error message
|
||||
* @param string $sExpression PHP expression read from the config file
|
||||
*
|
||||
* @return mixed value of the expression
|
||||
* @throws \ConfigException if the expression is not made of literals only
|
||||
*/
|
||||
private static function ParseLiteralExpression(string $sId, string $sExpression)
|
||||
{
|
||||
$aAllowedTokens = [T_WHITESPACE, T_CONSTANT_ENCAPSED_STRING, T_LNUMBER, T_DNUMBER, T_ARRAY, T_DOUBLE_ARROW, T_COMMENT];
|
||||
$aAllowedChars = ['[', ']', '(', ')', ',', '-', '+', '.'];
|
||||
$aTokens = token_get_all('<?php '.$sExpression.';');
|
||||
array_shift($aTokens); // open tag
|
||||
array_pop($aTokens); // trailing ;
|
||||
foreach ($aTokens as $token) {
|
||||
if (is_array($token)) {
|
||||
$bAllowed = in_array($token[0], $aAllowedTokens, true)
|
||||
|| ($token[0] === T_STRING && in_array(strtolower($token[1]), ['true', 'false', 'null'], true));
|
||||
} else {
|
||||
$bAllowed = in_array($token, $aAllowedChars, true);
|
||||
}
|
||||
if (!$bAllowed) {
|
||||
throw new ConfigException('This parameter is computed in the configuration file and cannot be moved to the sensitive configuration file', ['key' => $sId]);
|
||||
}
|
||||
}
|
||||
|
||||
// Safe: literals only (checked above)
|
||||
return eval('return '.$sExpression.';');
|
||||
}
|
||||
|
||||
private function IsSensitiveGuarded(string $sId): bool
|
||||
{
|
||||
return $this->bSensitiveGuardEnabled && $this->IsSensitive($sId);
|
||||
}
|
||||
|
||||
protected function Verify()
|
||||
@@ -2283,6 +2607,13 @@ class Config
|
||||
|
||||
public function SetModuleSetting($sModule, $sProperty, $value)
|
||||
{
|
||||
$sId = $sModule.'.'.$sProperty;
|
||||
if ($this->IsSensitiveGuarded($sId)) {
|
||||
if (!$this->oSensitiveStore->Has($sId) || $value !== $this->oSensitiveStore->Get($sId)) {
|
||||
throw new ConfigException('This parameter is managed in the sensitive configuration file and cannot be modified here', ['key' => $sId]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
$this->m_aModuleSettings[$sModule][$sProperty] = $value;
|
||||
}
|
||||
|
||||
@@ -2543,6 +2874,12 @@ class Config
|
||||
|
||||
public function SetEncryptionKey($sKey)
|
||||
{
|
||||
if ($this->IsSensitiveGuarded('encryption_key')) {
|
||||
if ((string)$sKey !== $this->GetSensitiveEffectiveValue('encryption_key')) {
|
||||
throw new ConfigException('This parameter is managed in the sensitive configuration file and cannot be modified here', ['key' => 'encryption_key']);
|
||||
}
|
||||
return;
|
||||
}
|
||||
$this->m_sEncryptionKey = $sKey;
|
||||
}
|
||||
|
||||
@@ -2608,6 +2945,16 @@ class Config
|
||||
$aSettings['addon_list'][] = $sFile;
|
||||
}
|
||||
|
||||
// N°10293: never export sensitive values
|
||||
foreach ($this->GetSensitiveKeys() as $sId) {
|
||||
$aKind = $this->GetSensitiveIdKind($sId);
|
||||
if ($aKind[0] === 'module') {
|
||||
unset($aSettings['module_settings'][$aKind[1]][$aKind[2]]);
|
||||
} else {
|
||||
unset($aSettings[$sId]);
|
||||
}
|
||||
}
|
||||
|
||||
return $aSettings;
|
||||
}
|
||||
|
||||
@@ -2628,9 +2975,32 @@ class Config
|
||||
if (empty($sFileName)) {
|
||||
$sFileName = $this->m_sFile;
|
||||
}
|
||||
$sContent = $this->RenderFileContent();
|
||||
|
||||
$hFile = @fopen($sFileName, 'w');
|
||||
if ($hFile !== false) {
|
||||
fwrite($hFile, $sContent);
|
||||
$bReturn = fclose($hFile);
|
||||
|
||||
utils::SetConfig($this);
|
||||
|
||||
return $bReturn;
|
||||
} else {
|
||||
throw new ConfigException("Could not write to configuration file", ['file' => $sFileName]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the content of the configuration file (php format), without any side effect.
|
||||
* Sensitive parameters (N°10293) are never part of the output.
|
||||
*
|
||||
* @throws \ConfigException
|
||||
* @since 3.2.4 N°10293
|
||||
*/
|
||||
public function RenderFileContent(): string
|
||||
{
|
||||
$oHandle = null;
|
||||
$sConfig = null;
|
||||
|
||||
if ($this->m_sFile !== null && is_file($this->m_sFile)) {
|
||||
$oHandle = fopen($this->m_sFile, 'r');
|
||||
$index = 0;
|
||||
@@ -2648,138 +3018,154 @@ class Config
|
||||
flock($oHandle, LOCK_UN);
|
||||
}
|
||||
|
||||
$hFile = @fopen($sFileName, 'w');
|
||||
if ($hFile !== false) {
|
||||
fwrite($hFile, "<?php\n");
|
||||
fwrite($hFile, "\n/**\n");
|
||||
fwrite($hFile, " *\n");
|
||||
fwrite($hFile, " * Configuration file, generated by the ".ITOP_APPLICATION." configuration wizard\n");
|
||||
fwrite($hFile, " *\n");
|
||||
fwrite(
|
||||
$hFile,
|
||||
" * The file is used in MetaModel::LoadConfig() which does all the necessary initialization job\n"
|
||||
);
|
||||
fwrite($hFile, " *\n");
|
||||
fwrite($hFile, " */\n");
|
||||
$sOut = '';
|
||||
$sOut .= "<?php\n";
|
||||
$sOut .= "\n/**\n";
|
||||
$sOut .= " *\n";
|
||||
$sOut .= " * Configuration file, generated by the ".ITOP_APPLICATION." configuration wizard\n";
|
||||
$sOut .= " *\n";
|
||||
$sOut .= " * The file is used in MetaModel::LoadConfig() which does all the necessary initialization job\n";
|
||||
$sOut .= " *\n";
|
||||
$sOut .= " */\n";
|
||||
|
||||
$aConfigSettings = $this->m_aSettings;
|
||||
$aConfigSettings = $this->m_aSettings;
|
||||
|
||||
// Old fashioned boolean settings
|
||||
$aBoolValues = [
|
||||
'log_global' => $this->m_bLogGlobal,
|
||||
'log_notification' => $this->m_bLogNotification,
|
||||
'log_issue' => $this->m_bLogIssue,
|
||||
'log_web_service' => $this->m_bLogWebService,
|
||||
'secure_connection_required' => $this->m_bSecureConnectionRequired,
|
||||
// Old fashioned boolean settings
|
||||
$aBoolValues = [
|
||||
'log_global' => $this->m_bLogGlobal,
|
||||
'log_notification' => $this->m_bLogNotification,
|
||||
'log_issue' => $this->m_bLogIssue,
|
||||
'log_web_service' => $this->m_bLogWebService,
|
||||
'secure_connection_required' => $this->m_bSecureConnectionRequired,
|
||||
];
|
||||
foreach ($aBoolValues as $sKey => $bValue) {
|
||||
$aConfigSettings[$sKey] = [
|
||||
'show_in_conf_sample' => true,
|
||||
'type' => 'bool',
|
||||
'value' => $bValue,
|
||||
];
|
||||
foreach ($aBoolValues as $sKey => $bValue) {
|
||||
$aConfigSettings[$sKey] = [
|
||||
'show_in_conf_sample' => true,
|
||||
'type' => 'bool',
|
||||
'value' => $bValue,
|
||||
];
|
||||
}
|
||||
|
||||
// Old fashioned integer settings
|
||||
$aIntValues = [
|
||||
'fast_reload_interval' => $this->m_iFastReloadInterval,
|
||||
'max_display_limit' => $this->m_iMaxDisplayLimit,
|
||||
'min_display_limit' => $this->m_iMinDisplayLimit,
|
||||
'standard_reload_interval' => $this->m_iStandardReloadInterval,
|
||||
];
|
||||
foreach ($aIntValues as $sKey => $iValue) {
|
||||
$aConfigSettings[$sKey] = [
|
||||
'show_in_conf_sample' => true,
|
||||
'type' => 'integer',
|
||||
'value' => $iValue,
|
||||
];
|
||||
}
|
||||
|
||||
// Old fashioned remaining values
|
||||
$aOtherValues = [
|
||||
'default_language' => $this->m_sDefaultLanguage,
|
||||
'allowed_login_types' => $this->m_sAllowedLoginTypes,
|
||||
'encryption_key' => $this->m_sEncryptionKey,
|
||||
'encryption_library' => $this->m_sEncryptionLibrary,
|
||||
'csv_import_charsets' => $this->m_aCharsets,
|
||||
'password_hash_algo' => $this->m_iPasswordHashAlgo,
|
||||
'application.secret' => $this->m_sAppSecret,
|
||||
];
|
||||
foreach ($aOtherValues as $sKey => $value) {
|
||||
$aConfigSettings[$sKey] = [
|
||||
'show_in_conf_sample' => true,
|
||||
'type' => is_string($value) ? 'string' : 'mixed',
|
||||
'value' => $value,
|
||||
];
|
||||
}
|
||||
|
||||
ksort($aConfigSettings);
|
||||
fwrite($hFile, "\$MySettings = array(\n");
|
||||
foreach ($aConfigSettings as $sPropCode => $aSettingInfo) {
|
||||
// Write all values that are either always visible or present in the cloned config file
|
||||
if ($aSettingInfo['show_in_conf_sample'] || (!empty($aSettingInfo['source_of_value']) && ($aSettingInfo['source_of_value'] != 'unknown'))) {
|
||||
fwrite($hFile, "\n");
|
||||
|
||||
if (isset($aSettingInfo['description'])) {
|
||||
fwrite($hFile, "\t// $sPropCode: {$aSettingInfo['description']}\n");
|
||||
}
|
||||
|
||||
if (isset($aSettingInfo['default'])) {
|
||||
$sComment = self::PrettyVarExport(null, $aSettingInfo['default'], "\t//\t\t", true);
|
||||
fwrite($hFile, "\t//\tdefault: {$sComment}\n");
|
||||
}
|
||||
|
||||
if (isset($this->m_aCanOverrideSettings[$sPropCode]) && $this->m_aCanOverrideSettings[$sPropCode]) {
|
||||
$aParserValue = $this->oItopConfigParser->GetVarValue('MySettings', $sPropCode);
|
||||
} else {
|
||||
$aParserValue = null;
|
||||
}
|
||||
$sSeenAs = self::PrettyVarExport($aParserValue, $aSettingInfo['value'], "\t");
|
||||
fwrite($hFile, "\t".var_export((string) $sPropCode, true)." => $sSeenAs,\n");
|
||||
}
|
||||
}
|
||||
fwrite($hFile, ");\n");
|
||||
|
||||
fwrite($hFile, "\n");
|
||||
fwrite($hFile, "/**\n *\n * Modules specific settings\n *\n */\n");
|
||||
fwrite($hFile, "\$MyModuleSettings = array(\n");
|
||||
foreach ($this->m_aModuleSettings as $sModule => $aProperties) {
|
||||
fwrite($hFile, "\t".var_export((string) $sModule, true)." => array (\n");
|
||||
foreach ($aProperties as $sProperty => $value) {
|
||||
$sNiceExport = self::PrettyVarExport($this->oItopConfigParser->GetVarValue('MyModuleSettings', $sProperty), $value, "\t\t");
|
||||
fwrite($hFile, "\t\t".var_export((string) $sProperty, true)." => $sNiceExport,\n");
|
||||
}
|
||||
fwrite($hFile, "\t),\n");
|
||||
}
|
||||
fwrite($hFile, ");\n");
|
||||
|
||||
fwrite($hFile, "\n/**\n");
|
||||
fwrite($hFile, " *\n");
|
||||
fwrite($hFile, " * Data model modules to be loaded. Names are specified as relative paths\n");
|
||||
fwrite($hFile, " *\n");
|
||||
fwrite($hFile, " */\n");
|
||||
fwrite($hFile, "\$MyModules = array(\n");
|
||||
$aParserValue = $this->oItopConfigParser->GetVarValue('MyModules', 'addons');
|
||||
if ($aParserValue['found']) {
|
||||
fwrite($hFile, "\t'addons' => {$aParserValue['value']},\n");
|
||||
} else {
|
||||
fwrite($hFile, "\t'addons' => array (\n");
|
||||
foreach ($this->m_aAddons as $sKey => $sFile) {
|
||||
fwrite($hFile, "\t\t".var_export((string) $sKey, true).' => '.var_export($sFile, true).",\n");
|
||||
}
|
||||
fwrite($hFile, "\t),\n");
|
||||
}
|
||||
fwrite($hFile, ");\n");
|
||||
fwrite($hFile, '?'.'>'); // Avoid perturbing the syntax highlighting !
|
||||
|
||||
$bReturn = fclose($hFile);
|
||||
|
||||
utils::SetConfig($this);
|
||||
|
||||
return $bReturn;
|
||||
} else {
|
||||
throw new ConfigException("Could not write to configuration file", ['file' => $sFileName]);
|
||||
}
|
||||
|
||||
// Old fashioned integer settings
|
||||
$aIntValues = [
|
||||
'fast_reload_interval' => $this->m_iFastReloadInterval,
|
||||
'max_display_limit' => $this->m_iMaxDisplayLimit,
|
||||
'min_display_limit' => $this->m_iMinDisplayLimit,
|
||||
'standard_reload_interval' => $this->m_iStandardReloadInterval,
|
||||
];
|
||||
foreach ($aIntValues as $sKey => $iValue) {
|
||||
$aConfigSettings[$sKey] = [
|
||||
'show_in_conf_sample' => true,
|
||||
'type' => 'integer',
|
||||
'value' => $iValue,
|
||||
];
|
||||
}
|
||||
|
||||
// Old fashioned remaining values
|
||||
$aOtherValues = [
|
||||
'default_language' => $this->m_sDefaultLanguage,
|
||||
'allowed_login_types' => $this->m_sAllowedLoginTypes,
|
||||
'encryption_key' => $this->m_sEncryptionKey,
|
||||
'encryption_library' => $this->m_sEncryptionLibrary,
|
||||
'csv_import_charsets' => $this->m_aCharsets,
|
||||
'password_hash_algo' => $this->m_iPasswordHashAlgo,
|
||||
'application.secret' => $this->m_sAppSecret,
|
||||
];
|
||||
foreach ($aOtherValues as $sKey => $value) {
|
||||
$aConfigSettings[$sKey] = [
|
||||
'show_in_conf_sample' => true,
|
||||
'type' => is_string($value) ? 'string' : 'mixed',
|
||||
'value' => $value,
|
||||
];
|
||||
}
|
||||
|
||||
// N°10293: sensitive values are never written to the config file
|
||||
$aSensitiveModuleSettings = [];
|
||||
foreach ($this->GetSensitiveKeys() as $sId) {
|
||||
$aKind = $this->GetSensitiveIdKind($sId);
|
||||
if ($aKind[0] === 'module') {
|
||||
$aSensitiveModuleSettings[$aKind[1]][$aKind[2]] = true;
|
||||
continue;
|
||||
}
|
||||
if ($aKind[0] === 'core') {
|
||||
$value = $this->m_aSettings[$sId]['value'];
|
||||
$expected = static::CastSettingValue($sId, $this->m_aSettings[$sId]['type'], $this->GetSensitiveEffectiveValue($sId));
|
||||
$bDiverges = static::CastSettingValue($sId, $this->m_aSettings[$sId]['type'], $value) !== $expected;
|
||||
} elseif ($aKind[0] === 'legacy') {
|
||||
$bDiverges = (string)$this->m_sEncryptionKey !== $this->GetSensitiveEffectiveValue($sId);
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
if ($bDiverges) {
|
||||
throw new ConfigException('This parameter is managed in the sensitive configuration file and cannot be modified here', ['key' => $sId]);
|
||||
}
|
||||
unset($aConfigSettings[$sId]);
|
||||
}
|
||||
|
||||
ksort($aConfigSettings);
|
||||
$sOut .= "\$MySettings = array(\n";
|
||||
foreach ($aConfigSettings as $sPropCode => $aSettingInfo) {
|
||||
// Write all values that are either always visible or present in the cloned config file
|
||||
if ($aSettingInfo['show_in_conf_sample'] || (!empty($aSettingInfo['source_of_value']) && ($aSettingInfo['source_of_value'] != 'unknown'))) {
|
||||
$sOut .= "\n";
|
||||
|
||||
if (isset($aSettingInfo['description'])) {
|
||||
$sOut .= "\t// $sPropCode: {$aSettingInfo['description']}\n";
|
||||
}
|
||||
|
||||
if (isset($aSettingInfo['default'])) {
|
||||
$sComment = self::PrettyVarExport(null, $aSettingInfo['default'], "\t//\t\t", true);
|
||||
$sOut .= "\t//\tdefault: {$sComment}\n";
|
||||
}
|
||||
|
||||
if (isset($this->m_aCanOverrideSettings[$sPropCode]) && $this->m_aCanOverrideSettings[$sPropCode]) {
|
||||
$aParserValue = $this->oItopConfigParser->GetVarValue('MySettings', $sPropCode);
|
||||
} else {
|
||||
$aParserValue = null;
|
||||
}
|
||||
$sSeenAs = self::PrettyVarExport($aParserValue, $aSettingInfo['value'], "\t");
|
||||
$sOut .= "\t".var_export((string) $sPropCode, true)." => $sSeenAs,\n";
|
||||
}
|
||||
}
|
||||
$sOut .= ");\n";
|
||||
|
||||
$sOut .= "\n";
|
||||
$sOut .= "/**\n *\n * Modules specific settings\n *\n */\n";
|
||||
$sOut .= "\$MyModuleSettings = array(\n";
|
||||
foreach ($this->m_aModuleSettings as $sModule => $aProperties) {
|
||||
$aProperties = array_diff_key($aProperties, $aSensitiveModuleSettings[$sModule] ?? []);
|
||||
if (count($aProperties) === 0 && isset($aSensitiveModuleSettings[$sModule])) {
|
||||
continue;
|
||||
}
|
||||
$sOut .= "\t".var_export((string) $sModule, true)." => array (\n";
|
||||
foreach ($aProperties as $sProperty => $value) {
|
||||
$sNiceExport = self::PrettyVarExport($this->oItopConfigParser->GetVarValue('MyModuleSettings', $sProperty), $value, "\t\t");
|
||||
$sOut .= "\t\t".var_export((string) $sProperty, true)." => $sNiceExport,\n";
|
||||
}
|
||||
$sOut .= "\t),\n";
|
||||
}
|
||||
$sOut .= ");\n";
|
||||
|
||||
$sOut .= "\n/**\n";
|
||||
$sOut .= " *\n";
|
||||
$sOut .= " * Data model modules to be loaded. Names are specified as relative paths\n";
|
||||
$sOut .= " *\n";
|
||||
$sOut .= " */\n";
|
||||
$sOut .= "\$MyModules = array(\n";
|
||||
$aParserValue = $this->oItopConfigParser->GetVarValue('MyModules', 'addons');
|
||||
if ($aParserValue['found']) {
|
||||
$sOut .= "\t'addons' => {$aParserValue['value']},\n";
|
||||
} else {
|
||||
$sOut .= "\t'addons' => array (\n";
|
||||
foreach ($this->m_aAddons as $sKey => $sFile) {
|
||||
$sOut .= "\t\t".var_export((string) $sKey, true).' => '.var_export($sFile, true).",\n";
|
||||
}
|
||||
$sOut .= "\t),\n";
|
||||
}
|
||||
$sOut .= ");\n";
|
||||
$sOut .= '?'.'>'; // Avoid perturbing the syntax highlighting !
|
||||
|
||||
return $sOut;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2880,8 +3266,8 @@ class Config
|
||||
if (isset($aModuleInfo['settings'])) {
|
||||
list($sName, $sVersion) = ModuleDiscovery::GetModuleName($sModuleId);
|
||||
foreach ($aModuleInfo['settings'] as $sProperty => $value) {
|
||||
if (isset($this->m_aModuleSettings[$sName][$sProperty])) {
|
||||
// Do nothing keep the original value
|
||||
if (isset($this->m_aModuleSettings[$sName][$sProperty]) || $this->IsSensitive($sName.'.'.$sProperty)) {
|
||||
// Do nothing keep the original value (N°10293: sensitive values live in the sensitive store)
|
||||
} else {
|
||||
$this->SetModuleSetting($sName, $sProperty, $value);
|
||||
}
|
||||
|
||||
@@ -14,7 +14,9 @@ use Combodo\iTop\Application\UI\Base\Component\Input\InputUIBlockFactory;
|
||||
use Combodo\iTop\Application\UI\Base\Component\Title\TitleUIBlockFactory;
|
||||
use Combodo\iTop\Application\WebPage\iTopWebPage;
|
||||
use Combodo\iTop\Config\Validator\iTopConfigAstValidator;
|
||||
use Combodo\iTop\Config\Validator\iTopConfigSensitiveEnvValidator;
|
||||
use Combodo\iTop\Config\Validator\iTopConfigSyntaxValidator;
|
||||
use Combodo\iTop\Core\Config\Sensitive\SensitiveConfigStore;
|
||||
|
||||
require_once(APPROOT.'application/startup.inc.php');
|
||||
|
||||
@@ -98,6 +100,16 @@ function GetAlertFromException(Exception $e): Alert
|
||||
return $oAlert;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string[] $aKeys parameter names (never values)
|
||||
*
|
||||
* @since 3.2.4 N°10293
|
||||
*/
|
||||
function FormatSensitiveKeys(array $aKeys): string
|
||||
{
|
||||
return utils::EscapeHtml(implode(', ', $aKeys));
|
||||
}
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// Main program
|
||||
//
|
||||
@@ -137,6 +149,20 @@ try {
|
||||
$sConfigContent = file_get_contents($sConfigFile);
|
||||
$sConfigChecksum = md5($sConfigContent);
|
||||
$sConfig = str_replace("\r\n", "\n", $sConfigContent);
|
||||
|
||||
// N°10293: sensitive parameters are managed by the system administrator, outside of this editor
|
||||
$oSensitiveStore = SensitiveConfigStore::ForEnvironment(utils::GetCurrentEnvironment());
|
||||
$bSensitiveStoreActive = $oSensitiveStore->IsActive();
|
||||
$aShadowedKeys = [];
|
||||
if ($bSensitiveStoreActive) {
|
||||
$oCurrentConfig = new Config($sConfigFile, true, $oSensitiveStore);
|
||||
$oP->AddUiBlock(AlertUIBlockFactory::MakeForInformation('', Dict::Format('config-sensitive-managed-by-sysadmin', FormatSensitiveKeys($oCurrentConfig->GetSensitiveKeys()))));
|
||||
$aShadowedKeys = $oCurrentConfig->GetShadowedSensitiveKeys();
|
||||
if (count($aShadowedKeys) > 0) {
|
||||
// Never display the values: show the file as it will be written
|
||||
$sConfig = $oCurrentConfig->RenderFileContent();
|
||||
}
|
||||
}
|
||||
$sOriginalConfig = $sConfig;
|
||||
|
||||
if (!empty($sOperation)) {
|
||||
@@ -160,7 +186,7 @@ try {
|
||||
throw new Exception(Dict::S('config-error-file-changed'), CONFIG_ERROR);
|
||||
}
|
||||
|
||||
if ($sConfig === $sOriginalConfig) {
|
||||
if (($sConfig === $sOriginalConfig) && (count($aShadowedKeys) === 0)) {
|
||||
throw new Exception(Dict::S('config-no-change'), CONFIG_INFO);
|
||||
}
|
||||
TestConfig($sConfig, $oP); // throws exceptions
|
||||
@@ -179,12 +205,39 @@ try {
|
||||
// 'config_editor' => 'disabled',
|
||||
// )
|
||||
file_put_contents($sTmpFile, $sConfig);
|
||||
$oTempConfig = new Config($sTmpFile, true);
|
||||
try {
|
||||
$bReadsProtectedEnv = false;
|
||||
if ($bSensitiveStoreActive) {
|
||||
// N°10293: never let the editor read the variables carrying secrets (checked before any placeholder resolution)
|
||||
$oEnvValidator = new iTopConfigSensitiveEnvValidator($oSensitiveStore->GetPlaceholderVariableNames());
|
||||
$bReadsProtectedEnv = $oEnvValidator->Check($sConfig, $sTmpFile);
|
||||
}
|
||||
// N°10293: the temporary file is explicitly bound to the sensitive store of the current environment
|
||||
$oTempConfig = $bReadsProtectedEnv ? null : new Config($sTmpFile, true, $bSensitiveStoreActive ? $oSensitiveStore : null);
|
||||
} finally {
|
||||
@unlink($sTmpFile);
|
||||
}
|
||||
if ($bReadsProtectedEnv) {
|
||||
@chmod($sConfigFile, 0440);
|
||||
IssueLog::Warning('Config editor: attempt to read protected environment variables refused', LogChannels::SECURITY, [
|
||||
'user' => UserRights::GetUserId() ? UserRights::GetUser() : '',
|
||||
]);
|
||||
throw new Exception(Dict::S('config-sensitive-env-refused'), CONFIG_ERROR);
|
||||
}
|
||||
$aSubmittedSensitiveKeys = $oTempConfig->GetShadowedSensitiveKeys();
|
||||
if (count($aSubmittedSensitiveKeys) > 0) {
|
||||
@chmod($sConfigFile, 0440);
|
||||
IssueLog::Warning('Config editor: attempt to write sensitive parameters refused', LogChannels::SECURITY, [
|
||||
'user' => UserRights::GetUserId() ? UserRights::GetUser() : '',
|
||||
'keys' => $aSubmittedSensitiveKeys,
|
||||
]);
|
||||
throw new Exception(Dict::Format('config-sensitive-write-refused', FormatSensitiveKeys($aSubmittedSensitiveKeys)), CONFIG_ERROR);
|
||||
}
|
||||
$oTempConfig->WriteToFile($sConfigFile);
|
||||
@unlink($sTmpFile);
|
||||
@chmod($sConfigFile, 0440); // Read-only
|
||||
|
||||
if (DBPasswordInNewConfigIsOk($sConfig)) {
|
||||
// N°10293: with the sensitive store, db_pwd is not in the config file
|
||||
if ($bSensitiveStoreActive || DBPasswordInNewConfigIsOk($sConfig)) {
|
||||
$oAlert = AlertUIBlockFactory::MakeForSuccess('', Dict::S('config-saved'));
|
||||
} else {
|
||||
$oAlert = AlertUIBlockFactory::MakeForInformation('', Dict::S('config-saved-warning-db-password'));
|
||||
@@ -198,12 +251,17 @@ try {
|
||||
$sConfigChecksum = md5($sConfigContent);
|
||||
$sConfig = str_replace("\r\n", "\n", $sConfigContent);
|
||||
$sOriginalConfig = $sConfig;
|
||||
$aShadowedKeys = [];
|
||||
}
|
||||
} catch (Exception $e) {
|
||||
$oAlert = GetAlertFromException($e);
|
||||
$oP->AddUiBlock($oAlert);
|
||||
}
|
||||
|
||||
if (count($aShadowedKeys) > 0) {
|
||||
$oP->AddUiBlock(AlertUIBlockFactory::MakeForWarning('', Dict::Format('config-sensitive-shadowed', FormatSensitiveKeys($aShadowedKeys))));
|
||||
}
|
||||
|
||||
// (remove EscapeHtml) N°5914 - Wrong encoding in modules configuration editor
|
||||
$oP->AddUiBlock(new Html('<p>'.Dict::S('config-edit-intro').'</p>'));
|
||||
|
||||
|
||||
@@ -41,4 +41,8 @@ Dict::Add('EN US', 'English', 'English', [
|
||||
'config-error-file-changed' => 'Error: The Configuration file has changed since you opened it and cannot be saved. Refresh and apply your changes again.',
|
||||
'config-not-allowed-in-demo' => 'Sorry, '.ITOP_APPLICATION_SHORT.' is in <b>demonstration mode</b>: the configuration file cannot be edited.',
|
||||
'config-interactive-not-allowed' => ITOP_APPLICATION_SHORT." interactive edition of the configuration as been disabled. See <code>'config_editor' => 'disabled'</code> in the configuration file.",
|
||||
'config-sensitive-managed-by-sysadmin' => 'The following sensitive parameters are managed by the system administrator in a dedicated file and cannot be viewed nor modified here: %1$s.',
|
||||
'config-sensitive-shadowed' => 'The configuration file still contains sensitive parameters, which are ignored and hidden here: %1$s. They will be removed from the file at the next save.',
|
||||
'config-sensitive-write-refused' => 'Error: sensitive parameters cannot be set in this editor: %1$s. The configuration was <b>NOT</b> modified.',
|
||||
'config-sensitive-env-refused' => 'Error: the configuration references environment or server variables that carry sensitive parameters (or uses $GLOBALS, dynamic variables, or non-literal $_SERVER / $_ENV indexes). The configuration was <b>NOT</b> modified.',
|
||||
]);
|
||||
|
||||
@@ -28,4 +28,8 @@ Dict::Add('FR FR', 'French', 'Français', [
|
||||
'config-error-file-changed' => 'Erreur : La configuration a été modifiée depuis que vous l\'avez ouvert. Vos modifications ne peuvent <b>PAS</b> être enregistrées. Rechargez la page et recommencez.',
|
||||
'config-not-allowed-in-demo' => 'Désolé, '.ITOP_APPLICATION_SHORT.' est en <b>mode démonstration</b> : la configuration ne peut pas être modifiée.',
|
||||
'config-interactive-not-allowed' => 'La modification interactive de la configuration n\'est pas autorisée. Voir le paramètre <code>\'config_editor\' => \'disabled\'</code> dans le fichier de configuration.',
|
||||
'config-sensitive-managed-by-sysadmin' => 'Les paramètres sensibles suivants sont gérés par l\'administrateur système dans un fichier dédié et ne peuvent être ni consultés ni modifiés ici : %1$s.',
|
||||
'config-sensitive-shadowed' => 'Le fichier de configuration contient encore des paramètres sensibles, ignorés et masqués ici : %1$s. Ils seront supprimés du fichier au prochain enregistrement.',
|
||||
'config-sensitive-write-refused' => 'Erreur : les paramètres sensibles ne peuvent pas être définis dans cet éditeur : %1$s. La configuration n\'a <b>PAS</b> été modifiée.',
|
||||
'config-sensitive-env-refused' => 'Erreur : la configuration référence des variables d\'environnement ou serveur portant des paramètres sensibles (ou utilise $GLOBALS, des variables dynamiques, ou des index non littéraux de $_SERVER / $_ENV). La configuration n\'a <b>PAS</b> été modifiée.',
|
||||
]);
|
||||
|
||||
@@ -21,6 +21,7 @@ SetupWebPage::AddModule(
|
||||
'src/Validator/ConfigNodesVisitor.php',
|
||||
'src/Validator/iTopConfigAstValidator.php',
|
||||
'src/Validator/iTopConfigSyntaxValidator.php',
|
||||
'src/Validator/iTopConfigSensitiveEnvValidator.php',
|
||||
],
|
||||
'webservice' => [],
|
||||
'dictionary' => [
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* @copyright Copyright (C) 2010-2026 Combodo SAS
|
||||
* @license http://opensource.org/licenses/AGPL-3.0
|
||||
*/
|
||||
|
||||
namespace Combodo\iTop\Config\Validator;
|
||||
|
||||
use PhpParser\Node;
|
||||
use PhpParser\NodeTraverser;
|
||||
use PhpParser\NodeVisitorAbstract;
|
||||
use PhpParser\ParserFactory;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* N°10293 / D-035: prevent the config editor from reading secrets carried by environment / server variables
|
||||
* referenced by the placeholders of the sensitive store.
|
||||
*
|
||||
* Checks are done on NAMES only (never on secret values, which would create a guessing oracle).
|
||||
*/
|
||||
class iTopConfigSensitiveEnvValidator
|
||||
{
|
||||
private const PLACEHOLDER_PATTERN = '/%(?:env|server)\((\w+)\)/';
|
||||
|
||||
/**
|
||||
* @param string[] $aProtectedNames variable names used by the placeholders of the sensitive store
|
||||
*/
|
||||
public function __construct(private readonly array $aProtectedNames)
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* AST check of the submitted PHP code
|
||||
*
|
||||
* @return bool true if the code may read a protected variable
|
||||
*/
|
||||
public function IsCodeReadingProtectedVariables(string $sConfig): bool
|
||||
{
|
||||
$aNodes = (new ParserFactory())->create(ParserFactory::PREFER_PHP7)->parse($sConfig) ?? [];
|
||||
$aProtected = array_map('strtoupper', $this->aProtectedNames);
|
||||
$oVisitor = new class ($aProtected) extends NodeVisitorAbstract {
|
||||
public bool $bViolation = false;
|
||||
private array $aCheckedVariables = [];
|
||||
|
||||
public function __construct(private readonly array $aProtected)
|
||||
{
|
||||
}
|
||||
|
||||
public function enterNode(Node $node)
|
||||
{
|
||||
if ($node instanceof Node\Expr\ArrayDimFetch && $node->var instanceof Node\Expr\Variable && $this->IsEnvSuperGlobal($node->var)) {
|
||||
// $_SERVER['LITERAL'] is allowed unless LITERAL is protected
|
||||
$this->aCheckedVariables[spl_object_id($node->var)] = true;
|
||||
if (!($node->dim instanceof Node\Scalar\String_) || in_array(strtoupper($node->dim->value), $this->aProtected, true)) {
|
||||
$this->bViolation = true;
|
||||
}
|
||||
} elseif ($node instanceof Node\Expr\Variable) {
|
||||
if (!is_string($node->name) || $node->name === 'GLOBALS') {
|
||||
$this->bViolation = true; // dynamic variable name or $GLOBALS
|
||||
} elseif ($this->IsEnvSuperGlobal($node) && !isset($this->aCheckedVariables[spl_object_id($node)])) {
|
||||
$this->bViolation = true; // whole $_SERVER / $_ENV
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function IsEnvSuperGlobal(Node\Expr\Variable $oVar): bool
|
||||
{
|
||||
return is_string($oVar->name) && in_array($oVar->name, ['_SERVER', '_ENV'], true);
|
||||
}
|
||||
};
|
||||
$oTraverser = new NodeTraverser();
|
||||
$oTraverser->addVisitor($oVisitor);
|
||||
$oTraverser->traverse($aNodes);
|
||||
|
||||
return $oVisitor->bViolation;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check of the evaluated (non resolved) values: placeholders referencing a protected variable
|
||||
*
|
||||
* @param array $aValues evaluated $MySettings / $MyModuleSettings
|
||||
*/
|
||||
public function AreValuesReferencingProtectedVariables(array $aValues): bool
|
||||
{
|
||||
$aProtected = array_map('strtoupper', $this->aProtectedNames);
|
||||
$bFound = false;
|
||||
array_walk_recursive($aValues, function ($value, $key) use ($aProtected, &$bFound) {
|
||||
foreach ([$key, $value] as $item) {
|
||||
if (is_string($item) && preg_match_all(self::PLACEHOLDER_PATTERN, $item, $aMatches)) {
|
||||
if (count(array_intersect(array_map('strtoupper', $aMatches[1]), $aProtected)) > 0) {
|
||||
$bFound = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return $bFound;
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate a config file in isolation, without resolving placeholders
|
||||
*
|
||||
* @return array{0: array, 1: array} $MySettings and $MyModuleSettings
|
||||
*/
|
||||
public static function ReadRawArrays(string $sFile): array
|
||||
{
|
||||
$fnRead = static function () use ($sFile): array {
|
||||
$MySettings = [];
|
||||
$MyModuleSettings = [];
|
||||
$MyModules = [];
|
||||
ob_start();
|
||||
try {
|
||||
include $sFile;
|
||||
} finally {
|
||||
ob_end_clean();
|
||||
}
|
||||
|
||||
return [is_array($MySettings) ? $MySettings : [], is_array($MyModuleSettings) ? $MyModuleSettings : []];
|
||||
};
|
||||
try {
|
||||
return $fnRead();
|
||||
} catch (Throwable $e) {
|
||||
return [[], []];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool true if the submitted config must be refused
|
||||
*/
|
||||
public function Check(string $sConfig, string $sEvaluatedFile): bool
|
||||
{
|
||||
return $this->IsCodeReadingProtectedVariables($sConfig)
|
||||
|| $this->AreValuesReferencingProtectedVariables(self::ReadRawArrays($sEvaluatedFile));
|
||||
}
|
||||
}
|
||||
@@ -419,6 +419,9 @@ return array(
|
||||
'Combodo\\iTop\\Core\\Authentication\\Client\\OAuth\\OAuthClientProviderFactory' => $baseDir . '/sources/Core/Authentication/Client/OAuth/OAuthClientProviderFactory.php',
|
||||
'Combodo\\iTop\\Core\\Authentication\\Client\\OAuth\\OAuthClientProviderGoogle' => $baseDir . '/sources/Core/Authentication/Client/OAuth/OAuthClientProviderGoogle.php',
|
||||
'Combodo\\iTop\\Core\\CMDBChange\\CMDBChangeOrigin' => $baseDir . '/sources/Core/CMDBChange/CMDBChangeOrigin.php',
|
||||
'Combodo\\iTop\\Core\\Config\\Sensitive\\SensitiveConfigDiagnostic' => $baseDir . '/sources/Core/Config/Sensitive/SensitiveConfigDiagnostic.php',
|
||||
'Combodo\\iTop\\Core\\Config\\Sensitive\\SensitiveConfigStore' => $baseDir . '/sources/Core/Config/Sensitive/SensitiveConfigStore.php',
|
||||
'Combodo\\iTop\\Core\\Config\\Sensitive\\SensitiveParameters' => $baseDir . '/sources/Core/Config/Sensitive/SensitiveParameters.php',
|
||||
'Combodo\\iTop\\Core\\DbConnectionWrapper' => $baseDir . '/core/DbConnectionWrapper.php',
|
||||
'Combodo\\iTop\\Core\\Email\\EMailSymfony' => $baseDir . '/sources/Core/Email/EmailSymfony.php',
|
||||
'Combodo\\iTop\\Core\\Email\\EmailFactory' => $baseDir . '/sources/Core/Email/EmailFactory.php',
|
||||
|
||||
@@ -774,6 +774,9 @@ class ComposerStaticInit7f81b4a2a468a061c306af5e447a9a9f
|
||||
'Combodo\\iTop\\Core\\Authentication\\Client\\OAuth\\OAuthClientProviderFactory' => __DIR__ . '/../..' . '/sources/Core/Authentication/Client/OAuth/OAuthClientProviderFactory.php',
|
||||
'Combodo\\iTop\\Core\\Authentication\\Client\\OAuth\\OAuthClientProviderGoogle' => __DIR__ . '/../..' . '/sources/Core/Authentication/Client/OAuth/OAuthClientProviderGoogle.php',
|
||||
'Combodo\\iTop\\Core\\CMDBChange\\CMDBChangeOrigin' => __DIR__ . '/../..' . '/sources/Core/CMDBChange/CMDBChangeOrigin.php',
|
||||
'Combodo\\iTop\\Core\\Config\\Sensitive\\SensitiveConfigDiagnostic' => __DIR__ . '/../..' . '/sources/Core/Config/Sensitive/SensitiveConfigDiagnostic.php',
|
||||
'Combodo\\iTop\\Core\\Config\\Sensitive\\SensitiveConfigStore' => __DIR__ . '/../..' . '/sources/Core/Config/Sensitive/SensitiveConfigStore.php',
|
||||
'Combodo\\iTop\\Core\\Config\\Sensitive\\SensitiveParameters' => __DIR__ . '/../..' . '/sources/Core/Config/Sensitive/SensitiveParameters.php',
|
||||
'Combodo\\iTop\\Core\\DbConnectionWrapper' => __DIR__ . '/../..' . '/core/DbConnectionWrapper.php',
|
||||
'Combodo\\iTop\\Core\\Email\\EMailSymfony' => __DIR__ . '/../..' . '/sources/Core/Email/EmailSymfony.php',
|
||||
'Combodo\\iTop\\Core\\Email\\EmailFactory' => __DIR__ . '/../..' . '/sources/Core/Email/EmailFactory.php',
|
||||
|
||||
@@ -1034,6 +1034,12 @@ class ApplicationInstaller
|
||||
@mkdir($sConfigDir);
|
||||
@chmod($sConfigDir, 0770); // RWX for owner and group, nothing for others
|
||||
|
||||
// New installations initialize the store; upgrades only use an existing one.
|
||||
if ($sMode === 'install') {
|
||||
$oProductionEnv->InitializeSensitiveConfigStoreForInstallation($oConfig);
|
||||
}
|
||||
$oProductionEnv->PrepareSensitiveConfigStore($oConfig);
|
||||
|
||||
$oConfig->WriteToFile($sConfigFile);
|
||||
|
||||
// try to make the final config file read-only
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with iTop. If not, see <http://www.gnu.org/licenses/>
|
||||
|
||||
use Combodo\iTop\Core\Config\Sensitive\SensitiveConfigStore;
|
||||
use Combodo\iTop\Service\InterfaceDiscovery\InterfaceDiscovery;
|
||||
|
||||
require_once(APPROOT.'core/tar-itop.class.inc.php');
|
||||
@@ -285,7 +286,11 @@ class DBBackup
|
||||
$sFile = $sTmpFolder.'/'.$sExtraFileOrDir;
|
||||
$this->LogInfo("backup: adding directory '$sExtraFileOrDir'");
|
||||
SetupUtils::copydir($sExtraFullPath, $sFile);
|
||||
$this->PurgeSensitiveConfigFiles($sExtraFullPath, $sFile);
|
||||
$aRet[] = $sFile;
|
||||
} elseif ($this->IsSensitiveConfigFile($sExtraFullPath)) {
|
||||
// N°10293: the sensitive store is never part of an iTop backup
|
||||
$this->LogInfo("backup: ignoring sensitive resource '$sExtraFileOrDir'");
|
||||
} elseif (file_exists($sExtraFullPath)) {
|
||||
$sFile = $sTmpFolder.'/'.$sExtraFileOrDir;
|
||||
$this->LogInfo("backup: adding file '$sExtraFileOrDir'");
|
||||
@@ -303,6 +308,50 @@ class DBBackup
|
||||
return $aRet;
|
||||
}
|
||||
|
||||
/**
|
||||
* N°10293: the sensitive store (by name, or by real path) must never be backed up
|
||||
*/
|
||||
protected function IsSensitiveConfigFile(string $sPath): bool
|
||||
{
|
||||
if (basename($sPath) === SensitiveConfigStore::FILE_NAME) {
|
||||
return true;
|
||||
}
|
||||
$sRealPath = realpath($sPath);
|
||||
if ($sRealPath === false) {
|
||||
return false;
|
||||
}
|
||||
if (basename($sRealPath) === SensitiveConfigStore::FILE_NAME) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
$sStoreRealPath = realpath(SensitiveConfigStore::ForEnvironment(utils::GetCurrentEnvironment())->GetPath());
|
||||
} catch (Exception $e) {
|
||||
$sStoreRealPath = false;
|
||||
}
|
||||
|
||||
return ($sStoreRealPath !== false) && ($sRealPath === $sStoreRealPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove from a copied directory every copy of a sensitive store found in the source directory
|
||||
*/
|
||||
protected function PurgeSensitiveConfigFiles(string $sSourceDir, string $sCopiedDir): void
|
||||
{
|
||||
foreach (scandir($sSourceDir) ?: [] as $sEntry) {
|
||||
if ($sEntry === '.' || $sEntry === '..') {
|
||||
continue;
|
||||
}
|
||||
$sSource = $sSourceDir.'/'.$sEntry;
|
||||
$sCopy = $sCopiedDir.'/'.$sEntry;
|
||||
if (is_dir($sSource)) {
|
||||
$this->PurgeSensitiveConfigFiles($sSource, $sCopy);
|
||||
} elseif ($this->IsSensitiveConfigFile($sSource) && (is_file($sCopy) || is_link($sCopy))) {
|
||||
$this->LogInfo("backup: excluding sensitive resource '$sCopy' from the backup");
|
||||
@unlink($sCopy);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static function EscapeShellArg($sValue)
|
||||
{
|
||||
// Note: See comment from the 23-Apr-2004 03:30 in the PHP documentation
|
||||
|
||||
@@ -24,6 +24,9 @@
|
||||
* @license http://opensource.org/licenses/AGPL-3.0
|
||||
*/
|
||||
|
||||
use Combodo\iTop\Core\Config\Sensitive\SensitiveConfigStore;
|
||||
use Combodo\iTop\Core\Config\Sensitive\SensitiveParameters;
|
||||
|
||||
require_once APPROOT."setup/modulediscovery.class.inc.php";
|
||||
require_once APPROOT.'setup/modelfactory.class.inc.php';
|
||||
require_once APPROOT.'setup/compiler.class.inc.php';
|
||||
@@ -341,6 +344,8 @@ class RunTimeEnvironment
|
||||
|
||||
$sTargetConfigFile = APPCONF.$this->sTargetEnv.'/'.ITOP_CONFIG_FILE;
|
||||
|
||||
$this->PrepareSensitiveConfigStore($oConfig);
|
||||
|
||||
// Write the config file
|
||||
@chmod($sTargetConfigFile, 0770); // In case it exists: RWX for owner and group, nothing for others
|
||||
$oConfig->WriteToFile($sTargetConfigFile);
|
||||
@@ -357,6 +362,70 @@ class RunTimeEnvironment
|
||||
return array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Use an existing sensitive store without initializing a missing file.
|
||||
* To be called before writing the config file.
|
||||
*
|
||||
* @throws \ConfigException
|
||||
* @since 3.2.4 N°10293
|
||||
*/
|
||||
public function PrepareSensitiveConfigStore(Config $oConfig): void
|
||||
{
|
||||
$sEnv = preg_replace('/-build$/', '', $this->sFinalEnv);
|
||||
$oSensitiveStore = SensitiveConfigStore::ForEnvironment($sEnv);
|
||||
if ($oSensitiveStore->IsActive()) {
|
||||
if (!$oConfig->IsSensitiveStoreActive()) {
|
||||
$oConfig->BindSensitiveConfigStore($oSensitiveStore);
|
||||
}
|
||||
$oParameters = $oConfig->GetSensitiveParameters();
|
||||
foreach ($oParameters->GetRemoved() as $sId) {
|
||||
SetupLog::Warning("Sensitive parameter declassified through ".SensitiveParameters::LOCAL_FILE_NAME.": $sId");
|
||||
}
|
||||
if (!$oParameters->WriteMaterializedFile(SensitiveParameters::GetDefaultMaterializedFilePath())) {
|
||||
SetupLog::Warning('Could not write '.SensitiveParameters::GetDefaultMaterializedFilePath());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize a missing sensitive store before writing a new installation's configuration.
|
||||
* Existing installations and environment rebuilds must not call this method.
|
||||
*
|
||||
* @throws \ConfigException
|
||||
* @since 3.2.4 N°10293
|
||||
*/
|
||||
public function InitializeSensitiveConfigStoreForInstallation(Config $oConfig): void
|
||||
{
|
||||
$sEnv = preg_replace('/-build$/', '', $this->sFinalEnv);
|
||||
$oSensitiveStore = SensitiveConfigStore::ForEnvironment($sEnv);
|
||||
if (!$oSensitiveStore->IsActive()) {
|
||||
$this->InitializeSensitiveConfigStore($oConfig, $oSensitiveStore);
|
||||
if (!$oSensitiveStore->IsActive()) {
|
||||
throw new ConfigException('Could not initialize the sensitive configuration file for the new installation');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Explicitly create the sensitive store with the current values of the sensitive parameters.
|
||||
* Automatically called only for new installations, never for upgrades or environment rebuilds.
|
||||
* On failure, the store remains inactive and a warning is logged; the caller decides whether to abort.
|
||||
*
|
||||
* @since 3.2.4 N°10293
|
||||
*/
|
||||
protected function InitializeSensitiveConfigStore(Config $oConfig, SensitiveConfigStore $oSensitiveStore): void
|
||||
{
|
||||
try {
|
||||
$oParameters = SensitiveParameters::FromLocalFile($oConfig->GetCoreSensitiveKeys(), $oSensitiveStore->GetLocalFilePath());
|
||||
$aValues = $oConfig->GetSensitiveValuesForStore($oParameters->GetEffective());
|
||||
$oSensitiveStore->Initialize($aValues);
|
||||
// Names only, never values
|
||||
SetupLog::Info('Sensitive configuration file created: '.$oSensitiveStore->GetPath(), null, ['keys' => array_keys($aValues)]);
|
||||
} catch (ConfigException $e) {
|
||||
SetupLog::Warning('Sensitive configuration file not created: '.$e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Decide whether or not the given extension is selected for installation
|
||||
* @param iTopExtension $oExtension
|
||||
|
||||
76
setup/validate-sensitive-config.php
Normal file
76
setup/validate-sensitive-config.php
Normal file
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
if (PHP_SAPI !== 'cli') {
|
||||
// N°10293: filesystem-only tool, never reachable from the web
|
||||
http_response_code(403);
|
||||
exit;
|
||||
}
|
||||
|
||||
/*
|
||||
* @copyright Copyright (C) 2010-2026 Combodo SAS
|
||||
* @license http://opensource.org/licenses/AGPL-3.0
|
||||
*
|
||||
* N°10293 - Consistency check of the sensitive configuration (read only).
|
||||
* Usage: php setup/validate-sensitive-config.php [--check] [--env=<env>] [--help]
|
||||
* Exit codes: 0 = no error, 1 = at least one error, 2 = invalid usage
|
||||
*/
|
||||
|
||||
use Combodo\iTop\Core\Config\Sensitive\SensitiveConfigDiagnostic;
|
||||
use Combodo\iTop\Core\Config\Sensitive\SensitiveConfigStore;
|
||||
|
||||
require_once __DIR__.'/../approot.inc.php';
|
||||
require_once APPROOT.'core/config.class.inc.php';
|
||||
|
||||
const USAGE = "Usage: php setup/validate-sensitive-config.php [--check] [--env=<env>] [--help]\n"
|
||||
." --check Read-only consistency check (default)\n"
|
||||
." --env=<env> iTop environment (default: production)\n"
|
||||
." --help Display this help\n"
|
||||
."Exit codes: 0 = no error, 1 = at least one error, 2 = invalid usage\n"
|
||||
."Run it as the web server user to check the permissions as seen by iTop (e.g. sudo -u www-data php ...).\n";
|
||||
|
||||
$sEnv = 'production';
|
||||
foreach (array_slice($argv, 1) as $sArg) {
|
||||
if ($sArg === '--help' || $sArg === '-h') {
|
||||
echo USAGE;
|
||||
exit(0);
|
||||
} elseif ($sArg === '--check') {
|
||||
continue;
|
||||
} elseif (str_starts_with($sArg, '--env=')) {
|
||||
$sEnv = substr($sArg, strlen('--env='));
|
||||
} else {
|
||||
fwrite(STDERR, "Unknown option: ".preg_replace('/[^\w=\-.\/]/', '?', $sArg)."\n".USAGE);
|
||||
exit(2);
|
||||
}
|
||||
}
|
||||
if (!preg_match('/^[A-Za-z0-9_\-]+$/', $sEnv)) {
|
||||
fwrite(STDERR, "Invalid environment name\n");
|
||||
exit(2);
|
||||
}
|
||||
|
||||
try {
|
||||
$sConfigFile = APPCONF.$sEnv.'/config-itop.php';
|
||||
$oStore = SensitiveConfigStore::ForEnvironment($sEnv);
|
||||
echo "[INFO] STATUS: environment=$sEnv, store=".$oStore->GetPath().', active='.($oStore->IsActive() ? 'yes' : 'no')."\n";
|
||||
|
||||
$oDiagnostic = new SensitiveConfigDiagnostic($sConfigFile, $oStore);
|
||||
$aFindings = $oDiagnostic->Run();
|
||||
foreach ($aFindings as $aFinding) {
|
||||
$sKey = ($aFinding['key'] === '') ? '' : ' '.$aFinding['key'];
|
||||
echo "[{$aFinding['severity']}] {$aFinding['code']}$sKey: {$aFinding['message']}\n";
|
||||
}
|
||||
foreach ($oDiagnostic->GetPlan() as $aStep) {
|
||||
echo "[PLAN] {$aStep['action']} {$aStep['key']}\n";
|
||||
}
|
||||
if (count($oDiagnostic->GetPlan()) > 0) {
|
||||
echo "[INFO] PLAN_NOT_APPLIED: the reconciliation plan is informative only, CONFLICT entries require an explicit decision\n";
|
||||
}
|
||||
exit(SensitiveConfigDiagnostic::HasErrors($aFindings) ? 1 : 0);
|
||||
} catch (Throwable $e) {
|
||||
// ConfigException messages never contain values (names, paths and line numbers only)
|
||||
if ($e instanceof ConfigException) {
|
||||
echo '[ERROR] E_STORE_INVALID: '.$e->getMessage()."\n";
|
||||
} else {
|
||||
echo '[ERROR] E_INTERNAL: unexpected '.get_class($e).' at '.basename($e->getFile()).':'.$e->getLine()."\n";
|
||||
}
|
||||
exit(1);
|
||||
}
|
||||
271
sources/Core/Config/Sensitive/SensitiveConfigDiagnostic.php
Normal file
271
sources/Core/Config/Sensitive/SensitiveConfigDiagnostic.php
Normal file
@@ -0,0 +1,271 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* @copyright Copyright (C) 2010-2026 Combodo SAS
|
||||
* @license http://opensource.org/licenses/AGPL-3.0
|
||||
*/
|
||||
|
||||
namespace Combodo\iTop\Core\Config\Sensitive;
|
||||
|
||||
use Config;
|
||||
use ConfigException;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Consistency check between config-itop.php and the sensitive store (N°10293).
|
||||
* Read only. Findings and plan contain parameter NAMES only, never values.
|
||||
*
|
||||
* @since 3.2.4 N°10293
|
||||
*/
|
||||
final class SensitiveConfigDiagnostic
|
||||
{
|
||||
public const SEVERITY_INFO = 'INFO';
|
||||
public const SEVERITY_WARNING = 'WARNING';
|
||||
public const SEVERITY_ERROR = 'ERROR';
|
||||
|
||||
public const PLAN_MOVE = 'MOVE';
|
||||
public const PLAN_DEDUPE = 'DEDUPE';
|
||||
public const PLAN_CONFLICT = 'CONFLICT';
|
||||
|
||||
private const PLACEHOLDER_PATTERN = '/%(env|server)\(\w+\)/';
|
||||
|
||||
/** @var array<int, array{severity: string, code: string, key: string, message: string}> */
|
||||
private array $aFindings = [];
|
||||
/** @var array<int, array{action: string, key: string}> */
|
||||
private array $aPlan = [];
|
||||
private Config $oDefaults;
|
||||
|
||||
public function __construct(
|
||||
private readonly string $sConfigFile,
|
||||
private readonly SensitiveConfigStore $oStore,
|
||||
private readonly ?string $sLocalFile = null,
|
||||
private readonly ?array $aEnv = null
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, array{severity: string, code: string, key: string, message: string}>
|
||||
*/
|
||||
public function Run(): array
|
||||
{
|
||||
$this->aFindings = [];
|
||||
$this->aPlan = [];
|
||||
|
||||
[$aFileSettings, $aFileModuleSettings] = $this->ReadConfigFile();
|
||||
$this->oDefaults = $oDefaults = new Config(null, false);
|
||||
|
||||
if (!$this->oStore->IsActive()) {
|
||||
$this->Add(self::SEVERITY_INFO, 'SENSITIVE_STORE_INACTIVE', '', 'Sensitive store not found, feature inactive: '.$this->oStore->GetPath());
|
||||
$oParameters = new SensitiveParameters($oDefaults->GetCoreSensitiveKeys());
|
||||
foreach ($oParameters->GetBaseline() as $sId) {
|
||||
if ($this->IsInFile($sId, $aFileSettings, $aFileModuleSettings)) {
|
||||
$this->Add(self::SEVERITY_INFO, 'PLAINTEXT_SENSITIVE', $sId, 'Sensitive parameter still stored in the standard configuration file');
|
||||
}
|
||||
}
|
||||
|
||||
return $this->aFindings;
|
||||
}
|
||||
|
||||
$this->CheckPermissions();
|
||||
try {
|
||||
$aStoreRaw = $this->oStore->GetRawValues();
|
||||
} catch (ConfigException $e) {
|
||||
// The message holds the path and line number only (see SensitiveConfigStore)
|
||||
$this->Add(self::SEVERITY_ERROR, 'E_STORE_INVALID', '', $e->getMessage());
|
||||
|
||||
return $this->aFindings;
|
||||
}
|
||||
|
||||
$oParameters = SensitiveParameters::FromLocalFile($oDefaults->GetCoreSensitiveKeys(), $this->sLocalFile ?? $this->oStore->GetLocalFilePath());
|
||||
foreach ($oParameters->GetRemoved() as $sId) {
|
||||
$this->Add(self::SEVERITY_INFO, 'I_DECLASSIFIED', $sId, 'Parameter declassified through '.SensitiveParameters::LOCAL_FILE_NAME);
|
||||
}
|
||||
foreach (array_keys($oParameters->GetInvalidLines()) as $iLine) {
|
||||
$this->Add(self::SEVERITY_WARNING, 'W_LOCAL_SYNTAX', 'line '.$iLine, 'Invalid line ignored in '.SensitiveParameters::LOCAL_FILE_NAME);
|
||||
}
|
||||
|
||||
$aEffective = $oParameters->GetEffective();
|
||||
foreach ($aEffective as $sId) {
|
||||
$bInStore = array_key_exists($sId, $aStoreRaw);
|
||||
$bInFile = $this->IsInFile($sId, $aFileSettings, $aFileModuleSettings);
|
||||
if ($bInStore && $bInFile) {
|
||||
$bSame = ($aStoreRaw[$sId] === $this->GetFileValue($sId, $aFileSettings, $aFileModuleSettings));
|
||||
$this->Add(self::SEVERITY_WARNING, 'W_DUPLICATE', $sId, 'Defined in both files, the value of the standard configuration file is ignored');
|
||||
$this->aPlan[] = ['action' => $bSame ? self::PLAN_DEDUPE : self::PLAN_CONFLICT, 'key' => $sId];
|
||||
} elseif ($bInFile) {
|
||||
$this->Add(self::SEVERITY_ERROR, 'E_MISPLACED', $sId, 'Only defined in the standard configuration file, where it is ignored');
|
||||
$this->aPlan[] = ['action' => self::PLAN_MOVE, 'key' => $sId];
|
||||
} elseif (!$bInStore) {
|
||||
$bIsCore = $oDefaults->IsProperty($sId);
|
||||
if (in_array($sId, SensitiveParameters::LEGACY_BASELINE, true) || ($bIsCore && $oDefaults->GetDefault($sId) === null)) {
|
||||
$this->Add(self::SEVERITY_ERROR, 'E_MISSING', $sId, 'Missing from the sensitive store and without usable default');
|
||||
}
|
||||
}
|
||||
if ($bInStore && $oDefaults->IsProperty($sId) && !$this->IsTypeCompatible($oDefaults->GetDescription($sId)['type'], $aStoreRaw[$sId])) {
|
||||
$this->Add(self::SEVERITY_WARNING, 'W_TYPE', $sId, 'Value type inconsistent with the declared type ('.$oDefaults->GetDescription($sId)['type'].')');
|
||||
}
|
||||
}
|
||||
|
||||
$bPlaceholdersEnabled = $this->ArePlaceholdersEnabled();
|
||||
foreach ($aStoreRaw as $sId => $value) {
|
||||
$bKnown = $oDefaults->IsProperty($sId) || in_array($sId, SensitiveParameters::LEGACY_BASELINE, true) || preg_match('/^[^.]+\.[^.].*$/', $sId);
|
||||
if (!$bKnown) {
|
||||
$this->Add(self::SEVERITY_WARNING, 'W_UNKNOWN', $sId, 'Unknown parameter (probable typo)');
|
||||
}
|
||||
if (!in_array($sId, $aEffective, true)) {
|
||||
$this->Add(self::SEVERITY_WARNING, 'W_ORPHAN', $sId, 'Not in the effective sensitive set: ignored');
|
||||
}
|
||||
if (!$bPlaceholdersEnabled && $this->ContainsPlaceholder($value)) {
|
||||
$this->Add(self::SEVERITY_WARNING, 'W_PLACEHOLDER_DISABLED', $sId, 'Placeholder found but ITOP_CONFIG_PLACEHOLDERS is not set in this context');
|
||||
}
|
||||
}
|
||||
|
||||
return $this->aFindings;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, array{action: string, key: string}> reconciliation plan (never applied by this class)
|
||||
*/
|
||||
public function GetPlan(): array
|
||||
{
|
||||
return $this->aPlan;
|
||||
}
|
||||
|
||||
public static function HasErrors(array $aFindings): bool
|
||||
{
|
||||
foreach ($aFindings as $aFinding) {
|
||||
if ($aFinding['severity'] === self::SEVERITY_ERROR) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remediation commands for the store permissions, according to the OS
|
||||
*/
|
||||
public static function GetRemediationCommand(string $sPath, string $sOsFamily = PHP_OS_FAMILY): string
|
||||
{
|
||||
$sArg = escapeshellarg($sPath);
|
||||
if ($sOsFamily === 'Windows') {
|
||||
return 'icacls "'.$sPath.'" /inheritance:r /grant:r "SYSTEM:F" "Administrators:F" "IIS_IUSRS:R"';
|
||||
}
|
||||
|
||||
return "chown root:<web-server-group> $sArg && chmod 0440 $sArg";
|
||||
}
|
||||
|
||||
private function CheckPermissions(): void
|
||||
{
|
||||
$sPath = $this->oStore->GetPath();
|
||||
$sFix = ' - remediation: '.self::GetRemediationCommand($sPath);
|
||||
if (!is_readable($sPath)) {
|
||||
$this->Add(self::SEVERITY_ERROR, 'E_PERMS_UNREADABLE', '', 'Sensitive store not readable by the current user (run this tool as the web server user)'.$sFix);
|
||||
|
||||
return;
|
||||
}
|
||||
if (is_writable($sPath)) {
|
||||
$this->Add(self::SEVERITY_WARNING, 'W_PERMS_WRITABLE', '', 'Sensitive store writable by the current user'.$sFix);
|
||||
}
|
||||
if (PHP_OS_FAMILY !== 'Windows' && (fileperms($sPath) & 0004)) {
|
||||
$this->Add(self::SEVERITY_WARNING, 'W_PERMS_WORLD_READABLE', '', 'Sensitive store readable by others'.$sFix);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0: array, 1: array} $MySettings and $MyModuleSettings of the config file (evaluated in isolation)
|
||||
*/
|
||||
private function ReadConfigFile(): array
|
||||
{
|
||||
if (!is_file($this->sConfigFile) || !is_readable($this->sConfigFile)) {
|
||||
throw new ConfigException('Could not read the configuration file', ['file' => $this->sConfigFile]);
|
||||
}
|
||||
$sFile = $this->sConfigFile;
|
||||
$fnRead = static function () use ($sFile): array {
|
||||
$MySettings = [];
|
||||
$MyModuleSettings = [];
|
||||
$MyModules = [];
|
||||
ob_start();
|
||||
try {
|
||||
include $sFile;
|
||||
} finally {
|
||||
ob_end_clean();
|
||||
}
|
||||
|
||||
return [is_array($MySettings) ? $MySettings : [], is_array($MyModuleSettings) ? $MyModuleSettings : []];
|
||||
};
|
||||
try {
|
||||
return $fnRead();
|
||||
} catch (Throwable $e) {
|
||||
throw new ConfigException('Error in configuration file', ['file' => $this->sConfigFile, 'line' => $e->getLine()]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0: string, 1?: string, 2?: string}
|
||||
*/
|
||||
private function SplitId(string $sId): array
|
||||
{
|
||||
if ($this->oDefaults->IsProperty($sId) || in_array($sId, SensitiveParameters::LEGACY_BASELINE, true) || !str_contains($sId, '.')) {
|
||||
return ['setting'];
|
||||
}
|
||||
[$sModule, $sProperty] = explode('.', $sId, 2);
|
||||
|
||||
return ['module', $sModule, $sProperty];
|
||||
}
|
||||
|
||||
private function IsInFile(string $sId, array $aFileSettings, array $aFileModuleSettings): bool
|
||||
{
|
||||
$aSplit = $this->SplitId($sId);
|
||||
if ($aSplit[0] === 'setting') {
|
||||
return array_key_exists($sId, $aFileSettings);
|
||||
}
|
||||
|
||||
return isset($aFileModuleSettings[$aSplit[1]]) && is_array($aFileModuleSettings[$aSplit[1]]) && array_key_exists($aSplit[2], $aFileModuleSettings[$aSplit[1]]);
|
||||
}
|
||||
|
||||
private function GetFileValue(string $sId, array $aFileSettings, array $aFileModuleSettings): mixed
|
||||
{
|
||||
$aSplit = $this->SplitId($sId);
|
||||
|
||||
return ($aSplit[0] === 'setting') ? $aFileSettings[$sId] : $aFileModuleSettings[$aSplit[1]][$aSplit[2]];
|
||||
}
|
||||
|
||||
private function IsTypeCompatible(string $sType, mixed $value): bool
|
||||
{
|
||||
return match ($sType) {
|
||||
'array' => is_array($value),
|
||||
'string', 'integer', 'float', 'bool' => is_scalar($value) || $value === null,
|
||||
default => true,
|
||||
};
|
||||
}
|
||||
|
||||
private function ContainsPlaceholder(mixed $value): bool
|
||||
{
|
||||
if (is_array($value)) {
|
||||
foreach ($value as $item) {
|
||||
if ($this->ContainsPlaceholder($item)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return is_string($value) && preg_match(self::PLACEHOLDER_PATTERN, $value) === 1;
|
||||
}
|
||||
|
||||
private function ArePlaceholdersEnabled(): bool
|
||||
{
|
||||
if ($this->aEnv !== null) {
|
||||
return !empty($this->aEnv['ITOP_CONFIG_PLACEHOLDERS']);
|
||||
}
|
||||
|
||||
return !empty(getenv('ITOP_CONFIG_PLACEHOLDERS')) || !empty($_ENV['ITOP_CONFIG_PLACEHOLDERS']) || !empty($_SERVER['ITOP_CONFIG_PLACEHOLDERS']);
|
||||
}
|
||||
|
||||
private function Add(string $sSeverity, string $sCode, string $sKey, string $sMessage): void
|
||||
{
|
||||
$this->aFindings[] = ['severity' => $sSeverity, 'code' => $sCode, 'key' => $sKey, 'message' => $sMessage];
|
||||
}
|
||||
}
|
||||
266
sources/Core/Config/Sensitive/SensitiveConfigStore.php
Normal file
266
sources/Core/Config/Sensitive/SensitiveConfigStore.php
Normal file
@@ -0,0 +1,266 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* @copyright Copyright (C) 2010-2026 Combodo SAS
|
||||
* @license http://opensource.org/licenses/AGPL-3.0
|
||||
*/
|
||||
|
||||
namespace Combodo\iTop\Core\Config\Sensitive;
|
||||
|
||||
use ConfigException;
|
||||
use ConfigPlaceholdersResolver;
|
||||
use Symfony\Component\Yaml\Exception\ParseException;
|
||||
use Symfony\Component\Yaml\Yaml;
|
||||
|
||||
/**
|
||||
* Access to the sensitive settings file of an environment (N°10293).
|
||||
* At runtime the file is only read. New installations create it with {@see Initialize()};
|
||||
* existing installations require explicit activation and are never split automatically.
|
||||
*
|
||||
* The file is YAML (no code execution), a flat mapping "identifier => value".
|
||||
* Error messages NEVER contain any excerpt of the file content.
|
||||
*
|
||||
* @since 3.2.4 N°10293
|
||||
*/
|
||||
final class SensitiveConfigStore
|
||||
{
|
||||
public const FILE_NAME = 'sensitive-config-itop.yml';
|
||||
public const ENV_VAR = 'ITOP_SENSITIVE_CONFIG_PATH';
|
||||
private const ENV_NAME_PATTERN = '/^[A-Za-z0-9_\-]+$/';
|
||||
|
||||
/** @var array<string, mixed>|null raw values, loaded lazily */
|
||||
private ?array $aRawValues = null;
|
||||
private ?array $aResolvedValues = null;
|
||||
|
||||
/**
|
||||
* @param string $sPath YAML file
|
||||
* @param \ConfigPlaceholdersResolver|null $oResolver
|
||||
* @param string|null $sLocalFile classification overrides file, null for {@see SensitiveParameters::GetDefaultLocalFilePath()}
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly string $sPath,
|
||||
private readonly ?ConfigPlaceholdersResolver $oResolver = null,
|
||||
private readonly ?string $sLocalFile = null
|
||||
) {
|
||||
}
|
||||
|
||||
public function GetLocalFilePath(): string
|
||||
{
|
||||
return $this->sLocalFile ?? SensitiveParameters::GetDefaultLocalFilePath();
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws \ConfigException if the environment name or the root directory is invalid
|
||||
*/
|
||||
public static function ForEnvironment(string $sEnv): self
|
||||
{
|
||||
if (!preg_match(self::ENV_NAME_PATTERN, $sEnv)) {
|
||||
throw new ConfigException('Invalid environment name for the sensitive configuration');
|
||||
}
|
||||
|
||||
return new self(self::GetRootDir().$sEnv.'/'.self::FILE_NAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string root directory, with a trailing slash
|
||||
* @throws \ConfigException if the env var is a relative path
|
||||
*/
|
||||
public static function GetRootDir(): string
|
||||
{
|
||||
$sRoot = getenv(self::ENV_VAR);
|
||||
if ($sRoot === false || $sRoot === '') {
|
||||
$sRoot = $_SERVER[self::ENV_VAR] ?? ($_ENV[self::ENV_VAR] ?? '');
|
||||
}
|
||||
$sRoot = is_string($sRoot) ? trim($sRoot) : '';
|
||||
if ($sRoot === '') {
|
||||
return APPCONF;
|
||||
}
|
||||
if (!preg_match('#^(/|[A-Za-z]:[\\\\/]|\\\\\\\\)#', $sRoot)) {
|
||||
throw new ConfigException(self::ENV_VAR.' must be an absolute path');
|
||||
}
|
||||
|
||||
return rtrim($sRoot, '/\\').'/';
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null environment when the file is APPCONF/<env>/config-itop.php ("-build" suffix removed), null otherwise
|
||||
*/
|
||||
public static function GetEnvironmentFromConfigFile(?string $sConfigFile): ?string
|
||||
{
|
||||
if (empty($sConfigFile) || !defined('APPCONF')) {
|
||||
return null;
|
||||
}
|
||||
$sConfDir = realpath(APPCONF);
|
||||
$sFileDir = realpath(dirname($sConfigFile));
|
||||
if ($sConfDir === false || $sFileDir === false || dirname($sFileDir) !== $sConfDir) {
|
||||
return null;
|
||||
}
|
||||
$sEnv = basename($sFileDir);
|
||||
if (str_ends_with($sEnv, '-build')) {
|
||||
$sEnv = substr($sEnv, 0, -strlen('-build'));
|
||||
}
|
||||
|
||||
return preg_match(self::ENV_NAME_PATTERN, $sEnv) ? $sEnv : null;
|
||||
}
|
||||
|
||||
public function GetPath(): string
|
||||
{
|
||||
return $this->sPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Opt-in: the feature is active only when the file exists
|
||||
*/
|
||||
public function IsActive(): bool
|
||||
{
|
||||
return is_file($this->sPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed> raw values (placeholders not resolved)
|
||||
* @throws \ConfigException
|
||||
*/
|
||||
public function GetRawValues(): array
|
||||
{
|
||||
if ($this->aRawValues === null) {
|
||||
$this->aRawValues = $this->Parse();
|
||||
}
|
||||
|
||||
return $this->aRawValues;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed> values with %env()% / %server()% placeholders resolved
|
||||
* @throws \ConfigException
|
||||
*/
|
||||
public function GetValues(): array
|
||||
{
|
||||
if ($this->aResolvedValues === null) {
|
||||
$oResolver = $this->oResolver ?? new ConfigPlaceholdersResolver();
|
||||
$aValues = [];
|
||||
foreach ($this->GetRawValues() as $sKey => $value) {
|
||||
try {
|
||||
$aValues[$sKey] = $oResolver->Resolve($value);
|
||||
} catch (ConfigException $e) {
|
||||
throw new ConfigException('Unresolved placeholder in the sensitive configuration', ['file' => $this->sPath, 'key' => $sKey]);
|
||||
}
|
||||
}
|
||||
$this->aResolvedValues = $aValues;
|
||||
}
|
||||
|
||||
return $this->aResolvedValues;
|
||||
}
|
||||
|
||||
/** @return string[] */
|
||||
public function GetKeys(): array
|
||||
{
|
||||
return array_keys($this->GetRawValues());
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string[] names of the env / server variables referenced by placeholders (D-035)
|
||||
* @throws \ConfigException
|
||||
*/
|
||||
public function GetPlaceholderVariableNames(): array
|
||||
{
|
||||
$aNames = [];
|
||||
$aRaw = $this->GetRawValues();
|
||||
array_walk_recursive($aRaw, function ($value) use (&$aNames) {
|
||||
if (is_string($value) && preg_match_all('/%(?:env|server)\((\w+)\)/', $value, $aMatches)) {
|
||||
array_push($aNames, ...$aMatches[1]);
|
||||
}
|
||||
});
|
||||
$aNames = array_values(array_unique($aNames));
|
||||
sort($aNames);
|
||||
|
||||
return $aNames;
|
||||
}
|
||||
|
||||
public function Has(string $sId): bool
|
||||
{
|
||||
return array_key_exists($sId, $this->GetRawValues());
|
||||
}
|
||||
|
||||
public function Get(string $sId): mixed
|
||||
{
|
||||
return $this->GetValues()[$sId] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the file with its initial values (setup). An existing file is never overwritten.
|
||||
* The file is made read-only (0440), as the config file written by the setup.
|
||||
*
|
||||
* @param array<string, mixed> $aValues identifier => value
|
||||
*
|
||||
* @throws \ConfigException if the file already exists or cannot be written
|
||||
* @since 3.2.4 N°10293
|
||||
*/
|
||||
public function Initialize(array $aValues): void
|
||||
{
|
||||
if (file_exists($this->sPath)) {
|
||||
throw new ConfigException('The sensitive configuration file already exists', ['file' => $this->sPath]);
|
||||
}
|
||||
$sDir = dirname($this->sPath);
|
||||
if (!is_dir($sDir) && !@mkdir($sDir, 0770, true) && !is_dir($sDir)) {
|
||||
throw new ConfigException('Could not create the directory of the sensitive configuration file', ['file' => $this->sPath]);
|
||||
}
|
||||
if (!is_writable($sDir)) {
|
||||
// Checked first: tempnam() would silently fall back to the system temporary directory
|
||||
throw new ConfigException('Could not write the sensitive configuration file', ['file' => $this->sPath]);
|
||||
}
|
||||
|
||||
ksort($aValues);
|
||||
$sContent = "# Sensitive configuration of iTop, managed by the system administrator.\n"
|
||||
."# Parameters listed here are ignored in config-itop.php and cannot be modified from the iTop console.\n"
|
||||
."# Values support the %env(VAR)% and %server(VAR)% placeholders.\n"
|
||||
.(($aValues === []) ? '' : Yaml::dump($aValues, 4, 2, Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE | Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK));
|
||||
|
||||
// Written aside then renamed: the file is never visible partially written nor with loose permissions
|
||||
$sTmpFile = @tempnam($sDir, '.'.self::FILE_NAME.'.');
|
||||
if ($sTmpFile === false || @file_put_contents($sTmpFile, $sContent, LOCK_EX) === false || !@chmod($sTmpFile, 0440)) {
|
||||
if (is_string($sTmpFile) && is_file($sTmpFile)) {
|
||||
@unlink($sTmpFile);
|
||||
}
|
||||
throw new ConfigException('Could not write the sensitive configuration file', ['file' => $this->sPath]);
|
||||
}
|
||||
if (file_exists($this->sPath) || !@rename($sTmpFile, $this->sPath)) {
|
||||
@unlink($sTmpFile);
|
||||
throw new ConfigException('Could not write the sensitive configuration file', ['file' => $this->sPath]);
|
||||
}
|
||||
$this->aRawValues = null;
|
||||
$this->aResolvedValues = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws \ConfigException
|
||||
*/
|
||||
private function Parse(): array
|
||||
{
|
||||
if (!is_file($this->sPath)) {
|
||||
return [];
|
||||
}
|
||||
if (!is_readable($this->sPath)) {
|
||||
throw new ConfigException('Could not read the sensitive configuration file', ['file' => $this->sPath]);
|
||||
}
|
||||
try {
|
||||
// No PARSE_OBJECT / PARSE_OBJECT_FOR_MAP / PARSE_CONSTANT / PARSE_CUSTOM_TAGS: data only
|
||||
$aData = Yaml::parseFile($this->sPath, Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE);
|
||||
} catch (ParseException $e) {
|
||||
// Never chain nor quote the Symfony message: it contains the offending line, which may hold a secret
|
||||
throw new ConfigException('Invalid YAML in the sensitive configuration file', ['file' => $this->sPath, 'line' => $e->getParsedLine()]);
|
||||
}
|
||||
if ($aData === null || $aData === []) {
|
||||
return [];
|
||||
}
|
||||
if (!is_array($aData) || array_is_list($aData)) {
|
||||
throw new ConfigException('The sensitive configuration file must contain a mapping of parameter names to values', ['file' => $this->sPath]);
|
||||
}
|
||||
foreach (array_keys($aData) as $key) {
|
||||
if (!is_string($key) || $key === '') {
|
||||
throw new ConfigException('The sensitive configuration file contains a non-string key', ['file' => $this->sPath]);
|
||||
}
|
||||
}
|
||||
|
||||
return $aData;
|
||||
}
|
||||
}
|
||||
150
sources/Core/Config/Sensitive/SensitiveParameters.php
Normal file
150
sources/Core/Config/Sensitive/SensitiveParameters.php
Normal file
@@ -0,0 +1,150 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* @copyright Copyright (C) 2010-2026 Combodo SAS
|
||||
* @license http://opensource.org/licenses/AGPL-3.0
|
||||
*/
|
||||
|
||||
namespace Combodo\iTop\Core\Config\Sensitive;
|
||||
|
||||
/**
|
||||
* Classification of sensitive parameters (N°10293).
|
||||
*
|
||||
* Effective set = baseline (coded, never editable from the UI) ∪ additions (.local) − removals (.local).
|
||||
* A removal always wins over an addition.
|
||||
*
|
||||
* @since 3.2.4 N°10293
|
||||
*/
|
||||
final class SensitiveParameters
|
||||
{
|
||||
/** Legacy settings (not declared in Config::$m_aSettings) classified as sensitive */
|
||||
public const LEGACY_BASELINE = ['encryption_key'];
|
||||
/** Module settings classified as sensitive, as "<module>.<property>" */
|
||||
public const MODULE_BASELINE = [
|
||||
'authent-ldap.default_pwd',
|
||||
'combodo-saml.x509cert',
|
||||
'combodo-saml.privatekey',
|
||||
];
|
||||
public const LOCAL_FILE_NAME = 'sensitive.parameters.env.local';
|
||||
public const MATERIALIZED_FILE_NAME = 'sensitive.parameters.env';
|
||||
public const ID_PATTERN = '/^[A-Za-z0-9_][A-Za-z0-9_.\-]*$/';
|
||||
public const MATERIALIZED_HEADER = '# GENERATED FILE - DO NOT EDIT - overrides go to '.self::LOCAL_FILE_NAME;
|
||||
|
||||
/** @var string[] */
|
||||
private array $aBaseline;
|
||||
/** @var string[] */
|
||||
private array $aAdded = [];
|
||||
/** @var string[] */
|
||||
private array $aRemoved = [];
|
||||
/** @var array<int, string> line number => raw line */
|
||||
private array $aInvalidLines = [];
|
||||
|
||||
/**
|
||||
* @param string[] $aCoreSensitiveKeys keys of Config::$m_aSettings flagged as sensitive
|
||||
* @param string|null $sLocalContent content of the .local override file (null = no file)
|
||||
*/
|
||||
public function __construct(array $aCoreSensitiveKeys, ?string $sLocalContent = null)
|
||||
{
|
||||
$aBaseline = array_unique(array_merge($aCoreSensitiveKeys, self::LEGACY_BASELINE, self::MODULE_BASELINE));
|
||||
sort($aBaseline);
|
||||
$this->aBaseline = $aBaseline;
|
||||
if ($sLocalContent !== null) {
|
||||
$this->ParseLocalContent($sLocalContent);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string[] $aCoreSensitiveKeys
|
||||
*/
|
||||
public static function FromLocalFile(array $aCoreSensitiveKeys, ?string $sLocalFile = null): self
|
||||
{
|
||||
$sLocalFile ??= self::GetDefaultLocalFilePath();
|
||||
$sContent = (is_file($sLocalFile) && is_readable($sLocalFile)) ? file_get_contents($sLocalFile) : null;
|
||||
|
||||
return new self($aCoreSensitiveKeys, $sContent === false ? null : $sContent);
|
||||
}
|
||||
|
||||
public static function GetDefaultLocalFilePath(): string
|
||||
{
|
||||
return APPROOT.'data/'.self::LOCAL_FILE_NAME;
|
||||
}
|
||||
|
||||
public static function GetDefaultMaterializedFilePath(): string
|
||||
{
|
||||
return APPROOT.'data/'.self::MATERIALIZED_FILE_NAME;
|
||||
}
|
||||
|
||||
private function ParseLocalContent(string $sContent): void
|
||||
{
|
||||
foreach (preg_split('/\R/', $sContent) as $iIndex => $sRawLine) {
|
||||
$sLine = trim($sRawLine);
|
||||
if ($sLine === '' || str_starts_with($sLine, '#')) {
|
||||
continue;
|
||||
}
|
||||
$bRemove = false;
|
||||
if ($sLine[0] === '+' || $sLine[0] === '-') {
|
||||
$bRemove = ($sLine[0] === '-');
|
||||
$sLine = substr($sLine, 1);
|
||||
}
|
||||
if (!preg_match(self::ID_PATTERN, $sLine)) {
|
||||
$this->aInvalidLines[$iIndex + 1] = $sRawLine;
|
||||
continue;
|
||||
}
|
||||
if ($bRemove) {
|
||||
$this->aRemoved[$sLine] = $sLine;
|
||||
} else {
|
||||
$this->aAdded[$sLine] = $sLine;
|
||||
}
|
||||
}
|
||||
$this->aRemoved = array_values($this->aRemoved);
|
||||
$this->aAdded = array_values($this->aAdded);
|
||||
}
|
||||
|
||||
/** @return string[] */
|
||||
public function GetBaseline(): array
|
||||
{
|
||||
return $this->aBaseline;
|
||||
}
|
||||
|
||||
/** @return string[] */
|
||||
public function GetAdded(): array
|
||||
{
|
||||
return $this->aAdded;
|
||||
}
|
||||
|
||||
/** @return string[] identifiers removed through .local (as written) */
|
||||
public function GetRemoved(): array
|
||||
{
|
||||
return $this->aRemoved;
|
||||
}
|
||||
|
||||
/** @return array<int, string> line number => raw line */
|
||||
public function GetInvalidLines(): array
|
||||
{
|
||||
return $this->aInvalidLines;
|
||||
}
|
||||
|
||||
/** @return string[] sorted effective set */
|
||||
public function GetEffective(): array
|
||||
{
|
||||
$aEffective = array_values(array_diff(array_unique(array_merge($this->aBaseline, $this->aAdded)), $this->aRemoved));
|
||||
sort($aEffective);
|
||||
|
||||
return $aEffective;
|
||||
}
|
||||
|
||||
public function IsSensitive(string $sId): bool
|
||||
{
|
||||
return in_array($sId, $this->GetEffective(), true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Regenerate the (informative only) materialized list
|
||||
*/
|
||||
public function WriteMaterializedFile(string $sPath): bool
|
||||
{
|
||||
$sContent = self::MATERIALIZED_HEADER."\n".implode("\n", $this->aBaseline)."\n";
|
||||
|
||||
return file_put_contents($sPath, $sContent, LOCK_EX) !== false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* @copyright Copyright (C) 2010-2026 Combodo SAS
|
||||
* @license http://opensource.org/licenses/AGPL-3.0
|
||||
*/
|
||||
|
||||
namespace Combodo\iTop\Test\UnitTest\Core\SensitiveConfig;
|
||||
|
||||
use Combodo\iTop\Test\UnitTest\ItopTestCase;
|
||||
use Config;
|
||||
use ConfigException;
|
||||
|
||||
require_once __DIR__.'/SensitiveConfigTestTrait.php';
|
||||
|
||||
class ConfigSensitiveTest extends ItopTestCase
|
||||
{
|
||||
use SensitiveConfigTestTrait;
|
||||
|
||||
private const FILE_SETTINGS = [
|
||||
'db_host' => 'localhost',
|
||||
'db_user' => 'itop',
|
||||
'db_pwd' => 'file_pwd',
|
||||
'encryption_key' => 'file_key',
|
||||
'email_transport_smtp.password' => 'file_smtp',
|
||||
'max_display_limit' => 20,
|
||||
'app_root_url' => 'http://%server(SERVER_NAME)?:localhost%/itop/',
|
||||
'application.secret' => 'fixed_application_secret',
|
||||
];
|
||||
private const FILE_MODULE_SETTINGS = [
|
||||
'authent-ldap' => ['default_pwd' => 'file_ldap', 'host' => 'ldap.example.com'],
|
||||
];
|
||||
private const STORE_YAML = "db_pwd: yaml_pwd\nencryption_key: yaml_key\nauthent-ldap.default_pwd: yaml_ldap\n";
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->RequireOnceItopFile('core/config.class.inc.php');
|
||||
$this->CreateFixtureDir();
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$this->RemoveFixtureDir();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
private function LoadConfig(?string $sYaml = self::STORE_YAML, ?string $sLocal = null, array $aSettings = self::FILE_SETTINGS, array $aModuleSettings = self::FILE_MODULE_SETTINGS): Config
|
||||
{
|
||||
$sConfigFile = $this->WriteConfigFile($aSettings, $aModuleSettings);
|
||||
|
||||
return new Config($sConfigFile, true, $this->CreateStore($sYaml, $sLocal));
|
||||
}
|
||||
|
||||
private function RenderWithoutStore(): string
|
||||
{
|
||||
return (new Config($this->WriteConfigFile(self::FILE_SETTINGS, self::FILE_MODULE_SETTINGS, 'reference.php')))->RenderFileContent();
|
||||
}
|
||||
|
||||
// F-1: opt-in, non-regression
|
||||
|
||||
public function testNoStoreKeepsCurrentBehavior(): void
|
||||
{
|
||||
$oConfig = $this->LoadConfig(null);
|
||||
$this->assertFalse($oConfig->IsSensitiveStoreActive());
|
||||
$this->assertSame('file_pwd', $oConfig->Get('db_pwd'));
|
||||
$this->assertSame('file_key', $oConfig->GetEncryptionKey());
|
||||
$this->assertSame('file_ldap', $oConfig->GetModuleSetting('authent-ldap', 'default_pwd'));
|
||||
$this->assertSame([], $oConfig->GetSensitiveKeys());
|
||||
$this->assertSame([], $oConfig->GetShadowedSensitiveKeys());
|
||||
|
||||
$oConfig->Set('db_pwd', 'x');
|
||||
$this->assertSame('x', $oConfig->Get('db_pwd'));
|
||||
$this->assertArrayHasKey('db_pwd', $oConfig->ToArray());
|
||||
}
|
||||
|
||||
public function testNoStoreRenderIsUnchanged(): void
|
||||
{
|
||||
$oConfig = $this->LoadConfig(null);
|
||||
$sContent = $oConfig->RenderFileContent();
|
||||
$this->assertSame($this->RenderWithoutStore(), $sContent);
|
||||
$this->assertStringContainsString("'db_pwd' => 'file_pwd'", $sContent);
|
||||
$this->assertStringContainsString("'encryption_key' => 'file_key'", $sContent);
|
||||
$this->assertStringContainsString("'default_pwd' => 'file_ldap'", $sContent);
|
||||
}
|
||||
|
||||
public function testUnboundConfigIgnoresTheStore(): void
|
||||
{
|
||||
$this->CreateStore(self::STORE_YAML);
|
||||
// Loaded outside of APPCONF/<env>/ and without injection
|
||||
$oConfig = new Config($this->WriteConfigFile(self::FILE_SETTINGS, self::FILE_MODULE_SETTINGS));
|
||||
$this->assertNull($oConfig->GetSensitiveConfigStore());
|
||||
$this->assertSame('file_pwd', $oConfig->Get('db_pwd'));
|
||||
}
|
||||
|
||||
// F-4: strict resolution
|
||||
|
||||
public function testStrictResolution(): void
|
||||
{
|
||||
$oConfig = $this->LoadConfig();
|
||||
$this->assertTrue($oConfig->IsSensitiveStoreActive());
|
||||
$this->assertSame('yaml_pwd', $oConfig->Get('db_pwd'));
|
||||
$this->assertSame('yaml_key', $oConfig->GetEncryptionKey());
|
||||
$this->assertSame('yaml_ldap', $oConfig->GetModuleSetting('authent-ldap', 'default_pwd'));
|
||||
$this->assertSame('ldap.example.com', $oConfig->GetModuleSetting('authent-ldap', 'host'));
|
||||
// Absent from YAML: declared default, never the config file
|
||||
$this->assertSame('', $oConfig->Get('email_transport_smtp.password'));
|
||||
$this->assertSame(
|
||||
['authent-ldap.default_pwd', 'db_pwd', 'email_transport_smtp.password', 'encryption_key'],
|
||||
$oConfig->GetShadowedSensitiveKeys()
|
||||
);
|
||||
// Non sensitive values are untouched
|
||||
$this->assertSame('itop', $oConfig->Get('db_user'));
|
||||
}
|
||||
|
||||
public function testModuleKeyAbsentFromYamlIgnoresConfigFile(): void
|
||||
{
|
||||
$oConfig = $this->LoadConfig("encryption_key: k\n");
|
||||
$this->assertSame('caller_default', $oConfig->GetModuleSetting('authent-ldap', 'default_pwd', 'caller_default'));
|
||||
}
|
||||
|
||||
public function testEncryptionKeyIsMandatory(): void
|
||||
{
|
||||
try {
|
||||
$this->LoadConfig("db_pwd: yaml_pwd\n");
|
||||
$this->fail('ConfigException expected');
|
||||
} catch (ConfigException $e) {
|
||||
$this->assertStringContainsString('encryption_key', $e->getMessage());
|
||||
$this->assertStringNotContainsString('file_key', (string)$e);
|
||||
}
|
||||
}
|
||||
|
||||
public function testEmptyStoreUsesDefaults(): void
|
||||
{
|
||||
$oConfig = $this->LoadConfig('', "-encryption_key\n");
|
||||
$this->assertSame('', $oConfig->Get('db_pwd')); // declared default (null), typed as string
|
||||
$this->assertSame('file_key', $oConfig->GetEncryptionKey());
|
||||
}
|
||||
|
||||
public function testValuesAreTyped(): void
|
||||
{
|
||||
$oConfig = $this->LoadConfig(self::STORE_YAML."email_transport_smtp.port: '25'\nauthent-ldap.servers: {a: {host: h}}\n", "+email_transport_smtp.port\n+authent-ldap.servers\n");
|
||||
$this->assertSame(25, $oConfig->Get('email_transport_smtp.port'));
|
||||
$this->assertSame(['a' => ['host' => 'h']], $oConfig->GetModuleSetting('authent-ldap', 'servers'));
|
||||
}
|
||||
|
||||
public function testDeclassifiedKeyIsReadFromConfigFile(): void
|
||||
{
|
||||
$oConfig = $this->LoadConfig(self::STORE_YAML."email_transport_smtp.password: yaml_smtp\n", "-email_transport_smtp.password\n");
|
||||
$this->assertSame('file_smtp', $oConfig->Get('email_transport_smtp.password'));
|
||||
$this->assertFalse($oConfig->IsSensitive('email_transport_smtp.password'));
|
||||
$oConfig->Set('email_transport_smtp.password', 'new', 'test');
|
||||
$this->assertStringContainsString("'email_transport_smtp.password' => 'new'", $oConfig->RenderFileContent());
|
||||
}
|
||||
|
||||
public function testOrphanYamlKeyHasNoEffect(): void
|
||||
{
|
||||
$oConfig = $this->LoadConfig(self::STORE_YAML."db_user: yaml_user\n");
|
||||
$this->assertSame('itop', $oConfig->Get('db_user'));
|
||||
}
|
||||
|
||||
// F-7: write guard
|
||||
|
||||
public function testSetIsGuarded(): void
|
||||
{
|
||||
$oConfig = $this->LoadConfig();
|
||||
$oConfig->Set('db_pwd', 'yaml_pwd'); // same value: no-op
|
||||
$this->assertSame('yaml_pwd', $oConfig->Get('db_pwd'));
|
||||
try {
|
||||
$oConfig->Set('db_pwd', 'other');
|
||||
$this->fail('ConfigException expected');
|
||||
} catch (ConfigException $e) {
|
||||
$this->assertStringContainsString('db_pwd', $e->getMessage());
|
||||
$this->assertStringNotContainsString('other', $e->getMessage());
|
||||
}
|
||||
$this->assertSame('yaml_pwd', $oConfig->Get('db_pwd'));
|
||||
}
|
||||
|
||||
public function testSetModuleSettingIsGuarded(): void
|
||||
{
|
||||
$oConfig = $this->LoadConfig();
|
||||
$oConfig->SetModuleSetting('authent-ldap', 'default_pwd', 'yaml_ldap');
|
||||
$this->expectException(ConfigException::class);
|
||||
$oConfig->SetModuleSetting('authent-ldap', 'default_pwd', 'x');
|
||||
}
|
||||
|
||||
public function testSetEncryptionKeyIsGuarded(): void
|
||||
{
|
||||
$oConfig = $this->LoadConfig();
|
||||
$oConfig->SetEncryptionKey('yaml_key');
|
||||
$this->expectException(ConfigException::class);
|
||||
$oConfig->SetEncryptionKey('x');
|
||||
}
|
||||
|
||||
public function testWriteNeverContainsSensitiveKeys(): void
|
||||
{
|
||||
$oConfig = $this->LoadConfig();
|
||||
$sTarget = $this->sFixtureDir.'/written.php';
|
||||
$oConfig->WriteToFile($sTarget);
|
||||
$sContent = file_get_contents($sTarget);
|
||||
$this->assertStringNotContainsString("'db_pwd'", $sContent);
|
||||
$this->assertStringNotContainsString("'encryption_key'", $sContent);
|
||||
$this->assertStringNotContainsString('default_pwd', $sContent);
|
||||
$this->assertStringNotContainsString('yaml_', $sContent);
|
||||
$this->assertStringNotContainsString('file_pwd', $sContent);
|
||||
$this->assertStringContainsString("'host' => 'ldap.example.com'", $sContent);
|
||||
$this->assertStringContainsString("'db_user' => 'itop'", $sContent);
|
||||
// Non evaluated placeholders are preserved
|
||||
$this->assertStringContainsString("'app_root_url' => 'http://%server(SERVER_NAME)?:localhost%/itop/'", $sContent);
|
||||
// The written file can be reloaded with the store
|
||||
$oReloaded = new Config($sTarget, true, $this->CreateStore(self::STORE_YAML));
|
||||
$this->assertSame([], $oReloaded->GetShadowedSensitiveKeys());
|
||||
$this->assertSame('yaml_pwd', $oReloaded->Get('db_pwd'));
|
||||
}
|
||||
|
||||
public function testModuleSectionWithOnlySensitiveKeysIsOmitted(): void
|
||||
{
|
||||
$oConfig = $this->LoadConfig(self::STORE_YAML, null, self::FILE_SETTINGS, ['authent-ldap' => ['default_pwd' => 'file_ldap']]);
|
||||
$this->assertStringNotContainsString("'authent-ldap'", $oConfig->RenderFileContent());
|
||||
}
|
||||
|
||||
public function testToArrayHasNoSensitiveKey(): void
|
||||
{
|
||||
$aArray = $this->LoadConfig(self::STORE_YAML."my_custom_module.api_key: k\n", "+my_custom_module.api_key\n")->ToArray();
|
||||
$this->assertArrayNotHasKey('db_pwd', $aArray);
|
||||
$this->assertArrayNotHasKey('encryption_key', $aArray);
|
||||
$this->assertArrayNotHasKey('email_transport_smtp.password', $aArray);
|
||||
$this->assertArrayNotHasKey('default_pwd', $aArray['module_settings']['authent-ldap']);
|
||||
$this->assertArrayNotHasKey('api_key', $aArray['module_settings']['my_custom_module'] ?? []);
|
||||
$this->assertArrayHasKey('db_user', $aArray);
|
||||
}
|
||||
|
||||
// F-8 support: shadowed keys of an editor submission
|
||||
|
||||
public function testShadowedKeysOfASubmission(): void
|
||||
{
|
||||
$oStore = $this->CreateStore(self::STORE_YAML, "+my_custom_module.api_key\n");
|
||||
$sSubmitted = $this->WriteConfigFile(['db_user' => 'itop'], ['my_custom_module' => ['api_key' => 'x']], 'submitted.php');
|
||||
$this->assertSame(['my_custom_module.api_key'], (new Config($sSubmitted, true, $oStore))->GetShadowedSensitiveKeys());
|
||||
}
|
||||
|
||||
// F-11: late binding (setup)
|
||||
|
||||
public function testLateBindingWithSameValue(): void
|
||||
{
|
||||
$oConfig = new Config();
|
||||
$oConfig->Set('db_pwd', 'yaml_pwd');
|
||||
$oConfig->SetEncryptionKey('yaml_key');
|
||||
$oConfig->BindSensitiveConfigStore($this->CreateStore(self::STORE_YAML));
|
||||
$this->assertStringNotContainsString("'db_pwd'", $oConfig->RenderFileContent());
|
||||
}
|
||||
|
||||
public function testLateBindingWithDivergentValue(): void
|
||||
{
|
||||
$oConfig = new Config();
|
||||
$oConfig->Set('db_pwd', 'wizard_pwd');
|
||||
$oConfig->SetEncryptionKey('yaml_key');
|
||||
$oConfig->BindSensitiveConfigStore($this->CreateStore(self::STORE_YAML));
|
||||
$this->expectException(ConfigException::class);
|
||||
$oConfig->RenderFileContent();
|
||||
}
|
||||
|
||||
public function testUpdateIncludesSkipsSensitiveModuleDefaults(): void
|
||||
{
|
||||
$this->RequireOnceItopFile('setup/runtimeenv.class.inc.php');
|
||||
$oConfig = $this->LoadConfig("db_pwd: yaml_pwd\nencryption_key: yaml_key\n", null, self::FILE_SETTINGS, ['authent-ldap' => ['host' => 'ldap.example.com']]);
|
||||
$oConfig->UpdateIncludes('datamodels/2.x/authent-ldap', ['authent-ldap']);
|
||||
$this->assertArrayNotHasKey('default_pwd', $oConfig->ToArray()['module_settings']['authent-ldap']);
|
||||
$this->assertStringNotContainsString('default_pwd', $oConfig->RenderFileContent());
|
||||
$this->assertSame('ldap.example.com', $oConfig->GetModuleSetting('authent-ldap', 'host'));
|
||||
}
|
||||
|
||||
// Setup: values moved to a new store (N°10293)
|
||||
|
||||
private const BASELINE_IDS = ['authent-ldap.default_pwd', 'combodo-saml.privatekey', 'combodo-saml.x509cert', 'db_pwd', 'email_transport_smtp.password', 'encryption_key'];
|
||||
|
||||
public function testGetSensitiveValuesForStoreFromConfigFile(): void
|
||||
{
|
||||
$aSettings = self::FILE_SETTINGS;
|
||||
$aSettings['db_pwd'] = '%env(ITOP_DB_PWD)?:fallback%';
|
||||
$oConfig = $this->LoadConfig(null, null, $aSettings);
|
||||
|
||||
$aValues = $oConfig->GetSensitiveValuesForStore(self::BASELINE_IDS);
|
||||
|
||||
$this->assertSame([
|
||||
'authent-ldap.default_pwd' => 'file_ldap',
|
||||
'db_pwd' => '%env(ITOP_DB_PWD)?:fallback%',
|
||||
'email_transport_smtp.password' => 'file_smtp',
|
||||
'encryption_key' => 'file_key',
|
||||
], $aValues, 'Placeholders kept, absent module settings skipped');
|
||||
}
|
||||
|
||||
public function testGetSensitiveValuesForStoreFromSetupValues(): void
|
||||
{
|
||||
$oConfig = new Config();
|
||||
$oConfig->Set('db_pwd', 'wizard_pwd');
|
||||
$oConfig->SetEncryptionKey('wizard_key');
|
||||
|
||||
$aValues = $oConfig->GetSensitiveValuesForStore(self::BASELINE_IDS);
|
||||
|
||||
$this->assertSame('wizard_pwd', $aValues['db_pwd']);
|
||||
$this->assertSame('wizard_key', $aValues['encryption_key']);
|
||||
$this->assertArrayNotHasKey('authent-ldap.default_pwd', $aValues);
|
||||
}
|
||||
|
||||
public function testGetSensitiveValuesForStoreRefusesComputedValue(): void
|
||||
{
|
||||
$sConfigFile = $this->WriteFile('config-itop.php', "<?php\n\$MySettings = array('db_pwd' => \$_SERVER['ITOP_WITNESS'], 'encryption_key' => 'k');\n\$MyModuleSettings = array();\n\$MyModules = array('addons' => array('user rights' => 'addons/userrights/userrightsprofile.class.inc.php'));\n");
|
||||
$_SERVER['ITOP_WITNESS'] = 'WITNESS_SECRET_42';
|
||||
try {
|
||||
$oConfig = new Config($sConfigFile, true, $this->CreateStore(null));
|
||||
$oConfig->GetSensitiveValuesForStore(self::BASELINE_IDS);
|
||||
$this->fail('ConfigException expected');
|
||||
} catch (ConfigException $e) {
|
||||
$this->assertStringContainsString('db_pwd', $e->getMessage());
|
||||
$this->assertStringNotContainsString('WITNESS_SECRET_42', (string)$e);
|
||||
} finally {
|
||||
unset($_SERVER['ITOP_WITNESS']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Explicit initialization followed by configuration rendering
|
||||
*/
|
||||
public function testMoveToNewStoreRemovesSecretsFromConfigFile(): void
|
||||
{
|
||||
$oConfig = $this->LoadConfig(null);
|
||||
$oStore = $this->CreateStore(null);
|
||||
|
||||
$oStore->Initialize($oConfig->GetSensitiveValuesForStore(self::BASELINE_IDS));
|
||||
$oConfig->BindSensitiveConfigStore($oStore);
|
||||
$sContent = $oConfig->RenderFileContent();
|
||||
|
||||
foreach (['file_pwd', 'file_key', 'file_smtp', 'file_ldap'] as $sSecret) {
|
||||
$this->assertStringNotContainsString($sSecret, $sContent);
|
||||
}
|
||||
$this->assertStringContainsString('ldap.example.com', $sContent);
|
||||
|
||||
$sConfigFile = $this->WriteFile('rewritten.php', $sContent);
|
||||
$oReloaded = new Config($sConfigFile, true, $oStore);
|
||||
$this->assertSame('file_pwd', $oReloaded->Get('db_pwd'));
|
||||
$this->assertSame('file_key', $oReloaded->GetEncryptionKey());
|
||||
$this->assertSame('file_smtp', $oReloaded->Get('email_transport_smtp.password'));
|
||||
$this->assertSame('file_ldap', $oReloaded->GetModuleSetting('authent-ldap', 'default_pwd'));
|
||||
$this->assertSame([], $oReloaded->GetShadowedSensitiveKeys());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* @copyright Copyright (C) 2010-2026 Combodo SAS
|
||||
* @license http://opensource.org/licenses/AGPL-3.0
|
||||
*/
|
||||
|
||||
namespace Combodo\iTop\Test\UnitTest\Core\SensitiveConfig;
|
||||
|
||||
use Combodo\iTop\Core\Config\Sensitive\SensitiveConfigDiagnostic;
|
||||
use Combodo\iTop\Test\UnitTest\ItopTestCase;
|
||||
|
||||
require_once __DIR__.'/SensitiveConfigTestTrait.php';
|
||||
|
||||
class SensitiveConfigDiagnosticTest extends ItopTestCase
|
||||
{
|
||||
use SensitiveConfigTestTrait;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->RequireOnceItopFile('core/config.class.inc.php');
|
||||
$this->CreateFixtureDir();
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$this->RemoveFixtureDir();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
private function Diagnose(array $aSettings, array $aModuleSettings, ?string $sYaml, ?string $sLocal = null, array $aEnv = []): SensitiveConfigDiagnostic
|
||||
{
|
||||
$sConfigFile = $this->WriteConfigFile($aSettings, $aModuleSettings);
|
||||
$oDiagnostic = new SensitiveConfigDiagnostic($sConfigFile, $this->CreateStore($sYaml, $sLocal), null, $aEnv);
|
||||
$oDiagnostic->Run();
|
||||
|
||||
return $oDiagnostic;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string[] "CODE key" entries
|
||||
*/
|
||||
private function Codes(SensitiveConfigDiagnostic $oDiagnostic): array
|
||||
{
|
||||
return array_map(fn ($a) => trim($a['code'].' '.$a['key']), $oDiagnostic->Run());
|
||||
}
|
||||
|
||||
private function Plan(SensitiveConfigDiagnostic $oDiagnostic): array
|
||||
{
|
||||
return array_map(fn ($a) => $a['action'].' '.$a['key'], $oDiagnostic->GetPlan());
|
||||
}
|
||||
|
||||
public function testInactiveStore(): void
|
||||
{
|
||||
$oDiagnostic = $this->Diagnose(['db_pwd' => 'p', 'db_user' => 'u'], [], null);
|
||||
$this->assertSame(['SENSITIVE_STORE_INACTIVE', 'PLAINTEXT_SENSITIVE db_pwd'], $this->Codes($oDiagnostic));
|
||||
$this->assertFalse(SensitiveConfigDiagnostic::HasErrors($oDiagnostic->Run()));
|
||||
}
|
||||
|
||||
public function testConsistentStore(): void
|
||||
{
|
||||
$oDiagnostic = $this->Diagnose(['db_user' => 'u'], [], "db_pwd: p\nencryption_key: k\n");
|
||||
$aFindings = $oDiagnostic->Run();
|
||||
$this->assertFalse(SensitiveConfigDiagnostic::HasErrors($aFindings), json_encode($aFindings));
|
||||
$this->assertSame([], $oDiagnostic->GetPlan());
|
||||
}
|
||||
|
||||
public function testMissing(): void
|
||||
{
|
||||
$oDiagnostic = $this->Diagnose(['db_user' => 'u'], [], "encryption_key: k\n");
|
||||
$this->assertContains('E_MISSING db_pwd', $this->Codes($oDiagnostic));
|
||||
$this->assertTrue(SensitiveConfigDiagnostic::HasErrors($oDiagnostic->Run()));
|
||||
}
|
||||
|
||||
public function testMissingEncryptionKey(): void
|
||||
{
|
||||
$this->assertContains('E_MISSING encryption_key', $this->Codes($this->Diagnose([], [], "db_pwd: p\n")));
|
||||
}
|
||||
|
||||
public function testDuplicateSameValueIsDeduped(): void
|
||||
{
|
||||
$oDiagnostic = $this->Diagnose(['db_pwd' => 'p'], [], "db_pwd: p\nencryption_key: k\n");
|
||||
$this->assertContains('W_DUPLICATE db_pwd', $this->Codes($oDiagnostic));
|
||||
$this->assertSame(['DEDUPE db_pwd'], $this->Plan($oDiagnostic));
|
||||
}
|
||||
|
||||
public function testDuplicateDifferentValueIsAConflict(): void
|
||||
{
|
||||
$oDiagnostic = $this->Diagnose(['db_pwd' => 'other'], [], "db_pwd: p\nencryption_key: k\n");
|
||||
$this->assertContains('W_DUPLICATE db_pwd', $this->Codes($oDiagnostic));
|
||||
$this->assertSame(['CONFLICT db_pwd'], $this->Plan($oDiagnostic));
|
||||
}
|
||||
|
||||
public function testMisplaced(): void
|
||||
{
|
||||
$oDiagnostic = $this->Diagnose([], ['authent-ldap' => ['default_pwd' => 'x']], "db_pwd: p\nencryption_key: k\n");
|
||||
$this->assertContains('E_MISPLACED authent-ldap.default_pwd', $this->Codes($oDiagnostic));
|
||||
$this->assertSame(['MOVE authent-ldap.default_pwd'], $this->Plan($oDiagnostic));
|
||||
}
|
||||
|
||||
public function testOrphanAndUnknown(): void
|
||||
{
|
||||
$aCodes = $this->Codes($this->Diagnose([], [], "db_pwd: p\nencryption_key: k\ndb_user: u\ndbpwd: typo\n"));
|
||||
$this->assertContains('W_ORPHAN db_user', $aCodes);
|
||||
$this->assertNotContains('W_UNKNOWN db_user', $aCodes);
|
||||
$this->assertContains('W_UNKNOWN dbpwd', $aCodes);
|
||||
}
|
||||
|
||||
public function testDeclassifiedAndLocalSyntax(): void
|
||||
{
|
||||
$aCodes = $this->Codes($this->Diagnose(['encryption_key' => 'k'], [], "db_pwd: p\n", "-encryption_key\nbad line\n"));
|
||||
$this->assertContains('I_DECLASSIFIED encryption_key', $aCodes);
|
||||
$this->assertContains('W_LOCAL_SYNTAX line 2', $aCodes);
|
||||
$this->assertNotContains('E_MISSING encryption_key', $aCodes);
|
||||
}
|
||||
|
||||
public function testType(): void
|
||||
{
|
||||
$this->assertContains('W_TYPE db_pwd', $this->Codes($this->Diagnose([], [], "db_pwd: [a, b]\nencryption_key: k\n")));
|
||||
}
|
||||
|
||||
public function testPlaceholderDisabled(): void
|
||||
{
|
||||
$sYaml = "db_pwd: '%env(ITOP_DB_PASSWORD)%'\nencryption_key: k\n";
|
||||
$this->assertContains('W_PLACEHOLDER_DISABLED db_pwd', $this->Codes($this->Diagnose([], [], $sYaml)));
|
||||
$this->assertNotContains('W_PLACEHOLDER_DISABLED db_pwd', $this->Codes($this->Diagnose([], [], $sYaml, null, ['ITOP_CONFIG_PLACEHOLDERS' => 1])));
|
||||
}
|
||||
|
||||
public function testInvalidStore(): void
|
||||
{
|
||||
$oDiagnostic = $this->Diagnose([], [], "db_pwd: 'WITNESS_SECRET_42\n : [\n");
|
||||
$aFindings = $oDiagnostic->Run();
|
||||
$this->assertSame('E_STORE_INVALID', $aFindings[count($aFindings) - 1]['code']);
|
||||
$this->assertTrue(SensitiveConfigDiagnostic::HasErrors($aFindings));
|
||||
$this->assertStringNotContainsString('WITNESS_SECRET_42', json_encode($aFindings));
|
||||
}
|
||||
|
||||
public function testPermissions(): void
|
||||
{
|
||||
$sYaml = "db_pwd: p\nencryption_key: k\n";
|
||||
$oStore = $this->CreateStore($sYaml);
|
||||
chmod($oStore->GetPath(), 0644);
|
||||
$aCodes = array_column((new SensitiveConfigDiagnostic($this->WriteConfigFile([], []), $oStore))->Run(), 'code');
|
||||
$this->assertContains('W_PERMS_WRITABLE', $aCodes);
|
||||
$this->assertContains('W_PERMS_WORLD_READABLE', $aCodes);
|
||||
$this->assertStringContainsString('chmod 0440', SensitiveConfigDiagnostic::GetRemediationCommand('/x', 'Linux'));
|
||||
$this->assertStringContainsString('icacls', SensitiveConfigDiagnostic::GetRemediationCommand('C:\\x', 'Windows'));
|
||||
}
|
||||
|
||||
public function testNoValueInOutput(): void
|
||||
{
|
||||
$oDiagnostic = $this->Diagnose(
|
||||
['db_pwd' => 'WITNESS_FILE_1', 'encryption_key' => 'WITNESS_FILE_2'],
|
||||
['authent-ldap' => ['default_pwd' => 'WITNESS_FILE_3']],
|
||||
"db_pwd: WITNESS_YAML_1\nother.key: WITNESS_YAML_2\nbad: [WITNESS_YAML_3]\n"
|
||||
);
|
||||
$sOutput = json_encode([$oDiagnostic->Run(), $oDiagnostic->GetPlan()]);
|
||||
$this->assertStringNotContainsString('WITNESS', $sOutput);
|
||||
}
|
||||
|
||||
public function testCliIsReadOnlyAndExitCodes(): void
|
||||
{
|
||||
$sScript = APPROOT.'setup/validate-sensitive-config.php';
|
||||
exec(PHP_BINARY.' '.escapeshellarg($sScript).' --fix 2>&1', $aOutput, $iCode);
|
||||
$this->assertSame(2, $iCode);
|
||||
exec(PHP_BINARY.' '.escapeshellarg($sScript).' --help 2>&1', $aOutput, $iCode);
|
||||
$this->assertSame(0, $iCode);
|
||||
exec(PHP_BINARY.' '.escapeshellarg($sScript).' --env=../x 2>&1', $aOutput, $iCode);
|
||||
$this->assertSame(2, $iCode);
|
||||
}
|
||||
|
||||
public function testCliOnFixture(): void
|
||||
{
|
||||
$sRoot = $this->sFixtureDir.'/root';
|
||||
mkdir($sRoot.'/sensitivetest', 0700, true);
|
||||
file_put_contents($sRoot.'/sensitivetest/sensitive-config-itop.yml', "db_pwd: WITNESS_YAML\n");
|
||||
$sConfDir = APPCONF.'sensitivetest';
|
||||
$bCreated = !is_dir($sConfDir) && mkdir($sConfDir);
|
||||
if (!$bCreated) {
|
||||
$this->markTestSkipped("$sConfDir already exists");
|
||||
}
|
||||
try {
|
||||
file_put_contents($sConfDir.'/config-itop.php', "<?php\n\$MySettings = array('db_pwd' => 'WITNESS_FILE', 'encryption_key' => 'WITNESS_KEY');\n\$MyModuleSettings = array();\n\$MyModules = array();\n");
|
||||
$sCmd = 'ITOP_SENSITIVE_CONFIG_PATH='.escapeshellarg($sRoot).' '.PHP_BINARY.' '.escapeshellarg(APPROOT.'setup/validate-sensitive-config.php').' --check --env=sensitivetest 2>&1';
|
||||
exec($sCmd, $aOutput, $iCode);
|
||||
} finally {
|
||||
@unlink($sConfDir.'/config-itop.php');
|
||||
@rmdir($sConfDir);
|
||||
}
|
||||
$sOutput = implode("\n", $aOutput);
|
||||
// Note: the CLI reads the instance-wide data/sensitive.parameters.env.local, so only baseline-independent findings are asserted
|
||||
$this->assertStringContainsString('active=yes', $sOutput);
|
||||
$this->assertStringContainsString('[WARNING] W_DUPLICATE db_pwd', $sOutput);
|
||||
$this->assertStringContainsString('[WARNING] W_PERMS_WRITABLE', $sOutput);
|
||||
$this->assertStringContainsString('[PLAN] CONFLICT db_pwd', $sOutput);
|
||||
$this->assertStringNotContainsString('WITNESS', $sOutput);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* @copyright Copyright (C) 2010-2026 Combodo SAS
|
||||
* @license http://opensource.org/licenses/AGPL-3.0
|
||||
*/
|
||||
|
||||
namespace Combodo\iTop\Test\UnitTest\Core\SensitiveConfig;
|
||||
|
||||
use Combodo\iTop\Core\Config\Sensitive\SensitiveConfigStore;
|
||||
use Combodo\iTop\Test\UnitTest\ItopTestCase;
|
||||
use ConfigException;
|
||||
|
||||
require_once __DIR__.'/SensitiveConfigTestTrait.php';
|
||||
|
||||
class SensitiveConfigStoreTest extends ItopTestCase
|
||||
{
|
||||
use SensitiveConfigTestTrait;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->RequireOnceItopFile('core/config.class.inc.php');
|
||||
$this->CreateFixtureDir();
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$this->RemoveFixtureDir();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function testDefaultPath(): void
|
||||
{
|
||||
$this->assertSame(APPCONF.'production/'.SensitiveConfigStore::FILE_NAME, SensitiveConfigStore::ForEnvironment('production')->GetPath());
|
||||
}
|
||||
|
||||
public function testEnvVarPath(): void
|
||||
{
|
||||
putenv(SensitiveConfigStore::ENV_VAR.'=/tmp/x/');
|
||||
$this->assertSame('/tmp/x/production/'.SensitiveConfigStore::FILE_NAME, SensitiveConfigStore::ForEnvironment('production')->GetPath());
|
||||
}
|
||||
|
||||
public function testEnvVarFromServer(): void
|
||||
{
|
||||
$_SERVER[SensitiveConfigStore::ENV_VAR] = '/etc/itop';
|
||||
$this->assertSame('/etc/itop/test/'.SensitiveConfigStore::FILE_NAME, SensitiveConfigStore::ForEnvironment('test')->GetPath());
|
||||
}
|
||||
|
||||
public function testRelativeEnvVarIsRefused(): void
|
||||
{
|
||||
putenv(SensitiveConfigStore::ENV_VAR.'=etc/itop');
|
||||
$this->expectException(ConfigException::class);
|
||||
SensitiveConfigStore::ForEnvironment('production');
|
||||
}
|
||||
|
||||
public function testInvalidEnvironmentNameIsRefused(): void
|
||||
{
|
||||
$this->expectException(ConfigException::class);
|
||||
SensitiveConfigStore::ForEnvironment('../production');
|
||||
}
|
||||
|
||||
public function testEnvironmentFromConfigFile(): void
|
||||
{
|
||||
$this->assertSame('production', SensitiveConfigStore::GetEnvironmentFromConfigFile(APPCONF.'production/config-itop.php'));
|
||||
$sBuildDir = APPCONF.'sensitivetest-build';
|
||||
$bCreated = !is_dir($sBuildDir) && mkdir($sBuildDir);
|
||||
try {
|
||||
$this->assertSame('sensitivetest', SensitiveConfigStore::GetEnvironmentFromConfigFile($sBuildDir.'/config-itop.php'));
|
||||
} finally {
|
||||
if ($bCreated) {
|
||||
rmdir($sBuildDir);
|
||||
}
|
||||
}
|
||||
$this->assertNull(SensitiveConfigStore::GetEnvironmentFromConfigFile($this->sFixtureDir.'/config-itop.php'));
|
||||
$this->assertNull(SensitiveConfigStore::GetEnvironmentFromConfigFile(null));
|
||||
}
|
||||
|
||||
public function testInactiveWhenAbsent(): void
|
||||
{
|
||||
$oStore = $this->CreateStore(null);
|
||||
$this->assertFalse($oStore->IsActive());
|
||||
$this->assertSame([], $oStore->GetValues());
|
||||
}
|
||||
|
||||
public function testValuesAreRead(): void
|
||||
{
|
||||
$oStore = $this->CreateStore("db_pwd: 'S3cr3t!'\nauthent-ldap.default_pwd: ldap\nlist_key: [a, b]\n");
|
||||
$this->assertTrue($oStore->IsActive());
|
||||
$this->assertSame('S3cr3t!', $oStore->Get('db_pwd'));
|
||||
$this->assertSame(['a', 'b'], $oStore->Get('list_key'));
|
||||
$this->assertTrue($oStore->Has('authent-ldap.default_pwd'));
|
||||
$this->assertFalse($oStore->Has('encryption_key'));
|
||||
}
|
||||
|
||||
public function testEmptyFileIsAnEmptyMapping(): void
|
||||
{
|
||||
$oStore = $this->CreateStore('');
|
||||
$this->assertTrue($oStore->IsActive());
|
||||
$this->assertSame([], $oStore->GetValues());
|
||||
}
|
||||
|
||||
public function testInvalidYamlNeverLeaksContent(): void
|
||||
{
|
||||
$oStore = $this->CreateStore("db_user: admin\ndb_pwd: 'WITNESS_SECRET_42\n : : [\n");
|
||||
try {
|
||||
$oStore->GetValues();
|
||||
$this->fail('ConfigException expected');
|
||||
} catch (ConfigException $e) {
|
||||
$this->assertStringNotContainsString('WITNESS_SECRET_42', $e->getMessage());
|
||||
$this->assertStringNotContainsString('WITNESS_SECRET_42', (string)$e);
|
||||
$this->assertStringContainsString(SensitiveConfigStore::FILE_NAME, $e->getMessage());
|
||||
$this->assertStringContainsString('line', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function testListRootIsRefused(): void
|
||||
{
|
||||
$this->expectException(ConfigException::class);
|
||||
$this->CreateStore("- a\n- b\n")->GetValues();
|
||||
}
|
||||
|
||||
public function testPhpObjectsAreNotInstantiated(): void
|
||||
{
|
||||
$this->expectException(\Throwable::class);
|
||||
$this->CreateStore("db_pwd: !php/object 'O:8:\"stdClass\":0:{}'\n")->GetValues();
|
||||
}
|
||||
|
||||
public function testPlaceholderResolvedWhenFlagSet(): void
|
||||
{
|
||||
$oStore = $this->CreateStore("db_pwd: '%env(ITOP_DB_PASSWORD)%'\n", null, ['ITOP_CONFIG_PLACEHOLDERS' => 1, 'ITOP_DB_PASSWORD' => 'abc']);
|
||||
$this->assertSame('abc', $oStore->Get('db_pwd'));
|
||||
}
|
||||
|
||||
public function testPlaceholderKeptWhenFlagAbsent(): void
|
||||
{
|
||||
$oStore = $this->CreateStore("db_pwd: '%env(ITOP_DB_PASSWORD)%'\n", null, ['ITOP_DB_PASSWORD' => 'abc']);
|
||||
$this->assertSame('%env(ITOP_DB_PASSWORD)%', $oStore->Get('db_pwd'));
|
||||
}
|
||||
|
||||
public function testUnresolvedPlaceholderThrowsWithoutValue(): void
|
||||
{
|
||||
$oStore = $this->CreateStore("db_pwd: '%env(ITOP_MISSING_VAR)%'\nother: 'WITNESS_SECRET_42'\n", null, ['ITOP_CONFIG_PLACEHOLDERS' => 1]);
|
||||
try {
|
||||
$oStore->GetValues();
|
||||
$this->fail('ConfigException expected');
|
||||
} catch (ConfigException $e) {
|
||||
$this->assertStringNotContainsString('WITNESS_SECRET_42', (string)$e);
|
||||
$this->assertStringContainsString('db_pwd', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// Setup: creation of the store (N°10293)
|
||||
|
||||
public function testInitializeCreatesReadOnlyStore(): void
|
||||
{
|
||||
$oStore = $this->CreateStore(null);
|
||||
$this->assertFalse($oStore->IsActive());
|
||||
|
||||
$oStore->Initialize(['encryption_key' => 'k3y', 'db_pwd' => '%env(ITOP_DB_PWD)%', 'authent-ldap.default_pwd' => "multi\nline"]);
|
||||
|
||||
$this->assertTrue($oStore->IsActive());
|
||||
$this->assertSame(['authent-ldap.default_pwd', 'db_pwd', 'encryption_key'], $oStore->GetKeys());
|
||||
$this->assertSame('%env(ITOP_DB_PWD)%', $oStore->Get('db_pwd'));
|
||||
$this->assertSame("multi\nline", $oStore->Get('authent-ldap.default_pwd'));
|
||||
$this->assertSame('k3y', $oStore->Get('encryption_key'));
|
||||
if (DIRECTORY_SEPARATOR === '/') {
|
||||
$this->assertSame(0440, fileperms($oStore->GetPath()) & 0777);
|
||||
}
|
||||
$this->assertSame(['.', '..', SensitiveConfigStore::FILE_NAME], scandir($this->sFixtureDir), 'No temporary file left behind');
|
||||
}
|
||||
|
||||
public function testInitializeWithoutValuesCreatesEmptyStore(): void
|
||||
{
|
||||
$oStore = $this->CreateStore(null);
|
||||
$oStore->Initialize([]);
|
||||
$this->assertTrue($oStore->IsActive());
|
||||
$this->assertSame([], $oStore->GetKeys());
|
||||
}
|
||||
|
||||
public function testInitializeNeverOverwrites(): void
|
||||
{
|
||||
$oStore = $this->CreateStore("db_pwd: original\n");
|
||||
try {
|
||||
$oStore->Initialize(['db_pwd' => 'other']);
|
||||
$this->fail('ConfigException expected');
|
||||
} catch (ConfigException $e) {
|
||||
$this->assertStringNotContainsString('other', $e->getMessage());
|
||||
}
|
||||
$this->assertSame("db_pwd: original\n", file_get_contents($oStore->GetPath()));
|
||||
}
|
||||
|
||||
public function testInitializeCreatesMissingDirectory(): void
|
||||
{
|
||||
$oStore = new SensitiveConfigStore($this->sFixtureDir.'/root/production/'.SensitiveConfigStore::FILE_NAME);
|
||||
$oStore->Initialize(['db_pwd' => 'pwd']);
|
||||
$this->assertTrue($oStore->IsActive());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* @copyright Copyright (C) 2010-2026 Combodo SAS
|
||||
* @license http://opensource.org/licenses/AGPL-3.0
|
||||
*/
|
||||
|
||||
namespace Combodo\iTop\Test\UnitTest\Core\SensitiveConfig;
|
||||
|
||||
use Combodo\iTop\Core\Config\Sensitive\SensitiveConfigStore;
|
||||
use ConfigPlaceholdersResolver;
|
||||
use SetupUtils;
|
||||
|
||||
/**
|
||||
* Fixtures for N°10293 tests: everything lives in a temporary directory
|
||||
*/
|
||||
trait SensitiveConfigTestTrait
|
||||
{
|
||||
protected string $sFixtureDir;
|
||||
|
||||
protected function CreateFixtureDir(): void
|
||||
{
|
||||
$this->sFixtureDir = sys_get_temp_dir().'/itop-sensitive-'.bin2hex(random_bytes(6));
|
||||
mkdir($this->sFixtureDir, 0700, true);
|
||||
putenv(SensitiveConfigStore::ENV_VAR);
|
||||
unset($_SERVER[SensitiveConfigStore::ENV_VAR], $_ENV[SensitiveConfigStore::ENV_VAR]);
|
||||
}
|
||||
|
||||
protected function RemoveFixtureDir(): void
|
||||
{
|
||||
putenv(SensitiveConfigStore::ENV_VAR);
|
||||
unset($_SERVER[SensitiveConfigStore::ENV_VAR], $_ENV[SensitiveConfigStore::ENV_VAR]);
|
||||
if (isset($this->sFixtureDir) && is_dir($this->sFixtureDir)) {
|
||||
$this->RemoveDir($this->sFixtureDir);
|
||||
}
|
||||
}
|
||||
|
||||
private function RemoveDir(string $sDir): void
|
||||
{
|
||||
foreach (scandir($sDir) as $sEntry) {
|
||||
if ($sEntry === '.' || $sEntry === '..') {
|
||||
continue;
|
||||
}
|
||||
$sPath = $sDir.'/'.$sEntry;
|
||||
is_dir($sPath) && !is_link($sPath) ? $this->RemoveDir($sPath) : unlink($sPath);
|
||||
}
|
||||
rmdir($sDir);
|
||||
}
|
||||
|
||||
protected function WriteFile(string $sName, string $sContent): string
|
||||
{
|
||||
$sPath = $this->sFixtureDir.'/'.$sName;
|
||||
@mkdir(dirname($sPath), 0700, true);
|
||||
file_put_contents($sPath, $sContent);
|
||||
|
||||
return $sPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $aSettings $MySettings
|
||||
* @param array $aModuleSettings $MyModuleSettings
|
||||
*/
|
||||
protected function WriteConfigFile(array $aSettings, array $aModuleSettings = [], string $sName = 'config-itop.php'): string
|
||||
{
|
||||
$sContent = "<?php\n\$MySettings = ".var_export($aSettings, true).";\n"
|
||||
."\$MyModuleSettings = ".var_export($aModuleSettings, true).";\n"
|
||||
."\$MyModules = array('addons' => array('user rights' => 'addons/userrights/userrightsprofile.class.inc.php'));\n?>";
|
||||
|
||||
return $this->WriteFile($sName, $sContent);
|
||||
}
|
||||
|
||||
protected function CreateStore(?string $sYaml, string $sLocal = null, ?array $aEnv = null): SensitiveConfigStore
|
||||
{
|
||||
$sStorePath = $this->sFixtureDir.'/'.SensitiveConfigStore::FILE_NAME;
|
||||
if ($sYaml !== null) {
|
||||
file_put_contents($sStorePath, $sYaml);
|
||||
}
|
||||
$sLocalPath = $this->sFixtureDir.'/sensitive.parameters.env.local';
|
||||
if ($sLocal !== null) {
|
||||
file_put_contents($sLocalPath, $sLocal);
|
||||
}
|
||||
$oResolver = ($aEnv === null) ? new ConfigPlaceholdersResolver(['NONE' => 1], ['NONE' => 1]) : new ConfigPlaceholdersResolver($aEnv, ['NONE' => 1]);
|
||||
|
||||
return new SensitiveConfigStore($sStorePath, $oResolver, $sLocalPath);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* @copyright Copyright (C) 2010-2026 Combodo SAS
|
||||
* @license http://opensource.org/licenses/AGPL-3.0
|
||||
*/
|
||||
|
||||
namespace Combodo\iTop\Test\UnitTest\Core\SensitiveConfig;
|
||||
|
||||
use Combodo\iTop\Core\Config\Sensitive\SensitiveParameters;
|
||||
use Combodo\iTop\SystemInformation\Service\SysInfoConfig;
|
||||
use Combodo\iTop\Test\UnitTest\ItopTestCase;
|
||||
use Config;
|
||||
|
||||
require_once __DIR__.'/SensitiveConfigTestTrait.php';
|
||||
|
||||
class SensitiveParametersTest extends ItopTestCase
|
||||
{
|
||||
use SensitiveConfigTestTrait;
|
||||
|
||||
private const BASELINE = [
|
||||
'authent-ldap.default_pwd',
|
||||
'combodo-saml.privatekey',
|
||||
'combodo-saml.x509cert',
|
||||
'db_pwd',
|
||||
'email_transport_smtp.password',
|
||||
'encryption_key',
|
||||
];
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->RequireOnceItopFile('core/config.class.inc.php');
|
||||
$this->CreateFixtureDir();
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$this->RemoveFixtureDir();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
private function GetCoreKeys(): array
|
||||
{
|
||||
return (new Config(null, false))->GetCoreSensitiveKeys();
|
||||
}
|
||||
|
||||
public function testBaselineWithoutLocalFile(): void
|
||||
{
|
||||
$oParameters = SensitiveParameters::FromLocalFile($this->GetCoreKeys(), $this->sFixtureDir.'/missing.local');
|
||||
$this->assertSame(self::BASELINE, $oParameters->GetEffective());
|
||||
$this->assertSame(self::BASELINE, $oParameters->GetBaseline());
|
||||
}
|
||||
|
||||
public function testLocalAdditionsAndRemovals(): void
|
||||
{
|
||||
$oParameters = new SensitiveParameters($this->GetCoreKeys(), "# comment\n\n+my_custom_module.api_key\nother_mod.token\n-db_tls.ca\n-email_transport_smtp.password\n");
|
||||
$aExpected = array_values(array_diff(array_merge(self::BASELINE, ['my_custom_module.api_key', 'other_mod.token']), ['email_transport_smtp.password']));
|
||||
sort($aExpected);
|
||||
$this->assertSame($aExpected, $oParameters->GetEffective());
|
||||
$this->assertFalse($oParameters->IsSensitive('db_tls.ca'));
|
||||
$this->assertSame(['db_tls.ca', 'email_transport_smtp.password'], $oParameters->GetRemoved());
|
||||
$this->assertSame([], $oParameters->GetInvalidLines());
|
||||
}
|
||||
|
||||
public function testRemovalWinsOverAddition(): void
|
||||
{
|
||||
$oParameters = new SensitiveParameters($this->GetCoreKeys(), "-foo.bar\n+foo.bar\n");
|
||||
$this->assertFalse($oParameters->IsSensitive('foo.bar'));
|
||||
}
|
||||
|
||||
public function testInvalidLinesAreReported(): void
|
||||
{
|
||||
$oParameters = new SensitiveParameters($this->GetCoreKeys(), "+\n- \ndb pwd\n\$x\n# ok\n+good.one\n");
|
||||
$this->assertSame([1 => '+', 2 => '- ', 3 => 'db pwd', 4 => '$x'], $oParameters->GetInvalidLines());
|
||||
$this->assertTrue($oParameters->IsSensitive('good.one'));
|
||||
$this->assertSame(self::BASELINE, array_values(array_diff($oParameters->GetEffective(), ['good.one'])));
|
||||
}
|
||||
|
||||
public function testSysInfoExclusionListIsPartOfTheBaseline(): void
|
||||
{
|
||||
$aExclusionList = class_exists(SysInfoConfig::class)
|
||||
? SysInfoConfig::EXCLUSION_LIST
|
||||
: ['db_pwd', 'default_pwd', 'email_transport_smtp.password', 'encryption_key', 'x509cert', 'privatekey'];
|
||||
$aBaseline = (new SensitiveParameters($this->GetCoreKeys()))->GetBaseline();
|
||||
foreach ($aExclusionList as $sKey) {
|
||||
$bFound = in_array($sKey, $aBaseline, true) || count(preg_grep('/\.'.preg_quote($sKey, '/').'$/', $aBaseline)) > 0;
|
||||
$this->assertTrue($bFound, "$sKey must be part of the baseline");
|
||||
}
|
||||
}
|
||||
|
||||
public function testWriteMaterializedFileOverwrites(): void
|
||||
{
|
||||
$sPath = $this->WriteFile('sensitive.parameters.env', "old content\n+hand.edit\n");
|
||||
$oParameters = new SensitiveParameters($this->GetCoreKeys(), "+my.custom\n");
|
||||
$this->assertTrue($oParameters->WriteMaterializedFile($sPath));
|
||||
$this->assertSame(SensitiveParameters::MATERIALIZED_HEADER."\n".implode("\n", self::BASELINE)."\n", file_get_contents($sPath));
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@
|
||||
|
||||
namespace Combodo\iTop\Test\UnitTest\Core;
|
||||
|
||||
use Combodo\iTop\Core\Config\Sensitive\SensitiveConfigStore;
|
||||
use Combodo\iTop\Test\UnitTest\ItopTestCase;
|
||||
use Config;
|
||||
use iTopConfigParser;
|
||||
@@ -213,10 +214,25 @@ CONF;
|
||||
*/
|
||||
public function testConfigWriteToFile_FromScratchInstallation()
|
||||
{
|
||||
$oConfig = new Config();
|
||||
clearstatcache();
|
||||
$oTestEnv = new RunTimeEnvironment('test-phpunit');
|
||||
$oTestEnv->WriteConfigFileSafe($oConfig);
|
||||
$this->assertTrue(true, "Config file was written");
|
||||
// N°10293: the setup creates the sensitive store, keep it out of the iTop conf directory
|
||||
$sSensitiveRoot = sys_get_temp_dir().'/itop-sensitive-'.bin2hex(random_bytes(6));
|
||||
putenv(SensitiveConfigStore::ENV_VAR.'='.$sSensitiveRoot);
|
||||
try {
|
||||
$oConfig = new Config();
|
||||
clearstatcache();
|
||||
$oTestEnv = new RunTimeEnvironment('test-phpunit');
|
||||
$oTestEnv->WriteConfigFileSafe($oConfig);
|
||||
$this->assertFileExists(SensitiveConfigStore::ForEnvironment('test-phpunit')->GetPath());
|
||||
$this->assertStringNotContainsString("'encryption_key'", file_get_contents(APPCONF.'test-phpunit/'.ITOP_CONFIG_FILE));
|
||||
} finally {
|
||||
putenv(SensitiveConfigStore::ENV_VAR);
|
||||
$sStore = $sSensitiveRoot.'/test-phpunit/'.SensitiveConfigStore::FILE_NAME;
|
||||
if (is_file($sStore)) {
|
||||
@chmod($sStore, 0600);
|
||||
unlink($sStore);
|
||||
rmdir(dirname($sStore));
|
||||
rmdir($sSensitiveRoot);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* @copyright Copyright (C) 2010-2026 Combodo SAS
|
||||
* @license http://opensource.org/licenses/AGPL-3.0
|
||||
*/
|
||||
|
||||
namespace Combodo\iTop\Test\UnitTest\Module\iTopConfig\Validator;
|
||||
|
||||
use Combodo\iTop\Config\Validator\iTopConfigSensitiveEnvValidator;
|
||||
use Combodo\iTop\Core\Config\Sensitive\SensitiveConfigStore;
|
||||
use Combodo\iTop\Test\UnitTest\ItopTestCase;
|
||||
|
||||
/**
|
||||
* N°10293 / D-035
|
||||
*/
|
||||
class iTopConfigSensitiveEnvValidatorTest extends ItopTestCase
|
||||
{
|
||||
private string $sDir;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->RequireOnceItopFile('core/config.class.inc.php');
|
||||
$this->RequireOnceItopFile('datamodels/2.x/itop-config/src/Validator/iTopConfigSensitiveEnvValidator.php');
|
||||
$this->sDir = sys_get_temp_dir().'/itop-sensitive-env-'.bin2hex(random_bytes(6));
|
||||
mkdir($this->sDir, 0700);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
array_map('unlink', glob($this->sDir.'/*'));
|
||||
rmdir($this->sDir);
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function testPlaceholderVariableNames(): void
|
||||
{
|
||||
$sPath = $this->sDir.'/'.SensitiveConfigStore::FILE_NAME;
|
||||
file_put_contents($sPath, "db_pwd: '%server(ITOP_DB_PWD)%'\nencryption_key: 'k-%env(ITOP_KEY)?:x%'\nnested.list: ['%env(ITOP_DB_PWD)%']\nplain: value\n");
|
||||
$this->assertSame(['ITOP_DB_PWD', 'ITOP_KEY'], (new SensitiveConfigStore($sPath))->GetPlaceholderVariableNames());
|
||||
}
|
||||
|
||||
private function IsRefused(string $sSettingsCode): bool
|
||||
{
|
||||
$sConfig = "<?php\n\$MyModuleSettings = array();\n\$MyModules = array();\n$sSettingsCode\n";
|
||||
$sFile = $this->sDir.'/submitted.php';
|
||||
file_put_contents($sFile, $sConfig);
|
||||
|
||||
return (new iTopConfigSensitiveEnvValidator(['ITOP_DB_PWD']))->Check($sConfig, $sFile);
|
||||
}
|
||||
|
||||
public function RefusedProvider(): array
|
||||
{
|
||||
return [
|
||||
'direct read' => ["\$MySettings = array('app_root_url' => \$_SERVER['ITOP_DB_PWD']);"],
|
||||
'case variation' => ["\$MySettings = array('app_root_url' => \$_SERVER['itop_db_pwd']);"],
|
||||
'env superglobal' => ["\$MySettings = array('app_root_url' => \$_ENV['ITOP_DB_PWD']);"],
|
||||
'concatenated index' => ["\$MySettings = array('app_root_url' => \$_SERVER['ITOP_'.'DB_PWD']);"],
|
||||
'variable index' => ["\$k = 'ITOP_DB_PWD';\n\$MySettings = array('app_root_url' => \$_SERVER[\$k]);"],
|
||||
'whole superglobal' => ["\$x = \$_SERVER;\n\$MySettings = array('app_root_url' => \$x['ITOP_DB_PWD']);"],
|
||||
'globals' => ["\$MySettings = array('app_root_url' => \$GLOBALS['_SERVER']['ITOP_DB_PWD']);"],
|
||||
'placeholder' => ["\$MySettings = array('app_root_url' => '%server(ITOP_DB_PWD)%');"],
|
||||
'env placeholder with default' => ["\$MySettings = array('app_root_url' => '%env(ITOP_DB_PWD)?:x%');"],
|
||||
'concatenated placeholder' => ["\$MySettings = array('app_root_url' => '%ser'.'ver(ITOP_DB_PWD)%');"],
|
||||
'module placeholder' => ["\$MySettings = array();\n\$MyModuleSettings = array('m' => array('p' => array('%env(ITOP_DB_PWD)%')));"],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider RefusedProvider
|
||||
*/
|
||||
public function testRefused(string $sSettingsCode): void
|
||||
{
|
||||
$this->assertTrue($this->IsRefused($sSettingsCode));
|
||||
}
|
||||
|
||||
public function AcceptedProvider(): array
|
||||
{
|
||||
return [
|
||||
'server name' => ["\$MySettings = array('app_root_url' => 'https://'.\$_SERVER['SERVER_NAME'].'/itop/');"],
|
||||
'isset server name' => ["\$MySettings = array('app_root_url' => isset(\$_SERVER['SERVER_NAME']) ? \$_SERVER['SERVER_NAME'] : 'localhost');"],
|
||||
'other placeholder' => ["\$MySettings = array('app_root_url' => '%env(OTHER_VAR)%');"],
|
||||
'plain' => ["\$MySettings = array('db_user' => 'itop');"],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider AcceptedProvider
|
||||
*/
|
||||
public function testAccepted(string $sSettingsCode): void
|
||||
{
|
||||
$this->assertFalse($this->IsRefused($sSettingsCode));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* @copyright Copyright (C) 2010-2026 Combodo SAS
|
||||
* @license http://opensource.org/licenses/AGPL-3.0
|
||||
*/
|
||||
|
||||
namespace Combodo\iTop\Test\UnitTest\Setup;
|
||||
|
||||
use Combodo\iTop\Test\UnitTest\ItopTestCase;
|
||||
use DBBackup;
|
||||
use ReflectionClass;
|
||||
|
||||
/**
|
||||
* N°10293: the sensitive store must never be part of an iTop backup
|
||||
*/
|
||||
class DBBackupSensitiveConfigTest extends ItopTestCase
|
||||
{
|
||||
private string $sDir;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->RequireOnceItopFile('setup/setuputils.class.inc.php');
|
||||
$this->RequireOnceItopFile('setup/backup.class.inc.php');
|
||||
$this->sDir = sys_get_temp_dir().'/itop-backup-sensitive-'.bin2hex(random_bytes(6));
|
||||
mkdir($this->sDir.'/src/conf/production', 0700, true);
|
||||
mkdir($this->sDir.'/src/conf/test', 0700, true);
|
||||
file_put_contents($this->sDir.'/src/conf/production/config-itop.php', '<?php');
|
||||
file_put_contents($this->sDir.'/src/conf/production/sensitive-config-itop.yml', 'db_pwd: secret');
|
||||
file_put_contents($this->sDir.'/src/conf/test/sensitive-config-itop.yml', 'db_pwd: secret');
|
||||
symlink($this->sDir.'/src/conf/production/sensitive-config-itop.yml', $this->sDir.'/src/conf/alias.txt');
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
exec('rm -rf '.escapeshellarg($this->sDir));
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
private function GetBackup(): DBBackup
|
||||
{
|
||||
return (new ReflectionClass(DBBackup::class))->newInstanceWithoutConstructor();
|
||||
}
|
||||
|
||||
public function testSensitiveFileIsDetectedByNameAndRealPath(): void
|
||||
{
|
||||
$oBackup = $this->GetBackup();
|
||||
$this->assertTrue($this->InvokeNonPublicMethod(DBBackup::class, 'IsSensitiveConfigFile', $oBackup, [$this->sDir.'/src/conf/production/sensitive-config-itop.yml']));
|
||||
$this->assertTrue($this->InvokeNonPublicMethod(DBBackup::class, 'IsSensitiveConfigFile', $oBackup, [$this->sDir.'/src/conf/alias.txt']));
|
||||
$this->assertFalse($this->InvokeNonPublicMethod(DBBackup::class, 'IsSensitiveConfigFile', $oBackup, [$this->sDir.'/src/conf/production/config-itop.php']));
|
||||
}
|
||||
|
||||
public function testCopiedDirectoryIsPurged(): void
|
||||
{
|
||||
$oBackup = $this->GetBackup();
|
||||
\SetupUtils::copydir($this->sDir.'/src/conf', $this->sDir.'/copy/conf');
|
||||
$this->InvokeNonPublicMethod(DBBackup::class, 'PurgeSensitiveConfigFiles', $oBackup, [$this->sDir.'/src/conf', $this->sDir.'/copy/conf']);
|
||||
|
||||
$this->assertFileExists($this->sDir.'/copy/conf/production/config-itop.php');
|
||||
$this->assertFileDoesNotExist($this->sDir.'/copy/conf/production/sensitive-config-itop.yml');
|
||||
$this->assertFileDoesNotExist($this->sDir.'/copy/conf/test/sensitive-config-itop.yml');
|
||||
$this->assertFalse(is_link($this->sDir.'/copy/conf/alias.txt') || file_exists($this->sDir.'/copy/conf/alias.txt'));
|
||||
// Source is left untouched
|
||||
$this->assertFileExists($this->sDir.'/src/conf/production/sensitive-config-itop.yml');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* @copyright Copyright (C) 2010-2026 Combodo SAS
|
||||
* @license http://opensource.org/licenses/AGPL-3.0
|
||||
*/
|
||||
|
||||
namespace Combodo\iTop\Test\UnitTest\Setup;
|
||||
|
||||
use Combodo\iTop\Core\Config\Sensitive\SensitiveConfigStore;
|
||||
use Config;
|
||||
use ConfigException;
|
||||
use FileLog;
|
||||
use LogAPI;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use ReflectionProperty;
|
||||
use RunTimeEnvironment;
|
||||
use SetupLog;
|
||||
|
||||
/** @since 3.2.4 N°10293 */
|
||||
class RunTimeEnvironmentTest extends TestCase
|
||||
{
|
||||
/** @since 3.2.4 N°10293 */
|
||||
private string $sRoot;
|
||||
/** @since 3.2.4 N°10293 */
|
||||
private $sPreviousEnv;
|
||||
/**
|
||||
* @var array{0: ?FileLog, 1: ?Config}
|
||||
* @since 3.2.4 N°10293
|
||||
*/
|
||||
private array $aPreviousLogState;
|
||||
/** @since 3.2.4 N°10293 */
|
||||
private FileLog $oFileLog;
|
||||
|
||||
/** @since 3.2.4 N°10293 */
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
require_once dirname(__DIR__, 4).'/approot.inc.php';
|
||||
require_once APPROOT.'setup/runtimeenv.class.inc.php';
|
||||
|
||||
$this->sRoot = sys_get_temp_dir().'/itop-optional-config-'.bin2hex(random_bytes(6));
|
||||
mkdir($this->sRoot, 0700);
|
||||
$this->sPreviousEnv = getenv(SensitiveConfigStore::ENV_VAR);
|
||||
putenv(SensitiveConfigStore::ENV_VAR.'='.$this->sRoot);
|
||||
|
||||
$oLogProperty = new ReflectionProperty(SetupLog::class, 'm_oFileLog');
|
||||
$oLogProperty->setAccessible(true);
|
||||
$oConfigProperty = new ReflectionProperty(LogAPI::class, 'm_oMockMetaModelConfig');
|
||||
$oConfigProperty->setAccessible(true);
|
||||
$this->aPreviousLogState = [$oLogProperty->getValue(), $oConfigProperty->getValue()];
|
||||
$this->oFileLog = $this->createMock(FileLog::class);
|
||||
$oLogConfig = new Config(null, false);
|
||||
$oLogConfig->Set('log_level_min', LogAPI::LEVEL_TRACE);
|
||||
$oLogConfig->Set('log_level_min.write_in_db', false);
|
||||
SetupLog::MockStaticObjects($this->oFileLog, $oLogConfig);
|
||||
}
|
||||
|
||||
/** @since 3.2.4 N°10293 */
|
||||
protected function tearDown(): void
|
||||
{
|
||||
SetupLog::MockStaticObjects(...$this->aPreviousLogState);
|
||||
putenv($this->sPreviousEnv === false ? SensitiveConfigStore::ENV_VAR : SensitiveConfigStore::ENV_VAR.'='.$this->sPreviousEnv);
|
||||
$sDirectory = $this->sRoot.'/production';
|
||||
if (is_dir($sDirectory)) {
|
||||
foreach (scandir($sDirectory) as $sFile) {
|
||||
if ($sFile !== '.' && $sFile !== '..') {
|
||||
unlink($sDirectory.'/'.$sFile);
|
||||
}
|
||||
}
|
||||
rmdir($sDirectory);
|
||||
} elseif (is_file($sDirectory)) {
|
||||
unlink($sDirectory);
|
||||
}
|
||||
rmdir($this->sRoot);
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider GetInactiveStoreEnvironments
|
||||
* @since 3.2.4 N°10293
|
||||
*/
|
||||
public function testPrepareSensitiveConfigStoreWithoutFile(string $sEnvironment, bool $bAutoCommit): void
|
||||
{
|
||||
$this->oFileLog->expects($this->never())->method('Info');
|
||||
$this->oFileLog->expects($this->never())->method('Warning');
|
||||
$oConfig = $this->CreateConfig();
|
||||
$sBefore = $oConfig->RenderFileContent();
|
||||
|
||||
(new RunTimeEnvironment($sEnvironment, $bAutoCommit))->PrepareSensitiveConfigStore($oConfig);
|
||||
|
||||
$this->assertFalse($oConfig->IsSensitiveStoreActive());
|
||||
$this->assertNull($oConfig->GetSensitiveConfigStore());
|
||||
$this->assertSame($sBefore, $oConfig->RenderFileContent());
|
||||
$this->assertSame('classic_pwd', $oConfig->Get('db_pwd'));
|
||||
$this->assertSame('classic_key', $oConfig->GetEncryptionKey());
|
||||
$this->assertSame(['.', '..'], scandir($this->sRoot));
|
||||
}
|
||||
|
||||
/** @since 3.2.4 N°10293 */
|
||||
public function testInitializeSensitiveConfigStoreForInstallation(): void
|
||||
{
|
||||
$this->oFileLog->expects($this->once())->method('Info');
|
||||
$this->oFileLog->expects($this->never())->method('Warning');
|
||||
$oConfig = $this->CreateConfig();
|
||||
$oEnvironment = new class ('production') extends RunTimeEnvironment {
|
||||
/** @since 3.2.4 N°10293 */
|
||||
protected function InitializeSensitiveConfigStore(Config $oConfig, SensitiveConfigStore $oStore): void
|
||||
{
|
||||
// Isolate classification overrides from the installed instance.
|
||||
parent::InitializeSensitiveConfigStore($oConfig, new SensitiveConfigStore($oStore->GetPath(), null, dirname($oStore->GetPath()).'/sensitive.parameters.env.local'));
|
||||
}
|
||||
};
|
||||
|
||||
$oEnvironment->InitializeSensitiveConfigStoreForInstallation($oConfig);
|
||||
$oStore = new SensitiveConfigStore(SensitiveConfigStore::ForEnvironment('production')->GetPath(), null, $this->sRoot.'/production/sensitive.parameters.env.local');
|
||||
$this->assertTrue($oStore->IsActive());
|
||||
$this->assertSame('classic_pwd', $oStore->Get('db_pwd'));
|
||||
$this->assertSame('classic_key', $oStore->Get('encryption_key'));
|
||||
$this->assertSame('smtp_pwd', $oStore->Get('email_transport_smtp.password'));
|
||||
$this->assertSame('ldap_pwd', $oStore->Get('authent-ldap.default_pwd'));
|
||||
|
||||
$oConfig->BindSensitiveConfigStore($oStore);
|
||||
$sContent = $oConfig->RenderFileContent();
|
||||
foreach (['db_pwd', 'encryption_key', 'email_transport_smtp.password', 'default_pwd'] as $sKey) {
|
||||
$this->assertStringNotContainsString("'$sKey' =>", $sContent);
|
||||
}
|
||||
$this->assertStringContainsString("'host' => 'ldap.example.com'", $sContent);
|
||||
}
|
||||
|
||||
/** @since 3.2.4 N°10293 */
|
||||
public function testInitializeSensitiveConfigStoreForInstallationPreservesExistingFile(): void
|
||||
{
|
||||
$this->oFileLog->expects($this->never())->method('Info');
|
||||
$this->oFileLog->expects($this->never())->method('Warning');
|
||||
mkdir($this->sRoot.'/production', 0700);
|
||||
$sPath = $this->sRoot.'/production/'.SensitiveConfigStore::FILE_NAME;
|
||||
$sContent = "db_pwd: existing_pwd\nencryption_key: existing_key\n";
|
||||
file_put_contents($sPath, $sContent);
|
||||
|
||||
(new RunTimeEnvironment('production'))->InitializeSensitiveConfigStoreForInstallation($this->CreateConfig());
|
||||
|
||||
$this->assertSame($sContent, file_get_contents($sPath));
|
||||
}
|
||||
|
||||
/** @since 3.2.4 N°10293 */
|
||||
public function testInitializeSensitiveConfigStoreForInstallationFailureIsBlocking(): void
|
||||
{
|
||||
$this->oFileLog->expects($this->never())->method('Info');
|
||||
$this->oFileLog->expects($this->once())->method('Warning');
|
||||
file_put_contents($this->sRoot.'/production', 'not a directory');
|
||||
|
||||
$this->expectException(ConfigException::class);
|
||||
$this->expectExceptionMessage('Could not initialize the sensitive configuration file for the new installation');
|
||||
(new RunTimeEnvironment('production'))->InitializeSensitiveConfigStoreForInstallation($this->CreateConfig());
|
||||
}
|
||||
|
||||
/** @since 3.2.4 N°10293 */
|
||||
private function CreateConfig(): Config
|
||||
{
|
||||
$oConfig = new Config(null, false);
|
||||
$oConfig->Set('db_pwd', 'classic_pwd');
|
||||
$oConfig->SetEncryptionKey('classic_key');
|
||||
$oConfig->Set('email_transport_smtp.password', 'smtp_pwd');
|
||||
$oConfig->SetModuleSetting('authent-ldap', 'default_pwd', 'ldap_pwd');
|
||||
$oConfig->SetModuleSetting('authent-ldap', 'host', 'ldap.example.com');
|
||||
|
||||
return $oConfig;
|
||||
}
|
||||
|
||||
/** @since 3.2.4 N°10293 */
|
||||
public static function GetInactiveStoreEnvironments(): array
|
||||
{
|
||||
return [
|
||||
'direct environment preparation' => ['production', true],
|
||||
'staged upgrade' => ['production', false],
|
||||
'build environment' => ['production-build', true],
|
||||
];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user