Repository navigation
Expand file tree
/
Copy pathRotateKey.php
More file actions
277 lines (221 loc) · 8.9 KB
/
Copy pathRotateKey.php
File metadata and controls
277 lines (221 loc) · 8.9 KB
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
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Encryption;
use CodeIgniter\CLI\AbstractCommand;
use CodeIgniter\CLI\Attributes\Command;
use CodeIgniter\CLI\CLI;
use CodeIgniter\CLI\Input\Option;
use Config\Paths;
/**
* Rotates the encryption key, demoting the current key to `previousKeys`.
*/
#[Command(
name: 'key:rotate',
description: 'Rotates the encryption key, demoting the current key to `encryption.previousKeys` in the `.env` file.',
group: 'Encryption',
)]
class RotateKey extends AbstractCommand
{
/**
* @var list<string>
*/
private const VALID_PREFIXES = ['hex2bin', 'base64'];
protected function configure(): void
{
$this
->addOption(new Option(
name: 'force',
shortcut: 'f',
description: 'Skip the key rotation confirmation.',
))
->addOption(new Option(
name: 'length',
description: 'The length of the random string for the new key, in bytes.',
requiresValue: true,
default: '32',
))
->addOption(new Option(
name: 'prefix',
description: 'Prefix for the new key (either hex2bin or base64).',
requiresValue: true,
default: 'hex2bin',
))
->addOption(new Option(
name: 'keep',
description: 'Maximum number of previous keys to retain. Older keys are dropped. 0 means unlimited.',
requiresValue: true,
default: '0',
));
}
protected function interact(array &$arguments, array &$options): void
{
$prefix = $this->getUnboundOption('prefix', $options);
if (is_string($prefix) && ! in_array($prefix, self::VALID_PREFIXES, true)) {
$options['prefix'] = CLI::prompt('Please provide a valid prefix to use.', self::VALID_PREFIXES, 'required');
}
if ($this->hasUnboundOption('force', $options)) {
return;
}
if (env('encryption.key', '') === '') {
return;
}
if (CLI::prompt('Rotate encryption key? The current key will be moved to `previousKeys`.', ['n', 'y']) === 'y') {
$options['force'] = null; // simulate the presence of the --force option
}
}
protected function execute(array $arguments, array $options): int
{
$prefix = $options['prefix'];
if (! in_array($prefix, self::VALID_PREFIXES, true)) {
CLI::error(sprintf('Invalid prefix "%s". Use either "hex2bin" or "base64".', $prefix));
return EXIT_ERROR;
}
$currentKey = env('encryption.key', '');
if ($currentKey === '') {
CLI::error('No existing `encryption.key` to rotate. Run `spark key:generate` first.');
return EXIT_ERROR;
}
if ($options['force'] === false) {
if ($this->isInteractive()) {
CLI::write('Key rotation cancelled.', 'yellow');
return EXIT_SUCCESS;
}
CLI::error('Key rotation aborted: pass --force to rotate the encryption key in non-interactive mode.');
return EXIT_ERROR;
}
$keep = $options['keep'];
if (! is_string($keep) || ! ctype_digit($keep)) {
CLI::error('The --keep option must be a non-negative integer.');
return EXIT_ERROR;
}
$length = $options['length'];
if (! is_string($length) || ! ctype_digit($length) || (int) $length < 1) {
CLI::error('The --length option must be a positive integer.');
return EXIT_ERROR;
}
$previousKeys = $this->mergePreviousKeys($currentKey, $this->parsePreviousKeys(), (int) $keep);
// Write previousKeys first. If the subsequent `key:generate` call fails,
// the worst case is a stale-but-still-decryptable `.env` (the rotated-out
// key is preserved on disk).
$envFile = ((new Paths())->envDirectory ?? ROOTPATH) . '.env'; // @phpstan-ignore nullCoalesce.property
if (! is_file($envFile)) {
CLI::error(sprintf('Cannot rotate: `.env` file not found at %s.', clean_path($envFile)));
return EXIT_ERROR;
}
if (! is_writable($envFile)) {
CLI::error(sprintf('Cannot rotate: `.env` file at %s is not writable.', clean_path($envFile)));
return EXIT_ERROR;
}
if (! $this->writePreviousKeys($previousKeys, $envFile)) {
// @codeCoverageIgnoreStart
CLI::error(sprintf('Failed to write `encryption.previousKeys` to %s.', clean_path($envFile)));
return EXIT_ERROR;
// @codeCoverageIgnoreEnd
}
// Clear `encryption.previousKeys` from all env sources so the DotEnv
// reload triggered by `key:generate` picks up the new value (DotEnv's
// `setVariable()` skips vars that are already set).
putenv('encryption.previousKeys');
unset($_ENV['encryption.previousKeys']);
service('superglobals')->unsetServer('encryption.previousKeys');
$exitCode = $this->callSilently('key:generate', options: [
'force' => null,
'prefix' => $prefix,
'length' => $length,
]);
if ($exitCode !== EXIT_SUCCESS) {
return $exitCode; // @codeCoverageIgnore
}
$count = count($previousKeys);
CLI::write(sprintf(
'Encryption key rotated. %d %s retained for decryption fallback.',
$count,
$count === 1 ? 'previous key' : 'previous keys',
), 'green');
CLI::write('Re-encrypt existing data with the new key when ready.', 'yellow');
return EXIT_SUCCESS;
}
/**
* Reads the existing `encryption.previousKeys` from the environment as a
* comma-separated list, ignoring blank entries.
*
* @return list<string>
*/
private function parsePreviousKeys(): array
{
$raw = env('encryption.previousKeys', '');
if (! is_string($raw) || $raw === '') {
return [];
}
return array_values(array_filter(
array_map(trim(...), explode(',', $raw)),
static fn (string $v): bool => $v !== '',
));
}
/**
* Prepends the rotated-out key, deduplicates while preserving newest-first order,
* and optionally caps the list length.
*
* @param list<string> $existing
*
* @return list<string>
*/
private function mergePreviousKeys(string $currentKey, array $existing, int $keep): array
{
$merged = [$currentKey, ...$existing];
$seen = [];
$result = [];
foreach ($merged as $key) {
if (isset($seen[$key])) {
continue;
}
$seen[$key] = true;
$result[] = $key;
}
if ($keep > 0) {
return array_slice($result, 0, $keep);
}
return $result;
}
/**
* Replaces or inserts the `encryption.previousKeys` line in the `.env` file.
* The caller is responsible for ensuring `$envFile` exists and is writable;
* `key:generate` handles the `encryption.key` line.
*
* @param list<string> $previousKeys
*/
private function writePreviousKeys(array $previousKeys, string $envFile): bool
{
$contents = (string) file_get_contents($envFile);
$value = implode(',', $previousKeys);
// Match an actual setting line, not a substring buried in a comment. The optional
// `export` prefix mirrors what DotEnv accepts.
$previousKeysPattern = '/^(\h*(?:export\h+)?encryption\.previousKeys\h*=\h*)[^\r\n]*$/m';
if (preg_match($previousKeysPattern, $contents) === 1) {
$contents = (string) preg_replace($previousKeysPattern, '$1' . $value, $contents, 1);
return file_put_contents($envFile, $contents) !== false;
}
// Insert right after the `encryption.key` line so the two stay grouped.
$injected = (string) preg_replace(
'/^(\h*(?:export\h+)?encryption\.key\h*=\h*[^\r\n]*)$/m',
"$1\nencryption.previousKeys = {$value}",
$contents,
1,
);
if ($injected === $contents) {
// Fallback: append to the end. Reachable only when `encryption.key`
// is set via a non-`.env` source (e.g., server config / `putenv()`),
// so the regex cannot find it as a line in the file.
$injected = $contents . "\nencryption.previousKeys = {$value}"; // @codeCoverageIgnore
}
return file_put_contents($envFile, $injected) !== false;
}
}