Files
iTop/sources/Core/Config/Sensitive/SensitiveConfigStore.php
2026-11-30 15:19:26 +01:00

267 lines
8.5 KiB
PHP

<?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;
}
}