Skip to content

Commit 4c74f2d

Browse files
authored
fix: harden regex matching on key:generate command (#10183)
1 parent 53096f2 commit 4c74f2d

3 files changed

Lines changed: 61 additions & 19 deletions

File tree

‎system/Commands/Encryption/GenerateKey.php‎

Lines changed: 24 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -171,36 +171,41 @@ protected function writeNewEncryptionKeyToFile(string $oldKey, string $newKey):
171171
}
172172

173173
$oldFileContents = (string) file_get_contents($envFile);
174-
$replacementKey = "\nencryption.key = {$newKey}";
175174

176-
if (! str_contains($oldFileContents, 'encryption.key')) {
177-
return file_put_contents($envFile, $replacementKey, FILE_APPEND) !== false;
175+
// Match an active setting line, preserving any leading whitespace and `export` prefix.
176+
$activePattern = $this->keyPattern($oldKey);
177+
178+
if (preg_match($activePattern, $oldFileContents) === 1) {
179+
$newFileContents = (string) preg_replace($activePattern, '$1' . $newKey, $oldFileContents, 1);
180+
181+
return file_put_contents($envFile, $newFileContents) !== false;
178182
}
179183

180-
$newFileContents = preg_replace($this->keyPattern($oldKey), $replacementKey, $oldFileContents);
184+
// Match a commented-out setting line (e.g., from the shipped `env` template) and
185+
// uncomment it. The optional `export` prefix is dropped on uncomment for predictability.
186+
$commentedPattern = '/^\h*#\h*(?:export\h+)?encryption\.key\h*=\h*[^\r\n]*$/m';
181187

182-
if ($newFileContents === $oldFileContents) {
183-
$newFileContents = preg_replace(
184-
'/^[#\s]*encryption.key[=\s]*(?:hex2bin\:[a-f0-9]{64}|base64\:(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?)$/m',
185-
$replacementKey,
186-
$oldFileContents,
187-
);
188+
if (preg_match($commentedPattern, $oldFileContents) === 1) {
189+
$newFileContents = (string) preg_replace($commentedPattern, "encryption.key = {$newKey}", $oldFileContents, 1);
190+
191+
return file_put_contents($envFile, $newFileContents) !== false;
188192
}
189193

190-
return file_put_contents($envFile, $newFileContents) !== false;
194+
// No setting present (active or commented); append.
195+
return file_put_contents($envFile, "\nencryption.key = {$newKey}", FILE_APPEND) !== false;
191196
}
192197

193198
/**
194-
* Get the regex of the current encryption key.
199+
* Returns the regex used to locate an active `encryption.key = ...` setting in the `.env`
200+
* contents. The single capture group spans everything up to (and including) the `=` and any
201+
* separating whitespace, so a `preg_replace` substitution preserves an optional `export`
202+
* prefix while rewriting only the value.
203+
*
204+
* The `$oldKey` parameter is retained for backward compatibility with subclasses that
205+
* override this method; it is no longer consulted because the pattern matches any value.
195206
*/
196207
protected function keyPattern(string $oldKey): string
197208
{
198-
$escaped = preg_quote($oldKey, '/');
199-
200-
if ($escaped !== '') {
201-
$escaped = "[{$escaped}]*";
202-
}
203-
204-
return "/^[#\\s]*encryption.key[=\\s]*{$escaped}$/m";
209+
return '/^(\h*(?:export\h+)?encryption\.key\h*=\h*)[^\r\n]*$/m';
205210
}
206211
}

‎tests/system/Commands/Encryption/GenerateKeyTest.php‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,4 +169,40 @@ public function testKeyGenerateWhenNewBase64KeyIsSubsequentlyCommentedOut(): voi
169169
$this->assertStringContainsString('was successfully set.', $this->getBuffer());
170170
$this->assertNotSame($key, env('encryption.key', $key), 'Failed replacing the commented out key.');
171171
}
172+
173+
public function testKeyGenerateReplacesExportPrefixedEncryptionKey(): void
174+
{
175+
$existingKey = 'hex2bin:' . str_repeat('a', 64);
176+
file_put_contents($this->envPath, "export encryption.key = {$existingKey}\n");
177+
178+
command('key:generate --force');
179+
180+
$contents = (string) file_get_contents($this->envPath);
181+
$this->assertMatchesRegularExpression(
182+
'/^export encryption\.key = hex2bin:[a-f0-9]{64}$/m',
183+
$contents,
184+
'The `export` prefix should be preserved and the value rewritten.',
185+
);
186+
$this->assertStringNotContainsString($existingKey, $contents, 'The old key value should be replaced.');
187+
}
188+
189+
public function testKeyGenerateNotFooledByCommentMentioningEncryptionKey(): void
190+
{
191+
$envContents = "# Note: encryption.key is set automatically by spark key:generate.\n";
192+
file_put_contents($this->envPath, $envContents);
193+
194+
command('key:generate --force');
195+
196+
$contents = (string) file_get_contents($this->envPath);
197+
$this->assertStringContainsString(
198+
$envContents,
199+
$contents,
200+
'The doc comment must be left intact.',
201+
);
202+
$this->assertMatchesRegularExpression(
203+
'/^encryption\.key = hex2bin:[a-f0-9]{64}$/m',
204+
$contents,
205+
'A real `encryption.key` setting must be appended even when a comment mentions the name.',
206+
);
207+
}
172208
}

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ Bugs Fixed
4040
- **CLI:** Fixed a bug where ``CLI::generateDimensions()`` leaked ``stty`` error output (e.g., ``stty: 'standard input': Inappropriate ioctl for device``) to stderr when stdin was not a TTY.
4141
- **CLI:** Fixed a bug where ``CLI::generateDimensions()`` leaked ``tput`` error output (``tput: No value for $TERM and no -T specified``) to stderr when the ``stty`` fallback was reached and the ``TERM`` environment variable was not set.
4242
- **Commands:** Fixed a bug in the ``env`` command where passing options only would cause the command to throw a ``TypeError`` instead of showing the current environment.
43+
- **Commands:** Fixed a bug in ``key:generate`` command where the regex used to locate the ``encryption.key`` line was fooled by a comment containing the substring (silently writing nothing), and did not handle DotEnv's ``export encryption.key = ...`` syntax.
4344
- **Common:** Fixed a bug where the ``command()`` helper function did not properly clean up output buffers, which could lead to risky tests when exceptions were thrown.
4445
- **Database:** Fixed a bug where ``BaseConnection::listTables()`` could return a sparse array when using cached table names after a table was dropped.
4546
- **Database:** Fixed a bug where the PostgreSQL driver's ``increment()`` and ``decrement()`` methods were not working for numeric columns.

0 commit comments

Comments
 (0)