Skip to content

Commit ec9311b

Browse files
lonnieezellclaude
andcommitted
fix(#10615): re-read live env vars on every config build
Cache only the names of env vars found with live getenv() calls, per leaf, and re-read their values on each build, so removed or changed values are not reused. Leaves first seen on a later instance are now probed too. On Windows, probe the underscore forms live as well, so they keep matching case-insensitively. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent a0190c5 commit ec9311b

5 files changed

Lines changed: 126 additions & 35 deletions

File tree

‎system/Config/BaseConfig.php‎

Lines changed: 55 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -86,12 +86,22 @@ class BaseConfig
8686
private static ?array $envSnapshot = null;
8787

8888
/**
89-
* Env vars found with live getenv() calls on each class's first build, keyed
90-
* by class name. The getenv() array omits names that contain ".", " " or "[".
89+
* Env var names that exist according to live getenv() calls, keyed by class
90+
* name, then by leaf name. Each leaf is probed once; its names are re-read on
91+
* every build. The getenv() array omits names that contain ".", " " or "[",
92+
* and on Windows only live calls match names case-insensitively.
9193
*
92-
* @var array<class-string, array<string, string>>
94+
* @var array<class-string, array<string, list<string>>>
9395
*/
94-
private static array $unlistedEnvVars = [];
96+
private static array $liveEnvNames = [];
97+
98+
/**
99+
* The property values of each class's last build, and the env var names of
100+
* all its leaves from $liveEnvNames, keyed by class name.
101+
*
102+
* @var array<class-string, array{array<string, mixed>, list<string>}>
103+
*/
104+
private static array $liveEnvLeaves = [];
95105

96106
/**
97107
* Whether a class overrides getEnvValue() or initEnvValue(), keyed by class name.
@@ -138,8 +148,8 @@ public static function reset(): void
138148
static::$didDiscovery = false;
139149
static::$moduleConfig = null;
140150

141-
self::$envIndex = self::$envSnapshot = null;
142-
self::$unlistedEnvVars = [];
151+
self::$envIndex = self::$envSnapshot = null;
152+
self::$liveEnvNames = self::$liveEnvLeaves = [];
143153
}
144154

145155
/**
@@ -170,8 +180,21 @@ public function __construct()
170180
: self::scopedEnvSources($prefix, $shortPrefix);
171181

172182
if ($sources !== null) {
173-
$sources['getenv'] = (self::$unlistedEnvVars[static::class] ??= self::findUnlistedEnvVars($values, $prefix, $shortPrefix))
174-
+ $sources['getenv'];
183+
// Unchanged property values share memory with the stored ones, so the
184+
// leaves are only walked again when a build changes them.
185+
if (($leaves = self::$liveEnvLeaves[static::class] ?? null) === null || $leaves[0] !== $values) {
186+
$leaves = self::$liveEnvLeaves[static::class] = [$values, self::findLiveEnvNames($values, $prefix, $shortPrefix)];
187+
}
188+
189+
$live = [];
190+
191+
foreach ($leaves[1] as $envKey) {
192+
if (($envValue = getenv($envKey)) !== false) {
193+
$live[$envKey] = $envValue;
194+
}
195+
}
196+
197+
$sources['getenv'] = $live + $sources['getenv'];
175198

176199
// Every env var that can override this class, for a fast miss check per leaf.
177200
$candidates = $sources['env'] + $sources['server'] + $sources['getenv'];
@@ -389,37 +412,47 @@ private static function scopedEnvSources(string $prefix, string $shortPrefix): a
389412
}
390413

391414
/**
392-
* Looks up, with getenv(), every leaf's env var names that the getenv()
393-
* array omits.
415+
* Returns every leaf's env var names that exist according to live getenv()
416+
* calls. Only leaves not seen before are probed.
394417
*
418+
* @param class-string $prefix
395419
* @param array<array-key, mixed> $values
396420
*
397-
* @return array<string, string>
421+
* @return list<string>
398422
*/
399-
private static function findUnlistedEnvVars(array $values, string $prefix, string $shortPrefix, string $parent = ''): array
423+
private static function findLiveEnvNames(array $values, string $prefix, string $shortPrefix, string $parent = ''): array
400424
{
401425
$found = [];
402426

403427
foreach ($values as $key => $value) {
404428
$name = $parent === '' ? (string) $key : "{$parent}.{$key}";
405429

406430
if (is_array($value)) {
407-
$found += self::findUnlistedEnvVars($value, $prefix, $shortPrefix, $name);
431+
array_push($found, ...self::findLiveEnvNames($value, $prefix, $shortPrefix, $name));
408432

409433
continue;
410434
}
411435

412-
// Dot forms always contain "."; underscore forms only need a live
413-
// lookup when the name itself contains " " or "[".
414-
$envKeys = strpbrk($name, ' [') === false
415-
? ["{$shortPrefix}.{$name}", "{$prefix}.{$name}"]
416-
: self::envKeys($name, $prefix, $shortPrefix);
417-
418-
foreach ($envKeys as $envKey) {
419-
if (($envValue = getenv($envKey)) !== false) {
420-
$found[$envKey] = $envValue;
436+
if (! isset(self::$liveEnvNames[$prefix][$name])) {
437+
self::$liveEnvNames[$prefix][$name] = [];
438+
439+
// Dot forms are never in the getenv() array, and underscore forms
440+
// only miss it when the name has " " or "[". On Windows, env var
441+
// names are case-insensitive, but only live getenv() calls match
442+
// them that way, so every form is probed there. Elsewhere that
443+
// would double the getenv() calls on a cold build for no gain.
444+
$envKeys = PHP_OS_FAMILY === 'Windows' || strpbrk($name, ' [') !== false
445+
? self::envKeys($name, $prefix, $shortPrefix)
446+
: ["{$shortPrefix}.{$name}", "{$prefix}.{$name}"];
447+
448+
foreach ($envKeys as $envKey) {
449+
if (getenv($envKey) !== false) {
450+
self::$liveEnvNames[$prefix][$name][] = $envKey;
451+
}
421452
}
422453
}
454+
455+
array_push($found, ...self::$liveEnvNames[$prefix][$name]);
423456
}
424457

425458
return $found;

‎tests/system/Config/BaseConfigTest.php‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
use CustomEnvHookConfig;
2222
use Encryption;
2323
use EnvIndexConfig;
24+
use GrowingEnvConfig;
2425
use MergeRegistrarConfig;
2526
use PHPUnit\Framework\Attributes\DataProvider;
2627
use PHPUnit\Framework\Attributes\Group;
@@ -71,7 +72,7 @@ protected function setUp(): void
7172
require $this->fixturesFolder . '/Encryption.php';
7273
}
7374

74-
foreach (['EnvIndexConfig', 'Snake_Config', 'CustomEnvHookConfig'] as $class) {
75+
foreach (['EnvIndexConfig', 'Snake_Config', 'CustomEnvHookConfig', 'GrowingEnvConfig'] as $class) {
7576
if (! class_exists($class, false)) {
7677
require $this->fixturesFolder . '/' . $class . '.php';
7778
}
@@ -87,6 +88,7 @@ protected function tearDown(): void
8788
parent::tearDown();
8889

8990
$this->clearEnvironmentOverrides();
91+
GrowingEnvConfig::$grow = false;
9092
// This test modifies BaseConfig::$modules, so should reset.
9193
BaseConfig::reset();
9294
// This test modifies Services locator, so should reset.
@@ -112,6 +114,7 @@ private function clearEnvironmentOverrides(): void
112114
'snake_config.name',
113115
'Snake_Config_name',
114116
'customenvhookconfig.name',
117+
'growingenvconfig.list.added',
115118
] as $key) {
116119
putenv($key);
117120
unset($_ENV[$key]);
@@ -557,4 +560,28 @@ public function testGetenvOnlyNameWithSpace(): void
557560

558561
$this->assertSame('from-getenv', (new EnvIndexConfig())->list['some key']);
559562
}
563+
564+
public function testRemovedGetenvOnlyNameIsNotReused(): void
565+
{
566+
putenv('envindexconfig.name=old');
567+
$_ENV['envindexconfig.name'] = 'old';
568+
service('superglobals')->setServer('envindexconfig.name', 'old');
569+
$this->assertSame('old', (new EnvIndexConfig())->name);
570+
571+
putenv('envindexconfig.name');
572+
unset($_ENV['envindexconfig.name']);
573+
service('superglobals')->unsetServer('envindexconfig.name');
574+
575+
$this->assertSame('default', (new EnvIndexConfig())->name);
576+
}
577+
578+
public function testGetenvOnlyNameForLeafAddedOnLaterInstance(): void
579+
{
580+
putenv('growingenvconfig.list.added=from-getenv');
581+
$this->assertSame(['key' => 'default'], (new GrowingEnvConfig())->list);
582+
583+
GrowingEnvConfig::$grow = true;
584+
585+
$this->assertSame(['key' => 'default', 'added' => 'from-getenv'], (new GrowingEnvConfig())->list);
586+
}
560587
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* This file is part of CodeIgniter 4 framework.
7+
*
8+
* (c) CodeIgniter Foundation <admin@codeigniter.com>
9+
*
10+
* For the full copyright and license information, please view
11+
* the LICENSE file that was distributed with this source code.
12+
*/
13+
14+
use CodeIgniter\Config\BaseConfig;
15+
16+
/**
17+
* Adds an array leaf only when $grow is set, like a constructor or registrar
18+
* that changes the shape between instances.
19+
*/
20+
class GrowingEnvConfig extends BaseConfig
21+
{
22+
public static bool $grow = false;
23+
24+
/**
25+
* @var array<string, string>
26+
*/
27+
public array $list = ['key' => 'default'];
28+
29+
public function __construct()
30+
{
31+
if (self::$grow) {
32+
$this->list['added'] = 'default';
33+
}
34+
35+
parent::__construct();
36+
}
37+
}

‎user_guide_src/source/changelogs/v4.8.0.rst‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,8 +64,7 @@ Behavior Changes
6464
- **Config:** ``CodeIgniter\Config\BaseService`` is now ``abstract``. It is intended to be extended (as ``Config\Services`` does) and accessed statically; code that instantiated it directly with ``new BaseService()`` will now throw an ``Error``.
6565
- **Config:** ``BaseConfig`` now scans the environment once instead of checking every property against it, which makes building config classes
6666
several times faster without config caching and in Worker Mode. As a result, a bare ``putenv()`` call made after the first config class was built
67-
may not be seen until ``BaseConfig::reset()`` runs, and on Windows, underscore-form environment variables that exist only in the OS environment
68-
now match case-sensitively. See :ref:`upgrade-480-config-env-lookups`.
67+
may not be seen until ``BaseConfig::reset()`` runs. See :ref:`upgrade-480-config-env-lookups`.
6968
- **Database:** The Postgre driver's ``$db->error()['code']`` previously always returned ``''``. It now returns the 5-character SQLSTATE string for query and transaction failures (e.g., ``'42P01'``), or ``'08006'`` for connection-level failures. Code that relied on ``$db->error()['code'] === ''`` will need updating.
7069
- **Debug:** ``CodeIgniter\Debug\Toolbar\Collectors\BaseCollector`` is now ``abstract``. Custom toolbar collectors must extend it; code that instantiated it directly with ``new BaseCollector()`` will now throw an ``Error``.
7170
- **Filters:** HTTP method matching for method-based filters is now case-sensitive. The keys in ``Config\Filters::$methods`` must exactly match the request method

‎user_guide_src/source/installation/upgrade_480.rst‎

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -167,16 +167,11 @@ Config Environment Lookups
167167

168168
``BaseConfig`` now reads the environment once and reuses the result, instead of
169169
looking up every property of every config class. The matching rules and their
170-
order are unchanged. Two edge cases behave differently:
171-
172-
- A ``putenv()`` call that does not also write ``$_ENV`` or ``$_SERVER``, made
173-
after the first config class was built, may not be seen by config classes
174-
built later until ``BaseConfig::reset()`` runs. Values loaded from the
175-
**.env** file are not affected, since they are written to ``$_ENV`` and
176-
``$_SERVER`` as well.
177-
- On Windows, environment variables in the underscore form (e.g.,
178-
``app_baseURL``) that exist only in the OS environment now match
179-
case-sensitively, like the values from the **.env** file already did.
170+
order are unchanged. One edge case behaves differently: a ``putenv()`` call
171+
that does not also write ``$_ENV`` or ``$_SERVER``, made after the first config
172+
class was built, may not be seen by config classes built later until
173+
``BaseConfig::reset()`` runs. Values loaded from the **.env** file are not
174+
affected, since they are written to ``$_ENV`` and ``$_SERVER`` as well.
180175

181176
Config classes that override ``getEnvValue()`` or ``initEnvValue()`` keep the
182177
previous behavior.

0 commit comments

Comments
 (0)