Repository navigation
Expand file tree
/
Copy pathKeyManagementBundle.php
More file actions
544 lines (493 loc) · 31.5 KB
/
Copy pathKeyManagementBundle.php
File metadata and controls
544 lines (493 loc) · 31.5 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
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\KeyManagement;
use Doctrine\DBAL\Types\Type;
use Doctrine\ORM\Mapping\Embeddable;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\MappedSuperclass;
use Symfony\Bridge\Doctrine\SchemaListener\AbstractSchemaListener;
use Symfony\Component\Config\Definition\Configurator\DefinitionConfigurator;
use Symfony\Component\Console\Application;
use Symfony\Component\DependencyInjection\Argument\AbstractArgument;
use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
use Symfony\Component\DependencyInjection\Argument\LazyProxyArgument;
use Symfony\Component\DependencyInjection\Argument\ServiceLocatorArgument;
use Symfony\Component\DependencyInjection\Argument\TaggedIteratorArgument;
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Kernel\AbstractBundle;
use Symfony\Component\DependencyInjection\Kernel\RequiredBundle;
use Symfony\Component\DependencyInjection\Kernel\ServicesBundle;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symfony\Component\DependencyInjection\Parameter;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ServiceLocator;
use Symfony\Component\KeyManagement\Bridge\DoctrineDbal\DataKeyStore;
use Symfony\Component\KeyManagement\Bridge\DoctrineDbal\EncryptedType;
use Symfony\Component\KeyManagement\Bridge\DoctrineOrm\DependencyInjection\RegisterBlindIndexesPass;
use Symfony\Component\KeyManagement\Bridge\DoctrineOrm\DependencyInjection\RegisterEncryptedColumnsPass;
use Symfony\Component\KeyManagement\Bridge\DoctrineOrm\SchemaListener\DataKeyStoreSchemaListener;
use Symfony\Component\KeyManagement\Bridge\Flysystem\DependencyInjection\RegisterFlysystemStoragesPass;
use Symfony\Component\KeyManagement\DependencyInjection\CheckDataKeyStoreSecretPass;
use Symfony\Component\KeyManagement\DependencyInjection\KeyManagementPass;
use Symfony\Component\KeyManagement\DependencyInjection\RegisterDoctrineDbalTypesPass;
use Symfony\Component\KeyManagement\Factory\KmsFactoryInterface;
/**
* Provides the KMS clients, the envelope encrypters and the data key store.
*
* @author Florent Morselli <florent.morselli@spomky-labs.com>
*
* @experimental
*/
#[RequiredBundle(ServicesBundle::class)]
class KeyManagementBundle extends AbstractBundle
{
/**
* Prefix of a "key_management.clients" DSN naming a client the application registered itself.
*
* Such a client is referenced rather than built by the factory registry.
*/
private const string SERVICE_SCHEME = 'service://';
/**
* Name the store's envelope encrypter answers to, both as an argument and as a target.
*/
private const string STORE_TARGET = 'stored';
public function getPath(): string
{
return $this->path ??= __DIR__;
}
public function build(ContainerBuilder $container): void
{
// the container can drop the data collector this pass looks for, so run after it
$container->addCompilerPass(new KeyManagementPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, -16);
$container->addCompilerPass(new CheckDataKeyStoreSecretPass());
if (class_exists(RegisterFlysystemStoragesPass::class)) {
$container->addCompilerPass(new RegisterFlysystemStoragesPass());
}
if (class_exists(RegisterBlindIndexesPass::class)) {
$container->addCompilerPass(new RegisterBlindIndexesPass());
}
if (class_exists(RegisterEncryptedColumnsPass::class)) {
$container->addCompilerPass(new RegisterEncryptedColumnsPass());
}
// after RegisterEncryptedColumnsPass and the passes that add mapping drivers, before the pass of DoctrineBundle that reads the "doctrine.dbal.type" tag at priority -10
$container->addCompilerPass(new RegisterDoctrineDbalTypesPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, -5);
}
public function configure(DefinitionConfigurator $definition): void
{
$definition->rootNode()
->acceptAndWrap(['string'], 'clients')
->canBeDisabled()
->children()
->scalarNode('default_client')
->resolvesAtCompileTime()
->info('Name of the default client (must match an entry of "clients"); inferred when only one client is registered.')
->defaultNull()
->end()
->arrayNode('clients', 'client')
->info('Map of client name to DSN, or to the members of a composite client; "service://<id>" takes the client the application registered under that service id instead of building one from a DSN.')
->beforeNormalization()
->ifString()
->then(static fn (string $dsn): array => ['default' => $dsn])
->end()
->normalizeKeys(false)
->useAttributeAsKey('name')
->validate()
->always(static function (array $clients): array {
foreach ($clients as $name => $client) {
if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_.-]*$/', $name)) {
throw new InvalidArgumentException(\sprintf('The KMS client name "%s" is invalid: it must start with a letter or an underscore and contain only letters, digits, underscores, dots and dashes.', $name));
}
if (\array_key_exists($name, $client['members'])) {
throw new InvalidArgumentException(\sprintf('The composite KMS client "%s" cannot be a member of itself.', $name));
}
if (\in_array($name, $client['retired'], true)) {
throw new InvalidArgumentException(\sprintf('The composite KMS client "%s" cannot be a retired member of itself.', $name));
}
foreach ($client['retired'] as $retired) {
if (\array_key_exists($retired, $client['members'])) {
throw new InvalidArgumentException(\sprintf('The KMS client "%s" cannot be both an active and a retired member of the composite KMS client "%s".', $retired, $name));
}
}
}
return $clients;
})
->end()
->arrayPrototype()
->beforeNormalization()
->ifString()
->then(static fn (string $dsn): array => ['dsn' => $dsn])
->end()
->validate()
->ifTrue(static fn (array $client): bool => isset($client['dsn']) === (bool) $client['members'])
->thenInvalid('A KMS client is either a DSN or the members of a composite client, not both nor neither.')
->end()
->validate()
->ifTrue(static fn (array $client): bool => isset($client['dsn']) && (bool) $client['retired'])
->thenInvalid('A KMS client with a DSN cannot have retired members.')
->end()
->children()
->stringNode('dsn')
->cannotBeEmpty()
->end()
->arrayNode('members', 'member')
->info('Map of member name to the master key it wraps under, null for the key id given to each call. Everything the composite client encrypts is wrapped by each member and read back through the first one that answers, the first member minting the data keys, so that losing one provider loses nothing. Each member is a full path to the data.')
->normalizeKeys(false)
->useAttributeAsKey('name')
->scalarPrototype()
->defaultNull()
->end()
->end()
->arrayNode('retired')
->resolvesAtCompileTime()
->info('Former member names accepted for reads but never used for writes. Each remains a full path to the plaintext.')
->validate()
->ifTrue(static fn (array $retired): bool => !array_is_list($retired))
->thenInvalid('The retired members of a composite KMS client are a list of names, got %s.')
->end()
->validate()
->ifTrue(static fn (array $retired): bool => \count($retired) !== \count(array_unique($retired)))
->thenInvalid('The retired members of a composite KMS client are listed once each, got %s.')
->end()
->scalarPrototype()
->cannotBeEmpty()
->validate()
->ifTrue(static fn ($name): bool => !\is_string($name) || 0xFF < \strlen($name))
->thenInvalid('A retired KMS client name is a string of at most 255 bytes, got %s.')
->end()
->end()
->end()
->end()
->end()
->end()
->arrayNode('store')
->info('Data key store: payloads then refer to a stored data key instead of carrying it, so the KMS is reached once per key and per process, and that key can be rewrapped under another provider without rewriting a payload.')
->children()
->scalarNode('connection')
->resolvesAtCompileTime()
->info('Service id of the DBAL connection holding the table.')
->defaultValue('doctrine.dbal.default_connection')
->cannotBeEmpty()
->end()
->scalarNode('client')
->resolvesAtCompileTime()
->info('Name of the client wrapping the data keys this store creates (must match an entry of "clients"); defaults to the default client.')
->defaultNull()
->cannotBeEmpty()
->end()
->arrayNode('allowed_clients')
->resolvesAtCompileTime()
->info('Additional clients trusted to wrap and unwrap stored data keys. The store client is always trusted.')
->scalarPrototype()->cannotBeEmpty()->end()
->defaultValue([])
->end()
->scalarNode('key_id')
->info('Master key wrapping the data keys this store creates (backend-specific: alias, ARN, key URL, ...).')
->isRequired()
->cannotBeEmpty()
->end()
->arrayNode('secret')
->info('Secret used to authenticate the stored data keys, defaults to the "kernel.secret" parameter. List several to rotate it: the first one signs, all of them verify.')
->acceptAndWrap(['string'])
->performNoDeepMerging()
->scalarPrototype()->cannotBeEmpty()->end()
->end()
->scalarNode('table')
->info('Name of the table holding the wrapped data keys.')
->defaultValue('key_management_data_keys')
->cannotBeEmpty()
->end()
->booleanNode('read_self_contained')
->resolvesAtCompileTime()
->info('Whether a payload carrying its own wrapped data key is still read, through the default client. On while migrating to the stored format, off afterwards: such a payload resolves no row, so nothing the store checks applies to it.')
->defaultFalse()
->end()
->booleanNode('bind_wrapping_context')
->info('Whether the backend authenticates the reference and the scope of each data key as it wraps it. Off by default: not every backend accepts authenticated data, and turning it on needs the stored keys rewrapped.')
->defaultFalse()
->end()
->variableNode('max_age')
->info('Seconds after which the current root key of a scope is retired. The default is 30 days; 0 forces rotation on every call and null disables retirement.')
->defaultValue(2592000)
->validate()
->ifTrue(static fn ($maxAge): bool => null !== $maxAge && (!\is_int($maxAge) || $maxAge < 0))
->thenInvalid('The maximum age of a data key must be null or a positive integer, got %s.')
->end()
->end()
->end()
->end()
->arrayNode('doctrine_dbal')
->children()
->arrayNode('types', 'type')
->info('Encrypted Doctrine DBAL types by name.')
->normalizeKeys(false)
->useAttributeAsKey('name')
->arrayPrototype()
->children()
->stringNode('type')
->info('Doctrine type converting the value before it is encrypted.')
->isRequired()
->cannotBeEmpty()
->end()
->stringNode('key')
->info('Master key encrypting the values, or the scope of their data key when "store" is configured.')
->isRequired()
->cannotBeEmpty()
->end()
->end()
->end()
->end()
->end()
->end()
->end()
;
}
/**
* A client the application built itself is named in "clients" through a "service://<id>" DSN.
*
* That scheme is resolved here, when the container is built, so it never reaches the factory
* registry: an application that hides it behind an environment variable gets an exception at
* runtime instead, since nothing can be referenced from a value that is unknown until then.
*
* What the scheme registers is a definition rather than an alias, and that is the point: the
* client keeps the tag the console commands look it up by, the profiler decorates it, and it
* gets an envelope encrypter and named argument aliases like a client built from a DSN. An
* alias would carry no tag and be invisible to all three.
*/
public function loadExtension(array $config, ContainerConfigurator $configurator, ContainerBuilder $container): void
{
if (!$config['enabled']) {
return;
}
$configurator->import('Resources/config/key_management.php');
$configurator->import('Resources/config/key_management_debug.php');
if ($container->getParameter('kernel.debug')) {
// so that a change to the mapping is seen without clearing the cache
$container->removeDefinition('cache.key_management.encrypted_columns');
}
if (class_exists(Application::class)) {
$configurator->import('Resources/config/console.php');
}
$container->registerForAutoconfiguration(KmsFactoryInterface::class)
->addTag('key_management.factory');
// The tag carries the name the index derives under, which nothing here can guess, so
// RegisterBlindIndexesPass refuses one without it. Tagging every index all the same is
// what makes that refusal happen: an index nobody tagged would leave the listener removed
// and every indexed column silently empty.
$container->registerForAutoconfiguration(BlindIndexInterface::class)
->addTag('key_management.blind_index');
if (class_exists(RegisterEncryptedColumnsPass::class)) {
foreach ([Entity::class, Embeddable::class, MappedSuperclass::class] as $mapping) {
$container->registerAttributeForAutoconfiguration($mapping, RegisterEncryptedColumnsPass::autoconfigure(...));
}
}
$clients = $config['clients'];
$defaultName = $config['default_client'] ?? (1 === \count($clients) ? array_key_first($clients) : null);
if (null !== $defaultName && !isset($clients[$defaultName])) {
throw new LogicException(\sprintf('Default KMS client "%s" is not registered in "key_management.clients".', $defaultName));
}
foreach ($clients as $name => $client) {
$serviceId = 'key_management.'.$name;
$definition = $container->register($serviceId, EncrypterInterface::class)
->addTag('key_management.client', ['key' => $name]);
if ($client['members']) {
$this->configureCompositeClient($definition, $name, $client['members'], $client['retired'], $clients);
} elseif (str_starts_with($dsn = $client['dsn'], self::SERVICE_SCHEME)) {
if ('' === $referencedId = substr($dsn, \strlen(self::SERVICE_SCHEME))) {
throw new InvalidArgumentException(\sprintf('The DSN of the KMS client "%s" must name a service id after "%s".', $name, self::SERVICE_SCHEME));
}
$definition->setFactory('current')
->setArguments([[new Reference($referencedId)]]);
} else {
$definition->setFactory([new Reference('key_management.factory'), 'fromString'])
->setArguments([$dsn]);
}
$envelopeId = 'key_management.envelope_encrypter.'.$name;
$container->register($envelopeId, EnvelopeEncrypter::class)
->setArguments([new Reference($serviceId)]);
foreach ([EncrypterInterface::class, DecrypterInterface::class, DataKeyGeneratorInterface::class] as $type) {
$container->registerAliasForArgument($serviceId, $type, $name.'.kms', $name);
}
foreach ([EnvelopeEncrypterInterface::class, EnvelopeDecrypterInterface::class] as $type) {
$container->registerAliasForArgument($envelopeId, $type, $name.'.envelope_encrypter', $name);
}
}
if (null !== $defaultName) {
$container->setAlias(EncrypterInterface::class, 'key_management.'.$defaultName);
$container->setAlias(DecrypterInterface::class, 'key_management.'.$defaultName);
$container->setAlias(DataKeyGeneratorInterface::class, 'key_management.'.$defaultName);
$container->setAlias(EnvelopeEncrypterInterface::class, 'key_management.envelope_encrypter.'.$defaultName);
$container->setAlias(EnvelopeDecrypterInterface::class, 'key_management.envelope_encrypter.'.$defaultName);
}
if (isset($config['store']['key_id'])) {
$this->registerStore($config['store'], array_keys($clients), $defaultName, $container);
}
$this->registerDoctrineDbalTypes($config['doctrine_dbal']['types'] ?? [], match (true) {
isset($config['store']['key_id']) => 'key_management.stored_envelope_encrypter',
null !== $defaultName => 'key_management.envelope_encrypter.'.$defaultName,
default => null,
}, $container);
}
/**
* Registers a composite client as a client like any other, tagged and aliased under its name.
*
* Its members are the configured clients, resolved lazily through the locator of the tagged
* ones, and they are checked here so that a typo is reported at compile time against a name.
* A client the application registers itself joins through a "service://" DSN, which makes it
* a configured client. Active and retired members cannot be configured composites themselves:
* two of them naming each other would read in circles.
*
* @param array<string, string|null> $members
* @param list<string> $retired
* @param array<string, array<mixed>> $clients
*/
private function configureCompositeClient(Definition $definition, string $name, array $members, array $retired, array $clients): void
{
foreach (array_merge(array_keys($members), $retired) as $member) {
if (!isset($clients[$member])) {
throw new LogicException(\sprintf('The member "%s" of the composite KMS client "%s" is not registered in "key_management.clients".', $member, $name));
}
if ($clients[$member]['members']) {
throw new LogicException(\sprintf('The member "%s" of the composite KMS client "%s" is a composite client itself, which is not supported: list its members instead.', $member, $name));
}
}
$definition->setClass(CompositeKms::class)
->setArguments([
new ServiceLocatorArgument(new TaggedIteratorArgument('key_management.client', 'key', true)),
$members,
$retired,
new Reference('logger', ContainerInterface::NULL_ON_INVALID_REFERENCE),
])
->addTag('monolog.logger', ['channel' => 'key_management']);
}
/**
* Makes the store-backed encrypter the one the envelope interfaces resolve to.
*
* Configuring a store is what an application does to stop carrying a wrapped data key in every
* payload. The payloads written before it are read by turning on "read_self_contained", which is
* a statement rather than a consequence of having a default client: that format carries its own
* wrapped data key, so it resolves no row and nothing the store checks applies to it. The
* per-client encrypters stay reachable under their own name for whoever wants the other regime
* explicitly.
*
* The store and its rewrap command use only explicitly trusted clients.
*
* @param list<string> $clientNames
*/
private function registerStore(array $config, array $clientNames, ?string $defaultName, ContainerBuilder $container): void
{
if (!ContainerBuilder::willBeAvailable('symfony/doctrine-dbal-key-management', DataKeyStore::class, ['symfony/key-management'])) {
throw new LogicException('Configuring "key_management.store" requires the "symfony/doctrine-dbal-key-management" package. Try running "composer require symfony/doctrine-dbal-key-management".');
}
if (\in_array(self::STORE_TARGET, $clientNames, true)) {
throw new LogicException(\sprintf('A KMS client cannot be named "%1$s" while a data key store is configured: the store registers the autowiring aliases of that name, which would leave the client of the same name unreachable. Rename the "%1$s" client.', self::STORE_TARGET));
}
$client = $config['client'] ?? $defaultName ?? throw new LogicException('The "key_management.store" needs a client to wrap its data keys with: set "key_management.store.client", or "key_management.default_client" to have it inferred.');
if (!\in_array($client, $clientNames, true)) {
throw new LogicException(\sprintf('The KMS client "%s" set on "key_management.store" is not registered in "key_management.clients".', $client));
}
if ($config['read_self_contained'] && null === $defaultName) {
throw new LogicException('The "key_management.store.read_self_contained" option needs a client to read those payloads with: set "key_management.default_client", or turn the option off.');
}
$allowedClients = [$client => new Reference('key_management.'.$client)];
foreach ($config['allowed_clients'] as $name) {
if (!\in_array($name, $clientNames, true)) {
throw new LogicException(\sprintf('The KMS client "%s" set in "key_management.store.allowed_clients" is not registered in "key_management.clients".', $name));
}
$allowedClients[$name] = new Reference('key_management.'.$name);
}
$container->register('.key_management.store.clients', ServiceLocator::class)
->setArguments([$allowedClients])
->addTag('container.service_locator');
$container->register('key_management.store', DataKeyStore::class)
->setArguments([
new Reference($config['connection']),
new Reference('.key_management.store.clients'),
$client,
$config['key_id'],
$config['secret'] ?: new Parameter('kernel.secret'),
$config['table'],
32,
$config['max_age'],
new Reference('clock', ContainerInterface::NULL_ON_INVALID_REFERENCE),
$config['bind_wrapping_context'],
])
->addTag('kernel.reset', ['method' => 'forget']);
if ($container->hasDefinition('console.command.key_management_rewrap_data_keys')) {
$container->getDefinition('console.command.key_management_rewrap_data_keys')
->setArgument(2, $client)
->setArgument(3, $config['key_id']);
}
$container->register('key_management.stored_envelope_encrypter', StoredEnvelopeEncrypter::class)
->setArguments([
new Reference('key_management.store'),
$config['read_self_contained'] ? new Reference('key_management.envelope_encrypter.'.$defaultName) : null,
]);
$container->setAlias(DataKeyStoreInterface::class, 'key_management.store');
$container->setAlias(RewrappableDataKeyStoreInterface::class, 'key_management.store');
$container->setAlias(EnvelopeEncrypterInterface::class, 'key_management.stored_envelope_encrypter');
$container->setAlias(EnvelopeDecrypterInterface::class, 'key_management.stored_envelope_encrypter');
foreach ([EnvelopeEncrypterInterface::class, EnvelopeDecrypterInterface::class] as $type) {
$container->registerAliasForArgument('key_management.stored_envelope_encrypter', $type, self::STORE_TARGET.'.envelope_encrypter', self::STORE_TARGET);
}
// The store writes its own table, so Doctrine has to know about it: without this, an
// application discovers it by having "doctrine:schema:update" ignore it and a migration
// diff propose to drop it. DoctrineBundle registers the listeners of the Lock, Messenger,
// Cache, Session and RememberMe stores itself and knows nothing of this one, so the store
// that was just registered brings its own. Its base class is checked first because the
// listener extends one the DoctrineBridge owns: loading it without that package around is
// a fatal error, not a false answer from class_exists().
if (
ContainerBuilder::willBeAvailable('symfony/doctrine-bridge', AbstractSchemaListener::class, ['symfony/doctrine-orm-key-management', 'symfony/key-management'])
&& ContainerBuilder::willBeAvailable('symfony/doctrine-orm-key-management', DataKeyStoreSchemaListener::class, ['symfony/key-management'])
) {
$container->register('key_management.store.schema_listener', DataKeyStoreSchemaListener::class)
->setArguments([new IteratorArgument([new Reference('key_management.store')])])
->addTag('doctrine.event_listener', ['event' => 'postGenerateSchema']);
}
}
/**
* Registers the encrypted Doctrine DBAL types, which RegisterDoctrineDbalTypesPass declares on the connections of DoctrineBundle.
*
* The types are listed in the ".key_management.doctrine_dbal.types" parameter, and each one is built from the ".key_management.doctrine_dbal.encrypted_type" definition.
* They encrypt with the encrypter the envelope interfaces resolve to: the store-backed one when a store is configured, the default client's otherwise.
* They get a lazy proxy of that encrypter, so that building a type doesn't create the store and its database connection.
*
* With the Doctrine ORM bridge, the parameter is registered even when no type is configured.
* RegisterEncryptedColumnsPass then adds the types of the columns marked with #[Encrypted].
*
* @param array<string, array{type: string, key: string}> $types
*/
private function registerDoctrineDbalTypes(array $types, ?string $encrypter, ContainerBuilder $container): void
{
if ($types) {
// EncryptedType extends a class of doctrine/dbal, so loading it without that package is a fatal error
if (!ContainerBuilder::willBeAvailable('doctrine/dbal', Type::class, ['symfony/doctrine-dbal-key-management', 'symfony/key-management'])) {
throw new LogicException('Configuring "key_management.doctrine_dbal.types" requires the "doctrine/dbal" package. Try running "composer require doctrine/dbal".');
}
if (!ContainerBuilder::willBeAvailable('symfony/doctrine-dbal-key-management', EncryptedType::class, ['symfony/key-management'])) {
throw new LogicException('Configuring "key_management.doctrine_dbal.types" requires the "symfony/doctrine-dbal-key-management" package. Try running "composer require symfony/doctrine-dbal-key-management".');
}
if (null === $encrypter) {
throw new LogicException('The "key_management.doctrine_dbal.types" need an envelope encrypter: configure "key_management.store", or set "key_management.default_client".');
}
} elseif (null === $encrypter || !class_exists(RegisterEncryptedColumnsPass::class)) {
return;
}
$container->register('.key_management.doctrine_dbal.encrypted_type', EncryptedType::class)
->setAbstract(true)
->setArguments([new AbstractArgument('the parent type'), new LazyProxyArgument(new Reference($encrypter)), new AbstractArgument('the key'), new AbstractArgument('the parent type name')]);
$container->setParameter('.key_management.doctrine_dbal.types', $types);
}
}