Skip to content

Commit 0790169

Browse files
Validate message categories when yii\i18n\PhpMessageSource loads messages, covering getMessageFilePath() overrides. (#21155)
1 parent cd4208c commit 0790169

5 files changed

Lines changed: 147 additions & 9 deletions

File tree

‎framework/CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@ Yii Framework 2 Change Log
9999
- Bug #21141: Allow the `__class` key in configuration arrays in `@return` annotations for `yii\base\Component::behaviors()` and `yii\base\Controller::actions()`, and in the `@var` annotation for `yii\filters\auth\CompositeAuth::$authMethods` (mspirkov)
100100
- Enh #21142: Add `@throws` annotation for `InvalidConfigException` in `yii\base\Component::__set()` (mspirkov)
101101
- Enh #21147: Add `@template` annotation for `$default` in `yii\web\HeaderCollection::get()` (mspirkov)
102+
- Enh #21155: Validate message categories when `yii\i18n\PhpMessageSource` loads messages, covering `getMessageFilePath()` overrides (terabytesoftw)
102103

103104

104105
2.0.55 May 09, 2026

‎framework/UPGRADE.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,10 @@ Upgrade from Yii 2.0.55
9999
publishes to new directories, and the old symlinks to the whole source directories, including the files excluded
100100
by the filters, stay accessible under the old URLs. Only when a custom `hashCallback` keeps the name of the
101101
published directory across the upgrade is the existing symlink replaced automatically on the next publish.
102+
* `yii\i18n\PhpMessageSource` now rejects message categories that contain `..` segments, an absolute path or a
103+
stream-wrapper scheme (such as `php://`) with `yii\base\InvalidArgumentException`, unless they are listed in
104+
`fileMap`. The check runs when messages are loaded, before `getMessageFilePath()` is called, so it also applies to
105+
subclasses that override `getMessageFilePath()`, and such overrides receive only categories that passed it.
102106

103107
Upgrade from Yii 2.0.53
104108
-----------------------

‎framework/i18n/PhpMessageSource.php‎

Lines changed: 47 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -65,14 +65,20 @@ class PhpMessageSource extends MessageSource
6565
* load the messages for [[sourceLanguage]]. For example: [[sourceLanguage]] is `en-GB`,
6666
* $language is `en`. The method will load the messages for `en` and merge them over `en-GB`.
6767
*
68+
* The category is validated before [[getMessageFilePath()]] is called, so the check described there also applies
69+
* when a subclass overrides that method.
70+
*
6871
* @param string $category the message category
6972
* @param string $language the target language
7073
* @return array the loaded messages. The keys are original messages, and the values are the translated messages.
74+
* @throws InvalidArgumentException if the category resolves to an unsafe path, or the language code is invalid.
7175
* @see loadFallbackMessages
7276
* @see sourceLanguage
7377
*/
7478
protected function loadMessages($category, $language)
7579
{
80+
$this->validateCategory($category);
81+
7682
$messageFile = $this->getMessageFilePath($category, $language);
7783
$messages = $this->loadMessagesFromFile($messageFile);
7884

@@ -133,7 +139,10 @@ protected function loadFallbackMessages($category, $fallbackLanguage, $messages,
133139
*
134140
* The category may use `/` or `\` as namespace separators (for example, `app/error`). Categories that contain `..`
135141
* segments, an absolute path, or a stream-wrapper scheme (such as `php://`) are rejected so the resolved path
136-
* cannot escape [[basePath]].
142+
* cannot escape [[basePath]]. Categories listed in [[fileMap]] are not checked.
143+
*
144+
* [[loadMessages()]] applies the same category check before calling this method, so an overriding implementation
145+
* receives only categories that passed it.
137146
*
138147
* @param string $category the message category
139148
* @param string $language the target language
@@ -143,25 +152,54 @@ protected function loadFallbackMessages($category, $fallbackLanguage, $messages,
143152
protected function getMessageFilePath($category, $language)
144153
{
145154
$language = (string) $language;
155+
146156
if ($language !== '' && !preg_match('/^[a-z0-9_-]+$/i', $language)) {
147157
throw new InvalidArgumentException(sprintf('Invalid language code: "%s".', $language));
148158
}
159+
160+
$this->validateCategory($category);
161+
149162
$messageFile = Yii::getAlias($this->basePath) . "/$language/";
163+
150164
if (isset($this->fileMap[$category])) {
151165
$messageFile .= $this->fileMap[$category];
152166
} else {
153-
$normalizedCategory = str_replace('\\', '/', (string) $category);
167+
$messageFile .= str_replace('\\', '/', (string) $category) . '.php';
168+
}
154169

155-
if (preg_match('~(?:^|/)\.\.(?:/|$)|^/|^[A-Za-z]:/|^[A-Za-z][A-Za-z0-9+.\-]*://~', $normalizedCategory)) {
156-
throw new InvalidArgumentException(
157-
sprintf('Invalid message category: "%s".', (string) $category),
158-
);
159-
}
170+
return $messageFile;
171+
}
160172

161-
$messageFile .= "{$normalizedCategory}.php";
173+
/**
174+
* Rejects a category that would resolve to a path outside [[basePath]].
175+
*
176+
* Backslashes are treated as `/` separators. A category that contains a `..` segment, starts with `/` or a drive
177+
* letter (such as `C:/`), or starts with a stream-wrapper scheme (such as `php://`) is rejected. A segment that
178+
* consists only of dots and spaces and has two or more dots (such as `.. ` or `...`) is treated as a `..` segment.
179+
* Categories listed in [[fileMap]] are trusted configuration and are not checked.
180+
*
181+
* @param string $category the message category
182+
* @throws InvalidArgumentException if the category resolves to an unsafe path.
183+
*/
184+
private function validateCategory($category)
185+
{
186+
if (isset($this->fileMap[$category])) {
187+
return;
162188
}
163189

164-
return $messageFile;
190+
$normalizedCategory = str_replace('\\', '/', (string) $category);
191+
192+
// A segment made only of dots and spaces with at least two dots is rejected, not just a literal `..`:
193+
// Windows may trim trailing dots and spaces from path components. The quantifiers are possessive so a long
194+
// run of dots cannot exhaust the backtrack limit.
195+
$pattern = '~(?:^|/) *+\. *+\.[. ]*+(?:/|$)|^/|^[A-Za-z]:/|^[A-Za-z][A-Za-z0-9+.\-]*://~';
196+
197+
// `preg_match()` returns `false` when matching fails to complete; such a category is rejected as well.
198+
if (preg_match($pattern, $normalizedCategory) !== 0) {
199+
throw new InvalidArgumentException(
200+
sprintf('Invalid message category: "%s".', (string) $category),
201+
);
202+
}
165203
}
166204

167205
/**

‎tests/framework/i18n/PhpMessageSourceTest.php‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
use Yii;
1414
use yii\base\InvalidArgumentException;
1515
use yiiunit\framework\i18n\stubs\ExposedPhpMessageSource;
16+
use yiiunit\framework\i18n\stubs\OverriddenPathPhpMessageSource;
1617
use yiiunit\TestCase;
1718

1819
/**
@@ -41,7 +42,12 @@ public static function unsafeCategoryProvider(): array
4142
'absolute unix path' => ['/etc/passwd'],
4243
'bare parent segment' => ['..'],
4344
'embedded traversal segment' => ['app/../../config/db'],
45+
'embedded traversal segment with dots and spaces' => ['app/. ./config/db'],
46+
'embedded traversal segment with extra dot' => ['app/.../config/db'],
47+
'embedded traversal segment with leading space' => ['app/ ../config/db'],
48+
'embedded traversal segment with trailing space' => ['app/.. /config/db'],
4449
'leading traversal segment' => ['../secret'],
50+
'long run of dots before traversal segment' => [str_repeat('.', 8192) . 'x/../secret'],
4551
'parent traversal' => ['../../etc/passwd'],
4652
'phar stream wrapper' => ['phar://archive.phar/config'],
4753
'php stream wrapper' => ['php://filter/resource=config/db'],
@@ -194,4 +200,55 @@ public function testReturnFileMapPathForMappedCategory(): void
194200
'fileMap entry must bypass category validation.',
195201
);
196202
}
203+
204+
/**
205+
* @dataProvider unsafeCategoryProvider
206+
*/
207+
public function testThrowInvalidArgumentExceptionForUnsafeCategoryWithOverriddenMessageFilePath(
208+
string $category
209+
): void {
210+
$source = new OverriddenPathPhpMessageSource(['basePath' => '@yiiunit/data/i18n/messages']);
211+
212+
$this->expectException(InvalidArgumentException::class);
213+
$this->expectExceptionMessage('Invalid message category:');
214+
215+
$source->translate($category, 'Hello world!', 'de');
216+
}
217+
218+
public function testTranslateSafeCategoryWithOverriddenMessageFilePath(): void
219+
{
220+
$source = new OverriddenPathPhpMessageSource(['basePath' => '@yiiunit/data/i18n/messages']);
221+
222+
$this->assertSame(
223+
'Hallo Welt!',
224+
$source->translate('test', 'Hello world!', 'de'),
225+
'Override must still resolve valid categories.',
226+
);
227+
$this->assertSame(
228+
['test'],
229+
$source->requestedCategories,
230+
'Valid category must reach the override unchanged.',
231+
);
232+
}
233+
234+
public function testTranslateMappedCategoryWithOverriddenMessageFilePath(): void
235+
{
236+
$source = new OverriddenPathPhpMessageSource(
237+
[
238+
'basePath' => '@yiiunit/data/i18n/messages',
239+
'fileMap' => ['weird/../category' => 'test.php'],
240+
],
241+
);
242+
243+
$this->assertSame(
244+
'Hallo Welt!',
245+
$source->translate('weird/../category', 'Hello world!', 'de'),
246+
'fileMap entry must bypass category validation.',
247+
);
248+
$this->assertSame(
249+
['weird/../category'],
250+
$source->requestedCategories,
251+
'Mapped category must reach the override unchanged.',
252+
);
253+
}
197254
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<?php
2+
3+
/**
4+
* @link https://www.yiiframework.com/
5+
* @copyright Copyright (c) 2008 Yii Software LLC
6+
* @license https://www.yiiframework.com/license/
7+
*/
8+
9+
namespace yiiunit\framework\i18n\stubs;
10+
11+
use Yii;
12+
use yii\i18n\PhpMessageSource;
13+
14+
/**
15+
* Test double overriding {@see PhpMessageSource::getMessageFilePath()} without calling the parent implementation.
16+
*
17+
* Records every category the override receives, so tests can assert which categories reach it.
18+
*/
19+
class OverriddenPathPhpMessageSource extends PhpMessageSource
20+
{
21+
/**
22+
* @var string[] categories passed to {@see getMessageFilePath()}, in call order.
23+
*/
24+
public $requestedCategories = [];
25+
26+
protected function getMessageFilePath($category, $language)
27+
{
28+
$this->requestedCategories[] = $category;
29+
30+
$messageFile = Yii::getAlias($this->basePath) . "/$language/";
31+
32+
if (isset($this->fileMap[$category])) {
33+
return $messageFile . $this->fileMap[$category];
34+
}
35+
36+
return $messageFile . str_replace('\\', '/', $category) . '.php';
37+
}
38+
}

0 commit comments

Comments
 (0)