forked from ambta/DoctrineEncryptBundle
-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathDoctrineEncryptSubscriber.php
More file actions
336 lines (297 loc) · 11 KB
/
DoctrineEncryptSubscriber.php
File metadata and controls
336 lines (297 loc) · 11 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
<?php
namespace Ambta\DoctrineEncryptBundle\Subscribers;
use Doctrine\ORM\Event\PreFlushEventArgs;
use ReflectionClass;
use Doctrine\ORM\Event\PostFlushEventArgs;
use Doctrine\ORM\Events;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\Common\Annotations\Reader;
use Doctrine\Common\Proxy\Proxy;
use Doctrine\Common\Util\ClassUtils;
use Ambta\DoctrineEncryptBundle\Encryptors\EncryptorInterface;
use ReflectionProperty;
use Symfony\Component\PropertyAccess\PropertyAccess;
/**
* Doctrine event subscriber which encrypt/decrypt entities
*/
class DoctrineEncryptSubscriber implements EventSubscriber
{
/**
* Appended to end of encrypted value
*/
const ENCRYPTION_MARKER = '<ENC>';
/**
* Encryptor interface namespace
*/
const ENCRYPTOR_INTERFACE_NS = 'Ambta\DoctrineEncryptBundle\Encryptors\EncryptorInterface';
/**
* Encrypted annotation full name
*/
const ENCRYPTED_ANN_NAME = 'Ambta\DoctrineEncryptBundle\Configuration\Encrypted';
/**
* Encryptor
* @var EncryptorInterface|null
*/
private ?EncryptorInterface $encryptor;
/**
* Annotation reader
* @var Reader
*/
private Reader $annReader;
/**
* Used for restoring the encryptor after changing it
* @var EncryptorInterface|string
*/
private EncryptorInterface|string $restoreEncryptor;
/**
* Count amount of decrypted values in this service
* @var integer
*/
public int $decryptCounter = 0;
/**
* Count amount of encrypted values in this service
* @var integer
*/
public int $encryptCounter = 0;
/** @var array */
private array $cachedDecryptions = [];
/**
* Initialization of subscriber
*
* @param Reader $annReader
* @param EncryptorInterface $encryptor (Optional) An EncryptorInterface.
*/
public function __construct(Reader $annReader, EncryptorInterface $encryptor)
{
$this->annReader = $annReader;
$this->encryptor = $encryptor;
$this->restoreEncryptor = $this->encryptor;
}
/**
* Change the encryptor
*
* @param EncryptorInterface|null $encryptor
*/
public function setEncryptor(?EncryptorInterface $encryptor = null)
{
$this->encryptor = $encryptor;
}
/**
* Get the current encryptor
*
* @return EncryptorInterface|null returns the encryptor class or null
*/
public function getEncryptor(): ?EncryptorInterface
{
return $this->encryptor;
}
/**
* Restore encryptor to the one set in the constructor.
*/
public function restoreEncryptor()
{
$this->encryptor = $this->restoreEncryptor;
}
/**
* Listen a postUpdate lifecycle event.
* Decrypt entities property's values when post updated.
*
* So for example after form submit the preUpdate encrypted the entity
* We have to decrypt them before showing them again.
*
* @param LifecycleEventArgs $args
*/
public function postUpdate(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
$this->processFields($entity, false);
}
/**
* Listen a preUpdate lifecycle event.
* Encrypt entities property's values on preUpdate, so they will be stored encrypted
*
* @param PreUpdateEventArgs $args
*/
public function preUpdate(PreUpdateEventArgs $args)
{
$entity = $args->getEntity();
$this->processFields($entity);
}
/**
* Listen a postLoad lifecycle event.
* Decrypt entities property's values when loaded into the entity manger
*
* @param LifecycleEventArgs $args
*/
public function postLoad(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
$this->processFields($entity, false);
}
/**
* Listen to onflush event
* Encrypt entities that are inserted into the database
*
* @param PreFlushEventArgs $preFlushEventArgs
*/
public function preFlush(PreFlushEventArgs $preFlushEventArgs)
{
$unitOfWOrk = $preFlushEventArgs->getEntityManager()->getUnitOfWork();
foreach ($unitOfWOrk->getIdentityMap() as $entityName => $entityArray) {
if (isset($this->cachedDecryptions[$entityName])) {
foreach ($entityArray as $entityId => $instance) {
if ($instance instanceof Proxy && !$instance->__isInitialized()) {
continue;
}
$this->processFields($instance);
}
}
}
$this->cachedDecryptions = [];
}
/**
* Listen to onflush event
* Encrypt entities that are inserted into the database
*
* @param OnFlushEventArgs $onFlushEventArgs
*/
public function onFlush(OnFlushEventArgs $onFlushEventArgs)
{
$unitOfWork = $onFlushEventArgs->getEntityManager()->getUnitOfWork();
foreach ($unitOfWork->getScheduledEntityInsertions() as $entity) {
$encryptCounterBefore = $this->encryptCounter;
$this->processFields($entity);
if ($this->encryptCounter > $encryptCounterBefore ) {
$classMetadata = $onFlushEventArgs->getEntityManager()->getClassMetadata(get_class($entity));
$unitOfWork->recomputeSingleEntityChangeSet($classMetadata, $entity);
}
}
}
/**
* Listen to postFlush event
* Decrypt entities after having been inserted into the database
*
* @param PostFlushEventArgs $postFlushEventArgs
*/
public function postFlush(PostFlushEventArgs $postFlushEventArgs)
{
$unitOfWork = $postFlushEventArgs->getEntityManager()->getUnitOfWork();
foreach ($unitOfWork->getIdentityMap() as $entityMap) {
foreach ($entityMap as $entity) {
if ($entity instanceof Proxy && !$entity->__isInitialized()) {
continue;
}
$this->processFields($entity, false);
}
}
}
/**
* Realization of EventSubscriber interface method.
*
* @return array Return all events which this subscriber is listening
*/
public function getSubscribedEvents(): array
{
return array(
Events::postUpdate,
Events::preUpdate,
Events::postLoad,
Events::onFlush,
Events::preFlush,
Events::postFlush,
);
}
/**
* Process (encrypt/decrypt) entities fields
*
* @param Object $entity doctrine entity
* @param Boolean $isEncryptOperation If true - encrypt, false - decrypt entity
*
* @return object|null
*@throws \RuntimeException
*
*/
public function processFields(object $entity, bool $isEncryptOperation = true): ?object
{
if (!empty($this->encryptor)) {
// Check which operation to be used
$encryptorMethod = $isEncryptOperation ? 'encrypt' : 'decrypt';
$realClass = ClassUtils::getClass($entity);
// Get ReflectionClass of our entity
$properties = $this->getClassProperties($realClass);
// Foreach property in the reflection class
foreach ($properties as $refProperty) {
if ($this->annReader->getPropertyAnnotation($refProperty, 'Doctrine\ORM\Mapping\Embedded')) {
$this->handleEmbeddedAnnotation($entity, $refProperty, $isEncryptOperation);
continue;
}
/**
* If property is an normal value and contains the Encrypt tag, lets encrypt/decrypt that property
*/
if ($this->annReader->getPropertyAnnotation($refProperty, self::ENCRYPTED_ANN_NAME)) {
$pac = PropertyAccess::createPropertyAccessor();
$value = $pac->getValue($entity, $refProperty->getName());
if ($encryptorMethod == 'decrypt') {
if (!is_null($value) and !empty($value)) {
if (substr($value, -strlen(self::ENCRYPTION_MARKER)) == self::ENCRYPTION_MARKER) {
$this->decryptCounter++;
$currentPropValue = $this->encryptor->decrypt(substr($value, 0, -5));
$pac->setValue($entity, $refProperty->getName(), $currentPropValue);
$this->cachedDecryptions[get_class($entity)][spl_object_id($entity)][$refProperty->getName()][$currentPropValue] = $value;
}
}
} else {
if (!is_null($value) and !empty($value)) {
if (isset($this->cachedDecryptions[get_class($entity)][spl_object_id($entity)][$refProperty->getName()][$value])) {
$pac->setValue($entity, $refProperty->getName(), $this->cachedDecryptions[get_class($entity)][spl_object_id($entity)][$refProperty->getName()][$value]);
} elseif (substr($value, -strlen(self::ENCRYPTION_MARKER)) != self::ENCRYPTION_MARKER) {
$this->encryptCounter++;
$currentPropValue = $this->encryptor->encrypt($value).self::ENCRYPTION_MARKER;
$pac->setValue($entity, $refProperty->getName(), $currentPropValue);
}
}
}
}
}
return $entity;
}
return $entity;
}
private function handleEmbeddedAnnotation($entity, ReflectionProperty $embeddedProperty, bool $isEncryptOperation = true)
{
$propName = $embeddedProperty->getName();
$pac = PropertyAccess::createPropertyAccessor();
$embeddedEntity = $pac->getValue($entity, $propName);
if ($embeddedEntity) {
$this->processFields($embeddedEntity, $isEncryptOperation);
}
}
/**
* Recursive function to get an associative array of class properties
* including inherited ones from extended classes
*
* @param string $className Class name
*
* @return array
*/
private function getClassProperties(string $className): array
{
$reflectionClass = new ReflectionClass($className);
$properties = $reflectionClass->getProperties();
$propertiesArray = array();
foreach ($properties as $property) {
$propertyName = $property->getName();
$propertiesArray[$propertyName] = $property;
}
if ($parentClass = $reflectionClass->getParentClass()) {
$parentPropertiesArray = $this->getClassProperties($parentClass->getName());
if (count($parentPropertiesArray) > 0) {
$propertiesArray = array_merge($parentPropertiesArray, $propertiesArray);
}
}
return $propertiesArray;
}
}