File size: 16,224 Bytes
e6beeb1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
diff --git a/typo3/sysext/backend/Classes/Controller/SiteConfigurationController.php b/typo3/sysext/backend/Classes/Controller/SiteConfigurationController.php
index 96745e424e99..fdf6d6271cb4 100644
--- a/typo3/sysext/backend/Classes/Controller/SiteConfigurationController.php
+++ b/typo3/sysext/backend/Classes/Controller/SiteConfigurationController.php
@@ -411,7 +411,7 @@ protected function saveAction(ServerRequestInterface $request): ResponseInterfac
                     $siteConfigurationManager->rename($currentIdentifier, $siteIdentifier);
                     $this->getBackendUser()->writelog(Type::SITE, SiteAction::RENAME, SystemLogErrorClassification::MESSAGE, 0, 'Site configuration \'%s\' was renamed to \'%s\'.', [$currentIdentifier, $siteIdentifier], 'site');
                 }
-                $siteConfigurationManager->write($siteIdentifier, $newSiteConfiguration);
+                $siteConfigurationManager->write($siteIdentifier, $newSiteConfiguration, true);
                 if ($isNewConfiguration) {
                     $this->getBackendUser()->writelog(Type::SITE, SiteAction::CREATE, SystemLogErrorClassification::MESSAGE, 0, 'Site configuration \'%s\' was created.', [$siteIdentifier], 'site');
                 } else {
diff --git a/typo3/sysext/core/Classes/Configuration/Loader/Exception/YamlPlaceholderException.php b/typo3/sysext/core/Classes/Configuration/Loader/Exception/YamlPlaceholderException.php
new file mode 100644
index 000000000000..3457557b2c10
--- /dev/null
+++ b/typo3/sysext/core/Classes/Configuration/Loader/Exception/YamlPlaceholderException.php
@@ -0,0 +1,22 @@
+<?php
+
+declare(strict_types=1);
+
+/*
+ * This file is part of the TYPO3 CMS project.
+ *
+ * It is free software; you can redistribute it and/or modify it under
+ * the terms of the GNU General Public License, either version 2
+ * of the License, or any later version.
+ *
+ * For the full copyright and license information, please read the
+ * LICENSE.txt file that was distributed with this source code.
+ *
+ * The TYPO3 project - inspiring people to share!
+ */
+
+namespace TYPO3\CMS\Core\Configuration\Loader\Exception;
+
+class YamlPlaceholderException extends \RuntimeException
+{
+}
diff --git a/typo3/sysext/core/Classes/Configuration/Loader/YamlFileLoader.php b/typo3/sysext/core/Classes/Configuration/Loader/YamlFileLoader.php
index cf36f3aa91ae..0c8425fa1e09 100644
--- a/typo3/sysext/core/Classes/Configuration/Loader/YamlFileLoader.php
+++ b/typo3/sysext/core/Classes/Configuration/Loader/YamlFileLoader.php
@@ -47,6 +47,7 @@ class YamlFileLoader implements LoggerAwareInterface
 {
     use LoggerAwareTrait;
 
+    public const PATTERN_PARTS = '%[^(%]+?\([\'"]?([^(]*?)[\'"]?\)%|%([^%()]*?)%';
     public const PROCESS_PLACEHOLDERS = 1;
     public const PROCESS_IMPORTS = 2;
 
@@ -252,7 +253,7 @@ protected function getParts(string $placeholders): array
         // find occurrences of placeholders like %some()% and %array.access%.
         // Only find the innermost ones, so we can nest them.
         preg_match_all(
-            '/%[^(%]+?\([\'"]?([^(]*?)[\'"]?\)%|%([^%()]*?)%/',
+            '/' . self::PATTERN_PARTS . '/',
             $placeholders,
             $parts,
             PREG_UNMATCHED_AS_NULL
diff --git a/typo3/sysext/core/Classes/Configuration/Loader/YamlPlaceholderGuard.php b/typo3/sysext/core/Classes/Configuration/Loader/YamlPlaceholderGuard.php
new file mode 100644
index 000000000000..80c8db0e5cd1
--- /dev/null
+++ b/typo3/sysext/core/Classes/Configuration/Loader/YamlPlaceholderGuard.php
@@ -0,0 +1,102 @@
+<?php
+
+/*
+ * This file is part of the TYPO3 CMS project.
+ *
+ * It is free software; you can redistribute it and/or modify it under
+ * the terms of the GNU General Public License, either version 2
+ * of the License, or any later version.
+ *
+ * For the full copyright and license information, please read the
+ * LICENSE.txt file that was distributed with this source code.
+ *
+ * The TYPO3 project - inspiring people to share!
+ */
+
+namespace TYPO3\CMS\Core\Configuration\Loader;
+
+use TYPO3\CMS\Core\Configuration\Loader\Exception\YamlPlaceholderException;
+use TYPO3\CMS\Core\Utility\GeneralUtility;
+use TYPO3\CMS\Core\Utility\String\StringFragmentPattern;
+use TYPO3\CMS\Core\Utility\String\StringFragmentSplitter;
+
+/**
+ * A guard for protecting YAML placeholders - keeps existing, but escalates on adding new placeholders
+ */
+class YamlPlaceholderGuard
+{
+    protected StringFragmentSplitter $fragmentSplitter;
+
+    public function __construct(protected array $existingConfiguration)
+    {
+        $fragmentPattern = GeneralUtility::makeInstance(
+            StringFragmentPattern::class,
+            StringFragmentSplitter::TYPE_EXPRESSION,
+            YamlFileLoader::PATTERN_PARTS
+        );
+        $this->fragmentSplitter = GeneralUtility::makeInstance(
+            StringFragmentSplitter::class,
+            $fragmentPattern
+        );
+    }
+
+    /**
+     * Modifies existing configuration.
+     */
+    public function process(array $modified): array
+    {
+        return $this->protectPlaceholders($this->existingConfiguration, $modified);
+    }
+
+    /**
+     * Detects placeholders that have been introduced and handles* them.
+     * (*) currently throws an exception, but could be purged or escaped as well
+     *
+     * @param array<string, mixed> $current
+     * @param array<string, mixed> $modified
+     * @param list<string> $steps configuration keys traversed so far
+     * @return array<string, mixed> sanitized configuration (currently not used, exception thrown before)
+     * @throws YamlPlaceholderException
+     */
+    protected function protectPlaceholders(array $current, array $modified, array $steps = []): array
+    {
+        foreach ($modified as $key => $value) {
+            $currentSteps = array_merge($steps, [$key]);
+            if (is_array($value)) {
+                $modified[$key] = $this->protectPlaceholders(
+                    $current[$key] ?? [],
+                    $value,
+                    $currentSteps
+                );
+            } elseif (is_string($value)) {
+                $splitFlags = StringFragmentSplitter::FLAG_UNMATCHED_AS_NULL;
+                $newFragments = $this->fragmentSplitter->split($value, $splitFlags);
+                if (is_string($current[$key] ?? null)) {
+                    $currentFragments = $this->fragmentSplitter->split($current[$key] ?? '', $splitFlags);
+                } else {
+                    $currentFragments = null;
+                }
+                // in case there are new fragments (at least one matching the pattern)
+                if ($newFragments !== null) {
+                    // compares differences in `expression` fragments only
+                    $differences = $currentFragments === null
+                        ? $newFragments->withOnlyType(StringFragmentSplitter::TYPE_EXPRESSION)
+                        : $newFragments->withOnlyType(StringFragmentSplitter::TYPE_EXPRESSION)
+                            ->diff($currentFragments->withOnlyType(StringFragmentSplitter::TYPE_EXPRESSION));
+                    if (count($differences) > 0) {
+                        throw new YamlPlaceholderException(
+                            sprintf(
+                                'Introducing placeholder%s %s for %s is not allowed',
+                                count($differences) !== 1 ? 's' : '',
+                                implode(', ', $differences->getFragments()),
+                                implode('.', $currentSteps)
+                            ),
+                            1651690534
+                        );
+                    }
+                }
+            }
+        }
+        return $modified;
+    }
+}
diff --git a/typo3/sysext/core/Classes/Configuration/SiteConfiguration.php b/typo3/sysext/core/Classes/Configuration/SiteConfiguration.php
index 82534ccdc15d..7e2ae4587141 100644
--- a/typo3/sysext/core/Classes/Configuration/SiteConfiguration.php
+++ b/typo3/sysext/core/Classes/Configuration/SiteConfiguration.php
@@ -26,7 +26,9 @@
 use TYPO3\CMS\Core\Configuration\Event\SiteConfigurationBeforeWriteEvent;
 use TYPO3\CMS\Core\Configuration\Event\SiteConfigurationLoadedEvent;
 use TYPO3\CMS\Core\Configuration\Exception\SiteConfigurationWriteException;
+use TYPO3\CMS\Core\Configuration\Loader\Exception\YamlPlaceholderException;
 use TYPO3\CMS\Core\Configuration\Loader\YamlFileLoader;
+use TYPO3\CMS\Core\Configuration\Loader\YamlPlaceholderGuard;
 use TYPO3\CMS\Core\Exception\SiteNotFoundException;
 use TYPO3\CMS\Core\SingletonInterface;
 use TYPO3\CMS\Core\Site\Entity\Site;
@@ -257,15 +259,20 @@ public function writeSettings(string $siteIdentifier, array $settings): void
     /**
      * Add or update a site configuration
      *
+     * @param bool $protectPlaceholders whether to disallow introducing new placeholders
+     * @todo enforce $protectPlaceholders with TYPO3 v13.0
      * @throws SiteConfigurationWriteException
      */
-    public function write(string $siteIdentifier, array $configuration): void
+    public function write(string $siteIdentifier, array $configuration, bool $protectPlaceholders = false): void
     {
         $folder = $this->configPath . '/' . $siteIdentifier;
         $fileName = $folder . '/' . $this->configFileName;
         $newConfiguration = $configuration;
         if (!file_exists($folder)) {
             GeneralUtility::mkdir_deep($folder);
+            if ($protectPlaceholders && $newConfiguration !== []) {
+                $newConfiguration = $this->protectPlaceholders([], $newConfiguration);
+            }
         } elseif (file_exists($fileName)) {
             $loader = GeneralUtility::makeInstance(YamlFileLoader::class);
             // load without any processing to have the unprocessed base to modify
@@ -277,6 +284,9 @@ public function write(string $siteIdentifier, array $configuration): void
                 self::findRemoved($processed, $configuration),
                 self::findModified($processed, $configuration)
             );
+            if ($protectPlaceholders && $newModified !== []) {
+                $newModified = $this->protectPlaceholders($newConfiguration, $newModified);
+            }
             // change _only_ the modified keys, leave the original non-changed areas alone
             ArrayUtility::mergeRecursiveWithOverrule($newConfiguration, $newModified);
         }
@@ -327,6 +337,25 @@ public function delete(string $siteIdentifier): void
         $this->firstLevelCache = null;
     }
 
+    /**
+     * Detects placeholders that have been introduced and handles* them.
+     * (*) currently throws an exception, but could be purged or escaped as well
+     *
+     * @param array<string, mixed> $existingConfiguration
+     * @param array<string, mixed> $modifiedConfiguration
+     * @return array<string, mixed> sanitized configuration (currently not used, exception thrown before)
+     * @throws SiteConfigurationWriteException
+     */
+    protected function protectPlaceholders(array $existingConfiguration, array $modifiedConfiguration): array
+    {
+        try {
+            return GeneralUtility::makeInstance(YamlPlaceholderGuard::class, $existingConfiguration)
+                ->process($modifiedConfiguration);
+        } catch (YamlPlaceholderException $exception) {
+            throw new SiteConfigurationWriteException($exception->getMessage(), 1670361271, $exception);
+        }
+    }
+
     protected function sortConfiguration(array $newConfiguration): array
     {
         ksort($newConfiguration);
diff --git a/typo3/sysext/core/Tests/Unit/Configuration/Fixtures/SiteConfigs/config2.yaml b/typo3/sysext/core/Tests/Unit/Configuration/Fixtures/SiteConfigs/config2.yaml
index b612292bca6e..eee4d05dceaa 100644
--- a/typo3/sysext/core/Tests/Unit/Configuration/Fixtures/SiteConfigs/config2.yaml
+++ b/typo3/sysext/core/Tests/Unit/Configuration/Fixtures/SiteConfigs/config2.yaml
@@ -3,6 +3,7 @@ baseVariants:
   -
     base: foo123
     condition: bar
+customProperty: 'Using %env("existing")% variable'
 errorHandling:
   -
     errorCode: '404'
diff --git a/typo3/sysext/core/Tests/Unit/Configuration/Fixtures/SiteConfigs/config2_expected.yaml b/typo3/sysext/core/Tests/Unit/Configuration/Fixtures/SiteConfigs/config2_expected.yaml
index 305e894edd5f..e72ab3957907 100644
--- a/typo3/sysext/core/Tests/Unit/Configuration/Fixtures/SiteConfigs/config2_expected.yaml
+++ b/typo3/sysext/core/Tests/Unit/Configuration/Fixtures/SiteConfigs/config2_expected.yaml
@@ -3,6 +3,7 @@ baseVariants:
   -
     base: foo123
     condition: bar
+customProperty: 'Using %env("existing")% variable'
 errorHandling:
   -
     errorCode: '404'
diff --git a/typo3/sysext/core/Tests/Unit/Configuration/SiteConfigurationTest.php b/typo3/sysext/core/Tests/Unit/Configuration/SiteConfigurationTest.php
index 0a2b10450e15..6a19b2fb85e7 100644
--- a/typo3/sysext/core/Tests/Unit/Configuration/SiteConfigurationTest.php
+++ b/typo3/sysext/core/Tests/Unit/Configuration/SiteConfigurationTest.php
@@ -19,6 +19,7 @@
 
 use Symfony\Component\Yaml\Yaml;
 use TYPO3\CMS\Core\Cache\Frontend\NullFrontend;
+use TYPO3\CMS\Core\Configuration\Exception\SiteConfigurationWriteException;
 use TYPO3\CMS\Core\Configuration\Loader\YamlFileLoader;
 use TYPO3\CMS\Core\Configuration\SiteConfiguration;
 use TYPO3\CMS\Core\Core\Environment;
@@ -107,7 +108,7 @@ public function writeOnlyWritesModifiedKeys(): void
         // delete values
         unset($configuration['someOtherValue'], $configuration['languages'][1]);
 
-        $this->siteConfiguration->write($identifier, $configuration);
+        $this->siteConfiguration->write($identifier, $configuration, true);
 
         // expect modified base but intact imports
         self::assertFileEquals($expected, $siteConfig);
@@ -146,9 +147,55 @@ public function writingOfNestedStructuresPreservesOrder(): void
             'navigationTitle' => 'English',
         ];
         array_unshift($configuration['languages'], $languageConfig);
-        $this->siteConfiguration->write($identifier, $configuration);
+        $this->siteConfiguration->write($identifier, $configuration, true);
 
         // expect modified base but intact imports
         self::assertFileEquals($expected, $siteConfig);
     }
+
+    public static function writingPlaceholdersIsHandledDataProvider(): \Generator
+    {
+        yield 'unchanged' => [
+            ['customProperty' => 'Using %env("existing")% variable'],
+            false,
+        ];
+        yield 'removed placeholder variable' => [
+            ['customProperty' => 'Not using any variable'],
+            false,
+        ];
+        yield 'changed raw text only' => [
+            ['customProperty' => 'Using %env("existing")% variable from system environment'],
+            false,
+        ];
+        yield 'added new placeholder variable' => [
+            ['customProperty' => 'Using %env("existing")% and %env("secret")% variable'],
+            true,
+        ];
+    }
+
+    /**
+     * @test
+     * @dataProvider writingPlaceholdersIsHandledDataProvider
+     */
+    public function writingPlaceholdersIsHandled(array $changes, bool $expectedException): void
+    {
+        if ($expectedException) {
+            $this->expectException(SiteConfigurationWriteException::class);
+            $this->expectExceptionCode(1670361271);
+        }
+
+        $identifier = 'testsite';
+        GeneralUtility::mkdir_deep($this->fixturePath . '/' . $identifier);
+        $configFixture = __DIR__ . '/Fixtures/SiteConfigs/config2.yaml';
+        $siteConfig = $this->fixturePath . '/' . $identifier . '/config.yaml';
+        copy($configFixture, $siteConfig);
+        // load with resolved imports as the module does
+        $configuration = GeneralUtility::makeInstance(YamlFileLoader::class)
+            ->load(
+                GeneralUtility::fixWindowsFilePath($siteConfig),
+                YamlFileLoader::PROCESS_IMPORTS
+            );
+        $configuration = array_merge($configuration, $changes);
+        $this->siteConfiguration->write($identifier, $configuration, true);
+    }
 }